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): ...
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 % ...
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 = ...
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(se...
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): ...
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 ...
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_back...
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.ce...
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, ...
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)) r...
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 ver...
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(...
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...
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_emp...
@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 Licens...
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_read...
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 = ...
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...
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...
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.re...
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. ...
@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_dur...
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, ...
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()...
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) ...
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) ...
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...
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", "continu...
@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.extensio...
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 L...
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...
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 PU...
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", "hal...
@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 t...
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 PURPOS...
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 = ...
@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 L...
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): ...
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): # pr...
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"], [ ...
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=F...
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 cove...
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._buf...
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"}, ...
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", "additionalPrope...
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.Valid...
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 ...
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", ["姓", "名", "生年月日", "郵便番号", "住所", "電話番号"], [ ["山田", "太郎", "20...
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") ...
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/...
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(): ...
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 ...
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: @pyte...
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" t...
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 nex...
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.ENCOD...
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 == expecte...
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 se...
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...
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_pa...
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 ope...
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() @pyte...
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) w...
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): va...
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...
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): ...
["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 cu...
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, InvalidFil...
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): ...
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 di...
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 ...
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 ...
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...
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 exten...
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 dire...
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 = '...
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....
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(o...
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.pyt...
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 connecti...
'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 dr...
'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)...
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': { ...
'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 ...
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_e...
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...
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(), ) ...
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...
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 st...
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 ...
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...
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...
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...
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. reco...
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|> . Us...
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 li...
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...
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 isins...
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@examp...
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@exam...
self.assertEqual(response.context['expiration_days'], up_settings.EMAIL_VERIFICATION_DAYS)