Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Next line prediction: <|code_start|> try: except ImportError: class IgdbScraper(AbstractScraper): def __init__(self, core): AbstractScraper.__init__(self, core) self.api_url = 'https://www.igdb.com/api/v1/games/%s' self.api_img_url = 'https://res.cloudinary.com/igdb/image/upload/t_%s/%s.jpg' self.cover_cache = self._set_up_path(os.path.join(self.base_path, 'art/poster/')) self.api_cache = self._set_up_path(os.path.join(self.base_path, 'api_cache/')) def name(self): return 'IGDB' def get_game_information(self, nvapp): if self.core.get_setting('api_key_file', str) == "": <|code_end|> . Use current file imports: (import ConfigParser import json import os import urllib2 import dateutil.parser as date_parser import xbmcgui from xbmcswift2 import xbmcgui from abcscraper import AbstractScraper from resources.lib.model.apiresponse import ApiResponse) and context including class names, function names, or small code snippets from other files: # Path: resources/lib/model/apiresponse.py # class ApiResponse: # def __init__(self, name=None, year=None, genre=None, plot=None, posters=None, fanarts=None): # if genre is None: # genre = [] # if posters is None: # posters = [] # if fanarts is None: # fanarts = {} # # self.name = name # self.year = year # self.genre = genre # self.plot = plot # self.posters = posters # self.fanarts = fanarts # # @classmethod # def from_dict(cls, name=None, year=None, genre=None, plot=None, posters=None, fanarts=None, **kwargs): # return cls(name, year, genre, plot, posters, fanarts) . Output only the next line.
return ApiResponse()
Given snippet: <|code_start|>class LoggerChain(object): def __init__(self, prefix): self.prefix = prefix self.logger_chain = [] def debug(self, message): for logger in self.logger_chain: logger.debug(self.prefix, message) def info(self, message): for logger in self.logger_chain: logger.info(self.prefix, message) def warning(self, message): for logger in self.logger_chain: logger.warning(self.prefix, message) def error(self, message): for logger in self.logger_chain: logger.error(self.prefix, message) def critical(self, message): for logger in self.logger_chain: logger.critical(self.prefix, message) def append(self, loggers): for logger in loggers: self._append_logger(logger) def _append_logger(self, logger): <|code_end|> , continue by predicting the next line. Consider current file imports: from resources.lib.core.logger.abstractlogger import AbstractLogger and context: # Path: resources/lib/core/logger/abstractlogger.py # class AbstractLogger: # __metaclass__ = ABCMeta # # LEVELS = { # 'debug': 0, # 'info': 1, # 'notice': 2, # 'warning': 3, # 'error': 4, # 'severe': 5, # 'fatal': 6 # } # # def __init__(self, log_level): # self.log_level = log_level # # @abstractmethod # def debug(self, channel, text): # pass # # @abstractmethod # def info(self, channel, text): # pass # # @abstractmethod # def warning(self, channel, text): # pass # # @abstractmethod # def error(self, channel, text): # pass # # @abstractmethod # def critical(self, channel, text): # pass which might include code, classes, or functions. Output only the next line.
if isinstance(logger, AbstractLogger):
Here is a snippet: <|code_start|> class GameListController(BaseController): def __init__(self, game_manager, game_helper, moonlight_helper, logger): self.game_manager = game_manager self.game_helper = game_helper self.moonlight_helper = moonlight_helper self.logger = logger self.window = None <|code_end|> . Write the next line using the current file imports: import threading import xbmcgui from resources.lib.controller.basecontroller import BaseController, route from resources.lib.views.gamelist import GameList and context from other files: # Path: resources/lib/controller/basecontroller.py # class BaseController(object): # def render(self, name, args=None): # if args: # return router.render(name, args=args) # else: # return router.render(name) # # def route_exists(self, name): # return router.route_exists(name) # # def cleanup(self): # raise NotImplementedError("Cleanup needs to be implemented.") # # def route(name): # def decorator(func): # xbmc.log("[script.luna.router]: Adding route with name %s to cache" % name) # assert name not in router._routes_cache, "Route with name %s already exists on the same class" % name # router._routes_cache[name] = func # return func # # return decorator # # Path: resources/lib/views/gamelist.py # class GameList(xbmcgui.WindowXML): # def __new__(cls, *args, **kwargs): # return super(GameList, cls).__new__(cls, "gamelist.xml", xbmcaddon.Addon().getAddonInfo('path')) # # def __init__(self, controller, host, game_list): # super(GameList, self).__init__("gamelist.xml", xbmcaddon.Addon().getAddonInfo('path')) # self.controller = controller # self.host = host # self.games = game_list # self.list = None # self.host_online_img = None # self.host_offline_img = None # self.host_name_label = None # # def onInit(self): # self.games.sort(key=lambda x: x['label'], reverse=False) # self.list = self.getControl(50) # self.host_online_img = self.getControl(2) # self.host_offline_img = self.getControl(3) # self.host_name_label = self.getControl(4) # # if self.host.state == self.host.STATE_OFFLINE: # self.host_online_img.setVisible(False) # else: # self.host_offline_img.setVisible(False) # # self.host_name_label.setLabel("%s | GPU: %s" % (self.host.name, self.host.gpu_type)) # # self.build_list() # self.setFocusId(50) # # def build_list(self): # items = [] # # for game in self.games: # item = xbmcgui.ListItem() # item.setLabel(game['label']) # item.setIconImage(game['icon']) # item.setThumbnailImage(game['thumbnail']) # item.setInfo('video', game['info']) # item.setProperty('icon', game['thumbnail']) # item.setProperty('fanart', game['properties']['fanart_image']) # item.setProperty('id', game['properties']['id']) # # items.append(item) # # self.list.addItems(items) # # def onAction(self, action): # focus_item_id = self.getFocusId() # focus_item = None # # if focus_item_id: # focus_item = self.getControl(focus_item_id) # # if action == xbmcgui.ACTION_NAV_BACK: # self.close() # # elif focus_item and focus_item == self.list and action.getId() == xbmcgui.ACTION_CONTEXT_MENU: # current_item = self.list.getListItem(self.list.getSelectedPosition()) # fanart_cache = current_item.getProperty('fanart') # cover_cache = current_item.getProperty('icon') # # current_game = self.controller.get_game_by_id(self.host, current_item.getProperty('id')) # # refresh = self.controller.render('gamecontext_menu', {'host': self.host, 'list_item': current_item, 'game': current_game}) # # loaded_game = self.controller.get_game_by_id(self.host, current_item.getProperty('id')) # # if fanart_cache != loaded_game.get_selected_fanart().get_original(): # self.list.getSelectedItem().setProperty('fanart', loaded_game.get_selected_fanart().get_original()) # # if cover_cache != loaded_game.get_selected_poster(): # self.list.getSelectedItem().setProperty('icon', loaded_game.get_selected_poster()) # self.list.getSelectedItem().setThumbnailImage(loaded_game.get_selected_poster()) # # if refresh: # self.controller.refresh_list(self.host) # # elif focus_item and focus_item == self.list and action == xbmcgui.ACTION_SELECT_ITEM: # current_item = self.list.getListItem(self.list.getSelectedPosition()) # loaded_game = self.controller.get_game_by_id(self.host, current_item.getProperty('id')) # # self.controller.launch_game(loaded_game) # # def update(self, games): # self.games = games # self.games.sort(key=lambda x: x['label'], reverse=False) # self.list.reset() # self.build_list() # return , which may include functions, classes, or code. Output only the next line.
@route(name='list')
Given the code snippet: <|code_start|> class GameListController(BaseController): def __init__(self, game_manager, game_helper, moonlight_helper, logger): self.game_manager = game_manager self.game_helper = game_helper self.moonlight_helper = moonlight_helper self.logger = logger self.window = None @route(name='list') def index_action(self, host): <|code_end|> , generate the next line using the imports in this file: import threading import xbmcgui from resources.lib.controller.basecontroller import BaseController, route from resources.lib.views.gamelist import GameList and context (functions, classes, or occasionally code) from other files: # Path: resources/lib/controller/basecontroller.py # class BaseController(object): # def render(self, name, args=None): # if args: # return router.render(name, args=args) # else: # return router.render(name) # # def route_exists(self, name): # return router.route_exists(name) # # def cleanup(self): # raise NotImplementedError("Cleanup needs to be implemented.") # # def route(name): # def decorator(func): # xbmc.log("[script.luna.router]: Adding route with name %s to cache" % name) # assert name not in router._routes_cache, "Route with name %s already exists on the same class" % name # router._routes_cache[name] = func # return func # # return decorator # # Path: resources/lib/views/gamelist.py # class GameList(xbmcgui.WindowXML): # def __new__(cls, *args, **kwargs): # return super(GameList, cls).__new__(cls, "gamelist.xml", xbmcaddon.Addon().getAddonInfo('path')) # # def __init__(self, controller, host, game_list): # super(GameList, self).__init__("gamelist.xml", xbmcaddon.Addon().getAddonInfo('path')) # self.controller = controller # self.host = host # self.games = game_list # self.list = None # self.host_online_img = None # self.host_offline_img = None # self.host_name_label = None # # def onInit(self): # self.games.sort(key=lambda x: x['label'], reverse=False) # self.list = self.getControl(50) # self.host_online_img = self.getControl(2) # self.host_offline_img = self.getControl(3) # self.host_name_label = self.getControl(4) # # if self.host.state == self.host.STATE_OFFLINE: # self.host_online_img.setVisible(False) # else: # self.host_offline_img.setVisible(False) # # self.host_name_label.setLabel("%s | GPU: %s" % (self.host.name, self.host.gpu_type)) # # self.build_list() # self.setFocusId(50) # # def build_list(self): # items = [] # # for game in self.games: # item = xbmcgui.ListItem() # item.setLabel(game['label']) # item.setIconImage(game['icon']) # item.setThumbnailImage(game['thumbnail']) # item.setInfo('video', game['info']) # item.setProperty('icon', game['thumbnail']) # item.setProperty('fanart', game['properties']['fanart_image']) # item.setProperty('id', game['properties']['id']) # # items.append(item) # # self.list.addItems(items) # # def onAction(self, action): # focus_item_id = self.getFocusId() # focus_item = None # # if focus_item_id: # focus_item = self.getControl(focus_item_id) # # if action == xbmcgui.ACTION_NAV_BACK: # self.close() # # elif focus_item and focus_item == self.list and action.getId() == xbmcgui.ACTION_CONTEXT_MENU: # current_item = self.list.getListItem(self.list.getSelectedPosition()) # fanart_cache = current_item.getProperty('fanart') # cover_cache = current_item.getProperty('icon') # # current_game = self.controller.get_game_by_id(self.host, current_item.getProperty('id')) # # refresh = self.controller.render('gamecontext_menu', {'host': self.host, 'list_item': current_item, 'game': current_game}) # # loaded_game = self.controller.get_game_by_id(self.host, current_item.getProperty('id')) # # if fanart_cache != loaded_game.get_selected_fanart().get_original(): # self.list.getSelectedItem().setProperty('fanart', loaded_game.get_selected_fanart().get_original()) # # if cover_cache != loaded_game.get_selected_poster(): # self.list.getSelectedItem().setProperty('icon', loaded_game.get_selected_poster()) # self.list.getSelectedItem().setThumbnailImage(loaded_game.get_selected_poster()) # # if refresh: # self.controller.refresh_list(self.host) # # elif focus_item and focus_item == self.list and action == xbmcgui.ACTION_SELECT_ITEM: # current_item = self.list.getListItem(self.list.getSelectedPosition()) # loaded_game = self.controller.get_game_by_id(self.host, current_item.getProperty('id')) # # self.controller.launch_game(loaded_game) # # def update(self, games): # self.games = games # self.games.sort(key=lambda x: x['label'], reverse=False) # self.list.reset() # self.build_list() # return . Output only the next line.
self.window = GameList(controller=self, host=host, game_list=self.game_helper.get_games_as_list(host))
Predict the next line after this snippet: <|code_start|> class AudioController(BaseController): def __init__(self, core, audio_manager, config_helper): self.core = core self.audio_manager = audio_manager self.config_helper = config_helper <|code_end|> using the current file's imports: import xbmcgui from resources.lib.controller.basecontroller import BaseController, route and any relevant context from other files: # Path: resources/lib/controller/basecontroller.py # class BaseController(object): # def render(self, name, args=None): # if args: # return router.render(name, args=args) # else: # return router.render(name) # # def route_exists(self, name): # return router.route_exists(name) # # def cleanup(self): # raise NotImplementedError("Cleanup needs to be implemented.") # # def route(name): # def decorator(func): # xbmc.log("[script.luna.router]: Adding route with name %s to cache" % name) # assert name not in router._routes_cache, "Route with name %s already exists on the same class" % name # router._routes_cache[name] = func # return func # # return decorator . Output only the next line.
@route(name="select")
Continue the code snippet: <|code_start|> if __name__ == '__main__': # TODO: This is sometimes called before main controller is known to router def callback(): RequiredFeature('core').request().check_script_permissions() updater = RequiredFeature('update-service').request() update_thread = threading.Thread(target=updater.check_for_update) update_thread.start() router = RequiredFeature('router').request() router.render('main_index') # do some cleanup controller_list = featurebroker.features.get_tagged_features('controller') for definition in controller_list: instance = featurebroker.features.get_initialized(definition.name) if instance and hasattr(instance, 'window'): delattr(instance, 'window') <|code_end|> . Use current file imports: from resources.lib.kernel.xbmcapplicationkernel import XBMCApplicationKernel from resources.lib.di.requiredfeature import RequiredFeature from resources.lib.di import featurebroker import threading and context (classes, functions, or code) from other files: # Path: resources/lib/kernel/xbmcapplicationkernel.py # class XBMCApplicationKernel(object): # def __init__(self): # self.featurebroker = None # self.router = None # # def bootstrap(self, callback=None): # xbmc.executebuiltin("Dialog.Close(busydialog)") # try: # self._bootstrap(callback) # except Exception as e: # xbmc.executebuiltin("Dialog.Close(busydialog)") # xbmc.log("[script.luna.kernel]: Failed to start Luna: %s" % e.message, xbmc.LOGERROR) # exc_type, exc_value, exc_tb = sys.exc_info() # sys.excepthook(exc_type, exc_value, exc_tb) # # def _bootstrap(self, callback=None): # xbmc.executebuiltin("ActivateWindow(busydialog)") # # xbmc.log("[script.luna.kernel]: Bootstrapping DI ...") # xbmc.log("[script.luna.kernel]: Bootstrapping Router ...") # # self.featurebroker = FeatureBroker() # featurebroker.features = self.featurebroker # di_thread = threading.Thread(target=self.featurebroker._parse_config()) # # self.router = Router() # self.featurebroker.provide('router', Router) # self.featurebroker.set_initialized('router', self.router) # # router_thread = threading.Thread(target=self.router._parse_config()) # # di_thread.start() # router_thread.start() # # di_thread.join() # # warmup_thread = None # preload_thread = None # # if not di_thread.isAlive(): # self.featurebroker.execute_calls() # xbmc.log("[script.luna.kernel]: Bootstrapping DI ... done") # xbmc.log('[script.luna.kernel]: Warming up managers ...') # warmup_thread = threading.Thread(target=self._warmup_repositories()) # warmup_thread.start() # # router_thread.join() # if not router_thread.isAlive(): # xbmc.log("[script.luna.kernel]: Bootstrapping Router ... done") # xbmc.log("[script.luna.kernel]: Pre-Loading Controllers ...") # preload_thread = threading.Thread(target=self._preload_controllers) # preload_thread.start() # # if not di_thread.isAlive() and not router_thread.isAlive(): # warmup_thread.join() # preload_thread.join() # # if not warmup_thread.isAlive() and not preload_thread.isAlive(): # xbmc.executebuiltin("Dialog.Close(busydialog)") # if callback: # try: # return callback() # except Exception, e: # exc_type, exc_value, exc_tb = sys.exc_info() # sys.excepthook(exc_type, exc_value, exc_tb) # # def _warmup_repositories(self): # managers = featurebroker.features.get_tagged_features('manager') # for manager in managers: # xbmc.log("[script.luna.kernel]: Currently warming up: %s" % manager.name) # RequiredFeature(manager.name).request() # xbmc.log('[script.luna.kernel]: Warming up managers ... done') # # def _preload_controllers(self): # from resources.lib.di.requiredfeature import RequiredFeature # main_route = self.router.main_route # controller = RequiredFeature(main_route.service[1:]).request() # self.router.register(controller.__class__) # # for key, route in self.router.routing.iteritems(): # if not route.is_main_route: # controller = RequiredFeature(route.service[1:]).request() # self.router.register(controller.__class__) # xbmc.log("[script.luna.kernel]: Pre-Loading Controllers ... done") . Output only the next line.
XBMCApplicationKernel().bootstrap(callback)
Next line prediction: <|code_start|> created. .. seealso:: :class:`xbmcswift2.TimedStorage` for more details. :param name: The name of the storage to retrieve. :param file_format: Choices are 'pickle', 'csv', and 'json'. Pickle is recommended as it supports python objects. .. note:: If a storage already exists for the given name, the file_format parameter is ignored. The format will be determined by the existing storage file. :param TTL: The time to live for storage items specified in minutes or None for no expiration. Since storage items aren't expired until a storage is loaded form disk, it is possible to call get_storage() with a different TTL than when the storage was created. The currently specified TTL is always honored. """ if not hasattr(self, '_unsynced_storages'): self._unsynced_storages = {} filename = os.path.join(self.storage_path, name) try: storage = self._unsynced_storages[filename] self.logger.info('Loaded storage "%s" from memory' % name) except KeyError: if TTL: TTL = timedelta(minutes=TTL) try: <|code_end|> . Use current file imports: (import json import os import stat import re import xbmc import xbmcaddon import xbmcgui from datetime import timedelta from xml.etree.ElementTree import ElementTree from resources.lib.storageengine.storage import TimedStorage) and context including class names, function names, or small code snippets from other files: # Path: resources/lib/storageengine/storage.py # class TimedStorage(_Storage): # """A dict with the ability to persist to disk and TTL for items.""" # # def dump(self, fileobj): # super(TimedStorage, self).dump(fileobj) # # def __init__(self, filename, file_format='pickle', TTL=None): # """TTL if provided should be a datetime.timedelta. Any entries # older than the provided TTL will be removed upon load and upon item # access. # """ # self.TTL = TTL # _Storage.__init__(self, filename, file_format=file_format) # # def __setitem__(self, key, val, raw=False): # if raw: # self._items[key] = val # else: # self._items[key] = (val, time.time()) # # def __getitem__(self, key): # val, timestamp = self._items[key] # if self.TTL and (datetime.utcnow() - # datetime.utcfromtimestamp(timestamp) > self.TTL): # del self._items[key] # return self._items[key][0] # Will raise KeyError # return val # # def initial_update(self, mapping): # '''Initially fills the underlying dictionary with keys, values and # timestamps. # ''' # for key, val in mapping.items(): # _, timestamp = val # if not self.TTL or (datetime.utcnow() - # datetime.utcfromtimestamp(timestamp) < self.TTL): # self.__setitem__(key, val, raw=True) . Output only the next line.
storage = TimedStorage(filename, file_format, TTL)
Based on the snippet: <|code_start|>MIN_INTERVAL = 0.100 ################################################################################ ### @class ScriptData ################################################################################ class ScriptData(): #################################################################### ### @fn __init__() #################################################################### def __init__(self, filename = None): self.filename = "" self.filesize = None self.last_edited = None self.data = None if filename: self.load_file(filename) #################################################################### ### @fn load_file(filename) #################################################################### def load_file(self, filename): if filename == self.filename and not self.needs_update(): return if not os.path.isfile(filename): return stats = os.stat(filename) <|code_end|> , predict the immediate next line with the help of imports: import logging import os import re import time import cPickle as pickle import pickle import common import list_files from script_file import ScriptFile and context (classes, functions, sometimes code) from other files: # Path: script_file.py # class ScriptFile(): # def __init__(self, filename = None, scene_info = None): # self.translated = "" # self.translated_notags = "" # self.original = "" # self.original_notags = "" # self.comments = "" # # self.filename = None # # if not filename == None: # self.open(filename) # # if scene_info == None: # # Squeeze the file ID out of the filename. # scene_info = SceneInfo(file_id = int(os.path.splitext(os.path.basename(filename))[0])) # # self.scene_info = scene_info # # def open(self, filename): # # if not filename or not os.path.isfile(filename): # return # # text = load_text(filename) # # self.from_data(text) # # self.filename = filename # # def from_data(self, data): # # self.filename = None # self.translated = "" # self.translated_notags = "" # self.original = "" # self.original_notags = "" # self.comments = "" # # # Sanitize our line-breaks. The game handles \r\n in some instances, # # but not all. It always handles \n properly. # text = LINE_BREAKS.sub("\n", data) # # match = TEXT_PARSER.search(text) # # if match: # # Remove any trailing linebreaks, because # first_part = match.group(1) # second_part = match.group(2) # third_part = match.group(4) # # if not second_part: # self.original = first_part # else: # self.translated = first_part # self.original = second_part # # if third_part: # self.comments = third_part # # self.original_notags = TAG_KILLER.sub("", self.original) # self.translated_notags = TAG_KILLER.sub("", self.translated) # # ############################################################################## # ### @fn pack() # ### @desc Converts all the data into the script file format. # ### @param for_game -- Whether to include the original, untranslated data. # ### True = exclude untranslated, since we don't need it. # ############################################################################## # def pack(self, for_game = False): # # if self.translated == "": # output = u"\ufeff" + self.original + u"\u0000" # # if self.comments != "" and not for_game: # output += "\n[" + self.comments + "]" # else: # output = u"\ufeff" + self.translated + u"\u0000" # # if not for_game: # output += "\n" + self.original # if self.comments != "": # # We want a newline, but not a thousand. # if not self.original[-1] == '\n': # output += "\n" # # output += "[" + self.comments + "]" # # # Sanitize our line breaks, just in case. # output = LINE_BREAKS.sub("\n", output) # # return output # # def save(self, filename = None): # # if filename == None: # if self.filename == None: # return # else: # filename = self.filename # # output = self.pack(for_game = False) # # save_text(output, filename) . Output only the next line.
data = ScriptFile(filename)
Next line prediction: <|code_start|> toc_count_pos = TOC_INFO[umdimage][game][COUNT] toc_name_off = TOC_INFO[umdimage][game][NAME_OFFSET] eboot_data.bytepos = toc_count_pos toc_count = eboot_data.read("uintle:32") eboot_data.bytepos = toc_start toc = [] file_starts = [] filenames = [] for i in xrange(toc_count): name_pos = eboot_data.read("uintle:32") file_pos_pos = eboot_data.bytepos file_pos = eboot_data.read("uintle:32") file_len_pos = eboot_data.bytepos file_len = eboot_data.read("uintle:32") name_pos += toc_name_off temp_pos = eboot_data.bytepos eboot_data.bytepos = name_pos filename = eboot_data.readto("0x00", bytealigned = True).bytes # Strip the null character. filename = filename[:-1] # Ensure the filenames don't conflict. <|code_end|> . Use current file imports: (from enum import Enum from .unique_postfix import add_unique_postfix) and context including class names, function names, or small code snippets from other files: # Path: extract/unique_postfix.py # def add_unique_postfix(fn, check_fn = os.path.exists): # if not check_fn(fn): # return fn # # path, name = os.path.split(fn) # name, ext = os.path.splitext(name) # # make_fn = lambda i: os.path.join(path, '%s_%d%s' % (name, i, ext)) # # for i in xrange(2, sys.maxint): # uni_fn = make_fn(i) # if not check_fn(uni_fn): # return uni_fn # # return None . Output only the next line.
filename = add_unique_postfix(filename, check_fn = (lambda fn: fn in filenames))
Here is a snippet: <|code_start|>################################################################################ ### Copyright © 2012-2013 BlackDragonHunt ### ### This file is part of the Super Duper Script Editor. ### ### The Super Duper Script Editor is free software: you can redistribute it ### and/or modify it under the terms of the GNU General Public License as ### published by the Free Software Foundation, either version 3 of the License, ### or (at your option) any later version. ### ### The Super Duper Script Editor 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 the Super Duper Script Editor. ### If not, see <http://www.gnu.org/licenses/>. ################################################################################ try: except: class KeywordEdit(QtGui.QTextEdit): def __init__(self, parent): super(KeywordEdit, self).__init__(parent) self.setAcceptRichText(False) <|code_end|> . Write the next line using the current file imports: from PyQt4 import Qt, QtGui, QtCore from PyQt4.QtCore import QRect, QSignalMapper from PyQt4.QtGui import QTextCursor, QApplication from keyword_highlighter import KeywordHighlighter, Keyword import cPickle as pickle import pickle import terminology import time and context from other files: # Path: keyword_highlighter.py # def allindices(string, sub, listindex=[], offset=0): # def __init__(self, parent = None): # def highlightBlock(self, text): # def add_keyword(self, word): # def add_keywords(self, words): # def set_keyword(self, word): # def set_keywords(self, words): # def clear_keywords(self): # class KeywordHighlighter(QtGui.QSyntaxHighlighter): , which may include functions, classes, or code. Output only the next line.
self.highlighter = KeywordHighlighter(self.document())
Predict the next line for this snippet: <|code_start|>### ### You should have received a copy of the GNU General Public License ### along with the Super Duper Script Editor. ### If not, see <http://www.gnu.org/licenses/>. ################################################################################ #from PyQt4 import QtGui #from PyQt4.QtGui import QImage, QColor #import text_printer #from common import SCENE_MODES, SCENE_SPECIAL, BOX_COLORS class SceneInfo(): def __init__(self, file_id = -1, speaker = -1, speaking = False, sprite = SpriteId(), voice = VoiceId(), bgm = -1, headshot = -1, mode = None, special = None, box_color = common.BOX_COLORS.orange, box_type = common.BOX_TYPES.normal, ammo = -1, bgd = -1, cutin = -1, flash = -1, movie = -1, <|code_end|> with the help of current file imports: from enum import Enum from text_printer import IMG_FILTERS from sprite import SpriteId from voice import VoiceId from text_printer import draw_scene import common and context from other files: # Path: text_printer.py # IMG_FILTERS = Enum("unfiltered", "sepia", "inverted") # # Path: voice.py # class VoiceId(): # def __init__( # self, # char_id = -1, # chapter = -1, # voice_id = -1 # ): # self.char_id = char_id # self.chapter = chapter # self.voice_id = voice_id , which may contain function names, class names, or code. Output only the next line.
img_filter = IMG_FILTERS.unfiltered,
Given the following code snippet before the placeholder: <|code_start|>### ### This file is part of the Super Duper Script Editor. ### ### The Super Duper Script Editor is free software: you can redistribute it ### and/or modify it under the terms of the GNU General Public License as ### published by the Free Software Foundation, either version 3 of the License, ### or (at your option) any later version. ### ### The Super Duper Script Editor 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 the Super Duper Script Editor. ### If not, see <http://www.gnu.org/licenses/>. ################################################################################ #from PyQt4 import QtGui #from PyQt4.QtGui import QImage, QColor #import text_printer #from common import SCENE_MODES, SCENE_SPECIAL, BOX_COLORS class SceneInfo(): def __init__(self, file_id = -1, speaker = -1, speaking = False, sprite = SpriteId(), <|code_end|> , predict the next line using imports from the current file: from enum import Enum from text_printer import IMG_FILTERS from sprite import SpriteId from voice import VoiceId from text_printer import draw_scene import common and context including class names, function names, and sometimes code from other files: # Path: text_printer.py # IMG_FILTERS = Enum("unfiltered", "sepia", "inverted") # # Path: voice.py # class VoiceId(): # def __init__( # self, # char_id = -1, # chapter = -1, # voice_id = -1 # ): # self.char_id = char_id # self.chapter = chapter # self.voice_id = voice_id . Output only the next line.
voice = VoiceId(),
Given the code snippet: <|code_start|>### along with the Super Duper Script Editor. ### If not, see <http://www.gnu.org/licenses/>. ################################################################################ _LOGGER_NAME = common.LOGGER_NAME + "." + __name__ _LOGGER = logging.getLogger(_LOGGER_NAME) _NAME = "Name" _START = "Start" _SIZE = "Size" _DATA = "Data" class ModelPak(): def __init__(self, filename = None): self.__data = None self.__gmo_files = [] if filename: self.load_file(filename) def load_file(self, filename): data = BitStream(filename = filename) self.load_data(data) def load_data(self, data): <|code_end|> , generate the next line using the imports in this file: import logging import os import common import glob from bitstring import BitStream, ConstBitStream from extract import get_pak_files, parse_pak_toc from gmo_file import GmoFile, GMO_MAGIC and context (functions, classes, or occasionally code) from other files: # Path: extract/pak_ex.py # def get_pak_files(data, recursive = False, file_ext = None, ext_mode = EXT_MODE.suggest, toc = None): # # # If we don't have enough to even get a file count, we're obviously no good. # if data.len < 32: # raise InvalidArchiveException # # file_starts = [] # file_ends = [] # filenames = None # # if toc == None: # # file_starts, file_ends = parse_pak_toc(data) # num_files = len(file_starts) # # else: # # num_files = data.read("uintle:32") # # filenames = [] # for entry in toc: # file_pos = entry["file_pos"] # file_end = file_pos + entry["file_len"] # filename = entry["filename"] # # file_starts.append(file_pos) # file_ends.append(file_end) # filenames.append(filename) # # ### if toc == None ### # # for i in xrange(num_files): # # file_start = file_starts[i] # file_end = file_ends[i] # # try: # filename, extension = os.path.splitext(filenames[i]) # # except TypeError, IndexError: # filename = "%04d" % i # extension = None # # if ext_mode == EXT_MODE.auto or ext_mode == EXT_MODE.suggest:# or file_ext == None: # extension = guess_ext(data, file_start, file_end) # # if ext_mode == EXT_MODE.force or (ext_mode == EXT_MODE.suggest and extension == None): # extension = file_ext # # # Look for a null character signifying the end of text data, # # so we don't end up with any left-over junk or extra nulls. # # Since text is UTF-16, we check two bytes at a time. # if extension == ".txt": # txt_end = file_end # for txt_byte in xrange(file_start * 8, file_end * 8, 16): # if data[txt_byte : txt_byte + 8] == NULL_BYTE and data[txt_byte + 8 : txt_byte + 16] == NULL_BYTE: # txt_end = (txt_byte / 8) + 2 # break # file_end = txt_end # # file_data = data[file_start * 8 : file_end * 8] # # #print file_start, file_end, filename, extension # # if extension == None: # if recursive == True: # try: # for subfile, subdata in get_pak_files(file_data, True, None): # full_filename = os.path.join(filename, subfile) # yield full_filename, subdata # except InvalidArchiveException: # extension = DEFAULT_EXT # else: # extension = DEFAULT_EXT # # if not extension == None: # filename = filename + extension # yield filename, file_data # # ### for i in xrange(num_files) ### # # def parse_pak_toc(data): # # # If we don't have enough to even get a file count, we're obviously no good. # if data.len < 32: # raise InvalidArchiveException # # data.bytepos = 0 # # num_files = data.read("uintle:32") # # One extra for the file count. # toc_len = (num_files + 1) * 4 # # if num_files <= 0 or toc_len >= data.len / 8: # raise InvalidArchiveException # # file_starts = [] # file_ends = [] # # for i in xrange(num_files): # file_start = data.read("uintle:32") # # # Obviously, a file can't start after the end of the archive # # or inside the table of contents. # if file_start < toc_len or file_start >= data.len / 8: # raise InvalidArchiveException # # # Doesn't make much sense if they're not in order. # if i > 0 and file_start < file_starts[-1]: # raise InvalidArchiveException # # file_starts.append(file_start) # # for i in xrange(num_files): # # file_start = file_starts[i] # if i == num_files - 1: # file_end = (data.len / 8) # else: # file_end = file_starts[i + 1] # # file_ends.append(file_end) # # return file_starts, file_ends . Output only the next line.
files = [entry_data for (entry_name, entry_data) in get_pak_files(data)]
Given the following code snippet before the placeholder: <|code_start|> self.__gmo_files = [] if filename: self.load_file(filename) def load_file(self, filename): data = BitStream(filename = filename) self.load_data(data) def load_data(self, data): files = [entry_data for (entry_name, entry_data) in get_pak_files(data)] # There are always at least four files in a model pak. # The first three I don't know a lot about, and then # the GMO files come after that. if len(files) < 4: _LOGGER.error("Invalid model PAK. %d files found, but at least 4 needed." % len(files)) return # The name pak contains a list of null-terminated names for # each of the models, stored in our standard pak format. name_pak = files[0] names = [entry_data.bytes.strip('\0') for (entry_name, entry_data) in get_pak_files(name_pak)] # Most of the model paks in SDR2 have a fourth unknown file before the models # start, so we'll just take everything from the back end and call it a day. models = files[-len(names):] # Now, we don't get file positions from the unpacker, so let's find those # and start filling out our internal list of GMO files. <|code_end|> , predict the next line using imports from the current file: import logging import os import common import glob from bitstring import BitStream, ConstBitStream from extract import get_pak_files, parse_pak_toc from gmo_file import GmoFile, GMO_MAGIC and context including class names, function names, and sometimes code from other files: # Path: extract/pak_ex.py # def get_pak_files(data, recursive = False, file_ext = None, ext_mode = EXT_MODE.suggest, toc = None): # # # If we don't have enough to even get a file count, we're obviously no good. # if data.len < 32: # raise InvalidArchiveException # # file_starts = [] # file_ends = [] # filenames = None # # if toc == None: # # file_starts, file_ends = parse_pak_toc(data) # num_files = len(file_starts) # # else: # # num_files = data.read("uintle:32") # # filenames = [] # for entry in toc: # file_pos = entry["file_pos"] # file_end = file_pos + entry["file_len"] # filename = entry["filename"] # # file_starts.append(file_pos) # file_ends.append(file_end) # filenames.append(filename) # # ### if toc == None ### # # for i in xrange(num_files): # # file_start = file_starts[i] # file_end = file_ends[i] # # try: # filename, extension = os.path.splitext(filenames[i]) # # except TypeError, IndexError: # filename = "%04d" % i # extension = None # # if ext_mode == EXT_MODE.auto or ext_mode == EXT_MODE.suggest:# or file_ext == None: # extension = guess_ext(data, file_start, file_end) # # if ext_mode == EXT_MODE.force or (ext_mode == EXT_MODE.suggest and extension == None): # extension = file_ext # # # Look for a null character signifying the end of text data, # # so we don't end up with any left-over junk or extra nulls. # # Since text is UTF-16, we check two bytes at a time. # if extension == ".txt": # txt_end = file_end # for txt_byte in xrange(file_start * 8, file_end * 8, 16): # if data[txt_byte : txt_byte + 8] == NULL_BYTE and data[txt_byte + 8 : txt_byte + 16] == NULL_BYTE: # txt_end = (txt_byte / 8) + 2 # break # file_end = txt_end # # file_data = data[file_start * 8 : file_end * 8] # # #print file_start, file_end, filename, extension # # if extension == None: # if recursive == True: # try: # for subfile, subdata in get_pak_files(file_data, True, None): # full_filename = os.path.join(filename, subfile) # yield full_filename, subdata # except InvalidArchiveException: # extension = DEFAULT_EXT # else: # extension = DEFAULT_EXT # # if not extension == None: # filename = filename + extension # yield filename, file_data # # ### for i in xrange(num_files) ### # # def parse_pak_toc(data): # # # If we don't have enough to even get a file count, we're obviously no good. # if data.len < 32: # raise InvalidArchiveException # # data.bytepos = 0 # # num_files = data.read("uintle:32") # # One extra for the file count. # toc_len = (num_files + 1) * 4 # # if num_files <= 0 or toc_len >= data.len / 8: # raise InvalidArchiveException # # file_starts = [] # file_ends = [] # # for i in xrange(num_files): # file_start = data.read("uintle:32") # # # Obviously, a file can't start after the end of the archive # # or inside the table of contents. # if file_start < toc_len or file_start >= data.len / 8: # raise InvalidArchiveException # # # Doesn't make much sense if they're not in order. # if i > 0 and file_start < file_starts[-1]: # raise InvalidArchiveException # # file_starts.append(file_start) # # for i in xrange(num_files): # # file_start = file_starts[i] # if i == num_files - 1: # file_end = (data.len / 8) # else: # file_end = file_starts[i + 1] # # file_ends.append(file_end) # # return file_starts, file_ends . Output only the next line.
file_starts, file_ends = parse_pak_toc(data)
Given the following code snippet before the placeholder: <|code_start|> check_char = -1 cur_ammo = -1 cur_cutin = -1 cur_bgd = -1 cur_flash = -1 cur_movie = -1 # Because we can put flashes on top of flashes. flash_stack = [] # If we set the speaker with a speaker tag, # don't let a voice file/sprite override it. speaker_set = False loaded_sprites = {} box_color = common.BOX_COLORS.orange box_type = common.BOX_TYPES.normal wrd_info = [] for op, params in commands: ######################################## ### Show line ######################################## if op == WRD_SHOW_LINE: line = params["line"] <|code_end|> , predict the next line using imports from the current file: import common from scene_info import SceneInfo from sprite import SpriteId, SPRITE_TYPE from text_printer import IMG_FILTERS from voice import VoiceId from wrd.ops import * and context including class names, function names, and sometimes code from other files: # Path: scene_info.py # class SceneInfo(): # def __init__(self, # file_id = -1, # speaker = -1, # speaking = False, # sprite = SpriteId(), # voice = VoiceId(), # bgm = -1, # headshot = -1, # mode = None, # special = None, # box_color = common.BOX_COLORS.orange, # box_type = common.BOX_TYPES.normal, # ammo = -1, # bgd = -1, # cutin = -1, # flash = -1, # movie = -1, # img_filter = IMG_FILTERS.unfiltered, # chapter = -1, # scene = -1, # room = -1, # extra_val = -1 # ): # self.file_id = file_id # # self.speaker = speaker # self.speaking = speaking # self.sprite = sprite # self.voice = voice # self.bgm = bgm # # self.headshot = headshot # # self.mode = mode # self.special = special # self.box_color = box_color # self.box_type = box_type # # self.ammo = ammo # self.bgd = bgd # self.cutin = cutin # self.flash = flash # self.movie = movie # # self.img_filter = img_filter # # self.chapter = chapter # self.scene = scene # self.room = room # # self.extra_val = extra_val # # Path: text_printer.py # IMG_FILTERS = Enum("unfiltered", "sepia", "inverted") # # Path: voice.py # class VoiceId(): # def __init__( # self, # char_id = -1, # chapter = -1, # voice_id = -1 # ): # self.char_id = char_id # self.chapter = chapter # self.voice_id = voice_id . Output only the next line.
scene_info = SceneInfo()
Here is a snippet: <|code_start|> scene_info.extra_val = option_val #scene_info.trialcam = cur_trialcam ############################## ### Reset stuff ############################## cur_ammo = -1 scene_info.headshot = cur_sprite_obj if is_option: is_option = False option_val = None # is_option_pt = False is_floating = False speaker_set = False cur_voice = VoiceId() wrd_info.append(scene_info) ######################################## ### Image filter ######################################## elif op == WRD_FILTER_IMG: filter = params["filter"] if filter == 0x00: <|code_end|> . Write the next line using the current file imports: import common from scene_info import SceneInfo from sprite import SpriteId, SPRITE_TYPE from text_printer import IMG_FILTERS from voice import VoiceId from wrd.ops import * and context from other files: # Path: scene_info.py # class SceneInfo(): # def __init__(self, # file_id = -1, # speaker = -1, # speaking = False, # sprite = SpriteId(), # voice = VoiceId(), # bgm = -1, # headshot = -1, # mode = None, # special = None, # box_color = common.BOX_COLORS.orange, # box_type = common.BOX_TYPES.normal, # ammo = -1, # bgd = -1, # cutin = -1, # flash = -1, # movie = -1, # img_filter = IMG_FILTERS.unfiltered, # chapter = -1, # scene = -1, # room = -1, # extra_val = -1 # ): # self.file_id = file_id # # self.speaker = speaker # self.speaking = speaking # self.sprite = sprite # self.voice = voice # self.bgm = bgm # # self.headshot = headshot # # self.mode = mode # self.special = special # self.box_color = box_color # self.box_type = box_type # # self.ammo = ammo # self.bgd = bgd # self.cutin = cutin # self.flash = flash # self.movie = movie # # self.img_filter = img_filter # # self.chapter = chapter # self.scene = scene # self.room = room # # self.extra_val = extra_val # # Path: text_printer.py # IMG_FILTERS = Enum("unfiltered", "sepia", "inverted") # # Path: voice.py # class VoiceId(): # def __init__( # self, # char_id = -1, # chapter = -1, # voice_id = -1 # ): # self.char_id = char_id # self.chapter = chapter # self.voice_id = voice_id , which may include functions, classes, or code. Output only the next line.
img_filter = IMG_FILTERS.unfiltered
Given the code snippet: <|code_start|>### Copyright © 2012-2013 BlackDragonHunt ### ### This file is part of the Super Duper Script Editor. ### ### The Super Duper Script Editor is free software: you can redistribute it ### and/or modify it under the terms of the GNU General Public License as ### published by the Free Software Foundation, either version 3 of the License, ### or (at your option) any later version. ### ### The Super Duper Script Editor 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 the Super Duper Script Editor. ### If not, see <http://www.gnu.org/licenses/>. ################################################################################ ############################################################################## ### Converts the parsed wrd file into a list of SceneInfo objects for use ### in the editor ############################################################################## def to_scene_info(commands): cur_speaker = 0x1F cur_sprite = SpriteId() last_sprite = -1 <|code_end|> , generate the next line using the imports in this file: import common from scene_info import SceneInfo from sprite import SpriteId, SPRITE_TYPE from text_printer import IMG_FILTERS from voice import VoiceId from wrd.ops import * and context (functions, classes, or occasionally code) from other files: # Path: scene_info.py # class SceneInfo(): # def __init__(self, # file_id = -1, # speaker = -1, # speaking = False, # sprite = SpriteId(), # voice = VoiceId(), # bgm = -1, # headshot = -1, # mode = None, # special = None, # box_color = common.BOX_COLORS.orange, # box_type = common.BOX_TYPES.normal, # ammo = -1, # bgd = -1, # cutin = -1, # flash = -1, # movie = -1, # img_filter = IMG_FILTERS.unfiltered, # chapter = -1, # scene = -1, # room = -1, # extra_val = -1 # ): # self.file_id = file_id # # self.speaker = speaker # self.speaking = speaking # self.sprite = sprite # self.voice = voice # self.bgm = bgm # # self.headshot = headshot # # self.mode = mode # self.special = special # self.box_color = box_color # self.box_type = box_type # # self.ammo = ammo # self.bgd = bgd # self.cutin = cutin # self.flash = flash # self.movie = movie # # self.img_filter = img_filter # # self.chapter = chapter # self.scene = scene # self.room = room # # self.extra_val = extra_val # # Path: text_printer.py # IMG_FILTERS = Enum("unfiltered", "sepia", "inverted") # # Path: voice.py # class VoiceId(): # def __init__( # self, # char_id = -1, # chapter = -1, # voice_id = -1 # ): # self.char_id = char_id # self.chapter = chapter # self.voice_id = voice_id . Output only the next line.
cur_voice = VoiceId()
Next line prediction: <|code_start|>################################################################################ ### Copyright © 2012-2013 BlackDragonHunt ### ### This file is part of the Super Duper Script Editor. ### ### The Super Duper Script Editor is free software: you can redistribute it ### and/or modify it under the terms of the GNU General Public License as ### published by the Free Software Foundation, either version 3 of the License, ### or (at your option) any later version. ### ### The Super Duper Script Editor 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 the Super Duper Script Editor. ### If not, see <http://www.gnu.org/licenses/>. ################################################################################ class NonstopViewer(QtGui.QDialog): def __init__(self, parent = None): super(NonstopViewer, self).__init__(parent) <|code_end|> . Use current file imports: (from PyQt4 import QtCore, QtGui, Qt from PyQt4.QtGui import QImage, QPainter, QColor, QLabel, QMatrix from PyQt4.QtCore import QRect, QRectF from ui_nonstop import Ui_Nonstop from nonstop import * from text_printer import * import math import os.path import re import sys import time import common import font_parser) and context including class names, function names, or small code snippets from other files: # Path: ui_nonstop.py # class Ui_Nonstop(object): # def setupUi(self, Nonstop): # Nonstop.setObjectName(_fromUtf8("Nonstop")) # Nonstop.resize(498, 311) # Nonstop.setMinimumSize(QtCore.QSize(498, 311)) # Nonstop.setMaximumSize(QtCore.QSize(498, 311)) # Nonstop.setWindowTitle(QtGui.QApplication.translate("Nonstop", "Nonstop Debate Viewer", None, QtGui.QApplication.UnicodeUTF8)) # icon = QtGui.QIcon() # icon.addPixmap(QtGui.QPixmap(_fromUtf8(":/monokuma.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) # Nonstop.setWindowIcon(icon) # self.buttonBox = QtGui.QDialogButtonBox(Nonstop) # self.buttonBox.setGeometry(QtCore.QRect(339, 280, 151, 31)) # self.buttonBox.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.UnitedStates)) # self.buttonBox.setOrientation(QtCore.Qt.Horizontal) # self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok) # self.buttonBox.setObjectName(_fromUtf8("buttonBox")) # self.lblPreview = QtGui.QLabel(Nonstop) # self.lblPreview.setGeometry(QtCore.QRect(9, 9, 480, 272)) # self.lblPreview.setFrameShape(QtGui.QFrame.StyledPanel) # self.lblPreview.setFrameShadow(QtGui.QFrame.Sunken) # self.lblPreview.setText(_fromUtf8("")) # self.lblPreview.setObjectName(_fromUtf8("lblPreview")) # # self.retranslateUi(Nonstop) # QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("accepted()")), Nonstop.accept) # QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("rejected()")), Nonstop.reject) # QtCore.QMetaObject.connectSlotsByName(Nonstop) # # def retranslateUi(self, Nonstop): # pass . Output only the next line.
self.ui = Ui_Nonstop()
Here is a snippet: <|code_start|> sprite_id = mtb.read("uintle:16") sprite = SpriteId(SPRITE_TYPE.stand, sprite_char, sprite_id) # --- TABLE FORMAT --- # XX XX XX XX -- Number of files # # [for each line] # XX XX XX XX -- Offset (from table start) of voice info. # # -- Voice Info -- # XX XX -- File ID # XX XX -- Voice ID (with char ID above and the chapter ID 0x63, we know which voice file to use) mtb.bytepos = table_offset num_files = mtb.read("uintle:32") for i in range(num_files): voice_offset = mtb.read("uintle:32") # Store our position in the table so we can jump back to it. table_pos = mtb.bytepos mtb.bytepos = table_offset + voice_offset file_id = mtb.read("uintle:16") voice_id = mtb.read("uintle:16") # Chapter is 0x63, which is where the non-Trial voice samples are stored, # but I don't see the information actually recorded in the MTB files, # so I'm magic-numbering it here. <|code_end|> . Write the next line using the current file imports: from bitstring import ConstBitStream from script_pack import ScriptPack from sprite import SpriteId, SPRITE_TYPE from voice import VoiceId import logging import os import common and context from other files: # Path: script_pack.py # class ScriptPack(): # def __init__(self, directory = None, umdimage = "umdimage"): # self.script_files = [] # self.directory = directory # self.wrd = None # self.wrd_file = None # # if not directory == None: # self.load_dir(directory, umdimage) # # def __getitem__(self, index): # return self.script_files[index] # # def __len__(self): # return len(self.script_files) # # def get_index(self, filename): # for index, file in enumerate(self.script_files): # if os.path.split(file.filename)[1] == filename: # return index # # return None # # def get_script(self, filename): # index = self.get_index(filename) # # if not index == None: # return self.__getitem__(index) # # else: # return None # # def get_real_dir(self): # # Rather than the easy to look at directory name we usually store, # # get the actual, untampered directory name where you can find the files. # return dir_tools.expand_dir(self.directory) # # def load_dir(self, directory, umdimage = "umdimage"): # # self.script_files = [] # self.directory = directory # self.wrd = None # self.wrd_file = None # self.py_file = None # # base_name = directory # directory, wrd_file = dir_tools.parse_dir(directory, umdimage) # # if directory == None: # self.directory = "" # raise Exception("Directory \"" + base_name + "\" not found.") # # full_dir = os.path.join(umdimage, directory) # # scene_info = [] # # if not wrd_file == None and os.path.isfile(wrd_file): # # # Even of the first directory existed and we have a .wrd file, # # it's possible there aren't actually any text files here. # if not os.path.isdir(full_dir): # raise Exception("There are no text files in \"" + directory + "\".") # # self.wrd = WrdFile() # # py_file = os.path.splitext(wrd_file)[0] + ".py" # # if os.path.isfile(py_file): # try: # self.wrd.load_python(py_file) # except: # _LOGGER.warning("%s failed to load. Parsing wrd file instead. Exception info:\n%s" % (py_file, traceback.format_exc())) # self.wrd.load_bin(wrd_file) # else: # # If we succeeded in loading the python file, compile it to binary. # # _LOGGER.info("%s loaded successfully. Compiling to binary." % py_file) # # self.wrd.save_bin(wrd_file) # _LOGGER.info("%s loaded successfully." % py_file) # # else: # _LOGGER.info("Decompiled wrd file not found. Generating %s" % py_file) # self.wrd.load_bin(wrd_file) # self.wrd.save_python(py_file) # # scene_info = self.wrd.to_scene_info() # self.wrd_file = wrd_file # self.py_file = py_file # # else: # scene_info = None # self.wrd = None # self.wrd_file = None # # self.script_files = [] # if scene_info == None: # text_files = list_all_files(full_dir) # for file in text_files: # self.script_files.append(ScriptFile(file)) # # else: # # Get our files in the order listed by the wrd. # for info in scene_info: # filename = os.path.join(full_dir, "%04d.txt" % info.file_id) # script_file = ScriptFile(filename, info) # # if script_file.filename == None: # _LOGGER.warning("File %s referenced by %s does not exist." % (filename, wrd_file)) # continue # # self.script_files.append(script_file) # # chapter, scene, room, mode = common.get_dir_info(base_name) # # for file in self.script_files: # if file.scene_info.chapter == -1: file.scene_info.chapter = chapter # if file.scene_info.scene == -1: file.scene_info.scene = scene # if file.scene_info.room == -1: file.scene_info.room = room # if file.scene_info.mode == None: file.scene_info.mode = mode # # Path: voice.py # class VoiceId(): # def __init__( # self, # char_id = -1, # chapter = -1, # voice_id = -1 # ): # self.char_id = char_id # self.chapter = chapter # self.voice_id = voice_id , which may include functions, classes, or code. Output only the next line.
voice = VoiceId(voice_char, 0x63, voice_id)
Predict the next line for this snippet: <|code_start|> _LOGGER_NAME = common.LOGGER_NAME + "." + __name__ _LOGGER = logging.getLogger(_LOGGER_NAME) FONT_TYPES = Enum("font01", "font02") GAMES = Enum("dr", "sdr2") LINE_HEIGHT = {FONT_TYPES.font01: 25, FONT_TYPES.font02: 26} MAX_HEIGHT = 2048 HEIGHT_FACTOR = 128 # UNKNOWN1 is different for every font I've seen. UNKNOWN1 = { GAMES.dr: { FONT_TYPES.font01: BitStream(hex = '0x2D000000'), FONT_TYPES.font02: BitStream(hex = '0x30000000'), }, GAMES.sdr2: { FONT_TYPES.font01: BitStream(hex = '0x24000000'), FONT_TYPES.font02: BitStream(hex = '0x2D000000'), } } UNKNOWN2 = BitStream(hex = '0x01000000') class FontData: def __init__(self): self.data = [] def save(self, filename, font_type = FONT_TYPES.font01, game = GAMES.dr): <|code_end|> with the help of current file imports: from PyQt4 import QtCore, QtGui, Qt from PyQt4.QtGui import QFont, QFontMetrics, QImage, QPainter, QPainterPath, QColor from bitstring import BitStream from enum import Enum from font_parser import SPFT_MAGIC import logging import math import os import sys import common and context from other files: # Path: font_parser.py # SPFT_MAGIC = ConstBitStream(hex='0x7446705304000000') , which may contain function names, class names, or code. Output only the next line.
data = BitStream(SPFT_MAGIC)
Here is a snippet: <|code_start|>### Copyright © 2012-2013 BlackDragonHunt ### ### This file is part of the Super Duper Script Editor. ### ### The Super Duper Script Editor is free software: you can redistribute it ### and/or modify it under the terms of the GNU General Public License as ### published by the Free Software Foundation, either version 3 of the License, ### or (at your option) any later version. ### ### The Super Duper Script Editor 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 the Super Duper Script Editor. ### If not, see <http://www.gnu.org/licenses/>. ################################################################################ try: except: MAX_SUGGESTIONS = 6 class SpellCheckEdit(QtGui.QTextEdit): def __init__(self, parent): super(SpellCheckEdit, self).__init__(parent) self.setAcceptRichText(False) <|code_end|> . Write the next line using the current file imports: from PyQt4 import QtGui, QtCore from PyQt4.QtGui import QTextCursor from PyQt4.QtCore import QSignalMapper from spellcheck_highlighter import SpellCheckHighlighter import cPickle as pickle import pickle import common and context from other files: # Path: spellcheck_highlighter.py # class SpellCheckHighlighter(QtGui.QSyntaxHighlighter): # def __init__(self, parent = None): # super(SpellCheckHighlighter, self).__init__(parent) # # self.set_language("en_US") # # self.format = QTextCharFormat() # self.format.setUnderlineColor(QColor(255, 0, 0)) # self.format.setUnderlineStyle(QTextCharFormat.SpellCheckUnderline) # # self.errors = [] # # def set_language(self, lang): # dict = enchant.DictWithPWL(lang, "data/dict/enchant.txt") # self.checker = SpellChecker(dict, chunkers = (HTMLChunker,)) # # def get_language(self): # return self.checker.dict.tag # # def highlightBlock(self, text): # # # If there is no previous state, then it's -1, which makes the first line 0. # # And every line after that increases as expected. # line = self.previousBlockState() + 1 # self.setCurrentBlockState(line) # # # Make sure our error list is long enough to hold this line. # for i in range(len(self.errors), line + 1): # self.errors.append([]) # # self.errors[line] = [] # self.checker.set_text(common.qt_to_unicode(text)) # # for err in self.checker: # self.setFormat(err.wordpos, len(err.word), self.format) # self.errors[line].append((err.word, err.wordpos)) # # def add(self, word): # self.checker.add(word) # self.rehighlight() # # def ignore(self, word): # self.checker.ignore_always(word) # self.rehighlight() , which may include functions, classes, or code. Output only the next line.
self.highlighter = SpellCheckHighlighter(self.document())
Based on the snippet: <|code_start|> if sprite: painter.drawImage(out.rect(), sprite, sprite.rect()) if not scene_info.img_filter == IMG_FILTERS.unfiltered: painter.end() out = filter_image(out, scene_info.img_filter) painter = QPainter(out) painter.setRenderHint(QPainter.Antialiasing, True) if show_box: box = get_box(scene_info) painter.drawImage(out.rect(), box, box.rect()) return out ############################################################################## ### @fn get_letter(clt, char) ### @desc Returns an image containing the letter rendered with the given CLT. ############################################################################## def get_letter(clt, char): if not clt in CLT: clt = 0 font = CLT[clt]['font'] hscale = CLT[clt]['hscale'] vscale = CLT[clt]['vscale'] try: <|code_end|> , predict the immediate next line with the help of imports: from PyQt4 import QtCore, QtGui, Qt from PyQt4.QtGui import QImage, QPainter, QColor, QPixmap, QBitmap, QMatrix from PyQt4.QtCore import QRect, QRectF from enum import Enum from font_parser import FONT_DATA, CLT from text_files import load_text from sprite import get_sprite_file, SPRITE_TYPE import ctypes import os.path import re import sys import time import common import font_parser and context (classes, functions, sometimes code) from other files: # Path: font_parser.py # FONT_DATA = { 1: {}, 2: {} } # # CLT = { # 0: {'font': 1, 'hscale': 1.00, 'vscale': 1.00, 'xshift': 0.00, 'yshift': 0.00}, # 1: {'font': 1, 'hscale': 1.00, 'vscale': 1.00, 'xshift': 0.00, 'yshift': 0.00}, # 2: {'font': 1, 'hscale': 1.00, 'vscale': 1.00, 'xshift': 0.00, 'yshift': 0.00}, # 3: {'font': 1, 'hscale': 1.00, 'vscale': 1.00, 'xshift': 0.00, 'yshift': 0.00}, # 4: {'font': 1, 'hscale': 1.00, 'vscale': 1.00, 'xshift': 0.00, 'yshift': 0.00}, # 5: {'font': 2, 'hscale': 0.69, 'vscale': 0.69, 'xshift': 0.00, 'yshift': 0.00}, # 6: {'font': 1, 'hscale': 0.80, 'vscale': 0.80, 'xshift': -1.00, 'yshift': 0.00}, # 7: {'font': 1, 'hscale': 0.80, 'vscale': 0.80, 'xshift': -1.00, 'yshift': 0.00}, # 8: {'font': 2, 'hscale': 5.0 / 6.0, 'vscale': 5.0 / 6.0, 'xshift': -1.00, 'yshift': 1.00}, # 9: {'font': 2, 'hscale': 1.00, 'vscale': 1.00, 'xshift': 0.00, 'yshift': 0.00}, # 10: {'font': 2, 'hscale': 1.00, 'vscale': 1.00, 'xshift': 0.00, 'yshift': 0.00}, # 11: {'font': 2, 'hscale': 1.00, 'vscale': 1.00, 'xshift': 0.00, 'yshift': 0.00}, # 12: {'font': 2, 'hscale': 5.0 / 6.0, 'vscale': 5.0 / 6.0, 'xshift': -1.00, 'yshift': 0.00}, # 13: {'font': 1, 'hscale': 0.80, 'vscale': 0.80, 'xshift': -1.00, 'yshift': 0.00}, # 14: {'font': 1, 'hscale': 0.80, 'vscale': 0.80, 'xshift': -1.00, 'yshift': 0.00}, # 15: {'font': 1, 'hscale': 1.00, 'vscale': 1.00, 'xshift': 0.00, 'yshift': 0.00}, # 16: {'font': 2, 'hscale': 1.00, 'vscale': 1.00, 'xshift': 0.00, 'yshift': 0.00}, # 17: {'font': 2, 'hscale': 2.0 / 3.0, 'vscale': 2.0 / 3.0, 'xshift': 0.00, 'yshift': 0.00}, # 18: {'font': 1, 'hscale': 0.80, 'vscale': 0.80, 'xshift': -1.00, 'yshift': 0.00}, # 19: {'font': 1, 'hscale': 0.80, 'vscale': 0.80, 'xshift': -1.00, 'yshift': 0.00}, # 20: {'font': 1, 'hscale': 1.00, 'vscale': 1.00, 'xshift': 0.00, 'yshift': 0.00}, # 21: {'font': 1, 'hscale': 0.80, 'vscale': 0.80, 'xshift': -1.00, 'yshift': 0.00}, # 22: {'font': 1, 'hscale': 0.80, 'vscale': 0.80, 'xshift': -1.00, 'yshift': 0.00}, # 23: {'font': 1, 'hscale': 1.00, 'vscale': 1.00, 'xshift': 0.00, 'yshift': 0.00}, # 24: {'font': 1, 'hscale': 0.80, 'vscale': 0.80, 'xshift': -1.00, 'yshift': 0.00}, # 25: {'font': 1, 'hscale': 1.00, 'vscale': 1.00, 'xshift': 0.00, 'yshift': 0.00}, # 26: {'font': 2, 'hscale': 1.00, 'vscale': 1.00, 'xshift': 0.00, 'yshift': 0.00}, # 98: {'font': 1, 'hscale': 1.00, 'vscale': 1.00, 'xshift': 0.00, 'yshift': 0.00}, # 99: {'font': 2, 'hscale': 1.00, 'vscale': 1.00, 'xshift': 0.00, 'yshift': 0.00}, # } . Output only the next line.
info = FONT_DATA[font][char]
Predict the next line after this snippet: <|code_start|> painter = QPainter(out) painter.setRenderHint(QPainter.Antialiasing, True) if show_sprite: sprite_id.sprite_type = SPRITE_TYPE.stand sprite = get_sprite(sprite_id) if sprite: painter.drawImage(out.rect(), sprite, sprite.rect()) if not scene_info.img_filter == IMG_FILTERS.unfiltered: painter.end() out = filter_image(out, scene_info.img_filter) painter = QPainter(out) painter.setRenderHint(QPainter.Antialiasing, True) if show_box: box = get_box(scene_info) painter.drawImage(out.rect(), box, box.rect()) return out ############################################################################## ### @fn get_letter(clt, char) ### @desc Returns an image containing the letter rendered with the given CLT. ############################################################################## def get_letter(clt, char): <|code_end|> using the current file's imports: from PyQt4 import QtCore, QtGui, Qt from PyQt4.QtGui import QImage, QPainter, QColor, QPixmap, QBitmap, QMatrix from PyQt4.QtCore import QRect, QRectF from enum import Enum from font_parser import FONT_DATA, CLT from text_files import load_text from sprite import get_sprite_file, SPRITE_TYPE import ctypes import os.path import re import sys import time import common import font_parser and any relevant context from other files: # Path: font_parser.py # FONT_DATA = { 1: {}, 2: {} } # # CLT = { # 0: {'font': 1, 'hscale': 1.00, 'vscale': 1.00, 'xshift': 0.00, 'yshift': 0.00}, # 1: {'font': 1, 'hscale': 1.00, 'vscale': 1.00, 'xshift': 0.00, 'yshift': 0.00}, # 2: {'font': 1, 'hscale': 1.00, 'vscale': 1.00, 'xshift': 0.00, 'yshift': 0.00}, # 3: {'font': 1, 'hscale': 1.00, 'vscale': 1.00, 'xshift': 0.00, 'yshift': 0.00}, # 4: {'font': 1, 'hscale': 1.00, 'vscale': 1.00, 'xshift': 0.00, 'yshift': 0.00}, # 5: {'font': 2, 'hscale': 0.69, 'vscale': 0.69, 'xshift': 0.00, 'yshift': 0.00}, # 6: {'font': 1, 'hscale': 0.80, 'vscale': 0.80, 'xshift': -1.00, 'yshift': 0.00}, # 7: {'font': 1, 'hscale': 0.80, 'vscale': 0.80, 'xshift': -1.00, 'yshift': 0.00}, # 8: {'font': 2, 'hscale': 5.0 / 6.0, 'vscale': 5.0 / 6.0, 'xshift': -1.00, 'yshift': 1.00}, # 9: {'font': 2, 'hscale': 1.00, 'vscale': 1.00, 'xshift': 0.00, 'yshift': 0.00}, # 10: {'font': 2, 'hscale': 1.00, 'vscale': 1.00, 'xshift': 0.00, 'yshift': 0.00}, # 11: {'font': 2, 'hscale': 1.00, 'vscale': 1.00, 'xshift': 0.00, 'yshift': 0.00}, # 12: {'font': 2, 'hscale': 5.0 / 6.0, 'vscale': 5.0 / 6.0, 'xshift': -1.00, 'yshift': 0.00}, # 13: {'font': 1, 'hscale': 0.80, 'vscale': 0.80, 'xshift': -1.00, 'yshift': 0.00}, # 14: {'font': 1, 'hscale': 0.80, 'vscale': 0.80, 'xshift': -1.00, 'yshift': 0.00}, # 15: {'font': 1, 'hscale': 1.00, 'vscale': 1.00, 'xshift': 0.00, 'yshift': 0.00}, # 16: {'font': 2, 'hscale': 1.00, 'vscale': 1.00, 'xshift': 0.00, 'yshift': 0.00}, # 17: {'font': 2, 'hscale': 2.0 / 3.0, 'vscale': 2.0 / 3.0, 'xshift': 0.00, 'yshift': 0.00}, # 18: {'font': 1, 'hscale': 0.80, 'vscale': 0.80, 'xshift': -1.00, 'yshift': 0.00}, # 19: {'font': 1, 'hscale': 0.80, 'vscale': 0.80, 'xshift': -1.00, 'yshift': 0.00}, # 20: {'font': 1, 'hscale': 1.00, 'vscale': 1.00, 'xshift': 0.00, 'yshift': 0.00}, # 21: {'font': 1, 'hscale': 0.80, 'vscale': 0.80, 'xshift': -1.00, 'yshift': 0.00}, # 22: {'font': 1, 'hscale': 0.80, 'vscale': 0.80, 'xshift': -1.00, 'yshift': 0.00}, # 23: {'font': 1, 'hscale': 1.00, 'vscale': 1.00, 'xshift': 0.00, 'yshift': 0.00}, # 24: {'font': 1, 'hscale': 0.80, 'vscale': 0.80, 'xshift': -1.00, 'yshift': 0.00}, # 25: {'font': 1, 'hscale': 1.00, 'vscale': 1.00, 'xshift': 0.00, 'yshift': 0.00}, # 26: {'font': 2, 'hscale': 1.00, 'vscale': 1.00, 'xshift': 0.00, 'yshift': 0.00}, # 98: {'font': 1, 'hscale': 1.00, 'vscale': 1.00, 'xshift': 0.00, 'yshift': 0.00}, # 99: {'font': 2, 'hscale': 1.00, 'vscale': 1.00, 'xshift': 0.00, 'yshift': 0.00}, # } . Output only the next line.
if not clt in CLT:
Given the code snippet: <|code_start|>################################################################################ ### Copyright © 2012-2013 BlackDragonHunt ### ### This file is part of the Super Duper Script Editor. ### ### The Super Duper Script Editor is free software: you can redistribute it ### and/or modify it under the terms of the GNU General Public License as ### published by the Free Software Foundation, either version 3 of the License, ### or (at your option) any later version. ### ### The Super Duper Script Editor 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 the Super Duper Script Editor. ### If not, see <http://www.gnu.org/licenses/>. ################################################################################ class TermEdit(QtGui.QDialog): def __init__(self, parent = None): super(TermEdit, self).__init__(parent) <|code_end|> , generate the next line using the imports in this file: from PyQt4 import QtCore, QtGui, Qt from ui_termedit import Ui_TermEdit and context (functions, classes, or occasionally code) from other files: # Path: ui_termedit.py # class Ui_TermEdit(object): # def setupUi(self, TermEdit): # TermEdit.setObjectName(_fromUtf8("TermEdit")) # TermEdit.resize(448, 97) # TermEdit.setWindowTitle(QtGui.QApplication.translate("TermEdit", "Term", None, QtGui.QApplication.UnicodeUTF8)) # icon = QtGui.QIcon() # icon.addPixmap(QtGui.QPixmap(_fromUtf8(":/monokuma.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) # TermEdit.setWindowIcon(icon) # self.buttonBox = QtGui.QDialogButtonBox(TermEdit) # self.buttonBox.setGeometry(QtCore.QRect(370, 39, 71, 51)) # self.buttonBox.setOrientation(QtCore.Qt.Vertical) # self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok) # self.buttonBox.setObjectName(_fromUtf8("buttonBox")) # self.txtJapanese = QtGui.QLineEdit(TermEdit) # self.txtJapanese.setGeometry(QtCore.QRect(70, 40, 291, 20)) # self.txtJapanese.setObjectName(_fromUtf8("txtJapanese")) # self.txtEnglish = QtGui.QLineEdit(TermEdit) # self.txtEnglish.setGeometry(QtCore.QRect(70, 70, 291, 20)) # self.txtEnglish.setObjectName(_fromUtf8("txtEnglish")) # self.label = QtGui.QLabel(TermEdit) # self.label.setGeometry(QtCore.QRect(10, 10, 431, 16)) # font = QtGui.QFont() # font.setPointSize(10) # self.label.setFont(font) # self.label.setText(QtGui.QApplication.translate("TermEdit", "Please input the original Japanese and the English translation of the term.", None, QtGui.QApplication.UnicodeUTF8)) # self.label.setAlignment(QtCore.Qt.AlignCenter) # self.label.setObjectName(_fromUtf8("label")) # self.label_2 = QtGui.QLabel(TermEdit) # self.label_2.setGeometry(QtCore.QRect(10, 40, 51, 18)) # self.label_2.setText(QtGui.QApplication.translate("TermEdit", "Japanese", None, QtGui.QApplication.UnicodeUTF8)) # self.label_2.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) # self.label_2.setObjectName(_fromUtf8("label_2")) # self.label_3 = QtGui.QLabel(TermEdit) # self.label_3.setGeometry(QtCore.QRect(10, 70, 51, 18)) # self.label_3.setText(QtGui.QApplication.translate("TermEdit", "English", None, QtGui.QApplication.UnicodeUTF8)) # self.label_3.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) # self.label_3.setObjectName(_fromUtf8("label_3")) # # self.retranslateUi(TermEdit) # QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("accepted()")), TermEdit.accept) # QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("rejected()")), TermEdit.reject) # QtCore.QMetaObject.connectSlotsByName(TermEdit) # TermEdit.setTabOrder(self.txtJapanese, self.txtEnglish) # TermEdit.setTabOrder(self.txtEnglish, self.buttonBox) # # def retranslateUi(self, TermEdit): # pass . Output only the next line.
self.ui = Ui_TermEdit()
Based on 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 the Super Duper Script Editor. ### If not, see <http://www.gnu.org/licenses/>. ################################################################################ # import mecab_parser # Some regexes for our enjoyment. LINE_BREAKS = re.compile(ur"\r\n?", re.UNICODE | re.DOTALL) TEXT_PARSER = re.compile(ur"([^\u0000\u0001]+)[\u0000\u0001]+[\n\r]*([^\[]+)?[\n\r]*(\[(.+)\])?", re.UNICODE | re.DOTALL) TAG_KILLER = re.compile(ur"\<CLT\>|\<CLT (?P<CLT_INDEX>\d+)\>|<DIG.*?>", re.UNICODE | re.DOTALL) class ScriptFile(): def __init__(self, filename = None, scene_info = None): self.translated = "" self.translated_notags = "" self.original = "" self.original_notags = "" self.comments = "" self.filename = None if not filename == None: self.open(filename) if scene_info == None: # Squeeze the file ID out of the filename. <|code_end|> , predict the immediate next line with the help of imports: import os import re from text_files import load_text, save_text from scene_info import SceneInfo and context (classes, functions, sometimes code) from other files: # Path: scene_info.py # class SceneInfo(): # def __init__(self, # file_id = -1, # speaker = -1, # speaking = False, # sprite = SpriteId(), # voice = VoiceId(), # bgm = -1, # headshot = -1, # mode = None, # special = None, # box_color = common.BOX_COLORS.orange, # box_type = common.BOX_TYPES.normal, # ammo = -1, # bgd = -1, # cutin = -1, # flash = -1, # movie = -1, # img_filter = IMG_FILTERS.unfiltered, # chapter = -1, # scene = -1, # room = -1, # extra_val = -1 # ): # self.file_id = file_id # # self.speaker = speaker # self.speaking = speaking # self.sprite = sprite # self.voice = voice # self.bgm = bgm # # self.headshot = headshot # # self.mode = mode # self.special = special # self.box_color = box_color # self.box_type = box_type # # self.ammo = ammo # self.bgd = bgd # self.cutin = cutin # self.flash = flash # self.movie = movie # # self.img_filter = img_filter # # self.chapter = chapter # self.scene = scene # self.room = room # # self.extra_val = extra_val . Output only the next line.
scene_info = SceneInfo(file_id = int(os.path.splitext(os.path.basename(filename))[0]))
Given the code snippet: <|code_start|>### published by the Free Software Foundation, either version 3 of the License, ### or (at your option) any later version. ### ### The Super Duper Script Editor 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 the Super Duper Script Editor. ### If not, see <http://www.gnu.org/licenses/>. ################################################################################ ################################################################################ ### Converts binary wrd data to a list of commands which can be used in all ### the other functions in this module. ################################################################################ def from_bin(data): # Eat the header. parse_command(data) commands = [] while True: try: op, params = parse_command(data) commands.append((op, params)) <|code_end|> , generate the next line using the imports in this file: import bitstring from bitstring import BitStream, ConstBitStream from wrd.ops import * from wrd.parser import parse_command, InvalidWrdHeader and context (functions, classes, or occasionally code) from other files: # Path: wrd/parser.py # def parse_command(data): # # header = data.peek("uint:8") # # if not header == CMD_MARKER: # raise InvalidWrdHeader("Command 0x%02X does not begin with 0x%02X" % (header, CMD_MARKER)) # # data.read("uint:8") # op = data.read("uint:8") # # params = OrderedDict() # # if op in OP_PARAMS: # param_info = OP_PARAMS[op] # # # If it's a custom function, use that. # if isinstance(param_info, basestring): # if param_info in globals(): # params = globals()[param_info](data) # else: # raise Exception("Function %s not defined." % param_info) # # # Otherwise, just use the param list. # else: # param_names = [info[0] for info in param_info] # param_types = [info[1] for info in param_info] # # param_vals = data.readlist(param_types) # # for name, val in zip(param_names, param_vals): # # if name == None: # try: # params[None].append(val) # except: # params[None] = [val] # else: # params[name] = val # # else: # print "Unknown opcode encountered: 0x%02X" % op # # return op, params # # class InvalidWrdHeader(Exception): # pass . Output only the next line.
except InvalidWrdHeader:
Given the code snippet: <|code_start|> # If there is no previous state, then it's -1, which makes the first line 0. # And every line after that increases as expected. line = self.previousBlockState() + 1 self.setCurrentBlockState(line) # Make sure we aren't too long. if len(self.matches) > self.parent().blockCount(): self.matches = self.matches[:self.parent().blockCount()] # Make sure our matches list is long enough to hold this line. for i in range(len(self.matches), line + 1): self.matches.append([]) if len(self.keywords) == 0: return self.matches[line] = [] text = common.qt_to_unicode(text) for keyword in self.keywords: #matches = [match.start() for match in re.finditer(re.escape(keyword.word), text)] #matches = [match for match in re.finditer(keyword.word, text, self.re_flags)] #matches = re.finditer(keyword.word, text, self.re_flags) #keyword.compiled.flags = self.re_flags matches = keyword.compiled.finditer(text) for match in matches: self.setFormat(match.start(), match.end() - match.start(), self.format) <|code_end|> , generate the next line using the imports in this file: from PyQt4 import QtGui, QtCore from PyQt4.QtGui import QTextCharFormat, QColor from terminology import Term as Keyword import re import common and context (functions, classes, or occasionally code) from other files: # Path: terminology.py # class Term(): # def __init__(self, word = "", meaning = "", section = ""): # self.word = word # self.meaning = meaning # self.section = section . Output only the next line.
keyword_match = Keyword()
Continue the code snippet: <|code_start|>################################################################################ ### Copyright © 2012-2013 BlackDragonHunt ### ### This file is part of the Super Duper Script Editor. ### ### The Super Duper Script Editor is free software: you can redistribute it ### and/or modify it under the terms of the GNU General Public License as ### published by the Free Software Foundation, either version 3 of the License, ### or (at your option) any later version. ### ### The Super Duper Script Editor 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 the Super Duper Script Editor. ### If not, see <http://www.gnu.org/licenses/>. ################################################################################ _LOGGER = logging.getLogger(common.LOGGER_NAME) LEVELS = ["Debug", "Info", "Warning", "Error", "Critical"] class Console(QtGui.QDialog): def __init__(self, parent = None): super(Console, self).__init__(parent) <|code_end|> . Use current file imports: import logging import common import sys from PyQt4 import QtCore, QtGui, Qt from ui_console import Ui_Console and context (classes, functions, or code) from other files: # Path: ui_console.py # class Ui_Console(object): # def setupUi(self, Console): # Console.setObjectName(_fromUtf8("Console")) # Console.resize(689, 369) # Console.setWindowTitle(QtGui.QApplication.translate("Console", "Console", None, QtGui.QApplication.UnicodeUTF8)) # icon = QtGui.QIcon() # icon.addPixmap(QtGui.QPixmap(_fromUtf8(":/monokuma-green.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) # Console.setWindowIcon(icon) # self.verticalLayout = QtGui.QVBoxLayout(Console) # self.verticalLayout.setSpacing(2) # self.verticalLayout.setMargin(2) # self.verticalLayout.setObjectName(_fromUtf8("verticalLayout")) # self.txtConsole = XLoggerWidget(Console) # self.txtConsole.setLineWrapMode(QtGui.QTextEdit.NoWrap) # self.txtConsole.setObjectName(_fromUtf8("txtConsole")) # self.verticalLayout.addWidget(self.txtConsole) # self.horizontalLayout = QtGui.QHBoxLayout() # self.horizontalLayout.setSpacing(8) # self.horizontalLayout.setContentsMargins(4, -1, 0, -1) # self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout")) # self.label = QtGui.QLabel(Console) # self.label.setText(QtGui.QApplication.translate("Console", "Logging Level", None, QtGui.QApplication.UnicodeUTF8)) # self.label.setObjectName(_fromUtf8("label")) # self.horizontalLayout.addWidget(self.label) # self.cboLevels = QtGui.QComboBox(Console) # self.cboLevels.setObjectName(_fromUtf8("cboLevels")) # self.horizontalLayout.addWidget(self.cboLevels) # self.chkWordWrap = QtGui.QCheckBox(Console) # self.chkWordWrap.setText(QtGui.QApplication.translate("Console", "Word wrap", None, QtGui.QApplication.UnicodeUTF8)) # self.chkWordWrap.setObjectName(_fromUtf8("chkWordWrap")) # self.horizontalLayout.addWidget(self.chkWordWrap) # spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) # self.horizontalLayout.addItem(spacerItem) # self.pushButton = QtGui.QPushButton(Console) # self.pushButton.setText(QtGui.QApplication.translate("Console", "Clear", None, QtGui.QApplication.UnicodeUTF8)) # self.pushButton.setObjectName(_fromUtf8("pushButton")) # self.horizontalLayout.addWidget(self.pushButton) # self.verticalLayout.addLayout(self.horizontalLayout) # # self.retranslateUi(Console) # QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8("clicked()")), self.txtConsole.clear) # QtCore.QObject.connect(self.cboLevels, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(QString)")), Console.updateLogLevel) # QtCore.QMetaObject.connectSlotsByName(Console) # # def retranslateUi(self, Console): # pass . Output only the next line.
self.ui = Ui_Console()
Given the code snippet: <|code_start|>################################################################################ ### Copyright © 2012-2013 BlackDragonHunt ### ### This file is part of the Super Duper Script Editor. ### ### The Super Duper Script Editor is free software: you can redistribute it ### and/or modify it under the terms of the GNU General Public License as ### published by the Free Software Foundation, either version 3 of the License, ### or (at your option) any later version. ### ### The Super Duper Script Editor 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 the Super Duper Script Editor. ### If not, see <http://www.gnu.org/licenses/>. ################################################################################ def get_save_file(parent, default, filter = ""): file = QFileDialog.getSaveFileName(parent, directory = default, filter = filter + ";;All files (*.*)") <|code_end|> , generate the next line using the imports in this file: from PyQt4 import QtGui from PyQt4.QtGui import QFileDialog from common import qt_to_unicode import os and context (functions, classes, or occasionally code) from other files: # Path: common.py # def qt_to_unicode(str, normalize = True): # if normalize: # str = str.normalized(QString.NormalizationForm_C) # # return unicode(str.toUtf8(), "UTF-8") . Output only the next line.
file = qt_to_unicode(file)
Next line prediction: <|code_start|> hard_orig = None if dat_file.pos >= dat_file.len: # If we don't have more data, then consider this untranslated. # Therefore, the data we collected becomes the data for the original anagram. easy_orig = easy normal_orig = normal hard_orig = hard num_letters = 0 easy = None normal = None hard = None else: # If we DO have more data, consider this translated and grab the # info about the untranslated anagram. This data is not used by the game, # only the translators. letters_orig = dat_file.read('uintle:16') easy_orig = dat_file.read(letters_orig * 2 * 8) normal_orig = dat_file.read(letters_orig * 2 * 8) if type == ANAGRAM_TYPE.Full: hard_orig = dat_file.read(letters_orig * 2 * 8) ########################################################## ### Now convert all this into a useful format. ########################################################## base_dir = os.path.dirname(self.filename) self.type = type self.solution_index = solution_index <|code_end|> . Use current file imports: (from bitstring import BitStream, ConstBitStream from enum import Enum from script_file import ScriptFile import os import re import shutil import time import common) and context including class names, function names, or small code snippets from other files: # Path: script_file.py # class ScriptFile(): # def __init__(self, filename = None, scene_info = None): # self.translated = "" # self.translated_notags = "" # self.original = "" # self.original_notags = "" # self.comments = "" # # self.filename = None # # if not filename == None: # self.open(filename) # # if scene_info == None: # # Squeeze the file ID out of the filename. # scene_info = SceneInfo(file_id = int(os.path.splitext(os.path.basename(filename))[0])) # # self.scene_info = scene_info # # def open(self, filename): # # if not filename or not os.path.isfile(filename): # return # # text = load_text(filename) # # self.from_data(text) # # self.filename = filename # # def from_data(self, data): # # self.filename = None # self.translated = "" # self.translated_notags = "" # self.original = "" # self.original_notags = "" # self.comments = "" # # # Sanitize our line-breaks. The game handles \r\n in some instances, # # but not all. It always handles \n properly. # text = LINE_BREAKS.sub("\n", data) # # match = TEXT_PARSER.search(text) # # if match: # # Remove any trailing linebreaks, because # first_part = match.group(1) # second_part = match.group(2) # third_part = match.group(4) # # if not second_part: # self.original = first_part # else: # self.translated = first_part # self.original = second_part # # if third_part: # self.comments = third_part # # self.original_notags = TAG_KILLER.sub("", self.original) # self.translated_notags = TAG_KILLER.sub("", self.translated) # # ############################################################################## # ### @fn pack() # ### @desc Converts all the data into the script file format. # ### @param for_game -- Whether to include the original, untranslated data. # ### True = exclude untranslated, since we don't need it. # ############################################################################## # def pack(self, for_game = False): # # if self.translated == "": # output = u"\ufeff" + self.original + u"\u0000" # # if self.comments != "" and not for_game: # output += "\n[" + self.comments + "]" # else: # output = u"\ufeff" + self.translated + u"\u0000" # # if not for_game: # output += "\n" + self.original # if self.comments != "": # # We want a newline, but not a thousand. # if not self.original[-1] == '\n': # output += "\n" # # output += "[" + self.comments + "]" # # # Sanitize our line breaks, just in case. # output = LINE_BREAKS.sub("\n", output) # # return output # # def save(self, filename = None): # # if filename == None: # if self.filename == None: # return # else: # filename = self.filename # # output = self.pack(for_game = False) # # save_text(output, filename) . Output only the next line.
self.solution = ScriptFile(os.path.join(base_dir, ANAGRAM_DIR, "%04d.txt" % self.solution_index))
Given the code snippet: <|code_start|>################################################################################ ### Copyright © 2012-2013 BlackDragonHunt ### ### This file is part of the Super Duper Script Editor. ### ### The Super Duper Script Editor is free software: you can redistribute it ### and/or modify it under the terms of the GNU General Public License as ### published by the Free Software Foundation, either version 3 of the License, ### or (at your option) any later version. ### ### The Super Duper Script Editor 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 the Super Duper Script Editor. ### If not, see <http://www.gnu.org/licenses/>. ################################################################################ class ReferenceEdit(QtGui.QTextEdit): ### SIGNALS ### refs_edited = pyqtSignal() def __init__(self, parent): super(ReferenceEdit, self).__init__(parent) self.setAcceptRichText(False) <|code_end|> , generate the next line using the imports in this file: from PyQt4 import QtGui, QtCore from PyQt4.QtCore import QRect, pyqtSignal from PyQt4.QtGui import QTextCursor from reference_highlighter import ReferenceHighlighter from make_unique import make_unique import copy import terminology import time and context (functions, classes, or occasionally code) from other files: # Path: reference_highlighter.py # class ReferenceHighlighter(QtGui.QSyntaxHighlighter): # ### SIGNALS ### # refs_edited = pyqtSignal() # # def __init__(self, parent = None): # super(ReferenceHighlighter, self).__init__(parent) # # self.format = QTextCharFormat() # self.format.setForeground(QColor(0, 0, 255)) # # self.references = [] # # def highlightBlock(self, text): # # # If there is no previous state, then it's -1, which makes the first line 0. # # And every line after that increases as expected. # line = self.previousBlockState() + 1 # self.setCurrentBlockState(line) # # old_refs = copy.deepcopy(self.references) # # # Make sure we aren't too long. # if len(self.references) > self.parent().blockCount(): # self.references = self.references[:self.parent().blockCount()] # # # Make sure our matches list is long enough to hold this line. # for i in range(len(self.references), line + 1): # self.references.append([]) # # if len(self.references) == 0: # return # # self.references[line] = [] # # text = common.qt_to_unicode(text).lower() # # matches = RE_REFERENCE.finditer(text) # # for match in matches: # self.setFormat(match.start(), match.end() - match.start(), self.format) # self.references[line].append((match.group(1), match.start() + 1)) # # if not old_refs == self.references: # self.refs_edited.emit() . Output only the next line.
self.highlighter = ReferenceHighlighter(self.document())
Next line prediction: <|code_start|>################################################################################ ### Copyright © 2012-2013 BlackDragonHunt ### ### This file is part of the Super Duper Script Editor. ### ### The Super Duper Script Editor is free software: you can redistribute it ### and/or modify it under the terms of the GNU General Public License as ### published by the Free Software Foundation, either version 3 of the License, ### or (at your option) any later version. ### ### The Super Duper Script Editor 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 the Super Duper Script Editor. ### If not, see <http://www.gnu.org/licenses/>. ################################################################################ def get_map_name(map_id, umdimage = common.editor_config.umdimage_dir): dir = os.path.join(umdimage, "18_mapname.pak") filename = os.path.join(dir, "%04d.txt" % map_id) if not os.path.isfile(filename): return None <|code_end|> . Use current file imports: (import os, codecs import common from list_files import list_all_files from script_file import ScriptFile) and context including class names, function names, or small code snippets from other files: # Path: script_file.py # class ScriptFile(): # def __init__(self, filename = None, scene_info = None): # self.translated = "" # self.translated_notags = "" # self.original = "" # self.original_notags = "" # self.comments = "" # # self.filename = None # # if not filename == None: # self.open(filename) # # if scene_info == None: # # Squeeze the file ID out of the filename. # scene_info = SceneInfo(file_id = int(os.path.splitext(os.path.basename(filename))[0])) # # self.scene_info = scene_info # # def open(self, filename): # # if not filename or not os.path.isfile(filename): # return # # text = load_text(filename) # # self.from_data(text) # # self.filename = filename # # def from_data(self, data): # # self.filename = None # self.translated = "" # self.translated_notags = "" # self.original = "" # self.original_notags = "" # self.comments = "" # # # Sanitize our line-breaks. The game handles \r\n in some instances, # # but not all. It always handles \n properly. # text = LINE_BREAKS.sub("\n", data) # # match = TEXT_PARSER.search(text) # # if match: # # Remove any trailing linebreaks, because # first_part = match.group(1) # second_part = match.group(2) # third_part = match.group(4) # # if not second_part: # self.original = first_part # else: # self.translated = first_part # self.original = second_part # # if third_part: # self.comments = third_part # # self.original_notags = TAG_KILLER.sub("", self.original) # self.translated_notags = TAG_KILLER.sub("", self.translated) # # ############################################################################## # ### @fn pack() # ### @desc Converts all the data into the script file format. # ### @param for_game -- Whether to include the original, untranslated data. # ### True = exclude untranslated, since we don't need it. # ############################################################################## # def pack(self, for_game = False): # # if self.translated == "": # output = u"\ufeff" + self.original + u"\u0000" # # if self.comments != "" and not for_game: # output += "\n[" + self.comments + "]" # else: # output = u"\ufeff" + self.translated + u"\u0000" # # if not for_game: # output += "\n" + self.original # if self.comments != "": # # We want a newline, but not a thousand. # if not self.original[-1] == '\n': # output += "\n" # # output += "[" + self.comments + "]" # # # Sanitize our line breaks, just in case. # output = LINE_BREAKS.sub("\n", output) # # return output # # def save(self, filename = None): # # if filename == None: # if self.filename == None: # return # else: # filename = self.filename # # output = self.pack(for_game = False) # # save_text(output, filename) . Output only the next line.
map_file = ScriptFile(filename)
Here is a snippet: <|code_start|> logger = logging.getLogger(__name__) class TestMetadataRegistryDefaults: @pytest.fixture(scope="session") def dataplex_expected_defaults(self): expected_defaults = { "DATAPLEX": { "projects": "<my-gcp-project-id>", "locations": "<my-gcp-dataplex-region-id>", "lakes": "<my-gcp-dataplex-lake-id>", "zones": "<my-gcp-dataplex-zone-id>", } } return expected_defaults def test_load_metadata_registry_default_configs(self, source_configs_path, dataplex_expected_defaults): metadata_defaults = load_metadata_registry_default_configs(configs_path=source_configs_path) assert 'DATAPLEX' in metadata_defaults.default_configs assert metadata_defaults.get_dataplex_registry_defaults('projects') == "<my-gcp-project-id>" assert metadata_defaults.get_dataplex_registry_defaults('locations') == "<my-gcp-dataplex-region-id>" assert metadata_defaults.get_dataplex_registry_defaults('lakes') == "<my-gcp-dataplex-lake-id>" assert metadata_defaults.get_dataplex_registry_defaults('zones') == "<my-gcp-dataplex-zone-id>" assert metadata_defaults.get_dataplex_registry_defaults() == dataplex_expected_defaults['DATAPLEX'] def test_from_dict_metadata_registry_default_configs(self, dataplex_expected_defaults): <|code_end|> . Write the next line using the current file imports: from pathlib import Path from clouddq.classes.metadata_registry_defaults import MetadataRegistryDefaults from clouddq.lib import load_metadata_registry_default_configs import logging import os import shutil import pytest import yaml and context from other files: # Path: clouddq/classes/metadata_registry_defaults.py # class MetadataRegistryDefaults: # """ """ # # default_configs: dict # # @classmethod # def from_dict( # cls: MetadataRegistryDefaults, kwargs: dict # ) -> MetadataRegistryDefaults: # default_configs = {} # logger.debug(f"Parsing input 'metadata_registry_defaults':\n {pformat(kwargs)}") # for registry_scheme, registry_defaults in kwargs.items(): # scheme = EntityUriScheme.from_scheme(registry_scheme) # default_configs[scheme.value] = {} # expected_uri_fields = None # if scheme == EntityUriScheme.DATAPLEX: # expected_uri_fields = DATAPLEX_URI_FIELDS # else: # raise NotImplementedError( # f"'metadata_registry_default' not implemented for registry '{scheme}' " # ) # for key, value in registry_defaults.items(): # if key not in expected_uri_fields: # raise ValueError( # f"'metadata_registry_default' for scheme '{scheme}' " # f"contains unexpected field '{key}'." # ) # default_configs[scheme][key] = value # return MetadataRegistryDefaults(default_configs=default_configs) # # def to_dict(self: MetadataRegistryDefaults) -> dict: # return self.default_configs # # def get_dataplex_registry_defaults(self, key: str | None = None) -> str | None: # if self.default_configs.get("DATAPLEX", None): # if key: # return self.default_configs["DATAPLEX"].get(key, None) # else: # return self.default_configs["DATAPLEX"] # else: # return None # # Path: clouddq/lib.py # def load_metadata_registry_default_configs( # configs_path: Path, # ) -> MetadataRegistryDefaults: # configs = load_configs(configs_path, DqConfigType.METADATA_REGISTRY_DEFAULTS) # try: # return MetadataRegistryDefaults.from_dict(configs) # except ValueError as e: # logger.warning(e) # return MetadataRegistryDefaults.from_dict({}) , which may include functions, classes, or code. Output only the next line.
metadata_registry_defaults = MetadataRegistryDefaults.from_dict(dataplex_expected_defaults)
Here is a snippet: <|code_start|># # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. logger = logging.getLogger(__name__) class TestMetadataRegistryDefaults: @pytest.fixture(scope="session") def dataplex_expected_defaults(self): expected_defaults = { "DATAPLEX": { "projects": "<my-gcp-project-id>", "locations": "<my-gcp-dataplex-region-id>", "lakes": "<my-gcp-dataplex-lake-id>", "zones": "<my-gcp-dataplex-zone-id>", } } return expected_defaults def test_load_metadata_registry_default_configs(self, source_configs_path, dataplex_expected_defaults): <|code_end|> . Write the next line using the current file imports: from pathlib import Path from clouddq.classes.metadata_registry_defaults import MetadataRegistryDefaults from clouddq.lib import load_metadata_registry_default_configs import logging import os import shutil import pytest import yaml and context from other files: # Path: clouddq/classes/metadata_registry_defaults.py # class MetadataRegistryDefaults: # """ """ # # default_configs: dict # # @classmethod # def from_dict( # cls: MetadataRegistryDefaults, kwargs: dict # ) -> MetadataRegistryDefaults: # default_configs = {} # logger.debug(f"Parsing input 'metadata_registry_defaults':\n {pformat(kwargs)}") # for registry_scheme, registry_defaults in kwargs.items(): # scheme = EntityUriScheme.from_scheme(registry_scheme) # default_configs[scheme.value] = {} # expected_uri_fields = None # if scheme == EntityUriScheme.DATAPLEX: # expected_uri_fields = DATAPLEX_URI_FIELDS # else: # raise NotImplementedError( # f"'metadata_registry_default' not implemented for registry '{scheme}' " # ) # for key, value in registry_defaults.items(): # if key not in expected_uri_fields: # raise ValueError( # f"'metadata_registry_default' for scheme '{scheme}' " # f"contains unexpected field '{key}'." # ) # default_configs[scheme][key] = value # return MetadataRegistryDefaults(default_configs=default_configs) # # def to_dict(self: MetadataRegistryDefaults) -> dict: # return self.default_configs # # def get_dataplex_registry_defaults(self, key: str | None = None) -> str | None: # if self.default_configs.get("DATAPLEX", None): # if key: # return self.default_configs["DATAPLEX"].get(key, None) # else: # return self.default_configs["DATAPLEX"] # else: # return None # # Path: clouddq/lib.py # def load_metadata_registry_default_configs( # configs_path: Path, # ) -> MetadataRegistryDefaults: # configs = load_configs(configs_path, DqConfigType.METADATA_REGISTRY_DEFAULTS) # try: # return MetadataRegistryDefaults.from_dict(configs) # except ValueError as e: # logger.warning(e) # return MetadataRegistryDefaults.from_dict({}) , which may include functions, classes, or code. Output only the next line.
metadata_defaults = load_metadata_registry_default_configs(configs_path=source_configs_path)
Based on the snippet: <|code_start|> output["description"] = self.column_description return dict({f"{self.column_id}": output}) def dict_values(self: DqEntityColumn) -> dict: """ Args: self: DqEntityColumn: Returns: """ return dict(self.to_dict().get(self.column_id)) @unique class DatabaseType(str, Enum): """ """ BIGQUERY = "BIGQUERY" DATAPLEX = "DATAPLEX" def get_column_type( self: DqEntityColumn, column_type: DatabaseColumnType | str ) -> str: if type(column_type) != DatabaseColumnType: column_type = DatabaseColumnType(column_type) if self == DatabaseType.BIGQUERY: database_column_type = BIGQUERY_COLUMN_TYPES_MAPPING.get(column_type, None) <|code_end|> , predict the immediate next line with the help of imports: from dataclasses import dataclass from enum import Enum from enum import unique from clouddq.utils import assert_not_none_or_empty from clouddq.utils import get_from_dict_and_assert and context (classes, functions, sometimes code) from other files: # Path: clouddq/utils.py # def assert_not_none_or_empty(value: typing.Any, error_msg: str) -> None: # """ # # Args: # value: typing.Any: # error_msg: str: # # Returns: # # """ # if not value: # raise ValueError(error_msg) # # Path: clouddq/utils.py # def get_from_dict_and_assert( # config_id: str, # kwargs: typing.Dict, # key: str, # assertion: typing.Callable[[typing.Any], bool] = None, # error_msg: str = None, # ) -> typing.Any: # value = kwargs.get(key, None) # assert_not_none_or_empty( # value, f"Config ID: {config_id} must define non-empty value: '{key}'." # ) # if assertion and not assertion(value): # raise ValueError( # f"Assertion failed on value {value}.\n" # f"Config ID: {config_id}, kwargs: {kwargs}.\n" # f"Error: {error_msg}" # ) # return value . Output only the next line.
assert_not_none_or_empty(
Continue the code snippet: <|code_start|> column_id: str column_name: str column_type: str column_description: str | None entity_source_database: str def get_column_type_value(self: DqEntityColumn) -> str: return DatabaseType(self.entity_source_database).get_column_type( self.column_type ) @classmethod def from_dict( cls: DqEntityColumn, entity_column_id: str, kwargs: dict, entity_source_database: str, ) -> DqEntityColumn: """ Args: cls: DqEntityColumn: entity_column_id: str: kwargs: typing.Dict: entity_source_database: str Returns: """ source_database: DatabaseType = DatabaseType(entity_source_database) <|code_end|> . Use current file imports: from dataclasses import dataclass from enum import Enum from enum import unique from clouddq.utils import assert_not_none_or_empty from clouddq.utils import get_from_dict_and_assert and context (classes, functions, or code) from other files: # Path: clouddq/utils.py # def assert_not_none_or_empty(value: typing.Any, error_msg: str) -> None: # """ # # Args: # value: typing.Any: # error_msg: str: # # Returns: # # """ # if not value: # raise ValueError(error_msg) # # Path: clouddq/utils.py # def get_from_dict_and_assert( # config_id: str, # kwargs: typing.Dict, # key: str, # assertion: typing.Callable[[typing.Any], bool] = None, # error_msg: str = None, # ) -> typing.Any: # value = kwargs.get(key, None) # assert_not_none_or_empty( # value, f"Config ID: {config_id} must define non-empty value: '{key}'." # ) # if assertion and not assertion(value): # raise ValueError( # f"Assertion failed on value {value}.\n" # f"Config ID: {config_id}, kwargs: {kwargs}.\n" # f"Error: {error_msg}" # ) # return value . Output only the next line.
column_name = get_from_dict_and_assert(
Based on the snippet: <|code_start|> @dataclass class DataplexEntityPartitionSchemaField: """ """ name: str type: str def to_dict(self: DataplexEntityPartitionSchemaField) -> dict: """ Args: self: DataplexEntityPartitionSchemaField: Returns: """ output = { "name": self.name, "type": self.type, } return dict(output) @classmethod def from_dict( cls: DataplexEntityPartitionSchemaField, entity_id: str, kwargs: dict ) -> DataplexEntityPartitionSchemaField: name = kwargs.get("name") <|code_end|> , predict the immediate next line with the help of imports: from dataclasses import dataclass from clouddq.utils import assert_not_none_or_empty and context (classes, functions, sometimes code) from other files: # Path: clouddq/utils.py # def assert_not_none_or_empty(value: typing.Any, error_msg: str) -> None: # """ # # Args: # value: typing.Any: # error_msg: str: # # Returns: # # """ # if not value: # raise ValueError(error_msg) . Output only the next line.
assert_not_none_or_empty(
Given the code snippet: <|code_start|># Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """todo: add classes docstring.""" from __future__ import annotations @dataclass class DqRule: """ """ rule_id: str <|code_end|> , generate the next line using the imports in this file: from dataclasses import dataclass from clouddq.classes.rule_type import RuleType and context (functions, classes, or occasionally code) from other files: # Path: clouddq/classes/rule_type.py # class RuleType(str, Enum): # """ """ # # CUSTOM_SQL_STATEMENT = "CUSTOM_SQL_STATEMENT" # CUSTOM_SQL_EXPR = "CUSTOM_SQL_EXPR" # NOT_NULL = "NOT_NULL" # REGEX = "REGEX" # NOT_BLANK = "NOT_BLANK" # # def to_sql(self: RuleType, params: dict | None) -> Template: # if self == RuleType.CUSTOM_SQL_EXPR: # return to_sql_custom_sql_expr(params) # elif self == RuleType.CUSTOM_SQL_STATEMENT: # return to_sql_custom_sql_statement(params) # elif self == RuleType.NOT_NULL: # return NOT_NULL_SQL # elif self == RuleType.REGEX: # return to_sql_regex(params) # elif self == RuleType.NOT_BLANK: # return NOT_BLANK_SQL # else: # raise NotImplementedError(f"Rule Type: {self} not implemented.") . Output only the next line.
rule_type: RuleType
Given the following code snippet before the placeholder: <|code_start|>class DataplexEntitySchemaField: """ """ name: str type: str mode: str def to_dict(self: DataplexEntitySchemaField) -> dict: """ Args: self: DataplexEntitySchemaField: Returns: """ output = { "name": self.name, "type": self.type, "mode": self.mode, } return dict(output) @classmethod def from_dict( cls: DataplexEntitySchemaField, entity_id: str, kwargs: dict ) -> DataplexEntitySchemaField: name = kwargs.get("name") <|code_end|> , predict the next line using imports from the current file: from dataclasses import dataclass from clouddq.utils import assert_not_none_or_empty and context including class names, function names, and sometimes code from other files: # Path: clouddq/utils.py # def assert_not_none_or_empty(value: typing.Any, error_msg: str) -> None: # """ # # Args: # value: typing.Any: # error_msg: str: # # Returns: # # """ # if not value: # raise ValueError(error_msg) . Output only the next line.
assert_not_none_or_empty(
Given snippet: <|code_start|># Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. logger = logging.getLogger(__name__) class TestUtils: def test_get_keys_from_dict_and_assert_oneof(self): kwargs = {'a': 1, 'b': 2, 'c': 3} keys = ['a'] <|code_end|> , continue by predicting the next line. Consider current file imports: import logging import pytest from clouddq import utils and context: # Path: clouddq/utils.py # MAXIMUM_EXPONENTIAL_BACKOFF_SECONDS = 32 # def load_yaml(file_path: Path, key: str = None) -> typing.Any: # def unnest_object_to_list(object: dict) -> list: # def convert_json_value_to_dict(object: dict, key: str): # def get_templates_path(file_path: Path) -> Path: # def get_template_file(file_path: Path) -> str: # def write_templated_file_to_path(path: Path, lookup_table: typing.Dict) -> None: # def working_directory(path): # def assert_not_none_or_empty(value: typing.Any, error_msg: str) -> None: # def get_from_dict_and_assert( # config_id: str, # kwargs: typing.Dict, # key: str, # assertion: typing.Callable[[typing.Any], bool] = None, # error_msg: str = None, # ) -> typing.Any: # def get_keys_from_dict_and_assert_oneof( # config_id: str, # kwargs: typing.Dict, # keys: typing.List[str], # assertion: typing.Callable[[typing.Any], bool] = None, # error_msg: str = None, # ) -> typing.Any: # def load_jinja_template(template_path: Path) -> Template: # def get_format_string_arguments(format_string: str) -> typing.List[str]: # def strip_margin(text: str) -> str: # def sha256_digest(text: str) -> str: # def exponential_backoff( # retry_iteration: int, max_retry_duration: int = MAXIMUM_EXPONENTIAL_BACKOFF_SECONDS # ): # def make_archive(source, destination, keep_top_level_folder=True): # def update_dict(dict1: dict, dict2: dict) -> dict: # class DebugChainableUndefined(ChainableUndefined, DebugUndefined): which might include code, classes, or functions. Output only the next line.
value = utils.get_keys_from_dict_and_assert_oneof('exactly_one', kwargs=kwargs, keys=keys)
Given the following code snippet before the placeholder: <|code_start|># you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """todo: add classes docstring.""" from __future__ import annotations @dataclass class DataplexEntity: """ """ name: str createTime: str updateTime: str id: str type: str asset: str dataPath: str system: str format: dict <|code_end|> , predict the next line using imports from the current file: from dataclasses import dataclass from clouddq.classes.dataplex_entity_schema import DataplexEntitySchema from clouddq.utils import assert_not_none_or_empty and context including class names, function names, and sometimes code from other files: # Path: clouddq/classes/dataplex_entity_schema.py # class DataplexEntitySchema: # """ """ # # fields: list[DataplexEntitySchemaField] # partitionFields: list[DataplexEntityPartitionSchemaField] # partitionStyle: str # # @classmethod # def from_dict( # cls: DataplexEntitySchema, entity_id: str, kwargs: dict # ) -> DataplexEntitySchema: # # fields: list[dict] = [] # fields_list = kwargs.get("fields") # if fields_list: # for obj in fields_list: # field = DataplexEntitySchemaField.from_dict( # entity_id=entity_id, kwargs=obj # ) # assert_not_none_or_empty( # value=field, # error_msg=f"Entity {entity_id}: must define non-empty value: 'fields'.", # ) # fields.append(field.to_dict()) # else: # fields = None # partition_fields: list[dict] = [] # if kwargs.get("partitionFields"): # partition_fields_list = kwargs.get("partitionFields") # for obj in partition_fields_list: # partition_field = DataplexEntityPartitionSchemaField.from_dict( # entity_id=entity_id, kwargs=obj # ) # assert_not_none_or_empty( # value=partition_field, # error_msg=f"Entity {entity_id}: must define non-empty value: " # f"'partitionFields'.", # ) # partition_fields.append(partition_field.to_dict()) # fields.append(partition_field.to_fields_dict()) # else: # partition_fields = None # # if kwargs.get("partitionStyle"): # partition_style = kwargs.get("partitionStyle", None) # assert_not_none_or_empty( # value=partition_style, # error_msg=f"Entity {entity_id}: must define non-empty value: 'partition_style'.", # ) # else: # partition_style = None # # return DataplexEntitySchema( # fields=fields, # partitionFields=partition_fields, # partitionStyle=partition_style, # ) # # def to_dict(self: DataplexEntitySchema) -> dict: # """ # Args: # self: DataplexEntitySchema: # # Returns: # # """ # # output = { # "fields": self.fields, # "partitionFields": self.partitionFields, # "partitionStyle": self.partitionStyle, # } # # return dict(output) # # Path: clouddq/utils.py # def assert_not_none_or_empty(value: typing.Any, error_msg: str) -> None: # """ # # Args: # value: typing.Any: # error_msg: str: # # Returns: # # """ # if not value: # raise ValueError(error_msg) . Output only the next line.
schema: DataplexEntitySchema
Here is a snippet: <|code_start|> return self.name.split("/")[3] @property def lake(self): return self.name.split("/")[5] @property def zone(self): return self.name.split("/")[7] def get_db_primary_key(self): return ( f"projects/{self.project_id}/locations/{self.location}/" + f"lakes/{self.lake}/zones/{self.zone}/entities/{self.id}" # noqa: W503 ) @classmethod def from_dict(cls: DataplexEntity, entity_id: str, kwargs: dict) -> DataplexEntity: """ Args: cls: DataplexEntity: kwargs: typing.Dict: Returns: """ try: entity_name = kwargs.get("name", None) <|code_end|> . Write the next line using the current file imports: from dataclasses import dataclass from clouddq.classes.dataplex_entity_schema import DataplexEntitySchema from clouddq.utils import assert_not_none_or_empty and context from other files: # Path: clouddq/classes/dataplex_entity_schema.py # class DataplexEntitySchema: # """ """ # # fields: list[DataplexEntitySchemaField] # partitionFields: list[DataplexEntityPartitionSchemaField] # partitionStyle: str # # @classmethod # def from_dict( # cls: DataplexEntitySchema, entity_id: str, kwargs: dict # ) -> DataplexEntitySchema: # # fields: list[dict] = [] # fields_list = kwargs.get("fields") # if fields_list: # for obj in fields_list: # field = DataplexEntitySchemaField.from_dict( # entity_id=entity_id, kwargs=obj # ) # assert_not_none_or_empty( # value=field, # error_msg=f"Entity {entity_id}: must define non-empty value: 'fields'.", # ) # fields.append(field.to_dict()) # else: # fields = None # partition_fields: list[dict] = [] # if kwargs.get("partitionFields"): # partition_fields_list = kwargs.get("partitionFields") # for obj in partition_fields_list: # partition_field = DataplexEntityPartitionSchemaField.from_dict( # entity_id=entity_id, kwargs=obj # ) # assert_not_none_or_empty( # value=partition_field, # error_msg=f"Entity {entity_id}: must define non-empty value: " # f"'partitionFields'.", # ) # partition_fields.append(partition_field.to_dict()) # fields.append(partition_field.to_fields_dict()) # else: # partition_fields = None # # if kwargs.get("partitionStyle"): # partition_style = kwargs.get("partitionStyle", None) # assert_not_none_or_empty( # value=partition_style, # error_msg=f"Entity {entity_id}: must define non-empty value: 'partition_style'.", # ) # else: # partition_style = None # # return DataplexEntitySchema( # fields=fields, # partitionFields=partition_fields, # partitionStyle=partition_style, # ) # # def to_dict(self: DataplexEntitySchema) -> dict: # """ # Args: # self: DataplexEntitySchema: # # Returns: # # """ # # output = { # "fields": self.fields, # "partitionFields": self.partitionFields, # "partitionStyle": self.partitionStyle, # } # # return dict(output) # # Path: clouddq/utils.py # def assert_not_none_or_empty(value: typing.Any, error_msg: str) -> None: # """ # # Args: # value: typing.Any: # error_msg: str: # # Returns: # # """ # if not value: # raise ValueError(error_msg) , which may include functions, classes, or code. Output only the next line.
assert_not_none_or_empty(
Given snippet: <|code_start|># http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. logger = logging.getLogger(__name__) class TestLib: def test_load_configs_identical(self, temp_configs_dir, tmp_path): # Load a config directory containing two copies of the same config try: temp_dir = Path(tmp_path).joinpath("clouddq_test_lib", "test_lib_1") config_path = Path(temp_configs_dir) temp_dir.mkdir(parents=True) assert os.path.isfile(config_path / 'entities' / 'test-data.yml') shutil.copy(config_path / 'entities' / 'test-data.yml', temp_dir / 'test-data1.yml') shutil.copy(config_path / 'entities' / 'test-data.yml', temp_dir / 'test-data2.yml') <|code_end|> , continue by predicting the next line. Consider current file imports: from pathlib import Path from clouddq import lib from clouddq.classes.dq_config_type import DqConfigType import logging import os import shutil import pytest import yaml and context: # Path: clouddq/lib.py # def load_configs(configs_path: Path, configs_type: DqConfigType) -> typing.Dict: # def load_rule_bindings_config(configs_path: Path) -> typing.Dict: # def load_rule_dimensions_config(configs_path: Path) -> list: # def load_entities_config(configs_path: Path) -> typing.Dict: # def load_rules_config(configs_path: Path) -> typing.Dict: # def load_row_filters_config(configs_path: Path) -> typing.Dict: # def load_metadata_registry_default_configs( # configs_path: Path, # ) -> MetadataRegistryDefaults: # def create_rule_binding_view_model( # rule_binding_id: str, # rule_binding_configs: typing.Dict, # dq_summary_table_name: str, # environment: str, # configs_cache: DqConfigsCache, # dq_summary_table_exists: bool = False, # metadata: typing.Optional[typing.Dict] = None, # debug: bool = False, # progress_watermark: bool = True, # default_configs: typing.Optional[typing.Dict] = None, # ) -> str: # def create_entity_summary_model( # entity_table_id: str, # entity_target_rule_binding_configs: dict, # gcp_project_id: str, # gcp_bq_dataset_id: str, # debug: bool = False, # ) -> str: # def write_sql_string_as_dbt_model( # model_id: str, sql_string: str, dbt_model_path: Path # ) -> None: # def prepare_configs_from_rule_binding_id( # rule_binding_id: str, # rule_binding_configs: typing.Dict, # dq_summary_table_name: str, # environment: typing.Optional[str], # configs_cache: DqConfigsCache, # dq_summary_table_exists: bool = False, # metadata: typing.Optional[typing.Dict] = None, # progress_watermark: bool = True, # default_configs: typing.Optional[typing.Dict] = None, # ) -> typing.Dict: # def prepare_configs_cache(configs_path: Path) -> DqConfigsCache: # # Path: clouddq/classes/dq_config_type.py # class DqConfigType(str, Enum): # """ """ # # RULES = "rules" # RULE_BINDINGS = "rule_bindings" # RULE_DIMENSIONS = "rule_dimensions" # ROW_FILTERS = "row_filters" # ENTITIES = "entities" # METADATA_REGISTRY_DEFAULTS = "metadata_registry_defaults" # # def is_required( # self: DqConfigType, # ) -> bool: # if self == DqConfigType.RULES: # return True # elif self == DqConfigType.RULE_BINDINGS: # return True # elif self == DqConfigType.RULE_DIMENSIONS: # return False # elif self == DqConfigType.ROW_FILTERS: # return True # elif self == DqConfigType.ENTITIES: # return False # elif self == DqConfigType.METADATA_REGISTRY_DEFAULTS: # return False # else: # raise NotImplementedError(f"DQ Config Type: {self} not implemented.") # # def to_class( # self: DqConfigType, # ) -> type[DqRule] | type[DqRuleBinding] | type[DqRuleDimensions] | type[ # DqRowFilter # ] | type[DqEntity] | type[MetadataRegistryDefaults]: # if self == DqConfigType.RULES: # return DqRule # elif self == DqConfigType.RULE_BINDINGS: # return DqRuleBinding # elif self == DqConfigType.RULE_DIMENSIONS: # return DqRuleDimensions # elif self == DqConfigType.ROW_FILTERS: # return DqRowFilter # elif self == DqConfigType.ENTITIES: # return DqEntity # elif self == DqConfigType.METADATA_REGISTRY_DEFAULTS: # return MetadataRegistryDefaults # else: # raise NotImplementedError(f"DQ Config Type: {self} not implemented.") which might include code, classes, or functions. Output only the next line.
loaded_config = lib.load_configs(temp_dir, DqConfigType.ENTITIES)
Predict the next line for this snippet: <|code_start|># http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. logger = logging.getLogger(__name__) class TestLib: def test_load_configs_identical(self, temp_configs_dir, tmp_path): # Load a config directory containing two copies of the same config try: temp_dir = Path(tmp_path).joinpath("clouddq_test_lib", "test_lib_1") config_path = Path(temp_configs_dir) temp_dir.mkdir(parents=True) assert os.path.isfile(config_path / 'entities' / 'test-data.yml') shutil.copy(config_path / 'entities' / 'test-data.yml', temp_dir / 'test-data1.yml') shutil.copy(config_path / 'entities' / 'test-data.yml', temp_dir / 'test-data2.yml') <|code_end|> with the help of current file imports: from pathlib import Path from clouddq import lib from clouddq.classes.dq_config_type import DqConfigType import logging import os import shutil import pytest import yaml and context from other files: # Path: clouddq/lib.py # def load_configs(configs_path: Path, configs_type: DqConfigType) -> typing.Dict: # def load_rule_bindings_config(configs_path: Path) -> typing.Dict: # def load_rule_dimensions_config(configs_path: Path) -> list: # def load_entities_config(configs_path: Path) -> typing.Dict: # def load_rules_config(configs_path: Path) -> typing.Dict: # def load_row_filters_config(configs_path: Path) -> typing.Dict: # def load_metadata_registry_default_configs( # configs_path: Path, # ) -> MetadataRegistryDefaults: # def create_rule_binding_view_model( # rule_binding_id: str, # rule_binding_configs: typing.Dict, # dq_summary_table_name: str, # environment: str, # configs_cache: DqConfigsCache, # dq_summary_table_exists: bool = False, # metadata: typing.Optional[typing.Dict] = None, # debug: bool = False, # progress_watermark: bool = True, # default_configs: typing.Optional[typing.Dict] = None, # ) -> str: # def create_entity_summary_model( # entity_table_id: str, # entity_target_rule_binding_configs: dict, # gcp_project_id: str, # gcp_bq_dataset_id: str, # debug: bool = False, # ) -> str: # def write_sql_string_as_dbt_model( # model_id: str, sql_string: str, dbt_model_path: Path # ) -> None: # def prepare_configs_from_rule_binding_id( # rule_binding_id: str, # rule_binding_configs: typing.Dict, # dq_summary_table_name: str, # environment: typing.Optional[str], # configs_cache: DqConfigsCache, # dq_summary_table_exists: bool = False, # metadata: typing.Optional[typing.Dict] = None, # progress_watermark: bool = True, # default_configs: typing.Optional[typing.Dict] = None, # ) -> typing.Dict: # def prepare_configs_cache(configs_path: Path) -> DqConfigsCache: # # Path: clouddq/classes/dq_config_type.py # class DqConfigType(str, Enum): # """ """ # # RULES = "rules" # RULE_BINDINGS = "rule_bindings" # RULE_DIMENSIONS = "rule_dimensions" # ROW_FILTERS = "row_filters" # ENTITIES = "entities" # METADATA_REGISTRY_DEFAULTS = "metadata_registry_defaults" # # def is_required( # self: DqConfigType, # ) -> bool: # if self == DqConfigType.RULES: # return True # elif self == DqConfigType.RULE_BINDINGS: # return True # elif self == DqConfigType.RULE_DIMENSIONS: # return False # elif self == DqConfigType.ROW_FILTERS: # return True # elif self == DqConfigType.ENTITIES: # return False # elif self == DqConfigType.METADATA_REGISTRY_DEFAULTS: # return False # else: # raise NotImplementedError(f"DQ Config Type: {self} not implemented.") # # def to_class( # self: DqConfigType, # ) -> type[DqRule] | type[DqRuleBinding] | type[DqRuleDimensions] | type[ # DqRowFilter # ] | type[DqEntity] | type[MetadataRegistryDefaults]: # if self == DqConfigType.RULES: # return DqRule # elif self == DqConfigType.RULE_BINDINGS: # return DqRuleBinding # elif self == DqConfigType.RULE_DIMENSIONS: # return DqRuleDimensions # elif self == DqConfigType.ROW_FILTERS: # return DqRowFilter # elif self == DqConfigType.ENTITIES: # return DqEntity # elif self == DqConfigType.METADATA_REGISTRY_DEFAULTS: # return MetadataRegistryDefaults # else: # raise NotImplementedError(f"DQ Config Type: {self} not implemented.") , which may contain function names, class names, or code. Output only the next line.
loaded_config = lib.load_configs(temp_dir, DqConfigType.ENTITIES)
Based on the snippet: <|code_start|> DATAPLEX_URI_FIELDS = ["projects", "locations", "lakes", "zones", "entities"] BIGQUERY_URI_FIELDS = ["projects", "datasets", "tables"] SAMPLE_DEFAULT_REGISTRIES_YAML = """ metadata_registry_defaults: dataplex: projects: <my-gcp-project-id> locations: <my-gcp-dataplex-region-id> lakes: <my-gcp-dataplex-lake-id> zones: <my-gcp-dataplex-zone-id> """ logger = logging.getLogger(__name__) @dataclass class MetadataRegistryDefaults: """ """ default_configs: dict @classmethod def from_dict( cls: MetadataRegistryDefaults, kwargs: dict ) -> MetadataRegistryDefaults: default_configs = {} logger.debug(f"Parsing input 'metadata_registry_defaults':\n {pformat(kwargs)}") for registry_scheme, registry_defaults in kwargs.items(): <|code_end|> , predict the immediate next line with the help of imports: from dataclasses import dataclass from pprint import pformat from clouddq.classes.entity_uri_schemes import EntityUriScheme import logging and context (classes, functions, sometimes code) from other files: # Path: clouddq/classes/entity_uri_schemes.py # class EntityUriScheme(str, Enum): # """ """ # # DATAPLEX = "DATAPLEX" # BIGQUERY = "BIGQUERY" # # @classmethod # def from_scheme(cls, scheme: str): # # try: # return cls(scheme.upper()) # except ValueError: # raise NotImplementedError(f"{scheme} scheme is not implemented.") . Output only the next line.
scheme = EntityUriScheme.from_scheme(registry_scheme)
Next line prediction: <|code_start|> logger.info("\nExecuting dbt command:\n %s", debug_commands) dbt(debug_commands) except SystemExit: pass else: if not dry_run: logger.info("\nExecuting dbt command:\n %s", command) dbt(command) else: logger.info("\ndbt command generated as part of dry-run:\n %s", command) except SystemExit as sysexit: if sysexit.code == 0: logger.debug("dbt run completed successfully.") else: raise RuntimeError( "dbt run failed with Runtime Error. " "See Runtime Error description in dbt run logs for details. " ) except Exception as e: raise RuntimeError(f"dbt run failed with unknown error: '{e}'") def extract_dbt_env_var(text: str) -> str: var_env = re.search(ENV_VAR_PATTERN, text).group(1) var_env = [x.strip().strip("'\"") for x in var_env.split(",")] enrironment_variable = var_env.pop(0) default_value = None if var_env: default_value = var_env.pop() value = os.environ.get(enrironment_variable, default_value) <|code_end|> . Use current file imports: (from pathlib import Path from pprint import pformat from typing import Dict from typing import Optional from dbt.main import main as dbt from clouddq.utils import assert_not_none_or_empty from clouddq.utils import load_yaml from clouddq.utils import working_directory import json import logging import os import re) and context including class names, function names, or small code snippets from other files: # Path: clouddq/utils.py # def assert_not_none_or_empty(value: typing.Any, error_msg: str) -> None: # """ # # Args: # value: typing.Any: # error_msg: str: # # Returns: # # """ # if not value: # raise ValueError(error_msg) # # Path: clouddq/utils.py # def load_yaml(file_path: Path, key: str = None) -> typing.Any: # with file_path.open() as f: # yaml_configs = yaml.safe_load(f) # if not yaml_configs: # return dict() # output = yaml_configs.get(key, dict()) # if type(output) == dict: # return {key.upper(): value for key, value in output.items()} # elif type(output) == list: # return [item.upper() for item in output] # elif type(output) == str: # return output # else: # raise RuntimeError( # f"CloudDQ configs file `{file_path}` has empty config node type `{key}:`. " # "Please remove the node if it is not being used." # ) # # Path: clouddq/utils.py # @contextlib.contextmanager # def working_directory(path): # """Changes working directory and returns to previous on exit.""" # prev_cwd = Path.cwd() # os.chdir(path) # try: # yield # finally: # os.chdir(prev_cwd) . Output only the next line.
assert_not_none_or_empty(
Given snippet: <|code_start|> raise RuntimeError(f"dbt run failed with unknown error: '{e}'") def extract_dbt_env_var(text: str) -> str: var_env = re.search(ENV_VAR_PATTERN, text).group(1) var_env = [x.strip().strip("'\"") for x in var_env.split(",")] enrironment_variable = var_env.pop(0) default_value = None if var_env: default_value = var_env.pop() value = os.environ.get(enrironment_variable, default_value) assert_not_none_or_empty( value, f"Enviromment variable not found for dbt env_var variable: {text}" ) return value def get_bigquery_dq_summary_table_name( dbt_path: Path, dbt_profiles_dir: Path, environment_target: str, table_name: str = "dq_summary", ) -> str: # Get bigquery project and dataset for dq_summary table names dbt_project_path = dbt_path.joinpath("dbt_project.yml") if not dbt_project_path.is_file(): raise ValueError( "Not able to find 'dbt_project.yml' config file at " "input path {dbt_project_path}." ) <|code_end|> , continue by predicting the next line. Consider current file imports: from pathlib import Path from pprint import pformat from typing import Dict from typing import Optional from dbt.main import main as dbt from clouddq.utils import assert_not_none_or_empty from clouddq.utils import load_yaml from clouddq.utils import working_directory import json import logging import os import re and context: # Path: clouddq/utils.py # def assert_not_none_or_empty(value: typing.Any, error_msg: str) -> None: # """ # # Args: # value: typing.Any: # error_msg: str: # # Returns: # # """ # if not value: # raise ValueError(error_msg) # # Path: clouddq/utils.py # def load_yaml(file_path: Path, key: str = None) -> typing.Any: # with file_path.open() as f: # yaml_configs = yaml.safe_load(f) # if not yaml_configs: # return dict() # output = yaml_configs.get(key, dict()) # if type(output) == dict: # return {key.upper(): value for key, value in output.items()} # elif type(output) == list: # return [item.upper() for item in output] # elif type(output) == str: # return output # else: # raise RuntimeError( # f"CloudDQ configs file `{file_path}` has empty config node type `{key}:`. " # "Please remove the node if it is not being used." # ) # # Path: clouddq/utils.py # @contextlib.contextmanager # def working_directory(path): # """Changes working directory and returns to previous on exit.""" # prev_cwd = Path.cwd() # os.chdir(path) # try: # yield # finally: # os.chdir(prev_cwd) which might include code, classes, or functions. Output only the next line.
dbt_profiles_key = load_yaml(dbt_project_path, "profile")
Predict the next line for this snippet: <|code_start|> environment: str = "clouddq", debug: bool = False, dry_run: bool = False, ) -> None: """ Args: dbt_path: Path: Path of dbt project described in `dbt_project.yml` dbt_profile_dir: str: configs: typing.Dict: environment: str: debug: bool: (Default value = False) dry_run: bool: (Default value = False) Returns: """ if not configs: configs = {} command = [] command.extend(["run"]) command += [ "--profiles-dir", str(dbt_profile_dir), "--vars", json.dumps(configs), "--target", environment, ] try: <|code_end|> with the help of current file imports: from pathlib import Path from pprint import pformat from typing import Dict from typing import Optional from dbt.main import main as dbt from clouddq.utils import assert_not_none_or_empty from clouddq.utils import load_yaml from clouddq.utils import working_directory import json import logging import os import re and context from other files: # Path: clouddq/utils.py # def assert_not_none_or_empty(value: typing.Any, error_msg: str) -> None: # """ # # Args: # value: typing.Any: # error_msg: str: # # Returns: # # """ # if not value: # raise ValueError(error_msg) # # Path: clouddq/utils.py # def load_yaml(file_path: Path, key: str = None) -> typing.Any: # with file_path.open() as f: # yaml_configs = yaml.safe_load(f) # if not yaml_configs: # return dict() # output = yaml_configs.get(key, dict()) # if type(output) == dict: # return {key.upper(): value for key, value in output.items()} # elif type(output) == list: # return [item.upper() for item in output] # elif type(output) == str: # return output # else: # raise RuntimeError( # f"CloudDQ configs file `{file_path}` has empty config node type `{key}:`. " # "Please remove the node if it is not being used." # ) # # Path: clouddq/utils.py # @contextlib.contextmanager # def working_directory(path): # """Changes working directory and returns to previous on exit.""" # prev_cwd = Path.cwd() # os.chdir(path) # try: # yield # finally: # os.chdir(prev_cwd) , which may contain function names, class names, or code. Output only the next line.
with working_directory(dbt_path):
Given the following code snippet before the placeholder: <|code_start|># Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """todo: add classes docstring.""" from __future__ import annotations UNSUPPORTED_URI_CONFIGS = re.compile("[@#?:]") logger = logging.getLogger(__name__) @dataclass class EntityUri: """ """ <|code_end|> , predict the next line using imports from the current file: from dataclasses import dataclass from clouddq.classes.entity_uri_schemes import EntityUriScheme from clouddq.classes.metadata_registry_defaults import BIGQUERY_URI_FIELDS from clouddq.classes.metadata_registry_defaults import DATAPLEX_URI_FIELDS from clouddq.classes.metadata_registry_defaults import SAMPLE_DEFAULT_REGISTRIES_YAML import logging import re import typing and context including class names, function names, and sometimes code from other files: # Path: clouddq/classes/entity_uri_schemes.py # class EntityUriScheme(str, Enum): # """ """ # # DATAPLEX = "DATAPLEX" # BIGQUERY = "BIGQUERY" # # @classmethod # def from_scheme(cls, scheme: str): # # try: # return cls(scheme.upper()) # except ValueError: # raise NotImplementedError(f"{scheme} scheme is not implemented.") # # Path: clouddq/classes/metadata_registry_defaults.py # BIGQUERY_URI_FIELDS = ["projects", "datasets", "tables"] # # Path: clouddq/classes/metadata_registry_defaults.py # DATAPLEX_URI_FIELDS = ["projects", "locations", "lakes", "zones", "entities"] # # Path: clouddq/classes/metadata_registry_defaults.py # SAMPLE_DEFAULT_REGISTRIES_YAML = """ # metadata_registry_defaults: # dataplex: # projects: <my-gcp-project-id> # locations: <my-gcp-dataplex-region-id> # lakes: <my-gcp-dataplex-lake-id> # zones: <my-gcp-dataplex-zone-id> # """ . Output only the next line.
scheme: EntityUriScheme
Continue the code snippet: <|code_start|> f"lakes/{self.get_configs('lakes')}/" f"zones/{self.get_configs('zones')}/" f"entities/{self.get_configs('entities')}" ) elif self.scheme == EntityUriScheme.BIGQUERY: return ( f"projects/{self.get_configs('projects')}/" f"datasets/{self.get_configs('datasets')}/" f"tables/{self.get_configs('tables')}" ) else: raise NotImplementedError( f"EntityUri.get_db_primary_key() for scheme '{self.scheme}' " f"is not yet supported in entity_uri '{self.complete_uri_string}'." ) def _validate_dataplex_uri_fields(self, config_id: str, configs: dict) -> None: expected_fields = DATAPLEX_URI_FIELDS for field in expected_fields: value = configs.get(field, None) if not value: raise ValueError( f"Required argument '{field}' not found in entity_uri: {config_id}.\n" f"Either add '{field}' to the URI or specify default Dataplex configs for " f"projects/locations/lakes/zones as part of a YAML " f"'metadata_default_registries' config, e.g.\n" f"{SAMPLE_DEFAULT_REGISTRIES_YAML}" ) def _validate_bigquery_uri_fields(self, config_id: str, configs: dict) -> None: <|code_end|> . Use current file imports: from dataclasses import dataclass from clouddq.classes.entity_uri_schemes import EntityUriScheme from clouddq.classes.metadata_registry_defaults import BIGQUERY_URI_FIELDS from clouddq.classes.metadata_registry_defaults import DATAPLEX_URI_FIELDS from clouddq.classes.metadata_registry_defaults import SAMPLE_DEFAULT_REGISTRIES_YAML import logging import re import typing and context (classes, functions, or code) from other files: # Path: clouddq/classes/entity_uri_schemes.py # class EntityUriScheme(str, Enum): # """ """ # # DATAPLEX = "DATAPLEX" # BIGQUERY = "BIGQUERY" # # @classmethod # def from_scheme(cls, scheme: str): # # try: # return cls(scheme.upper()) # except ValueError: # raise NotImplementedError(f"{scheme} scheme is not implemented.") # # Path: clouddq/classes/metadata_registry_defaults.py # BIGQUERY_URI_FIELDS = ["projects", "datasets", "tables"] # # Path: clouddq/classes/metadata_registry_defaults.py # DATAPLEX_URI_FIELDS = ["projects", "locations", "lakes", "zones", "entities"] # # Path: clouddq/classes/metadata_registry_defaults.py # SAMPLE_DEFAULT_REGISTRIES_YAML = """ # metadata_registry_defaults: # dataplex: # projects: <my-gcp-project-id> # locations: <my-gcp-dataplex-region-id> # lakes: <my-gcp-dataplex-lake-id> # zones: <my-gcp-dataplex-zone-id> # """ . Output only the next line.
expected_fields = BIGQUERY_URI_FIELDS
Next line prediction: <|code_start|> elif self.scheme == EntityUriScheme.BIGQUERY: return self.get_db_primary_key() else: raise NotImplementedError( f"EntityUri.get_entity_id() for scheme '{self.scheme}' " f"is not yet supported in entity_uri '{self.complete_uri_string}'." ) def get_db_primary_key(self) -> str: if self.scheme == EntityUriScheme.DATAPLEX: return ( f"projects/{self.get_configs('projects')}/" f"locations/{self.get_configs('locations')}/" f"lakes/{self.get_configs('lakes')}/" f"zones/{self.get_configs('zones')}/" f"entities/{self.get_configs('entities')}" ) elif self.scheme == EntityUriScheme.BIGQUERY: return ( f"projects/{self.get_configs('projects')}/" f"datasets/{self.get_configs('datasets')}/" f"tables/{self.get_configs('tables')}" ) else: raise NotImplementedError( f"EntityUri.get_db_primary_key() for scheme '{self.scheme}' " f"is not yet supported in entity_uri '{self.complete_uri_string}'." ) def _validate_dataplex_uri_fields(self, config_id: str, configs: dict) -> None: <|code_end|> . Use current file imports: (from dataclasses import dataclass from clouddq.classes.entity_uri_schemes import EntityUriScheme from clouddq.classes.metadata_registry_defaults import BIGQUERY_URI_FIELDS from clouddq.classes.metadata_registry_defaults import DATAPLEX_URI_FIELDS from clouddq.classes.metadata_registry_defaults import SAMPLE_DEFAULT_REGISTRIES_YAML import logging import re import typing) and context including class names, function names, or small code snippets from other files: # Path: clouddq/classes/entity_uri_schemes.py # class EntityUriScheme(str, Enum): # """ """ # # DATAPLEX = "DATAPLEX" # BIGQUERY = "BIGQUERY" # # @classmethod # def from_scheme(cls, scheme: str): # # try: # return cls(scheme.upper()) # except ValueError: # raise NotImplementedError(f"{scheme} scheme is not implemented.") # # Path: clouddq/classes/metadata_registry_defaults.py # BIGQUERY_URI_FIELDS = ["projects", "datasets", "tables"] # # Path: clouddq/classes/metadata_registry_defaults.py # DATAPLEX_URI_FIELDS = ["projects", "locations", "lakes", "zones", "entities"] # # Path: clouddq/classes/metadata_registry_defaults.py # SAMPLE_DEFAULT_REGISTRIES_YAML = """ # metadata_registry_defaults: # dataplex: # projects: <my-gcp-project-id> # locations: <my-gcp-dataplex-region-id> # lakes: <my-gcp-dataplex-lake-id> # zones: <my-gcp-dataplex-zone-id> # """ . Output only the next line.
expected_fields = DATAPLEX_URI_FIELDS
Predict the next line for this snippet: <|code_start|> if self.scheme == EntityUriScheme.DATAPLEX: return ( f"projects/{self.get_configs('projects')}/" f"locations/{self.get_configs('locations')}/" f"lakes/{self.get_configs('lakes')}/" f"zones/{self.get_configs('zones')}/" f"entities/{self.get_configs('entities')}" ) elif self.scheme == EntityUriScheme.BIGQUERY: return ( f"projects/{self.get_configs('projects')}/" f"datasets/{self.get_configs('datasets')}/" f"tables/{self.get_configs('tables')}" ) else: raise NotImplementedError( f"EntityUri.get_db_primary_key() for scheme '{self.scheme}' " f"is not yet supported in entity_uri '{self.complete_uri_string}'." ) def _validate_dataplex_uri_fields(self, config_id: str, configs: dict) -> None: expected_fields = DATAPLEX_URI_FIELDS for field in expected_fields: value = configs.get(field, None) if not value: raise ValueError( f"Required argument '{field}' not found in entity_uri: {config_id}.\n" f"Either add '{field}' to the URI or specify default Dataplex configs for " f"projects/locations/lakes/zones as part of a YAML " f"'metadata_default_registries' config, e.g.\n" <|code_end|> with the help of current file imports: from dataclasses import dataclass from clouddq.classes.entity_uri_schemes import EntityUriScheme from clouddq.classes.metadata_registry_defaults import BIGQUERY_URI_FIELDS from clouddq.classes.metadata_registry_defaults import DATAPLEX_URI_FIELDS from clouddq.classes.metadata_registry_defaults import SAMPLE_DEFAULT_REGISTRIES_YAML import logging import re import typing and context from other files: # Path: clouddq/classes/entity_uri_schemes.py # class EntityUriScheme(str, Enum): # """ """ # # DATAPLEX = "DATAPLEX" # BIGQUERY = "BIGQUERY" # # @classmethod # def from_scheme(cls, scheme: str): # # try: # return cls(scheme.upper()) # except ValueError: # raise NotImplementedError(f"{scheme} scheme is not implemented.") # # Path: clouddq/classes/metadata_registry_defaults.py # BIGQUERY_URI_FIELDS = ["projects", "datasets", "tables"] # # Path: clouddq/classes/metadata_registry_defaults.py # DATAPLEX_URI_FIELDS = ["projects", "locations", "lakes", "zones", "entities"] # # Path: clouddq/classes/metadata_registry_defaults.py # SAMPLE_DEFAULT_REGISTRIES_YAML = """ # metadata_registry_defaults: # dataplex: # projects: <my-gcp-project-id> # locations: <my-gcp-dataplex-region-id> # lakes: <my-gcp-dataplex-lake-id> # zones: <my-gcp-dataplex-zone-id> # """ , which may contain function names, class names, or code. Output only the next line.
f"{SAMPLE_DEFAULT_REGISTRIES_YAML}"
Next line prediction: <|code_start|>from __future__ import annotations @dataclass class DqRowFilter: """ """ row_filter_id: str filter_sql_expr: str @classmethod def from_dict( cls: DqRowFilter, row_filter_id: str, kwargs: dict, ) -> DqRowFilter: """ Args: cls: DqRowFilter: row_filter_id: str: kwargs: typing.Dict: Returns: """ filter_sql_expr: str = kwargs.get("filter_sql_expr", "") <|code_end|> . Use current file imports: (from dataclasses import dataclass from clouddq.utils import assert_not_none_or_empty) and context including class names, function names, or small code snippets from other files: # Path: clouddq/utils.py # def assert_not_none_or_empty(value: typing.Any, error_msg: str) -> None: # """ # # Args: # value: typing.Any: # error_msg: str: # # Returns: # # """ # if not value: # raise ValueError(error_msg) . Output only the next line.
assert_not_none_or_empty(
Predict the next line after this snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations limiter = Limiter( RequestRate(2, Duration.SECOND), RequestRate(8, Duration.MINUTE), bucket_class=MemoryListBucket, ) logger = logging.getLogger(__name__) class DataplexClient: <|code_end|> using the current file's imports: from pathlib import Path from pprint import pformat from google.auth.credentials import Credentials from pyrate_limiter import Duration from pyrate_limiter import Limiter from pyrate_limiter import MemoryListBucket from pyrate_limiter import RequestRate from requests import Response from requests import Session from requests_oauth2 import OAuth2BearerToken from clouddq.integration.gcp_credentials import GcpCredentials import json import logging import google.auth import google.auth.transport.requests and any relevant context from other files: # Path: clouddq/integration/gcp_credentials.py # class GcpCredentials: # credentials: Credentials = None # project_id: str = None # user_id: str = None # # def __init__( # self, # credentials: Credentials = None, # gcp_project_id: str = None, # gcp_service_account_key_path: Path = None, # gcp_impersonation_credentials: str = None, # ) -> None: # # Use Credentials object directly if provided # if credentials: # source_credentials = credentials # # Use service account json key if provided # elif gcp_service_account_key_path: # source_credentials = service_account.Credentials.from_service_account_file( # filename=gcp_service_account_key_path, # scopes=TARGET_SCOPES, # quota_project_id=gcp_project_id, # ) # # Otherwise, use Application Default Credentials # else: # application_credentials_file = os.environ.get( # "GOOGLE_APPLICATION_CREDENTIALS", None # ) # if application_credentials_file: # logger.info( # "Using environment variable GOOGLE_APPLICATION_CREDENTIALS " # f"path: {application_credentials_file}" # ) # source_credentials, _ = google.auth.default( # scopes=TARGET_SCOPES, quota_project_id=gcp_project_id # ) # if not source_credentials.valid: # self.__refresh_credentials(source_credentials) # # Attempt service account impersonation if requested # if gcp_impersonation_credentials: # target_credentials = impersonated_credentials.Credentials( # source_credentials=source_credentials, # target_principal=gcp_impersonation_credentials, # target_scopes=TARGET_SCOPES, # lifetime=3600, # ) # self.credentials = target_credentials # else: # # Otherwise use source_credentials # self.credentials = source_credentials # self.project_id = self.__resolve_project_id( # credentials=self.credentials, project_id=gcp_project_id # ) # self.user_id = self.__resolve_credentials_username(credentials=self.credentials) # if self.user_id: # logger.info("Successfully created GCP Client.") # else: # logger.warning( # "Encountered error while retrieving user from GCP credentials.", # ) # # def __refresh_credentials(self, credentials: Credentials) -> str: # # Attempt to refresh token if not currently valid # try: # auth_req = google.auth.transport.requests.Request() # credentials.refresh(auth_req) # except RefreshError as err: # logger.error( # "Could not get refreshed credentials for GCP. " # "Reauthentication Required." # ) # raise err # # def __resolve_credentials_username(self, credentials: Credentials) -> str: # # Attempt to refresh token if not currently valid # if not credentials.valid: # self.__refresh_credentials(credentials=credentials) # # Try to get service account credentials user_id # if credentials.__dict__.get("_service_account_email"): # user_id = credentials.service_account_email # elif credentials.__dict__.get("_target_principal"): # user_id = credentials.service_account_email # else: # # Otherwise try to get ADC credentials user_id # request = google.auth.transport.requests.Request() # token = credentials.id_token # id_info = id_token.verify_oauth2_token(token, request) # user_id = id_info["email"] # return user_id # # def __resolve_project_id( # self, credentials: Credentials, project_id: str = None # ) -> str: # """Get project ID from local configs""" # if project_id: # _project_id = project_id # elif credentials.__dict__.get("_project_id"): # _project_id = credentials.project_id # else: # _project_id = None # logger.warning( # "Could not retrieve project_id from GCP credentials.", exc_info=True # ) # return _project_id . Output only the next line.
_gcp_credentials: GcpCredentials
Predict the next line after this snippet: <|code_start|># Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """todo: add classes docstring.""" from __future__ import annotations @dataclass class DataplexEntitySchema: """ """ <|code_end|> using the current file's imports: from dataclasses import dataclass from clouddq.classes.dataplex_entity_schema_field import DataplexEntitySchemaField from clouddq.classes.dataplex_entity_schema_partition_fields import ( DataplexEntityPartitionSchemaField, ) from clouddq.utils import assert_not_none_or_empty and any relevant context from other files: # Path: clouddq/classes/dataplex_entity_schema_field.py # class DataplexEntitySchemaField: # """ """ # # name: str # type: str # mode: str # # def to_dict(self: DataplexEntitySchemaField) -> dict: # """ # Args: # self: DataplexEntitySchemaField: # # Returns: # # """ # # output = { # "name": self.name, # "type": self.type, # "mode": self.mode, # } # # return dict(output) # # @classmethod # def from_dict( # cls: DataplexEntitySchemaField, entity_id: str, kwargs: dict # ) -> DataplexEntitySchemaField: # # name = kwargs.get("name") # assert_not_none_or_empty( # value=name, # error_msg=f"DataplexEntity {entity_id}: must define non-empty value: 'name'", # ) # # type = kwargs.get("type") # assert_not_none_or_empty( # value=type, # error_msg=f"DataplexEntity {entity_id}: must define non-empty value: 'type'", # ) # # mode = kwargs.get("mode") # assert_not_none_or_empty( # value=mode, # error_msg=f"DataplexEntity {entity_id}: must define non-empty value: 'mode'", # ) # # return DataplexEntitySchemaField( # name=name, # type=type, # mode=mode, # ) # # Path: clouddq/classes/dataplex_entity_schema_partition_fields.py # class DataplexEntityPartitionSchemaField: # """ """ # # name: str # type: str # # def to_dict(self: DataplexEntityPartitionSchemaField) -> dict: # """ # Args: # self: DataplexEntityPartitionSchemaField: # # Returns: # # """ # # output = { # "name": self.name, # "type": self.type, # } # # return dict(output) # # @classmethod # def from_dict( # cls: DataplexEntityPartitionSchemaField, entity_id: str, kwargs: dict # ) -> DataplexEntityPartitionSchemaField: # # name = kwargs.get("name") # assert_not_none_or_empty( # value=name, # error_msg=f"DataplexEntity {entity_id}: must define non-empty value: 'name'", # ) # # type = kwargs.get("type") # assert_not_none_or_empty( # value=type, # error_msg=f"DataplexEntity {entity_id}: must define non-empty value: 'type'", # ) # # return DataplexEntityPartitionSchemaField( # name=name, # type=type, # ) # # def to_fields_dict(self: DataplexEntityPartitionSchemaField) -> dict: # """ # Args: # self: DataplexEntityPartitionSchemaField: # # Returns: # # """ # # output = { # "name": self.name, # "type": "TIMESTAMP", # "mode": "Required", # } # # return dict(output) # # Path: clouddq/utils.py # def assert_not_none_or_empty(value: typing.Any, error_msg: str) -> None: # """ # # Args: # value: typing.Any: # error_msg: str: # # Returns: # # """ # if not value: # raise ValueError(error_msg) . Output only the next line.
fields: list[DataplexEntitySchemaField]
Continue the code snippet: <|code_start|># Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """todo: add classes docstring.""" from __future__ import annotations @dataclass class DataplexEntitySchema: """ """ fields: list[DataplexEntitySchemaField] <|code_end|> . Use current file imports: from dataclasses import dataclass from clouddq.classes.dataplex_entity_schema_field import DataplexEntitySchemaField from clouddq.classes.dataplex_entity_schema_partition_fields import ( DataplexEntityPartitionSchemaField, ) from clouddq.utils import assert_not_none_or_empty and context (classes, functions, or code) from other files: # Path: clouddq/classes/dataplex_entity_schema_field.py # class DataplexEntitySchemaField: # """ """ # # name: str # type: str # mode: str # # def to_dict(self: DataplexEntitySchemaField) -> dict: # """ # Args: # self: DataplexEntitySchemaField: # # Returns: # # """ # # output = { # "name": self.name, # "type": self.type, # "mode": self.mode, # } # # return dict(output) # # @classmethod # def from_dict( # cls: DataplexEntitySchemaField, entity_id: str, kwargs: dict # ) -> DataplexEntitySchemaField: # # name = kwargs.get("name") # assert_not_none_or_empty( # value=name, # error_msg=f"DataplexEntity {entity_id}: must define non-empty value: 'name'", # ) # # type = kwargs.get("type") # assert_not_none_or_empty( # value=type, # error_msg=f"DataplexEntity {entity_id}: must define non-empty value: 'type'", # ) # # mode = kwargs.get("mode") # assert_not_none_or_empty( # value=mode, # error_msg=f"DataplexEntity {entity_id}: must define non-empty value: 'mode'", # ) # # return DataplexEntitySchemaField( # name=name, # type=type, # mode=mode, # ) # # Path: clouddq/classes/dataplex_entity_schema_partition_fields.py # class DataplexEntityPartitionSchemaField: # """ """ # # name: str # type: str # # def to_dict(self: DataplexEntityPartitionSchemaField) -> dict: # """ # Args: # self: DataplexEntityPartitionSchemaField: # # Returns: # # """ # # output = { # "name": self.name, # "type": self.type, # } # # return dict(output) # # @classmethod # def from_dict( # cls: DataplexEntityPartitionSchemaField, entity_id: str, kwargs: dict # ) -> DataplexEntityPartitionSchemaField: # # name = kwargs.get("name") # assert_not_none_or_empty( # value=name, # error_msg=f"DataplexEntity {entity_id}: must define non-empty value: 'name'", # ) # # type = kwargs.get("type") # assert_not_none_or_empty( # value=type, # error_msg=f"DataplexEntity {entity_id}: must define non-empty value: 'type'", # ) # # return DataplexEntityPartitionSchemaField( # name=name, # type=type, # ) # # def to_fields_dict(self: DataplexEntityPartitionSchemaField) -> dict: # """ # Args: # self: DataplexEntityPartitionSchemaField: # # Returns: # # """ # # output = { # "name": self.name, # "type": "TIMESTAMP", # "mode": "Required", # } # # return dict(output) # # Path: clouddq/utils.py # def assert_not_none_or_empty(value: typing.Any, error_msg: str) -> None: # """ # # Args: # value: typing.Any: # error_msg: str: # # Returns: # # """ # if not value: # raise ValueError(error_msg) . Output only the next line.
partitionFields: list[DataplexEntityPartitionSchemaField]
Given the following code snippet before the placeholder: <|code_start|># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """todo: add classes docstring.""" from __future__ import annotations @dataclass class DataplexEntitySchema: """ """ fields: list[DataplexEntitySchemaField] partitionFields: list[DataplexEntityPartitionSchemaField] partitionStyle: str @classmethod def from_dict( cls: DataplexEntitySchema, entity_id: str, kwargs: dict ) -> DataplexEntitySchema: fields: list[dict] = [] fields_list = kwargs.get("fields") if fields_list: for obj in fields_list: field = DataplexEntitySchemaField.from_dict( entity_id=entity_id, kwargs=obj ) <|code_end|> , predict the next line using imports from the current file: from dataclasses import dataclass from clouddq.classes.dataplex_entity_schema_field import DataplexEntitySchemaField from clouddq.classes.dataplex_entity_schema_partition_fields import ( DataplexEntityPartitionSchemaField, ) from clouddq.utils import assert_not_none_or_empty and context including class names, function names, and sometimes code from other files: # Path: clouddq/classes/dataplex_entity_schema_field.py # class DataplexEntitySchemaField: # """ """ # # name: str # type: str # mode: str # # def to_dict(self: DataplexEntitySchemaField) -> dict: # """ # Args: # self: DataplexEntitySchemaField: # # Returns: # # """ # # output = { # "name": self.name, # "type": self.type, # "mode": self.mode, # } # # return dict(output) # # @classmethod # def from_dict( # cls: DataplexEntitySchemaField, entity_id: str, kwargs: dict # ) -> DataplexEntitySchemaField: # # name = kwargs.get("name") # assert_not_none_or_empty( # value=name, # error_msg=f"DataplexEntity {entity_id}: must define non-empty value: 'name'", # ) # # type = kwargs.get("type") # assert_not_none_or_empty( # value=type, # error_msg=f"DataplexEntity {entity_id}: must define non-empty value: 'type'", # ) # # mode = kwargs.get("mode") # assert_not_none_or_empty( # value=mode, # error_msg=f"DataplexEntity {entity_id}: must define non-empty value: 'mode'", # ) # # return DataplexEntitySchemaField( # name=name, # type=type, # mode=mode, # ) # # Path: clouddq/classes/dataplex_entity_schema_partition_fields.py # class DataplexEntityPartitionSchemaField: # """ """ # # name: str # type: str # # def to_dict(self: DataplexEntityPartitionSchemaField) -> dict: # """ # Args: # self: DataplexEntityPartitionSchemaField: # # Returns: # # """ # # output = { # "name": self.name, # "type": self.type, # } # # return dict(output) # # @classmethod # def from_dict( # cls: DataplexEntityPartitionSchemaField, entity_id: str, kwargs: dict # ) -> DataplexEntityPartitionSchemaField: # # name = kwargs.get("name") # assert_not_none_or_empty( # value=name, # error_msg=f"DataplexEntity {entity_id}: must define non-empty value: 'name'", # ) # # type = kwargs.get("type") # assert_not_none_or_empty( # value=type, # error_msg=f"DataplexEntity {entity_id}: must define non-empty value: 'type'", # ) # # return DataplexEntityPartitionSchemaField( # name=name, # type=type, # ) # # def to_fields_dict(self: DataplexEntityPartitionSchemaField) -> dict: # """ # Args: # self: DataplexEntityPartitionSchemaField: # # Returns: # # """ # # output = { # "name": self.name, # "type": "TIMESTAMP", # "mode": "Required", # } # # return dict(output) # # Path: clouddq/utils.py # def assert_not_none_or_empty(value: typing.Any, error_msg: str) -> None: # """ # # Args: # value: typing.Any: # error_msg: str: # # Returns: # # """ # if not value: # raise ValueError(error_msg) . Output only the next line.
assert_not_none_or_empty(
Continue the code snippet: <|code_start|>), SELECT CURRENT_TIMESTAMP() AS execution_ts, '{{ rule_binding_id }}' AS rule_binding_id, '{{ rule_id }}' AS rule_id, (select distinct num_rows_validated from data) as num_rows_validated, FALSE AS simple_rule_row_is_valid, COUNT(*) as complex_rule_validation_errors_count, FROM zero_record LEFT JOIN ( {{ custom_sql_statement }} ) custom_sql_statement_validation_errors ON zero_record.rule_binding_id = custom_sql_statement_validation_errors.rule_binding_id """ def check_for_invalid_sql(rule_type: RuleType, sql_string: str) -> None: if RE_FORBIDDEN_SQL.search(sql_string): raise ValueError( f"RuleType: {rule_type.name} contains " f"invalid characters.\n" f"Current value: {sql_string}" ) def to_sql_custom_sql_expr(params: dict) -> Template: custom_sql_expr = params.get("custom_sql_expr", "") <|code_end|> . Use current file imports: from enum import Enum from enum import unique from pprint import pformat from string import Template from clouddq.utils import assert_not_none_or_empty import re and context (classes, functions, or code) from other files: # Path: clouddq/utils.py # def assert_not_none_or_empty(value: typing.Any, error_msg: str) -> None: # """ # # Args: # value: typing.Any: # error_msg: str: # # Returns: # # """ # if not value: # raise ValueError(error_msg) . Output only the next line.
assert_not_none_or_empty(
Given the code snippet: <|code_start|> class Defer(Producer): def __init__(self, observableFactory): self.observableFactory = observableFactory def run(self, observer, cancel, setSink): sink = self.Sink(self, observer, cancel) setSink(sink) return sink.run() def eval(self): return self.observableFactory() class Sink(rx.linq.sink.Sink): def __init__(self, parent, observer, cancel): super(Defer.Sink, self).__init__(observer, cancel) self.parent = parent def run(self): try: result = self.parent.eval() except Exception as e: self.observer.onError(e) self.dispose() <|code_end|> , generate the next line using the imports in this file: from rx.disposable import Disposable from rx.observable import Producer import rx.linq.sink and context (functions, classes, or occasionally code) from other files: # Path: rx/disposable.py # class Disposable(object): # """Represents a disposable object""" # # def dispose(self): # pass # # def __enter__(self): # return self # # def __exit__(self, exc_type, exc_value, traceback): # self.dispose() # # @staticmethod # def create(action): # return AnonymouseDisposable(action) # # @staticmethod # def empty(): # return disposableEmpty # # Path: rx/observable.py # class Producer(Observable): # """Base class for implementation of query operators, providing # performance benefits over the use of Observable.Create""" # # def subscribeCore(self, observer): # return self.subscribeRaw(observer, True) # # def subscribeRaw(self, observer, enableSafequard): # sink = SingleAssignmentDisposable() # subscription = SingleAssignmentDisposable() # # d = CompositeDisposable(sink, subscription) # # if enableSafequard: # observer = AutoDetachObserver(observer, d) # # def assignSink(s): # sink.disposable = s # # def scheduled(): # subscription.disposable = self.run(observer, subscription, assignSink) # return Disposable.empty() # # if Scheduler.currentThread.isScheduleRequired(): # Scheduler.currentThread.schedule(scheduled) # else: # scheduled() # # return d # # def run(self, observer, cancel, setSink): # raise NotImplementedError() . Output only the next line.
return Disposable.empty()
Continue the code snippet: <|code_start|> class Amb(Producer): LEFT = 0 RIGHT = 1 NEITHER = 2 def __init__(self, left, right): self.left = left self.right = right def run(self, observer, cancel, setSink): sink = self.Sink(self, observer, cancel) setSink(sink) return sink.run() <|code_end|> . Use current file imports: from rx.observer import Observer from rx.observable import Producer from rx.disposable import CompositeDisposable, SingleAssignmentDisposable from threading import RLock import rx.linq.sink and context (classes, functions, or code) from other files: # Path: rx/observer.py # class Observer(Disposable): # """Represents the IObserver Interface. # Has some static helper methods attached""" # # @staticmethod # def create(onNext=None, onError=None, onCompleted=None): # if onNext == None: # onNext = noop # if onError == None: # onError = defaultError # if onCompleted == None: # onCompleted = noop # # return AnonymousObserver(onNext, onError, onCompleted) # # @staticmethod # def synchronize(observer, lock=None): # if lock == None: # lock = RLock() # # return SynchronizedObserver(observer, lock) # # @staticmethod # def fromNotifier(handler): # return AnonymousObserver( # lambda x: handler(Notification.createOnNext(x)), # lambda ex: handler(Notification.createOnError(ex)), # lambda: handler(Notification.createOnCompleted()) # ) # # def toNotifier(self): # return lambda n: n.accept(self) # # def asObserver(self): # return AnonymousObserver(self.onNext, self.onError, self.onCompleted) # # def checked(self): # return CheckedObserver(self) # # def notifyOn(self, scheduler): # return ScheduledObserver(scheduler, self) # # def onNext(self, value): # raise NotImplementedError() # # def onError(self, exception): # raise NotImplementedError() # # def onCompleted(self): # raise NotImplementedError() # # Path: rx/observable.py # class Producer(Observable): # """Base class for implementation of query operators, providing # performance benefits over the use of Observable.Create""" # # def subscribeCore(self, observer): # return self.subscribeRaw(observer, True) # # def subscribeRaw(self, observer, enableSafequard): # sink = SingleAssignmentDisposable() # subscription = SingleAssignmentDisposable() # # d = CompositeDisposable(sink, subscription) # # if enableSafequard: # observer = AutoDetachObserver(observer, d) # # def assignSink(s): # sink.disposable = s # # def scheduled(): # subscription.disposable = self.run(observer, subscription, assignSink) # return Disposable.empty() # # if Scheduler.currentThread.isScheduleRequired(): # Scheduler.currentThread.schedule(scheduled) # else: # scheduled() # # return d # # def run(self, observer, cancel, setSink): # raise NotImplementedError() # # Path: rx/disposable.py # class CompositeDisposable(Cancelable): # """Represents a group of disposable resources that # are disposed together""" # # def __init__(self, *disposables): # super(CompositeDisposable, self).__init__() # # if len(disposables) == 0: # self.disposables = [] # elif len(disposables) == 1 and not isinstance(disposables[0], Disposable): # self.disposables = [d for d in disposables[0] if d != None] # else: # self.disposables = [d for d in disposables if d != None] # # self.length = len(self.disposables) # # def add(self, disposable): # shouldDispose = False # # with self.lock: # shouldDispose = self.isDisposed # # if not shouldDispose: # self.disposables.append(disposable) # self.length += 1 # # if shouldDispose: # disposable.dispose() # # def contains(self, disposable): # with self.lock: # return self.disposables.index(disposable) >= 0 # # def remove(self, disposable): # shouldDispose = False # # with self.lock: # if self.isDisposed: # return False # # index = self.disposables.index(disposable) # # if index < 0: # return False # # shouldDispose = True # # self.disposables.remove(disposable) # self.length -= 1 # # if shouldDispose: # disposable.dispose() # # return shouldDispose # # def clear(self): # disposables = [] # # with self.lock: # disposables = self.disposables # self.disposables = [] # self.length = 0 # # for disposable in disposables: # disposable.dispose() # # def dispose(self): # if not self._isDisposed.exchange(True): # self.clear() # # class SingleAssignmentDisposable(Cancelable): # """Represents a disposable resource which only allows # a single assignment of its underlying disposable resource. # If an underlying disposable resource has already been set, # future attempts to set the underlying disposable resource # will throw an Error.""" # # def __init__(self): # super(SingleAssignmentDisposable, self).__init__() # self.current = None # # def disposable(): # def fget(self): # with self.lock: # if self.isDisposed: # return Disposable.empty() # else: # return self.current # def fset(self, value): # old = self.current # self.current = value # # if old != None: raise Exception("Disposable has already been assigned") # # if self.isDisposed and value != None: value.dispose() # return locals() # # disposable = property(**disposable()) # # def dispose(self): # if not self._isDisposed.exchange(True): # if self.current != None: # self.current.dispose() . Output only the next line.
class DecisionObserver(Observer):
Predict the next line after this snippet: <|code_start|> super(TestScheduler, self).start() return state.observer class MockObserver(Observer): def __init__(self, scheduler): super(TestScheduler.MockObserver, self).__init__() self.scheduler = scheduler self.messages = [] def onNext(self, value): self.messages.append(( self.scheduler.now(), OnNext(value) )) def onError(self, exception): self.messages.append(( self.scheduler.now(), OnError(exception) )) def onCompleted(self): self.messages.append(( self.scheduler.now(), OnCompleted() )) <|code_end|> using the current file's imports: import unittest from rx.disposable import Disposable from rx.internal import Struct from rx.notification import Notification from rx.observable import Observable from rx.observer import Observer from rx.scheduler import HistoricalScheduler and any relevant context from other files: # Path: rx/disposable.py # class Disposable(object): # """Represents a disposable object""" # # def dispose(self): # pass # # def __enter__(self): # return self # # def __exit__(self, exc_type, exc_value, traceback): # self.dispose() # # @staticmethod # def create(action): # return AnonymouseDisposable(action) # # @staticmethod # def empty(): # return disposableEmpty # # Path: rx/internal.py # class Struct(object): # def __init__(self, **entries): # self.__dict__.update(entries) # # def __eq__(self, other): # if not isinstance(other, Struct): # return False # # return self.__dict__ == other.__dict__ # # def __repr__(self): # return repr(self.__dict__) # # Path: rx/notification.py # class Notification(object): # """Represents a notification to an observer.""" # # KIND_NEXT = 0 # KIND_ERROR = 1 # KIND_COMPLETED = 2 # # def __eq__(self, other): # if not isinstance(other, Notification): # return False # # return ( # self.kind == other.kind and # self.value == other.value and # self.hasValue == other.hasValue and # self.exception == other.exception # ) # # def accept(self, observerOrOnNext, onError=None, onCompleted=None): # """Accepts an observer or the methods onNext, onError, onCompleted and invokes # either onNext, onError, onCompleted depending on which type of :class:`Notification` # it is. This is an abstract method that is implemented by # :class:`OnNextNotification`, :class:`OnErrorNotification`, # and :class:`OnCompletedNotification`.""" # # if observerOrOnNext == None or hasattr(observerOrOnNext, '__call__'): # # observer = Observer.create(observerOrOnNext, onError, onComplete) # raise NotImplementedError() # # @staticmethod # def createOnNext(value): # return OnNextNotification(value) # # @staticmethod # def createOnError(exception): # return OnErrorNotification(exception) # # @staticmethod # def createOnCompleted(): # return OnCompletedNotification() # # Path: rx/observable.py # class Observable(object): # """Provides all extension methods to Observable""" # # def subscribe(self, observerOrOnNext=noop, onError=noop, onComplete=noop): # observer = observerOrOnNext # # if observerOrOnNext == None or callable(observerOrOnNext): # observer = Observer.create(observerOrOnNext, onError, onComplete) # # return self.subscribeCore(observer) # # def subscribeCore(self, observer): # raise NotImplementedError() # # def subscribeSafe(self, observer): # if isinstance(self, ObservableBase): # return self.subscribeCore(observer) # elif isinstance(self, Producer): # return self.subscribeRaw(observer, False) # # d = Disposable.empty() # # try: # d = self.subscribeCore(observer) # except Exception as e: # observer.onError(e) # # return d # # Path: rx/observer.py # class Observer(Disposable): # """Represents the IObserver Interface. # Has some static helper methods attached""" # # @staticmethod # def create(onNext=None, onError=None, onCompleted=None): # if onNext == None: # onNext = noop # if onError == None: # onError = defaultError # if onCompleted == None: # onCompleted = noop # # return AnonymousObserver(onNext, onError, onCompleted) # # @staticmethod # def synchronize(observer, lock=None): # if lock == None: # lock = RLock() # # return SynchronizedObserver(observer, lock) # # @staticmethod # def fromNotifier(handler): # return AnonymousObserver( # lambda x: handler(Notification.createOnNext(x)), # lambda ex: handler(Notification.createOnError(ex)), # lambda: handler(Notification.createOnCompleted()) # ) # # def toNotifier(self): # return lambda n: n.accept(self) # # def asObserver(self): # return AnonymousObserver(self.onNext, self.onError, self.onCompleted) # # def checked(self): # return CheckedObserver(self) # # def notifyOn(self, scheduler): # return ScheduledObserver(scheduler, self) # # def onNext(self, value): # raise NotImplementedError() # # def onError(self, exception): # raise NotImplementedError() # # def onCompleted(self): # raise NotImplementedError() # # Path: rx/scheduler.py # class HistoricalScheduler(VirtualTimeScheduler): # """Provides a virtual time scheduler that uses number for # absolute time and number for relative time.""" # def __init__(self, initialClock = 0, comparer = defaultSubComparer): # super(HistoricalScheduler, self).__init__(initialClock, comparer) # self.clock = initialClock # self.cmp = comparer # # def add(self, absolute, relative): # return absolute + relative # # def toDateTimeOffset(self, absolute): # return absolute # # def toRelative(self, timeSpan): # return timeSpan . Output only the next line.
class HotObservable(Observable):
Given the code snippet: <|code_start|> def OnNext(value): return Notification.createOnNext(value) def OnError(exception): return Notification.createOnError(exception) def OnCompleted(): return Notification.createOnCompleted() <|code_end|> , generate the next line using the imports in this file: import unittest from rx.disposable import Disposable from rx.internal import Struct from rx.notification import Notification from rx.observable import Observable from rx.observer import Observer from rx.scheduler import HistoricalScheduler and context (functions, classes, or occasionally code) from other files: # Path: rx/disposable.py # class Disposable(object): # """Represents a disposable object""" # # def dispose(self): # pass # # def __enter__(self): # return self # # def __exit__(self, exc_type, exc_value, traceback): # self.dispose() # # @staticmethod # def create(action): # return AnonymouseDisposable(action) # # @staticmethod # def empty(): # return disposableEmpty # # Path: rx/internal.py # class Struct(object): # def __init__(self, **entries): # self.__dict__.update(entries) # # def __eq__(self, other): # if not isinstance(other, Struct): # return False # # return self.__dict__ == other.__dict__ # # def __repr__(self): # return repr(self.__dict__) # # Path: rx/notification.py # class Notification(object): # """Represents a notification to an observer.""" # # KIND_NEXT = 0 # KIND_ERROR = 1 # KIND_COMPLETED = 2 # # def __eq__(self, other): # if not isinstance(other, Notification): # return False # # return ( # self.kind == other.kind and # self.value == other.value and # self.hasValue == other.hasValue and # self.exception == other.exception # ) # # def accept(self, observerOrOnNext, onError=None, onCompleted=None): # """Accepts an observer or the methods onNext, onError, onCompleted and invokes # either onNext, onError, onCompleted depending on which type of :class:`Notification` # it is. This is an abstract method that is implemented by # :class:`OnNextNotification`, :class:`OnErrorNotification`, # and :class:`OnCompletedNotification`.""" # # if observerOrOnNext == None or hasattr(observerOrOnNext, '__call__'): # # observer = Observer.create(observerOrOnNext, onError, onComplete) # raise NotImplementedError() # # @staticmethod # def createOnNext(value): # return OnNextNotification(value) # # @staticmethod # def createOnError(exception): # return OnErrorNotification(exception) # # @staticmethod # def createOnCompleted(): # return OnCompletedNotification() # # Path: rx/observable.py # class Observable(object): # """Provides all extension methods to Observable""" # # def subscribe(self, observerOrOnNext=noop, onError=noop, onComplete=noop): # observer = observerOrOnNext # # if observerOrOnNext == None or callable(observerOrOnNext): # observer = Observer.create(observerOrOnNext, onError, onComplete) # # return self.subscribeCore(observer) # # def subscribeCore(self, observer): # raise NotImplementedError() # # def subscribeSafe(self, observer): # if isinstance(self, ObservableBase): # return self.subscribeCore(observer) # elif isinstance(self, Producer): # return self.subscribeRaw(observer, False) # # d = Disposable.empty() # # try: # d = self.subscribeCore(observer) # except Exception as e: # observer.onError(e) # # return d # # Path: rx/observer.py # class Observer(Disposable): # """Represents the IObserver Interface. # Has some static helper methods attached""" # # @staticmethod # def create(onNext=None, onError=None, onCompleted=None): # if onNext == None: # onNext = noop # if onError == None: # onError = defaultError # if onCompleted == None: # onCompleted = noop # # return AnonymousObserver(onNext, onError, onCompleted) # # @staticmethod # def synchronize(observer, lock=None): # if lock == None: # lock = RLock() # # return SynchronizedObserver(observer, lock) # # @staticmethod # def fromNotifier(handler): # return AnonymousObserver( # lambda x: handler(Notification.createOnNext(x)), # lambda ex: handler(Notification.createOnError(ex)), # lambda: handler(Notification.createOnCompleted()) # ) # # def toNotifier(self): # return lambda n: n.accept(self) # # def asObserver(self): # return AnonymousObserver(self.onNext, self.onError, self.onCompleted) # # def checked(self): # return CheckedObserver(self) # # def notifyOn(self, scheduler): # return ScheduledObserver(scheduler, self) # # def onNext(self, value): # raise NotImplementedError() # # def onError(self, exception): # raise NotImplementedError() # # def onCompleted(self): # raise NotImplementedError() # # Path: rx/scheduler.py # class HistoricalScheduler(VirtualTimeScheduler): # """Provides a virtual time scheduler that uses number for # absolute time and number for relative time.""" # def __init__(self, initialClock = 0, comparer = defaultSubComparer): # super(HistoricalScheduler, self).__init__(initialClock, comparer) # self.clock = initialClock # self.cmp = comparer # # def add(self, absolute, relative): # return absolute + relative # # def toDateTimeOffset(self, absolute): # return absolute # # def toRelative(self, timeSpan): # return timeSpan . Output only the next line.
class TestScheduler(HistoricalScheduler):
Using the snippet: <|code_start|> self.dispose() class SkipLastTime(Producer): def __init__(self, source, duration, scheduler): self.source = source self.duration = duration self.scheduler = scheduler def run(self, observer, cancel, setSink): sink = self.Sink(self, observer, cancel) setSink(sink) return sink.run() class Sink(rx.linq.sink.Sink): def __init__(self, parent, observer, cancel): super(SkipLastTime.Sink, self).__init__(observer, cancel) self.parent = parent def run(self): self.startTime = self.parent.scheduler.now() return self.parent.subscribeSafe(self) def elapsed(self): return self.parent.scheduler.now() - self.startTime def onNext(self, value): now = self.elapsed() <|code_end|> , determine the next line of code. You have imports: from rx.internal import Struct from rx.observable import Producer from collections import deque import rx.linq.sink and context (class names, function names, or code) available: # Path: rx/internal.py # class Struct(object): # def __init__(self, **entries): # self.__dict__.update(entries) # # def __eq__(self, other): # if not isinstance(other, Struct): # return False # # return self.__dict__ == other.__dict__ # # def __repr__(self): # return repr(self.__dict__) # # Path: rx/observable.py # class Producer(Observable): # """Base class for implementation of query operators, providing # performance benefits over the use of Observable.Create""" # # def subscribeCore(self, observer): # return self.subscribeRaw(observer, True) # # def subscribeRaw(self, observer, enableSafequard): # sink = SingleAssignmentDisposable() # subscription = SingleAssignmentDisposable() # # d = CompositeDisposable(sink, subscription) # # if enableSafequard: # observer = AutoDetachObserver(observer, d) # # def assignSink(s): # sink.disposable = s # # def scheduled(): # subscription.disposable = self.run(observer, subscription, assignSink) # return Disposable.empty() # # if Scheduler.currentThread.isScheduleRequired(): # Scheduler.currentThread.schedule(scheduled) # else: # scheduled() # # return d # # def run(self, observer, cancel, setSink): # raise NotImplementedError() . Output only the next line.
self.queue.append(Struct(value=value,timeStamp=now))
Given the following code snippet before the placeholder: <|code_start|> class TimeInterval(Producer): def __init__(self, source, scheduler): self.source = source self.scheduler = scheduler def run(self, observer, cancel, setSink): sink = self.Sink(self, observer, cancel) setSink(sink) return sink.run() class Sink(rx.linq.sink.Sink): def __init__(self, parent, observer, cancel): super(TimeInterval.Sink, self).__init__(observer, cancel) self.parent = parent def run(self): self.startTime = self.parent.scheduler.now() self.last = 0 return self.parent.source.subscribeSafe(self) def elapsed(self): return self.parent.scheduler.now() - self.startTime def onNext(self, value): now = self.elapsed() span = now - self.last self.last = now <|code_end|> , predict the next line using imports from the current file: from rx.internal import Struct from rx.observable import Producer import rx.linq.sink and context including class names, function names, and sometimes code from other files: # Path: rx/internal.py # class Struct(object): # def __init__(self, **entries): # self.__dict__.update(entries) # # def __eq__(self, other): # if not isinstance(other, Struct): # return False # # return self.__dict__ == other.__dict__ # # def __repr__(self): # return repr(self.__dict__) # # Path: rx/observable.py # class Producer(Observable): # """Base class for implementation of query operators, providing # performance benefits over the use of Observable.Create""" # # def subscribeCore(self, observer): # return self.subscribeRaw(observer, True) # # def subscribeRaw(self, observer, enableSafequard): # sink = SingleAssignmentDisposable() # subscription = SingleAssignmentDisposable() # # d = CompositeDisposable(sink, subscription) # # if enableSafequard: # observer = AutoDetachObserver(observer, d) # # def assignSink(s): # sink.disposable = s # # def scheduled(): # subscription.disposable = self.run(observer, subscription, assignSink) # return Disposable.empty() # # if Scheduler.currentThread.isScheduleRequired(): # Scheduler.currentThread.schedule(scheduled) # else: # scheduled() # # return d # # def run(self, observer, cancel, setSink): # raise NotImplementedError() . Output only the next line.
self.observer.onNext(Struct(value=value, interval=span))
Given snippet: <|code_start|> self.connectableSubscription = None def run(self, observer, cancel, setSink): sink = self.Sink(self, observer, cancel) setSink(sink) return sink.run() class Sink(rx.linq.sink.Sink): def __init__(self, parent, observer, cancel): super(RefCount.Sink, self).__init__(observer, cancel) self.parent = parent def run(self): subscription = self.parent.source.subscribeSafe(self) with self.parent.gate: self.parent.count += 1 if self.parent.count == 1: self.parent.connectableSubscription = self.parent.source.connect() def dispose(): subscription.dispose() with self.parent.gate: self.parent.count -= 1 if self.parent.count == 0: self.parent.connectableSubscription.dispose() <|code_end|> , continue by predicting the next line. Consider current file imports: from rx.disposable import Disposable from rx.observable import Producer from threading import RLock import rx.linq.sink and context: # Path: rx/disposable.py # class Disposable(object): # """Represents a disposable object""" # # def dispose(self): # pass # # def __enter__(self): # return self # # def __exit__(self, exc_type, exc_value, traceback): # self.dispose() # # @staticmethod # def create(action): # return AnonymouseDisposable(action) # # @staticmethod # def empty(): # return disposableEmpty # # Path: rx/observable.py # class Producer(Observable): # """Base class for implementation of query operators, providing # performance benefits over the use of Observable.Create""" # # def subscribeCore(self, observer): # return self.subscribeRaw(observer, True) # # def subscribeRaw(self, observer, enableSafequard): # sink = SingleAssignmentDisposable() # subscription = SingleAssignmentDisposable() # # d = CompositeDisposable(sink, subscription) # # if enableSafequard: # observer = AutoDetachObserver(observer, d) # # def assignSink(s): # sink.disposable = s # # def scheduled(): # subscription.disposable = self.run(observer, subscription, assignSink) # return Disposable.empty() # # if Scheduler.currentThread.isScheduleRequired(): # Scheduler.currentThread.schedule(scheduled) # else: # scheduled() # # return d # # def run(self, observer, cancel, setSink): # raise NotImplementedError() which might include code, classes, or functions. Output only the next line.
return Disposable.create(dispose)
Here is a snippet: <|code_start|> class Finally(Producer): def __init__(self, source, action): self.source = source self.action = action def run(self, observer, cancel, setSink): sink = self.Sink(self, observer, cancel) setSink(sink) return sink.run() class Sink(rx.linq.sink.Sink): def __init__(self, parent, observer, cancel): super(Finally.Sink, self).__init__(observer, cancel) self.parent = parent def run(self): def dispose(): try: subscription.dispose() finally: self.parent.action() subscription = self.parent.source.subscribeSafe(self) <|code_end|> . Write the next line using the current file imports: from rx.disposable import Disposable from rx.observable import Producer import rx.linq.sink and context from other files: # Path: rx/disposable.py # class Disposable(object): # """Represents a disposable object""" # # def dispose(self): # pass # # def __enter__(self): # return self # # def __exit__(self, exc_type, exc_value, traceback): # self.dispose() # # @staticmethod # def create(action): # return AnonymouseDisposable(action) # # @staticmethod # def empty(): # return disposableEmpty # # Path: rx/observable.py # class Producer(Observable): # """Base class for implementation of query operators, providing # performance benefits over the use of Observable.Create""" # # def subscribeCore(self, observer): # return self.subscribeRaw(observer, True) # # def subscribeRaw(self, observer, enableSafequard): # sink = SingleAssignmentDisposable() # subscription = SingleAssignmentDisposable() # # d = CompositeDisposable(sink, subscription) # # if enableSafequard: # observer = AutoDetachObserver(observer, d) # # def assignSink(s): # sink.disposable = s # # def scheduled(): # subscription.disposable = self.run(observer, subscription, assignSink) # return Disposable.empty() # # if Scheduler.currentThread.isScheduleRequired(): # Scheduler.currentThread.schedule(scheduled) # else: # scheduled() # # return d # # def run(self, observer, cancel, setSink): # raise NotImplementedError() , which may include functions, classes, or code. Output only the next line.
return Disposable.create(dispose)
Given the following code snippet before the placeholder: <|code_start|> self.defaultValue = defaultValue def run(self, observer, cancel, setSink): sink = self.Sink(self, observer, cancel) setSink(sink) return self.source.subscribeSafe(sink) class Sink(rx.linq.sink.Sink): def __init__(self, parent, observer, cancel): super(FirstAsync.Sink, self).__init__(observer, cancel) self.parent = parent def onNext(self, value): try: b = self.parent.predicate(value) except Exception as e: self.observer.onError(e) self.dispose() else: if b: self.observer.onNext(value) self.observer.onCompleted() self.dispose() def onError(self, exception): self.observer.onError(exception) self.dispose() def onCompleted(self): if self.parent.throwOnEmpty: <|code_end|> , predict the next line using imports from the current file: from rx.exceptions import InvalidOperationException from rx.observable import Producer import rx.linq.sink and context including class names, function names, and sometimes code from other files: # Path: rx/exceptions.py # class InvalidOperationException(Exception): # def __init__(self, text): # super(InvalidOperationException, self).__init__("Invalid operation: %s" % text) # # Path: rx/observable.py # class Producer(Observable): # """Base class for implementation of query operators, providing # performance benefits over the use of Observable.Create""" # # def subscribeCore(self, observer): # return self.subscribeRaw(observer, True) # # def subscribeRaw(self, observer, enableSafequard): # sink = SingleAssignmentDisposable() # subscription = SingleAssignmentDisposable() # # d = CompositeDisposable(sink, subscription) # # if enableSafequard: # observer = AutoDetachObserver(observer, d) # # def assignSink(s): # sink.disposable = s # # def scheduled(): # subscription.disposable = self.run(observer, subscription, assignSink) # return Disposable.empty() # # if Scheduler.currentThread.isScheduleRequired(): # Scheduler.currentThread.schedule(scheduled) # else: # scheduled() # # return d # # def run(self, observer, cancel, setSink): # raise NotImplementedError() . Output only the next line.
self.observer.onError(InvalidOperationException("No elements in observable"))
Using the snippet: <|code_start|> sink = self.Sink(self, observer, cancel) setSink(sink) return self.source.subscribeSafe(sink) class Sink(rx.linq.sink.Sink): def __init__(self, parent, observer, cancel): super(Max.Sink, self).__init__(observer, cancel) self.parent = parent self.lastValue = None self.hasValue = False def onNext(self, value): if value != None: if not self.hasValue: self.lastValue = value self.hasValue = True else: try: if self.parent.compareTo(value, self.lastValue) > 0: self.lastValue = value except Exception as e: self.observer.onError(e) self.dispose() def onError(self, exception): self.observer.onError(exception) self.dispose() def onCompleted(self): if not self.hasValue: <|code_end|> , determine the next line of code. You have imports: from rx.exceptions import InvalidOperationException from rx.observable import Producer import rx.linq.sink and context (class names, function names, or code) available: # Path: rx/exceptions.py # class InvalidOperationException(Exception): # def __init__(self, text): # super(InvalidOperationException, self).__init__("Invalid operation: %s" % text) # # Path: rx/observable.py # class Producer(Observable): # """Base class for implementation of query operators, providing # performance benefits over the use of Observable.Create""" # # def subscribeCore(self, observer): # return self.subscribeRaw(observer, True) # # def subscribeRaw(self, observer, enableSafequard): # sink = SingleAssignmentDisposable() # subscription = SingleAssignmentDisposable() # # d = CompositeDisposable(sink, subscription) # # if enableSafequard: # observer = AutoDetachObserver(observer, d) # # def assignSink(s): # sink.disposable = s # # def scheduled(): # subscription.disposable = self.run(observer, subscription, assignSink) # return Disposable.empty() # # if Scheduler.currentThread.isScheduleRequired(): # Scheduler.currentThread.schedule(scheduled) # else: # scheduled() # # return d # # def run(self, observer, cancel, setSink): # raise NotImplementedError() . Output only the next line.
self.observer.onError(InvalidOperationException("No elements in observable"))
Here is a snippet: <|code_start|> class Disposable(object): """Represents a disposable object""" def dispose(self): pass def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): self.dispose() @staticmethod def create(action): return AnonymouseDisposable(action) @staticmethod def empty(): return disposableEmpty disposableEmpty = Disposable() class Cancelable(Disposable): """Inherits :class:`Disposable` and adds the :attr:`isDisposed` attribute.""" def __init__(self): super(Cancelable, self).__init__() <|code_end|> . Write the next line using the current file imports: from rx.concurrency import Atomic from collections import deque and context from other files: # Path: rx/concurrency.py # class Atomic: # def __init__(self, value=None, lock=RLock()): # self.lock = lock # self._value = value # # def value(): # doc = "The value property." # def fget(self): # return self._value # def fset(self, value): # self.exchange(value) # return locals() # value = property(**value()) # # def exchange(self, value): # with self.lock: # old = self._value # self._value = value # return old # # def compareExchange(self, value, expected): # with self.lock: # old = self._value # # if old == expected: # self._value = value # # return old # # def inc(self, by=1): # with self.lock: # self._value += by # return self.value # # def dec(self, by=1): # with self.lock: # self._value -= by # return self.value , which may include functions, classes, or code. Output only the next line.
self._isDisposed = Atomic(False)
Next line prediction: <|code_start|> class Never(Observable): def __init__(self): super(Never, self).__init__() def subscribeCore(self, observer): <|code_end|> . Use current file imports: (from rx.disposable import Disposable from rx.observable import Observable) and context including class names, function names, or small code snippets from other files: # Path: rx/disposable.py # class Disposable(object): # """Represents a disposable object""" # # def dispose(self): # pass # # def __enter__(self): # return self # # def __exit__(self, exc_type, exc_value, traceback): # self.dispose() # # @staticmethod # def create(action): # return AnonymouseDisposable(action) # # @staticmethod # def empty(): # return disposableEmpty # # Path: rx/observable.py # class Observable(object): # """Provides all extension methods to Observable""" # # def subscribe(self, observerOrOnNext=noop, onError=noop, onComplete=noop): # observer = observerOrOnNext # # if observerOrOnNext == None or callable(observerOrOnNext): # observer = Observer.create(observerOrOnNext, onError, onComplete) # # return self.subscribeCore(observer) # # def subscribeCore(self, observer): # raise NotImplementedError() # # def subscribeSafe(self, observer): # if isinstance(self, ObservableBase): # return self.subscribeCore(observer) # elif isinstance(self, Producer): # return self.subscribeRaw(observer, False) # # d = Disposable.empty() # # try: # d = self.subscribeCore(observer) # except Exception as e: # observer.onError(e) # # return d . Output only the next line.
return Disposable.empty()
Next line prediction: <|code_start|> sink = self.Sink(self, observer, cancel) setSink(sink) return self.source.subscribeSafe(sink) class Sink(rx.linq.sink.Sink): def __init__(self, parent, observer, cancel): super(Min.Sink, self).__init__(observer, cancel) self.parent = parent self.lastValue = None self.hasValue = False def onNext(self, value): if value != None: if not self.hasValue: self.lastValue = value self.hasValue = True else: try: if self.parent.compareTo(value, self.lastValue) < 0: self.lastValue = value except Exception as e: self.observer.onError(e) self.dispose() def onError(self, exception): self.observer.onError(exception) self.dispose() def onCompleted(self): if not self.hasValue: <|code_end|> . Use current file imports: (from rx.exceptions import InvalidOperationException from rx.observable import Producer import rx.linq.sink) and context including class names, function names, or small code snippets from other files: # Path: rx/exceptions.py # class InvalidOperationException(Exception): # def __init__(self, text): # super(InvalidOperationException, self).__init__("Invalid operation: %s" % text) # # Path: rx/observable.py # class Producer(Observable): # """Base class for implementation of query operators, providing # performance benefits over the use of Observable.Create""" # # def subscribeCore(self, observer): # return self.subscribeRaw(observer, True) # # def subscribeRaw(self, observer, enableSafequard): # sink = SingleAssignmentDisposable() # subscription = SingleAssignmentDisposable() # # d = CompositeDisposable(sink, subscription) # # if enableSafequard: # observer = AutoDetachObserver(observer, d) # # def assignSink(s): # sink.disposable = s # # def scheduled(): # subscription.disposable = self.run(observer, subscription, assignSink) # return Disposable.empty() # # if Scheduler.currentThread.isScheduleRequired(): # Scheduler.currentThread.schedule(scheduled) # else: # scheduled() # # return d # # def run(self, observer, cancel, setSink): # raise NotImplementedError() . Output only the next line.
self.observer.onError(InvalidOperationException("No elements in observable"))
Given the code snippet: <|code_start|> class MostRecent(PushToPullAdapter): def __init__(self, source, initialValue): super(MostRecent, self).__init__(source) self.initialValue = initialValue def run(self, subscription): return self.Sink(self.initialValue, subscription) class Sink(rx.linq.sink.PushToPullSink): def __init__(self, initialValue, subscription): super(MostRecent.Sink, self).__init__(subscription) <|code_end|> , generate the next line using the imports in this file: from rx.notification import Notification from rx.observable import PushToPullAdapter import rx.linq.sink and context (functions, classes, or occasionally code) from other files: # Path: rx/notification.py # class Notification(object): # """Represents a notification to an observer.""" # # KIND_NEXT = 0 # KIND_ERROR = 1 # KIND_COMPLETED = 2 # # def __eq__(self, other): # if not isinstance(other, Notification): # return False # # return ( # self.kind == other.kind and # self.value == other.value and # self.hasValue == other.hasValue and # self.exception == other.exception # ) # # def accept(self, observerOrOnNext, onError=None, onCompleted=None): # """Accepts an observer or the methods onNext, onError, onCompleted and invokes # either onNext, onError, onCompleted depending on which type of :class:`Notification` # it is. This is an abstract method that is implemented by # :class:`OnNextNotification`, :class:`OnErrorNotification`, # and :class:`OnCompletedNotification`.""" # # if observerOrOnNext == None or hasattr(observerOrOnNext, '__call__'): # # observer = Observer.create(observerOrOnNext, onError, onComplete) # raise NotImplementedError() # # @staticmethod # def createOnNext(value): # return OnNextNotification(value) # # @staticmethod # def createOnError(exception): # return OnErrorNotification(exception) # # @staticmethod # def createOnCompleted(): # return OnCompletedNotification() # # Path: rx/observable.py # class PushToPullAdapter(object): # def __init__(self, source): # self.source = source # # def __iter__(self): # d = SingleAssignmentDisposable() # res = self.run(d) # d.disposable = self.source.subscribeSafe(res) # return res # # def run(self, subscription): # raise NotImplementedError() . Output only the next line.
self.kind = Notification.KIND_NEXT
Using the snippet: <|code_start|> class TakeLastCount(Producer): def __init__(self, source, count, scheduler): self.source = source self.count = count self.scheduler = scheduler def run(self, observer, cancel, setSink): sink = self.Sink(self, observer, cancel) setSink(sink) return sink.run() class Sink(rx.linq.sink.Sink): def __init__(self, parent, observer, cancel): super(TakeLastCount.Sink, self).__init__(observer, cancel) self.parent = parent self.queue = deque() def run(self): self.subscription = SingleAssignmentDisposable() self.loopDisposable = SingleAssignmentDisposable() self.subscription.disposable = self.parent.source.subscribeSafe(self) <|code_end|> , determine the next line of code. You have imports: from rx.disposable import CompositeDisposable, SingleAssignmentDisposable from rx.internal import Struct from rx.observable import Producer from collections import deque import rx.linq.sink and context (class names, function names, or code) available: # Path: rx/disposable.py # class CompositeDisposable(Cancelable): # """Represents a group of disposable resources that # are disposed together""" # # def __init__(self, *disposables): # super(CompositeDisposable, self).__init__() # # if len(disposables) == 0: # self.disposables = [] # elif len(disposables) == 1 and not isinstance(disposables[0], Disposable): # self.disposables = [d for d in disposables[0] if d != None] # else: # self.disposables = [d for d in disposables if d != None] # # self.length = len(self.disposables) # # def add(self, disposable): # shouldDispose = False # # with self.lock: # shouldDispose = self.isDisposed # # if not shouldDispose: # self.disposables.append(disposable) # self.length += 1 # # if shouldDispose: # disposable.dispose() # # def contains(self, disposable): # with self.lock: # return self.disposables.index(disposable) >= 0 # # def remove(self, disposable): # shouldDispose = False # # with self.lock: # if self.isDisposed: # return False # # index = self.disposables.index(disposable) # # if index < 0: # return False # # shouldDispose = True # # self.disposables.remove(disposable) # self.length -= 1 # # if shouldDispose: # disposable.dispose() # # return shouldDispose # # def clear(self): # disposables = [] # # with self.lock: # disposables = self.disposables # self.disposables = [] # self.length = 0 # # for disposable in disposables: # disposable.dispose() # # def dispose(self): # if not self._isDisposed.exchange(True): # self.clear() # # class SingleAssignmentDisposable(Cancelable): # """Represents a disposable resource which only allows # a single assignment of its underlying disposable resource. # If an underlying disposable resource has already been set, # future attempts to set the underlying disposable resource # will throw an Error.""" # # def __init__(self): # super(SingleAssignmentDisposable, self).__init__() # self.current = None # # def disposable(): # def fget(self): # with self.lock: # if self.isDisposed: # return Disposable.empty() # else: # return self.current # def fset(self, value): # old = self.current # self.current = value # # if old != None: raise Exception("Disposable has already been assigned") # # if self.isDisposed and value != None: value.dispose() # return locals() # # disposable = property(**disposable()) # # def dispose(self): # if not self._isDisposed.exchange(True): # if self.current != None: # self.current.dispose() # # Path: rx/internal.py # class Struct(object): # def __init__(self, **entries): # self.__dict__.update(entries) # # def __eq__(self, other): # if not isinstance(other, Struct): # return False # # return self.__dict__ == other.__dict__ # # def __repr__(self): # return repr(self.__dict__) # # Path: rx/observable.py # class Producer(Observable): # """Base class for implementation of query operators, providing # performance benefits over the use of Observable.Create""" # # def subscribeCore(self, observer): # return self.subscribeRaw(observer, True) # # def subscribeRaw(self, observer, enableSafequard): # sink = SingleAssignmentDisposable() # subscription = SingleAssignmentDisposable() # # d = CompositeDisposable(sink, subscription) # # if enableSafequard: # observer = AutoDetachObserver(observer, d) # # def assignSink(s): # sink.disposable = s # # def scheduled(): # subscription.disposable = self.run(observer, subscription, assignSink) # return Disposable.empty() # # if Scheduler.currentThread.isScheduleRequired(): # Scheduler.currentThread.schedule(scheduled) # else: # scheduled() # # return d # # def run(self, observer, cancel, setSink): # raise NotImplementedError() . Output only the next line.
return CompositeDisposable(self.subscription, self.loopDisposable)
Based on the snippet: <|code_start|> class TakeLastCount(Producer): def __init__(self, source, count, scheduler): self.source = source self.count = count self.scheduler = scheduler def run(self, observer, cancel, setSink): sink = self.Sink(self, observer, cancel) setSink(sink) return sink.run() class Sink(rx.linq.sink.Sink): def __init__(self, parent, observer, cancel): super(TakeLastCount.Sink, self).__init__(observer, cancel) self.parent = parent self.queue = deque() def run(self): <|code_end|> , predict the immediate next line with the help of imports: from rx.disposable import CompositeDisposable, SingleAssignmentDisposable from rx.internal import Struct from rx.observable import Producer from collections import deque import rx.linq.sink and context (classes, functions, sometimes code) from other files: # Path: rx/disposable.py # class CompositeDisposable(Cancelable): # """Represents a group of disposable resources that # are disposed together""" # # def __init__(self, *disposables): # super(CompositeDisposable, self).__init__() # # if len(disposables) == 0: # self.disposables = [] # elif len(disposables) == 1 and not isinstance(disposables[0], Disposable): # self.disposables = [d for d in disposables[0] if d != None] # else: # self.disposables = [d for d in disposables if d != None] # # self.length = len(self.disposables) # # def add(self, disposable): # shouldDispose = False # # with self.lock: # shouldDispose = self.isDisposed # # if not shouldDispose: # self.disposables.append(disposable) # self.length += 1 # # if shouldDispose: # disposable.dispose() # # def contains(self, disposable): # with self.lock: # return self.disposables.index(disposable) >= 0 # # def remove(self, disposable): # shouldDispose = False # # with self.lock: # if self.isDisposed: # return False # # index = self.disposables.index(disposable) # # if index < 0: # return False # # shouldDispose = True # # self.disposables.remove(disposable) # self.length -= 1 # # if shouldDispose: # disposable.dispose() # # return shouldDispose # # def clear(self): # disposables = [] # # with self.lock: # disposables = self.disposables # self.disposables = [] # self.length = 0 # # for disposable in disposables: # disposable.dispose() # # def dispose(self): # if not self._isDisposed.exchange(True): # self.clear() # # class SingleAssignmentDisposable(Cancelable): # """Represents a disposable resource which only allows # a single assignment of its underlying disposable resource. # If an underlying disposable resource has already been set, # future attempts to set the underlying disposable resource # will throw an Error.""" # # def __init__(self): # super(SingleAssignmentDisposable, self).__init__() # self.current = None # # def disposable(): # def fget(self): # with self.lock: # if self.isDisposed: # return Disposable.empty() # else: # return self.current # def fset(self, value): # old = self.current # self.current = value # # if old != None: raise Exception("Disposable has already been assigned") # # if self.isDisposed and value != None: value.dispose() # return locals() # # disposable = property(**disposable()) # # def dispose(self): # if not self._isDisposed.exchange(True): # if self.current != None: # self.current.dispose() # # Path: rx/internal.py # class Struct(object): # def __init__(self, **entries): # self.__dict__.update(entries) # # def __eq__(self, other): # if not isinstance(other, Struct): # return False # # return self.__dict__ == other.__dict__ # # def __repr__(self): # return repr(self.__dict__) # # Path: rx/observable.py # class Producer(Observable): # """Base class for implementation of query operators, providing # performance benefits over the use of Observable.Create""" # # def subscribeCore(self, observer): # return self.subscribeRaw(observer, True) # # def subscribeRaw(self, observer, enableSafequard): # sink = SingleAssignmentDisposable() # subscription = SingleAssignmentDisposable() # # d = CompositeDisposable(sink, subscription) # # if enableSafequard: # observer = AutoDetachObserver(observer, d) # # def assignSink(s): # sink.disposable = s # # def scheduled(): # subscription.disposable = self.run(observer, subscription, assignSink) # return Disposable.empty() # # if Scheduler.currentThread.isScheduleRequired(): # Scheduler.currentThread.schedule(scheduled) # else: # scheduled() # # return d # # def run(self, observer, cancel, setSink): # raise NotImplementedError() . Output only the next line.
self.subscription = SingleAssignmentDisposable()
Given the code snippet: <|code_start|> return sink.run() class Sink(rx.linq.sink.Sink): def __init__(self, parent, observer, cancel): super(TakeLastTime.Sink, self).__init__(observer, cancel) self.parent = parent def run(self): self.subscription = SingleAssignmentDisposable() self.loop = SingleAssignmentDisposable() self.startTime = self.parent.scheduler.now() self.subscription.disposable = self.parent.source.subscribeSafe(self) return CompositeDisposable(self.subscription, self.loop) def elapsed(self): return self.parent.scheduler.now() - self.startTime def trim(self, now): while len(self.queue) > 0: current = self.queue.popleft() if current.interval < self.parent.duration: self.queue.appendleft(current) break def onNext(self, value): now = self.elapsed() <|code_end|> , generate the next line using the imports in this file: from rx.disposable import CompositeDisposable, SingleAssignmentDisposable from rx.internal import Struct from rx.observable import Producer from collections import deque import rx.linq.sink and context (functions, classes, or occasionally code) from other files: # Path: rx/disposable.py # class CompositeDisposable(Cancelable): # """Represents a group of disposable resources that # are disposed together""" # # def __init__(self, *disposables): # super(CompositeDisposable, self).__init__() # # if len(disposables) == 0: # self.disposables = [] # elif len(disposables) == 1 and not isinstance(disposables[0], Disposable): # self.disposables = [d for d in disposables[0] if d != None] # else: # self.disposables = [d for d in disposables if d != None] # # self.length = len(self.disposables) # # def add(self, disposable): # shouldDispose = False # # with self.lock: # shouldDispose = self.isDisposed # # if not shouldDispose: # self.disposables.append(disposable) # self.length += 1 # # if shouldDispose: # disposable.dispose() # # def contains(self, disposable): # with self.lock: # return self.disposables.index(disposable) >= 0 # # def remove(self, disposable): # shouldDispose = False # # with self.lock: # if self.isDisposed: # return False # # index = self.disposables.index(disposable) # # if index < 0: # return False # # shouldDispose = True # # self.disposables.remove(disposable) # self.length -= 1 # # if shouldDispose: # disposable.dispose() # # return shouldDispose # # def clear(self): # disposables = [] # # with self.lock: # disposables = self.disposables # self.disposables = [] # self.length = 0 # # for disposable in disposables: # disposable.dispose() # # def dispose(self): # if not self._isDisposed.exchange(True): # self.clear() # # class SingleAssignmentDisposable(Cancelable): # """Represents a disposable resource which only allows # a single assignment of its underlying disposable resource. # If an underlying disposable resource has already been set, # future attempts to set the underlying disposable resource # will throw an Error.""" # # def __init__(self): # super(SingleAssignmentDisposable, self).__init__() # self.current = None # # def disposable(): # def fget(self): # with self.lock: # if self.isDisposed: # return Disposable.empty() # else: # return self.current # def fset(self, value): # old = self.current # self.current = value # # if old != None: raise Exception("Disposable has already been assigned") # # if self.isDisposed and value != None: value.dispose() # return locals() # # disposable = property(**disposable()) # # def dispose(self): # if not self._isDisposed.exchange(True): # if self.current != None: # self.current.dispose() # # Path: rx/internal.py # class Struct(object): # def __init__(self, **entries): # self.__dict__.update(entries) # # def __eq__(self, other): # if not isinstance(other, Struct): # return False # # return self.__dict__ == other.__dict__ # # def __repr__(self): # return repr(self.__dict__) # # Path: rx/observable.py # class Producer(Observable): # """Base class for implementation of query operators, providing # performance benefits over the use of Observable.Create""" # # def subscribeCore(self, observer): # return self.subscribeRaw(observer, True) # # def subscribeRaw(self, observer, enableSafequard): # sink = SingleAssignmentDisposable() # subscription = SingleAssignmentDisposable() # # d = CompositeDisposable(sink, subscription) # # if enableSafequard: # observer = AutoDetachObserver(observer, d) # # def assignSink(s): # sink.disposable = s # # def scheduled(): # subscription.disposable = self.run(observer, subscription, assignSink) # return Disposable.empty() # # if Scheduler.currentThread.isScheduleRequired(): # Scheduler.currentThread.schedule(scheduled) # else: # scheduled() # # return d # # def run(self, observer, cancel, setSink): # raise NotImplementedError() . Output only the next line.
self.queue.append(Struct(value=value,interval=now))
Predict the next line for this snippet: <|code_start|> class TakeLastBufferCount(Producer): def __init__(self, source, count): self.source = source self.count = count def run(self, observer, cancel, setSink): sink = self.Sink(self, observer, cancel) setSink(sink) return sink.run() class Sink(rx.linq.sink.Sink): def __init__(self, parent, observer, cancel): super(TakeLastBufferCount.Sink, self).__init__(observer, cancel) self.parent = parent self.queue = deque() def run(self): self.subscription = SingleAssignmentDisposable() self.loop = SingleAssignmentDisposable() self.subscription.disposable = self.parent.source.subscribeSafe(self) <|code_end|> with the help of current file imports: from rx.disposable import CompositeDisposable, SingleAssignmentDisposable from rx.internal import Struct from rx.observable import Producer from collections import deque import rx.linq.sink and context from other files: # Path: rx/disposable.py # class CompositeDisposable(Cancelable): # """Represents a group of disposable resources that # are disposed together""" # # def __init__(self, *disposables): # super(CompositeDisposable, self).__init__() # # if len(disposables) == 0: # self.disposables = [] # elif len(disposables) == 1 and not isinstance(disposables[0], Disposable): # self.disposables = [d for d in disposables[0] if d != None] # else: # self.disposables = [d for d in disposables if d != None] # # self.length = len(self.disposables) # # def add(self, disposable): # shouldDispose = False # # with self.lock: # shouldDispose = self.isDisposed # # if not shouldDispose: # self.disposables.append(disposable) # self.length += 1 # # if shouldDispose: # disposable.dispose() # # def contains(self, disposable): # with self.lock: # return self.disposables.index(disposable) >= 0 # # def remove(self, disposable): # shouldDispose = False # # with self.lock: # if self.isDisposed: # return False # # index = self.disposables.index(disposable) # # if index < 0: # return False # # shouldDispose = True # # self.disposables.remove(disposable) # self.length -= 1 # # if shouldDispose: # disposable.dispose() # # return shouldDispose # # def clear(self): # disposables = [] # # with self.lock: # disposables = self.disposables # self.disposables = [] # self.length = 0 # # for disposable in disposables: # disposable.dispose() # # def dispose(self): # if not self._isDisposed.exchange(True): # self.clear() # # class SingleAssignmentDisposable(Cancelable): # """Represents a disposable resource which only allows # a single assignment of its underlying disposable resource. # If an underlying disposable resource has already been set, # future attempts to set the underlying disposable resource # will throw an Error.""" # # def __init__(self): # super(SingleAssignmentDisposable, self).__init__() # self.current = None # # def disposable(): # def fget(self): # with self.lock: # if self.isDisposed: # return Disposable.empty() # else: # return self.current # def fset(self, value): # old = self.current # self.current = value # # if old != None: raise Exception("Disposable has already been assigned") # # if self.isDisposed and value != None: value.dispose() # return locals() # # disposable = property(**disposable()) # # def dispose(self): # if not self._isDisposed.exchange(True): # if self.current != None: # self.current.dispose() # # Path: rx/internal.py # class Struct(object): # def __init__(self, **entries): # self.__dict__.update(entries) # # def __eq__(self, other): # if not isinstance(other, Struct): # return False # # return self.__dict__ == other.__dict__ # # def __repr__(self): # return repr(self.__dict__) # # Path: rx/observable.py # class Producer(Observable): # """Base class for implementation of query operators, providing # performance benefits over the use of Observable.Create""" # # def subscribeCore(self, observer): # return self.subscribeRaw(observer, True) # # def subscribeRaw(self, observer, enableSafequard): # sink = SingleAssignmentDisposable() # subscription = SingleAssignmentDisposable() # # d = CompositeDisposable(sink, subscription) # # if enableSafequard: # observer = AutoDetachObserver(observer, d) # # def assignSink(s): # sink.disposable = s # # def scheduled(): # subscription.disposable = self.run(observer, subscription, assignSink) # return Disposable.empty() # # if Scheduler.currentThread.isScheduleRequired(): # Scheduler.currentThread.schedule(scheduled) # else: # scheduled() # # return d # # def run(self, observer, cancel, setSink): # raise NotImplementedError() , which may contain function names, class names, or code. Output only the next line.
return CompositeDisposable(self.subscription, self.loop)
Predict the next line after this snippet: <|code_start|> class TakeLastBufferCount(Producer): def __init__(self, source, count): self.source = source self.count = count def run(self, observer, cancel, setSink): sink = self.Sink(self, observer, cancel) setSink(sink) return sink.run() class Sink(rx.linq.sink.Sink): def __init__(self, parent, observer, cancel): super(TakeLastBufferCount.Sink, self).__init__(observer, cancel) self.parent = parent self.queue = deque() def run(self): <|code_end|> using the current file's imports: from rx.disposable import CompositeDisposable, SingleAssignmentDisposable from rx.internal import Struct from rx.observable import Producer from collections import deque import rx.linq.sink and any relevant context from other files: # Path: rx/disposable.py # class CompositeDisposable(Cancelable): # """Represents a group of disposable resources that # are disposed together""" # # def __init__(self, *disposables): # super(CompositeDisposable, self).__init__() # # if len(disposables) == 0: # self.disposables = [] # elif len(disposables) == 1 and not isinstance(disposables[0], Disposable): # self.disposables = [d for d in disposables[0] if d != None] # else: # self.disposables = [d for d in disposables if d != None] # # self.length = len(self.disposables) # # def add(self, disposable): # shouldDispose = False # # with self.lock: # shouldDispose = self.isDisposed # # if not shouldDispose: # self.disposables.append(disposable) # self.length += 1 # # if shouldDispose: # disposable.dispose() # # def contains(self, disposable): # with self.lock: # return self.disposables.index(disposable) >= 0 # # def remove(self, disposable): # shouldDispose = False # # with self.lock: # if self.isDisposed: # return False # # index = self.disposables.index(disposable) # # if index < 0: # return False # # shouldDispose = True # # self.disposables.remove(disposable) # self.length -= 1 # # if shouldDispose: # disposable.dispose() # # return shouldDispose # # def clear(self): # disposables = [] # # with self.lock: # disposables = self.disposables # self.disposables = [] # self.length = 0 # # for disposable in disposables: # disposable.dispose() # # def dispose(self): # if not self._isDisposed.exchange(True): # self.clear() # # class SingleAssignmentDisposable(Cancelable): # """Represents a disposable resource which only allows # a single assignment of its underlying disposable resource. # If an underlying disposable resource has already been set, # future attempts to set the underlying disposable resource # will throw an Error.""" # # def __init__(self): # super(SingleAssignmentDisposable, self).__init__() # self.current = None # # def disposable(): # def fget(self): # with self.lock: # if self.isDisposed: # return Disposable.empty() # else: # return self.current # def fset(self, value): # old = self.current # self.current = value # # if old != None: raise Exception("Disposable has already been assigned") # # if self.isDisposed and value != None: value.dispose() # return locals() # # disposable = property(**disposable()) # # def dispose(self): # if not self._isDisposed.exchange(True): # if self.current != None: # self.current.dispose() # # Path: rx/internal.py # class Struct(object): # def __init__(self, **entries): # self.__dict__.update(entries) # # def __eq__(self, other): # if not isinstance(other, Struct): # return False # # return self.__dict__ == other.__dict__ # # def __repr__(self): # return repr(self.__dict__) # # Path: rx/observable.py # class Producer(Observable): # """Base class for implementation of query operators, providing # performance benefits over the use of Observable.Create""" # # def subscribeCore(self, observer): # return self.subscribeRaw(observer, True) # # def subscribeRaw(self, observer, enableSafequard): # sink = SingleAssignmentDisposable() # subscription = SingleAssignmentDisposable() # # d = CompositeDisposable(sink, subscription) # # if enableSafequard: # observer = AutoDetachObserver(observer, d) # # def assignSink(s): # sink.disposable = s # # def scheduled(): # subscription.disposable = self.run(observer, subscription, assignSink) # return Disposable.empty() # # if Scheduler.currentThread.isScheduleRequired(): # Scheduler.currentThread.schedule(scheduled) # else: # scheduled() # # return d # # def run(self, observer, cancel, setSink): # raise NotImplementedError() . Output only the next line.
self.subscription = SingleAssignmentDisposable()
Predict the next line after this snippet: <|code_start|> return sink.run() class Sink(rx.linq.sink.Sink): def __init__(self, parent, observer, cancel): super(TakeLastBufferTime.Sink, self).__init__(observer, cancel) self.parent = parent def run(self): self.subscription = SingleAssignmentDisposable() self.loop = SingleAssignmentDisposable() self.startTime = self.parent.scheduler.now() self.subscription.disposable = self.parent.source.subscribeSafe(self) return CompositeDisposable(self.subscription, self.loop) def elapsed(self): return self.parent.scheduler.now() - self.startTime def trim(self, now): while len(self.queue) > 0: current = self.queue.popleft() if current.interval < self.parent.duration: self.queue.appendleft(current) break def onNext(self, value): now = self.elapsed() <|code_end|> using the current file's imports: from rx.disposable import CompositeDisposable, SingleAssignmentDisposable from rx.internal import Struct from rx.observable import Producer from collections import deque import rx.linq.sink and any relevant context from other files: # Path: rx/disposable.py # class CompositeDisposable(Cancelable): # """Represents a group of disposable resources that # are disposed together""" # # def __init__(self, *disposables): # super(CompositeDisposable, self).__init__() # # if len(disposables) == 0: # self.disposables = [] # elif len(disposables) == 1 and not isinstance(disposables[0], Disposable): # self.disposables = [d for d in disposables[0] if d != None] # else: # self.disposables = [d for d in disposables if d != None] # # self.length = len(self.disposables) # # def add(self, disposable): # shouldDispose = False # # with self.lock: # shouldDispose = self.isDisposed # # if not shouldDispose: # self.disposables.append(disposable) # self.length += 1 # # if shouldDispose: # disposable.dispose() # # def contains(self, disposable): # with self.lock: # return self.disposables.index(disposable) >= 0 # # def remove(self, disposable): # shouldDispose = False # # with self.lock: # if self.isDisposed: # return False # # index = self.disposables.index(disposable) # # if index < 0: # return False # # shouldDispose = True # # self.disposables.remove(disposable) # self.length -= 1 # # if shouldDispose: # disposable.dispose() # # return shouldDispose # # def clear(self): # disposables = [] # # with self.lock: # disposables = self.disposables # self.disposables = [] # self.length = 0 # # for disposable in disposables: # disposable.dispose() # # def dispose(self): # if not self._isDisposed.exchange(True): # self.clear() # # class SingleAssignmentDisposable(Cancelable): # """Represents a disposable resource which only allows # a single assignment of its underlying disposable resource. # If an underlying disposable resource has already been set, # future attempts to set the underlying disposable resource # will throw an Error.""" # # def __init__(self): # super(SingleAssignmentDisposable, self).__init__() # self.current = None # # def disposable(): # def fget(self): # with self.lock: # if self.isDisposed: # return Disposable.empty() # else: # return self.current # def fset(self, value): # old = self.current # self.current = value # # if old != None: raise Exception("Disposable has already been assigned") # # if self.isDisposed and value != None: value.dispose() # return locals() # # disposable = property(**disposable()) # # def dispose(self): # if not self._isDisposed.exchange(True): # if self.current != None: # self.current.dispose() # # Path: rx/internal.py # class Struct(object): # def __init__(self, **entries): # self.__dict__.update(entries) # # def __eq__(self, other): # if not isinstance(other, Struct): # return False # # return self.__dict__ == other.__dict__ # # def __repr__(self): # return repr(self.__dict__) # # Path: rx/observable.py # class Producer(Observable): # """Base class for implementation of query operators, providing # performance benefits over the use of Observable.Create""" # # def subscribeCore(self, observer): # return self.subscribeRaw(observer, True) # # def subscribeRaw(self, observer, enableSafequard): # sink = SingleAssignmentDisposable() # subscription = SingleAssignmentDisposable() # # d = CompositeDisposable(sink, subscription) # # if enableSafequard: # observer = AutoDetachObserver(observer, d) # # def assignSink(s): # sink.disposable = s # # def scheduled(): # subscription.disposable = self.run(observer, subscription, assignSink) # return Disposable.empty() # # if Scheduler.currentThread.isScheduleRequired(): # Scheduler.currentThread.schedule(scheduled) # else: # scheduled() # # return d # # def run(self, observer, cancel, setSink): # raise NotImplementedError() . Output only the next line.
self.queue.append(Struct(value=value,interval=now))
Predict the next line after this snippet: <|code_start|> class SequenceEqual(Producer): def __init__(self, left, right, equals): self.left = left self.right = right self.equals = equals def run(self, observer, cancel, setSink): <|code_end|> using the current file's imports: from rx.disposable import CompositeDisposable from rx.observable import Observable, Producer from rx.observer import Observer from collections import deque from threading import RLock import rx.linq.sink and any relevant context from other files: # Path: rx/disposable.py # class CompositeDisposable(Cancelable): # """Represents a group of disposable resources that # are disposed together""" # # def __init__(self, *disposables): # super(CompositeDisposable, self).__init__() # # if len(disposables) == 0: # self.disposables = [] # elif len(disposables) == 1 and not isinstance(disposables[0], Disposable): # self.disposables = [d for d in disposables[0] if d != None] # else: # self.disposables = [d for d in disposables if d != None] # # self.length = len(self.disposables) # # def add(self, disposable): # shouldDispose = False # # with self.lock: # shouldDispose = self.isDisposed # # if not shouldDispose: # self.disposables.append(disposable) # self.length += 1 # # if shouldDispose: # disposable.dispose() # # def contains(self, disposable): # with self.lock: # return self.disposables.index(disposable) >= 0 # # def remove(self, disposable): # shouldDispose = False # # with self.lock: # if self.isDisposed: # return False # # index = self.disposables.index(disposable) # # if index < 0: # return False # # shouldDispose = True # # self.disposables.remove(disposable) # self.length -= 1 # # if shouldDispose: # disposable.dispose() # # return shouldDispose # # def clear(self): # disposables = [] # # with self.lock: # disposables = self.disposables # self.disposables = [] # self.length = 0 # # for disposable in disposables: # disposable.dispose() # # def dispose(self): # if not self._isDisposed.exchange(True): # self.clear() # # Path: rx/observable.py # class Observable(object): # """Provides all extension methods to Observable""" # # def subscribe(self, observerOrOnNext=noop, onError=noop, onComplete=noop): # observer = observerOrOnNext # # if observerOrOnNext == None or callable(observerOrOnNext): # observer = Observer.create(observerOrOnNext, onError, onComplete) # # return self.subscribeCore(observer) # # def subscribeCore(self, observer): # raise NotImplementedError() # # def subscribeSafe(self, observer): # if isinstance(self, ObservableBase): # return self.subscribeCore(observer) # elif isinstance(self, Producer): # return self.subscribeRaw(observer, False) # # d = Disposable.empty() # # try: # d = self.subscribeCore(observer) # except Exception as e: # observer.onError(e) # # return d # # class Producer(Observable): # """Base class for implementation of query operators, providing # performance benefits over the use of Observable.Create""" # # def subscribeCore(self, observer): # return self.subscribeRaw(observer, True) # # def subscribeRaw(self, observer, enableSafequard): # sink = SingleAssignmentDisposable() # subscription = SingleAssignmentDisposable() # # d = CompositeDisposable(sink, subscription) # # if enableSafequard: # observer = AutoDetachObserver(observer, d) # # def assignSink(s): # sink.disposable = s # # def scheduled(): # subscription.disposable = self.run(observer, subscription, assignSink) # return Disposable.empty() # # if Scheduler.currentThread.isScheduleRequired(): # Scheduler.currentThread.schedule(scheduled) # else: # scheduled() # # return d # # def run(self, observer, cancel, setSink): # raise NotImplementedError() # # Path: rx/observer.py # class Observer(Disposable): # """Represents the IObserver Interface. # Has some static helper methods attached""" # # @staticmethod # def create(onNext=None, onError=None, onCompleted=None): # if onNext == None: # onNext = noop # if onError == None: # onError = defaultError # if onCompleted == None: # onCompleted = noop # # return AnonymousObserver(onNext, onError, onCompleted) # # @staticmethod # def synchronize(observer, lock=None): # if lock == None: # lock = RLock() # # return SynchronizedObserver(observer, lock) # # @staticmethod # def fromNotifier(handler): # return AnonymousObserver( # lambda x: handler(Notification.createOnNext(x)), # lambda ex: handler(Notification.createOnError(ex)), # lambda: handler(Notification.createOnCompleted()) # ) # # def toNotifier(self): # return lambda n: n.accept(self) # # def asObserver(self): # return AnonymousObserver(self.onNext, self.onError, self.onCompleted) # # def checked(self): # return CheckedObserver(self) # # def notifyOn(self, scheduler): # return ScheduledObserver(scheduler, self) # # def onNext(self, value): # raise NotImplementedError() # # def onError(self, exception): # raise NotImplementedError() # # def onCompleted(self): # raise NotImplementedError() . Output only the next line.
if isinstance(self.right, Observable):
Predict the next line for this snippet: <|code_start|> class ObserveOn(Producer): def __init__(self, source, scheduler): self.source = source self.scheduler = scheduler def run(self, observer, cancel, setSink): <|code_end|> with the help of current file imports: from rx.observable import Producer from rx.observer import ObserveOnObserver and context from other files: # Path: rx/observable.py # class Producer(Observable): # """Base class for implementation of query operators, providing # performance benefits over the use of Observable.Create""" # # def subscribeCore(self, observer): # return self.subscribeRaw(observer, True) # # def subscribeRaw(self, observer, enableSafequard): # sink = SingleAssignmentDisposable() # subscription = SingleAssignmentDisposable() # # d = CompositeDisposable(sink, subscription) # # if enableSafequard: # observer = AutoDetachObserver(observer, d) # # def assignSink(s): # sink.disposable = s # # def scheduled(): # subscription.disposable = self.run(observer, subscription, assignSink) # return Disposable.empty() # # if Scheduler.currentThread.isScheduleRequired(): # Scheduler.currentThread.schedule(scheduled) # else: # scheduled() # # return d # # def run(self, observer, cancel, setSink): # raise NotImplementedError() # # Path: rx/observer.py # class ObserveOnObserver(ScheduledObserver): # def __init__(self, scheduler, observer, cancel): # super(ObserveOnObserver, self).__init__(scheduler, observer) # self.cancel = Atomic(cancel, self.lock) # # def onNextCore(self, value): # super(ObserveOnObserver, self).onNextCore(value) # self.ensureActive() # # def onErrorCore(self, exception): # super(ObserveOnObserver, self).onErrorCore(exception) # self.ensureActive() # # def onCompletedCore(self): # super(ObserveOnObserver, self).onCompletedCore() # self.ensureActive() # # def dispose(self): # super(ObserveOnObserver, self).dispose() # # old = self.cancel.exchange(None) # # if old != None: # old.dispose() , which may contain function names, class names, or code. Output only the next line.
sink = ObserveOnObserver(self.scheduler, observer, cancel)
Next line prediction: <|code_start|> class Using(Producer): def __init__(self, resourceFactory, observableFactory): self.resourceFactory = resourceFactory self.observableFactory = observableFactory def run(self, observer, cancel, setSink): sink = self.Sink(self, observer, cancel) setSink(sink) return sink.run() class Sink(rx.linq.sink.Sink): def __init__(self, parent, observer, cancel): super(Using.Sink, self).__init__(observer, cancel) self.parent = parent def run(self): source = None disposable = Disposable.empty() try: resource = self.parent.resourceFactory() if resource != None: disposable = resource source = self.parent.observableFactory(resource) except Exception as e: <|code_end|> . Use current file imports: (from rx.disposable import CompositeDisposable, Disposable from rx.observable import Observable, Producer import rx.linq.sink) and context including class names, function names, or small code snippets from other files: # Path: rx/disposable.py # class CompositeDisposable(Cancelable): # """Represents a group of disposable resources that # are disposed together""" # # def __init__(self, *disposables): # super(CompositeDisposable, self).__init__() # # if len(disposables) == 0: # self.disposables = [] # elif len(disposables) == 1 and not isinstance(disposables[0], Disposable): # self.disposables = [d for d in disposables[0] if d != None] # else: # self.disposables = [d for d in disposables if d != None] # # self.length = len(self.disposables) # # def add(self, disposable): # shouldDispose = False # # with self.lock: # shouldDispose = self.isDisposed # # if not shouldDispose: # self.disposables.append(disposable) # self.length += 1 # # if shouldDispose: # disposable.dispose() # # def contains(self, disposable): # with self.lock: # return self.disposables.index(disposable) >= 0 # # def remove(self, disposable): # shouldDispose = False # # with self.lock: # if self.isDisposed: # return False # # index = self.disposables.index(disposable) # # if index < 0: # return False # # shouldDispose = True # # self.disposables.remove(disposable) # self.length -= 1 # # if shouldDispose: # disposable.dispose() # # return shouldDispose # # def clear(self): # disposables = [] # # with self.lock: # disposables = self.disposables # self.disposables = [] # self.length = 0 # # for disposable in disposables: # disposable.dispose() # # def dispose(self): # if not self._isDisposed.exchange(True): # self.clear() # # class Disposable(object): # """Represents a disposable object""" # # def dispose(self): # pass # # def __enter__(self): # return self # # def __exit__(self, exc_type, exc_value, traceback): # self.dispose() # # @staticmethod # def create(action): # return AnonymouseDisposable(action) # # @staticmethod # def empty(): # return disposableEmpty # # Path: rx/observable.py # class Observable(object): # """Provides all extension methods to Observable""" # # def subscribe(self, observerOrOnNext=noop, onError=noop, onComplete=noop): # observer = observerOrOnNext # # if observerOrOnNext == None or callable(observerOrOnNext): # observer = Observer.create(observerOrOnNext, onError, onComplete) # # return self.subscribeCore(observer) # # def subscribeCore(self, observer): # raise NotImplementedError() # # def subscribeSafe(self, observer): # if isinstance(self, ObservableBase): # return self.subscribeCore(observer) # elif isinstance(self, Producer): # return self.subscribeRaw(observer, False) # # d = Disposable.empty() # # try: # d = self.subscribeCore(observer) # except Exception as e: # observer.onError(e) # # return d # # class Producer(Observable): # """Base class for implementation of query operators, providing # performance benefits over the use of Observable.Create""" # # def subscribeCore(self, observer): # return self.subscribeRaw(observer, True) # # def subscribeRaw(self, observer, enableSafequard): # sink = SingleAssignmentDisposable() # subscription = SingleAssignmentDisposable() # # d = CompositeDisposable(sink, subscription) # # if enableSafequard: # observer = AutoDetachObserver(observer, d) # # def assignSink(s): # sink.disposable = s # # def scheduled(): # subscription.disposable = self.run(observer, subscription, assignSink) # return Disposable.empty() # # if Scheduler.currentThread.isScheduleRequired(): # Scheduler.currentThread.schedule(scheduled) # else: # scheduled() # # return d # # def run(self, observer, cancel, setSink): # raise NotImplementedError() . Output only the next line.
return CompositeDisposable(Observable.throw(e).subscribeSafe(self), disposable)
Using the snippet: <|code_start|> class Using(Producer): def __init__(self, resourceFactory, observableFactory): self.resourceFactory = resourceFactory self.observableFactory = observableFactory def run(self, observer, cancel, setSink): sink = self.Sink(self, observer, cancel) setSink(sink) return sink.run() class Sink(rx.linq.sink.Sink): def __init__(self, parent, observer, cancel): super(Using.Sink, self).__init__(observer, cancel) self.parent = parent def run(self): source = None <|code_end|> , determine the next line of code. You have imports: from rx.disposable import CompositeDisposable, Disposable from rx.observable import Observable, Producer import rx.linq.sink and context (class names, function names, or code) available: # Path: rx/disposable.py # class CompositeDisposable(Cancelable): # """Represents a group of disposable resources that # are disposed together""" # # def __init__(self, *disposables): # super(CompositeDisposable, self).__init__() # # if len(disposables) == 0: # self.disposables = [] # elif len(disposables) == 1 and not isinstance(disposables[0], Disposable): # self.disposables = [d for d in disposables[0] if d != None] # else: # self.disposables = [d for d in disposables if d != None] # # self.length = len(self.disposables) # # def add(self, disposable): # shouldDispose = False # # with self.lock: # shouldDispose = self.isDisposed # # if not shouldDispose: # self.disposables.append(disposable) # self.length += 1 # # if shouldDispose: # disposable.dispose() # # def contains(self, disposable): # with self.lock: # return self.disposables.index(disposable) >= 0 # # def remove(self, disposable): # shouldDispose = False # # with self.lock: # if self.isDisposed: # return False # # index = self.disposables.index(disposable) # # if index < 0: # return False # # shouldDispose = True # # self.disposables.remove(disposable) # self.length -= 1 # # if shouldDispose: # disposable.dispose() # # return shouldDispose # # def clear(self): # disposables = [] # # with self.lock: # disposables = self.disposables # self.disposables = [] # self.length = 0 # # for disposable in disposables: # disposable.dispose() # # def dispose(self): # if not self._isDisposed.exchange(True): # self.clear() # # class Disposable(object): # """Represents a disposable object""" # # def dispose(self): # pass # # def __enter__(self): # return self # # def __exit__(self, exc_type, exc_value, traceback): # self.dispose() # # @staticmethod # def create(action): # return AnonymouseDisposable(action) # # @staticmethod # def empty(): # return disposableEmpty # # Path: rx/observable.py # class Observable(object): # """Provides all extension methods to Observable""" # # def subscribe(self, observerOrOnNext=noop, onError=noop, onComplete=noop): # observer = observerOrOnNext # # if observerOrOnNext == None or callable(observerOrOnNext): # observer = Observer.create(observerOrOnNext, onError, onComplete) # # return self.subscribeCore(observer) # # def subscribeCore(self, observer): # raise NotImplementedError() # # def subscribeSafe(self, observer): # if isinstance(self, ObservableBase): # return self.subscribeCore(observer) # elif isinstance(self, Producer): # return self.subscribeRaw(observer, False) # # d = Disposable.empty() # # try: # d = self.subscribeCore(observer) # except Exception as e: # observer.onError(e) # # return d # # class Producer(Observable): # """Base class for implementation of query operators, providing # performance benefits over the use of Observable.Create""" # # def subscribeCore(self, observer): # return self.subscribeRaw(observer, True) # # def subscribeRaw(self, observer, enableSafequard): # sink = SingleAssignmentDisposable() # subscription = SingleAssignmentDisposable() # # d = CompositeDisposable(sink, subscription) # # if enableSafequard: # observer = AutoDetachObserver(observer, d) # # def assignSink(s): # sink.disposable = s # # def scheduled(): # subscription.disposable = self.run(observer, subscription, assignSink) # return Disposable.empty() # # if Scheduler.currentThread.isScheduleRequired(): # Scheduler.currentThread.schedule(scheduled) # else: # scheduled() # # return d # # def run(self, observer, cancel, setSink): # raise NotImplementedError() . Output only the next line.
disposable = Disposable.empty()
Using the snippet: <|code_start|> class Using(Producer): def __init__(self, resourceFactory, observableFactory): self.resourceFactory = resourceFactory self.observableFactory = observableFactory def run(self, observer, cancel, setSink): sink = self.Sink(self, observer, cancel) setSink(sink) return sink.run() class Sink(rx.linq.sink.Sink): def __init__(self, parent, observer, cancel): super(Using.Sink, self).__init__(observer, cancel) self.parent = parent def run(self): source = None disposable = Disposable.empty() try: resource = self.parent.resourceFactory() if resource != None: disposable = resource source = self.parent.observableFactory(resource) except Exception as e: <|code_end|> , determine the next line of code. You have imports: from rx.disposable import CompositeDisposable, Disposable from rx.observable import Observable, Producer import rx.linq.sink and context (class names, function names, or code) available: # Path: rx/disposable.py # class CompositeDisposable(Cancelable): # """Represents a group of disposable resources that # are disposed together""" # # def __init__(self, *disposables): # super(CompositeDisposable, self).__init__() # # if len(disposables) == 0: # self.disposables = [] # elif len(disposables) == 1 and not isinstance(disposables[0], Disposable): # self.disposables = [d for d in disposables[0] if d != None] # else: # self.disposables = [d for d in disposables if d != None] # # self.length = len(self.disposables) # # def add(self, disposable): # shouldDispose = False # # with self.lock: # shouldDispose = self.isDisposed # # if not shouldDispose: # self.disposables.append(disposable) # self.length += 1 # # if shouldDispose: # disposable.dispose() # # def contains(self, disposable): # with self.lock: # return self.disposables.index(disposable) >= 0 # # def remove(self, disposable): # shouldDispose = False # # with self.lock: # if self.isDisposed: # return False # # index = self.disposables.index(disposable) # # if index < 0: # return False # # shouldDispose = True # # self.disposables.remove(disposable) # self.length -= 1 # # if shouldDispose: # disposable.dispose() # # return shouldDispose # # def clear(self): # disposables = [] # # with self.lock: # disposables = self.disposables # self.disposables = [] # self.length = 0 # # for disposable in disposables: # disposable.dispose() # # def dispose(self): # if not self._isDisposed.exchange(True): # self.clear() # # class Disposable(object): # """Represents a disposable object""" # # def dispose(self): # pass # # def __enter__(self): # return self # # def __exit__(self, exc_type, exc_value, traceback): # self.dispose() # # @staticmethod # def create(action): # return AnonymouseDisposable(action) # # @staticmethod # def empty(): # return disposableEmpty # # Path: rx/observable.py # class Observable(object): # """Provides all extension methods to Observable""" # # def subscribe(self, observerOrOnNext=noop, onError=noop, onComplete=noop): # observer = observerOrOnNext # # if observerOrOnNext == None or callable(observerOrOnNext): # observer = Observer.create(observerOrOnNext, onError, onComplete) # # return self.subscribeCore(observer) # # def subscribeCore(self, observer): # raise NotImplementedError() # # def subscribeSafe(self, observer): # if isinstance(self, ObservableBase): # return self.subscribeCore(observer) # elif isinstance(self, Producer): # return self.subscribeRaw(observer, False) # # d = Disposable.empty() # # try: # d = self.subscribeCore(observer) # except Exception as e: # observer.onError(e) # # return d # # class Producer(Observable): # """Base class for implementation of query operators, providing # performance benefits over the use of Observable.Create""" # # def subscribeCore(self, observer): # return self.subscribeRaw(observer, True) # # def subscribeRaw(self, observer, enableSafequard): # sink = SingleAssignmentDisposable() # subscription = SingleAssignmentDisposable() # # d = CompositeDisposable(sink, subscription) # # if enableSafequard: # observer = AutoDetachObserver(observer, d) # # def assignSink(s): # sink.disposable = s # # def scheduled(): # subscription.disposable = self.run(observer, subscription, assignSink) # return Disposable.empty() # # if Scheduler.currentThread.isScheduleRequired(): # Scheduler.currentThread.schedule(scheduled) # else: # scheduled() # # return d # # def run(self, observer, cancel, setSink): # raise NotImplementedError() . Output only the next line.
return CompositeDisposable(Observable.throw(e).subscribeSafe(self), disposable)
Based on the snippet: <|code_start|> class ToObservable(Producer): def __init__(self, source, scheduler): self.source = source self.scheduler = scheduler def run(self, observer, cancel, setSink): sink = self.Sink(self, observer, cancel) setSink(sink) return sink.run() class Sink(rx.linq.sink.Sink): def __init__(self, parent, observer, cancel): super(ToObservable.Sink, self).__init__(observer, cancel) self.parent = parent def run(self): it = None try: it = iter(self.parent.source) except Exception as e: self.observer.onError(e) self.dispose() return Disposable.empty() scheduler = self.parent.scheduler if scheduler.isLongRunning: return scheduler.scheduleLongRunningWithState(it, self.loop) else: <|code_end|> , predict the immediate next line with the help of imports: from rx.disposable import BooleanDisposable, Disposable from rx.internal import Struct from rx.observable import Producer import rx.linq.sink and context (classes, functions, sometimes code) from other files: # Path: rx/disposable.py # class BooleanDisposable(Cancelable): # """Represents a disposable resource that # can be checked if it already has been disposed""" # # def __init__(self): # super(BooleanDisposable, self).__init__() # # def dispose(self): # self._isDisposed.exchange(True) # # class Disposable(object): # """Represents a disposable object""" # # def dispose(self): # pass # # def __enter__(self): # return self # # def __exit__(self, exc_type, exc_value, traceback): # self.dispose() # # @staticmethod # def create(action): # return AnonymouseDisposable(action) # # @staticmethod # def empty(): # return disposableEmpty # # Path: rx/internal.py # class Struct(object): # def __init__(self, **entries): # self.__dict__.update(entries) # # def __eq__(self, other): # if not isinstance(other, Struct): # return False # # return self.__dict__ == other.__dict__ # # def __repr__(self): # return repr(self.__dict__) # # Path: rx/observable.py # class Producer(Observable): # """Base class for implementation of query operators, providing # performance benefits over the use of Observable.Create""" # # def subscribeCore(self, observer): # return self.subscribeRaw(observer, True) # # def subscribeRaw(self, observer, enableSafequard): # sink = SingleAssignmentDisposable() # subscription = SingleAssignmentDisposable() # # d = CompositeDisposable(sink, subscription) # # if enableSafequard: # observer = AutoDetachObserver(observer, d) # # def assignSink(s): # sink.disposable = s # # def scheduled(): # subscription.disposable = self.run(observer, subscription, assignSink) # return Disposable.empty() # # if Scheduler.currentThread.isScheduleRequired(): # Scheduler.currentThread.schedule(scheduled) # else: # scheduled() # # return d # # def run(self, observer, cancel, setSink): # raise NotImplementedError() . Output only the next line.
flag = BooleanDisposable()
Here is a snippet: <|code_start|> class ToObservable(Producer): def __init__(self, source, scheduler): self.source = source self.scheduler = scheduler def run(self, observer, cancel, setSink): sink = self.Sink(self, observer, cancel) setSink(sink) return sink.run() class Sink(rx.linq.sink.Sink): def __init__(self, parent, observer, cancel): super(ToObservable.Sink, self).__init__(observer, cancel) self.parent = parent def run(self): it = None try: it = iter(self.parent.source) except Exception as e: self.observer.onError(e) self.dispose() <|code_end|> . Write the next line using the current file imports: from rx.disposable import BooleanDisposable, Disposable from rx.internal import Struct from rx.observable import Producer import rx.linq.sink and context from other files: # Path: rx/disposable.py # class BooleanDisposable(Cancelable): # """Represents a disposable resource that # can be checked if it already has been disposed""" # # def __init__(self): # super(BooleanDisposable, self).__init__() # # def dispose(self): # self._isDisposed.exchange(True) # # class Disposable(object): # """Represents a disposable object""" # # def dispose(self): # pass # # def __enter__(self): # return self # # def __exit__(self, exc_type, exc_value, traceback): # self.dispose() # # @staticmethod # def create(action): # return AnonymouseDisposable(action) # # @staticmethod # def empty(): # return disposableEmpty # # Path: rx/internal.py # class Struct(object): # def __init__(self, **entries): # self.__dict__.update(entries) # # def __eq__(self, other): # if not isinstance(other, Struct): # return False # # return self.__dict__ == other.__dict__ # # def __repr__(self): # return repr(self.__dict__) # # Path: rx/observable.py # class Producer(Observable): # """Base class for implementation of query operators, providing # performance benefits over the use of Observable.Create""" # # def subscribeCore(self, observer): # return self.subscribeRaw(observer, True) # # def subscribeRaw(self, observer, enableSafequard): # sink = SingleAssignmentDisposable() # subscription = SingleAssignmentDisposable() # # d = CompositeDisposable(sink, subscription) # # if enableSafequard: # observer = AutoDetachObserver(observer, d) # # def assignSink(s): # sink.disposable = s # # def scheduled(): # subscription.disposable = self.run(observer, subscription, assignSink) # return Disposable.empty() # # if Scheduler.currentThread.isScheduleRequired(): # Scheduler.currentThread.schedule(scheduled) # else: # scheduled() # # return d # # def run(self, observer, cancel, setSink): # raise NotImplementedError() , which may include functions, classes, or code. Output only the next line.
return Disposable.empty()
Given the following code snippet before the placeholder: <|code_start|>class ToObservable(Producer): def __init__(self, source, scheduler): self.source = source self.scheduler = scheduler def run(self, observer, cancel, setSink): sink = self.Sink(self, observer, cancel) setSink(sink) return sink.run() class Sink(rx.linq.sink.Sink): def __init__(self, parent, observer, cancel): super(ToObservable.Sink, self).__init__(observer, cancel) self.parent = parent def run(self): it = None try: it = iter(self.parent.source) except Exception as e: self.observer.onError(e) self.dispose() return Disposable.empty() scheduler = self.parent.scheduler if scheduler.isLongRunning: return scheduler.scheduleLongRunningWithState(it, self.loop) else: flag = BooleanDisposable() <|code_end|> , predict the next line using imports from the current file: from rx.disposable import BooleanDisposable, Disposable from rx.internal import Struct from rx.observable import Producer import rx.linq.sink and context including class names, function names, and sometimes code from other files: # Path: rx/disposable.py # class BooleanDisposable(Cancelable): # """Represents a disposable resource that # can be checked if it already has been disposed""" # # def __init__(self): # super(BooleanDisposable, self).__init__() # # def dispose(self): # self._isDisposed.exchange(True) # # class Disposable(object): # """Represents a disposable object""" # # def dispose(self): # pass # # def __enter__(self): # return self # # def __exit__(self, exc_type, exc_value, traceback): # self.dispose() # # @staticmethod # def create(action): # return AnonymouseDisposable(action) # # @staticmethod # def empty(): # return disposableEmpty # # Path: rx/internal.py # class Struct(object): # def __init__(self, **entries): # self.__dict__.update(entries) # # def __eq__(self, other): # if not isinstance(other, Struct): # return False # # return self.__dict__ == other.__dict__ # # def __repr__(self): # return repr(self.__dict__) # # Path: rx/observable.py # class Producer(Observable): # """Base class for implementation of query operators, providing # performance benefits over the use of Observable.Create""" # # def subscribeCore(self, observer): # return self.subscribeRaw(observer, True) # # def subscribeRaw(self, observer, enableSafequard): # sink = SingleAssignmentDisposable() # subscription = SingleAssignmentDisposable() # # d = CompositeDisposable(sink, subscription) # # if enableSafequard: # observer = AutoDetachObserver(observer, d) # # def assignSink(s): # sink.disposable = s # # def scheduled(): # subscription.disposable = self.run(observer, subscription, assignSink) # return Disposable.empty() # # if Scheduler.currentThread.isScheduleRequired(): # Scheduler.currentThread.schedule(scheduled) # else: # scheduled() # # return d # # def run(self, observer, cancel, setSink): # raise NotImplementedError() . Output only the next line.
scheduler.scheduleRecursiveWithState(Struct(flag=flag, it=it), self.loopRec)
Using the snippet: <|code_start|> class ForEach(Producer): class Sink(Observer): def __init__(self, onNext, done): self.onNextAction = onNext self.doneAction = done <|code_end|> , determine the next line of code. You have imports: from rx.observable import Producer from rx.observer import Observer from rx.concurrency import Atomic and context (class names, function names, or code) available: # Path: rx/observable.py # class Producer(Observable): # """Base class for implementation of query operators, providing # performance benefits over the use of Observable.Create""" # # def subscribeCore(self, observer): # return self.subscribeRaw(observer, True) # # def subscribeRaw(self, observer, enableSafequard): # sink = SingleAssignmentDisposable() # subscription = SingleAssignmentDisposable() # # d = CompositeDisposable(sink, subscription) # # if enableSafequard: # observer = AutoDetachObserver(observer, d) # # def assignSink(s): # sink.disposable = s # # def scheduled(): # subscription.disposable = self.run(observer, subscription, assignSink) # return Disposable.empty() # # if Scheduler.currentThread.isScheduleRequired(): # Scheduler.currentThread.schedule(scheduled) # else: # scheduled() # # return d # # def run(self, observer, cancel, setSink): # raise NotImplementedError() # # Path: rx/observer.py # class Observer(Disposable): # """Represents the IObserver Interface. # Has some static helper methods attached""" # # @staticmethod # def create(onNext=None, onError=None, onCompleted=None): # if onNext == None: # onNext = noop # if onError == None: # onError = defaultError # if onCompleted == None: # onCompleted = noop # # return AnonymousObserver(onNext, onError, onCompleted) # # @staticmethod # def synchronize(observer, lock=None): # if lock == None: # lock = RLock() # # return SynchronizedObserver(observer, lock) # # @staticmethod # def fromNotifier(handler): # return AnonymousObserver( # lambda x: handler(Notification.createOnNext(x)), # lambda ex: handler(Notification.createOnError(ex)), # lambda: handler(Notification.createOnCompleted()) # ) # # def toNotifier(self): # return lambda n: n.accept(self) # # def asObserver(self): # return AnonymousObserver(self.onNext, self.onError, self.onCompleted) # # def checked(self): # return CheckedObserver(self) # # def notifyOn(self, scheduler): # return ScheduledObserver(scheduler, self) # # def onNext(self, value): # raise NotImplementedError() # # def onError(self, exception): # raise NotImplementedError() # # def onCompleted(self): # raise NotImplementedError() # # Path: rx/concurrency.py # class Atomic: # def __init__(self, value=None, lock=RLock()): # self.lock = lock # self._value = value # # def value(): # doc = "The value property." # def fget(self): # return self._value # def fset(self, value): # self.exchange(value) # return locals() # value = property(**value()) # # def exchange(self, value): # with self.lock: # old = self._value # self._value = value # return old # # def compareExchange(self, value, expected): # with self.lock: # old = self._value # # if old == expected: # self._value = value # # return old # # def inc(self, by=1): # with self.lock: # self._value += by # return self.value # # def dec(self, by=1): # with self.lock: # self._value -= by # return self.value . Output only the next line.
self.stopped = Atomic(False)
Next line prediction: <|code_start|> class Materialize(Producer): def __init__(self, source): self.source = source def dematerialize(self): return self.source.asObservable() def run(self, observer, cancel, setSink): sink = self.Sink(observer, cancel) setSink(sink) return self.source.subscribeSafe(sink) class Sink(rx.linq.sink.Sink): def __init__(self, observer, cancel): super(Materialize.Sink, self).__init__(observer, cancel) def onNext(self, value): <|code_end|> . Use current file imports: (from rx.notification import Notification from rx.observable import Producer import rx.linq.sink) and context including class names, function names, or small code snippets from other files: # Path: rx/notification.py # class Notification(object): # """Represents a notification to an observer.""" # # KIND_NEXT = 0 # KIND_ERROR = 1 # KIND_COMPLETED = 2 # # def __eq__(self, other): # if not isinstance(other, Notification): # return False # # return ( # self.kind == other.kind and # self.value == other.value and # self.hasValue == other.hasValue and # self.exception == other.exception # ) # # def accept(self, observerOrOnNext, onError=None, onCompleted=None): # """Accepts an observer or the methods onNext, onError, onCompleted and invokes # either onNext, onError, onCompleted depending on which type of :class:`Notification` # it is. This is an abstract method that is implemented by # :class:`OnNextNotification`, :class:`OnErrorNotification`, # and :class:`OnCompletedNotification`.""" # # if observerOrOnNext == None or hasattr(observerOrOnNext, '__call__'): # # observer = Observer.create(observerOrOnNext, onError, onComplete) # raise NotImplementedError() # # @staticmethod # def createOnNext(value): # return OnNextNotification(value) # # @staticmethod # def createOnError(exception): # return OnErrorNotification(exception) # # @staticmethod # def createOnCompleted(): # return OnCompletedNotification() # # Path: rx/observable.py # class Producer(Observable): # """Base class for implementation of query operators, providing # performance benefits over the use of Observable.Create""" # # def subscribeCore(self, observer): # return self.subscribeRaw(observer, True) # # def subscribeRaw(self, observer, enableSafequard): # sink = SingleAssignmentDisposable() # subscription = SingleAssignmentDisposable() # # d = CompositeDisposable(sink, subscription) # # if enableSafequard: # observer = AutoDetachObserver(observer, d) # # def assignSink(s): # sink.disposable = s # # def scheduled(): # subscription.disposable = self.run(observer, subscription, assignSink) # return Disposable.empty() # # if Scheduler.currentThread.isScheduleRequired(): # Scheduler.currentThread.schedule(scheduled) # else: # scheduled() # # return d # # def run(self, observer, cancel, setSink): # raise NotImplementedError() . Output only the next line.
self.observer.onNext(Notification.createOnNext(value))
Given the code snippet: <|code_start|> class TimeStamp(Producer): def __init__(self, source, scheduler): self.source = source self.scheduler = scheduler def run(self, observer, cancel, setSink): sink = self.Sink(self, observer, cancel) setSink(sink) return self.source.subscribeSafe(sink) class Sink(rx.linq.sink.Sink): def __init__(self, parent, observer, cancel): super(TimeStamp.Sink, self).__init__(observer, cancel) self.parent = parent def onNext(self, value): <|code_end|> , generate the next line using the imports in this file: from rx.internal import Struct from rx.observable import Producer import rx.linq.sink and context (functions, classes, or occasionally code) from other files: # Path: rx/internal.py # class Struct(object): # def __init__(self, **entries): # self.__dict__.update(entries) # # def __eq__(self, other): # if not isinstance(other, Struct): # return False # # return self.__dict__ == other.__dict__ # # def __repr__(self): # return repr(self.__dict__) # # Path: rx/observable.py # class Producer(Observable): # """Base class for implementation of query operators, providing # performance benefits over the use of Observable.Create""" # # def subscribeCore(self, observer): # return self.subscribeRaw(observer, True) # # def subscribeRaw(self, observer, enableSafequard): # sink = SingleAssignmentDisposable() # subscription = SingleAssignmentDisposable() # # d = CompositeDisposable(sink, subscription) # # if enableSafequard: # observer = AutoDetachObserver(observer, d) # # def assignSink(s): # sink.disposable = s # # def scheduled(): # subscription.disposable = self.run(observer, subscription, assignSink) # return Disposable.empty() # # if Scheduler.currentThread.isScheduleRequired(): # Scheduler.currentThread.schedule(scheduled) # else: # scheduled() # # return d # # def run(self, observer, cancel, setSink): # raise NotImplementedError() . Output only the next line.
self.observer.onNext(Struct(value=value, timestamp=self.parent.scheduler.now()))
Predict the next line after this snippet: <|code_start|> class GetIterator(Observer): def __init__(self): self.queue = Queue() self.gate = Semaphore(0) <|code_end|> using the current file's imports: from rx.disposable import SingleAssignmentDisposable from rx.exceptions import DisposedException from rx.observer import Observer from queue import Empty, Queue from threading import Semaphore import rx.linq.sink and any relevant context from other files: # Path: rx/disposable.py # class SingleAssignmentDisposable(Cancelable): # """Represents a disposable resource which only allows # a single assignment of its underlying disposable resource. # If an underlying disposable resource has already been set, # future attempts to set the underlying disposable resource # will throw an Error.""" # # def __init__(self): # super(SingleAssignmentDisposable, self).__init__() # self.current = None # # def disposable(): # def fget(self): # with self.lock: # if self.isDisposed: # return Disposable.empty() # else: # return self.current # def fset(self, value): # old = self.current # self.current = value # # if old != None: raise Exception("Disposable has already been assigned") # # if self.isDisposed and value != None: value.dispose() # return locals() # # disposable = property(**disposable()) # # def dispose(self): # if not self._isDisposed.exchange(True): # if self.current != None: # self.current.dispose() # # Path: rx/exceptions.py # class DisposedException(Exception): # def __init__(self): # super(DisposedException, self).__init__("Object already disposed") # # Path: rx/observer.py # class Observer(Disposable): # """Represents the IObserver Interface. # Has some static helper methods attached""" # # @staticmethod # def create(onNext=None, onError=None, onCompleted=None): # if onNext == None: # onNext = noop # if onError == None: # onError = defaultError # if onCompleted == None: # onCompleted = noop # # return AnonymousObserver(onNext, onError, onCompleted) # # @staticmethod # def synchronize(observer, lock=None): # if lock == None: # lock = RLock() # # return SynchronizedObserver(observer, lock) # # @staticmethod # def fromNotifier(handler): # return AnonymousObserver( # lambda x: handler(Notification.createOnNext(x)), # lambda ex: handler(Notification.createOnError(ex)), # lambda: handler(Notification.createOnCompleted()) # ) # # def toNotifier(self): # return lambda n: n.accept(self) # # def asObserver(self): # return AnonymousObserver(self.onNext, self.onError, self.onCompleted) # # def checked(self): # return CheckedObserver(self) # # def notifyOn(self, scheduler): # return ScheduledObserver(scheduler, self) # # def onNext(self, value): # raise NotImplementedError() # # def onError(self, exception): # raise NotImplementedError() # # def onCompleted(self): # raise NotImplementedError() . Output only the next line.
self.subscription = SingleAssignmentDisposable()
Predict the next line for this snippet: <|code_start|> self.error = None self.done = False self.disposed = False def run(self, source): # [OK] Use of unsafe Subscribe: non-pretentious exact mirror with the dual GetEnumerator method. self.subscription.disposable = source.subscribe(self) return self def onNext(self, value): self.queue.put(value) self.gate.release() def onError(self, exception): self.error = exception self.subscription.dispose() self.gate.release() def onCompleted(self): self.done = True self.subscription.dispose() self.gate.release() def __iter__(self): return self def __next__(self): self.gate.acquire() if self.disposed: <|code_end|> with the help of current file imports: from rx.disposable import SingleAssignmentDisposable from rx.exceptions import DisposedException from rx.observer import Observer from queue import Empty, Queue from threading import Semaphore import rx.linq.sink and context from other files: # Path: rx/disposable.py # class SingleAssignmentDisposable(Cancelable): # """Represents a disposable resource which only allows # a single assignment of its underlying disposable resource. # If an underlying disposable resource has already been set, # future attempts to set the underlying disposable resource # will throw an Error.""" # # def __init__(self): # super(SingleAssignmentDisposable, self).__init__() # self.current = None # # def disposable(): # def fget(self): # with self.lock: # if self.isDisposed: # return Disposable.empty() # else: # return self.current # def fset(self, value): # old = self.current # self.current = value # # if old != None: raise Exception("Disposable has already been assigned") # # if self.isDisposed and value != None: value.dispose() # return locals() # # disposable = property(**disposable()) # # def dispose(self): # if not self._isDisposed.exchange(True): # if self.current != None: # self.current.dispose() # # Path: rx/exceptions.py # class DisposedException(Exception): # def __init__(self): # super(DisposedException, self).__init__("Object already disposed") # # Path: rx/observer.py # class Observer(Disposable): # """Represents the IObserver Interface. # Has some static helper methods attached""" # # @staticmethod # def create(onNext=None, onError=None, onCompleted=None): # if onNext == None: # onNext = noop # if onError == None: # onError = defaultError # if onCompleted == None: # onCompleted = noop # # return AnonymousObserver(onNext, onError, onCompleted) # # @staticmethod # def synchronize(observer, lock=None): # if lock == None: # lock = RLock() # # return SynchronizedObserver(observer, lock) # # @staticmethod # def fromNotifier(handler): # return AnonymousObserver( # lambda x: handler(Notification.createOnNext(x)), # lambda ex: handler(Notification.createOnError(ex)), # lambda: handler(Notification.createOnCompleted()) # ) # # def toNotifier(self): # return lambda n: n.accept(self) # # def asObserver(self): # return AnonymousObserver(self.onNext, self.onError, self.onCompleted) # # def checked(self): # return CheckedObserver(self) # # def notifyOn(self, scheduler): # return ScheduledObserver(scheduler, self) # # def onNext(self, value): # raise NotImplementedError() # # def onError(self, exception): # raise NotImplementedError() # # def onCompleted(self): # raise NotImplementedError() , which may contain function names, class names, or code. Output only the next line.
raise DisposedException()
Predict the next line after this snippet: <|code_start|>class SingleAsync(Producer): def __init__(self, source, predicate, throwOnEmpty, defaultValue): self.source = source self.predicate = predicate self.throwOnEmpty = throwOnEmpty self.defaultValue = defaultValue def run(self, observer, cancel, setSink): sink = self.Sink(self, observer, cancel) setSink(sink) return self.source.subscribeSafe(sink) class Sink(rx.linq.sink.Sink): def __init__(self, parent, observer, cancel): super(SingleAsync.Sink, self).__init__(observer, cancel) self.parent = parent self.value = self.parent.defaultValue self.hasValue = False def onNext(self, value): b = False try: b = self.parent.predicate(value) except Exception as e: self.observer.onError(e) self.dispose() if b: if self.hasValue: <|code_end|> using the current file's imports: from rx.exceptions import InvalidOperationException from rx.observable import Producer import rx.linq.sink and any relevant context from other files: # Path: rx/exceptions.py # class InvalidOperationException(Exception): # def __init__(self, text): # super(InvalidOperationException, self).__init__("Invalid operation: %s" % text) # # Path: rx/observable.py # class Producer(Observable): # """Base class for implementation of query operators, providing # performance benefits over the use of Observable.Create""" # # def subscribeCore(self, observer): # return self.subscribeRaw(observer, True) # # def subscribeRaw(self, observer, enableSafequard): # sink = SingleAssignmentDisposable() # subscription = SingleAssignmentDisposable() # # d = CompositeDisposable(sink, subscription) # # if enableSafequard: # observer = AutoDetachObserver(observer, d) # # def assignSink(s): # sink.disposable = s # # def scheduled(): # subscription.disposable = self.run(observer, subscription, assignSink) # return Disposable.empty() # # if Scheduler.currentThread.isScheduleRequired(): # Scheduler.currentThread.schedule(scheduled) # else: # scheduled() # # return d # # def run(self, observer, cancel, setSink): # raise NotImplementedError() . Output only the next line.
self.observer.onError(InvalidOperationException("More than one element in observable"))
Given snippet: <|code_start|> class Dematerialize(Producer): def __init__(self, source): self.source = source def run(self, observer, cancel, setSink): sink = self.Sink(observer, cancel) setSink(sink) return self.source.subscribeSafe(sink) class Sink(rx.linq.sink.Sink): def __init__(self, observer, cancel): super(Dematerialize.Sink, self).__init__(observer, cancel) def onNext(self, value): <|code_end|> , continue by predicting the next line. Consider current file imports: from rx.observable import Producer from rx.notification import Notification import rx.linq.sink and context: # Path: rx/observable.py # class Producer(Observable): # """Base class for implementation of query operators, providing # performance benefits over the use of Observable.Create""" # # def subscribeCore(self, observer): # return self.subscribeRaw(observer, True) # # def subscribeRaw(self, observer, enableSafequard): # sink = SingleAssignmentDisposable() # subscription = SingleAssignmentDisposable() # # d = CompositeDisposable(sink, subscription) # # if enableSafequard: # observer = AutoDetachObserver(observer, d) # # def assignSink(s): # sink.disposable = s # # def scheduled(): # subscription.disposable = self.run(observer, subscription, assignSink) # return Disposable.empty() # # if Scheduler.currentThread.isScheduleRequired(): # Scheduler.currentThread.schedule(scheduled) # else: # scheduled() # # return d # # def run(self, observer, cancel, setSink): # raise NotImplementedError() # # Path: rx/notification.py # class Notification(object): # """Represents a notification to an observer.""" # # KIND_NEXT = 0 # KIND_ERROR = 1 # KIND_COMPLETED = 2 # # def __eq__(self, other): # if not isinstance(other, Notification): # return False # # return ( # self.kind == other.kind and # self.value == other.value and # self.hasValue == other.hasValue and # self.exception == other.exception # ) # # def accept(self, observerOrOnNext, onError=None, onCompleted=None): # """Accepts an observer or the methods onNext, onError, onCompleted and invokes # either onNext, onError, onCompleted depending on which type of :class:`Notification` # it is. This is an abstract method that is implemented by # :class:`OnNextNotification`, :class:`OnErrorNotification`, # and :class:`OnCompletedNotification`.""" # # if observerOrOnNext == None or hasattr(observerOrOnNext, '__call__'): # # observer = Observer.create(observerOrOnNext, onError, onComplete) # raise NotImplementedError() # # @staticmethod # def createOnNext(value): # return OnNextNotification(value) # # @staticmethod # def createOnError(exception): # return OnErrorNotification(exception) # # @staticmethod # def createOnCompleted(): # return OnCompletedNotification() which might include code, classes, or functions. Output only the next line.
if value.kind == Notification.KIND_NEXT:
Given the code snippet: <|code_start|> class Multicast(Producer): def __init__(self, source, subjectSelector, selector): self.source = source self.subjectSelector = subjectSelector self.selector = selector def run(self, observer, cancel, setSink): sink = self.Sink(self, observer, cancel) setSink(sink) return sink.run() class Sink(rx.linq.sink.Sink): def __init__(self, parent, observer, cancel): super(Multicast.Sink, self).__init__(observer, cancel) self.parent = parent def run(self): observable = None connectable = None try: subject = self.parent.subjectSelector() connectable = ConnectableObservable(self.parent.source, subject) observable = self.parent.selector(connectable) except Exception as e: self.observer.onError(e) self.dispose() <|code_end|> , generate the next line using the imports in this file: from rx.disposable import Disposable, CompositeDisposable from rx.observable import Producer, ConnectableObservable import rx.linq.sink and context (functions, classes, or occasionally code) from other files: # Path: rx/disposable.py # class Disposable(object): # """Represents a disposable object""" # # def dispose(self): # pass # # def __enter__(self): # return self # # def __exit__(self, exc_type, exc_value, traceback): # self.dispose() # # @staticmethod # def create(action): # return AnonymouseDisposable(action) # # @staticmethod # def empty(): # return disposableEmpty # # class CompositeDisposable(Cancelable): # """Represents a group of disposable resources that # are disposed together""" # # def __init__(self, *disposables): # super(CompositeDisposable, self).__init__() # # if len(disposables) == 0: # self.disposables = [] # elif len(disposables) == 1 and not isinstance(disposables[0], Disposable): # self.disposables = [d for d in disposables[0] if d != None] # else: # self.disposables = [d for d in disposables if d != None] # # self.length = len(self.disposables) # # def add(self, disposable): # shouldDispose = False # # with self.lock: # shouldDispose = self.isDisposed # # if not shouldDispose: # self.disposables.append(disposable) # self.length += 1 # # if shouldDispose: # disposable.dispose() # # def contains(self, disposable): # with self.lock: # return self.disposables.index(disposable) >= 0 # # def remove(self, disposable): # shouldDispose = False # # with self.lock: # if self.isDisposed: # return False # # index = self.disposables.index(disposable) # # if index < 0: # return False # # shouldDispose = True # # self.disposables.remove(disposable) # self.length -= 1 # # if shouldDispose: # disposable.dispose() # # return shouldDispose # # def clear(self): # disposables = [] # # with self.lock: # disposables = self.disposables # self.disposables = [] # self.length = 0 # # for disposable in disposables: # disposable.dispose() # # def dispose(self): # if not self._isDisposed.exchange(True): # self.clear() # # Path: rx/observable.py # class Producer(Observable): # """Base class for implementation of query operators, providing # performance benefits over the use of Observable.Create""" # # def subscribeCore(self, observer): # return self.subscribeRaw(observer, True) # # def subscribeRaw(self, observer, enableSafequard): # sink = SingleAssignmentDisposable() # subscription = SingleAssignmentDisposable() # # d = CompositeDisposable(sink, subscription) # # if enableSafequard: # observer = AutoDetachObserver(observer, d) # # def assignSink(s): # sink.disposable = s # # def scheduled(): # subscription.disposable = self.run(observer, subscription, assignSink) # return Disposable.empty() # # if Scheduler.currentThread.isScheduleRequired(): # Scheduler.currentThread.schedule(scheduled) # else: # scheduled() # # return d # # def run(self, observer, cancel, setSink): # raise NotImplementedError() # # class ConnectableObservable(Observable): # """Represents an observable wrapper that can be connected # and disconnected from its underlying observable sequence.""" # def __init__(self, source, subject): # self.source = source.asObservable() # self.subject = subject # self.gate = RLock() # self.connection = None # # def connect(self): # with self.gate: # if self.connection == None: # subscription = self.source.subscribeSafe(self.subject) # self.connection = self.Connection(self, subscription) # # return self.connection # # def subscribeCore(self, observer): # return self.subject.subscribeSafe(observer) # # class Connection(Disposable): # def __init__(self, parent, subscription): # self.parent = parent # self.subscription = subscription # # def dispose(self): # with self.parent.gate: # if self.subscription != None: # self.subscription.dispose() # self.subscription = None # # self.parent.connection = None . Output only the next line.
return Disposable.empty()
Predict the next line for this snippet: <|code_start|> self.source = source self.subjectSelector = subjectSelector self.selector = selector def run(self, observer, cancel, setSink): sink = self.Sink(self, observer, cancel) setSink(sink) return sink.run() class Sink(rx.linq.sink.Sink): def __init__(self, parent, observer, cancel): super(Multicast.Sink, self).__init__(observer, cancel) self.parent = parent def run(self): observable = None connectable = None try: subject = self.parent.subjectSelector() connectable = ConnectableObservable(self.parent.source, subject) observable = self.parent.selector(connectable) except Exception as e: self.observer.onError(e) self.dispose() return Disposable.empty() else: subscription = observable.subscribeSafe(self) connection = connectable.connect() <|code_end|> with the help of current file imports: from rx.disposable import Disposable, CompositeDisposable from rx.observable import Producer, ConnectableObservable import rx.linq.sink and context from other files: # Path: rx/disposable.py # class Disposable(object): # """Represents a disposable object""" # # def dispose(self): # pass # # def __enter__(self): # return self # # def __exit__(self, exc_type, exc_value, traceback): # self.dispose() # # @staticmethod # def create(action): # return AnonymouseDisposable(action) # # @staticmethod # def empty(): # return disposableEmpty # # class CompositeDisposable(Cancelable): # """Represents a group of disposable resources that # are disposed together""" # # def __init__(self, *disposables): # super(CompositeDisposable, self).__init__() # # if len(disposables) == 0: # self.disposables = [] # elif len(disposables) == 1 and not isinstance(disposables[0], Disposable): # self.disposables = [d for d in disposables[0] if d != None] # else: # self.disposables = [d for d in disposables if d != None] # # self.length = len(self.disposables) # # def add(self, disposable): # shouldDispose = False # # with self.lock: # shouldDispose = self.isDisposed # # if not shouldDispose: # self.disposables.append(disposable) # self.length += 1 # # if shouldDispose: # disposable.dispose() # # def contains(self, disposable): # with self.lock: # return self.disposables.index(disposable) >= 0 # # def remove(self, disposable): # shouldDispose = False # # with self.lock: # if self.isDisposed: # return False # # index = self.disposables.index(disposable) # # if index < 0: # return False # # shouldDispose = True # # self.disposables.remove(disposable) # self.length -= 1 # # if shouldDispose: # disposable.dispose() # # return shouldDispose # # def clear(self): # disposables = [] # # with self.lock: # disposables = self.disposables # self.disposables = [] # self.length = 0 # # for disposable in disposables: # disposable.dispose() # # def dispose(self): # if not self._isDisposed.exchange(True): # self.clear() # # Path: rx/observable.py # class Producer(Observable): # """Base class for implementation of query operators, providing # performance benefits over the use of Observable.Create""" # # def subscribeCore(self, observer): # return self.subscribeRaw(observer, True) # # def subscribeRaw(self, observer, enableSafequard): # sink = SingleAssignmentDisposable() # subscription = SingleAssignmentDisposable() # # d = CompositeDisposable(sink, subscription) # # if enableSafequard: # observer = AutoDetachObserver(observer, d) # # def assignSink(s): # sink.disposable = s # # def scheduled(): # subscription.disposable = self.run(observer, subscription, assignSink) # return Disposable.empty() # # if Scheduler.currentThread.isScheduleRequired(): # Scheduler.currentThread.schedule(scheduled) # else: # scheduled() # # return d # # def run(self, observer, cancel, setSink): # raise NotImplementedError() # # class ConnectableObservable(Observable): # """Represents an observable wrapper that can be connected # and disconnected from its underlying observable sequence.""" # def __init__(self, source, subject): # self.source = source.asObservable() # self.subject = subject # self.gate = RLock() # self.connection = None # # def connect(self): # with self.gate: # if self.connection == None: # subscription = self.source.subscribeSafe(self.subject) # self.connection = self.Connection(self, subscription) # # return self.connection # # def subscribeCore(self, observer): # return self.subject.subscribeSafe(observer) # # class Connection(Disposable): # def __init__(self, parent, subscription): # self.parent = parent # self.subscription = subscription # # def dispose(self): # with self.parent.gate: # if self.subscription != None: # self.subscription.dispose() # self.subscription = None # # self.parent.connection = None , which may contain function names, class names, or code. Output only the next line.
return CompositeDisposable(subscription, connection)
Here is a snippet: <|code_start|> class Multicast(Producer): def __init__(self, source, subjectSelector, selector): self.source = source self.subjectSelector = subjectSelector self.selector = selector def run(self, observer, cancel, setSink): sink = self.Sink(self, observer, cancel) setSink(sink) return sink.run() class Sink(rx.linq.sink.Sink): def __init__(self, parent, observer, cancel): super(Multicast.Sink, self).__init__(observer, cancel) self.parent = parent def run(self): observable = None connectable = None try: subject = self.parent.subjectSelector() <|code_end|> . Write the next line using the current file imports: from rx.disposable import Disposable, CompositeDisposable from rx.observable import Producer, ConnectableObservable import rx.linq.sink and context from other files: # Path: rx/disposable.py # class Disposable(object): # """Represents a disposable object""" # # def dispose(self): # pass # # def __enter__(self): # return self # # def __exit__(self, exc_type, exc_value, traceback): # self.dispose() # # @staticmethod # def create(action): # return AnonymouseDisposable(action) # # @staticmethod # def empty(): # return disposableEmpty # # class CompositeDisposable(Cancelable): # """Represents a group of disposable resources that # are disposed together""" # # def __init__(self, *disposables): # super(CompositeDisposable, self).__init__() # # if len(disposables) == 0: # self.disposables = [] # elif len(disposables) == 1 and not isinstance(disposables[0], Disposable): # self.disposables = [d for d in disposables[0] if d != None] # else: # self.disposables = [d for d in disposables if d != None] # # self.length = len(self.disposables) # # def add(self, disposable): # shouldDispose = False # # with self.lock: # shouldDispose = self.isDisposed # # if not shouldDispose: # self.disposables.append(disposable) # self.length += 1 # # if shouldDispose: # disposable.dispose() # # def contains(self, disposable): # with self.lock: # return self.disposables.index(disposable) >= 0 # # def remove(self, disposable): # shouldDispose = False # # with self.lock: # if self.isDisposed: # return False # # index = self.disposables.index(disposable) # # if index < 0: # return False # # shouldDispose = True # # self.disposables.remove(disposable) # self.length -= 1 # # if shouldDispose: # disposable.dispose() # # return shouldDispose # # def clear(self): # disposables = [] # # with self.lock: # disposables = self.disposables # self.disposables = [] # self.length = 0 # # for disposable in disposables: # disposable.dispose() # # def dispose(self): # if not self._isDisposed.exchange(True): # self.clear() # # Path: rx/observable.py # class Producer(Observable): # """Base class for implementation of query operators, providing # performance benefits over the use of Observable.Create""" # # def subscribeCore(self, observer): # return self.subscribeRaw(observer, True) # # def subscribeRaw(self, observer, enableSafequard): # sink = SingleAssignmentDisposable() # subscription = SingleAssignmentDisposable() # # d = CompositeDisposable(sink, subscription) # # if enableSafequard: # observer = AutoDetachObserver(observer, d) # # def assignSink(s): # sink.disposable = s # # def scheduled(): # subscription.disposable = self.run(observer, subscription, assignSink) # return Disposable.empty() # # if Scheduler.currentThread.isScheduleRequired(): # Scheduler.currentThread.schedule(scheduled) # else: # scheduled() # # return d # # def run(self, observer, cancel, setSink): # raise NotImplementedError() # # class ConnectableObservable(Observable): # """Represents an observable wrapper that can be connected # and disconnected from its underlying observable sequence.""" # def __init__(self, source, subject): # self.source = source.asObservable() # self.subject = subject # self.gate = RLock() # self.connection = None # # def connect(self): # with self.gate: # if self.connection == None: # subscription = self.source.subscribeSafe(self.subject) # self.connection = self.Connection(self, subscription) # # return self.connection # # def subscribeCore(self, observer): # return self.subject.subscribeSafe(observer) # # class Connection(Disposable): # def __init__(self, parent, subscription): # self.parent = parent # self.subscription = subscription # # def dispose(self): # with self.parent.gate: # if self.subscription != None: # self.subscription.dispose() # self.subscription = None # # self.parent.connection = None , which may include functions, classes, or code. Output only the next line.
connectable = ConnectableObservable(self.parent.source, subject)
Given the code snippet: <|code_start|> self.throwOnEmpty = throwOnEmpty self.defaultValue = defaultValue def run(self, observer, cancel, setSink): sink = self.Sink(self, observer, cancel) setSink(sink) return self.source.subscribeSafe(sink) class Sink(rx.linq.sink.Sink): def __init__(self, parent, observer, cancel): super(LastAsync.Sink, self).__init__(observer, cancel) self.parent = parent self.value = self.parent.defaultValue self.hasValue = False def onNext(self, value): try: if self.parent.predicate(value): self.value = value self.hasValue = True except Exception as e: self.observer.onError(e) self.dispose() def onError(self, exception): self.observer.onError(exception) self.dispose() def onCompleted(self): if not self.hasValue and self.parent.throwOnEmpty: <|code_end|> , generate the next line using the imports in this file: from rx.exceptions import InvalidOperationException from rx.observable import Producer import rx.linq.sink and context (functions, classes, or occasionally code) from other files: # Path: rx/exceptions.py # class InvalidOperationException(Exception): # def __init__(self, text): # super(InvalidOperationException, self).__init__("Invalid operation: %s" % text) # # Path: rx/observable.py # class Producer(Observable): # """Base class for implementation of query operators, providing # performance benefits over the use of Observable.Create""" # # def subscribeCore(self, observer): # return self.subscribeRaw(observer, True) # # def subscribeRaw(self, observer, enableSafequard): # sink = SingleAssignmentDisposable() # subscription = SingleAssignmentDisposable() # # d = CompositeDisposable(sink, subscription) # # if enableSafequard: # observer = AutoDetachObserver(observer, d) # # def assignSink(s): # sink.disposable = s # # def scheduled(): # subscription.disposable = self.run(observer, subscription, assignSink) # return Disposable.empty() # # if Scheduler.currentThread.isScheduleRequired(): # Scheduler.currentThread.schedule(scheduled) # else: # scheduled() # # return d # # def run(self, observer, cancel, setSink): # raise NotImplementedError() . Output only the next line.
self.observer.onError(InvalidOperationException("No elements in observable"))
Predict the next line for this snippet: <|code_start|> # catch up loop. In the best case, all work will be dispatched on the periodic scheduler. # # # We start with one tick pending because we're about to start doing OnNext(0L). # self.pendingTickCount.value = 1 d = SingleAssignmentDisposable() self.periodic = d d.disposable = scheduler.schedulePeriodicWithState(1, self.parent.period, self.tock) try: self.observer.onNext(0) except Exception as e: d.dispose() raise e # # If the periodic scheduling job already ran before we finished dispatching the OnNext(0L) # call, we'll find pendingTickCount to be > 1. In this case, we need to catch up by dispatching # subsequent calls to OnNext as fast as possible, but without running a loop in order to ensure # fair play with the scheduler. So, we run a tail-recursive loop in CatchUp instead. # if self.pendingTickCount.dec() > 0: c = SingleAssignmentDisposable() c.disposable = scheduler.scheduleRecursiveWithState(1, self.catchUp) <|code_end|> with the help of current file imports: from rx.concurrency import Atomic from rx.disposable import CompositeDisposable, SingleAssignmentDisposable from rx.observable import Producer import rx.linq.sink and context from other files: # Path: rx/concurrency.py # class Atomic: # def __init__(self, value=None, lock=RLock()): # self.lock = lock # self._value = value # # def value(): # doc = "The value property." # def fget(self): # return self._value # def fset(self, value): # self.exchange(value) # return locals() # value = property(**value()) # # def exchange(self, value): # with self.lock: # old = self._value # self._value = value # return old # # def compareExchange(self, value, expected): # with self.lock: # old = self._value # # if old == expected: # self._value = value # # return old # # def inc(self, by=1): # with self.lock: # self._value += by # return self.value # # def dec(self, by=1): # with self.lock: # self._value -= by # return self.value # # Path: rx/disposable.py # class CompositeDisposable(Cancelable): # """Represents a group of disposable resources that # are disposed together""" # # def __init__(self, *disposables): # super(CompositeDisposable, self).__init__() # # if len(disposables) == 0: # self.disposables = [] # elif len(disposables) == 1 and not isinstance(disposables[0], Disposable): # self.disposables = [d for d in disposables[0] if d != None] # else: # self.disposables = [d for d in disposables if d != None] # # self.length = len(self.disposables) # # def add(self, disposable): # shouldDispose = False # # with self.lock: # shouldDispose = self.isDisposed # # if not shouldDispose: # self.disposables.append(disposable) # self.length += 1 # # if shouldDispose: # disposable.dispose() # # def contains(self, disposable): # with self.lock: # return self.disposables.index(disposable) >= 0 # # def remove(self, disposable): # shouldDispose = False # # with self.lock: # if self.isDisposed: # return False # # index = self.disposables.index(disposable) # # if index < 0: # return False # # shouldDispose = True # # self.disposables.remove(disposable) # self.length -= 1 # # if shouldDispose: # disposable.dispose() # # return shouldDispose # # def clear(self): # disposables = [] # # with self.lock: # disposables = self.disposables # self.disposables = [] # self.length = 0 # # for disposable in disposables: # disposable.dispose() # # def dispose(self): # if not self._isDisposed.exchange(True): # self.clear() # # class SingleAssignmentDisposable(Cancelable): # """Represents a disposable resource which only allows # a single assignment of its underlying disposable resource. # If an underlying disposable resource has already been set, # future attempts to set the underlying disposable resource # will throw an Error.""" # # def __init__(self): # super(SingleAssignmentDisposable, self).__init__() # self.current = None # # def disposable(): # def fget(self): # with self.lock: # if self.isDisposed: # return Disposable.empty() # else: # return self.current # def fset(self, value): # old = self.current # self.current = value # # if old != None: raise Exception("Disposable has already been assigned") # # if self.isDisposed and value != None: value.dispose() # return locals() # # disposable = property(**disposable()) # # def dispose(self): # if not self._isDisposed.exchange(True): # if self.current != None: # self.current.dispose() # # Path: rx/observable.py # class Producer(Observable): # """Base class for implementation of query operators, providing # performance benefits over the use of Observable.Create""" # # def subscribeCore(self, observer): # return self.subscribeRaw(observer, True) # # def subscribeRaw(self, observer, enableSafequard): # sink = SingleAssignmentDisposable() # subscription = SingleAssignmentDisposable() # # d = CompositeDisposable(sink, subscription) # # if enableSafequard: # observer = AutoDetachObserver(observer, d) # # def assignSink(s): # sink.disposable = s # # def scheduled(): # subscription.disposable = self.run(observer, subscription, assignSink) # return Disposable.empty() # # if Scheduler.currentThread.isScheduleRequired(): # Scheduler.currentThread.schedule(scheduled) # else: # scheduled() # # return d # # def run(self, observer, cancel, setSink): # raise NotImplementedError() , which may contain function names, class names, or code. Output only the next line.
return CompositeDisposable(d, c)
Continue the code snippet: <|code_start|> def onCompleted(self): self.observer.onCompleted() self.dispose() def done(self): if self.lastException != None: self.observer.onError(self.lastException) else: self.observer.onCompleted() self.dispose() class CatchException(Producer): def __init__(self, source, handler, exceptionType): self.source = source self.handler = handler self.exceptionType = exceptionType def run(self, observer, cancel, setSink): sink = self.Sink(self, observer, cancel) setSink(sink) return sink.run() class Sink(rx.linq.sink.Sink): def __init__(self, parent, observer, cancel): super(CatchException.Sink, self).__init__(observer, cancel) self.parent = parent def run(self): <|code_end|> . Use current file imports: from rx.disposable import SerialDisposable, SingleAssignmentDisposable from rx.observable import Producer from rx.observer import Observer import rx.linq.sink and context (classes, functions, or code) from other files: # Path: rx/disposable.py # class SerialDisposable(Cancelable): # """Represents a disposable resource whose underlying # disposable resource can be replaced by # another disposable resource, causing automatic # disposal of the previous underlying disposable resource. # Also known as MultipleAssignmentDisposable.""" # # def __init__(self): # super(SerialDisposable, self).__init__() # self.current = None # # def disposable(): # doc = "The disposable property." # def fget(self): # with self.lock: # if self.isDisposed: # return Disposable.empty() # else: # return self.current # def fset(self, value): # old = None # shouldDispose = False # # with self.lock: # shouldDispose = self.isDisposed # # if not shouldDispose: # old = self.current # self.current = value # # if old != None: # old.dispose() # # if shouldDispose: # value.dispose() # return locals() # disposable = property(**disposable()) # # def dispose(self): # if not self._isDisposed.exchange(True): # old = self.current # # self.current = None # # if old != None: # old.dispose() # # class SingleAssignmentDisposable(Cancelable): # """Represents a disposable resource which only allows # a single assignment of its underlying disposable resource. # If an underlying disposable resource has already been set, # future attempts to set the underlying disposable resource # will throw an Error.""" # # def __init__(self): # super(SingleAssignmentDisposable, self).__init__() # self.current = None # # def disposable(): # def fget(self): # with self.lock: # if self.isDisposed: # return Disposable.empty() # else: # return self.current # def fset(self, value): # old = self.current # self.current = value # # if old != None: raise Exception("Disposable has already been assigned") # # if self.isDisposed and value != None: value.dispose() # return locals() # # disposable = property(**disposable()) # # def dispose(self): # if not self._isDisposed.exchange(True): # if self.current != None: # self.current.dispose() # # Path: rx/observable.py # class Producer(Observable): # """Base class for implementation of query operators, providing # performance benefits over the use of Observable.Create""" # # def subscribeCore(self, observer): # return self.subscribeRaw(observer, True) # # def subscribeRaw(self, observer, enableSafequard): # sink = SingleAssignmentDisposable() # subscription = SingleAssignmentDisposable() # # d = CompositeDisposable(sink, subscription) # # if enableSafequard: # observer = AutoDetachObserver(observer, d) # # def assignSink(s): # sink.disposable = s # # def scheduled(): # subscription.disposable = self.run(observer, subscription, assignSink) # return Disposable.empty() # # if Scheduler.currentThread.isScheduleRequired(): # Scheduler.currentThread.schedule(scheduled) # else: # scheduled() # # return d # # def run(self, observer, cancel, setSink): # raise NotImplementedError() # # Path: rx/observer.py # class Observer(Disposable): # """Represents the IObserver Interface. # Has some static helper methods attached""" # # @staticmethod # def create(onNext=None, onError=None, onCompleted=None): # if onNext == None: # onNext = noop # if onError == None: # onError = defaultError # if onCompleted == None: # onCompleted = noop # # return AnonymousObserver(onNext, onError, onCompleted) # # @staticmethod # def synchronize(observer, lock=None): # if lock == None: # lock = RLock() # # return SynchronizedObserver(observer, lock) # # @staticmethod # def fromNotifier(handler): # return AnonymousObserver( # lambda x: handler(Notification.createOnNext(x)), # lambda ex: handler(Notification.createOnError(ex)), # lambda: handler(Notification.createOnCompleted()) # ) # # def toNotifier(self): # return lambda n: n.accept(self) # # def asObserver(self): # return AnonymousObserver(self.onNext, self.onError, self.onCompleted) # # def checked(self): # return CheckedObserver(self) # # def notifyOn(self, scheduler): # return ScheduledObserver(scheduler, self) # # def onNext(self, value): # raise NotImplementedError() # # def onError(self, exception): # raise NotImplementedError() # # def onCompleted(self): # raise NotImplementedError() . Output only the next line.
self.subscription = SerialDisposable()
Given the code snippet: <|code_start|> self.dispose() def done(self): if self.lastException != None: self.observer.onError(self.lastException) else: self.observer.onCompleted() self.dispose() class CatchException(Producer): def __init__(self, source, handler, exceptionType): self.source = source self.handler = handler self.exceptionType = exceptionType def run(self, observer, cancel, setSink): sink = self.Sink(self, observer, cancel) setSink(sink) return sink.run() class Sink(rx.linq.sink.Sink): def __init__(self, parent, observer, cancel): super(CatchException.Sink, self).__init__(observer, cancel) self.parent = parent def run(self): self.subscription = SerialDisposable() <|code_end|> , generate the next line using the imports in this file: from rx.disposable import SerialDisposable, SingleAssignmentDisposable from rx.observable import Producer from rx.observer import Observer import rx.linq.sink and context (functions, classes, or occasionally code) from other files: # Path: rx/disposable.py # class SerialDisposable(Cancelable): # """Represents a disposable resource whose underlying # disposable resource can be replaced by # another disposable resource, causing automatic # disposal of the previous underlying disposable resource. # Also known as MultipleAssignmentDisposable.""" # # def __init__(self): # super(SerialDisposable, self).__init__() # self.current = None # # def disposable(): # doc = "The disposable property." # def fget(self): # with self.lock: # if self.isDisposed: # return Disposable.empty() # else: # return self.current # def fset(self, value): # old = None # shouldDispose = False # # with self.lock: # shouldDispose = self.isDisposed # # if not shouldDispose: # old = self.current # self.current = value # # if old != None: # old.dispose() # # if shouldDispose: # value.dispose() # return locals() # disposable = property(**disposable()) # # def dispose(self): # if not self._isDisposed.exchange(True): # old = self.current # # self.current = None # # if old != None: # old.dispose() # # class SingleAssignmentDisposable(Cancelable): # """Represents a disposable resource which only allows # a single assignment of its underlying disposable resource. # If an underlying disposable resource has already been set, # future attempts to set the underlying disposable resource # will throw an Error.""" # # def __init__(self): # super(SingleAssignmentDisposable, self).__init__() # self.current = None # # def disposable(): # def fget(self): # with self.lock: # if self.isDisposed: # return Disposable.empty() # else: # return self.current # def fset(self, value): # old = self.current # self.current = value # # if old != None: raise Exception("Disposable has already been assigned") # # if self.isDisposed and value != None: value.dispose() # return locals() # # disposable = property(**disposable()) # # def dispose(self): # if not self._isDisposed.exchange(True): # if self.current != None: # self.current.dispose() # # Path: rx/observable.py # class Producer(Observable): # """Base class for implementation of query operators, providing # performance benefits over the use of Observable.Create""" # # def subscribeCore(self, observer): # return self.subscribeRaw(observer, True) # # def subscribeRaw(self, observer, enableSafequard): # sink = SingleAssignmentDisposable() # subscription = SingleAssignmentDisposable() # # d = CompositeDisposable(sink, subscription) # # if enableSafequard: # observer = AutoDetachObserver(observer, d) # # def assignSink(s): # sink.disposable = s # # def scheduled(): # subscription.disposable = self.run(observer, subscription, assignSink) # return Disposable.empty() # # if Scheduler.currentThread.isScheduleRequired(): # Scheduler.currentThread.schedule(scheduled) # else: # scheduled() # # return d # # def run(self, observer, cancel, setSink): # raise NotImplementedError() # # Path: rx/observer.py # class Observer(Disposable): # """Represents the IObserver Interface. # Has some static helper methods attached""" # # @staticmethod # def create(onNext=None, onError=None, onCompleted=None): # if onNext == None: # onNext = noop # if onError == None: # onError = defaultError # if onCompleted == None: # onCompleted = noop # # return AnonymousObserver(onNext, onError, onCompleted) # # @staticmethod # def synchronize(observer, lock=None): # if lock == None: # lock = RLock() # # return SynchronizedObserver(observer, lock) # # @staticmethod # def fromNotifier(handler): # return AnonymousObserver( # lambda x: handler(Notification.createOnNext(x)), # lambda ex: handler(Notification.createOnError(ex)), # lambda: handler(Notification.createOnCompleted()) # ) # # def toNotifier(self): # return lambda n: n.accept(self) # # def asObserver(self): # return AnonymousObserver(self.onNext, self.onError, self.onCompleted) # # def checked(self): # return CheckedObserver(self) # # def notifyOn(self, scheduler): # return ScheduledObserver(scheduler, self) # # def onNext(self, value): # raise NotImplementedError() # # def onError(self, exception): # raise NotImplementedError() # # def onCompleted(self): # raise NotImplementedError() . Output only the next line.
d = SingleAssignmentDisposable()