text:
#ifndef __ROOT__
#define __ROOT__

// Precompiler options
#include "OgrePrerequisites.h"

#include "OgreSingleton.h"
#include "OgreString.h"
#include "OgreSceneManagerEnumerator.h"
#include "OgreResourceGroupManager.h"
#include "OgreLodStrategyManager.h"
#include "OgreWorkQueue.h"

#include <exception>

namespace Ogre
{
	/** \addtogroup Core
	*  @{
	*/
	/** \addtogroup General
	*  @{
	*/

    typedef vector<RenderSystem*>::type RenderSystemList;

    /** The root class of the Ogre system.
        @remarks
            The Ogre::Root class represents a starting point for the client
            application. From here, the application can gain access to the
            fundamentals of the system, namely the rendering systems
            available, management of saved configurations, logging, and
            access to other classes in the system. Acts as a hub from which
            all other objects may be reached. An instance of Root must be
            created before any other Ogre operations are called. Once an
            instance has been created, the same instance is accessible
            throughout the life of that object by using Root::getSingleton
            (as a reference) or Root::getSingletonPtr (as a pointer).
    */
    class _OgreExport Root : public Singleton<Root>, public RootAlloc
    {
        // To allow update of active renderer if
        // RenderSystem::initialise is used directly
        friend class RenderSystem;
	protected:
        RenderSystemList mRenderers;
        RenderSystem* mActiveRenderer;
        String mVersion;
		String mConfigFileName;
	    bool mQueuedEnd;
        // In case multiple render windows are created, only once are the resources loaded.
        bool mFirstTimePostWindowInit;

        // Singletons
        LogManager* mLogManager;
        ControllerManager* mControllerManager;
        SceneManagerEnumerator* mSceneManagerEnum;
		typedef deque<SceneManager*>::type SceneManagerStack;
		SceneManagerStack mSceneManagerStack;
        DynLibManager* mDynLibManager;
        ArchiveManager* mArchiveManager;
        MaterialManager* mMaterialManager;
        MeshManager* mMeshManager;
        ParticleSystemManager* mParticleManager;
        SkeletonManager* mSkeletonManager;
        OverlayElementFactory* mPanelFactory;
        OverlayElementFactory* mBorderPanelFactory;
        OverlayElementFactory* mTextAreaFactory;
        OverlayManager* mOverlayManager;
        FontManager* mFontManager;
        ArchiveFactory *mZipArchiveFactory;
        ArchiveFactory *mEmbeddedZipArchiveFactory;
        ArchiveFactory *mFileSystemArchiveFactory;
		ResourceGroupManager* mResourceGroupManager;
		ResourceBackgroundQueue* mResourceBackgroundQueue;
		ShadowTextureManager* mShadowTextureManager;
		RenderSystemCapabilitiesManager* mRenderSystemCapabilitiesManager;
		ScriptCompilerManager *mCompilerManager;
        LodStrategyManager *mLodStrategyManager;

        Timer* mTimer;
        RenderWindow* mAutoWindow;
        Profiler* mProfiler;
        HighLevelGpuProgramManager* mHighLevelGpuProgramManager;
		ExternalTextureSourceManager* mExternalTextureSourceManager;
        CompositorManager* mCompositorManager;
        unsigned long mNextFrame;
		Real mFrameSmoothingTime;
		bool mRemoveQueueStructuresOnClear;
		Real mDefaultMinPixelSize;

	public:
		typedef vector<DynLib*>::type PluginLibList;
		typedef vector<Plugin*>::type PluginInstanceList;
	protected:
		/// List of plugin DLLs loaded
        PluginLibList mPluginLibs;
		/// List of Plugin instances registered
		PluginInstanceList mPlugins;

		typedef map<String, MovableObjectFactory*>::type MovableObjectFactoryMap;
		MovableObjectFactoryMap mMovableObjectFactoryMap;
		uint32 mNextMovableObjectTypeFlag;
		// stock movable factories
		MovableObjectFactory* mEntityFactory;
		MovableObjectFactory* mLightFactory;
		MovableObjectFactory* mBillboardSetFactory;
		MovableObjectFactory* mManualObjectFactory;
		MovableObjectFactory* mBillboardChainFactory;
		MovableObjectFactory* mRibbonTrailFactory;

		typedef map<String, RenderQueueInvocationSequence*>::type RenderQueueInvocationSequenceMap;
		RenderQueueInvocationSequenceMap mRQSequenceMap;

		/// Are we initialised yet?
		bool mIsInitialised;

		WorkQueue* mWorkQueue;

		///Tells whether blend indices information needs to be passed to the GPU
		bool mIsBlendIndicesGpuRedundant;
		///Tells whether blend weights information needs to be passed to the GPU
		bool mIsBlendWeightsGpuRedundant;

        /** Method reads a plugins configuration file and instantiates all
            plugins.
            @param
                pluginsfile The file that contains plugins information.
                Defaults to "plugins.cfg".
        */
        void loadPlugins( const String& pluginsfile = "plugins.cfg" );
		/** Initialise all loaded plugins - allows plugins to perform actions
			once the renderer is initialised.
		*/
		void initialisePlugins();
		/** Shuts down all loaded plugins - allows things to be tidied up whilst
			all plugins are still loaded.
		*/
		void shutdownPlugins();

		/** Unloads all loaded plugins.
        */
        void unloadPlugins();

        // Internal method for one-time tasks after first window creation
        void oneTimePostWindowInit(void);

        /** Set of registered frame listeners */
        set<FrameListener*>::type mFrameListeners;

        /** Set of frame listeners marked for removal*/
        set<FrameListener*>::type mRemovedFrameListeners;

        /** Indicates the type of event to be considered by calculateEventTime(). */
        enum FrameEventTimeType {
            FETT_ANY = 0,
			FETT_STARTED = 1,
			FETT_QUEUED = 2,
			FETT_ENDED = 3,
			FETT_COUNT = 4
        };

        /// Contains the times of recently fired events
		typedef deque<unsigned long>::type EventTimesQueue;
        EventTimesQueue mEventTimes[FETT_COUNT];

        /** Internal method for calculating the average time between recently fired events.
        @param now The current time in ms.
        @param type The type of event to be considered.
        */
        Real calculateEventTime(unsigned long now, FrameEventTimeType type);

		/** Update a set of event times (note, progressive, only call once for each type per frame) */
		void populateFrameEvent(FrameEventTimeType type, FrameEvent& evtToUpdate);

    public:

        /** Constructor
        @param pluginFileName The file that contains plugins information.
            Defaults to "plugins.cfg", may be left blank to ignore.
		@param configFileName The file that contains the configuration to be loaded.
			Defaults to "ogre.cfg", may be left blank to load nothing.
		@param logFileName The logfile to create, defaults to Ogre.log, may be
			left blank if you've already set up LogManager & Log yourself
		*/
        Root(const String& pluginFileName = "plugins.cfg",
			const String& configFileName = "ogre.cfg",
			const String& logFileName = "Ogre.log");
        ~Root();

        /** Saves the details of the current configuration
            @remarks
                Stores details of the current configuration so it may be
                restored later on.
        */
        void saveConfig(void);

        /** Checks for saved video/sound/etc settings
            @remarks
                This method checks to see if there is a valid saved configuration
                from a previous run. If there is, the state of the system will
                be restored to that configuration.

            @return
                If a valid configuration was found, true is returned.
            @par
                If there is no saved configuration, or if the system failed
                with the last config settings, false is returned.
        */
        bool restoreConfig(void);

        /** Displays a dialog asking the user to choose system settings.
            @remarks
                This method displays the default dialog allowing the user to
                choose the rendering system, video mode etc. If there is are
                any settings saved already, they will be restored automatically
                before displaying the dialogue. When the user accepts a group of
                settings, this will automatically call Root::setRenderSystem,
                RenderSystem::setConfigOption and Root::saveConfig with the
                user's choices. This is the easiest way to get the system
                configured.
            @return
                If the user clicked 'Ok', true is returned.
            @par
                If they clicked 'Cancel' (in which case the app should
                strongly consider terminating), false is returned.
         */
        bool showConfigDialog(void);

        /** Adds a new rendering subsystem to the list of available renderers.
            @remarks
                Intended for use by advanced users and plugin writers only!
                Calling this method with a pointer to a valid RenderSystem
                (subclass) adds a rendering API implementation to the list of
                available ones. Typical examples would be an OpenGL
                implementation and a Direct3D implementation.
            @note

This should usually be called from the dllStartPlugin()
                function of an extension plug-in.
        */
        void addRenderSystem(RenderSystem* newRend);

        /** Retrieve a list of the available render systems.
            @remarks
                Retrieves a pointer to the list of available renderers as a
                list of RenderSystem subclasses. Can be used to build a
                custom settings dialog.
        */
        const RenderSystemList& getAvailableRenderers(void);

        /** Retrieve a pointer to the render system by the given name
            @param
                name Name of the render system intend to retrieve.
            @return
                A pointer to the render system, NULL if no found.
        */
        RenderSystem* getRenderSystemByName(const String& name);

        /** Sets the rendering subsystem to be used.
            @remarks
                This method indicates to OGRE which rendering system is to be
                used (e.g. Direct3D, OpenGL etc). This is called
                automatically by the default config dialog, and when settings
                are restored from a previous configuraion. If used manually
                it could be used to set the renderer from a custom settings
                dialog. Once this has been done, the renderer can be
                initialised using Root::initialise.
            @par
                This method is also called by render systems if they are
                initialised directly.
            @param
                system Pointer to the render system to use.
            @see
                RenderSystem
        */
        void setRenderSystem(RenderSystem* system);

        /** Retrieve a pointer to the currently selected render system.
        */
        RenderSystem* getRenderSystem(void);

        /** Initialises the renderer.
            @remarks
                This method can only be called after a renderer has been
                selected with Root::setRenderSystem, and it will initialise
                the selected rendering system ready for use.
            @param
                autoCreateWindow If true, a rendering window will
                automatically be created (saving a call to
                Root::createRenderWindow). The window will be
                created based on the options currently set on the render
                system.
            @return
                A pointer to the automatically created window, if
                requested, otherwise NULL.
        */
	    RenderWindow* initialise(bool autoCreateWindow, const String& windowTitle = "OGRE Render Window",
                                    const String& customCapabilitiesConfig = StringUtil::BLANK);

		/** Returns whether the system is initialised or not. */
		bool isInitialised(void) const { return mIsInitialised; }

        /** Requests active RenderSystem to use custom RenderSystemCapabilities
        @remarks
            This is useful for testing how the RenderSystem would behave on a machine with
            less advanced GPUs. This method MUST be called before creating the first RenderWindow
        */
        void useCustomRenderSystemCapabilities(RenderSystemCapabilities* capabilities);

		/** Get whether the entire render queue structure should be emptied on clearing,
			or whether just the objects themselves should be cleared.
		*/
		bool getRemoveRenderQueueStructuresOnClear() const { return mRemoveQueueStructuresOnClear; }

		/** Set whether the entire render queue structure should be emptied on clearing,
		or whether just the objects themselves should be cleared.
		*/
		void setRemoveRenderQueueStructuresOnClear(bool r) { mRemoveQueueStructuresOnClear = r; }

		/** Register a new SceneManagerFactory, a factory object for creating instances
			of specific SceneManagers.
		@remarks
			Plugins should call this to register as new SceneManager providers.
		*/
		void addSceneManagerFactory(SceneManagerFactory* fact);

		/** Unregister a SceneManagerFactory.
		*/
		void removeSceneManagerFactory(SceneManagerFactory* fact);

		/** Get more information about a given type of SceneManager.
		@remarks
			The metadata returned tells you a few things about a given type
			of SceneManager, which can be created using a factory that has been
			registered already.
		@param typeName The type name of the SceneManager you want to enquire on.
			If you don't know the typeName already, you can iterate over the
			metadata for all types using getMetaDataIterator.
		*/
		const SceneManagerMetaData* getSceneManagerMetaData(const String& typeName) const;

		/** Iterate over all types of SceneManager available for construction,
			providing some information about each one.
		*/
		SceneManagerEnumerator::MetaDataIterator getSceneManagerMetaDataIterator(void) const;

		/** Create a SceneManager instance of a given type.
		@remarks
			You can use this method to create a SceneManager instance of a
			given specific type. You may know this type already, or you may
			have discovered it by looking at the results from getMetaDataIterator.
		@note
			This method throws an exception if the named type is not found.
		@param typeName String identifying a unique SceneManager type
		@param instanceName Optional name to given the new instance that is
			created. If you leave this blank, an auto name will be assigned.
		*/
		SceneManager* createSceneManager(const String& typeName,
			const String& instanceName = StringUtil::BLANK);

		/** Create a SceneManager instance based on scene type support.
		@remarks
			Creates an instance of a SceneManager which supports the scene types
			identified in the parameter. If more than one type of SceneManager
			has been registered as handling that combination of scene types,
			in instance of the last one registered is returned.
		@note This method always succeeds, if a specific scene manager is not
			found, the default implementation is always returned.
		@param typeMask A mask containing one or more SceneType flags
		@param instanceName Optional name to given the new instance that is
			created. If you leave this blank, an auto name will be assigned.
		*/
		SceneManager* createSceneManager(SceneTypeMask typeMask,
			const String& instanceName = StringUtil::BLANK);

		/** Destroy an instance of a SceneManager. */
		void destroySceneManager(SceneManager* sm);

		/** Get an existing SceneManager instance that has already been created,
			identified by the instance name.
		@param instanceName The name of the instance to retrieve.
		*/
		SceneManager* getSceneManager(const String& instanceName) const;

		/** Determines if a given SceneManager already exists
		@param instanceName The name of the instance to retrieve.
		*/
		bool hasSceneManager(const String& instanceName) const;
		/** Get an iterator over all the existing SceneManager instances. */
		SceneManagerEnumerator::SceneManagerIterator getSceneManagerIterator(void);

        /** Retrieves a reference to the current TextureManager.
            @remarks
                This performs the same function as
                TextureManager::getSingleton, but is provided for convenience
                particularly to scripting engines.
            @par
                Note that a TextureManager will NOT be available until the
                Ogre system has been initialised by selecting a RenderSystem,
                calling Root::initialise and a window having been created
                (this may have been done by initialise if required). This is
                because the exact runtime subclass which will be implementing
                the calls will differ depending on the rendering engine
                selected, and these typically require a window upon which to
                base texture format decisions.
        */
        TextureManager* getTextureManager(void);

        /** Retrieves a reference to the current MeshManager.
            @remarks
                This performs the same function as MeshManager::getSingleton
                and is provided for convenience to scripting engines.
        */
        MeshManager* getMeshManager(void);

        /** Utility function for getting a better description of an error
            code.
        */
        String getErrorDescription(long errorNumber);

        /** Registers a FrameListener which will be called back every frame.
            @remarks
                A FrameListener is a class which implements methods which
                will be called every frame.
            @par
                See the FrameListener class for more details on the specifics
                It is imperitive that the instance passed to this method is
                not destroyed before either the rendering loop ends, or the
                class is removed from the listening list using
                removeFrameListener.
            @note

This method can only be called after Root::initialise has
                been called.
            @see
                FrameListener, Root::removeFrameListener
        */
        void addFrameListener(FrameListener* newListener);

        /** Removes a FrameListener from the list of listening classes.
            @see
                FrameListener, Root::addFrameListener
        */
        void removeFrameListener(FrameListener* oldListener);

        /** Queues the end of rendering.
            @remarks
                This method will do nothing unless startRendering() has
                been called, in which case before the next frame is rendered
                the rendering loop will bail out.
            @see
                Root, Root::startRendering
        */
        void queueEndRendering(void);

        /** Starts / restarts the automatic rendering cycle.
            @remarks
                This method begins the automatic rendering of the scene. It
                will NOT return until the rendering cycle is halted.
            @par
                During rendering, any FrameListener classes registered using
                addFrameListener will be called back for each frame that is
                to be rendered, These classes can tell OGRE to halt the
                rendering if required, which will cause this method to
                return.
            @note

Users of the OGRE library do not have to use this
                automatic rendering loop. It is there as a convenience and is
                most useful for high frame rate applications e.g. games. For
                applications that don't need to constantly refresh the
                rendering targets (e.g. an editor utility), it is better to
                manually refresh each render target only when required by
                calling RenderTarget::update, or if you want to run your own
				render loop you can update all targets on demand using
				Root::renderOneFrame.
            @note
                This frees up the CPU to do other things in between
                refreshes, since in this case frame rate is less important.
            @note
                This method can only be called after Root::initialise has
                been called.
        */
        void startRendering(void);

        /** Render one frame.
        @remarks
            Updates all the render targets automatically and then returns,
            raising frame events before and after.
        */
        bool renderOneFrame(void);

		/** Render one frame, with custom frame time information.
		@remarks
		Updates all the render targets automatically and then returns,
		raising frame events before and after - all per-frame times are based on
		the time value you pass in.
		*/
		bool renderOneFrame(Real timeSinceLastFrame);

        /** Shuts down the system manually.
            @remarks
                This is normally done by Ogre automatically so don't think
                you have to call this yourself. However this is here for
                convenience, especially for dealing with unexpected errors or
                for systems which need to shut down Ogre on demand.
        */
        void shutdown(void);

        /** Adds a location to the list of searchable locations for a
            Resource type.
            @remarks
                Resource files (textures, models etc) need to be loaded from
                specific locations. By calling this method, you add another
				search location to the list. Locations added first are preferred
				over locations added later.
            @par
                Locations can be folders, compressed archives, even perhaps
                remote locations. Facilities for loading from different
                locations are provided by plugins which provide
                implementations of the Archive class.
                All the application user has to do is specify a 'loctype'
                string in order to indicate the type of location, which
                should map onto one of the provided plugins. Ogre comes
                configured with the 'FileSystem' (folders) and 'Zip' (archive
                compressed with the pkzip / WinZip etc utilities) types.
            @par
				You can also supply the name of a resource group which should
				have this location applied to it. The
				ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME group is the
				default, and one resource group which will always exist. You
				should consider defining resource groups for your more specific
				resources (e.g. per level) so that you can control loading /
				unloading better.
            @param
                name The name of the location, e.g. './data' or
                '/compressed/gamedata.zip'
            @param
                locType A string identifying the location type, e.g.
                'FileSystem' (for folders), 'Zip' etc. Must map to a
                registered plugin which deals with this type (FileSystem and
                Zip should always be available)
            @param
                groupName Type of name of the resource group which this location
				should apply to; defaults to the General group which applies to
				all non-specific resources.
			@param
				recursive If the resource location has a concept of recursive
				directory traversal, enabling this option will mean you can load
				resources in subdirectories using only their unqualified name.
				The default is to disable this so that resources in subdirectories
				with the same name are still unique.
            @see
                Archive
        */
        void addResourceLocation(const String& name, const String& locType,
			const String& groupName = ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
			bool recursive = false);

		/** Removes a resource location from the list.
		@see addResourceLocation
		@param name The name of the resource location as specified in addResourceLocation
		@param groupName The name of the resource group to which this location
			was assigned.
		*/
		void removeResourceLocation(const String& name,
			const String& groupName = ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);

		/** Helper method to assist you in creating writeable file streams.
		@remarks
			This is a high-level utility method which you can use to find a place to
			save a file more easily. If the filename you specify is either an
			absolute or relative filename (ie it includes path separators), then
			the file will be created in the normal filesystem using that specification.
			If it doesn't, then the method will look for a writeable resource location
			via ResourceGroupManager::createResource using the other params provided.
		@param filename The name of the file to create. If it includes path separators,
			the filesystem will be accessed direct. If no path separators are
			present the resource system is used, falling back on the raw filesystem after.
		@param groupName The name of the group in which to create the file, if the
			resource system is used
		@param overwrite If true, an existing file will be overwritten, if false
			an error will occur if the file already exists
		@param locationPattern If the resource group contains multiple locations,
			then usually the file will be created in the first writable location. If you
			want to be more specific, you can include a location pattern here and
			only locations which match that pattern (as determined by StringUtil::match)
			will be considered candidates for creation.
		*/
		DataStreamPtr createFileStream(const String& filename, const String& groupName = ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
			bool overwrite = false, const String& locationPattern = StringUtil::BLANK);

		/** Helper method to assist you in accessing readable file streams.
		@remarks
			This is a high-level utility method which you can use to find a place to
			open a file more easily. It checks the resource system first, and if
			that fails falls back on accessing the file system directly.
		@param filename The name of the file to open.
		@param groupName The name of the group in which to create the file, if the
			resource system is used
		@param locationPattern If the resource group contains multiple locations,
			then usually the file will be created in the first writable location. If you
			want to be more specific, you can include a location pattern here and
			only locations which match that pattern (as determined by StringUtil::match)
			will be considered candidates for creation.
		*/
		DataStreamPtr openFileStream(const String& filename, const String& groupName = ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
			const String& locationPattern = StringUtil::BLANK);

        /** Generates a packed data version of the passed in ColourValue suitable for
            use with the current RenderSystem.
        @remarks
            Since different render systems have different colour data formats (eg
            RGBA for GL, ARGB for D3D) this method allows you to use 1 method for all.
        @param colour The colour to convert
        @param pDest Pointer to location to put the result.
        */
        void convertColourValue(const ColourValue& colour, uint32* pDest);

        /** Retrieves a pointer to the window that was created automatically
            @remarks
                When Root is initialised an optional window is created. This
                method retreives a pointer to that window.
            @note
                returns a null pointer when Root has not been initialised with
                the option of creating a window.
        */
        RenderWindow* getAutoCreatedWindow(void);

        /** @copydoc RenderSystem::_createRenderWindow
        */
		RenderWindow* createRenderWindow(const String &name, unsigned int width, unsigned int height,
			bool fullScreen, const NameValuePairList *miscParams = 0) ;

		/** @copydoc RenderSystem::_createRenderWindows
		*/
		bool createRenderWindows(const RenderWindowDescriptionList& renderWindowDescriptions,
			RenderWindowList& createdWindows);

        /** Detaches a RenderTarget from the active render system
        and returns a pointer to it.
        @note
        If the render target cannot be found, NULL is returned.
        */
        RenderTarget* detachRenderTarget( RenderTarget* pWin );

        /** Detaches a named RenderTarget from the active render system
        and returns a pointer to it.
        @note
        If the render target cannot be found, NULL is returned.
        */
        RenderTarget* detachRenderTarget( const String & name );

        /** Destroys the given RenderTarget.
        */
        void destroyRenderTarget(RenderTarget* target);

        /** Destroys the given named RenderTarget.
        */
        void destroyRenderTarget(const String &name);

        /** Retrieves a pointer to a named render target.
        */
        RenderTarget * getRenderTarget(const String &name);

		/** Manually load a Plugin contained in a DLL / DSO.
		 @remarks
		 	Plugins embedded in DLLs can be loaded at startup using the plugin
			configuration file specified when you create Root (default: plugins.cfg).
			This method allows you to load plugin DLLs directly in code.
			The DLL in question is expected to implement a dllStartPlugin
			method which instantiates a Plugin subclass and calls Root::installPlugin.
			It should also implement dllStopPlugin (see Root::unloadPlugin)
		@param pluginName Name of the plugin library to load
		*/
		void loadPlugin(const String& pluginName);

		/** Manually unloads a Plugin contained in a DLL / DSO.
		 @remarks
		 	Plugin DLLs are unloaded at shutdown automatically. This method
			allows you to unload plugins in code, but make sure their
			dependencies are decoupled first. This method will call the
			dllStopPlugin method defined in the DLL, which in turn should call
			Root::uninstallPlugin.
		@param pluginName Name of the plugin library to unload
		*/
		void unloadPlugin(const String& pluginName);

		/** Install a new plugin.
		@remarks
			This installs a new extension to OGRE. The plugin itself may be loaded
			from a DLL / DSO, or it might be statically linked into your own
			application. Either way, something has to call this method to get
			it registered and functioning. You should only call this method directly
			if your plugin is not in a DLL that could otherwise be loaded with
			loadPlugin, since the DLL function dllStartPlugin should call this
			method when the DLL is loaded.
		*/
		void installPlugin(Plugin* plugin);

		/** Uninstall an existing plugin.
		@remarks
			This uninstalls an extension to OGRE. Plugins are automatically
			uninstalled at shutdown but this lets you remove them early.
			If the plugin was loaded from a DLL / DSO you should call unloadPlugin
			which should result in this method getting called anyway (if the DLL
			is well behaved).
		*/
		void uninstallPlugin(Plugin* plugin);

		/** Gets a read-only list of the currently installed plugins. */
		const PluginInstanceList& getInstalledPlugins() const { return mPlugins; }

        /** Gets a pointer to the central timer used for all OGRE timings */
        Timer* getTimer(void);

        /** Method for raising frame started events.
        @remarks
            This method is only for internal use when you use OGRE's inbuilt rendering
            loop (Root::startRendering). However, if you run your own rendering loop then
            you should call this method to ensure that FrameListener objects are notified
            of frame events; processes like texture animation and particle systems rely on
            this.
        @par
            Calling this method also increments the frame number, which is
            important for keeping some elements of the engine up to date.
        @note
            This method takes an event object as a parameter, so you can specify the times
            yourself. If you are happy for OGRE to automatically calculate the frame time
            for you, then call the other version of this method with no parameters.
        @param evt Event object which includes all the timing information which you have
            calculated for yourself
        @return False if one or more frame listeners elected that the rendering loop should
            be terminated, true otherwise.
        */
        bool _fireFrameStarted(FrameEvent& evt);
        /** Method for raising frame rendering queued events.
        @remarks
            This method is only for internal use when you use OGRE's inbuilt rendering
            loop (Root::startRendering). However, if you run your own rendering loop then
            you should call this method too, to ensure that all state is updated
			correctly. You should call it after the windows have been updated
			but before the buffers are swapped, or if you are not separating the
			update and buffer swap, then after the update just before _fireFrameEnded.
        */
        bool _fireFrameRenderingQueued(FrameEvent& evt);

        /** Method for raising frame ended events.
        @remarks
            This method is only for internal use when you use OGRE's inbuilt rendering
            loop (Root::startRendering). However, if you run your own rendering loop then
            you should call this method to ensure that FrameListener objects are notified
            of frame events; processes like texture animation and particle systems rely on
            this.
        @note
            This method takes an event object as a parameter, so you can specify the times
            yourself. If you are happy for OGRE to automatically calculate the frame time
            for you, then call the other version of this method with no parameters.
        @param evt Event object which includes all the timing information which you have
            calculated for yourself
        @return False if one or more frame listeners elected that the rendering loop should
            be terminated, true otherwise.
        */
        bool _fireFrameEnded(FrameEvent& evt);
        /** Method for raising frame started events.
        @remarks
            This method is only for internal use when you use OGRE's inbuilt rendering
            loop (Root::startRendering). However, if you run your own rendering loop then
            you should call this method to ensure that FrameListener objects are notified
            of frame events; processes like texture animation and particle systems rely on
            this.
        @par
            Calling this method also increments the frame number, which is
            important for keeping some elements of the engine up to date.
        @note
            This method calculates the frame timing information for you based on the elapsed
            time. If you want to specify elapsed times yourself you should call the other
            version of this method which takes event details as a parameter.
        @return False if one or more frame listeners elected that the rendering loop should
            be terminated, true otherwise.
        */
        bool _fireFrameStarted();
        /** Method for raising frame rendering queued events.
        @remarks
            This method is only for internal use when you use OGRE's inbuilt rendering
            loop (Root::startRendering). However, if you run your own rendering loop then
            you you may want to call this method too, although nothing in OGRE relies on this
			particular event. Really if you're running your own rendering loop at
			this level of detail then you can get the same effect as doing your
			updates in a frameRenderingQueued callback by just calling
			RenderWindow::update with the 'swapBuffers' option set to false.
        */
        bool _fireFrameRenderingQueued();
        /** Method for raising frame ended events.
        @remarks
            This method is only for internal use when you use OGRE's inbuilt rendering
            loop (Root::startRendering). However, if you run your own rendering loop then
            you should call this method to ensure that FrameListener objects are notified
            of frame events; processes like texture animation and particle systems rely on
            this.
        @note
            This method calculates the frame timing information for you based on the elapsed
            time. If you want to specify elapsed times yourself you should call the other
            version of this method which takes event details as a parameter.
        @return False if one or more frame listeners elected that the rendering loop should
            be terminated, true otherwise.
        */
        bool _fireFrameEnded();

        /** Gets the number of the next frame to be rendered.
		@remarks
			Note that this is 'next frame' rather than 'current frame' because
			it indicates the frame number that current changes made to the scene
			will take effect. It is incremented after all rendering commands for
			the current frame have been queued, thus reflecting that if you
			start performing changes then, you will actually see them in the
			next frame. */
        unsigned long getNextFrameNumber(void) const { return mNextFrame; }

        /** Returns the scene manager currently being used to render a frame.
        @remarks
            This is only intended for internal use; it is only valid during the
            rendering of a frame.
        */
        SceneManager* _getCurrentSceneManager(void) const;
        /** Pushes the scene manager currently being used to render.
        @remarks
            This is only intended for internal use.
        */
        void _pushCurrentSceneManager(SceneManager* sm);
		/** Pops the scene manager currently being used to render.
		@remarks
		This is only intended for internal use.
		*/
		void _popCurrentSceneManager(SceneManager* sm);

        /** Internal method used for updating all RenderTarget objects (windows,
            renderable textures etc) which are set to auto-update.
        @remarks
            You don't need to use this method if you're using Ogre's own internal
            rendering loop (Root::startRendering). If you're running your own loop
            you may wish to call it to update all the render targets which are
            set to auto update (RenderTarget::setAutoUpdated). You can also update
            individual RenderTarget instances using their own update() method.
		@return false if a FrameListener indicated it wishes to exit the render loop
        */
        bool _updateAllRenderTargets(void);

        /** Internal method used for updating all RenderTarget objects (windows,
            renderable textures etc) which are set to auto-update, with a custom time
			passed to the frameRenderingQueued events.
        @remarks
            You don't need to use this method if you're using Ogre's own internal
            rendering loop (Root::startRendering). If you're running your own loop
            you may wish to call it to update all the render targets which are
            set to auto update (RenderTarget::setAutoUpdated). You can also update
            individual RenderTarget instances using their own update() method.
		@return false if a FrameListener indicated it wishes to exit the render loop
        */
        bool _updateAllRenderTargets(FrameEvent& evt);

		/** Create a new RenderQueueInvocationSequence, useful for linking to
			Viewport instances to perform custom rendering.
		@param name The name to give the new sequence
		*/
		RenderQueueInvocationSequence* createRenderQueueInvocationSequence(
			const String& name);

		/** Get a RenderQueueInvocationSequence.
		@param name The name to identify the sequence
		*/
		RenderQueueInvocationSequence* getRenderQueueInvocationSequence(
			const String& name);

		/** Destroy a RenderQueueInvocationSequence.
		@remarks
			You must ensure that no Viewports are using this sequence.
		@param name The name to identify the sequence
		*/
		void destroyRenderQueueInvocationSequence(
			const String& name);

		/** Destroy all RenderQueueInvocationSequences.
		@remarks
			You must ensure that no Viewports are using custom sequences.
		@param name The name to identify the sequence
		*/
		void destroyAllRenderQueueInvocationSequences(void);

        /** Override standard Singleton retrieval.
            @remarks
                Why do we do this? Well, it's because the Singleton
                implementation is in a .h file, which means it gets compiled
                into anybody who includes it. This is needed for the
                Singleton template to work, but we actually only want it
                compiled into the implementation of the class based on the
                Singleton, not all of them. If we don't change this, we get
                link errors when trying to use the Singleton-based class from
                an outside dll.
            @par
                This method just delegates to the template version anyway,
                but the implementation stays in this single compilation unit,
                preventing link errors.
        */
        static Root& getSingleton(void);
        /** Override standard Singleton retrieval.
            @remarks
                Why do we do this? Well, it's because the Singleton
                implementation is in a .h file, which means it gets compiled
                into anybody who includes it. This is needed for the
                Singleton template to work, but we actually only want it
                compiled into the implementation of the class based on the
                Singleton, not all of them. If we don't change this, we get
                link errors when trying to use the Singleton-based class from
                an outside dll.
            @par
                This method just delegates to the template version anyway,
                but the implementation stays in this single compilation unit,
                preventing link errors.
        */
        static Root* getSingletonPtr(void);

		/** Clears the history of all event times.
		@remarks
			OGRE stores a history of the last few event times in order to smooth
			out any inaccuracies and temporary fluctuations. However, if you
			pause or don't render for a little while this can cause a lurch, so
			if you're resuming rendering after a break, call this method to reset
			the stored times
		*/
		void clearEventTimes(void);

		/** Sets the period over which OGRE smooths out fluctuations in frame times.
		@remarks
			OGRE by default gives you the raw frame time, but can optionally
			smooths it out over several frames, in order to reduce the
			noticeable effect of occasional hiccups in framerate.
			These smoothed values are passed back as parameters to FrameListener
			calls.
		@par
			This method allow you to tweak the smoothing period, and is expressed
			in seconds. Setting it to 0 will result in completely unsmoothed
			frame times (the default).
		*/
		void setFrameSmoothingPeriod(Real period) { mFrameSmoothingTime = period; }
		/** Gets the period over which OGRE smooths out fluctuations in frame times. */
		Real getFrameSmoothingPeriod(void) const { return mFrameSmoothingTime; }

		/** Register a new MovableObjectFactory which will create new MovableObject
			instances of a particular type, as identified by the getType() method.
		@remarks
			Plugin creators can create subclasses of MovableObjectFactory which
			construct custom subclasses of MovableObject for insertion in the
			scene. This is the primary way that plugins can make custom objects
			available.
		@param fact Pointer to the factory instance
		@param overrideExisting Set this to true to override any existing
			factories which are registered for the same type. You should only
			change this if you are very sure you know what you're doing.
		*/
		void addMovableObjectFactory(MovableObjectFactory* fact,
			bool overrideExisting = false);
		/** Removes a previously registered MovableObjectFactory.
		@remarks
			All instances of objects created by this factory will be destroyed
			before removing the factory (by calling back the factories
			'destroyInstance' method). The plugin writer is responsible for actually
			destroying the factory.
		*/
		void removeMovableObjectFactory(MovableObjectFactory* fact);
		/// Checks whether a factory is registered for a given MovableObject type
		bool hasMovableObjectFactory(const String& typeName) const;
		/// Get a MovableObjectFactory for the given type
		MovableObjectFactory* getMovableObjectFactory(const String& typeName);
		/** Allocate the next MovableObject type flag.
		@remarks
			This is done automatically if MovableObjectFactory::requestTypeFlags
			returns true; don't call this manually unless you're sure you need to.
		*/
		uint32 _allocateNextMovableObjectTypeFlag(void);

		typedef ConstMapIterator<MovableObjectFactoryMap> MovableObjectFactoryIterator;
		/** Return an iterator over all the MovableObjectFactory instances currently
			registered.
		*/
		MovableObjectFactoryIterator getMovableObjectFactoryIterator(void) const;

		/**
		* Gets the number of display monitors.
		*/
		unsigned int getDisplayMonitorCount() const;

		/** Get the WorkQueue for processing background tasks.
			You are free to add new requests and handlers to this queue to
			process your custom background tasks using the shared thread pool.
			However, you must remember to assign yourself a new channel through
			which to process your tasks.
		*/
		WorkQueue* getWorkQueue() const { return mWorkQueue; }

		/** Replace the current work queue with an alternative.
			You can use this method to replace the internal implementation of
			WorkQueue with  your own, e.g. to externalise the processing of
			background events. Doing so will delete the existing queue and
			replace it with this one.
		@param queue The new WorkQueue instance. Root will delete this work queue
			at shutdown, so do not destroy it yourself.
		*/
		void setWorkQueue(WorkQueue* queue);

		/** Sets whether blend indices information needs to be passed to the GPU.
			When entities use software animation they remove blend information such as
			indices and weights from the vertex buffers sent to the graphic card. This function
			can be used to limit which information is removed.
		@param redundant Set to true to remove blend indices information.
		*/
		void setBlendIndicesGpuRedundant(bool redundant) {	mIsBlendIndicesGpuRedundant = redundant; }
		/** Returns whether blend indices information needs to be passed to the GPU
		see setBlendIndicesGpuRedundant() for more information
		*/
		bool isBlendIndicesGpuRedundant() const { return mIsBlendIndicesGpuRedundant; }

		/** Sets whether blend weights information needs to be passed to the GPU.
		When entities use software animation they remove blend information such as
		indices and weights from the vertex buffers sent to the graphic card. This function
		can be used to limit which information is removed.
		@param redundant Set to true to remove blend weights information.
		*/
		void setBlendWeightsGpuRedundant(bool redundant) {	mIsBlendWeightsGpuRedundant = redundant; }
		/** Returns whether blend weights information needs to be passed to the GPU
		see setBlendWeightsGpuRedundant() for more information
		*/
		bool isBlendWeightsGpuRedundant() const { return mIsBlendWeightsGpuRedundant; }

		/** Set the default minimum pixel size for object to be rendered by
		@note
			To use this feature see Camera::setUseMinPixelSize()
		*/
		void setDefaultMinPixelSize(Real pixelSize) { mDefaultMinPixelSize = pixelSize; }

		/** Get the default minimum pixel size for object to be rendered by
		*/
		Real getDefaultMinPixelSize() { return mDefaultMinPixelSize; }

    };
	/** @} */
	/** @} */
} // Namespace Ogre
#endif


text:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;

class SearchController extends Controller
{
    public function search(Request $request){
        $keywords = $request->keywords;
        dd(explode(" ", $keywords));
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class procedures   extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		//VolumeStatistics Procedure
		$sql = <<<SQL
		CREATE PROCEDURE `volume_stats`(IN days INT)
		BEGIN
        	select                  distinct date(created_at) as udate,
                                        round((select max(iops) from VolumeStatistics where date(created_at) = udate),2) as max_iops,
                                        round((select max(`rd-iops`) from VolumeStatistics where date(created_at) = udate),2) as rd_iops,
                                        round((select max(`wr-iops`) from VolumeStatistics where date(created_at) = udate),2) as wr_iops,
                                        round((select max(`logical-space-in-use`) from VolumeStatistics where date(created_at) = udate) /1024 /1024,2) as gb,
                                        round((select avg(`avg-latency`) from VolumeStatistics where date(created_at) = udate),2) as total_latency,
                                        round((select avg(`rd-latency`) from VolumeStatistics where date(created_at) = udate),2) as rd_latency,
                                        round((select avg(`wr-latency`) from VolumeStatistics where date(created_at) = udate),2) as wr_latency
	        from                    VolumeStatistics vs
	        where                   created_at > date_sub(now(),interval days day);
		END
SQL;

		DB::connection()->getPdo()->exec($sql);

		//Cluster Stats Procedure
		$sql = <<<SQL
		CREATE PROCEDURE `cluster_stats`(IN days INT)
		BEGIN

        select                  distinct date(created_at) as udate,
                                        round((select max(iops) from ClusterStatistics where date(created_at) = udate),2) as max_iops,
                                        round((select max(`rd-iops`) from ClusterStatistics where date(created_at) = udate),2) as rd_iops,
                                        round((select max(`wr-iops`) from ClusterStatistics where date(created_at) = udate),2) as wr_iops,
                                        round((select max(`logical-space-in-use`) from ClusterStatistics where date(created_at) = udate) /1024 /1024,2) as gb,
                                        round((select avg(`avg-latency`) from ClusterStatistics where date(created_at) = udate),2) as total_latency,
                                        round((select avg(`rd-latency`) from ClusterStatistics where date(created_at) = udate),2) as rd_latency,
                                        round((select avg(`wr-latency`) from ClusterStatistics where date(created_at) = udate),2) as wr_latency
        from                    ClusterStatistics vs
        where                   created_at > date_sub(now(),interval days day);
		END
SQL;

		DB::connection()->getPdo()->exec($sql);

	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		$sql = 'DROP PROCEDURE IF EXISTS volume_stats';
		DB::connection()->getPdo()->exec($sql);

		$sql = 'DROP PROCEDURE IF EXISTS cluster_stats';
		DB::connection()->getPdo()->exec($sql);
	}

}


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
/**
 * Operator use ToString
 *
 * @path ch15/15.1/15.1.3/15.1.3.3/S15.1.3.3_A6_T1.js
 * @description If Type(value) is Object, evaluate ToPrimitive(value, String)
 */

//CHECK#1
var object = {valueOf: function() {return "^"}};
if (encodeURI(object) !== "%5Bobject%20Object%5D") {
  $ERROR('#1: var object = {valueOf: function() {return "^"}}; encodeURI(object) === %5Bobject%20Object%5D. Actual: ' + (encodeURI(object)));
}

//CHECK#2
var object = {valueOf: function() {return ""}, toString: function() {return "^"}};
if (encodeURI(object) !== "%5E") {
  $ERROR('#2: var object = {valueOf: function() {return ""}, toString: function() {return "^"}}; encodeURI(object) === "%5E". Actual: ' + (encodeURI(object)));
}

//CHECK#3
var object = {valueOf: function() {return "^"}, toString: function() {return {}}};
if (encodeURI(object) !== "%5E") {
  $ERROR('#3: var object = {valueOf: function() {return "^"}, toString: function() {return {}}}; encodeURI(object) === "%5E". Actual: ' + (encodeURI(object)));
}

//CHECK#4
try {
  var object = {valueOf: function() {throw "error"}, toString: function() {return "^"}};
  if (encodeURI(object) !== "%5E") {
    $ERROR('#4.1: var object = {valueOf: function() {throw "error"}, toString: function() {return "^"}}; encodeURI(object) === "%5E". Actual: ' + (encodeURI(object)));
  }
}
catch (e) {
  if (e === "error") {
    $ERROR('#4.2: var object = {valueOf: function() {throw "error"}, toString: function() {return "^"}}; encodeURI(object) not throw "error"');
  } else {
    $ERROR('#4.3: var object = {valueOf: function() {throw "error"}, toString: function() {return "^"}}; encodeURI(object) not throw Error. Actual: ' + (e));
  }
}

//CHECK#5
var object = {toString: function() {return "^"}};
if (encodeURI(object) !== "%5E") {
  $ERROR('#5: var object = {toString: function() {return "^"}}; encodeURI(object) === "%5E". Actual: ' + (encodeURI(object)));
}

//CHECK#6
var object = {valueOf: function() {return {}}, toString: function() {return "^"}}
if (encodeURI(object) !== "%5E") {
  $ERROR('#6: var object = {valueOf: function() {return {}}, toString: function() {return "^"}}; encodeURI(object) === "%5E". Actual: ' + (encodeURI(object)));
}

//CHECK#7
try {
  var object = {valueOf: function() {return "^"}, toString: function() {throw "error"}};
  encodeURI(object);
  $ERROR('#7.1: var object = {valueOf: function() {return "^"}, toString: function() {throw "error"}}; encodeURI(object) throw "error". Actual: ' + (encodeURI(object)));
}
catch (e) {
  if (e !== "error") {
    $ERROR('#7.2: var object = {valueOf: function() {return "^"}, toString: function() {throw "error"}}; encodeURI(object) throw "error". Actual: ' + (e));
  }
}

//CHECK#8
try {
  var object = {valueOf: function() {return {}}, toString: function() {return {}}};
  encodeURI(object);
  $ERROR('#8.1: var object = {valueOf: function() {return {}}, toString: function() {return {}}}; encodeURI(object) throw TypeError. Actual: ' + (encodeURI(object)));
}
catch (e) {
  if ((e instanceof TypeError) !== true) {
    $ERROR('#8.2: var object = {valueOf: function() {return {}}, toString: function() {return {}}}; encodeURI(object) throw TypeError. Actual: ' + (e));
  }
}


text:
/* SASL Config file API
 * Rob Siemborski
 * Tim Martin (originally in Cyrus distribution)
 * $Id: config.c,v 1.15 2006/04/10 13:28:06 mel Exp $
 */
/*
 * Copyright (c) 1998-2003 Carnegie Mellon University.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The name "Carnegie Mellon University" must not be used to
 *    endorse or promote products derived from this software without
 *    prior written permission. For permission or any other legal
 *    details, please contact
 *      Office of Technology Transfer
 *      Carnegie Mellon University
 *      5000 Forbes Avenue
 *      Pittsburgh, PA  15213-3890
 *      (412) 268-4387, fax: (412) 268-7395
 *      tech-transfer@andrew.cmu.edu
 *
 * 4. Redistributions of any form whatsoever must retain the following
 *    acknowledgment:
 *    "This product includes software developed by Computing Services
 *     at Carnegie Mellon University (http://www.cmu.edu/computing/)."
 *
 * CARNEGIE MELLON UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO
 * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS, IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY BE LIABLE
 * FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
 * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
 * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

/*
 * Current Valid keys:
 *
 * canon_user_plugin: <string>
 * pwcheck_method: <string>
 * auto_transition: <boolean>
 * plugin_list: <string>
 *
 * srvtab: <string>
 */

#include "sasl.h"
#include "saslint.h"

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

struct configlist {
    char *key;
    char *value;
};

static struct configlist *configlist;
static int nconfiglist;

#define CONFIGLISTGROWSIZE 100

int sasl_config_init(const char *filename)
{
    FILE *infile;
    int lineno = 0;
    int alloced = 0;
    char buf[4096];
    char *p, *key;
    int result;

    nconfiglist=0;

    infile = fopen(filename, "r");
    if (!infile) {
        return SASL_CONTINUE;
    }

    while (fgets(buf, sizeof(buf), infile)) {
	lineno++;

	if (buf[strlen(buf)-1] == '\n') buf[strlen(buf)-1] = '\0';
	for (p = buf; *p && isspace((int) *p); p++);
	if (!*p || *p == '#') continue;

	key = p;
	while (*p && (isalnum((int) *p) || *p == '-' || *p == '_')) {
	    if (isupper((int) *p)) *p = tolower(*p);
	    p++;
	}
	if (*p != ':') {
	    return SASL_FAIL;
	}
	*p++ = '\0';

	while (*p && isspace((int) *p)) p++;

	if (!*p) {
	    return SASL_FAIL;
	}

	if (nconfiglist == alloced) {
	    alloced += CONFIGLISTGROWSIZE;
	    configlist=sasl_REALLOC((char *)configlist,
				    alloced * sizeof(struct configlist));
	    if (configlist==NULL) return SASL_NOMEM;
	}

	result = _sasl_strdup(key,
			      &(configlist[nconfiglist].key),
			      NULL);
	if (result!=SASL_OK) return result;
	result = _sasl_strdup(p,
			      &(configlist[nconfiglist].value),
			      NULL);
	if (result!=SASL_OK) return result;

	nconfiglist++;
    }
    fclose(infile);

    return SASL_OK;
}

const char *sasl_config_getstring(const char *key,const char *def)
{
    int opt;

    for (opt = 0; opt < nconfiglist; opt++) {
	if (*key == configlist[opt].key[0] &&
	    !strcmp(key, configlist[opt].key))
	  return configlist[opt].value;
    }
    return def;
}


text:
package burai.input.namelist;

@FunctionalInterface
public interface QEValueListener {

    public void onValueChanged(QEValue value);

}


text:
using System;
using System.Globalization;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using Redmine.Net.Api.Internals;

namespace Redmine.Net.Api.Types
{
    /// <summary>
    ///
    /// </summary>
    public class IdentifiableName : Identifiable<IdentifiableName>, IXmlSerializable, IEquatable<IdentifiableName>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="IdentifiableName"/> class.
        /// </summary>
        public IdentifiableName()
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="IdentifiableName"/> class.
        /// </summary>
        /// <param name="reader">The reader.</param>
        public IdentifiableName(XmlReader reader)
        {
            Initialize(reader);
        }

        private void Initialize(XmlReader reader)
        {
            ReadXml(reader);
        }

        /// <summary>
        /// Gets or sets the name.
        /// </summary>
        /// <value>The name.</value>
        [XmlAttribute(RedmineKeys.NAME)]
        public String Name { get; set; }

        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public XmlSchema GetSchema() { return null; }

        /// <summary>
        ///
        /// </summary>
        /// <param name="reader"></param>
        public virtual void ReadXml(XmlReader reader)
        {
            Id = Convert.ToInt32(reader.GetAttribute(RedmineKeys.ID));
            Name = reader.GetAttribute(RedmineKeys.NAME);
            reader.Read();
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="writer"></param>
        public virtual void WriteXml(XmlWriter writer)
        {
            writer.WriteAttributeString(RedmineKeys.ID, Id.ToString(CultureInfo.InvariantCulture));
            writer.WriteAttributeString(RedmineKeys.NAME, Name);
        }
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            return $"[IdentifiableName: Id={Id}, Name={Name}]";
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="other"></param>
        /// <returns></returns>
        public bool Equals(IdentifiableName other)
        {
            if (other == null) return false;
            return (Id == other.Id && Name == other.Name);
        }

        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public override int GetHashCode()
        {
            unchecked
            {
                var hashCode = base.GetHashCode();
                hashCode = HashCodeHelper.GetHashCode(Name, hashCode);
                return hashCode;
            }
        }
    }
}


text:
[TOC]

At this point, we are eager to generate actual code and see our Toy language
take life. We will use LLVM to generate code, but just showing the LLVM builder
interface here wouldn't be very exciting. Instead, we will show how to perform
progressive lowering through a mix of dialects coexisting in the same function.

To make it more interesting, in this chapter we will consider that we want to
reuse existing optimizations implemented in a dialect optimizing affine
transformations: `Affine`. This dialect is tailored to the computation-heavy
part of the program and is limited: it doesn't support representing our
`toy.print` builtin, for instance, neither should it! Instead, we can target
`Affine` for the computation heavy part of Toy, and in the
[next chapter](Ch-6.md) directly the `LLVM IR` dialect for lowering `print`. As
part of this lowering, we will be lowering from the
[TensorType](../../LangRef.md#tensor-type) that `Toy` operates on to the
[MemRefType](../../LangRef.md#memref-type) that is indexed via an affine
loop-nest. Tensors represent an abstract value-typed sequence of data, meaning
that they don't live in any memory. MemRefs, on the other hand, represent lower
level buffer access, as they are concrete references to a region of memory.

# Dialect Conversions

MLIR has many different dialects, so it is important to have a unified framework
for [converting](../../Glossary.md#conversion) between them. This is where the
`DialectConversion` framework comes into play. This framework allows for
transforming a set of `illegal` operations to a set of `legal` ones. To use this
framework, we need to provide two things (and an optional third):

*   A [Conversion Target](../../DialectConversion.md#conversion-target)

    -   This is the formal specification of what operations or dialects are
        legal for the conversion. Operations that aren't legal will require
        rewrite patterns to perform
        [legalization](./../../Glossary.md#legalization).

*   A set of
    [Rewrite Patterns](../../DialectConversion.md#rewrite-pattern-specification)

    -   These are the set of [patterns](../../QuickstartRewrites.md) used to
        convert `illegal` operations into a set of zero or more `legal` ones.

*   Optionally, a [Type Converter](../../DialectConversion.md#type-conversion).

    -   If provided, this is used to convert the types of block arguments. We
        won't be needing this for our conversion.

## Conversion Target

For our purposes, we want to convert the compute-intensive `Toy` operations into
a combination of operations from the `Affine` `Standard` dialects for further
optimization. To start off the lowering, we first define our conversion target:

```c++
void ToyToAffineLoweringPass::runOnFunction() {
  // The first thing to define is the conversion target. This will define the
  // final target for this lowering.
  mlir::ConversionTarget target(getContext());

  // We define the specific operations, or dialects, that are legal targets for
  // this lowering. In our case, we are lowering to a combination of the
  // `Affine` and `Standard` dialects.
  target.addLegalDialect<mlir::AffineOpsDialect, mlir::StandardOpsDialect>();

  // We also define the Toy dialect as Illegal so that the conversion will fail
  // if any of these operations are *not* converted. Given that we actually want
  // a partial lowering, we explicitly mark the Toy operations that don't want
  // to lower, `toy.print`, as `legal`.
  target.addIllegalDialect<ToyDialect>();
  target.addLegalOp<PrintOp>();
  ...
}
```

## Conversion Patterns

After the conversion target has been defined, we can define how to convert the
`illegal` operations into `legal` ones. Similarly to the canonicalization
framework introduced in [chapter 3](Ch-3.md), the
[`DialectConversion` framework](../../DialectConversion.md) also uses
[RewritePatterns](../../QuickstartRewrites.md) to perform the conversion logic.
These patterns may be the `RewritePatterns` seen before or a new type of pattern
specific to the conversion framework `ConversionPattern`. `ConversionPatterns`
are different from traditional `RewritePatterns` in that they accept an
additional `operands` parameter containing operands that have been
remapped/replaced. This is used when dealing with type conversions, as the
pattern will want to operate on values of the new type but match against the
old. For our lowering, this invariant will be useful as it translates from the
[TensorType](../../LangRef.md#tensor-type) currently being operated on to the
[MemRefType](../../LangRef.md#memref-type). Let's look at a snippet of lowering
the `toy.transpose` operation:

```c++
/// Lower the `toy.transpose` operation to an affine loop nest.
struct TransposeOpLowering : public mlir::ConversionPattern {
  TransposeOpLowering(mlir::MLIRContext *ctx)
      : mlir::ConversionPattern(TransposeOp::getOperationName(), 1, ctx) {}

  /// Match and rewrite the given `toy.transpose` operation, with the given
  /// operands that have been remapped from `tensor<...>` to `memref<...>`.
  mlir::PatternMatchResult
  matchAndRewrite(mlir::Operation *op, ArrayRef<mlir::Value *> operands,
                  mlir::ConversionPatternRewriter &rewriter) const final {
    auto loc = op->getLoc();

    // Call to a helper function that will lower the current operation to a set
    // of affine loops. We provide a functor that operates on the remapped
    // operands, as well as the loop induction variables for the inner most
    // loop body.
    lowerOpToLoops(
        op, operands, rewriter,
        [loc](mlir::PatternRewriter &rewriter,
              ArrayRef<mlir::Value *> memRefOperands,
              ArrayRef<mlir::Value *> loopIvs) {
          // Generate an adaptor for the remapped operands of the TransposeOp.
          // This allows for using the nice named accessors that are generated
          // by the ODS. This adaptor is automatically provided by the ODS
          // framework.
          TransposeOpOperandAdaptor tranposeAdaptor(memRefOperands);
          mlir::Value *input = tranposeAdaptor.input();

          // Transpose the elements by generating a load from the reverse
          // indices.
          SmallVector<mlir::Value *, 2> reverseIvs(llvm::reverse(loopIvs));
          return rewriter.create<mlir::AffineLoadOp>(loc, input, reverseIvs);
        });
    return matchSuccess();
  }
};
```

Now we can prepare the list of patterns to use during the lowering process:

```c++
void ToyToAffineLoweringPass::runOnFunction() {
  ...

  // Now that the conversion target has been defined, we just need to provide
  // the set of patterns that will lower the Toy operations.
  mlir::OwningRewritePatternList patterns;
  patterns.insert<..., TransposeOpLowering>(&getContext());

  ...
```

## Partial Lowering

Once the patterns have been defined, we can perform the actual lowering. The
`DialectConversion` framework provides several different modes of lowering, but,
for our purposes, we will perform a partial lowering, as we will not convert
`toy.print` at this time.

```c++
void ToyToAffineLoweringPass::runOnFunction() {
  // The first thing to define is the conversion target. This will define the
  // final target for this lowering.
  mlir::ConversionTarget target(getContext());

  // We define the specific operations, or dialects, that are legal targets for
  // this lowering. In our case, we are lowering to a combination of the
  // `Affine` and `Standard` dialects.
  target.addLegalDialect<mlir::AffineOpsDialect, mlir::StandardOpsDialect>();

  // We also define the Toy dialect as Illegal so that the conversion will fail
  // if any of these operations are *not* converted. Given that we actually want
  // a partial lowering, we explicitly mark the Toy operations that don't want
  // to lower, `toy.print`, as `legal`.
  target.addIllegalDialect<ToyDialect>();
  target.addLegalOp<PrintOp>();

  // Now that the conversion target has been defined, we just need to provide
  // the set of patterns that will lower the Toy operations.
  mlir::OwningRewritePatternList patterns;
  patterns.insert<..., TransposeOpLowering>(&getContext());

  // With the target and rewrite patterns defined, we can now attempt the
  // conversion. The conversion will signal failure if any of our `illegal`
  // operations were not converted successfully.
  auto function = getFunction();
  if (mlir::failed(mlir::applyPartialConversion(function, target, patterns)))
    signalPassFailure();
}
```

### Design Considerations With Partial Lowering

Before diving into the result of our lowering, this is a good time to discuss
potential design considerations when it comes to partial lowering. In our
lowering, we transform from a value-type, TensorType, to an allocated
(buffer-like) type, MemRefType. However, given that we do not lower the
`toy.print` operation, we need to temporarily bridge these two worlds. There are
many ways to go about this, each with their own tradeoffs:

*   Generate `load` operations from the buffer

One option is to generate `load` operations from the buffer type to materialize
an instance of the value type. This allows for the definition of the `toy.print`
operation to remain unchanged. The downside to this approach is that the
optimizations on the `affine` dialect are limited, because the `load` will
actually involve a full copy that is only visible *after* our optimizations have
been performed.

*   Generate a new version of `toy.print` that operates on the lowered type

Another option would be to have another, lowered, variant of `toy.print` that
operates on the lowered type. The benefit of this option is that there is no
hidden, unnecessary copy to the optimizer. The downside is that another
operation definition is needed that may duplicate many aspects of the first.
Defining a base class in [ODS](../../OpDefinitions.md) may simplify this, but
you still need to treat these operations separately.

*   Update `toy.print` to allow for operating on the lowered type

A third option is to update the current definition of `toy.print` to allow for
operating the on the lowered type. The benefit of this approach is that it is
simple, does not introduce an additional hidden copy, and does not require
another operation definition. The downside to this option is that it requires
mixing abstraction levels in the `Toy` dialect.

For the sake of simplicity, we will use the third option for this lowering. This
involves updating the type constraints on the PrintOp in the operation
definition file:

```tablegen
def PrintOp : Toy_Op<"print"> {
  ...

  // The print operation takes an input tensor to print.
  // We also allow a F64MemRef to enable interop during partial lowering.
  let arguments = (ins AnyTypeOf<[F64Tensor, F64MemRef]>:$input);
}
```

## Complete Toy Example

Looking back at our current working example:

```.mlir
func @main() {
  %0 = "toy.constant"() {value = dense<[[1.000000e+00, 2.000000e+00, 3.000000e+00], [4.000000e+00, 5.000000e+00, 6.000000e+00]]> : tensor<2x3xf64>} : () -> tensor<2x3xf64>
  %2 = "toy.transpose"(%0) : (tensor<2x3xf64>) -> tensor<3x2xf64>
  %3 = "toy.mul"(%2, %2) : (tensor<3x2xf64>, tensor<3x2xf64>) -> tensor<3x2xf64>
  "toy.print"(%3) : (tensor<3x2xf64>) -> ()
  "toy.return"() : () -> ()
}
```

With affine lowering added to our pipeline, we can now generate:

```mlir
func @main() {
  %cst = constant 1.000000e+00 : f64
  %cst_0 = constant 2.000000e+00 : f64
  %cst_1 = constant 3.000000e+00 : f64
  %cst_2 = constant 4.000000e+00 : f64
  %cst_3 = constant 5.000000e+00 : f64
  %cst_4 = constant 6.000000e+00 : f64

  // Allocating buffers for the inputs and outputs.
  %0 = alloc() : memref<3x2xf64>
  %1 = alloc() : memref<3x2xf64>
  %2 = alloc() : memref<2x3xf64>

  // Initialize the input buffer with the constant values.
  affine.store %cst, %2[0, 0] : memref<2x3xf64>
  affine.store %cst_0, %2[0, 1] : memref<2x3xf64>
  affine.store %cst_1, %2[0, 2] : memref<2x3xf64>
  affine.store %cst_2, %2[1, 0] : memref<2x3xf64>
  affine.store %cst_3, %2[1, 1] : memref<2x3xf64>
  affine.store %cst_4, %2[1, 2] : memref<2x3xf64>

  // Load the transpose value from the input buffer and store it into the
  // next input buffer.
  affine.for %arg0 = 0 to 3 {
    affine.for %arg1 = 0 to 2 {
      %3 = affine.load %2[%arg1, %arg0] : memref<2x3xf64>
      affine.store %3, %1[%arg0, %arg1] : memref<3x2xf64>
    }
  }

  // Multiply and store into the output buffer.
  affine.for %arg0 = 0 to 2 {
    affine.for %arg1 = 0 to 3 {
      %3 = affine.load %1[%arg0, %arg1] : memref<3x2xf64>
      %4 = affine.load %1[%arg0, %arg1] : memref<3x2xf64>
      %5 = mulf %3, %4 : f64
      affine.store %5, %0[%arg0, %arg1] : memref<3x2xf64>
    }
  }

  // Print the value held by the buffer.
  "toy.print"(%0) : (memref<3x2xf64>) -> ()
  dealloc %2 : memref<2x3xf64>
  dealloc %1 : memref<3x2xf64>
  dealloc %0 : memref<3x2xf64>
  return
}
```

## Taking Advantage of Affine Optimization

Our naive lowering is correct, but it leaves a lot to be desired with regards to
efficiency. For example, the lowering of `toy.mul` has generated some redundant
loads. Let's look at how adding a few existing optimizations to the pipeline can
help clean this up. Adding the `LoopFusion` and `MemRefDataFlowOpt` passes to
the pipeline gives the following result:

```mlir
func @main() {
  %cst = constant 1.000000e+00 : f64
  %cst_0 = constant 2.000000e+00 : f64
  %cst_1 = constant 3.000000e+00 : f64
  %cst_2 = constant 4.000000e+00 : f64
  %cst_3 = constant 5.000000e+00 : f64
  %cst_4 = constant 6.000000e+00 : f64

  // Allocating buffers for the inputs and outputs.
  %0 = alloc() : memref<3x2xf64>
  %1 = alloc() : memref<2x3xf64>

  // Initialize the input buffer with the constant values.
  affine.store %cst, %1[0, 0] : memref<2x3xf64>
  affine.store %cst_0, %1[0, 1] : memref<2x3xf64>
  affine.store %cst_1, %1[0, 2] : memref<2x3xf64>
  affine.store %cst_2, %1[1, 0] : memref<2x3xf64>
  affine.store %cst_3, %1[1, 1] : memref<2x3xf64>
  affine.store %cst_4, %1[1, 2] : memref<2x3xf64>

  affine.for %arg0 = 0 to 3 {
    affine.for %arg1 = 0 to 2 {
      // Load the transpose value from the input buffer.
      %2 = affine.load %1[%arg1, %arg0] : memref<2x3xf64>

      // Multiply and store into the output buffer.
      %3 = mulf %2, %2 : f64
      affine.store %3, %0[%arg0, %arg1] : memref<3x2xf64>
    }
  }

  // Print the value held by the buffer.
  "toy.print"(%0) : (memref<3x2xf64>) -> ()
  dealloc %1 : memref<2x3xf64>
  dealloc %0 : memref<3x2xf64>
  return
}
```

Here, we can see that a redundant allocation was removed, the two loop nests
were fused, and some unnecessary `load`s were removed. You can build `toyc-ch5`
and try yourself: `toyc-ch5 test/lowering.toy -emit=mlir-affine`. We can also
check our optimizations by adding `-opt`.

In this chapter we explored some aspects of partial lowering, with the intent to
optimize. In the [next chapter](Ch-6.md) we will continue the discussion about
dialect conversion by targeting LLVM for code generation.


text:
package tectonicus.renderer;

import org.joml.Vector3f;

public interface Camera
{
	public void apply();

	public Vector3f getEyePosition();
	public Vector3f getForward();

	public Vector3f[] getFrustumVertices();

	public Vector3f[] getClearQuad();

	public int classify(final float worldX, final float worldY, final float worldZ);
}


text:
/** @constructor */
ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2 = (function() {
  ScalaJS.c.scala_collection_mutable_IndexedSeqView$AbstractTransformed.call(this);
  this.endpoints$3 = null;
  this.$$outer$3 = null
});
ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype = new ScalaJS.inheritable.scala_collection_mutable_IndexedSeqView$AbstractTransformed();
ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.constructor = ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2;
ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.length__I = (function() {
  return ScalaJS.impls.scala_collection_mutable_IndexedSeqView$Sliced$class__length__Lscala_collection_mutable_IndexedSeqView$Sliced__I(this)
});
ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.update__I__O__V = (function(idx, elem) {
  ScalaJS.impls.scala_collection_mutable_IndexedSeqView$Sliced$class__update__Lscala_collection_mutable_IndexedSeqView$Sliced__I__O__V(this, idx, elem)
});
ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.apply__I__O = (function(idx) {
  return ScalaJS.impls.scala_collection_GenSeqViewLike$Sliced$class__apply__Lscala_collection_GenSeqViewLike$Sliced__I__O(this, idx)
});
ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.foreach__Lscala_Function1__V = (function(f) {
  ScalaJS.impls.scala_collection_GenSeqViewLike$Sliced$class__foreach__Lscala_collection_GenSeqViewLike$Sliced__Lscala_Function1__V(this, f)
});
ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.iterator__Lscala_collection_Iterator = (function() {
  return ScalaJS.impls.scala_collection_GenSeqViewLike$Sliced$class__iterator__Lscala_collection_GenSeqViewLike$Sliced__Lscala_collection_Iterator(this)
});
ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.from__I = (function() {
  return ScalaJS.impls.scala_collection_GenTraversableViewLike$Sliced$class__from__Lscala_collection_GenTraversableViewLike$Sliced__I(this)
});
ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.until__I = (function() {
  return ScalaJS.impls.scala_collection_GenTraversableViewLike$Sliced$class__until__Lscala_collection_GenTraversableViewLike$Sliced__I(this)
});
ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.viewIdentifier__T = (function() {
  return ScalaJS.impls.scala_collection_GenTraversableViewLike$Sliced$class__viewIdentifier__Lscala_collection_GenTraversableViewLike$Sliced__T(this)
});
ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.endpoints__Lscala_collection_generic_SliceInterval = (function() {
  return this.endpoints$3
});
ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.scala$collection$mutable$IndexedSeqView$Sliced$$$outer__Lscala_collection_mutable_IndexedSeqView = (function() {
  return this.$$outer$3
});
ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.scala$collection$GenSeqViewLike$Sliced$$$outer__Lscala_collection_GenSeqViewLike = (function() {
  return this.$$outer$3
});
ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.scala$collection$GenIterableViewLike$Sliced$$$outer__Lscala_collection_GenIterableViewLike = (function() {
  return this.$$outer$3
});
ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.scala$collection$GenTraversableViewLike$Sliced$$$outer__Lscala_collection_GenTraversableViewLike = (function() {
  return this.$$outer$3
});
ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.apply__O__O = (function(v1) {
  return this.apply__I__O(ScalaJS.uI(v1))
});
ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.init___Lscala_collection_mutable_IndexedSeqView__Lscala_collection_generic_SliceInterval = (function($$outer, _endpoints$1) {
  if (($$outer === null)) {
    throw new ScalaJS.c.java_lang_NullPointerException().init___()
  } else {
    this.$$outer$3 = $$outer
  };
  var endpoints = _endpoints$1;
  this.endpoints$3 = endpoints;
  ScalaJS.c.scala_collection_mutable_IndexedSeqView$AbstractTransformed.prototype.init___Lscala_collection_mutable_IndexedSeqView.call(this, $$outer);
  ScalaJS.impls.scala_collection_GenTraversableViewLike$Sliced$class__$init$__Lscala_collection_GenTraversableViewLike$Sliced__V(this);
  ScalaJS.impls.scala_collection_GenIterableViewLike$Sliced$class__$init$__Lscala_collection_GenIterableViewLike$Sliced__V(this);
  ScalaJS.impls.scala_collection_GenSeqViewLike$Sliced$class__$init$__Lscala_collection_GenSeqViewLike$Sliced__V(this);
  ScalaJS.impls.scala_collection_mutable_IndexedSeqView$Sliced$class__$init$__Lscala_collection_mutable_IndexedSeqView$Sliced__V(this);
  return this
});
ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.until__ = (function() {
  return ScalaJS.bI(this.until__I())
});
ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.from__ = (function() {
  return ScalaJS.bI(this.from__I())
});
ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.scala$collection$GenTraversableViewLike$Sliced$$$outer__ = (function() {
  return this.scala$collection$GenTraversableViewLike$Sliced$$$outer__Lscala_collection_GenTraversableViewLike()
});
ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.scala$collection$GenIterableViewLike$Sliced$$$outer__ = (function() {
  return this.scala$collection$GenIterableViewLike$Sliced$$$outer__Lscala_collection_GenIterableViewLike()
});
ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.scala$collection$GenSeqViewLike$Sliced$$$outer__ = (function() {
  return this.scala$collection$GenSeqViewLike$Sliced$$$outer__Lscala_collection_GenSeqViewLike()
});
ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.scala$collection$mutable$IndexedSeqView$Sliced$$$outer__ = (function() {
  return this.scala$collection$mutable$IndexedSeqView$Sliced$$$outer__Lscala_collection_mutable_IndexedSeqView()
});
ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.endpoints__ = (function() {
  return this.endpoints__Lscala_collection_generic_SliceInterval()
});
/** @constructor */
ScalaJS.inheritable.scala_collection_mutable_IndexedSeqView$$anon$2 = (function() {
  /*<skip>*/
});
ScalaJS.inheritable.scala_collection_mutable_IndexedSeqView$$anon$2.prototype = ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype;
ScalaJS.is.scala_collection_mutable_IndexedSeqView$$anon$2 = (function(obj) {
  return (!(!((obj && obj.$classData) && obj.$classData.ancestors.scala_collection_mutable_IndexedSeqView$$anon$2)))
});
ScalaJS.as.scala_collection_mutable_IndexedSeqView$$anon$2 = (function(obj) {
  if ((ScalaJS.is.scala_collection_mutable_IndexedSeqView$$anon$2(obj) || (obj === null))) {
    return obj
  } else {
    ScalaJS.throwClassCastException(obj, "scala.collection.mutable.IndexedSeqView$$anon$2")
  }
});
ScalaJS.isArrayOf.scala_collection_mutable_IndexedSeqView$$anon$2 = (function(obj, depth) {
  return (!(!(((obj && obj.$classData) && (obj.$classData.arrayDepth === depth)) && obj.$classData.arrayBase.ancestors.scala_collection_mutable_IndexedSeqView$$anon$2)))
});
ScalaJS.asArrayOf.scala_collection_mutable_IndexedSeqView$$anon$2 = (function(obj, depth) {
  if ((ScalaJS.isArrayOf.scala_collection_mutable_IndexedSeqView$$anon$2(obj, depth) || (obj === null))) {
    return obj
  } else {
    ScalaJS.throwArrayCastException(obj, "Lscala.collection.mutable.IndexedSeqView$$anon$2;", depth)
  }
});
ScalaJS.data.scala_collection_mutable_IndexedSeqView$$anon$2 = new ScalaJS.ClassTypeData({
  scala_collection_mutable_IndexedSeqView$$anon$2: 0
}, false, "scala.collection.mutable.IndexedSeqView$$anon$2", ScalaJS.data.scala_collection_mutable_IndexedSeqView$AbstractTransformed, {
  scala_collection_mutable_IndexedSeqView$$anon$2: 1,
  scala_collection_mutable_IndexedSeqView$Sliced: 1,
  scala_collection_SeqViewLike$Sliced: 1,
  scala_collection_GenSeqViewLike$Sliced: 1,
  scala_collection_IterableViewLike$Sliced: 1,
  scala_collection_GenIterableViewLike$Sliced: 1,
  scala_collection_TraversableViewLike$Sliced: 1,
  scala_collection_GenTraversableViewLike$Sliced: 1,
  scala_collection_mutable_IndexedSeqView$AbstractTransformed: 1,
  scala_collection_mutable_IndexedSeqView$Transformed: 1,
  scala_collection_mutable_IndexedSeqView: 1,
  scala_collection_mutable_IndexedSeqOptimized: 1,
  scala_collection_IndexedSeqOptimized: 1,
  scala_collection_mutable_IndexedSeq: 1,
  scala_collection_mutable_IndexedSeqLike: 1,
  scala_collection_IndexedSeq: 1,
  scala_collection_IndexedSeqLike: 1,
  scala_collection_mutable_Seq: 1,
  scala_collection_mutable_SeqLike: 1,
  scala_collection_mutable_Cloneable: 1,
  scala_Cloneable: 1,
  java_lang_Cloneable: 1,
  scala_collection_mutable_Iterable: 1,
  scala_collection_mutable_Traversable: 1,
  scala_Mutable: 1,
  scala_collection_SeqViewLike$AbstractTransformed: 1,
  scala_collection_SeqViewLike$Transformed: 1,
  scala_collection_GenSeqViewLike$Transformed: 1,
  scala_collection_SeqView: 1,
  scala_collection_GenSeqView: 1,
  scala_collection_SeqViewLike: 1,
  scala_collection_GenSeqViewLike: 1,
  scala_collection_IterableViewLike$Transformed: 1,
  scala_collection_GenIterableViewLike$Transformed: 1,
  scala_collection_TraversableViewLike$Transformed: 1,
  scala_collection_GenTraversableViewLike$Transformed: 1,
  scala_collection_IterableView: 1,
  scala_collection_GenIterableView: 1,
  scala_collection_IterableViewLike: 1,
  scala_collection_GenIterableViewLike: 1,
  scala_collection_TraversableView: 1,
  scala_collection_GenTraversableView: 1,
  scala_collection_TraversableViewLike: 1,
  scala_collection_GenTraversableViewLike: 1,
  scala_collection_ViewMkString: 1,
  scala_collection_Seq: 1,
  scala_collection_SeqLike: 1,
  scala_collection_GenSeq: 1,
  scala_collection_GenSeqLike: 1,
  scala_collection_Iterable: 1,
  scala_collection_IterableLike: 1,
  scala_Equals: 1,
  scala_collection_GenIterable: 1,
  scala_collection_GenIterableLike: 1,
  scala_collection_Traversable: 1,
  scala_collection_GenTraversable: 1,
  scala_collection_generic_GenericTraversableTemplate: 1,
  scala_collection_TraversableLike: 1,
  scala_collection_GenTraversableLike: 1,
  scala_collection_Parallelizable: 1,
  scala_collection_TraversableOnce: 1,
  scala_collection_GenTraversableOnce: 1,
  scala_collection_generic_FilterMonadic: 1,
  scala_collection_generic_HasNewBuilder: 1,
  scala_PartialFunction: 1,
  scala_Function1: 1,
  java_lang_Object: 1
});
ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.$classData = ScalaJS.data.scala_collection_mutable_IndexedSeqView$$anon$2;
//@ sourceMappingURL=IndexedSeqView$$anon$2.js.map


text:
const requestV4 = require('../v4/request')

/**
 * Metadata Request (Version: 5) => [topics] allow_auto_topic_creation
 *   topics => STRING
 *   allow_auto_topic_creation => BOOLEAN
 */

module.exports = ({ topics, allowAutoTopicCreation = true }) =>
  Object.assign(requestV4({ topics, allowAutoTopicCreation }), { apiVersion: 5 })


text:
class UState::Query
  class Greater < Node
    include Binarity

    def ===(state)
      x = state.send(@a) and x > @b
    end
  end
end


text:
package net.grandcentrix.thirtyinch.sample;

import net.grandcentrix.thirtyinch.TiView;
import net.grandcentrix.thirtyinch.callonmainthread.CallOnMainThread;

public interface SampleView extends TiView {

    @CallOnMainThread
    void showText(final String s);

}


text: <title>ThreatConnect Javascript SDK - Group Retrieve Example</title>


text:
//
//  request.hpp
//  ql_fetcher
//
//  Created by Yarrik Shkurat on 21/09/2017.
//  Copyright © 2017 Yarrik Sh. All rights reserved.
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is furnished
//  to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in all
//  copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
//  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
//  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

#ifndef ql_request_hpp
#define ql_request_hpp

#include "request_params.hpp"
#include "response.hpp"
#include "networking.hpp"
#include <string>
#include <future>
#include <functional>

namespace ql_fetcher
{
    std::string& get_api_key();

    class request
    {
    public:
        request(const std::string& data_code, const std::string& source_code)
        {
            dataset(data_code);
            database(source_code);
            params._api_key = get_api_key();
        }

        request& database(const std::string& source_code)
        {
            params.update(params._database_code != source_code);

            params._database_code = source_code;
            return *this;
        }

        request& dataset(const std::string& data_code)
        {
            params.update(params._dataset_code != data_code);

            params._dataset_code = data_code;
            return *this;
        }

        request& limit(size_t n)
        {
            params.update(params._limit != n);

            params._limit = n;
            return *this;
        }

        request& column(size_t n)
        {
            params.update(params._column_index != n);

            params._column_index = n;
            return *this;
        }

        request& begin(const std::string& yyyy_mm_dd)
        {
            params.update(params._start_date != yyyy_mm_dd);

            params._start_date = yyyy_mm_dd;
            return *this;
        }

        request& end(const std::string& yyyy_mm_dd)
        {
            params.update(params._end_date != yyyy_mm_dd);

            params._end_date = yyyy_mm_dd;
            return *this;
        }

        request& order(sort_order _order)
        {
            params.update(params._order != _order);

            params._order = _order;
            return *this;
        }

        request& timeframe(sampling_freq freq)
        {
            params.update(params._timeframe != freq);

            params._timeframe = freq;
            return *this;
        }

        request& transform(calc_kind calc)
        {
            params.update(params._transform != calc);

            params._transform = calc;
            return *this;
        }

        request& api_key(const std::string& key)
        {
            params.update(params._api_key != key);

            params._api_key = key;
            return *this;
        }

        request& as(result_kind data_kind)
        {
            params.update(params._fetch_as != data_kind);

            params._fetch_as = data_kind;
            return *this;
        }

        const std::string& database() const
        {
            return params._database_code;
        }

        const std::string& dataset() const
        {
            return params._dataset_code;
        }

        size_t limit() const
        {
            return params._limit;
        }

        size_t column() const
        {
            return params._column_index;
        }

        const std::string& begin() const
        {
            return params._start_date;
        }

        const std::string& end() const
        {
            return params._end_date;
        }

        sort_order order() const
        {
            return params._order;
        }

        sampling_freq timeframe() const
        {
            return params._timeframe;
        }

        calc_kind transform() const
        {
            return params._transform;
        }

        const std::string& api_key() const
        {
            return params._api_key;
        }

        std::string url() const
        {
            return form_request(params);
        }

        template <typename CallBack>
        auto with(CallBack cb)
        {
            return std::async(std::launch::deferred,
            [=] {
                return cb(make().get());
            });
        }

        template <typename CallBack, typename FallBack>
        auto with_or(CallBack cb, FallBack fb)
        {
            return with([=](response& resp)
            {
                if (resp.empty() || resp.fail())
                    return fb(resp);
                else
                    return cb(resp);
            });
        }

        std::future<response&> make()
        {
            if (params.updated())
                cached_resp = response{ fetch_raw(url()) };

            return std::async(std::launch::async,
            [&] () -> response& {
                return cached_resp;
            });
        }

    private:
        request_params params;
        response cached_resp { "" };
    };
}

#endif /* ql_request_hpp */


text:
class Solution {
    public String evaluate(String s, List<List<String>> knowledge) {
        Map<String, String> m = new HashMap<>();
        for (List<String> p : knowledge)
            m.put(p.get(0), p.get(1));
        StringBuilder ans = new StringBuilder();
        StringBuilder cur = new StringBuilder();
        boolean in = false;
        for (char c : s.toCharArray()) {
            if (c == '(') {
                in = true;
            } else if (c == ')') {
                if (m.containsKey(cur.toString()))
                    ans.append(m.get(cur.toString()));
                else
                    ans.append("?");
                cur.setLength(0); // 注意StringBuilder没有clear()方法!!!
                in = false;
            } else {
                if (!in) ans.append(c);
                else cur.append(c);
            }
        }
        return ans.toString();
    }
}


text:
package gh2011c.models

import net.liftweb.json.JsonAST.JValue

case class DownloadEventPayload(id: Long, url: String)

object DownloadEventPayload
{
   def apply(json: JValue): Option[DownloadEventPayload] =
   {
      val n2s = gh3.node2String(json)(_)
      val n2l = gh3.node2Long(json)(_)
      val n2os = gh3.node2OptionString(json)(_)

      val id = n2l("id")
      val url = n2s("url")

      val params = Seq(id, url)

      if(params.forall(_.isDefined)) Some(DownloadEventPayload(id.get, url.get))
      else None
   }
}