Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Based on the snippet: <|code_start|>from __future__ import print_function
def test_sampling_and_containment(test_object, d, contained, not_contained):
for _ in range(5):
test_object.assertTrue(d.contains(d.sample()))
for contained_spec in contained:
try:
contained = d.contains(contained_spec)
except KeyError:
# Having the wrong keys also indicate it is not contained.
contained = False
test_object.assertTrue(contained)
for not_contained_spec in not_contained:
try:
contained = d.contains(not_contained_spec)
except KeyError:
contained = False
test_object.assertFalse(contained)
class ContinuousTest(parameterized.TestCase):
"""Runs tests for Continuous distribution."""
@parameterized.parameters(
(0.0, 1.0, (-0.5, 2.0)),
(-1.0, -0.1, (-1.4, 0.5)),
)
def testSamplingContainmentContinuous(self, minval, maxval, not_contained):
<|code_end|>
, predict the immediate next line with the help of imports:
from absl.testing import absltest
from absl.testing import parameterized
from six.moves import range
from spriteworld import factor_distributions as distribs
and context (classes, functions, sometimes code) from other files:
# Path: spriteworld/factor_distributions.py
# _MAX_TRIES = int(1e5)
# class AbstractDistribution(object):
# class Continuous(AbstractDistribution):
# class Discrete(AbstractDistribution):
# class Mixture(AbstractDistribution):
# class Intersection(AbstractDistribution):
# class Product(AbstractDistribution):
# class SetMinus(AbstractDistribution):
# class Selection(AbstractDistribution):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def __str__(self):
# def _get_rng(self, rng=None):
# def keys(self):
# def __init__(self, key, minval, maxval, dtype='float32'):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, key, candidates, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, index_for_sampling=0):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, hold_out):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, filtering):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
. Output only the next line. | d = distribs.Continuous('x', minval, maxval) |
Predict the next line for this snippet: <|code_start|># limitations under the License.
# ============================================================================
# python2 python3
"""Exploration task used in COBRA.
There is no reward for this task, as it is used for task-free curiosity-drive
exploration.
Episodes last 10 steps, and each is initialized with 1-6 sprites of random
shape, color, and position.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def get_config(mode=None):
"""Generate environment config.
Args:
mode: Unused.
Returns:
config: Dictionary defining task/environment configuration. Can be fed as
kwargs to environment.Environment.
"""
del mode # No train/test split for pure exploration
<|code_end|>
with the help of current file imports:
import os
import numpy as np
from spriteworld import factor_distributions as distribs
from spriteworld import sprite_generators
from spriteworld import tasks
from spriteworld.configs.cobra import common
and context from other files:
# Path: spriteworld/factor_distributions.py
# _MAX_TRIES = int(1e5)
# class AbstractDistribution(object):
# class Continuous(AbstractDistribution):
# class Discrete(AbstractDistribution):
# class Mixture(AbstractDistribution):
# class Intersection(AbstractDistribution):
# class Product(AbstractDistribution):
# class SetMinus(AbstractDistribution):
# class Selection(AbstractDistribution):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def __str__(self):
# def _get_rng(self, rng=None):
# def keys(self):
# def __init__(self, key, minval, maxval, dtype='float32'):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, key, candidates, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, index_for_sampling=0):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, hold_out):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, filtering):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
#
# Path: spriteworld/sprite_generators.py
# def generate_sprites(factor_dist, num_sprites=1):
# def _generate():
# def chain_generators(*sprite_generators):
# def _generate():
# def sample_generator(sprite_generators, p=None):
# def _generate():
# def shuffle(sprite_generator):
# def _generate():
#
# Path: spriteworld/tasks.py
# class AbstractTask(object):
# class NoReward(AbstractTask):
# class FindGoalPosition(AbstractTask):
# class Clustering(AbstractTask):
# class MetaAggregated(AbstractTask):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self):
# def reward(self, unused_sprites):
# def success(self, unused_sprites):
# def __init__(self,
# filter_distrib=None,
# goal_position=(0.5, 0.5),
# terminate_distance=0.05,
# terminate_bonus=0.0,
# weights_dimensions=(1, 1),
# sparse_reward=False,
# raw_reward_multiplier=50):
# def _single_sprite_reward(self, sprite):
# def _filtered_sprites_rewards(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# cluster_distribs,
# termination_threshold=2.5,
# terminate_bonus=0.0,
# sparse_reward=False,
# reward_range=10):
# def _cluster_assignments(self, sprites):
# def _compute_clustering_metric(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# subtasks,
# reward_aggregator='sum',
# termination_criterion='all',
# terminate_bonus=0.0):
# def reward(self, sprites):
# def success(self, sprites):
# REWARD_AGGREGATOR = {
# 'sum': np.nansum,
# 'max': np.nanmax,
# 'min': np.nanmin,
# 'mean': np.nanmean
# }
# TERMINATION_CRITERION = {'all': np.all, 'any': np.any}
#
# Path: spriteworld/configs/cobra/common.py
# def action_space():
# def renderers():
, which may contain function names, class names, or code. Output only the next line. | factors = distribs.Product([ |
Given the following code snippet before the placeholder: <|code_start|>"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def get_config(mode=None):
"""Generate environment config.
Args:
mode: Unused.
Returns:
config: Dictionary defining task/environment configuration. Can be fed as
kwargs to environment.Environment.
"""
del mode # No train/test split for pure exploration
factors = distribs.Product([
distribs.Continuous('x', 0.1, 0.9),
distribs.Continuous('y', 0.1, 0.9),
distribs.Discrete('shape', ['square', 'triangle', 'circle']),
distribs.Discrete('scale', [0.13]),
distribs.Continuous('c0', 0., 1.),
distribs.Continuous('c1', 0.3, 1.),
distribs.Continuous('c2', 0.9, 1.),
])
num_sprites = lambda: np.random.randint(1, 7)
<|code_end|>
, predict the next line using imports from the current file:
import os
import numpy as np
from spriteworld import factor_distributions as distribs
from spriteworld import sprite_generators
from spriteworld import tasks
from spriteworld.configs.cobra import common
and context including class names, function names, and sometimes code from other files:
# Path: spriteworld/factor_distributions.py
# _MAX_TRIES = int(1e5)
# class AbstractDistribution(object):
# class Continuous(AbstractDistribution):
# class Discrete(AbstractDistribution):
# class Mixture(AbstractDistribution):
# class Intersection(AbstractDistribution):
# class Product(AbstractDistribution):
# class SetMinus(AbstractDistribution):
# class Selection(AbstractDistribution):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def __str__(self):
# def _get_rng(self, rng=None):
# def keys(self):
# def __init__(self, key, minval, maxval, dtype='float32'):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, key, candidates, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, index_for_sampling=0):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, hold_out):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, filtering):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
#
# Path: spriteworld/sprite_generators.py
# def generate_sprites(factor_dist, num_sprites=1):
# def _generate():
# def chain_generators(*sprite_generators):
# def _generate():
# def sample_generator(sprite_generators, p=None):
# def _generate():
# def shuffle(sprite_generator):
# def _generate():
#
# Path: spriteworld/tasks.py
# class AbstractTask(object):
# class NoReward(AbstractTask):
# class FindGoalPosition(AbstractTask):
# class Clustering(AbstractTask):
# class MetaAggregated(AbstractTask):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self):
# def reward(self, unused_sprites):
# def success(self, unused_sprites):
# def __init__(self,
# filter_distrib=None,
# goal_position=(0.5, 0.5),
# terminate_distance=0.05,
# terminate_bonus=0.0,
# weights_dimensions=(1, 1),
# sparse_reward=False,
# raw_reward_multiplier=50):
# def _single_sprite_reward(self, sprite):
# def _filtered_sprites_rewards(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# cluster_distribs,
# termination_threshold=2.5,
# terminate_bonus=0.0,
# sparse_reward=False,
# reward_range=10):
# def _cluster_assignments(self, sprites):
# def _compute_clustering_metric(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# subtasks,
# reward_aggregator='sum',
# termination_criterion='all',
# terminate_bonus=0.0):
# def reward(self, sprites):
# def success(self, sprites):
# REWARD_AGGREGATOR = {
# 'sum': np.nansum,
# 'max': np.nanmax,
# 'min': np.nanmin,
# 'mean': np.nanmean
# }
# TERMINATION_CRITERION = {'all': np.all, 'any': np.any}
#
# Path: spriteworld/configs/cobra/common.py
# def action_space():
# def renderers():
. Output only the next line. | sprite_gen = sprite_generators.generate_sprites( |
Given the following code snippet before the placeholder: <|code_start|>from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def get_config(mode=None):
"""Generate environment config.
Args:
mode: Unused.
Returns:
config: Dictionary defining task/environment configuration. Can be fed as
kwargs to environment.Environment.
"""
del mode # No train/test split for pure exploration
factors = distribs.Product([
distribs.Continuous('x', 0.1, 0.9),
distribs.Continuous('y', 0.1, 0.9),
distribs.Discrete('shape', ['square', 'triangle', 'circle']),
distribs.Discrete('scale', [0.13]),
distribs.Continuous('c0', 0., 1.),
distribs.Continuous('c1', 0.3, 1.),
distribs.Continuous('c2', 0.9, 1.),
])
num_sprites = lambda: np.random.randint(1, 7)
sprite_gen = sprite_generators.generate_sprites(
factors, num_sprites=num_sprites)
<|code_end|>
, predict the next line using imports from the current file:
import os
import numpy as np
from spriteworld import factor_distributions as distribs
from spriteworld import sprite_generators
from spriteworld import tasks
from spriteworld.configs.cobra import common
and context including class names, function names, and sometimes code from other files:
# Path: spriteworld/factor_distributions.py
# _MAX_TRIES = int(1e5)
# class AbstractDistribution(object):
# class Continuous(AbstractDistribution):
# class Discrete(AbstractDistribution):
# class Mixture(AbstractDistribution):
# class Intersection(AbstractDistribution):
# class Product(AbstractDistribution):
# class SetMinus(AbstractDistribution):
# class Selection(AbstractDistribution):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def __str__(self):
# def _get_rng(self, rng=None):
# def keys(self):
# def __init__(self, key, minval, maxval, dtype='float32'):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, key, candidates, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, index_for_sampling=0):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, hold_out):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, filtering):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
#
# Path: spriteworld/sprite_generators.py
# def generate_sprites(factor_dist, num_sprites=1):
# def _generate():
# def chain_generators(*sprite_generators):
# def _generate():
# def sample_generator(sprite_generators, p=None):
# def _generate():
# def shuffle(sprite_generator):
# def _generate():
#
# Path: spriteworld/tasks.py
# class AbstractTask(object):
# class NoReward(AbstractTask):
# class FindGoalPosition(AbstractTask):
# class Clustering(AbstractTask):
# class MetaAggregated(AbstractTask):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self):
# def reward(self, unused_sprites):
# def success(self, unused_sprites):
# def __init__(self,
# filter_distrib=None,
# goal_position=(0.5, 0.5),
# terminate_distance=0.05,
# terminate_bonus=0.0,
# weights_dimensions=(1, 1),
# sparse_reward=False,
# raw_reward_multiplier=50):
# def _single_sprite_reward(self, sprite):
# def _filtered_sprites_rewards(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# cluster_distribs,
# termination_threshold=2.5,
# terminate_bonus=0.0,
# sparse_reward=False,
# reward_range=10):
# def _cluster_assignments(self, sprites):
# def _compute_clustering_metric(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# subtasks,
# reward_aggregator='sum',
# termination_criterion='all',
# terminate_bonus=0.0):
# def reward(self, sprites):
# def success(self, sprites):
# REWARD_AGGREGATOR = {
# 'sum': np.nansum,
# 'max': np.nanmax,
# 'min': np.nanmin,
# 'mean': np.nanmean
# }
# TERMINATION_CRITERION = {'all': np.all, 'any': np.any}
#
# Path: spriteworld/configs/cobra/common.py
# def action_space():
# def renderers():
. Output only the next line. | task = tasks.NoReward() |
Given the code snippet: <|code_start|>
def get_config(mode=None):
"""Generate environment config.
Args:
mode: Unused.
Returns:
config: Dictionary defining task/environment configuration. Can be fed as
kwargs to environment.Environment.
"""
del mode # No train/test split for pure exploration
factors = distribs.Product([
distribs.Continuous('x', 0.1, 0.9),
distribs.Continuous('y', 0.1, 0.9),
distribs.Discrete('shape', ['square', 'triangle', 'circle']),
distribs.Discrete('scale', [0.13]),
distribs.Continuous('c0', 0., 1.),
distribs.Continuous('c1', 0.3, 1.),
distribs.Continuous('c2', 0.9, 1.),
])
num_sprites = lambda: np.random.randint(1, 7)
sprite_gen = sprite_generators.generate_sprites(
factors, num_sprites=num_sprites)
task = tasks.NoReward()
config = {
'task': task,
<|code_end|>
, generate the next line using the imports in this file:
import os
import numpy as np
from spriteworld import factor_distributions as distribs
from spriteworld import sprite_generators
from spriteworld import tasks
from spriteworld.configs.cobra import common
and context (functions, classes, or occasionally code) from other files:
# Path: spriteworld/factor_distributions.py
# _MAX_TRIES = int(1e5)
# class AbstractDistribution(object):
# class Continuous(AbstractDistribution):
# class Discrete(AbstractDistribution):
# class Mixture(AbstractDistribution):
# class Intersection(AbstractDistribution):
# class Product(AbstractDistribution):
# class SetMinus(AbstractDistribution):
# class Selection(AbstractDistribution):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def __str__(self):
# def _get_rng(self, rng=None):
# def keys(self):
# def __init__(self, key, minval, maxval, dtype='float32'):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, key, candidates, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, index_for_sampling=0):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, hold_out):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, filtering):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
#
# Path: spriteworld/sprite_generators.py
# def generate_sprites(factor_dist, num_sprites=1):
# def _generate():
# def chain_generators(*sprite_generators):
# def _generate():
# def sample_generator(sprite_generators, p=None):
# def _generate():
# def shuffle(sprite_generator):
# def _generate():
#
# Path: spriteworld/tasks.py
# class AbstractTask(object):
# class NoReward(AbstractTask):
# class FindGoalPosition(AbstractTask):
# class Clustering(AbstractTask):
# class MetaAggregated(AbstractTask):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self):
# def reward(self, unused_sprites):
# def success(self, unused_sprites):
# def __init__(self,
# filter_distrib=None,
# goal_position=(0.5, 0.5),
# terminate_distance=0.05,
# terminate_bonus=0.0,
# weights_dimensions=(1, 1),
# sparse_reward=False,
# raw_reward_multiplier=50):
# def _single_sprite_reward(self, sprite):
# def _filtered_sprites_rewards(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# cluster_distribs,
# termination_threshold=2.5,
# terminate_bonus=0.0,
# sparse_reward=False,
# reward_range=10):
# def _cluster_assignments(self, sprites):
# def _compute_clustering_metric(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# subtasks,
# reward_aggregator='sum',
# termination_criterion='all',
# terminate_bonus=0.0):
# def reward(self, sprites):
# def success(self, sprites):
# REWARD_AGGREGATOR = {
# 'sum': np.nansum,
# 'max': np.nanmax,
# 'min': np.nanmin,
# 'mean': np.nanmean
# }
# TERMINATION_CRITERION = {'all': np.all, 'any': np.any}
#
# Path: spriteworld/configs/cobra/common.py
# def action_space():
# def renderers():
. Output only the next line. | 'action_space': common.action_space(), |
Continue the code snippet: <|code_start|> """Construct sprite.
This class is agnostic to the color scheme, namely (c1, c2, c3) could be in
RGB coordinates or HSV, HSL, etc. without this class knowing. The color
scheme conversion for rendering must be done in the renderer.
Args:
x: Float in [0, 1]. x-position.
y: Float in [0, 1]. y-position.
shape: String. Shape of the sprite. Must be a key of constants.SHAPES.
angle: Int. Angle in degrees.
scale: Float in [0, 1]. Scale of the sprite, from a point to the area of
the entire frame. This scales linearly with respect to sprite width,
hence with power 1/2 with respect to sprite area.
c0: Scalar. First coordinate of color.
c1: Scalar. Second coordinate of color.
c2: Scalar. Third coordinate of color.
x_vel: Float. x-velocity.
y_vel: Float. y-velocity.
"""
self._position = np.array([x, y])
self._shape = shape
self._angle = angle
self._scale = scale
self._color = (c0, c1, c2)
self._velocity = (x_vel, y_vel)
self._reset_centered_path()
def _reset_centered_path(self):
<|code_end|>
. Use current file imports:
import collections
import numpy as np
from matplotlib import path as mpl_path
from matplotlib import transforms as mpl_transforms
from spriteworld import constants
and context (classes, functions, or code) from other files:
# Path: spriteworld/constants.py
# SHAPES = {
# 'triangle': shapes.polygon(num_sides=3, theta_0=np.pi/2),
# 'square': shapes.polygon(num_sides=4, theta_0=np.pi/4),
# 'pentagon': shapes.polygon(num_sides=5, theta_0=np.pi/2),
# 'hexagon': shapes.polygon(num_sides=6),
# 'octagon': shapes.polygon(num_sides=8),
# 'circle': shapes.polygon(num_sides=30),
# 'star_4': shapes.star(num_sides=4, theta_0=np.pi/4),
# 'star_5': shapes.star(num_sides=5, theta_0=np.pi + np.pi/10),
# 'star_6': shapes.star(num_sides=6),
# 'spoke_4': shapes.spokes(num_sides=4, theta_0=np.pi/4),
# 'spoke_5': shapes.spokes(num_sides=5, theta_0=np.pi + np.pi/10),
# 'spoke_6': shapes.spokes(num_sides=6),
# }
# class ShapeType(enum.IntEnum):
. Output only the next line. | path = mpl_path.Path(constants.SHAPES[self._shape]) |
Based on the snippet: <|code_start|> """
if not set(factors).issubset(set(sprite_lib.FACTOR_NAMES)):
raise ValueError('Factors have to belong to {}.'.format(
sprite_lib.FACTOR_NAMES))
self._num_sprites = None
self._factors = factors
self._per_object_spec = {
factor: specs.Array(shape=(), dtype=np.float32) for factor in factors
}
def render(self, sprites=(), global_state=None):
"""Renders a list of sprites into a list of sprite factors.
Args:
sprites: a list of sprites with a method `get_sprite`. This method
receives a single argument `upscale_factor`, and returns a pygame
sprite.
global_state: Unused global state.
Returns:
A list of dictionaries of factor -> values mappings.
"""
del global_state
# Set number of sprites so that observation_spec is callable
self._num_sprites = len(sprites)
def _process_factor(name, value):
if name == 'shape':
<|code_end|>
, predict the immediate next line with the help of imports:
from dm_env import specs
from spriteworld import constants
from spriteworld import sprite as sprite_lib
from spriteworld.renderers import abstract_renderer
import numpy as np
and context (classes, functions, sometimes code) from other files:
# Path: spriteworld/constants.py
# SHAPES = {
# 'triangle': shapes.polygon(num_sides=3, theta_0=np.pi/2),
# 'square': shapes.polygon(num_sides=4, theta_0=np.pi/4),
# 'pentagon': shapes.polygon(num_sides=5, theta_0=np.pi/2),
# 'hexagon': shapes.polygon(num_sides=6),
# 'octagon': shapes.polygon(num_sides=8),
# 'circle': shapes.polygon(num_sides=30),
# 'star_4': shapes.star(num_sides=4, theta_0=np.pi/4),
# 'star_5': shapes.star(num_sides=5, theta_0=np.pi + np.pi/10),
# 'star_6': shapes.star(num_sides=6),
# 'spoke_4': shapes.spokes(num_sides=4, theta_0=np.pi/4),
# 'spoke_5': shapes.spokes(num_sides=5, theta_0=np.pi + np.pi/10),
# 'spoke_6': shapes.spokes(num_sides=6),
# }
# class ShapeType(enum.IntEnum):
#
# Path: spriteworld/sprite.py
# FACTOR_NAMES = (
# 'x', # x-position of sprite center-of-mass (float)
# 'y', # y-position of sprite center-of-mass (float)
# 'shape', # shape (string)
# 'angle', # angle in degrees (scalar)
# 'scale', # size of sprite (float)
# 'c0', # first color component (scalar)
# 'c1', # second color component (scalar)
# 'c2', # third color component (scalar)
# 'x_vel', # x-component of velocity (float)
# 'y_vel', # y-component of velocity (float)
# )
# _MAX_TRIES = int(1e6)
# class Sprite(object):
# def __init__(self,
# x=0.5,
# y=0.5,
# shape='square',
# angle=0,
# scale=0.1,
# c0=0,
# c1=0,
# c2=0,
# x_vel=0.0,
# y_vel=0.0):
# def _reset_centered_path(self):
# def move(self, motion, keep_in_frame=False):
# def update_position(self, keep_in_frame=False):
# def contains_point(self, point):
# def sample_contained_position(self):
# def vertices(self):
# def out_of_frame(self):
# def x(self):
# def y(self):
# def shape(self):
# def shape(self, s):
# def angle(self):
# def angle(self, a):
# def scale(self):
# def scale(self, s):
# def c0(self):
# def c1(self):
# def c2(self):
# def x_vel(self):
# def y_vel(self):
# def color(self):
# def position(self):
# def velocity(self):
# def factors(self):
#
# Path: spriteworld/renderers/abstract_renderer.py
# class AbstractRenderer(object):
# def render(self, sprites=(), global_state=None):
# def observation_spec(self):
. Output only the next line. | value = constants.ShapeType[value].value |
Given the code snippet: <|code_start|># Copyright 2019 DeepMind Technologies Limited.
#
# 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.
# ============================================================================
# python2 python3
"""Handcrafted renderers for Spriteworld."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class SpriteFactors(abstract_renderer.AbstractRenderer):
"""Aggregates factors of the sprites into an array."""
<|code_end|>
, generate the next line using the imports in this file:
from dm_env import specs
from spriteworld import constants
from spriteworld import sprite as sprite_lib
from spriteworld.renderers import abstract_renderer
import numpy as np
and context (functions, classes, or occasionally code) from other files:
# Path: spriteworld/constants.py
# SHAPES = {
# 'triangle': shapes.polygon(num_sides=3, theta_0=np.pi/2),
# 'square': shapes.polygon(num_sides=4, theta_0=np.pi/4),
# 'pentagon': shapes.polygon(num_sides=5, theta_0=np.pi/2),
# 'hexagon': shapes.polygon(num_sides=6),
# 'octagon': shapes.polygon(num_sides=8),
# 'circle': shapes.polygon(num_sides=30),
# 'star_4': shapes.star(num_sides=4, theta_0=np.pi/4),
# 'star_5': shapes.star(num_sides=5, theta_0=np.pi + np.pi/10),
# 'star_6': shapes.star(num_sides=6),
# 'spoke_4': shapes.spokes(num_sides=4, theta_0=np.pi/4),
# 'spoke_5': shapes.spokes(num_sides=5, theta_0=np.pi + np.pi/10),
# 'spoke_6': shapes.spokes(num_sides=6),
# }
# class ShapeType(enum.IntEnum):
#
# Path: spriteworld/sprite.py
# FACTOR_NAMES = (
# 'x', # x-position of sprite center-of-mass (float)
# 'y', # y-position of sprite center-of-mass (float)
# 'shape', # shape (string)
# 'angle', # angle in degrees (scalar)
# 'scale', # size of sprite (float)
# 'c0', # first color component (scalar)
# 'c1', # second color component (scalar)
# 'c2', # third color component (scalar)
# 'x_vel', # x-component of velocity (float)
# 'y_vel', # y-component of velocity (float)
# )
# _MAX_TRIES = int(1e6)
# class Sprite(object):
# def __init__(self,
# x=0.5,
# y=0.5,
# shape='square',
# angle=0,
# scale=0.1,
# c0=0,
# c1=0,
# c2=0,
# x_vel=0.0,
# y_vel=0.0):
# def _reset_centered_path(self):
# def move(self, motion, keep_in_frame=False):
# def update_position(self, keep_in_frame=False):
# def contains_point(self, point):
# def sample_contained_position(self):
# def vertices(self):
# def out_of_frame(self):
# def x(self):
# def y(self):
# def shape(self):
# def shape(self, s):
# def angle(self):
# def angle(self, a):
# def scale(self):
# def scale(self, s):
# def c0(self):
# def c1(self):
# def c2(self):
# def x_vel(self):
# def y_vel(self):
# def color(self):
# def position(self):
# def velocity(self):
# def factors(self):
#
# Path: spriteworld/renderers/abstract_renderer.py
# class AbstractRenderer(object):
# def render(self, sprites=(), global_state=None):
# def observation_spec(self):
. Output only the next line. | def __init__(self, factors=sprite_lib.FACTOR_NAMES): |
Based on the snippet: <|code_start|># Copyright 2019 DeepMind Technologies Limited.
#
# 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.
# ============================================================================
# python2 python3
"""Handcrafted renderers for Spriteworld."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
<|code_end|>
, predict the immediate next line with the help of imports:
from dm_env import specs
from spriteworld import constants
from spriteworld import sprite as sprite_lib
from spriteworld.renderers import abstract_renderer
import numpy as np
and context (classes, functions, sometimes code) from other files:
# Path: spriteworld/constants.py
# SHAPES = {
# 'triangle': shapes.polygon(num_sides=3, theta_0=np.pi/2),
# 'square': shapes.polygon(num_sides=4, theta_0=np.pi/4),
# 'pentagon': shapes.polygon(num_sides=5, theta_0=np.pi/2),
# 'hexagon': shapes.polygon(num_sides=6),
# 'octagon': shapes.polygon(num_sides=8),
# 'circle': shapes.polygon(num_sides=30),
# 'star_4': shapes.star(num_sides=4, theta_0=np.pi/4),
# 'star_5': shapes.star(num_sides=5, theta_0=np.pi + np.pi/10),
# 'star_6': shapes.star(num_sides=6),
# 'spoke_4': shapes.spokes(num_sides=4, theta_0=np.pi/4),
# 'spoke_5': shapes.spokes(num_sides=5, theta_0=np.pi + np.pi/10),
# 'spoke_6': shapes.spokes(num_sides=6),
# }
# class ShapeType(enum.IntEnum):
#
# Path: spriteworld/sprite.py
# FACTOR_NAMES = (
# 'x', # x-position of sprite center-of-mass (float)
# 'y', # y-position of sprite center-of-mass (float)
# 'shape', # shape (string)
# 'angle', # angle in degrees (scalar)
# 'scale', # size of sprite (float)
# 'c0', # first color component (scalar)
# 'c1', # second color component (scalar)
# 'c2', # third color component (scalar)
# 'x_vel', # x-component of velocity (float)
# 'y_vel', # y-component of velocity (float)
# )
# _MAX_TRIES = int(1e6)
# class Sprite(object):
# def __init__(self,
# x=0.5,
# y=0.5,
# shape='square',
# angle=0,
# scale=0.1,
# c0=0,
# c1=0,
# c2=0,
# x_vel=0.0,
# y_vel=0.0):
# def _reset_centered_path(self):
# def move(self, motion, keep_in_frame=False):
# def update_position(self, keep_in_frame=False):
# def contains_point(self, point):
# def sample_contained_position(self):
# def vertices(self):
# def out_of_frame(self):
# def x(self):
# def y(self):
# def shape(self):
# def shape(self, s):
# def angle(self):
# def angle(self, a):
# def scale(self):
# def scale(self, s):
# def c0(self):
# def c1(self):
# def c2(self):
# def x_vel(self):
# def y_vel(self):
# def color(self):
# def position(self):
# def velocity(self):
# def factors(self):
#
# Path: spriteworld/renderers/abstract_renderer.py
# class AbstractRenderer(object):
# def render(self, sprites=(), global_state=None):
# def observation_spec(self):
. Output only the next line. | class SpriteFactors(abstract_renderer.AbstractRenderer): |
Based on the snippet: <|code_start|># Copyright 2019 DeepMind Technologies Limited.
#
# 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.
# ============================================================================
# python2 python3
"""Python Image Library (PIL/Pillow) renderer."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
<|code_end|>
, predict the immediate next line with the help of imports:
from dm_env import specs
from PIL import Image
from PIL import ImageDraw
from spriteworld.renderers import abstract_renderer
import numpy as np
and context (classes, functions, sometimes code) from other files:
# Path: spriteworld/renderers/abstract_renderer.py
# class AbstractRenderer(object):
# def render(self, sprites=(), global_state=None):
# def observation_spec(self):
. Output only the next line. | class PILRenderer(abstract_renderer.AbstractRenderer): |
Here is a snippet: <|code_start|># 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.
# ============================================================================
# python2 python3
"""Goal-Finding tasks testing for generalization to new initial positions.
In this task there is one target sprite of orange-green-ish color and one
distractor sprite of blue-purple-ish color. The target must be brought to the
goal location, which is the center of the arena, while the distractor does not
contribute to the reward.
In train mode the target is initialized in any position except the lower-right
quadrant, while in test mode it is initialized only in the lower-right quadrant.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
TERMINATE_DISTANCE = 0.075
NUM_TARGETS = 1
NUM_DISTRACTORS = 1
MODES_TARGET_POSITIONS = {
'train':
<|code_end|>
. Write the next line using the current file imports:
import os
from spriteworld import factor_distributions as distribs
from spriteworld import sprite_generators
from spriteworld import tasks
from spriteworld.configs.cobra import common
and context from other files:
# Path: spriteworld/factor_distributions.py
# _MAX_TRIES = int(1e5)
# class AbstractDistribution(object):
# class Continuous(AbstractDistribution):
# class Discrete(AbstractDistribution):
# class Mixture(AbstractDistribution):
# class Intersection(AbstractDistribution):
# class Product(AbstractDistribution):
# class SetMinus(AbstractDistribution):
# class Selection(AbstractDistribution):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def __str__(self):
# def _get_rng(self, rng=None):
# def keys(self):
# def __init__(self, key, minval, maxval, dtype='float32'):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, key, candidates, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, index_for_sampling=0):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, hold_out):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, filtering):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
#
# Path: spriteworld/sprite_generators.py
# def generate_sprites(factor_dist, num_sprites=1):
# def _generate():
# def chain_generators(*sprite_generators):
# def _generate():
# def sample_generator(sprite_generators, p=None):
# def _generate():
# def shuffle(sprite_generator):
# def _generate():
#
# Path: spriteworld/tasks.py
# class AbstractTask(object):
# class NoReward(AbstractTask):
# class FindGoalPosition(AbstractTask):
# class Clustering(AbstractTask):
# class MetaAggregated(AbstractTask):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self):
# def reward(self, unused_sprites):
# def success(self, unused_sprites):
# def __init__(self,
# filter_distrib=None,
# goal_position=(0.5, 0.5),
# terminate_distance=0.05,
# terminate_bonus=0.0,
# weights_dimensions=(1, 1),
# sparse_reward=False,
# raw_reward_multiplier=50):
# def _single_sprite_reward(self, sprite):
# def _filtered_sprites_rewards(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# cluster_distribs,
# termination_threshold=2.5,
# terminate_bonus=0.0,
# sparse_reward=False,
# reward_range=10):
# def _cluster_assignments(self, sprites):
# def _compute_clustering_metric(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# subtasks,
# reward_aggregator='sum',
# termination_criterion='all',
# terminate_bonus=0.0):
# def reward(self, sprites):
# def success(self, sprites):
# REWARD_AGGREGATOR = {
# 'sum': np.nansum,
# 'max': np.nanmax,
# 'min': np.nanmin,
# 'mean': np.nanmean
# }
# TERMINATION_CRITERION = {'all': np.all, 'any': np.any}
#
# Path: spriteworld/configs/cobra/common.py
# def action_space():
# def renderers():
, which may include functions, classes, or code. Output only the next line. | distribs.SetMinus( |
Predict the next line after this snippet: <|code_start|> """Generate environment config.
Args:
mode: 'train' or 'test'.
Returns:
config: Dictionary defining task/environment configuration. Can be fed as
kwargs to environment.Environment.
"""
shared_factors = distribs.Product([
distribs.Discrete('shape', ['square', 'triangle', 'circle']),
distribs.Discrete('scale', [0.13]),
distribs.Continuous('c1', 0.3, 1.),
distribs.Continuous('c2', 0.9, 1.),
])
target_hue = distribs.Continuous('c0', 0., 0.4)
distractor_hue = distribs.Continuous('c0', 0.5, 0.9)
target_factors = distribs.Product([
MODES_TARGET_POSITIONS[mode],
target_hue,
shared_factors,
])
distractor_factors = distribs.Product([
distribs.Continuous('x', 0.1, 0.9),
distribs.Continuous('y', 0.1, 0.9),
distractor_hue,
shared_factors,
])
<|code_end|>
using the current file's imports:
import os
from spriteworld import factor_distributions as distribs
from spriteworld import sprite_generators
from spriteworld import tasks
from spriteworld.configs.cobra import common
and any relevant context from other files:
# Path: spriteworld/factor_distributions.py
# _MAX_TRIES = int(1e5)
# class AbstractDistribution(object):
# class Continuous(AbstractDistribution):
# class Discrete(AbstractDistribution):
# class Mixture(AbstractDistribution):
# class Intersection(AbstractDistribution):
# class Product(AbstractDistribution):
# class SetMinus(AbstractDistribution):
# class Selection(AbstractDistribution):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def __str__(self):
# def _get_rng(self, rng=None):
# def keys(self):
# def __init__(self, key, minval, maxval, dtype='float32'):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, key, candidates, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, index_for_sampling=0):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, hold_out):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, filtering):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
#
# Path: spriteworld/sprite_generators.py
# def generate_sprites(factor_dist, num_sprites=1):
# def _generate():
# def chain_generators(*sprite_generators):
# def _generate():
# def sample_generator(sprite_generators, p=None):
# def _generate():
# def shuffle(sprite_generator):
# def _generate():
#
# Path: spriteworld/tasks.py
# class AbstractTask(object):
# class NoReward(AbstractTask):
# class FindGoalPosition(AbstractTask):
# class Clustering(AbstractTask):
# class MetaAggregated(AbstractTask):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self):
# def reward(self, unused_sprites):
# def success(self, unused_sprites):
# def __init__(self,
# filter_distrib=None,
# goal_position=(0.5, 0.5),
# terminate_distance=0.05,
# terminate_bonus=0.0,
# weights_dimensions=(1, 1),
# sparse_reward=False,
# raw_reward_multiplier=50):
# def _single_sprite_reward(self, sprite):
# def _filtered_sprites_rewards(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# cluster_distribs,
# termination_threshold=2.5,
# terminate_bonus=0.0,
# sparse_reward=False,
# reward_range=10):
# def _cluster_assignments(self, sprites):
# def _compute_clustering_metric(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# subtasks,
# reward_aggregator='sum',
# termination_criterion='all',
# terminate_bonus=0.0):
# def reward(self, sprites):
# def success(self, sprites):
# REWARD_AGGREGATOR = {
# 'sum': np.nansum,
# 'max': np.nanmax,
# 'min': np.nanmin,
# 'mean': np.nanmean
# }
# TERMINATION_CRITERION = {'all': np.all, 'any': np.any}
#
# Path: spriteworld/configs/cobra/common.py
# def action_space():
# def renderers():
. Output only the next line. | target_sprite_gen = sprite_generators.generate_sprites( |
Using the snippet: <|code_start|>
shared_factors = distribs.Product([
distribs.Discrete('shape', ['square', 'triangle', 'circle']),
distribs.Discrete('scale', [0.13]),
distribs.Continuous('c1', 0.3, 1.),
distribs.Continuous('c2', 0.9, 1.),
])
target_hue = distribs.Continuous('c0', 0., 0.4)
distractor_hue = distribs.Continuous('c0', 0.5, 0.9)
target_factors = distribs.Product([
MODES_TARGET_POSITIONS[mode],
target_hue,
shared_factors,
])
distractor_factors = distribs.Product([
distribs.Continuous('x', 0.1, 0.9),
distribs.Continuous('y', 0.1, 0.9),
distractor_hue,
shared_factors,
])
target_sprite_gen = sprite_generators.generate_sprites(
target_factors, num_sprites=NUM_TARGETS)
distractor_sprite_gen = sprite_generators.generate_sprites(
distractor_factors, num_sprites=NUM_DISTRACTORS)
sprite_gen = sprite_generators.chain_generators(target_sprite_gen,
distractor_sprite_gen)
# Randomize sprite ordering to eliminate any task information from occlusions
sprite_gen = sprite_generators.shuffle(sprite_gen)
<|code_end|>
, determine the next line of code. You have imports:
import os
from spriteworld import factor_distributions as distribs
from spriteworld import sprite_generators
from spriteworld import tasks
from spriteworld.configs.cobra import common
and context (class names, function names, or code) available:
# Path: spriteworld/factor_distributions.py
# _MAX_TRIES = int(1e5)
# class AbstractDistribution(object):
# class Continuous(AbstractDistribution):
# class Discrete(AbstractDistribution):
# class Mixture(AbstractDistribution):
# class Intersection(AbstractDistribution):
# class Product(AbstractDistribution):
# class SetMinus(AbstractDistribution):
# class Selection(AbstractDistribution):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def __str__(self):
# def _get_rng(self, rng=None):
# def keys(self):
# def __init__(self, key, minval, maxval, dtype='float32'):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, key, candidates, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, index_for_sampling=0):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, hold_out):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, filtering):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
#
# Path: spriteworld/sprite_generators.py
# def generate_sprites(factor_dist, num_sprites=1):
# def _generate():
# def chain_generators(*sprite_generators):
# def _generate():
# def sample_generator(sprite_generators, p=None):
# def _generate():
# def shuffle(sprite_generator):
# def _generate():
#
# Path: spriteworld/tasks.py
# class AbstractTask(object):
# class NoReward(AbstractTask):
# class FindGoalPosition(AbstractTask):
# class Clustering(AbstractTask):
# class MetaAggregated(AbstractTask):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self):
# def reward(self, unused_sprites):
# def success(self, unused_sprites):
# def __init__(self,
# filter_distrib=None,
# goal_position=(0.5, 0.5),
# terminate_distance=0.05,
# terminate_bonus=0.0,
# weights_dimensions=(1, 1),
# sparse_reward=False,
# raw_reward_multiplier=50):
# def _single_sprite_reward(self, sprite):
# def _filtered_sprites_rewards(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# cluster_distribs,
# termination_threshold=2.5,
# terminate_bonus=0.0,
# sparse_reward=False,
# reward_range=10):
# def _cluster_assignments(self, sprites):
# def _compute_clustering_metric(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# subtasks,
# reward_aggregator='sum',
# termination_criterion='all',
# terminate_bonus=0.0):
# def reward(self, sprites):
# def success(self, sprites):
# REWARD_AGGREGATOR = {
# 'sum': np.nansum,
# 'max': np.nanmax,
# 'min': np.nanmin,
# 'mean': np.nanmean
# }
# TERMINATION_CRITERION = {'all': np.all, 'any': np.any}
#
# Path: spriteworld/configs/cobra/common.py
# def action_space():
# def renderers():
. Output only the next line. | task = tasks.FindGoalPosition( |
Using the snippet: <|code_start|> distribs.Continuous('c2', 0.9, 1.),
])
target_hue = distribs.Continuous('c0', 0., 0.4)
distractor_hue = distribs.Continuous('c0', 0.5, 0.9)
target_factors = distribs.Product([
MODES_TARGET_POSITIONS[mode],
target_hue,
shared_factors,
])
distractor_factors = distribs.Product([
distribs.Continuous('x', 0.1, 0.9),
distribs.Continuous('y', 0.1, 0.9),
distractor_hue,
shared_factors,
])
target_sprite_gen = sprite_generators.generate_sprites(
target_factors, num_sprites=NUM_TARGETS)
distractor_sprite_gen = sprite_generators.generate_sprites(
distractor_factors, num_sprites=NUM_DISTRACTORS)
sprite_gen = sprite_generators.chain_generators(target_sprite_gen,
distractor_sprite_gen)
# Randomize sprite ordering to eliminate any task information from occlusions
sprite_gen = sprite_generators.shuffle(sprite_gen)
task = tasks.FindGoalPosition(
filter_distrib=target_hue, terminate_distance=TERMINATE_DISTANCE)
config = {
'task': task,
<|code_end|>
, determine the next line of code. You have imports:
import os
from spriteworld import factor_distributions as distribs
from spriteworld import sprite_generators
from spriteworld import tasks
from spriteworld.configs.cobra import common
and context (class names, function names, or code) available:
# Path: spriteworld/factor_distributions.py
# _MAX_TRIES = int(1e5)
# class AbstractDistribution(object):
# class Continuous(AbstractDistribution):
# class Discrete(AbstractDistribution):
# class Mixture(AbstractDistribution):
# class Intersection(AbstractDistribution):
# class Product(AbstractDistribution):
# class SetMinus(AbstractDistribution):
# class Selection(AbstractDistribution):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def __str__(self):
# def _get_rng(self, rng=None):
# def keys(self):
# def __init__(self, key, minval, maxval, dtype='float32'):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, key, candidates, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, index_for_sampling=0):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, hold_out):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, filtering):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
#
# Path: spriteworld/sprite_generators.py
# def generate_sprites(factor_dist, num_sprites=1):
# def _generate():
# def chain_generators(*sprite_generators):
# def _generate():
# def sample_generator(sprite_generators, p=None):
# def _generate():
# def shuffle(sprite_generator):
# def _generate():
#
# Path: spriteworld/tasks.py
# class AbstractTask(object):
# class NoReward(AbstractTask):
# class FindGoalPosition(AbstractTask):
# class Clustering(AbstractTask):
# class MetaAggregated(AbstractTask):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self):
# def reward(self, unused_sprites):
# def success(self, unused_sprites):
# def __init__(self,
# filter_distrib=None,
# goal_position=(0.5, 0.5),
# terminate_distance=0.05,
# terminate_bonus=0.0,
# weights_dimensions=(1, 1),
# sparse_reward=False,
# raw_reward_multiplier=50):
# def _single_sprite_reward(self, sprite):
# def _filtered_sprites_rewards(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# cluster_distribs,
# termination_threshold=2.5,
# terminate_bonus=0.0,
# sparse_reward=False,
# reward_range=10):
# def _cluster_assignments(self, sprites):
# def _compute_clustering_metric(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# subtasks,
# reward_aggregator='sum',
# termination_criterion='all',
# terminate_bonus=0.0):
# def reward(self, sprites):
# def success(self, sprites):
# REWARD_AGGREGATOR = {
# 'sum': np.nansum,
# 'max': np.nanmax,
# 'min': np.nanmin,
# 'mean': np.nanmean
# }
# TERMINATION_CRITERION = {'all': np.all, 'any': np.any}
#
# Path: spriteworld/configs/cobra/common.py
# def action_space():
# def renderers():
. Output only the next line. | 'action_space': common.action_space(), |
Predict the next line after this snippet: <|code_start|># 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.
# ============================================================================
# python2 python3
"""Sorting task used in COBRA.
Sort sprites into target locations based on color.
We use 5 narrow hue ranges (red, blue, green, purple, yellow), and associated to
each a goal location (the corners and center of the arena). Each episode we
sample two sprites in random locations with different colors and reward the
agent for bringing them each to their respective goal location. in the training
mode we hold out one color pair, and in the test mode we sample only that pair.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Task Parameters
MAX_EPISODE_LENGTH = 50
TERMINATE_DISTANCE = 0.075
RAW_REWARD_MULTIPLIER = 20.
NUM_TARGETS = 2
# Sub-tasks for each color/goal
SUBTASKS = (
{
<|code_end|>
using the current file's imports:
import itertools
import os
import numpy as np
from spriteworld import factor_distributions as distribs
from spriteworld import sprite_generators
from spriteworld import tasks
from spriteworld.configs.cobra import common
and any relevant context from other files:
# Path: spriteworld/factor_distributions.py
# _MAX_TRIES = int(1e5)
# class AbstractDistribution(object):
# class Continuous(AbstractDistribution):
# class Discrete(AbstractDistribution):
# class Mixture(AbstractDistribution):
# class Intersection(AbstractDistribution):
# class Product(AbstractDistribution):
# class SetMinus(AbstractDistribution):
# class Selection(AbstractDistribution):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def __str__(self):
# def _get_rng(self, rng=None):
# def keys(self):
# def __init__(self, key, minval, maxval, dtype='float32'):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, key, candidates, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, index_for_sampling=0):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, hold_out):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, filtering):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
#
# Path: spriteworld/sprite_generators.py
# def generate_sprites(factor_dist, num_sprites=1):
# def _generate():
# def chain_generators(*sprite_generators):
# def _generate():
# def sample_generator(sprite_generators, p=None):
# def _generate():
# def shuffle(sprite_generator):
# def _generate():
#
# Path: spriteworld/tasks.py
# class AbstractTask(object):
# class NoReward(AbstractTask):
# class FindGoalPosition(AbstractTask):
# class Clustering(AbstractTask):
# class MetaAggregated(AbstractTask):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self):
# def reward(self, unused_sprites):
# def success(self, unused_sprites):
# def __init__(self,
# filter_distrib=None,
# goal_position=(0.5, 0.5),
# terminate_distance=0.05,
# terminate_bonus=0.0,
# weights_dimensions=(1, 1),
# sparse_reward=False,
# raw_reward_multiplier=50):
# def _single_sprite_reward(self, sprite):
# def _filtered_sprites_rewards(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# cluster_distribs,
# termination_threshold=2.5,
# terminate_bonus=0.0,
# sparse_reward=False,
# reward_range=10):
# def _cluster_assignments(self, sprites):
# def _compute_clustering_metric(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# subtasks,
# reward_aggregator='sum',
# termination_criterion='all',
# terminate_bonus=0.0):
# def reward(self, sprites):
# def success(self, sprites):
# REWARD_AGGREGATOR = {
# 'sum': np.nansum,
# 'max': np.nanmax,
# 'min': np.nanmin,
# 'mean': np.nanmean
# }
# TERMINATION_CRITERION = {'all': np.all, 'any': np.any}
#
# Path: spriteworld/configs/cobra/common.py
# def action_space():
# def renderers():
. Output only the next line. | 'distrib': distribs.Continuous('c0', 0.9, 1.), # red |
Continue the code snippet: <|code_start|>def get_config(mode='train'):
"""Generate environment config.
Args:
mode: 'train' or 'test'.
Returns:
config: Dictionary defining task/environment configuration. Can be fed as
kwargs to environment.Environment.
"""
# Create the subtasks and their corresponding sprite generators
subtasks = []
sprite_gen_per_subtask = []
for subtask in SUBTASKS:
subtasks.append(tasks.FindGoalPosition(
filter_distrib=subtask['distrib'],
goal_position=subtask['goal_position'],
terminate_distance=TERMINATE_DISTANCE,
raw_reward_multiplier=RAW_REWARD_MULTIPLIER))
factors = distribs.Product((
subtask['distrib'],
distribs.Continuous('x', 0.1, 0.9),
distribs.Continuous('y', 0.1, 0.9),
distribs.Discrete('shape', ['square', 'triangle', 'circle']),
distribs.Discrete('scale', [0.13]),
distribs.Continuous('c1', 0.3, 1.),
distribs.Continuous('c2', 0.9, 1.),
))
sprite_gen_per_subtask.append(
<|code_end|>
. Use current file imports:
import itertools
import os
import numpy as np
from spriteworld import factor_distributions as distribs
from spriteworld import sprite_generators
from spriteworld import tasks
from spriteworld.configs.cobra import common
and context (classes, functions, or code) from other files:
# Path: spriteworld/factor_distributions.py
# _MAX_TRIES = int(1e5)
# class AbstractDistribution(object):
# class Continuous(AbstractDistribution):
# class Discrete(AbstractDistribution):
# class Mixture(AbstractDistribution):
# class Intersection(AbstractDistribution):
# class Product(AbstractDistribution):
# class SetMinus(AbstractDistribution):
# class Selection(AbstractDistribution):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def __str__(self):
# def _get_rng(self, rng=None):
# def keys(self):
# def __init__(self, key, minval, maxval, dtype='float32'):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, key, candidates, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, index_for_sampling=0):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, hold_out):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, filtering):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
#
# Path: spriteworld/sprite_generators.py
# def generate_sprites(factor_dist, num_sprites=1):
# def _generate():
# def chain_generators(*sprite_generators):
# def _generate():
# def sample_generator(sprite_generators, p=None):
# def _generate():
# def shuffle(sprite_generator):
# def _generate():
#
# Path: spriteworld/tasks.py
# class AbstractTask(object):
# class NoReward(AbstractTask):
# class FindGoalPosition(AbstractTask):
# class Clustering(AbstractTask):
# class MetaAggregated(AbstractTask):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self):
# def reward(self, unused_sprites):
# def success(self, unused_sprites):
# def __init__(self,
# filter_distrib=None,
# goal_position=(0.5, 0.5),
# terminate_distance=0.05,
# terminate_bonus=0.0,
# weights_dimensions=(1, 1),
# sparse_reward=False,
# raw_reward_multiplier=50):
# def _single_sprite_reward(self, sprite):
# def _filtered_sprites_rewards(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# cluster_distribs,
# termination_threshold=2.5,
# terminate_bonus=0.0,
# sparse_reward=False,
# reward_range=10):
# def _cluster_assignments(self, sprites):
# def _compute_clustering_metric(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# subtasks,
# reward_aggregator='sum',
# termination_criterion='all',
# terminate_bonus=0.0):
# def reward(self, sprites):
# def success(self, sprites):
# REWARD_AGGREGATOR = {
# 'sum': np.nansum,
# 'max': np.nanmax,
# 'min': np.nanmin,
# 'mean': np.nanmean
# }
# TERMINATION_CRITERION = {'all': np.all, 'any': np.any}
#
# Path: spriteworld/configs/cobra/common.py
# def action_space():
# def renderers():
. Output only the next line. | sprite_generators.generate_sprites(factors, num_sprites=1)) |
Here is a snippet: <|code_start|> {
'distrib': distribs.Continuous('c0', 0.27, 0.37), # green
'goal_position': np.array([0.25, 0.75])
},
{
'distrib': distribs.Continuous('c0', 0.73, 0.83), # purple
'goal_position': np.array([0.25, 0.25])
},
{
'distrib': distribs.Continuous('c0', 0.1, 0.2), # yellow
'goal_position': np.array([0.5, 0.5])
},
)
def get_config(mode='train'):
"""Generate environment config.
Args:
mode: 'train' or 'test'.
Returns:
config: Dictionary defining task/environment configuration. Can be fed as
kwargs to environment.Environment.
"""
# Create the subtasks and their corresponding sprite generators
subtasks = []
sprite_gen_per_subtask = []
for subtask in SUBTASKS:
<|code_end|>
. Write the next line using the current file imports:
import itertools
import os
import numpy as np
from spriteworld import factor_distributions as distribs
from spriteworld import sprite_generators
from spriteworld import tasks
from spriteworld.configs.cobra import common
and context from other files:
# Path: spriteworld/factor_distributions.py
# _MAX_TRIES = int(1e5)
# class AbstractDistribution(object):
# class Continuous(AbstractDistribution):
# class Discrete(AbstractDistribution):
# class Mixture(AbstractDistribution):
# class Intersection(AbstractDistribution):
# class Product(AbstractDistribution):
# class SetMinus(AbstractDistribution):
# class Selection(AbstractDistribution):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def __str__(self):
# def _get_rng(self, rng=None):
# def keys(self):
# def __init__(self, key, minval, maxval, dtype='float32'):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, key, candidates, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, index_for_sampling=0):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, hold_out):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, filtering):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
#
# Path: spriteworld/sprite_generators.py
# def generate_sprites(factor_dist, num_sprites=1):
# def _generate():
# def chain_generators(*sprite_generators):
# def _generate():
# def sample_generator(sprite_generators, p=None):
# def _generate():
# def shuffle(sprite_generator):
# def _generate():
#
# Path: spriteworld/tasks.py
# class AbstractTask(object):
# class NoReward(AbstractTask):
# class FindGoalPosition(AbstractTask):
# class Clustering(AbstractTask):
# class MetaAggregated(AbstractTask):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self):
# def reward(self, unused_sprites):
# def success(self, unused_sprites):
# def __init__(self,
# filter_distrib=None,
# goal_position=(0.5, 0.5),
# terminate_distance=0.05,
# terminate_bonus=0.0,
# weights_dimensions=(1, 1),
# sparse_reward=False,
# raw_reward_multiplier=50):
# def _single_sprite_reward(self, sprite):
# def _filtered_sprites_rewards(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# cluster_distribs,
# termination_threshold=2.5,
# terminate_bonus=0.0,
# sparse_reward=False,
# reward_range=10):
# def _cluster_assignments(self, sprites):
# def _compute_clustering_metric(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# subtasks,
# reward_aggregator='sum',
# termination_criterion='all',
# terminate_bonus=0.0):
# def reward(self, sprites):
# def success(self, sprites):
# REWARD_AGGREGATOR = {
# 'sum': np.nansum,
# 'max': np.nanmax,
# 'min': np.nanmin,
# 'mean': np.nanmean
# }
# TERMINATION_CRITERION = {'all': np.all, 'any': np.any}
#
# Path: spriteworld/configs/cobra/common.py
# def action_space():
# def renderers():
, which may include functions, classes, or code. Output only the next line. | subtasks.append(tasks.FindGoalPosition( |
Continue the code snippet: <|code_start|> distribs.Continuous('c2', 0.9, 1.),
))
sprite_gen_per_subtask.append(
sprite_generators.generate_sprites(factors, num_sprites=1))
# Consider all combinations of subtasks
subtask_combos = list(
itertools.combinations(np.arange(len(SUBTASKS)), NUM_TARGETS))
if mode == 'train':
# Randomly sample a combination of subtasks, holding one combination out
sprite_gen = sprite_generators.sample_generator([
sprite_generators.chain_generators(
*[sprite_gen_per_subtask[i] for i in c]) for c in subtask_combos[1:]
])
elif mode == 'test':
# Use the held-out subtask combination for testing
sprite_gen = sprite_generators.chain_generators(
*[sprite_gen_per_subtask[i] for i in subtask_combos[0]])
else:
raise ValueError('Invalide mode {}.'.format(mode))
# Randomize sprite ordering to eliminate any task information from occlusions
sprite_gen = sprite_generators.shuffle(sprite_gen)
task = tasks.MetaAggregated(
subtasks, reward_aggregator='sum', termination_criterion='all')
config = {
'task': task,
<|code_end|>
. Use current file imports:
import itertools
import os
import numpy as np
from spriteworld import factor_distributions as distribs
from spriteworld import sprite_generators
from spriteworld import tasks
from spriteworld.configs.cobra import common
and context (classes, functions, or code) from other files:
# Path: spriteworld/factor_distributions.py
# _MAX_TRIES = int(1e5)
# class AbstractDistribution(object):
# class Continuous(AbstractDistribution):
# class Discrete(AbstractDistribution):
# class Mixture(AbstractDistribution):
# class Intersection(AbstractDistribution):
# class Product(AbstractDistribution):
# class SetMinus(AbstractDistribution):
# class Selection(AbstractDistribution):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def __str__(self):
# def _get_rng(self, rng=None):
# def keys(self):
# def __init__(self, key, minval, maxval, dtype='float32'):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, key, candidates, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, index_for_sampling=0):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, hold_out):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, filtering):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
#
# Path: spriteworld/sprite_generators.py
# def generate_sprites(factor_dist, num_sprites=1):
# def _generate():
# def chain_generators(*sprite_generators):
# def _generate():
# def sample_generator(sprite_generators, p=None):
# def _generate():
# def shuffle(sprite_generator):
# def _generate():
#
# Path: spriteworld/tasks.py
# class AbstractTask(object):
# class NoReward(AbstractTask):
# class FindGoalPosition(AbstractTask):
# class Clustering(AbstractTask):
# class MetaAggregated(AbstractTask):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self):
# def reward(self, unused_sprites):
# def success(self, unused_sprites):
# def __init__(self,
# filter_distrib=None,
# goal_position=(0.5, 0.5),
# terminate_distance=0.05,
# terminate_bonus=0.0,
# weights_dimensions=(1, 1),
# sparse_reward=False,
# raw_reward_multiplier=50):
# def _single_sprite_reward(self, sprite):
# def _filtered_sprites_rewards(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# cluster_distribs,
# termination_threshold=2.5,
# terminate_bonus=0.0,
# sparse_reward=False,
# reward_range=10):
# def _cluster_assignments(self, sprites):
# def _compute_clustering_metric(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# subtasks,
# reward_aggregator='sum',
# termination_criterion='all',
# terminate_bonus=0.0):
# def reward(self, sprites):
# def success(self, sprites):
# REWARD_AGGREGATOR = {
# 'sum': np.nansum,
# 'max': np.nanmax,
# 'min': np.nanmin,
# 'mean': np.nanmean
# }
# TERMINATION_CRITERION = {'all': np.all, 'any': np.any}
#
# Path: spriteworld/configs/cobra/common.py
# def action_space():
# def renderers():
. Output only the next line. | 'action_space': common.action_space(), |
Next line prediction: <|code_start|># Copyright 2019 DeepMind Technologies Limited.
#
# 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.
# ============================================================================
# python2 python3
"""Tests for sprite_generators."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
<|code_end|>
. Use current file imports:
(from absl.testing import absltest
from absl.testing import parameterized
from spriteworld import factor_distributions as distribs
from spriteworld import sprite
from spriteworld import sprite_generators
import numpy as np)
and context including class names, function names, or small code snippets from other files:
# Path: spriteworld/factor_distributions.py
# _MAX_TRIES = int(1e5)
# class AbstractDistribution(object):
# class Continuous(AbstractDistribution):
# class Discrete(AbstractDistribution):
# class Mixture(AbstractDistribution):
# class Intersection(AbstractDistribution):
# class Product(AbstractDistribution):
# class SetMinus(AbstractDistribution):
# class Selection(AbstractDistribution):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def __str__(self):
# def _get_rng(self, rng=None):
# def keys(self):
# def __init__(self, key, minval, maxval, dtype='float32'):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, key, candidates, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, index_for_sampling=0):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, hold_out):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, filtering):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
#
# Path: spriteworld/sprite.py
# FACTOR_NAMES = (
# 'x', # x-position of sprite center-of-mass (float)
# 'y', # y-position of sprite center-of-mass (float)
# 'shape', # shape (string)
# 'angle', # angle in degrees (scalar)
# 'scale', # size of sprite (float)
# 'c0', # first color component (scalar)
# 'c1', # second color component (scalar)
# 'c2', # third color component (scalar)
# 'x_vel', # x-component of velocity (float)
# 'y_vel', # y-component of velocity (float)
# )
# _MAX_TRIES = int(1e6)
# class Sprite(object):
# def __init__(self,
# x=0.5,
# y=0.5,
# shape='square',
# angle=0,
# scale=0.1,
# c0=0,
# c1=0,
# c2=0,
# x_vel=0.0,
# y_vel=0.0):
# def _reset_centered_path(self):
# def move(self, motion, keep_in_frame=False):
# def update_position(self, keep_in_frame=False):
# def contains_point(self, point):
# def sample_contained_position(self):
# def vertices(self):
# def out_of_frame(self):
# def x(self):
# def y(self):
# def shape(self):
# def shape(self, s):
# def angle(self):
# def angle(self, a):
# def scale(self):
# def scale(self, s):
# def c0(self):
# def c1(self):
# def c2(self):
# def x_vel(self):
# def y_vel(self):
# def color(self):
# def position(self):
# def velocity(self):
# def factors(self):
#
# Path: spriteworld/sprite_generators.py
# def generate_sprites(factor_dist, num_sprites=1):
# def _generate():
# def chain_generators(*sprite_generators):
# def _generate():
# def sample_generator(sprite_generators, p=None):
# def _generate():
# def shuffle(sprite_generator):
# def _generate():
. Output only the next line. | _distrib_0 = distribs.Product([ |
Continue the code snippet: <|code_start|>from __future__ import print_function
_distrib_0 = distribs.Product([
distribs.Discrete('x', [0.5]),
distribs.Discrete('y', [0.5]),
distribs.Discrete('shape', ['square', 'triangle']),
distribs.Discrete('c0', [255]),
distribs.Discrete('c1', [255]),
distribs.Discrete('c2', [255]),
])
_distrib_1 = distribs.Product([
distribs.Discrete('x', [0.5]),
distribs.Discrete('y', [0.5]),
distribs.Discrete('shape', ['hexagon', 'circle', 'star_5']),
distribs.Discrete('c0', [255]),
distribs.Discrete('c1', [255]),
distribs.Discrete('c2', [255]),
])
class SpriteGeneratorTest(parameterized.TestCase):
@parameterized.parameters(1, 2, 5)
def testGenerateSpritesLengthType(self, num_sprites):
g = sprite_generators.generate_sprites(_distrib_0, num_sprites=num_sprites)
sprite_list = g()
self.assertIsInstance(sprite_list, list)
self.assertLen(sprite_list, num_sprites)
<|code_end|>
. Use current file imports:
from absl.testing import absltest
from absl.testing import parameterized
from spriteworld import factor_distributions as distribs
from spriteworld import sprite
from spriteworld import sprite_generators
import numpy as np
and context (classes, functions, or code) from other files:
# Path: spriteworld/factor_distributions.py
# _MAX_TRIES = int(1e5)
# class AbstractDistribution(object):
# class Continuous(AbstractDistribution):
# class Discrete(AbstractDistribution):
# class Mixture(AbstractDistribution):
# class Intersection(AbstractDistribution):
# class Product(AbstractDistribution):
# class SetMinus(AbstractDistribution):
# class Selection(AbstractDistribution):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def __str__(self):
# def _get_rng(self, rng=None):
# def keys(self):
# def __init__(self, key, minval, maxval, dtype='float32'):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, key, candidates, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, index_for_sampling=0):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, hold_out):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, filtering):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
#
# Path: spriteworld/sprite.py
# FACTOR_NAMES = (
# 'x', # x-position of sprite center-of-mass (float)
# 'y', # y-position of sprite center-of-mass (float)
# 'shape', # shape (string)
# 'angle', # angle in degrees (scalar)
# 'scale', # size of sprite (float)
# 'c0', # first color component (scalar)
# 'c1', # second color component (scalar)
# 'c2', # third color component (scalar)
# 'x_vel', # x-component of velocity (float)
# 'y_vel', # y-component of velocity (float)
# )
# _MAX_TRIES = int(1e6)
# class Sprite(object):
# def __init__(self,
# x=0.5,
# y=0.5,
# shape='square',
# angle=0,
# scale=0.1,
# c0=0,
# c1=0,
# c2=0,
# x_vel=0.0,
# y_vel=0.0):
# def _reset_centered_path(self):
# def move(self, motion, keep_in_frame=False):
# def update_position(self, keep_in_frame=False):
# def contains_point(self, point):
# def sample_contained_position(self):
# def vertices(self):
# def out_of_frame(self):
# def x(self):
# def y(self):
# def shape(self):
# def shape(self, s):
# def angle(self):
# def angle(self, a):
# def scale(self):
# def scale(self, s):
# def c0(self):
# def c1(self):
# def c2(self):
# def x_vel(self):
# def y_vel(self):
# def color(self):
# def position(self):
# def velocity(self):
# def factors(self):
#
# Path: spriteworld/sprite_generators.py
# def generate_sprites(factor_dist, num_sprites=1):
# def _generate():
# def chain_generators(*sprite_generators):
# def _generate():
# def sample_generator(sprite_generators, p=None):
# def _generate():
# def shuffle(sprite_generator):
# def _generate():
. Output only the next line. | self.assertIsInstance(sprite_list[0], sprite.Sprite) |
Continue the code snippet: <|code_start|>"""Tests for sprite_generators."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
_distrib_0 = distribs.Product([
distribs.Discrete('x', [0.5]),
distribs.Discrete('y', [0.5]),
distribs.Discrete('shape', ['square', 'triangle']),
distribs.Discrete('c0', [255]),
distribs.Discrete('c1', [255]),
distribs.Discrete('c2', [255]),
])
_distrib_1 = distribs.Product([
distribs.Discrete('x', [0.5]),
distribs.Discrete('y', [0.5]),
distribs.Discrete('shape', ['hexagon', 'circle', 'star_5']),
distribs.Discrete('c0', [255]),
distribs.Discrete('c1', [255]),
distribs.Discrete('c2', [255]),
])
class SpriteGeneratorTest(parameterized.TestCase):
@parameterized.parameters(1, 2, 5)
def testGenerateSpritesLengthType(self, num_sprites):
<|code_end|>
. Use current file imports:
from absl.testing import absltest
from absl.testing import parameterized
from spriteworld import factor_distributions as distribs
from spriteworld import sprite
from spriteworld import sprite_generators
import numpy as np
and context (classes, functions, or code) from other files:
# Path: spriteworld/factor_distributions.py
# _MAX_TRIES = int(1e5)
# class AbstractDistribution(object):
# class Continuous(AbstractDistribution):
# class Discrete(AbstractDistribution):
# class Mixture(AbstractDistribution):
# class Intersection(AbstractDistribution):
# class Product(AbstractDistribution):
# class SetMinus(AbstractDistribution):
# class Selection(AbstractDistribution):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def __str__(self):
# def _get_rng(self, rng=None):
# def keys(self):
# def __init__(self, key, minval, maxval, dtype='float32'):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, key, candidates, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, index_for_sampling=0):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, hold_out):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, filtering):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
#
# Path: spriteworld/sprite.py
# FACTOR_NAMES = (
# 'x', # x-position of sprite center-of-mass (float)
# 'y', # y-position of sprite center-of-mass (float)
# 'shape', # shape (string)
# 'angle', # angle in degrees (scalar)
# 'scale', # size of sprite (float)
# 'c0', # first color component (scalar)
# 'c1', # second color component (scalar)
# 'c2', # third color component (scalar)
# 'x_vel', # x-component of velocity (float)
# 'y_vel', # y-component of velocity (float)
# )
# _MAX_TRIES = int(1e6)
# class Sprite(object):
# def __init__(self,
# x=0.5,
# y=0.5,
# shape='square',
# angle=0,
# scale=0.1,
# c0=0,
# c1=0,
# c2=0,
# x_vel=0.0,
# y_vel=0.0):
# def _reset_centered_path(self):
# def move(self, motion, keep_in_frame=False):
# def update_position(self, keep_in_frame=False):
# def contains_point(self, point):
# def sample_contained_position(self):
# def vertices(self):
# def out_of_frame(self):
# def x(self):
# def y(self):
# def shape(self):
# def shape(self, s):
# def angle(self):
# def angle(self, a):
# def scale(self):
# def scale(self, s):
# def c0(self):
# def c1(self):
# def c2(self):
# def x_vel(self):
# def y_vel(self):
# def color(self):
# def position(self):
# def velocity(self):
# def factors(self):
#
# Path: spriteworld/sprite_generators.py
# def generate_sprites(factor_dist, num_sprites=1):
# def _generate():
# def chain_generators(*sprite_generators):
# def _generate():
# def sample_generator(sprite_generators, p=None):
# def _generate():
# def shuffle(sprite_generator):
# def _generate():
. Output only the next line. | g = sprite_generators.generate_sprites(_distrib_0, num_sprites=num_sprites) |
Based on the snippet: <|code_start|># Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
# python2 python3
"""Generators for producing lists of sprites based on factor distributions."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def generate_sprites(factor_dist, num_sprites=1):
"""Create callable that samples sprites from a factor distribution.
Args:
factor_dist: The factor distribution from which to sample. Should be an
instance of factor_distributions.AbstractDistribution.
num_sprites: Int or callable returning int. Number of sprites to generate
per call.
Returns:
_generate: Callable that returns a list of Sprites.
"""
def _generate():
n = num_sprites() if callable(num_sprites) else num_sprites
<|code_end|>
, predict the immediate next line with the help of imports:
import itertools
import numpy as np
from spriteworld import sprite
and context (classes, functions, sometimes code) from other files:
# Path: spriteworld/sprite.py
# FACTOR_NAMES = (
# 'x', # x-position of sprite center-of-mass (float)
# 'y', # y-position of sprite center-of-mass (float)
# 'shape', # shape (string)
# 'angle', # angle in degrees (scalar)
# 'scale', # size of sprite (float)
# 'c0', # first color component (scalar)
# 'c1', # second color component (scalar)
# 'c2', # third color component (scalar)
# 'x_vel', # x-component of velocity (float)
# 'y_vel', # y-component of velocity (float)
# )
# _MAX_TRIES = int(1e6)
# class Sprite(object):
# def __init__(self,
# x=0.5,
# y=0.5,
# shape='square',
# angle=0,
# scale=0.1,
# c0=0,
# c1=0,
# c2=0,
# x_vel=0.0,
# y_vel=0.0):
# def _reset_centered_path(self):
# def move(self, motion, keep_in_frame=False):
# def update_position(self, keep_in_frame=False):
# def contains_point(self, point):
# def sample_contained_position(self):
# def vertices(self):
# def out_of_frame(self):
# def x(self):
# def y(self):
# def shape(self):
# def shape(self, s):
# def angle(self):
# def angle(self, a):
# def scale(self):
# def scale(self, s):
# def c0(self):
# def c1(self):
# def c2(self):
# def x_vel(self):
# def y_vel(self):
# def color(self):
# def position(self):
# def velocity(self):
# def factors(self):
. Output only the next line. | sprites = [sprite.Sprite(**factor_dist.sample()) for _ in range(n)] |
Given the following code snippet before the placeholder: <|code_start|>
@parameterized.parameters((1, ('x', 'y', 'scale', 'c0', 'c1', 'c2', 'shape',
'angle', 'x_vel', 'y_vel')),
(1, ('x', 'y', 'scale', 'c0', 'c1', 'c2', 'shape')),
(2, ('x', 'y', 'scale', 'c0', 'c1', 'c2', 'shape')),
(5, ('x', 'y', 'angle', 'x_vel', 'y_vel')))
def testObservationSpec(self, num_sprites, factors):
sprites = [sprite_lib.Sprite() for _ in range(num_sprites)]
renderer = handcrafted.SpriteFactors(factors=factors)
renderer.render(sprites=sprites)
obs_spec = renderer.observation_spec()
for v in obs_spec[0].values():
self.assertEqual(v.shape, ())
obs_spec_keys = [set(x) for x in obs_spec]
self.assertSequenceEqual(obs_spec_keys, num_sprites * [set(factors)])
@parameterized.parameters(
(0.5, 0.5, 'square', 0, 0, 255, 0.5, 0),
(0.5, 0.5, 'square', 255, 0, 0, 0.5, 0),
(0.5, 0.8, 'octagon', 0.4, 0.8, 0.5, 0.6, 90),
(0.5, 0.3, 'star_5', 180, 180, 0, 0.2, 240),
)
def testAttributesSingleton(self, x, y, shape, c0, c1, c2, scale, angle):
sprite = sprite_lib.Sprite(
x=x, y=y, shape=shape, c0=c0, c1=c1, c2=c2, scale=scale, angle=angle)
renderer = handcrafted.SpriteFactors()
outputs = renderer.render(sprites=[sprite])[0]
<|code_end|>
, predict the next line using imports from the current file:
from absl.testing import absltest
from absl.testing import parameterized
from six.moves import range
from spriteworld import constants as const
from spriteworld import sprite as sprite_lib
from spriteworld.renderers import handcrafted
import numpy as np
and context including class names, function names, and sometimes code from other files:
# Path: spriteworld/constants.py
# SHAPES = {
# 'triangle': shapes.polygon(num_sides=3, theta_0=np.pi/2),
# 'square': shapes.polygon(num_sides=4, theta_0=np.pi/4),
# 'pentagon': shapes.polygon(num_sides=5, theta_0=np.pi/2),
# 'hexagon': shapes.polygon(num_sides=6),
# 'octagon': shapes.polygon(num_sides=8),
# 'circle': shapes.polygon(num_sides=30),
# 'star_4': shapes.star(num_sides=4, theta_0=np.pi/4),
# 'star_5': shapes.star(num_sides=5, theta_0=np.pi + np.pi/10),
# 'star_6': shapes.star(num_sides=6),
# 'spoke_4': shapes.spokes(num_sides=4, theta_0=np.pi/4),
# 'spoke_5': shapes.spokes(num_sides=5, theta_0=np.pi + np.pi/10),
# 'spoke_6': shapes.spokes(num_sides=6),
# }
# class ShapeType(enum.IntEnum):
#
# Path: spriteworld/sprite.py
# FACTOR_NAMES = (
# 'x', # x-position of sprite center-of-mass (float)
# 'y', # y-position of sprite center-of-mass (float)
# 'shape', # shape (string)
# 'angle', # angle in degrees (scalar)
# 'scale', # size of sprite (float)
# 'c0', # first color component (scalar)
# 'c1', # second color component (scalar)
# 'c2', # third color component (scalar)
# 'x_vel', # x-component of velocity (float)
# 'y_vel', # y-component of velocity (float)
# )
# _MAX_TRIES = int(1e6)
# class Sprite(object):
# def __init__(self,
# x=0.5,
# y=0.5,
# shape='square',
# angle=0,
# scale=0.1,
# c0=0,
# c1=0,
# c2=0,
# x_vel=0.0,
# y_vel=0.0):
# def _reset_centered_path(self):
# def move(self, motion, keep_in_frame=False):
# def update_position(self, keep_in_frame=False):
# def contains_point(self, point):
# def sample_contained_position(self):
# def vertices(self):
# def out_of_frame(self):
# def x(self):
# def y(self):
# def shape(self):
# def shape(self, s):
# def angle(self):
# def angle(self, a):
# def scale(self):
# def scale(self, s):
# def c0(self):
# def c1(self):
# def c2(self):
# def x_vel(self):
# def y_vel(self):
# def color(self):
# def position(self):
# def velocity(self):
# def factors(self):
#
# Path: spriteworld/renderers/handcrafted.py
# class SpriteFactors(abstract_renderer.AbstractRenderer):
# class SpritePassthrough(abstract_renderer.AbstractRenderer):
# class Success(abstract_renderer.AbstractRenderer):
# def __init__(self, factors=sprite_lib.FACTOR_NAMES):
# def render(self, sprites=(), global_state=None):
# def _process_factor(name, value):
# def _sprite_to_factors(sprite):
# def observation_spec(self):
# def __init__(self):
# def render(self, sprites=(), global_state=None):
# def observation_spec(self):
# def render(self, sprites=(), global_state=None):
# def observation_spec(self):
. Output only the next line. | self.assertEqual(outputs['shape'], const.ShapeType[shape].value) |
Continue the code snippet: <|code_start|># 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.
# ============================================================================
# python2 python3
"""Tests for handcrafted."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class SpriteFactorsTest(parameterized.TestCase):
def testWrongFactors(self):
handcrafted.SpriteFactors(factors=('x', 'y', 'scale'))
with self.assertRaises(ValueError):
handcrafted.SpriteFactors(factors=('position', 'scale'))
with self.assertRaises(ValueError):
handcrafted.SpriteFactors(factors=('x', 'y', 'size'))
def testSingleton(self):
<|code_end|>
. Use current file imports:
from absl.testing import absltest
from absl.testing import parameterized
from six.moves import range
from spriteworld import constants as const
from spriteworld import sprite as sprite_lib
from spriteworld.renderers import handcrafted
import numpy as np
and context (classes, functions, or code) from other files:
# Path: spriteworld/constants.py
# SHAPES = {
# 'triangle': shapes.polygon(num_sides=3, theta_0=np.pi/2),
# 'square': shapes.polygon(num_sides=4, theta_0=np.pi/4),
# 'pentagon': shapes.polygon(num_sides=5, theta_0=np.pi/2),
# 'hexagon': shapes.polygon(num_sides=6),
# 'octagon': shapes.polygon(num_sides=8),
# 'circle': shapes.polygon(num_sides=30),
# 'star_4': shapes.star(num_sides=4, theta_0=np.pi/4),
# 'star_5': shapes.star(num_sides=5, theta_0=np.pi + np.pi/10),
# 'star_6': shapes.star(num_sides=6),
# 'spoke_4': shapes.spokes(num_sides=4, theta_0=np.pi/4),
# 'spoke_5': shapes.spokes(num_sides=5, theta_0=np.pi + np.pi/10),
# 'spoke_6': shapes.spokes(num_sides=6),
# }
# class ShapeType(enum.IntEnum):
#
# Path: spriteworld/sprite.py
# FACTOR_NAMES = (
# 'x', # x-position of sprite center-of-mass (float)
# 'y', # y-position of sprite center-of-mass (float)
# 'shape', # shape (string)
# 'angle', # angle in degrees (scalar)
# 'scale', # size of sprite (float)
# 'c0', # first color component (scalar)
# 'c1', # second color component (scalar)
# 'c2', # third color component (scalar)
# 'x_vel', # x-component of velocity (float)
# 'y_vel', # y-component of velocity (float)
# )
# _MAX_TRIES = int(1e6)
# class Sprite(object):
# def __init__(self,
# x=0.5,
# y=0.5,
# shape='square',
# angle=0,
# scale=0.1,
# c0=0,
# c1=0,
# c2=0,
# x_vel=0.0,
# y_vel=0.0):
# def _reset_centered_path(self):
# def move(self, motion, keep_in_frame=False):
# def update_position(self, keep_in_frame=False):
# def contains_point(self, point):
# def sample_contained_position(self):
# def vertices(self):
# def out_of_frame(self):
# def x(self):
# def y(self):
# def shape(self):
# def shape(self, s):
# def angle(self):
# def angle(self, a):
# def scale(self):
# def scale(self, s):
# def c0(self):
# def c1(self):
# def c2(self):
# def x_vel(self):
# def y_vel(self):
# def color(self):
# def position(self):
# def velocity(self):
# def factors(self):
#
# Path: spriteworld/renderers/handcrafted.py
# class SpriteFactors(abstract_renderer.AbstractRenderer):
# class SpritePassthrough(abstract_renderer.AbstractRenderer):
# class Success(abstract_renderer.AbstractRenderer):
# def __init__(self, factors=sprite_lib.FACTOR_NAMES):
# def render(self, sprites=(), global_state=None):
# def _process_factor(name, value):
# def _sprite_to_factors(sprite):
# def observation_spec(self):
# def __init__(self):
# def render(self, sprites=(), global_state=None):
# def observation_spec(self):
# def render(self, sprites=(), global_state=None):
# def observation_spec(self):
. Output only the next line. | sprite = sprite_lib.Sprite( |
Using the snippet: <|code_start|># Copyright 2019 DeepMind Technologies Limited.
#
# 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.
# ============================================================================
# python2 python3
"""Tests for handcrafted."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class SpriteFactorsTest(parameterized.TestCase):
def testWrongFactors(self):
<|code_end|>
, determine the next line of code. You have imports:
from absl.testing import absltest
from absl.testing import parameterized
from six.moves import range
from spriteworld import constants as const
from spriteworld import sprite as sprite_lib
from spriteworld.renderers import handcrafted
import numpy as np
and context (class names, function names, or code) available:
# Path: spriteworld/constants.py
# SHAPES = {
# 'triangle': shapes.polygon(num_sides=3, theta_0=np.pi/2),
# 'square': shapes.polygon(num_sides=4, theta_0=np.pi/4),
# 'pentagon': shapes.polygon(num_sides=5, theta_0=np.pi/2),
# 'hexagon': shapes.polygon(num_sides=6),
# 'octagon': shapes.polygon(num_sides=8),
# 'circle': shapes.polygon(num_sides=30),
# 'star_4': shapes.star(num_sides=4, theta_0=np.pi/4),
# 'star_5': shapes.star(num_sides=5, theta_0=np.pi + np.pi/10),
# 'star_6': shapes.star(num_sides=6),
# 'spoke_4': shapes.spokes(num_sides=4, theta_0=np.pi/4),
# 'spoke_5': shapes.spokes(num_sides=5, theta_0=np.pi + np.pi/10),
# 'spoke_6': shapes.spokes(num_sides=6),
# }
# class ShapeType(enum.IntEnum):
#
# Path: spriteworld/sprite.py
# FACTOR_NAMES = (
# 'x', # x-position of sprite center-of-mass (float)
# 'y', # y-position of sprite center-of-mass (float)
# 'shape', # shape (string)
# 'angle', # angle in degrees (scalar)
# 'scale', # size of sprite (float)
# 'c0', # first color component (scalar)
# 'c1', # second color component (scalar)
# 'c2', # third color component (scalar)
# 'x_vel', # x-component of velocity (float)
# 'y_vel', # y-component of velocity (float)
# )
# _MAX_TRIES = int(1e6)
# class Sprite(object):
# def __init__(self,
# x=0.5,
# y=0.5,
# shape='square',
# angle=0,
# scale=0.1,
# c0=0,
# c1=0,
# c2=0,
# x_vel=0.0,
# y_vel=0.0):
# def _reset_centered_path(self):
# def move(self, motion, keep_in_frame=False):
# def update_position(self, keep_in_frame=False):
# def contains_point(self, point):
# def sample_contained_position(self):
# def vertices(self):
# def out_of_frame(self):
# def x(self):
# def y(self):
# def shape(self):
# def shape(self, s):
# def angle(self):
# def angle(self, a):
# def scale(self):
# def scale(self, s):
# def c0(self):
# def c1(self):
# def c2(self):
# def x_vel(self):
# def y_vel(self):
# def color(self):
# def position(self):
# def velocity(self):
# def factors(self):
#
# Path: spriteworld/renderers/handcrafted.py
# class SpriteFactors(abstract_renderer.AbstractRenderer):
# class SpritePassthrough(abstract_renderer.AbstractRenderer):
# class Success(abstract_renderer.AbstractRenderer):
# def __init__(self, factors=sprite_lib.FACTOR_NAMES):
# def render(self, sprites=(), global_state=None):
# def _process_factor(name, value):
# def _sprite_to_factors(sprite):
# def observation_spec(self):
# def __init__(self):
# def render(self, sprites=(), global_state=None):
# def observation_spec(self):
# def render(self, sprites=(), global_state=None):
# def observation_spec(self):
. Output only the next line. | handcrafted.SpriteFactors(factors=('x', 'y', 'scale')) |
Continue the code snippet: <|code_start|># Copyright 2019 DeepMind Technologies Limited.
#
# 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.
# ============================================================================
# python2 python3
"""Tests for sprite."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class SpriteTest(parameterized.TestCase):
def testBasicInitialization(self):
<|code_end|>
. Use current file imports:
from absl.testing import absltest
from absl.testing import parameterized
from six.moves import range
from spriteworld import sprite
import numpy as np
and context (classes, functions, or code) from other files:
# Path: spriteworld/sprite.py
# FACTOR_NAMES = (
# 'x', # x-position of sprite center-of-mass (float)
# 'y', # y-position of sprite center-of-mass (float)
# 'shape', # shape (string)
# 'angle', # angle in degrees (scalar)
# 'scale', # size of sprite (float)
# 'c0', # first color component (scalar)
# 'c1', # second color component (scalar)
# 'c2', # third color component (scalar)
# 'x_vel', # x-component of velocity (float)
# 'y_vel', # y-component of velocity (float)
# )
# _MAX_TRIES = int(1e6)
# class Sprite(object):
# def __init__(self,
# x=0.5,
# y=0.5,
# shape='square',
# angle=0,
# scale=0.1,
# c0=0,
# c1=0,
# c2=0,
# x_vel=0.0,
# y_vel=0.0):
# def _reset_centered_path(self):
# def move(self, motion, keep_in_frame=False):
# def update_position(self, keep_in_frame=False):
# def contains_point(self, point):
# def sample_contained_position(self):
# def vertices(self):
# def out_of_frame(self):
# def x(self):
# def y(self):
# def shape(self):
# def shape(self, s):
# def angle(self):
# def angle(self, a):
# def scale(self):
# def scale(self, s):
# def c0(self):
# def c1(self):
# def c2(self):
# def x_vel(self):
# def y_vel(self):
# def color(self):
# def position(self):
# def velocity(self):
# def factors(self):
. Output only the next line. | sprite.Sprite( |
Given the code snippet: <|code_start|># Copyright 2019 DeepMind Technologies Limited.
#
# 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.
# ============================================================================
# python2 python3
"""Goal-Finding tasks testing for generalization to new shapes.
In this task there is one sprite per episode. That sprite must be brought to the
goal location, which is always the center of the arena. At training time the
sprite is a square. At test time it is either a circle or a triangle.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
TERMINATE_DISTANCE = 0.075
NUM_TARGETS = 1
MODES_SHAPES = {
<|code_end|>
, generate the next line using the imports in this file:
import os
from spriteworld import factor_distributions as distribs
from spriteworld import sprite_generators
from spriteworld import tasks
from spriteworld.configs.cobra import common
and context (functions, classes, or occasionally code) from other files:
# Path: spriteworld/factor_distributions.py
# _MAX_TRIES = int(1e5)
# class AbstractDistribution(object):
# class Continuous(AbstractDistribution):
# class Discrete(AbstractDistribution):
# class Mixture(AbstractDistribution):
# class Intersection(AbstractDistribution):
# class Product(AbstractDistribution):
# class SetMinus(AbstractDistribution):
# class Selection(AbstractDistribution):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def __str__(self):
# def _get_rng(self, rng=None):
# def keys(self):
# def __init__(self, key, minval, maxval, dtype='float32'):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, key, candidates, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, index_for_sampling=0):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, hold_out):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, filtering):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
#
# Path: spriteworld/sprite_generators.py
# def generate_sprites(factor_dist, num_sprites=1):
# def _generate():
# def chain_generators(*sprite_generators):
# def _generate():
# def sample_generator(sprite_generators, p=None):
# def _generate():
# def shuffle(sprite_generator):
# def _generate():
#
# Path: spriteworld/tasks.py
# class AbstractTask(object):
# class NoReward(AbstractTask):
# class FindGoalPosition(AbstractTask):
# class Clustering(AbstractTask):
# class MetaAggregated(AbstractTask):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self):
# def reward(self, unused_sprites):
# def success(self, unused_sprites):
# def __init__(self,
# filter_distrib=None,
# goal_position=(0.5, 0.5),
# terminate_distance=0.05,
# terminate_bonus=0.0,
# weights_dimensions=(1, 1),
# sparse_reward=False,
# raw_reward_multiplier=50):
# def _single_sprite_reward(self, sprite):
# def _filtered_sprites_rewards(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# cluster_distribs,
# termination_threshold=2.5,
# terminate_bonus=0.0,
# sparse_reward=False,
# reward_range=10):
# def _cluster_assignments(self, sprites):
# def _compute_clustering_metric(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# subtasks,
# reward_aggregator='sum',
# termination_criterion='all',
# terminate_bonus=0.0):
# def reward(self, sprites):
# def success(self, sprites):
# REWARD_AGGREGATOR = {
# 'sum': np.nansum,
# 'max': np.nanmax,
# 'min': np.nanmin,
# 'mean': np.nanmean
# }
# TERMINATION_CRITERION = {'all': np.all, 'any': np.any}
#
# Path: spriteworld/configs/cobra/common.py
# def action_space():
# def renderers():
. Output only the next line. | 'train': distribs.Discrete('shape', ['square']), |
Based on the snippet: <|code_start|>
TERMINATE_DISTANCE = 0.075
NUM_TARGETS = 1
MODES_SHAPES = {
'train': distribs.Discrete('shape', ['square']),
'test': distribs.Discrete('shape', ['triangle', 'circle']),
}
def get_config(mode='train'):
"""Generate environment config.
Args:
mode: 'train' or 'test'.
Returns:
config: Dictionary defining task/environment configuration. Can be fed as
kwargs to environment.Environment.
"""
factors = distribs.Product([
MODES_SHAPES[mode],
distribs.Continuous('x', 0.1, 0.9),
distribs.Continuous('y', 0.1, 0.9),
distribs.Discrete('scale', [0.13]),
distribs.Continuous('c0', 0., 0.4),
distribs.Continuous('c1', 0.3, 1.),
distribs.Continuous('c2', 0.9, 1.),
])
<|code_end|>
, predict the immediate next line with the help of imports:
import os
from spriteworld import factor_distributions as distribs
from spriteworld import sprite_generators
from spriteworld import tasks
from spriteworld.configs.cobra import common
and context (classes, functions, sometimes code) from other files:
# Path: spriteworld/factor_distributions.py
# _MAX_TRIES = int(1e5)
# class AbstractDistribution(object):
# class Continuous(AbstractDistribution):
# class Discrete(AbstractDistribution):
# class Mixture(AbstractDistribution):
# class Intersection(AbstractDistribution):
# class Product(AbstractDistribution):
# class SetMinus(AbstractDistribution):
# class Selection(AbstractDistribution):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def __str__(self):
# def _get_rng(self, rng=None):
# def keys(self):
# def __init__(self, key, minval, maxval, dtype='float32'):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, key, candidates, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, index_for_sampling=0):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, hold_out):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, filtering):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
#
# Path: spriteworld/sprite_generators.py
# def generate_sprites(factor_dist, num_sprites=1):
# def _generate():
# def chain_generators(*sprite_generators):
# def _generate():
# def sample_generator(sprite_generators, p=None):
# def _generate():
# def shuffle(sprite_generator):
# def _generate():
#
# Path: spriteworld/tasks.py
# class AbstractTask(object):
# class NoReward(AbstractTask):
# class FindGoalPosition(AbstractTask):
# class Clustering(AbstractTask):
# class MetaAggregated(AbstractTask):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self):
# def reward(self, unused_sprites):
# def success(self, unused_sprites):
# def __init__(self,
# filter_distrib=None,
# goal_position=(0.5, 0.5),
# terminate_distance=0.05,
# terminate_bonus=0.0,
# weights_dimensions=(1, 1),
# sparse_reward=False,
# raw_reward_multiplier=50):
# def _single_sprite_reward(self, sprite):
# def _filtered_sprites_rewards(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# cluster_distribs,
# termination_threshold=2.5,
# terminate_bonus=0.0,
# sparse_reward=False,
# reward_range=10):
# def _cluster_assignments(self, sprites):
# def _compute_clustering_metric(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# subtasks,
# reward_aggregator='sum',
# termination_criterion='all',
# terminate_bonus=0.0):
# def reward(self, sprites):
# def success(self, sprites):
# REWARD_AGGREGATOR = {
# 'sum': np.nansum,
# 'max': np.nanmax,
# 'min': np.nanmin,
# 'mean': np.nanmean
# }
# TERMINATION_CRITERION = {'all': np.all, 'any': np.any}
#
# Path: spriteworld/configs/cobra/common.py
# def action_space():
# def renderers():
. Output only the next line. | sprite_gen = sprite_generators.generate_sprites( |
Given the code snippet: <|code_start|> 'train': distribs.Discrete('shape', ['square']),
'test': distribs.Discrete('shape', ['triangle', 'circle']),
}
def get_config(mode='train'):
"""Generate environment config.
Args:
mode: 'train' or 'test'.
Returns:
config: Dictionary defining task/environment configuration. Can be fed as
kwargs to environment.Environment.
"""
factors = distribs.Product([
MODES_SHAPES[mode],
distribs.Continuous('x', 0.1, 0.9),
distribs.Continuous('y', 0.1, 0.9),
distribs.Discrete('scale', [0.13]),
distribs.Continuous('c0', 0., 0.4),
distribs.Continuous('c1', 0.3, 1.),
distribs.Continuous('c2', 0.9, 1.),
])
sprite_gen = sprite_generators.generate_sprites(
factors, num_sprites=NUM_TARGETS)
# Randomize sprite ordering to eliminate any task information from occlusions
sprite_gen = sprite_generators.shuffle(sprite_gen)
<|code_end|>
, generate the next line using the imports in this file:
import os
from spriteworld import factor_distributions as distribs
from spriteworld import sprite_generators
from spriteworld import tasks
from spriteworld.configs.cobra import common
and context (functions, classes, or occasionally code) from other files:
# Path: spriteworld/factor_distributions.py
# _MAX_TRIES = int(1e5)
# class AbstractDistribution(object):
# class Continuous(AbstractDistribution):
# class Discrete(AbstractDistribution):
# class Mixture(AbstractDistribution):
# class Intersection(AbstractDistribution):
# class Product(AbstractDistribution):
# class SetMinus(AbstractDistribution):
# class Selection(AbstractDistribution):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def __str__(self):
# def _get_rng(self, rng=None):
# def keys(self):
# def __init__(self, key, minval, maxval, dtype='float32'):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, key, candidates, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, index_for_sampling=0):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, hold_out):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, filtering):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
#
# Path: spriteworld/sprite_generators.py
# def generate_sprites(factor_dist, num_sprites=1):
# def _generate():
# def chain_generators(*sprite_generators):
# def _generate():
# def sample_generator(sprite_generators, p=None):
# def _generate():
# def shuffle(sprite_generator):
# def _generate():
#
# Path: spriteworld/tasks.py
# class AbstractTask(object):
# class NoReward(AbstractTask):
# class FindGoalPosition(AbstractTask):
# class Clustering(AbstractTask):
# class MetaAggregated(AbstractTask):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self):
# def reward(self, unused_sprites):
# def success(self, unused_sprites):
# def __init__(self,
# filter_distrib=None,
# goal_position=(0.5, 0.5),
# terminate_distance=0.05,
# terminate_bonus=0.0,
# weights_dimensions=(1, 1),
# sparse_reward=False,
# raw_reward_multiplier=50):
# def _single_sprite_reward(self, sprite):
# def _filtered_sprites_rewards(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# cluster_distribs,
# termination_threshold=2.5,
# terminate_bonus=0.0,
# sparse_reward=False,
# reward_range=10):
# def _cluster_assignments(self, sprites):
# def _compute_clustering_metric(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# subtasks,
# reward_aggregator='sum',
# termination_criterion='all',
# terminate_bonus=0.0):
# def reward(self, sprites):
# def success(self, sprites):
# REWARD_AGGREGATOR = {
# 'sum': np.nansum,
# 'max': np.nanmax,
# 'min': np.nanmin,
# 'mean': np.nanmean
# }
# TERMINATION_CRITERION = {'all': np.all, 'any': np.any}
#
# Path: spriteworld/configs/cobra/common.py
# def action_space():
# def renderers():
. Output only the next line. | task = tasks.FindGoalPosition(terminate_distance=TERMINATE_DISTANCE) |
Given the code snippet: <|code_start|>
def get_config(mode='train'):
"""Generate environment config.
Args:
mode: 'train' or 'test'.
Returns:
config: Dictionary defining task/environment configuration. Can be fed as
kwargs to environment.Environment.
"""
factors = distribs.Product([
MODES_SHAPES[mode],
distribs.Continuous('x', 0.1, 0.9),
distribs.Continuous('y', 0.1, 0.9),
distribs.Discrete('scale', [0.13]),
distribs.Continuous('c0', 0., 0.4),
distribs.Continuous('c1', 0.3, 1.),
distribs.Continuous('c2', 0.9, 1.),
])
sprite_gen = sprite_generators.generate_sprites(
factors, num_sprites=NUM_TARGETS)
# Randomize sprite ordering to eliminate any task information from occlusions
sprite_gen = sprite_generators.shuffle(sprite_gen)
task = tasks.FindGoalPosition(terminate_distance=TERMINATE_DISTANCE)
config = {
'task': task,
<|code_end|>
, generate the next line using the imports in this file:
import os
from spriteworld import factor_distributions as distribs
from spriteworld import sprite_generators
from spriteworld import tasks
from spriteworld.configs.cobra import common
and context (functions, classes, or occasionally code) from other files:
# Path: spriteworld/factor_distributions.py
# _MAX_TRIES = int(1e5)
# class AbstractDistribution(object):
# class Continuous(AbstractDistribution):
# class Discrete(AbstractDistribution):
# class Mixture(AbstractDistribution):
# class Intersection(AbstractDistribution):
# class Product(AbstractDistribution):
# class SetMinus(AbstractDistribution):
# class Selection(AbstractDistribution):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def __str__(self):
# def _get_rng(self, rng=None):
# def keys(self):
# def __init__(self, key, minval, maxval, dtype='float32'):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, key, candidates, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, index_for_sampling=0):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, hold_out):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, filtering):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
#
# Path: spriteworld/sprite_generators.py
# def generate_sprites(factor_dist, num_sprites=1):
# def _generate():
# def chain_generators(*sprite_generators):
# def _generate():
# def sample_generator(sprite_generators, p=None):
# def _generate():
# def shuffle(sprite_generator):
# def _generate():
#
# Path: spriteworld/tasks.py
# class AbstractTask(object):
# class NoReward(AbstractTask):
# class FindGoalPosition(AbstractTask):
# class Clustering(AbstractTask):
# class MetaAggregated(AbstractTask):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self):
# def reward(self, unused_sprites):
# def success(self, unused_sprites):
# def __init__(self,
# filter_distrib=None,
# goal_position=(0.5, 0.5),
# terminate_distance=0.05,
# terminate_bonus=0.0,
# weights_dimensions=(1, 1),
# sparse_reward=False,
# raw_reward_multiplier=50):
# def _single_sprite_reward(self, sprite):
# def _filtered_sprites_rewards(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# cluster_distribs,
# termination_threshold=2.5,
# terminate_bonus=0.0,
# sparse_reward=False,
# reward_range=10):
# def _cluster_assignments(self, sprites):
# def _compute_clustering_metric(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# subtasks,
# reward_aggregator='sum',
# termination_criterion='all',
# terminate_bonus=0.0):
# def reward(self, sprites):
# def success(self, sprites):
# REWARD_AGGREGATOR = {
# 'sum': np.nansum,
# 'max': np.nanmax,
# 'min': np.nanmin,
# 'mean': np.nanmean
# }
# TERMINATION_CRITERION = {'all': np.all, 'any': np.any}
#
# Path: spriteworld/configs/cobra/common.py
# def action_space():
# def renderers():
. Output only the next line. | 'action_space': common.action_space(), |
Given the code snippet: <|code_start|># 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.
# ============================================================================
# python2 python3
"""Clustering task used in COBRA.
Cluster sprites by color.
We use 4 types of sprites, based on their hue.
We then compute a Davies-Bouldin clustering metric to assess clustering quality
(and generate a reward). The Clustering task uses a threshold to terminate an
episode when the clustering metric is good enough.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Task Parameters
NUM_SPRITES_PER_CLUSTER = 2
MAX_EPISODE_LENGTH = 50
# Define possible clusters (here using Hue as selection attribute)
CLUSTERS_DISTS = {
<|code_end|>
, generate the next line using the imports in this file:
import os
from spriteworld import factor_distributions as distribs
from spriteworld import sprite_generators
from spriteworld import tasks
from spriteworld.configs.cobra import common
and context (functions, classes, or occasionally code) from other files:
# Path: spriteworld/factor_distributions.py
# _MAX_TRIES = int(1e5)
# class AbstractDistribution(object):
# class Continuous(AbstractDistribution):
# class Discrete(AbstractDistribution):
# class Mixture(AbstractDistribution):
# class Intersection(AbstractDistribution):
# class Product(AbstractDistribution):
# class SetMinus(AbstractDistribution):
# class Selection(AbstractDistribution):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def __str__(self):
# def _get_rng(self, rng=None):
# def keys(self):
# def __init__(self, key, minval, maxval, dtype='float32'):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, key, candidates, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, index_for_sampling=0):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, hold_out):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, filtering):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
#
# Path: spriteworld/sprite_generators.py
# def generate_sprites(factor_dist, num_sprites=1):
# def _generate():
# def chain_generators(*sprite_generators):
# def _generate():
# def sample_generator(sprite_generators, p=None):
# def _generate():
# def shuffle(sprite_generator):
# def _generate():
#
# Path: spriteworld/tasks.py
# class AbstractTask(object):
# class NoReward(AbstractTask):
# class FindGoalPosition(AbstractTask):
# class Clustering(AbstractTask):
# class MetaAggregated(AbstractTask):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self):
# def reward(self, unused_sprites):
# def success(self, unused_sprites):
# def __init__(self,
# filter_distrib=None,
# goal_position=(0.5, 0.5),
# terminate_distance=0.05,
# terminate_bonus=0.0,
# weights_dimensions=(1, 1),
# sparse_reward=False,
# raw_reward_multiplier=50):
# def _single_sprite_reward(self, sprite):
# def _filtered_sprites_rewards(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# cluster_distribs,
# termination_threshold=2.5,
# terminate_bonus=0.0,
# sparse_reward=False,
# reward_range=10):
# def _cluster_assignments(self, sprites):
# def _compute_clustering_metric(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# subtasks,
# reward_aggregator='sum',
# termination_criterion='all',
# terminate_bonus=0.0):
# def reward(self, sprites):
# def success(self, sprites):
# REWARD_AGGREGATOR = {
# 'sum': np.nansum,
# 'max': np.nanmax,
# 'min': np.nanmin,
# 'mean': np.nanmean
# }
# TERMINATION_CRITERION = {'all': np.all, 'any': np.any}
#
# Path: spriteworld/configs/cobra/common.py
# def action_space():
# def renderers():
. Output only the next line. | 'red': distribs.Continuous('c0', 0.9, 1.), |
Predict the next line for this snippet: <|code_start|>
Args:
mode: 'train' or 'test'.
Returns:
config: Dictionary defining task/environment configuration. Can be fed as
kwargs to environment.Environment.
"""
# Select clusters to use, and their c0 factor distribution.
c0_clusters = [CLUSTERS_DISTS[cluster] for cluster in MODES[mode]]
print('Clustering task: {}, #sprites: {}'.format(MODES[mode],
NUM_SPRITES_PER_CLUSTER))
other_factors = distribs.Product([
distribs.Continuous('x', 0.1, 0.9),
distribs.Continuous('y', 0.1, 0.9),
distribs.Discrete('shape', ['square', 'triangle', 'circle']),
distribs.Discrete('scale', [0.13]),
distribs.Continuous('c1', 0.3, 1.),
distribs.Continuous('c2', 0.9, 1.),
])
# Generate the sprites to be used in this task, by combining Hue with the
# other factors.
sprite_factors = [
distribs.Product((other_factors, c0)) for c0 in c0_clusters
]
# Convert to sprites, generating the appropriate number per cluster.
sprite_gen_per_cluster = [
<|code_end|>
with the help of current file imports:
import os
from spriteworld import factor_distributions as distribs
from spriteworld import sprite_generators
from spriteworld import tasks
from spriteworld.configs.cobra import common
and context from other files:
# Path: spriteworld/factor_distributions.py
# _MAX_TRIES = int(1e5)
# class AbstractDistribution(object):
# class Continuous(AbstractDistribution):
# class Discrete(AbstractDistribution):
# class Mixture(AbstractDistribution):
# class Intersection(AbstractDistribution):
# class Product(AbstractDistribution):
# class SetMinus(AbstractDistribution):
# class Selection(AbstractDistribution):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def __str__(self):
# def _get_rng(self, rng=None):
# def keys(self):
# def __init__(self, key, minval, maxval, dtype='float32'):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, key, candidates, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, index_for_sampling=0):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, hold_out):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, filtering):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
#
# Path: spriteworld/sprite_generators.py
# def generate_sprites(factor_dist, num_sprites=1):
# def _generate():
# def chain_generators(*sprite_generators):
# def _generate():
# def sample_generator(sprite_generators, p=None):
# def _generate():
# def shuffle(sprite_generator):
# def _generate():
#
# Path: spriteworld/tasks.py
# class AbstractTask(object):
# class NoReward(AbstractTask):
# class FindGoalPosition(AbstractTask):
# class Clustering(AbstractTask):
# class MetaAggregated(AbstractTask):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self):
# def reward(self, unused_sprites):
# def success(self, unused_sprites):
# def __init__(self,
# filter_distrib=None,
# goal_position=(0.5, 0.5),
# terminate_distance=0.05,
# terminate_bonus=0.0,
# weights_dimensions=(1, 1),
# sparse_reward=False,
# raw_reward_multiplier=50):
# def _single_sprite_reward(self, sprite):
# def _filtered_sprites_rewards(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# cluster_distribs,
# termination_threshold=2.5,
# terminate_bonus=0.0,
# sparse_reward=False,
# reward_range=10):
# def _cluster_assignments(self, sprites):
# def _compute_clustering_metric(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# subtasks,
# reward_aggregator='sum',
# termination_criterion='all',
# terminate_bonus=0.0):
# def reward(self, sprites):
# def success(self, sprites):
# REWARD_AGGREGATOR = {
# 'sum': np.nansum,
# 'max': np.nanmax,
# 'min': np.nanmin,
# 'mean': np.nanmean
# }
# TERMINATION_CRITERION = {'all': np.all, 'any': np.any}
#
# Path: spriteworld/configs/cobra/common.py
# def action_space():
# def renderers():
, which may contain function names, class names, or code. Output only the next line. | sprite_generators.generate_sprites( |
Based on the snippet: <|code_start|> c0_clusters = [CLUSTERS_DISTS[cluster] for cluster in MODES[mode]]
print('Clustering task: {}, #sprites: {}'.format(MODES[mode],
NUM_SPRITES_PER_CLUSTER))
other_factors = distribs.Product([
distribs.Continuous('x', 0.1, 0.9),
distribs.Continuous('y', 0.1, 0.9),
distribs.Discrete('shape', ['square', 'triangle', 'circle']),
distribs.Discrete('scale', [0.13]),
distribs.Continuous('c1', 0.3, 1.),
distribs.Continuous('c2', 0.9, 1.),
])
# Generate the sprites to be used in this task, by combining Hue with the
# other factors.
sprite_factors = [
distribs.Product((other_factors, c0)) for c0 in c0_clusters
]
# Convert to sprites, generating the appropriate number per cluster.
sprite_gen_per_cluster = [
sprite_generators.generate_sprites(
factors, num_sprites=NUM_SPRITES_PER_CLUSTER)
for factors in sprite_factors
]
# Concat clusters into single scene to generate.
sprite_gen = sprite_generators.chain_generators(*sprite_gen_per_cluster)
# Randomize sprite ordering to eliminate any task information from occlusions
sprite_gen = sprite_generators.shuffle(sprite_gen)
# Clustering task will define rewards
<|code_end|>
, predict the immediate next line with the help of imports:
import os
from spriteworld import factor_distributions as distribs
from spriteworld import sprite_generators
from spriteworld import tasks
from spriteworld.configs.cobra import common
and context (classes, functions, sometimes code) from other files:
# Path: spriteworld/factor_distributions.py
# _MAX_TRIES = int(1e5)
# class AbstractDistribution(object):
# class Continuous(AbstractDistribution):
# class Discrete(AbstractDistribution):
# class Mixture(AbstractDistribution):
# class Intersection(AbstractDistribution):
# class Product(AbstractDistribution):
# class SetMinus(AbstractDistribution):
# class Selection(AbstractDistribution):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def __str__(self):
# def _get_rng(self, rng=None):
# def keys(self):
# def __init__(self, key, minval, maxval, dtype='float32'):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, key, candidates, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, index_for_sampling=0):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, hold_out):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, filtering):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
#
# Path: spriteworld/sprite_generators.py
# def generate_sprites(factor_dist, num_sprites=1):
# def _generate():
# def chain_generators(*sprite_generators):
# def _generate():
# def sample_generator(sprite_generators, p=None):
# def _generate():
# def shuffle(sprite_generator):
# def _generate():
#
# Path: spriteworld/tasks.py
# class AbstractTask(object):
# class NoReward(AbstractTask):
# class FindGoalPosition(AbstractTask):
# class Clustering(AbstractTask):
# class MetaAggregated(AbstractTask):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self):
# def reward(self, unused_sprites):
# def success(self, unused_sprites):
# def __init__(self,
# filter_distrib=None,
# goal_position=(0.5, 0.5),
# terminate_distance=0.05,
# terminate_bonus=0.0,
# weights_dimensions=(1, 1),
# sparse_reward=False,
# raw_reward_multiplier=50):
# def _single_sprite_reward(self, sprite):
# def _filtered_sprites_rewards(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# cluster_distribs,
# termination_threshold=2.5,
# terminate_bonus=0.0,
# sparse_reward=False,
# reward_range=10):
# def _cluster_assignments(self, sprites):
# def _compute_clustering_metric(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# subtasks,
# reward_aggregator='sum',
# termination_criterion='all',
# terminate_bonus=0.0):
# def reward(self, sprites):
# def success(self, sprites):
# REWARD_AGGREGATOR = {
# 'sum': np.nansum,
# 'max': np.nanmax,
# 'min': np.nanmin,
# 'mean': np.nanmean
# }
# TERMINATION_CRITERION = {'all': np.all, 'any': np.any}
#
# Path: spriteworld/configs/cobra/common.py
# def action_space():
# def renderers():
. Output only the next line. | task = tasks.Clustering(c0_clusters, terminate_bonus=0., reward_range=10.) |
Predict the next line for this snippet: <|code_start|> other_factors = distribs.Product([
distribs.Continuous('x', 0.1, 0.9),
distribs.Continuous('y', 0.1, 0.9),
distribs.Discrete('shape', ['square', 'triangle', 'circle']),
distribs.Discrete('scale', [0.13]),
distribs.Continuous('c1', 0.3, 1.),
distribs.Continuous('c2', 0.9, 1.),
])
# Generate the sprites to be used in this task, by combining Hue with the
# other factors.
sprite_factors = [
distribs.Product((other_factors, c0)) for c0 in c0_clusters
]
# Convert to sprites, generating the appropriate number per cluster.
sprite_gen_per_cluster = [
sprite_generators.generate_sprites(
factors, num_sprites=NUM_SPRITES_PER_CLUSTER)
for factors in sprite_factors
]
# Concat clusters into single scene to generate.
sprite_gen = sprite_generators.chain_generators(*sprite_gen_per_cluster)
# Randomize sprite ordering to eliminate any task information from occlusions
sprite_gen = sprite_generators.shuffle(sprite_gen)
# Clustering task will define rewards
task = tasks.Clustering(c0_clusters, terminate_bonus=0., reward_range=10.)
config = {
'task': task,
<|code_end|>
with the help of current file imports:
import os
from spriteworld import factor_distributions as distribs
from spriteworld import sprite_generators
from spriteworld import tasks
from spriteworld.configs.cobra import common
and context from other files:
# Path: spriteworld/factor_distributions.py
# _MAX_TRIES = int(1e5)
# class AbstractDistribution(object):
# class Continuous(AbstractDistribution):
# class Discrete(AbstractDistribution):
# class Mixture(AbstractDistribution):
# class Intersection(AbstractDistribution):
# class Product(AbstractDistribution):
# class SetMinus(AbstractDistribution):
# class Selection(AbstractDistribution):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def __str__(self):
# def _get_rng(self, rng=None):
# def keys(self):
# def __init__(self, key, minval, maxval, dtype='float32'):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, key, candidates, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, index_for_sampling=0):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, hold_out):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, filtering):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
#
# Path: spriteworld/sprite_generators.py
# def generate_sprites(factor_dist, num_sprites=1):
# def _generate():
# def chain_generators(*sprite_generators):
# def _generate():
# def sample_generator(sprite_generators, p=None):
# def _generate():
# def shuffle(sprite_generator):
# def _generate():
#
# Path: spriteworld/tasks.py
# class AbstractTask(object):
# class NoReward(AbstractTask):
# class FindGoalPosition(AbstractTask):
# class Clustering(AbstractTask):
# class MetaAggregated(AbstractTask):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self):
# def reward(self, unused_sprites):
# def success(self, unused_sprites):
# def __init__(self,
# filter_distrib=None,
# goal_position=(0.5, 0.5),
# terminate_distance=0.05,
# terminate_bonus=0.0,
# weights_dimensions=(1, 1),
# sparse_reward=False,
# raw_reward_multiplier=50):
# def _single_sprite_reward(self, sprite):
# def _filtered_sprites_rewards(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# cluster_distribs,
# termination_threshold=2.5,
# terminate_bonus=0.0,
# sparse_reward=False,
# reward_range=10):
# def _cluster_assignments(self, sprites):
# def _compute_clustering_metric(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# subtasks,
# reward_aggregator='sum',
# termination_criterion='all',
# terminate_bonus=0.0):
# def reward(self, sprites):
# def success(self, sprites):
# REWARD_AGGREGATOR = {
# 'sum': np.nansum,
# 'max': np.nanmax,
# 'min': np.nanmin,
# 'mean': np.nanmean
# }
# TERMINATION_CRITERION = {'all': np.all, 'any': np.any}
#
# Path: spriteworld/configs/cobra/common.py
# def action_space():
# def renderers():
, which may contain function names, class names, or code. Output only the next line. | 'action_space': common.action_space(), |
Predict the next line after this snippet: <|code_start|>#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 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.
# ============================================================================
# python2 python3
"""Tests for action_spaces."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class SelectMoveTest(parameterized.TestCase):
@parameterized.named_parameters(
('Motion', 1, np.array([0.5, 0.5, 0.2, 0.75]), (-0.3, 0.25)),
('SameMotion', 1, np.array([0.2, 0.5, 0.2, 0.75]), (-0.3, 0.25)),
('SmallerScale', 0.5, np.array([0.2, 0.5, 0.2, 0.75]), (-0.15, 0.125)),
)
def testGetMotion(self, scale, action, true_motion):
<|code_end|>
using the current file's imports:
from absl.testing import absltest
from absl.testing import parameterized
from spriteworld import action_spaces
from spriteworld import sprite
import numpy as np
and any relevant context from other files:
# Path: spriteworld/action_spaces.py
# class SelectMove(object):
# class DragAndDrop(SelectMove):
# class Embodied(object):
# def __init__(self, scale=1.0, motion_cost=0.0, noise_scale=None):
# def get_motion(self, action):
# def apply_noise_to_action(self, action):
# def get_sprite_from_position(self, position, sprites):
# def step(self, action, sprites, keep_in_frame):
# def sample(self):
# def action_spec(self):
# def get_motion(self, action):
# def __init__(self, step_size=0.05, motion_cost=0.):
# def get_body_sprite(self, sprites):
# def get_non_body_sprites(self, sprites):
# def get_carried_sprite(self, sprites):
# def step(self, action, sprites, keep_in_frame):
# def sample(self):
# def action_spec(self):
#
# Path: spriteworld/sprite.py
# FACTOR_NAMES = (
# 'x', # x-position of sprite center-of-mass (float)
# 'y', # y-position of sprite center-of-mass (float)
# 'shape', # shape (string)
# 'angle', # angle in degrees (scalar)
# 'scale', # size of sprite (float)
# 'c0', # first color component (scalar)
# 'c1', # second color component (scalar)
# 'c2', # third color component (scalar)
# 'x_vel', # x-component of velocity (float)
# 'y_vel', # y-component of velocity (float)
# )
# _MAX_TRIES = int(1e6)
# class Sprite(object):
# def __init__(self,
# x=0.5,
# y=0.5,
# shape='square',
# angle=0,
# scale=0.1,
# c0=0,
# c1=0,
# c2=0,
# x_vel=0.0,
# y_vel=0.0):
# def _reset_centered_path(self):
# def move(self, motion, keep_in_frame=False):
# def update_position(self, keep_in_frame=False):
# def contains_point(self, point):
# def sample_contained_position(self):
# def vertices(self):
# def out_of_frame(self):
# def x(self):
# def y(self):
# def shape(self):
# def shape(self, s):
# def angle(self):
# def angle(self, a):
# def scale(self):
# def scale(self, s):
# def c0(self):
# def c1(self):
# def c2(self):
# def x_vel(self):
# def y_vel(self):
# def color(self):
# def position(self):
# def velocity(self):
# def factors(self):
. Output only the next line. | action_space = action_spaces.SelectMove(scale=scale) |
Predict the next line for this snippet: <|code_start|>
class SelectMoveTest(parameterized.TestCase):
@parameterized.named_parameters(
('Motion', 1, np.array([0.5, 0.5, 0.2, 0.75]), (-0.3, 0.25)),
('SameMotion', 1, np.array([0.2, 0.5, 0.2, 0.75]), (-0.3, 0.25)),
('SmallerScale', 0.5, np.array([0.2, 0.5, 0.2, 0.75]), (-0.15, 0.125)),
)
def testGetMotion(self, scale, action, true_motion):
action_space = action_spaces.SelectMove(scale=scale)
motion = action_space.get_motion(action)
self.assertTrue(np.allclose(motion, true_motion, atol=1e-4))
@parameterized.named_parameters(
('NoCost', 1, np.array([0.5, 0.5, 0.2, 0.75]), 0., 0.),
('Cost', 1, np.array([0.5, 0.5, 0.2, 0.75]), 1., -0.39),
('SameCost', 1, np.array([0.2, 0.3, 0.2, 0.75]), 1., -0.39),
('LowerCost', 0.5, np.array([0.5, 0.5, 0.2, 0.75]), 1., -0.195),
)
def testMotionCost(self, scale, action, motion_cost, true_cost):
action_space = action_spaces.SelectMove(
scale=scale, motion_cost=motion_cost)
cost = action_space.step(action, sprites=[], keep_in_frame=False)
self.assertAlmostEqual(cost, true_cost, delta=0.01)
def testMoveSprites(self):
"""Take a series of actions and repeatedly check sprite motions."""
action_space = action_spaces.SelectMove(scale=0.5)
<|code_end|>
with the help of current file imports:
from absl.testing import absltest
from absl.testing import parameterized
from spriteworld import action_spaces
from spriteworld import sprite
import numpy as np
and context from other files:
# Path: spriteworld/action_spaces.py
# class SelectMove(object):
# class DragAndDrop(SelectMove):
# class Embodied(object):
# def __init__(self, scale=1.0, motion_cost=0.0, noise_scale=None):
# def get_motion(self, action):
# def apply_noise_to_action(self, action):
# def get_sprite_from_position(self, position, sprites):
# def step(self, action, sprites, keep_in_frame):
# def sample(self):
# def action_spec(self):
# def get_motion(self, action):
# def __init__(self, step_size=0.05, motion_cost=0.):
# def get_body_sprite(self, sprites):
# def get_non_body_sprites(self, sprites):
# def get_carried_sprite(self, sprites):
# def step(self, action, sprites, keep_in_frame):
# def sample(self):
# def action_spec(self):
#
# Path: spriteworld/sprite.py
# FACTOR_NAMES = (
# 'x', # x-position of sprite center-of-mass (float)
# 'y', # y-position of sprite center-of-mass (float)
# 'shape', # shape (string)
# 'angle', # angle in degrees (scalar)
# 'scale', # size of sprite (float)
# 'c0', # first color component (scalar)
# 'c1', # second color component (scalar)
# 'c2', # third color component (scalar)
# 'x_vel', # x-component of velocity (float)
# 'y_vel', # y-component of velocity (float)
# )
# _MAX_TRIES = int(1e6)
# class Sprite(object):
# def __init__(self,
# x=0.5,
# y=0.5,
# shape='square',
# angle=0,
# scale=0.1,
# c0=0,
# c1=0,
# c2=0,
# x_vel=0.0,
# y_vel=0.0):
# def _reset_centered_path(self):
# def move(self, motion, keep_in_frame=False):
# def update_position(self, keep_in_frame=False):
# def contains_point(self, point):
# def sample_contained_position(self):
# def vertices(self):
# def out_of_frame(self):
# def x(self):
# def y(self):
# def shape(self):
# def shape(self, s):
# def angle(self):
# def angle(self, a):
# def scale(self):
# def scale(self, s):
# def c0(self):
# def c1(self):
# def c2(self):
# def x_vel(self):
# def y_vel(self):
# def color(self):
# def position(self):
# def velocity(self):
# def factors(self):
, which may contain function names, class names, or code. Output only the next line. | sprites = [sprite.Sprite(x=0.55, y=0.5), sprite.Sprite(x=0.5, y=0.5)] |
Predict the next line after this snippet: <|code_start|># Copyright 2019 DeepMind Technologies Limited.
#
# 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.
# ============================================================================
# python2 python3
"""Constants for shapes."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# A selection of simple shapes
SHAPES = {
<|code_end|>
using the current file's imports:
import enum
import numpy as np
from spriteworld import shapes
and any relevant context from other files:
# Path: spriteworld/shapes.py
# def _polar2cartesian(r, theta):
# def polygon(num_sides, theta_0=0.):
# def star(num_sides, point_height=1, theta_0=0.):
# def spokes(num_sides, spoke_height=1, theta_0=0.):
. Output only the next line. | 'triangle': shapes.polygon(num_sides=3, theta_0=np.pi/2), |
Here is a snippet: <|code_start|># Copyright 2019 DeepMind Technologies Limited.
#
# 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.
# ============================================================================
# python2 python3
"""Tests for pil_renderer."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class PilRendererTest(absltest.TestCase):
def _get_sprites(self):
"""Get list of sprites."""
sprites = [
<|code_end|>
. Write the next line using the current file imports:
import colorsys
import numpy as np
from absl.testing import absltest
from spriteworld import sprite
from spriteworld.renderers import pil_renderer
and context from other files:
# Path: spriteworld/sprite.py
# FACTOR_NAMES = (
# 'x', # x-position of sprite center-of-mass (float)
# 'y', # y-position of sprite center-of-mass (float)
# 'shape', # shape (string)
# 'angle', # angle in degrees (scalar)
# 'scale', # size of sprite (float)
# 'c0', # first color component (scalar)
# 'c1', # second color component (scalar)
# 'c2', # third color component (scalar)
# 'x_vel', # x-component of velocity (float)
# 'y_vel', # y-component of velocity (float)
# )
# _MAX_TRIES = int(1e6)
# class Sprite(object):
# def __init__(self,
# x=0.5,
# y=0.5,
# shape='square',
# angle=0,
# scale=0.1,
# c0=0,
# c1=0,
# c2=0,
# x_vel=0.0,
# y_vel=0.0):
# def _reset_centered_path(self):
# def move(self, motion, keep_in_frame=False):
# def update_position(self, keep_in_frame=False):
# def contains_point(self, point):
# def sample_contained_position(self):
# def vertices(self):
# def out_of_frame(self):
# def x(self):
# def y(self):
# def shape(self):
# def shape(self, s):
# def angle(self):
# def angle(self, a):
# def scale(self):
# def scale(self, s):
# def c0(self):
# def c1(self):
# def c2(self):
# def x_vel(self):
# def y_vel(self):
# def color(self):
# def position(self):
# def velocity(self):
# def factors(self):
#
# Path: spriteworld/renderers/pil_renderer.py
# class PILRenderer(abstract_renderer.AbstractRenderer):
# def __init__(self,
# image_size=(64, 64),
# anti_aliasing=1,
# bg_color=None,
# color_to_rgb=None):
# def render(self, sprites=(), global_state=None):
# def observation_spec(self):
, which may include functions, classes, or code. Output only the next line. | sprite.Sprite( |
Next line prediction: <|code_start|># 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.
# ============================================================================
# python2 python3
"""Tests for pil_renderer."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class PilRendererTest(absltest.TestCase):
def _get_sprites(self):
"""Get list of sprites."""
sprites = [
sprite.Sprite(
x=0.75, y=0.95, shape='spoke_6', scale=0.2, c0=20, c1=50, c2=80),
sprite.Sprite(
x=0.2, y=0.3, shape='triangle', scale=0.1, c0=150, c1=255, c2=100),
sprite.Sprite(
x=0.7, y=0.5, shape='square', scale=0.3, c0=0, c1=255, c2=0),
sprite.Sprite(
x=0.5, y=0.5, shape='square', scale=0.3, c0=255, c1=0, c2=0),
]
return sprites
def testBasicFunctionality(self):
<|code_end|>
. Use current file imports:
(import colorsys
import numpy as np
from absl.testing import absltest
from spriteworld import sprite
from spriteworld.renderers import pil_renderer)
and context including class names, function names, or small code snippets from other files:
# Path: spriteworld/sprite.py
# FACTOR_NAMES = (
# 'x', # x-position of sprite center-of-mass (float)
# 'y', # y-position of sprite center-of-mass (float)
# 'shape', # shape (string)
# 'angle', # angle in degrees (scalar)
# 'scale', # size of sprite (float)
# 'c0', # first color component (scalar)
# 'c1', # second color component (scalar)
# 'c2', # third color component (scalar)
# 'x_vel', # x-component of velocity (float)
# 'y_vel', # y-component of velocity (float)
# )
# _MAX_TRIES = int(1e6)
# class Sprite(object):
# def __init__(self,
# x=0.5,
# y=0.5,
# shape='square',
# angle=0,
# scale=0.1,
# c0=0,
# c1=0,
# c2=0,
# x_vel=0.0,
# y_vel=0.0):
# def _reset_centered_path(self):
# def move(self, motion, keep_in_frame=False):
# def update_position(self, keep_in_frame=False):
# def contains_point(self, point):
# def sample_contained_position(self):
# def vertices(self):
# def out_of_frame(self):
# def x(self):
# def y(self):
# def shape(self):
# def shape(self, s):
# def angle(self):
# def angle(self, a):
# def scale(self):
# def scale(self, s):
# def c0(self):
# def c1(self):
# def c2(self):
# def x_vel(self):
# def y_vel(self):
# def color(self):
# def position(self):
# def velocity(self):
# def factors(self):
#
# Path: spriteworld/renderers/pil_renderer.py
# class PILRenderer(abstract_renderer.AbstractRenderer):
# def __init__(self,
# image_size=(64, 64),
# anti_aliasing=1,
# bg_color=None,
# color_to_rgb=None):
# def render(self, sprites=(), global_state=None):
# def observation_spec(self):
. Output only the next line. | renderer = pil_renderer.PILRenderer(image_size=(64, 64)) |
Predict the next line for this snippet: <|code_start|>
def _repr_info(self):
info = super()._repr_info()
info.append('ID=%s' % self.message_id)
return info
async def _wait(task_future):
await task_future.backend.channels.connect()
result = await task_future
return result
class BaseComponent:
def __init__(self, backend):
self.backend = backend
self.logger = self.backend.logger
@property
def cfg(self):
return self.backend.cfg
@property
def _loop(self):
return self.backend._loop
def encode(self, message, serializer=None):
"""Encode a message"""
serializer = serializer or self.cfg.message_serializer
<|code_end|>
with the help of current file imports:
from abc import ABC, abstractmethod
from asyncio import Future, ensure_future
from collections import OrderedDict
from pulsar.api import chain_future, ImproperlyConfigured
from pulsar.apps.http import HttpClient
from pulsar.apps.greenio import GreenPool
from pulsar.apps.data.channels import Connector
from pulsar.utils.importer import module_attribute
from .utils.serializers import serializers
and context from other files:
# Path: pq/utils/serializers.py
# def serializer(cls):
# def __new__(cls, name, bases, attrs):
# def consumer(cls):
# def get(self, name):
# def tojson(self):
# def __init__(self, *args, **kwargs):
# def decode(cls, data):
# def encode(cls, message):
# def decode(cls, data):
# def encode(cls, message):
# def queue_message(d, type=None):
# def default(self, o):
# def as_message(o):
# class MessageMetaClass(type):
# class Message(metaclass=MessageMetaClass):
# class MessageDict(Message):
# class Json:
# class MsgPack:
# class JSONEncoder(json.JSONEncoder):
, which may contain function names, class names, or code. Output only the next line. | return serializers[serializer].encode(message) |
Predict the next line after this snippet: <|code_start|>
class TaskPaths(TaskSetting):
name = "task_paths"
validator = validate_list
default = []
desc = """\
List of python dotted paths where tasks are located.
This parameter can only be specified during initialization or in a
:ref:`config file <setting-config>`.
"""
class SchedulePeriodic(TaskSetting):
name = 'schedule_periodic'
flags = ["--schedule-periodic"]
validator = validate_bool
action = "store_true"
default = False
desc = '''\
Enable scheduling of periodic tasks.
If enabled, :class:`.PeriodicJob` will produce
tasks according to their schedule.
'''
class MessageSerializer(TaskSetting):
name = 'message_serializer'
flags = ["--message-serializer"]
<|code_end|>
using the current file's imports:
from pulsar.api import Setting
from pulsar.utils.config import (
validate_list, validate_bool, validate_pos_float
)
from pulsar.utils.importer import module_attribute
from ..utils.serializers import serializers
and any relevant context from other files:
# Path: pq/utils/serializers.py
# def serializer(cls):
# def __new__(cls, name, bases, attrs):
# def consumer(cls):
# def get(self, name):
# def tojson(self):
# def __init__(self, *args, **kwargs):
# def decode(cls, data):
# def encode(cls, message):
# def decode(cls, data):
# def encode(cls, message):
# def queue_message(d, type=None):
# def default(self, o):
# def as_message(o):
# class MessageMetaClass(type):
# class Message(metaclass=MessageMetaClass):
# class MessageDict(Message):
# class Json:
# class MsgPack:
# class JSONEncoder(json.JSONEncoder):
. Output only the next line. | choices = tuple(serializers) |
Given the following code snippet before the placeholder: <|code_start|> self.manager.store_message(message),
self.channels.publish(message.type, event, message)
]
if message.id:
coro.append(
self.channels.publish(message.type, message.id, message)
)
await gather(*coro)
def tick(self, monitor):
pass
def info(self):
for consumer in self.consumers:
try:
info = consumer.info()
except Exception:
self.logger.exception('Unhandled information exception')
else:
if info:
yield consumer.name, info
def lock(self, name, **kwargs):
"""aquire a distributed global lock for ``name``
"""
return self.channels.lock('lock-%s' % name, **kwargs)
def http_sessions(self, model=None):
"""Return an HTTP session handler for a given concurrency model
"""
<|code_end|>
, predict the next line using imports from the current file:
import platform
from asyncio import gather, new_event_loop
from pulsar.api import ensure_future, EventHandler, as_coroutine
from pulsar.apps.data import create_store
from pulsar.apps.greenio import GreenHttp
from pulsar.apps.http import HttpClient
from pulsar.utils.importer import module_attribute
from ..utils.serializers import MessageDict
from ..utils import concurrency
from ..mq import Manager, register_broker
and context including class names, function names, and sometimes code from other files:
# Path: pq/utils/serializers.py
# class MessageDict(Message):
#
# def __init__(self, *args, **kwargs):
# self.__dict__.update(*args, **kwargs)
#
# Path: pq/utils/concurrency.py
# ASYNC_IO = 1 # run in the worker event loop
# THREAD_IO = 3 # run in the event loop executor
# CPUBOUND = 4 # run in a subprocess
#
# Path: pq/mq.py
# class Manager(BaseComponent):
#
# def green_pool(self):
# return GreenPool(loop=self._loop)
#
# def http(self):
# return HttpClient(loop=self._loop)
#
# def queues(self):
# """List of queue names for Message consumers
# """
# queues = [self.backend.node_name]
# queues.extend(self.cfg.task_queues)
# return queues
#
# async def store_message(self, message):
# """Dummy function to store a message into a persistent database
# """
# pass
#
# def start(self):
# """Optional start method, called by the backend when it starts
# """
# pass
#
# def close(self):
# pass
#
# def register_broker(name, factory=None):
# if factory is None:
# dotted_path = brokers.get(name)
# if not dotted_path:
# raise ImproperlyConfigured('No such message broker: %s' % name)
# factory = module_attribute(dotted_path, safe=True)
# if not factory:
# raise ImproperlyConfigured(
# '"%s" store not available' % dotted_path)
# else:
# brokers[name] = factory
# return factory
. Output only the next line. | if model == concurrency.THREAD_IO: |
Given snippet: <|code_start|>
register_broker('redis', 'pq.backends.redis:MQ')
class ConsumerMessage(MessageDict):
type = 'consumer'
class Producer(EventHandler):
"""Produce tasks by queuing them
Abstract base class for both task schedulers and task consumers
"""
app = None
ONE_TIME_EVENTS = ('close',)
def __init__(self, cfg, *, logger=None, **kw):
# create the store for channels
store = create_store(cfg.data_store, loop=cfg.params.pop('loop', None))
self.cfg = cfg
self._loop = store._loop
self.logger = logger
self._closing_waiter = None
if not cfg.message_broker:
broker = store
else:
broker = create_store(cfg.message_broker, loop=self._loop)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import platform
from asyncio import gather, new_event_loop
from pulsar.api import ensure_future, EventHandler, as_coroutine
from pulsar.apps.data import create_store
from pulsar.apps.greenio import GreenHttp
from pulsar.apps.http import HttpClient
from pulsar.utils.importer import module_attribute
from ..utils.serializers import MessageDict
from ..utils import concurrency
from ..mq import Manager, register_broker
and context:
# Path: pq/utils/serializers.py
# class MessageDict(Message):
#
# def __init__(self, *args, **kwargs):
# self.__dict__.update(*args, **kwargs)
#
# Path: pq/utils/concurrency.py
# ASYNC_IO = 1 # run in the worker event loop
# THREAD_IO = 3 # run in the event loop executor
# CPUBOUND = 4 # run in a subprocess
#
# Path: pq/mq.py
# class Manager(BaseComponent):
#
# def green_pool(self):
# return GreenPool(loop=self._loop)
#
# def http(self):
# return HttpClient(loop=self._loop)
#
# def queues(self):
# """List of queue names for Message consumers
# """
# queues = [self.backend.node_name]
# queues.extend(self.cfg.task_queues)
# return queues
#
# async def store_message(self, message):
# """Dummy function to store a message into a persistent database
# """
# pass
#
# def start(self):
# """Optional start method, called by the backend when it starts
# """
# pass
#
# def close(self):
# pass
#
# def register_broker(name, factory=None):
# if factory is None:
# dotted_path = brokers.get(name)
# if not dotted_path:
# raise ImproperlyConfigured('No such message broker: %s' % name)
# factory = module_attribute(dotted_path, safe=True)
# if not factory:
# raise ImproperlyConfigured(
# '"%s" store not available' % dotted_path)
# else:
# brokers[name] = factory
# return factory
which might include code, classes, or functions. Output only the next line. | self.manager = (self.cfg.callable or Manager)(self) |
Given snippet: <|code_start|>
__all__ = ['TaskError',
'TaskNotAvailable',
'TaskTimeout',
'Task']
class TaskError(PulsarException):
status = states.FAILURE
class TaskNotAvailable(TaskError):
MESSAGE = 'Task {0} is not registered'
def __init__(self, task_name):
self.task_name = task_name
super().__init__(self.MESSAGE.format(task_name))
class TaskTimeout(TaskError):
pass
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from pulsar.api import PulsarException
from pulsar.utils.log import LazyString
from ..utils.serializers import Message
from . import states
and context:
# Path: pq/utils/serializers.py
# class Message(metaclass=MessageMetaClass):
# id = None
# """Message ID - all messages should have one"""
#
# @classmethod
# def consumer(cls):
# pass
#
# def get(self, name):
# return self.__dict__.get(name)
#
# def tojson(self):
# '''A serializable dictionary
# '''
# data = self.__dict__.copy()
# data['type'] = self.type
# return data
which might include code, classes, or functions. Output only the next line. | class Task(Message): |
Next line prediction: <|code_start|>"""Tests connection errors"""
class Tester:
def __init__(self):
self.end = Future()
def __call__(self, *args, **kwargs):
if not self.end.done():
self.end.set_result((args, kwargs))
class TestConnectionDrop(unittest.TestCase):
app = None
async def setUp(self):
<|code_end|>
. Use current file imports:
(import unittest
from asyncio import Future
from pulsar.api import send
from pulsar.utils.string import random_string
from pq import api)
and context including class names, function names, or small code snippets from other files:
# Path: pq/api.py
. Output only the next line. | self.app = api.QueueApp( |
Here is a snippet: <|code_start|> # - queue the task at the right time
# - otherwise proceed to next
# - Set status to STARTED and consume the task
logger = self.logger
task_id = task.id
time_ended = time.time()
job = None
JobClass = self.registry.get(task.name)
try:
if not JobClass:
raise RuntimeError('%s not in registry' % task.name)
if task.status > states.STARTED:
queued = task.time_queued
timeout = task.timeout
delay = task.delay or 0
start = queued + delay
if delay: # Task with delay
gap = start - time_ended
if gap > 0:
self._loop.call_later(gap, self._queue_again, task)
if worker:
self._concurrent_tasks.pop(task_id, None)
return task
if timeout: # Handle timeout
timeout = timeout + start - time_ended
if timeout <= 0:
<|code_end|>
. Write the next line using the current file imports:
import sys
import time
import traceback
import json
from asyncio import wait_for
from asyncio import CancelledError, TimeoutError
from asyncio.subprocess import Process
from .task import TaskError, TaskTimeout
from . import states
from ..cpubound import StreamProtocol, PROCESS_FILE
from ..utils.exc import string_exception
from ..utils import concurrency
and context from other files:
# Path: pq/tasks/task.py
# class TaskError(PulsarException):
# status = states.FAILURE
#
# class TaskTimeout(TaskError):
# pass
#
# Path: pq/cpubound.py
# class StreamProtocol(subprocess.SubprocessStreamProtocol):
#
# def __init__(self, job):
# super().__init__(streams._DEFAULT_LIMIT, job._loop)
# self.info = CpuTaskInfo(job)
# self.error = CpuTaskInfo(job)
#
# def pipe_data_received(self, fd, data):
# if fd == 1:
# self.info.feed(data)
# elif fd == 2:
# self.error.feed(data)
# super().pipe_data_received(fd, data)
#
# PROCESS_FILE = os.path.join(PQPATH, "cpubound.py")
#
# Path: pq/utils/exc.py
# def string_exception(exc):
# args = []
# for arg in exc.args:
# if isinstance(arg, str):
# args.append(arg)
# if args:
# return args[0] if len(args) == 1 else args
# return str(exc)
#
# Path: pq/utils/concurrency.py
# ASYNC_IO = 1 # run in the worker event loop
# THREAD_IO = 3 # run in the event loop executor
# CPUBOUND = 4 # run in a subprocess
, which may include functions, classes, or code. Output only the next line. | raise TaskTimeout |
Based on the snippet: <|code_start|> if worker:
self._concurrent_tasks.pop(task_id, None)
await self.backend.publish('done', task)
if job:
if worker:
await self.broker.decr(job.name)
if self._should_retry(job):
await self._requeue_task(job)
return task
def _consume(self, job, kwargs):
model = job.get_concurrency()
if model == concurrency.THREAD_IO:
return job._loop.run_in_executor(None, lambda: job(**kwargs))
elif model == concurrency.CPUBOUND:
return self._consume_in_subprocess(job, kwargs)
else:
return self.backend.green_pool.submit(job, **kwargs)
async def _consume_in_subprocess(self, job, kwargs):
params = dict(self.json_params())
loop = job._loop
transport, protocol = await loop.subprocess_exec(
<|code_end|>
, predict the immediate next line with the help of imports:
import sys
import time
import traceback
import json
from asyncio import wait_for
from asyncio import CancelledError, TimeoutError
from asyncio.subprocess import Process
from .task import TaskError, TaskTimeout
from . import states
from ..cpubound import StreamProtocol, PROCESS_FILE
from ..utils.exc import string_exception
from ..utils import concurrency
and context (classes, functions, sometimes code) from other files:
# Path: pq/tasks/task.py
# class TaskError(PulsarException):
# status = states.FAILURE
#
# class TaskTimeout(TaskError):
# pass
#
# Path: pq/cpubound.py
# class StreamProtocol(subprocess.SubprocessStreamProtocol):
#
# def __init__(self, job):
# super().__init__(streams._DEFAULT_LIMIT, job._loop)
# self.info = CpuTaskInfo(job)
# self.error = CpuTaskInfo(job)
#
# def pipe_data_received(self, fd, data):
# if fd == 1:
# self.info.feed(data)
# elif fd == 2:
# self.error.feed(data)
# super().pipe_data_received(fd, data)
#
# PROCESS_FILE = os.path.join(PQPATH, "cpubound.py")
#
# Path: pq/utils/exc.py
# def string_exception(exc):
# args = []
# for arg in exc.args:
# if isinstance(arg, str):
# args.append(arg)
# if args:
# return args[0] if len(args) == 1 else args
# return str(exc)
#
# Path: pq/utils/concurrency.py
# ASYNC_IO = 1 # run in the worker event loop
# THREAD_IO = 3 # run in the event loop executor
# CPUBOUND = 4 # run in a subprocess
. Output only the next line. | lambda: StreamProtocol(job), |
Predict the next line for this snippet: <|code_start|>
await self.backend.publish('done', task)
if job:
if worker:
await self.broker.decr(job.name)
if self._should_retry(job):
await self._requeue_task(job)
return task
def _consume(self, job, kwargs):
model = job.get_concurrency()
if model == concurrency.THREAD_IO:
return job._loop.run_in_executor(None, lambda: job(**kwargs))
elif model == concurrency.CPUBOUND:
return self._consume_in_subprocess(job, kwargs)
else:
return self.backend.green_pool.submit(job, **kwargs)
async def _consume_in_subprocess(self, job, kwargs):
params = dict(self.json_params())
loop = job._loop
transport, protocol = await loop.subprocess_exec(
lambda: StreamProtocol(job),
sys.executable,
<|code_end|>
with the help of current file imports:
import sys
import time
import traceback
import json
from asyncio import wait_for
from asyncio import CancelledError, TimeoutError
from asyncio.subprocess import Process
from .task import TaskError, TaskTimeout
from . import states
from ..cpubound import StreamProtocol, PROCESS_FILE
from ..utils.exc import string_exception
from ..utils import concurrency
and context from other files:
# Path: pq/tasks/task.py
# class TaskError(PulsarException):
# status = states.FAILURE
#
# class TaskTimeout(TaskError):
# pass
#
# Path: pq/cpubound.py
# class StreamProtocol(subprocess.SubprocessStreamProtocol):
#
# def __init__(self, job):
# super().__init__(streams._DEFAULT_LIMIT, job._loop)
# self.info = CpuTaskInfo(job)
# self.error = CpuTaskInfo(job)
#
# def pipe_data_received(self, fd, data):
# if fd == 1:
# self.info.feed(data)
# elif fd == 2:
# self.error.feed(data)
# super().pipe_data_received(fd, data)
#
# PROCESS_FILE = os.path.join(PQPATH, "cpubound.py")
#
# Path: pq/utils/exc.py
# def string_exception(exc):
# args = []
# for arg in exc.args:
# if isinstance(arg, str):
# args.append(arg)
# if args:
# return args[0] if len(args) == 1 else args
# return str(exc)
#
# Path: pq/utils/concurrency.py
# ASYNC_IO = 1 # run in the worker event loop
# THREAD_IO = 3 # run in the event loop executor
# CPUBOUND = 4 # run in a subprocess
, which may contain function names, class names, or code. Output only the next line. | PROCESS_FILE, |
Predict the next line for this snippet: <|code_start|> if job.max_concurrency and concurrent > job.max_concurrency:
raise TooManyTasksForJob('max concurrency %d reached',
job.max_concurrency)
kwargs = task.kwargs or {}
task.status = states.STARTED
task.time_started = time_ended
if worker:
task.worker = worker.aid
logger.info(task.lazy_info())
await self.backend.publish('started', task)
future = self._consume(job, kwargs)
#
# record future for cancellation
if worker:
self._concurrent_tasks[task_id].future = future
#
# This may block until timeout
task.result = await wait_for(future, timeout)
else:
raise TaskError('Invalid status %s' % task.status_string)
except (CancelledError, TimeoutError, TaskTimeout):
task.result = None
task.status = states.REVOKED
logger.error(task.lazy_info())
except RemoteStackTrace:
task.status = states.FAILURE
logger.error(task.lazy_info())
except TaskError as exc:
<|code_end|>
with the help of current file imports:
import sys
import time
import traceback
import json
from asyncio import wait_for
from asyncio import CancelledError, TimeoutError
from asyncio.subprocess import Process
from .task import TaskError, TaskTimeout
from . import states
from ..cpubound import StreamProtocol, PROCESS_FILE
from ..utils.exc import string_exception
from ..utils import concurrency
and context from other files:
# Path: pq/tasks/task.py
# class TaskError(PulsarException):
# status = states.FAILURE
#
# class TaskTimeout(TaskError):
# pass
#
# Path: pq/cpubound.py
# class StreamProtocol(subprocess.SubprocessStreamProtocol):
#
# def __init__(self, job):
# super().__init__(streams._DEFAULT_LIMIT, job._loop)
# self.info = CpuTaskInfo(job)
# self.error = CpuTaskInfo(job)
#
# def pipe_data_received(self, fd, data):
# if fd == 1:
# self.info.feed(data)
# elif fd == 2:
# self.error.feed(data)
# super().pipe_data_received(fd, data)
#
# PROCESS_FILE = os.path.join(PQPATH, "cpubound.py")
#
# Path: pq/utils/exc.py
# def string_exception(exc):
# args = []
# for arg in exc.args:
# if isinstance(arg, str):
# args.append(arg)
# if args:
# return args[0] if len(args) == 1 else args
# return str(exc)
#
# Path: pq/utils/concurrency.py
# ASYNC_IO = 1 # run in the worker event loop
# THREAD_IO = 3 # run in the event loop executor
# CPUBOUND = 4 # run in a subprocess
, which may contain function names, class names, or code. Output only the next line. | task.result = string_exception(exc) |
Next line prediction: <|code_start|> logger.error(task.lazy_info())
except Exception as exc:
exc_info = sys.exc_info()
task.result = string_exception(exc)
task.status = states.FAILURE
task.stacktrace = traceback.format_tb(exc_info[2])
task.exception = traceback.format_exception_only(
exc_info[0], exc_info[1])[0]
logger.exception(task.lazy_info())
else:
task.status = states.SUCCESS
logger.info(task.lazy_info())
#
task.time_ended = time.time()
if worker:
self._concurrent_tasks.pop(task_id, None)
await self.backend.publish('done', task)
if job:
if worker:
await self.broker.decr(job.name)
if self._should_retry(job):
await self._requeue_task(job)
return task
def _consume(self, job, kwargs):
model = job.get_concurrency()
<|code_end|>
. Use current file imports:
(import sys
import time
import traceback
import json
from asyncio import wait_for
from asyncio import CancelledError, TimeoutError
from asyncio.subprocess import Process
from .task import TaskError, TaskTimeout
from . import states
from ..cpubound import StreamProtocol, PROCESS_FILE
from ..utils.exc import string_exception
from ..utils import concurrency)
and context including class names, function names, or small code snippets from other files:
# Path: pq/tasks/task.py
# class TaskError(PulsarException):
# status = states.FAILURE
#
# class TaskTimeout(TaskError):
# pass
#
# Path: pq/cpubound.py
# class StreamProtocol(subprocess.SubprocessStreamProtocol):
#
# def __init__(self, job):
# super().__init__(streams._DEFAULT_LIMIT, job._loop)
# self.info = CpuTaskInfo(job)
# self.error = CpuTaskInfo(job)
#
# def pipe_data_received(self, fd, data):
# if fd == 1:
# self.info.feed(data)
# elif fd == 2:
# self.error.feed(data)
# super().pipe_data_received(fd, data)
#
# PROCESS_FILE = os.path.join(PQPATH, "cpubound.py")
#
# Path: pq/utils/exc.py
# def string_exception(exc):
# args = []
# for arg in exc.args:
# if isinstance(arg, str):
# args.append(arg)
# if args:
# return args[0] if len(args) == 1 else args
# return str(exc)
#
# Path: pq/utils/concurrency.py
# ASYNC_IO = 1 # run in the worker event loop
# THREAD_IO = 3 # run in the event loop executor
# CPUBOUND = 4 # run in a subprocess
. Output only the next line. | if model == concurrency.THREAD_IO: |
Based on the snippet: <|code_start|>
class ShellError(RuntimeError):
@property
def returncode(self):
return self.args[1] if len(self.args) > 1 else 1
class RegistryMixin:
@lazyproperty
def registry(self):
'''The :class:`.JobRegistry` for this backend.
'''
return JobRegistry.load(self.cfg.task_paths)
def job_list(self, jobnames=None):
registry = self.registry
jobnames = jobnames or registry
all = []
for name in jobnames:
if name not in registry:
continue
job = registry[name]()
d = {'doc': job.__doc__,
'doc_syntax': job.doc_syntax,
<|code_end|>
, predict the immediate next line with the help of imports:
import sys
import logging
import inspect
import asyncio
from datetime import datetime, date
from pulsar.utils.slugify import slugify
from pulsar.utils.importer import import_modules
from pulsar.utils.log import lazyproperty
from pulsar.utils.string import to_bytes
from ..utils.concurrency import concurrency_name, ASYNC_IO
and context (classes, functions, sometimes code) from other files:
# Path: pq/utils/concurrency.py
# ASYNC_IO = 1 # run in the worker event loop
# THREAD_IO = 3 # run in the event loop executor
# CPUBOUND = 4 # run in a subprocess
. Output only the next line. | 'concurrency': concurrency_name.get(job.concurrency), |
Predict the next line for this snippet: <|code_start|> def cfg(self):
"""Configuration object from :attr:`backend`"""
return self.backend.cfg
@property
def green_pool(self):
return self.backend.green_pool
@property
def wait(self):
return self.backend.green_pool.wait
@property
def http(self):
"""Best possible HTTP session handler
"""
return self.backend.http_sessions(self.get_concurrency())
@property
def _loop(self):
return self.backend._loop if self.backend else None
@property
def type(self):
'''Type of Job, one of ``regular`` and ``periodic``.'''
return 'regular'
def get_concurrency(self):
'''The concurrency for this job
'''
<|code_end|>
with the help of current file imports:
import sys
import logging
import inspect
import asyncio
from datetime import datetime, date
from pulsar.utils.slugify import slugify
from pulsar.utils.importer import import_modules
from pulsar.utils.log import lazyproperty
from pulsar.utils.string import to_bytes
from ..utils.concurrency import concurrency_name, ASYNC_IO
and context from other files:
# Path: pq/utils/concurrency.py
# ASYNC_IO = 1 # run in the worker event loop
# THREAD_IO = 3 # run in the event loop executor
# CPUBOUND = 4 # run in a subprocess
, which may contain function names, class names, or code. Output only the next line. | return self.concurrency or ASYNC_IO |
Given the following code snippet before the placeholder: <|code_start|> concurrent_tasks = None
tq_app = None
rpc = None
schedule_periodic = False
message_serializer = 'json'
@classmethod
def name(cls):
return cls.__name__.lower()
@classmethod
def rpc_name(cls):
return 'rpc_%s' % cls.name()
@classmethod
async def setUpClass(cls):
# The name of the task queue application
params = cls.params()
params.update(
wsgi=True,
schedule_periodic=cls.schedule_periodic,
rpc_bind='127.0.0.1:0',
rpc_workers=0,
concurrent_tasks=cls.concurrent_tasks,
max_requests=cls.max_requests,
message_serializer=cls.message_serializer,
task_pool_timeout=0.1,
task_pool_timeout_max=0.1,
rpc_keep_alive=cls.rpc_timeout,
)
<|code_end|>
, predict the next line using imports from the current file:
import os
import sys
import asyncio
import threading
from pulsar.api import send, create_future
from pulsar.apps import rpc
from pq import api
and context including class names, function names, and sometimes code from other files:
# Path: pq/api.py
. Output only the next line. | pq = api.PulsarQueue(**params) |
Using the snippet: <|code_start|>"""Tests the api"""
class TestTasks(unittest.TestCase):
def app(self, task_paths=None, **kwargs):
task_paths = task_paths or ['tests.example.sampletasks.*']
<|code_end|>
, determine the next line of code. You have imports:
import unittest
from datetime import datetime
from unittest import mock
from pq import api
from pq.utils.time import format_time
from pq.tasks.consumer import poll_time
from tests.app import simple_task
and context (class names, function names, or code) available:
# Path: pq/api.py
#
# Path: pq/utils/time.py
# def format_time(dt):
# dt = timestamp_to_datetime(dt)
# return dt.isoformat() if dt else '?'
#
# Path: pq/tasks/consumer.py
# def poll_time(a, b, x, lag=0):
# a = max(a, 0) # 0 minimum pool gap
# b = max(a, b) # b cannot be less than a
# return max(a + (b-a) * (exp(x) - x - 1)/FACTOR - lag, 0)
#
# Path: tests/app.py
# def simple_task(self, value=0):
# return self.v0 + value
. Output only the next line. | app = api.QueueApp(task_paths=task_paths, **kwargs) |
Continue the code snippet: <|code_start|>"""Tests the api"""
class TestTasks(unittest.TestCase):
def app(self, task_paths=None, **kwargs):
task_paths = task_paths or ['tests.example.sampletasks.*']
app = api.QueueApp(task_paths=task_paths, **kwargs)
app.backend.tasks.queue = mock.MagicMock()
return app
def test_decorator(self):
job_cls = api.job('bla foo', v0=6)(simple_task)
job = job_cls()
self.assertIsInstance(job, api.Job)
self.assertEqual(job(value=4), 10)
self.assertEqual(str(job), 'bla.foo')
self.assertFalse(job.task)
def test_unknown_state(self):
self.assertEqual(api.status_string(243134), 'UNKNOWN')
self.assertEqual(api.status_string('jhbjhbj'), 'UNKNOWN')
self.assertEqual(api.status_string(1), 'SUCCESS')
def test_format_time(self):
dt = datetime.now()
<|code_end|>
. Use current file imports:
import unittest
from datetime import datetime
from unittest import mock
from pq import api
from pq.utils.time import format_time
from pq.tasks.consumer import poll_time
from tests.app import simple_task
and context (classes, functions, or code) from other files:
# Path: pq/api.py
#
# Path: pq/utils/time.py
# def format_time(dt):
# dt = timestamp_to_datetime(dt)
# return dt.isoformat() if dt else '?'
#
# Path: pq/tasks/consumer.py
# def poll_time(a, b, x, lag=0):
# a = max(a, 0) # 0 minimum pool gap
# b = max(a, b) # b cannot be less than a
# return max(a + (b-a) * (exp(x) - x - 1)/FACTOR - lag, 0)
#
# Path: tests/app.py
# def simple_task(self, value=0):
# return self.v0 + value
. Output only the next line. | st = format_time(dt) |
Continue the code snippet: <|code_start|> def test_close(self):
t = api.QueueApp().api()
self.assertEqual(t.closing(), False)
t.close()
self.assertEqual(t.closing(), True)
self.assertEqual(t.tasks.closing(), True)
warn = mock.MagicMock()
t.tasks.logger.warning = warn
self.assertFalse(t.tasks.queue('foo'))
self.assertEqual(warn.call_count, 1)
self.assertEqual(
warn.call_args[0][0],
'Cannot queue task, task backend closing'
)
def test_task_not_available(self):
t = api.QueueApp().api()
self.assertRaises(api.TaskNotAvailable,
t.tasks.queue, 'jsdbcjsdhbc')
def test_queues(self):
t = api.QueueApp().api()
self.assertTrue(t.tasks.queues())
def test_namespace(self):
t = api.QueueApp(config='tests.config').api()
self.assertEqual(t.broker.namespace, 'pqtests_')
self.assertEqual(t.broker.prefixed('foo'), 'pqtests_foo')
def test_poll_time(self):
<|code_end|>
. Use current file imports:
import unittest
from datetime import datetime
from unittest import mock
from pq import api
from pq.utils.time import format_time
from pq.tasks.consumer import poll_time
from tests.app import simple_task
and context (classes, functions, or code) from other files:
# Path: pq/api.py
#
# Path: pq/utils/time.py
# def format_time(dt):
# dt = timestamp_to_datetime(dt)
# return dt.isoformat() if dt else '?'
#
# Path: pq/tasks/consumer.py
# def poll_time(a, b, x, lag=0):
# a = max(a, 0) # 0 minimum pool gap
# b = max(a, b) # b cannot be less than a
# return max(a + (b-a) * (exp(x) - x - 1)/FACTOR - lag, 0)
#
# Path: tests/app.py
# def simple_task(self, value=0):
# return self.v0 + value
. Output only the next line. | self.assertEqual(poll_time(1, 4, 0), 1) |
Based on the snippet: <|code_start|>"""Tests the api"""
class TestTasks(unittest.TestCase):
def app(self, task_paths=None, **kwargs):
task_paths = task_paths or ['tests.example.sampletasks.*']
app = api.QueueApp(task_paths=task_paths, **kwargs)
app.backend.tasks.queue = mock.MagicMock()
return app
def test_decorator(self):
<|code_end|>
, predict the immediate next line with the help of imports:
import unittest
from datetime import datetime
from unittest import mock
from pq import api
from pq.utils.time import format_time
from pq.tasks.consumer import poll_time
from tests.app import simple_task
and context (classes, functions, sometimes code) from other files:
# Path: pq/api.py
#
# Path: pq/utils/time.py
# def format_time(dt):
# dt = timestamp_to_datetime(dt)
# return dt.isoformat() if dt else '?'
#
# Path: pq/tasks/consumer.py
# def poll_time(a, b, x, lag=0):
# a = max(a, 0) # 0 minimum pool gap
# b = max(a, b) # b cannot be less than a
# return max(a + (b-a) * (exp(x) - x - 1)/FACTOR - lag, 0)
#
# Path: tests/app.py
# def simple_task(self, value=0):
# return self.v0 + value
. Output only the next line. | job_cls = api.job('bla foo', v0=6)(simple_task) |
Using the snippet: <|code_start|>"""Tests task execution with MsgPack serialiser"""
try:
except ImportError:
msgpack = None
@unittest.skipUnless(msgpack, "Requires msgpack library")
<|code_end|>
, determine the next line of code. You have imports:
import unittest
import msgpack
from tests import app
and context (class names, function names, or code) available:
# Path: tests/app.py
# CODE_TEST = '''\
# import time
# def task_function(N = 10, lag = 0.1):
# time.sleep(lag)
# return N*N
# '''
# PATH = os.path.dirname(__file__)
# def simple_task(self, value=0):
# def name(cls):
# def rpc_name(cls):
# async def setUpClass(cls):
# def tearDownClass(cls):
# def queues(cls):
# def params(cls):
# def test_registry(self):
# def test_consumer(self):
# def test_job_list(self):
# async def test_simple_task(self):
# async def test_info(self):
# async def test_async_job(self):
# async def test_failure(self):
# async def test_execute_addition(self):
# async def test_green_executor(self):
# async def test_queue_local(self):
# async def test_no_callback(self):
# async def test_cpubound_task(self):
# async def __test_error_cpubound_task(self):
# async def test_is_in_greenlet(self):
# async def test_cpu_supports_asyncio(self):
# async def test_big_log(self):
# async def test_execute_python_code(self):
# async def test_execute_python_script(self):
# async def test_queue_size(self):
# async def test_lock(self):
# async def test_queue_from_task(self):
# async def test_scrape(self):
# async def test_delay(self):
# async def test_thread_io(self):
# async def test_bad_task(self):
# async def test_retry(self):
# def __call__(self, _, event, task):
# async def test_max_concurrency(self):
# async def test_task_timeout(self):
# async def test_rpc_job_list(self):
# async def test_rpc_queue_task(self):
# class TaskQueueBase:
# class TaskQueueApp(TaskQueueBase):
# class CheckRetry:
. Output only the next line. | class TestMsgPackQueue(app.TaskQueueApp, unittest.TestCase): |
Predict the next line for this snippet: <|code_start|>
.. attribute:: total_run_count
Total number of times this periodic task has been executed by the
:class:`.TaskBackend`.
'''
def __init__(self, name, run_every, anchor=None):
self.name = name
self.run_every = run_every
self.anchor = anchor
self.last_run_at = datetime.now()
self.total_run_count = 0
def __repr__(self):
return self.name
__str__ = __repr__
@property
def scheduled_last_run_at(self):
'''The scheduled last run datetime.
This is different from :attr:`last_run_at` only when
:attr:`anchor` is set.
'''
last_run_at = self.last_run_at
anchor = self.anchor
if last_run_at and anchor:
run_every = self.run_every
<|code_end|>
with the help of current file imports:
import time
from datetime import datetime, timedelta
from pulsar.utils.log import lazyproperty
from ..utils.time import timedelta_seconds
and context from other files:
# Path: pq/utils/time.py
# def timedelta_seconds(delta):
# return max(delta.total_seconds(), 0)
, which may contain function names, class names, or code. Output only the next line. | times = int(timedelta_seconds(last_run_at - anchor) / |
Given the following code snippet before the placeholder: <|code_start|>
HEARTBEAT = 2
class Consumer(Producer):
"""The consumer is used by the server side application
"""
def __repr__(self):
return 'consumer <%s>' % self.broker
@property
def is_consumer(self):
return True
def tick(self, monitor):
for consumer in self.consumers:
consumer.tick()
async def worker_tick(self, worker, next=None):
pnext, next = next, HEARTBEAT
try:
info = dict(self.info())
info['consumer'] = worker.aid
info['node'] = self.node_name
info['pubsub'] = str(self.channels)
info['cores'] = cpu_count()
info['message-broker'] = str(self.broker.store)
info['time'] = time.time()
if self.cfg.debug:
self.logger.debug('publishing worker %s info', worker)
<|code_end|>
, predict the next line using imports from the current file:
import time
import asyncio
from multiprocessing import cpu_count
from pulsar.apps.data.channels import backoff
from .producer import Producer, ConsumerMessage
and context including class names, function names, and sometimes code from other files:
# Path: pq/server/producer.py
# class Producer(EventHandler):
# """Produce tasks by queuing them
#
# Abstract base class for both task schedulers and task consumers
# """
# app = None
# ONE_TIME_EVENTS = ('close',)
#
# def __init__(self, cfg, *, logger=None, **kw):
# # create the store for channels
# store = create_store(cfg.data_store, loop=cfg.params.pop('loop', None))
# self.cfg = cfg
# self._loop = store._loop
# self.logger = logger
# self._closing_waiter = None
# if not cfg.message_broker:
# broker = store
# else:
# broker = create_store(cfg.message_broker, loop=self._loop)
# self.manager = (self.cfg.callable or Manager)(self)
# self.broker = register_broker(broker.name)(self, broker)
# self.channels = store.channels(
# protocol=self.broker,
# status_channel=ConsumerMessage.type,
# logger=self.logger
# )
# self.http = self.manager.http()
# self.green_pool = self.manager.green_pool()
# self.consumers = []
# for consumer_path in self.cfg.consumers:
# consumer = module_attribute(consumer_path)(self)
# self.consumers.append(consumer)
# setattr(self, consumer.name, consumer)
#
# def __str__(self):
# return repr(self)
#
# def __repr__(self):
# return 'producer <%s>' % self.broker
#
# @property
# def node_name(self):
# return platform.node().lower()
#
# @property
# def is_consumer(self):
# return False
#
# async def start(self):
# # Register consumers
# for consumer in self.consumers:
# await as_coroutine(consumer.register())
# # connect channels
# await self.channels.connect()
# self.manager.start()
# return self
#
# async def publish(self, event, message):
# """Publish an event to the message channel
# """
# coro = [
# self.manager.store_message(message),
# self.channels.publish(message.type, event, message)
# ]
# if message.id:
# coro.append(
# self.channels.publish(message.type, message.id, message)
# )
# await gather(*coro)
#
# def tick(self, monitor):
# pass
#
# def info(self):
# for consumer in self.consumers:
# try:
# info = consumer.info()
# except Exception:
# self.logger.exception('Unhandled information exception')
# else:
# if info:
# yield consumer.name, info
#
# def lock(self, name, **kwargs):
# """aquire a distributed global lock for ``name``
# """
# return self.channels.lock('lock-%s' % name, **kwargs)
#
# def http_sessions(self, model=None):
# """Return an HTTP session handler for a given concurrency model
# """
# if model == concurrency.THREAD_IO:
# return HttpClient(loop=new_event_loop())
# elif model == concurrency.ASYNC_IO:
# return self.http
# else:
# return GreenHttp(self.http)
#
# def on_events(self, channel, event, callback):
# return self._loop.create_task(
# self.channels.register(channel, event, callback)
# )
#
# def remove_event_callback(self, channel, event, callback):
# return self._loop.create_task(
# self.channels.unregister(channel, event, callback)
# )
#
# def queue(self, message, callback=True):
# return self.broker.queue(message, callback=callback)
#
# def execute(self, message):
# consumer = message.consumer()
# if consumer:
# return getattr(self, consumer).execute(message)
# return message
#
# def closing(self):
# return self._closing_waiter is not None
#
# def close(self, msg=None):
# '''Close this :class:`.TaskBackend`.
#
# Invoked by the :class:`.Actor` when stopping.
# '''
# if not self._closing_waiter:
# if msg:
# self.logger.warning(msg)
# closing = []
# for consumer in self.consumers:
# result = consumer.close()
# if not result.done():
# closing.append(result)
#
# self._closing_waiter = ensure_future(
# _close(self, closing, self._loop),
# loop=self._loop
# )
# return self._closing_waiter
#
# class ConsumerMessage(MessageDict):
# type = 'consumer'
. Output only the next line. | await self.publish('status', ConsumerMessage(info)) |
Predict the next line after this snippet: <|code_start|> >>> do("cat -", stdin=b"ELBE")
[CMD] cat -
>>> do("cat - && false", stdin=b"ELBE") # doctest: +ELLIPSIS
Traceback (most recent call last):
...
elbepack.shellhelper.CommandError: ...
>>> do("false") # doctest: +ELLIPSIS
Traceback (most recent call last):
...
elbepack.shellhelper.CommandError: ...
"""
new_env = os.environ.copy()
if env_add:
new_env.update(env_add)
if isinstance(stdin, str):
stdin = stdin.encode()
logging.info(cmd, extra={"context":"[CMD] "})
r, w = os.pipe()
if stdin is None:
p = Popen(cmd, shell=True, stdout=w, stderr=STDOUT, env=new_env)
else:
p = Popen(cmd, shell=True, stdin=PIPE, stdout=w, stderr=STDOUT, env=new_env)
<|code_end|>
using the current file's imports:
import os
import logging
from subprocess import Popen, PIPE, STDOUT, call
from io import TextIOWrapper, BytesIO
from elbepack.log import async_logging
and any relevant context from other files:
# Path: elbepack/log.py
# def async_logging(r, w, stream, block, atmost=4096):
# t = threading.Thread(target=AsyncLogging(atmost, stream, block),
# args=(r, w))
# t.daemon = True
# t.start()
. Output only the next line. | async_logging(r, w, soap, log) |
Given the following code snippet before the placeholder: <|code_start|>
sels = []
for l in fp.readlines():
if not l:
continue
if l[0] == '#':
continue
sp = l.split()
print("%s %s" % (sp[0], sp[1]))
if sp[1] == 'install':
sels.append(sp[0])
print(sels)
return sels
def run_command(argv):
oparser = OptionParser(usage="usage: %prog setsel <xmlfile> <pkglist.txt>")
(_, args) = oparser.parse_args(argv)
if len(args) != 2:
print("Wrong number of arguments")
oparser.print_help()
sys.exit(20)
<|code_end|>
, predict the next line using imports from the current file:
import sys
from optparse import OptionParser
from elbepack.treeutils import etree
and context including class names, function names, and sometimes code from other files:
# Path: elbepack/treeutils.py
# class etree(ebase):
# def __init__(self, fname):
# if fname is not None:
# parser = XMLParser(huge_tree=True, remove_comments=False)
# et = parse(fname, parser=parser)
# else:
# et = ElementTree(file=None)
#
# ebase.__init__(self, et)
#
# def write(self, fname, encoding=None):
# # Make sure, that we end with a newline
# self.et.getroot().tail = '\n'
# self.et.write(fname, encoding=encoding)
#
# def tostring(self):
# return self.et.tostring()
#
# def ensure_child(self, tag):
# retval = self.et.find("./" + tag)
# if retval is not None:
# return elem(retval)
# return elem(SubElement(self.et.getroot(), tag))
#
# def set_child_position(self, child, pos):
# root = self.et.getroot()
# root.remove(child.et)
# root.insert(pos, child.et)
#
# def setroot(self, tag):
# retval = elem(Element(tag))
# # pylint: disable=protected-access
# self.et._setroot(retval.et)
# return retval
#
# @property
# def root(self):
# return elem(self.et.getroot())
. Output only the next line. | xml = etree(args[0]) |
Next line prediction: <|code_start|> pass
class ValidationMode:
NO_CHECK = 1
CHECK_BINARIES = 2
CHECK_ALL = 0
def replace_localmachine(mirror, initvm=True):
if initvm:
localmachine = "10.0.2.2"
else:
localmachine = "localhost"
return mirror.replace("LOCALMACHINE", localmachine)
class ElbeXML:
# pylint: disable=too-many-public-methods
def __init__(
self,
fname,
buildtype=None,
skip_validate=False,
url_validation=ValidationMode.NO_CHECK):
if not skip_validate:
validation = validate_xml(fname)
if validation:
raise ValidationError(validation)
<|code_end|>
. Use current file imports:
(import os
import re
from urllib.error import URLError
from urllib.request import (urlopen, install_opener, build_opener,
HTTPPasswordMgrWithDefaultRealm,
HTTPBasicAuthHandler)
from elbepack.treeutils import etree
from elbepack.validate import validate_xml
from elbepack.xmldefaults import ElbeDefaults
from elbepack.version import elbe_version, is_devel)
and context including class names, function names, or small code snippets from other files:
# Path: elbepack/treeutils.py
# class etree(ebase):
# def __init__(self, fname):
# if fname is not None:
# parser = XMLParser(huge_tree=True, remove_comments=False)
# et = parse(fname, parser=parser)
# else:
# et = ElementTree(file=None)
#
# ebase.__init__(self, et)
#
# def write(self, fname, encoding=None):
# # Make sure, that we end with a newline
# self.et.getroot().tail = '\n'
# self.et.write(fname, encoding=encoding)
#
# def tostring(self):
# return self.et.tostring()
#
# def ensure_child(self, tag):
# retval = self.et.find("./" + tag)
# if retval is not None:
# return elem(retval)
# return elem(SubElement(self.et.getroot(), tag))
#
# def set_child_position(self, child, pos):
# root = self.et.getroot()
# root.remove(child.et)
# root.insert(pos, child.et)
#
# def setroot(self, tag):
# retval = elem(Element(tag))
# # pylint: disable=protected-access
# self.et._setroot(retval.et)
# return retval
#
# @property
# def root(self):
# return elem(self.et.getroot())
#
# Path: elbepack/validate.py
# def validate_xml(fname):
# if os.path.getsize(fname) > (1 << 30):
# return ["%s is greater than 1 GiB. "
# "Elbe does not support files of this size." % fname]
#
# schema_file = "https://www.linutronix.de/projects/Elbe/dbsfed.xsd"
# parser = XMLParser(huge_tree=True)
# schema_tree = etree.parse(schema_file)
# schema = etree.XMLSchema(schema_tree)
#
# try:
# xml = parse(fname, parser=parser)
#
# if schema.validate(xml):
# return validate_xml_content(xml)
# except etree.XMLSyntaxError:
# return ["XML Parse error\n" + str(sys.exc_info()[1])]
# except BaseException:
# return ["Unknown Exception during validation\n" +
# str(sys.exc_info()[1])]
#
# # We have errors, return them in string form...
# return error_log_to_strings(schema.error_log)
#
# Path: elbepack/xmldefaults.py
# class ElbeDefaults:
#
# def __init__(self, build_type):
#
# assert build_type in defaults, ("Invalid buildtype %s\n"
# "Valid buildtypes are:\n - %s" %
# (build_type, "\n - ".join(defaults.keys())))
#
# self.defaults = defaults[build_type]
# self.defaults["nicmac"] = get_random_mac()
#
# self.generic_defaults = archindep_defaults
#
# def __getitem__(self, key):
# if key in self.defaults:
# return self.defaults[key]
# if key in self.generic_defaults:
# return self.generic_defaults[key]
#
# return None
#
# Path: elbepack/version.py
. Output only the next line. | self.xml = etree(fname) |
Continue the code snippet: <|code_start|> return retval
class NoInitvmNode(Exception):
pass
class ValidationMode:
NO_CHECK = 1
CHECK_BINARIES = 2
CHECK_ALL = 0
def replace_localmachine(mirror, initvm=True):
if initvm:
localmachine = "10.0.2.2"
else:
localmachine = "localhost"
return mirror.replace("LOCALMACHINE", localmachine)
class ElbeXML:
# pylint: disable=too-many-public-methods
def __init__(
self,
fname,
buildtype=None,
skip_validate=False,
url_validation=ValidationMode.NO_CHECK):
if not skip_validate:
<|code_end|>
. Use current file imports:
import os
import re
from urllib.error import URLError
from urllib.request import (urlopen, install_opener, build_opener,
HTTPPasswordMgrWithDefaultRealm,
HTTPBasicAuthHandler)
from elbepack.treeutils import etree
from elbepack.validate import validate_xml
from elbepack.xmldefaults import ElbeDefaults
from elbepack.version import elbe_version, is_devel
and context (classes, functions, or code) from other files:
# Path: elbepack/treeutils.py
# class etree(ebase):
# def __init__(self, fname):
# if fname is not None:
# parser = XMLParser(huge_tree=True, remove_comments=False)
# et = parse(fname, parser=parser)
# else:
# et = ElementTree(file=None)
#
# ebase.__init__(self, et)
#
# def write(self, fname, encoding=None):
# # Make sure, that we end with a newline
# self.et.getroot().tail = '\n'
# self.et.write(fname, encoding=encoding)
#
# def tostring(self):
# return self.et.tostring()
#
# def ensure_child(self, tag):
# retval = self.et.find("./" + tag)
# if retval is not None:
# return elem(retval)
# return elem(SubElement(self.et.getroot(), tag))
#
# def set_child_position(self, child, pos):
# root = self.et.getroot()
# root.remove(child.et)
# root.insert(pos, child.et)
#
# def setroot(self, tag):
# retval = elem(Element(tag))
# # pylint: disable=protected-access
# self.et._setroot(retval.et)
# return retval
#
# @property
# def root(self):
# return elem(self.et.getroot())
#
# Path: elbepack/validate.py
# def validate_xml(fname):
# if os.path.getsize(fname) > (1 << 30):
# return ["%s is greater than 1 GiB. "
# "Elbe does not support files of this size." % fname]
#
# schema_file = "https://www.linutronix.de/projects/Elbe/dbsfed.xsd"
# parser = XMLParser(huge_tree=True)
# schema_tree = etree.parse(schema_file)
# schema = etree.XMLSchema(schema_tree)
#
# try:
# xml = parse(fname, parser=parser)
#
# if schema.validate(xml):
# return validate_xml_content(xml)
# except etree.XMLSyntaxError:
# return ["XML Parse error\n" + str(sys.exc_info()[1])]
# except BaseException:
# return ["Unknown Exception during validation\n" +
# str(sys.exc_info()[1])]
#
# # We have errors, return them in string form...
# return error_log_to_strings(schema.error_log)
#
# Path: elbepack/xmldefaults.py
# class ElbeDefaults:
#
# def __init__(self, build_type):
#
# assert build_type in defaults, ("Invalid buildtype %s\n"
# "Valid buildtypes are:\n - %s" %
# (build_type, "\n - ".join(defaults.keys())))
#
# self.defaults = defaults[build_type]
# self.defaults["nicmac"] = get_random_mac()
#
# self.generic_defaults = archindep_defaults
#
# def __getitem__(self, key):
# if key in self.defaults:
# return self.defaults[key]
# if key in self.generic_defaults:
# return self.generic_defaults[key]
#
# return None
#
# Path: elbepack/version.py
. Output only the next line. | validation = validate_xml(fname) |
Continue the code snippet: <|code_start|> else:
localmachine = "localhost"
return mirror.replace("LOCALMACHINE", localmachine)
class ElbeXML:
# pylint: disable=too-many-public-methods
def __init__(
self,
fname,
buildtype=None,
skip_validate=False,
url_validation=ValidationMode.NO_CHECK):
if not skip_validate:
validation = validate_xml(fname)
if validation:
raise ValidationError(validation)
self.xml = etree(fname)
self.prj = self.xml.node("/project")
self.tgt = self.xml.node("/target")
if buildtype:
pass
elif self.xml.has("project/buildtype"):
buildtype = self.xml.text("/project/buildtype")
else:
buildtype = "nodefaults"
<|code_end|>
. Use current file imports:
import os
import re
from urllib.error import URLError
from urllib.request import (urlopen, install_opener, build_opener,
HTTPPasswordMgrWithDefaultRealm,
HTTPBasicAuthHandler)
from elbepack.treeutils import etree
from elbepack.validate import validate_xml
from elbepack.xmldefaults import ElbeDefaults
from elbepack.version import elbe_version, is_devel
and context (classes, functions, or code) from other files:
# Path: elbepack/treeutils.py
# class etree(ebase):
# def __init__(self, fname):
# if fname is not None:
# parser = XMLParser(huge_tree=True, remove_comments=False)
# et = parse(fname, parser=parser)
# else:
# et = ElementTree(file=None)
#
# ebase.__init__(self, et)
#
# def write(self, fname, encoding=None):
# # Make sure, that we end with a newline
# self.et.getroot().tail = '\n'
# self.et.write(fname, encoding=encoding)
#
# def tostring(self):
# return self.et.tostring()
#
# def ensure_child(self, tag):
# retval = self.et.find("./" + tag)
# if retval is not None:
# return elem(retval)
# return elem(SubElement(self.et.getroot(), tag))
#
# def set_child_position(self, child, pos):
# root = self.et.getroot()
# root.remove(child.et)
# root.insert(pos, child.et)
#
# def setroot(self, tag):
# retval = elem(Element(tag))
# # pylint: disable=protected-access
# self.et._setroot(retval.et)
# return retval
#
# @property
# def root(self):
# return elem(self.et.getroot())
#
# Path: elbepack/validate.py
# def validate_xml(fname):
# if os.path.getsize(fname) > (1 << 30):
# return ["%s is greater than 1 GiB. "
# "Elbe does not support files of this size." % fname]
#
# schema_file = "https://www.linutronix.de/projects/Elbe/dbsfed.xsd"
# parser = XMLParser(huge_tree=True)
# schema_tree = etree.parse(schema_file)
# schema = etree.XMLSchema(schema_tree)
#
# try:
# xml = parse(fname, parser=parser)
#
# if schema.validate(xml):
# return validate_xml_content(xml)
# except etree.XMLSyntaxError:
# return ["XML Parse error\n" + str(sys.exc_info()[1])]
# except BaseException:
# return ["Unknown Exception during validation\n" +
# str(sys.exc_info()[1])]
#
# # We have errors, return them in string form...
# return error_log_to_strings(schema.error_log)
#
# Path: elbepack/xmldefaults.py
# class ElbeDefaults:
#
# def __init__(self, build_type):
#
# assert build_type in defaults, ("Invalid buildtype %s\n"
# "Valid buildtypes are:\n - %s" %
# (build_type, "\n - ".join(defaults.keys())))
#
# self.defaults = defaults[build_type]
# self.defaults["nicmac"] = get_random_mac()
#
# self.generic_defaults = archindep_defaults
#
# def __getitem__(self, key):
# if key in self.defaults:
# return self.defaults[key]
# if key in self.generic_defaults:
# return self.generic_defaults[key]
#
# return None
#
# Path: elbepack/version.py
. Output only the next line. | self.defs = ElbeDefaults(buildtype) |
Given the following code snippet before the placeholder: <|code_start|>
for e in other.node('debootstrappkgs'):
tree.append_treecopy(e)
def get_initvmnode_from(self, other):
ivm = other.node('initvm')
if ivm is None:
raise NoInitvmNode()
tree = self.xml.ensure_child('initvm')
tree.clear()
for e in ivm:
tree.append_treecopy(e)
self.xml.set_child_position(tree, 0)
def get_initvm_codename(self):
if self.has("initvm/suite"):
return self.text("initvm/suite")
return None
def set_cdrom_mirror(self, abspath):
mirror = self.node("project/mirror")
mirror.clear()
cdrom = mirror.ensure_child("cdrom")
cdrom.set_text(abspath)
def dump_elbe_version(self):
if is_devel:
<|code_end|>
, predict the next line using imports from the current file:
import os
import re
from urllib.error import URLError
from urllib.request import (urlopen, install_opener, build_opener,
HTTPPasswordMgrWithDefaultRealm,
HTTPBasicAuthHandler)
from elbepack.treeutils import etree
from elbepack.validate import validate_xml
from elbepack.xmldefaults import ElbeDefaults
from elbepack.version import elbe_version, is_devel
and context including class names, function names, and sometimes code from other files:
# Path: elbepack/treeutils.py
# class etree(ebase):
# def __init__(self, fname):
# if fname is not None:
# parser = XMLParser(huge_tree=True, remove_comments=False)
# et = parse(fname, parser=parser)
# else:
# et = ElementTree(file=None)
#
# ebase.__init__(self, et)
#
# def write(self, fname, encoding=None):
# # Make sure, that we end with a newline
# self.et.getroot().tail = '\n'
# self.et.write(fname, encoding=encoding)
#
# def tostring(self):
# return self.et.tostring()
#
# def ensure_child(self, tag):
# retval = self.et.find("./" + tag)
# if retval is not None:
# return elem(retval)
# return elem(SubElement(self.et.getroot(), tag))
#
# def set_child_position(self, child, pos):
# root = self.et.getroot()
# root.remove(child.et)
# root.insert(pos, child.et)
#
# def setroot(self, tag):
# retval = elem(Element(tag))
# # pylint: disable=protected-access
# self.et._setroot(retval.et)
# return retval
#
# @property
# def root(self):
# return elem(self.et.getroot())
#
# Path: elbepack/validate.py
# def validate_xml(fname):
# if os.path.getsize(fname) > (1 << 30):
# return ["%s is greater than 1 GiB. "
# "Elbe does not support files of this size." % fname]
#
# schema_file = "https://www.linutronix.de/projects/Elbe/dbsfed.xsd"
# parser = XMLParser(huge_tree=True)
# schema_tree = etree.parse(schema_file)
# schema = etree.XMLSchema(schema_tree)
#
# try:
# xml = parse(fname, parser=parser)
#
# if schema.validate(xml):
# return validate_xml_content(xml)
# except etree.XMLSyntaxError:
# return ["XML Parse error\n" + str(sys.exc_info()[1])]
# except BaseException:
# return ["Unknown Exception during validation\n" +
# str(sys.exc_info()[1])]
#
# # We have errors, return them in string form...
# return error_log_to_strings(schema.error_log)
#
# Path: elbepack/xmldefaults.py
# class ElbeDefaults:
#
# def __init__(self, build_type):
#
# assert build_type in defaults, ("Invalid buildtype %s\n"
# "Valid buildtypes are:\n - %s" %
# (build_type, "\n - ".join(defaults.keys())))
#
# self.defaults = defaults[build_type]
# self.defaults["nicmac"] = get_random_mac()
#
# self.generic_defaults = archindep_defaults
#
# def __getitem__(self, key):
# if key in self.defaults:
# return self.defaults[key]
# if key in self.generic_defaults:
# return self.generic_defaults[key]
#
# return None
#
# Path: elbepack/version.py
. Output only the next line. | ver_text = elbe_version + '-devel' |
Given the code snippet: <|code_start|> return
for e in other.node('debootstrappkgs'):
tree.append_treecopy(e)
def get_initvmnode_from(self, other):
ivm = other.node('initvm')
if ivm is None:
raise NoInitvmNode()
tree = self.xml.ensure_child('initvm')
tree.clear()
for e in ivm:
tree.append_treecopy(e)
self.xml.set_child_position(tree, 0)
def get_initvm_codename(self):
if self.has("initvm/suite"):
return self.text("initvm/suite")
return None
def set_cdrom_mirror(self, abspath):
mirror = self.node("project/mirror")
mirror.clear()
cdrom = mirror.ensure_child("cdrom")
cdrom.set_text(abspath)
def dump_elbe_version(self):
<|code_end|>
, generate the next line using the imports in this file:
import os
import re
from urllib.error import URLError
from urllib.request import (urlopen, install_opener, build_opener,
HTTPPasswordMgrWithDefaultRealm,
HTTPBasicAuthHandler)
from elbepack.treeutils import etree
from elbepack.validate import validate_xml
from elbepack.xmldefaults import ElbeDefaults
from elbepack.version import elbe_version, is_devel
and context (functions, classes, or occasionally code) from other files:
# Path: elbepack/treeutils.py
# class etree(ebase):
# def __init__(self, fname):
# if fname is not None:
# parser = XMLParser(huge_tree=True, remove_comments=False)
# et = parse(fname, parser=parser)
# else:
# et = ElementTree(file=None)
#
# ebase.__init__(self, et)
#
# def write(self, fname, encoding=None):
# # Make sure, that we end with a newline
# self.et.getroot().tail = '\n'
# self.et.write(fname, encoding=encoding)
#
# def tostring(self):
# return self.et.tostring()
#
# def ensure_child(self, tag):
# retval = self.et.find("./" + tag)
# if retval is not None:
# return elem(retval)
# return elem(SubElement(self.et.getroot(), tag))
#
# def set_child_position(self, child, pos):
# root = self.et.getroot()
# root.remove(child.et)
# root.insert(pos, child.et)
#
# def setroot(self, tag):
# retval = elem(Element(tag))
# # pylint: disable=protected-access
# self.et._setroot(retval.et)
# return retval
#
# @property
# def root(self):
# return elem(self.et.getroot())
#
# Path: elbepack/validate.py
# def validate_xml(fname):
# if os.path.getsize(fname) > (1 << 30):
# return ["%s is greater than 1 GiB. "
# "Elbe does not support files of this size." % fname]
#
# schema_file = "https://www.linutronix.de/projects/Elbe/dbsfed.xsd"
# parser = XMLParser(huge_tree=True)
# schema_tree = etree.parse(schema_file)
# schema = etree.XMLSchema(schema_tree)
#
# try:
# xml = parse(fname, parser=parser)
#
# if schema.validate(xml):
# return validate_xml_content(xml)
# except etree.XMLSyntaxError:
# return ["XML Parse error\n" + str(sys.exc_info()[1])]
# except BaseException:
# return ["Unknown Exception during validation\n" +
# str(sys.exc_info()[1])]
#
# # We have errors, return them in string form...
# return error_log_to_strings(schema.error_log)
#
# Path: elbepack/xmldefaults.py
# class ElbeDefaults:
#
# def __init__(self, build_type):
#
# assert build_type in defaults, ("Invalid buildtype %s\n"
# "Valid buildtypes are:\n - %s" %
# (build_type, "\n - ".join(defaults.keys())))
#
# self.defaults = defaults[build_type]
# self.defaults["nicmac"] = get_random_mac()
#
# self.generic_defaults = archindep_defaults
#
# def __getitem__(self, key):
# if key in self.defaults:
# return self.defaults[key]
# if key in self.generic_defaults:
# return self.generic_defaults[key]
#
# return None
#
# Path: elbepack/version.py
. Output only the next line. | if is_devel: |
Predict the next line for this snippet: <|code_start|>
oparser.add_option("--verbose", action="store_true", dest="verbose",
default=False,
help="show detailed project informations")
oparser.add_option("--skip-validation", action="store_true",
dest="skip_validation", default=False,
help="Skip xml schema validation")
(opt, args) = oparser.parse_args(argv)
if not args:
print("No Filename specified")
oparser.print_help()
sys.exit(20)
if len(args) > 1:
print("too many filenames specified")
oparser.print_help()
sys.exit(20)
try:
if not opt.skip_validation:
validation = validate_xml(args[0])
if validation:
print("xml validation failed. Bailing out")
for i in validation:
print(i)
sys.exit(20)
<|code_end|>
with the help of current file imports:
import sys
from optparse import OptionParser
from elbepack.treeutils import etree
from elbepack.validate import validate_xml
and context from other files:
# Path: elbepack/treeutils.py
# class etree(ebase):
# def __init__(self, fname):
# if fname is not None:
# parser = XMLParser(huge_tree=True, remove_comments=False)
# et = parse(fname, parser=parser)
# else:
# et = ElementTree(file=None)
#
# ebase.__init__(self, et)
#
# def write(self, fname, encoding=None):
# # Make sure, that we end with a newline
# self.et.getroot().tail = '\n'
# self.et.write(fname, encoding=encoding)
#
# def tostring(self):
# return self.et.tostring()
#
# def ensure_child(self, tag):
# retval = self.et.find("./" + tag)
# if retval is not None:
# return elem(retval)
# return elem(SubElement(self.et.getroot(), tag))
#
# def set_child_position(self, child, pos):
# root = self.et.getroot()
# root.remove(child.et)
# root.insert(pos, child.et)
#
# def setroot(self, tag):
# retval = elem(Element(tag))
# # pylint: disable=protected-access
# self.et._setroot(retval.et)
# return retval
#
# @property
# def root(self):
# return elem(self.et.getroot())
#
# Path: elbepack/validate.py
# def validate_xml(fname):
# if os.path.getsize(fname) > (1 << 30):
# return ["%s is greater than 1 GiB. "
# "Elbe does not support files of this size." % fname]
#
# schema_file = "https://www.linutronix.de/projects/Elbe/dbsfed.xsd"
# parser = XMLParser(huge_tree=True)
# schema_tree = etree.parse(schema_file)
# schema = etree.XMLSchema(schema_tree)
#
# try:
# xml = parse(fname, parser=parser)
#
# if schema.validate(xml):
# return validate_xml_content(xml)
# except etree.XMLSyntaxError:
# return ["XML Parse error\n" + str(sys.exc_info()[1])]
# except BaseException:
# return ["Unknown Exception during validation\n" +
# str(sys.exc_info()[1])]
#
# # We have errors, return them in string form...
# return error_log_to_strings(schema.error_log)
, which may contain function names, class names, or code. Output only the next line. | xml = etree(args[0]) |
Given the code snippet: <|code_start|>
def run_command(argv):
# pylint: disable=too-many-branches
oparser = OptionParser(usage="usage: %prog show [options] <filename>")
oparser.add_option("--verbose", action="store_true", dest="verbose",
default=False,
help="show detailed project informations")
oparser.add_option("--skip-validation", action="store_true",
dest="skip_validation", default=False,
help="Skip xml schema validation")
(opt, args) = oparser.parse_args(argv)
if not args:
print("No Filename specified")
oparser.print_help()
sys.exit(20)
if len(args) > 1:
print("too many filenames specified")
oparser.print_help()
sys.exit(20)
try:
if not opt.skip_validation:
<|code_end|>
, generate the next line using the imports in this file:
import sys
from optparse import OptionParser
from elbepack.treeutils import etree
from elbepack.validate import validate_xml
and context (functions, classes, or occasionally code) from other files:
# Path: elbepack/treeutils.py
# class etree(ebase):
# def __init__(self, fname):
# if fname is not None:
# parser = XMLParser(huge_tree=True, remove_comments=False)
# et = parse(fname, parser=parser)
# else:
# et = ElementTree(file=None)
#
# ebase.__init__(self, et)
#
# def write(self, fname, encoding=None):
# # Make sure, that we end with a newline
# self.et.getroot().tail = '\n'
# self.et.write(fname, encoding=encoding)
#
# def tostring(self):
# return self.et.tostring()
#
# def ensure_child(self, tag):
# retval = self.et.find("./" + tag)
# if retval is not None:
# return elem(retval)
# return elem(SubElement(self.et.getroot(), tag))
#
# def set_child_position(self, child, pos):
# root = self.et.getroot()
# root.remove(child.et)
# root.insert(pos, child.et)
#
# def setroot(self, tag):
# retval = elem(Element(tag))
# # pylint: disable=protected-access
# self.et._setroot(retval.et)
# return retval
#
# @property
# def root(self):
# return elem(self.et.getroot())
#
# Path: elbepack/validate.py
# def validate_xml(fname):
# if os.path.getsize(fname) > (1 << 30):
# return ["%s is greater than 1 GiB. "
# "Elbe does not support files of this size." % fname]
#
# schema_file = "https://www.linutronix.de/projects/Elbe/dbsfed.xsd"
# parser = XMLParser(huge_tree=True)
# schema_tree = etree.parse(schema_file)
# schema = etree.XMLSchema(schema_tree)
#
# try:
# xml = parse(fname, parser=parser)
#
# if schema.validate(xml):
# return validate_xml_content(xml)
# except etree.XMLSyntaxError:
# return ["XML Parse error\n" + str(sys.exc_info()[1])]
# except BaseException:
# return ["Unknown Exception during validation\n" +
# str(sys.exc_info()[1])]
#
# # We have errors, return them in string form...
# return error_log_to_strings(schema.error_log)
. Output only the next line. | validation = validate_xml(args[0]) |
Given the code snippet: <|code_start|>
oparser.add_option("--cpuset", default=-1, type="int",
help="Limit cpuset of pbuilder commands (bitmask) "
"(defaults to -1 for all CPUs)")
oparser.add_option("--profile", dest="profile", default="",
help="profile that shall be built")
oparser.add_option("--cross", dest="cross", default=False,
action="store_true",
help="Creates an environment for crossbuilding if "
"combined with create. Combined with build it"
" will use this environment.")
oparser.add_option("--no-ccache", dest="noccache", default=False,
action="store_true",
help="Deactivates the compiler cache 'ccache'")
oparser.add_option("--ccache-size", dest="ccachesize", default="10G",
action="store", type="string",
help="set a limit for the compiler cache size "
"(should be a number followed by an optional "
"suffix: k, M, G, T. Use 0 for no limit.)")
PreprocessWrapper.add_options(oparser)
(opt, args) = oparser.parse_args(argv)
if not args:
print("elbe pbuilder - no subcommand given", file=sys.stderr)
<|code_end|>
, generate the next line using the imports in this file:
import sys
from optparse import OptionParser
from elbepack.pbuilderaction import PBuilderAction, PBuilderError
from elbepack.xmlpreprocess import PreprocessWrapper
and context (functions, classes, or occasionally code) from other files:
# Path: elbepack/pbuilderaction.py
# class PBuilderAction:
# actiondict = {}
#
# @classmethod
# def register(cls, action):
# cls.actiondict[action.tag] = action
#
# @classmethod
# def print_actions(cls):
# print("available subcommands are:", file=sys.stderr)
# for a in cls.actiondict:
# print(" %s" % a, file=sys.stderr)
#
# def __new__(cls, node):
# action = cls.actiondict[node]
# return object.__new__(action)
#
# def __init__(self, node):
# self.node = node
#
# def execute(self, _opt, _args):
# raise NotImplementedError('execute() not implemented')
#
# class PBuilderError(Exception):
# def __init__(self, msg):
# Exception.__init__(self, msg)
#
# Path: elbepack/xmlpreprocess.py
# class PreprocessWrapper:
# def __init__(self, xmlfile, opt):
# self.xmlfile = xmlfile
# self.outxml = None
# self.options = ""
#
# if opt.variant:
# self.options += ' --variants "%s"' % opt.variant
#
# def __enter__(self):
# self.outxml = NamedTemporaryFile(prefix='elbe', suffix='xml')
#
# cmd = '%s preprocess %s -o %s %s' % (elbe_exe,
# self.options,
# self.outxml.name,
# self.xmlfile)
# ret, _, err = command_out_stderr(cmd)
# if ret != 0:
# print("elbe preprocess failed.", file=sys.stderr)
# print(err, file=sys.stderr)
# raise CommandError(cmd, ret)
#
# return self
#
# def __exit__(self, _typ, _value, _traceback):
# self.outxml = None
#
# @staticmethod
# def add_options(oparser):
# # import it here because of cyclic imports
# # pylint: disable=cyclic-import
# from elbepack.commands.preprocess import add_pass_through_options
#
# group = OptionGroup(oparser,
# 'Elbe preprocess options',
# 'Options passed through to invocation of '
# '"elbe preprocess"')
# add_pass_through_options(group)
# oparser.add_option_group(group)
#
# @property
# def preproc(self):
# return self.outxml.name
. Output only the next line. | PBuilderAction.print_actions() |
Predict the next line after this snippet: <|code_start|> " will use this environment.")
oparser.add_option("--no-ccache", dest="noccache", default=False,
action="store_true",
help="Deactivates the compiler cache 'ccache'")
oparser.add_option("--ccache-size", dest="ccachesize", default="10G",
action="store", type="string",
help="set a limit for the compiler cache size "
"(should be a number followed by an optional "
"suffix: k, M, G, T. Use 0 for no limit.)")
PreprocessWrapper.add_options(oparser)
(opt, args) = oparser.parse_args(argv)
if not args:
print("elbe pbuilder - no subcommand given", file=sys.stderr)
PBuilderAction.print_actions()
return
try:
action = PBuilderAction(args[0])
except KeyError:
print("elbe pbuilder - unknown subcommand", file=sys.stderr)
PBuilderAction.print_actions()
sys.exit(20)
try:
action.execute(opt, args[1:])
<|code_end|>
using the current file's imports:
import sys
from optparse import OptionParser
from elbepack.pbuilderaction import PBuilderAction, PBuilderError
from elbepack.xmlpreprocess import PreprocessWrapper
and any relevant context from other files:
# Path: elbepack/pbuilderaction.py
# class PBuilderAction:
# actiondict = {}
#
# @classmethod
# def register(cls, action):
# cls.actiondict[action.tag] = action
#
# @classmethod
# def print_actions(cls):
# print("available subcommands are:", file=sys.stderr)
# for a in cls.actiondict:
# print(" %s" % a, file=sys.stderr)
#
# def __new__(cls, node):
# action = cls.actiondict[node]
# return object.__new__(action)
#
# def __init__(self, node):
# self.node = node
#
# def execute(self, _opt, _args):
# raise NotImplementedError('execute() not implemented')
#
# class PBuilderError(Exception):
# def __init__(self, msg):
# Exception.__init__(self, msg)
#
# Path: elbepack/xmlpreprocess.py
# class PreprocessWrapper:
# def __init__(self, xmlfile, opt):
# self.xmlfile = xmlfile
# self.outxml = None
# self.options = ""
#
# if opt.variant:
# self.options += ' --variants "%s"' % opt.variant
#
# def __enter__(self):
# self.outxml = NamedTemporaryFile(prefix='elbe', suffix='xml')
#
# cmd = '%s preprocess %s -o %s %s' % (elbe_exe,
# self.options,
# self.outxml.name,
# self.xmlfile)
# ret, _, err = command_out_stderr(cmd)
# if ret != 0:
# print("elbe preprocess failed.", file=sys.stderr)
# print(err, file=sys.stderr)
# raise CommandError(cmd, ret)
#
# return self
#
# def __exit__(self, _typ, _value, _traceback):
# self.outxml = None
#
# @staticmethod
# def add_options(oparser):
# # import it here because of cyclic imports
# # pylint: disable=cyclic-import
# from elbepack.commands.preprocess import add_pass_through_options
#
# group = OptionGroup(oparser,
# 'Elbe preprocess options',
# 'Options passed through to invocation of '
# '"elbe preprocess"')
# add_pass_through_options(group)
# oparser.add_option_group(group)
#
# @property
# def preproc(self):
# return self.outxml.name
. Output only the next line. | except PBuilderError as e: |
Given snippet: <|code_start|> default=[],
action="append",
help="upload orig file")
oparser.add_option("--output", dest="outdir", default=None,
help="directory where to save downloaded Files")
oparser.add_option("--cpuset", default=-1, type="int",
help="Limit cpuset of pbuilder commands (bitmask) "
"(defaults to -1 for all CPUs)")
oparser.add_option("--profile", dest="profile", default="",
help="profile that shall be built")
oparser.add_option("--cross", dest="cross", default=False,
action="store_true",
help="Creates an environment for crossbuilding if "
"combined with create. Combined with build it"
" will use this environment.")
oparser.add_option("--no-ccache", dest="noccache", default=False,
action="store_true",
help="Deactivates the compiler cache 'ccache'")
oparser.add_option("--ccache-size", dest="ccachesize", default="10G",
action="store", type="string",
help="set a limit for the compiler cache size "
"(should be a number followed by an optional "
"suffix: k, M, G, T. Use 0 for no limit.)")
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sys
from optparse import OptionParser
from elbepack.pbuilderaction import PBuilderAction, PBuilderError
from elbepack.xmlpreprocess import PreprocessWrapper
and context:
# Path: elbepack/pbuilderaction.py
# class PBuilderAction:
# actiondict = {}
#
# @classmethod
# def register(cls, action):
# cls.actiondict[action.tag] = action
#
# @classmethod
# def print_actions(cls):
# print("available subcommands are:", file=sys.stderr)
# for a in cls.actiondict:
# print(" %s" % a, file=sys.stderr)
#
# def __new__(cls, node):
# action = cls.actiondict[node]
# return object.__new__(action)
#
# def __init__(self, node):
# self.node = node
#
# def execute(self, _opt, _args):
# raise NotImplementedError('execute() not implemented')
#
# class PBuilderError(Exception):
# def __init__(self, msg):
# Exception.__init__(self, msg)
#
# Path: elbepack/xmlpreprocess.py
# class PreprocessWrapper:
# def __init__(self, xmlfile, opt):
# self.xmlfile = xmlfile
# self.outxml = None
# self.options = ""
#
# if opt.variant:
# self.options += ' --variants "%s"' % opt.variant
#
# def __enter__(self):
# self.outxml = NamedTemporaryFile(prefix='elbe', suffix='xml')
#
# cmd = '%s preprocess %s -o %s %s' % (elbe_exe,
# self.options,
# self.outxml.name,
# self.xmlfile)
# ret, _, err = command_out_stderr(cmd)
# if ret != 0:
# print("elbe preprocess failed.", file=sys.stderr)
# print(err, file=sys.stderr)
# raise CommandError(cmd, ret)
#
# return self
#
# def __exit__(self, _typ, _value, _traceback):
# self.outxml = None
#
# @staticmethod
# def add_options(oparser):
# # import it here because of cyclic imports
# # pylint: disable=cyclic-import
# from elbepack.commands.preprocess import add_pass_through_options
#
# group = OptionGroup(oparser,
# 'Elbe preprocess options',
# 'Options passed through to invocation of '
# '"elbe preprocess"')
# add_pass_through_options(group)
# oparser.add_option_group(group)
#
# @property
# def preproc(self):
# return self.outxml.name
which might include code, classes, or functions. Output only the next line. | PreprocessWrapper.add_options(oparser) |
Here is a snippet: <|code_start|> "sdkgccpkg": "g++-powerpc-linux-gnu",
"elfcode": "PowerPC or cisco 4500",
}
ppcspe_defaults = {
"arch": "powerpcspe",
"interpreter": "qemu-system-ppc",
"interpreterversion": "0.0.0",
"userinterpr": "qemu-ppc-static",
"console": "ttyS0,115200n1",
"machine": "mpc8544ds",
"nicmodel": "rtl8139",
"triplet": "powerpc-linux-gnuspe",
}
ppc64el_defaults = {
"arch": "ppc64el",
"interpreter": "qemu-system-ppc64",
"interpreterversion": "0.0.0",
"userinterpr": "qemu-ppc64le-static",
"console": "ttyS0,115200n1",
"machine": "none",
"nicmodel": "virtio",
"triplet": "powerpc64le-linux-gnu",
"sdkgccpkg": "g++-powerpc64le-linux-gnu",
"elfcode": "64-bit PowerPC or cisco 7500",
}
amd64_defaults = {
"arch": "amd64",
<|code_end|>
. Write the next line using the current file imports:
import random
from elbepack.kvm import find_kvm_exe
and context from other files:
# Path: elbepack/kvm.py
# def find_kvm_exe():
#
# # pylint: disable=global-statement
# global cached_kvm_infos
#
# if cached_kvm_infos:
# return cached_kvm_infos
#
# version = "0.0.0"
# args = []
#
# for fname in kvm_exe_list:
#
# if os.path.isfile(fname) and os.access(fname, os.X_OK):
# # determine kvm version
# _, stdout = command_out(fname + ' --version')
# for line in stdout.splitlines():
# if "version" in line:
# version = line.split()[3].split('(')[0].strip()
#
# if fname == "/usr/bin/qemu-system-x86_64":
# args.append("-enable-kvm")
#
# cached_kvm_infos = {
# "exec_name": fname,
# "version": version,
# "args":args
# }
#
# return cached_kvm_infos
#
# return {
# "exec_name": "kvm_executable_not_found",
# "version": version,
# "args": args
# }
, which may include functions, classes, or code. Output only the next line. | "interpreter": find_kvm_exe()["exec_name"], |
Given the following code snippet before the placeholder: <|code_start|> xml = combinearchivedir(xml)
preprocess_mirror_replacement(xml)
preprocess_proxy_add(xml, proxy)
# Change public PGP url key to raw key
preprocess_pgp_key(xml)
# Replace old debootstrapvariant with debootstrap
preprocess_bootstrap(xml)
preprocess_iso_option(xml)
preprocess_initvm_ports(xml)
preprocess_mirrors(xml)
if schema.validate(xml):
# if validation succedes write xml file
xml.write(
output,
encoding="UTF-8",
pretty_print=True,
compression=9)
# the rest of the code is exception and error handling
return
except etree.XMLSyntaxError:
raise XMLPreprocessError("XML Parse error\n" + str(sys.exc_info()[1]))
<|code_end|>
, predict the next line using imports from the current file:
import os
import re
import sys
from tempfile import NamedTemporaryFile
from optparse import OptionGroup
from itertools import islice
from urllib.error import HTTPError,URLError
from urllib.request import urlopen
from lxml import etree
from lxml.etree import XMLParser, parse, Element
from elbepack.archivedir import ArchivedirError, combinearchivedir
from elbepack.config import cfg
from elbepack.directories import elbe_exe
from elbepack.shellhelper import command_out_stderr, CommandError
from elbepack.isooptions import iso_option_valid
from elbepack.validate import error_log_to_strings
from elbepack.commands.preprocess import add_pass_through_options
and context including class names, function names, and sometimes code from other files:
# Path: elbepack/archivedir.py
# class ArchivedirError(Exception):
# pass
#
# def combinearchivedir(xml):
# if xml.find("//archivedir") is None:
# return xml
#
# _combinearchivedir(xml, "archivedir", False)
# _combinearchivedir(xml, "src-cdrom/archivedir", True)
#
# return xml
#
# Path: elbepack/config.py
# class Config(dict):
# def __init__(self):
#
# Path: elbepack/directories.py
# def init_directories(elbe_relpath):
# def get_cmdlist():
#
# Path: elbepack/shellhelper.py
# def command_out_stderr(cmd, stdin=None, env_add=None):
# """command_out_stderr() - Execute cmd in a shell.
#
# Returns a tuple of the exitcode, stdout and stderr of cmd.
#
# --
#
# >>> command_out_stderr("$TRUE && cat -", stdin=b"ELBE", env_add={"TRUE":"true"})
# (0, 'ELBE', '')
#
# >>> command_out_stderr("1>&2 cat - && false", stdin=b"ELBE")
# (1, '', 'ELBE')
#
# >>> command_out_stderr("1>&2 cat - && false", stdin="ELBE")
# (1, '', 'ELBE')
#
# >>> command_out_stderr("true")
# (0, '', '')
#
# """
# new_env = os.environ.copy()
# if env_add:
# new_env.update(env_add)
#
# if isinstance(stdin, str):
# stdin = stdin.encode()
#
# if stdin is None:
# p = Popen(cmd, shell=True,
# stdout=PIPE, stderr=PIPE, env=new_env)
# output, stderr = p.communicate()
# else:
# p = Popen(cmd, shell=True,
# stdout=PIPE, stderr=PIPE, stdin=PIPE, env=new_env)
# output, stderr = p.communicate(input=stdin)
#
# output = TextIOWrapper(BytesIO(output), encoding='utf-8', errors='replace').read()
# stderr = TextIOWrapper(BytesIO(stderr), encoding='utf-8', errors='replace').read()
#
# return p.returncode, output, stderr
#
# class CommandError(Exception):
#
# def __init__(self, cmd, returncode):
# super(CommandError, self).__init__(cmd, returncode)
# self.returncode = returncode
# self.cmd = cmd
#
# def __str__(self):
# return "Error: %d returned from Command %s" % (
# self.returncode, self.cmd)
#
# Path: elbepack/isooptions.py
# def iso_option_valid(opt_name, text):
# if opt_name not in iso_options:
# return False
# str_type = encoding[iso_options[opt_name][3]]
# if len(text) > iso_options[opt_name][1]:
# return len(text) - iso_options[opt_name][1]
# for c in text:
# if c not in str_type:
# return c
# return True
#
# Path: elbepack/validate.py
# def error_log_to_strings(error_log):
# errors = []
# uses_xinclude = False
# uses_norecommend = False
#
# for err in error_log:
# errors.append("%s:%d error %s" % (err.filename, err.line, err.message))
# if "http://www.w3.org/2003/XInclude" in err.message:
# uses_xinclude = True
# if "norecommend" in err.message:
# uses_norecommend = True
#
# if uses_xinclude:
# errors.append("\nThere are XIncludes in the XML file. "
# "Run 'elbe preprocess' first!\n")
# if uses_norecommend:
# errors.append("\nThe XML file uses <norecommend />. "
# "This function was broken all the time and did the "
# "opposite. If you want to retain the original "
# "behaviour, please specify <install-recommends /> !\n")
# return errors
. Output only the next line. | except ArchivedirError: |
Next line prediction: <|code_start|> tag.attrib.pop('variant')
else:
# tag has a variant attribute but the variant was not
# specified: remove the tag delayed
rmlist.append(tag)
for tag in rmlist:
tag.getparent().remove(tag)
# if there are multiple sections because of sth like '<finetuning
# variant='A'> ... and <finetuning variant='B'> and running preprocess
# with --variant=A,B the two sections need to be merged
#
# Use xpath expressions to identify mergeable sections.
for mergepath in mergepaths:
mergenodes = xml.xpath(mergepath)
# if there is just one section of a type
# or no section, nothing needs to be done
if len(mergenodes) < 2:
continue
# append all childrens of section[1..n] to section[0] and delete
# section[1..n]
for section in mergenodes[1:]:
for c in section.getchildren():
mergenodes[0].append(c)
section.getparent().remove(section)
# handle archivedir elements
<|code_end|>
. Use current file imports:
(import os
import re
import sys
from tempfile import NamedTemporaryFile
from optparse import OptionGroup
from itertools import islice
from urllib.error import HTTPError,URLError
from urllib.request import urlopen
from lxml import etree
from lxml.etree import XMLParser, parse, Element
from elbepack.archivedir import ArchivedirError, combinearchivedir
from elbepack.config import cfg
from elbepack.directories import elbe_exe
from elbepack.shellhelper import command_out_stderr, CommandError
from elbepack.isooptions import iso_option_valid
from elbepack.validate import error_log_to_strings
from elbepack.commands.preprocess import add_pass_through_options)
and context including class names, function names, or small code snippets from other files:
# Path: elbepack/archivedir.py
# class ArchivedirError(Exception):
# pass
#
# def combinearchivedir(xml):
# if xml.find("//archivedir") is None:
# return xml
#
# _combinearchivedir(xml, "archivedir", False)
# _combinearchivedir(xml, "src-cdrom/archivedir", True)
#
# return xml
#
# Path: elbepack/config.py
# class Config(dict):
# def __init__(self):
#
# Path: elbepack/directories.py
# def init_directories(elbe_relpath):
# def get_cmdlist():
#
# Path: elbepack/shellhelper.py
# def command_out_stderr(cmd, stdin=None, env_add=None):
# """command_out_stderr() - Execute cmd in a shell.
#
# Returns a tuple of the exitcode, stdout and stderr of cmd.
#
# --
#
# >>> command_out_stderr("$TRUE && cat -", stdin=b"ELBE", env_add={"TRUE":"true"})
# (0, 'ELBE', '')
#
# >>> command_out_stderr("1>&2 cat - && false", stdin=b"ELBE")
# (1, '', 'ELBE')
#
# >>> command_out_stderr("1>&2 cat - && false", stdin="ELBE")
# (1, '', 'ELBE')
#
# >>> command_out_stderr("true")
# (0, '', '')
#
# """
# new_env = os.environ.copy()
# if env_add:
# new_env.update(env_add)
#
# if isinstance(stdin, str):
# stdin = stdin.encode()
#
# if stdin is None:
# p = Popen(cmd, shell=True,
# stdout=PIPE, stderr=PIPE, env=new_env)
# output, stderr = p.communicate()
# else:
# p = Popen(cmd, shell=True,
# stdout=PIPE, stderr=PIPE, stdin=PIPE, env=new_env)
# output, stderr = p.communicate(input=stdin)
#
# output = TextIOWrapper(BytesIO(output), encoding='utf-8', errors='replace').read()
# stderr = TextIOWrapper(BytesIO(stderr), encoding='utf-8', errors='replace').read()
#
# return p.returncode, output, stderr
#
# class CommandError(Exception):
#
# def __init__(self, cmd, returncode):
# super(CommandError, self).__init__(cmd, returncode)
# self.returncode = returncode
# self.cmd = cmd
#
# def __str__(self):
# return "Error: %d returned from Command %s" % (
# self.returncode, self.cmd)
#
# Path: elbepack/isooptions.py
# def iso_option_valid(opt_name, text):
# if opt_name not in iso_options:
# return False
# str_type = encoding[iso_options[opt_name][3]]
# if len(text) > iso_options[opt_name][1]:
# return len(text) - iso_options[opt_name][1]
# for c in text:
# if c not in str_type:
# return c
# return True
#
# Path: elbepack/validate.py
# def error_log_to_strings(error_log):
# errors = []
# uses_xinclude = False
# uses_norecommend = False
#
# for err in error_log:
# errors.append("%s:%d error %s" % (err.filename, err.line, err.message))
# if "http://www.w3.org/2003/XInclude" in err.message:
# uses_xinclude = True
# if "norecommend" in err.message:
# uses_norecommend = True
#
# if uses_xinclude:
# errors.append("\nThere are XIncludes in the XML file. "
# "Run 'elbe preprocess' first!\n")
# if uses_norecommend:
# errors.append("\nThe XML file uses <norecommend />. "
# "This function was broken all the time and did the "
# "opposite. If you want to retain the original "
# "behaviour, please specify <install-recommends /> !\n")
# return errors
. Output only the next line. | xml = combinearchivedir(xml) |
Given snippet: <|code_start|> valid = iso_option_valid(opt.tag, opt.text)
if valid is True:
continue
tag = '<%s>%s</%s>' % (opt.tag, opt.text, opt.tag)
if valid is False:
violation = "Invalid ISO option %s" % tag
elif isinstance(valid, int):
violation = ("Option %s will be truncated by %d characters" %
(tag, valid))
elif isinstance(valid, str):
violation = ("Character '%c' (%d) in ISO option %s "
"violated ISO-9660" %
(valid, ord(valid[0]), tag))
if strict:
raise XMLPreprocessError(violation)
print("[WARN] %s" % violation)
def preprocess_initvm_ports(xml):
"Filters out the default port forwardings to prevent qemu conflict"
for forward in xml.iterfind('initvm/portforwarding/forward'):
prot = forward.find('proto')
benv = forward.find('buildenv')
host = forward.find('host')
if prot is None or benv is None or host is None:
continue
if prot.text == 'tcp' and (
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import re
import sys
from tempfile import NamedTemporaryFile
from optparse import OptionGroup
from itertools import islice
from urllib.error import HTTPError,URLError
from urllib.request import urlopen
from lxml import etree
from lxml.etree import XMLParser, parse, Element
from elbepack.archivedir import ArchivedirError, combinearchivedir
from elbepack.config import cfg
from elbepack.directories import elbe_exe
from elbepack.shellhelper import command_out_stderr, CommandError
from elbepack.isooptions import iso_option_valid
from elbepack.validate import error_log_to_strings
from elbepack.commands.preprocess import add_pass_through_options
and context:
# Path: elbepack/archivedir.py
# class ArchivedirError(Exception):
# pass
#
# def combinearchivedir(xml):
# if xml.find("//archivedir") is None:
# return xml
#
# _combinearchivedir(xml, "archivedir", False)
# _combinearchivedir(xml, "src-cdrom/archivedir", True)
#
# return xml
#
# Path: elbepack/config.py
# class Config(dict):
# def __init__(self):
#
# Path: elbepack/directories.py
# def init_directories(elbe_relpath):
# def get_cmdlist():
#
# Path: elbepack/shellhelper.py
# def command_out_stderr(cmd, stdin=None, env_add=None):
# """command_out_stderr() - Execute cmd in a shell.
#
# Returns a tuple of the exitcode, stdout and stderr of cmd.
#
# --
#
# >>> command_out_stderr("$TRUE && cat -", stdin=b"ELBE", env_add={"TRUE":"true"})
# (0, 'ELBE', '')
#
# >>> command_out_stderr("1>&2 cat - && false", stdin=b"ELBE")
# (1, '', 'ELBE')
#
# >>> command_out_stderr("1>&2 cat - && false", stdin="ELBE")
# (1, '', 'ELBE')
#
# >>> command_out_stderr("true")
# (0, '', '')
#
# """
# new_env = os.environ.copy()
# if env_add:
# new_env.update(env_add)
#
# if isinstance(stdin, str):
# stdin = stdin.encode()
#
# if stdin is None:
# p = Popen(cmd, shell=True,
# stdout=PIPE, stderr=PIPE, env=new_env)
# output, stderr = p.communicate()
# else:
# p = Popen(cmd, shell=True,
# stdout=PIPE, stderr=PIPE, stdin=PIPE, env=new_env)
# output, stderr = p.communicate(input=stdin)
#
# output = TextIOWrapper(BytesIO(output), encoding='utf-8', errors='replace').read()
# stderr = TextIOWrapper(BytesIO(stderr), encoding='utf-8', errors='replace').read()
#
# return p.returncode, output, stderr
#
# class CommandError(Exception):
#
# def __init__(self, cmd, returncode):
# super(CommandError, self).__init__(cmd, returncode)
# self.returncode = returncode
# self.cmd = cmd
#
# def __str__(self):
# return "Error: %d returned from Command %s" % (
# self.returncode, self.cmd)
#
# Path: elbepack/isooptions.py
# def iso_option_valid(opt_name, text):
# if opt_name not in iso_options:
# return False
# str_type = encoding[iso_options[opt_name][3]]
# if len(text) > iso_options[opt_name][1]:
# return len(text) - iso_options[opt_name][1]
# for c in text:
# if c not in str_type:
# return c
# return True
#
# Path: elbepack/validate.py
# def error_log_to_strings(error_log):
# errors = []
# uses_xinclude = False
# uses_norecommend = False
#
# for err in error_log:
# errors.append("%s:%d error %s" % (err.filename, err.line, err.message))
# if "http://www.w3.org/2003/XInclude" in err.message:
# uses_xinclude = True
# if "norecommend" in err.message:
# uses_norecommend = True
#
# if uses_xinclude:
# errors.append("\nThere are XIncludes in the XML file. "
# "Run 'elbe preprocess' first!\n")
# if uses_norecommend:
# errors.append("\nThe XML file uses <norecommend />. "
# "This function was broken all the time and did the "
# "opposite. If you want to retain the original "
# "behaviour, please specify <install-recommends /> !\n")
# return errors
which might include code, classes, or functions. Output only the next line. | host.text == cfg['sshport'] and benv.text == '22' or |
Given snippet: <|code_start|> pretty_print=True,
compression=9)
# the rest of the code is exception and error handling
return
except etree.XMLSyntaxError:
raise XMLPreprocessError("XML Parse error\n" + str(sys.exc_info()[1]))
except ArchivedirError:
raise XMLPreprocessError("<archivedir> handling failed\n" +
str(sys.exc_info()[1]))
except BaseException:
raise XMLPreprocessError(
"Unknown Exception during validation\n" + str(sys.exc_info()[1]))
# We have errors, return them in string form...
raise XMLPreprocessError("\n".join(error_log_to_strings(schema.error_log)))
class PreprocessWrapper:
def __init__(self, xmlfile, opt):
self.xmlfile = xmlfile
self.outxml = None
self.options = ""
if opt.variant:
self.options += ' --variants "%s"' % opt.variant
def __enter__(self):
self.outxml = NamedTemporaryFile(prefix='elbe', suffix='xml')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import re
import sys
from tempfile import NamedTemporaryFile
from optparse import OptionGroup
from itertools import islice
from urllib.error import HTTPError,URLError
from urllib.request import urlopen
from lxml import etree
from lxml.etree import XMLParser, parse, Element
from elbepack.archivedir import ArchivedirError, combinearchivedir
from elbepack.config import cfg
from elbepack.directories import elbe_exe
from elbepack.shellhelper import command_out_stderr, CommandError
from elbepack.isooptions import iso_option_valid
from elbepack.validate import error_log_to_strings
from elbepack.commands.preprocess import add_pass_through_options
and context:
# Path: elbepack/archivedir.py
# class ArchivedirError(Exception):
# pass
#
# def combinearchivedir(xml):
# if xml.find("//archivedir") is None:
# return xml
#
# _combinearchivedir(xml, "archivedir", False)
# _combinearchivedir(xml, "src-cdrom/archivedir", True)
#
# return xml
#
# Path: elbepack/config.py
# class Config(dict):
# def __init__(self):
#
# Path: elbepack/directories.py
# def init_directories(elbe_relpath):
# def get_cmdlist():
#
# Path: elbepack/shellhelper.py
# def command_out_stderr(cmd, stdin=None, env_add=None):
# """command_out_stderr() - Execute cmd in a shell.
#
# Returns a tuple of the exitcode, stdout and stderr of cmd.
#
# --
#
# >>> command_out_stderr("$TRUE && cat -", stdin=b"ELBE", env_add={"TRUE":"true"})
# (0, 'ELBE', '')
#
# >>> command_out_stderr("1>&2 cat - && false", stdin=b"ELBE")
# (1, '', 'ELBE')
#
# >>> command_out_stderr("1>&2 cat - && false", stdin="ELBE")
# (1, '', 'ELBE')
#
# >>> command_out_stderr("true")
# (0, '', '')
#
# """
# new_env = os.environ.copy()
# if env_add:
# new_env.update(env_add)
#
# if isinstance(stdin, str):
# stdin = stdin.encode()
#
# if stdin is None:
# p = Popen(cmd, shell=True,
# stdout=PIPE, stderr=PIPE, env=new_env)
# output, stderr = p.communicate()
# else:
# p = Popen(cmd, shell=True,
# stdout=PIPE, stderr=PIPE, stdin=PIPE, env=new_env)
# output, stderr = p.communicate(input=stdin)
#
# output = TextIOWrapper(BytesIO(output), encoding='utf-8', errors='replace').read()
# stderr = TextIOWrapper(BytesIO(stderr), encoding='utf-8', errors='replace').read()
#
# return p.returncode, output, stderr
#
# class CommandError(Exception):
#
# def __init__(self, cmd, returncode):
# super(CommandError, self).__init__(cmd, returncode)
# self.returncode = returncode
# self.cmd = cmd
#
# def __str__(self):
# return "Error: %d returned from Command %s" % (
# self.returncode, self.cmd)
#
# Path: elbepack/isooptions.py
# def iso_option_valid(opt_name, text):
# if opt_name not in iso_options:
# return False
# str_type = encoding[iso_options[opt_name][3]]
# if len(text) > iso_options[opt_name][1]:
# return len(text) - iso_options[opt_name][1]
# for c in text:
# if c not in str_type:
# return c
# return True
#
# Path: elbepack/validate.py
# def error_log_to_strings(error_log):
# errors = []
# uses_xinclude = False
# uses_norecommend = False
#
# for err in error_log:
# errors.append("%s:%d error %s" % (err.filename, err.line, err.message))
# if "http://www.w3.org/2003/XInclude" in err.message:
# uses_xinclude = True
# if "norecommend" in err.message:
# uses_norecommend = True
#
# if uses_xinclude:
# errors.append("\nThere are XIncludes in the XML file. "
# "Run 'elbe preprocess' first!\n")
# if uses_norecommend:
# errors.append("\nThe XML file uses <norecommend />. "
# "This function was broken all the time and did the "
# "opposite. If you want to retain the original "
# "behaviour, please specify <install-recommends /> !\n")
# return errors
which might include code, classes, or functions. Output only the next line. | cmd = '%s preprocess %s -o %s %s' % (elbe_exe, |
Predict the next line for this snippet: <|code_start|>
except etree.XMLSyntaxError:
raise XMLPreprocessError("XML Parse error\n" + str(sys.exc_info()[1]))
except ArchivedirError:
raise XMLPreprocessError("<archivedir> handling failed\n" +
str(sys.exc_info()[1]))
except BaseException:
raise XMLPreprocessError(
"Unknown Exception during validation\n" + str(sys.exc_info()[1]))
# We have errors, return them in string form...
raise XMLPreprocessError("\n".join(error_log_to_strings(schema.error_log)))
class PreprocessWrapper:
def __init__(self, xmlfile, opt):
self.xmlfile = xmlfile
self.outxml = None
self.options = ""
if opt.variant:
self.options += ' --variants "%s"' % opt.variant
def __enter__(self):
self.outxml = NamedTemporaryFile(prefix='elbe', suffix='xml')
cmd = '%s preprocess %s -o %s %s' % (elbe_exe,
self.options,
self.outxml.name,
self.xmlfile)
<|code_end|>
with the help of current file imports:
import os
import re
import sys
from tempfile import NamedTemporaryFile
from optparse import OptionGroup
from itertools import islice
from urllib.error import HTTPError,URLError
from urllib.request import urlopen
from lxml import etree
from lxml.etree import XMLParser, parse, Element
from elbepack.archivedir import ArchivedirError, combinearchivedir
from elbepack.config import cfg
from elbepack.directories import elbe_exe
from elbepack.shellhelper import command_out_stderr, CommandError
from elbepack.isooptions import iso_option_valid
from elbepack.validate import error_log_to_strings
from elbepack.commands.preprocess import add_pass_through_options
and context from other files:
# Path: elbepack/archivedir.py
# class ArchivedirError(Exception):
# pass
#
# def combinearchivedir(xml):
# if xml.find("//archivedir") is None:
# return xml
#
# _combinearchivedir(xml, "archivedir", False)
# _combinearchivedir(xml, "src-cdrom/archivedir", True)
#
# return xml
#
# Path: elbepack/config.py
# class Config(dict):
# def __init__(self):
#
# Path: elbepack/directories.py
# def init_directories(elbe_relpath):
# def get_cmdlist():
#
# Path: elbepack/shellhelper.py
# def command_out_stderr(cmd, stdin=None, env_add=None):
# """command_out_stderr() - Execute cmd in a shell.
#
# Returns a tuple of the exitcode, stdout and stderr of cmd.
#
# --
#
# >>> command_out_stderr("$TRUE && cat -", stdin=b"ELBE", env_add={"TRUE":"true"})
# (0, 'ELBE', '')
#
# >>> command_out_stderr("1>&2 cat - && false", stdin=b"ELBE")
# (1, '', 'ELBE')
#
# >>> command_out_stderr("1>&2 cat - && false", stdin="ELBE")
# (1, '', 'ELBE')
#
# >>> command_out_stderr("true")
# (0, '', '')
#
# """
# new_env = os.environ.copy()
# if env_add:
# new_env.update(env_add)
#
# if isinstance(stdin, str):
# stdin = stdin.encode()
#
# if stdin is None:
# p = Popen(cmd, shell=True,
# stdout=PIPE, stderr=PIPE, env=new_env)
# output, stderr = p.communicate()
# else:
# p = Popen(cmd, shell=True,
# stdout=PIPE, stderr=PIPE, stdin=PIPE, env=new_env)
# output, stderr = p.communicate(input=stdin)
#
# output = TextIOWrapper(BytesIO(output), encoding='utf-8', errors='replace').read()
# stderr = TextIOWrapper(BytesIO(stderr), encoding='utf-8', errors='replace').read()
#
# return p.returncode, output, stderr
#
# class CommandError(Exception):
#
# def __init__(self, cmd, returncode):
# super(CommandError, self).__init__(cmd, returncode)
# self.returncode = returncode
# self.cmd = cmd
#
# def __str__(self):
# return "Error: %d returned from Command %s" % (
# self.returncode, self.cmd)
#
# Path: elbepack/isooptions.py
# def iso_option_valid(opt_name, text):
# if opt_name not in iso_options:
# return False
# str_type = encoding[iso_options[opt_name][3]]
# if len(text) > iso_options[opt_name][1]:
# return len(text) - iso_options[opt_name][1]
# for c in text:
# if c not in str_type:
# return c
# return True
#
# Path: elbepack/validate.py
# def error_log_to_strings(error_log):
# errors = []
# uses_xinclude = False
# uses_norecommend = False
#
# for err in error_log:
# errors.append("%s:%d error %s" % (err.filename, err.line, err.message))
# if "http://www.w3.org/2003/XInclude" in err.message:
# uses_xinclude = True
# if "norecommend" in err.message:
# uses_norecommend = True
#
# if uses_xinclude:
# errors.append("\nThere are XIncludes in the XML file. "
# "Run 'elbe preprocess' first!\n")
# if uses_norecommend:
# errors.append("\nThe XML file uses <norecommend />. "
# "This function was broken all the time and did the "
# "opposite. If you want to retain the original "
# "behaviour, please specify <install-recommends /> !\n")
# return errors
, which may contain function names, class names, or code. Output only the next line. | ret, _, err = command_out_stderr(cmd) |
Predict the next line for this snippet: <|code_start|> raise XMLPreprocessError("<archivedir> handling failed\n" +
str(sys.exc_info()[1]))
except BaseException:
raise XMLPreprocessError(
"Unknown Exception during validation\n" + str(sys.exc_info()[1]))
# We have errors, return them in string form...
raise XMLPreprocessError("\n".join(error_log_to_strings(schema.error_log)))
class PreprocessWrapper:
def __init__(self, xmlfile, opt):
self.xmlfile = xmlfile
self.outxml = None
self.options = ""
if opt.variant:
self.options += ' --variants "%s"' % opt.variant
def __enter__(self):
self.outxml = NamedTemporaryFile(prefix='elbe', suffix='xml')
cmd = '%s preprocess %s -o %s %s' % (elbe_exe,
self.options,
self.outxml.name,
self.xmlfile)
ret, _, err = command_out_stderr(cmd)
if ret != 0:
print("elbe preprocess failed.", file=sys.stderr)
print(err, file=sys.stderr)
<|code_end|>
with the help of current file imports:
import os
import re
import sys
from tempfile import NamedTemporaryFile
from optparse import OptionGroup
from itertools import islice
from urllib.error import HTTPError,URLError
from urllib.request import urlopen
from lxml import etree
from lxml.etree import XMLParser, parse, Element
from elbepack.archivedir import ArchivedirError, combinearchivedir
from elbepack.config import cfg
from elbepack.directories import elbe_exe
from elbepack.shellhelper import command_out_stderr, CommandError
from elbepack.isooptions import iso_option_valid
from elbepack.validate import error_log_to_strings
from elbepack.commands.preprocess import add_pass_through_options
and context from other files:
# Path: elbepack/archivedir.py
# class ArchivedirError(Exception):
# pass
#
# def combinearchivedir(xml):
# if xml.find("//archivedir") is None:
# return xml
#
# _combinearchivedir(xml, "archivedir", False)
# _combinearchivedir(xml, "src-cdrom/archivedir", True)
#
# return xml
#
# Path: elbepack/config.py
# class Config(dict):
# def __init__(self):
#
# Path: elbepack/directories.py
# def init_directories(elbe_relpath):
# def get_cmdlist():
#
# Path: elbepack/shellhelper.py
# def command_out_stderr(cmd, stdin=None, env_add=None):
# """command_out_stderr() - Execute cmd in a shell.
#
# Returns a tuple of the exitcode, stdout and stderr of cmd.
#
# --
#
# >>> command_out_stderr("$TRUE && cat -", stdin=b"ELBE", env_add={"TRUE":"true"})
# (0, 'ELBE', '')
#
# >>> command_out_stderr("1>&2 cat - && false", stdin=b"ELBE")
# (1, '', 'ELBE')
#
# >>> command_out_stderr("1>&2 cat - && false", stdin="ELBE")
# (1, '', 'ELBE')
#
# >>> command_out_stderr("true")
# (0, '', '')
#
# """
# new_env = os.environ.copy()
# if env_add:
# new_env.update(env_add)
#
# if isinstance(stdin, str):
# stdin = stdin.encode()
#
# if stdin is None:
# p = Popen(cmd, shell=True,
# stdout=PIPE, stderr=PIPE, env=new_env)
# output, stderr = p.communicate()
# else:
# p = Popen(cmd, shell=True,
# stdout=PIPE, stderr=PIPE, stdin=PIPE, env=new_env)
# output, stderr = p.communicate(input=stdin)
#
# output = TextIOWrapper(BytesIO(output), encoding='utf-8', errors='replace').read()
# stderr = TextIOWrapper(BytesIO(stderr), encoding='utf-8', errors='replace').read()
#
# return p.returncode, output, stderr
#
# class CommandError(Exception):
#
# def __init__(self, cmd, returncode):
# super(CommandError, self).__init__(cmd, returncode)
# self.returncode = returncode
# self.cmd = cmd
#
# def __str__(self):
# return "Error: %d returned from Command %s" % (
# self.returncode, self.cmd)
#
# Path: elbepack/isooptions.py
# def iso_option_valid(opt_name, text):
# if opt_name not in iso_options:
# return False
# str_type = encoding[iso_options[opt_name][3]]
# if len(text) > iso_options[opt_name][1]:
# return len(text) - iso_options[opt_name][1]
# for c in text:
# if c not in str_type:
# return c
# return True
#
# Path: elbepack/validate.py
# def error_log_to_strings(error_log):
# errors = []
# uses_xinclude = False
# uses_norecommend = False
#
# for err in error_log:
# errors.append("%s:%d error %s" % (err.filename, err.line, err.message))
# if "http://www.w3.org/2003/XInclude" in err.message:
# uses_xinclude = True
# if "norecommend" in err.message:
# uses_norecommend = True
#
# if uses_xinclude:
# errors.append("\nThere are XIncludes in the XML file. "
# "Run 'elbe preprocess' first!\n")
# if uses_norecommend:
# errors.append("\nThe XML file uses <norecommend />. "
# "This function was broken all the time and did the "
# "opposite. If you want to retain the original "
# "behaviour, please specify <install-recommends /> !\n")
# return errors
, which may contain function names, class names, or code. Output only the next line. | raise CommandError(cmd, ret) |
Here is a snippet: <|code_start|> old_node = xml.find(".//debootstrapvariant")
if old_node is None:
return
print("[WARN] <debootstrapvariant> is deprecated. Use <debootstrap> instead.")
bootstrap = Element("debootstrap")
bootstrap_variant = Element("variant")
bootstrap_variant.text = old_node.text
bootstrap.append(bootstrap_variant)
old_includepkgs = old_node.get("includepkgs")
if old_includepkgs:
bootstrap_include = Element("include")
bootstrap_include.text = old_includepkgs
bootstrap.append(bootstrap_include)
old_node.getparent().replace(old_node, bootstrap)
def preprocess_iso_option(xml):
src_opts = xml.find(".//src-cdrom/src-opts")
if src_opts is None:
return
strict = ("strict" in src_opts.attrib
and src_opts.attrib["strict"] == "true")
for opt in src_opts.iterfind("./*"):
<|code_end|>
. Write the next line using the current file imports:
import os
import re
import sys
from tempfile import NamedTemporaryFile
from optparse import OptionGroup
from itertools import islice
from urllib.error import HTTPError,URLError
from urllib.request import urlopen
from lxml import etree
from lxml.etree import XMLParser, parse, Element
from elbepack.archivedir import ArchivedirError, combinearchivedir
from elbepack.config import cfg
from elbepack.directories import elbe_exe
from elbepack.shellhelper import command_out_stderr, CommandError
from elbepack.isooptions import iso_option_valid
from elbepack.validate import error_log_to_strings
from elbepack.commands.preprocess import add_pass_through_options
and context from other files:
# Path: elbepack/archivedir.py
# class ArchivedirError(Exception):
# pass
#
# def combinearchivedir(xml):
# if xml.find("//archivedir") is None:
# return xml
#
# _combinearchivedir(xml, "archivedir", False)
# _combinearchivedir(xml, "src-cdrom/archivedir", True)
#
# return xml
#
# Path: elbepack/config.py
# class Config(dict):
# def __init__(self):
#
# Path: elbepack/directories.py
# def init_directories(elbe_relpath):
# def get_cmdlist():
#
# Path: elbepack/shellhelper.py
# def command_out_stderr(cmd, stdin=None, env_add=None):
# """command_out_stderr() - Execute cmd in a shell.
#
# Returns a tuple of the exitcode, stdout and stderr of cmd.
#
# --
#
# >>> command_out_stderr("$TRUE && cat -", stdin=b"ELBE", env_add={"TRUE":"true"})
# (0, 'ELBE', '')
#
# >>> command_out_stderr("1>&2 cat - && false", stdin=b"ELBE")
# (1, '', 'ELBE')
#
# >>> command_out_stderr("1>&2 cat - && false", stdin="ELBE")
# (1, '', 'ELBE')
#
# >>> command_out_stderr("true")
# (0, '', '')
#
# """
# new_env = os.environ.copy()
# if env_add:
# new_env.update(env_add)
#
# if isinstance(stdin, str):
# stdin = stdin.encode()
#
# if stdin is None:
# p = Popen(cmd, shell=True,
# stdout=PIPE, stderr=PIPE, env=new_env)
# output, stderr = p.communicate()
# else:
# p = Popen(cmd, shell=True,
# stdout=PIPE, stderr=PIPE, stdin=PIPE, env=new_env)
# output, stderr = p.communicate(input=stdin)
#
# output = TextIOWrapper(BytesIO(output), encoding='utf-8', errors='replace').read()
# stderr = TextIOWrapper(BytesIO(stderr), encoding='utf-8', errors='replace').read()
#
# return p.returncode, output, stderr
#
# class CommandError(Exception):
#
# def __init__(self, cmd, returncode):
# super(CommandError, self).__init__(cmd, returncode)
# self.returncode = returncode
# self.cmd = cmd
#
# def __str__(self):
# return "Error: %d returned from Command %s" % (
# self.returncode, self.cmd)
#
# Path: elbepack/isooptions.py
# def iso_option_valid(opt_name, text):
# if opt_name not in iso_options:
# return False
# str_type = encoding[iso_options[opt_name][3]]
# if len(text) > iso_options[opt_name][1]:
# return len(text) - iso_options[opt_name][1]
# for c in text:
# if c not in str_type:
# return c
# return True
#
# Path: elbepack/validate.py
# def error_log_to_strings(error_log):
# errors = []
# uses_xinclude = False
# uses_norecommend = False
#
# for err in error_log:
# errors.append("%s:%d error %s" % (err.filename, err.line, err.message))
# if "http://www.w3.org/2003/XInclude" in err.message:
# uses_xinclude = True
# if "norecommend" in err.message:
# uses_norecommend = True
#
# if uses_xinclude:
# errors.append("\nThere are XIncludes in the XML file. "
# "Run 'elbe preprocess' first!\n")
# if uses_norecommend:
# errors.append("\nThe XML file uses <norecommend />. "
# "This function was broken all the time and did the "
# "opposite. If you want to retain the original "
# "behaviour, please specify <install-recommends /> !\n")
# return errors
, which may include functions, classes, or code. Output only the next line. | valid = iso_option_valid(opt.tag, opt.text) |
Next line prediction: <|code_start|>
# Replace old debootstrapvariant with debootstrap
preprocess_bootstrap(xml)
preprocess_iso_option(xml)
preprocess_initvm_ports(xml)
preprocess_mirrors(xml)
if schema.validate(xml):
# if validation succedes write xml file
xml.write(
output,
encoding="UTF-8",
pretty_print=True,
compression=9)
# the rest of the code is exception and error handling
return
except etree.XMLSyntaxError:
raise XMLPreprocessError("XML Parse error\n" + str(sys.exc_info()[1]))
except ArchivedirError:
raise XMLPreprocessError("<archivedir> handling failed\n" +
str(sys.exc_info()[1]))
except BaseException:
raise XMLPreprocessError(
"Unknown Exception during validation\n" + str(sys.exc_info()[1]))
# We have errors, return them in string form...
<|code_end|>
. Use current file imports:
(import os
import re
import sys
from tempfile import NamedTemporaryFile
from optparse import OptionGroup
from itertools import islice
from urllib.error import HTTPError,URLError
from urllib.request import urlopen
from lxml import etree
from lxml.etree import XMLParser, parse, Element
from elbepack.archivedir import ArchivedirError, combinearchivedir
from elbepack.config import cfg
from elbepack.directories import elbe_exe
from elbepack.shellhelper import command_out_stderr, CommandError
from elbepack.isooptions import iso_option_valid
from elbepack.validate import error_log_to_strings
from elbepack.commands.preprocess import add_pass_through_options)
and context including class names, function names, or small code snippets from other files:
# Path: elbepack/archivedir.py
# class ArchivedirError(Exception):
# pass
#
# def combinearchivedir(xml):
# if xml.find("//archivedir") is None:
# return xml
#
# _combinearchivedir(xml, "archivedir", False)
# _combinearchivedir(xml, "src-cdrom/archivedir", True)
#
# return xml
#
# Path: elbepack/config.py
# class Config(dict):
# def __init__(self):
#
# Path: elbepack/directories.py
# def init_directories(elbe_relpath):
# def get_cmdlist():
#
# Path: elbepack/shellhelper.py
# def command_out_stderr(cmd, stdin=None, env_add=None):
# """command_out_stderr() - Execute cmd in a shell.
#
# Returns a tuple of the exitcode, stdout and stderr of cmd.
#
# --
#
# >>> command_out_stderr("$TRUE && cat -", stdin=b"ELBE", env_add={"TRUE":"true"})
# (0, 'ELBE', '')
#
# >>> command_out_stderr("1>&2 cat - && false", stdin=b"ELBE")
# (1, '', 'ELBE')
#
# >>> command_out_stderr("1>&2 cat - && false", stdin="ELBE")
# (1, '', 'ELBE')
#
# >>> command_out_stderr("true")
# (0, '', '')
#
# """
# new_env = os.environ.copy()
# if env_add:
# new_env.update(env_add)
#
# if isinstance(stdin, str):
# stdin = stdin.encode()
#
# if stdin is None:
# p = Popen(cmd, shell=True,
# stdout=PIPE, stderr=PIPE, env=new_env)
# output, stderr = p.communicate()
# else:
# p = Popen(cmd, shell=True,
# stdout=PIPE, stderr=PIPE, stdin=PIPE, env=new_env)
# output, stderr = p.communicate(input=stdin)
#
# output = TextIOWrapper(BytesIO(output), encoding='utf-8', errors='replace').read()
# stderr = TextIOWrapper(BytesIO(stderr), encoding='utf-8', errors='replace').read()
#
# return p.returncode, output, stderr
#
# class CommandError(Exception):
#
# def __init__(self, cmd, returncode):
# super(CommandError, self).__init__(cmd, returncode)
# self.returncode = returncode
# self.cmd = cmd
#
# def __str__(self):
# return "Error: %d returned from Command %s" % (
# self.returncode, self.cmd)
#
# Path: elbepack/isooptions.py
# def iso_option_valid(opt_name, text):
# if opt_name not in iso_options:
# return False
# str_type = encoding[iso_options[opt_name][3]]
# if len(text) > iso_options[opt_name][1]:
# return len(text) - iso_options[opt_name][1]
# for c in text:
# if c not in str_type:
# return c
# return True
#
# Path: elbepack/validate.py
# def error_log_to_strings(error_log):
# errors = []
# uses_xinclude = False
# uses_norecommend = False
#
# for err in error_log:
# errors.append("%s:%d error %s" % (err.filename, err.line, err.message))
# if "http://www.w3.org/2003/XInclude" in err.message:
# uses_xinclude = True
# if "norecommend" in err.message:
# uses_norecommend = True
#
# if uses_xinclude:
# errors.append("\nThere are XIncludes in the XML file. "
# "Run 'elbe preprocess' first!\n")
# if uses_norecommend:
# errors.append("\nThe XML file uses <norecommend />. "
# "This function was broken all the time and did the "
# "opposite. If you want to retain the original "
# "behaviour, please specify <install-recommends /> !\n")
# return errors
. Output only the next line. | raise XMLPreprocessError("\n".join(error_log_to_strings(schema.error_log))) |
Given the following code snippet before the placeholder: <|code_start|> with open(fname, "rb") as f:
buf = f.read(65536)
while buf:
m.update(buf)
buf = f.read(65536)
if m.hexdigest() != expected_hash:
raise HashValidationFailed(
'file "%s" failed to verify ! got: "%s" expected: "%s"' %
(fname, m.hexdigest(), expected_hash))
class HashValidator:
def __init__(self, base_url):
self.hashes = {}
self.base_url = base_url
def insert_fname_hash(self, algo, fname, hash_val):
if algo not in self.hashes:
self.hashes[algo] = {}
self.hashes[algo][fname] = hash_val
def validate_file(self, upstream_fname, local_fname):
if upstream_fname not in self.hashes['SHA256']:
raise HashValidationFailed('Value to expect for "%s" is not known')
validate_sha256(local_fname, self.hashes['SHA256'][upstream_fname])
def download_and_validate_file(self, upstream_fname, local_fname):
url = self.base_url + upstream_fname
try:
<|code_end|>
, predict the next line using imports from the current file:
import hashlib
from elbepack.shellhelper import system, CommandError
and context including class names, function names, and sometimes code from other files:
# Path: elbepack/shellhelper.py
# def system(cmd, allow_fail=False, env_add=None):
# """system() - Execute cmd in a shell.
#
# Throws a CommandError if cmd returns none-zero and allow_fail=False
#
# --
#
# >>> system("true")
#
# >>> system("false", allow_fail=True)
#
# >>> system("$FALSE", env_add={"FALSE":"false"}) # doctest: +ELLIPSIS
# Traceback (most recent call last):
# ...
# elbepack.shellhelper.CommandError: ...
#
# """
# new_env = os.environ.copy()
# if env_add:
# new_env.update(env_add)
#
# ret = call(cmd, shell=True, env=new_env)
#
# if ret != 0:
# if not allow_fail:
# raise CommandError(cmd, ret)
#
# class CommandError(Exception):
#
# def __init__(self, cmd, returncode):
# super(CommandError, self).__init__(cmd, returncode)
# self.returncode = returncode
# self.cmd = cmd
#
# def __str__(self):
# return "Error: %d returned from Command %s" % (
# self.returncode, self.cmd)
. Output only the next line. | system('wget -O "%s" "%s"' % (local_fname, url)) |
Given snippet: <|code_start|> buf = f.read(65536)
while buf:
m.update(buf)
buf = f.read(65536)
if m.hexdigest() != expected_hash:
raise HashValidationFailed(
'file "%s" failed to verify ! got: "%s" expected: "%s"' %
(fname, m.hexdigest(), expected_hash))
class HashValidator:
def __init__(self, base_url):
self.hashes = {}
self.base_url = base_url
def insert_fname_hash(self, algo, fname, hash_val):
if algo not in self.hashes:
self.hashes[algo] = {}
self.hashes[algo][fname] = hash_val
def validate_file(self, upstream_fname, local_fname):
if upstream_fname not in self.hashes['SHA256']:
raise HashValidationFailed('Value to expect for "%s" is not known')
validate_sha256(local_fname, self.hashes['SHA256'][upstream_fname])
def download_and_validate_file(self, upstream_fname, local_fname):
url = self.base_url + upstream_fname
try:
system('wget -O "%s" "%s"' % (local_fname, url))
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import hashlib
from elbepack.shellhelper import system, CommandError
and context:
# Path: elbepack/shellhelper.py
# def system(cmd, allow_fail=False, env_add=None):
# """system() - Execute cmd in a shell.
#
# Throws a CommandError if cmd returns none-zero and allow_fail=False
#
# --
#
# >>> system("true")
#
# >>> system("false", allow_fail=True)
#
# >>> system("$FALSE", env_add={"FALSE":"false"}) # doctest: +ELLIPSIS
# Traceback (most recent call last):
# ...
# elbepack.shellhelper.CommandError: ...
#
# """
# new_env = os.environ.copy()
# if env_add:
# new_env.update(env_add)
#
# ret = call(cmd, shell=True, env=new_env)
#
# if ret != 0:
# if not allow_fail:
# raise CommandError(cmd, ret)
#
# class CommandError(Exception):
#
# def __init__(self, cmd, returncode):
# super(CommandError, self).__init__(cmd, returncode)
# self.returncode = returncode
# self.cmd = cmd
#
# def __str__(self):
# return "Error: %d returned from Command %s" % (
# self.returncode, self.cmd)
which might include code, classes, or functions. Output only the next line. | except CommandError: |
Here is a snippet: <|code_start|> "debianize/panels/base.py",
"debianize/panels/kernel.py",
"debianize/widgets/button.py",
"debianize/widgets/edit.py",
"debianize/widgets/form.py",
"debianize/widgets/grid.py",
"debianize/widgets/radio.py",
# FIXME: This one is an actual bug to be fixed
# 274:30: W0631: Using possibly undefined loop variable 'entry' (undefined-loop-variable)
# 276:26: W0631: Using possibly undefined loop variable 'entry' (undefined-loop-variable)
"hdimg.py",
"initvmaction.py",
"log.py",
"pbuilderaction.py",
"repomanager.py",
"rfs.py",
"rpcaptcache.py",
]}
@staticmethod
def params():
files = system_out("find %s -iname '*.py'" % pack_dir).splitlines()
files.append(elbe_exe)
return files
def test_lint(self):
try:
<|code_end|>
. Write the next line using the current file imports:
import os
from elbepack.commands.test import ElbeTestCase, system, ElbeTestException
from elbepack.shellhelper import system_out
from elbepack.directories import pack_dir, elbe_exe, elbe_dir
and context from other files:
# Path: elbepack/commands/test.py
# class ElbeTestCase(unittest.TestCase):
#
# level = ElbeTestLevel.BASE
#
# def __init__(self, methodName='runTest', param=None):
# self.methodName = methodName
# self.param = param
# self.stdout = None
# super().__init__(methodName)
#
# def __str__(self):
# name = super(ElbeTestCase, self).__str__()
# if self.param:
# return "%s : param=%s" % (name, self.param)
# return name
#
# def parameterize(self, param):
# return self.__class__(methodName=self.methodName, param=param)
#
# def system(cmd, allow_fail=False):
# ret, out = command_out(cmd)
# if ret != 0 and not allow_fail:
# raise ElbeTestException(cmd, ret, out)
#
# class ElbeTestException(Exception):
#
# def __init__(self, cmd, ret, out):
# super().__init__()
# self.cmd = cmd
# self.ret = ret
# self.out = out
#
# def __repr__(self):
# return f"ElbeTestException: \"{self.cmd}\" returns {self.ret}"
#
# def __str__(self):
# return f"ElbeTestException: \"{self.cmd}\" returns {self.ret}"
#
# Path: elbepack/shellhelper.py
# def system_out(cmd, stdin=None, allow_fail=False, env_add=None):
# """system_out() - Wrapper around command_out().
#
# On failure, raises an exception if allow_fail=False, on success,
# returns the output of cmd.
#
# --
#
# >>> system_out("false") # doctest: +ELLIPSIS
# Traceback (most recent call last):
# ...
# elbepack.shellhelper.CommandError: ...
#
# >>> system_out("false", allow_fail=True)
# ''
#
# """
# code, out = command_out(cmd, stdin=stdin, env_add=env_add)
#
# if code != 0:
# if not allow_fail:
# raise CommandError(cmd, code)
#
# return out
#
# Path: elbepack/directories.py
# def init_directories(elbe_relpath):
# def get_cmdlist():
, which may include functions, classes, or code. Output only the next line. | system("pylint3 %s %s" % (' '.join(self.pylint_opts), self.param)) |
Given the code snippet: <|code_start|> "debianize/panels/kernel.py",
"debianize/widgets/button.py",
"debianize/widgets/edit.py",
"debianize/widgets/form.py",
"debianize/widgets/grid.py",
"debianize/widgets/radio.py",
# FIXME: This one is an actual bug to be fixed
# 274:30: W0631: Using possibly undefined loop variable 'entry' (undefined-loop-variable)
# 276:26: W0631: Using possibly undefined loop variable 'entry' (undefined-loop-variable)
"hdimg.py",
"initvmaction.py",
"log.py",
"pbuilderaction.py",
"repomanager.py",
"rfs.py",
"rpcaptcache.py",
]}
@staticmethod
def params():
files = system_out("find %s -iname '*.py'" % pack_dir).splitlines()
files.append(elbe_exe)
return files
def test_lint(self):
try:
system("pylint3 %s %s" % (' '.join(self.pylint_opts), self.param))
<|code_end|>
, generate the next line using the imports in this file:
import os
from elbepack.commands.test import ElbeTestCase, system, ElbeTestException
from elbepack.shellhelper import system_out
from elbepack.directories import pack_dir, elbe_exe, elbe_dir
and context (functions, classes, or occasionally code) from other files:
# Path: elbepack/commands/test.py
# class ElbeTestCase(unittest.TestCase):
#
# level = ElbeTestLevel.BASE
#
# def __init__(self, methodName='runTest', param=None):
# self.methodName = methodName
# self.param = param
# self.stdout = None
# super().__init__(methodName)
#
# def __str__(self):
# name = super(ElbeTestCase, self).__str__()
# if self.param:
# return "%s : param=%s" % (name, self.param)
# return name
#
# def parameterize(self, param):
# return self.__class__(methodName=self.methodName, param=param)
#
# def system(cmd, allow_fail=False):
# ret, out = command_out(cmd)
# if ret != 0 and not allow_fail:
# raise ElbeTestException(cmd, ret, out)
#
# class ElbeTestException(Exception):
#
# def __init__(self, cmd, ret, out):
# super().__init__()
# self.cmd = cmd
# self.ret = ret
# self.out = out
#
# def __repr__(self):
# return f"ElbeTestException: \"{self.cmd}\" returns {self.ret}"
#
# def __str__(self):
# return f"ElbeTestException: \"{self.cmd}\" returns {self.ret}"
#
# Path: elbepack/shellhelper.py
# def system_out(cmd, stdin=None, allow_fail=False, env_add=None):
# """system_out() - Wrapper around command_out().
#
# On failure, raises an exception if allow_fail=False, on success,
# returns the output of cmd.
#
# --
#
# >>> system_out("false") # doctest: +ELLIPSIS
# Traceback (most recent call last):
# ...
# elbepack.shellhelper.CommandError: ...
#
# >>> system_out("false", allow_fail=True)
# ''
#
# """
# code, out = command_out(cmd, stdin=stdin, env_add=env_add)
#
# if code != 0:
# if not allow_fail:
# raise CommandError(cmd, code)
#
# return out
#
# Path: elbepack/directories.py
# def init_directories(elbe_relpath):
# def get_cmdlist():
. Output only the next line. | except ElbeTestException as e: |
Given the following code snippet before the placeholder: <|code_start|> for path
in [
"daemons/soap/esoap.py",
# These are not needed to be fixed since
# debianize is going to be rewritten
"debianize/base/tui.py",
"debianize/panels/base.py",
"debianize/panels/kernel.py",
"debianize/widgets/button.py",
"debianize/widgets/edit.py",
"debianize/widgets/form.py",
"debianize/widgets/grid.py",
"debianize/widgets/radio.py",
# FIXME: This one is an actual bug to be fixed
# 274:30: W0631: Using possibly undefined loop variable 'entry' (undefined-loop-variable)
# 276:26: W0631: Using possibly undefined loop variable 'entry' (undefined-loop-variable)
"hdimg.py",
"initvmaction.py",
"log.py",
"pbuilderaction.py",
"repomanager.py",
"rfs.py",
"rpcaptcache.py",
]}
@staticmethod
def params():
<|code_end|>
, predict the next line using imports from the current file:
import os
from elbepack.commands.test import ElbeTestCase, system, ElbeTestException
from elbepack.shellhelper import system_out
from elbepack.directories import pack_dir, elbe_exe, elbe_dir
and context including class names, function names, and sometimes code from other files:
# Path: elbepack/commands/test.py
# class ElbeTestCase(unittest.TestCase):
#
# level = ElbeTestLevel.BASE
#
# def __init__(self, methodName='runTest', param=None):
# self.methodName = methodName
# self.param = param
# self.stdout = None
# super().__init__(methodName)
#
# def __str__(self):
# name = super(ElbeTestCase, self).__str__()
# if self.param:
# return "%s : param=%s" % (name, self.param)
# return name
#
# def parameterize(self, param):
# return self.__class__(methodName=self.methodName, param=param)
#
# def system(cmd, allow_fail=False):
# ret, out = command_out(cmd)
# if ret != 0 and not allow_fail:
# raise ElbeTestException(cmd, ret, out)
#
# class ElbeTestException(Exception):
#
# def __init__(self, cmd, ret, out):
# super().__init__()
# self.cmd = cmd
# self.ret = ret
# self.out = out
#
# def __repr__(self):
# return f"ElbeTestException: \"{self.cmd}\" returns {self.ret}"
#
# def __str__(self):
# return f"ElbeTestException: \"{self.cmd}\" returns {self.ret}"
#
# Path: elbepack/shellhelper.py
# def system_out(cmd, stdin=None, allow_fail=False, env_add=None):
# """system_out() - Wrapper around command_out().
#
# On failure, raises an exception if allow_fail=False, on success,
# returns the output of cmd.
#
# --
#
# >>> system_out("false") # doctest: +ELLIPSIS
# Traceback (most recent call last):
# ...
# elbepack.shellhelper.CommandError: ...
#
# >>> system_out("false", allow_fail=True)
# ''
#
# """
# code, out = command_out(cmd, stdin=stdin, env_add=env_add)
#
# if code != 0:
# if not allow_fail:
# raise CommandError(cmd, code)
#
# return out
#
# Path: elbepack/directories.py
# def init_directories(elbe_relpath):
# def get_cmdlist():
. Output only the next line. | files = system_out("find %s -iname '*.py'" % pack_dir).splitlines() |
Given the code snippet: <|code_start|># ELBE - Debian Based Embedded Rootfilesystem Builder
# Copyright (c) 2020 Olivier Dion <dion@linutronix.de>
#
# SPDX-License-Identifier: GPL-3.0-or-later
class TestPylint(ElbeTestCase):
pylint_opts = ["--reports=n",
"--score=n",
"--rcfile=%s" % os.path.join(elbe_dir, ".pylintrc"),
"--disable=W0511,R0801"]
<|code_end|>
, generate the next line using the imports in this file:
import os
from elbepack.commands.test import ElbeTestCase, system, ElbeTestException
from elbepack.shellhelper import system_out
from elbepack.directories import pack_dir, elbe_exe, elbe_dir
and context (functions, classes, or occasionally code) from other files:
# Path: elbepack/commands/test.py
# class ElbeTestCase(unittest.TestCase):
#
# level = ElbeTestLevel.BASE
#
# def __init__(self, methodName='runTest', param=None):
# self.methodName = methodName
# self.param = param
# self.stdout = None
# super().__init__(methodName)
#
# def __str__(self):
# name = super(ElbeTestCase, self).__str__()
# if self.param:
# return "%s : param=%s" % (name, self.param)
# return name
#
# def parameterize(self, param):
# return self.__class__(methodName=self.methodName, param=param)
#
# def system(cmd, allow_fail=False):
# ret, out = command_out(cmd)
# if ret != 0 and not allow_fail:
# raise ElbeTestException(cmd, ret, out)
#
# class ElbeTestException(Exception):
#
# def __init__(self, cmd, ret, out):
# super().__init__()
# self.cmd = cmd
# self.ret = ret
# self.out = out
#
# def __repr__(self):
# return f"ElbeTestException: \"{self.cmd}\" returns {self.ret}"
#
# def __str__(self):
# return f"ElbeTestException: \"{self.cmd}\" returns {self.ret}"
#
# Path: elbepack/shellhelper.py
# def system_out(cmd, stdin=None, allow_fail=False, env_add=None):
# """system_out() - Wrapper around command_out().
#
# On failure, raises an exception if allow_fail=False, on success,
# returns the output of cmd.
#
# --
#
# >>> system_out("false") # doctest: +ELLIPSIS
# Traceback (most recent call last):
# ...
# elbepack.shellhelper.CommandError: ...
#
# >>> system_out("false", allow_fail=True)
# ''
#
# """
# code, out = command_out(cmd, stdin=stdin, env_add=env_add)
#
# if code != 0:
# if not allow_fail:
# raise CommandError(cmd, code)
#
# return out
#
# Path: elbepack/directories.py
# def init_directories(elbe_relpath):
# def get_cmdlist():
. Output only the next line. | failure_set = {os.path.join(pack_dir, path) |
Predict the next line after this snippet: <|code_start|> in [
"daemons/soap/esoap.py",
# These are not needed to be fixed since
# debianize is going to be rewritten
"debianize/base/tui.py",
"debianize/panels/base.py",
"debianize/panels/kernel.py",
"debianize/widgets/button.py",
"debianize/widgets/edit.py",
"debianize/widgets/form.py",
"debianize/widgets/grid.py",
"debianize/widgets/radio.py",
# FIXME: This one is an actual bug to be fixed
# 274:30: W0631: Using possibly undefined loop variable 'entry' (undefined-loop-variable)
# 276:26: W0631: Using possibly undefined loop variable 'entry' (undefined-loop-variable)
"hdimg.py",
"initvmaction.py",
"log.py",
"pbuilderaction.py",
"repomanager.py",
"rfs.py",
"rpcaptcache.py",
]}
@staticmethod
def params():
files = system_out("find %s -iname '*.py'" % pack_dir).splitlines()
<|code_end|>
using the current file's imports:
import os
from elbepack.commands.test import ElbeTestCase, system, ElbeTestException
from elbepack.shellhelper import system_out
from elbepack.directories import pack_dir, elbe_exe, elbe_dir
and any relevant context from other files:
# Path: elbepack/commands/test.py
# class ElbeTestCase(unittest.TestCase):
#
# level = ElbeTestLevel.BASE
#
# def __init__(self, methodName='runTest', param=None):
# self.methodName = methodName
# self.param = param
# self.stdout = None
# super().__init__(methodName)
#
# def __str__(self):
# name = super(ElbeTestCase, self).__str__()
# if self.param:
# return "%s : param=%s" % (name, self.param)
# return name
#
# def parameterize(self, param):
# return self.__class__(methodName=self.methodName, param=param)
#
# def system(cmd, allow_fail=False):
# ret, out = command_out(cmd)
# if ret != 0 and not allow_fail:
# raise ElbeTestException(cmd, ret, out)
#
# class ElbeTestException(Exception):
#
# def __init__(self, cmd, ret, out):
# super().__init__()
# self.cmd = cmd
# self.ret = ret
# self.out = out
#
# def __repr__(self):
# return f"ElbeTestException: \"{self.cmd}\" returns {self.ret}"
#
# def __str__(self):
# return f"ElbeTestException: \"{self.cmd}\" returns {self.ret}"
#
# Path: elbepack/shellhelper.py
# def system_out(cmd, stdin=None, allow_fail=False, env_add=None):
# """system_out() - Wrapper around command_out().
#
# On failure, raises an exception if allow_fail=False, on success,
# returns the output of cmd.
#
# --
#
# >>> system_out("false") # doctest: +ELLIPSIS
# Traceback (most recent call last):
# ...
# elbepack.shellhelper.CommandError: ...
#
# >>> system_out("false", allow_fail=True)
# ''
#
# """
# code, out = command_out(cmd, stdin=stdin, env_add=env_add)
#
# if code != 0:
# if not allow_fail:
# raise CommandError(cmd, code)
#
# return out
#
# Path: elbepack/directories.py
# def init_directories(elbe_relpath):
# def get_cmdlist():
. Output only the next line. | files.append(elbe_exe) |
Predict the next line for this snippet: <|code_start|># ELBE - Debian Based Embedded Rootfilesystem Builder
# Copyright (c) 2020 Olivier Dion <dion@linutronix.de>
#
# SPDX-License-Identifier: GPL-3.0-or-later
class TestPylint(ElbeTestCase):
pylint_opts = ["--reports=n",
"--score=n",
<|code_end|>
with the help of current file imports:
import os
from elbepack.commands.test import ElbeTestCase, system, ElbeTestException
from elbepack.shellhelper import system_out
from elbepack.directories import pack_dir, elbe_exe, elbe_dir
and context from other files:
# Path: elbepack/commands/test.py
# class ElbeTestCase(unittest.TestCase):
#
# level = ElbeTestLevel.BASE
#
# def __init__(self, methodName='runTest', param=None):
# self.methodName = methodName
# self.param = param
# self.stdout = None
# super().__init__(methodName)
#
# def __str__(self):
# name = super(ElbeTestCase, self).__str__()
# if self.param:
# return "%s : param=%s" % (name, self.param)
# return name
#
# def parameterize(self, param):
# return self.__class__(methodName=self.methodName, param=param)
#
# def system(cmd, allow_fail=False):
# ret, out = command_out(cmd)
# if ret != 0 and not allow_fail:
# raise ElbeTestException(cmd, ret, out)
#
# class ElbeTestException(Exception):
#
# def __init__(self, cmd, ret, out):
# super().__init__()
# self.cmd = cmd
# self.ret = ret
# self.out = out
#
# def __repr__(self):
# return f"ElbeTestException: \"{self.cmd}\" returns {self.ret}"
#
# def __str__(self):
# return f"ElbeTestException: \"{self.cmd}\" returns {self.ret}"
#
# Path: elbepack/shellhelper.py
# def system_out(cmd, stdin=None, allow_fail=False, env_add=None):
# """system_out() - Wrapper around command_out().
#
# On failure, raises an exception if allow_fail=False, on success,
# returns the output of cmd.
#
# --
#
# >>> system_out("false") # doctest: +ELLIPSIS
# Traceback (most recent call last):
# ...
# elbepack.shellhelper.CommandError: ...
#
# >>> system_out("false", allow_fail=True)
# ''
#
# """
# code, out = command_out(cmd, stdin=stdin, env_add=env_add)
#
# if code != 0:
# if not allow_fail:
# raise CommandError(cmd, code)
#
# return out
#
# Path: elbepack/directories.py
# def init_directories(elbe_relpath):
# def get_cmdlist():
, which may contain function names, class names, or code. Output only the next line. | "--rcfile=%s" % os.path.join(elbe_dir, ".pylintrc"), |
Predict the next line for this snippet: <|code_start|>
def authenticated_uid(func):
""" decorator, which Checks, that the current session is logged in,
and also passes the current uid to the function
Allows for being wrapped in a soapmethod...
Example:
@soapmethod (String, _returns=Array(SoapFile))
@authenticated_uid
def get_files (self, uid, builddir):
"""
# Do not edit this code. Although using *args is tempting here,
# it will not work because Spyne is doing introspection on the
# function's signature. I think it would be possible to do
# something with func.__code__.replace, but this requires deep
# Python's internal knowledges.
# pylint: disable=function-redefined
if func.__code__.co_argcount == 2:
@wraps(func)
def wrapped(self):
s = self.transport.req_env['beaker.session']
try:
uid = s['userid']
except KeyError:
<|code_end|>
with the help of current file imports:
from functools import wraps
from .faults import SoapElbeNotLoggedIn, SoapElbeNotAuthorized
and context from other files:
# Path: elbepack/daemons/soap/faults.py
# class SoapElbeNotLoggedIn(Fault):
# def __init__(self):
# Fault.__init__(
# self,
# faultcode="ElbeNotLoggedIn",
# faultstring="Not authenticated ! "
# "Cant let you perform this command.")
#
# class SoapElbeNotAuthorized(Fault):
# def __init__(self):
# Fault.__init__(
# self,
# faultcode="ElbeNotAuthorized",
# faultstring="Not Authorized ! Cant let you perform this command.")
, which may contain function names, class names, or code. Output only the next line. | raise SoapElbeNotLoggedIn() |
Next line prediction: <|code_start|>
def authenticated_admin(func):
""" decorator, which Checks, that the current session is logged in as an admin
Allows for being wrapped in a soapmethod...
Example:
@soapmethod (String, _returns=Array(SoapFile))
@authenticated_uid
def get_files (self, uid, builddir):
"""
# Do not edit this code. Although using *args is tempting here,
# it will not work because Spyne is doing introspection on the
# function's signature. I think it would be possible to do
# something with func.__code__.replace, but this requires deep
# Python's internal knowledges.
# pylint: disable=function-redefined
if func.__code__.co_argcount == 1:
@wraps(func)
def wrapped(self):
s = self.transport.req_env['beaker.session']
try:
uid = s['userid']
except KeyError:
raise SoapElbeNotLoggedIn()
if not self.app.pm.db.is_admin(uid):
<|code_end|>
. Use current file imports:
(from functools import wraps
from .faults import SoapElbeNotLoggedIn, SoapElbeNotAuthorized)
and context including class names, function names, or small code snippets from other files:
# Path: elbepack/daemons/soap/faults.py
# class SoapElbeNotLoggedIn(Fault):
# def __init__(self):
# Fault.__init__(
# self,
# faultcode="ElbeNotLoggedIn",
# faultstring="Not authenticated ! "
# "Cant let you perform this command.")
#
# class SoapElbeNotAuthorized(Fault):
# def __init__(self):
# Fault.__init__(
# self,
# faultcode="ElbeNotAuthorized",
# faultstring="Not Authorized ! Cant let you perform this command.")
. Output only the next line. | raise SoapElbeNotAuthorized() |
Given the code snippet: <|code_start|> action="store_true",
help="Deactivates the compiler cache 'ccache'")
oparser.add_option("--ccache-size", dest="ccachesize", default="10G",
action="store", type="string",
help="set a limit for the compiler cache size "
"(should be a number followed by an optional "
"suffix: k, M, G, T. Use 0 for no limit.)")
devel = OptionGroup(
oparser,
"options for elbe developers",
"Caution: Don't use these options in a productive environment")
devel.add_option("--skip-urlcheck", action="store_true",
dest="url_validation", default=ValidationMode.CHECK_ALL,
help="Skip URL Check inside initvm")
devel.add_option("--debug", action="store_true",
dest="debug", default=False,
help="Enable debug mode.")
devel.add_option("--ignore-version-diff", action="store_true",
dest="ignore_version", default=False,
help="allow different elbe version on host and initvm")
oparser.add_option_group(devel)
(opt, args) = oparser.parse_args(argv)
if not args:
print("elbe control - no subcommand given", file=sys.stderr)
<|code_end|>
, generate the next line using the imports in this file:
import socket
import sys
from http.client import BadStatusLine
from optparse import (OptionParser, OptionGroup)
from urllib.error import URLError
from suds import WebFault
from elbepack.soapclient import ClientAction, ElbeSoapClient
from elbepack.version import elbe_version
from elbepack.config import cfg
from elbepack.elbexml import ValidationMode
and context (functions, classes, or occasionally code) from other files:
# Path: elbepack/soapclient.py
# class ClientAction:
# actiondict = {}
#
# @classmethod
# def register(cls, action):
# cls.actiondict[action.tag] = action
#
# @classmethod
# def print_actions(cls):
# print("available subcommands are:", file=sys.stderr)
# for a in cls.actiondict:
# print(" %s" % a, file=sys.stderr)
#
# def __new__(cls, node):
# action = cls.actiondict[node]
# return object.__new__(action)
#
# def __init__(self, node):
# self.node = node
#
# @staticmethod
# def upload_file(append, build_dir, filename):
#
# size = 1024 * 1024
#
# with open(filename, "rb") as f:
#
# while True:
#
# bin_data = f.read(size)
# data = binascii.b2a_base64(bin_data)
#
# if not isinstance(data, str):
# data = data.decode("ascii")
#
# append(build_dir, data)
#
# if len(bin_data) != size:
# break
#
# def execute(self, _client, _opt, _args):
# raise NotImplementedError('execute() not implemented')
#
# class ElbeSoapClient:
# def __init__(self, host, port, user, passwd, retries=10, debug=False):
#
# # pylint: disable=too-many-arguments
#
# # Mess with suds logging, for debug, or squelch warnings
# set_suds_debug(debug)
#
# # Attributes
# self.wsdl = "http://" + host + ":" + str(port) + "/soap/?wsdl"
# self.control = None
# self.retries = 0
#
# # Loop and try to connect
# while self.control is None:
# self.retries += 1
# try:
# self.control = Client(self.wsdl, timeout=cfg['soaptimeout'])
# except URLError as e:
# if self.retries > retries:
# raise e
# time.sleep(1)
# except socket.error as e:
# if self.retries > retries:
# raise e
# time.sleep(1)
# except BadStatusLine as e:
# if self.retries > retries:
# raise e
# time.sleep(1)
#
# # Make sure, that client.service still maps
# # to the service object.
# self.service = self.control.service
#
# # We have a Connection, now login
# self.service.login(user, passwd)
#
# def download_file(self, builddir, filename, dst_fname):
# fp = open(dst_fname, "wb")
# part = 0
#
# # XXX the retry logic might get removed in the future, if the error
# # doesn't occur in real world. If it occurs, we should think about
# # the root cause instead of stupid retrying.
# retry = 5
#
# while True:
# try:
# ret = self.service.get_file(builddir, filename, part)
# except BadStatusLine as e:
# retry = retry - 1
#
# print("get_file part %d failed, retry %d times" % (part, retry),
# file=sys.stderr)
# print(str(e), file=sys.stderr)
# print(repr(e.line), file=sys.stderr)
#
# if not retry:
# fp.close()
# print("file transfer failed", file=sys.stderr)
# sys.exit(20)
#
# if ret == "FileNotFound":
# print(ret, file=sys.stderr)
# sys.exit(20)
# if ret == "EndOfFile":
# fp.close()
# return
#
# fp.write(binascii.a2b_base64(ret))
# part = part + 1
#
# Path: elbepack/version.py
#
# Path: elbepack/config.py
# class Config(dict):
# def __init__(self):
#
# Path: elbepack/elbexml.py
# class ValidationMode:
# NO_CHECK = 1
# CHECK_BINARIES = 2
# CHECK_ALL = 0
. Output only the next line. | ClientAction.print_actions() |
Next line prediction: <|code_start|> action="store", type="string",
help="set a limit for the compiler cache size "
"(should be a number followed by an optional "
"suffix: k, M, G, T. Use 0 for no limit.)")
devel = OptionGroup(
oparser,
"options for elbe developers",
"Caution: Don't use these options in a productive environment")
devel.add_option("--skip-urlcheck", action="store_true",
dest="url_validation", default=ValidationMode.CHECK_ALL,
help="Skip URL Check inside initvm")
devel.add_option("--debug", action="store_true",
dest="debug", default=False,
help="Enable debug mode.")
devel.add_option("--ignore-version-diff", action="store_true",
dest="ignore_version", default=False,
help="allow different elbe version on host and initvm")
oparser.add_option_group(devel)
(opt, args) = oparser.parse_args(argv)
if not args:
print("elbe control - no subcommand given", file=sys.stderr)
ClientAction.print_actions()
return
try:
<|code_end|>
. Use current file imports:
(import socket
import sys
from http.client import BadStatusLine
from optparse import (OptionParser, OptionGroup)
from urllib.error import URLError
from suds import WebFault
from elbepack.soapclient import ClientAction, ElbeSoapClient
from elbepack.version import elbe_version
from elbepack.config import cfg
from elbepack.elbexml import ValidationMode)
and context including class names, function names, or small code snippets from other files:
# Path: elbepack/soapclient.py
# class ClientAction:
# actiondict = {}
#
# @classmethod
# def register(cls, action):
# cls.actiondict[action.tag] = action
#
# @classmethod
# def print_actions(cls):
# print("available subcommands are:", file=sys.stderr)
# for a in cls.actiondict:
# print(" %s" % a, file=sys.stderr)
#
# def __new__(cls, node):
# action = cls.actiondict[node]
# return object.__new__(action)
#
# def __init__(self, node):
# self.node = node
#
# @staticmethod
# def upload_file(append, build_dir, filename):
#
# size = 1024 * 1024
#
# with open(filename, "rb") as f:
#
# while True:
#
# bin_data = f.read(size)
# data = binascii.b2a_base64(bin_data)
#
# if not isinstance(data, str):
# data = data.decode("ascii")
#
# append(build_dir, data)
#
# if len(bin_data) != size:
# break
#
# def execute(self, _client, _opt, _args):
# raise NotImplementedError('execute() not implemented')
#
# class ElbeSoapClient:
# def __init__(self, host, port, user, passwd, retries=10, debug=False):
#
# # pylint: disable=too-many-arguments
#
# # Mess with suds logging, for debug, or squelch warnings
# set_suds_debug(debug)
#
# # Attributes
# self.wsdl = "http://" + host + ":" + str(port) + "/soap/?wsdl"
# self.control = None
# self.retries = 0
#
# # Loop and try to connect
# while self.control is None:
# self.retries += 1
# try:
# self.control = Client(self.wsdl, timeout=cfg['soaptimeout'])
# except URLError as e:
# if self.retries > retries:
# raise e
# time.sleep(1)
# except socket.error as e:
# if self.retries > retries:
# raise e
# time.sleep(1)
# except BadStatusLine as e:
# if self.retries > retries:
# raise e
# time.sleep(1)
#
# # Make sure, that client.service still maps
# # to the service object.
# self.service = self.control.service
#
# # We have a Connection, now login
# self.service.login(user, passwd)
#
# def download_file(self, builddir, filename, dst_fname):
# fp = open(dst_fname, "wb")
# part = 0
#
# # XXX the retry logic might get removed in the future, if the error
# # doesn't occur in real world. If it occurs, we should think about
# # the root cause instead of stupid retrying.
# retry = 5
#
# while True:
# try:
# ret = self.service.get_file(builddir, filename, part)
# except BadStatusLine as e:
# retry = retry - 1
#
# print("get_file part %d failed, retry %d times" % (part, retry),
# file=sys.stderr)
# print(str(e), file=sys.stderr)
# print(repr(e.line), file=sys.stderr)
#
# if not retry:
# fp.close()
# print("file transfer failed", file=sys.stderr)
# sys.exit(20)
#
# if ret == "FileNotFound":
# print(ret, file=sys.stderr)
# sys.exit(20)
# if ret == "EndOfFile":
# fp.close()
# return
#
# fp.write(binascii.a2b_base64(ret))
# part = part + 1
#
# Path: elbepack/version.py
#
# Path: elbepack/config.py
# class Config(dict):
# def __init__(self):
#
# Path: elbepack/elbexml.py
# class ValidationMode:
# NO_CHECK = 1
# CHECK_BINARIES = 2
# CHECK_ALL = 0
. Output only the next line. | control = ElbeSoapClient( |
Given the following code snippet before the placeholder: <|code_start|> opt.passwd,
debug=opt.debug,
retries=int(
opt.retries))
except URLError as e:
print("Failed to connect to Soap server %s:%s\n" %
(opt.host, opt.port), file=sys.stderr)
print("", file=sys.stderr)
print("Check, wether the initvm is actually running.", file=sys.stderr)
print("try 'elbe initvm start'", file=sys.stderr)
sys.exit(10)
except socket.error as e:
print("Failed to connect to Soap server %s:%s\n" %
(opt.host, opt.port), file=sys.stderr)
print("", file=sys.stderr)
print(
"Check, wether the Soap Server is running inside the initvm",
file=sys.stderr)
print("try 'elbe initvm attach'", file=sys.stderr)
sys.exit(10)
except BadStatusLine as e:
print("Failed to connect to Soap server %s:%s\n" %
(opt.host, opt.port), file=sys.stderr)
print("", file=sys.stderr)
print("Check, wether the initvm is actually running.", file=sys.stderr)
print("try 'elbe initvm start'", file=sys.stderr)
sys.exit(10)
try:
v_server = control.service.get_version()
<|code_end|>
, predict the next line using imports from the current file:
import socket
import sys
from http.client import BadStatusLine
from optparse import (OptionParser, OptionGroup)
from urllib.error import URLError
from suds import WebFault
from elbepack.soapclient import ClientAction, ElbeSoapClient
from elbepack.version import elbe_version
from elbepack.config import cfg
from elbepack.elbexml import ValidationMode
and context including class names, function names, and sometimes code from other files:
# Path: elbepack/soapclient.py
# class ClientAction:
# actiondict = {}
#
# @classmethod
# def register(cls, action):
# cls.actiondict[action.tag] = action
#
# @classmethod
# def print_actions(cls):
# print("available subcommands are:", file=sys.stderr)
# for a in cls.actiondict:
# print(" %s" % a, file=sys.stderr)
#
# def __new__(cls, node):
# action = cls.actiondict[node]
# return object.__new__(action)
#
# def __init__(self, node):
# self.node = node
#
# @staticmethod
# def upload_file(append, build_dir, filename):
#
# size = 1024 * 1024
#
# with open(filename, "rb") as f:
#
# while True:
#
# bin_data = f.read(size)
# data = binascii.b2a_base64(bin_data)
#
# if not isinstance(data, str):
# data = data.decode("ascii")
#
# append(build_dir, data)
#
# if len(bin_data) != size:
# break
#
# def execute(self, _client, _opt, _args):
# raise NotImplementedError('execute() not implemented')
#
# class ElbeSoapClient:
# def __init__(self, host, port, user, passwd, retries=10, debug=False):
#
# # pylint: disable=too-many-arguments
#
# # Mess with suds logging, for debug, or squelch warnings
# set_suds_debug(debug)
#
# # Attributes
# self.wsdl = "http://" + host + ":" + str(port) + "/soap/?wsdl"
# self.control = None
# self.retries = 0
#
# # Loop and try to connect
# while self.control is None:
# self.retries += 1
# try:
# self.control = Client(self.wsdl, timeout=cfg['soaptimeout'])
# except URLError as e:
# if self.retries > retries:
# raise e
# time.sleep(1)
# except socket.error as e:
# if self.retries > retries:
# raise e
# time.sleep(1)
# except BadStatusLine as e:
# if self.retries > retries:
# raise e
# time.sleep(1)
#
# # Make sure, that client.service still maps
# # to the service object.
# self.service = self.control.service
#
# # We have a Connection, now login
# self.service.login(user, passwd)
#
# def download_file(self, builddir, filename, dst_fname):
# fp = open(dst_fname, "wb")
# part = 0
#
# # XXX the retry logic might get removed in the future, if the error
# # doesn't occur in real world. If it occurs, we should think about
# # the root cause instead of stupid retrying.
# retry = 5
#
# while True:
# try:
# ret = self.service.get_file(builddir, filename, part)
# except BadStatusLine as e:
# retry = retry - 1
#
# print("get_file part %d failed, retry %d times" % (part, retry),
# file=sys.stderr)
# print(str(e), file=sys.stderr)
# print(repr(e.line), file=sys.stderr)
#
# if not retry:
# fp.close()
# print("file transfer failed", file=sys.stderr)
# sys.exit(20)
#
# if ret == "FileNotFound":
# print(ret, file=sys.stderr)
# sys.exit(20)
# if ret == "EndOfFile":
# fp.close()
# return
#
# fp.write(binascii.a2b_base64(ret))
# part = part + 1
#
# Path: elbepack/version.py
#
# Path: elbepack/config.py
# class Config(dict):
# def __init__(self):
#
# Path: elbepack/elbexml.py
# class ValidationMode:
# NO_CHECK = 1
# CHECK_BINARIES = 2
# CHECK_ALL = 0
. Output only the next line. | if v_server != elbe_version: |
Predict the next line for this snippet: <|code_start|> dest="pbuilder_only", default=False,
help="Only list/download pbuilder Files")
oparser.add_option("--cpuset", default=-1, type="int",
help="Limit cpuset of pbuilder commands (bitmask) (defaults to -1 for all CPUs)")
oparser.add_option("--profile", dest="profile", default="",
help="Make pbuilder commands build the specified profile")
oparser.add_option("--cross", dest="cross", default=False,
action="store_true",
help="Creates an environment for crossbuilding if "
"combined with create. Combined with build it"
" will use this environment.")
oparser.add_option("--no-ccache", dest="noccache", default=False,
action="store_true",
help="Deactivates the compiler cache 'ccache'")
oparser.add_option("--ccache-size", dest="ccachesize", default="10G",
action="store", type="string",
help="set a limit for the compiler cache size "
"(should be a number followed by an optional "
"suffix: k, M, G, T. Use 0 for no limit.)")
devel = OptionGroup(
oparser,
"options for elbe developers",
"Caution: Don't use these options in a productive environment")
devel.add_option("--skip-urlcheck", action="store_true",
<|code_end|>
with the help of current file imports:
import socket
import sys
from http.client import BadStatusLine
from optparse import (OptionParser, OptionGroup)
from urllib.error import URLError
from suds import WebFault
from elbepack.soapclient import ClientAction, ElbeSoapClient
from elbepack.version import elbe_version
from elbepack.config import cfg
from elbepack.elbexml import ValidationMode
and context from other files:
# Path: elbepack/soapclient.py
# class ClientAction:
# actiondict = {}
#
# @classmethod
# def register(cls, action):
# cls.actiondict[action.tag] = action
#
# @classmethod
# def print_actions(cls):
# print("available subcommands are:", file=sys.stderr)
# for a in cls.actiondict:
# print(" %s" % a, file=sys.stderr)
#
# def __new__(cls, node):
# action = cls.actiondict[node]
# return object.__new__(action)
#
# def __init__(self, node):
# self.node = node
#
# @staticmethod
# def upload_file(append, build_dir, filename):
#
# size = 1024 * 1024
#
# with open(filename, "rb") as f:
#
# while True:
#
# bin_data = f.read(size)
# data = binascii.b2a_base64(bin_data)
#
# if not isinstance(data, str):
# data = data.decode("ascii")
#
# append(build_dir, data)
#
# if len(bin_data) != size:
# break
#
# def execute(self, _client, _opt, _args):
# raise NotImplementedError('execute() not implemented')
#
# class ElbeSoapClient:
# def __init__(self, host, port, user, passwd, retries=10, debug=False):
#
# # pylint: disable=too-many-arguments
#
# # Mess with suds logging, for debug, or squelch warnings
# set_suds_debug(debug)
#
# # Attributes
# self.wsdl = "http://" + host + ":" + str(port) + "/soap/?wsdl"
# self.control = None
# self.retries = 0
#
# # Loop and try to connect
# while self.control is None:
# self.retries += 1
# try:
# self.control = Client(self.wsdl, timeout=cfg['soaptimeout'])
# except URLError as e:
# if self.retries > retries:
# raise e
# time.sleep(1)
# except socket.error as e:
# if self.retries > retries:
# raise e
# time.sleep(1)
# except BadStatusLine as e:
# if self.retries > retries:
# raise e
# time.sleep(1)
#
# # Make sure, that client.service still maps
# # to the service object.
# self.service = self.control.service
#
# # We have a Connection, now login
# self.service.login(user, passwd)
#
# def download_file(self, builddir, filename, dst_fname):
# fp = open(dst_fname, "wb")
# part = 0
#
# # XXX the retry logic might get removed in the future, if the error
# # doesn't occur in real world. If it occurs, we should think about
# # the root cause instead of stupid retrying.
# retry = 5
#
# while True:
# try:
# ret = self.service.get_file(builddir, filename, part)
# except BadStatusLine as e:
# retry = retry - 1
#
# print("get_file part %d failed, retry %d times" % (part, retry),
# file=sys.stderr)
# print(str(e), file=sys.stderr)
# print(repr(e.line), file=sys.stderr)
#
# if not retry:
# fp.close()
# print("file transfer failed", file=sys.stderr)
# sys.exit(20)
#
# if ret == "FileNotFound":
# print(ret, file=sys.stderr)
# sys.exit(20)
# if ret == "EndOfFile":
# fp.close()
# return
#
# fp.write(binascii.a2b_base64(ret))
# part = part + 1
#
# Path: elbepack/version.py
#
# Path: elbepack/config.py
# class Config(dict):
# def __init__(self):
#
# Path: elbepack/elbexml.py
# class ValidationMode:
# NO_CHECK = 1
# CHECK_BINARIES = 2
# CHECK_ALL = 0
, which may contain function names, class names, or code. Output only the next line. | dest="url_validation", default=ValidationMode.CHECK_ALL, |
Given the following code snippet before the placeholder: <|code_start|># ELBE - Debian Based Embedded Rootfilesystem Builder
# Copyright (c) 2019 Olivier Dion <dion@linutronix.de>
#
# SPDX-License-Identifier: GPL-3.0-or-later
class RadioPolicy(object):
HORIZONTAL = 0
VERTICAL = 1
<|code_end|>
, predict the next line using imports from the current file:
from urwid import (
LineBox,
RadioButton,
Text
)
from elbepack.debianize.widgets.grid import Grid
and context including class names, function names, and sometimes code from other files:
# Path: elbepack/debianize/widgets/grid.py
# class Grid(WidgetWrap):
#
# def __init__(self, rows):
#
# m = 1
# cols = []
#
# for row in rows:
# if len(row) > m:
# m = len(row)
#
# for c in row:
# if isinstance(c, Grid):
# c.parent = self
#
# cols.append(Columns(row))
#
# super(Grid, self).__init__(Rows(cols))
#
# self.n = len(rows)
# self.m = m
#
# self.i = 0
# self.j = 0
#
# self.focus(self.i, self.j)
#
# self.keybind = {
# "down" : lambda: self.focus_recursive(forward=True, horizontal=False),
# "up" : lambda: self.focus_recursive(forward=False, horizontal=False),
# "tab" : lambda: self.focus_recursive(forward=True, horizontal=True),
# "shift tab": lambda: self.focus_recursive(forward=False, horizontal=True)
# }
#
# self.aliases = {
# "ctrl f": "right",
# "ctrl b": "left",
# "ctrl p": "up",
# "ctrl n": "down"
# }
#
# self.parent = None
#
# def focus_direction(self, forward, horizontal):
#
# j = self.j
# i = self.i
# direction = 1 if forward else -1
#
# while True:
# if horizontal:
# j += direction
# i += j // self.m
# else:
# i += direction
# j += i // self.n
#
# i %= self.n
# j %= self.m
#
# try:
# self.focus(i, j)
# break
# except IndexError:
# pass
#
# def focus_recursive(self, forward, horizontal):
# while True:
# child = self.current_focus()
#
# if isinstance(child, Grid):
# child.focus_recursive(forward, horizontal)
# elif not forward and self._is_first():
# if self.parent is not None and not self.parent._is_first():
# return self.parent.focus_direction(forward, horizontal)
# else:
# self.focus_direction(forward, horizontal)
# elif forward and self._is_last():
# if self.parent is not None and not self.parent._is_last():
# return self.parent.focus_direction(forward, horizontal)
# else:
# self.focus_direction(forward, horizontal)
# else:
# self.focus_direction(forward, horizontal)
#
# if self.current_focus().selectable():
# break
#
# def focus_first(self):
# self.focus(0, 0)
# self.i = 0
# self.j = 0
#
# def focus(self, i, j):
# self._w.base_widget.set_focus_path([i, j])
# self.i = i
# self.j = j
#
# def current_focus(self):
# return self._w.base_widget.contents[self.i][0].contents[self.j][0].base_widget
#
# def _is_last(self):
# return self.i == self.n - 1 and self.j == self.m - 1
#
# def _is_first(self):
# return self.i == 0 and self.j == 0
#
# def keypress(self, size, key):
#
# if key in self.aliases:
# key = self.aliases[key]
#
# if key in self.keybind:
# self.keybind[key]()
# return None
#
# return super(Grid, self).keypress(size, key)
. Output only the next line. | class RadioGroup(Grid): |
Given the following code snippet before the placeholder: <|code_start|> """A method to determine absolute path
for a relative path inside project's directory."""
return os.path.abspath(
os.path.join(
os.path.dirname(__file__), path))
class my_install(install):
def run(self):
install.run(self)
if self.root:
envvars = dict({"prefix": self.prefix,
"DESTDIR": self.root},
**dict(os.environ))
else:
envvars = dict({"prefix": self.prefix}, **dict(os.environ))
docs_dir = abspath("./docs/")
output = subprocess.Popen("make install",
shell=True,
stdout=subprocess.PIPE,
cwd=docs_dir,
env=envvars).communicate()[0]
print(output)
setup(name='elbe',
<|code_end|>
, predict the next line using imports from the current file:
import subprocess
import os
import glob
from setuptools import setup
from setuptools.command.install import install
from elbepack.version import elbe_version
and context including class names, function names, and sometimes code from other files:
# Path: elbepack/version.py
. Output only the next line. | version=elbe_version, |
Given the code snippet: <|code_start|> help="enable only tags with empty or given variant")
oparser.add_option("-p", "--proxy", dest="proxy",
default=None,
help="add proxy to mirrors")
def run_command(argv):
oparser = OptionParser(usage="usage: %prog preprocess [options] <xmlfile>")
oparser.add_option("-o", "--output", dest="output",
default="preprocess.xml",
help="preprocessed output file", metavar="<xmlfile>")
add_pass_through_options(oparser)
(opt, args) = oparser.parse_args(argv)
if len(args) != 1:
print("Wrong number of arguments", file=sys.stderr)
oparser.print_help()
sys.exit(20)
if not os.path.isfile(args[0]):
print("%s doesn't exist" % args[0], file=sys.stderr)
sys.exit(20)
variants = []
if opt.variant:
variants = opt.variant.split(',')
try:
xmlpreprocess(args[0], opt.output, variants, opt.proxy)
<|code_end|>
, generate the next line using the imports in this file:
import sys
import os
from optparse import OptionParser
from elbepack.xmlpreprocess import XMLPreprocessError, xmlpreprocess
and context (functions, classes, or occasionally code) from other files:
# Path: elbepack/xmlpreprocess.py
# class XMLPreprocessError(Exception):
# pass
#
# def xmlpreprocess(fname, output, variants=None, proxy=None):
#
# # pylint: disable=too-many-locals
# # pylint: disable=too-many-branches
#
# # first convert variants to a set
# if not variants:
# variants = set([])
# else:
# variants = set(variants)
#
# schema_file = "https://www.linutronix.de/projects/Elbe/dbsfed.xsd"
# parser = XMLParser(huge_tree=True)
# schema_tree = etree.parse(schema_file)
# schema = etree.XMLSchema(schema_tree)
#
# try:
# xml = parse(fname, parser=parser)
# xml.xinclude()
#
# # Variant management
# # check all nodes for variant field, and act accordingly.
# # The result will not contain any variant attributes anymore.
# rmlist = []
# for tag in xml.iter('*'):
# if 'variant' in tag.attrib:
# tag_variants = set(tag.attrib['variant'].split(','))
#
# # check if tag_variants intersects with
# # active variants.
# intersect = variants.intersection(tag_variants)
#
# if intersect:
# # variant is wanted, keep it and remove the variant
# # attribute
# tag.attrib.pop('variant')
# else:
# # tag has a variant attribute but the variant was not
# # specified: remove the tag delayed
# rmlist.append(tag)
#
# for tag in rmlist:
# tag.getparent().remove(tag)
#
# # if there are multiple sections because of sth like '<finetuning
# # variant='A'> ... and <finetuning variant='B'> and running preprocess
# # with --variant=A,B the two sections need to be merged
# #
# # Use xpath expressions to identify mergeable sections.
# for mergepath in mergepaths:
# mergenodes = xml.xpath(mergepath)
#
# # if there is just one section of a type
# # or no section, nothing needs to be done
# if len(mergenodes) < 2:
# continue
#
# # append all childrens of section[1..n] to section[0] and delete
# # section[1..n]
# for section in mergenodes[1:]:
# for c in section.getchildren():
# mergenodes[0].append(c)
# section.getparent().remove(section)
#
# # handle archivedir elements
# xml = combinearchivedir(xml)
#
# preprocess_mirror_replacement(xml)
#
# preprocess_proxy_add(xml, proxy)
#
# # Change public PGP url key to raw key
# preprocess_pgp_key(xml)
#
# # Replace old debootstrapvariant with debootstrap
# preprocess_bootstrap(xml)
#
# preprocess_iso_option(xml)
#
# preprocess_initvm_ports(xml)
#
# preprocess_mirrors(xml)
#
# if schema.validate(xml):
# # if validation succedes write xml file
# xml.write(
# output,
# encoding="UTF-8",
# pretty_print=True,
# compression=9)
# # the rest of the code is exception and error handling
# return
#
# except etree.XMLSyntaxError:
# raise XMLPreprocessError("XML Parse error\n" + str(sys.exc_info()[1]))
# except ArchivedirError:
# raise XMLPreprocessError("<archivedir> handling failed\n" +
# str(sys.exc_info()[1]))
# except BaseException:
# raise XMLPreprocessError(
# "Unknown Exception during validation\n" + str(sys.exc_info()[1]))
#
# # We have errors, return them in string form...
# raise XMLPreprocessError("\n".join(error_log_to_strings(schema.error_log)))
. Output only the next line. | except XMLPreprocessError as e: |
Here is a snippet: <|code_start|> default=None,
help="enable only tags with empty or given variant")
oparser.add_option("-p", "--proxy", dest="proxy",
default=None,
help="add proxy to mirrors")
def run_command(argv):
oparser = OptionParser(usage="usage: %prog preprocess [options] <xmlfile>")
oparser.add_option("-o", "--output", dest="output",
default="preprocess.xml",
help="preprocessed output file", metavar="<xmlfile>")
add_pass_through_options(oparser)
(opt, args) = oparser.parse_args(argv)
if len(args) != 1:
print("Wrong number of arguments", file=sys.stderr)
oparser.print_help()
sys.exit(20)
if not os.path.isfile(args[0]):
print("%s doesn't exist" % args[0], file=sys.stderr)
sys.exit(20)
variants = []
if opt.variant:
variants = opt.variant.split(',')
try:
<|code_end|>
. Write the next line using the current file imports:
import sys
import os
from optparse import OptionParser
from elbepack.xmlpreprocess import XMLPreprocessError, xmlpreprocess
and context from other files:
# Path: elbepack/xmlpreprocess.py
# class XMLPreprocessError(Exception):
# pass
#
# def xmlpreprocess(fname, output, variants=None, proxy=None):
#
# # pylint: disable=too-many-locals
# # pylint: disable=too-many-branches
#
# # first convert variants to a set
# if not variants:
# variants = set([])
# else:
# variants = set(variants)
#
# schema_file = "https://www.linutronix.de/projects/Elbe/dbsfed.xsd"
# parser = XMLParser(huge_tree=True)
# schema_tree = etree.parse(schema_file)
# schema = etree.XMLSchema(schema_tree)
#
# try:
# xml = parse(fname, parser=parser)
# xml.xinclude()
#
# # Variant management
# # check all nodes for variant field, and act accordingly.
# # The result will not contain any variant attributes anymore.
# rmlist = []
# for tag in xml.iter('*'):
# if 'variant' in tag.attrib:
# tag_variants = set(tag.attrib['variant'].split(','))
#
# # check if tag_variants intersects with
# # active variants.
# intersect = variants.intersection(tag_variants)
#
# if intersect:
# # variant is wanted, keep it and remove the variant
# # attribute
# tag.attrib.pop('variant')
# else:
# # tag has a variant attribute but the variant was not
# # specified: remove the tag delayed
# rmlist.append(tag)
#
# for tag in rmlist:
# tag.getparent().remove(tag)
#
# # if there are multiple sections because of sth like '<finetuning
# # variant='A'> ... and <finetuning variant='B'> and running preprocess
# # with --variant=A,B the two sections need to be merged
# #
# # Use xpath expressions to identify mergeable sections.
# for mergepath in mergepaths:
# mergenodes = xml.xpath(mergepath)
#
# # if there is just one section of a type
# # or no section, nothing needs to be done
# if len(mergenodes) < 2:
# continue
#
# # append all childrens of section[1..n] to section[0] and delete
# # section[1..n]
# for section in mergenodes[1:]:
# for c in section.getchildren():
# mergenodes[0].append(c)
# section.getparent().remove(section)
#
# # handle archivedir elements
# xml = combinearchivedir(xml)
#
# preprocess_mirror_replacement(xml)
#
# preprocess_proxy_add(xml, proxy)
#
# # Change public PGP url key to raw key
# preprocess_pgp_key(xml)
#
# # Replace old debootstrapvariant with debootstrap
# preprocess_bootstrap(xml)
#
# preprocess_iso_option(xml)
#
# preprocess_initvm_ports(xml)
#
# preprocess_mirrors(xml)
#
# if schema.validate(xml):
# # if validation succedes write xml file
# xml.write(
# output,
# encoding="UTF-8",
# pretty_print=True,
# compression=9)
# # the rest of the code is exception and error handling
# return
#
# except etree.XMLSyntaxError:
# raise XMLPreprocessError("XML Parse error\n" + str(sys.exc_info()[1]))
# except ArchivedirError:
# raise XMLPreprocessError("<archivedir> handling failed\n" +
# str(sys.exc_info()[1]))
# except BaseException:
# raise XMLPreprocessError(
# "Unknown Exception during validation\n" + str(sys.exc_info()[1]))
#
# # We have errors, return them in string form...
# raise XMLPreprocessError("\n".join(error_log_to_strings(schema.error_log)))
, which may include functions, classes, or code. Output only the next line. | xmlpreprocess(args[0], opt.output, variants, opt.proxy) |
Given the code snippet: <|code_start|> for p in cache:
if not p.is_installed:
continue
if p.is_auto_removable:
p.mark_delete(purge=True)
logging.info("MARKED AS AUTOREMOVE %s", p.name)
cache.commit(apt.progress.base.AcquireProgress(),
apt.progress.base.InstallProgress())
return errors
def run_command(argv):
oparser = OptionParser(usage="usage: %prog adjustpkgs [options] <xmlfile>")
oparser.add_option("-o", "--output", dest="output",
help="name of logfile")
oparser.add_option("-n", "--name", dest="name",
help="name of the project (included in the report)")
(opt, args) = oparser.parse_args(argv)
if len(args) != 1:
print("Wrong number of arguments")
oparser.print_help()
sys.exit(20)
if not opt.output:
return 0
<|code_end|>
, generate the next line using the imports in this file:
import logging
import sys
import apt
import apt.progress
from optparse import OptionParser
from elbepack.treeutils import etree
from elbepack.log import elbe_logging
and context (functions, classes, or occasionally code) from other files:
# Path: elbepack/treeutils.py
# class etree(ebase):
# def __init__(self, fname):
# if fname is not None:
# parser = XMLParser(huge_tree=True, remove_comments=False)
# et = parse(fname, parser=parser)
# else:
# et = ElementTree(file=None)
#
# ebase.__init__(self, et)
#
# def write(self, fname, encoding=None):
# # Make sure, that we end with a newline
# self.et.getroot().tail = '\n'
# self.et.write(fname, encoding=encoding)
#
# def tostring(self):
# return self.et.tostring()
#
# def ensure_child(self, tag):
# retval = self.et.find("./" + tag)
# if retval is not None:
# return elem(retval)
# return elem(SubElement(self.et.getroot(), tag))
#
# def set_child_position(self, child, pos):
# root = self.et.getroot()
# root.remove(child.et)
# root.insert(pos, child.et)
#
# def setroot(self, tag):
# retval = elem(Element(tag))
# # pylint: disable=protected-access
# self.et._setroot(retval.et)
# return retval
#
# @property
# def root(self):
# return elem(self.et.getroot())
#
# Path: elbepack/log.py
# @contextmanager
# def elbe_logging(*args, **kwargs):
# try:
# open_logging(*args, **kwargs)
# yield
# finally:
# close_logging()
. Output only the next line. | xml = etree(args[0]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.