Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Continue the code snippet: <|code_start|> class Position(Leaf): """ Composites holding this has a position in the dungeon. """ def __init__(self): super(Position, self).__init__() self.component_type = "position" self._value = (-1, -1) @property def value(self): """ Gets the dungeon_level the entity is currently in. """ return self._value @value.setter def value(self, new_value): self._value = new_value if self.has_parent() and not self.value is None: <|code_end|> . Use current file imports: from compositecore import Leaf, CompositeMessage and context (classes, functions, or code) from other files: # Path: compositecore.py # class Leaf(Component): # """ # Abstract leaf class of composite design pattern. # # Component classes of leaf type should inherit from this class. # """ # # def __init__(self): # super(Leaf, self).__init__() # # def get_relative_of_type(self, component_type): # return self.parent.get_child_or_ancestor(component_type) # # def has_relative_of_type(self, component_type): # return self.parent.has_child_or_ancestor(component_type) # # class CompositeMessage(object): # """ # Enumerator defining class. Defines all messages that may be sent. # """ # DUNGEON_LEVEL_CHANGED = 0 # POSITION_CHANGED = 1 # # def __init__(self): # """ # Should not be initiated. # """ # raise . Output only the next line.
self.parent.send_message(CompositeMessage.POSITION_CHANGED)
Based on the snippet: <|code_start|> self.hit_trigger_effect = hit_trigger_effect self.crit_chance = crit_chance self.crit_multiplier = crit_multiplier self.crit_message = crit_message def send_miss_message(self): messenger.msg.send_visual_message(self.miss_message % {"source_entity": self.source_entity.description.long_name, "target_entity": self.target_entity.description.long_name}, self.target_entity.position.value) def send_hit_message(self, message_template, damage_caused): source_entity_name = self.source_entity.description.long_name if self.source_entity else None target_entity_name = self.target_entity.description.long_name if self.target_entity else None m = message_template % {"source_entity": source_entity_name, "target_entity": target_entity_name, "damage": str(int(damage_caused))} messenger.msg.send_visual_message(m, self.target_entity.position.value) def is_a_hit(self): return self.target_entity.dodger.is_a_hit(self.accuracy) or self.target_entity.has("sleeping") def is_a_crit(self): return self.crit_chance > random.random() or self.target_entity.has("sleeping") def hit_target(self): is_crit = self.is_a_crit() damage = self.damage if is_crit: damage = self.damage * self.crit_multiplier <|code_end|> , predict the immediate next line with the help of imports: import random import trigger import colors import gametime import icon import messenger from animation import animate_point from compositecore import Leaf from graphic import GraphicChar from statusflags import StatusFlags and context (classes, functions, sometimes code) from other files: # Path: animation.py # def animate_point(game_state, position, graphic_chars): # if not game_state.player.dungeon_mask.can_see_point(position): # return # camera = game_state.camera # x, y = camera.dungeon_to_screen_position(position) # for graphic_char in graphic_chars: # game_state.prepare_draw() # console.set_color_fg((x, y), graphic_char.color_fg) # console.set_symbol((x, y), graphic_char.icon) # for _ in range(settings.MISSILE_ANIMATION_DELAY): # console.flush() # # Path: compositecore.py # class Leaf(Component): # """ # Abstract leaf class of composite design pattern. # # Component classes of leaf type should inherit from this class. # """ # # def __init__(self): # super(Leaf, self).__init__() # # def get_relative_of_type(self, component_type): # return self.parent.get_child_or_ancestor(component_type) # # def has_relative_of_type(self, component_type): # return self.parent.has_child_or_ancestor(component_type) # # Path: graphic.py # class GraphicChar(Leaf): # """ # Composites holding this has a graphical representation as a char. # """ # # def __init__(self, color_bg, color_fg, icon): # super(GraphicChar, self).__init__() # self.component_type = "graphic_char" # self._color_bg = color_bg # self._color_fg = color_fg # self._icon = icon # # @property # def color_bg(self): # if self._color_bg: # return self._color_bg # elif self.next: # return self.next.color_bg # return None # # # @color_bg.setter # def color_bg(self, value): # self._color_bg = value # # @property # def color_fg(self): # if self._color_fg: # return self._color_fg # elif self.next: # return self.next.color_fg # return None # # @color_fg.setter # def color_fg(self, value): # self._color_fg = value # # @property # def icon(self): # if self._icon: # return self._icon # elif self.next: # return self.next.icon # return None # # @icon.setter # def icon(self, value): # self._icon = value # # def copy(self): # """ # Makes a copy of this component. # """ # return GraphicChar(self.color_bg, self.color_fg, self.icon) # # Path: statusflags.py # class StatusFlags(Leaf): # """ # Composites holding this has status flags, describing their behaviour. # """ # INVISIBILE = 0 # SEE_INVISIBILITY = 1 # FLYING = 2 # IS_ALIVE = 3 # CAN_OPEN_DOORS = 4 # HAS_HEART = 5 # # def __init__(self, status_flags=[]): # super(StatusFlags, self).__init__() # self.component_type = "status_flags" # self._status_flags = set(status_flags) # self._temp_status_flags = set() # # def has_status(self, status): # """ # Returns True if parent entity has the status given. # """ # if not self.next is None: # return (status in self._status_flags or # status in self._temp_status_flags or # next.has_status(status)) # else: # return (status in self._status_flags or # status in self._temp_status_flags) # # def add_temp_status(self, status): # """ # Adds a temporary status that will be removed the next tick. # """ # self._temp_status_flags.add(status) # # def before_tick(self, time): # self._temp_status_flags = set() . Output only the next line.
animate_point(self.target_entity.game_state.value, self.target_entity.position.value,
Next line prediction: <|code_start|> # TODO: Idea replace effect types with spoofchildren and add time to live to spoof children. # Effect types in execution order class EffectTypes(object): EFFECT_REMOVER = 0 STATUS_REMOVER = 1 ADD_SPOOF_CHILD = 2 REMOVE_CHILD = 3 BLOCKER = 4 STATUS_ADDER = 5 TELEPORT = 6 HEAL = 7 UI = 8 DAMAGE = 9 EQUIPMENT = 10 ALLTYPES = [EFFECT_REMOVER, STATUS_REMOVER, ADD_SPOOF_CHILD, REMOVE_CHILD, BLOCKER, STATUS_ADDER, TELEPORT, HEAL, UI, DAMAGE, EQUIPMENT] class EffectStackID(object): SLIME_DISSOLVE = "slime_dissolve" <|code_end|> . Use current file imports: (import random import trigger import colors import gametime import icon import messenger from animation import animate_point from compositecore import Leaf from graphic import GraphicChar from statusflags import StatusFlags) and context including class names, function names, or small code snippets from other files: # Path: animation.py # def animate_point(game_state, position, graphic_chars): # if not game_state.player.dungeon_mask.can_see_point(position): # return # camera = game_state.camera # x, y = camera.dungeon_to_screen_position(position) # for graphic_char in graphic_chars: # game_state.prepare_draw() # console.set_color_fg((x, y), graphic_char.color_fg) # console.set_symbol((x, y), graphic_char.icon) # for _ in range(settings.MISSILE_ANIMATION_DELAY): # console.flush() # # Path: compositecore.py # class Leaf(Component): # """ # Abstract leaf class of composite design pattern. # # Component classes of leaf type should inherit from this class. # """ # # def __init__(self): # super(Leaf, self).__init__() # # def get_relative_of_type(self, component_type): # return self.parent.get_child_or_ancestor(component_type) # # def has_relative_of_type(self, component_type): # return self.parent.has_child_or_ancestor(component_type) # # Path: graphic.py # class GraphicChar(Leaf): # """ # Composites holding this has a graphical representation as a char. # """ # # def __init__(self, color_bg, color_fg, icon): # super(GraphicChar, self).__init__() # self.component_type = "graphic_char" # self._color_bg = color_bg # self._color_fg = color_fg # self._icon = icon # # @property # def color_bg(self): # if self._color_bg: # return self._color_bg # elif self.next: # return self.next.color_bg # return None # # # @color_bg.setter # def color_bg(self, value): # self._color_bg = value # # @property # def color_fg(self): # if self._color_fg: # return self._color_fg # elif self.next: # return self.next.color_fg # return None # # @color_fg.setter # def color_fg(self, value): # self._color_fg = value # # @property # def icon(self): # if self._icon: # return self._icon # elif self.next: # return self.next.icon # return None # # @icon.setter # def icon(self, value): # self._icon = value # # def copy(self): # """ # Makes a copy of this component. # """ # return GraphicChar(self.color_bg, self.color_fg, self.icon) # # Path: statusflags.py # class StatusFlags(Leaf): # """ # Composites holding this has status flags, describing their behaviour. # """ # INVISIBILE = 0 # SEE_INVISIBILITY = 1 # FLYING = 2 # IS_ALIVE = 3 # CAN_OPEN_DOORS = 4 # HAS_HEART = 5 # # def __init__(self, status_flags=[]): # super(StatusFlags, self).__init__() # self.component_type = "status_flags" # self._status_flags = set(status_flags) # self._temp_status_flags = set() # # def has_status(self, status): # """ # Returns True if parent entity has the status given. # """ # if not self.next is None: # return (status in self._status_flags or # status in self._temp_status_flags or # next.has_status(status)) # else: # return (status in self._status_flags or # status in self._temp_status_flags) # # def add_temp_status(self, status): # """ # Adds a temporary status that will be removed the next tick. # """ # self._temp_status_flags.add(status) # # def before_tick(self, time): # self._temp_status_flags = set() . Output only the next line.
class EffectQueue(Leaf):
Based on the snippet: <|code_start|> EffectTypes.EFFECT_REMOVER) self.the_message = message self.effect_id_to_remove = effect_id_to_remove def update(self, time_spent): old_size = len(self.queue.effects) self.queue.remove_effects_with_id(self.effect_id_to_remove) if not old_size == len(self.queue.effects): self.message() self.tick(time_spent) def message(self): messenger.msg.send_visual_message(self.the_message % {"source_entity": self.source_entity.description.long_name, "target_entity": self.target_entity.description.long_name}, self.target_entity.position.value) class HeartStop(EntityEffect): def __init__(self, source_entity, time_to_live=1, message=messenger.HEART_STOP_MESSAGE): super(HeartStop, self).__init__(source_entity, time_to_live, EffectTypes.STATUS_REMOVER) self.message = message def send_message(self): messenger.msg.send_visual_message(self.message % {"source_entity": self.source_entity.description.long_name, "target_entity": self.target_entity.description.long_name}, self.target_entity.position.value) def update(self, time_spent): if self.is_new_round(time_spent): <|code_end|> , predict the immediate next line with the help of imports: import random import trigger import colors import gametime import icon import messenger from animation import animate_point from compositecore import Leaf from graphic import GraphicChar from statusflags import StatusFlags and context (classes, functions, sometimes code) from other files: # Path: animation.py # def animate_point(game_state, position, graphic_chars): # if not game_state.player.dungeon_mask.can_see_point(position): # return # camera = game_state.camera # x, y = camera.dungeon_to_screen_position(position) # for graphic_char in graphic_chars: # game_state.prepare_draw() # console.set_color_fg((x, y), graphic_char.color_fg) # console.set_symbol((x, y), graphic_char.icon) # for _ in range(settings.MISSILE_ANIMATION_DELAY): # console.flush() # # Path: compositecore.py # class Leaf(Component): # """ # Abstract leaf class of composite design pattern. # # Component classes of leaf type should inherit from this class. # """ # # def __init__(self): # super(Leaf, self).__init__() # # def get_relative_of_type(self, component_type): # return self.parent.get_child_or_ancestor(component_type) # # def has_relative_of_type(self, component_type): # return self.parent.has_child_or_ancestor(component_type) # # Path: graphic.py # class GraphicChar(Leaf): # """ # Composites holding this has a graphical representation as a char. # """ # # def __init__(self, color_bg, color_fg, icon): # super(GraphicChar, self).__init__() # self.component_type = "graphic_char" # self._color_bg = color_bg # self._color_fg = color_fg # self._icon = icon # # @property # def color_bg(self): # if self._color_bg: # return self._color_bg # elif self.next: # return self.next.color_bg # return None # # # @color_bg.setter # def color_bg(self, value): # self._color_bg = value # # @property # def color_fg(self): # if self._color_fg: # return self._color_fg # elif self.next: # return self.next.color_fg # return None # # @color_fg.setter # def color_fg(self, value): # self._color_fg = value # # @property # def icon(self): # if self._icon: # return self._icon # elif self.next: # return self.next.icon # return None # # @icon.setter # def icon(self, value): # self._icon = value # # def copy(self): # """ # Makes a copy of this component. # """ # return GraphicChar(self.color_bg, self.color_fg, self.icon) # # Path: statusflags.py # class StatusFlags(Leaf): # """ # Composites holding this has status flags, describing their behaviour. # """ # INVISIBILE = 0 # SEE_INVISIBILITY = 1 # FLYING = 2 # IS_ALIVE = 3 # CAN_OPEN_DOORS = 4 # HAS_HEART = 5 # # def __init__(self, status_flags=[]): # super(StatusFlags, self).__init__() # self.component_type = "status_flags" # self._status_flags = set(status_flags) # self._temp_status_flags = set() # # def has_status(self, status): # """ # Returns True if parent entity has the status given. # """ # if not self.next is None: # return (status in self._status_flags or # status in self._temp_status_flags or # next.has_status(status)) # else: # return (status in self._status_flags or # status in self._temp_status_flags) # # def add_temp_status(self, status): # """ # Adds a temporary status that will be removed the next tick. # """ # self._temp_status_flags.add(status) # # def before_tick(self, time): # self._temp_status_flags = set() . Output only the next line.
gray_heart = GraphicChar(None, colors.GRAY, icon.HEART)
Given snippet: <|code_start|> class HeartStop(EntityEffect): def __init__(self, source_entity, time_to_live=1, message=messenger.HEART_STOP_MESSAGE): super(HeartStop, self).__init__(source_entity, time_to_live, EffectTypes.STATUS_REMOVER) self.message = message def send_message(self): messenger.msg.send_visual_message(self.message % {"source_entity": self.source_entity.description.long_name, "target_entity": self.target_entity.description.long_name}, self.target_entity.position.value) def update(self, time_spent): if self.is_new_round(time_spent): gray_heart = GraphicChar(None, colors.GRAY, icon.HEART) self.target_entity.char_printer.append_graphic_char_temporary_frames([gray_heart]) self.send_message() self.tick(time_spent) def _on_remove_effect(self): self.target_entity.health_modifier.kill() class StatusAdder(EntityEffect): def __init__(self, source_entity, status_flag, time_to_live=1): super(StatusAdder, self).__init__(source_entity, time_to_live, EffectTypes.STATUS_ADDER) self.status_flag = status_flag def update(self, time_spent): <|code_end|> , continue by predicting the next line. Consider current file imports: import random import trigger import colors import gametime import icon import messenger from animation import animate_point from compositecore import Leaf from graphic import GraphicChar from statusflags import StatusFlags and context: # Path: animation.py # def animate_point(game_state, position, graphic_chars): # if not game_state.player.dungeon_mask.can_see_point(position): # return # camera = game_state.camera # x, y = camera.dungeon_to_screen_position(position) # for graphic_char in graphic_chars: # game_state.prepare_draw() # console.set_color_fg((x, y), graphic_char.color_fg) # console.set_symbol((x, y), graphic_char.icon) # for _ in range(settings.MISSILE_ANIMATION_DELAY): # console.flush() # # Path: compositecore.py # class Leaf(Component): # """ # Abstract leaf class of composite design pattern. # # Component classes of leaf type should inherit from this class. # """ # # def __init__(self): # super(Leaf, self).__init__() # # def get_relative_of_type(self, component_type): # return self.parent.get_child_or_ancestor(component_type) # # def has_relative_of_type(self, component_type): # return self.parent.has_child_or_ancestor(component_type) # # Path: graphic.py # class GraphicChar(Leaf): # """ # Composites holding this has a graphical representation as a char. # """ # # def __init__(self, color_bg, color_fg, icon): # super(GraphicChar, self).__init__() # self.component_type = "graphic_char" # self._color_bg = color_bg # self._color_fg = color_fg # self._icon = icon # # @property # def color_bg(self): # if self._color_bg: # return self._color_bg # elif self.next: # return self.next.color_bg # return None # # # @color_bg.setter # def color_bg(self, value): # self._color_bg = value # # @property # def color_fg(self): # if self._color_fg: # return self._color_fg # elif self.next: # return self.next.color_fg # return None # # @color_fg.setter # def color_fg(self, value): # self._color_fg = value # # @property # def icon(self): # if self._icon: # return self._icon # elif self.next: # return self.next.icon # return None # # @icon.setter # def icon(self, value): # self._icon = value # # def copy(self): # """ # Makes a copy of this component. # """ # return GraphicChar(self.color_bg, self.color_fg, self.icon) # # Path: statusflags.py # class StatusFlags(Leaf): # """ # Composites holding this has status flags, describing their behaviour. # """ # INVISIBILE = 0 # SEE_INVISIBILITY = 1 # FLYING = 2 # IS_ALIVE = 3 # CAN_OPEN_DOORS = 4 # HAS_HEART = 5 # # def __init__(self, status_flags=[]): # super(StatusFlags, self).__init__() # self.component_type = "status_flags" # self._status_flags = set(status_flags) # self._temp_status_flags = set() # # def has_status(self, status): # """ # Returns True if parent entity has the status given. # """ # if not self.next is None: # return (status in self._status_flags or # status in self._temp_status_flags or # next.has_status(status)) # else: # return (status in self._status_flags or # status in self._temp_status_flags) # # def add_temp_status(self, status): # """ # Adds a temporary status that will be removed the next tick. # """ # self._temp_status_flags.add(status) # # def before_tick(self, time): # self._temp_status_flags = set() which might include code, classes, or functions. Output only the next line.
status_flags = StatusFlags([self.status_flag])
Given the code snippet: <|code_start|> libtcod.console_set_default_background(console, color) def set_symbol(self, position, icon, console=0): x, y = position libtcod.console_set_char(console, x, y, icon) def set_color_fg(self, position, color, console=0): x, y = position libtcod.console_set_char_foreground(console, x, y, color) def set_color_bg(self, position, color, effect=libtcod.BKGND_SET, console=0): x, y = position libtcod.console_set_char_background(console, x, y, color, effect) def print_text(self, position, text): for idx, char in enumerate(text): self.set_color_fg((position[0] + idx, position[1]), self.get_default_color_fg()) self.set_symbol((position[0] + idx, position[1]), char) def print_text_vertical(self, position, text): for idx, char in enumerate(text): self.set_color_fg((position[0], position[1] + idx), self.get_default_color_fg()) self.set_symbol((position[0], position[1] + idx), char) def set_colors_and_symbol(self, position, color_fg, color_bg, icon, console=0): x, y = position libtcod.console_put_char_ex(console, x, y, icon, color_fg, color_bg) def print_char_big(self, icon_position, destination, console=0): <|code_end|> , generate the next line using the imports in this file: import colors import frame import settings import libtcodpy as libtcod from icon import ROW_LENGTH from init import FONT_FILE_PATH and context (functions, classes, or occasionally code) from other files: # Path: icon.py # ROW_LENGTH = 16 # # Path: init.py # FONT_FILE_PATH = os.path.join('fonts', 'terminal16x16_gs_ro.png') . Output only the next line.
source_pixel_x = (icon_position % ROW_LENGTH) * settings.TILE_WIDTH
Given snippet: <|code_start|> def set_color_fg(self, position, color, console=0): x, y = position libtcod.console_set_char_foreground(console, x, y, color) def set_color_bg(self, position, color, effect=libtcod.BKGND_SET, console=0): x, y = position libtcod.console_set_char_background(console, x, y, color, effect) def print_text(self, position, text): for idx, char in enumerate(text): self.set_color_fg((position[0] + idx, position[1]), self.get_default_color_fg()) self.set_symbol((position[0] + idx, position[1]), char) def print_text_vertical(self, position, text): for idx, char in enumerate(text): self.set_color_fg((position[0], position[1] + idx), self.get_default_color_fg()) self.set_symbol((position[0], position[1] + idx), char) def set_colors_and_symbol(self, position, color_fg, color_bg, icon, console=0): x, y = position libtcod.console_put_char_ex(console, x, y, icon, color_fg, color_bg) def print_char_big(self, icon_position, destination, console=0): source_pixel_x = (icon_position % ROW_LENGTH) * settings.TILE_WIDTH source_pixel_y = (icon_position / ROW_LENGTH) * settings.TILE_WIDTH dx, dy = destination if not self.font_image: <|code_end|> , continue by predicting the next line. Consider current file imports: import colors import frame import settings import libtcodpy as libtcod from icon import ROW_LENGTH from init import FONT_FILE_PATH and context: # Path: icon.py # ROW_LENGTH = 16 # # Path: init.py # FONT_FILE_PATH = os.path.join('fonts', 'terminal16x16_gs_ro.png') which might include code, classes, or functions. Output only the next line.
self.font_image = libtcod.image_load(FONT_FILE_PATH)
Next line prediction: <|code_start|> class MenuStyle(object): def __init__(self, rect_style, inactive_text_color, margin): self.rect_style = rect_style self.inactive_text_color = inactive_text_color self.margin = margin class RectangleStyle(object): def __init__(self): self.center = None self.top = None self.left = None self.bottom = None self.right = None self.mid_vertical = self.left self.mid_horizontal = self.top <|code_end|> . Use current file imports: (from graphic import GraphicChar import icon import colors import libtcodpy as libtcod import settings) and context including class names, function names, or small code snippets from other files: # Path: graphic.py # class GraphicChar(Leaf): # """ # Composites holding this has a graphical representation as a char. # """ # # def __init__(self, color_bg, color_fg, icon): # super(GraphicChar, self).__init__() # self.component_type = "graphic_char" # self._color_bg = color_bg # self._color_fg = color_fg # self._icon = icon # # @property # def color_bg(self): # if self._color_bg: # return self._color_bg # elif self.next: # return self.next.color_bg # return None # # # @color_bg.setter # def color_bg(self, value): # self._color_bg = value # # @property # def color_fg(self): # if self._color_fg: # return self._color_fg # elif self.next: # return self.next.color_fg # return None # # @color_fg.setter # def color_fg(self, value): # self._color_fg = value # # @property # def icon(self): # if self._icon: # return self._icon # elif self.next: # return self.next.icon # return None # # @icon.setter # def icon(self, value): # self._icon = value # # def copy(self): # """ # Makes a copy of this component. # """ # return GraphicChar(self.color_bg, self.color_fg, self.icon) . Output only the next line.
self.top_cross = GraphicChar(bg, fg, " ")
Given snippet: <|code_start|> " " + str(range_crit_chance).rjust(value_width), text_box_margin, colors.RED) status_stack_panel = gui.StackPanelVertical((0, 0), alignment=gui.StackPanelVertical.ALIGN_LEFT, vertical_space=0) status_stack_panel.append(heading_stack_panel) status_stack_panel.append(gui.VerticalSpace(1)) status_stack_panel.append(damage_text_box) status_stack_panel.append(hit_text_box) status_stack_panel.append(crit_chance_text_box) return status_stack_panel def player_status_menu(player): split_width = 27 content_padding = (2, 2) player_status_stack_panel = gui.StackPanelVertical(geo.add_2d((0, 0), content_padding), alignment=gui.StackPanelVertical.ALIGN_LEFT, vertical_space=1) player_status_stack_panel_row_1 = gui.StackPanelHorizontal((0, 0), alignment=gui.StackPanelHorizontal.ALIGN_TOP, horizontal_space=1) player_status_stack_panel.append(player_status_stack_panel_row_1) player_status_stack_panel_row_1.append(gui.BigSymbolUIElement((0, 0), player.graphic_char)) player_description_stack = gui.StackPanelVertical((0, 0), alignment=gui.StackPanelVertical.ALIGN_LEFT, vertical_space=1) player_status_stack_panel_row_1.append(player_description_stack) player_description_stack.append(gui.TextBox(player.description.name, (2, 0), colors.WHITE)) player_description_stack.append(gui.TextBox(player.race.value + "\n" + player.job.value, (2, 0), colors.WHITE)) player_description_stack.append(gui.new_player_hp_bar(12, player.health.hp)) <|code_end|> , continue by predicting the next line. Consider current file imports: import action import constants import colors import dungeoncreatorvisualizer import gametime import geometry as geo import graphic import gui import menu import rectfactory import sacrifice import save import settings import state import style import icon from counter import Counter from equipment import EquipmentSlots and context: # Path: counter.py # class Counter(object): # def __init__(self, init_value, max_value, min_value=0): # if not(min_value <= init_value <= max_value): # raise Exception("Incorrectly Initialized Counter") # # self._value = init_value # self.min_value = min_value # self.max_value = max_value # # @property # def value(self): # return self._value # # @value.setter # def value(self, new_value): # self._value = new_value # # def ratio_of_full(self): # return float(self.value - self.min_value) / float(self.size()) # # def is_full(self): # return self.value == self.max_value # # def size(self): # return self.max_value - self.min_value # # def decrease(self, delta): # self._value = max(self.min_value, self.value - delta) # # def increase(self, delta): # self._value = min(self.max_value, self.value + delta) # # def set_max(self): # self._value = self.max_value # # def set_min(self): # self._value = self.min_value # # Path: equipment.py # class EquipmentSlots(object): # # Weapons # MELEE_WEAPON = EquipmentSlot("Melee Weapon", EquipmentTypes.MELEE_WEAPON, icon.SWORD) # RANGED_WEAPON = EquipmentSlot("Ranged Weapon", EquipmentTypes.RANGED_WEAPON, icon.GUN) # # # Armor # HEADGEAR = EquipmentSlot("Headgear", EquipmentTypes.HEADGEAR, icon.HELM) # ARMOR = EquipmentSlot("Armor", EquipmentTypes.ARMOR, icon.ARMOR) # BOOTS = EquipmentSlot("Boots", EquipmentTypes.BOOTS, icon.BOOTS) # # # Jewelry # RIGHT_RING = EquipmentSlot("Right Ring", EquipmentTypes.RING, icon.RING) # LEFT_RING = EquipmentSlot("Left Ring", EquipmentTypes.RING, icon.RING) # AMULET = EquipmentSlot("Amulet", EquipmentTypes.AMULET, icon.AMULET) # # ALL = [MELEE_WEAPON, RANGED_WEAPON, HEADGEAR, ARMOR, # BOOTS, RIGHT_RING, LEFT_RING, AMULET] which might include code, classes, or functions. Output only the next line.
player_description_stack.append(gui.new_player_sanity_bar(12, Counter(10, 10)))
Given the following code snippet before the placeholder: <|code_start|> margin=style.menu_theme.margin) background_rect = get_menu_background(context_menu_rect) ui_elements = [background_rect, resulting_menu] ui_state = state.UIState(gui.UIElementList(ui_elements)) return ui_state def new_player_status_stack(player, width): text_margin = width - 3 text_box_margin = (0, 0) strength_text_box = gui.TextBox("Str" + str(player.strength.value).rjust(text_margin), text_box_margin, colors.ORANGE) armor_text_box = gui.TextBox("Def" + str(player.armor.value).rjust(text_margin), text_box_margin, colors.GRAY) evasion_text_box = gui.TextBox("Eva" + str(player.evasion.value).rjust(text_margin), text_box_margin, colors.GREEN) stealth_text_box = gui.TextBox("Sth" + str(player.stealth.value).rjust(text_margin), text_box_margin, colors.BLUE) movement_speed_text_box = gui.TextBox("Mov" + str(int(120.0 / player.movement_speed.value * 10)).rjust(text_margin), text_box_margin, colors.CHAMPAGNE) status_stack_panel = gui.StackPanelVertical((0, 0), alignment=gui.StackPanelVertical.ALIGN_LEFT, vertical_space=0) status_stack_panel.append(strength_text_box) status_stack_panel.append(armor_text_box) status_stack_panel.append(evasion_text_box) status_stack_panel.append(stealth_text_box) status_stack_panel.append(movement_speed_text_box) return status_stack_panel def new_player_weapon_table(player, width): equipment = player.equipment <|code_end|> , predict the next line using imports from the current file: import action import constants import colors import dungeoncreatorvisualizer import gametime import geometry as geo import graphic import gui import menu import rectfactory import sacrifice import save import settings import state import style import icon from counter import Counter from equipment import EquipmentSlots and context including class names, function names, and sometimes code from other files: # Path: counter.py # class Counter(object): # def __init__(self, init_value, max_value, min_value=0): # if not(min_value <= init_value <= max_value): # raise Exception("Incorrectly Initialized Counter") # # self._value = init_value # self.min_value = min_value # self.max_value = max_value # # @property # def value(self): # return self._value # # @value.setter # def value(self, new_value): # self._value = new_value # # def ratio_of_full(self): # return float(self.value - self.min_value) / float(self.size()) # # def is_full(self): # return self.value == self.max_value # # def size(self): # return self.max_value - self.min_value # # def decrease(self, delta): # self._value = max(self.min_value, self.value - delta) # # def increase(self, delta): # self._value = min(self.max_value, self.value + delta) # # def set_max(self): # self._value = self.max_value # # def set_min(self): # self._value = self.min_value # # Path: equipment.py # class EquipmentSlots(object): # # Weapons # MELEE_WEAPON = EquipmentSlot("Melee Weapon", EquipmentTypes.MELEE_WEAPON, icon.SWORD) # RANGED_WEAPON = EquipmentSlot("Ranged Weapon", EquipmentTypes.RANGED_WEAPON, icon.GUN) # # # Armor # HEADGEAR = EquipmentSlot("Headgear", EquipmentTypes.HEADGEAR, icon.HELM) # ARMOR = EquipmentSlot("Armor", EquipmentTypes.ARMOR, icon.ARMOR) # BOOTS = EquipmentSlot("Boots", EquipmentTypes.BOOTS, icon.BOOTS) # # # Jewelry # RIGHT_RING = EquipmentSlot("Right Ring", EquipmentTypes.RING, icon.RING) # LEFT_RING = EquipmentSlot("Left Ring", EquipmentTypes.RING, icon.RING) # AMULET = EquipmentSlot("Amulet", EquipmentTypes.AMULET, icon.AMULET) # # ALL = [MELEE_WEAPON, RANGED_WEAPON, HEADGEAR, ARMOR, # BOOTS, RIGHT_RING, LEFT_RING, AMULET] . Output only the next line.
if equipment.slot_is_equiped(EquipmentSlots.MELEE_WEAPON):
Predict the next line after this snippet: <|code_start|># Poupool - swimming pool control software # Copyright (C) 2020 Cyril Jaquier # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. @pytest.fixture def temperature_reader(mocker): reader = TemperatureReader({}) return reader class TestTemperatureReader: def test_slope_empty(self, mocker, temperature_reader): mock_values = mocker.patch( "controller.sensor.TemperatureReader.values", new_callable=mocker.PropertyMock) <|code_end|> using the current file's imports: import pytest from controller.sensor import MovingAverage from controller.sensor import TemperatureReader and any relevant context from other files: # Path: controller/sensor.py # class MovingAverage: # # def __init__(self, maxlen): # self.__data = collections.deque(maxlen=maxlen) # # def clear(self): # self.__data.clear() # # def push(self, value): # self.__data.append(value) # # def all(self): # return list(self.__data) # # def mean(self): # return statistics.mean(self.__data) if self.__data else None . Output only the next line.
mock_values.return_value = {"pool": MovingAverage(10)}
Given snippet: <|code_start|> # from transitions.extensions import GraphMachine as Machine logger = logging.getLogger(__name__) class Tank(PoupoolActor): STATE_REFRESH_DELAY = 10 states = ["halt", "fill", "low", "normal", "high"] hysteresis = int(config["tank", "hysteresis"]) levels_too_low = int(config["tank", "too_low"]) levels_eco = { "low": int(config["tank", "eco_low"]), "high": int(config["tank", "eco_high"]), } levels_overflow = { "low": int(config["tank", "overflow_low"]), "high": int(config["tank", "overflow_high"]), } def __init__(self, encoder, devices): super().__init__() self.__encoder = encoder self.__devices = devices self.__force_empty = False self.levels = self.levels_eco # Initialize the state machine <|code_end|> , continue by predicting the next line. Consider current file imports: import logging import datetime from .actor import PoupoolActor from .actor import PoupoolModel from .actor import StopRepeatException, do_repeat from .config import config and context: # Path: controller/actor.py # class PoupoolActor(pykka.ThreadingActor): # # def __init__(self): # super().__init__() # self._proxy = self.actor_ref.proxy() # self.__timer = None # # def on_failure(self, exception_type, exception_value, traceback): # # The actor is going to die # logger.fatal(exception_type, exception_value, traceback) # # def on_stop(self): # self.do_cancel() # # def get_actor(self, name): # fsm = pykka.ActorRegistry.get_by_class_name(name) # if fsm: # return fsm[0].proxy() # logger.critical("Actor %s not found!!!" % name) # return None # # def __do_cancel(self): # if self.__timer: # self.__timer.cancel() # self.__timer = None # # def do_cancel(self): # self.__do_cancel() # # def do_delay(self, delay, method, *args, **kwargs): # assert type(method) == str # assert delay >= 0 # # Stop an already running timer # self.__do_cancel() # func = getattr(self._proxy, method) # if delay > 0: # self.__timer = Timer(delay, func.defer, *args, **kwargs) # self.__timer.start() # else: # func.defer(*args, **kwargs) # # Path: controller/actor.py # class PoupoolModel(Machine): # # def __init__(self, *args, **kwargs): # kwargs.setdefault("before_state_change", []).extend(["do_cancel", self.__update_state_time]) # super().__init__( # auto_transitions=False, # ignore_invalid_triggers=True, # *args, # **kwargs # ) # self.__state_time = None # # def __update_state_time(self): # self.__state_time = datetime.now() # # def get_time_in_state(self): # return datetime.now() - self.__state_time # # Path: controller/actor.py # class StopRepeatException(Exception): # pass # # def do_repeat(): # def wrap(func): # @functools.wraps(func) # def wrapped_func(self, *args, **kwargs): # try: # func(self, *args, **kwargs) # except StopRepeatException: # pass # else: # method = re.sub("on_enter_", "do_repeat_", func.__name__) # function = getattr(self._proxy, method) # function.defer() # return wrapped_func # return wrap # # Path: controller/config.py # class Config: # def __init__(self, config_files): # def __getitem__(self, pair): # def as_list(value, type_cast=int): which might include code, classes, or functions. Output only the next line.
self.__machine = PoupoolModel(model=self, states=Tank.states, initial="halt")
Given the code snippet: <|code_start|> if not previous and self.__force_empty and not self.is_halt(): # In case the user enable the settings and we are running already, we stop everything. # The user can continue from the halt state. logger.warning("The tank is not in the halt state, stopping everything") self.get_actor("Filtration").halt.defer() elif previous and not self.__force_empty and self.is_halt(): # Deactivation of the function, we start the tank FSM. self._proxy.fill.defer() def is_force_empty(self): return self.__force_empty def set_mode(self, mode): logger.info("Tank level set to %s" % mode) self.levels = self.levels_eco if mode == "eco" else self.levels_overflow def on_enter_halt(self): logger.info("Entering halt state") self.__encoder.tank_state("halt") self.__devices.get_valve("main").off() @do_repeat() def on_enter_fill(self): logger.info("Entering fill state") self.__encoder.tank_state("fill") height = self.__get_tank_height() if height < self.levels_too_low: self.__devices.get_valve("main").on() else: self._proxy.normal.defer() <|code_end|> , generate the next line using the imports in this file: import logging import datetime from .actor import PoupoolActor from .actor import PoupoolModel from .actor import StopRepeatException, do_repeat from .config import config and context (functions, classes, or occasionally code) from other files: # Path: controller/actor.py # class PoupoolActor(pykka.ThreadingActor): # # def __init__(self): # super().__init__() # self._proxy = self.actor_ref.proxy() # self.__timer = None # # def on_failure(self, exception_type, exception_value, traceback): # # The actor is going to die # logger.fatal(exception_type, exception_value, traceback) # # def on_stop(self): # self.do_cancel() # # def get_actor(self, name): # fsm = pykka.ActorRegistry.get_by_class_name(name) # if fsm: # return fsm[0].proxy() # logger.critical("Actor %s not found!!!" % name) # return None # # def __do_cancel(self): # if self.__timer: # self.__timer.cancel() # self.__timer = None # # def do_cancel(self): # self.__do_cancel() # # def do_delay(self, delay, method, *args, **kwargs): # assert type(method) == str # assert delay >= 0 # # Stop an already running timer # self.__do_cancel() # func = getattr(self._proxy, method) # if delay > 0: # self.__timer = Timer(delay, func.defer, *args, **kwargs) # self.__timer.start() # else: # func.defer(*args, **kwargs) # # Path: controller/actor.py # class PoupoolModel(Machine): # # def __init__(self, *args, **kwargs): # kwargs.setdefault("before_state_change", []).extend(["do_cancel", self.__update_state_time]) # super().__init__( # auto_transitions=False, # ignore_invalid_triggers=True, # *args, # **kwargs # ) # self.__state_time = None # # def __update_state_time(self): # self.__state_time = datetime.now() # # def get_time_in_state(self): # return datetime.now() - self.__state_time # # Path: controller/actor.py # class StopRepeatException(Exception): # pass # # def do_repeat(): # def wrap(func): # @functools.wraps(func) # def wrapped_func(self, *args, **kwargs): # try: # func(self, *args, **kwargs) # except StopRepeatException: # pass # else: # method = re.sub("on_enter_", "do_repeat_", func.__name__) # function = getattr(self._proxy, method) # function.defer() # return wrapped_func # return wrap # # Path: controller/config.py # class Config: # def __init__(self, config_files): # def __getitem__(self, pair): # def as_list(value, type_cast=int): . Output only the next line.
raise StopRepeatException
Continue the code snippet: <|code_start|> height = self.__devices.get_sensor("tank").value logger.debug("Tank level: %d" % height) self.__encoder.tank_height(int(round(height))) return height def force_empty(self, value): previous = self.__force_empty self.__force_empty = value logger.info("Force empty tank is %sabled" % ("en" if value else "dis")) if not previous and self.__force_empty and not self.is_halt(): # In case the user enable the settings and we are running already, we stop everything. # The user can continue from the halt state. logger.warning("The tank is not in the halt state, stopping everything") self.get_actor("Filtration").halt.defer() elif previous and not self.__force_empty and self.is_halt(): # Deactivation of the function, we start the tank FSM. self._proxy.fill.defer() def is_force_empty(self): return self.__force_empty def set_mode(self, mode): logger.info("Tank level set to %s" % mode) self.levels = self.levels_eco if mode == "eco" else self.levels_overflow def on_enter_halt(self): logger.info("Entering halt state") self.__encoder.tank_state("halt") self.__devices.get_valve("main").off() <|code_end|> . Use current file imports: import logging import datetime from .actor import PoupoolActor from .actor import PoupoolModel from .actor import StopRepeatException, do_repeat from .config import config and context (classes, functions, or code) from other files: # Path: controller/actor.py # class PoupoolActor(pykka.ThreadingActor): # # def __init__(self): # super().__init__() # self._proxy = self.actor_ref.proxy() # self.__timer = None # # def on_failure(self, exception_type, exception_value, traceback): # # The actor is going to die # logger.fatal(exception_type, exception_value, traceback) # # def on_stop(self): # self.do_cancel() # # def get_actor(self, name): # fsm = pykka.ActorRegistry.get_by_class_name(name) # if fsm: # return fsm[0].proxy() # logger.critical("Actor %s not found!!!" % name) # return None # # def __do_cancel(self): # if self.__timer: # self.__timer.cancel() # self.__timer = None # # def do_cancel(self): # self.__do_cancel() # # def do_delay(self, delay, method, *args, **kwargs): # assert type(method) == str # assert delay >= 0 # # Stop an already running timer # self.__do_cancel() # func = getattr(self._proxy, method) # if delay > 0: # self.__timer = Timer(delay, func.defer, *args, **kwargs) # self.__timer.start() # else: # func.defer(*args, **kwargs) # # Path: controller/actor.py # class PoupoolModel(Machine): # # def __init__(self, *args, **kwargs): # kwargs.setdefault("before_state_change", []).extend(["do_cancel", self.__update_state_time]) # super().__init__( # auto_transitions=False, # ignore_invalid_triggers=True, # *args, # **kwargs # ) # self.__state_time = None # # def __update_state_time(self): # self.__state_time = datetime.now() # # def get_time_in_state(self): # return datetime.now() - self.__state_time # # Path: controller/actor.py # class StopRepeatException(Exception): # pass # # def do_repeat(): # def wrap(func): # @functools.wraps(func) # def wrapped_func(self, *args, **kwargs): # try: # func(self, *args, **kwargs) # except StopRepeatException: # pass # else: # method = re.sub("on_enter_", "do_repeat_", func.__name__) # function = getattr(self._proxy, method) # function.defer() # return wrapped_func # return wrap # # Path: controller/config.py # class Config: # def __init__(self, config_files): # def __getitem__(self, pair): # def as_list(value, type_cast=int): . Output only the next line.
@do_repeat()
Based on the snippet: <|code_start|># Poupool - swimming pool control software # Copyright (C) 2019 Cyril Jaquier # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # from transitions.extensions import GraphMachine as Machine logger = logging.getLogger(__name__) class Tank(PoupoolActor): STATE_REFRESH_DELAY = 10 states = ["halt", "fill", "low", "normal", "high"] <|code_end|> , predict the immediate next line with the help of imports: import logging import datetime from .actor import PoupoolActor from .actor import PoupoolModel from .actor import StopRepeatException, do_repeat from .config import config and context (classes, functions, sometimes code) from other files: # Path: controller/actor.py # class PoupoolActor(pykka.ThreadingActor): # # def __init__(self): # super().__init__() # self._proxy = self.actor_ref.proxy() # self.__timer = None # # def on_failure(self, exception_type, exception_value, traceback): # # The actor is going to die # logger.fatal(exception_type, exception_value, traceback) # # def on_stop(self): # self.do_cancel() # # def get_actor(self, name): # fsm = pykka.ActorRegistry.get_by_class_name(name) # if fsm: # return fsm[0].proxy() # logger.critical("Actor %s not found!!!" % name) # return None # # def __do_cancel(self): # if self.__timer: # self.__timer.cancel() # self.__timer = None # # def do_cancel(self): # self.__do_cancel() # # def do_delay(self, delay, method, *args, **kwargs): # assert type(method) == str # assert delay >= 0 # # Stop an already running timer # self.__do_cancel() # func = getattr(self._proxy, method) # if delay > 0: # self.__timer = Timer(delay, func.defer, *args, **kwargs) # self.__timer.start() # else: # func.defer(*args, **kwargs) # # Path: controller/actor.py # class PoupoolModel(Machine): # # def __init__(self, *args, **kwargs): # kwargs.setdefault("before_state_change", []).extend(["do_cancel", self.__update_state_time]) # super().__init__( # auto_transitions=False, # ignore_invalid_triggers=True, # *args, # **kwargs # ) # self.__state_time = None # # def __update_state_time(self): # self.__state_time = datetime.now() # # def get_time_in_state(self): # return datetime.now() - self.__state_time # # Path: controller/actor.py # class StopRepeatException(Exception): # pass # # def do_repeat(): # def wrap(func): # @functools.wraps(func) # def wrapped_func(self, *args, **kwargs): # try: # func(self, *args, **kwargs) # except StopRepeatException: # pass # else: # method = re.sub("on_enter_", "do_repeat_", func.__name__) # function = getattr(self._proxy, method) # function.defer() # return wrapped_func # return wrap # # Path: controller/config.py # class Config: # def __init__(self, config_files): # def __getitem__(self, pair): # def as_list(value, type_cast=int): . Output only the next line.
hysteresis = int(config["tank", "hysteresis"])
Using the snippet: <|code_start|> CL_PWM_PERIOD = int(config["disinfection", "cl_pwm_period"]) states = [ "halt", "waiting", {"name": "running", "initial": "adjusting", "children": [ "adjusting", "treating"]}] def __init__(self, encoder, devices, sensors_reader, sensors_writer, disable=False): super().__init__() self.__is_disabled = disable self.__encoder = encoder self.__devices = devices self.__sensors_reader = sensors_reader self.__sensors_writer = sensors_writer # pH self.__ph_enable = True self.__ph = PWM.start("pH", self.__devices.get_pump("ph")).proxy() self.__ph.period = Disinfection.PH_PWM_PERIOD self.__ph_controller = PController(pterm=-1.0) self.__ph_controller.setpoint = 7 # ORP self.__orp_enable = True self.__orp_controller = PController(pterm=1.0, scale=0.005) self.__orp_controller.setpoint = 600 # Chlorine self.__cl = PWM.start("cl", self.__devices.get_pump("cl")).proxy() self.__cl.period = Disinfection.CL_PWM_PERIOD # Initialize the state machine <|code_end|> , determine the next line of code. You have imports: import time import logging from datetime import datetime, timedelta from .actor import PoupoolModel from .actor import PoupoolActor from .util import constrain, Timer from .config import config and context (class names, function names, or code) available: # Path: controller/actor.py # class PoupoolModel(Machine): # # def __init__(self, *args, **kwargs): # kwargs.setdefault("before_state_change", []).extend(["do_cancel", self.__update_state_time]) # super().__init__( # auto_transitions=False, # ignore_invalid_triggers=True, # *args, # **kwargs # ) # self.__state_time = None # # def __update_state_time(self): # self.__state_time = datetime.now() # # def get_time_in_state(self): # return datetime.now() - self.__state_time # # Path: controller/actor.py # class PoupoolActor(pykka.ThreadingActor): # # def __init__(self): # super().__init__() # self._proxy = self.actor_ref.proxy() # self.__timer = None # # def on_failure(self, exception_type, exception_value, traceback): # # The actor is going to die # logger.fatal(exception_type, exception_value, traceback) # # def on_stop(self): # self.do_cancel() # # def get_actor(self, name): # fsm = pykka.ActorRegistry.get_by_class_name(name) # if fsm: # return fsm[0].proxy() # logger.critical("Actor %s not found!!!" % name) # return None # # def __do_cancel(self): # if self.__timer: # self.__timer.cancel() # self.__timer = None # # def do_cancel(self): # self.__do_cancel() # # def do_delay(self, delay, method, *args, **kwargs): # assert type(method) == str # assert delay >= 0 # # Stop an already running timer # self.__do_cancel() # func = getattr(self._proxy, method) # if delay > 0: # self.__timer = Timer(delay, func.defer, *args, **kwargs) # self.__timer.start() # else: # func.defer(*args, **kwargs) # # Path: controller/util.py # def constrain(x, out_min, out_max): # return min(max(x, out_min), out_max) # # class Timer(object): # # def __init__(self, name): # self.__duration = timedelta() # self.__name = name # self.__last = None # self.__last_print = datetime(2000, 1, 1) # self.__delay = timedelta() # # @property # def duration(self): # return self.__duration # # @duration.setter # def duration(self, value): # self.__duration = value # # @property # def remaining(self): # return max(timedelta(), self.__delay - self.__duration) # # @property # def delay(self): # return self.__delay # # @delay.setter # def delay(self, value): # self.__delay = value # self.reset() # # def clear(self): # self.__last = None # # def reset(self): # self.clear() # self.__duration = timedelta() # # def update(self, now, factor=1): # if self.__last is not None: # self.__duration += factor * (now - self.__last) # remaining = max(timedelta(), self.delay - self.__duration) # if self.__last_print + timedelta(seconds=20) <= now: # logger.debug("(%s) Timer: %s Remaining: %s" % # (self.__name, self.__duration, remaining)) # self.__last_print = now # self.__last = now # # def elapsed(self): # return self.__duration >= self.__delay # # Path: controller/config.py # class Config: # def __init__(self, config_files): # def __getitem__(self, pair): # def as_list(value, type_cast=int): . Output only the next line.
self.__machine = PoupoolModel(model=self, states=Disinfection.states, initial="halt")
Predict the next line for this snippet: <|code_start|>class PWM(PoupoolActor): SECURITY_DURATION = int(config["disinfection", "security_duration"]) def __init__(self, name, pump, period=120, min_runtime=3): super().__init__() self.__name = name self.__pump = pump self.period = period self.__last = None self.__duration = 0 self.__state = False self.__security_duration = Timer("PWM for %s" % name) self.__security_duration.delay = timedelta(hours=PWM.SECURITY_DURATION) self.__security_reset = datetime.now() + timedelta(days=1) self.__min_runtime = min_runtime self.value = 0.0 def do_cancel(self): super().do_cancel() # Clear the security duration counter and last time during a pause self.__security_duration.clear() self.__last = None self.__pump.off() def do_run(self): now = time.time() if self.__last is not None: diff = now - self.__last self.__duration += diff <|code_end|> with the help of current file imports: import time import logging from datetime import datetime, timedelta from .actor import PoupoolModel from .actor import PoupoolActor from .util import constrain, Timer from .config import config and context from other files: # Path: controller/actor.py # class PoupoolModel(Machine): # # def __init__(self, *args, **kwargs): # kwargs.setdefault("before_state_change", []).extend(["do_cancel", self.__update_state_time]) # super().__init__( # auto_transitions=False, # ignore_invalid_triggers=True, # *args, # **kwargs # ) # self.__state_time = None # # def __update_state_time(self): # self.__state_time = datetime.now() # # def get_time_in_state(self): # return datetime.now() - self.__state_time # # Path: controller/actor.py # class PoupoolActor(pykka.ThreadingActor): # # def __init__(self): # super().__init__() # self._proxy = self.actor_ref.proxy() # self.__timer = None # # def on_failure(self, exception_type, exception_value, traceback): # # The actor is going to die # logger.fatal(exception_type, exception_value, traceback) # # def on_stop(self): # self.do_cancel() # # def get_actor(self, name): # fsm = pykka.ActorRegistry.get_by_class_name(name) # if fsm: # return fsm[0].proxy() # logger.critical("Actor %s not found!!!" % name) # return None # # def __do_cancel(self): # if self.__timer: # self.__timer.cancel() # self.__timer = None # # def do_cancel(self): # self.__do_cancel() # # def do_delay(self, delay, method, *args, **kwargs): # assert type(method) == str # assert delay >= 0 # # Stop an already running timer # self.__do_cancel() # func = getattr(self._proxy, method) # if delay > 0: # self.__timer = Timer(delay, func.defer, *args, **kwargs) # self.__timer.start() # else: # func.defer(*args, **kwargs) # # Path: controller/util.py # def constrain(x, out_min, out_max): # return min(max(x, out_min), out_max) # # class Timer(object): # # def __init__(self, name): # self.__duration = timedelta() # self.__name = name # self.__last = None # self.__last_print = datetime(2000, 1, 1) # self.__delay = timedelta() # # @property # def duration(self): # return self.__duration # # @duration.setter # def duration(self, value): # self.__duration = value # # @property # def remaining(self): # return max(timedelta(), self.__delay - self.__duration) # # @property # def delay(self): # return self.__delay # # @delay.setter # def delay(self, value): # self.__delay = value # self.reset() # # def clear(self): # self.__last = None # # def reset(self): # self.clear() # self.__duration = timedelta() # # def update(self, now, factor=1): # if self.__last is not None: # self.__duration += factor * (now - self.__last) # remaining = max(timedelta(), self.delay - self.__duration) # if self.__last_print + timedelta(seconds=20) <= now: # logger.debug("(%s) Timer: %s Remaining: %s" % # (self.__name, self.__duration, remaining)) # self.__last_print = now # self.__last = now # # def elapsed(self): # return self.__duration >= self.__delay # # Path: controller/config.py # class Config: # def __init__(self, config_files): # def __getitem__(self, pair): # def as_list(value, type_cast=int): , which may contain function names, class names, or code. Output only the next line.
self.__duration = constrain(self.__duration, 0, self.period)
Given the code snippet: <|code_start|># This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. logger = logging.getLogger(__name__) class PWM(PoupoolActor): SECURITY_DURATION = int(config["disinfection", "security_duration"]) def __init__(self, name, pump, period=120, min_runtime=3): super().__init__() self.__name = name self.__pump = pump self.period = period self.__last = None self.__duration = 0 self.__state = False <|code_end|> , generate the next line using the imports in this file: import time import logging from datetime import datetime, timedelta from .actor import PoupoolModel from .actor import PoupoolActor from .util import constrain, Timer from .config import config and context (functions, classes, or occasionally code) from other files: # Path: controller/actor.py # class PoupoolModel(Machine): # # def __init__(self, *args, **kwargs): # kwargs.setdefault("before_state_change", []).extend(["do_cancel", self.__update_state_time]) # super().__init__( # auto_transitions=False, # ignore_invalid_triggers=True, # *args, # **kwargs # ) # self.__state_time = None # # def __update_state_time(self): # self.__state_time = datetime.now() # # def get_time_in_state(self): # return datetime.now() - self.__state_time # # Path: controller/actor.py # class PoupoolActor(pykka.ThreadingActor): # # def __init__(self): # super().__init__() # self._proxy = self.actor_ref.proxy() # self.__timer = None # # def on_failure(self, exception_type, exception_value, traceback): # # The actor is going to die # logger.fatal(exception_type, exception_value, traceback) # # def on_stop(self): # self.do_cancel() # # def get_actor(self, name): # fsm = pykka.ActorRegistry.get_by_class_name(name) # if fsm: # return fsm[0].proxy() # logger.critical("Actor %s not found!!!" % name) # return None # # def __do_cancel(self): # if self.__timer: # self.__timer.cancel() # self.__timer = None # # def do_cancel(self): # self.__do_cancel() # # def do_delay(self, delay, method, *args, **kwargs): # assert type(method) == str # assert delay >= 0 # # Stop an already running timer # self.__do_cancel() # func = getattr(self._proxy, method) # if delay > 0: # self.__timer = Timer(delay, func.defer, *args, **kwargs) # self.__timer.start() # else: # func.defer(*args, **kwargs) # # Path: controller/util.py # def constrain(x, out_min, out_max): # return min(max(x, out_min), out_max) # # class Timer(object): # # def __init__(self, name): # self.__duration = timedelta() # self.__name = name # self.__last = None # self.__last_print = datetime(2000, 1, 1) # self.__delay = timedelta() # # @property # def duration(self): # return self.__duration # # @duration.setter # def duration(self, value): # self.__duration = value # # @property # def remaining(self): # return max(timedelta(), self.__delay - self.__duration) # # @property # def delay(self): # return self.__delay # # @delay.setter # def delay(self, value): # self.__delay = value # self.reset() # # def clear(self): # self.__last = None # # def reset(self): # self.clear() # self.__duration = timedelta() # # def update(self, now, factor=1): # if self.__last is not None: # self.__duration += factor * (now - self.__last) # remaining = max(timedelta(), self.delay - self.__duration) # if self.__last_print + timedelta(seconds=20) <= now: # logger.debug("(%s) Timer: %s Remaining: %s" % # (self.__name, self.__duration, remaining)) # self.__last_print = now # self.__last = now # # def elapsed(self): # return self.__duration >= self.__delay # # Path: controller/config.py # class Config: # def __init__(self, config_files): # def __getitem__(self, pair): # def as_list(value, type_cast=int): . Output only the next line.
self.__security_duration = Timer("PWM for %s" % name)
Given the following code snippet before the placeholder: <|code_start|> "normal"]}, "comfort", "sweep", "reload", {"name": "wash", "initial": "backwash", "children": [ "backwash", "rinse"]}, {"name": "wintering", "initial": "waiting", "children": [ "stir", "waiting"]}] def __init__(self, temperature, encoder, devices): super().__init__() self.__temperature = temperature self.__encoder = encoder self.__devices = devices # Parameters self.__eco_mode = EcoMode(encoder) self.__stir_mode = StirMode(devices) self.__boost_duration = timedelta(minutes=5) self.__cover_position_eco = 0 self.__speed_eco = 1 self.__speed_standby = 1 self.__speed_overflow = 4 self.__overflow_in_comfort = False self.__backwash_backwash_duration = 120 self.__backwash_rinse_duration = 60 self.__backwash_period = 30 self.__backwash_last = datetime.fromtimestamp(0) # Initialize the state machine <|code_end|> , predict the next line using imports from the current file: import pykka import time import logging from datetime import datetime, timedelta from astral import geocoder, sun from .actor import PoupoolModel from .actor import PoupoolActor from .actor import do_repeat from .util import round_timedelta, Timer from .config import config from transitions.extensions import HierarchicalGraphMachine and context including class names, function names, and sometimes code from other files: # Path: controller/actor.py # class PoupoolModel(Machine): # # def __init__(self, *args, **kwargs): # kwargs.setdefault("before_state_change", []).extend(["do_cancel", self.__update_state_time]) # super().__init__( # auto_transitions=False, # ignore_invalid_triggers=True, # *args, # **kwargs # ) # self.__state_time = None # # def __update_state_time(self): # self.__state_time = datetime.now() # # def get_time_in_state(self): # return datetime.now() - self.__state_time # # Path: controller/actor.py # class PoupoolActor(pykka.ThreadingActor): # # def __init__(self): # super().__init__() # self._proxy = self.actor_ref.proxy() # self.__timer = None # # def on_failure(self, exception_type, exception_value, traceback): # # The actor is going to die # logger.fatal(exception_type, exception_value, traceback) # # def on_stop(self): # self.do_cancel() # # def get_actor(self, name): # fsm = pykka.ActorRegistry.get_by_class_name(name) # if fsm: # return fsm[0].proxy() # logger.critical("Actor %s not found!!!" % name) # return None # # def __do_cancel(self): # if self.__timer: # self.__timer.cancel() # self.__timer = None # # def do_cancel(self): # self.__do_cancel() # # def do_delay(self, delay, method, *args, **kwargs): # assert type(method) == str # assert delay >= 0 # # Stop an already running timer # self.__do_cancel() # func = getattr(self._proxy, method) # if delay > 0: # self.__timer = Timer(delay, func.defer, *args, **kwargs) # self.__timer.start() # else: # func.defer(*args, **kwargs) # # Path: controller/actor.py # def do_repeat(): # def wrap(func): # @functools.wraps(func) # def wrapped_func(self, *args, **kwargs): # try: # func(self, *args, **kwargs) # except StopRepeatException: # pass # else: # method = re.sub("on_enter_", "do_repeat_", func.__name__) # function = getattr(self._proxy, method) # function.defer() # return wrapped_func # return wrap # # Path: controller/util.py # def round_timedelta(x): # return timedelta(seconds=round(x.total_seconds())) # # class Timer(object): # # def __init__(self, name): # self.__duration = timedelta() # self.__name = name # self.__last = None # self.__last_print = datetime(2000, 1, 1) # self.__delay = timedelta() # # @property # def duration(self): # return self.__duration # # @duration.setter # def duration(self, value): # self.__duration = value # # @property # def remaining(self): # return max(timedelta(), self.__delay - self.__duration) # # @property # def delay(self): # return self.__delay # # @delay.setter # def delay(self, value): # self.__delay = value # self.reset() # # def clear(self): # self.__last = None # # def reset(self): # self.clear() # self.__duration = timedelta() # # def update(self, now, factor=1): # if self.__last is not None: # self.__duration += factor * (now - self.__last) # remaining = max(timedelta(), self.delay - self.__duration) # if self.__last_print + timedelta(seconds=20) <= now: # logger.debug("(%s) Timer: %s Remaining: %s" % # (self.__name, self.__duration, remaining)) # self.__last_print = now # self.__last = now # # def elapsed(self): # return self.__duration >= self.__delay # # Path: controller/config.py # class Config: # def __init__(self, config_files): # def __getitem__(self, pair): # def as_list(value, type_cast=int): . Output only the next line.
self.__machine = PoupoolModel(model=self, states=Filtration.states, initial="halt",
Next line prediction: <|code_start|> def __pause(self, now): if now is None: self.__current.delay = max(timedelta(), self.__period - self.__duration) self.__stir_state = False self.__devices.get_pump("boost").off() logger.info("Stir deactivated for %s" % self.__current.remaining) def __stir(self): self.__stir_state = True self.__current.delay = self.__duration self.__devices.get_pump("boost").on() logger.info("Stir activated for %s" % self.__current.remaining) def clear(self, now): self.__pause(now) def update(self, now): self.__current.update(now) # We only activate the stir mode if the sun elevation is greater than ~20°. # No need to stir at night, this mode is meant to lower the solar cover # temperature. if self.__period > timedelta() and self.__current.elapsed(): elevation = sun.elevation(self.__city) if self.__stir_state: self.__pause(None) elif elevation >= StirMode.SOLAR_ELEVATION and self.__duration > timedelta(): self.__stir() <|code_end|> . Use current file imports: (import pykka import time import logging from datetime import datetime, timedelta from astral import geocoder, sun from .actor import PoupoolModel from .actor import PoupoolActor from .actor import do_repeat from .util import round_timedelta, Timer from .config import config from transitions.extensions import HierarchicalGraphMachine) and context including class names, function names, or small code snippets from other files: # Path: controller/actor.py # class PoupoolModel(Machine): # # def __init__(self, *args, **kwargs): # kwargs.setdefault("before_state_change", []).extend(["do_cancel", self.__update_state_time]) # super().__init__( # auto_transitions=False, # ignore_invalid_triggers=True, # *args, # **kwargs # ) # self.__state_time = None # # def __update_state_time(self): # self.__state_time = datetime.now() # # def get_time_in_state(self): # return datetime.now() - self.__state_time # # Path: controller/actor.py # class PoupoolActor(pykka.ThreadingActor): # # def __init__(self): # super().__init__() # self._proxy = self.actor_ref.proxy() # self.__timer = None # # def on_failure(self, exception_type, exception_value, traceback): # # The actor is going to die # logger.fatal(exception_type, exception_value, traceback) # # def on_stop(self): # self.do_cancel() # # def get_actor(self, name): # fsm = pykka.ActorRegistry.get_by_class_name(name) # if fsm: # return fsm[0].proxy() # logger.critical("Actor %s not found!!!" % name) # return None # # def __do_cancel(self): # if self.__timer: # self.__timer.cancel() # self.__timer = None # # def do_cancel(self): # self.__do_cancel() # # def do_delay(self, delay, method, *args, **kwargs): # assert type(method) == str # assert delay >= 0 # # Stop an already running timer # self.__do_cancel() # func = getattr(self._proxy, method) # if delay > 0: # self.__timer = Timer(delay, func.defer, *args, **kwargs) # self.__timer.start() # else: # func.defer(*args, **kwargs) # # Path: controller/actor.py # def do_repeat(): # def wrap(func): # @functools.wraps(func) # def wrapped_func(self, *args, **kwargs): # try: # func(self, *args, **kwargs) # except StopRepeatException: # pass # else: # method = re.sub("on_enter_", "do_repeat_", func.__name__) # function = getattr(self._proxy, method) # function.defer() # return wrapped_func # return wrap # # Path: controller/util.py # def round_timedelta(x): # return timedelta(seconds=round(x.total_seconds())) # # class Timer(object): # # def __init__(self, name): # self.__duration = timedelta() # self.__name = name # self.__last = None # self.__last_print = datetime(2000, 1, 1) # self.__delay = timedelta() # # @property # def duration(self): # return self.__duration # # @duration.setter # def duration(self, value): # self.__duration = value # # @property # def remaining(self): # return max(timedelta(), self.__delay - self.__duration) # # @property # def delay(self): # return self.__delay # # @delay.setter # def delay(self, value): # self.__delay = value # self.reset() # # def clear(self): # self.__last = None # # def reset(self): # self.clear() # self.__duration = timedelta() # # def update(self, now, factor=1): # if self.__last is not None: # self.__duration += factor * (now - self.__last) # remaining = max(timedelta(), self.delay - self.__duration) # if self.__last_print + timedelta(seconds=20) <= now: # logger.debug("(%s) Timer: %s Remaining: %s" % # (self.__name, self.__duration, remaining)) # self.__last_print = now # self.__last = now # # def elapsed(self): # return self.__duration >= self.__delay # # Path: controller/config.py # class Config: # def __init__(self, config_files): # def __getitem__(self, pair): # def as_list(value, type_cast=int): . Output only the next line.
class Filtration(PoupoolActor):
Predict the next line after this snippet: <|code_start|> def __actor_halt(self, name): actor = self.get_actor(name) try: # We have seen situation where this creates a deadlock. We add a timeout so that we # eventually return from the get() and force the halt transition. if not actor.is_halt().get(timeout=1): actor.halt.defer() except pykka.Timeout: actor.halt.defer() def on_enter_halt(self): logger.info("Entering halt state") self.__encoder.filtration_state("halt") self.__actor_halt("Disinfection") self.__actor_halt("Tank") self.__actor_halt("Arduino") self.__actor_halt("Heating") self.__actor_halt("Light") self.__actor_halt("Swim") self.__devices.get_pump("variable").off() self.__devices.get_pump("boost").off() self.__devices.get_valve("gravity").off() self.__devices.get_valve("backwash").off() self.__devices.get_valve("tank").off() self.__devices.get_valve("drain").off() def on_exit_halt(self): logger.info("Exiting halt state") self.__stir_mode.clear(None) <|code_end|> using the current file's imports: import pykka import time import logging from datetime import datetime, timedelta from astral import geocoder, sun from .actor import PoupoolModel from .actor import PoupoolActor from .actor import do_repeat from .util import round_timedelta, Timer from .config import config from transitions.extensions import HierarchicalGraphMachine and any relevant context from other files: # Path: controller/actor.py # class PoupoolModel(Machine): # # def __init__(self, *args, **kwargs): # kwargs.setdefault("before_state_change", []).extend(["do_cancel", self.__update_state_time]) # super().__init__( # auto_transitions=False, # ignore_invalid_triggers=True, # *args, # **kwargs # ) # self.__state_time = None # # def __update_state_time(self): # self.__state_time = datetime.now() # # def get_time_in_state(self): # return datetime.now() - self.__state_time # # Path: controller/actor.py # class PoupoolActor(pykka.ThreadingActor): # # def __init__(self): # super().__init__() # self._proxy = self.actor_ref.proxy() # self.__timer = None # # def on_failure(self, exception_type, exception_value, traceback): # # The actor is going to die # logger.fatal(exception_type, exception_value, traceback) # # def on_stop(self): # self.do_cancel() # # def get_actor(self, name): # fsm = pykka.ActorRegistry.get_by_class_name(name) # if fsm: # return fsm[0].proxy() # logger.critical("Actor %s not found!!!" % name) # return None # # def __do_cancel(self): # if self.__timer: # self.__timer.cancel() # self.__timer = None # # def do_cancel(self): # self.__do_cancel() # # def do_delay(self, delay, method, *args, **kwargs): # assert type(method) == str # assert delay >= 0 # # Stop an already running timer # self.__do_cancel() # func = getattr(self._proxy, method) # if delay > 0: # self.__timer = Timer(delay, func.defer, *args, **kwargs) # self.__timer.start() # else: # func.defer(*args, **kwargs) # # Path: controller/actor.py # def do_repeat(): # def wrap(func): # @functools.wraps(func) # def wrapped_func(self, *args, **kwargs): # try: # func(self, *args, **kwargs) # except StopRepeatException: # pass # else: # method = re.sub("on_enter_", "do_repeat_", func.__name__) # function = getattr(self._proxy, method) # function.defer() # return wrapped_func # return wrap # # Path: controller/util.py # def round_timedelta(x): # return timedelta(seconds=round(x.total_seconds())) # # class Timer(object): # # def __init__(self, name): # self.__duration = timedelta() # self.__name = name # self.__last = None # self.__last_print = datetime(2000, 1, 1) # self.__delay = timedelta() # # @property # def duration(self): # return self.__duration # # @duration.setter # def duration(self, value): # self.__duration = value # # @property # def remaining(self): # return max(timedelta(), self.__delay - self.__duration) # # @property # def delay(self): # return self.__delay # # @delay.setter # def delay(self, value): # self.__delay = value # self.reset() # # def clear(self): # self.__last = None # # def reset(self): # self.clear() # self.__duration = timedelta() # # def update(self, now, factor=1): # if self.__last is not None: # self.__duration += factor * (now - self.__last) # remaining = max(timedelta(), self.delay - self.__duration) # if self.__last_print + timedelta(seconds=20) <= now: # logger.debug("(%s) Timer: %s Remaining: %s" % # (self.__name, self.__duration, remaining)) # self.__last_print = now # self.__last = now # # def elapsed(self): # return self.__duration >= self.__delay # # Path: controller/config.py # class Config: # def __init__(self, config_files): # def __getitem__(self, pair): # def as_list(value, type_cast=int): . Output only the next line.
@do_repeat()
Predict the next line for this snippet: <|code_start|> tm = datetime.now() self.__next_reset = tm.replace(hour=hour, minute=0, second=0, microsecond=0) if self.__next_reset < tm: self.__next_reset += timedelta(days=1) def __recompute_period_duration(self): self.period_duration = self.filtration.delay / self.period assert self.period_duration > timedelta() @property def period(self): return self.__period @period.setter def period(self, value): self.__period = value self.__recompute_period_duration() @property def daily(self): return self.filtration.delay @daily.setter def daily(self, value): self.filtration.delay = value self.__recompute_period_duration() def clear(self): self.filtration.clear() self.current.delay = timedelta() <|code_end|> with the help of current file imports: import pykka import time import logging from datetime import datetime, timedelta from astral import geocoder, sun from .actor import PoupoolModel from .actor import PoupoolActor from .actor import do_repeat from .util import round_timedelta, Timer from .config import config from transitions.extensions import HierarchicalGraphMachine and context from other files: # Path: controller/actor.py # class PoupoolModel(Machine): # # def __init__(self, *args, **kwargs): # kwargs.setdefault("before_state_change", []).extend(["do_cancel", self.__update_state_time]) # super().__init__( # auto_transitions=False, # ignore_invalid_triggers=True, # *args, # **kwargs # ) # self.__state_time = None # # def __update_state_time(self): # self.__state_time = datetime.now() # # def get_time_in_state(self): # return datetime.now() - self.__state_time # # Path: controller/actor.py # class PoupoolActor(pykka.ThreadingActor): # # def __init__(self): # super().__init__() # self._proxy = self.actor_ref.proxy() # self.__timer = None # # def on_failure(self, exception_type, exception_value, traceback): # # The actor is going to die # logger.fatal(exception_type, exception_value, traceback) # # def on_stop(self): # self.do_cancel() # # def get_actor(self, name): # fsm = pykka.ActorRegistry.get_by_class_name(name) # if fsm: # return fsm[0].proxy() # logger.critical("Actor %s not found!!!" % name) # return None # # def __do_cancel(self): # if self.__timer: # self.__timer.cancel() # self.__timer = None # # def do_cancel(self): # self.__do_cancel() # # def do_delay(self, delay, method, *args, **kwargs): # assert type(method) == str # assert delay >= 0 # # Stop an already running timer # self.__do_cancel() # func = getattr(self._proxy, method) # if delay > 0: # self.__timer = Timer(delay, func.defer, *args, **kwargs) # self.__timer.start() # else: # func.defer(*args, **kwargs) # # Path: controller/actor.py # def do_repeat(): # def wrap(func): # @functools.wraps(func) # def wrapped_func(self, *args, **kwargs): # try: # func(self, *args, **kwargs) # except StopRepeatException: # pass # else: # method = re.sub("on_enter_", "do_repeat_", func.__name__) # function = getattr(self._proxy, method) # function.defer() # return wrapped_func # return wrap # # Path: controller/util.py # def round_timedelta(x): # return timedelta(seconds=round(x.total_seconds())) # # class Timer(object): # # def __init__(self, name): # self.__duration = timedelta() # self.__name = name # self.__last = None # self.__last_print = datetime(2000, 1, 1) # self.__delay = timedelta() # # @property # def duration(self): # return self.__duration # # @duration.setter # def duration(self, value): # self.__duration = value # # @property # def remaining(self): # return max(timedelta(), self.__delay - self.__duration) # # @property # def delay(self): # return self.__delay # # @delay.setter # def delay(self, value): # self.__delay = value # self.reset() # # def clear(self): # self.__last = None # # def reset(self): # self.clear() # self.__duration = timedelta() # # def update(self, now, factor=1): # if self.__last is not None: # self.__duration += factor * (now - self.__last) # remaining = max(timedelta(), self.delay - self.__duration) # if self.__last_print + timedelta(seconds=20) <= now: # logger.debug("(%s) Timer: %s Remaining: %s" % # (self.__name, self.__duration, remaining)) # self.__last_print = now # self.__last = now # # def elapsed(self): # return self.__duration >= self.__delay # # Path: controller/config.py # class Config: # def __init__(self, config_files): # def __getitem__(self, pair): # def as_list(value, type_cast=int): , which may contain function names, class names, or code. Output only the next line.
self.__encoder.filtration_next(str(round_timedelta(self.current.remaining)))
Here is a snippet: <|code_start|># Poupool - swimming pool control software # Copyright (C) 2019 Cyril Jaquier # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. logger = logging.getLogger(__name__) class EcoMode(object): def __init__(self, encoder): self.__encoder = encoder <|code_end|> . Write the next line using the current file imports: import pykka import time import logging from datetime import datetime, timedelta from astral import geocoder, sun from .actor import PoupoolModel from .actor import PoupoolActor from .actor import do_repeat from .util import round_timedelta, Timer from .config import config from transitions.extensions import HierarchicalGraphMachine and context from other files: # Path: controller/actor.py # class PoupoolModel(Machine): # # def __init__(self, *args, **kwargs): # kwargs.setdefault("before_state_change", []).extend(["do_cancel", self.__update_state_time]) # super().__init__( # auto_transitions=False, # ignore_invalid_triggers=True, # *args, # **kwargs # ) # self.__state_time = None # # def __update_state_time(self): # self.__state_time = datetime.now() # # def get_time_in_state(self): # return datetime.now() - self.__state_time # # Path: controller/actor.py # class PoupoolActor(pykka.ThreadingActor): # # def __init__(self): # super().__init__() # self._proxy = self.actor_ref.proxy() # self.__timer = None # # def on_failure(self, exception_type, exception_value, traceback): # # The actor is going to die # logger.fatal(exception_type, exception_value, traceback) # # def on_stop(self): # self.do_cancel() # # def get_actor(self, name): # fsm = pykka.ActorRegistry.get_by_class_name(name) # if fsm: # return fsm[0].proxy() # logger.critical("Actor %s not found!!!" % name) # return None # # def __do_cancel(self): # if self.__timer: # self.__timer.cancel() # self.__timer = None # # def do_cancel(self): # self.__do_cancel() # # def do_delay(self, delay, method, *args, **kwargs): # assert type(method) == str # assert delay >= 0 # # Stop an already running timer # self.__do_cancel() # func = getattr(self._proxy, method) # if delay > 0: # self.__timer = Timer(delay, func.defer, *args, **kwargs) # self.__timer.start() # else: # func.defer(*args, **kwargs) # # Path: controller/actor.py # def do_repeat(): # def wrap(func): # @functools.wraps(func) # def wrapped_func(self, *args, **kwargs): # try: # func(self, *args, **kwargs) # except StopRepeatException: # pass # else: # method = re.sub("on_enter_", "do_repeat_", func.__name__) # function = getattr(self._proxy, method) # function.defer() # return wrapped_func # return wrap # # Path: controller/util.py # def round_timedelta(x): # return timedelta(seconds=round(x.total_seconds())) # # class Timer(object): # # def __init__(self, name): # self.__duration = timedelta() # self.__name = name # self.__last = None # self.__last_print = datetime(2000, 1, 1) # self.__delay = timedelta() # # @property # def duration(self): # return self.__duration # # @duration.setter # def duration(self, value): # self.__duration = value # # @property # def remaining(self): # return max(timedelta(), self.__delay - self.__duration) # # @property # def delay(self): # return self.__delay # # @delay.setter # def delay(self, value): # self.__delay = value # self.reset() # # def clear(self): # self.__last = None # # def reset(self): # self.clear() # self.__duration = timedelta() # # def update(self, now, factor=1): # if self.__last is not None: # self.__duration += factor * (now - self.__last) # remaining = max(timedelta(), self.delay - self.__duration) # if self.__last_print + timedelta(seconds=20) <= now: # logger.debug("(%s) Timer: %s Remaining: %s" % # (self.__name, self.__duration, remaining)) # self.__last_print = now # self.__last = now # # def elapsed(self): # return self.__duration >= self.__delay # # Path: controller/config.py # class Config: # def __init__(self, config_files): # def __getitem__(self, pair): # def as_list(value, type_cast=int): , which may include functions, classes, or code. Output only the next line.
self.filtration = Timer("filtration")
Next line prediction: <|code_start|> def update(self, now, factor=1): self.current.update(now) self.filtration.update(now, factor) self.__encoder.filtration_next(str(round_timedelta(self.current.remaining))) seconds = (self.filtration.delay - self.filtration.duration).total_seconds() remaining = max(timedelta(), timedelta(seconds=int(seconds))) self.__encoder.filtration_remaining(str(remaining)) # Check if we reached the daily reset reset = False if now >= self.__next_reset: self.__next_reset += timedelta(days=1) self.filtration.reset() reset = True # Only persist the duration every 5 minutes if (now - self.__duration_last_save) > timedelta(minutes=5) or reset: self.__duration_last_save = now value = str(round(self.filtration.duration.total_seconds())) self.__encoder.filtration_duration(value, retain=True) return reset def elapsed_on(self): return self.current.elapsed() or self.filtration.elapsed() def elapsed_off(self): return self.current.elapsed() and not self.filtration.elapsed() class StirMode(object): <|code_end|> . Use current file imports: (import pykka import time import logging from datetime import datetime, timedelta from astral import geocoder, sun from .actor import PoupoolModel from .actor import PoupoolActor from .actor import do_repeat from .util import round_timedelta, Timer from .config import config from transitions.extensions import HierarchicalGraphMachine) and context including class names, function names, or small code snippets from other files: # Path: controller/actor.py # class PoupoolModel(Machine): # # def __init__(self, *args, **kwargs): # kwargs.setdefault("before_state_change", []).extend(["do_cancel", self.__update_state_time]) # super().__init__( # auto_transitions=False, # ignore_invalid_triggers=True, # *args, # **kwargs # ) # self.__state_time = None # # def __update_state_time(self): # self.__state_time = datetime.now() # # def get_time_in_state(self): # return datetime.now() - self.__state_time # # Path: controller/actor.py # class PoupoolActor(pykka.ThreadingActor): # # def __init__(self): # super().__init__() # self._proxy = self.actor_ref.proxy() # self.__timer = None # # def on_failure(self, exception_type, exception_value, traceback): # # The actor is going to die # logger.fatal(exception_type, exception_value, traceback) # # def on_stop(self): # self.do_cancel() # # def get_actor(self, name): # fsm = pykka.ActorRegistry.get_by_class_name(name) # if fsm: # return fsm[0].proxy() # logger.critical("Actor %s not found!!!" % name) # return None # # def __do_cancel(self): # if self.__timer: # self.__timer.cancel() # self.__timer = None # # def do_cancel(self): # self.__do_cancel() # # def do_delay(self, delay, method, *args, **kwargs): # assert type(method) == str # assert delay >= 0 # # Stop an already running timer # self.__do_cancel() # func = getattr(self._proxy, method) # if delay > 0: # self.__timer = Timer(delay, func.defer, *args, **kwargs) # self.__timer.start() # else: # func.defer(*args, **kwargs) # # Path: controller/actor.py # def do_repeat(): # def wrap(func): # @functools.wraps(func) # def wrapped_func(self, *args, **kwargs): # try: # func(self, *args, **kwargs) # except StopRepeatException: # pass # else: # method = re.sub("on_enter_", "do_repeat_", func.__name__) # function = getattr(self._proxy, method) # function.defer() # return wrapped_func # return wrap # # Path: controller/util.py # def round_timedelta(x): # return timedelta(seconds=round(x.total_seconds())) # # class Timer(object): # # def __init__(self, name): # self.__duration = timedelta() # self.__name = name # self.__last = None # self.__last_print = datetime(2000, 1, 1) # self.__delay = timedelta() # # @property # def duration(self): # return self.__duration # # @duration.setter # def duration(self, value): # self.__duration = value # # @property # def remaining(self): # return max(timedelta(), self.__delay - self.__duration) # # @property # def delay(self): # return self.__delay # # @delay.setter # def delay(self, value): # self.__delay = value # self.reset() # # def clear(self): # self.__last = None # # def reset(self): # self.clear() # self.__duration = timedelta() # # def update(self, now, factor=1): # if self.__last is not None: # self.__duration += factor * (now - self.__last) # remaining = max(timedelta(), self.delay - self.__duration) # if self.__last_print + timedelta(seconds=20) <= now: # logger.debug("(%s) Timer: %s Remaining: %s" % # (self.__name, self.__duration, remaining)) # self.__last_print = now # self.__last = now # # def elapsed(self): # return self.__duration >= self.__delay # # Path: controller/config.py # class Config: # def __init__(self, config_files): # def __getitem__(self, pair): # def as_list(value, type_cast=int): . Output only the next line.
LOCATION = config["misc", "location"]
Here is a snippet: <|code_start|> time.sleep(0.1) except OSError: logger.exception("Unable to read temperature (%s)" % self.name) return None class TankSensorDevice(SensorDevice): def __init__(self, name, adc, channel, gain, low, high): super().__init__(name) self.__adc = adc self.__adc.gain = gain self.__channel = channel self.__low = low self.__high = high @property def value(self): values = [] for _ in range(10): try: values.append(self.__adc.read(self.__channel)) time.sleep(0.05) except OSError: logger.exception("Unable to read ADC %s" % self.name) time.sleep(0.5) # In case we got really no readings, we return 0 in order for the system to go into # emergency stop. value = sum(values) / len(values) if values else 0 logger.debug("Tank sensor average ADC=%.2f" % value) <|code_end|> . Write the next line using the current file imports: import time import logging import re import serial import io import subprocess from abc import abstractmethod, ABC from .util import mapping, constrain from lcdbackpack import LcdBackpack and context from other files: # Path: controller/util.py # def mapping(x, in_min, in_max, out_min, out_max): # return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min # # def constrain(x, out_min, out_max): # return min(max(x, out_min), out_max) , which may include functions, classes, or code. Output only the next line.
return constrain(mapping(value, self.__low, self.__high, 0, 100), 0, 100)
Given snippet: <|code_start|> time.sleep(0.1) except OSError: logger.exception("Unable to read temperature (%s)" % self.name) return None class TankSensorDevice(SensorDevice): def __init__(self, name, adc, channel, gain, low, high): super().__init__(name) self.__adc = adc self.__adc.gain = gain self.__channel = channel self.__low = low self.__high = high @property def value(self): values = [] for _ in range(10): try: values.append(self.__adc.read(self.__channel)) time.sleep(0.05) except OSError: logger.exception("Unable to read ADC %s" % self.name) time.sleep(0.5) # In case we got really no readings, we return 0 in order for the system to go into # emergency stop. value = sum(values) / len(values) if values else 0 logger.debug("Tank sensor average ADC=%.2f" % value) <|code_end|> , continue by predicting the next line. Consider current file imports: import time import logging import re import serial import io import subprocess from abc import abstractmethod, ABC from .util import mapping, constrain from lcdbackpack import LcdBackpack and context: # Path: controller/util.py # def mapping(x, in_min, in_max, out_min, out_max): # return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min # # def constrain(x, out_min, out_max): # return min(max(x, out_min), out_max) which might include code, classes, or functions. Output only the next line.
return constrain(mapping(value, self.__low, self.__high, 0, 100), 0, 100)
Given the code snippet: <|code_start|># with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # from transitions.extensions import GraphMachine as Machine logger = logging.getLogger(__name__) class Swim(PoupoolActor): STATE_REFRESH_DELAY = 1 # faster refresh rate because speed can change WINTERING_PERIOD = int(config["wintering", "swim_period"]) WINTERING_ONLY_BELOW = float(config["wintering", "swim_only_below"]) WINTERING_DURATION = int(config["wintering", "swim_duration"]) states = ["halt", "timed", "continuous", {"name": "wintering", "initial": "waiting", "children": [ "stir", "waiting"]}] def __init__(self, temperature, encoder, devices): super().__init__() self.__temperature = temperature self.__encoder = encoder self.__devices = devices self.__timer = Timer("swim") self.__speed = 50 # Initialize the state machine <|code_end|> , generate the next line using the imports in this file: import logging from datetime import datetime, timedelta from .actor import PoupoolActor from .actor import PoupoolModel from .actor import do_repeat from .util import Timer from .config import config and context (functions, classes, or occasionally code) from other files: # Path: controller/actor.py # class PoupoolActor(pykka.ThreadingActor): # # def __init__(self): # super().__init__() # self._proxy = self.actor_ref.proxy() # self.__timer = None # # def on_failure(self, exception_type, exception_value, traceback): # # The actor is going to die # logger.fatal(exception_type, exception_value, traceback) # # def on_stop(self): # self.do_cancel() # # def get_actor(self, name): # fsm = pykka.ActorRegistry.get_by_class_name(name) # if fsm: # return fsm[0].proxy() # logger.critical("Actor %s not found!!!" % name) # return None # # def __do_cancel(self): # if self.__timer: # self.__timer.cancel() # self.__timer = None # # def do_cancel(self): # self.__do_cancel() # # def do_delay(self, delay, method, *args, **kwargs): # assert type(method) == str # assert delay >= 0 # # Stop an already running timer # self.__do_cancel() # func = getattr(self._proxy, method) # if delay > 0: # self.__timer = Timer(delay, func.defer, *args, **kwargs) # self.__timer.start() # else: # func.defer(*args, **kwargs) # # Path: controller/actor.py # class PoupoolModel(Machine): # # def __init__(self, *args, **kwargs): # kwargs.setdefault("before_state_change", []).extend(["do_cancel", self.__update_state_time]) # super().__init__( # auto_transitions=False, # ignore_invalid_triggers=True, # *args, # **kwargs # ) # self.__state_time = None # # def __update_state_time(self): # self.__state_time = datetime.now() # # def get_time_in_state(self): # return datetime.now() - self.__state_time # # Path: controller/actor.py # def do_repeat(): # def wrap(func): # @functools.wraps(func) # def wrapped_func(self, *args, **kwargs): # try: # func(self, *args, **kwargs) # except StopRepeatException: # pass # else: # method = re.sub("on_enter_", "do_repeat_", func.__name__) # function = getattr(self._proxy, method) # function.defer() # return wrapped_func # return wrap # # Path: controller/util.py # class Timer(object): # # def __init__(self, name): # self.__duration = timedelta() # self.__name = name # self.__last = None # self.__last_print = datetime(2000, 1, 1) # self.__delay = timedelta() # # @property # def duration(self): # return self.__duration # # @duration.setter # def duration(self, value): # self.__duration = value # # @property # def remaining(self): # return max(timedelta(), self.__delay - self.__duration) # # @property # def delay(self): # return self.__delay # # @delay.setter # def delay(self, value): # self.__delay = value # self.reset() # # def clear(self): # self.__last = None # # def reset(self): # self.clear() # self.__duration = timedelta() # # def update(self, now, factor=1): # if self.__last is not None: # self.__duration += factor * (now - self.__last) # remaining = max(timedelta(), self.delay - self.__duration) # if self.__last_print + timedelta(seconds=20) <= now: # logger.debug("(%s) Timer: %s Remaining: %s" % # (self.__name, self.__duration, remaining)) # self.__last_print = now # self.__last = now # # def elapsed(self): # return self.__duration >= self.__delay # # Path: controller/config.py # class Config: # def __init__(self, config_files): # def __getitem__(self, pair): # def as_list(value, type_cast=int): . Output only the next line.
self.__machine = PoupoolModel(model=self, states=Swim.states, initial="halt")
Given snippet: <|code_start|> conditions="filtration_allow_swim") self.__machine.add_transition("continuous", "halt", "continuous", conditions="filtration_allow_swim") self.__machine.add_transition("continuous", "timed", "continuous", conditions="filtration_allow_swim") self.__machine.add_transition("halt", ["timed", "continuous", "wintering"], "halt") def timer(self, value): self.__timer.delay = timedelta(minutes=value) logger.info("Timer for swim set to: %s" % self.__timer.delay) def speed(self, value): self.__speed = value logger.info("Speed for swim pump set to: %d" % self.__speed) def filtration_allow_swim(self): actor = self.get_actor("Filtration") is_opened = actor.is_overflow_normal().get() or actor.is_standby_normal().get() is_opened = is_opened or actor.is_comfort().get() return is_opened or self.filtration_is_wintering() def filtration_is_wintering(self): actor = self.get_actor("Filtration") return actor.is_wintering_waiting().get() or actor.is_wintering_stir().get() def on_enter_halt(self): logger.info("Entering halt state") self.__encoder.swim_state("halt") self.__devices.get_pump("swim").off() <|code_end|> , continue by predicting the next line. Consider current file imports: import logging from datetime import datetime, timedelta from .actor import PoupoolActor from .actor import PoupoolModel from .actor import do_repeat from .util import Timer from .config import config and context: # Path: controller/actor.py # class PoupoolActor(pykka.ThreadingActor): # # def __init__(self): # super().__init__() # self._proxy = self.actor_ref.proxy() # self.__timer = None # # def on_failure(self, exception_type, exception_value, traceback): # # The actor is going to die # logger.fatal(exception_type, exception_value, traceback) # # def on_stop(self): # self.do_cancel() # # def get_actor(self, name): # fsm = pykka.ActorRegistry.get_by_class_name(name) # if fsm: # return fsm[0].proxy() # logger.critical("Actor %s not found!!!" % name) # return None # # def __do_cancel(self): # if self.__timer: # self.__timer.cancel() # self.__timer = None # # def do_cancel(self): # self.__do_cancel() # # def do_delay(self, delay, method, *args, **kwargs): # assert type(method) == str # assert delay >= 0 # # Stop an already running timer # self.__do_cancel() # func = getattr(self._proxy, method) # if delay > 0: # self.__timer = Timer(delay, func.defer, *args, **kwargs) # self.__timer.start() # else: # func.defer(*args, **kwargs) # # Path: controller/actor.py # class PoupoolModel(Machine): # # def __init__(self, *args, **kwargs): # kwargs.setdefault("before_state_change", []).extend(["do_cancel", self.__update_state_time]) # super().__init__( # auto_transitions=False, # ignore_invalid_triggers=True, # *args, # **kwargs # ) # self.__state_time = None # # def __update_state_time(self): # self.__state_time = datetime.now() # # def get_time_in_state(self): # return datetime.now() - self.__state_time # # Path: controller/actor.py # def do_repeat(): # def wrap(func): # @functools.wraps(func) # def wrapped_func(self, *args, **kwargs): # try: # func(self, *args, **kwargs) # except StopRepeatException: # pass # else: # method = re.sub("on_enter_", "do_repeat_", func.__name__) # function = getattr(self._proxy, method) # function.defer() # return wrapped_func # return wrap # # Path: controller/util.py # class Timer(object): # # def __init__(self, name): # self.__duration = timedelta() # self.__name = name # self.__last = None # self.__last_print = datetime(2000, 1, 1) # self.__delay = timedelta() # # @property # def duration(self): # return self.__duration # # @duration.setter # def duration(self, value): # self.__duration = value # # @property # def remaining(self): # return max(timedelta(), self.__delay - self.__duration) # # @property # def delay(self): # return self.__delay # # @delay.setter # def delay(self, value): # self.__delay = value # self.reset() # # def clear(self): # self.__last = None # # def reset(self): # self.clear() # self.__duration = timedelta() # # def update(self, now, factor=1): # if self.__last is not None: # self.__duration += factor * (now - self.__last) # remaining = max(timedelta(), self.delay - self.__duration) # if self.__last_print + timedelta(seconds=20) <= now: # logger.debug("(%s) Timer: %s Remaining: %s" % # (self.__name, self.__duration, remaining)) # self.__last_print = now # self.__last = now # # def elapsed(self): # return self.__duration >= self.__delay # # Path: controller/config.py # class Config: # def __init__(self, config_files): # def __getitem__(self, pair): # def as_list(value, type_cast=int): which might include code, classes, or functions. Output only the next line.
@do_repeat()
Using the snippet: <|code_start|># GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # from transitions.extensions import GraphMachine as Machine logger = logging.getLogger(__name__) class Swim(PoupoolActor): STATE_REFRESH_DELAY = 1 # faster refresh rate because speed can change WINTERING_PERIOD = int(config["wintering", "swim_period"]) WINTERING_ONLY_BELOW = float(config["wintering", "swim_only_below"]) WINTERING_DURATION = int(config["wintering", "swim_duration"]) states = ["halt", "timed", "continuous", {"name": "wintering", "initial": "waiting", "children": [ "stir", "waiting"]}] def __init__(self, temperature, encoder, devices): super().__init__() self.__temperature = temperature self.__encoder = encoder self.__devices = devices <|code_end|> , determine the next line of code. You have imports: import logging from datetime import datetime, timedelta from .actor import PoupoolActor from .actor import PoupoolModel from .actor import do_repeat from .util import Timer from .config import config and context (class names, function names, or code) available: # Path: controller/actor.py # class PoupoolActor(pykka.ThreadingActor): # # def __init__(self): # super().__init__() # self._proxy = self.actor_ref.proxy() # self.__timer = None # # def on_failure(self, exception_type, exception_value, traceback): # # The actor is going to die # logger.fatal(exception_type, exception_value, traceback) # # def on_stop(self): # self.do_cancel() # # def get_actor(self, name): # fsm = pykka.ActorRegistry.get_by_class_name(name) # if fsm: # return fsm[0].proxy() # logger.critical("Actor %s not found!!!" % name) # return None # # def __do_cancel(self): # if self.__timer: # self.__timer.cancel() # self.__timer = None # # def do_cancel(self): # self.__do_cancel() # # def do_delay(self, delay, method, *args, **kwargs): # assert type(method) == str # assert delay >= 0 # # Stop an already running timer # self.__do_cancel() # func = getattr(self._proxy, method) # if delay > 0: # self.__timer = Timer(delay, func.defer, *args, **kwargs) # self.__timer.start() # else: # func.defer(*args, **kwargs) # # Path: controller/actor.py # class PoupoolModel(Machine): # # def __init__(self, *args, **kwargs): # kwargs.setdefault("before_state_change", []).extend(["do_cancel", self.__update_state_time]) # super().__init__( # auto_transitions=False, # ignore_invalid_triggers=True, # *args, # **kwargs # ) # self.__state_time = None # # def __update_state_time(self): # self.__state_time = datetime.now() # # def get_time_in_state(self): # return datetime.now() - self.__state_time # # Path: controller/actor.py # def do_repeat(): # def wrap(func): # @functools.wraps(func) # def wrapped_func(self, *args, **kwargs): # try: # func(self, *args, **kwargs) # except StopRepeatException: # pass # else: # method = re.sub("on_enter_", "do_repeat_", func.__name__) # function = getattr(self._proxy, method) # function.defer() # return wrapped_func # return wrap # # Path: controller/util.py # class Timer(object): # # def __init__(self, name): # self.__duration = timedelta() # self.__name = name # self.__last = None # self.__last_print = datetime(2000, 1, 1) # self.__delay = timedelta() # # @property # def duration(self): # return self.__duration # # @duration.setter # def duration(self, value): # self.__duration = value # # @property # def remaining(self): # return max(timedelta(), self.__delay - self.__duration) # # @property # def delay(self): # return self.__delay # # @delay.setter # def delay(self, value): # self.__delay = value # self.reset() # # def clear(self): # self.__last = None # # def reset(self): # self.clear() # self.__duration = timedelta() # # def update(self, now, factor=1): # if self.__last is not None: # self.__duration += factor * (now - self.__last) # remaining = max(timedelta(), self.delay - self.__duration) # if self.__last_print + timedelta(seconds=20) <= now: # logger.debug("(%s) Timer: %s Remaining: %s" % # (self.__name, self.__duration, remaining)) # self.__last_print = now # self.__last = now # # def elapsed(self): # return self.__duration >= self.__delay # # Path: controller/config.py # class Config: # def __init__(self, config_files): # def __getitem__(self, pair): # def as_list(value, type_cast=int): . Output only the next line.
self.__timer = Timer("swim")
Continue the code snippet: <|code_start|># Poupool - swimming pool control software # Copyright (C) 2019 Cyril Jaquier # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # from transitions.extensions import GraphMachine as Machine logger = logging.getLogger(__name__) class Swim(PoupoolActor): STATE_REFRESH_DELAY = 1 # faster refresh rate because speed can change <|code_end|> . Use current file imports: import logging from datetime import datetime, timedelta from .actor import PoupoolActor from .actor import PoupoolModel from .actor import do_repeat from .util import Timer from .config import config and context (classes, functions, or code) from other files: # Path: controller/actor.py # class PoupoolActor(pykka.ThreadingActor): # # def __init__(self): # super().__init__() # self._proxy = self.actor_ref.proxy() # self.__timer = None # # def on_failure(self, exception_type, exception_value, traceback): # # The actor is going to die # logger.fatal(exception_type, exception_value, traceback) # # def on_stop(self): # self.do_cancel() # # def get_actor(self, name): # fsm = pykka.ActorRegistry.get_by_class_name(name) # if fsm: # return fsm[0].proxy() # logger.critical("Actor %s not found!!!" % name) # return None # # def __do_cancel(self): # if self.__timer: # self.__timer.cancel() # self.__timer = None # # def do_cancel(self): # self.__do_cancel() # # def do_delay(self, delay, method, *args, **kwargs): # assert type(method) == str # assert delay >= 0 # # Stop an already running timer # self.__do_cancel() # func = getattr(self._proxy, method) # if delay > 0: # self.__timer = Timer(delay, func.defer, *args, **kwargs) # self.__timer.start() # else: # func.defer(*args, **kwargs) # # Path: controller/actor.py # class PoupoolModel(Machine): # # def __init__(self, *args, **kwargs): # kwargs.setdefault("before_state_change", []).extend(["do_cancel", self.__update_state_time]) # super().__init__( # auto_transitions=False, # ignore_invalid_triggers=True, # *args, # **kwargs # ) # self.__state_time = None # # def __update_state_time(self): # self.__state_time = datetime.now() # # def get_time_in_state(self): # return datetime.now() - self.__state_time # # Path: controller/actor.py # def do_repeat(): # def wrap(func): # @functools.wraps(func) # def wrapped_func(self, *args, **kwargs): # try: # func(self, *args, **kwargs) # except StopRepeatException: # pass # else: # method = re.sub("on_enter_", "do_repeat_", func.__name__) # function = getattr(self._proxy, method) # function.defer() # return wrapped_func # return wrap # # Path: controller/util.py # class Timer(object): # # def __init__(self, name): # self.__duration = timedelta() # self.__name = name # self.__last = None # self.__last_print = datetime(2000, 1, 1) # self.__delay = timedelta() # # @property # def duration(self): # return self.__duration # # @duration.setter # def duration(self, value): # self.__duration = value # # @property # def remaining(self): # return max(timedelta(), self.__delay - self.__duration) # # @property # def delay(self): # return self.__delay # # @delay.setter # def delay(self, value): # self.__delay = value # self.reset() # # def clear(self): # self.__last = None # # def reset(self): # self.clear() # self.__duration = timedelta() # # def update(self, now, factor=1): # if self.__last is not None: # self.__duration += factor * (now - self.__last) # remaining = max(timedelta(), self.delay - self.__duration) # if self.__last_print + timedelta(seconds=20) <= now: # logger.debug("(%s) Timer: %s Remaining: %s" % # (self.__name, self.__duration, remaining)) # self.__last_print = now # self.__last = now # # def elapsed(self): # return self.__duration >= self.__delay # # Path: controller/config.py # class Config: # def __init__(self, config_files): # def __getitem__(self, pair): # def as_list(value, type_cast=int): . Output only the next line.
WINTERING_PERIOD = int(config["wintering", "swim_period"])
Given the code snippet: <|code_start|># This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # from transitions.extensions import GraphMachine as Machine logger = logging.getLogger(__name__) class Light(PoupoolActor): STATE_REFRESH_DELAY = 10 states = ["halt", "on"] def __init__(self, encoder, devices): super().__init__() self.__encoder = encoder self.__devices = devices # Initialize the state machine <|code_end|> , generate the next line using the imports in this file: import logging from .actor import PoupoolActor from .actor import PoupoolModel and context (functions, classes, or occasionally code) from other files: # Path: controller/actor.py # class PoupoolActor(pykka.ThreadingActor): # # def __init__(self): # super().__init__() # self._proxy = self.actor_ref.proxy() # self.__timer = None # # def on_failure(self, exception_type, exception_value, traceback): # # The actor is going to die # logger.fatal(exception_type, exception_value, traceback) # # def on_stop(self): # self.do_cancel() # # def get_actor(self, name): # fsm = pykka.ActorRegistry.get_by_class_name(name) # if fsm: # return fsm[0].proxy() # logger.critical("Actor %s not found!!!" % name) # return None # # def __do_cancel(self): # if self.__timer: # self.__timer.cancel() # self.__timer = None # # def do_cancel(self): # self.__do_cancel() # # def do_delay(self, delay, method, *args, **kwargs): # assert type(method) == str # assert delay >= 0 # # Stop an already running timer # self.__do_cancel() # func = getattr(self._proxy, method) # if delay > 0: # self.__timer = Timer(delay, func.defer, *args, **kwargs) # self.__timer.start() # else: # func.defer(*args, **kwargs) # # Path: controller/actor.py # class PoupoolModel(Machine): # # def __init__(self, *args, **kwargs): # kwargs.setdefault("before_state_change", []).extend(["do_cancel", self.__update_state_time]) # super().__init__( # auto_transitions=False, # ignore_invalid_triggers=True, # *args, # **kwargs # ) # self.__state_time = None # # def __update_state_time(self): # self.__state_time = datetime.now() # # def get_time_in_state(self): # return datetime.now() - self.__state_time . Output only the next line.
self.__machine = PoupoolModel(model=self, states=Light.states, initial="halt")
Using the snippet: <|code_start|># the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # from transitions.extensions import GraphMachine as Machine logger = logging.getLogger(__name__) class Arduino(PoupoolActor): STATE_REFRESH_DELAY = 60 states = ["halt", "run"] def __init__(self, encoder, devices): super().__init__() self.__encoder = encoder self.__arduino = devices.get_device("arduino") self.__water_counter = 0 self.__water_counter_last = None # Initialize the state machine <|code_end|> , determine the next line of code. You have imports: import logging from .actor import PoupoolActor from .actor import PoupoolModel from .actor import do_repeat and context (class names, function names, or code) available: # Path: controller/actor.py # class PoupoolActor(pykka.ThreadingActor): # # def __init__(self): # super().__init__() # self._proxy = self.actor_ref.proxy() # self.__timer = None # # def on_failure(self, exception_type, exception_value, traceback): # # The actor is going to die # logger.fatal(exception_type, exception_value, traceback) # # def on_stop(self): # self.do_cancel() # # def get_actor(self, name): # fsm = pykka.ActorRegistry.get_by_class_name(name) # if fsm: # return fsm[0].proxy() # logger.critical("Actor %s not found!!!" % name) # return None # # def __do_cancel(self): # if self.__timer: # self.__timer.cancel() # self.__timer = None # # def do_cancel(self): # self.__do_cancel() # # def do_delay(self, delay, method, *args, **kwargs): # assert type(method) == str # assert delay >= 0 # # Stop an already running timer # self.__do_cancel() # func = getattr(self._proxy, method) # if delay > 0: # self.__timer = Timer(delay, func.defer, *args, **kwargs) # self.__timer.start() # else: # func.defer(*args, **kwargs) # # Path: controller/actor.py # class PoupoolModel(Machine): # # def __init__(self, *args, **kwargs): # kwargs.setdefault("before_state_change", []).extend(["do_cancel", self.__update_state_time]) # super().__init__( # auto_transitions=False, # ignore_invalid_triggers=True, # *args, # **kwargs # ) # self.__state_time = None # # def __update_state_time(self): # self.__state_time = datetime.now() # # def get_time_in_state(self): # return datetime.now() - self.__state_time # # Path: controller/actor.py # def do_repeat(): # def wrap(func): # @functools.wraps(func) # def wrapped_func(self, *args, **kwargs): # try: # func(self, *args, **kwargs) # except StopRepeatException: # pass # else: # method = re.sub("on_enter_", "do_repeat_", func.__name__) # function = getattr(self._proxy, method) # function.defer() # return wrapped_func # return wrap . Output only the next line.
self.__machine = PoupoolModel(model=self, states=Arduino.states, initial="halt")
Using the snippet: <|code_start|> self.__water_counter_last = None # Initialize the state machine self.__machine = PoupoolModel(model=self, states=Arduino.states, initial="halt") self.__machine.add_transition("run", "halt", "run") self.__machine.add_transition("halt", "run", "halt") def restore_water_counter(self, value): self.__water_counter = value logger.info("Water counter set to: %d" % self.__water_counter) def cover_open(self): self.__arduino.cover_open() def cover_close(self): self.__arduino.cover_close() def cover_stop(self): self.__arduino.cover_stop() def cover_position(self): return self.__arduino.cover_position def water_counter(self): return self.__water_counter def on_enter_halt(self): logger.info("Entering halt state") self.cover_stop() <|code_end|> , determine the next line of code. You have imports: import logging from .actor import PoupoolActor from .actor import PoupoolModel from .actor import do_repeat and context (class names, function names, or code) available: # Path: controller/actor.py # class PoupoolActor(pykka.ThreadingActor): # # def __init__(self): # super().__init__() # self._proxy = self.actor_ref.proxy() # self.__timer = None # # def on_failure(self, exception_type, exception_value, traceback): # # The actor is going to die # logger.fatal(exception_type, exception_value, traceback) # # def on_stop(self): # self.do_cancel() # # def get_actor(self, name): # fsm = pykka.ActorRegistry.get_by_class_name(name) # if fsm: # return fsm[0].proxy() # logger.critical("Actor %s not found!!!" % name) # return None # # def __do_cancel(self): # if self.__timer: # self.__timer.cancel() # self.__timer = None # # def do_cancel(self): # self.__do_cancel() # # def do_delay(self, delay, method, *args, **kwargs): # assert type(method) == str # assert delay >= 0 # # Stop an already running timer # self.__do_cancel() # func = getattr(self._proxy, method) # if delay > 0: # self.__timer = Timer(delay, func.defer, *args, **kwargs) # self.__timer.start() # else: # func.defer(*args, **kwargs) # # Path: controller/actor.py # class PoupoolModel(Machine): # # def __init__(self, *args, **kwargs): # kwargs.setdefault("before_state_change", []).extend(["do_cancel", self.__update_state_time]) # super().__init__( # auto_transitions=False, # ignore_invalid_triggers=True, # *args, # **kwargs # ) # self.__state_time = None # # def __update_state_time(self): # self.__state_time = datetime.now() # # def get_time_in_state(self): # return datetime.now() - self.__state_time # # Path: controller/actor.py # def do_repeat(): # def wrap(func): # @functools.wraps(func) # def wrapped_func(self, *args, **kwargs): # try: # func(self, *args, **kwargs) # except StopRepeatException: # pass # else: # method = re.sub("on_enter_", "do_repeat_", func.__name__) # function = getattr(self._proxy, method) # function.defer() # return wrapped_func # return wrap . Output only the next line.
@do_repeat()
Given snippet: <|code_start|># but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. logger = logging.getLogger(__name__) class MovingAverage: def __init__(self, maxlen): self.__data = collections.deque(maxlen=maxlen) def clear(self): self.__data.clear() def push(self, value): self.__data.append(value) def all(self): return list(self.__data) def mean(self): return statistics.mean(self.__data) if self.__data else None <|code_end|> , continue by predicting the next line. Consider current file imports: import logging import statistics import collections from .actor import PoupoolActor from datetime import timedelta and context: # Path: controller/actor.py # class PoupoolActor(pykka.ThreadingActor): # # def __init__(self): # super().__init__() # self._proxy = self.actor_ref.proxy() # self.__timer = None # # def on_failure(self, exception_type, exception_value, traceback): # # The actor is going to die # logger.fatal(exception_type, exception_value, traceback) # # def on_stop(self): # self.do_cancel() # # def get_actor(self, name): # fsm = pykka.ActorRegistry.get_by_class_name(name) # if fsm: # return fsm[0].proxy() # logger.critical("Actor %s not found!!!" % name) # return None # # def __do_cancel(self): # if self.__timer: # self.__timer.cancel() # self.__timer = None # # def do_cancel(self): # self.__do_cancel() # # def do_delay(self, delay, method, *args, **kwargs): # assert type(method) == str # assert delay >= 0 # # Stop an already running timer # self.__do_cancel() # func = getattr(self._proxy, method) # if delay > 0: # self.__timer = Timer(delay, func.defer, *args, **kwargs) # self.__timer.start() # else: # func.defer(*args, **kwargs) which might include code, classes, or functions. Output only the next line.
class BaseReader(PoupoolActor):
Given snippet: <|code_start|># the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. logger = logging.getLogger(__name__) class Heater(PoupoolActor): STATE_REFRESH_DELAY = 10 HYSTERESIS_DOWN = float(config["heater", "hysteresis_down"]) HYSTERESIS_UP = float(config["heater", "hysteresis_up"]) states = ["halt", "waiting", "heating"] def __init__(self, temperature, heater): super().__init__() self.__temperature = temperature self.__heater = heater self.__setpoint = 5.0 # Initialize the state machine <|code_end|> , continue by predicting the next line. Consider current file imports: import logging from datetime import datetime, timedelta from .actor import PoupoolActor from .actor import PoupoolModel from .actor import do_repeat from .config import config from .util import Duration and context: # Path: controller/actor.py # class PoupoolActor(pykka.ThreadingActor): # # def __init__(self): # super().__init__() # self._proxy = self.actor_ref.proxy() # self.__timer = None # # def on_failure(self, exception_type, exception_value, traceback): # # The actor is going to die # logger.fatal(exception_type, exception_value, traceback) # # def on_stop(self): # self.do_cancel() # # def get_actor(self, name): # fsm = pykka.ActorRegistry.get_by_class_name(name) # if fsm: # return fsm[0].proxy() # logger.critical("Actor %s not found!!!" % name) # return None # # def __do_cancel(self): # if self.__timer: # self.__timer.cancel() # self.__timer = None # # def do_cancel(self): # self.__do_cancel() # # def do_delay(self, delay, method, *args, **kwargs): # assert type(method) == str # assert delay >= 0 # # Stop an already running timer # self.__do_cancel() # func = getattr(self._proxy, method) # if delay > 0: # self.__timer = Timer(delay, func.defer, *args, **kwargs) # self.__timer.start() # else: # func.defer(*args, **kwargs) # # Path: controller/actor.py # class PoupoolModel(Machine): # # def __init__(self, *args, **kwargs): # kwargs.setdefault("before_state_change", []).extend(["do_cancel", self.__update_state_time]) # super().__init__( # auto_transitions=False, # ignore_invalid_triggers=True, # *args, # **kwargs # ) # self.__state_time = None # # def __update_state_time(self): # self.__state_time = datetime.now() # # def get_time_in_state(self): # return datetime.now() - self.__state_time # # Path: controller/actor.py # def do_repeat(): # def wrap(func): # @functools.wraps(func) # def wrapped_func(self, *args, **kwargs): # try: # func(self, *args, **kwargs) # except StopRepeatException: # pass # else: # method = re.sub("on_enter_", "do_repeat_", func.__name__) # function = getattr(self._proxy, method) # function.defer() # return wrapped_func # return wrap # # Path: controller/config.py # class Config: # def __init__(self, config_files): # def __getitem__(self, pair): # def as_list(value, type_cast=int): # # Path: controller/util.py # class Duration(object): # # def __init__(self, name): # self.__name = name # self.__total_duration = timedelta() # self.__start = datetime.now() # self.__callback = None # # def set_callback(self, callback): # self.__callback = callback # # def init(self, value): # assert isinstance(value, timedelta) # self.__total_duration = value # # @property # def duration(self): # return self.__total_duration # # def start(self, value=None): # value = value or datetime.now() # assert isinstance(value, datetime) # self.__start = value # # def stop(self, value=None): # value = value or datetime.now() # assert isinstance(value, datetime) # diff = value - self.__start # assert diff > timedelta() # self.__total_duration += diff # if self.__callback: # self.__callback(self.__total_duration) which might include code, classes, or functions. Output only the next line.
self.__machine = PoupoolModel(model=self, states=Heating.states, initial="halt")
Next line prediction: <|code_start|> states = ["halt", "waiting", "heating"] def __init__(self, temperature, heater): super().__init__() self.__temperature = temperature self.__heater = heater self.__setpoint = 5.0 # Initialize the state machine self.__machine = PoupoolModel(model=self, states=Heating.states, initial="halt") self.__machine.add_transition( "wait", ["halt", "heating"], "waiting", conditions="has_heater") self.__machine.add_transition("heat", "waiting", "heating") self.__machine.add_transition("halt", ["waiting", "heating"], "halt") def __read_temperature(self): return self.__temperature.get_temperature("temperature_local").get() def has_heater(self): return self.__heater is not None def setpoint(self, value): self.__setpoint = value logger.info("Setpoint set to %.1f" % self.__setpoint) def on_enter_halt(self): logger.info("Entering halt state") self.__heater.off() <|code_end|> . Use current file imports: (import logging from datetime import datetime, timedelta from .actor import PoupoolActor from .actor import PoupoolModel from .actor import do_repeat from .config import config from .util import Duration) and context including class names, function names, or small code snippets from other files: # Path: controller/actor.py # class PoupoolActor(pykka.ThreadingActor): # # def __init__(self): # super().__init__() # self._proxy = self.actor_ref.proxy() # self.__timer = None # # def on_failure(self, exception_type, exception_value, traceback): # # The actor is going to die # logger.fatal(exception_type, exception_value, traceback) # # def on_stop(self): # self.do_cancel() # # def get_actor(self, name): # fsm = pykka.ActorRegistry.get_by_class_name(name) # if fsm: # return fsm[0].proxy() # logger.critical("Actor %s not found!!!" % name) # return None # # def __do_cancel(self): # if self.__timer: # self.__timer.cancel() # self.__timer = None # # def do_cancel(self): # self.__do_cancel() # # def do_delay(self, delay, method, *args, **kwargs): # assert type(method) == str # assert delay >= 0 # # Stop an already running timer # self.__do_cancel() # func = getattr(self._proxy, method) # if delay > 0: # self.__timer = Timer(delay, func.defer, *args, **kwargs) # self.__timer.start() # else: # func.defer(*args, **kwargs) # # Path: controller/actor.py # class PoupoolModel(Machine): # # def __init__(self, *args, **kwargs): # kwargs.setdefault("before_state_change", []).extend(["do_cancel", self.__update_state_time]) # super().__init__( # auto_transitions=False, # ignore_invalid_triggers=True, # *args, # **kwargs # ) # self.__state_time = None # # def __update_state_time(self): # self.__state_time = datetime.now() # # def get_time_in_state(self): # return datetime.now() - self.__state_time # # Path: controller/actor.py # def do_repeat(): # def wrap(func): # @functools.wraps(func) # def wrapped_func(self, *args, **kwargs): # try: # func(self, *args, **kwargs) # except StopRepeatException: # pass # else: # method = re.sub("on_enter_", "do_repeat_", func.__name__) # function = getattr(self._proxy, method) # function.defer() # return wrapped_func # return wrap # # Path: controller/config.py # class Config: # def __init__(self, config_files): # def __getitem__(self, pair): # def as_list(value, type_cast=int): # # Path: controller/util.py # class Duration(object): # # def __init__(self, name): # self.__name = name # self.__total_duration = timedelta() # self.__start = datetime.now() # self.__callback = None # # def set_callback(self, callback): # self.__callback = callback # # def init(self, value): # assert isinstance(value, timedelta) # self.__total_duration = value # # @property # def duration(self): # return self.__total_duration # # def start(self, value=None): # value = value or datetime.now() # assert isinstance(value, datetime) # self.__start = value # # def stop(self, value=None): # value = value or datetime.now() # assert isinstance(value, datetime) # diff = value - self.__start # assert diff > timedelta() # self.__total_duration += diff # if self.__callback: # self.__callback(self.__total_duration) . Output only the next line.
@do_repeat()
Continue the code snippet: <|code_start|># Poupool - swimming pool control software # Copyright (C) 2019 Cyril Jaquier # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. logger = logging.getLogger(__name__) class Heater(PoupoolActor): STATE_REFRESH_DELAY = 10 <|code_end|> . Use current file imports: import logging from datetime import datetime, timedelta from .actor import PoupoolActor from .actor import PoupoolModel from .actor import do_repeat from .config import config from .util import Duration and context (classes, functions, or code) from other files: # Path: controller/actor.py # class PoupoolActor(pykka.ThreadingActor): # # def __init__(self): # super().__init__() # self._proxy = self.actor_ref.proxy() # self.__timer = None # # def on_failure(self, exception_type, exception_value, traceback): # # The actor is going to die # logger.fatal(exception_type, exception_value, traceback) # # def on_stop(self): # self.do_cancel() # # def get_actor(self, name): # fsm = pykka.ActorRegistry.get_by_class_name(name) # if fsm: # return fsm[0].proxy() # logger.critical("Actor %s not found!!!" % name) # return None # # def __do_cancel(self): # if self.__timer: # self.__timer.cancel() # self.__timer = None # # def do_cancel(self): # self.__do_cancel() # # def do_delay(self, delay, method, *args, **kwargs): # assert type(method) == str # assert delay >= 0 # # Stop an already running timer # self.__do_cancel() # func = getattr(self._proxy, method) # if delay > 0: # self.__timer = Timer(delay, func.defer, *args, **kwargs) # self.__timer.start() # else: # func.defer(*args, **kwargs) # # Path: controller/actor.py # class PoupoolModel(Machine): # # def __init__(self, *args, **kwargs): # kwargs.setdefault("before_state_change", []).extend(["do_cancel", self.__update_state_time]) # super().__init__( # auto_transitions=False, # ignore_invalid_triggers=True, # *args, # **kwargs # ) # self.__state_time = None # # def __update_state_time(self): # self.__state_time = datetime.now() # # def get_time_in_state(self): # return datetime.now() - self.__state_time # # Path: controller/actor.py # def do_repeat(): # def wrap(func): # @functools.wraps(func) # def wrapped_func(self, *args, **kwargs): # try: # func(self, *args, **kwargs) # except StopRepeatException: # pass # else: # method = re.sub("on_enter_", "do_repeat_", func.__name__) # function = getattr(self._proxy, method) # function.defer() # return wrapped_func # return wrap # # Path: controller/config.py # class Config: # def __init__(self, config_files): # def __getitem__(self, pair): # def as_list(value, type_cast=int): # # Path: controller/util.py # class Duration(object): # # def __init__(self, name): # self.__name = name # self.__total_duration = timedelta() # self.__start = datetime.now() # self.__callback = None # # def set_callback(self, callback): # self.__callback = callback # # def init(self, value): # assert isinstance(value, timedelta) # self.__total_duration = value # # @property # def duration(self): # return self.__total_duration # # def start(self, value=None): # value = value or datetime.now() # assert isinstance(value, datetime) # self.__start = value # # def stop(self, value=None): # value = value or datetime.now() # assert isinstance(value, datetime) # diff = value - self.__start # assert diff > timedelta() # self.__total_duration += diff # if self.__callback: # self.__callback(self.__total_duration) . Output only the next line.
HYSTERESIS_DOWN = float(config["heater", "hysteresis_down"])
Using the snippet: <|code_start|> temp = self.__read_temperature() if temp is not None and temp > self.__setpoint + Heater.HYSTERESIS_UP: self._proxy.wait.defer() else: self.do_delay(self.STATE_REFRESH_DELAY, self.do_repeat_heating.__name__) class Heating(PoupoolActor): STATE_REFRESH_DELAY = 10 HYSTERESIS_DOWN = float(config["heating", "hysteresis_down"]) HYSTERESIS_UP = float(config["heating", "hysteresis_up"]) HYSTERESIS_MIN_TEMP = float(config["heating", "hysteresis_min_temp"]) RECOVER_PERIOD = int(config["heating", "recover_period"]) states = ["halt", "waiting", "heating", "forcing", "recovering"] class DurationEncoderCallback(object): def __init__(self, encoder): self.__encoder = encoder def __call__(self, value): self.__encoder.heating_total__seconds(round(value.total_seconds()), retain=True) def __init__(self, temperature, encoder, devices): super().__init__() self.__enable = True self.__temperature = temperature self.__encoder = encoder <|code_end|> , determine the next line of code. You have imports: import logging from datetime import datetime, timedelta from .actor import PoupoolActor from .actor import PoupoolModel from .actor import do_repeat from .config import config from .util import Duration and context (class names, function names, or code) available: # Path: controller/actor.py # class PoupoolActor(pykka.ThreadingActor): # # def __init__(self): # super().__init__() # self._proxy = self.actor_ref.proxy() # self.__timer = None # # def on_failure(self, exception_type, exception_value, traceback): # # The actor is going to die # logger.fatal(exception_type, exception_value, traceback) # # def on_stop(self): # self.do_cancel() # # def get_actor(self, name): # fsm = pykka.ActorRegistry.get_by_class_name(name) # if fsm: # return fsm[0].proxy() # logger.critical("Actor %s not found!!!" % name) # return None # # def __do_cancel(self): # if self.__timer: # self.__timer.cancel() # self.__timer = None # # def do_cancel(self): # self.__do_cancel() # # def do_delay(self, delay, method, *args, **kwargs): # assert type(method) == str # assert delay >= 0 # # Stop an already running timer # self.__do_cancel() # func = getattr(self._proxy, method) # if delay > 0: # self.__timer = Timer(delay, func.defer, *args, **kwargs) # self.__timer.start() # else: # func.defer(*args, **kwargs) # # Path: controller/actor.py # class PoupoolModel(Machine): # # def __init__(self, *args, **kwargs): # kwargs.setdefault("before_state_change", []).extend(["do_cancel", self.__update_state_time]) # super().__init__( # auto_transitions=False, # ignore_invalid_triggers=True, # *args, # **kwargs # ) # self.__state_time = None # # def __update_state_time(self): # self.__state_time = datetime.now() # # def get_time_in_state(self): # return datetime.now() - self.__state_time # # Path: controller/actor.py # def do_repeat(): # def wrap(func): # @functools.wraps(func) # def wrapped_func(self, *args, **kwargs): # try: # func(self, *args, **kwargs) # except StopRepeatException: # pass # else: # method = re.sub("on_enter_", "do_repeat_", func.__name__) # function = getattr(self._proxy, method) # function.defer() # return wrapped_func # return wrap # # Path: controller/config.py # class Config: # def __init__(self, config_files): # def __getitem__(self, pair): # def as_list(value, type_cast=int): # # Path: controller/util.py # class Duration(object): # # def __init__(self, name): # self.__name = name # self.__total_duration = timedelta() # self.__start = datetime.now() # self.__callback = None # # def set_callback(self, callback): # self.__callback = callback # # def init(self, value): # assert isinstance(value, timedelta) # self.__total_duration = value # # @property # def duration(self): # return self.__total_duration # # def start(self, value=None): # value = value or datetime.now() # assert isinstance(value, datetime) # self.__start = value # # def stop(self, value=None): # value = value or datetime.now() # assert isinstance(value, datetime) # diff = value - self.__start # assert diff > timedelta() # self.__total_duration += diff # if self.__callback: # self.__callback(self.__total_duration) . Output only the next line.
self.__total_duration = Duration("heating")
Predict the next line after this snippet: <|code_start|> self._end_col_idx = None @abc.abstractproperty def _sheet_name(self): # pragma: no cover pass @abc.abstractproperty def _row_count(self): # pragma: no cover pass @abc.abstractproperty def _col_count(self): # pragma: no cover pass @abc.abstractmethod def _is_empty_sheet(self): # pragma: no cover pass @abc.abstractmethod def _get_start_row_idx(self): # pragma: no cover pass @property def format_name(self): return "spreadsheet" def _make_table_name(self): kv_mapping = self._get_basic_tablename_keyvalue_mapping() try: <|code_end|> using the current file's imports: import abc from .._constant import TableNameTemplate as tnt from ..interface import AbstractTableReader and any relevant context from other files: # Path: pytablereader/_constant.py # class TableNameTemplate: # __FORMAT = "%({:s})s" # DEFAULT = __FORMAT.format("default") # FILENAME = __FORMAT.format("filename") # FORMAT_NAME = __FORMAT.format("format_name") # FORMAT_ID = __FORMAT.format("format_id") # GLOBAL_ID = __FORMAT.format("global_id") # KEY = __FORMAT.format("key") # TITLE = __FORMAT.format("title") # SHEET = __FORMAT.format("sheet") # # Path: pytablereader/interface.py # class AbstractTableReader(TableLoaderInterface, metaclass=abc.ABCMeta): # """ # The abstract class of table data file loader. # # .. py:attribute:: table_name # # Table name string. # # .. py:attribute:: source # # Table data source to load. # """ # # __table_count_lock = threading.Lock() # __global_table_count = 0 # __format_table_count = {} # # @property # def source_type(self): # return self._validator.source_type # # @property # def quoting_flags(self): # return self.__quoting_flags # # @property # def dp_extractor(self): # return self.__dp_extractor # # def __init__(self, source, quoting_flags, type_hints, type_hint_rules=None): # self.table_name = tnt.DEFAULT # self.source = source # self.__quoting_flags = quoting_flags # self.type_hints = type_hints # self.type_hint_rules = type_hint_rules # self._validator = None # self._logger = None # # self.__dp_extractor = DataPropertyExtractor() # self.__dp_extractor.quoting_flags = self.quoting_flags # self.__dp_extractor.update_strict_level_map({typepy.Typecode.BOOL: 1}) # # def get_format_key(self): # return f"{self.format_name:s}{self.__get_format_table_count():d}" # # def make_table_name(self): # return self._make_table_name() # # def inc_table_count(self): # with self.__table_count_lock: # self.__global_table_count += 1 # self.__format_table_count[self.format_name] = self.__get_format_table_count() + 1 # # @abc.abstractmethod # def _get_default_table_name_template(self): # pragma: no cover # pass # # def _validate(self): # self._validate_table_name() # self._validate_source() # # def _validate_table_name(self): # try: # if typepy.is_null_string(self.table_name): # raise ValueError("table name is empty") # except (TypeError, AttributeError): # raise TypeError("table_name must be a string") # # def _validate_source(self): # self._validator.validate() # # def __get_format_table_count(self): # return self.__format_table_count.get(self.format_name, 0) # # def _get_filename_tablename_mapping(self): # filename = "" # if all([self.source_type == SourceType.FILE, typepy.is_not_null_string(self.source)]): # filename = path.Path(self.source).stem # # return (tnt.FILENAME, filename) # # def _get_basic_tablename_keyvalue_mapping(self): # from collections import OrderedDict # # return OrderedDict( # [ # (tnt.DEFAULT, self._get_default_table_name_template()), # (tnt.FORMAT_NAME, self.format_name), # (tnt.FORMAT_ID, str(self.__get_format_table_count())), # (tnt.GLOBAL_ID, str(self.__global_table_count)), # self._get_filename_tablename_mapping(), # ] # ) # # def _expand_table_name_format(self, table_name_kv_mapping): # self._validate_table_name() # # table_name = self.table_name # for template, value in table_name_kv_mapping.items(): # table_name = table_name.replace(template, value) # # return self._sanitize_table_name(table_name) # # def _make_table_name(self): # self._validate_table_name() # # return self._expand_table_name_format(self._get_basic_tablename_keyvalue_mapping()) # # @staticmethod # def _sanitize_table_name(table_name): # if typepy.is_null_string(table_name): # raise InvalidTableNameError("table name is empty after the template replacement") # # return table_name.strip("_") # # @classmethod # def clear_table_count(cls): # with cls.__table_count_lock: # cls.__global_table_count = 0 # cls.__format_table_count = {} . Output only the next line.
kv_mapping[tnt.SHEET] = self._sheet_name
Given the code snippet: <|code_start|> """\ <html> <head> header </head> <body> hogehoge </body> </html> """ ) @pytest.mark.xfail(run=False) class MediaWikiTableFormatter_constructor: @pytest.mark.parametrize( ["value", "source", "expected"], [ ["tablename", None, ptr.DataError], ["tablename", "", ptr.DataError], ], ) def test_exception(self, monkeypatch, value, source, expected): with pytest.raises(expected): MediaWikiTableFormatter(source) @pytest.mark.xfail(run=False) class Test_MediaWikiTableFormatter_make_table_name: def setup_method(self, method): <|code_end|> , generate the next line using the imports in this file: import collections import pytest import pytablereader as ptr from textwrap import dedent from path import Path from tabledata import TableData from pytablereader.interface import AbstractTableReader from pytablereader.mediawiki.formatter import MediaWikiTableFormatter and context (functions, classes, or occasionally code) from other files: # Path: pytablereader/interface.py # class AbstractTableReader(TableLoaderInterface, metaclass=abc.ABCMeta): # """ # The abstract class of table data file loader. # # .. py:attribute:: table_name # # Table name string. # # .. py:attribute:: source # # Table data source to load. # """ # # __table_count_lock = threading.Lock() # __global_table_count = 0 # __format_table_count = {} # # @property # def source_type(self): # return self._validator.source_type # # @property # def quoting_flags(self): # return self.__quoting_flags # # @property # def dp_extractor(self): # return self.__dp_extractor # # def __init__(self, source, quoting_flags, type_hints, type_hint_rules=None): # self.table_name = tnt.DEFAULT # self.source = source # self.__quoting_flags = quoting_flags # self.type_hints = type_hints # self.type_hint_rules = type_hint_rules # self._validator = None # self._logger = None # # self.__dp_extractor = DataPropertyExtractor() # self.__dp_extractor.quoting_flags = self.quoting_flags # self.__dp_extractor.update_strict_level_map({typepy.Typecode.BOOL: 1}) # # def get_format_key(self): # return f"{self.format_name:s}{self.__get_format_table_count():d}" # # def make_table_name(self): # return self._make_table_name() # # def inc_table_count(self): # with self.__table_count_lock: # self.__global_table_count += 1 # self.__format_table_count[self.format_name] = self.__get_format_table_count() + 1 # # @abc.abstractmethod # def _get_default_table_name_template(self): # pragma: no cover # pass # # def _validate(self): # self._validate_table_name() # self._validate_source() # # def _validate_table_name(self): # try: # if typepy.is_null_string(self.table_name): # raise ValueError("table name is empty") # except (TypeError, AttributeError): # raise TypeError("table_name must be a string") # # def _validate_source(self): # self._validator.validate() # # def __get_format_table_count(self): # return self.__format_table_count.get(self.format_name, 0) # # def _get_filename_tablename_mapping(self): # filename = "" # if all([self.source_type == SourceType.FILE, typepy.is_not_null_string(self.source)]): # filename = path.Path(self.source).stem # # return (tnt.FILENAME, filename) # # def _get_basic_tablename_keyvalue_mapping(self): # from collections import OrderedDict # # return OrderedDict( # [ # (tnt.DEFAULT, self._get_default_table_name_template()), # (tnt.FORMAT_NAME, self.format_name), # (tnt.FORMAT_ID, str(self.__get_format_table_count())), # (tnt.GLOBAL_ID, str(self.__global_table_count)), # self._get_filename_tablename_mapping(), # ] # ) # # def _expand_table_name_format(self, table_name_kv_mapping): # self._validate_table_name() # # table_name = self.table_name # for template, value in table_name_kv_mapping.items(): # table_name = table_name.replace(template, value) # # return self._sanitize_table_name(table_name) # # def _make_table_name(self): # self._validate_table_name() # # return self._expand_table_name_format(self._get_basic_tablename_keyvalue_mapping()) # # @staticmethod # def _sanitize_table_name(table_name): # if typepy.is_null_string(table_name): # raise InvalidTableNameError("table name is empty after the template replacement") # # return table_name.strip("_") # # @classmethod # def clear_table_count(cls): # with cls.__table_count_lock: # cls.__global_table_count = 0 # cls.__format_table_count = {} # # Path: pytablereader/mediawiki/formatter.py # class MediaWikiTableFormatter(HtmlTableFormatter): # def __init__(self, source_data): # try: # import pypandoc # except ImportError as e: # # pypandoc package may do not installed in the system since the package is # # an optional dependency # raise PypandocImportError(e) # # super().__init__(pypandoc.convert_text(source_data, "html", format="mediawiki")) . Output only the next line.
AbstractTableReader.clear_table_count()
Given the following code snippet before the placeholder: <|code_start|> ], ), ], ) test_empty_data_00 = "= empty table =" test_empty_data_01 = dedent( """\ <html> <head> header </head> <body> hogehoge </body> </html> """ ) @pytest.mark.xfail(run=False) class MediaWikiTableFormatter_constructor: @pytest.mark.parametrize( ["value", "source", "expected"], [ ["tablename", None, ptr.DataError], ["tablename", "", ptr.DataError], ], ) def test_exception(self, monkeypatch, value, source, expected): with pytest.raises(expected): <|code_end|> , predict the next line using imports from the current file: import collections import pytest import pytablereader as ptr from textwrap import dedent from path import Path from tabledata import TableData from pytablereader.interface import AbstractTableReader from pytablereader.mediawiki.formatter import MediaWikiTableFormatter and context including class names, function names, and sometimes code from other files: # Path: pytablereader/interface.py # class AbstractTableReader(TableLoaderInterface, metaclass=abc.ABCMeta): # """ # The abstract class of table data file loader. # # .. py:attribute:: table_name # # Table name string. # # .. py:attribute:: source # # Table data source to load. # """ # # __table_count_lock = threading.Lock() # __global_table_count = 0 # __format_table_count = {} # # @property # def source_type(self): # return self._validator.source_type # # @property # def quoting_flags(self): # return self.__quoting_flags # # @property # def dp_extractor(self): # return self.__dp_extractor # # def __init__(self, source, quoting_flags, type_hints, type_hint_rules=None): # self.table_name = tnt.DEFAULT # self.source = source # self.__quoting_flags = quoting_flags # self.type_hints = type_hints # self.type_hint_rules = type_hint_rules # self._validator = None # self._logger = None # # self.__dp_extractor = DataPropertyExtractor() # self.__dp_extractor.quoting_flags = self.quoting_flags # self.__dp_extractor.update_strict_level_map({typepy.Typecode.BOOL: 1}) # # def get_format_key(self): # return f"{self.format_name:s}{self.__get_format_table_count():d}" # # def make_table_name(self): # return self._make_table_name() # # def inc_table_count(self): # with self.__table_count_lock: # self.__global_table_count += 1 # self.__format_table_count[self.format_name] = self.__get_format_table_count() + 1 # # @abc.abstractmethod # def _get_default_table_name_template(self): # pragma: no cover # pass # # def _validate(self): # self._validate_table_name() # self._validate_source() # # def _validate_table_name(self): # try: # if typepy.is_null_string(self.table_name): # raise ValueError("table name is empty") # except (TypeError, AttributeError): # raise TypeError("table_name must be a string") # # def _validate_source(self): # self._validator.validate() # # def __get_format_table_count(self): # return self.__format_table_count.get(self.format_name, 0) # # def _get_filename_tablename_mapping(self): # filename = "" # if all([self.source_type == SourceType.FILE, typepy.is_not_null_string(self.source)]): # filename = path.Path(self.source).stem # # return (tnt.FILENAME, filename) # # def _get_basic_tablename_keyvalue_mapping(self): # from collections import OrderedDict # # return OrderedDict( # [ # (tnt.DEFAULT, self._get_default_table_name_template()), # (tnt.FORMAT_NAME, self.format_name), # (tnt.FORMAT_ID, str(self.__get_format_table_count())), # (tnt.GLOBAL_ID, str(self.__global_table_count)), # self._get_filename_tablename_mapping(), # ] # ) # # def _expand_table_name_format(self, table_name_kv_mapping): # self._validate_table_name() # # table_name = self.table_name # for template, value in table_name_kv_mapping.items(): # table_name = table_name.replace(template, value) # # return self._sanitize_table_name(table_name) # # def _make_table_name(self): # self._validate_table_name() # # return self._expand_table_name_format(self._get_basic_tablename_keyvalue_mapping()) # # @staticmethod # def _sanitize_table_name(table_name): # if typepy.is_null_string(table_name): # raise InvalidTableNameError("table name is empty after the template replacement") # # return table_name.strip("_") # # @classmethod # def clear_table_count(cls): # with cls.__table_count_lock: # cls.__global_table_count = 0 # cls.__format_table_count = {} # # Path: pytablereader/mediawiki/formatter.py # class MediaWikiTableFormatter(HtmlTableFormatter): # def __init__(self, source_data): # try: # import pypandoc # except ImportError as e: # # pypandoc package may do not installed in the system since the package is # # an optional dependency # raise PypandocImportError(e) # # super().__init__(pypandoc.convert_text(source_data, "html", format="mediawiki")) . Output only the next line.
MediaWikiTableFormatter(source)
Next line prediction: <|code_start|> {"type": "number"}, {"type": "boolean"}, {"type": "null"}, {"type": "object"}, ] } def __init__(self, json_buffer): self._buffer = json_buffer @abc.abstractproperty def _schema(self): # pragma: no cover pass def _validate_source_data(self): """ :raises ValidationError: """ try: jsonschema.validate(self._buffer, self._schema) except jsonschema.ValidationError as e: raise ValidationError(e) class SingleJsonTableConverterBase(JsonConverter): def _make_table_name(self): kv_mapping = self._loader._get_basic_tablename_keyvalue_mapping() kv_mapping[tnt.KEY] = self._loader.get_format_key() <|code_end|> . Use current file imports: (import abc import jsonschema from tabledata import TableData from .._constant import SourceType from .._constant import TableNameTemplate as tnt from ..error import ValidationError from ..formatter import TableFormatter) and context including class names, function names, or small code snippets from other files: # Path: pytablereader/_constant.py # class SourceType: # TEXT = "text" # FILE = "file" # URL = "url" # OBJECT = "object" # # Path: pytablereader/_constant.py # class TableNameTemplate: # __FORMAT = "%({:s})s" # DEFAULT = __FORMAT.format("default") # FILENAME = __FORMAT.format("filename") # FORMAT_NAME = __FORMAT.format("format_name") # FORMAT_ID = __FORMAT.format("format_id") # GLOBAL_ID = __FORMAT.format("global_id") # KEY = __FORMAT.format("key") # TITLE = __FORMAT.format("title") # SHEET = __FORMAT.format("sheet") # # Path: pytablereader/error.py # class ValidationError(Exception): # """ # Exception raised when data is not properly formatted. # """ # # Path: pytablereader/formatter.py # class TableFormatter(LoaderAcceptor, TableFormatterInterface): # """ # The abstract class of |TableData| formatter. # """ # # def _validate_source_data(self): # if not self._source_data: # raise DataError("source data is empty") # # def __init__(self, source_data): # self._source_data = source_data # # self._validate_source_data() # # def _extract_type_hints(self, headers=None): # if self._loader.type_hints: # return self._loader.type_hints # # if not self._loader.type_hint_rules or not headers: # return [] # # type_hints = [] # for header in headers: # for regexp, type_hint in self._loader.type_hint_rules.items(): # if regexp.search(header): # type_hints.append(type_hint) # break # else: # type_hints.append(None) # # logger.debug( # dedent( # """\ # extracted type hints: # {} # """ # ).format( # json.dumps( # OrderedDict( # {header: str(type_hint) for header, type_hint in zip(headers, type_hints)} # ), # indent=4, # ) # ) # ) # # return type_hints . Output only the next line.
if self._loader.source_type == SourceType.FILE:
Given the following code snippet before the placeholder: <|code_start|> "anyOf": [ {"type": "string"}, {"type": "number"}, {"type": "boolean"}, {"type": "null"}, {"type": "object"}, ] } def __init__(self, json_buffer): self._buffer = json_buffer @abc.abstractproperty def _schema(self): # pragma: no cover pass def _validate_source_data(self): """ :raises ValidationError: """ try: jsonschema.validate(self._buffer, self._schema) except jsonschema.ValidationError as e: raise ValidationError(e) class SingleJsonTableConverterBase(JsonConverter): def _make_table_name(self): kv_mapping = self._loader._get_basic_tablename_keyvalue_mapping() <|code_end|> , predict the next line using imports from the current file: import abc import jsonschema from tabledata import TableData from .._constant import SourceType from .._constant import TableNameTemplate as tnt from ..error import ValidationError from ..formatter import TableFormatter and context including class names, function names, and sometimes code from other files: # Path: pytablereader/_constant.py # class SourceType: # TEXT = "text" # FILE = "file" # URL = "url" # OBJECT = "object" # # Path: pytablereader/_constant.py # class TableNameTemplate: # __FORMAT = "%({:s})s" # DEFAULT = __FORMAT.format("default") # FILENAME = __FORMAT.format("filename") # FORMAT_NAME = __FORMAT.format("format_name") # FORMAT_ID = __FORMAT.format("format_id") # GLOBAL_ID = __FORMAT.format("global_id") # KEY = __FORMAT.format("key") # TITLE = __FORMAT.format("title") # SHEET = __FORMAT.format("sheet") # # Path: pytablereader/error.py # class ValidationError(Exception): # """ # Exception raised when data is not properly formatted. # """ # # Path: pytablereader/formatter.py # class TableFormatter(LoaderAcceptor, TableFormatterInterface): # """ # The abstract class of |TableData| formatter. # """ # # def _validate_source_data(self): # if not self._source_data: # raise DataError("source data is empty") # # def __init__(self, source_data): # self._source_data = source_data # # self._validate_source_data() # # def _extract_type_hints(self, headers=None): # if self._loader.type_hints: # return self._loader.type_hints # # if not self._loader.type_hint_rules or not headers: # return [] # # type_hints = [] # for header in headers: # for regexp, type_hint in self._loader.type_hint_rules.items(): # if regexp.search(header): # type_hints.append(type_hint) # break # else: # type_hints.append(None) # # logger.debug( # dedent( # """\ # extracted type hints: # {} # """ # ).format( # json.dumps( # OrderedDict( # {header: str(type_hint) for header, type_hint in zip(headers, type_hints)} # ), # indent=4, # ) # ) # ) # # return type_hints . Output only the next line.
kv_mapping[tnt.KEY] = self._loader.get_format_key()
Based on the snippet: <|code_start|> class JsonConverter(TableFormatter): """ The abstract class of JSON data converter. """ _VALUE_TYPE_SCHEMA = { "anyOf": [ {"type": "string"}, {"type": "number"}, {"type": "boolean"}, {"type": "null"}, {"type": "object"}, ] } def __init__(self, json_buffer): self._buffer = json_buffer @abc.abstractproperty def _schema(self): # pragma: no cover pass def _validate_source_data(self): """ :raises ValidationError: """ try: jsonschema.validate(self._buffer, self._schema) <|code_end|> , predict the immediate next line with the help of imports: import abc import jsonschema from tabledata import TableData from .._constant import SourceType from .._constant import TableNameTemplate as tnt from ..error import ValidationError from ..formatter import TableFormatter and context (classes, functions, sometimes code) from other files: # Path: pytablereader/_constant.py # class SourceType: # TEXT = "text" # FILE = "file" # URL = "url" # OBJECT = "object" # # Path: pytablereader/_constant.py # class TableNameTemplate: # __FORMAT = "%({:s})s" # DEFAULT = __FORMAT.format("default") # FILENAME = __FORMAT.format("filename") # FORMAT_NAME = __FORMAT.format("format_name") # FORMAT_ID = __FORMAT.format("format_id") # GLOBAL_ID = __FORMAT.format("global_id") # KEY = __FORMAT.format("key") # TITLE = __FORMAT.format("title") # SHEET = __FORMAT.format("sheet") # # Path: pytablereader/error.py # class ValidationError(Exception): # """ # Exception raised when data is not properly formatted. # """ # # Path: pytablereader/formatter.py # class TableFormatter(LoaderAcceptor, TableFormatterInterface): # """ # The abstract class of |TableData| formatter. # """ # # def _validate_source_data(self): # if not self._source_data: # raise DataError("source data is empty") # # def __init__(self, source_data): # self._source_data = source_data # # self._validate_source_data() # # def _extract_type_hints(self, headers=None): # if self._loader.type_hints: # return self._loader.type_hints # # if not self._loader.type_hint_rules or not headers: # return [] # # type_hints = [] # for header in headers: # for regexp, type_hint in self._loader.type_hint_rules.items(): # if regexp.search(header): # type_hints.append(type_hint) # break # else: # type_hints.append(None) # # logger.debug( # dedent( # """\ # extracted type hints: # {} # """ # ).format( # json.dumps( # OrderedDict( # {header: str(type_hint) for header, type_hint in zip(headers, type_hints)} # ), # indent=4, # ) # ) # ) # # return type_hints . Output only the next line.
except jsonschema.ValidationError as e:
Given snippet: <|code_start|>""" .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ class FlatJsonTableConverter(SingleJsonTableConverterBase): """ A concrete class of JSON table data formatter. """ @property def _schema(self): return {"type": "object", "additionalProperties": self._VALUE_TYPE_SCHEMA} def _validate_source_data(self): for json_record in self._buffer: try: jsonschema.validate(json_record, self._schema) <|code_end|> , continue by predicting the next line. Consider current file imports: import jsonschema from tabledata import TableData from ..error import ValidationError from ..formatter import TableFormatter from ..json.formatter import SingleJsonTableConverterBase and context: # Path: pytablereader/error.py # class ValidationError(Exception): # """ # Exception raised when data is not properly formatted. # """ # # Path: pytablereader/formatter.py # class TableFormatter(LoaderAcceptor, TableFormatterInterface): # """ # The abstract class of |TableData| formatter. # """ # # def _validate_source_data(self): # if not self._source_data: # raise DataError("source data is empty") # # def __init__(self, source_data): # self._source_data = source_data # # self._validate_source_data() # # def _extract_type_hints(self, headers=None): # if self._loader.type_hints: # return self._loader.type_hints # # if not self._loader.type_hint_rules or not headers: # return [] # # type_hints = [] # for header in headers: # for regexp, type_hint in self._loader.type_hint_rules.items(): # if regexp.search(header): # type_hints.append(type_hint) # break # else: # type_hints.append(None) # # logger.debug( # dedent( # """\ # extracted type hints: # {} # """ # ).format( # json.dumps( # OrderedDict( # {header: str(type_hint) for header, type_hint in zip(headers, type_hints)} # ), # indent=4, # ) # ) # ) # # return type_hints # # Path: pytablereader/json/formatter.py # class SingleJsonTableConverterBase(JsonConverter): # def _make_table_name(self): # kv_mapping = self._loader._get_basic_tablename_keyvalue_mapping() # kv_mapping[tnt.KEY] = self._loader.get_format_key() # # if self._loader.source_type == SourceType.FILE: # kv_mapping[tnt.DEFAULT] = tnt.FILENAME # elif self._loader.source_type == SourceType.TEXT: # kv_mapping[tnt.DEFAULT] = tnt.KEY # # return self._loader._expand_table_name_format(kv_mapping) which might include code, classes, or functions. Output only the next line.
except jsonschema.ValidationError as e:
Based on the snippet: <|code_start|> try: jsonschema.validate(json_record, self._schema) except jsonschema.ValidationError as e: raise ValidationError(e) def to_table_data(self): """ :raises ValueError: :raises pytablereader.error.ValidationError: """ self._validate_source_data() header_list = [] for json_record in self._buffer: for key in json_record: if key not in header_list: header_list.append(key) self._loader.inc_table_count() yield TableData( self._make_table_name(), header_list, self._buffer, dp_extractor=self._loader.dp_extractor, type_hints=self._extract_type_hints(header_list), ) <|code_end|> , predict the immediate next line with the help of imports: import jsonschema from tabledata import TableData from ..error import ValidationError from ..formatter import TableFormatter from ..json.formatter import SingleJsonTableConverterBase and context (classes, functions, sometimes code) from other files: # Path: pytablereader/error.py # class ValidationError(Exception): # """ # Exception raised when data is not properly formatted. # """ # # Path: pytablereader/formatter.py # class TableFormatter(LoaderAcceptor, TableFormatterInterface): # """ # The abstract class of |TableData| formatter. # """ # # def _validate_source_data(self): # if not self._source_data: # raise DataError("source data is empty") # # def __init__(self, source_data): # self._source_data = source_data # # self._validate_source_data() # # def _extract_type_hints(self, headers=None): # if self._loader.type_hints: # return self._loader.type_hints # # if not self._loader.type_hint_rules or not headers: # return [] # # type_hints = [] # for header in headers: # for regexp, type_hint in self._loader.type_hint_rules.items(): # if regexp.search(header): # type_hints.append(type_hint) # break # else: # type_hints.append(None) # # logger.debug( # dedent( # """\ # extracted type hints: # {} # """ # ).format( # json.dumps( # OrderedDict( # {header: str(type_hint) for header, type_hint in zip(headers, type_hints)} # ), # indent=4, # ) # ) # ) # # return type_hints # # Path: pytablereader/json/formatter.py # class SingleJsonTableConverterBase(JsonConverter): # def _make_table_name(self): # kv_mapping = self._loader._get_basic_tablename_keyvalue_mapping() # kv_mapping[tnt.KEY] = self._loader.get_format_key() # # if self._loader.source_type == SourceType.FILE: # kv_mapping[tnt.DEFAULT] = tnt.FILENAME # elif self._loader.source_type == SourceType.TEXT: # kv_mapping[tnt.DEFAULT] = tnt.KEY # # return self._loader._expand_table_name_format(kv_mapping) . Output only the next line.
class JsonLinesTableFormatter(TableFormatter):
Predict the next line after this snippet: <|code_start|>""" .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ class MediaWikiTableFormatter(HtmlTableFormatter): def __init__(self, source_data): try: except ImportError as e: # pypandoc package may do not installed in the system since the package is # an optional dependency <|code_end|> using the current file's imports: from ..error import PypandocImportError from ..html.formatter import HtmlTableFormatter import pypandoc and any relevant context from other files: # Path: pytablereader/error.py # class PypandocImportError(ImportError): # """ # Exception raised when import error occurred with pypandoc package. # """ # # Path: pytablereader/html/formatter.py # class HtmlTableFormatter(TableFormatter): # @property # def table_id(self): # return self.__table_id # # def __init__(self, source_data, logger=None): # super().__init__(source_data) # # if logger: # self.__logger = logger # else: # self.__logger = NullSourceLogger(None) # # self.__table_id = None # # if typepy.is_null_string(source_data): # raise DataError # # try: # self.__soup = bs4.BeautifulSoup(self._source_data, "lxml") # except bs4.FeatureNotFound: # self.__soup = bs4.BeautifulSoup(self._source_data, "html.parser") # # def to_table_data(self): # for table in self.__soup.find_all("table"): # try: # table_data = self.__parse_html(table) # except ValueError: # continue # # if table_data.is_empty_rows(): # continue # # self.__logger.logging_table(table_data) # # yield table_data # # def _make_table_name(self): # from collections import OrderedDict # # key = self.table_id # if typepy.is_null_string(key): # key = self._loader.get_format_key() # # try: # title = self.__soup.title.text # except AttributeError: # title = "" # # kv_mapping = self._loader._get_basic_tablename_keyvalue_mapping() # kv_mapping.update(OrderedDict([(tnt.KEY, key), (tnt.TITLE, title)])) # # return self._loader._expand_table_name_format(kv_mapping) # # def __parse_tag_id(self, table): # self.__table_id = table.get("id") # # if self.__table_id is None: # caption = table.find("caption") # if caption is not None: # caption = caption.text.strip() # if typepy.is_not_null_string(caption): # self.__table_id = caption # # def __parse_html(self, table): # headers = [] # data_matrix = [] # # self.__parse_tag_id(table) # # rows = table.find_all("tr") # re_table_val = re.compile("td|th") # for row in rows: # td_list = row.find_all("td") # if typepy.is_empty_sequence(td_list): # if typepy.is_not_empty_sequence(headers): # continue # # th_list = row.find_all("th") # if typepy.is_empty_sequence(th_list): # continue # # headers = [row.text.strip() for row in th_list] # continue # # data_matrix.append([value.get_text().strip() for value in row.find_all(re_table_val)]) # # if typepy.is_empty_sequence(data_matrix): # raise ValueError("data matrix is empty") # # self._loader.inc_table_count() # # return TableData( # self._make_table_name(), # headers, # data_matrix, # dp_extractor=self._loader.dp_extractor, # type_hints=self._extract_type_hints(headers), # ) . Output only the next line.
raise PypandocImportError(e)
Using the snippet: <|code_start|> "tmp", ["attr_a", "attr_b", "attr_c"], [[1, 4, "a"], [2, "2.1", "bb"], [3, "120.9", "ccc"]], ) ], ) test_data_05 = Data( TableData( "tmp", ["姓", "名", "生年月日", "郵便番号", "住所", "電話番号"], [ ["山田", "太郎", "2001/1/1", "100-0002", "東京都千代田区皇居外苑", "03-1234-5678"], ["山田", "次郎", "2001/1/2", "251-0036", "神奈川県藤沢市江の島1丁目", "03-9999-9999"], ], ), [ TableData( "tmp", ["姓", "名", "生年月日", "郵便番号", "住所", "電話番号"], [ ["山田", "太郎", "2001/1/1", "100-0002", "東京都千代田区皇居外苑", "03-1234-5678"], ["山田", "次郎", "2001/1/2", "251-0036", "神奈川県藤沢市江の島1丁目", "03-9999-9999"], ], ) ], ) class Test_SqliteFileLoader_load: def setup_method(self, method): <|code_end|> , determine the next line of code. You have imports: import collections import pytest import pytablereader as ptr from decimal import Decimal from path import Path from pytablewriter import dumps_tabledata from simplesqlite import SimpleSQLite from tabledata import TableData from pytablereader.interface import AbstractTableReader and context (class names, function names, or code) available: # Path: pytablereader/interface.py # class AbstractTableReader(TableLoaderInterface, metaclass=abc.ABCMeta): # """ # The abstract class of table data file loader. # # .. py:attribute:: table_name # # Table name string. # # .. py:attribute:: source # # Table data source to load. # """ # # __table_count_lock = threading.Lock() # __global_table_count = 0 # __format_table_count = {} # # @property # def source_type(self): # return self._validator.source_type # # @property # def quoting_flags(self): # return self.__quoting_flags # # @property # def dp_extractor(self): # return self.__dp_extractor # # def __init__(self, source, quoting_flags, type_hints, type_hint_rules=None): # self.table_name = tnt.DEFAULT # self.source = source # self.__quoting_flags = quoting_flags # self.type_hints = type_hints # self.type_hint_rules = type_hint_rules # self._validator = None # self._logger = None # # self.__dp_extractor = DataPropertyExtractor() # self.__dp_extractor.quoting_flags = self.quoting_flags # self.__dp_extractor.update_strict_level_map({typepy.Typecode.BOOL: 1}) # # def get_format_key(self): # return f"{self.format_name:s}{self.__get_format_table_count():d}" # # def make_table_name(self): # return self._make_table_name() # # def inc_table_count(self): # with self.__table_count_lock: # self.__global_table_count += 1 # self.__format_table_count[self.format_name] = self.__get_format_table_count() + 1 # # @abc.abstractmethod # def _get_default_table_name_template(self): # pragma: no cover # pass # # def _validate(self): # self._validate_table_name() # self._validate_source() # # def _validate_table_name(self): # try: # if typepy.is_null_string(self.table_name): # raise ValueError("table name is empty") # except (TypeError, AttributeError): # raise TypeError("table_name must be a string") # # def _validate_source(self): # self._validator.validate() # # def __get_format_table_count(self): # return self.__format_table_count.get(self.format_name, 0) # # def _get_filename_tablename_mapping(self): # filename = "" # if all([self.source_type == SourceType.FILE, typepy.is_not_null_string(self.source)]): # filename = path.Path(self.source).stem # # return (tnt.FILENAME, filename) # # def _get_basic_tablename_keyvalue_mapping(self): # from collections import OrderedDict # # return OrderedDict( # [ # (tnt.DEFAULT, self._get_default_table_name_template()), # (tnt.FORMAT_NAME, self.format_name), # (tnt.FORMAT_ID, str(self.__get_format_table_count())), # (tnt.GLOBAL_ID, str(self.__global_table_count)), # self._get_filename_tablename_mapping(), # ] # ) # # def _expand_table_name_format(self, table_name_kv_mapping): # self._validate_table_name() # # table_name = self.table_name # for template, value in table_name_kv_mapping.items(): # table_name = table_name.replace(template, value) # # return self._sanitize_table_name(table_name) # # def _make_table_name(self): # self._validate_table_name() # # return self._expand_table_name_format(self._get_basic_tablename_keyvalue_mapping()) # # @staticmethod # def _sanitize_table_name(table_name): # if typepy.is_null_string(table_name): # raise InvalidTableNameError("table name is empty after the template replacement") # # return table_name.strip("_") # # @classmethod # def clear_table_count(cls): # with cls.__table_count_lock: # cls.__global_table_count = 0 # cls.__format_table_count = {} . Output only the next line.
AbstractTableReader.clear_table_count()
Using the snippet: <|code_start|> rows, dp_extractor=self.dp_extractor, type_hints=self._extract_type_hints(headers), ) except gspread.exceptions.SpreadsheetNotFound: raise OpenError(f"spreadsheet '{self.title}' not found") except gspread.exceptions.APIError as e: raise APIError(e) def _is_empty_sheet(self): return len(self.__all_values) <= 1 def _get_start_row_idx(self): row_idx = 0 for row_values in self.__all_values: if all([typepy.is_not_null_string(value) for value in row_values]): break row_idx += 1 return self.start_row + row_idx def _validate_title(self): if typepy.is_null_string(self.title): raise ValueError("spreadsheet title is empty") def _make_table_name(self): self._validate_title() kv_mapping = self._get_basic_tablename_keyvalue_mapping() <|code_end|> , determine the next line of code. You have imports: import typepy import gspread from tabledata import TableData from .._constant import TableNameTemplate as tnt from .._validator import TextValidator from ..error import APIError, OpenError from .core import SpreadSheetLoader from oauth2client.service_account import ServiceAccountCredentials from simplesqlite import connect_memdb from simplesqlite.query import Attr, AttrList and context (class names, function names, or code) available: # Path: pytablereader/_constant.py # class TableNameTemplate: # __FORMAT = "%({:s})s" # DEFAULT = __FORMAT.format("default") # FILENAME = __FORMAT.format("filename") # FORMAT_NAME = __FORMAT.format("format_name") # FORMAT_ID = __FORMAT.format("format_id") # GLOBAL_ID = __FORMAT.format("global_id") # KEY = __FORMAT.format("key") # TITLE = __FORMAT.format("title") # SHEET = __FORMAT.format("sheet") # # Path: pytablereader/_validator.py # class TextValidator(BaseValidator): # """ # Validator class for text object data source. # """ # # @property # def source_type(self): # return SourceType.TEXT # # def validate(self): # if typepy.is_null_string(self.source): # raise DataError("data source is empty") # # Path: pytablereader/error.py # class APIError(Exception): # """ # Exception raised when failed to execute API requests. # """ # # class OpenError(IOError): # """ # Exception raised when failed to open a file. # """ # # Path: pytablereader/spreadsheet/core.py # class SpreadSheetLoader(AbstractTableReader): # """ # An abstract class of table data. # Especially spreadsheets that consists multiple rows. # # .. py:attribute:: start_row # # The first row to search header row. # """ # # def __init__(self, source, quoting_flags, type_hints, type_hint_rules): # super().__init__(source, quoting_flags, type_hints, type_hint_rules) # # self.start_row = 0 # self._worksheet = None # self._start_col_idx = None # self._end_col_idx = None # # @abc.abstractproperty # def _sheet_name(self): # pragma: no cover # pass # # @abc.abstractproperty # def _row_count(self): # pragma: no cover # pass # # @abc.abstractproperty # def _col_count(self): # pragma: no cover # pass # # @abc.abstractmethod # def _is_empty_sheet(self): # pragma: no cover # pass # # @abc.abstractmethod # def _get_start_row_idx(self): # pragma: no cover # pass # # @property # def format_name(self): # return "spreadsheet" # # def _make_table_name(self): # kv_mapping = self._get_basic_tablename_keyvalue_mapping() # # try: # kv_mapping[tnt.SHEET] = self._sheet_name # except AttributeError: # kv_mapping[tnt.SHEET] = "" # # return self._expand_table_name_format(kv_mapping) # # def _get_default_table_name_template(self): # return f"{tnt.SHEET:s}" # # def _extract_type_hints(self, headers=None): # if self.type_hints: # return self.type_hints # # if not self.type_hint_rules or not headers: # return [] # # type_hints = [] # for header in headers: # for regexp, type_hint in self.type_hint_rules.items(): # if regexp.search(header): # type_hints.append(type_hint) # break # else: # type_hints.append(None) # # return type_hints . Output only the next line.
kv_mapping[tnt.TITLE] = self.title
Continue the code snippet: <|code_start|> :param str file_path: Path to the Google Sheets credential JSON file. :Dependency Packages: - `gspread <https://github.com/burnash/gspread>`_ - `SimpleSQLite <https://github.com/thombashi/SimpleSQLite>`_ - `oauth2client <https://pypi.org/project/oauth2client>`_ - `pyOpenSSL <https://pypi.org/project/pyOpenSSL>`_ :Examples: :ref:`example-gs-table-loader` """ @property def _sheet_name(self): return self._worksheet.title @property def _row_count(self): return self._worksheet.row_count @property def _col_count(self): return self._worksheet.col_count def __init__(self, file_path=None, quoting_flags=None, type_hints=None, type_hint_rules=None): super().__init__(file_path, quoting_flags, type_hints, type_hint_rules) self.title = None self.start_row = 0 <|code_end|> . Use current file imports: import typepy import gspread from tabledata import TableData from .._constant import TableNameTemplate as tnt from .._validator import TextValidator from ..error import APIError, OpenError from .core import SpreadSheetLoader from oauth2client.service_account import ServiceAccountCredentials from simplesqlite import connect_memdb from simplesqlite.query import Attr, AttrList and context (classes, functions, or code) from other files: # Path: pytablereader/_constant.py # class TableNameTemplate: # __FORMAT = "%({:s})s" # DEFAULT = __FORMAT.format("default") # FILENAME = __FORMAT.format("filename") # FORMAT_NAME = __FORMAT.format("format_name") # FORMAT_ID = __FORMAT.format("format_id") # GLOBAL_ID = __FORMAT.format("global_id") # KEY = __FORMAT.format("key") # TITLE = __FORMAT.format("title") # SHEET = __FORMAT.format("sheet") # # Path: pytablereader/_validator.py # class TextValidator(BaseValidator): # """ # Validator class for text object data source. # """ # # @property # def source_type(self): # return SourceType.TEXT # # def validate(self): # if typepy.is_null_string(self.source): # raise DataError("data source is empty") # # Path: pytablereader/error.py # class APIError(Exception): # """ # Exception raised when failed to execute API requests. # """ # # class OpenError(IOError): # """ # Exception raised when failed to open a file. # """ # # Path: pytablereader/spreadsheet/core.py # class SpreadSheetLoader(AbstractTableReader): # """ # An abstract class of table data. # Especially spreadsheets that consists multiple rows. # # .. py:attribute:: start_row # # The first row to search header row. # """ # # def __init__(self, source, quoting_flags, type_hints, type_hint_rules): # super().__init__(source, quoting_flags, type_hints, type_hint_rules) # # self.start_row = 0 # self._worksheet = None # self._start_col_idx = None # self._end_col_idx = None # # @abc.abstractproperty # def _sheet_name(self): # pragma: no cover # pass # # @abc.abstractproperty # def _row_count(self): # pragma: no cover # pass # # @abc.abstractproperty # def _col_count(self): # pragma: no cover # pass # # @abc.abstractmethod # def _is_empty_sheet(self): # pragma: no cover # pass # # @abc.abstractmethod # def _get_start_row_idx(self): # pragma: no cover # pass # # @property # def format_name(self): # return "spreadsheet" # # def _make_table_name(self): # kv_mapping = self._get_basic_tablename_keyvalue_mapping() # # try: # kv_mapping[tnt.SHEET] = self._sheet_name # except AttributeError: # kv_mapping[tnt.SHEET] = "" # # return self._expand_table_name_format(kv_mapping) # # def _get_default_table_name_template(self): # return f"{tnt.SHEET:s}" # # def _extract_type_hints(self, headers=None): # if self.type_hints: # return self.type_hints # # if not self.type_hint_rules or not headers: # return [] # # type_hints = [] # for header in headers: # for regexp, type_hint in self.type_hint_rules.items(): # if regexp.search(header): # type_hints.append(type_hint) # break # else: # type_hints.append(None) # # return type_hints . Output only the next line.
self._validator = TextValidator(file_path)
Given the following code snippet before the placeholder: <|code_start|> for worksheet in gc.open(self.title).worksheets(): self._worksheet = worksheet self.__all_values = [row for row in worksheet.get_all_values()] if self._is_empty_sheet(): continue try: self.__strip_empty_col() except ValueError: continue value_matrix = self.__all_values[self._get_start_row_idx() :] try: headers = value_matrix[0] rows = value_matrix[1:] except IndexError: continue self.inc_table_count() yield TableData( self.make_table_name(), headers, rows, dp_extractor=self.dp_extractor, type_hints=self._extract_type_hints(headers), ) except gspread.exceptions.SpreadsheetNotFound: raise OpenError(f"spreadsheet '{self.title}' not found") <|code_end|> , predict the next line using imports from the current file: import typepy import gspread from tabledata import TableData from .._constant import TableNameTemplate as tnt from .._validator import TextValidator from ..error import APIError, OpenError from .core import SpreadSheetLoader from oauth2client.service_account import ServiceAccountCredentials from simplesqlite import connect_memdb from simplesqlite.query import Attr, AttrList and context including class names, function names, and sometimes code from other files: # Path: pytablereader/_constant.py # class TableNameTemplate: # __FORMAT = "%({:s})s" # DEFAULT = __FORMAT.format("default") # FILENAME = __FORMAT.format("filename") # FORMAT_NAME = __FORMAT.format("format_name") # FORMAT_ID = __FORMAT.format("format_id") # GLOBAL_ID = __FORMAT.format("global_id") # KEY = __FORMAT.format("key") # TITLE = __FORMAT.format("title") # SHEET = __FORMAT.format("sheet") # # Path: pytablereader/_validator.py # class TextValidator(BaseValidator): # """ # Validator class for text object data source. # """ # # @property # def source_type(self): # return SourceType.TEXT # # def validate(self): # if typepy.is_null_string(self.source): # raise DataError("data source is empty") # # Path: pytablereader/error.py # class APIError(Exception): # """ # Exception raised when failed to execute API requests. # """ # # class OpenError(IOError): # """ # Exception raised when failed to open a file. # """ # # Path: pytablereader/spreadsheet/core.py # class SpreadSheetLoader(AbstractTableReader): # """ # An abstract class of table data. # Especially spreadsheets that consists multiple rows. # # .. py:attribute:: start_row # # The first row to search header row. # """ # # def __init__(self, source, quoting_flags, type_hints, type_hint_rules): # super().__init__(source, quoting_flags, type_hints, type_hint_rules) # # self.start_row = 0 # self._worksheet = None # self._start_col_idx = None # self._end_col_idx = None # # @abc.abstractproperty # def _sheet_name(self): # pragma: no cover # pass # # @abc.abstractproperty # def _row_count(self): # pragma: no cover # pass # # @abc.abstractproperty # def _col_count(self): # pragma: no cover # pass # # @abc.abstractmethod # def _is_empty_sheet(self): # pragma: no cover # pass # # @abc.abstractmethod # def _get_start_row_idx(self): # pragma: no cover # pass # # @property # def format_name(self): # return "spreadsheet" # # def _make_table_name(self): # kv_mapping = self._get_basic_tablename_keyvalue_mapping() # # try: # kv_mapping[tnt.SHEET] = self._sheet_name # except AttributeError: # kv_mapping[tnt.SHEET] = "" # # return self._expand_table_name_format(kv_mapping) # # def _get_default_table_name_template(self): # return f"{tnt.SHEET:s}" # # def _extract_type_hints(self, headers=None): # if self.type_hints: # return self.type_hints # # if not self.type_hint_rules or not headers: # return [] # # type_hints = [] # for header in headers: # for regexp, type_hint in self.type_hint_rules.items(): # if regexp.search(header): # type_hints.append(type_hint) # break # else: # type_hints.append(None) # # return type_hints . Output only the next line.
except gspread.exceptions.APIError as e:
Here is a snippet: <|code_start|> try: for worksheet in gc.open(self.title).worksheets(): self._worksheet = worksheet self.__all_values = [row for row in worksheet.get_all_values()] if self._is_empty_sheet(): continue try: self.__strip_empty_col() except ValueError: continue value_matrix = self.__all_values[self._get_start_row_idx() :] try: headers = value_matrix[0] rows = value_matrix[1:] except IndexError: continue self.inc_table_count() yield TableData( self.make_table_name(), headers, rows, dp_extractor=self.dp_extractor, type_hints=self._extract_type_hints(headers), ) except gspread.exceptions.SpreadsheetNotFound: <|code_end|> . Write the next line using the current file imports: import typepy import gspread from tabledata import TableData from .._constant import TableNameTemplate as tnt from .._validator import TextValidator from ..error import APIError, OpenError from .core import SpreadSheetLoader from oauth2client.service_account import ServiceAccountCredentials from simplesqlite import connect_memdb from simplesqlite.query import Attr, AttrList and context from other files: # Path: pytablereader/_constant.py # class TableNameTemplate: # __FORMAT = "%({:s})s" # DEFAULT = __FORMAT.format("default") # FILENAME = __FORMAT.format("filename") # FORMAT_NAME = __FORMAT.format("format_name") # FORMAT_ID = __FORMAT.format("format_id") # GLOBAL_ID = __FORMAT.format("global_id") # KEY = __FORMAT.format("key") # TITLE = __FORMAT.format("title") # SHEET = __FORMAT.format("sheet") # # Path: pytablereader/_validator.py # class TextValidator(BaseValidator): # """ # Validator class for text object data source. # """ # # @property # def source_type(self): # return SourceType.TEXT # # def validate(self): # if typepy.is_null_string(self.source): # raise DataError("data source is empty") # # Path: pytablereader/error.py # class APIError(Exception): # """ # Exception raised when failed to execute API requests. # """ # # class OpenError(IOError): # """ # Exception raised when failed to open a file. # """ # # Path: pytablereader/spreadsheet/core.py # class SpreadSheetLoader(AbstractTableReader): # """ # An abstract class of table data. # Especially spreadsheets that consists multiple rows. # # .. py:attribute:: start_row # # The first row to search header row. # """ # # def __init__(self, source, quoting_flags, type_hints, type_hint_rules): # super().__init__(source, quoting_flags, type_hints, type_hint_rules) # # self.start_row = 0 # self._worksheet = None # self._start_col_idx = None # self._end_col_idx = None # # @abc.abstractproperty # def _sheet_name(self): # pragma: no cover # pass # # @abc.abstractproperty # def _row_count(self): # pragma: no cover # pass # # @abc.abstractproperty # def _col_count(self): # pragma: no cover # pass # # @abc.abstractmethod # def _is_empty_sheet(self): # pragma: no cover # pass # # @abc.abstractmethod # def _get_start_row_idx(self): # pragma: no cover # pass # # @property # def format_name(self): # return "spreadsheet" # # def _make_table_name(self): # kv_mapping = self._get_basic_tablename_keyvalue_mapping() # # try: # kv_mapping[tnt.SHEET] = self._sheet_name # except AttributeError: # kv_mapping[tnt.SHEET] = "" # # return self._expand_table_name_format(kv_mapping) # # def _get_default_table_name_template(self): # return f"{tnt.SHEET:s}" # # def _extract_type_hints(self, headers=None): # if self.type_hints: # return self.type_hints # # if not self.type_hint_rules or not headers: # return [] # # type_hints = [] # for header in headers: # for regexp, type_hint in self.type_hint_rules.items(): # if regexp.search(header): # type_hints.append(type_hint) # break # else: # type_hints.append(None) # # return type_hints , which may include functions, classes, or code. Output only the next line.
raise OpenError(f"spreadsheet '{self.title}' not found")
Given the following code snippet before the placeholder: <|code_start|> ], ) test_empty_data_00 = "# empty table" test_empty_data_01 = dedent( """\ <html> <head> header </head> <body> hogehoge </body> </html> """ ) class MarkdownTableFormatter_constructor: @pytest.mark.parametrize( ["value", "source", "expected"], [["tablename", None, ptr.DataError], ["tablename", "", ptr.DataError]], ) def test_exception(self, monkeypatch, value, source, expected): with pytest.raises(expected): MarkdownTableFormatter(source) class Test_MarkdownTableFormatter_make_table_name: def setup_method(self, method): <|code_end|> , predict the next line using imports from the current file: import collections import pytest import pytablereader as ptr from textwrap import dedent from path import Path from pytablewriter import dumps_tabledata from tabledata import TableData from pytablereader.interface import AbstractTableReader from pytablereader.markdown.formatter import MarkdownTableFormatter and context including class names, function names, and sometimes code from other files: # Path: pytablereader/interface.py # class AbstractTableReader(TableLoaderInterface, metaclass=abc.ABCMeta): # """ # The abstract class of table data file loader. # # .. py:attribute:: table_name # # Table name string. # # .. py:attribute:: source # # Table data source to load. # """ # # __table_count_lock = threading.Lock() # __global_table_count = 0 # __format_table_count = {} # # @property # def source_type(self): # return self._validator.source_type # # @property # def quoting_flags(self): # return self.__quoting_flags # # @property # def dp_extractor(self): # return self.__dp_extractor # # def __init__(self, source, quoting_flags, type_hints, type_hint_rules=None): # self.table_name = tnt.DEFAULT # self.source = source # self.__quoting_flags = quoting_flags # self.type_hints = type_hints # self.type_hint_rules = type_hint_rules # self._validator = None # self._logger = None # # self.__dp_extractor = DataPropertyExtractor() # self.__dp_extractor.quoting_flags = self.quoting_flags # self.__dp_extractor.update_strict_level_map({typepy.Typecode.BOOL: 1}) # # def get_format_key(self): # return f"{self.format_name:s}{self.__get_format_table_count():d}" # # def make_table_name(self): # return self._make_table_name() # # def inc_table_count(self): # with self.__table_count_lock: # self.__global_table_count += 1 # self.__format_table_count[self.format_name] = self.__get_format_table_count() + 1 # # @abc.abstractmethod # def _get_default_table_name_template(self): # pragma: no cover # pass # # def _validate(self): # self._validate_table_name() # self._validate_source() # # def _validate_table_name(self): # try: # if typepy.is_null_string(self.table_name): # raise ValueError("table name is empty") # except (TypeError, AttributeError): # raise TypeError("table_name must be a string") # # def _validate_source(self): # self._validator.validate() # # def __get_format_table_count(self): # return self.__format_table_count.get(self.format_name, 0) # # def _get_filename_tablename_mapping(self): # filename = "" # if all([self.source_type == SourceType.FILE, typepy.is_not_null_string(self.source)]): # filename = path.Path(self.source).stem # # return (tnt.FILENAME, filename) # # def _get_basic_tablename_keyvalue_mapping(self): # from collections import OrderedDict # # return OrderedDict( # [ # (tnt.DEFAULT, self._get_default_table_name_template()), # (tnt.FORMAT_NAME, self.format_name), # (tnt.FORMAT_ID, str(self.__get_format_table_count())), # (tnt.GLOBAL_ID, str(self.__global_table_count)), # self._get_filename_tablename_mapping(), # ] # ) # # def _expand_table_name_format(self, table_name_kv_mapping): # self._validate_table_name() # # table_name = self.table_name # for template, value in table_name_kv_mapping.items(): # table_name = table_name.replace(template, value) # # return self._sanitize_table_name(table_name) # # def _make_table_name(self): # self._validate_table_name() # # return self._expand_table_name_format(self._get_basic_tablename_keyvalue_mapping()) # # @staticmethod # def _sanitize_table_name(table_name): # if typepy.is_null_string(table_name): # raise InvalidTableNameError("table name is empty after the template replacement") # # return table_name.strip("_") # # @classmethod # def clear_table_count(cls): # with cls.__table_count_lock: # cls.__global_table_count = 0 # cls.__format_table_count = {} # # Path: pytablereader/markdown/formatter.py # class MarkdownTableFormatter(HtmlTableFormatter): # def __init__(self, source_data, logger=None): # import markdown # # if typepy.is_null_string(source_data): # raise DataError # # super().__init__( # markdown.markdown(source_data, extensions=["markdown.extensions.tables"]), logger=logger # ) . Output only the next line.
AbstractTableReader.clear_table_count()
Continue the code snippet: <|code_start|> "tmp_markdown1", ["a", "b", "c"], [[1, "123.1", "a"], [2, "2.2", "bb"], ["3", "3.3", "ccc"]], ), TableData("tmp_markdown2", ["a", "b"], [[1, "123.1"], [2, "2.2"], ["3", "3.3"]]), ], ) test_empty_data_00 = "# empty table" test_empty_data_01 = dedent( """\ <html> <head> header </head> <body> hogehoge </body> </html> """ ) class MarkdownTableFormatter_constructor: @pytest.mark.parametrize( ["value", "source", "expected"], [["tablename", None, ptr.DataError], ["tablename", "", ptr.DataError]], ) def test_exception(self, monkeypatch, value, source, expected): with pytest.raises(expected): <|code_end|> . Use current file imports: import collections import pytest import pytablereader as ptr from textwrap import dedent from path import Path from pytablewriter import dumps_tabledata from tabledata import TableData from pytablereader.interface import AbstractTableReader from pytablereader.markdown.formatter import MarkdownTableFormatter and context (classes, functions, or code) from other files: # Path: pytablereader/interface.py # class AbstractTableReader(TableLoaderInterface, metaclass=abc.ABCMeta): # """ # The abstract class of table data file loader. # # .. py:attribute:: table_name # # Table name string. # # .. py:attribute:: source # # Table data source to load. # """ # # __table_count_lock = threading.Lock() # __global_table_count = 0 # __format_table_count = {} # # @property # def source_type(self): # return self._validator.source_type # # @property # def quoting_flags(self): # return self.__quoting_flags # # @property # def dp_extractor(self): # return self.__dp_extractor # # def __init__(self, source, quoting_flags, type_hints, type_hint_rules=None): # self.table_name = tnt.DEFAULT # self.source = source # self.__quoting_flags = quoting_flags # self.type_hints = type_hints # self.type_hint_rules = type_hint_rules # self._validator = None # self._logger = None # # self.__dp_extractor = DataPropertyExtractor() # self.__dp_extractor.quoting_flags = self.quoting_flags # self.__dp_extractor.update_strict_level_map({typepy.Typecode.BOOL: 1}) # # def get_format_key(self): # return f"{self.format_name:s}{self.__get_format_table_count():d}" # # def make_table_name(self): # return self._make_table_name() # # def inc_table_count(self): # with self.__table_count_lock: # self.__global_table_count += 1 # self.__format_table_count[self.format_name] = self.__get_format_table_count() + 1 # # @abc.abstractmethod # def _get_default_table_name_template(self): # pragma: no cover # pass # # def _validate(self): # self._validate_table_name() # self._validate_source() # # def _validate_table_name(self): # try: # if typepy.is_null_string(self.table_name): # raise ValueError("table name is empty") # except (TypeError, AttributeError): # raise TypeError("table_name must be a string") # # def _validate_source(self): # self._validator.validate() # # def __get_format_table_count(self): # return self.__format_table_count.get(self.format_name, 0) # # def _get_filename_tablename_mapping(self): # filename = "" # if all([self.source_type == SourceType.FILE, typepy.is_not_null_string(self.source)]): # filename = path.Path(self.source).stem # # return (tnt.FILENAME, filename) # # def _get_basic_tablename_keyvalue_mapping(self): # from collections import OrderedDict # # return OrderedDict( # [ # (tnt.DEFAULT, self._get_default_table_name_template()), # (tnt.FORMAT_NAME, self.format_name), # (tnt.FORMAT_ID, str(self.__get_format_table_count())), # (tnt.GLOBAL_ID, str(self.__global_table_count)), # self._get_filename_tablename_mapping(), # ] # ) # # def _expand_table_name_format(self, table_name_kv_mapping): # self._validate_table_name() # # table_name = self.table_name # for template, value in table_name_kv_mapping.items(): # table_name = table_name.replace(template, value) # # return self._sanitize_table_name(table_name) # # def _make_table_name(self): # self._validate_table_name() # # return self._expand_table_name_format(self._get_basic_tablename_keyvalue_mapping()) # # @staticmethod # def _sanitize_table_name(table_name): # if typepy.is_null_string(table_name): # raise InvalidTableNameError("table name is empty after the template replacement") # # return table_name.strip("_") # # @classmethod # def clear_table_count(cls): # with cls.__table_count_lock: # cls.__global_table_count = 0 # cls.__format_table_count = {} # # Path: pytablereader/markdown/formatter.py # class MarkdownTableFormatter(HtmlTableFormatter): # def __init__(self, source_data, logger=None): # import markdown # # if typepy.is_null_string(source_data): # raise DataError # # super().__init__( # markdown.markdown(source_data, extensions=["markdown.extensions.tables"]), logger=logger # ) . Output only the next line.
MarkdownTableFormatter(source)
Here is a snippet: <|code_start|>""" .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ try: except ImportError: def get_file_encoding(file_path, encoding): if encoding: return encoding encoding = detect_file_encoding(file_path) if not encoding: <|code_end|> . Write the next line using the current file imports: import os.path import posixpath import pathvalidate import typepy import simplejson as json import json # type: ignore # noqa from urllib.parse import urlparse from ._constant import Default from .error import InvalidFilePathError from mbstrdecoder import detect_file_encoding and context from other files: # Path: pytablereader/_constant.py # class Default: # ENCODING = "utf-8" # # Path: pytablereader/error.py # class InvalidFilePathError(PathError): # """ # Exception raised when invalid file path used. # # TODO: rename the error class # """ , which may include functions, classes, or code. Output only the next line.
return Default.ENCODING
Using the snippet: <|code_start|>""" .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ try: except ImportError: def get_file_encoding(file_path, encoding): if encoding: return encoding encoding = detect_file_encoding(file_path) if not encoding: return Default.ENCODING return encoding def get_extension(file_path): if typepy.is_null_string(file_path): <|code_end|> , determine the next line of code. You have imports: import os.path import posixpath import pathvalidate import typepy import simplejson as json import json # type: ignore # noqa from urllib.parse import urlparse from ._constant import Default from .error import InvalidFilePathError from mbstrdecoder import detect_file_encoding and context (class names, function names, or code) available: # Path: pytablereader/_constant.py # class Default: # ENCODING = "utf-8" # # Path: pytablereader/error.py # class InvalidFilePathError(PathError): # """ # Exception raised when invalid file path used. # # TODO: rename the error class # """ . Output only the next line.
raise InvalidFilePathError("file path is empty")
Given the code snippet: <|code_start|> test_file_path.parent.makedirs_p() with open(test_file_path, "w") as f: f.write("""{}""") loader = ptr.TableFileLoader(test_file_path, format_name=format_name) expected_loader = expected("") assert loader.source_type == expected_loader.source_type assert loader.format_name == expected_loader.format_name @pytest.mark.parametrize( ["value", "format_name", "expected"], [ [None, None, ValueError], ["", None, ptr.InvalidFilePathError], ["https://github.com/", None, ptr.LoaderNotFoundError], ["/tmp/test.txt", None, ptr.LoaderNotFoundError], ["c:\\tmp\test.txt", None, ptr.LoaderNotFoundError], ["/tmp/valid/test/data/validext.csv/", None, ptr.LoaderNotFoundError], ["/tmp/invalid/test/data/invalidext.txt", "invalidformat", ptr.LoaderNotFoundError], ], ) def test_exception(self, value, format_name, expected): with pytest.raises(expected): ptr.TableFileLoader(value, format_name=format_name) class Test_TableFileLoader_load: def setup_method(self, method): <|code_end|> , generate the next line using the imports in this file: from textwrap import dedent from mbstrdecoder import MultiByteStrDecoder from path import Path from pytablewriter import ExcelXlsxTableWriter, dumps_tabledata from tabledata import TableData from pytablereader.interface import AbstractTableReader import pathvalidate as pv import pytest import pytablereader as ptr and context (functions, classes, or occasionally code) from other files: # Path: pytablereader/interface.py # class AbstractTableReader(TableLoaderInterface, metaclass=abc.ABCMeta): # """ # The abstract class of table data file loader. # # .. py:attribute:: table_name # # Table name string. # # .. py:attribute:: source # # Table data source to load. # """ # # __table_count_lock = threading.Lock() # __global_table_count = 0 # __format_table_count = {} # # @property # def source_type(self): # return self._validator.source_type # # @property # def quoting_flags(self): # return self.__quoting_flags # # @property # def dp_extractor(self): # return self.__dp_extractor # # def __init__(self, source, quoting_flags, type_hints, type_hint_rules=None): # self.table_name = tnt.DEFAULT # self.source = source # self.__quoting_flags = quoting_flags # self.type_hints = type_hints # self.type_hint_rules = type_hint_rules # self._validator = None # self._logger = None # # self.__dp_extractor = DataPropertyExtractor() # self.__dp_extractor.quoting_flags = self.quoting_flags # self.__dp_extractor.update_strict_level_map({typepy.Typecode.BOOL: 1}) # # def get_format_key(self): # return f"{self.format_name:s}{self.__get_format_table_count():d}" # # def make_table_name(self): # return self._make_table_name() # # def inc_table_count(self): # with self.__table_count_lock: # self.__global_table_count += 1 # self.__format_table_count[self.format_name] = self.__get_format_table_count() + 1 # # @abc.abstractmethod # def _get_default_table_name_template(self): # pragma: no cover # pass # # def _validate(self): # self._validate_table_name() # self._validate_source() # # def _validate_table_name(self): # try: # if typepy.is_null_string(self.table_name): # raise ValueError("table name is empty") # except (TypeError, AttributeError): # raise TypeError("table_name must be a string") # # def _validate_source(self): # self._validator.validate() # # def __get_format_table_count(self): # return self.__format_table_count.get(self.format_name, 0) # # def _get_filename_tablename_mapping(self): # filename = "" # if all([self.source_type == SourceType.FILE, typepy.is_not_null_string(self.source)]): # filename = path.Path(self.source).stem # # return (tnt.FILENAME, filename) # # def _get_basic_tablename_keyvalue_mapping(self): # from collections import OrderedDict # # return OrderedDict( # [ # (tnt.DEFAULT, self._get_default_table_name_template()), # (tnt.FORMAT_NAME, self.format_name), # (tnt.FORMAT_ID, str(self.__get_format_table_count())), # (tnt.GLOBAL_ID, str(self.__global_table_count)), # self._get_filename_tablename_mapping(), # ] # ) # # def _expand_table_name_format(self, table_name_kv_mapping): # self._validate_table_name() # # table_name = self.table_name # for template, value in table_name_kv_mapping.items(): # table_name = table_name.replace(template, value) # # return self._sanitize_table_name(table_name) # # def _make_table_name(self): # self._validate_table_name() # # return self._expand_table_name_format(self._get_basic_tablename_keyvalue_mapping()) # # @staticmethod # def _sanitize_table_name(table_name): # if typepy.is_null_string(table_name): # raise InvalidTableNameError("table name is empty after the template replacement") # # return table_name.strip("_") # # @classmethod # def clear_table_count(cls): # with cls.__table_count_lock: # cls.__global_table_count = 0 # cls.__format_table_count = {} . Output only the next line.
AbstractTableReader.clear_table_count()
Predict the next line for this snippet: <|code_start|>""" .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ class BaseTableLoaderFactory(metaclass=abc.ABCMeta): @property def source(self): """ :return: Data source to load. :rtype: str """ return self._source def __init__(self, source, encoding=None): if not encoding: <|code_end|> with the help of current file imports: import abc import warnings from mbstrdecoder import MultiByteStrDecoder from .._constant import Default from ..error import LoaderNotFoundError and context from other files: # Path: pytablereader/_constant.py # class Default: # ENCODING = "utf-8" # # Path: pytablereader/error.py # class LoaderNotFoundError(Exception): # """ # Exception raised when loader not found. # """ , which may contain function names, class names, or code. Output only the next line.
self._encoding = Default.ENCODING
Next line prediction: <|code_start|> :rtype: list """ return sorted(self._get_format_name_loader_mapping()) def get_format_name_list(self): warnings.warn("'get_format_name_list' has moved to 'get_format_names'", DeprecationWarning) return self.get_format_names() def get_extensions(self): """ :return: Available format file extensions. :rtype: list """ return sorted(self._get_extension_loader_mapping()) def get_extension_list(self): warnings.warn("'get_extension_list' has moved to 'get_extensions'", DeprecationWarning) return self.get_extensions() def _get_loader_class(self, loader_mapping, format_name): try: format_name = format_name.casefold() except AttributeError: raise TypeError("format name must be a string") try: return loader_mapping[format_name] except KeyError: <|code_end|> . Use current file imports: (import abc import warnings from mbstrdecoder import MultiByteStrDecoder from .._constant import Default from ..error import LoaderNotFoundError) and context including class names, function names, or small code snippets from other files: # Path: pytablereader/_constant.py # class Default: # ENCODING = "utf-8" # # Path: pytablereader/error.py # class LoaderNotFoundError(Exception): # """ # Exception raised when loader not found. # """ . Output only the next line.
raise LoaderNotFoundError(
Continue the code snippet: <|code_start|>""" .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ class Test_FileValidator_validate: @pytest.mark.parametrize(["value"], [["test"]]) def test_normal(self, tmpdir, value): p_file_path = tmpdir.join(value) with open(str(p_file_path), "w"): pass validator = FileValidator(str(p_file_path)) <|code_end|> . Use current file imports: import platform import pytest import pytablereader as ptr from pytablereader._constant import SourceType from pytablereader._validator import FileValidator, TextValidator, UrlValidator, is_fifo and context (classes, functions, or code) from other files: # Path: pytablereader/_constant.py # class SourceType: # TEXT = "text" # FILE = "file" # URL = "url" # OBJECT = "object" # # Path: pytablereader/_validator.py # class FileValidator(BaseValidator): # """ # Validator class for file data source. # """ # # @property # def source_type(self): # return SourceType.FILE # # def validate(self): # try: # pv.validate_filepath(self.source, platform="auto") # except pv.ValidationError as e: # raise InvalidFilePathError(e) # # if os.path.isfile(self.source) or is_fifo(self.source): # return # # raise OSError("file not found") # # class TextValidator(BaseValidator): # """ # Validator class for text object data source. # """ # # @property # def source_type(self): # return SourceType.TEXT # # def validate(self): # if typepy.is_null_string(self.source): # raise DataError("data source is empty") # # class UrlValidator(BaseValidator): # """ # Validator class for URL data source. # """ # # @property # def source_type(self): # return SourceType.URL # # def validate(self): # if typepy.is_null_string(self.source): # raise UrlError("url is empty") # # scheme = urlparse(self.source).scheme # if scheme not in ["http", "https"]: # raise UrlError(f"invalid scheme: expected=http/https, actual={scheme}") # # def is_fifo(file_path: str) -> bool: # try: # return stat.S_ISFIFO(os.stat(file_path).st_mode) # except OSError as e: # logger.error(f"errno: {e.errno}") # # if e.errno not in (EBADF, ENAMETOOLONG, ENOENT, ENOTDIR): # raise # # return False # except ValueError: # return False . Output only the next line.
assert validator.source_type == SourceType.FILE
Predict the next line after this snippet: <|code_start|>""" .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ class Test_FileValidator_validate: @pytest.mark.parametrize(["value"], [["test"]]) def test_normal(self, tmpdir, value): p_file_path = tmpdir.join(value) with open(str(p_file_path), "w"): pass <|code_end|> using the current file's imports: import platform import pytest import pytablereader as ptr from pytablereader._constant import SourceType from pytablereader._validator import FileValidator, TextValidator, UrlValidator, is_fifo and any relevant context from other files: # Path: pytablereader/_constant.py # class SourceType: # TEXT = "text" # FILE = "file" # URL = "url" # OBJECT = "object" # # Path: pytablereader/_validator.py # class FileValidator(BaseValidator): # """ # Validator class for file data source. # """ # # @property # def source_type(self): # return SourceType.FILE # # def validate(self): # try: # pv.validate_filepath(self.source, platform="auto") # except pv.ValidationError as e: # raise InvalidFilePathError(e) # # if os.path.isfile(self.source) or is_fifo(self.source): # return # # raise OSError("file not found") # # class TextValidator(BaseValidator): # """ # Validator class for text object data source. # """ # # @property # def source_type(self): # return SourceType.TEXT # # def validate(self): # if typepy.is_null_string(self.source): # raise DataError("data source is empty") # # class UrlValidator(BaseValidator): # """ # Validator class for URL data source. # """ # # @property # def source_type(self): # return SourceType.URL # # def validate(self): # if typepy.is_null_string(self.source): # raise UrlError("url is empty") # # scheme = urlparse(self.source).scheme # if scheme not in ["http", "https"]: # raise UrlError(f"invalid scheme: expected=http/https, actual={scheme}") # # def is_fifo(file_path: str) -> bool: # try: # return stat.S_ISFIFO(os.stat(file_path).st_mode) # except OSError as e: # logger.error(f"errno: {e.errno}") # # if e.errno not in (EBADF, ENAMETOOLONG, ENOENT, ENOTDIR): # raise # # return False # except ValueError: # return False . Output only the next line.
validator = FileValidator(str(p_file_path))
Given snippet: <|code_start|> def test_normal(self, tmpdir, value): p_file_path = tmpdir.join(value) with open(str(p_file_path), "w"): pass validator = FileValidator(str(p_file_path)) assert validator.source_type == SourceType.FILE validator.validate() @pytest.mark.parametrize( ["value", "expected"], [[None, ptr.InvalidFilePathError], ["", ptr.InvalidFilePathError]] ) def test_exception_null(self, value, expected): validator = FileValidator(value) with pytest.raises(expected): validator.validate() @pytest.mark.parametrize(["value", "expected"], [["te\0st", ptr.InvalidFilePathError]]) def test_exception_invalid_path(self, tmpdir, value, expected): validator = FileValidator(value) with pytest.raises(expected): validator.validate() class Test_TextValidator_validate: @pytest.mark.parametrize(["value"], [["test"]]) def test_normal(self, value): <|code_end|> , continue by predicting the next line. Consider current file imports: import platform import pytest import pytablereader as ptr from pytablereader._constant import SourceType from pytablereader._validator import FileValidator, TextValidator, UrlValidator, is_fifo and context: # Path: pytablereader/_constant.py # class SourceType: # TEXT = "text" # FILE = "file" # URL = "url" # OBJECT = "object" # # Path: pytablereader/_validator.py # class FileValidator(BaseValidator): # """ # Validator class for file data source. # """ # # @property # def source_type(self): # return SourceType.FILE # # def validate(self): # try: # pv.validate_filepath(self.source, platform="auto") # except pv.ValidationError as e: # raise InvalidFilePathError(e) # # if os.path.isfile(self.source) or is_fifo(self.source): # return # # raise OSError("file not found") # # class TextValidator(BaseValidator): # """ # Validator class for text object data source. # """ # # @property # def source_type(self): # return SourceType.TEXT # # def validate(self): # if typepy.is_null_string(self.source): # raise DataError("data source is empty") # # class UrlValidator(BaseValidator): # """ # Validator class for URL data source. # """ # # @property # def source_type(self): # return SourceType.URL # # def validate(self): # if typepy.is_null_string(self.source): # raise UrlError("url is empty") # # scheme = urlparse(self.source).scheme # if scheme not in ["http", "https"]: # raise UrlError(f"invalid scheme: expected=http/https, actual={scheme}") # # def is_fifo(file_path: str) -> bool: # try: # return stat.S_ISFIFO(os.stat(file_path).st_mode) # except OSError as e: # logger.error(f"errno: {e.errno}") # # if e.errno not in (EBADF, ENAMETOOLONG, ENOENT, ENOTDIR): # raise # # return False # except ValueError: # return False which might include code, classes, or functions. Output only the next line.
validator = TextValidator(value)
Based on the snippet: <|code_start|> with pytest.raises(expected): validator.validate() @pytest.mark.parametrize(["value", "expected"], [["te\0st", ptr.InvalidFilePathError]]) def test_exception_invalid_path(self, tmpdir, value, expected): validator = FileValidator(value) with pytest.raises(expected): validator.validate() class Test_TextValidator_validate: @pytest.mark.parametrize(["value"], [["test"]]) def test_normal(self, value): validator = TextValidator(value) assert validator.source_type == SourceType.TEXT validator.validate() @pytest.mark.parametrize(["value", "expected"], [[None, ptr.DataError], ["", ptr.DataError]]) def test_exception(self, value, expected): validator = TextValidator(value) with pytest.raises(expected): validator.validate() class Test_UrlValidator_validate: @pytest.mark.parametrize(["value"], [["http://www.google.com"], ["https://github.com/"]]) def test_normal(self, value): <|code_end|> , predict the immediate next line with the help of imports: import platform import pytest import pytablereader as ptr from pytablereader._constant import SourceType from pytablereader._validator import FileValidator, TextValidator, UrlValidator, is_fifo and context (classes, functions, sometimes code) from other files: # Path: pytablereader/_constant.py # class SourceType: # TEXT = "text" # FILE = "file" # URL = "url" # OBJECT = "object" # # Path: pytablereader/_validator.py # class FileValidator(BaseValidator): # """ # Validator class for file data source. # """ # # @property # def source_type(self): # return SourceType.FILE # # def validate(self): # try: # pv.validate_filepath(self.source, platform="auto") # except pv.ValidationError as e: # raise InvalidFilePathError(e) # # if os.path.isfile(self.source) or is_fifo(self.source): # return # # raise OSError("file not found") # # class TextValidator(BaseValidator): # """ # Validator class for text object data source. # """ # # @property # def source_type(self): # return SourceType.TEXT # # def validate(self): # if typepy.is_null_string(self.source): # raise DataError("data source is empty") # # class UrlValidator(BaseValidator): # """ # Validator class for URL data source. # """ # # @property # def source_type(self): # return SourceType.URL # # def validate(self): # if typepy.is_null_string(self.source): # raise UrlError("url is empty") # # scheme = urlparse(self.source).scheme # if scheme not in ["http", "https"]: # raise UrlError(f"invalid scheme: expected=http/https, actual={scheme}") # # def is_fifo(file_path: str) -> bool: # try: # return stat.S_ISFIFO(os.stat(file_path).st_mode) # except OSError as e: # logger.error(f"errno: {e.errno}") # # if e.errno not in (EBADF, ENAMETOOLONG, ENOENT, ENOTDIR): # raise # # return False # except ValueError: # return False . Output only the next line.
validator = UrlValidator(value)
Here is a snippet: <|code_start|> validator = TextValidator(value) with pytest.raises(expected): validator.validate() class Test_UrlValidator_validate: @pytest.mark.parametrize(["value"], [["http://www.google.com"], ["https://github.com/"]]) def test_normal(self, value): validator = UrlValidator(value) assert validator.source_type == SourceType.URL validator.validate() @pytest.mark.parametrize( ["value", "expected"], [[None, ptr.UrlError], ["", ptr.UrlError], ["www.google.com", ptr.UrlError]], ) def test_exception(self, value, expected): validator = UrlValidator(value) with pytest.raises(expected): validator.validate() class Test_is_fifo: @pytest.mark.skipif( platform.system() == "Windows", reason="platform dependent tests: only failed at GitHub Actions", ) def test_filename_too_long(self): <|code_end|> . Write the next line using the current file imports: import platform import pytest import pytablereader as ptr from pytablereader._constant import SourceType from pytablereader._validator import FileValidator, TextValidator, UrlValidator, is_fifo and context from other files: # Path: pytablereader/_constant.py # class SourceType: # TEXT = "text" # FILE = "file" # URL = "url" # OBJECT = "object" # # Path: pytablereader/_validator.py # class FileValidator(BaseValidator): # """ # Validator class for file data source. # """ # # @property # def source_type(self): # return SourceType.FILE # # def validate(self): # try: # pv.validate_filepath(self.source, platform="auto") # except pv.ValidationError as e: # raise InvalidFilePathError(e) # # if os.path.isfile(self.source) or is_fifo(self.source): # return # # raise OSError("file not found") # # class TextValidator(BaseValidator): # """ # Validator class for text object data source. # """ # # @property # def source_type(self): # return SourceType.TEXT # # def validate(self): # if typepy.is_null_string(self.source): # raise DataError("data source is empty") # # class UrlValidator(BaseValidator): # """ # Validator class for URL data source. # """ # # @property # def source_type(self): # return SourceType.URL # # def validate(self): # if typepy.is_null_string(self.source): # raise UrlError("url is empty") # # scheme = urlparse(self.source).scheme # if scheme not in ["http", "https"]: # raise UrlError(f"invalid scheme: expected=http/https, actual={scheme}") # # def is_fifo(file_path: str) -> bool: # try: # return stat.S_ISFIFO(os.stat(file_path).st_mode) # except OSError as e: # logger.error(f"errno: {e.errno}") # # if e.errno not in (EBADF, ENAMETOOLONG, ENOENT, ENOTDIR): # raise # # return False # except ValueError: # return False , which may include functions, classes, or code. Output only the next line.
assert not is_fifo("a" * 1000)
Given the code snippet: <|code_start|> ["", None, ptr.UrlError], ["https://github.com/", None, ptr.UrlError], ["/tmp/test.txt", None, ptr.UrlError], ["c:\\tmp\test.txt", None, ptr.UrlError], [ "https://raw.githubusercontent.com/invalid/test/data/invalidext.txt", None, ptr.LoaderNotFoundError, ], [ "https://raw.githubusercontent.com/invalid/test/data/notexist.json", None, ptr.HTTPError, ], [ "https://raw.githubusercontent.com/invalid/test/data/invalidext.txt", "invalidformat", ptr.LoaderNotFoundError, ], ], ) def test_exception(self, value, format_name, expected): responses.add(responses.GET, value, body="""404: Not Found""", status=404) with pytest.raises(expected): ptr.TableUrlLoader(value, format_name) class Test_TableUrlLoader_load: def setup_method(self, method): <|code_end|> , generate the next line using the imports in this file: import os.path import pytest import responses import pytablereader as ptr from os.path import dirname from textwrap import dedent from pytablewriter import dumps_tabledata from tabledata import TableData from pytablereader.interface import AbstractTableReader and context (functions, classes, or occasionally code) from other files: # Path: pytablereader/interface.py # class AbstractTableReader(TableLoaderInterface, metaclass=abc.ABCMeta): # """ # The abstract class of table data file loader. # # .. py:attribute:: table_name # # Table name string. # # .. py:attribute:: source # # Table data source to load. # """ # # __table_count_lock = threading.Lock() # __global_table_count = 0 # __format_table_count = {} # # @property # def source_type(self): # return self._validator.source_type # # @property # def quoting_flags(self): # return self.__quoting_flags # # @property # def dp_extractor(self): # return self.__dp_extractor # # def __init__(self, source, quoting_flags, type_hints, type_hint_rules=None): # self.table_name = tnt.DEFAULT # self.source = source # self.__quoting_flags = quoting_flags # self.type_hints = type_hints # self.type_hint_rules = type_hint_rules # self._validator = None # self._logger = None # # self.__dp_extractor = DataPropertyExtractor() # self.__dp_extractor.quoting_flags = self.quoting_flags # self.__dp_extractor.update_strict_level_map({typepy.Typecode.BOOL: 1}) # # def get_format_key(self): # return f"{self.format_name:s}{self.__get_format_table_count():d}" # # def make_table_name(self): # return self._make_table_name() # # def inc_table_count(self): # with self.__table_count_lock: # self.__global_table_count += 1 # self.__format_table_count[self.format_name] = self.__get_format_table_count() + 1 # # @abc.abstractmethod # def _get_default_table_name_template(self): # pragma: no cover # pass # # def _validate(self): # self._validate_table_name() # self._validate_source() # # def _validate_table_name(self): # try: # if typepy.is_null_string(self.table_name): # raise ValueError("table name is empty") # except (TypeError, AttributeError): # raise TypeError("table_name must be a string") # # def _validate_source(self): # self._validator.validate() # # def __get_format_table_count(self): # return self.__format_table_count.get(self.format_name, 0) # # def _get_filename_tablename_mapping(self): # filename = "" # if all([self.source_type == SourceType.FILE, typepy.is_not_null_string(self.source)]): # filename = path.Path(self.source).stem # # return (tnt.FILENAME, filename) # # def _get_basic_tablename_keyvalue_mapping(self): # from collections import OrderedDict # # return OrderedDict( # [ # (tnt.DEFAULT, self._get_default_table_name_template()), # (tnt.FORMAT_NAME, self.format_name), # (tnt.FORMAT_ID, str(self.__get_format_table_count())), # (tnt.GLOBAL_ID, str(self.__global_table_count)), # self._get_filename_tablename_mapping(), # ] # ) # # def _expand_table_name_format(self, table_name_kv_mapping): # self._validate_table_name() # # table_name = self.table_name # for template, value in table_name_kv_mapping.items(): # table_name = table_name.replace(template, value) # # return self._sanitize_table_name(table_name) # # def _make_table_name(self): # self._validate_table_name() # # return self._expand_table_name_format(self._get_basic_tablename_keyvalue_mapping()) # # @staticmethod # def _sanitize_table_name(table_name): # if typepy.is_null_string(table_name): # raise InvalidTableNameError("table name is empty after the template replacement") # # return table_name.strip("_") # # @classmethod # def clear_table_count(cls): # with cls.__table_count_lock: # cls.__global_table_count = 0 # cls.__format_table_count = {} . Output only the next line.
AbstractTableReader.clear_table_count()
Predict the next line for this snippet: <|code_start|>""" .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ class Test_get_extension: @pytest.mark.parametrize( ["value", "expected"], [["test.txt", "txt"], [".csv", ""], ["html", ""]] ) def test_normal(self, value, expected): assert get_extension(value) == expected @pytest.mark.parametrize( <|code_end|> with the help of current file imports: import pytest from pytablereader import InvalidFilePathError from pytablereader._common import get_extension, make_temp_file_path_from_url and context from other files: # Path: pytablereader/error.py # class InvalidFilePathError(PathError): # """ # Exception raised when invalid file path used. # # TODO: rename the error class # """ # # Path: pytablereader/_common.py # def get_extension(file_path): # if typepy.is_null_string(file_path): # raise InvalidFilePathError("file path is empty") # # return os.path.splitext(file_path)[1].lstrip(".") # # def make_temp_file_path_from_url(temp_dir_path, url): # try: # url_path = urlparse(url).path # except AttributeError: # raise InvalidFilePathError("url must be a string") # # if typepy.is_null_string(url_path): # raise InvalidFilePathError(f"invalid URL path: {url_path}") # # temp_name = os.path.basename(url_path.rstrip("/")) # if typepy.is_null_string(temp_name): # temp_name = pathvalidate.replace_symbol(temp_name, replacement_text="_") # # if typepy.is_null_string(temp_name): # raise InvalidFilePathError(f"invalid URL: {url}") # # try: # return posixpath.join(temp_dir_path, temp_name) # except (TypeError, AttributeError): # raise InvalidFilePathError("temp_dir_path must be a string") , which may contain function names, class names, or code. Output only the next line.
["value", "expected"], [["", InvalidFilePathError], [None, InvalidFilePathError]]
Next line prediction: <|code_start|>""" .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ class Test_get_extension: @pytest.mark.parametrize( ["value", "expected"], [["test.txt", "txt"], [".csv", ""], ["html", ""]] ) def test_normal(self, value, expected): <|code_end|> . Use current file imports: (import pytest from pytablereader import InvalidFilePathError from pytablereader._common import get_extension, make_temp_file_path_from_url) and context including class names, function names, or small code snippets from other files: # Path: pytablereader/error.py # class InvalidFilePathError(PathError): # """ # Exception raised when invalid file path used. # # TODO: rename the error class # """ # # Path: pytablereader/_common.py # def get_extension(file_path): # if typepy.is_null_string(file_path): # raise InvalidFilePathError("file path is empty") # # return os.path.splitext(file_path)[1].lstrip(".") # # def make_temp_file_path_from_url(temp_dir_path, url): # try: # url_path = urlparse(url).path # except AttributeError: # raise InvalidFilePathError("url must be a string") # # if typepy.is_null_string(url_path): # raise InvalidFilePathError(f"invalid URL path: {url_path}") # # temp_name = os.path.basename(url_path.rstrip("/")) # if typepy.is_null_string(temp_name): # temp_name = pathvalidate.replace_symbol(temp_name, replacement_text="_") # # if typepy.is_null_string(temp_name): # raise InvalidFilePathError(f"invalid URL: {url}") # # try: # return posixpath.join(temp_dir_path, temp_name) # except (TypeError, AttributeError): # raise InvalidFilePathError("temp_dir_path must be a string") . Output only the next line.
assert get_extension(value) == expected
Using the snippet: <|code_start|> ["value", "expected"], [["test.txt", "txt"], [".csv", ""], ["html", ""]] ) def test_normal(self, value, expected): assert get_extension(value) == expected @pytest.mark.parametrize( ["value", "expected"], [["", InvalidFilePathError], [None, InvalidFilePathError]] ) def test_null_table_name(self, value, expected): with pytest.raises(expected): get_extension(value) class Test_make_temp_file_path_from_url: @pytest.mark.parametrize( ["temp_dir_path", "value", "expected"], [ [ "/tmp", "https://raw.githubusercontent.com/valid/test/data/validext.csv", "/tmp/validext.csv", ], [ "/tmp", "https://raw.githubusercontent.com/valid/test/data/validext/", "/tmp/validext", ], ], ) def test_normal(self, temp_dir_path, value, expected): <|code_end|> , determine the next line of code. You have imports: import pytest from pytablereader import InvalidFilePathError from pytablereader._common import get_extension, make_temp_file_path_from_url and context (class names, function names, or code) available: # Path: pytablereader/error.py # class InvalidFilePathError(PathError): # """ # Exception raised when invalid file path used. # # TODO: rename the error class # """ # # Path: pytablereader/_common.py # def get_extension(file_path): # if typepy.is_null_string(file_path): # raise InvalidFilePathError("file path is empty") # # return os.path.splitext(file_path)[1].lstrip(".") # # def make_temp_file_path_from_url(temp_dir_path, url): # try: # url_path = urlparse(url).path # except AttributeError: # raise InvalidFilePathError("url must be a string") # # if typepy.is_null_string(url_path): # raise InvalidFilePathError(f"invalid URL path: {url_path}") # # temp_name = os.path.basename(url_path.rstrip("/")) # if typepy.is_null_string(temp_name): # temp_name = pathvalidate.replace_symbol(temp_name, replacement_text="_") # # if typepy.is_null_string(temp_name): # raise InvalidFilePathError(f"invalid URL: {url}") # # try: # return posixpath.join(temp_dir_path, temp_name) # except (TypeError, AttributeError): # raise InvalidFilePathError("temp_dir_path must be a string") . Output only the next line.
assert make_temp_file_path_from_url(temp_dir_path, value) == expected
Given the code snippet: <|code_start|> write_worksheet( workbook.add_worksheet("invalid_sheet"), table=[["", "", "", ""], ["", "a", "", "c"], ["", "aa", "ab", ""], ["", "", 1.1, "a"]], ) workbook.close() return str(test_file_path) @pytest.fixture def invalid_excel_file_path(tmpdir): test_file_path = tmpdir.join("invalid.xlsx") workbook = xlsxwriter.Workbook(str(test_file_path)) write_worksheet( workbook.add_worksheet("testsheet1"), table=[["", "", "", ""], ["", "a", "", "c"], ["", "aa", "ab", ""], ["", "", 1.1, "a"]], ) worksheet = workbook.add_worksheet("testsheet2") # noqa: W0612 workbook.close() return str(test_file_path) @pytest.mark.xfail(run=False) class Test_ExcelTableFileLoader_make_table_name: def setup_method(self, method): <|code_end|> , generate the next line using the imports in this file: import pytest import xlsxwriter import pytablereader as ptr from pytablewriter import dumps_tabledata from tabledata import TableData from pytablereader.interface import AbstractTableReader and context (functions, classes, or occasionally code) from other files: # Path: pytablereader/interface.py # class AbstractTableReader(TableLoaderInterface, metaclass=abc.ABCMeta): # """ # The abstract class of table data file loader. # # .. py:attribute:: table_name # # Table name string. # # .. py:attribute:: source # # Table data source to load. # """ # # __table_count_lock = threading.Lock() # __global_table_count = 0 # __format_table_count = {} # # @property # def source_type(self): # return self._validator.source_type # # @property # def quoting_flags(self): # return self.__quoting_flags # # @property # def dp_extractor(self): # return self.__dp_extractor # # def __init__(self, source, quoting_flags, type_hints, type_hint_rules=None): # self.table_name = tnt.DEFAULT # self.source = source # self.__quoting_flags = quoting_flags # self.type_hints = type_hints # self.type_hint_rules = type_hint_rules # self._validator = None # self._logger = None # # self.__dp_extractor = DataPropertyExtractor() # self.__dp_extractor.quoting_flags = self.quoting_flags # self.__dp_extractor.update_strict_level_map({typepy.Typecode.BOOL: 1}) # # def get_format_key(self): # return f"{self.format_name:s}{self.__get_format_table_count():d}" # # def make_table_name(self): # return self._make_table_name() # # def inc_table_count(self): # with self.__table_count_lock: # self.__global_table_count += 1 # self.__format_table_count[self.format_name] = self.__get_format_table_count() + 1 # # @abc.abstractmethod # def _get_default_table_name_template(self): # pragma: no cover # pass # # def _validate(self): # self._validate_table_name() # self._validate_source() # # def _validate_table_name(self): # try: # if typepy.is_null_string(self.table_name): # raise ValueError("table name is empty") # except (TypeError, AttributeError): # raise TypeError("table_name must be a string") # # def _validate_source(self): # self._validator.validate() # # def __get_format_table_count(self): # return self.__format_table_count.get(self.format_name, 0) # # def _get_filename_tablename_mapping(self): # filename = "" # if all([self.source_type == SourceType.FILE, typepy.is_not_null_string(self.source)]): # filename = path.Path(self.source).stem # # return (tnt.FILENAME, filename) # # def _get_basic_tablename_keyvalue_mapping(self): # from collections import OrderedDict # # return OrderedDict( # [ # (tnt.DEFAULT, self._get_default_table_name_template()), # (tnt.FORMAT_NAME, self.format_name), # (tnt.FORMAT_ID, str(self.__get_format_table_count())), # (tnt.GLOBAL_ID, str(self.__global_table_count)), # self._get_filename_tablename_mapping(), # ] # ) # # def _expand_table_name_format(self, table_name_kv_mapping): # self._validate_table_name() # # table_name = self.table_name # for template, value in table_name_kv_mapping.items(): # table_name = table_name.replace(template, value) # # return self._sanitize_table_name(table_name) # # def _make_table_name(self): # self._validate_table_name() # # return self._expand_table_name_format(self._get_basic_tablename_keyvalue_mapping()) # # @staticmethod # def _sanitize_table_name(table_name): # if typepy.is_null_string(table_name): # raise InvalidTableNameError("table name is empty after the template replacement") # # return table_name.strip("_") # # @classmethod # def clear_table_count(cls): # with cls.__table_count_lock: # cls.__global_table_count = 0 # cls.__format_table_count = {} . Output only the next line.
AbstractTableReader.clear_table_count()
Predict the next line for this snippet: <|code_start|>class TableTextLoader(TableLoaderManager): """ Loader class to loading tables from URL. :param str url: URL to load. :param str format_name: Data format name to load. Supported formats can be get by :py:meth:`.get_format_names` :param dict proxies: http/https proxy information. .. seealso:: `requests proxies <http://docs.python-requests.org/en/master/user/advanced/#proxies>`__ :raises pytablereader.LoaderNotFoundError: |LoaderNotFoundError_desc| loading the URL. .. py:method:: load Load tables from text as ``format_name`` format. :return: Loaded table data iterator. :rtype: |TableData| iterator .. seealso:: * :py:meth:`pytablereader.factory.TableTextLoaderFactory.create_from_format_name` * :py:meth:`pytablereader.factory.TableTextLoaderFactory.create_from_path` """ def __init__( self, source: str, format_name: str, encoding: Optional[str] = None, type_hint_rules=None ) -> None: <|code_end|> with the help of current file imports: from typing import Optional, Sequence from ..factory import TableTextLoaderFactory from ._base import TableLoaderManager import typepy and context from other files: # Path: pytablereader/factory/_text.py # class TableTextLoaderFactory(BaseTableLoaderFactory): # def create_from_path(self): # raise NotImplementedError() # # def create_from_format_name(self, format_name): # """ # Create a file loader from a format name. # Supported file formats are as follows: # # ========================== ====================================== # Format name Loader # ========================== ====================================== # ``"csv"`` :py:class:`~.CsvTableTextLoader` # ``"html"`` :py:class:`~.HtmlTableTextLoader` # ``"json"`` :py:class:`~.JsonTableTextLoader` # ``"json_lines"`` :py:class:`~.JsonLinesTableTextLoader` # ``"jsonl"`` :py:class:`~.JsonLinesTableTextLoader` # ``"ldjson"`` :py:class:`~.JsonLinesTableTextLoader` # ``"ltsv"`` :py:class:`~.LtsvTableTextLoader` # ``"markdown"`` :py:class:`~.MarkdownTableTextLoader` # ``"mediawiki"`` :py:class:`~.MediaWikiTableTextLoader` # ``"ndjson"`` :py:class:`~.JsonLinesTableTextLoader` # ``"ssv"`` :py:class:`~.CsvTableTextLoader` # ``"tsv"`` :py:class:`~.TsvTableTextLoader` # ========================== ====================================== # # :param str format_name: Format name string (case insensitive). # :return: Loader that coincide with the ``format_name``: # :raises pytablereader.LoaderNotFoundError: # |LoaderNotFoundError_desc| the format. # :raises TypeError: If ``format_name`` is not a string. # """ # # loader = self._create_from_format_name(format_name) # # logger.debug(f"TableTextLoaderFactory: name={format_name}, loader={loader.format_name}") # # return loader # # def _get_common_loader_mapping(self): # return { # "csv": CsvTableTextLoader, # "html": HtmlTableTextLoader, # "json": JsonTableTextLoader, # "jsonl": JsonLinesTableTextLoader, # "ldjson": JsonLinesTableTextLoader, # "ltsv": LtsvTableTextLoader, # "ndjson": JsonLinesTableTextLoader, # "tsv": TsvTableTextLoader, # } # # def _get_extension_loader_mapping(self): # """ # :return: Mappings of format-extension and loader class. # :rtype: dict # """ # # loader_table = self._get_common_loader_mapping() # loader_table.update({"htm": HtmlTableTextLoader, "md": MarkdownTableTextLoader}) # # return loader_table # # def _get_format_name_loader_mapping(self): # """ # :return: Mappings of format-name and loader class. # :rtype: dict # """ # # loader_table = self._get_common_loader_mapping() # loader_table.update( # { # "json_lines": JsonLinesTableTextLoader, # "markdown": MarkdownTableTextLoader, # "mediawiki": MediaWikiTableTextLoader, # "ssv": CsvTableTextLoader, # } # ) # # return loader_table # # Path: pytablereader/loadermanager/_base.py # class TableLoaderManager(TableLoaderInterface): # def __init__(self, loader): # self.__loader = loader # # @property # def loader(self): # return self.__loader # # @property # def format_name(self): # return self.__loader.format_name # # @property # def source_type(self): # return self.__loader.source_type # # @property # def table_name(self): # return self.__loader.table_name # # @table_name.setter # def table_name(self, value): # self.__loader.table_name = value # # @property # def encoding(self): # try: # return self.__loader.encoding # except AttributeError: # return None # # @encoding.setter # def encoding(self, codec_name): # self.__loader.encoding = codec_name # # @property # def type_hints(self): # return self.__loader.type_hints # # @type_hints.setter # def type_hints(self, value): # self.__loader.type_hints = value # # def load(self): # return self.__loader.load() # # def inc_table_count(self): # self.__loader.inc_table_count() , which may contain function names, class names, or code. Output only the next line.
loader_factory = TableTextLoaderFactory(source, encoding)
Next line prediction: <|code_start|>""" .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ class TsvTableFileLoader(CsvTableFileLoader): """ Tab separated values (TSV) format file loader class. :param str file_path: Path to the loading TSV file. .. py:attribute:: table_name Table name string. Defaults to ``%(filename)s``. """ @property def format_name(self): return "tsv" def __init__(self, file_path, quoting_flags=None, type_hints=None, type_hint_rules=None): super().__init__(file_path, quoting_flags, type_hints, type_hint_rules) self.delimiter = "\t" <|code_end|> . Use current file imports: (from .._validator import FileValidator, TextValidator from ..csv.core import CsvTableFileLoader, CsvTableTextLoader) and context including class names, function names, or small code snippets from other files: # Path: pytablereader/_validator.py # class FileValidator(BaseValidator): # """ # Validator class for file data source. # """ # # @property # def source_type(self): # return SourceType.FILE # # def validate(self): # try: # pv.validate_filepath(self.source, platform="auto") # except pv.ValidationError as e: # raise InvalidFilePathError(e) # # if os.path.isfile(self.source) or is_fifo(self.source): # return # # raise OSError("file not found") # # class TextValidator(BaseValidator): # """ # Validator class for text object data source. # """ # # @property # def source_type(self): # return SourceType.TEXT # # def validate(self): # if typepy.is_null_string(self.source): # raise DataError("data source is empty") # # Path: pytablereader/csv/core.py # class CsvTableFileLoader(CsvTableLoader): # """ # A file loader class to extract tabular data from CSV files. # # :param str file_path: Path to the loading CSV file. # # .. py:attribute:: table_name # # Table name string. Defaults to ``%(filename)s``. # # :Examples: # :ref:`example-csv-table-loader` # """ # # def __init__(self, file_path, quoting_flags=None, type_hints=None, type_hint_rules=None): # super().__init__(file_path, quoting_flags, type_hints, type_hint_rules) # # self._validator = FileValidator(file_path) # self._logger = FileSourceLogger(self) # # def load(self): # """ # Extract tabular data as |TableData| instances from a CSV file. # |load_source_desc_file| # # :return: # Loaded table data. # |load_table_name_desc| # # =================== ======================================== # Format specifier Value after the replacement # =================== ======================================== # ``%(filename)s`` |filename_desc| # ``%(format_name)s`` ``"csv"`` # ``%(format_id)s`` |format_id_desc| # ``%(global_id)s`` |global_id| # =================== ======================================== # :rtype: |TableData| iterator # :raises pytablereader.DataError: # If the CSV data is invalid. # # .. seealso:: # :py:func:`csv.reader` # """ # # self._validate() # self._logger.logging_load() # self.encoding = get_file_encoding(self.source, self.encoding) # # self._csv_reader = csv.reader( # open(self.source, encoding=self.encoding), # delimiter=self.delimiter, # quotechar=self.quotechar, # strict=True, # skipinitialspace=True, # ) # # formatter = CsvTableFormatter(self._to_data_matrix()) # formatter.accept(self) # # return formatter.to_table_data() # # def _get_default_table_name_template(self): # return tnt.FILENAME # # class CsvTableTextLoader(CsvTableLoader): # """ # A text loader class to extract tabular data from CSV text data. # # :param str text: CSV text to load. # # .. py:attribute:: table_name # # Table name string. Defaults to ``%(format_name)s%(format_id)s``. # # :Examples: # :ref:`example-csv-table-loader` # """ # # def __init__(self, text, quoting_flags=None, type_hints=None, type_hint_rules=None): # super().__init__(text, quoting_flags, type_hints, type_hint_rules) # # self._validator = TextValidator(text) # self._logger = TextSourceLogger(self) # # def load(self): # """ # Extract tabular data as |TableData| instances from a CSV text object. # |load_source_desc_text| # # :return: # Loaded table data. # |load_table_name_desc| # # =================== ======================================== # Format specifier Value after the replacement # =================== ======================================== # ``%(filename)s`` ``""`` # ``%(format_name)s`` ``"csv"`` # ``%(format_id)s`` |format_id_desc| # ``%(global_id)s`` |global_id| # =================== ======================================== # :rtype: |TableData| iterator # :raises pytablereader.DataError: # If the CSV data is invalid. # # .. seealso:: # :py:func:`csv.reader` # """ # # self._validate() # self._logger.logging_load() # # self._csv_reader = csv.reader( # io.StringIO(self.source.strip()), # delimiter=self.delimiter, # quotechar=self.quotechar, # strict=True, # skipinitialspace=True, # ) # formatter = CsvTableFormatter(self._to_data_matrix()) # formatter.accept(self) # # return formatter.to_table_data() # # def _get_default_table_name_template(self): # return f"{tnt.FORMAT_NAME:s}{tnt.FORMAT_ID:s}" . Output only the next line.
self._validator = FileValidator(file_path)
Based on the snippet: <|code_start|>""" .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ class TsvTableFileLoader(CsvTableFileLoader): """ Tab separated values (TSV) format file loader class. :param str file_path: Path to the loading TSV file. .. py:attribute:: table_name Table name string. Defaults to ``%(filename)s``. """ @property def format_name(self): return "tsv" def __init__(self, file_path, quoting_flags=None, type_hints=None, type_hint_rules=None): super().__init__(file_path, quoting_flags, type_hints, type_hint_rules) self.delimiter = "\t" self._validator = FileValidator(file_path) <|code_end|> , predict the immediate next line with the help of imports: from .._validator import FileValidator, TextValidator from ..csv.core import CsvTableFileLoader, CsvTableTextLoader and context (classes, functions, sometimes code) from other files: # Path: pytablereader/_validator.py # class FileValidator(BaseValidator): # """ # Validator class for file data source. # """ # # @property # def source_type(self): # return SourceType.FILE # # def validate(self): # try: # pv.validate_filepath(self.source, platform="auto") # except pv.ValidationError as e: # raise InvalidFilePathError(e) # # if os.path.isfile(self.source) or is_fifo(self.source): # return # # raise OSError("file not found") # # class TextValidator(BaseValidator): # """ # Validator class for text object data source. # """ # # @property # def source_type(self): # return SourceType.TEXT # # def validate(self): # if typepy.is_null_string(self.source): # raise DataError("data source is empty") # # Path: pytablereader/csv/core.py # class CsvTableFileLoader(CsvTableLoader): # """ # A file loader class to extract tabular data from CSV files. # # :param str file_path: Path to the loading CSV file. # # .. py:attribute:: table_name # # Table name string. Defaults to ``%(filename)s``. # # :Examples: # :ref:`example-csv-table-loader` # """ # # def __init__(self, file_path, quoting_flags=None, type_hints=None, type_hint_rules=None): # super().__init__(file_path, quoting_flags, type_hints, type_hint_rules) # # self._validator = FileValidator(file_path) # self._logger = FileSourceLogger(self) # # def load(self): # """ # Extract tabular data as |TableData| instances from a CSV file. # |load_source_desc_file| # # :return: # Loaded table data. # |load_table_name_desc| # # =================== ======================================== # Format specifier Value after the replacement # =================== ======================================== # ``%(filename)s`` |filename_desc| # ``%(format_name)s`` ``"csv"`` # ``%(format_id)s`` |format_id_desc| # ``%(global_id)s`` |global_id| # =================== ======================================== # :rtype: |TableData| iterator # :raises pytablereader.DataError: # If the CSV data is invalid. # # .. seealso:: # :py:func:`csv.reader` # """ # # self._validate() # self._logger.logging_load() # self.encoding = get_file_encoding(self.source, self.encoding) # # self._csv_reader = csv.reader( # open(self.source, encoding=self.encoding), # delimiter=self.delimiter, # quotechar=self.quotechar, # strict=True, # skipinitialspace=True, # ) # # formatter = CsvTableFormatter(self._to_data_matrix()) # formatter.accept(self) # # return formatter.to_table_data() # # def _get_default_table_name_template(self): # return tnt.FILENAME # # class CsvTableTextLoader(CsvTableLoader): # """ # A text loader class to extract tabular data from CSV text data. # # :param str text: CSV text to load. # # .. py:attribute:: table_name # # Table name string. Defaults to ``%(format_name)s%(format_id)s``. # # :Examples: # :ref:`example-csv-table-loader` # """ # # def __init__(self, text, quoting_flags=None, type_hints=None, type_hint_rules=None): # super().__init__(text, quoting_flags, type_hints, type_hint_rules) # # self._validator = TextValidator(text) # self._logger = TextSourceLogger(self) # # def load(self): # """ # Extract tabular data as |TableData| instances from a CSV text object. # |load_source_desc_text| # # :return: # Loaded table data. # |load_table_name_desc| # # =================== ======================================== # Format specifier Value after the replacement # =================== ======================================== # ``%(filename)s`` ``""`` # ``%(format_name)s`` ``"csv"`` # ``%(format_id)s`` |format_id_desc| # ``%(global_id)s`` |global_id| # =================== ======================================== # :rtype: |TableData| iterator # :raises pytablereader.DataError: # If the CSV data is invalid. # # .. seealso:: # :py:func:`csv.reader` # """ # # self._validate() # self._logger.logging_load() # # self._csv_reader = csv.reader( # io.StringIO(self.source.strip()), # delimiter=self.delimiter, # quotechar=self.quotechar, # strict=True, # skipinitialspace=True, # ) # formatter = CsvTableFormatter(self._to_data_matrix()) # formatter.accept(self) # # return formatter.to_table_data() # # def _get_default_table_name_template(self): # return f"{tnt.FORMAT_NAME:s}{tnt.FORMAT_ID:s}" . Output only the next line.
class TsvTableTextLoader(CsvTableTextLoader):
Predict the next line for this snippet: <|code_start|> "json_lines", "jsonl", "ldjson", "ltsv", "markdown", "mediawiki", "ndjson", "ssv", "tsv", ] class Test_TableTextLoader_constructor: @pytest.mark.parametrize( ["value", "format_name", "expected"], [ [None, None, ValueError], ["", None, ValueError], ["https://github.com/", None, ValueError], ["/tmp/valid/test/data/validext.csv/", None, ValueError], ["/tmp/invalid/test/data/invalidext.txt", "invalidformat", ptr.LoaderNotFoundError], ], ) def test_exception(self, value, format_name, expected): with pytest.raises(expected): ptr.TableTextLoader(value, format_name=format_name) class Test_TableTextLoader_load: def setup_method(self, method): <|code_end|> with the help of current file imports: from textwrap import dedent from pytablewriter import dumps_tabledata from tabledata import TableData from pytablereader.interface import AbstractTableReader import pytest import pytablereader as ptr and context from other files: # Path: pytablereader/interface.py # class AbstractTableReader(TableLoaderInterface, metaclass=abc.ABCMeta): # """ # The abstract class of table data file loader. # # .. py:attribute:: table_name # # Table name string. # # .. py:attribute:: source # # Table data source to load. # """ # # __table_count_lock = threading.Lock() # __global_table_count = 0 # __format_table_count = {} # # @property # def source_type(self): # return self._validator.source_type # # @property # def quoting_flags(self): # return self.__quoting_flags # # @property # def dp_extractor(self): # return self.__dp_extractor # # def __init__(self, source, quoting_flags, type_hints, type_hint_rules=None): # self.table_name = tnt.DEFAULT # self.source = source # self.__quoting_flags = quoting_flags # self.type_hints = type_hints # self.type_hint_rules = type_hint_rules # self._validator = None # self._logger = None # # self.__dp_extractor = DataPropertyExtractor() # self.__dp_extractor.quoting_flags = self.quoting_flags # self.__dp_extractor.update_strict_level_map({typepy.Typecode.BOOL: 1}) # # def get_format_key(self): # return f"{self.format_name:s}{self.__get_format_table_count():d}" # # def make_table_name(self): # return self._make_table_name() # # def inc_table_count(self): # with self.__table_count_lock: # self.__global_table_count += 1 # self.__format_table_count[self.format_name] = self.__get_format_table_count() + 1 # # @abc.abstractmethod # def _get_default_table_name_template(self): # pragma: no cover # pass # # def _validate(self): # self._validate_table_name() # self._validate_source() # # def _validate_table_name(self): # try: # if typepy.is_null_string(self.table_name): # raise ValueError("table name is empty") # except (TypeError, AttributeError): # raise TypeError("table_name must be a string") # # def _validate_source(self): # self._validator.validate() # # def __get_format_table_count(self): # return self.__format_table_count.get(self.format_name, 0) # # def _get_filename_tablename_mapping(self): # filename = "" # if all([self.source_type == SourceType.FILE, typepy.is_not_null_string(self.source)]): # filename = path.Path(self.source).stem # # return (tnt.FILENAME, filename) # # def _get_basic_tablename_keyvalue_mapping(self): # from collections import OrderedDict # # return OrderedDict( # [ # (tnt.DEFAULT, self._get_default_table_name_template()), # (tnt.FORMAT_NAME, self.format_name), # (tnt.FORMAT_ID, str(self.__get_format_table_count())), # (tnt.GLOBAL_ID, str(self.__global_table_count)), # self._get_filename_tablename_mapping(), # ] # ) # # def _expand_table_name_format(self, table_name_kv_mapping): # self._validate_table_name() # # table_name = self.table_name # for template, value in table_name_kv_mapping.items(): # table_name = table_name.replace(template, value) # # return self._sanitize_table_name(table_name) # # def _make_table_name(self): # self._validate_table_name() # # return self._expand_table_name_format(self._get_basic_tablename_keyvalue_mapping()) # # @staticmethod # def _sanitize_table_name(table_name): # if typepy.is_null_string(table_name): # raise InvalidTableNameError("table name is empty after the template replacement") # # return table_name.strip("_") # # @classmethod # def clear_table_count(cls): # with cls.__table_count_lock: # cls.__global_table_count = 0 # cls.__format_table_count = {} , which may contain function names, class names, or code. Output only the next line.
AbstractTableReader.clear_table_count()
Here is a snippet: <|code_start|>def url_as_file(url, ext=None): """ Context manager that GETs a given `url` and provides it as a local file. The file is in a closed state upon entering the context, and removed when leaving it, if still there. To give the file name a specific extension, use `ext`; the extension can optionally include a separating dot, otherwise it will be added. Parameters: url (str): URL to retrieve. ext (str, optional): Extension for the generated filename. Yields: str: The path to a temporary file with the content of the URL. Raises: requests.RequestException: Base exception of ``requests``, see its docs for more detailed ones. Example: >>> import io, re, json >>> with url_as_file('https://api.github.com/meta', ext='json') as meta: ... meta, json.load(io.open(meta, encoding='ascii'))['hooks'] (u'/tmp/www-api.github.com-Ba5OhD.json', [u'192.30.252.0/22']) """ if ext: ext = '.' + ext.strip('.') # normalize extension <|code_end|> . Write the next line using the current file imports: import os import re import tempfile import requests from contextlib import contextmanager from ._compat import urlparse, decode_filename and context from other files: # Path: src/rituals/util/_compat.py # PY2 = sys.version_info[0] == 2 # PYPY = hasattr(sys, 'pypy_translation_info') # def reraise(tp, value, tb=None): # def decode_filename(filename): # def implements_iterator(cls): # def implements_to_string(cls): # def encode_filename(filename): # def decode_filename(filename): # def with_metaclass(meta, *bases): # def __new__(cls, name, this_bases, d): # def isodate(datestamp=None, microseconds=False): # class metaclass(meta): , which may include functions, classes, or code. Output only the next line.
url_hint = 'www-{}-'.format(urlparse(url).hostname or 'any')
Given the code snippet: <|code_start|> """ Ant-style file and directory matching. Produces an iterator of all of the files that match the provided patterns. Note that directory matches must end with a slash, and if they're exclusions, they won't be scanned (which prunes anything in that directory that would otherwise match). Directory specifiers: ** matches zero or more directories. / path separator. File specifiers: * glob style wildcard. [chars] inclusive character sets. [^chars] exclusive character sets. Examples: **/*.py recursively match all python files. foo/**/*.py recursively match all python files in the 'foo' directory. *.py match all the python files in the current directory. */*.txt match all the text files in top-level directories. foo/**/* all files under directory 'foo'. */ top-level directories. foo/ the directory 'foo' itself. **/foo/ any directory named 'foo'. **/.* hidden files. **/.*/ hidden directories. """ def __init__(self, root, patterns): <|code_end|> , generate the next line using the imports in this file: import os import re from ._compat import string_types and context (functions, classes, or occasionally code) from other files: # Path: src/rituals/util/_compat.py # PY2 = sys.version_info[0] == 2 # PYPY = hasattr(sys, 'pypy_translation_info') # def reraise(tp, value, tb=None): # def decode_filename(filename): # def implements_iterator(cls): # def implements_to_string(cls): # def encode_filename(filename): # def decode_filename(filename): # def with_metaclass(meta, *bases): # def __new__(cls, name, this_bases, d): # def isodate(datestamp=None, microseconds=False): # class metaclass(meta): . Output only the next line.
if isinstance(patterns, string_types):
Using the snippet: <|code_start|>sys.path.insert(0, os.path.abspath("../src")) on_rtd = os.environ.get('READTHEDOCS', None) == 'True' if not on_rtd: # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. needs_sphinx = '1.3' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.coverage', 'sphinx.ext.ifconfig', 'sphinx.ext.viewcode', 'sphinx.ext.napoleon', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. <|code_end|> , determine the next line of code. You have imports: import os import re import sys import sphinx_rtd_theme from setup import project as meta and context (class names, function names, or code) available: # Path: setup.py # def srcfile(*args): # def initialize_options(self): # def finalize_options(self): # def run_tests(self): # def _build_metadata(): # pylint: disable=too-many-locals, too-many-branches # class PyTest(TestCommand): . Output only the next line.
project = meta["name"]
Here is a snippet: <|code_start|> store = self.root.substorage(path) self.storage_cache[path] = store return store def get_storage(self, item): storagedir = getattr(item, '_storagedir', None) if not storagedir: storagedir = '{:03}-{}'.format(next(self.counter), sanitized_name(item.name)) item._storagedir = storagedir return self.join(storagedir) def pytest_runtest_setup(self, item): # Make sure the test storage directory is created, even if the # test doesn't happen to use it self.get_storage(item) @pytest.hookimpl def pytest_lab_process_logs(self, config, item, logs): for ctl, logset in logs.items(): prefix_path = '@'.join((ctl.name, ctl.hostname)) prefix_dir = self.get_storage(item).join('logs').join(prefix_path) prefix_dir.mkdir() for remotefile, contents in logset.items(): absname = filename = str(remotefile) # any plumbum remote path should be encoded as an # appropriate file name if getattr(remotefile, 'dirname', None): <|code_end|> . Write the next line using the current file imports: from builtins import str from builtins import next from builtins import object from lab.utils import encode_path import pytest import re import plumbum import py import itertools and context from other files: # Path: lab/utils.py # def encode_path(path): # """Encode paths for use as file names the same way systemd does: # # "Some unit names reflect paths existing in the file system namespace. # Example: a device unit dev-sda.device refers to a device with the # device node /dev/sda in the file system namespace. If this applies, a # special way to escape the path name is used, so that the result is # usable as part of a filename. Basically, given a path, "/" is # replaced by "-", and all other characters which are not ASCII # alphanumerics are replaced by C-style "\x2d" escapes (except that "_" # is never replaced and "." is only replaced when it would be the first # character in the escaped path). The root directory "/" is encoded as # single dash, while otherwise the initial and ending "/" are removed # from all paths during transformation. This escaping is reversible." # """ # # strip any initial/ending '/' # name = path.strip('/') if len(path) > 1 else path # name = ''.join(map(encode_char, name)) # if name[0] == '.': # name = '\\x{:x}'.format(ord('.')) + name[1:] # return name , which may include functions, classes, or code. Output only the next line.
absname = encode_path(absname)
Next line prediction: <|code_start|># # Copyright 2017 Sangoma Technologies Inc. # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. """ RPC controls """ class RPyCCtl(object): """Per location ``rpyc`` control. Offers connection factory methods as well as a cached master connection. """ <|code_end|> . Use current file imports: (import inspect import importlib import pytest import execnet from builtins import object from contextlib import contextmanager from lab.comms import connection from rpyc.utils.zerodeploy import DeployedServer from rpyc.experimental.splitbrain import (splitbrain, disable_splitbrain)) and context including class names, function names, or small code snippets from other files: # Path: lab/comms.py # class connection(object): # """A descriptor for declaring connection types on role controllers # which does lazy loading of a ``Reliable`` proxy wrapper. # """ # def __init__(self, key, **kwargs): # if key not in _registry: # raise KeyError( # "No comms driver for {} has been registered".format(key)) # self.key = key # self._proxies = {} # # def __get__(self, ctl, type=None): # if ctl is None: # return self # # # cache connections per location # proxy = self._proxies.get(ctl.location, None) # if proxy is None: # logging.debug("Creating new {} connection for {}" # .format(self.key, ctl.location)) # proxy = reliable_proxy(ctl.location, self.key) # self._proxies[ctl.location] = proxy # # return proxy . Output only the next line.
ssh = connection('ssh')
Predict the next line for this snippet: <|code_start|> @pytest.hookimpl def pytest_addoption(parser): group = parser.getgroup('environment') group.addoption('--env', action='store') group.addoption('--zone', action='store') @pytest.hookimpl def pytest_lab_map(config, roles): mapfile = config.hook.pytest_lab_getcfg(config=config, filenames=['map.yaml']) if not mapfile: return <|code_end|> with the help of current file imports: import pytest from lab import config_v1 from .locker import EtcdLocker, Locker and context from other files: # Path: lab/config_v1.py # class LabConfigError(Exception): # class Error(Enum): # class Loader(object): # class Union(dict): # def __init__(self, name, kwargs): # def __call__(self): # def __init__(self, data, zone=None): # def __missing__(self, key): # def load(config_path): # def _parse_role(name, yaml, container, domain=None): # def _parse_provider(name, yaml, container): # def _parse_roles(roles, domain=None): # def _parse_providers(providers): # def _parse_common(yaml, domain=None): # def _parse_zones(config): # def _parse_environments(config): , which may contain function names, class names, or code. Output only the next line.
mapdata = config_v1.load(mapfile)
Next line prediction: <|code_start|># # Copyright 2017 Sangoma Technologies Inc. # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. """ Communication drivers and connection management. """ log = logging.getLogger(name='lab.comms') _registry = { 'ssh': { <|code_end|> . Use current file imports: (from builtins import object from lab.ssh import get_ssh, get_sftp import logging) and context including class names, function names, or small code snippets from other files: # Path: lab/ssh.py # SSH_OPTS = ['-o', 'UserKnownHostsFile=/dev/null', # '-o', 'StrictHostKeyChecking=no', # '-o', 'ServerAliveInterval=5'] # def walk(self, remotepath): # def get_paramiko_sftp(hostname, **kwargs): # def get_paramiko_ssh(hostname, **kwargs): # def get_generic_sftp(hostname, **kwargs): # def get_transport(**kwargs): # def get_sftp(transport): # def iter_credentials(): # def get_generic_ssh(hostname, **kwargs): . Output only the next line.
'factory': lambda location: get_ssh(location),
Predict the next line for this snippet: <|code_start|># # Copyright 2017 Sangoma Technologies Inc. # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. """ Communication drivers and connection management. """ log = logging.getLogger(name='lab.comms') _registry = { 'ssh': { 'factory': lambda location: get_ssh(location), 'is_up': lambda ssh: ssh._session.alive(), 'magic_methods': ['__getitem__'] }, 'sftp': { <|code_end|> with the help of current file imports: from builtins import object from lab.ssh import get_ssh, get_sftp import logging and context from other files: # Path: lab/ssh.py # SSH_OPTS = ['-o', 'UserKnownHostsFile=/dev/null', # '-o', 'StrictHostKeyChecking=no', # '-o', 'ServerAliveInterval=5'] # def walk(self, remotepath): # def get_paramiko_sftp(hostname, **kwargs): # def get_paramiko_ssh(hostname, **kwargs): # def get_generic_sftp(hostname, **kwargs): # def get_transport(**kwargs): # def get_sftp(transport): # def iter_credentials(): # def get_generic_ssh(hostname, **kwargs): , which may contain function names, class names, or code. Output only the next line.
'factory': lambda location: get_sftp(location),
Continue the code snippet: <|code_start|># # Copyright 2017 Sangoma Technologies Inc. # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. class RoleNotFound(LookupError): pass class Roles(object): def __init__(self, config): self.config = config self.data = None self.loaded = weakref.WeakValueDictionary() self.config.hook.pytest_lab_map.call_historic( kwargs=dict(config=self.config, roles=self) ) def load(self, config, zone=None): <|code_end|> . Use current file imports: from builtins import object from lab import config_v1 from . import hookspec import importlib import weakref import pytest and context (classes, functions, or code) from other files: # Path: lab/config_v1.py # class LabConfigError(Exception): # class Error(Enum): # class Loader(object): # class Union(dict): # def __init__(self, name, kwargs): # def __call__(self): # def __init__(self, data, zone=None): # def __missing__(self, key): # def load(config_path): # def _parse_role(name, yaml, container, domain=None): # def _parse_provider(name, yaml, container): # def _parse_roles(roles, domain=None): # def _parse_providers(providers): # def _parse_common(yaml, domain=None): # def _parse_zones(config): # def _parse_environments(config): . Output only the next line.
self.data = config_v1.Union(config, zone=zone)
Given the code snippet: <|code_start|> class ParseError(RuntimeError): """Failed to unpack structure.""" TYPES = { 'uint8': 'B', 'uint16': 'H', 'be16': '>H', 'ip4addr': { 'format': '4s', 'decode': IPv4Address, 'encode': lambda addr: addr.packed }, 'l2addr': { 'format': '6s', <|code_end|> , generate the next line using the imports in this file: import struct from ipaddress import IPv4Address from .utils import HWAddress and context (functions, classes, or occasionally code) from other files: # Path: pnet/utils.py # class HWAddress(object): # """Represent and manipulate MAC addresses.""" # def __init__(self, address): # """ # Args: # address: A string or integer representing the MAC # """ # # if isinstance(address, bytes) and len(address) == 6: # self.packed = address # elif isinstance(address, HWAddress): # self.packed = address.packed # else: # self.packed = unhexlify(address.replace(':', '')) # assert len(self.packed) == 6 # # def __str__(self): # return ':'.join([format(ord(x), 'x') for x in self.packed]) # # def __repr__(self): # return "HWAddress('{}')".format(self) . Output only the next line.
'decode': HWAddress,
Here is a snippet: <|code_start|> A context manager is provided for convenience and is the recommended way to use this library:: with MacVLan('eno1', name='test-network', mac='00:19:d1:29:d2:58') as vlan: ... Will create a new mavlan called ``test-network`` bound to ``eno1`` using the provided mac. It will also try and aquire an IP over DHCP.:: 31: test-network@eno1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UNKNOWN group default link/ether 9e:dc:e3:d6:1e:ad brd ff:ff:ff:ff:ff:ff inet6 fe80::9cdc:e3ff:fed6:1ead/64 scope link tentative dadfailed valid_lft forever preferred_lft forever """ def __init__(self, interface, name='macvlan', dhcp=True): self.name = _generate_device_name(name) self.dhcp = None self.ipdb = pyroute2.IPDB() vlan = self.ipdb.create(kind='macvlan', link=self.ipdb.interfaces[interface], ifname=self.name, mode='bridge') vlan.up() vlan.commit() # Start dhcp process if necessary if dhcp: try: <|code_end|> . Write the next line using the current file imports: from builtins import range from builtins import object from .dhcp import DHCP4 import time import logging import socket import ipaddress import pyroute2 and context from other files: # Path: lab/network/dhcp.py # class DHCP4(object): # def __init__(self, iface): # self.iface = iface # self.sock = DHCP4Socket(iface.ifname) # # self._yiaddr = None # self._subnet_mask = None # self._ready_event = threading.Event() # self._stop_event = threading.Event() # self._thread = threading.Thread(target=self._lease) # self._thread.daemon = True # self._thread.start() # if not self._ready_event.wait(10.0): # raise RuntimeError('Failed to get DHCP lease') # # logger.info('Setting {} on {}...'.format(self.yiaddr, # self.iface.ifname)) # self.iface.add_ip(self.yiaddr.compressed, # mask=self.subnet_mask.compressed) # self.iface.commit() # # def _discover(self, src=None): # logger.info('Sending DHCP4 discover on {}...'.format(self.iface.ifname)) # chaddr = src or self.sock.src # options = build_options(DHCPMessage.Discover, chaddr) # packet = DHCPPacket(DHCPOpCode.Request, chaddr=chaddr, options=options) # return self.sock.send(packet, src=src, expect=DHCPMessage.Offer) # # def _request(self, yiaddr, src=None): # logger.info('Sending DHCP4 request on {}...'.format(self.iface.ifname)) # chaddr = src or self.sock.src # options = build_options(DHCPMessage.Request, chaddr, requested_ip=yiaddr) # packet = DHCPPacket(DHCPOpCode.Request, chaddr=chaddr, options=options) # return self.sock.send(packet, src=src, expect=DHCPMessage.ACK) # # def _release(self, yiaddr, src=None): # logger.info('Sending DHCP4 release on {}...'.format(self.iface.ifname)) # chaddr = src or self.sock.src # options = build_options(DHCPMessage.Release, chaddr, requested_ip=yiaddr) # packet = DHCPPacket(DHCPOpCode.Request, chaddr=chaddr, options=options) # self.sock.send(packet, src=src) # # def _lease(self): # offer = self._discover() # self._yiaddr = offer.yiaddr # # while True: # reply = self._request(self._yiaddr) # options = dict(reply.options) # # self._yiaddr = reply.yiaddr # self._subnet_mask = options[DHCPOption.SubnetMask].tobytes() # self._ready_event.set() # # # TODO: fix # lease_time = reply.secs # # # If there's either no leasetime, or the stop event has # # been set before our renew timeout, renew our lease # if not lease_time: # logger.debug('No lease time on DHCP lease!') # return # elif self._stop_event.wait(lease_time // 2): # logger.debug('Leaving DHCP renewal loop!') # return # # def close(self): # self._stop_event.set() # self._release(self._yiaddr) # # @property # def yiaddr(self): # return ipaddress.IPv4Address(self._yiaddr) # # @property # def subnet_mask(self): # return ipaddress.IPv4Address(self._subnet_mask) , which may include functions, classes, or code. Output only the next line.
self.dhcp = DHCP4(vlan)
Given the following code snippet before the placeholder: <|code_start|>""" EXP4.P: An extention to exponential-weight algorithm for exploration and exploitation. This module contains a class that implements EXP4.P, a contextual bandit algorithm with expert advice. """ LOGGER = logging.getLogger(__name__) <|code_end|> , predict the next line using imports from the current file: import logging import six import numpy as np from six.moves import zip from striatum.bandit.bandit import BaseBandit and context including class names, function names, and sometimes code from other files: # Path: striatum/bandit/bandit.py # class BaseBandit(object): # r"""Bandit algorithm # # Parameters # ---------- # history_storage : HistoryStorage object # The HistoryStorage object to store history context, actions and rewards. # # model_storage : ModelStorage object # The ModelStorage object to store model parameters. # # action_storage : ActionStorage object # The ActionStorage object to store actions. # # recommendation_cls : class (default: None) # The class used to initiate the recommendations. If None, then use # default Recommendation class. # # Attributes # ---------- # history_storage : HistoryStorage object # The HistoryStorage object to store history context, actions and rewards. # """ # # def __init__(self, history_storage, model_storage, action_storage, # recommendation_cls=None): # self._history_storage = history_storage # self._model_storage = model_storage # self._action_storage = action_storage # if recommendation_cls is None: # self._recommendation_cls = Recommendation # else: # self._recommendation_cls = recommendation_cls # # @property # def history_storage(self): # return self._history_storage # # @abstractmethod # def get_action(self, context, n_actions=None): # """Return the action to perform # # Parameters # ---------- # context : dictionary # Contexts {action_id: context} of different actions. # # n_actions: int (default: None) # Number of actions wanted to recommend users. If None, only return # one action. If -1, get all actions. # # Returns # ------- # history_id : int # The history id of the action. # # recommendations : list of dict # Each dict contains # {Action object, estimated_reward, uncertainty}. # """ # pass # # def _get_action_with_empty_action_storage(self, context, n_actions): # if n_actions is None: # recommendations = None # else: # recommendations = [] # history_id = self._history_storage.add_history(context, # recommendations) # return history_id, recommendations # # @abstractmethod # def reward(self, history_id, rewards): # """Reward the previous action with reward. # # Parameters # ---------- # history_id : int # The history id of the action to reward. # # rewards : dictionary # The dictionary {action_id, reward}, where reward is a float. # """ # pass # # @abstractmethod # def add_action(self, actions): # """ Add new actions (if needed). # # Parameters # ---------- # actions : iterable # A list of Action objects for recommendation. # """ # pass # # def update_action(self, action): # """Update action. # # Parameters # ---------- # action : Action # The Action object to update. # """ # self._action_storage.update(action) # # @abstractmethod # def remove_action(self, action_id): # """Remove action by id. # # Parameters # ---------- # action_id : int # The id of the action to remove. # """ # pass # # def calculate_cum_reward(self): # """Calculate cumulative reward with respect to time. # """ # return rplt.calculate_cum_reward(self) # # def calculate_avg_reward(self): # """Calculate average reward with respect to time. # """ # return rplt.calculate_avg_reward(self) # # def plot_avg_reward(self): # """Plot average reward with respect to time. # """ # rplt.plot_avg_reward(self) # # def plot_avg_regret(self): # """Plot average regret with respect to time. # """ # rplt.plot_avg_regret(self) . Output only the next line.
class Exp4P(BaseBandit):
Given the code snippet: <|code_start|> actions = [] for key in actions_id: action = Action(key) actions.append(action) return streaming_batch, user_feature, actions, reward_list, action_context def train_expert(action_context): logreg = OneVsRestClassifier(LogisticRegression()) mnb = OneVsRestClassifier(MultinomialNB(), ) logreg.fit(action_context.iloc[:, 2:], action_context.iloc[:, 1]) mnb.fit(action_context.iloc[:, 2:], action_context.iloc[:, 1]) return [logreg, mnb] def get_advice(context, actions_id, experts): advice = {} for time in context.keys(): advice[time] = {} for i in range(len(experts)): prob = experts[i].predict_proba(context[time])[0] advice[time][i] = {} for j in range(len(prob)): advice[time][i][actions_id[j]] = prob[j] return advice def policy_generation(bandit, actions): historystorage = history.MemoryHistoryStorage() <|code_end|> , generate the next line using the imports in this file: import pandas as pd import numpy as np import matplotlib.pyplot as plt from striatum.storage import history from striatum.storage import model from striatum.bandit import ucb1 from striatum.bandit import linucb from striatum.bandit import linthompsamp from striatum.bandit import exp4p from striatum.bandit import exp3 from striatum.bandit.bandit import Action from sklearn.naive_bayes import MultinomialNB from sklearn.linear_model import LogisticRegression from sklearn.multiclass import OneVsRestClassifier and context (functions, classes, or occasionally code) from other files: # Path: striatum/storage/history.py # class History(object): # class HistoryStorage(object): # class MemoryHistoryStorage(HistoryStorage): # def __init__(self, history_id, context, recommendations, created_at, # rewarded_at=None): # def update_reward(self, rewards, rewarded_at): # def rewards(self): # def get_history(self, history_id): # def get_unrewarded_history(self, history_id): # def add_history(self, context, recommendations, rewards=None): # def add_reward(self, history_id, rewards): # def __init__(self): # def get_history(self, history_id): # def get_unrewarded_history(self, history_id): # def add_history(self, context, recommendations, rewards=None): # def add_reward(self, history_id, rewards): # # Path: striatum/storage/model.py # class ModelStorage(object): # class MemoryModelStorage(ModelStorage): # def get_model(self): # def save_model(self): # def __init__(self): # def get_model(self): # def save_model(self, model): # # Path: striatum/bandit/ucb1.py # class UCB1(BaseBandit): # def __init__(self, history_storage, model_storage, action_storage, # recommendation_cls=None): # def _ucb1_score(self): # def get_action(self, context=None, n_actions=None): # def reward(self, history_id, rewards): # def add_action(self, actions): # def remove_action(self, action_id): # # Path: striatum/bandit/linucb.py # LOGGER = logging.getLogger(__name__) # A = model['A'] # pylint: disable=invalid-name # class LinUCB(BaseBandit): # def __init__(self, history_storage, model_storage, action_storage, # recommendation_cls=None, context_dimension=128, alpha=0.5): # def _init_action_model(self, model, action_id): # def _linucb_score(self, context): # def get_action(self, context, n_actions=None): # def reward(self, history_id, rewards): # def add_action(self, actions): # def remove_action(self, action_id): # # Path: striatum/bandit/linthompsamp.py # LOGGER = logging.getLogger(__name__) # B = np.identity(self.context_dimension) # pylint: disable=invalid-name # B = model['B'] # pylint: disable=invalid-name # B = model['B'] # pylint: disable=invalid-name # class LinThompSamp(BaseBandit): # def __init__(self, history_storage, model_storage, action_storage, # recommendation_cls=None, context_dimension=128, delta=0.5, # R=0.01, epsilon=0.5, random_state=None): # def _linthompsamp_score(self, context): # def get_action(self, context, n_actions=None): # def reward(self, history_id, rewards): # def add_action(self, actions): # def remove_action(self, action_id): # # Path: striatum/bandit/exp4p.py # LOGGER = logging.getLogger(__name__) # class Exp4P(BaseBandit): # def __init__(self, actions, historystorage, modelstorage, delta=0.1, # p_min=None, max_rounds=10000): # def _exp4p_score(self, context): # def get_action(self, context=None, n_actions=1): # def reward(self, history_id, rewards): # # Path: striatum/bandit/exp3.py # LOGGER = logging.getLogger(__name__) # class Exp3(BaseBandit): # def __init__(self, history_storage, model_storage, action_storage, # recommendation_cls=None, gamma=0.3, random_state=None): # def _exp3_probs(self): # def get_action(self, context=None, n_actions=None): # def reward(self, history_id, rewards): # def add_action(self, actions): # def remove_action(self, action_id): # # Path: striatum/bandit/bandit.py # class BaseBandit(object): # def __init__(self, history_storage, model_storage, action_storage, # recommendation_cls=None): # def history_storage(self): # def get_action(self, context, n_actions=None): # def _get_action_with_empty_action_storage(self, context, n_actions): # def reward(self, history_id, rewards): # def add_action(self, actions): # def update_action(self, action): # def remove_action(self, action_id): # def calculate_cum_reward(self): # def calculate_avg_reward(self): # def plot_avg_reward(self): # def plot_avg_regret(self): . Output only the next line.
modelstorage = model.MemoryModelStorage()
Continue the code snippet: <|code_start|> action = Action(key) actions.append(action) return streaming_batch, user_feature, actions, reward_list, action_context def train_expert(action_context): logreg = OneVsRestClassifier(LogisticRegression()) mnb = OneVsRestClassifier(MultinomialNB(), ) logreg.fit(action_context.iloc[:, 2:], action_context.iloc[:, 1]) mnb.fit(action_context.iloc[:, 2:], action_context.iloc[:, 1]) return [logreg, mnb] def get_advice(context, actions_id, experts): advice = {} for time in context.keys(): advice[time] = {} for i in range(len(experts)): prob = experts[i].predict_proba(context[time])[0] advice[time][i] = {} for j in range(len(prob)): advice[time][i][actions_id[j]] = prob[j] return advice def policy_generation(bandit, actions): historystorage = history.MemoryHistoryStorage() modelstorage = model.MemoryModelStorage() if bandit == 'Exp4P': <|code_end|> . Use current file imports: import pandas as pd import numpy as np import matplotlib.pyplot as plt from striatum.storage import history from striatum.storage import model from striatum.bandit import ucb1 from striatum.bandit import linucb from striatum.bandit import linthompsamp from striatum.bandit import exp4p from striatum.bandit import exp3 from striatum.bandit.bandit import Action from sklearn.naive_bayes import MultinomialNB from sklearn.linear_model import LogisticRegression from sklearn.multiclass import OneVsRestClassifier and context (classes, functions, or code) from other files: # Path: striatum/storage/history.py # class History(object): # class HistoryStorage(object): # class MemoryHistoryStorage(HistoryStorage): # def __init__(self, history_id, context, recommendations, created_at, # rewarded_at=None): # def update_reward(self, rewards, rewarded_at): # def rewards(self): # def get_history(self, history_id): # def get_unrewarded_history(self, history_id): # def add_history(self, context, recommendations, rewards=None): # def add_reward(self, history_id, rewards): # def __init__(self): # def get_history(self, history_id): # def get_unrewarded_history(self, history_id): # def add_history(self, context, recommendations, rewards=None): # def add_reward(self, history_id, rewards): # # Path: striatum/storage/model.py # class ModelStorage(object): # class MemoryModelStorage(ModelStorage): # def get_model(self): # def save_model(self): # def __init__(self): # def get_model(self): # def save_model(self, model): # # Path: striatum/bandit/ucb1.py # class UCB1(BaseBandit): # def __init__(self, history_storage, model_storage, action_storage, # recommendation_cls=None): # def _ucb1_score(self): # def get_action(self, context=None, n_actions=None): # def reward(self, history_id, rewards): # def add_action(self, actions): # def remove_action(self, action_id): # # Path: striatum/bandit/linucb.py # LOGGER = logging.getLogger(__name__) # A = model['A'] # pylint: disable=invalid-name # class LinUCB(BaseBandit): # def __init__(self, history_storage, model_storage, action_storage, # recommendation_cls=None, context_dimension=128, alpha=0.5): # def _init_action_model(self, model, action_id): # def _linucb_score(self, context): # def get_action(self, context, n_actions=None): # def reward(self, history_id, rewards): # def add_action(self, actions): # def remove_action(self, action_id): # # Path: striatum/bandit/linthompsamp.py # LOGGER = logging.getLogger(__name__) # B = np.identity(self.context_dimension) # pylint: disable=invalid-name # B = model['B'] # pylint: disable=invalid-name # B = model['B'] # pylint: disable=invalid-name # class LinThompSamp(BaseBandit): # def __init__(self, history_storage, model_storage, action_storage, # recommendation_cls=None, context_dimension=128, delta=0.5, # R=0.01, epsilon=0.5, random_state=None): # def _linthompsamp_score(self, context): # def get_action(self, context, n_actions=None): # def reward(self, history_id, rewards): # def add_action(self, actions): # def remove_action(self, action_id): # # Path: striatum/bandit/exp4p.py # LOGGER = logging.getLogger(__name__) # class Exp4P(BaseBandit): # def __init__(self, actions, historystorage, modelstorage, delta=0.1, # p_min=None, max_rounds=10000): # def _exp4p_score(self, context): # def get_action(self, context=None, n_actions=1): # def reward(self, history_id, rewards): # # Path: striatum/bandit/exp3.py # LOGGER = logging.getLogger(__name__) # class Exp3(BaseBandit): # def __init__(self, history_storage, model_storage, action_storage, # recommendation_cls=None, gamma=0.3, random_state=None): # def _exp3_probs(self): # def get_action(self, context=None, n_actions=None): # def reward(self, history_id, rewards): # def add_action(self, actions): # def remove_action(self, action_id): # # Path: striatum/bandit/bandit.py # class BaseBandit(object): # def __init__(self, history_storage, model_storage, action_storage, # recommendation_cls=None): # def history_storage(self): # def get_action(self, context, n_actions=None): # def _get_action_with_empty_action_storage(self, context, n_actions): # def reward(self, history_id, rewards): # def add_action(self, actions): # def update_action(self, action): # def remove_action(self, action_id): # def calculate_cum_reward(self): # def calculate_avg_reward(self): # def plot_avg_reward(self): # def plot_avg_regret(self): . Output only the next line.
policy = exp4p.Exp4P(actions, historystorage, modelstorage, delta=0.5, pmin=None)
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- """ ============================== Contextual bandit on MovieLens ============================== The script uses real-world data to conduct contextual bandit experiments. Here we use MovieLens 10M Dataset, which is released by GroupLens at 1/2009. Please fist pre-process datasets (use "movielens_preprocess.py"), and then you can run this example. """ def get_data(): streaming_batch = pd.read_csv('streaming_batch.csv', sep='\t', names=['user_id'], engine='c') user_feature = pd.read_csv('user_feature.csv', sep='\t', header=0, index_col=0, engine='c') actions_id = list(pd.read_csv('actions.csv', sep='\t', header=0, engine='c')['movie_id']) reward_list = pd.read_csv('reward_list.csv', sep='\t', header=0, engine='c') action_context = pd.read_csv('action_context.csv', sep='\t', header=0, engine='c') actions = [] for key in actions_id: <|code_end|> with the help of current file imports: import pandas as pd import numpy as np import matplotlib.pyplot as plt from striatum.storage import history from striatum.storage import model from striatum.bandit import ucb1 from striatum.bandit import linucb from striatum.bandit import linthompsamp from striatum.bandit import exp4p from striatum.bandit import exp3 from striatum.bandit.bandit import Action from sklearn.naive_bayes import MultinomialNB from sklearn.linear_model import LogisticRegression from sklearn.multiclass import OneVsRestClassifier and context from other files: # Path: striatum/storage/history.py # class History(object): # class HistoryStorage(object): # class MemoryHistoryStorage(HistoryStorage): # def __init__(self, history_id, context, recommendations, created_at, # rewarded_at=None): # def update_reward(self, rewards, rewarded_at): # def rewards(self): # def get_history(self, history_id): # def get_unrewarded_history(self, history_id): # def add_history(self, context, recommendations, rewards=None): # def add_reward(self, history_id, rewards): # def __init__(self): # def get_history(self, history_id): # def get_unrewarded_history(self, history_id): # def add_history(self, context, recommendations, rewards=None): # def add_reward(self, history_id, rewards): # # Path: striatum/storage/model.py # class ModelStorage(object): # class MemoryModelStorage(ModelStorage): # def get_model(self): # def save_model(self): # def __init__(self): # def get_model(self): # def save_model(self, model): # # Path: striatum/bandit/ucb1.py # class UCB1(BaseBandit): # def __init__(self, history_storage, model_storage, action_storage, # recommendation_cls=None): # def _ucb1_score(self): # def get_action(self, context=None, n_actions=None): # def reward(self, history_id, rewards): # def add_action(self, actions): # def remove_action(self, action_id): # # Path: striatum/bandit/linucb.py # LOGGER = logging.getLogger(__name__) # A = model['A'] # pylint: disable=invalid-name # class LinUCB(BaseBandit): # def __init__(self, history_storage, model_storage, action_storage, # recommendation_cls=None, context_dimension=128, alpha=0.5): # def _init_action_model(self, model, action_id): # def _linucb_score(self, context): # def get_action(self, context, n_actions=None): # def reward(self, history_id, rewards): # def add_action(self, actions): # def remove_action(self, action_id): # # Path: striatum/bandit/linthompsamp.py # LOGGER = logging.getLogger(__name__) # B = np.identity(self.context_dimension) # pylint: disable=invalid-name # B = model['B'] # pylint: disable=invalid-name # B = model['B'] # pylint: disable=invalid-name # class LinThompSamp(BaseBandit): # def __init__(self, history_storage, model_storage, action_storage, # recommendation_cls=None, context_dimension=128, delta=0.5, # R=0.01, epsilon=0.5, random_state=None): # def _linthompsamp_score(self, context): # def get_action(self, context, n_actions=None): # def reward(self, history_id, rewards): # def add_action(self, actions): # def remove_action(self, action_id): # # Path: striatum/bandit/exp4p.py # LOGGER = logging.getLogger(__name__) # class Exp4P(BaseBandit): # def __init__(self, actions, historystorage, modelstorage, delta=0.1, # p_min=None, max_rounds=10000): # def _exp4p_score(self, context): # def get_action(self, context=None, n_actions=1): # def reward(self, history_id, rewards): # # Path: striatum/bandit/exp3.py # LOGGER = logging.getLogger(__name__) # class Exp3(BaseBandit): # def __init__(self, history_storage, model_storage, action_storage, # recommendation_cls=None, gamma=0.3, random_state=None): # def _exp3_probs(self): # def get_action(self, context=None, n_actions=None): # def reward(self, history_id, rewards): # def add_action(self, actions): # def remove_action(self, action_id): # # Path: striatum/bandit/bandit.py # class BaseBandit(object): # def __init__(self, history_storage, model_storage, action_storage, # recommendation_cls=None): # def history_storage(self): # def get_action(self, context, n_actions=None): # def _get_action_with_empty_action_storage(self, context, n_actions): # def reward(self, history_id, rewards): # def add_action(self, actions): # def update_action(self, action): # def remove_action(self, action_id): # def calculate_cum_reward(self): # def calculate_avg_reward(self): # def plot_avg_reward(self): # def plot_avg_regret(self): , which may contain function names, class names, or code. Output only the next line.
action = Action(key)
Using the snippet: <|code_start|>"""Upper Confidence Bound 1 This module contains a class that implements UCB1 algorithm, a famous multi-armed bandit algorithm without context. """ from __future__ import division <|code_end|> , determine the next line of code. You have imports: import numpy as np import six from striatum.bandit.bandit import BaseBandit and context (class names, function names, or code) available: # Path: striatum/bandit/bandit.py # class BaseBandit(object): # r"""Bandit algorithm # # Parameters # ---------- # history_storage : HistoryStorage object # The HistoryStorage object to store history context, actions and rewards. # # model_storage : ModelStorage object # The ModelStorage object to store model parameters. # # action_storage : ActionStorage object # The ActionStorage object to store actions. # # recommendation_cls : class (default: None) # The class used to initiate the recommendations. If None, then use # default Recommendation class. # # Attributes # ---------- # history_storage : HistoryStorage object # The HistoryStorage object to store history context, actions and rewards. # """ # # def __init__(self, history_storage, model_storage, action_storage, # recommendation_cls=None): # self._history_storage = history_storage # self._model_storage = model_storage # self._action_storage = action_storage # if recommendation_cls is None: # self._recommendation_cls = Recommendation # else: # self._recommendation_cls = recommendation_cls # # @property # def history_storage(self): # return self._history_storage # # @abstractmethod # def get_action(self, context, n_actions=None): # """Return the action to perform # # Parameters # ---------- # context : dictionary # Contexts {action_id: context} of different actions. # # n_actions: int (default: None) # Number of actions wanted to recommend users. If None, only return # one action. If -1, get all actions. # # Returns # ------- # history_id : int # The history id of the action. # # recommendations : list of dict # Each dict contains # {Action object, estimated_reward, uncertainty}. # """ # pass # # def _get_action_with_empty_action_storage(self, context, n_actions): # if n_actions is None: # recommendations = None # else: # recommendations = [] # history_id = self._history_storage.add_history(context, # recommendations) # return history_id, recommendations # # @abstractmethod # def reward(self, history_id, rewards): # """Reward the previous action with reward. # # Parameters # ---------- # history_id : int # The history id of the action to reward. # # rewards : dictionary # The dictionary {action_id, reward}, where reward is a float. # """ # pass # # @abstractmethod # def add_action(self, actions): # """ Add new actions (if needed). # # Parameters # ---------- # actions : iterable # A list of Action objects for recommendation. # """ # pass # # def update_action(self, action): # """Update action. # # Parameters # ---------- # action : Action # The Action object to update. # """ # self._action_storage.update(action) # # @abstractmethod # def remove_action(self, action_id): # """Remove action by id. # # Parameters # ---------- # action_id : int # The id of the action to remove. # """ # pass # # def calculate_cum_reward(self): # """Calculate cumulative reward with respect to time. # """ # return rplt.calculate_cum_reward(self) # # def calculate_avg_reward(self): # """Calculate average reward with respect to time. # """ # return rplt.calculate_avg_reward(self) # # def plot_avg_reward(self): # """Plot average reward with respect to time. # """ # rplt.plot_avg_reward(self) # # def plot_avg_regret(self): # """Plot average regret with respect to time. # """ # rplt.plot_avg_regret(self) . Output only the next line.
class UCB1(BaseBandit):
Predict the next line for this snippet: <|code_start|> random_state=None): """Simulate dataset for the contextual bandit problem. Parameters ---------- n_rounds: int Total number of (context, reward) tuples you want to generate. context_dimension: int Dimension of the context. action_storage : ActionStorage object The ActionStorage object to store actions. algorithm: string The bandit algorithm you want to use. random_state: {int, np.random.RandomState} (default: None) If int, np.random.RandomState will used it as seed. If None, a random seed will be used. Return --------- context: dict The dict stores contexts (dict with {action_id: context_dimension ndarray}) at each iteration. desired_actions: dict The action which will receive reward 1 ({history_id: action_id}). """ <|code_end|> with the help of current file imports: from six.moves import range from .utils import get_random_state import numpy as np import matplotlib.pyplot as plt and context from other files: # Path: striatum/utils/misc.py # def get_random_state(random_state=None): # if random_state is None: # random_state = np.random.RandomState() # elif not isinstance(random_state, np.random.RandomState): # random_state = np.random.RandomState(seed=random_state) # return random_state , which may contain function names, class names, or code. Output only the next line.
random_state = get_random_state(random_state)
Next line prediction: <|code_start|> ---------- actions : iterable A list of Action objects for recommendation. """ pass def update_action(self, action): """Update action. Parameters ---------- action : Action The Action object to update. """ self._action_storage.update(action) @abstractmethod def remove_action(self, action_id): """Remove action by id. Parameters ---------- action_id : int The id of the action to remove. """ pass def calculate_cum_reward(self): """Calculate cumulative reward with respect to time. """ <|code_end|> . Use current file imports: (from abc import abstractmethod from striatum import rewardplot as rplt from ..storage import Recommendation) and context including class names, function names, or small code snippets from other files: # Path: striatum/rewardplot.py # def calculate_cum_reward(policy): # def calculate_avg_reward(policy): # def plot_avg_reward(policy): # def plot_avg_regret(policy): # # Path: striatum/storage/recommendation.py # class Recommendation(object): # """The object to store a recommendation. # # Parameters # ---------- # action : Action # estimated_reward: float # uncertainty: float # score: float # """ # # def __init__(self, action, estimated_reward, uncertainty, score, # reward=None): # self.action = action # self.estimated_reward = estimated_reward # self.uncertainty = uncertainty # self.score = score # self.reward = reward . Output only the next line.
return rplt.calculate_cum_reward(self)
Given the code snippet: <|code_start|>class BaseBandit(object): r"""Bandit algorithm Parameters ---------- history_storage : HistoryStorage object The HistoryStorage object to store history context, actions and rewards. model_storage : ModelStorage object The ModelStorage object to store model parameters. action_storage : ActionStorage object The ActionStorage object to store actions. recommendation_cls : class (default: None) The class used to initiate the recommendations. If None, then use default Recommendation class. Attributes ---------- history_storage : HistoryStorage object The HistoryStorage object to store history context, actions and rewards. """ def __init__(self, history_storage, model_storage, action_storage, recommendation_cls=None): self._history_storage = history_storage self._model_storage = model_storage self._action_storage = action_storage if recommendation_cls is None: <|code_end|> , generate the next line using the imports in this file: from abc import abstractmethod from striatum import rewardplot as rplt from ..storage import Recommendation and context (functions, classes, or occasionally code) from other files: # Path: striatum/rewardplot.py # def calculate_cum_reward(policy): # def calculate_avg_reward(policy): # def plot_avg_reward(policy): # def plot_avg_regret(policy): # # Path: striatum/storage/recommendation.py # class Recommendation(object): # """The object to store a recommendation. # # Parameters # ---------- # action : Action # estimated_reward: float # uncertainty: float # score: float # """ # # def __init__(self, action, estimated_reward, uncertainty, score, # reward=None): # self.action = action # self.estimated_reward = estimated_reward # self.uncertainty = uncertainty # self.score = score # self.reward = reward . Output only the next line.
self._recommendation_cls = Recommendation
Given snippet: <|code_start|>""" Exp3: Exponential-weight algorithm for Exploration and Exploitation This module contains a class that implements EXP3, a bandit algorithm that randomly choose an action according to a learned probability distribution. """ LOGGER = logging.getLogger(__name__) <|code_end|> , continue by predicting the next line. Consider current file imports: import logging import numpy as np import six from .bandit import BaseBandit from ..utils import get_random_state and context: # Path: striatum/bandit/bandit.py # class BaseBandit(object): # r"""Bandit algorithm # # Parameters # ---------- # history_storage : HistoryStorage object # The HistoryStorage object to store history context, actions and rewards. # # model_storage : ModelStorage object # The ModelStorage object to store model parameters. # # action_storage : ActionStorage object # The ActionStorage object to store actions. # # recommendation_cls : class (default: None) # The class used to initiate the recommendations. If None, then use # default Recommendation class. # # Attributes # ---------- # history_storage : HistoryStorage object # The HistoryStorage object to store history context, actions and rewards. # """ # # def __init__(self, history_storage, model_storage, action_storage, # recommendation_cls=None): # self._history_storage = history_storage # self._model_storage = model_storage # self._action_storage = action_storage # if recommendation_cls is None: # self._recommendation_cls = Recommendation # else: # self._recommendation_cls = recommendation_cls # # @property # def history_storage(self): # return self._history_storage # # @abstractmethod # def get_action(self, context, n_actions=None): # """Return the action to perform # # Parameters # ---------- # context : dictionary # Contexts {action_id: context} of different actions. # # n_actions: int (default: None) # Number of actions wanted to recommend users. If None, only return # one action. If -1, get all actions. # # Returns # ------- # history_id : int # The history id of the action. # # recommendations : list of dict # Each dict contains # {Action object, estimated_reward, uncertainty}. # """ # pass # # def _get_action_with_empty_action_storage(self, context, n_actions): # if n_actions is None: # recommendations = None # else: # recommendations = [] # history_id = self._history_storage.add_history(context, # recommendations) # return history_id, recommendations # # @abstractmethod # def reward(self, history_id, rewards): # """Reward the previous action with reward. # # Parameters # ---------- # history_id : int # The history id of the action to reward. # # rewards : dictionary # The dictionary {action_id, reward}, where reward is a float. # """ # pass # # @abstractmethod # def add_action(self, actions): # """ Add new actions (if needed). # # Parameters # ---------- # actions : iterable # A list of Action objects for recommendation. # """ # pass # # def update_action(self, action): # """Update action. # # Parameters # ---------- # action : Action # The Action object to update. # """ # self._action_storage.update(action) # # @abstractmethod # def remove_action(self, action_id): # """Remove action by id. # # Parameters # ---------- # action_id : int # The id of the action to remove. # """ # pass # # def calculate_cum_reward(self): # """Calculate cumulative reward with respect to time. # """ # return rplt.calculate_cum_reward(self) # # def calculate_avg_reward(self): # """Calculate average reward with respect to time. # """ # return rplt.calculate_avg_reward(self) # # def plot_avg_reward(self): # """Plot average reward with respect to time. # """ # rplt.plot_avg_reward(self) # # def plot_avg_regret(self): # """Plot average regret with respect to time. # """ # rplt.plot_avg_regret(self) # # Path: striatum/utils/misc.py # def get_random_state(random_state=None): # if random_state is None: # random_state = np.random.RandomState() # elif not isinstance(random_state, np.random.RandomState): # random_state = np.random.RandomState(seed=random_state) # return random_state which might include code, classes, or functions. Output only the next line.
class Exp3(BaseBandit):
Next line prediction: <|code_start|> The HistoryStorage object to store history context, actions and rewards. model_storage : ModelStorage object The ModelStorage object to store model parameters. action_storage : ActionStorage object The ActionStorage object to store actions. recommendation_cls : class (default: None) The class used to initiate the recommendations. If None, then use default Recommendation class. gamma: float, 0 < gamma <= 1 The parameter used to control the minimum chosen probability for each action. random_state: {int, np.random.RandomState} (default: None) If int, np.random.RandomState will used it as seed. If None, a random seed will be used. References ---------- .. [1] Peter Auer, Nicolo Cesa-Bianchi, et al. "The non-stochastic multi-armed bandit problem ." SIAM Journal of Computing. 2002. """ def __init__(self, history_storage, model_storage, action_storage, recommendation_cls=None, gamma=0.3, random_state=None): super(Exp3, self).__init__(history_storage, model_storage, action_storage, recommendation_cls) <|code_end|> . Use current file imports: (import logging import numpy as np import six from .bandit import BaseBandit from ..utils import get_random_state) and context including class names, function names, or small code snippets from other files: # Path: striatum/bandit/bandit.py # class BaseBandit(object): # r"""Bandit algorithm # # Parameters # ---------- # history_storage : HistoryStorage object # The HistoryStorage object to store history context, actions and rewards. # # model_storage : ModelStorage object # The ModelStorage object to store model parameters. # # action_storage : ActionStorage object # The ActionStorage object to store actions. # # recommendation_cls : class (default: None) # The class used to initiate the recommendations. If None, then use # default Recommendation class. # # Attributes # ---------- # history_storage : HistoryStorage object # The HistoryStorage object to store history context, actions and rewards. # """ # # def __init__(self, history_storage, model_storage, action_storage, # recommendation_cls=None): # self._history_storage = history_storage # self._model_storage = model_storage # self._action_storage = action_storage # if recommendation_cls is None: # self._recommendation_cls = Recommendation # else: # self._recommendation_cls = recommendation_cls # # @property # def history_storage(self): # return self._history_storage # # @abstractmethod # def get_action(self, context, n_actions=None): # """Return the action to perform # # Parameters # ---------- # context : dictionary # Contexts {action_id: context} of different actions. # # n_actions: int (default: None) # Number of actions wanted to recommend users. If None, only return # one action. If -1, get all actions. # # Returns # ------- # history_id : int # The history id of the action. # # recommendations : list of dict # Each dict contains # {Action object, estimated_reward, uncertainty}. # """ # pass # # def _get_action_with_empty_action_storage(self, context, n_actions): # if n_actions is None: # recommendations = None # else: # recommendations = [] # history_id = self._history_storage.add_history(context, # recommendations) # return history_id, recommendations # # @abstractmethod # def reward(self, history_id, rewards): # """Reward the previous action with reward. # # Parameters # ---------- # history_id : int # The history id of the action to reward. # # rewards : dictionary # The dictionary {action_id, reward}, where reward is a float. # """ # pass # # @abstractmethod # def add_action(self, actions): # """ Add new actions (if needed). # # Parameters # ---------- # actions : iterable # A list of Action objects for recommendation. # """ # pass # # def update_action(self, action): # """Update action. # # Parameters # ---------- # action : Action # The Action object to update. # """ # self._action_storage.update(action) # # @abstractmethod # def remove_action(self, action_id): # """Remove action by id. # # Parameters # ---------- # action_id : int # The id of the action to remove. # """ # pass # # def calculate_cum_reward(self): # """Calculate cumulative reward with respect to time. # """ # return rplt.calculate_cum_reward(self) # # def calculate_avg_reward(self): # """Calculate average reward with respect to time. # """ # return rplt.calculate_avg_reward(self) # # def plot_avg_reward(self): # """Plot average reward with respect to time. # """ # rplt.plot_avg_reward(self) # # def plot_avg_regret(self): # """Plot average regret with respect to time. # """ # rplt.plot_avg_regret(self) # # Path: striatum/utils/misc.py # def get_random_state(random_state=None): # if random_state is None: # random_state = np.random.RandomState() # elif not isinstance(random_state, np.random.RandomState): # random_state = np.random.RandomState(seed=random_state) # return random_state . Output only the next line.
self.random_state = get_random_state(random_state)
Continue the code snippet: <|code_start|>"""LinUCB with Disjoint Linear Models This module contains a class that implements LinUCB with disjoint linear model, a contextual bandit algorithm assuming the reward function is a linear function of the context. """ LOGGER = logging.getLogger(__name__) <|code_end|> . Use current file imports: import logging import six import numpy as np from striatum.bandit.bandit import BaseBandit and context (classes, functions, or code) from other files: # Path: striatum/bandit/bandit.py # class BaseBandit(object): # r"""Bandit algorithm # # Parameters # ---------- # history_storage : HistoryStorage object # The HistoryStorage object to store history context, actions and rewards. # # model_storage : ModelStorage object # The ModelStorage object to store model parameters. # # action_storage : ActionStorage object # The ActionStorage object to store actions. # # recommendation_cls : class (default: None) # The class used to initiate the recommendations. If None, then use # default Recommendation class. # # Attributes # ---------- # history_storage : HistoryStorage object # The HistoryStorage object to store history context, actions and rewards. # """ # # def __init__(self, history_storage, model_storage, action_storage, # recommendation_cls=None): # self._history_storage = history_storage # self._model_storage = model_storage # self._action_storage = action_storage # if recommendation_cls is None: # self._recommendation_cls = Recommendation # else: # self._recommendation_cls = recommendation_cls # # @property # def history_storage(self): # return self._history_storage # # @abstractmethod # def get_action(self, context, n_actions=None): # """Return the action to perform # # Parameters # ---------- # context : dictionary # Contexts {action_id: context} of different actions. # # n_actions: int (default: None) # Number of actions wanted to recommend users. If None, only return # one action. If -1, get all actions. # # Returns # ------- # history_id : int # The history id of the action. # # recommendations : list of dict # Each dict contains # {Action object, estimated_reward, uncertainty}. # """ # pass # # def _get_action_with_empty_action_storage(self, context, n_actions): # if n_actions is None: # recommendations = None # else: # recommendations = [] # history_id = self._history_storage.add_history(context, # recommendations) # return history_id, recommendations # # @abstractmethod # def reward(self, history_id, rewards): # """Reward the previous action with reward. # # Parameters # ---------- # history_id : int # The history id of the action to reward. # # rewards : dictionary # The dictionary {action_id, reward}, where reward is a float. # """ # pass # # @abstractmethod # def add_action(self, actions): # """ Add new actions (if needed). # # Parameters # ---------- # actions : iterable # A list of Action objects for recommendation. # """ # pass # # def update_action(self, action): # """Update action. # # Parameters # ---------- # action : Action # The Action object to update. # """ # self._action_storage.update(action) # # @abstractmethod # def remove_action(self, action_id): # """Remove action by id. # # Parameters # ---------- # action_id : int # The id of the action to remove. # """ # pass # # def calculate_cum_reward(self): # """Calculate cumulative reward with respect to time. # """ # return rplt.calculate_cum_reward(self) # # def calculate_avg_reward(self): # """Calculate average reward with respect to time. # """ # return rplt.calculate_avg_reward(self) # # def plot_avg_reward(self): # """Plot average reward with respect to time. # """ # rplt.plot_avg_reward(self) # # def plot_avg_regret(self): # """Plot average regret with respect to time. # """ # rplt.plot_avg_regret(self) . Output only the next line.
class LinUCB(BaseBandit):
Next line prediction: <|code_start|>""" Thompson Sampling with Linear Payoff In This module contains a class that implements Thompson Sampling with Linear Payoff. Thompson Sampling with linear payoff is a contexutal multi-armed bandit algorithm which assume the underlying relationship between rewards and contexts is linear. The sampling method is used to balance the exploration and exploitation. Please check the reference for more details. """ LOGGER = logging.getLogger(__name__) <|code_end|> . Use current file imports: (import logging import six import numpy as np from six.moves import zip from .bandit import BaseBandit from ..utils import get_random_state) and context including class names, function names, or small code snippets from other files: # Path: striatum/bandit/bandit.py # class BaseBandit(object): # r"""Bandit algorithm # # Parameters # ---------- # history_storage : HistoryStorage object # The HistoryStorage object to store history context, actions and rewards. # # model_storage : ModelStorage object # The ModelStorage object to store model parameters. # # action_storage : ActionStorage object # The ActionStorage object to store actions. # # recommendation_cls : class (default: None) # The class used to initiate the recommendations. If None, then use # default Recommendation class. # # Attributes # ---------- # history_storage : HistoryStorage object # The HistoryStorage object to store history context, actions and rewards. # """ # # def __init__(self, history_storage, model_storage, action_storage, # recommendation_cls=None): # self._history_storage = history_storage # self._model_storage = model_storage # self._action_storage = action_storage # if recommendation_cls is None: # self._recommendation_cls = Recommendation # else: # self._recommendation_cls = recommendation_cls # # @property # def history_storage(self): # return self._history_storage # # @abstractmethod # def get_action(self, context, n_actions=None): # """Return the action to perform # # Parameters # ---------- # context : dictionary # Contexts {action_id: context} of different actions. # # n_actions: int (default: None) # Number of actions wanted to recommend users. If None, only return # one action. If -1, get all actions. # # Returns # ------- # history_id : int # The history id of the action. # # recommendations : list of dict # Each dict contains # {Action object, estimated_reward, uncertainty}. # """ # pass # # def _get_action_with_empty_action_storage(self, context, n_actions): # if n_actions is None: # recommendations = None # else: # recommendations = [] # history_id = self._history_storage.add_history(context, # recommendations) # return history_id, recommendations # # @abstractmethod # def reward(self, history_id, rewards): # """Reward the previous action with reward. # # Parameters # ---------- # history_id : int # The history id of the action to reward. # # rewards : dictionary # The dictionary {action_id, reward}, where reward is a float. # """ # pass # # @abstractmethod # def add_action(self, actions): # """ Add new actions (if needed). # # Parameters # ---------- # actions : iterable # A list of Action objects for recommendation. # """ # pass # # def update_action(self, action): # """Update action. # # Parameters # ---------- # action : Action # The Action object to update. # """ # self._action_storage.update(action) # # @abstractmethod # def remove_action(self, action_id): # """Remove action by id. # # Parameters # ---------- # action_id : int # The id of the action to remove. # """ # pass # # def calculate_cum_reward(self): # """Calculate cumulative reward with respect to time. # """ # return rplt.calculate_cum_reward(self) # # def calculate_avg_reward(self): # """Calculate average reward with respect to time. # """ # return rplt.calculate_avg_reward(self) # # def plot_avg_reward(self): # """Plot average reward with respect to time. # """ # rplt.plot_avg_reward(self) # # def plot_avg_regret(self): # """Plot average regret with respect to time. # """ # rplt.plot_avg_regret(self) # # Path: striatum/utils/misc.py # def get_random_state(random_state=None): # if random_state is None: # random_state = np.random.RandomState() # elif not isinstance(random_state, np.random.RandomState): # random_state = np.random.RandomState(seed=random_state) # return random_state . Output only the next line.
class LinThompSamp(BaseBandit):
Given the following code snippet before the placeholder: <|code_start|> delta: float, 0 < delta < 1 With probability 1 - delta, LinThompSamp satisfies the theoretical regret bound. R: float, R >= 0 Assume that the residual :math:`ri(t) - bi(t)^T \hat{\mu}` is R-sub-gaussian. In this case, R^2 represents the variance for residuals of the linear model :math:`bi(t)^T`. epsilon: float, 0 < epsilon < 1 A parameter used by the Thompson Sampling algorithm. If the total trials T is known, we can choose epsilon = 1/ln(T). random_state: {int, np.random.RandomState} (default: None) If int, np.random.RandomState will used it as seed. If None, a random seed will be used. References ---------- .. [1] Shipra Agrawal, and Navin Goyal. "Thompson Sampling for Contextual Bandits with Linear Payoffs." Advances in Neural Information Processing Systems 24. 2011. """ def __init__(self, history_storage, model_storage, action_storage, recommendation_cls=None, context_dimension=128, delta=0.5, R=0.01, epsilon=0.5, random_state=None): super(LinThompSamp, self).__init__(history_storage, model_storage, action_storage, recommendation_cls) <|code_end|> , predict the next line using imports from the current file: import logging import six import numpy as np from six.moves import zip from .bandit import BaseBandit from ..utils import get_random_state and context including class names, function names, and sometimes code from other files: # Path: striatum/bandit/bandit.py # class BaseBandit(object): # r"""Bandit algorithm # # Parameters # ---------- # history_storage : HistoryStorage object # The HistoryStorage object to store history context, actions and rewards. # # model_storage : ModelStorage object # The ModelStorage object to store model parameters. # # action_storage : ActionStorage object # The ActionStorage object to store actions. # # recommendation_cls : class (default: None) # The class used to initiate the recommendations. If None, then use # default Recommendation class. # # Attributes # ---------- # history_storage : HistoryStorage object # The HistoryStorage object to store history context, actions and rewards. # """ # # def __init__(self, history_storage, model_storage, action_storage, # recommendation_cls=None): # self._history_storage = history_storage # self._model_storage = model_storage # self._action_storage = action_storage # if recommendation_cls is None: # self._recommendation_cls = Recommendation # else: # self._recommendation_cls = recommendation_cls # # @property # def history_storage(self): # return self._history_storage # # @abstractmethod # def get_action(self, context, n_actions=None): # """Return the action to perform # # Parameters # ---------- # context : dictionary # Contexts {action_id: context} of different actions. # # n_actions: int (default: None) # Number of actions wanted to recommend users. If None, only return # one action. If -1, get all actions. # # Returns # ------- # history_id : int # The history id of the action. # # recommendations : list of dict # Each dict contains # {Action object, estimated_reward, uncertainty}. # """ # pass # # def _get_action_with_empty_action_storage(self, context, n_actions): # if n_actions is None: # recommendations = None # else: # recommendations = [] # history_id = self._history_storage.add_history(context, # recommendations) # return history_id, recommendations # # @abstractmethod # def reward(self, history_id, rewards): # """Reward the previous action with reward. # # Parameters # ---------- # history_id : int # The history id of the action to reward. # # rewards : dictionary # The dictionary {action_id, reward}, where reward is a float. # """ # pass # # @abstractmethod # def add_action(self, actions): # """ Add new actions (if needed). # # Parameters # ---------- # actions : iterable # A list of Action objects for recommendation. # """ # pass # # def update_action(self, action): # """Update action. # # Parameters # ---------- # action : Action # The Action object to update. # """ # self._action_storage.update(action) # # @abstractmethod # def remove_action(self, action_id): # """Remove action by id. # # Parameters # ---------- # action_id : int # The id of the action to remove. # """ # pass # # def calculate_cum_reward(self): # """Calculate cumulative reward with respect to time. # """ # return rplt.calculate_cum_reward(self) # # def calculate_avg_reward(self): # """Calculate average reward with respect to time. # """ # return rplt.calculate_avg_reward(self) # # def plot_avg_reward(self): # """Plot average reward with respect to time. # """ # rplt.plot_avg_reward(self) # # def plot_avg_regret(self): # """Plot average regret with respect to time. # """ # rplt.plot_avg_regret(self) # # Path: striatum/utils/misc.py # def get_random_state(random_state=None): # if random_state is None: # random_state = np.random.RandomState() # elif not isinstance(random_state, np.random.RandomState): # random_state = np.random.RandomState(seed=random_state) # return random_state . Output only the next line.
self.random_state = get_random_state(random_state)
Based on the snippet: <|code_start|> self.to_screen(render_table( ['Language', 'formats'], [[lang, ', '.join(f['ext'] for f in reversed(formats))] for lang, formats in subtitles.items()])) def urlopen(self, req): """ Start an HTTP download """ if isinstance(req, compat_basestring): req = sanitized_Request(req) return self._opener.open(req, timeout=self._socket_timeout) def print_debug_header(self): if not self.params.get('verbose'): return if type('') is not compat_str: # Python 2.6 on SLES11 SP1 (https://github.com/rg3/youtube-dl/issues/3326) self.report_warning( 'Your Python is broken! Update to a newer and supported version') stdout_encoding = getattr( sys.stdout, 'encoding', 'missing (%s)' % type(sys.stdout).__name__) encoding_str = ( '[debug] Encodings: locale %s, fs %s, out %s, pref %s\n' % ( locale.getpreferredencoding(), sys.getfilesystemencoding(), stdout_encoding, self.get_encoding())) write_string(encoding_str, encoding=None) <|code_end|> , predict the immediate next line with the help of imports: import collections import contextlib import copy import datetime import errno import fileinput import io import itertools import json import locale import operator import os import platform import re import shutil import subprocess import socket import sys import time import tokenize import traceback import random import ctypes import pty from string import ascii_letters from .compat import ( compat_basestring, compat_cookiejar, compat_get_terminal_size, compat_http_client, compat_kwargs, compat_numeric_types, compat_os_name, compat_str, compat_tokenize_tokenize, compat_urllib_error, compat_urllib_request, compat_urllib_request_DataHandler, ) from .utils import ( age_restricted, args_to_str, ContentTooShortError, date_from_str, DateRange, DEFAULT_OUTTMPL, determine_ext, determine_protocol, DownloadError, encode_compat_str, encodeFilename, error_to_compat_str, expand_path, ExtractorError, format_bytes, formatSeconds, GeoRestrictedError, int_or_none, ISO3166Utils, locked_file, make_HTTPS_handler, MaxDownloadsReached, PagedList, parse_filesize, PerRequestProxyHandler, platform_name, PostProcessingError, preferredencoding, prepend_extension, register_socks_protocols, render_table, replace_extension, SameFileError, sanitize_filename, sanitize_path, sanitize_url, sanitized_Request, std_headers, subtitles_filename, UnavailableVideoError, url_basename, version_tuple, write_json_file, write_string, YoutubeDLCookieProcessor, YoutubeDLHandler, ) from .cache import Cache from .extractor import get_info_extractor, gen_extractor_classes, _LAZY_LOADER from .downloader import get_suitable_downloader from .downloader.rtmp import rtmpdump_version from .postprocessor import ( FFmpegFixupM3u8PP, FFmpegFixupM4aPP, FFmpegFixupStretchedPP, FFmpegMergerPP, FFmpegPostProcessor, get_postprocessor, ) from .version import __version__ and context (classes, functions, sometimes code) from other files: # Path: Cut/RBXLegacyDiscordBot/lib/youtube_dl/version.py . Output only the next line.
self._write_string('[debug] youtube-dl version ' + __version__ + '\n')
Here is a snippet: <|code_start|> @override_settings(USERPROFILES_USE_PROFILE=False, USERPROFILES_USE_EMAIL_VERIFICATION=True) class ViewTests(TestCase): def setUp(self): self.data = { 'username': 'newuser', 'email': 'newuser@example.com', 'email_repeat': 'newuser@example.com', 'password': 'newuserpass', 'password_repeat': 'newuserpass', 'first_name': 'New', 'last_name': 'User', } self.user = User.objects.create_user(self.data['username'], self.data['email'], self.data['password']) def tearDown(self): self.user.delete() def test_email_change(self): self.client.login(username=self.data['username'], password=self.data['password']) response = self.client.get(reverse('userprofiles_email_change')) response = self.client.post(reverse('userprofiles_email_change'), {'new_email': 'test@example.com'}, follow=True) <|code_end|> . Write the next line using the current file imports: from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.test import TestCase from django.test.utils import override_settings from userprofiles.contrib.emailverification.models import EmailVerification from userprofiles.settings import up_settings and context from other files: # Path: userprofiles/contrib/emailverification/models.py # class EmailVerification(models.Model): # user = models.ForeignKey(User, verbose_name=_('User'), blank=False) # old_email = models.EmailField(_('Old e-mail address')) # new_email = models.EmailField(_('New e-mail address')) # # token = models.CharField(_('Token'), max_length=40, default=generate_token) # code = models.CharField(_('Code'), max_length=40, default=generate_token) # # is_approved = models.BooleanField(_('Approved'), default=False) # is_expired = models.BooleanField(_('Expired'), default=False) # # expiration_date = models.DateTimeField(_('Expiration date'), # default=generate_confirm_expire_date) # # def __unicode__(self): # return '%s - %s/%s' % (self.user, self.old_email, self.new_email) # # def save(self, *args, **kwargs): # if self.is_approved: # EmailVerification.objects.filter( # user=self.user, is_approved=False).update(is_expired=True) # # self.is_expired = True # # if self.user.email == self.old_email: # self.user.email = self.new_email # self.user.save() # return super(EmailVerification, self).save(*args, **kwargs) # # class Meta: # app_label = 'userprofiles' # verbose_name = _('E-mail verification') # verbose_name_plural = _('E-mail verifications') # # Path: userprofiles/settings.py # class Settings(object): # def __init__(self, **kwargs): # def __getattr__(self, key): # def validate_settings(): , which may include functions, classes, or code. Output only the next line.
self.assertTrue(EmailVerification.objects.filter(user=self.user).exists())
Next line prediction: <|code_start|>@override_settings(USERPROFILES_USE_PROFILE=False, USERPROFILES_USE_EMAIL_VERIFICATION=True) class ViewTests(TestCase): def setUp(self): self.data = { 'username': 'newuser', 'email': 'newuser@example.com', 'email_repeat': 'newuser@example.com', 'password': 'newuserpass', 'password_repeat': 'newuserpass', 'first_name': 'New', 'last_name': 'User', } self.user = User.objects.create_user(self.data['username'], self.data['email'], self.data['password']) def tearDown(self): self.user.delete() def test_email_change(self): self.client.login(username=self.data['username'], password=self.data['password']) response = self.client.get(reverse('userprofiles_email_change')) response = self.client.post(reverse('userprofiles_email_change'), {'new_email': 'test@example.com'}, follow=True) self.assertTrue(EmailVerification.objects.filter(user=self.user).exists()) <|code_end|> . Use current file imports: (from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.test import TestCase from django.test.utils import override_settings from userprofiles.contrib.emailverification.models import EmailVerification from userprofiles.settings import up_settings) and context including class names, function names, or small code snippets from other files: # Path: userprofiles/contrib/emailverification/models.py # class EmailVerification(models.Model): # user = models.ForeignKey(User, verbose_name=_('User'), blank=False) # old_email = models.EmailField(_('Old e-mail address')) # new_email = models.EmailField(_('New e-mail address')) # # token = models.CharField(_('Token'), max_length=40, default=generate_token) # code = models.CharField(_('Code'), max_length=40, default=generate_token) # # is_approved = models.BooleanField(_('Approved'), default=False) # is_expired = models.BooleanField(_('Expired'), default=False) # # expiration_date = models.DateTimeField(_('Expiration date'), # default=generate_confirm_expire_date) # # def __unicode__(self): # return '%s - %s/%s' % (self.user, self.old_email, self.new_email) # # def save(self, *args, **kwargs): # if self.is_approved: # EmailVerification.objects.filter( # user=self.user, is_approved=False).update(is_expired=True) # # self.is_expired = True # # if self.user.email == self.old_email: # self.user.email = self.new_email # self.user.save() # return super(EmailVerification, self).save(*args, **kwargs) # # class Meta: # app_label = 'userprofiles' # verbose_name = _('E-mail verification') # verbose_name_plural = _('E-mail verifications') # # Path: userprofiles/settings.py # class Settings(object): # def __init__(self, **kwargs): # def __getattr__(self, key): # def validate_settings(): . Output only the next line.
self.assertEqual(response.context['expiration_days'], up_settings.EMAIL_VERIFICATION_DAYS)