text:
<?php namespace Cms\Classes;

use URL;
use Str;
use App;
use File;
use View;
use Lang;
use Route;
use Event;
use Config;
use Session;
use Request;
use Response;
use Exception;
use BackendAuth;
use Twig_Environment;
use Cms\Twig\Loader as TwigLoader;
use Cms\Twig\DebugExtension;
use Cms\Twig\Extension as CmsTwigExtension;
use Cms\Models\MaintenanceSetting;
use System\Models\RequestLog;
use System\Helpers\View as ViewHelper;
use System\Classes\ErrorHandler;
use System\Classes\CombineAssets;
use System\Twig\Extension as SystemTwigExtension;
use October\Rain\Exception\AjaxException;
use October\Rain\Exception\SystemException;
use October\Rain\Exception\ValidationException;
use October\Rain\Exception\ApplicationException;
use October\Rain\Parse\Bracket as TextParser;
use Illuminate\Http\RedirectResponse;

/**
 * The CMS controller class.
 * The controller finds and serves requested pages.
 *
 * @package october\cms
 * @author Alexey Bobkov, Samuel Georges
 */
class Controller
{
    use \System\Traits\AssetMaker;
    use \October\Rain\Support\Traits\Emitter;

    /**
     * @var \Cms\Classes\Theme A reference to the CMS theme processed by the controller.
     */
    protected $theme;

    /**
     * @var \Cms\Classes\Router A reference to the Router object.
     */
    protected $router;

    /**
     * @var \Cms\Twig\Loader A reference to the Twig template loader.
     */
    protected $loader;

    /**
     * @var \Cms\Classes\Page A reference to the CMS page template being processed.
     */
    protected $page;

    /**
     * @var \Cms\Classes\CodeBase A reference to the CMS page code section object.
     */
    protected $pageObj;

    /**
     * @var \Cms\Classes\Layout A reference to the CMS layout template used by the page.
     */
    protected $layout;

    /**
     * @var \Cms\Classes\CodeBase A reference to the CMS layout code section object.
     */
    protected $layoutObj;

    /**
     * @var \Twig_Environment Keeps the Twig environment object.
     */
    protected $twig;

    /**
     * @var string Contains the rendered page contents string.
     */
    protected $pageContents;

    /**
     * @var array A list of variables to pass to the page.
     */
    public $vars = [];

    /**
     * @var int Response status code
     */
    protected $statusCode = 200;

    /**
     * @var self Cache of self
     */
    protected static $instance = null;

    /**
     * @var \Cms\Classes\ComponentBase Object of the active component, used internally.
     */
    protected $componentContext = null;

    /**
     * @var array Component partial stack, used internally.
     */
    protected $partialStack = [];

    /**
     * Creates the controller.
     * @param \Cms\Classes\Theme $theme Specifies the CMS theme.
     * If the theme is not specified, the current active theme used.
     */
    public function __construct($theme = null)
    {
        $this->theme = $theme ? $theme : Theme::getActiveTheme();
        if (!$this->theme) {
            throw new CmsException(Lang::get('cms::lang.theme.active.not_found'));
        }

        $this->assetPath = Config::get('cms.themesPath', '/themes').'/'.$this->theme->getDirName();
        $this->router = new Router($this->theme);
        $this->partialStack = new PartialStack;
        $this->initTwigEnvironment();

        self::$instance = $this;
    }

    /**
     * Finds and serves the requested page.
     * If the page cannot be found, returns the page with the URL /404.
     * If the /404 page doesn't exist, returns the system 404 page.
     * @param string $url Specifies the requested page URL.
     * If the parameter is omitted, the current URL used.
     * @return string Returns the processed page content.
     */
    public function run($url = '/')
    {
        if ($url === null) {
            $url = Request::path();
        }

        if (!strlen($url)) {
            $url = '/';
        }

        /*
         * Hidden page
         */
        $page = $this->router->findByUrl($url);
        if ($page && $page->is_hidden) {
            if (!BackendAuth::getUser()) {
                $page = null;
            }
        }

        /*
         * Maintenance mode
         */
        if (
            MaintenanceSetting::isConfigured() &&
            MaintenanceSetting::get('is_enabled', false) &&
            !BackendAuth::getUser()
        ) {
            if (!Request::ajax()) {
                $this->setStatusCode(503);
            }

            $page = Page::loadCached($this->theme, MaintenanceSetting::get('cms_page'));
        }

        /*
         * Extensibility
         */
        if (
            ($event = $this->fireEvent('page.beforeDisplay', [$url, $page], true)) ||
            ($event = Event::fire('cms.page.beforeDisplay', [$this, $url, $page], true))
        ) {
            if ($event instanceof Page) {
                $page = $event;
            }
            else {
                return $event;
            }
        }

        /*
         * If the page was not found, render the 404 page - either provided by the theme or the built-in one.
         */
        if (!$page || $url === '404') {
            if (!Request::ajax()) {
                $this->setStatusCode(404);
            }

            // Log the 404 request
            if (!App::runningUnitTests()) {
                RequestLog::add();
            }

            if (!$page = $this->router->findByUrl('/404')) {
                return Response::make(View::make('cms::404'), $this->statusCode);
            }
        }

        /*
         * Run the page
         */
        $result = $this->runPage($page);

        /*
         * Post-processing
         */
        $result = $this->postProcessResult($page, $url, $result);

        /*
         * Extensibility
         */
        if (
            ($event = $this->fireEvent('page.display', [$url, $page, $result], true)) ||
            ($event = Event::fire('cms.page.display', [$this, $url, $page, $result], true))
        ) {
            return $event;
        }

        if (!is_string($result)) {
            return $result;
        }

        return Response::make($result, $this->statusCode);
    }

    /**
     * Renders a page in its entirety, including component initialization.
     * AJAX will be disabled for this process.
     * @param string $pageFile Specifies the CMS page file name to run.
     * @param array  $parameters  Routing parameters.
     * @param \Cms\Classes\Theme  $theme  Theme object
     */
    public static function render($pageFile, $parameters = [], $theme = null)
    {
        if (!$theme && (!$theme = Theme::getActiveTheme())) {
            throw new CmsException(Lang::get('cms::lang.theme.active.not_found'));
        }

        $controller = new static($theme);
        $controller->getRouter()->setParameters($parameters);

        if (($page = Page::load($theme, $pageFile)) === null) {
            throw new CmsException(Lang::get('cms::lang.page.not_found_name', ['name'=>$pageFile]));
        }

        return $controller->runPage($page, false);
    }

    /**
     * Runs a page directly from its object and supplied parameters.
     * @param \Cms\Classes\Page $page Specifies the CMS page to run.
     * @return string
     */
    public function runPage($page, $useAjax = true)
    {
        $this->page = $page;

        /*
         * If the page doesn't refer any layout, create the fallback layout.
         * Otherwise load the layout specified in the page.
         */
        if (!$page->layout) {
            $layout = Layout::initFallback($this->theme);
        }
        elseif (($layout = Layout::loadCached($this->theme, $page->layout)) === null) {
            throw new CmsException(Lang::get('cms::lang.layout.not_found_name', ['name'=>$page->layout]));
        }

        $this->layout = $layout;

        /*
         * The 'this' variable is reserved for default variables.
         */
        $this->vars['this'] = [
            'page'        => $this->page,
            'layout'      => $this->layout,
            'theme'       => $this->theme,
            'param'       => $this->router->getParameters(),
            'controller'  => $this,
            'environment' => App::environment(),
            'session'     => App::make('session'),
        ];

        /*
         * Check for the presence of validation errors in the session.
         */
        $this->vars['errors'] = (Config::get('session.driver') && Session::has('errors'))
            ? Session::get('errors')
            : new \Illuminate\Support\ViewErrorBag;

        /*
         * Handle AJAX requests and execute the life cycle functions
         */
        $this->initCustomObjects();

        $this->initComponents();

        /*
         * Give the layout and page an opportunity to participate
         * after components are initialized and before AJAX is handled.
         */
        if ($this->layoutObj) {
            CmsException::mask($this->layout, 300);
            $this->layoutObj->onInit();
            CmsException::unmask();
        }

        CmsException::mask($this->page, 300);
        $this->pageObj->onInit();
        CmsException::unmask();

        /*
         * Extensibility
         */
        if (
            ($event = $this->fireEvent('page.init', [$page], true)) ||
            ($event = Event::fire('cms.page.init', [$this, $page], true))
        ) {
            return $event;
        }

        /*
         * Execute AJAX event
         */
        if ($useAjax && $ajaxResponse = $this->execAjaxHandlers()) {
            return $ajaxResponse;
        }

        /*
         * Execute postback handler
         */
        if (
            $useAjax &&
            ($handler = post('_handler')) &&
            ($handlerResponse = $this->runAjaxHandler($handler)) &&
            $handlerResponse !== true
        ) {
            return $handlerResponse;
        }

        /*
         * Execute page lifecycle
         */
        if ($cycleResponse = $this->execPageCycle()) {
            return $cycleResponse;
        }

        /*
         * Extensibility
         */
        if (
            ($event = $this->fireEvent('page.beforeRenderPage', [$page], true)) ||
            ($event = Event::fire('cms.page.beforeRenderPage', [$this, $page], true))
        ) {
            $this->pageContents = $event;
        }
        else {
            /*
             * Render the page
             */
            CmsException::mask($this->page, 400);
            $this->loader->setObject($this->page);
            $template = $this->twig->loadTemplate($this->page->getFilePath());
            $this->pageContents = $template->render($this->vars);
            CmsException::unmask();
        }

        /*
         * Render the layout
         */
        CmsException::mask($this->layout, 400);
        $this->loader->setObject($this->layout);
        $template = $this->twig->loadTemplate($this->layout->getFilePath());
        $result = $template->render($this->vars);
        CmsException::unmask();

        return $result;
    }

    /**
     * Invokes the current page cycle without rendering the page,
     * used by AJAX handler that may rely on the logic inside the action.
     */
    public function pageCycle()
    {
        return $this->execPageCycle();
    }

    /**
     * Executes the page life cycle.
     * Creates an object from the PHP sections of the page and
     * it's layout, then executes their life cycle functions.
     */
    protected function execPageCycle()
    {
        /*
         * Extensibility
         */
        if (
            ($event = $this->fireEvent('page.start', [], true)) ||
            ($event = Event::fire('cms.page.start', [$this], true))
        ) {
            return $event;
        }

        /*
         * Run layout functions
         */
        if ($this->layoutObj) {
            CmsException::mask($this->layout, 300);
            $response = (($result = $this->layoutObj->onStart()) ||
                ($result = $this->layout->runComponents()) ||
                ($result = $this->layoutObj->onBeforePageStart())) ? $result: null;
            CmsException::unmask();

            if ($response) {
                return $response;
            }
        }

        /*
         * Run page functions
         */
        CmsException::mask($this->page, 300);
        $response = (($result = $this->pageObj->onStart()) ||
            ($result = $this->page->runComponents()) ||
            ($result = $this->pageObj->onEnd())) ? $result : null;
        CmsException::unmask();

        if ($response) {
            return $response;
        }

        /*
         * Run remaining layout functions
         */
        if ($this->layoutObj) {
            CmsException::mask($this->layout, 300);
            $response = ($result = $this->layoutObj->onEnd()) ? $result : null;
            CmsException::unmask();
        }

        /*
         * Extensibility
         */
        if (
            ($event = $this->fireEvent('page.end', [], true)) ||
            ($event = Event::fire('cms.page.end', [$this], true))
        ) {
            return $event;
        }

        return $response;
    }

    /**
     * Post-processes page HTML code before it's sent to the client.
     * Note for pre-processing see cms.template.processTwigContent event.
     * @param \Cms\Classes\Page $page Specifies the current CMS page.
     * @param string $url Specifies the current URL.
     * @param string $content The page markup to post processs.
     * @return string Returns the updated result string.
     */
    protected function postProcessResult($page, $url, $content)
    {
        $content = MediaViewHelper::instance()->processHtml($content);

        $dataHolder = (object) ['content' => $content];

        Event::fire('cms.page.postprocess', [$this, $url, $page, $dataHolder]);

        return $dataHolder->content;
    }

    //
    // Initialization
    //

    /**
     * Initializes the Twig environment and loader.
     * Registers the \Cms\Twig\Extension object with Twig.
     * @return void
     */
    protected function initTwigEnvironment()
    {
        $this->loader = new TwigLoader;

        $isDebugMode = Config::get('app.debug', false);

        $options = [
            'auto_reload' => true,
            'debug' => $isDebugMode,
        ];
        if (!Config::get('cms.twigNoCache')) {
            $options['cache'] =  storage_path().'/cms/twig';
        }

        $this->twig = new Twig_Environment($this->loader, $options);
        $this->twig->addExtension(new CmsTwigExtension($this));
        $this->twig->addExtension(new SystemTwigExtension);

        if ($isDebugMode) {
            $this->twig->addExtension(new DebugExtension($this));
        }
    }

    /**
     * Initializes the custom layout and page objects.
     * @return void
     */
    protected function initCustomObjects()
    {
        $this->layoutObj = null;

        if (!$this->layout->isFallBack()) {
            CmsException::mask($this->layout, 300);
            $parser = new CodeParser($this->layout);
            $this->layoutObj = $parser->source($this->page, $this->layout, $this);
            CmsException::unmask();
        }

        CmsException::mask($this->page, 300);
        $parser = new CodeParser($this->page);
        $this->pageObj = $parser->source($this->page, $this->layout, $this);
        CmsException::unmask();
    }

    /**
     * Initializes the components for the layout and page.
     * @return void
     */
    protected function initComponents()
    {
        if (!$this->layout->isFallBack()) {
            foreach ($this->layout->settings['components'] as $component => $properties) {
                list($name, $alias) = strpos($component, ' ')
                    ? explode(' ', $component)
                    : [$component, $component];

                $this->addComponent($name, $alias, $properties, true);
            }
        }

        foreach ($this->page->settings['components'] as $component => $properties) {
            list($name, $alias) = strpos($component, ' ')
                ? explode(' ', $component)
                : [$component, $component];

            $this->addComponent($name, $alias, $properties);
        }

        /*
         * Extensibility
         */
        $this->fireEvent('page.initComponents', [$this->page, $this->layout]);
        Event::fire('cms.page.initComponents', [$this, $this->page, $this->layout]);
    }

    //
    // AJAX
    //

    /**
     * Returns the AJAX handler for the current request, if available.
     * @return string
     */
    public function getAjaxHandler()
    {
        if (!Request::ajax() || Request::method() != 'POST') {
            return null;
        }

        if ($handler = Request::header('X_OCTOBER_REQUEST_HANDLER')) {
            return trim($handler);
        }

        return null;
    }

    /**
     * Executes the page, layout, component and plugin AJAX handlers.
     * @return mixed Returns the AJAX Response object or null.
     */
    protected function execAjaxHandlers()
    {
        if ($handler = $this->getAjaxHandler()) {
            try {
                /*
                 * Validate the handler name
                 */
                if (!preg_match('/^(?:\w+\:{2})?on[A-Z]{1}[\w+]*$/', $handler)) {
                    throw new CmsException(Lang::get('cms::lang.ajax_handler.invalid_name', ['name'=>$handler]));
                }

                /*
                 * Validate the handler partial list
                 */
                if ($partialList = trim(Request::header('X_OCTOBER_REQUEST_PARTIALS'))) {
                    $partialList = explode('&', $partialList);

                    foreach ($partialList as $partial) {
                        if (!preg_match('/^(?:\w+\:{2}|@)?[a-z0-9\_\-\.\/]+$/i', $partial)) {
                            throw new CmsException(Lang::get('cms::lang.partial.invalid_name', ['name'=>$partial]));
                        }
                    }
                }
                else {
                    $partialList = [];
                }

                $responseContents = [];

                /*
                 * Execute the handler
                 */
                if (!$result = $this->runAjaxHandler($handler)) {
                    throw new CmsException(Lang::get('cms::lang.ajax_handler.not_found', ['name'=>$handler]));
                }

                /*
                 * If the handler returned an array, we should add it to output for rendering.
                 * If it is a string, add it to the array with the key "result".
                 */
                if (is_array($result)) {
                    $responseContents = array_merge($responseContents, $result);
                }
                elseif (is_string($result)) {
                    $responseContents['result'] = $result;
                }

                /*
                 * Render partials and return the response as array that will be converted to JSON automatically.
                 */
                foreach ($partialList as $partial) {
                    $responseContents[$partial] = $this->renderPartial($partial);
                }

                /*
                 * If the handler returned a redirect, process it so framework.js knows to redirect
                 * the browser and not the request!
                 */
                if ($result instanceof RedirectResponse) {
                    $responseContents['X_OCTOBER_REDIRECT'] = $result->getTargetUrl();
                }

                return Response::make($responseContents, $this->statusCode);
            }
            catch (ValidationException $ex) {
                /*
                 * Handle validation errors
                 */
                $responseContents['X_OCTOBER_ERROR_FIELDS'] = $ex->getFields();
                $responseContents['X_OCTOBER_ERROR_MESSAGE'] = $ex->getMessage();
                throw new AjaxException($responseContents);
            }
            catch (Exception $ex) {
                throw $ex;
            }
        }

        return null;
    }

    /**
     * Tries to find and run an AJAX handler in the page, layout, components and plugins.
     * The method stops as soon as the handler is found.
     * @param string $handler name of the ajax handler
     * @return boolean Returns true if the handler was found. Returns false otherwise.
     */
    protected function runAjaxHandler($handler)
    {
        /*
         * Process Component handler
         */
        if (strpos($handler, '::')) {

            list($componentName, $handlerName) = explode('::', $handler);
            $componentObj = $this->findComponentByName($componentName);

            if ($componentObj && $componentObj->methodExists($handlerName)) {
                $this->componentContext = $componentObj;
                $result = $componentObj->runAjaxHandler($handlerName);
                return ($result) ?: true;
            }
        }
        /*
         * Process code section handler
         */
        else {
            if (method_exists($this->pageObj, $handler)) {
                $result = $this->pageObj->$handler();
                return ($result) ?: true;
            }

            if (!$this->layout->isFallBack() && method_exists($this->layoutObj, $handler)) {
                $result = $this->layoutObj->$handler();
                return ($result) ?: true;
            }

            /*
             * Cycle each component to locate a usable handler
             */
            if (($componentObj = $this->findComponentByHandler($handler)) !== null) {
                $this->componentContext = $componentObj;
                $result = $componentObj->runAjaxHandler($handler);
                return ($result) ?: true;
            }
        }

        return false;
    }

    //
    // Rendering
    //

    /**
     * Renders a requested page.
     * The framework uses this method internally.
     */
    public function renderPage()
    {
        $contents = $this->pageContents;

        /*
         * Extensibility
         */
        if (
            ($event = $this->fireEvent('page.render', [$contents], true)) ||
            ($event = Event::fire('cms.page.render', [$this, $contents], true))
        ) {
            return $event;
        }

        return $contents;
    }

    /**
     * Renders a requested partial.
     * The framework uses this method internally.
     * @param string $name The view to load.
     * @param array $parameters Parameter variables to pass to the view.
     * @param bool $throwException Throw an exception if the partial is not found.
     * @return mixed Partial contents or false if not throwing an exception.
     */
    public function renderPartial($name, $parameters = [], $throwException = true)
    {
        $vars = $this->vars;
        $this->vars = array_merge($this->vars, $parameters);

        /*
         * Alias @ symbol for ::
         */
        if (substr($name, 0, 1) == '@') {
            $name = '::' . substr($name, 1);
        }

        /*
         * Process Component partial
         */
        if (strpos($name, '::') !== false) {

            list($componentAlias, $partialName) = explode('::', $name);

            /*
             * Component alias not supplied
             */
            if (!strlen($componentAlias)) {
                if ($this->componentContext !== null) {
                    $componentObj = $this->componentContext;
                }
                elseif (($componentObj = $this->findComponentByPartial($partialName)) === null) {
                    if ($throwException) {
                        throw new CmsException(Lang::get('cms::lang.partial.not_found_name', ['name'=>$partialName]));
                    }
                    else {
                        return false;
                    }
                }
            /*
             * Component alias is supplied
             */
            }
            else {
                if (($componentObj = $this->findComponentByName($componentAlias)) === null) {
                    if ($throwException) {
                        throw new CmsException(Lang::get('cms::lang.component.not_found', ['name'=>$componentAlias]));
                    }
                    else {
                        return false;
                    }
                }
            }

            $partial = null;
            $this->componentContext = $componentObj;

            /*
             * Check if the theme has an override
             */
            if (strpos($partialName, '/') === false) {
                $overrideName = $componentObj->alias . '/' . $partialName;
                $partial = Partial::loadCached($this->theme, $overrideName);
            }

            /*
             * Check the component partial
             */
            if ($partial === null) {
                $partial = ComponentPartial::loadCached($componentObj, $partialName);
            }

            if ($partial === null) {
                if ($throwException) {
                    throw new CmsException(Lang::get('cms::lang.partial.not_found_name', ['name'=>$name]));
                }
                else {
                    return false;
                }
            }

            /*
             * Set context for self access
             */
            $this->vars['__SELF__'] = $componentObj;
        }
        else {
            /*
             * Process theme partial
             */
            if (($partial = Partial::loadCached($this->theme, $name)) === null) {
                if ($throwException) {
                    throw new CmsException(Lang::get('cms::lang.partial.not_found_name', ['name'=>$name]));
                }
                else {
                    return false;
                }
            }
        }

        /*
         * Run functions for CMS partials only (Cms\Classes\Partial)
         */

        if ($partial instanceof Partial) {
            $this->partialStack->stackPartial();

            $manager = ComponentManager::instance();

            foreach ($partial->settings['components'] as $component => $properties) {
                // Do not inject the viewBag component to the environment.
                // Not sure if they're needed there by the requirements,
                // but there were problems with array-typed properties used by Static Pages
                // snippets and setComponentPropertiesFromParams(). --ab
                if ($component == 'viewBag')
                    continue;

                list($name, $alias) = strpos($component, ' ')
                    ? explode(' ', $component)
                    : [$component, $component];

                if (!$componentObj = $manager->makeComponent($name, $this->pageObj, $properties)) {
                    throw new CmsException(Lang::get('cms::lang.component.not_found', ['name'=>$name]));
                }

                $componentObj->alias = $alias;
                $parameters[$alias] = $partial->components[$alias] = $componentObj;

                $this->partialStack->addComponent($alias, $componentObj);

                $this->setComponentPropertiesFromParams($componentObj, $parameters);
                $componentObj->init();
            }

            CmsException::mask($this->page, 300);
            $parser = new CodeParser($partial);
            $partialObj = $parser->source($this->page, $this->layout, $this);
            CmsException::unmask();

            CmsException::mask($partial, 300);
            $partialObj->onStart();
            $partial->runComponents();
            $partialObj->onEnd();
            CmsException::unmask();
        }

        /*
         * Render the partial
         */
        CmsException::mask($partial, 400);
        $this->loader->setObject($partial);
        $template = $this->twig->loadTemplate($partial->getFilePath());
        $result = $template->render(array_merge($this->vars, $parameters));
        CmsException::unmask();

        if ($partial instanceof Partial) {
            $this->partialStack->unstackPartial();
        }

        $this->vars = $vars;
        return $result;
    }

    /**
     * Renders a requested content file.
     * The framework uses this method internally.
     * @param string $name The content view to load.
     * @param array $parameters Parameter variables to pass to the view.
     * @return string
     */
    public function renderContent($name, $parameters = [])
    {
        /*
         * Extensibility
         */
        if (
            ($event = $this->fireEvent('page.beforeRenderContent', [$name], true)) ||
            ($event = Event::fire('cms.page.beforeRenderContent', [$this, $name], true))
        ) {
            $content = $event;
        }
        /*
         * Load content from theme
         */
        elseif (($content = Content::loadCached($this->theme, $name)) === null) {
            throw new CmsException(Lang::get('cms::lang.content.not_found_name', ['name'=>$name]));
        }

        $fileContent = $content->parsedMarkup;

        /*
         * Inject global view variables
         */
        $globalVars = ViewHelper::getGlobalVars();
        if (!empty($globalVars)) {
            $parameters = (array) $parameters + $globalVars;
        }

        /*
         * Parse basic template variables
         */
        if (!empty($parameters)) {
            $fileContent = TextParser::parse($fileContent, $parameters);
        }

        /*
         * Extensibility
         */
        if (
            ($event = $this->fireEvent('page.renderContent', [$name, $fileContent], true)) ||
            ($event = Event::fire('cms.page.renderContent', [$this, $name, $fileContent], true))
        ) {
            return $event;
        }

        return $fileContent;
    }

    /**
     * Renders a component's default content.
     * @param $name
     * @param array $parameters
     * @return string Returns the component default contents.
     */
    public function renderComponent($name, $parameters = [])
    {
        if ($componentObj = $this->findComponentByName($name)) {
            $componentObj->id = uniqid($name);
            $componentObj->setProperties(array_merge($componentObj->getProperties(), $parameters));
            if ($result = $componentObj->onRender()) {
                return $result;
            }
        }

        return $this->renderPartial($name.'::default', [], false);
    }

    //
    // Setters
    //

    /**
     * Sets the status code for the current web response.
     * @param int $code Status code
     * @return self
     */
    public function setStatusCode($code)
    {
        $this->statusCode = (int) $code;
        return $this;
    }

    //
    // Getters
    //

    /**
     * Returns an existing instance of the controller.
     * If the controller doesn't exists, returns null.
     * @return mixed Returns the controller object or null.
     */
    public static function getController()
    {
        return self::$instance;
    }

    /**
     * Returns the current CMS theme.
     * @return \Cms\Classes\Theme
     */
    public function getTheme()
    {
        return $this->theme;
    }

    /**
     * Returns the Twig environment.
     * @return Twig_Environment
     */
    public function getTwig()
    {
        return $this->twig;
    }

    /**
     * Returns the Twig loader.
     * @return \Cms\Twig\Loader
     */
    public function getLoader()
    {
        return $this->loader;
    }

    /**
     * Returns the routing object.
     * @return \Cms\Classes\Router
     */
    public function getRouter()
    {
        return $this->router;
    }

    /**
     * Intended to be called from the layout, returns the page code base object.
     * @return \Cms\Classes\CodeBase
     */
    public function getPageObject()
    {
        return $this->pageObj;
    }

    /**
     * Returns the CMS page object being processed by the controller.
     * The object is not available on the early stages of the controller
     * initialization.
     * @return \Cms\Classes\Page Returns the Page object or null.
     */
    public function getPage()
    {
        return $this->page;
    }

    /**
     * Intended to be called from the page, returns the layout code base object.
     * @return \Cms\Classes\CodeBase
     */
    public function getLayoutObject()
    {
        return $this->layoutObj;
    }

    //
    // Page helpers
    //

    /**
     * Looks up the URL for a supplied page and returns it relative to the website root.
     *
     * @param mixed $name Specifies the Cms Page file name.
     * @param array $parameters Route parameters to consider in the URL.
     * @param bool $routePersistence By default the existing routing parameters will be included
     * @return string
     */
    public function pageUrl($name, $parameters = [], $routePersistence = true)
    {
        if (!$name) {
            return $this->currentPageUrl($parameters, $routePersistence);
        }

        /*
         * Second parameter can act as third
         */
        if (is_bool($parameters)) {
            $routePersistence = $parameters;
        }

        if (!is_array($parameters)) {
            $parameters = [];
        }

        if ($routePersistence) {
            $parameters = array_merge($this->router->getParameters(), $parameters);
        }

        if (!$url = $this->router->findByFile($name, $parameters)) {
            return null;
        }

        if (substr($url, 0, 1) == '/') {
            $url = substr($url, 1);
        }

        $routeAction = 'Cms\Classes\CmsController@run';
        $actionExists = Route::getRoutes()->getByAction($routeAction) !== null;

        if ($actionExists) {
            return URL::action($routeAction, ['slug' => $url]);
        }
        else {
            return URL::to($url);
        }
    }

    /**
     * Looks up the current page URL with supplied parameters and route persistence.
     * @param array $parameters
     * @param bool $routePersistence
     * @return null|string
     */
    public function currentPageUrl($parameters = [], $routePersistence = true)
    {
        if (!$currentFile = $this->page->getFileName()) {
            return null;
        }

        return $this->pageUrl($currentFile, $parameters, $routePersistence);
    }

    /**
     * Converts supplied URL to a theme URL relative to the website root. If the URL provided is an
     * array then the files will be combined.
     * @param mixed $url Specifies the theme-relative URL. If null, the theme path is returned.
     * @return string
     */
    public function themeUrl($url = null)
    {
        $themeDir = $this->getTheme()->getDirName();

        if (is_array($url)) {
            $_url = URL::to(CombineAssets::combine($url, themes_path().'/'.$themeDir));
        }
        else {
            $_url = Config::get('cms.themesPath', '/themes').'/'.$themeDir;
            if ($url !== null) {
                $_url .= '/'.$url;
            }
            $_url = URL::asset($_url);
        }

        return $_url;
    }

    /**
     * Converts supplied file to a URL relative to the media library.
     * @param string $file Specifies the media-relative file
     * @return string
     */
    public function mediaUrl($file = null)
    {
        return MediaLibrary::url($file);
    }

    /**
     * Returns a routing parameter.
     * @param string $name Routing parameter name.
     * @param string $default Default to use if none is found.
     * @return string
     */
    public function param($name, $default = null)
    {
        return $this->router->getParameter($name, $default);
    }

    //
    // Component helpers
    //

    /**
     * Adds a component to the page object
     * @param mixed  $name        Component class name or short name
     * @param string $alias       Alias to give the component
     * @param array  $properties  Component properties
     * @param bool   $addToLayout Add to layout, instead of page
     * @return ComponentBase Component object
     */
    public function addComponent($name, $alias, $properties, $addToLayout = false)
    {
        $manager = ComponentManager::instance();

        if ($addToLayout) {
            if (!$componentObj = $manager->makeComponent($name, $this->layoutObj, $properties)) {
                throw new CmsException(Lang::get('cms::lang.component.not_found', ['name'=>$name]));
            }

            $componentObj->alias = $alias;
            $this->vars[$alias] = $this->layout->components[$alias] = $componentObj;
        }
        else {
            if (!$componentObj = $manager->makeComponent($name, $this->pageObj, $properties)) {
                throw new CmsException(Lang::get('cms::lang.component.not_found', ['name'=>$name]));
            }

            $componentObj->alias = $alias;
            $this->vars[$alias] = $this->page->components[$alias] = $componentObj;
        }

        $this->setComponentPropertiesFromParams($componentObj);
        $componentObj->init();
        return $componentObj;
    }

    /**
     * Searches the layout and page components by an alias
     * @param $name
     * @return ComponentBase The component object, if found
     */
    public function findComponentByName($name)
    {
        if (isset($this->page->components[$name])) {
            return $this->page->components[$name];
        }

        if (isset($this->layout->components[$name])) {
            return $this->layout->components[$name];
        }

        $partialComponent = $this->partialStack->getComponent($name);
        if ($partialComponent !== null) {
            return $partialComponent;
        }

        return null;
    }

    /**
     * Searches the layout and page components by an AJAX handler
     * @param string $handler
     * @return ComponentBase The component object, if found
     */
    public function findComponentByHandler($handler)
    {
        foreach ($this->page->components as $component) {
            if (method_exists($component, $handler)) {
                return $component;
            }
        }

        foreach ($this->layout->components as $component) {
            if (method_exists($component, $handler)) {
                return $component;
            }
        }

        return null;
    }

    /**
     * Searches the layout and page components by a partial file
     * @param string $partial
     * @return ComponentBase The component object, if found
     */
    public function findComponentByPartial($partial)
    {
        foreach ($this->page->components as $component) {
            if (ComponentPartial::check($component, $partial)) {
                return $component;
            }
        }

        foreach ($this->layout->components as $component) {
            if (ComponentPartial::check($component, $partial)) {
                return $component;
            }
        }

        return null;
    }

    /**
     * Set the component context manually, used by Components when calling renderPartial.
     * @param ComponentBase $component
     * @return void
     */
    public function setComponentContext(ComponentBase $component = null)
    {
        $this->componentContext = $component;
    }

    /**
     * Sets component property values from partial parameters.
     * The property values should be defined as {{ param }}.
     * @param ComponentBase $component The component object.
     * @param array $parameters Specifies the partial parameters.
     */
    protected function setComponentPropertiesFromParams($component, $parameters = [])
    {
        $properties = $component->getProperties();
        $routerParameters = $this->router->getParameters();

        foreach ($properties as $propertyName => $propertyValue) {
            if (is_array($propertyValue)) {
                continue;
            }

            $matches = [];
            if (preg_match('/^\{\{([^\}]+)\}\}$/', $propertyValue, $matches)) {
                $paramName = trim($matches[1]);

                if (substr($paramName, 0, 1) == ':') {
                    $routeParamName = substr($paramName, 1);
                    $newPropertyValue = array_key_exists($routeParamName, $routerParameters)
                        ? $routerParameters[$routeParamName]
                        : null;

                }
                else {
                    $newPropertyValue = array_key_exists($paramName, $parameters)
                        ? $parameters[$paramName]
                        : null;
                }

                $component->setProperty($propertyName, $newPropertyValue);
                $component->setExternalPropertyName($propertyName, $paramName);
            }
        }
    }
}


text:
@implementation NSURL (LFURLRouteParser)

- (NSDictionary *)lfur_parseAsPathInfo {
    if ([self path].length) {
        NSMutableDictionary *result = [NSMutableDictionary dictionary];
        __block NSString *keyString;
        __block NSString *valueString;
        NSArray *components = [[[self path] substringFromIndex:1] componentsSeparatedByString:@"/"];
        [components enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            if (idx % 2 == 0) {
                keyString = obj;
            }
            else if (idx % 2 == 1) {
                valueString = obj;
            }
            if (keyString != nil && valueString != nil) {
                [result setObject:valueString
                           forKey:keyString];
                keyString = valueString = nil;
            }
        }];
        return [result copy];
    }
    return nil;
}

- (NSDictionary *)lfur_parseAsQueryString {
    if ([self query].length) {
        NSMutableDictionary *result = [NSMutableDictionary dictionary];
        NSString *pattern = @"([^=]+)=(.*?)&";
        NSRegularExpression *expression = [[NSRegularExpression alloc] initWithPattern:pattern
                                                                               options:kNilOptions
                                                                                error:nil];
        NSString *query = [[self query] stringByAppendingString:@"&"];
        NSArray *matches = [expression matchesInString:query
                                               options:NSMatchingReportCompletion
                                                 range:NSMakeRange(0, [query length])];
        [matches enumerateObjectsUsingBlock:^(NSTextCheckingResult *obj, NSUInteger idx, BOOL *stop) {
            if ([obj numberOfRanges] >= 3) {
                [result setObject:[query substringWithRange:[obj rangeAtIndex:2]]
                           forKey:[query substringWithRange:[obj rangeAtIndex:1]]];
            }
        }];
        return result;
    }
    return nil;
}

@end

redpajama_set_name: RedPajamaGithub


text:
% tss2_pcrread(1) tpm2-tools | General Commands Manual
%
% APRIL 2019

# NAME

**tss2_pcrread**(1) -

# SYNOPSIS

**tss2_pcrread** [*OPTIONS*]

[common fapi references](common/tss2-fapi-references.md)

# DESCRIPTION

**tss2_pcrread**(1) - This command provides a PCRs value and corresponding event
log. The PCR bank to be used per PCR is defined in the cryptographic profile
(cf., **fapi-profile(5)**).

# OPTIONS

These are the available options:

  * **-o**, **\--pcrValue**=_FILENAME_ or _-_ (for stdout):

    Returns PCR digest. Optional parameter.

  * **-x**, **\--pcrIndex**=_INTEGER_:

    Identifies the PCR to read.

  * **-f**, **\--force**:

    Force overwriting the output files.

  * **-l**, **\--pcrLog**=_FILENAME_ or _-_ (for stdout):

    Returns the PCR log for that PCR. Optional parameter.

    PCR event logs are a list (arbitrary length JSON array) of log entries with
    the following content.

        - recnum: Unique record number
        - pcr: PCR index
        - digest: The digests
        - type: The type of event. At the moment the only possible value is: "LINUX_IMA" (legacy IMA)
        - eventDigest: Digest of the event; e.g. the digest of the measured file
        - eventName: Name of the event; e.g. the name of the measured file.

[common tss2 options](common/tss2-options.md)

# EXAMPLE
```
tss2_pcrread --pcrIndex=16 --pcrValue=pcrValue.file --pcrLog=pcrLog.file
```

# RETURNS

0 on success or 1 on failure.

[footer](common/footer.md)


text:
#ifndef SKY_ENGINE_CORE_DOM_SHADOW_INSERTIONPOINT_H_
#define SKY_ENGINE_CORE_DOM_SHADOW_INSERTIONPOINT_H_

#include "sky/engine/core/css/CSSSelectorList.h"
#include "sky/engine/core/dom/shadow/ContentDistribution.h"
#include "sky/engine/core/dom/shadow/ShadowRoot.h"
#include "sky/engine/core/html/HTMLElement.h"

namespace blink {

class InsertionPoint : public HTMLElement {
public:
    virtual ~InsertionPoint();

    bool hasDistribution() const { return !m_distribution.isEmpty(); }
    void setDistribution(ContentDistribution&);
    void clearDistribution() { m_distribution.clear(); }
    bool isActive() const;
    bool canBeActive() const;

    bool isContentInsertionPoint() const;

    Vector<RefPtr<Node>> getDistributedNodes();

    virtual bool canAffectSelector() const { return false; }

    void attachDistribution(const AttachContext&);
    void detachDistribution(const AttachContext&);

    bool shouldUseFallbackElements() const;

    size_t size() const { return m_distribution.size(); }
    Node* at(size_t index)  const { return m_distribution.at(index).get(); }
    Node* first() const { return m_distribution.isEmpty() ? 0 : m_distribution.first().get(); }
    Node* last() const { return m_distribution.isEmpty() ? 0 : m_distribution.last().get(); }
    Node* nextTo(const Node* node) const { return m_distribution.nextTo(node); }
    Node* previousTo(const Node* node) const { return m_distribution.previousTo(node); }

    void willRecalcStyle(StyleRecalcChange);

protected:
    InsertionPoint(const QualifiedName&, Document&);
    virtual void childrenChanged(const ChildrenChange&) override;
    virtual void insertedInto(ContainerNode*) override;
    virtual void removedFrom(ContainerNode*) override;

private:
    bool isInsertionPoint() const = delete; // This will catch anyone doing an unnecessary check.

    ContentDistribution m_distribution;
    bool m_registeredWithShadowRoot;
};

typedef Vector<RefPtr<InsertionPoint> > DestinationInsertionPoints;

DEFINE_ELEMENT_TYPE_CASTS(InsertionPoint, isInsertionPoint());

inline bool isActiveInsertionPoint(const Node& node)
{
    return node.isInsertionPoint() && toInsertionPoint(node).isActive();
}

inline ElementShadow* shadowWhereNodeCanBeDistributed(const Node& node)
{
    Node* parent = node.parentNode();
    if (!parent)
        return 0;
    if (isActiveInsertionPoint(*parent))
        return node.shadowHost()->shadow();
    if (parent->isElementNode())
        return toElement(parent)->shadow();
    return 0;
}

const InsertionPoint* resolveReprojection(const Node*);

void collectDestinationInsertionPoints(const Node&, Vector<RawPtr<InsertionPoint>, 8>& results);

} // namespace blink

#endif  // SKY_ENGINE_CORE_DOM_SHADOW_INSERTIONPOINT_H_


text:
<?php namespace OpenCFP\Provider;

use Aptoma\Twig\Extension\MarkdownExtension;
use Ciconia\Ciconia;
use Ciconia\Extension\Gfm\InlineStyleExtension;
use Ciconia\Extension\Gfm\WhiteSpaceExtension;
use Silex\Application;
use Silex\Provider\TwigServiceProvider as SilexTwigServiceProvider;
use Silex\ServiceProviderInterface;
use Twig_Environment;
use Twig_Extension_Debug;
use Twig_SimpleFunction;

class TwigServiceProvider implements ServiceProviderInterface
{
    /**
     * {@inheritdoc}
     */
    public function register(Application $app)
    {
        $app->register(new SilexTwigServiceProvider(), [
            'twig.path' => $app->templatesPath(),
            'twig.options' => [
                'debug' => !$app->isProduction(),
                'cache' => $app->config('cache.enabled') ? $app->cacheTwigPath() : false,
            ],
        ]);

        /* @var Twig_Environment $twig */
        $twig = $app['twig'];

        if (!$app->isProduction()) {
            $twig->addExtension(new Twig_Extension_Debug);
        }

        $twig->addFunction(new Twig_SimpleFunction('uploads', function ($path) {
            return '/uploads/' . $path;
        }));

        $twig->addFunction(new Twig_SimpleFunction('assets', function ($path) {
            return '/assets/' . $path;
        }));

        $twig->addGlobal('site', $app->config('application'));

        // Twig Markdown Extension
        $markdown = new Ciconia();
        $markdown->addExtension(new InlineStyleExtension);
        $markdown->addExtension(new WhiteSpaceExtension);
        $engine = new CiconiaEngine($markdown);

        $twig->addExtension(new MarkdownExtension($engine));
    }

    /**
     * {@inheritdoc}
     */
    public function boot(Application $app)
    {
    }
}


text:
// Copyright 2011 Software Freedom Conservancy. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview File to include for turning any HTML file page into a WebDriver
 * JSUnit test suite by configuring an onload listener to the body that will
 * instantiate and start the test runner.
 */

goog.provide('webdriver.testing.jsunit');
goog.provide('webdriver.testing.jsunit.TestRunner');

goog.require('goog.testing.TestRunner');
goog.require('webdriver.testing.Client');
goog.require('webdriver.testing.TestCase');

/**
 * Constructs a test runner.
 * @constructor
 * @extends {goog.testing.TestRunner}
 */
webdriver.testing.jsunit.TestRunner = function() {
  goog.base(this);

  /** @private {!webdriver.testing.Client} */
  this.client_ = new webdriver.testing.Client();
};
goog.inherits(webdriver.testing.jsunit.TestRunner, goog.testing.TestRunner);

/**
 * Element created in the document to add test results to.
 * @private {Element}
 */
webdriver.testing.jsunit.TestRunner.prototype.logEl_ = null;

/**
 * DOM element used to stored screenshots. Screenshots are stored in the DOM to
 * avoid exhausting JS stack-space.
 * @private {Element}
 */
webdriver.testing.jsunit.TestRunner.prototype.screenshotCacheEl_ = null;

/** @override */
webdriver.testing.jsunit.TestRunner.prototype.initialize = function(testCase) {
  goog.base(this, 'initialize', testCase);
  this.screenshotCacheEl_ = document.createElement('div');
  document.body.appendChild(this.screenshotCacheEl_);
  this.screenshotCacheEl_.style.display = 'none';
};

/** @override */
webdriver.testing.jsunit.TestRunner.prototype.execute = function() {
  if (!this.testCase) {
    throw Error('The test runner must be initialized with a test case before ' +
                'execute can be called.');
  }
  this.screenshotCacheEl_.innerHTML = '';
  this.client_.sendInitEvent();
  this.testCase.setCompletedCallback(goog.bind(this.onComplete_, this));
  this.testCase.runTests();
};

/**
 * Writes a nicely formatted log out to the document. Overrides
 * {@link goog.testing.TestRunner#writeLog} to handle writing screenshots to the
 *     log.
 * @param {string} log The string to write.
 * @override
 */
webdriver.testing.jsunit.TestRunner.prototype.writeLog = function(log) {
  var lines = log.split('\n');
  for (var i = 0; i < lines.length; i++) {
    var line = lines[i];
    var color;
    var isFailOrError = /FAILED/.test(line) || /ERROR/.test(line);
    var isScreenshot = / \[SCREENSHOT\] /.test(line);
    if (/PASSED/.test(line)) {
      color = 'darkgreen';
    } else if (isFailOrError) {
      color = 'darkred';
    } else if (isScreenshot) {
      color = 'darkblue';
    } else {
      color = '#333';
    }

    var div = document.createElement('div');
    if (line.substr(0, 2) == '> ') {
      // The stack trace may contain links so it has to be interpreted as HTML.
      div.innerHTML = line;
    } else {
      div.appendChild(document.createTextNode(line));
    }

    if (isFailOrError) {
      var testNameMatch = /(\S+) (\[[^\]]*] )?: (FAILED|ERROR)/.exec(line);
      if (testNameMatch) {
        // Build a URL to run the test individually.  If this test was already
        // part of another subset test, we need to overwrite the old runTests
        // query parameter.  We also need to do this without bringing in any
        // extra dependencies, otherwise we could mask missing dependency bugs.
        var newSearch = 'runTests=' + testNameMatch[1];
        var search = window.location.search;
        if (search) {
          var oldTests = /runTests=([^&]*)/.exec(search);
          if (oldTests) {
            newSearch = search.substr(0, oldTests.index) +
                        newSearch +
                        search.substr(oldTests.index + oldTests[0].length);
          } else {
            newSearch = search + '&' + newSearch;
          }
        } else {
          newSearch = '?' + newSearch;
        }
        var href = window.location.href;
        var hash = window.location.hash;
        if (hash && hash.charAt(0) != '#') {
          hash = '#' + hash;
        }
        href = href.split('#')[0].split('?')[0] + newSearch + hash;

        // Add the link.
        var a = document.createElement('A');
        a.innerHTML = '(run individually)';
        a.style.fontSize = '0.8em';
        a.href = href;
        div.appendChild(document.createTextNode(' '));
        div.appendChild(a);
      }
    }

    if (isScreenshot && this.screenshotCacheEl_.childNodes.length) {
      var nextScreenshot = this.screenshotCacheEl_.childNodes[0];
      this.screenshotCacheEl_.removeChild(nextScreenshot);

      a = document.createElement('A');
      a.style.fontSize = '0.8em';
      a.href = 'javascript:void(0);';
      a.onclick = goog.partial(toggleVisibility, a, nextScreenshot);
      toggleVisibility(a, nextScreenshot);
      div.appendChild(document.createTextNode(' '));
      div.appendChild(a);
    }

    div.style.color = color;
    div.style.font = 'normal 100% monospace';

    try {
      div.style.whiteSpace = 'pre-wrap';
    } catch (e) {
      // NOTE(user): IE raises an exception when assigning to pre-wrap.
      // Thankfully, it doesn't collapse whitespace when using monospace fonts,
      // so it will display correctly if we ignore the exception.
    }

    if (i < 2) {
      div.style.fontWeight = 'bold';
    }
    this.logEl_.appendChild(div);

    if (nextScreenshot) {
      a = document.createElement('A');
      // Accessing the |src| property in IE sometimes results in an
      // "Invalid pointer" error, which indicates it has been garbage
      // collected. This does not occur when using getAttribute.
      a.href = nextScreenshot.getAttribute('src');
      a.target = '_blank';
      a.appendChild(nextScreenshot);
      this.logEl_.appendChild(a);
      nextScreenshot = null;
    }
  }

  function toggleVisibility(link, img) {
    if (img.style.display === 'none') {
      img.style.display = '';
      link.innerHTML = '(hide screenshot)';
    } else {
      img.style.display = 'none';
      link.innerHTML = '(view screenshot)';
    }
  }
};

/**
 * Copied from goog.testing.TestRunner.prototype.onComplete_, which has private
 * visibility.
 * @private
 */
webdriver.testing.jsunit.TestRunner.prototype.onComplete_ = function() {
  var log = this.testCase.getReport(true);
  if (this.errors.length > 0) {
    log += '\n' + this.errors.join('\n');
  }

  if (!this.logEl_) {
    this.logEl_ = document.createElement('div');
    document.body.appendChild(this.logEl_);
  }

  // Remove all children from the log element.
  var logEl = this.logEl_;
  while (logEl.firstChild) {
    logEl.removeChild(logEl.firstChild);
  }

  this.writeLog(log);
  this.client_.sendResultsEvent(this.isSuccess(), this.getReport(true));
};

/**
 * Takes a screenshot. In addition to saving the screenshot for viewing in the
 * HTML logs, the screenshot will also be saved using
 * @param {!webdriver.WebDriver} driver The driver to take the screenshot with.
 * @param {string=} opt_label An optional debug label to identify the screenshot
 *     with.
 * @return {!webdriver.promise.Promise} A promise that will be resolved to the
 *     screenshot as a base-64 encoded PNG.
 */
webdriver.testing.jsunit.TestRunner.prototype.takeScreenshot = function(
    driver, opt_label) {
  if (!this.isInitialized()) {
    throw Error(
        'The test runner must be initialized before it may be used to' +
        ' take screenshots');
  }

  var client = this.client_;
  var testCase = this.testCase;
  var screenshotCache = this.screenshotCacheEl_;
  return driver.takeScreenshot().then(function(png) {
    client.sendScreenshotEvent(png, opt_label);

    var img = document.createElement('img');
    img.src = 'data:image/png;base64,' + png;
    img.style.border = '1px solid black';
    img.style.maxWidth = '500px';
    screenshotCache.appendChild(img);

    if (testCase) {
      testCase.saveMessage('[SCREENSHOT] ' + (opt_label || '<Not Labeled>'));
    }
    return png;
  });
};

(function() {
  var tr = new webdriver.testing.jsunit.TestRunner();

  // Export our test runner so it can be accessed by Selenium/WebDriver. This
  // will only work if webdriver.WebDriver is using a pure-JavaScript
  // webdriver.CommandExecutor. Otherwise, the JS-client could change the
  // driver's focus to another window or frame and the Java/Python-client
  // wouldn't be able to access this object.
  goog.exportSymbol('G_testRunner', tr);
  goog.exportSymbol('G_testRunner.initialize', tr.initialize);
  goog.exportSymbol('G_testRunner.isInitialized', tr.isInitialized);
  goog.exportSymbol('G_testRunner.isFinished', tr.isFinished);
  goog.exportSymbol('G_testRunner.isSuccess', tr.isSuccess);
  goog.exportSymbol('G_testRunner.getReport', tr.getReport);
  goog.exportSymbol('G_testRunner.getRunTime', tr.getRunTime);
  goog.exportSymbol('G_testRunner.getNumFilesLoaded', tr.getNumFilesLoaded);
  goog.exportSymbol('G_testRunner.setStrict', tr.setStrict);
  goog.exportSymbol('G_testRunner.logTestFailure', tr.logTestFailure);

  // Export debug as a global function for JSUnit compatibility.  This just
  // calls log on the current test case.
  if (!goog.global['debug']) {
    goog.exportSymbol('debug', goog.bind(tr.log, tr));
  }

  // Add an error handler to report errors that may occur during
  // initialization of the page.
  var onerror = window.onerror;
  window.onerror = function(error, url, line) {
    // Call any existing onerror handlers.
    if (onerror) {
      onerror(error, url, line);
    }
    if (typeof error == 'object') {
      // Webkit started passing an event object as the only argument to
      // window.onerror.  It doesn't contain an error message, url or line
      // number.  We therefore log as much info as we can.
      if (error.target && error.target.tagName == 'SCRIPT') {
        tr.logError('UNKNOWN ERROR: Script ' + error.target.src);
      } else {
        tr.logError('UNKNOWN ERROR: No error information available.');
      }
    } else {
      tr.logError('JS ERROR: ' + error + '\nURL: ' + url + '\nLine: ' + line);
    }
  };

  var onload = window.onload;
  window.onload = function() {
    // Call any existing onload handlers.
    if (onload) {
      onload();
    }

    var testCase = new webdriver.testing.TestCase(document.title);
    testCase.autoDiscoverTests();

    tr.initialize(testCase);
    tr.execute();
  };
})();


text:
#include "tiledb/sm/buffer/buffer_list.h"
#include "tiledb/common/logger.h"
#include "tiledb/sm/buffer/buffer.h"

#include <algorithm>

using namespace tiledb::common;

namespace tiledb {
namespace sm {

BufferList::BufferList()
    : current_buffer_index_(0)
    , current_relative_offset_(0)
    , offset_(0) {
}

Status BufferList::add_buffer(Buffer&& buffer) {
  buffers_.emplace_back(std::move(buffer));
  return Status::Ok();
}

Status BufferList::get_buffer(uint64_t index, Buffer** buffer) {
  if (index >= buffers_.size())
    return LOG_STATUS(Status_BufferError(
        "Cannot get buffer " + std::to_string(index) +
        " from buffer list; index out of bounds."));

  *buffer = &buffers_[index];

  return Status::Ok();
}

uint64_t BufferList::num_buffers() const {
  return buffers_.size();
}

Status BufferList::read(void* dest, uint64_t nbytes) {
  uint64_t bytes_read = 0;
  RETURN_NOT_OK(read(dest, nbytes, &bytes_read));

  if (bytes_read != nbytes)
    return LOG_STATUS(Status_BufferError(
        "BufferList error; could not read requested byte count."));

  return Status::Ok();
}

Status BufferList::read_at_most(
    void* dest, uint64_t nbytes, uint64_t* bytes_read) {
  return read(dest, nbytes, bytes_read);
}

Status BufferList::read(void* dest, uint64_t nbytes, uint64_t* bytes_read) {
  uint64_t bytes_left = nbytes;
  uint64_t dest_offset = 0;
  auto dest_ptr = static_cast<char*>(dest);

  // Starting from current buffer, read bytes until finished.
  for (size_t idx = current_buffer_index_;
       idx < buffers_.size() && bytes_left > 0;
       ++idx) {
    Buffer& src = buffers_[idx];
    src.set_offset(current_relative_offset_);

    // Read from buffer
    const uint64_t bytes_in_src = src.size() - current_relative_offset_;
    const uint64_t bytes_from_src = std::min(bytes_in_src, bytes_left);
    // If the destination pointer is not null, then read into it
    // if it is null then we are just seeking
    if (dest_ptr != nullptr)
      RETURN_NOT_OK(src.read(dest_ptr + dest_offset, bytes_from_src));
    bytes_left -= bytes_from_src;
    dest_offset += bytes_from_src;

    // Always keep current buffer and offset in sync.
    current_buffer_index_ = idx;
    current_relative_offset_ += bytes_from_src;

    if (bytes_left > 0) {
      // Moving to next buffer; set relative offset to 0.
      current_relative_offset_ = 0;
    }
  }

  if (bytes_read != nullptr)
    *bytes_read = nbytes - bytes_left;

  return Status::Ok();
}

Status BufferList::seek(off_t offset, int whence) {
  switch (whence) {
    case SEEK_SET:
      // We just reset the offsets to 0/start, then fall through to seek_current
      reset_offset();
      // fall through
    case SEEK_CUR:
      return read(nullptr, offset);
    case SEEK_END:
      return Status_BufferError(
          "SEEK_END operation not supported for BufferList");
    default:
      return Status_BufferError("Invalid seek operation for BufferList");
  }

  return Status::Ok();
}

void BufferList::reset_offset() {
  offset_ = 0;
  current_buffer_index_ = 0;
  current_relative_offset_ = 0;
}

uint64_t BufferList::total_size() const {
  uint64_t size = 0;
  for (const auto& b : buffers_)
    size += b.size();
  return size;
}

}  // namespace sm
}  // namespace tiledb


text:
import org.globus.cog.abstraction.impl.common.AbstractionFactory;
import org.globus.cog.abstraction.impl.common.StatusEvent;
import org.globus.cog.abstraction.impl.common.task.JobSpecificationImpl;
import org.globus.cog.abstraction.impl.common.task.ServiceContactImpl;
import org.globus.cog.abstraction.impl.common.task.ServiceImpl;
import org.globus.cog.abstraction.impl.common.task.TaskImpl;
import org.globus.cog.abstraction.interfaces.JobSpecification;
import org.globus.cog.abstraction.interfaces.Service;
import org.globus.cog.abstraction.interfaces.Status;
import org.globus.cog.abstraction.interfaces.StatusListener;
import org.globus.cog.abstraction.interfaces.Task;

/*
gridSites.put("karwendel.dps.uibk.ac.at",new GridSite("karwendel.dps.uibk.ac.at","/home/fritz/deployments/povray/povray","/software/ffmpeg/bin/ffmpeg"));
gridSites.put("login.leo1.uibk.ac.at",new GridSite("login.leo1.uibk.ac.at","/home/c703/c703246/povray/bin/povray","/home/c703/c703246/scratch/leo1/ffmpeg/bin/ffmpeg"));
gridSites.put("altix1.uibk.ac.at",new GridSite("altix1.uibk.ac.at","/home/cb56/cb561004/povray/bin/povray","/home/cb56/cb561004/ffmpeg/bin/ffpmeg"));
gridSites.put("alex.jku.austriangrid.at",new GridSite("alex.jku.austriangrid.at","/data1/home/agpool/agp11169/povray/bin/povray","/data1/home/agpool/agp11169/ffmpeg/bin/ffmpeg"));
gridSites.put("lilli.edvz.uni-linz.ac.at",new GridSite("lilli.edvz.uni-linz.ac.at","/usr/bin/povray","/home/agpool/agp11138/ffmpeg/ffmpeg"));
*/

public class Slave {

//	../sbin/hadoop-daemon.sh --config ../etc/hadoop start datanode
//	../sbin/hadoop-daemon.sh --config ../etc/hadoop start tasktracker

	public Slave(String exec, String parameter) {
		submitJob(exec, parameter, "slaves.out", "slaves.err","karwendel.dps.uibk.ac.at","sge");
	}

	public void submitJob(String exec, String args, String stdout, String stderr,
			String hostName, String jobManager) {
		try {

            JobSpecification js = new JobSpecificationImpl();
            js.setExecutable(exec);
            js.setArguments(args);
            js.setStdOutput(stdout);
            js.setStdError(stderr);

            Task t = new TaskImpl("test", Task.JOB_SUBMISSION);
            t.setSpecification(js);

            t.setService(Service.JOB_SUBMISSION_SERVICE, new ServiceImpl("gt2",
            		new ServiceContactImpl(hostName+"/jobmanager-"+jobManager), null));

            System.out.println("Submitting Job @ "+hostName+"/jobmanager-"+jobManager);

            SlaveStatusListener listener = new SlaveStatusListener(this);
            t.addStatusListener(listener);

            AbstractionFactory.newExecutionTaskHandler("gt2").submit(t);

            //System.out.println("waiting 30sec... and cancel task");
            //Thread.sleep(30000);
            //AbstractionFactory.newExecutionTaskHandler("gt2").cancel(t);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

	public static class SlaveStatusListener implements StatusListener {
		private Slave slave;

		public SlaveStatusListener(Slave slave) {
			this.slave = slave;
		}

        public void statusChanged(StatusEvent event) {

           if (event.getStatus().getStatusCode() == Status.ACTIVE) {
        	   		//Task t = (Task)event.getSource();
             	System.out.println("Job active @ "+event.getSource().getName());

            } else if (event.getStatus().getStatusCode() == Status.COMPLETED) {
            		//Task t = (Task)event.getSource();
            		System.out.println("Job finished @ "+event.getSource().getName());

            } else if (event.getStatus().getStatusCode() == Status.SUBMITTED) {
            } else if (event.getStatus().getStatusCode() == Status.UNSUBMITTED) {
            } else if (event.getStatus().getStatusCode() == Status.UNKNOWN) {
            } else if (event.getStatus().getStatusCode() == Status.CANCELED) {
            	 System.out.println("Job canceled @ "+event.getSource());
            } else if (event.getStatus().getStatusCode() == Status.FAILED) {
            	 System.out.println("Job failed @ "+event.getSource());
            } else {
            	 System.out.println("Warning: got unexpected StatusEvent ("+event.getStatus().getStatusString()+")");
            }
        }
    }
}


text:
namespace Sitecore.Feature.Demo.Models
{
  public class Device
  {
    public string Title { get; set; }
    public string Browser { get; set; }
  }
}


text:
package org.fife.rsta.ac.java.buildpath;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import org.fife.rsta.ac.java.classreader.ClassFile;
import org.fife.rsta.ac.java.rjc.ast.CompilationUnit;
import org.fife.rsta.ac.java.rjc.lexer.Scanner;
import org.fife.rsta.ac.java.rjc.parser.ASTFactory;

/**
 * Represents Java source in a directory, such as in a project's source folder.
 *
 * @author Robert Futrell
 * @version 1.0
 */
public class DirSourceLocation implements SourceLocation {

	private File dir;

	/**
	 * Constructor.
	 *
	 * @param dir The directory containing the source files.
	 */
	public DirSourceLocation(String dir) {
		this(new File(dir));
	}

	/**
	 * Constructor.
	 *
	 * @param dir The directory containing the source files.
	 */
	public DirSourceLocation(File dir) {
		this.dir = dir;
	}

	/**
	 * {@inheritDoc}
	 */
	public CompilationUnit getCompilationUnit(ClassFile cf) throws IOException {

		CompilationUnit cu = null;

		String entryName = cf.getClassName(true);
		entryName = entryName.replace('.', '/');
		entryName += ".java";
		//System.out.println("DEBUG: entry name: " + entryName);
		File file = new File(dir, entryName);
		if (!file.isFile()) {
			// Be nice and check for "src/" subdirectory
			file = new File(dir, "src/" + entryName);
		}

		if (file.isFile()) {
			BufferedReader r = new BufferedReader(new FileReader(file));
			try {
				Scanner s = new Scanner(r);
				cu = new ASTFactory().getCompilationUnit(entryName, s);
				//System.out.println("DEBUG: cu: " + cu);
			} finally {
				r.close();
			}
		}

		return cu;

	}

	/**
	 * {@inheritDoc}
	 */
	public String getLocationAsString() {
		return dir.getAbsolutePath();
	}

}


text:
=======================================================
Hardware-assisted AddressSanitizer Design Documentation
=======================================================

This page is a design document for
**hardware-assisted AddressSanitizer** (or **HWASAN**)
a tool similar to :doc:`AddressSanitizer`,
but based on partial hardware assistance.

Introduction
============

:doc:`AddressSanitizer`
tags every 8 bytes of the application memory with a 1 byte tag (using *shadow memory*),
uses *redzones* to find buffer-overflows and
*quarantine* to find use-after-free.
The redzones, the quarantine, and, to a less extent, the shadow, are the
sources of AddressSanitizer's memory overhead.
See the `AddressSanitizer paper`_ for details.

AArch64 has the `Address Tagging`_ (or top-byte-ignore, TBI), a hardware feature that allows
software to use 8 most significant bits of a 64-bit pointer as
a tag. HWASAN uses `Address Tagging`_
to implement a memory safety tool, similar to :doc:`AddressSanitizer`,
but with smaller memory overhead and slightly different (mostly better)
accuracy guarantees.

Algorithm
=========
* Every heap/stack/global memory object is forcibly aligned by `TG` bytes
  (`TG` is e.g. 16 or 64). We call `TG` the **tagging granularity**.
* For every such object a random `TS`-bit tag `T` is chosen (`TS`, or tag size, is e.g. 4 or 8)
* The pointer to the object is tagged with `T`.
* The memory for the object is also tagged with `T` (using a `TG=>1` shadow memory)
* Every load and store is instrumented to read the memory tag and compare it
  with the pointer tag, exception is raised on tag mismatch.

For a more detailed discussion of this approach see https://arxiv.org/pdf/1802.09517.pdf

Short granules
--------------

A short granule is a granule of size between 1 and `TG-1` bytes. The size
of a short granule is stored at the location in shadow memory where the
granule's tag is normally stored, while the granule's actual tag is stored
in the last byte of the granule. This means that in order to verify that a
pointer tag matches a memory tag, HWASAN must check for two possibilities:

* the pointer tag is equal to the memory tag in shadow memory, or
* the shadow memory tag is actually a short granule size, the value being loaded
  is in bounds of the granule and the pointer tag is equal to the last byte of
  the granule.

Pointer tags between 1 to `TG-1` are possible and are as likely as any other
tag. This means that these tags in memory have two interpretations: the full
tag interpretation (where the pointer tag is between 1 and `TG-1` and the
last byte of the granule is ordinary data) and the short tag interpretation
(where the pointer tag is stored in the granule).

When HWASAN detects an error near a memory tag between 1 and `TG-1`, it
will show both the memory tag and the last byte of the granule. Currently,
it is up to the user to disambiguate the two possibilities.

Instrumentation
===============

Memory Accesses
---------------
In the majority of cases, memory accesses are prefixed with a call to
an outlined instruction sequence that verifies the tags. The code size
and performance overhead of the call is reduced by using a custom calling
convention that

* preserves most registers, and
* is specialized to the register containing the address, and the type and
  size of the memory access.

Currently, the following sequence is used:

.. code-block:: none

  // int foo(int *a) { return *a; }
  // clang -O2 --target=aarch64-linux-android30 -fsanitize=hwaddress -S -o - load.c
  [...]
  foo:
        str     x30, [sp, #-16]!
        adrp    x9, :got:__hwasan_shadow                // load shadow address from GOT into x9
        ldr     x9, [x9, :got_lo12:__hwasan_shadow]
        bl      __hwasan_check_x0_2_short               // call outlined tag check
                                                        // (arguments: x0 = address, x9 = shadow base;
                                                        // "2" encodes the access type and size)
        ldr     w0, [x0]                                // inline load
        ldr     x30, [sp], #16
        ret

  [...]
  __hwasan_check_x0_2_short:
        ubfx    x16, x0, #4, #52                        // shadow offset
        ldrb    w16, [x9, x16]                          // load shadow tag
        cmp     x16, x0, lsr #56                        // extract address tag, compare with shadow tag
        b.ne    .Ltmp0                                  // jump to short tag handler on mismatch
  .Ltmp1:
        ret
  .Ltmp0:
        cmp     w16, #15                                // is this a short tag?
        b.hi    .Ltmp2                                  // if not, error
        and     x17, x0, #0xf                           // find the address's position in the short granule
        add     x17, x17, #3                            // adjust to the position of the last byte loaded
        cmp     w16, w17                                // check that position is in bounds
        b.ls    .Ltmp2                                  // if not, error
        orr     x16, x0, #0xf                           // compute address of last byte of granule
        ldrb    w16, [x16]                              // load tag from it
        cmp     x16, x0, lsr #56                        // compare with pointer tag
        b.eq    .Ltmp1                                  // if matches, continue
  .Ltmp2:
        stp     x0, x1, [sp, #-256]!                    // save original x0, x1 on stack (they will be overwritten)
        stp     x29, x30, [sp, #232]                    // create frame record
        mov     x1, #2                                  // set x1 to a constant indicating the type of failure
        adrp    x16, :got:__hwasan_tag_mismatch_v2      // call runtime function to save remaining registers and report error
        ldr     x16, [x16, :got_lo12:__hwasan_tag_mismatch_v2] // (load address from GOT to avoid potential register clobbers in delay load handler)
        br      x16

Heap
----

Tagging the heap memory/pointers is done by `malloc`.
This can be based on any malloc that forces all objects to be TG-aligned.
`free` tags the memory with a different tag.

Stack
-----

Stack frames are instrumented by aligning all non-promotable allocas
by `TG` and tagging stack memory in function prologue and epilogue.

Tags for different allocas in one function are **not** generated
independently; doing that in a function with `M` allocas would require
maintaining `M` live stack pointers, significantly increasing register
pressure. Instead we generate a single base tag value in the prologue,
and build the tag for alloca number `M` as `ReTag(BaseTag, M)`, where
ReTag can be as simple as exclusive-or with constant `M`.

Stack instrumentation is expected to be a major source of overhead,
but could be optional.

Globals
-------

Most globals in HWASAN instrumented code are tagged. This is accomplished
using the following mechanisms:

  * The address of each global has a static tag associated with it. The first
    defined global in a translation unit has a pseudorandom tag associated
    with it, based on the hash of the file path. Subsequent global tags are
    incremental from the previously-assigned tag.

  * The global's tag is added to its symbol address in the object file's symbol
    table. This causes the global's address to be tagged when its address is
    taken.

  * When the address of a global is taken directly (i.e. not via the GOT), a special
    instruction sequence needs to be used to add the tag to the address,
    because the tag would otherwise take the address outside of the small code
    model (4GB on AArch64). No changes are required when the address is taken
    via the GOT because the address stored in the GOT will contain the tag.

  * An associated ``hwasan_globals`` section is emitted for each tagged global,
    which indicates the address of the global, its size and its tag.  These
    sections are concatenated by the linker into a single ``hwasan_globals``
    section that is enumerated by the runtime (via an ELF note) when a binary
    is loaded and the memory is tagged accordingly.

A complete example is given below:

.. code-block:: none

  // int x = 1; int *f() { return &x; }
  // clang -O2 --target=aarch64-linux-android30 -fsanitize=hwaddress -S -o - global.c

  [...]
  f:
        adrp    x0, :pg_hi21_nc:x            // set bits 12-63 to upper bits of untagged address
        movk    x0, #:prel_g3:x+0x100000000  // set bits 48-63 to tag
        add     x0, x0, :lo12:x              // set bits 0-11 to lower bits of address
        ret

  [...]
        .data
  .Lx.hwasan:
        .word   1

        .globl  x
        .set x, .Lx.hwasan+0x2d00000000000000

  [...]
        .section        .note.hwasan.globals,"aG",@note,hwasan.module_ctor,comdat
  .Lhwasan.note:
        .word   8                            // namesz
        .word   8                            // descsz
        .word   3                            // NT_LLVM_HWASAN_GLOBALS
        .asciz  "LLVM\000\000\000"
        .word   __start_hwasan_globals-.Lhwasan.note
        .word   __stop_hwasan_globals-.Lhwasan.note

  [...]
        .section        hwasan_globals,"ao",@progbits,.Lx.hwasan,unique,2
  .Lx.hwasan.descriptor:
        .word   .Lx.hwasan-.Lx.hwasan.descriptor
        .word   0x2d000004                   // tag = 0x2d, size = 4

Error reporting
---------------

Errors are generated by the `HLT` instruction and are handled by a signal handler.

Attribute
---------

HWASAN uses its own LLVM IR Attribute `sanitize_hwaddress` and a matching
C function attribute. An alternative would be to re-use ASAN's attribute
`sanitize_address`. The reasons to use a separate attribute are:

  * Users may need to disable ASAN but not HWASAN, or vise versa,
    because the tools have different trade-offs and compatibility issues.
  * LLVM (ideally) does not use flags to decide which pass is being used,
    ASAN or HWASAN are being applied, based on the function attributes.

This does mean that users of HWASAN may need to add the new attribute
to the code that already uses the old attribute.

Comparison with AddressSanitizer
================================

HWASAN:
  * Is less portable than :doc:`AddressSanitizer`
    as it relies on hardware `Address Tagging`_ (AArch64).
    Address Tagging can be emulated with compiler instrumentation,
    but it will require the instrumentation to remove the tags before
    any load or store, which is infeasible in any realistic environment
    that contains non-instrumented code.
  * May have compatibility problems if the target code uses higher
    pointer bits for other purposes.
  * May require changes in the OS kernels (e.g. Linux seems to dislike
    tagged pointers passed from address space:
    https://www.kernel.org/doc/Documentation/arm64/tagged-pointers.txt).
  * **Does not require redzones to detect buffer overflows**,
    but the buffer overflow detection is probabilistic, with roughly
    `1/(2**TS)` chance of missing a bug (6.25% or 0.39% with 4 and 8-bit TS
    respectively).
  * **Does not require quarantine to detect heap-use-after-free,
    or stack-use-after-return**.
    The detection is similarly probabilistic.

The memory overhead of HWASAN is expected to be much smaller
than that of AddressSanitizer:
`1/TG` extra memory for the shadow
and some overhead due to `TG`-aligning all objects.

Supported architectures
=======================
HWASAN relies on `Address Tagging`_ which is only available on AArch64.
For other 64-bit architectures it is possible to remove the address tags
before every load and store by compiler instrumentation, but this variant
will have limited deployability since not all of the code is
typically instrumented.

The HWASAN's approach is not applicable to 32-bit architectures.

Related Work
============
* `SPARC ADI`_ implements a similar tool mostly in hardware.
* `Effective and Efficient Memory Protection Using Dynamic Tainting`_ discusses
  similar approaches ("lock & key").
* `Watchdog`_ discussed a heavier, but still somewhat similar
  "lock & key" approach.
* *TODO: add more "related work" links. Suggestions are welcome.*

.. _Watchdog: https://www.cis.upenn.edu/acg/papers/isca12_watchdog.pdf
.. _Effective and Efficient Memory Protection Using Dynamic Tainting: https://www.cc.gatech.edu/~orso/papers/clause.doudalis.orso.prvulovic.pdf
.. _SPARC ADI: https://lazytyped.blogspot.com/2017/09/getting-started-with-adi.html
.. _AddressSanitizer paper: https://www.usenix.org/system/files/conference/atc12/atc12-final39.pdf
.. _Address Tagging: http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.den0024a/ch12s05s01.html


text: CKEDITOR.plugins.setLang("preview","ku",{preview:"پێشبینین"});


text:
namespace chromeos {
namespace power {
namespace auto_screen_brightness {

// Model customization config.
struct ModelConfig {
  double auto_brightness_als_horizon_seconds = -1.0;
  bool enabled = false;
  std::vector<double> log_lux;
  std::vector<double> brightness;
  std::string metrics_key;
  double model_als_horizon_seconds = -1.0;

  ModelConfig();
  ModelConfig(const ModelConfig& config);
  ~ModelConfig();

  bool operator==(const ModelConfig& config) const;
};

bool IsValidModelConfig(const ModelConfig& model_config);

}  // namespace auto_screen_brightness
}  // namespace power
}  // namespace chromeos

#endif  // CHROME_BROWSER_CHROMEOS_POWER_AUTO_SCREEN_BRIGHTNESS_MODEL_CONFIG_H_


text:
BEGIN_INANITY

class MemoryFile;

END_INANITY

BEGIN_INANITY_GRAPHICS

class Device;
class RenderBuffer;
class FrameBuffer;

END_INANITY_GRAPHICS

BEGIN_INANITY_PLATFORM

/// Cross-platform graphics presenter for NPAPI plugin.
class NpapiPresenter : public Graphics::Presenter
{
private:
	ptr<Graphics::Device> device;
	/// Renderbuffer to draw into.
	mutable ptr<Graphics::RenderBuffer> renderBuffer;
	/// Actual size of render buffer.
	mutable int renderBufferWidth;
	mutable int renderBufferHeight;
	/// Framebuffer containing renderbuffer.
	mutable ptr<Graphics::FrameBuffer> frameBuffer;
	/// Size of present area.
	int width;
	int height;

#if defined(___INANITY_PLATFORM_WINDOWS)

	mutable BITMAPINFOHEADER bfh;
	mutable ptr<MemoryFile> imageFile;

#elif defined(___INANITY_PLATFORM_LINUX) || defined(___INANITY_PLATFORM_FREEBSD)

	mutable XImage image;
	mutable ptr<MemoryFile> imageFile;

#endif

public:
	NpapiPresenter(ptr<Graphics::Device> device);
	~NpapiPresenter();

	//*** Presenter's methods.
	ptr<Graphics::Device> GetDevice() const;
	int GetWidth() const;
	int GetHeight() const;
	ptr<Graphics::FrameBuffer> GetFrameBuffer() const;
	void SetMode(ptr<Graphics::MonitorMode> mode);
	void Present();
	void Resize(int width, int height);

#ifdef ___INANITY_PLATFORM_WINDOWS
	void PresentOnHdc(HDC hdc, int left, int top);
#endif
#if defined(___INANITY_PLATFORM_LINUX) || defined(___INANITY_PLATFORM_FREEBSD)
	void PresentOnXGraphicsExposeEvent(const XGraphicsExposeEvent& e, int left, int top);
#endif
};

END_INANITY_PLATFORM

#endif


text: TFS Test Data Loader


text:
[Full Changelog](https://github.com/chef/chef-provisioning-azure/compare/v0.5.0...v0.6.0)

**Merged pull requests:**

- 0.6.0 release with chef-provisioning 2.0 compatibility [#50](https://github.com/chef/chef-provisioning-azure/pull/50) ([tas50](https://github.com/tas50))
- changed to right user path [#48](https://github.com/chef/chef-provisioning-azure/pull/48) ([cjohannsen81](https://github.com/cjohannsen81))

## [v0.5.0](https://github.com/chef/chef-provisioning-azure/tree/v0.5.0) (2016-02-03)

[Full Changelog](https://github.com/chef/chef-provisioning-azure/compare/v0.4.0...v0.5.0)

**Merged pull requests:**

- Bump revision to 0.5.0 [#44](https://github.com/chef/chef-provisioning-azure/pull/44) ([jkeiser](https://github.com/jkeiser))
- Add gemspec files to allow bundler to run from the gem [#41](https://github.com/chef/chef-provisioning-azure/pull/41) ([ksubrama](https://github.com/ksubrama))

## [v0.4.0](https://github.com/chef/chef-provisioning-azure/tree/v0.4.0) (2015-09-16)

[Full Changelog](https://github.com/chef/chef-provisioning-azure/compare/v0.3.3...v0.4.0)

**Merged pull requests:**

- Make chef a development dependency. [#40](https://github.com/chef/chef-provisioning-azure/pull/40) ([ksubrama](https://github.com/ksubrama))

## [v0.3.3](https://github.com/chef/chef-provisioning-azure/tree/v0.3.3) (2015-09-10)

[Full Changelog](https://github.com/chef/chef-provisioning-azure/compare/v0.3.2...v0.3.3)

**Merged pull requests:**

- Adding a CONTRIBUTING document [#38](https://github.com/chef/chef-provisioning-azure/pull/38) ([tyler-ball](https://github.com/tyler-ball))
- Update README.md [#37](https://github.com/chef/chef-provisioning-azure/pull/37) ([stuartpreston](https://github.com/stuartpreston))
- Closing down ASM issues in preparation for ARM mode driver [#35](https://github.com/chef/chef-provisioning-azure/pull/35) ([stuartpreston](https://github.com/stuartpreston))
- Setting SSH username to vm_user other than specific machine/bootstrap_options property [#34](https://github.com/chef/chef-provisioning-azure/pull/34) ([plant42](https://github.com/plant42))
- Adding ancillary resources [#31](https://github.com/chef/chef-provisioning-azure/pull/31) ([stuartpreston](https://github.com/stuartpreston))

## [v0.3.2](https://github.com/chef/chef-provisioning-azure/tree/v0.3.2) (2015-04-03)

[Full Changelog](https://github.com/chef/chef-provisioning-azure/compare/v0.3.1...v0.3.2)

## [v0.3.1](https://github.com/chef/chef-provisioning-azure/tree/v0.3.1) (2015-04-03)

[Full Changelog](https://github.com/chef/chef-provisioning-azure/compare/v0.3...v0.3.1)

## [v0.3](https://github.com/chef/chef-provisioning-azure/tree/v0.3) (2015-04-02)

[Full Changelog](https://github.com/chef/chef-provisioning-azure/compare/v0.2.1...v0.3)

**Merged pull requests:**

- Add .azure/azureProfile.json and Azure environment variable support [#25](https://github.com/chef/chef-provisioning-azure/pull/25) ([stuartpreston](https://github.com/stuartpreston))
- Support for Windows VM roles with WinRM bootstrap support for Azure driver [#15](https://github.com/chef/chef-provisioning-azure/pull/15) ([stuartpreston](https://github.com/stuartpreston))
- Fixing readme example to include required options [#12](https://github.com/chef/chef-provisioning-azure/pull/12) ([stuartpreston](https://github.com/stuartpreston))

## [v0.2.1](https://github.com/chef/chef-provisioning-azure/tree/v0.2.1) (2015-02-26)

[Full Changelog](https://github.com/chef/chef-provisioning-azure/compare/v0.2...v0.2.1)

**Merged pull requests:**

- Allow multiple VMs to be created per cloud service and bootstrapped using their public SSH ports [#7](https://github.com/chef/chef-provisioning-azure/pull/7) ([stuartpreston](https://github.com/stuartpreston))

## [v0.2](https://github.com/chef/chef-provisioning-azure/tree/v0.2) (2015-02-11)

[Full Changelog](https://github.com/chef/chef-provisioning-azure/compare/v0.1...v0.2)

**Merged pull requests:**

- Changes to paths and filenames to match chef-provisioning expectations [#4](https://github.com/chef/chef-provisioning-azure/pull/4) ([stuartpreston](https://github.com/stuartpreston))

## [v0.1](https://github.com/chef/chef-provisioning-azure/tree/v0.1) (2014-11-05)

**Merged pull requests:**

- Rename to chef-provisioning-azure [#3](https://github.com/chef/chef-provisioning-azure/pull/3) ([jkeiser](https://github.com/jkeiser))

- _This Change Log was automatically generated by [github_changelog_generator](https://github.com/skywinder/Github-Changelog-Generator)_


text:
package spdy

import (
	"bytes"
	"crypto/tls"
	"fmt"
	"github.com/DanielMorsing/spdy/framing"
	"io/ioutil"
	"net"
	"net/http"
	"testing"
	"time"
)

func init() {
	var response = `

	<form action="hej" method="post">
	First name: <input type="text" name="firstname">

	Last name: <input type="text" name="lastname">

	<input type="submit" value="Submit"/>
	</form>

	`
	ds := http.DefaultServeMux
	ds.HandleFunc("/", func(rw http.ResponseWriter, rq *http.Request) {
		rw.WriteHeader(200)
		<-corkch
		rw.Write([]byte(response))
	})
	ds.HandleFunc("/hej", func(rw http.ResponseWriter, rq *http.Request) {
		rq.ParseForm()
		rw.WriteHeader(200)
		fmt.Fprintf(rw, "your name is %s %s\n", rq.Form["firstname"][0], rq.Form["lastname"][0])
	})
	testsrv = &Server{
		Server: http.Server{
			Addr:    "localhost:4444",
			Handler: ds,
		},
	}
}

var testsrv *Server

var corkch = func() chan struct{} {
	c := make(chan struct{})
	close(c)
	return c
}()

func cork() {
	corkch = make(chan struct{})
}

func uncork() {
	corkch <- struct{}{}
	close(corkch)
}

var clientConfig = tls.Config{
	InsecureSkipVerify: true,
	NextProtos:         []string{"spdy/3"},
}

func newClientSession() (*framing.Framer, net.Conn) {
	srv, clnt := net.Pipe()
	sess, err := newSession(&testsrv.Server, srv, testsrv.Server.Handler)
	if err != nil {
		panic(err)
	}
	go func() {
		sess.serve()
		srv.Close()
	}()
	framer, err := framing.NewFramer(clnt, clnt)
	if err != nil {
		panic(err)
	}
	return framer, clnt
}

func goldenHeader() http.Header {
	m := make(http.Header)
	m[":host"] = []string{"localhost:4444"}
	m[":path"] = []string{"/"}
	m[":scheme"] = []string{"https"}
	m[":version"] = []string{"HTTP/1.1"}
	m["User-Agent"] = []string{"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36"}
	m["Accept"] = []string{"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"}
	m[":method"] = []string{"GET"}
	m["Accept-Encoding"] = []string{"gzip,deflate,sdch"}
	m["Accept-Language"] = []string{"en-US,en;q=0.8,da;q=0.6"}
	return m
}

func makeRequest() *framing.SynStreamFrame {
	return &framing.SynStreamFrame{
		framing.ControlFrameHeader{
			Flags: framing.ControlFlagFin,
		},
		1,
		0,
		0,
		0,
		goldenHeader(),
	}
}

func goldenSettings() *framing.SettingsFrame {
	return &framing.SettingsFrame{
		FlagIdValues: []framing.SettingsFlagIdValue{
			framing.SettingsFlagIdValue{0, 4, 1000},
			framing.SettingsFlagIdValue{0, 7, 10485760},
		},
	}
}

func frameRead(t *testing.T, f *framing.Framer) framing.Frame {
	for {
		frame, err := f.ReadFrame()
		if err != nil {
			t.Fatal(err)
		}
		if _, ok := frame.(*framing.WindowUpdateFrame); !ok {
			return frame
		}
	}

}

func frameWrite(t *testing.T, f *framing.Framer, frame framing.Frame) {
	err := f.WriteFrame(frame)
	if err != nil {
		t.Fatal(err)
	}
}

func TestPing(t *testing.T) {
	f, n := newClientSession()
	defer n.Close()

	p := framing.PingFrame{Id: 1}
	frameWrite(t, f, &p)

	retf := frameRead(t, f)
	if retp, ok := retf.(*framing.PingFrame); ok {
		if retp.Id != 1 {
			t.Error("ping id returned is not the one sent")
		}
	} else {
		t.Error("Received non ping frame")
	}
}

func TestSettings(t *testing.T) {
	f, n := newClientSession()
	defer n.Close()

	set := goldenSettings()
	frameWrite(t, f, set)
}

func TestBasicRequest(t *testing.T) {
	f, n := newClientSession()
	defer n.Close()

	set := goldenSettings()
	frameWrite(t, f, set)
	syn := makeRequest()
	frameWrite(t, f, syn)

	r := frameRead(t, f)
	rp, ok := r.(*framing.SynReplyFrame)
	if !ok {
		t.Fatal("did not get reply frame")
	}
	if rp.StreamId != 1 {
		t.Fatal("Wrong StreamId")
	}
	for {
		frame := frameRead(t, f)
		d, ok := frame.(*framing.InDataFrame)
		if !ok {
			t.Fatalf("non data frame received: %T", frame)
		}
		d.Close()
		// got fin
		if d.Flags != 0 {
			break
		}
	}
}

func TestReset(t *testing.T) {
	f, n := newClientSession()
	defer n.Close()

	set := goldenSettings()
	frameWrite(t, f, set)
	syn := makeRequest()
	cork()
	frameWrite(t, f, syn)
	r := frameRead(t, f)
	_, ok := r.(*framing.SynReplyFrame)
	if !ok {
		t.Fatal("did not get reply frame")
	}
	rst := framing.RstStreamFrame{
		StreamId: 1,
		Status:   framing.Cancel,
	}
	frameWrite(t, f, &rst)

	// there is a acknowledged race condition here.
	// where the server may send inflight dataframes
	// after a rst has been sent.
	//
	// make sure that reset has been received by sending a ping
	p := framing.PingFrame{Id: 1}
	frameWrite(t, f, &p)
	retf := frameRead(t, f)
	if _, ok := retf.(*framing.PingFrame); !ok {
		t.Error("Received non ping frame")
	}

	var ch = make(chan framing.Frame, 1)
	go func() {
		for {
			f, err := f.ReadFrame()
			if err != nil {
				return
			}
			ch <- f
		}
	}()
	uncork()

	timech := time.After(500 * time.Millisecond)
	select {
	case <-ch:
		t.Fatal("got frame after reset")
	case <-timech:
		return
	}
}

func TestWindowLimit(t *testing.T) {
	f, n := newClientSession()
	defer n.Close()

	set := goldenSettings()
	for i := range set.FlagIdValues {
		if set.FlagIdValues[i].Id == framing.SettingsInitialWindowSize {
			set.FlagIdValues[i].Value = 1
		}
	}
	frameWrite(t, f, set)

	syn := makeRequest()
	frameWrite(t, f, syn)

	frame := frameRead(t, f)
	_, ok := frame.(*framing.SynReplyFrame)
	if !ok {
		t.Fatal("did not get reply frame")
	}

	frame = frameRead(t, f)
	d, ok := frame.(*framing.InDataFrame)
	if !ok {
		t.Fatal("did not get data frame")
	}
	d.Close()
	if d.Length != 1 {
		t.Fatal("Data frame larger than window")
	}
	var ch = make(chan framing.Frame, 1)
	go func() {
		f := frameRead(t, f)
		ch <- f
	}()
	select {
	case <-ch:
		t.Error("got data even though it's supposed to be blocked on window")
	case <-time.After(200 * time.Millisecond):
		wnd := framing.WindowUpdateFrame{
			StreamId:        1,
			DeltaWindowSize: 1 << 20,
		}
		frameWrite(t, f, &wnd)
	}
	select {
	case <-ch:
	case <-time.After(500 * time.Millisecond):
		t.Error("didn't get data after window unblocked")
	}
}

func TestResetWhileWindowblocked(t *testing.T) {
	f, n := newClientSession()
	defer n.Close()

	set := goldenSettings()
	for i := range set.FlagIdValues {
		if set.FlagIdValues[i].Id == framing.SettingsInitialWindowSize {
			set.FlagIdValues[i].Value = 1
		}
	}
	frameWrite(t, f, set)

	syn := makeRequest()
	frameWrite(t, f, syn)

	frame := frameRead(t, f)
	_, ok := frame.(*framing.SynReplyFrame)
	if !ok {
		t.Fatal("did not get reply frame")
	}
	frame = frameRead(t, f)
	d, ok := frame.(*framing.InDataFrame)
	if !ok {
		t.Fatal("did not get data frame")
	}
	d.Close()
	if d.Length != 1 {
		t.Fatal("Data frame larger than window")
	}

	var ch = make(chan framing.Frame, 1)
	go func() {
		f, _ := f.ReadFrame()
		ch <- f
	}()
	select {
	case <-ch:
		t.Error("got data even though it's supposed to be blocked on window")
	case <-time.After(200 * time.Millisecond):
		rst := framing.RstStreamFrame{
			StreamId: 1,
			Status:   framing.Cancel,
		}
		frameWrite(t, f, &rst)
	}
}

func TestPostRequest(t *testing.T) {
	f, n := newClientSession()
	defer n.Close()

	set := goldenSettings()
	frameWrite(t, f, set)
	syn := makeRequest()
	syn.Headers[":path"] = []string{"/hej"}
	syn.Headers[":method"] = []string{"POST"}
	syn.Headers["Content-Type"] = []string{"application/x-www-form-urlencoded"}
	syn.CFHeader.Flags = 0
	frameWrite(t, f, syn)
	d := &framing.DataFrame{}
	d.StreamId = 1
	d.Flags = framing.DataFlagFin
	d.Data = []byte("firstname=daniel&lastname=morsing")
	frameWrite(t, f, d)

	r := frameRead(t, f)
	rp, ok := r.(*framing.SynReplyFrame)
	if !ok {
		t.Fatalf("did not get reply frame: %T", r)
	}
	if rp.StreamId != 1 {
		t.Fatal("Wrong StreamId")
	}

	frame := frameRead(t, f)
	id, ok := frame.(*framing.InDataFrame)
	if !ok {
		t.Fatal("non data frame received:", frame)
	}
	got, err := ioutil.ReadAll(id)
	id.Close()
	if err != nil {
		t.Error(err)
	}
	exp := []byte("your name is daniel morsing\n")
	if !bytes.Equal(got, exp) {
		t.Errorf("expected %s; got %s", exp, d.Data)
	}
}

func TestInvalidStreamId(t *testing.T) {
	f, n := newClientSession()
	defer n.Close()

	syn := makeRequest()
	syn.StreamId = 2

	frameWrite(t, f, syn)
	goaway := frameRead(t, f)
	g, ok := goaway.(*framing.GoAwayFrame)
	if !ok {
		// didn't get reset
		t.Errorf("did not get goaway frame. got %T instead", g)
		return
	}
	if g.Status != framing.GoAwayProtocolError {
		t.Error("Wrong error code")
	}
	_, err := f.ReadFrame()
	if err == nil {
		t.Error("Session not closed")
	}
}


text:
using System;
using System.Data.SqlClient;
using System.Runtime.Serialization;
using Newtonsoft.Json;

namespace Dapper.SimpleLoad
{
    [Serializable]
    public class AnnotatedSqlException : Exception, ISerializable
    {
        public AnnotatedSqlException(
            SqlException source,
            string sql,
            string splitOn,
            object parameters) : base(BuildMessage(source.Message, sql, splitOn, parameters), source)
        {
            Sql = sql;
            SplitOn = splitOn;
            Parameters = parameters;
        }

        public AnnotatedSqlException(
            string message,
            string sql,
            string splitOn,
            object parameters) : base(BuildMessage(message, sql, splitOn, parameters))
        {

        }

        protected AnnotatedSqlException(SerializationInfo info, StreamingContext context) : base(info, context)
        {
            Sql = info.GetString("_Sql");
            SplitOn = info.GetString("_SplitOn");
            Parameters = JsonConvert.DeserializeObject(info.GetString("_Parameters"));
        }

        public override void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            base.GetObjectData(info, context);

            info.AddValue("_Sql", Sql);
            info.AddValue("_SplitOn", SplitOn);
            info.AddValue("_Parameters", JsonConvert.SerializeObject(Parameters));
        }

        public string Sql { get; private set; }
        public string SplitOn { get; private set; }
        public object Parameters { get; private set; }

        private static string BuildMessage(string message, string sql, string splitOn, object parameters)
        {
            var temp = message
                       + Environment.NewLine
                       + "For SQL: " + sql
                       + Environment.NewLine
                       + "Split On: " + splitOn;

            if (SimpleLoadConfiguration.IncludeParametersInException)
            {
                temp += Environment.NewLine
                        + "Parameters: " + JsonConvert.SerializeObject(parameters);
            }

            return temp;
        }
    }
}