text:
[![Build Status](https://github.com/wbsch/bash_tap/actions/workflows/tests.yml/badge.svg)](https://github.com/wbsch/bash_tap/actions/workflows/tests.yml)

## WHAT
`bash_tap.sh` is a simple Bash script to [TAP](https://testanything.org/) output converter. Any command exiting with a non-zero exit code, even if it is part | of | a | piped | command, makes `bash_tap.sh` output `not ok` TAP information.

`bash_tap.sh` tries to keep things simple. Tests look a lot like regular Bash scripts - because they are. If you are looking for a fully-featured Bash TAP producer with helper functions and a rigid formula for tests, `bash_tap.sh` is not it.

The Bash script:
```bash
#!/bin/bash
source bash_tap.sh

# This successfully finds "world" and exits with a zero exit code:
echo "Hello world" | grep "world"
# This cannot find "cookies" in the text, so it exits non-zero:
echo "Got milk?" | grep "cookies"
```

saved as `test_fail_grep.sh` leads to this output:
```console
$ ./test_fail_grep.sh
Hello world

$ ./test_fail_grep.sh -t
1..1
# This successfully finds "world" and exits with a zero exit code:
# $ echo "Hello world" | grep "world"
# >>> Hello world
# This cannot find "cookies" in the text, so it exits non-zero:
# $ echo "Got milk?" | grep "cookies"
not ok 1 - echo "Got milk?" | grep "cookies"
```

Renaming the file to have a `.t` ending makes `-t` mode the default, meaning that TAP harnesses can be run on it directly to integrate it into a pre-existing TAP test suite if needed:
```console
$ mv test_fail_grep.sh test_fail_grep.t

$ ./test_fail_grep.t
1..1
# This successfully finds "world" and exits with a zero exit code:
# $ echo "Hello world" | grep "world"
# >>> Hello world
# This cannot find "cookies" in the text, so it exits non-zero:
# $ echo "Got milk?" | grep "cookies"
not ok 1 - echo "Got milk?" | grep "cookies"

$ prove -v test_fail_grep.t
test_fail_grep.t ..
1..1
# $ echo "Hello world!" | grep "world"
# >>> Hello world!
# $ echo "Got milk?" | grep "cookies"
not ok 1 - echo "Got milk?" | grep "cookies"
Dubious, test returned 1 (wstat 256, 0x100)
Failed 1/1 subtests

Test Summary Report
-------------------
test_fail_grep.t (Wstat: 256 Tests: 1 Failed: 1)
  Failed test:  1
  Non-zero exit status: 1
Files=1, Tests=1,  0 wallclock secs ( 0.02 usr  0.01 sys +  0.00 cusr  0.03 csys =  0.06 CPU)
Result: FAIL
```

In `-t` mode, all commands are run in a temporary directory that is removed on exit. In `normal` mode, all commands are run in the current directory and no cleanup is done.

## WHY
`bash_tap.sh` is for people who have many small snippets lying around their project folder, each reproducing some kind of malfunction reported in a bug somewhere. Turning these snippets into proper TAP tests usually involves more work than one is willing or able to invest at that point in time, making those snippets linger and be forgotten.

Copy & paste is often enough to make `bash_tap.sh` run these as tests.

## HOW
All you need for writing your own tests is `bash_tap.sh`. It is important not to rename it since there is some deeply disturbing magic involved. Additionally, naming helper scripts anything but `bash_tap_HELPERNAME.sh` will lead to problems.

Included in the repo's `misc` folder is `bash_tap_tw.sh`, a file used in [Taskwarrior](http://taskwarrior.org)'s test suite. It shows how to extend `bash_tap.sh` for your own usage should plain Bash and installed commands not suffice.

## LIMITATIONS
### No multi-line Bash constructs
Good:
```bash
if [ "foo" == "bar" ]; then echo "they are the same!"; fi
```
Bad:
```bash
if [ "foo" == "bar" ]; then
    echo "they are the same!"
fi
```
While more readable, it will break when run by `bash_tap.sh`.

### One file, one test
Each file is counted as one test. Any command exiting with a non-zero exit status is output as "the failing test", even if it is part of the setup process and not an actual test at all.

### No TAP specific commands
Keeping things simple at the expense of more advanced functionality was a design decision, if "design" is what you want to call what spawned this abomination.
Other Bash TAP producers offer commands like `assertEqual [command1] [command2]` instead of relying on Bash one-liners. `bash_tap.sh` will never do that.

If you are looking for a Bash TAP producer with more features, consider evaluating (no particular order, list not exhaustive):
[bats](https://github.com/sstephenson/bats), [bash-tap](https://github.com/illusori/bash-tap), [bash-tap-functions](https://github.com/goozbach/bash-tap-functions), [sharness](http://mlafeldt.github.io/sharness/).

### Lacking portability
Unless you use nothing but Bash builtins in your tests, cross-platform portability is quite bad. Be sure to know your POSIX standards. Keep the tests simple, use a proper TAP Producer for bigger tests instead, and you will be fine.


text:
<?php
/**
 * The manifest of files that are local to specific environment.
 * This file returns a list of environments that the application
 * may be installed under. The returned data must be in the following
 * format:
 *
 * ```php
 * return [
 *     'environment name' => [
 *         'path' => 'directory storing the local files',
 *         'setWritable' => [
 *             // list of directories that should be set writable
 *         ],
 *         'setExecutable' => [
 *             // list of directories that should be set executable
 *         ],
 *         'setCookieValidationKey' => [
 *             // list of config files that need to be inserted with
 *             automatically generated cookie validation keys
 *         ],
 *         'createSymlink' => [
 *             // list of symlinks to be created.
 *             Keys are symlinks, and values are the targets.
 *         ],
 *     ],
 * ];
 * ```
 */
return [
    'Development' => [
        'path' => 'dev',
        'setWritable' => [
            '_protected/backend/runtime',
            '_protected/frontend/runtime',
            '_protected/frontend/runtime/mail',
            '/assets',
            '/backend/assets'
        ],
        'setExecutable' => [
            '_protected/yii',
        ],
        'setCookieValidationKey' => [
            '_protected/backend/config/main-local.php',
            '_protected/frontend/config/main-local.php',
        ],
    ],
    'Production' => [
        'path' => 'prod',
        'setWritable' => [
            '_protected/backend/runtime',
            '_protected/frontend/runtime',
            '/assets',
            '/backend/assets'
        ],
        'setExecutable' => [
            '_protected/yii',
            '_protected/frontend/runtime/mail',
        ],
        'setCookieValidationKey' => [
            '_protected/backend/config/main-local.php',
            '_protected/frontend/config/main-local.php',
        ],
    ],
];

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace PhpBench\Tests\Unit\Expression\Parselet;

use Generator;
use PhpBench\Expression\Ast\IntegerNode;
use PhpBench\Expression\Ast\ListNode;
use PhpBench\Tests\Unit\Expression\ParseletTestCase;

class ListParseletTest extends ParseletTestCase
{
    /**
     * @return Generator<mixed>
     */
    public function provideParse(): Generator
    {
        yield 'single value is not an argument list' => [
            '[12]',
            new ListNode([new IntegerNode(12)])
        ];
    }

    /**
     * {@inheritDoc}
     */
    public function provideEvaluate(): Generator
    {
        yield [
            '[12]',
            [],
            '[12]'
        ];
    }

    /**
     * {@inheritDoc}
     */
    public function providePrint(): Generator
    {
        yield ['12, 12'];

        yield ['12, 12, 12, 12'];
    }
}


text:
package org.jadira.scanner.core.helper;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.WeakHashMap;

import javassist.bytecode.ClassFile;

public final class JavassistClassFileHelper {

	private static final WeakHashMap<String, ClassFile> CLASSFILES_BY_NAME = new WeakHashMap<String, ClassFile>(1024, 0.6f);
	private static final WeakHashMap<String, ClassFile> CLASSFILES_BY_FILE = new WeakHashMap<String, ClassFile>(1024, 0.6f);

	private static final int MAXIMUM_SIZE = 2048;

	private JavassistClassFileHelper() {
	}

    public static ClassFile constructClassFile(String className, InputStream bits) throws IOException {

		ClassFile cachedClassFile = CLASSFILES_BY_NAME.get(className);
		if (cachedClassFile != null) {
			return cachedClassFile;
		}

    	DataInputStream dstream = new DataInputStream(new BufferedInputStream(bits));
        ClassFile cf = null;
        try {
            cf = new ClassFile(dstream);
        } finally {
            dstream.close();
            bits.close();
        }

        if (cf != null) {
        	CLASSFILES_BY_NAME.put(className, cf);
        }
        return cf;
    }

    public static ClassFile constructClassFileForPath(String path, InputStream bits) throws IOException {

		ClassFile cachedClassFile = CLASSFILES_BY_FILE.get(path);
		if (cachedClassFile != null) {
			return cachedClassFile;
		}

    	DataInputStream dstream = new DataInputStream(new BufferedInputStream(bits));
        ClassFile cf = null;
        try {
            cf = new ClassFile(dstream);
        } finally {
            dstream.close();
            bits.close();
        }

        if (cf != null) {
        	if (CLASSFILES_BY_NAME.size() < MAXIMUM_SIZE) {
        		CLASSFILES_BY_NAME.put(cf.getName(), cf);
        	}
        	if (CLASSFILES_BY_FILE.size() < MAXIMUM_SIZE) {
        		CLASSFILES_BY_FILE.put(path, cf);
        	}
        }
        return cf;
    }}


text:
(function () {
    'use strict';

    angular
        .module('app')
        .controller('HomeController', HomeController);

    HomeController.$inject = ['UserService', '$rootScope', '$cookieStore'];
    function HomeController(UserService, $rootScope, $cookieStore) {
        var vm = this;

        vm.user = null;
        vm.allUsers = [];
        vm.deleteUser = deleteUser;

        initController();

        function initController() {
            loadCurrentUser();
            loadAllUsers();
        }

        function loadCurrentUser() {
            UserService.GetByUsername($rootScope.globals.currentUser.username)
                .then(function (user) {
                    vm.user = user;
                    //$cookies.put('favorite','test');
                    $cookieStore.put('myFavorite','oatmeal');
                });
        }

        function loadAllUsers() {
            UserService.GetAll()
                .then(function (users) {
                    vm.allUsers = users;
                });
        }

        function deleteUser(id) {
            UserService.Delete(id)
            .then(function () {
                loadAllUsers();
            });
        }
    }

})();


text:
package org.joyrest.ittest.aspect;

import org.joyrest.interceptor.Interceptor;
import org.joyrest.interceptor.InterceptorChain;
import org.joyrest.model.request.InternalRequest;
import org.joyrest.model.response.InternalResponse;
import static org.joyrest.ittest.aspect.ContextHolder.RegistryKey.FIRST_KEY;
import static org.joyrest.ittest.aspect.ContextHolder.RegistryKey.SECOND_KEY;
import static org.joyrest.ittest.aspect.ContextHolder.RegistryKey.THIRD_KEY;

import static java.util.Objects.isNull;
import static java.util.Objects.nonNull;

public class SecondInterceptor implements Interceptor {

    @Override
    public InternalResponse<Object> around(InterceptorChain chain,
                                           InternalRequest<Object> request,
                                           InternalResponse<Object> response) throws Exception {
        if (isNull(ContextHolder.get(FIRST_KEY)) ||
            nonNull(ContextHolder.get(SECOND_KEY)) ||
            nonNull(ContextHolder.get(THIRD_KEY))) {
            throw new RuntimeException("Fail during Request side in FirstAspect");
        }

        ContextHolder.put(SECOND_KEY, "yes");

        InternalResponse<Object> resp = chain.proceed(request, response);

        if (isNull(ContextHolder.get(FIRST_KEY)) ||
            isNull(ContextHolder.get(SECOND_KEY)) ||
            nonNull(ContextHolder.get(THIRD_KEY))) {
            throw new RuntimeException("Fail during Response side in FirstAspect");
        }

        ContextHolder.put(SECOND_KEY, null);
        return resp;
    }

    @Override
    public int getOrder() {
        return 50;
    }
}


text:
// Copyright 2007-2017 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// 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.
namespace MassTransit.NinjectIntegration
{
    using Ninject;
    using Saga;

    public class SagaCachedConfigurator<T> :
        ICachedConfigurator
        where T : class, ISaga
    {
        public void Configure(IReceiveEndpointConfigurator configurator, IKernel kernel)
        {
            var sagaRepository = kernel.Get<ISagaRepository<T>>();

            var repository = new NinjectSagaRepository<T>(sagaRepository);

            configurator.Saga(repository);
        }
    }
}


text:
package typeassert

import (
	"levee_analysistest/example/core"
)

func TestTypeSwitch(i interface{}) {
	switch t := i.(type) {
	case core.Innocuous:
		core.Sink(i)
		core.Sink(t)
	case *core.Source:
		// The type of i is definitively known within this block
		core.Sink(i) // TODO(#161) want "a source has reached a sink"
		core.Sink(t) // want "a source has reached a sink"
	case core.Source:
		// The type of i is definitively known within this block
		core.Sink(i) // TODO(#161) want "a source has reached a sink"
		core.Sink(t) // want "a source has reached a sink"
	default:
		core.Sink(i)
		core.Sink(t)
	}
}

func TestTypeSwitchInline(i interface{}) {
	switch i.(type) {
	case core.Innocuous, *core.Source, core.Source:
		// While not definitively known, the type of i may be asserted to be a source type
		core.Sink(i) // TODO(#161) want "a source has reached a sink"
	default:
		// do nothing
	}
}

func TestPanicTypeAssertSource(i interface{}) {
	s := i.(core.Source)
	_ = s
	// The dominating type assertion would panic if i were not a source type.
	core.Sink(i) // want "a source has reached a sink"
}

func TestPanicTypeAssertInnocuous(i interface{}) {
	// TypeAssert instructions should not cause reports by themselves.
	innoc := i.(core.Innocuous)
	_ = innoc
	core.Sink(i)
}

func TestOkayTypeAssert(i interface{}) {
	s, ok := i.(core.Source)
	_, _ = s, ok
	// The dominating type assertion will not panic.
	core.Sink(i)
}


text:
<?php

require_once '../Router.php';
require_once '../Config.php';

class RouterTest extends PHPUnit_Framework_TestCase
{

	public function setUp() {
		set('base', false);

	}

	public function testGet() {
		$r = new RouterTestWrapper();
		$r->get('/', function() {});
		$this->assertEquals(1, count($r->routes['GET']));
	}

	public function testPut() {
		$r = new RouterTestWrapper();
		$r->put('/', function() {echo 'test put';});
		$this->assertEquals(1, count($r->routes['PUT']));
	}

	public function testPost() {
		$r = new RouterTestWrapper();
		$r->post('/', function() {echo 'test post';});
		$this->assertEquals(1, count($r->routes['POST']));
	}

	public function testDelete() {
		$r = new RouterTestWrapper();
		$r->delete('/', function() {echo 'test delete';});
		$this->assertEquals(1, count($r->routes['DELETE']));
	}

	public function testPatternToRegex() {
		$r = new RouterTestWrapper();
		$r->get('/', function() {});
		$this->assertEquals('|^/?()/?$|', $r->routes['GET'][0]->regex());

		$r->get('/thing/:id', function() {});
		$this->assertEquals('|^/?(thing)/([^\/]+)/?|', $r->routes['GET'][1]->regex());

		$r->get('/thing/:name/:id', function() {});
		$this->assertEquals('|^/?(thing)/([^\/]+)/([^\/]+)/?|', $r->routes['GET'][2]->regex());

		$r->get('/gobble/*', function() {});
		$this->assertEquals('|^/?(gobble)/?(.*)/?|', $r->routes['GET'][3]->regex());
	}

	public function testUserRegex() {
		$r = new RouterTestWrapper();
		$r->get(r('|/|'), function() {});
		$this->assertEquals('|/|', $r->routes['GET'][0]->regex());
	}

	public function testUsesAltDelimiter() {
		$r = new RouterTestWrapper();
		$r->get('|/|', function() {});
		$reg = $r->routes['GET'][0]->regex();
		$this->assertEquals('`', $reg{0});
	}

	public function testUrlMatchesRoute() {
		$r = new RouterTestWrapper();
		$r->get('/', function() {});
		$this->assertTrue($r->url_matches_route('/', $r->routes['GET'][0]));
	}

	public function testUrlMatchesRouteUsingBase() {
		$r = new RouterTestWrapper();
		$url = '/hello/world';
		set('base', $url);
		$r->get('/', function() {});
		$this->assertTrue($r->url_matches_route($url, $r->routes['GET'][0]));
	}

	public function testUrlMatchesRouteUsingDeepBase() {
		$r = new RouterTestWrapper();
		$base = '/hello/world';
		$url = $base . '/name/bob';
		set('base', $base);
		$r->get('/name/bob', function() {});
		$this->assertTrue($r->url_matches_route($url, $r->routes['GET'][0]));
	}

	public function testParamsForUrlWithRoute() {
		$r = new RouterTestWrapper();
		$r->get('/person/:name/:id', function() {});

		# fail to match /
		$this->assertFalse($r->params_for_url_with_route('/', $r->routes['GET'][0]));

		# match something
		$e = array ('name' => 'bob', 'id' => '55');
		$p = $r->params_for_url_with_route('/person/bob/55', $r->routes['GET'][0]);
		$this->assertEquals($e, $p);

		# match a splat
		$r->get('/stuff/*', function() {});
		$e = array ('splat' => 'four-score-and-seven-years');
		$p = $r->params_for_url_with_route('/stuff/four-score-and-seven-years', $r->routes['GET'][1]);
		$this->assertEquals($e, $p);

	}

	public function testMatchRequest() {
		$r = new RouterTestWrapper();
		$r->get('/person/:name/:id', function() {});
		$r->get('/post/:title/:id', function() {});
		$r->get('/stuff/*', function() {});
		$r->get('/', function() {});

		$this->assertEquals($r->routes['GET'][0], $r->match_request('GET', '/person/bob/55'));
		$this->assertEquals($r->routes['GET'][1], $r->match_request('GET', '/post/super-stuff/99'));
		$this->assertEquals($r->routes['GET'][2], $r->match_request('GET', '/stuff/four-score-and-seven-years'));
		$this->assertEquals($r->routes['GET'][3], $r->match_request('GET', '/'));
		$this->assertFalse($r->match_request('GET', '/blahblah'));
	}

	public function testRouteForRequest() {
		$r = new RouterTestWrapper();
		$r->get('/person/:name/:id', function() {});
		$r->get('/post/:title/:id', function() {});
		$r->get('/stuff/*', function() {});
		$r->get('/', function() {});

		$route = $r->route_for_request('GET', '/person/bob/55');
		$e = array ('name' => 'bob', 'id' => '55');
		$this->assertEquals($r->routes['GET'][0], $route);
		$this->assertEquals($e, $route->params());

		$route = $r->route_for_request('GET', '/stuff/four-score-and-seven-years');
		$e = array ('splat' => 'four-score-and-seven-years');
		$this->assertEquals($r->routes['GET'][2], $route);
		$this->assertEquals($e, $route->params());

		$route = $r->route_for_request('GET', '/post/super-stuff/99');
		$e = array ('title' => 'super-stuff', 'id' => '99');
		$this->assertEquals($r->routes['GET'][1], $route);
		$this->assertEquals($e, $route->params());
	}

	public function testProcessRequestVars() {
		$p = array();
		$p['foo'] = 'bar';
		$p['nested']['param1'] = 'nested-1';
		$p['nested']['param2'] = 'nested-2';

		$_POST = $p;
		$_GET['get_var'] = 'v';
		$p = array_merge($p, $_GET);

		$r = new RouterTestWrapper();
		$o = $r->process_request_vars(array());
		$this->assertEquals($p, $o);

	}

	public function testThrowsNotFound() {
		$this->setExpectedException('vicious\NotFound');
		$router = new vicious\Router();
		$router->route_for_request('GET', '/');
	}
}

// ===========================================================
// - WRAPPER CLASS FOR TESTING PROTECTED METHODS
// ===========================================================
class RouterTestWrapper extends vicious\Router
{
	public $routes;

	public function process_request_vars($params) {
		return parent::process_request_vars($params);
	}

	public function url_matches_route($url, $route) {
		return parent::url_matches_route($url, $route);
	}

	public function params_for_url_with_route($url, $route) {
		return parent::params_for_url_with_route($url, $route);
	}

	public function match_request($verb, $url) {
		return parent::match_request($verb, $url);
	}

}

?>


text:
  > Custom Diff lexer which show diff along with JSON/Ruby syntax highlighting.

## Demo

* Install dependencies

```
bundle
```

* Start the server

```
rackup config.ru
```

## Screenshots

![diff](images/diff.png) | ![ruby](images/ruby.png)  | ![ruby-diff](images/ruby-diff.png)
---|---|---
Diff Lexer | Ruby Lexer  | RubyDiff custom lexer

## Try a different theme

Get the list of themes from [rouge/lib/rouge/themes](https://github.com/jneen/rouge/tree/ec665bb2ccac767874e85c5b9d6fdefbf471058e/lib/rouge/themes) and generate theme via command

```
rougify style <theme> > public/css/style.css
```

## License

[MIT](https://revathskumar.mit-license.org/)

```
The MIT License (MIT)
Copyright © 2017 Revath S Kumar

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
```


text:
const { ProgressBar } = require('../lib')

const bar = new ProgressBar({
  schema:
    ' [:filled.gradient(red,magenta):blank] :current/:total :percent :elapseds :etas',
})

const iv = setInterval(() => {
  bar.tick()

  if (bar.completed) {
    clearInterval(iv)
  }
}, 100)


text:
using System;
using System.Collections;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

namespace Interop.Excel {
#pragma warning disable 1591

    /// <summary>
    /// Workbook interface
    /// </summary>
    [Guid("00024471-0000-0000-C000-000000000046"), ComImport, InterfaceType(2), TypeLibType(4160)]
    public interface IListObject {

        [DispId(2313)]
        IRange HeaderRowRange {
            [DispId(2313), MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
            get;
        }

        [DispId(705)]
        IRange DataBodyRange {
            [DispId(705), MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
            get;
        }

    }

}


text:
<!DOCTYPE HTML>

<meta charset="utf-8">
<title>JavaScript Templates Test</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.3.4/mocha.min.css">


text:
/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId])
/******/ 			return installedModules[moduleId].exports;
/******/
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			exports: {},
/******/ 			id: moduleId,
/******/ 			loaded: false
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.loaded = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/*!********************************!*\
  !*** ./loaders/query/index.js ***!
  \********************************/
/***/ function(module, exports, __webpack_require__) {

	it("should pass query to loader", function() {
		var result = __webpack_require__(/*! ./loaders/queryloader?query!./a?resourcequery */ 3);
		result.should.be.eql({
			resourceQuery: "?resourcequery",
			query: "?query",
			prev: "module.exports = \"a\";"
		});
	});

	it("should pass query to loader without resource with resource query", function() {
		var result = __webpack_require__(/*! ./loaders/queryloader?query!?resourcequery */ 1);
		result.should.be.eql({
			resourceQuery: "?resourcequery",
			query: "?query",
			prev: null
		});
	});

	it("should pass query to loader without resource", function() {
		var result = __webpack_require__(/*! ./loaders/queryloader?query */ 2);
		result.should.be.eql({
			query: "?query",
			prev: null
		});
	});

	it("should pass query to multiple loaders", function() {
		var result = __webpack_require__(/*! ./loaders/queryloader?query1!./loaders/queryloader?query2!./a?resourcequery */ 4);
		result.should.have.type("object");
		result.should.have.property("resourceQuery").be.eql("?resourcequery");
		result.should.have.property("query").be.eql("?query1");
		result.should.have.property("prev").be.eql("module.exports = " + JSON.stringify({
			resourceQuery: "?resourcequery",
			query: "?query2",
			prev: "module.exports = \"a\";"
		}));
	});

	it("should pass query to loader over context", function() {
		var test = "test";
		var result = __webpack_require__(/*! ./loaders/queryloader?query!./context-query-test */ 5)("./" + test);
		result.should.be.eql({
			resourceQuery: null,
			query: "?query",
			prev: "test content"
		});
	});

/***/ },
/* 1 */
/*!*******************************************************************!*\
  !*** ./loaders/query/loaders/queryloader.js?query!?resourcequery ***!
  \*******************************************************************/
/***/ function(module, exports, __webpack_require__) {

	module.exports = {"resourceQuery":"?resourcequery","query":"?query","prev":null}

/***/ },
/* 2 */
/*!*****************************************************!*\
  !*** ./loaders/query/loaders/queryloader.js?query! ***!
  \*****************************************************/
/***/ function(module, exports, __webpack_require__) {

	module.exports = {"query":"?query","prev":null}

/***/ },
/* 3 */
/*!***************************************************************************************!*\
  !*** ./loaders/query/loaders/queryloader.js?query!./loaders/query/a.js?resourcequery ***!
  \***************************************************************************************/
/***/ function(module, exports, __webpack_require__) {

	module.exports = {"resourceQuery":"?resourcequery","query":"?query","prev":"module.exports = \"a\";"}

/***/ },
/* 4 */
/*!**************************************************************************************************************************************!*\
  !*** ./loaders/query/loaders/queryloader.js?query1!./loaders/query/loaders/queryloader.js?query2!./loaders/query/a.js?resourcequery ***!
  \**************************************************************************************************************************************/
/***/ function(module, exports, __webpack_require__) {

	module.exports = {"resourceQuery":"?resourcequery","query":"?query1","prev":"module.exports = {\"resourceQuery\":\"?resourcequery\",\"query\":\"?query2\",\"prev\":\"module.exports = \\\"a\\\";\"}"}

/***/ },
/* 5 */
/*!************************************************************************************************!*\
  !*** ./loaders/query/context-query-test ./loaders/query/loaders/queryloader.js?query!^\.\/.*$ ***!
  \************************************************************************************************/
/***/ function(module, exports, __webpack_require__) {

	var map = {
		"./test": 6,
		"./test.js": 6
	};
	function webpackContext(req) {
		return __webpack_require__(webpackContextResolve(req));
	};
	function webpackContextResolve(req) {
		return map[req] || (function() { throw new Error("Cannot find module '" + req + "'.") }());
	};
	webpackContext.id = 5;
	webpackContext.keys = function webpackContextKeys() {
		return Object.keys(map);
	};
	webpackContext.resolve = webpackContextResolve;
	module.exports = webpackContext;

/***/ },
/* 6 */
/*!***********************************************************************************************!*\
  !*** ./loaders/query/loaders/queryloader.js?query!./loaders/query/context-query-test/test.js ***!
  \***********************************************************************************************/
/***/ function(module, exports, __webpack_require__) {

	module.exports = {"resourceQuery":null,"query":"?query","prev":"test content"}

/***/ }
/******/ ])


text:
/*******************************
 * bio_printing_dialog_box.cpp *
 *******************************/

/****************************************************************************
 *   Written By Mark Pelletier  2017 - Aleph Objects, Inc.                  *
 *   Written By Marcio Teixeira 2018 - Aleph Objects, Inc.                  *
 *                                                                          *
 *   This program is free software: you can redistribute it and/or modify   *
 *   it under the terms of the GNU General Public License as published by   *
 *   the Free Software Foundation, either version 3 of the License, or      *
 *   (at your option) any later version.                                    *
 *                                                                          *
 *   This program is distributed in the hope that it will be useful,        *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of         *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the          *
 *   GNU General Public License for more details.                           *
 *                                                                          *
 *   To view a copy of the GNU General Public License, go to the following  *
 *   location: <https://www.gnu.org/licenses/>.                             *
 ****************************************************************************/

#include "../config.h"
#include "../screens.h"

#ifdef FTDI_BIO_PRINTING_DIALOG_BOX

using namespace FTDI;
using namespace ExtUI;
using namespace Theme;

#define GRID_COLS 2
#define GRID_ROWS 9

void BioPrintingDialogBox::draw_status_message(draw_mode_t what, const char *message) {
  if (what & BACKGROUND) {
    CommandProcessor cmd;
    cmd.cmd(COLOR_RGB(bg_text_enabled))
       .tag(0);
    draw_text_box(cmd, BTN_POS(1,2), BTN_SIZE(2,2), message, OPT_CENTER, font_large);
  }
}

void BioPrintingDialogBox::draw_progress(draw_mode_t what) {
  if (what & FOREGROUND) {
    CommandProcessor cmd;
    cmd.font(font_large)
       .text(BTN_POS(1,1), BTN_SIZE(2,2), isPrinting() ? F("Printing...") : F("Finished."))
       .tag(1)
       .font(font_xlarge);

    draw_circular_progress(cmd, BTN_POS(1,4), BTN_SIZE(2,3), getProgress_percent(), theme_dark, theme_darkest);
  }
}

void BioPrintingDialogBox::draw_time_remaining(draw_mode_t what) {
  if (what & FOREGROUND) {
    const uint32_t elapsed = getProgress_seconds_elapsed();
    const uint8_t hrs = elapsed/3600;
    const uint8_t min = (elapsed/60)%60;

    char time_str[10];
    sprintf_P(time_str, PSTR("%02dh %02dm"), hrs, min);

    CommandProcessor cmd;
    cmd.font(font_large)
       .text(BTN_POS(1,7), BTN_SIZE(2,2), time_str);
  }
}

void BioPrintingDialogBox::draw_interaction_buttons(draw_mode_t what) {
  if (what & FOREGROUND) {
    CommandProcessor cmd;
    cmd.colors(normal_btn)
       .font(font_medium)
       .colors(isPrinting() ? action_btn : normal_btn)
       .tag(2).button(BTN_POS(1,9), BTN_SIZE(1,1), F("Menu"))
       .enabled(isPrinting() ? TERN0(SDSUPPORT, isPrintingFromMedia()) : 1)
       .tag(3)
       .colors(isPrinting() ? normal_btn : action_btn)
       .button(BTN_POS(2,9), BTN_SIZE(1,1), isPrinting() ? F("Cancel") : F("Back"));
  }
}

void BioPrintingDialogBox::onRedraw(draw_mode_t what) {
  if (what & FOREGROUND) {
    draw_progress(FOREGROUND);
    draw_time_remaining(FOREGROUND);
    draw_interaction_buttons(FOREGROUND);
  }
}

bool BioPrintingDialogBox::onTouchEnd(uint8_t tag) {
  switch (tag) {
    case 1: GOTO_SCREEN(FeedratePercentScreen); break;
    case 2: GOTO_SCREEN(TuneMenu); break;
    case 3:
      if (isPrinting())
        GOTO_SCREEN(ConfirmAbortPrintDialogBox);
      else
        GOTO_SCREEN(StatusScreen);
      break;
    default: return false;
  }
  return true;
}

void BioPrintingDialogBox::setStatusMessage(progmem_str message) {
  char buff[strlen_P((const char*)message)+1];
  strcpy_P(buff, (const char*) message);
  setStatusMessage(buff);
}

void BioPrintingDialogBox::setStatusMessage(const char *message) {
  CommandProcessor cmd;
  cmd.cmd(CMD_DLSTART)
     .cmd(CLEAR_COLOR_RGB(bg_color))
     .cmd(CLEAR(true,true,true));

  draw_status_message(BACKGROUND, message);
  draw_progress(BACKGROUND);
  draw_time_remaining(BACKGROUND);
  draw_interaction_buttons(BACKGROUND);
  storeBackground();

  #if ENABLED(TOUCH_UI_DEBUG)
    SERIAL_ECHO_MSG("New status message: ", message);
  #endif

  if (AT_SCREEN(BioPrintingDialogBox))
    current_screen.onRefresh();
}

void BioPrintingDialogBox::onIdle() {
  reset_menu_timeout();
  if (refresh_timer.elapsed(STATUS_UPDATE_INTERVAL)) {
    onRefresh();
    refresh_timer.start();
  }
  BaseScreen::onIdle();
}

void BioPrintingDialogBox::show() {
  GOTO_SCREEN(BioPrintingDialogBox);
}

#endif // FTDI_BIO_PRINTING_DIALOG_BOX


text:
'''
Helpful generators and other tools
'''

# Import python libs
from __future__ import absolute_import
import re

def split(orig, sep=None):
    '''
    Generator function for iterating through large strings, particularly useful
    as a replacement for str.splitlines().

    See http://stackoverflow.com/a/3865367
    '''
    exp = re.compile(r'\s+' if sep is None else re.escape(sep))
    pos = 0
    length = len(orig)
    while True:
        match = exp.search(orig, pos)
        if not match:
            if pos < length or sep is not None:
                val = orig[pos:]
                if val:
                    # Only yield a value if the slice was not an empty string,
                    # because if it is then we've reached the end. This keeps
                    # us from yielding an extra blank value at the end.
                    yield val
            break
        if pos < match.start() or sep is not None:
            yield orig[pos:match.start()]
        pos = match.end()


text:
class BenchmarkChannel < ApplicationCable::Channel
  def subscribed
    Rails.logger.info "a client subscribed: #{id}"
    stream_from id
    stream_from "all"
  end

  def echo(data)
    ActionCable.server.broadcast id, data
  end

  def broadcast(data)
    ActionCable.server.broadcast "all", data
    data["action"] = "broadcastResult"
    ActionCable.server.broadcast id, data
  end
end


text:
from .functions import (concat, reader, writer, output_dir_path,
                        normalize_path, normalize_dir)

__all__ = (concat, reader, writer, output_dir_path,
           normalize_path, normalize_dir)


text:
namespace BEPUphysics.OtherSpaceStages
{
    ///
    /// Defines an object that owns a deferred event creator.
    ///
    public interface IDeferredEventCreatorOwner
    {
        ///
        /// Gets the event creator owned by the object.
        ///
        IDeferredEventCreator EventCreator { get; }
    }
}


text:
import os
import sys
import re
import json
import traceback

# Sanity checks for path string
MP4folder = os.environ['NZBPO_MP4_FOLDER'].strip()
MP4folder = MP4folder.replace('"', '')
MP4folder = MP4folder.replace("'", "")
MP4folder = MP4folder.replace("\\", "/")
if not(MP4folder.endswith("/")):
    MP4folder += "/"
#DEBUG#print MP4folder+" the original is "+os.environ['NZBPO_MP4_FOLDER']

output_dir = None
if 'NZBPO_OUTPUT_DIR' in os.environ:
    output_dir = os.environ['NZBPO_OUTPUT_DIR'].strip()
    if len(output_dir) > 0:
        output_dir = output_dir.replace('"', '')
        output_dir = output_dir.replace("'", "")
        output_dir = output_dir.replace("\\", "/")
        if not(output_dir.endswith("/")):
            output_dir += "/"
        #DEBUG#print Overriding output directory

sys.path.append(MP4folder)
try:
    from readSettings import ReadSettings
    from mkvtomp4 import MkvtoMp4
    from autoprocess import autoProcessMovie, autoProcessTV, autoProcessTVSR, sonarr, radarr
    import logging
    from logging.config import fileConfig
except ImportError:
    print("[ERROR] Wrong path to sickbeard_mp4_automator: " + os.environ['NZBPO_MP4_FOLDER'])
    print("[ERROR] %s" % traceback.print_exc())
    sys.exit(0)

# Setup Logging
logpath = '/var/log/sickbeard_mp4_automator'
if os.name == 'nt':
    logpath = MP4folder
elif not os.path.isdir(logpath):
    try:
        os.mkdir(logpath)
    except:
        logpath = MP4folder
configPath = os.path.abspath(os.path.join(MP4folder, 'logging.ini')).replace("\\", "\\\\")
logPath = os.path.abspath(os.path.join(logpath, 'index.log')).replace("\\", "\\\\")
fileConfig(configPath, defaults={'logfilename': logPath})
log = logging.getLogger("NZBGetPostProcess")

# Determine if conversion will take place
shouldConvert = (os.environ['NZBPO_SHOULDCONVERT'].lower() in ("yes", "true", "t", "1"))

if 'NZBOP_SCRIPTDIR' in os.environ and not os.environ['NZBOP_VERSION'][0:5] < '11.0':
    log.info("Script triggered from NZBGet (11.0 or later).")

    path = os.environ['NZBPP_DIRECTORY']  # Path to NZB directory
    nzb = os.environ['NZBPP_NZBFILENAME']  # Original NZB name
    category = os.environ['NZBPP_CATEGORY']  # NZB Category to determine destination
    #DEBUG#print "Category is %s." % category

    couchcat = os.environ['NZBPO_CP_CAT'].lower()
    sonarrcat = os.environ['NZBPO_SONARR_CAT'].lower()
    radarrcat = os.environ['NZBPO_RADARR_CAT'].lower()
    sickbeardcat = os.environ['NZBPO_SICKBEARD_CAT'].lower()
    sickragecat = os.environ['NZBPO_SICKRAGE_CAT'].lower()
    bypass = os.environ['NZBPO_BYPASS_CAT'].lower()

    categories = [sickbeardcat, couchcat, sonarrcat, radarrcat, sickragecat, bypass]

    log.debug("Path: %s" % path)
    log.debug("NZB: %s" % nzb)
    log.debug("Category: %s" % category)
    log.debug("Categories: %s" % categories)

    # NZBGet argv: all passed as environment variables.
    clientAgent = "nzbget"
    # Exit codes used by NZBGet
    POSTPROCESS_PARCHECK = 92
    POSTPROCESS_SUCCESS = 93
    POSTPROCESS_ERROR = 94
    POSTPROCESS_NONE = 95

    # Check nzbget.conf options
    status = 0

    if os.environ['NZBOP_UNPACK'] != 'yes':
        log.error("Please enable option \"Unpack\" in nzbget configuration file, exiting.")
        sys.exit(POSTPROCESS_NONE)

    # Check par status
    if os.environ['NZBPP_PARSTATUS'] == '3':
        log.error("Par-check successful, but Par-repair disabled, exiting")
        sys.exit(POSTPROCESS_NONE)

    if os.environ['NZBPP_PARSTATUS'] == '1':
        log.error("Par-check failed, setting status \"failed\".")
        status = 1
        sys.exit(POSTPROCESS_NONE)

    # Check unpack status
    if os.environ['NZBPP_UNPACKSTATUS'] == '1':
        log.error("Unpack failed, setting status \"failed\".")
        status = 1
        sys.exit(POSTPROCESS_NONE)

    if os.environ['NZBPP_UNPACKSTATUS'] == '0' and os.environ['NZBPP_PARSTATUS'] != '2':
        # Unpack is disabled or was skipped due to nzb-file properties or due to errors during par-check

        for dirpath, dirnames, filenames in os.walk(os.environ['NZBPP_DIRECTORY']):
            for file in filenames:
                fileExtension = os.path.splitext(file)[1]

                if fileExtension in ['.par2']:
                    log.error("Post-Process: Unpack skipped and par-check skipped (although par2-files exist), setting status \"failed\".")
                    status = 1
                    break

        if os.path.isfile(os.path.join(os.environ['NZBPP_DIRECTORY'], "_brokenlog.txt")) and not status == 1:
            log.error("Post-Process: _brokenlog.txt exists, download is probably damaged, exiting.")
            status = 1

        if not status == 1:
            log.error("Neither par2-files found, _brokenlog.txt doesn't exist, considering download successful.")

    # Check if destination directory exists (important for reprocessing of history items)
    if not os.path.isdir(os.environ['NZBPP_DIRECTORY']):
        log.error("Post-Process: Nothing to post-process: destination directory ", os.environ['NZBPP_DIRECTORY'], "doesn't exist.")
        status = 1
        sys.exit(POSTPROCESS_NONE)

    # Make sure one of the appropriate categories is set
    if category.lower() not in categories:
        log.error("Post-Process: No valid category detected. Category was %s." % (category))
        status = 1
        sys.exit(POSTPROCESS_NONE)

    # Make sure there are no duplicate categories
    if len(categories) != len(set(categories)):
        log.error("Duplicate category detected. Category names must be unique.")
        status = 1
        sys.exit(POSTPROCESS_NONE)

    # All checks done, now launching the script.
    settings = ReadSettings(MP4folder, "autoProcess.ini")

    successful_process = False
    if shouldConvert:
        if output_dir:
            settings.output_dir = output_dir
        converter = MkvtoMp4(settings, logger=log)
        biggest_file_size = 0
        biggest_file_name = ""
        m2ts_file = False
        for r, d, f in os.walk(path):
            for file in f:
                filepath = os.path.join(r, file)
                if filepath.endswith('.m2ts'): #m2ts files just screw up everything, but typically the largest file is the file that we want to convert.
                    m2ts_file = True
                    size = os.path.getsize(filepath)
                    if size > biggest_file_size:
                        biggest_file_size = size
                        biggest_file_name = filepath
            for files in f:
                inputfile = os.path.join(r, files)
                if m2ts_file == True:
                    dir_name = os.path.dirname(os.path.realpath( biggest_file_name ))
                    inputfile = biggest_file_name
                #DEBUG#print inputfile
                #Ignores files under 50MB
                if os.path.getsize(inputfile) > 50000000:
                    if MkvtoMp4(settings, logger=log).validSource(inputfile):
                        try:
                            output = converter.process(inputfile)
                            if output:
                                log.info("Successfully processed %s." % inputfile)
                                successful_process = True
                            else:
                                log.exception( "File Processing Failed" )
                        except:
                            log.exception("File processing failed.")
                        if m2ts_file == True:
                            filelist = [ f_r for f_r in os.listdir(dir_name) if f_r.endswith(".m2ts") ]
                            for f_r in filelist:
                                file_to_remove = os.path.join(r, f_r)
                                os.remove(file_to_remove)
                            break
        if converter.output_dir:
            path = converter.output_dir

    if successful_process == False: #This means that there were no files that could be converted, i.e: probably an iso
        sys.exit( POSTPROCESS_ERROR )
    elif (category.lower() == categories[0]):
        #DEBUG#print "Sickbeard Processing Activated"
        autoProcessTV.processEpisode(path, settings, nzb)
        sys.exit(POSTPROCESS_SUCCESS)
    elif (category.lower() == categories[1]):
        #DEBUG#print "CouchPotato Processing Activated"
        autoProcessMovie.process(path, settings, nzb, status)
        sys.exit(POSTPROCESS_SUCCESS)
    elif (category.lower() == categories[2]):
        #DEBUG#print "Sonarr Processing Activated"
        success = sonarr.processEpisode(path, settings, True)
        if success:
            sys.exit(POSTPROCESS_SUCCESS)
        else:
            sys.exit(POSTPROCESS_ERROR)
    elif (category.lower() == categories[3]):
        #DEBUG#print "Radarr Processing Activated"
        success = radarr.processMovie(path, settings, True)
        if success:
            sys.exit(POSTPROCESS_SUCCESS)
        else:
            sys.exit(POSTPROCESS_ERROR)
    elif (category.lower() == categories[4]):
        #DEBUG#print "Sickrage Processing Activated"
        autoProcessTVSR.processEpisode(path, settings, nzb)
        sys.exit(POSTPROCESS_SUCCESS)
    elif (category.lower() == categories[5]):
        #DEBUG#print "Bypass Further Processing"
        sys.exit(POSTPROCESS_NONE)

else:
    log.error("This script can only be called from NZBGet (11.0 or later).")
    sys.exit(0)


text:
import cv2
import numpy as np

class ImgGreyscale():

    def run(self, img_arr):
        img_arr = cv2.cvtColor(img_arr, cv2.COLOR_RGB2GRAY)
        return img_arr

class ImgCanny():

    def __init__(self, low_threshold=60, high_threshold=110):
        self.low_threshold = low_threshold
        self.high_threshold = high_threshold

    def run(self, img_arr):
        return cv2.Canny(img_arr,
                         self.low_threshold,
                         self.high_threshold)

class ImgGaussianBlur():

    def __init__(self, kernal_size=5):
        self.kernal_size = kernal_size

    def run(self, img_arr):
        return cv2.GaussianBlur(img_arr,
                                (self.kernel_size, self.kernel_size), 0)

class ImgCrop:
    """
    Crop an image to an area of interest.
    """
    def __init__(self, top=0, bottom=0, left=0, right=0):
        self.top = top
        self.bottom = bottom
        self.left = left
        self.right = right

    def run(self, img_arr):
        width, height, _ = img_arr.shape
        img_arr = img_arr[self.top:height-self.bottom,
                          self.left: width-self.right]
        return img_arr

class ImgFIFO:
    """
    Stack N previous images into a single N channel image, after converting each to grayscale.
    The most recent image is the last channel, and pushes previous images towards the front.
    """
    def __init__(self, num_channels=3):
        self.img_arr = None
        self.num_channels = num_channels

    def run(self, img_arr):
        width, height, _ = img_arr.shape
        gray = cv2.cvtColor(img_arr, cv2.COLOR_RGB2GRAY)

        if self.img_arr is None:
            self.img_arr = np.zeros([width, height, self.num_channels], dtype=np.dtype('B'))

        for ch in range(self.num_channels - 1):
            self.img_arr[...,ch] = self.img_arr[...,ch+1]

        self.img_arr[...,self.num_channels - 1:] = np.reshape(gray, (width, height, 1))

        return self.img_arr

class Pipeline():
    def __init__(self, steps):
        self.steps = steps

    def run(self, val):
        for step in self.steps:
            f = step['f']
            args = step['args']
            kwargs = step['kwargs']

            val = f(val, *args, **kwargs)
        return val


text:
package ge.edu.freeuni.sdp.arkanoid.model;

import ge.edu.freeuni.sdp.arkanoid.model.geometry.Direction;
import ge.edu.freeuni.sdp.arkanoid.model.geometry.Point;

/**
 * Created by misho on 4/7/2016.
 */
public class ScrollingBrick extends MovingBrick {
    private static final long SCROLLING_DELAY = 3000;

    public ScrollingBrick(Point position, BrickColor color, Capsule capsule) {
        super(position, color, capsule, Direction.RIGHT, SCROLLING_DELAY);
    }
}


text:
function nifti_4dto3d_convert_recursive(rootpath, spmpath)
% nifti_4dto3d_convert_recursive(rootpath, spmpath)
% Converts all 4D nifti files to 3D nifti recursively, using SPM.
% WARNING: will delete the 4D nifti files! Make a backup before!
% Useful to avoid memory errors when processing (the dreaded "cant map view" error) when the nifti is too big.
% This script needs both SPM (to convert from 4D to 3D) and dirPlus (https://github.com/kpeaton/dirPlus).
% by Stephen Larroque, 2017, from the Coma Science Group, University of Liege
%
% Temporarily restore factory path and set path to SPM and its toolboxes, this avoids conflicts when having different versions of SPM installed on the same machine
bakpath = path; % backup the current path variable
restoredefaultpath(); matlabpath(strrep(matlabpath, userpath, '')); % clean up the path
addpath(spmpath); % add the path to SPM

% Get list of all nifti files (recursively, all .img or .nii files)
niftifiles = dirPlus(rootpath, 'PrependPath', true, 'FileFilter', '.*\.(img|nii)$');

if numel(niftifiles) > 0
    % Test which are 4D nifti files
    idx4d = [];
    for i=1:size(niftifiles, 1)
        if is4D(niftifiles{i})
            idx4d = [idx4d i];
        end
    end %endfor

    if numel(idx4d) > 0
        % Extract only 4D nifti files
        nifti4dfiles = niftifiles(idx4d);

        % Convert each 4D nifti to 3D nifti
        for i=1:numel(nifti4dfiles)
            % Get one 4D nifti file
            nfile = nifti4dfiles{i};
            % Convert to 3D nifti by using SPM
            spm_file_split(nfile);
            % Delete 4D nifti
            delete(nfile);
            % If format is old 4D nifti (with two files: .img/.hdr), delete also the .hdr file
            if strcmpi(nfile(end-3:end), '.img')
                delete([nfile(1:end-4) '.hdr']);
            end %endif
        end %endfor
    end %endif
end %endif

fprintf('All 4D nifti files converted to 3D! Restoring path and exiting...\n');
path(bakpath); % restore the path to the previous state
diary off;
end % end script

function res = is4D(file)
    nbframes = spm_select_get_nbframes(file);
    if nbframes > 1
        res = true;
    else
        res = false;
    end
end

function n = spm_select_get_nbframes(file)
% spm_select_get_nbframes(file) from SPM12 spm_select.m (copied here to be compatible with SPM8)
    N   = nifti(file);
    dim = [N.dat.dim 1 1 1 1 1];
    n   = dim(4);
    fclose('all'); % don't forget to close, else it might get stuck! Else you will get the infamous "Cant map view of file.  It may be locked by another program."
end

function out = expand_4d_vols(files)
% expand_4d_vols(nifti)  Given a path to a 4D nifti file, count the number of volumes and generate a list of all volumes
% updated by Stephen Larroque (LRQ3000) to expand multiple files
% this is an alternative to adding to the batch after named file selector the module: SPM -> Util -> Expand image frames or matlabbatch{2}.spm.util.exp_frames. This is necessary for VBM apply deformations (but not SPM steps), else you will get error Failed 'Apply Deformations (Many images)' Error using ==> inv Too many input arguments.
    out = {}; % use a cell because we will get strings of variable lengths (so can't use char)
    for i=1:size(files,1)
        s = files(i,:);
        nb_vols = spm_select_get_nbframes(s);
        out = [ out , cellstr(strcat(repmat(s, nb_vols, 1), ',', num2str([1:nb_vols]')))' ];
    end
    % Convert the cell to a char array
    out = char(out);
end


text:
package com.gs.fw.common.mithra.test.domain;
import java.sql.Timestamp;
public class Trade extends TradeAbstract
{
	public Trade(Timestamp businessDate, Timestamp processingDate)
	{
		super(businessDate,processingDate);
	}

	public Trade(Timestamp businessDate)
	{
		super(businessDate);
	}
}


text:
package HTML::Mason::Interp;

use strict;
use warnings;

use File::Basename;
use File::Path;
use File::Spec;
use File::Temp;
use HTML::Mason;
use HTML::Mason::Escapes;
use HTML::Mason::Request;
use HTML::Mason::Resolver::File;
use HTML::Mason::Tools qw(read_file taint_is_on load_pkg);

use HTML::Mason::Exceptions( abbr => [qw(param_error system_error wrong_compiler_error compilation_error error)] );

use Params::Validate qw(:all);
Params::Validate::validation_options( on_fail => sub { param_error join '', @_  } );

use Class::Container;
use base qw(Class::Container);

BEGIN
{
    # Fields that can be set in new method, with defaults
    __PACKAGE__->valid_params
        (
         autohandler_name =>
         { parse => 'string',  default => 'autohandler', type => SCALAR,
           descr => "The filename to use for Mason's 'autohandler' capability" },

         buffer_preallocate_size =>
         { parse => 'string', default => 0, type => SCALAR,
           descr => "Number of bytes to preallocate in request buffer" },

         code_cache_max_size =>
         { parse => 'string',  default => 'unlimited', type => SCALAR,
           descr => "The maximum number of components in the code cache" },

         comp_root =>
         { parse => 'list',
           type => SCALAR|ARRAYREF,
           default => File::Spec->rel2abs( Cwd::cwd ),
           descr => "A string or array of arrays indicating the search path for component calls" },

         compiler =>
         { isa => 'HTML::Mason::Compiler',
           descr => "A Compiler object for compiling components" },

         data_dir =>
         { parse => 'string', optional => 1, type => SCALAR,
           descr => "A directory for storing cache files and other state information" },

         dynamic_comp_root =>
         { parse => 'boolean', default => 0, type => BOOLEAN,
           descr => "Indicates whether the comp_root may be changed between requests" },

         escape_flags =>
         { parse => 'hash_list', optional => 1, type => HASHREF,
           descr => "A list of escape flags to set (as if calling the set_escape() method" },

         object_file_extension =>
         { parse => 'string',  type => SCALAR, default => '.obj',
           descr => "Extension to add to the end of object files" },

         # OBJECT cause qr// returns an object
         ignore_warnings_expr =>
         { parse => 'string',  type => SCALAR|OBJECT, default => qr/Subroutine .* redefined/i,
           descr => "A regular expression describing Perl warning messages to ignore" },

         preloads =>
         { parse => 'list', optional => 1, type => ARRAYREF,
           descr => "A list of components to load immediately when creating the Interpreter" },

         resolver =>
         { isa => 'HTML::Mason::Resolver',
           descr => "A Resolver object for fetching components from storage" },

         static_source =>
         { parse => 'boolean', default => 0, type => BOOLEAN,
           descr => "When true, we only compile source files once" },

         static_source_touch_file =>
         { parse => 'string', optional => 1, type => SCALAR,
           descr => "A file that, when touched, causes Mason to clear its component caches" },

         use_object_files =>
         { parse => 'boolean', default => 1, type => BOOLEAN,
           descr => "Whether to cache component objects on disk" },
        );

    __PACKAGE__->contained_objects
        (
         resolver => { class => 'HTML::Mason::Resolver::File',
                       descr => "This class is expected to return component information based on a component path" },
         compiler => { class => 'HTML::Mason::Compiler::ToObject',
                       descr => "This class is used to translate component source into code" },
         request  => { class => 'HTML::Mason::Request',
                       delayed => 1,
                       descr => "Objects returned by make_request are members of this class" },
        );
}

use HTML::Mason::MethodMaker
    ( read_only => [ qw( autohandler_name
                         buffer_preallocate_size
                         code_cache
                         code_cache_min_size
                         code_cache_max_size
                         compiler
                         data_dir
                         dynamic_comp_root
                         object_file_extension
                         preallocated_output_buffer
                         preloads
                         resolver
                         source_cache
                         static_source
                         static_source_touch_file
                         use_internal_component_caches
                         use_object_files
                        ) ],

      read_write => [ map { [ $_ => __PACKAGE__->validation_spec->{$_} ] }
                      qw( ignore_warnings_expr
                         )
                    ],

      read_write_contained => { request =>
                                [ [ autoflush => { type => BOOLEAN } ],
                                  [ data_cache_api => { type => SCALAR } ],
                                  [ data_cache_defaults => { type => HASHREF } ],
                                  [ dhandler_name => { type => SCALAR } ],
                                  [ error_format => { type => SCALAR } ],
                                  [ error_mode => { type => SCALAR } ],
                                  [ max_recurse => { type => SCALAR } ],
                                  [ out_method => { type => SCALARREF | CODEREF } ],
                                  [ plugins => { type => ARRAYREF } ],
                                ]
                              },
      );

sub new
{
    my $class = shift;
    my $self = $class->SUPER::new(@_);

    $self->_initialize;
    return $self;
}

sub _initialize
{
    my ($self) = shift;
    $self->{code_cache} = {};
    $self->{source_cache} = {};
    $self->{files_written} = [];
    $self->{static_source_touch_file_lastmod} = 0;

    $self->_assign_comp_root($self->{comp_root});
    $self->_check_data_dir();
    $self->_create_data_subdirs();
    $self->_initialize_escapes();

    #
    # Create preallocated buffer for requests.
    #
    $self->{preallocated_output_buffer} = ' ' x $self->buffer_preallocate_size;

    $self->_set_code_cache_attributes();

    #
    # If static_source=1, unlimited_code_cache=1, and
    # dynamic_comp_root=0, we can safely cache component objects keyed
    # on path throughout the framework (e.g. within other component
    # objects). These internal caches can be cleared in
    # $interp->flush_code_cache (the only legimiate place for a
    # component to be eliminated from the cache), eliminating any
    # chance for leaked objects.
    #
    # static_source has to be on or else we might keep around
    # old versions of components that have changed.
    #
    # unlimited_code_cache has to be on or else we might leak
    # components when we discard.
    #
    # dynamic_comp_root has to be 0 because the cache would not be
    # valid for different combinations of component root across
    # different requests.
    #
    $self->{use_internal_component_caches} =
        ($self->{static_source} &&
         $self->{unlimited_code_cache} &&
         !$self->{dynamic_comp_root});

    $self->_preload_components();
}

sub _check_data_dir
{
    my $self = shift;

    return unless $self->{data_dir};

    $self->{data_dir} = File::Spec->canonpath( $self->{data_dir} );
    param_error "data_dir '$self->{data_dir}' must be an absolute directory"
        unless File::Spec->file_name_is_absolute( $self->{data_dir} );
}

sub _create_data_subdirs
{
    my $self = shift;

    if ($self->data_dir) {
        $self->_make_object_dir;
        $self->_make_cache_dir;
    } else {
        $self->{use_object_files} = 0;
    }
}

sub _initialize_escapes
{
    my $self = shift;

    #
    # Add the escape flags (including defaults)
    #
    foreach ( [ h => \&HTML::Mason::Escapes::html_entities_escape ],
              [ u => \&HTML::Mason::Escapes::url_escape ],
            )
    {
        $self->set_escape(@$_);
    }

    if ( my $e = delete $self->{escape_flags} )
    {
        while ( my ($flag, $code) = each %$e )
        {
            $self->set_escape( $flag => $code );
        }
    }
}

sub _set_code_cache_attributes
{
    my $self = shift;

    $self->{unlimited_code_cache} = ($self->{code_cache_max_size} eq 'unlimited');
    unless ($self->{unlimited_code_cache}) {
        $self->{code_cache_min_size} = $self->{code_cache_max_size} * 0.75;
    }
}

sub _preload_components
{
    my $self = shift;

    return unless $self->preloads;

    foreach my $pattern (@{$self->preloads}) {
        error "preload pattern '$pattern' must be an absolute path"
            unless File::Spec->file_name_is_absolute($pattern);
        my %path_hash;
        foreach my $pair ($self->comp_root_array) {
            my $root = $pair->[1];
            foreach my $path ($self->resolver->glob_path($pattern, $root)) {
                $path_hash{$path}++;
            }
        }
        my @paths = keys(%path_hash);
        warn "Didn't find any components for preload pattern '$pattern'"
            unless @paths;
        foreach (@paths)
        {
            $self->load($_)
                or error "Cannot load component $_, found via pattern $pattern";
        }
    }
}

#
# Functions for retrieving and creating data subdirectories.
#
sub object_dir { my $self = shift; return $self->data_dir ? File::Spec->catdir( $self->data_dir, 'obj' ) : ''; }
sub object_create_marker_file { my $self = shift; return $self->object_dir ? File::Spec->catfile($self->object_dir, '.__obj_create_marker') : ''; }
sub cache_dir  { my $self = shift; return $self->data_dir ? File::Spec->catdir( $self->data_dir, 'cache' ) : ''; }

sub _make_data_subdir
{
    my ($self, $dir) = @_;

    unless (-d $dir) {
        my @newdirs = eval { mkpath( $dir, 0, 0775 ) };
        if ($@) {
            my $user  = getpwuid($<);
            my $group = getgrgid($();
            my $data_dir = $self->data_dir;
            error "Cannot create directory '$dir' ($@) for user '$user', group '$group'. " .
                "Perhaps you need to create or set permissions on your data_dir ('$data_dir'). ";
        }
        $self->push_files_written(@newdirs);
    }
}

sub _make_object_dir
{
    my ($self) = @_;

    my $object_dir = $self->object_dir;
    $self->_make_data_subdir($object_dir);
    my $object_create_marker_file = $self->object_create_marker_file;
    unless (-f $object_create_marker_file) {
        open my $fh, ">$object_create_marker_file"
            or system_error "Could not create '$object_create_marker_file': $!";
        $self->push_files_written($object_create_marker_file);
    }
}

sub _make_cache_dir
{
    my ($self) = @_;

    my $cache_dir = $self->cache_dir;
    $self->_make_data_subdir($cache_dir);
}

#
# exec is the initial entry point for executing a component
# in a new request.
#
sub exec {
    my $self = shift;
    my $comp = shift;
    $self->make_request(comp=>$comp, args=>\@_)->exec;
}

sub make_request {
    my $self = shift;

    return $self->create_delayed_object( 'request', interp => $self, @_ );
}

sub comp_exists {
    my ($self, $path) = @_;
    return $self->resolve_comp_path_to_source($path);
}

#
# Load <$path> into a component, possibly parsing the source and/or
# caching the code. Returns a component object or undef if the
# component was not found.
#
sub load {
    my ($self, $path) = @_;
    my ($maxfilemod, $objfile, $objfilemod);
    my $code_cache = $self->{code_cache};
    my $resolver = $self->{resolver};

    #
    # Path must be absolute.
    #
    unless (substr($path, 0, 1) eq '/') {
        error "Component path given to Interp->load must be absolute (was given $path)";
    }

    #
    # Get source info from resolver.
    #
    my $source = $self->resolve_comp_path_to_source($path);

    # No component matches this path.
    return unless defined $source;

    # comp_id is the unique name for the component, used for cache key
    # and object file name.
    my $comp_id = $source->comp_id;

    #
    # Get last modified time of source.
    #
    my $srcmod = $source->last_modified;

    #
    # If code cache contains an up to date entry for this path, use
    # the cached comp.  Always use the cached comp in static_source
    # mode.
    #
    if ( exists $code_cache->{$comp_id} &&
         ( $self->static_source || $code_cache->{$comp_id}->{lastmod} >= $srcmod )
       ) {
        return $code_cache->{$comp_id}->{comp};
    }

    if ($self->{use_object_files}) {
        $objfile = $self->comp_id_to_objfile($comp_id);

        my @stat = stat $objfile;
        if ( @stat && ! -f _ ) {
            error "The object file '$objfile' exists but it is not a file!";
        }

        if ($self->static_source) {
            # No entry in the code cache so if the object file exists,
            # we will use it, otherwise we must create it.  These
            # values make that happen.
            $objfilemod = @stat ? $srcmod : 0;
        } else {
            # If the object file exists, get its modification time.
            # Otherwise (it doesn't exist or it is a directory) we
            # must create it.
            $objfilemod = @stat ? $stat[9] : 0;
        }
    }

    my $comp;
    if ($objfile) {
        #
        # We are using object files.  Update object file if necessary
        # and load component from there.
        #
        # If loading the object file generates an error, or results in
        # a non-component object, try regenerating the object file
        # once before giving up and reporting an error. This can be
        # handy in the rare case of an empty or corrupted object file.
        #
        if ($objfilemod < $srcmod) {
            $self->compiler->compile_to_file( file => $objfile, source => $source);
        }
        $comp = eval { $self->eval_object_code( object_file => $objfile ) };

        if (!UNIVERSAL::isa($comp, 'HTML::Mason::Component')) {
            $self->compiler->compile_to_file( file => $objfile, source => $source);
            $comp = eval { $self->eval_object_code( object_file => $objfile ) };

            if (!UNIVERSAL::isa($comp, 'HTML::Mason::Component')) {
                my $error = $@ ? $@ : "Could not get HTML::Mason::Component object from object file '$objfile'";
                $self->_compilation_error( $source->friendly_name, $error );
            }
        }
    } else {
        #
        # Not using object files. Load component directly into memory.
        #
        my $object_code = $source->object_code( compiler => $self->compiler );
        $comp = eval { $self->eval_object_code( object_code => $object_code ) };
        $self->_compilation_error( $source->friendly_name, $@ ) if $@;
    }
    $comp->assign_runtime_properties($self, $source);

    #
    # Delete any stale cached version of this component, then
    # cache it.
    #
    $self->delete_from_code_cache($comp_id);
    $code_cache->{$comp_id} = { lastmod => $srcmod, comp => $comp };

    return $comp;
}

sub delete_from_code_cache {
    my ($self, $comp_id) = @_;
    return unless defined $self->{code_cache}{$comp_id}{comp};

    delete $self->{code_cache}{$comp_id};
    return;
}

sub comp_id_to_objfile {
    my ($self, $comp_id) = @_;

    return File::Spec->catfile
               ( $self->object_dir,
                 $self->compiler->object_id,
                 ( split /\//, $comp_id ),
               ) . $self->object_file_extension;
}

#
# Empty in-memory code cache.
#
sub flush_code_cache {
    my $self = shift;

    # Necessary for preventing memory leaks
    if ($self->use_internal_component_caches) {
        foreach my $entry (values %{$self->{code_cache}}) {
            my $comp = $entry->{comp};
            $comp->flush_internal_caches;
        }
    }
    $self->{code_cache} = {};
    $self->{source_cache} = {};
}

#
# If code cache has exceeded maximum, remove least frequently used
# elements from cache until size falls below minimum.
#
sub purge_code_cache {
    my ($self) = @_;

    return if $self->{unlimited_code_cache};
    my $current_size = scalar(keys(%{$self->{code_cache}}));
    if ($current_size > $self->code_cache_max_size) {
        my $code_cache = $self->{code_cache};
        my $min_size = $self->code_cache_min_size;
        my $decay_factor = 0.75;

        my @elems;
        while (my ($path,$href) = each(%{$code_cache})) {
            push(@elems,[$path,$href->{comp}->mfu_count,$href->{comp}]);
        }
        @elems = sort { $a->[1] <=> $b->[1] } @elems;
        while (($current_size > $min_size) and @elems) {
            $self->delete_from_code_cache(shift(@elems)->[0]);
            $current_size--;
        }

        #
        # Multiply each remaining cache item's count by a decay factor,
        # to gradually reduce impact of old information.
        #
        foreach my $elem (@elems) {
            $elem->[2]->mfu_count( $elem->[2]->mfu_count * $decay_factor );
        }
    }
}

#
# Clear the object directory of all current files and subdirectories.
# Do this by renaming the object directory to a temporary name,
# immediately recreating an empty object directory, then removing
# the empty object directory. If another process tries to write
# the object file in between these steps, it'll create the top
# object directory instead.
#
# Would be nice to fork off a separate process to do the removing so
# that it doesn't affect a request's response time, but difficult to
# do this in an environment-generic way.
#
sub remove_object_files
{
    my $self = shift;

    my $object_dir = $self->object_dir;
    if (-d $object_dir) {
        my $temp_dir = File::Temp::tempdir(DIR => $self->data_dir);
        rename($object_dir, File::Spec->catdir( $temp_dir, 'target' ) )
            or die "could not rename '$object_dir' to '$temp_dir': $@";
        $self->_make_object_dir();
        rmtree($temp_dir);
    } else {
        $self->_make_object_dir();
    }
}

#
# Check the static_source_touch_file, if one exists, to see if it has
# changed since we last checked. If it has, clear the code cache and
# object files if appropriate.
#
sub check_static_source_touch_file
{
    my $self = shift;

    if (my $touch_file = $self->static_source_touch_file) {
        return unless -f $touch_file;
        my $touch_file_lastmod = (stat($touch_file))[9];
        if ($touch_file_lastmod > $self->{static_source_touch_file_lastmod}) {

            # File has been touched since we last checked.  First,
            # clear the object file directory if the last mod of
            # its ._object_create_marker is earlier than the touch file,
            # or if the marker doesn't exist.
            #
            if ($self->use_object_files) {
                my $object_create_marker_file = $self->object_create_marker_file;
                if (!-e $object_create_marker_file ||
                    (stat($object_create_marker_file))[9] < $touch_file_lastmod) {
                    $self->remove_object_files;
                }
            }

            # Next, clear the in-memory component cache.
            #
            $self->flush_code_cache;

            # Reset lastmod value.
            #
            $self->{static_source_touch_file_lastmod} = $touch_file_lastmod;
        }
    }
}

#
# Construct a component on the fly.  Virtual if 'path' parameter is
# given, otherwise anonymous.
#
sub make_component {
    my $self = shift;

    my %p = validate(@_, { comp_source => { type => SCALAR, optional => 1 },
                           comp_file   => { type => SCALAR, optional => 1 },
                           name        => { type => SCALAR, optional => 1 } });

    $p{comp_source} = read_file(delete $p{comp_file}) if exists $p{comp_file};
    param_error "Must specify either 'comp_source' or 'comp_file' parameter to 'make_component()'"
        unless defined $p{comp_source};

    $p{name} ||= '<anonymous component>';

    my $source = HTML::Mason::ComponentSource->new( friendly_name => $p{name},
                                                    comp_path => $p{name},
                                                    comp_id => undef,
                                                    last_modified => time,
                                                    comp_class => 'HTML::Mason::Component',
                                                    source_callback => sub { $p{comp_source} },
                                                  );

    my $object_code = $source->object_code( compiler => $self->compiler);

    my $comp = eval { $self->eval_object_code( object_code => $object_code ) };
    $self->_compilation_error( $p{name}, $@ ) if $@;

    $comp->assign_runtime_properties($self, $source);

    return $comp;
}

sub set_global
{
    my ($self, $decl, @values) = @_;
    param_error "Interp->set_global: expects a variable name and one or more values"
        unless @values;
    my ($prefix, $name) = ($decl =~ s/^([\$@%])//) ? ($1, $decl) : ('$', $decl);

    my $varname = sprintf("%s::%s",$self->compiler->in_package,$name);
    no strict 'refs';
    if ($prefix eq '$') {
        $$varname = $values[0];
    } elsif ($prefix eq '@') {
        @$varname = @values;
    } else {
        %$varname = @values;
    }
}

sub comp_root
{
    my $self = shift;

    if (my $new_comp_root = shift) {
        die "cannot assign new comp_root unless dynamic_comp_root parameter is set"
          unless $self->dynamic_comp_root;
        $self->_assign_comp_root($new_comp_root);
    }
    if (@{$self->{comp_root}} == 1 and $self->{comp_root}[0][0] eq 'MAIN') {
        return $self->{comp_root}[0][1];
    } else {
        return $self->{comp_root};
    }
}

sub comp_root_array
{
    return @{ $_[0]->{comp_root} };
}

sub _assign_comp_root
{
    my ($self, $new_comp_root) = @_;

    # Force into lol format.
    if (!ref($new_comp_root)) {
        $new_comp_root = [[ MAIN => $new_comp_root ]];
    } elsif (ref($new_comp_root) ne 'ARRAY') {
        die "Component root $new_comp_root must be a scalar or array reference";
    }

    # Validate key/path pairs, and check to see if any of them
    # conflict with old pairs.
    my $comp_root_key_map = $self->{comp_root_key_map} ||= {};
    foreach my $pair (@$new_comp_root) {
        param_error "Multiple-path component root must consist of a list of two-element lists"
          if ref($pair) ne 'ARRAY';
        param_error "Component root key '$pair->[0]' cannot contain slash"
          if $pair->[0] =~ /\//;
        $pair->[1] = File::Spec->canonpath( $pair->[1] );
        param_error "comp_root path '$pair->[1]' is not an absolute directory"
          unless File::Spec->file_name_is_absolute( $pair->[1] );

        my ($key, $path) = @$pair;
        if (my $orig_path = $comp_root_key_map->{$key}) {
            if ($path ne $orig_path) {
                die "comp_root key '$key' was originally associated with '$path', cannot change to '$orig_path'";
            }
        } else {
            $comp_root_key_map->{$key} = $path;
        }
    }
    $self->{comp_root} = $new_comp_root;
}

sub resolve_comp_path_to_source
{
    my ($self, $path) = @_;

    my $source;
    if ($self->{static_source}) {
        # Maintain a separate source_cache for each component root,
        # because the set of active component roots can change
        # from request to request.
        #
        my $source_cache = $self->{source_cache};
        foreach my $pair (@{$self->{comp_root}}) {
            my $source_cache_for_root = $source_cache->{$pair->[0]} ||= {};
            unless (exists($source_cache_for_root->{$path})) {
                $source_cache_for_root->{$path}
                  = $self->{resolver}->get_info($path, @$pair);
            }
            last if $source = $source_cache_for_root->{$path};
        }
    } else {
        my $resolver = $self->{resolver};
        foreach my $pair ($self->comp_root_array) {
            last if $source = $resolver->get_info($path, @$pair);
        }
    }
    return $source;
}

sub files_written
{
    my $self = shift;
    return @{$self->{files_written}};
}

#
# Push onto list of written files.
#
sub push_files_written
{
    my $self = shift;
    my $fref = $self->{'files_written'};
    push(@$fref,@_);
}

#
# Look for component <$name> starting in <$startpath> and moving upwards
# to the root. Return component object or undef.
#
sub find_comp_upwards
{
    my ($self, $startpath, $name) = @_;
    $startpath =~ s{/+$}{};

    # Don't use File::Spec here, this is a URL path.
    do {
      my $comp = $self->load("$startpath/$name");
      return $comp if $comp;
    } while $startpath =~ s{/+[^/]*$}{};

    return;  # Nothing found
}

###################################################################
# The eval_object_code & write_object_file methods used to be in
# Parser.pm.  This is a temporary home only.  They need to be moved
# again at some point in the future (during some sort of interp
# re-architecting).
###################################################################

#
# eval_object_code
#   (object_code, object_file, error)
# Evaluate an object file or object text.  Return a component object
# or undef if error.
#
# I think this belongs in the resolver (or comp loader) - Dave
#
sub eval_object_code
{
    my ($self, %p) = @_;

    #
    # Evaluate object file or text with warnings on, unless
    # ignore_warnings_expr is '.'.
    #
    my $ignore_expr = $self->ignore_warnings_expr;
    my ($comp, $err);
    my $warnstr = '';

    {
        local $^W = $ignore_expr eq '.' ? 0 : 1;
        local $SIG{__WARN__} =
            ( $ignore_expr ?
              ( $ignore_expr eq '.' ?
                sub { } :
                sub { $warnstr .= $_[0] if $_[0] !~ /$ignore_expr/ }
              ) :
              sub { $warnstr .= $_[0] } );

        $comp = $self->_do_or_eval(\%p);
    }

    $err = $warnstr . $@;

    #
    # Return component or error
    #
    if ($err) {
        # attempt to stem very long eval errors
        $err =~ s/has too many errors\..+/has too many errors./s;
        compilation_error $err;
    } else {
        return $comp;
    }
}

sub _do_or_eval
{
    my ($self, $p) = @_;

    if ($p->{object_file}) {
        return do $p->{object_file};
    } else {
        # If in taint mode, untaint the object text
        (${$p->{object_code}}) = ${$p->{object_code}} =~ /^(.*)/s if taint_is_on;

        return eval ${$p->{object_code}};
    }
}

sub _compilation_error {
    my ($self, $filename, $err) = @_;

    HTML::Mason::Exception::Compilation->throw(error=>$err, filename=>$filename);
}

sub object_file {
    my ($self, $comp) = @_;
    return $comp->persistent ?
        $self->comp_id_to_objfile($comp->comp_id) :
        undef;
}

sub use_autohandlers
{
    my $self = shift;
    return defined $self->{autohandler_name} and length $self->{autohandler_name};
}

# Generate HTML that describes Interp's current status.
# This is used in things like Apache::Status reports.  Currently shows:
# -- Interp properties
# -- loaded (cached) components
sub status_as_html {
    my ($self, %p) = @_;

    # Should I be scared about this?  =)

    my $comp_source = <<'EOF';
<h3>Interpreter properties:</h3>
<blockquote>
 <h4>Startup options:</h4>
 <tt>
<table width="100%">
<%perl>
foreach my $property (sort keys %$interp) {
    my $val = $interp->{$property};

    my $default = ( defined $val && defined $valid{$property}{default} && $val eq $valid{$property}{default} ) || ( ! defined $val && exists $valid{$property}{default} && ! defined $valid{$property}{default} );

    my $display = $val;
    if (ref $val) {
        $display = '<font color="darkred">';
        # only object can ->can, others die
        my $is_object = eval { $val->can('anything'); 1 };
        if ($is_object) {
            $display .= ref $val . ' object';
        } else {
            if (UNIVERSAL::isa($val, 'ARRAY')) {
                $display .= 'ARRAY reference - [ ';
                $display .= join ', ', @$val;
                $display .= '] ';
            } elsif (UNIVERSAL::isa($val, 'HASH')) {
                $display .= 'HASH reference - { ';
                my @pairs;
                while (my ($k, $v) = each %$val) {
                   push @pairs, "$k => $v";
                }
                $display .= join ', ', @pairs;
                $display .= ' }';
            } else {
                $display = ref $val . ' reference';
            }
        }
        $display .= '</font>';
    }

    defined $display && $display =~ s,([\x00-\x1F]),'<font color="purple">control-' . chr( ord('A') + ord($1) - 1 ) . '</font>',eg; # does this work for non-ASCII?
</%perl>
 <tr valign="top" cellspacing="10">
  <td>
    <% $property | h %>
  </td>
  <td>
   <% defined $display ? $display : '<i>undef</i>' %>
   <% $default ? '<font color=green>(default)</font>' : '' %>
  </td>
 </tr>
% }
</table>
  </tt>

 <h4>Components in memory cache:</h4>
 <tt>
% my $cache;
% if ($cache = $interp->code_cache and %$cache) {
%   foreach my $key (sort keys %$cache) {
      <% $key |h%> (modified <% scalar localtime $cache->{$key}->{lastmod} %>)
      <br>
%   }
% } else {
    <I>None</I>
% }
  </tt>
</blockquote>

<%args>
 $interp   # The interpreter we'll elucidate
 %valid    # Default values for interp member data
</%args>
EOF

    my $comp = $self->make_component(comp_source => $comp_source);
    my $out;

    my $args = [interp => $self, valid => $self->validation_spec];
    $self->make_request(comp=>$comp, args=>$args, out_method=>\$out, %p)->exec;

    return $out;
}

sub set_escape
{
    my $self = shift;
    my %p = @_;

    while ( my ($name, $sub) = each %p )
    {
        my $flag_regex = $self->compiler->lexer->escape_flag_regex;

        param_error "Invalid escape name ($name)"
            if $name !~ /^$flag_regex$/ || $name =~ /^n$/;

        my $coderef;
        if ( ref $sub )
        {
            $coderef = $sub;
        }
        else
        {
            if ( $sub =~ /^\w+$/ )
            {
                no strict 'refs';
                unless ( defined &{"HTML::Mason::Escapes::$sub"} )
                {
                    param_error "Invalid escape: $sub (no matching subroutine in HTML::Mason::Escapes";
                }

                $coderef = \&{"HTML::Mason::Escapes::$sub"};
            }
            else
            {
                $coderef = eval $sub;
                param_error "Invalid escape: $sub ($@)" if $@;
            }
        }

        $self->{escapes}{$name} = $coderef;
    }
}

sub remove_escape
{
    my $self = shift;

    delete $self->{escapes}{ shift() };
}

sub apply_escapes
{
    my $self = shift;
    my $text = shift;

    foreach my $flag (@_)
    {
        param_error "Invalid escape flag: $flag"
            unless exists $self->{escapes}{$flag};

        $self->{escapes}{$flag}->(\$text);
    }

    return $text;
}

1;

__END__

=head1 NAME

HTML::Mason::Interp - Mason Component Interpreter

=head1 SYNOPSIS

    my $i = HTML::Mason::Interp->new (data_dir=>'/usr/local/mason',
                                      comp_root=>'/usr/local/www/htdocs/',
                                      ...other params...);

=head1 DESCRIPTION

Interp is the Mason workhorse, executing components and routing their
output and errors to all the right places. In a mod_perl environment,
Interp objects are handed off immediately to an ApacheHandler object
which internally calls the Interp implementation methods. In that case
the only user method is the new() constructor.

=head1 PARAMETERS TO THE new() CONSTRUCTOR

=over

=item autohandler_name

File name used for
L<autohandlers|HTML::Mason::Devel/autohandlers>. Default is
"autohandler".  If this is set to an empty string ("") then
autohandlers are turned off entirely.

=item buffer_preallocate_size

=for html <a name="item_buffer_preallocate_size"></a>

Number of bytes to preallocate in the output buffer for each request.
Defaults to 0. Setting this to, say, your maximum page size (or close
to it) can reduce the number of reallocations Perl performs as
components add to the output buffer.

=item code_cache_max_size

=for html <a name="item_code_cache_max_size"></a>

Specifies the maximum number of components that should be held in the
in-memory code cache. The default is 'unlimited', meaning no
components will ever be discarded; Mason can perform certain
optimizations in this mode. Setting this to zero disables the code
cache entirely. See the L<code cache|HTML::Mason::Admin/code cache>
section of the administrator's manual for further details.

=item comp_root

=for html <a name="item_comp_root"></a>

The component root marks the top of your component hierarchy and
defines how component paths are translated into real file paths. For
example, if your component root is F</usr/local/httpd/docs>, a component
path of F</products/index.html> translates to the file
F</usr/local/httpd/docs/products/index.html>.

Under L<Apache|HTML::Mason::ApacheHandler> and
L<CGI|HTML::Mason::CGIHandler>, comp_root defaults to the server's
document root. In standalone mode comp_root defaults to the current
working directory.

This parameter may be either a scalar or an array reference.  If it is
a scalar, it should be a filesystem path indicating the component
root. If it is an array reference, it should be of the following form:

 [ [ foo => '/usr/local/foo' ],
   [ bar => '/usr/local/bar' ] ]

This is an array of two-element array references, not a hash.  The
"keys" for each path must be unique and their "values" must be
filesystem paths.  These paths will be searched in the provided order
whenever a component path is resolved. For example, given the above
component roots and a component path of F</products/index.html>, Mason
would search first for F</usr/local/foo/products/index.html>, then for
F</usr/local/bar/products/index.html>.

The keys are used in several ways. They help to distinguish component
caches and object files between different component roots, and they
appear in the C<title()> of a component.

When you specify a single path for a component root, this is actually
translated into

  [ [ MAIN => path ] ]

If you have turned on L<dynamic_comp_root|HTML::Mason::Params/dynamic_comp_root>, you may modify the
component root(s) of an interpreter between requests by calling
C<$interp-E<gt>comp_root> with a value. However, the path associated
with any given key may not change between requests. For example,
if the initial component root is

 [ [ foo => '/usr/local/foo' ],
   [ bar => '/usr/local/bar' ], ]

then it may not be changed to

 [ [ foo => '/usr/local/bar' ],
   [ bar => '/usr/local/baz' ],

but it may be changed to

 [ [ foo   => '/usr/local/foo' ],
   [ blarg => '/usr/local/blarg' ] ]

In other words, you may add or remove key/path pairs but not modify an
already-used key/path pair. The reason for this restriction is that
the interpreter maintains a component cache per key that would become
invalid if the associated paths were to change.

=item compiler

The Compiler object to associate with this Interpreter.  By default a
new object of class L<compiler_class|HTML::Mason::Params/compiler_class> will be created.

=item compiler_class

The class to use when creating a compiler. Defaults to
L<HTML::Mason::Compiler|HTML::Mason::Compiler>.

=item data_dir

The data directory is a writable directory that Mason uses for various
features and optimizations: for example, component object files and
data cache files. Mason will create the directory on startup, if necessary, and set its
permissions according to the web server User/Group.

Under L<Apache|HTML::Mason::ApacheHandler>, data_dir defaults to a
directory called "mason" under the Apache server root. You will
need to change this on certain systems that assign a high-level
server root such as F</usr>!

In non-Apache environments, data_dir has no default. If it is left
unspecified, Mason will not use L<object files|HTML::Mason::Admin/object files>, and the default
L<data cache class|HTML::Mason::Request/item_cache> will be
C<MemoryCache> instead of C<FileCache>.

=item dynamic_comp_root

True or false, defaults to false. Indicates whether the L<comp_root|HTML::Mason::Params/comp_root>
can be modified on this interpreter between requests. Mason can
perform a few optimizations with a fixed component root, so you
should only set this to true if you actually need it.

=item escape_flags

A hash reference of escape flags to set for this object.  See the
section on the L<set_escape
method|HTML::Mason::Interp/item_set_escape> for more details.

=item ignore_warnings_expr

Regular expression indicating which warnings to ignore when loading
components. Any warning that is not ignored will prevent the
component from being loaded and executed. For example:

    ignore_warnings_expr =>
        'Global symbol.*requires explicit package'

If set to undef, all warnings are heeded. If set to '.', warnings
are turned off completely as a specially optimized case.

By default, this is set to 'Subroutine .* redefined'.  This allows you
to declare global subroutines inside <%once> sections and not receive
an error when the component is reloaded.

=item object_file_extension

Extension to add to the end of object files. Default is ".obj".

=item preloads

A list of component paths, optionally with glob wildcards, to load
when the interpreter initializes. e.g.

    preloads => ['/foo/index.html','/bar/*.pl']

Default is the empty list.  For maximum performance, this should only
be used for components that are frequently viewed and rarely updated.
See the L<preloading components|HTML::Mason::Admin/preloading components> section of the administrator's manual for further details.

As mentioned in the developer's manual, a component's C<< <%once> >>
section is executed when it is loaded.  For preloaded components, this
means that this section will be executed before a Mason or Apache
request exist, so preloading a component that uses C<$m> or C<$r> in a
C<< <%once> >> section will fail.

=item request_class

The class to use when creating requests. Defaults to
L<HTML::Mason::Request|HTML::Mason::Request>.

=item resolver

The Resolver object to associate with this Compiler. By default a new
object of class L<resolver_class|HTML::Mason::Params/resolver_class> will be created.

=item resolver_class

The class to use when creating a resolver. Defaults to
L<HTML::Mason::Resolver::File|HTML::Mason::Resolver::File>.

=item static_source

True or false, default is false. When false, Mason checks the
timestamp of the component source file each time the component is used
to see if it has changed. This provides the instant feedback for
source changes that is expected for development.  However it does
entail a file stat for each component executed.

When true, Mason assumes that the component source tree is unchanging:
it will not check component source files to determine if the memory
cache or object file has expired.  This can save many file stats per
request. However, in order to get Mason to recognize a component
source change, you must flush the memory cache and remove object files.
See L<static_source_touch_file|HTML::Mason::Params/static_source_touch_file> for one easy way to arrange this.

We recommend turning this mode on in your production sites if
possible, if performance is of any concern.

=item static_source_touch_file

Specifies a filename that Mason will check once at the beginning of
of every request. When the file timestamp changes, Mason will (1) clear
its in-memory component cache, and (2) remove object files if
they have not already been deleted by another process.

This provides a convenient way to implement L<static_source|HTML::Mason::Params/static_source> mode.
All you need to do is make sure that a single file gets touched
whenever components change. For Mason's part, checking a single
file at the beginning of a request is much cheaper than checking
every component file when static_source=0.

=item use_object_files

True or false, default is true.  Specifies whether Mason creates
object files to save the results of component parsing. You may want to
turn off object files for disk space reasons, but otherwise this
should be left alone.

=back

=head1 ACCESSOR METHODS

All of the above properties have standard accessor methods of the same
name. Only comp_root and ignore_warnings_expr can be modified in an
existing interpreter; the rest are read-only.

=head1 ESCAPE FLAG METHODS

=over

=item apply_escapes ($text, $flags, [more flags...])

=for html <a name="item_apply_escapes"></a>

This method applies a one or more escapes to a piece of text.  The
escapes are specified by giving their flag.  Each escape is applied to
the text in turn, after which the now-modified text is returned.

=item remove_escape ($name)

=for html <a name="item_remove_escape"></a>

Given an escape name, this removes that escape from the interpreter's
known escapes.  If the name is not recognized, it is simply ignored.

=item set_escape ($name => see below])

=for html <a name="item_set_escape"></a>

This method is called to add an escape flag to the list of known
escapes for the interpreter.  The flag may only consist of the
characters matching C<\w> and the dash (-).  It must start with an
alpha character or an underscore (_).

The right hand side may be one of several things.  It can be a
subroutine reference.  It can also be a string match C</^\w+$/>, in
which case it is assumed to be the name of a subroutine in the
C<HTML::Mason::Escapes> module.  Finally, if it is a string that does
not match the above regex, then it is assumed to be C<eval>able code,
which will return a subroutine reference.

When setting these with C<PerlSetVar> directives in an Apache
configuration file, you can set them like this:

  PerlSetVar  MasonEscapeFlags  "h => \&HTML::Mason::Escapes::basic_html_escape"
  PerlSetVar  MasonEscapeFlags  "flag  => \&subroutine"
  PerlSetVar  MasonEscapeFlags  "uc    => sub { ${$_[0]} = uc ${$_[0]}; }"
  PerlAddVar  MasonEscapeFlags  "thing => other_thing"

=back

=head1 OTHER METHODS

=over

=item comp_exists (path)

=for html <a name="item_comp_exists"></a>

Given an I<absolute> component path, this method returns a boolean
value indicating whether or not a component exists for that path.

=item exec (comp, args...)

=for html <a name="item_exec"></a>

Creates a new HTML::Mason::Request object for the given I<comp> and
I<args>, and executes it. The return value is the return value of
I<comp>, if any.

This is useful for running Mason outside of a web environment.
See L<HTML::Mason::Admin/using Mason from a standalone script>
for examples.

This method isn't generally useful in a mod_perl environment; see
L<subrequests|HTML::Mason::Devel/Subrequests> instead.

=item flush_code_cache

=for html <a name="flush_code_cache"></a>

Empties the component cache. When using Perl 5.00503 or earlier, you
should call this when finished with an interpreter, in order to remove
circular references that would prevent the interpreter from being
destroyed.

=item load (path)

=for html <a name="item_load"></a>

Returns the component object corresponding to an absolute component
C<path>, or undef if none exists. Dies with an error if the component
fails to load because of a syntax error.

=item make_component (comp_source => ... )

=item make_component (comp_file => ... )

=for html <a name="item_make_component"></a>

This method compiles Mason component source code and returns a
Component object.  The source may be passed in as a string in C<comp_source>,
or as a filename in C<comp_file>.  When using C<comp_file>, the
filename is specified as a path on the file system, not as a path
relative to Mason's component root (see
L<$m-E<gt>fetch_comp|HTML::Mason::Request/item_fetch_comp> for that).

If Mason encounters an error during processing, an exception will be thrown.

Example of usage:

    # Make an anonymous component
    my $anon_comp =
      eval { $interp->make_component
               ( comp_source => '<%perl>my $name = "World";</%perl>Hello <% $name %>!' ) };
    die $@ if $@;

    $m->comp($anon_comp);

=item make_request (@request_params)

=for html <a name="item_make_request"></a>

This method creates a Mason request object. The arguments to be passed
are the same as those for the C<< HTML::Mason::Request->new >>
constructor or its relevant subclass. This method will likely only be
of interest to those attempting to write new handlers or to subclass
C<HTML::Mason::Interp>.  If you want to create a I<subrequest>, see
L<subrequests|HTML::Mason::Devel/Subrequests> instead.

=item purge_code_cache ()

=for html <a name="purge_code_cache"></a>

Called during request execution in order to clear out the code
cache. Mainly useful to subclasses that may want to take some custom
action upon clearing the cache.

=item set_global ($varname, [values...])

=for html <a name="item_set_global"></a>

This method sets a global to be used in components. C<varname> is a
variable name, optionally preceded with a prefix (C<$>, C<@>, or
C<%>); if the prefix is omitted then C<$> is assumed. C<varname> is
followed by a value, in the case of a scalar, or by one or more values
in the case of a list or hash.  For example:

    # Set a global variable $dbh containing the database handle
    $interp->set_global(dbh => DBI->connect(...));

    # Set a global hash %session from a local hash
    $interp->set_global('%session', %s);

The global is set in the package that components run in: usually
C<HTML::Mason::Commands>, although this can be overridden via the
L<in_package|HTML::Mason::Params/in_package> parameter.
The lines above, for example, are equivalent to:

    $HTML::Mason::Commands::dbh = DBI->connect(...);
    %HTML::Mason::Commands::session = %s;

assuming that L<in_package|HTML::Mason::Params/in_package> has not been changed.

Any global that you set should also be registered with the
L<allow_globals|HTML::Mason::Params/allow_globals> parameter; otherwise you'll get warnings from
C<strict>.

=back

=head1 SEE ALSO

L<HTML::Mason|HTML::Mason>,
L<HTML::Mason::Admin|HTML::Mason::Admin>,
L<HTML::Mason::ApacheHandler|HTML::Mason::ApacheHandler>

=cut