text:
<?php

namespace {

from('Hoa')

/**
 * \Hoa\Compiler\Llk\Rule
 */
-> import('Compiler.Llk.Rule.~')

/**
 * \Hoa\File\Read
 */
-> import('File.Read')

/**
 * \Hoa\Compiler\Llk
 */
-> import('Compiler.Llk.~');

}

namespace Hoa\Compiler\Llk\Rule {

/**
 * Class \Hoa\Compiler\Llk\Rule\Token.
 *
 * The token rule.
 *
 * @author     Frédéric Dadeau <frederic.dadeau@femto-st.fr>
 * @author     Ivan Enderlin <ivan.enderlin@hoa-project.net>
 * @copyright  Copyright © 2007-2014 Frédéric Dadeau, Ivan Enderlin.
 * @license    New BSD License
 */

class Token extends Rule {

    /**
     * LL(k) compiler of hoa://Library/Regex/Grammar.pp
     *
     * @var \Hoa\Compiler\Llk object
     */
    protected static $_regexCompiler = null;

    /**
     * Token name.
     *
     * @var \Hoa\Compiler\Llk\Rule\Token string
     */
    protected $_tokenName            = null;

    /**
     * Namespace.
     *
     * @var \Hoa\Compiler\Llk\Rule\Token string
     */
    protected $_namespace            = null;

    /**
     * Token representation.
     *
     * @var \Hoa\Compiler\Llk\Rule\Token string
     */
    protected $_regex                = null;

    /**
     * AST of the regex.
     *
     * @var \Hoa\Compiler\Llk\TreeNode object
     */
    protected $_ast                  = null;

    /**
     * Token value.
     *
     * @var \Hoa\Compiler\Llk\Rule\Token string
     */
    protected $_value                = null;

    /**
     * Whether the token is kept or not in the AST.
     *
     * @var \Hoa\Compiler\Llk\Rule\Token bool
     */
    protected $_kept                 = false;

    /**
     * Unification index.
     *
     * @var \Hoa\Compiler\Llk\Rule\Token int
     */
    protected $_unification          = -1;

    /**
     * Constructor.
     *
     * @access  public
     * @param   string  $name           Name.
     * @param   string  $tokenName      Token name.
     * @param   string  $nodeId         Node ID.
     * @param   int     $unification    Unification index.
     * @return  void
     */
    public function __construct ( $name, $tokenName, $nodeId, $unification ) {

        parent::__construct($name, null, $nodeId);
        $this->_tokenName   = $tokenName;
        $this->_unification = $unification;

        return;
    }

    /**
     * Get token name.
     *
     * @access  public
     * @return  string
     */
    public function getTokenName ( ) {

        return $this->_tokenName;
    }

    /**
     * Set token namespace.
     *
     * @access  public
     * @param   string  $namespace    Namespace.
     * @return  string
     */
    public function setNamespace ( $namespace ) {

        $old              = $this->_namespace;
        $this->_namespace = $namespace;

        return $old;
    }

    /**
     * Get token namespace.
     *
     * @access  public
     * @return  string
     */
    public function getNamespace ( ) {

        return $this->_namespace;
    }

    /**
     * Set representation.
     *
     * @access  public
     * @param   string  $regex    Representation.
     * @return  string
     */
    public function setRepresentation ( $regex ) {

        $old          = $this->_regex;
        $this->_regex = $regex;

        return $old;
    }

    /**
     * Get token representation.
     *
     * @access  public
     * @return  string
     */
    public function getRepresentation ( ) {

        return $this->_regex;
    }

    /**
     * Get AST of the token representation.
     *
     * @access  public
     * @return  \Hoa\Compiler\Llk\TreeNode
     */
    public function getAST ( ) {

        if(null === static::$_regexCompiler) {

            $stream = new \Hoa\File\Read('hoa://Library/Regex/Grammar.pp');
            $stream->rewind();

            static::$_regexCompiler = \Hoa\Compiler\Llk::load($stream);
        }

        if(null === $this->_ast)
            $this->_ast = static::$_regexCompiler->parse(
                $this->getRepresentation()
            );

        return $this->_ast;
    }

    /**
     * Set token value.
     *
     * @access  public
     * @param   string  $value    Value.
     * @return  string
     */
    public function setValue ( $value ) {

        $old          = $this->_value;
        $this->_value = $value;

        return $old;
    }

    /**
     * Get token value.
     *
     * @access  public
     * @return  string
     */
    public function getValue ( ) {

        return $this->_value;
    }

    /**
     * Set whether the token is kept or not in the AST.
     *
     * @access  public
     * @param   bool  $kept    Kept.
     * @return  bool
     */
    public function setKept ( $kept ) {

        $old         = $this->_kept;
        $this->_kept = $kept;

        return $old;
    }

    /**
     * Check whether the token is kept in the AST or not.
     *
     * @access  public
     * @return  bool
     */
    public function isKept ( ) {

        return $this->_kept;
    }

    /**
     * Get unification index.
     *
     * @access  public
     * @return  int
     */
    public function getUnificationIndex ( ) {

        return $this->_unification;
    }
}

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WebStuff.Services
{
    public class UsefulStuff
    {

    #region URL Manipulation
        /// <summary>
        /// Extracts the scheme + host information from a URL (i.e. http(s)://www.domain.name)
        /// </summary>
        /// <param name="p_strUrl">The URL to be broken up as a URL - needs to be absolute</param>
        /// <returns>The scheme and host name as a string</returns>
        public static string GrabHostAndScheme(string p_strUrl) {
            try
            {
                Uri uriReturnUri = new Uri(p_strUrl, UriKind.Absolute);
                return uriReturnUri.Scheme + "://" + uriReturnUri.Host;
            }
            catch (Exception) { return ""; }
        }

        /// <summary>
        /// Checks a URL and creates a well-formed, absolute URL adding the scheme and host if necessary
        /// </summary>
        /// <param name="p_strUrl">The URL to be checked</param>
        /// <param name="p_strDomain">The host and scheme information to be added if necessary</param>
        /// <returns>The well-formed URL as a string, the original URL if no modifications or empty string if it's not useable.</returns>
        public static string CreateWellFormedUrl(string p_strUrl, string p_strDomain, bool p_blnRemoveDifferingDomain = false) {

            //  In case nothing needs to be changed, return the original URL
            string strToReturn = p_strUrl;

            //  Append http if URL is absolute and doesn't have it already.
            if (!Uri.IsWellFormedUriString(p_strUrl, UriKind.Absolute))
            {
                if (Uri.IsWellFormedUriString(p_strUrl, UriKind.Relative))   //  Append host if URL is relative
                {
                    //  Check for exceptions:
                    //    * javascript function
                    //    * email, tel
                    //    * #
                    if (p_strUrl.StartsWith("javascript:")
                        || p_strUrl.StartsWith("mailto:")
                        || p_strUrl.StartsWith("tel:")
                        || p_strUrl.StartsWith("#"))
                        strToReturn = "";
                    else
                        strToReturn = CombineDomainAndPath(p_strDomain, p_strUrl);
                } else { strToReturn = ""; }

            }
            else  //  The URL appears to be absolute, but might not have a scheme prefixed to it
            {
                // Exception:
                //    * differing domain
                if (p_blnRemoveDifferingDomain)
                {
                    Uri uriNewDomain = new Uri(p_strUrl, UriKind.Absolute);
                    Uri uriIncomingDomain = new Uri(p_strDomain, UriKind.Absolute);
                    if (uriNewDomain.Host == uriIncomingDomain.Host)
                    {
                        strToReturn = "";
                    }
                }

                //  Prefix scheme if needed
                string strScheme = new Uri(p_strDomain, UriKind.Absolute).Scheme;
                if (!p_strUrl.StartsWith("http"))
                {
                    strToReturn = strScheme + "://" + p_strUrl;
                }
                else { strToReturn = p_strUrl; }    //  Return the URL as is since it's fully qualified
            }

            //  If all else fails, return with an empty string, otherwise with the well-formed string
            return strToReturn;

        }

        /// <summary>
        /// Combines a domain and path safely (taking duplicate slashes into consideration)
        /// </summary>
        /// <param name="p_strDomain">The domain to attach the path to</param>
        /// <param name="p_strUrl">The absolute path (either with slash at the beginning or without) that gets joined in</param>
        /// <returns></returns>
        public static string CombineDomainAndPath(string p_strDomain, string p_strUrl)
        {
            //  Check if the absolute path already contains the domain
            if (p_strUrl.StartsWith("http://") || p_strUrl.StartsWith("https://"))
                return p_strUrl;
            else if (p_strUrl.StartsWith(p_strDomain))
                return p_strDomain;
            else if (p_strUrl.StartsWith("http://" + p_strDomain))
                return "http://" + p_strUrl;
            else if (p_strUrl.StartsWith("https://" + p_strDomain))
                return "https://" + p_strUrl;

            if (!p_strDomain.Contains("://"))
                p_strDomain = "http://" + p_strDomain;

            //  Check leading and trailing slashes and combine the domain with path
            p_strDomain = (p_strDomain.EndsWith("/") && p_strUrl.StartsWith("/") ? p_strDomain.Substring(0, p_strDomain.Length - 1) : p_strDomain);
            return p_strDomain + (p_strDomain.EndsWith("/") || p_strUrl.StartsWith("/") ? "" : "/") + p_strUrl;
        }
        #endregion

    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Pandora\SyliusFilterBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class PandoraSyliusFilterBundle extends Bundle
{
}


text:
<?php

declare(strict_types=1);

namespace DiContainerBenchmarks\Fixture\C;

class FixtureC528
{
    public function __construct(FixtureC527 $dependency)
    {
    }
}


text:
from vgengine import game

import unittest

class RoomTest(unittest.TestCase):
	def setUp(self):
		self.room = game.Room()
		self.scene = game.Scene()
		self.scene.add(self.room)
		self.game_object = game.GameObject()
		self.game_object2 = game.GameObject()

	def test_add_game_object(self):
		self.room._add_game_object(self.game_object)
		self.assertTrue(self.game_object in self.room.game_objects)

	def test_remove_game_object(self):
		self.room._add_game_object(self.game_object)
		self.room._remove_game_object(self.game_object)
		self.assertFalse(self.game_object in self.room.game_objects)

	def test_add(self):
		self.room.add(self.game_object, self.game_object2)
		self.assertTrue(self.game_object in self.room.game_objects)
		self.assertTrue(self.game_object2 in self.room.game_objects)

	def test_remove(self):
		self.room.add(self.game_object, self.game_object2)
		self.room.remove(self.game_object, self.game_object2)
		self.assertFalse(self.game_object in self.room.game_objects)
		self.assertFalse(self.game_object2 in self.room.game_objects)

if __name__ == '__main__':
	unittest.main()


text:
<?php

namespace app\packages\blog;

use yii\filters\AccessControl;

class Module extends \app\classes\Module
{
    public $controllerNamespace = 'app\packages\blog\controllers';

    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
//                    [
//                        'controllers' => ['account/backend/auth'],
//                        'allow' => true,
//                    ],
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }

    public function init()
    {
        parent::init();
        \Yii::$app->formatter->nullDisplay = '';
    }

    public function getModulePermissions()
    {
        return require(__DIR__ . '/permissions.php');
    }

	public function getDIYWidgets()
	{
		return require (__DIR__ . '/diywidgets.php');
	}
}


text:
require "nail_polish/engine"

require "hogan_assets"
require "compass-rails"

module NailPolish
end


text:
from kaira.app import App
from kaira.response import response
from kaira.wrapper import ContextManager
from kaira.log import log

app = App()

class ContextHandler(ContextManager):
    def __init__(self, name="default"):
        self.name = name

    def on_start(self, request):
        log.info("On start: '%s'" % self.name)

    def on_success(self, request):
        log.info("On success: '%s'" % self.name)

    def on_failure(self, request):
        log.info("On fail: '%s'" % self.name)

context_1 = ContextHandler('context 1')
context_2 = ContextHandler('context 2')

@app.route("/", context=[context_1, context_2])
def hello_world(request):
    return response.text('Hello World!')

if __name__ == '__main__':
    app.run(debug=True, host="0.0.0.0", port=8000)


text:
using System;
using System.Reflection;

namespace Gallio.Model
{
    /// <summary>
    /// Provides common metadata keys.
    /// </summary>
    public static class MetadataKeys
    {
        /// <summary>
        /// The metadata key for the author's email.
        /// </summary>
        /// <remarks>
        /// <para>
        /// May be derived from <c>AuthorAttribute</c> in MbUnit or its equivalent.
        /// </para>
        /// </remarks>
        public const string AuthorEmail = "AuthorEmail";

        /// <summary>
        /// The metadata key for the author's name.
        /// </summary>
        /// <remarks>
        /// <para>
        /// May be derived from <c>AuthorAttribute</c> in MbUnit or its equivalent.
        /// </para>
        /// </remarks>
        public const string AuthorName = "AuthorName";

        /// <summary>
        /// The metadata key for the author's homepage.
        /// </summary>
        /// <remarks>
        /// <para>
        /// May be derived from <c>AuthorAttribute</c> in MbUnit or its equivalent.
        /// </para>
        /// </remarks>
        public const string AuthorHomepage = "AuthorHomepage";

        /// <summary>
        /// The metadata key for the name of a category to which a test belongs.
        /// </summary>
        /// <remarks>
        /// <para>
        /// May be derived from <c>CategoryAttribute</c> in MbUnit or its equivalent.
        /// </para>
        /// </remarks>
        public const string Category = "Category";

        /// <summary>
        /// The matadata key for the location of an assembly as a local
        /// file path or as a Uri.
        /// </summary>
        /// <remarks>
        /// <para>
        /// May be derived from the assembly's <see cref="Assembly.CodeBase" /> property.
        /// </para>
        /// </remarks>
        public const string CodeBase = "CodeBase";

        /// <summary>
        /// The metadata key for the name of the company associated with a test.
        /// </summary>
        /// <remarks>
        /// <para>
        /// May be derived from <see cref="AssemblyCompanyAttribute" />.
        /// </para>
        /// </remarks>
        public const string Company = "Company";

        /// <summary>
        /// The metadata key for build/release configuration information associated with a test.
        /// </summary>
        /// <remarks>
        /// <para>
        /// It describes the target environment or usage for the test.
        /// </para>
        /// <para>
        /// May be derived from <see cref="AssemblyConfigurationAttribute" />.
        /// </para>
        /// </remarks>
        public const string Configuration = "Configuration";

        /// <summary>
        /// The metadata key for a copyright associated with a test.
        /// </summary>
        /// <remarks>
        /// <para>
        /// May be derived from <see cref="AssemblyCopyrightAttribute" />.
        /// </para>
        /// </remarks>
        public const string Copyright = "Copyright";

        /// <summary>
        /// The metadata key for specifying the origin of data used by a test.
        /// </summary>
        /// <remarks>
        /// <para>
        /// May be the file name and line number of a record in a file, the ID
        /// of a database record or some other identifying characteristic.
        /// </para>
        /// </remarks>
        public const string DataLocation = "DataLocation";

        /// <summary>
        /// The metadata key for the description of a test component.
        /// </summary>
        /// <remarks>
        /// <para>
        /// May be derived from <see cref="AssemblyDescriptionAttribute" />
        /// or <c>DescriptionAttribute</c> in MbUnit or its equivalent.
        /// </para>
        /// </remarks>
        public const string Description = "Description";

        /// <summary>
        /// The metadata key for the expected exception type which should be the name,
        /// full name or assembly-qualified name of the expected exception type.
        /// </summary>
        /// <remarks>
        /// <para>
        /// May be derived from <c>ExpectedExceptionAttribute</c> in MbUnit
        /// or its equivalent.
        /// </para>
        /// </remarks>
        public const string ExpectedException = "ExpectedException";

        /// <summary>
        /// The metadata key for the expected inner exception type which should be the name,
        /// full name or assembly-qualified name of the expected inner exception type.
        /// </summary>
        /// <remarks>
        /// <para>
        /// May be derived from <c>ExpectedExceptionAttribute</c> in MbUnit
        /// or its equivalent.
        /// </para>
        /// </remarks>
        public const string ExpectedInnerException = "ExpectedInnerException";

        /// <summary>
        /// The metadata key for the expected exception message.
        /// May be a substring of the actual exception message.
        /// </summary>
        /// <remarks>
        /// <para>
        /// May be derived from <c>ExpectedExceptionAttribute</c> in MbUnit
        /// or its equivalent.
        /// </para>
        /// </remarks>
        public const string ExpectedExceptionMessage = "ExpectedExceptionMessage";

        /// <summary>
        /// The metadata key that describes the reason that a test should be run explicitly.
        /// </summary>
        /// <remarks>
        /// <para>
        /// Tests may of course be marked explicit without a declared reason.
        /// </para>
        /// <para>
        /// May be derived from <c>ExplicitAttribute</c> in MbUnit or its equivalent.
        /// </para>
        /// </remarks>
        public const string ExplicitReason = "ExplicitReason";

        /// <summary>
        /// The metadata key for a file associated with a test.
        /// </summary>
        /// <remarks>
        /// <para>
        /// The file key should be associated with the top test produced by a file that
        /// the test framework was asked to explore.  For example, if the test package
        /// included "C:\Tests\MyTests.dll" then the assembly-level test emitted by the framework
        /// should have a File metadata entry with the value "C:\Tests\MyTests.dll".
        /// </para>
        /// </remarks>
        public const string File = "File";

        /// <summary>
        /// The metadata key for a file version number associated with a test.
        /// </summary>
        /// <remarks>
        /// <para>
        /// May be derived from <see cref="AssemblyFileVersionAttribute" />.
        /// </para>
        /// </remarks>
        public const string FileVersion = "FileVersion";

        /// <summary>
        /// The metadata key for the test framework name associated with a test assembly in the test tree.
        /// </summary>
        /// <remarks>
        /// <para>
        /// The value should be the descriptive name of the framework including its version.  eg. "MbUnit v3.1 build 200"
        /// </para>
        /// <para>
        /// A single assembly may have multiple associated frameworks.
        /// </para>
        /// </remarks>
        public const string Framework = "Framework";

        /// <summary>
        /// The metadata key that describes the reason that a test is being ignored.
        /// </summary>
        /// <remarks>
        /// <para>
        /// Tests may of course be ignored without a declared reason.
        /// </para>
        /// <para>
        /// May be derived from <c>IgnoreAttribute</c> in MbUnit or its equivalent.
        /// </para>
        /// </remarks>
        public const string IgnoreReason = "IgnoreReason";

        /// <summary>
        /// The metadata key for the importance of a test component as the
        /// string representation of one of the <c>TestImportance</c> constants in MbUnit
        /// or its equivalent.
        /// </summary>
        /// <remarks>
        /// <para>
        /// May be derived from <c>ImportantAttribute</c> in MbUnit or its equivalent.
        /// </para>
        /// </remarks>
        public const string Importance = "Importance";

        /// <summary>
        /// The metadata key for an informational version number associated with a test.
        /// </summary>
        /// <remarks>
        /// <para>
        /// May be derived from <see cref="AssemblyInformationalVersionAttribute" />.
        /// </para>
        /// </remarks>
        public const string InformationalVersion = "InformationalVersion";

        /// <summary>
        /// The metadata key that describes the reason that a test is pending.
        /// </summary>
        /// <remarks>
        /// <para>
        /// Tests may of course be marked pending without a declared reason.
        /// </para>
        /// <para>
        /// May be derived from <c>PendingAttribute</c> in MbUnit or its equivalent.
        /// </para>
        /// </remarks>
        public const string PendingReason = "PendingReason";

        /// <summary>
        /// The metadata key for a product associated with a test.
        /// </summary>
        /// <remarks>
        /// <para>
        /// May be derived from <see cref="AssemblyProductAttribute" />.
        /// </para>
        /// </remarks>
        public const string Product = "Product";

        /// <summary>
        /// The metadata key for the name of the type being tested.
        /// </summary>
        /// <remarks>
        /// <para>
        /// The associated value should be the full name of the type from <see cref="Type.FullName" />
        /// or the assembly qualified name of the type from <see cref="Type.AssemblyQualifiedName" />.
        /// </para>
        /// <para>
        /// May be derived from <c>TestsOnAttribute</c> in MbUnit or its equivalent.
        /// </para>
        /// </remarks>
        public const string TestsOn = "TestsOn";

        /// <summary>
        /// The metadata key used to describe the kind of a test as the
        /// string representation of one of the <see cref="TestKinds" /> constants.
        /// </summary>
        public const string TestKind = "TestKind";

        /// <summary>
        /// The metadata key for a title associated with a test.
        /// </summary>
        /// <remarks>
        /// <para>
        /// May be derived from <see cref="AssemblyTitleAttribute" />.
        /// </para>
        /// </remarks>
        public const string Title = "Title";

        /// <summary>
        /// The metadata key for a trademark associated with a test.
        /// </summary>
        /// <remarks>
        /// <para>
        /// May be derived from <see cref="AssemblyTrademarkAttribute" />.
        /// </para>
        /// </remarks>
        public const string Trademark = "Trademark";

        /// <summary>
        /// The metadata key for a version number associated with a test.
        /// </summary>
        /// <remarks>
        /// <para>
        /// May be derived from <see cref="AssemblyVersionAttribute" />.
        /// </para>
        /// </remarks>
        public const string Version = "Version";

        /// <summary>
        /// The metadata key for the XML documentation of the test derived from
        /// XML code documentation comments.
        /// </summary>
        public const string XmlDocumentation = "XmlDocumentation";
    }
}


text:
var Tools = require('/app/Tools');

module.exports = function(){
	var btClose = Ti.UI.createButton({
		backgroundImage:'/images/common/bt_help.png',
		width:Tools.pixelToDp(39),
		height:Tools.pixelToDp(31),
	});
	var win = Ti.UI.createWindow({
		barColor:'#2a3d5d',
		barImage:'/images/common/bg_header.png',
		backgroundImage:'/images/common/bg.png',
		title:L('win_history'),
		rightNavButton:btClose,
		modal:true,
	});

	btClose.addEventListener('click', function(){
		win.close();
	});

	return win;
};


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

	 <!--
		This package contains the non-secure portions of the Struts 2 Portfolio.  This allows these
		public actions to share inheritance of things specialized to the non-secure portions of the application.
	 -->

    <package name="chapterTenPublic" namespace="/chapterTen" extends="struts-default">

 		<global-results>
  		  <result name="error">/chapterTen/Error.jsp</result>
  	</global-results>

    <global-exception-mappings>
       <exception-mapping exception="java.lang.Exception" result="error"/>
    </global-exception-mappings>

		<action name="PortfolioHomePage" class="manning.chapterTen.PortfolioHomePage">
       <result>/chapterTen/PortfolioHomePage.jsp</result>
		</action>

		<action name="ArtistHomePage" class="manning.chapterTen.PortfolioHomePage">
       <result>/chapterTen/ArtistHomePage.jsp</result>
		</action>

		<action name="VisitorHomePage" class="manning.chapterTen.PortfolioHomePage">
       <result>/chapterTen/VisitorHomePage.jsp</result>
		</action>

    <action name="ViewPortfolioJSP" class="manning.chapterTen.ViewPortfolio" >
			<result>/chapterTen/ViewPortfolio.jsp</result>
    </action>

 		<action name="LoginForm" >
			<result>/chapterTen/Login.jsp</result>
    </action>

		<action name="Login" class="manning.chapterTen.Login">
			<result type="redirectAction">
			   <param name="actionName">AdminPortfolio</param>
         <param name="namespace">/chapterTen/secure</param>
      </result>
			<result name="input">/chapterTen/Login.jsp</result>
    </action>

   <action name="Registration" >
      <result>/chapterTen/Registration.jsp</result>
   </action>

   <action name="Register" class="manning.chapterTen.Register">
      <result>/chapterTen/RegistrationSuccess.jsp</result>
      <result name="input">/chapterTen/Registration.jsp</result>
   </action>

</package>

		 <!--
		 			This package contains the secure portions of the Struts 2 Portfolio.  This allows these
		 			secure actions to share inheritance of things specialized to the secure portions of the application.
		 -->
		 <package name="chapterTenSecure" namespace="/chapterTen/secure" extends="struts-default">

				<!-- We need to define the authentication interceptor and configure a new stack, based upon the
							builtin default stack.  We will simply add our authentication stack to the top of the default
							stack and make it the default intercptor reference for the actions in this package.
				-->
				<interceptors>

					<interceptor name="authenticationInterceptor" class="manning.utils.AuthenticationInterceptor"/>

					<interceptor-stack name="secureStack">
						<interceptor-ref name="authenticationInterceptor"/>
						<interceptor-ref name="defaultStack"/>
					</interceptor-stack>

			</interceptors>

				<default-interceptor-ref name="secureStack"/>

				<global-results>
  				<result name="login" type="redirect">/chapterTen/LoginForm.action</result>
  			  <result name="error">/chapterTen/Error.jsp</result>
  			</global-results>

        <global-exception-mappings>
            <exception-mapping exception="java.lang.Exception" result="error"/>
        </global-exception-mappings>

      	<action name="AdminPortfolio" class="manning.chapterTen.UpdateAccountForm">
			     <result>/chapterTen/AdminPortfolio.jsp</result>
		    </action>

		    <action name="CreatePortfolioForm">
			     <result>/chapterTen/CreatePortfolio.jsp</result>
		    </action>

		    <action name="CreatePortfolio" class="manning.chapterNine.CreatePortfolio">
		       <result name="input">/chapterTen/CreatePortfolio.jsp</result>
			     <result>/chapterTen/PortfolioAdded.jsp</result>
		    </action>

		    <action name="UpdatePortfolio" class="manning.chapterTen.UpdatePortfolio">
			      <result>/chapterNine/UpdatePortfolioSuccess.jsp</result>
			      <interceptor-ref name="paramsPrepareParamsStack"/>
		    </action>

	   	 <action name="EditPortfolio" class="manning.chapterTen.EditPortfolio">
			   <result>/chapterNine/EditPortfolio.jsp</result>
		   </action>

        <action name="UpdateAccountForm" class="manning.chapterTen.UpdateAccountForm">
			<result>/chapterTen/UpdateAccountForm.jsp</result>
        </action>

        <action name="UpdateAccount" class="manning.chapterTen.UpdateAccount">
			<result>/chapterTen/UpdateAccountSuccess.jsp</result>
			<result name="input">/chapterTen/UpdateAccountForm.jsp</result>
        </action>

      <action name="AddImage" >
          <result>/chapterTen/ImageUploadForm.jsp</result>
        </action>

        <action name="ImageUpload" class="manning.chapterTen.ImageUpload" >
        	<result>/chapterTen/ImageAdded.jsp</result>
					<result name="input">/chapterTen/ImageUploadForm.jsp</result>
        </action>

     </package>

</struts>


text:
package com.example.repository;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import com.example.entity.Company;
import com.example.vo.SearchCompany;

public interface CompanyRepositoryCustom {

	Page<Company> search(SearchCompany searchCompany, Pageable pageable);
}


text:
NES, NeoGeo emulator based on LLVM

6502, M68k/Z80 emulation via dynamic translation


text:
<?xml version="1.0" encoding="UTF-8"?>

<recipeml version="0.5">
  <recipe>
    <head>
      <title>Baked Ziti</title>
      <categories>
        <cat>None</cat></categories>
      <yield>1</yield></head>
    <ingredients>
      <ing>
        <amt>
          <qty>1/2</qty>
          <unit>pounds</unit></amt>
        <item>Hamburger</item></ing>
      <ing>
        <amt>
          <qty>1/2</qty>
          <unit>pounds</unit></amt>
        <item>Sausage</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit/></amt>
        <item>Jar Prego Spaghetti Sauce</item></ing>
      <ing>
        <amt>
          <qty/>
          <unit/></amt>
        <item>Ziti Noodles or any other big noodles</item></ing>
      <ing>
        <amt>
          <qty/>
          <unit/></amt>
        <item>Mozarella cheese</item></ing>
      <ing>
        <amt>
          <qty/>
          <unit/></amt>
        <item>Other cheeses as desired</item></ing></ingredients>
    <directions>
      <step>  Mix hamburger and sausage together and make into balls and cook until done
  and brown. Mix in prego sauce. Cook noodles according to package. Layer
  noodles in bottom of casserole dish. Then spoon on sauce/meat mixture. Then
  a layer of cheese(s). Continue to layer items until dish is full or you use
  all the sauce and noodles. Bake in preheated oven at 325 degrees for 25-35
  minutes until cheese is melted and golden. Posted to EAT-L Digest by
  "Winona Y. Wentworth" <wyw@ATOMIC.NET> on Sep 2, 1997

</step></directions></recipe></recipeml>


text:
package org.ohdsi.webapi.shiro.filters.auth;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.util.WebUtils;
import org.ohdsi.webapi.helper.Guard;
import org.ohdsi.webapi.shiro.filters.AtlasAuthFilter;
import org.ohdsi.webapi.shiro.tokens.JwtAuthToken;
import org.pac4j.core.context.JEEContext;
import org.pac4j.saml.client.SAML2Client;
import org.pac4j.saml.credentials.SAML2Credentials;
import org.pac4j.saml.exceptions.SAMLAuthnInstantException;
import org.pac4j.saml.profile.SAML2Profile;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

import static org.ohdsi.webapi.shiro.management.AtlasSecurity.AUTH_CLIENT_ATTRIBUTE;
import static org.ohdsi.webapi.shiro.management.AtlasSecurity.AUTH_CLIENT_SAML;

/**
 * SAML authentication callback filter
 */
public class SamlHandleFilter extends AtlasAuthFilter {
    private final SAML2Client saml2Client;
    private final SAML2Client saml2ForceClient;
    protected final String oauthUiCallback;
    private final static String AUTH_COOKIE = "forceAuth";

    public SamlHandleFilter(SAML2Client saml2Client, SAML2Client saml2ForceClient, String oauthUiCallback) {
        this.saml2Client = saml2Client;
        this.saml2ForceClient = saml2ForceClient;
        this.oauthUiCallback = oauthUiCallback;
    }

    /**
     * @see org.apache.shiro.web.filter.authc.AuthenticatingFilter#createToken(ServletRequest,
     *      ServletResponse)
     */
    @Override
    protected AuthenticationToken createToken(ServletRequest servletRequest,
                                              ServletResponse servletResponse) throws Exception {
        final ShiroHttpServletRequest request = (ShiroHttpServletRequest) servletRequest;
        AuthenticationToken token = null;
        if (request.getSession() != null) {
            if (!SecurityUtils.getSubject().isAuthenticated()) {
                request.setAttribute(AUTH_CLIENT_ATTRIBUTE, AUTH_CLIENT_SAML);

                HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
                HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
                JEEContext context = new JEEContext(httpRequest, httpResponse);

                SAML2Client client;
                if (isForceAuth(request)) {
                    client = saml2ForceClient;
                } else {
                    client = saml2Client;
                }
                SAML2Credentials credentials = client.getCredentials(context).get();
                SAML2Profile samlProfile = (SAML2Profile)client.getUserProfile(credentials, context).get();

                token = new JwtAuthToken(samlProfile.getId());
            }
        }
        return token;
    }

    /**
     * @see org.apache.shiro.web.filter.AccessControlFilter#onAccessDenied(ServletRequest,
     *      ServletResponse)
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        try {
            boolean loggedIn = executeLogin(request, response);

            return loggedIn;
        } catch (SAMLAuthnInstantException e) {
            if (!isForceAuth(request)) {
                createForceAuthCookie(response);

                WebUtils.toHttp(response).sendRedirect(WebUtils.toHttp(request).getContextPath() + "/user/login/samlForce");
            } else {
                deleteForceAuthCookie(response);

                String urlValue = oauthUiCallback.replaceAll("/+$", "");
                urlValue = urlValue + "/" + AUTH_CLIENT_SAML + "/reloginRequired";
                WebUtils.toHttp(response).sendRedirect(urlValue);
            }
        }
        return false;
    }

    private boolean isForceAuth(ServletRequest request) {
        Cookie[] cookies = WebUtils.toHttp(request).getCookies();
        if (Objects.nonNull(cookies)) {
            for (Cookie cookie: cookies) {
                if (AUTH_COOKIE.equals(cookie.getName())) {
                    return Boolean.TRUE.toString().equals(cookie.getValue());
                }
            }
        }
        return false;
    }

    private void createForceAuthCookie(ServletResponse response) {
        Cookie cookie = new Cookie(AUTH_COOKIE, Boolean.TRUE.toString());
        cookie.setPath("/");
        WebUtils.toHttp(response).addCookie(cookie);
    }

    private void deleteForceAuthCookie(ServletResponse response) {
        Cookie cookie = new Cookie(AUTH_COOKIE, Boolean.TRUE.toString());
        cookie.setMaxAge(0);
        cookie.setPath("/");
        WebUtils.toHttp(response).addCookie(cookie);
    }
}


text:
package org.gradoop.flink.model.impl.operators.matching.single.cypher.planning.queryplan.unary;

import com.google.common.collect.Sets;
import org.apache.flink.api.java.DataSet;
import org.gradoop.common.model.impl.id.GradoopId;
import org.gradoop.common.model.impl.properties.PropertyValue;
import org.gradoop.flink.model.GradoopFlinkTestBase;
import org.gradoop.flink.model.impl.operators.matching.common.query.QueryHandler;
import org.gradoop.flink.model.impl.operators.matching.common.query.predicates.CNF;
import org.gradoop.flink.model.impl.operators.matching.single.cypher.pojos.Embedding;
import org.gradoop.flink.model.impl.operators.matching.single.cypher.pojos.EmbeddingMetaData;
import org.gradoop.flink.model.impl.operators.matching.single.cypher.pojos.EmbeddingMetaData.EntryType;
import org.gradoop.flink.model.impl.operators.matching.single.cypher.planning.queryplan.MockPlanNode;
import org.gradoop.flink.model.impl.operators.matching.single.cypher.planning.queryplan.PlanNode;
import org.junit.Test;

import java.util.List;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

public class FilterEmbeddingsNodeTest extends GradoopFlinkTestBase {

  @Test
  public void testMetaDataInitialization() throws Exception {
    EmbeddingMetaData mockMeta = new EmbeddingMetaData();
    mockMeta.setEntryColumn("a", EntryType.VERTEX, 0);
    mockMeta.setPropertyColumn("a", "age", 0);
    PlanNode mockNode = new MockPlanNode(null, mockMeta);

    FilterEmbeddingsNode node = new FilterEmbeddingsNode(mockNode, new CNF());

    assertTrue(mockNode.getEmbeddingMetaData().equals(node.getEmbeddingMetaData()));
  }

  @Test
  public void testExecute() throws Exception {
    String query = "MATCH (a)-->(b) WHERE a.age > b.age";
    QueryHandler queryHandler = new QueryHandler(query);
    CNF filterPredicate = queryHandler.getPredicates().getSubCNF(Sets.newHashSet("a", "b"));

    GradoopId vertexAId = GradoopId.get();
    GradoopId vertexBId = GradoopId.get();
    GradoopId vertexCId = GradoopId.get();

    EmbeddingMetaData metaData = new EmbeddingMetaData();
    metaData.setEntryColumn("a", EntryType.VERTEX, 0);
    metaData.setEntryColumn("b", EntryType.VERTEX, 1);
    metaData.setPropertyColumn("a", "age", 0);
    metaData.setPropertyColumn("b", "age", 1);

    Embedding embedding1 = new Embedding();
    embedding1.add(vertexAId, PropertyValue.create(42));
    embedding1.add(vertexBId, PropertyValue.create(23));

    Embedding embedding2 = new Embedding();
    embedding2.add(vertexAId, PropertyValue.create(42));
    embedding2.add(vertexCId, PropertyValue.create(84));

    DataSet<Embedding> input = getExecutionEnvironment().fromElements(embedding1, embedding2);
    PlanNode mockChild = new MockPlanNode(input, metaData);

    List<Embedding> result = new FilterEmbeddingsNode(mockChild, filterPredicate).execute().collect();

    assertThat(result.size(), is(1));
    assertTrue(result.get(0).getId(0).equals(vertexAId));
    assertTrue(result.get(0).getId(1).equals(vertexBId));
    assertTrue(result.get(0).getProperty(0).equals(PropertyValue.create(42)));
    assertTrue(result.get(0).getProperty(1).equals(PropertyValue.create(23)));
  }
}


text:
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2012-2013 DreamWorks Animation LLC
//
// All rights reserved. This software is distributed under the
// Mozilla Public License 2.0 ( http://www.mozilla.org/MPL/2.0/ )
//
// Redistributions of source code must retain the above copyright
// and license notice and the following restrictions and disclaimer.
//
// *     Neither the name of DreamWorks Animation nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// IN NO EVENT SHALL THE COPYRIGHT HOLDERS' AND CONTRIBUTORS' AGGREGATE
// LIABILITY FOR ALL CLAIMS REGARDLESS OF THEIR BASIS EXCEED US$250.00.
//
///////////////////////////////////////////////////////////////////////////
//
/// @file Statistics.h
///
/// @brief Functions to efficiently compute histograms and statistics
/// (mean, variance, etc.) of grid values

#ifndef OPENVDB_TOOLS_STATISTICS_HAS_BEEN_INCLUDED
#define OPENVDB_TOOLS_STATISTICS_HAS_BEEN_INCLUDED

#include <openvdb/Types.h>
#include <openvdb/Exceptions.h>
#include <openvdb/math/Stats.h>
#include "ValueTransformer.h"

namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace tools {

/// @brief Iterate over a scalar grid and compute a histogram of the values
/// of the voxels that are visited, or iterate over a vector-valued grid
/// and compute a histogram of the magnitudes of the vectors.
/// @param iter      an iterator over the values of a grid or its tree
///                  (@c Grid::ValueOnCIter, @c Tree::ValueOffIter, etc.)
/// @param minVal    the smallest value that can be added to the histogram
/// @param maxVal    the largest value that can be added to the histogram
/// @param numBins   the number of histogram bins
/// @param threaded  if true, iterate over the grid in parallel
template<typename IterT>
inline math::Histogram
histogram(const IterT& iter, double minVal, double maxVal,
          size_t numBins = 10, bool threaded = true);

/// @brief Iterate over a scalar grid and compute statistics (mean, variance, etc.)
/// of the values of the voxels that are visited, or iterate over a vector-valued grid
/// and compute statistics of the magnitudes of the vectors.
/// @param iter      an iterator over the values of a grid or its tree
///                  (@c Grid::ValueOnCIter, @c Tree::ValueOffIter, etc.)
/// @param threaded  if true, iterate over the grid in parallel
template<typename IterT>
inline math::Stats
statistics(const IterT& iter, bool threaded = true);

/// @brief Iterate over a grid and compute statistics (mean, variance, etc.) of
/// the values produced by applying the given functor at each voxel that is visited.
/// @param iter      an iterator over the values of a grid or its tree
///                  (@c Grid::ValueOnCIter, @c Tree::ValueOffIter, etc.)
/// @param op        a functor of the form <tt>void op(const IterT&, math::Stats&)</tt>,
///                  where @c IterT is the type of @a iter, that inserts zero or more
///                  floating-point values into the provided @c math::Stats object
/// @param threaded  if true, iterate over the grid in parallel
/// @note When @a threaded is true, each thread gets its own copy of the functor.
///
/// @par Example:
/// Compute statistics of just the active and positive-valued voxels of a scalar,
/// floating-point grid.
/// @code
/// struct Local {
///     static inline
///     void addIfPositive(const FloatGrid::ValueOnCIter& iter, math::Stats& stats)
///     {
///         const float f = *iter;
///         if (f > 0.0) {
///             if (iter.isVoxelValue()) stats.add(f);
///             else stats.add(f, iter.getVoxelCount());
///         }
///     }
/// };
/// FloatGrid grid = ...;
/// math::Stats stats =
///     tools::statistics(grid.cbeginValueOn(), Local::addIfPositive, /*threaded=*/true);
/// @endcode
template<typename IterT, typename ValueOp>
inline math::Stats
statistics(const IterT& iter, const ValueOp& op, bool threaded);

/// @brief Iterate over a grid and compute statistics (mean, variance, etc.)
/// of the values produced by applying a given operator (see math/Operators.h)
/// at each voxel that is visited.
/// @param iter      an iterator over the values of a grid or its tree
///                  (@c Grid::ValueOnCIter, @c Tree::ValueOffIter, etc.)
/// @param op        an operator object with a method of the form
///                  <tt>double result(Accessor&, const Coord&)</tt>
/// @param threaded  if true, iterate over the grid in parallel
/// @note World-space operators, whose @c result() methods are of the form
/// <tt>double result(const Map&, Accessor&, const Coord&)</tt>, must be wrapped
/// in a math::MapAdapter.
/// @note Vector-valued operators like math::Gradient must be wrapped in an adapter
/// such as math::OpMagnitude.
///
/// @par Example:
/// Compute statistics of the magnitude of the gradient at the active voxels of
/// a scalar, floating-point grid.  (Note the use of the math::MapAdapter and
/// math::OpMagnitude adapters.)
/// @code
/// FloatGrid grid = ...;
///
/// // Assume that we know that the grid has a uniform scale map.
/// typedef math::UniformScaleMap MapType;
/// // Specify a world-space gradient operator that uses first-order differencing.
/// typedef math::Gradient<MapType, math::FD_1ST> GradientOp;
/// // Wrap the operator with an adapter that computes the magnitude of the gradient.
/// typedef math::OpMagnitude<GradientOp, MapType> MagnitudeOp;
/// // Wrap the operator with an adapter that associates a map with it.
/// typedef math::MapAdapter<MapType, GradientOp, double> CompoundOp;
///
/// if (MapType::Ptr map = grid.constTransform().constMap<MapType>()) {
///     math::Stats stats = tools::opStatistics(grid.cbeginValueOn(), CompoundOp(*map));
/// }
/// @endcode
///
/// @par Example:
/// Compute statistics of the divergence at the active voxels of a vector-valued grid.
/// @code
/// Vec3SGrid grid = ...;
///
/// // Assume that we know that the grid has a uniform scale map.
/// typedef math::UniformScaleMap MapType;
/// // Specify a world-space divergence operator that uses first-order differencing.
/// typedef math::Divergence<MapType, math::FD_1ST> DivergenceOp;
/// // Wrap the operator with an adapter that associates a map with it.
/// typedef math::MapAdapter<MapType, DivergenceOp, double> CompoundOp;
///
/// if (MapType::Ptr map = grid.constTransform().constMap<MapType>()) {
///     math::Stats stats = tools::opStatistics(grid.cbeginValueOn(), CompoundOp(*map));
/// }
/// @endcode
///
/// @par Example:
/// As above, but computing the divergence in index space.
/// @code
/// Vec3SGrid grid = ...;
///
/// // Specify an index-space divergence operator that uses first-order differencing.
/// typedef math::ISDivergence<math::FD_1ST> DivergenceOp;
///
/// math::Stats stats = tools::opStatistics(grid.cbeginValueOn(), DivergenceOp());
/// @endcode
template<typename OperatorT, typename IterT>
inline math::Stats
opStatistics(const IterT& iter, const OperatorT& op = OperatorT(), bool threaded = true);

////////////////////////////////////////

namespace stats_internal {

/// @todo This traits class is needed because tree::TreeValueIteratorBase uses
/// the name ValueT for the type of the value to which the iterator points,
/// whereas node-level iterators use the name ValueType.
template<typename IterT, typename AuxT = void>
struct IterTraits {
    typedef typename IterT::ValueType ValueType;
};

template<typename TreeT, typename ValueIterT>
struct IterTraits<tree::TreeValueIteratorBase<TreeT, ValueIterT> > {
    typedef typename tree::TreeValueIteratorBase<TreeT, ValueIterT>::ValueT ValueType;
};

// Helper class to compute a scalar value from either a scalar or a vector value
// (the latter by computing the vector's magnitude)
template<typename T, bool IsVector> struct GetValImpl;

template<typename T>
struct GetValImpl<T, /*IsVector=*/false> {
    static inline double get(const T& val) { return double(val); }
};

template<typename T>
struct GetValImpl<T, /*IsVector=*/true> {
    static inline double get(const T& val) { return val.length(); }
};

// Helper class to compute a scalar value from a tree or node iterator
// that points to a value in either a scalar or a vector grid, and to
// add that value to a math::Stats object.
template<typename IterT, typename StatsT>
struct GetVal
{
    typedef typename IterTraits<IterT>::ValueType ValueT;
    typedef GetValImpl<ValueT, VecTraits<ValueT>::IsVec> ImplT;

    inline void operator()(const IterT& iter, StatsT& stats) const {
        if (iter.isVoxelValue()) stats.add(ImplT::get(*iter));
        else stats.add(ImplT::get(*iter), iter.getVoxelCount());
    }
};

// Helper class to accumulate scalar voxel values or vector voxel magnitudes
// into a math::Stats object
template<typename IterT, typename ValueOp>
struct StatsOp
{
    StatsOp(const ValueOp& op): getValue(op) {}

    // Accumulate voxel and tile values into this functor's Stats object.
    inline void operator()(const IterT& iter) { getValue(iter, stats); }

    // Accumulate another functor's Stats object into this functor's.
    inline void join(StatsOp& other) { stats.add(other.stats); }

    math::Stats stats;
    ValueOp getValue;
};

// Helper class to accumulate scalar voxel values or vector voxel magnitudes
// into a math::Histogram object
template<typename IterT, typename ValueOp>
struct HistOp
{
    HistOp(const ValueOp& op, double vmin, double vmax, size_t bins):
        hist(vmin, vmax, bins), getValue(op)
    {}

    // Accumulate voxel and tile values into this functor's Histogram object.
    inline void operator()(const IterT& iter) { getValue(iter, hist); }

    // Accumulate another functor's Histogram object into this functor's.
    inline void join(HistOp& other) { hist.add(other.hist); }

    math::Histogram hist;
    ValueOp getValue;
};

// Helper class to apply an operator such as math::Gradient or math::Laplacian
// to voxels and accumulate the scalar results or the magnitudes of vector results
// into a math::Stats object
template<typename IterT, typename OpT>
struct MathOp
{
    typedef typename IterT::TreeT                     TreeT;
    typedef typename TreeT::ValueType                 ValueT;
    typedef typename tree::ValueAccessor<const TreeT> ConstAccessor;

    // Each thread gets its own accessor and its own copy of the operator.
    ConstAccessor mAcc;
    OpT mOp;
    math::Stats mStats;

    template<typename TreeT>
    static inline TreeT* THROW_IF_NULL(TreeT* ptr) {
        if (ptr == NULL) OPENVDB_THROW(ValueError, "iterator references a null tree");
        return ptr;
    }

    MathOp(const IterT& iter, const OpT& op):
        mAcc(*THROW_IF_NULL(iter.getTree())), mOp(op)
    {}

    // Accumulate voxel and tile values into this functor's Stats object.
    void operator()(const IterT& it)
    {
        if (it.isVoxelValue()) {
            // Add the magnitude of the gradient at a single voxel.
            mStats.add(mOp.result(mAcc, it.getCoord()));
        } else {
            // Iterate over the voxels enclosed by a tile and add the results
            // of applying the operator at each voxel.
            /// @todo This could be specialized to be done more efficiently for some operators.
            /// For example, all voxels in the interior of a tile (i.e., not on the borders)
            /// have gradient zero, so there's no need to apply the operator to every voxel.
            CoordBBox bbox = it.getBoundingBox();
            Coord xyz;
            int &x = xyz.x(), &y = xyz.y(), &z = xyz.z();
            for (x = bbox.min().x(); x <= bbox.max().x(); ++x) {
                for (y = bbox.min().y(); y <= bbox.max().y(); ++y) {
                    for (z = bbox.min().z(); z <= bbox.max().z(); ++z) {
                        mStats.add(mOp.result(mAcc, it.getCoord()));
                    }
                }
            }
        }
    }

    // Accumulate another functor's Stats object into this functor's.
    inline void join(MathOp& other) { mStats.add(other.mStats); }
}; // struct MathOp

} // namespace stats_internal

template<typename IterT>
inline math::Histogram
histogram(const IterT& iter, double vmin, double vmax, size_t numBins, bool threaded)
{
    typedef stats_internal::GetVal<IterT, math::Histogram> ValueOp;
    ValueOp valOp;
    stats_internal::HistOp<IterT, ValueOp> op(valOp, vmin, vmax, numBins);
    tools::accumulate(iter, op, threaded);
    return op.hist;
}

template<typename IterT>
inline math::Stats
statistics(const IterT& iter, bool threaded)
{
    stats_internal::GetVal<IterT, math::Stats> valOp;
    return statistics(iter, valOp, threaded);
}

template<typename IterT, typename ValueOp>
inline math::Stats
statistics(const IterT& iter, const ValueOp& valOp, bool threaded)
{
    stats_internal::StatsOp<IterT, const ValueOp> op(valOp);
    tools::accumulate(iter, op, threaded);
    return op.stats;
}

template<typename OperatorT, typename IterT>
inline math::Stats
opStatistics(const IterT& iter, const OperatorT& op, bool threaded)
{
    stats_internal::MathOp<IterT, OperatorT> func(iter, op);
    tools::accumulate(iter, func, threaded);
    return func.mStats;
}

} // namespace tools
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb

#endif // OPENVDB_TOOLS_STATISTICS_HAS_BEEN_INCLUDED

// Copyright (c) 2012-2013 DreamWorks Animation LLC
// All rights reserved. This software is distributed under the
// Mozilla Public License 2.0 ( http://www.mozilla.org/MPL/2.0/ )


text:
<?php

namespace Ivory\Tests\GoogleMap\Helper\Renderer\Overlay;

use Ivory\GoogleMap\Base\Coordinate;
use Ivory\GoogleMap\Base\Size;
use Ivory\GoogleMap\Helper\Formatter\Formatter;
use Ivory\GoogleMap\Helper\Renderer\Overlay\AbstractInfoWindowRenderer;
use Ivory\GoogleMap\Helper\Renderer\Overlay\DefaultInfoWindowRenderer;
use Ivory\GoogleMap\Overlay\InfoWindow;
use Ivory\GoogleMap\Overlay\InfoWindowType;
use Ivory\JsonBuilder\JsonBuilder;

/**
 * @author GeLo <geloen.eric@gmail.com>
 */
class DefaultInfoWindowRendererTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var DefaultInfoWindowRenderer|\PHPUnit_Framework_MockObject_MockObject
     */
    private $defaultInfoWindowRenderer;

    /**
     * {@inheritdoc}
     */
    protected function setUp()
    {
        $this->defaultInfoWindowRenderer = new DefaultInfoWindowRenderer(new Formatter(), new JsonBuilder());
    }

    public function testInheritance()
    {
        $this->assertInstanceOf(AbstractInfoWindowRenderer::class, $this->defaultInfoWindowRenderer);
    }

    public function testRender()
    {
        $position = new Coordinate();
        $position->setVariable('position');

        $pixelOffset = new Size();
        $pixelOffset->setVariable('pixel_offset');

        $infoWindow = new InfoWindow('content', InfoWindowType::DEFAULT_, $position);
        $infoWindow->setVariable('info_window');
        $infoWindow->setPixelOffset($pixelOffset);
        $infoWindow->setOptions(['foo' => 'bar']);

        $this->assertSame(
            'info_window=new google.maps.InfoWindow({"position":position,"pixelOffset":pixel_offset,"content":"content","foo":"bar"})',
            $this->defaultInfoWindowRenderer->render($infoWindow)
        );
    }

    public function testRenderWithoutPosition()
    {
        $infoWindow = new InfoWindow('content');
        $infoWindow->setVariable('info_window');

        $this->assertSame(
            'info_window=new google.maps.InfoWindow({"content":"content"})',
            $this->defaultInfoWindowRenderer->render($infoWindow, false)
        );
    }
}


text:
import math
import mock
import random
import socketIO_client as sio

from libs import psmoveapi

from src.base import event
from src.base import racket
from src.events import clear_event

class GameState(object):
  '''
  Game states for the controller.
  '''
  COLOR_SELECTION = 0
  COLOR_WAIT = 1
  START_WAIT = 2
  SERVER = 3
  GAMEPLAY = 4
  HIT_BALL = 5
  WON_RALLY = 6
  LOST_RALLY = 7
  END_GAME_WIN = 8
  END_GAME_LOST = 9

def filter_player(func):
  def inner(self, data):
    if(('player_num' in data) and (data['player_num'] == self.player_num)):
      del data['player_num']
      if(len(data) > 0):
        func(self, data)
      else:
        func(self)

  return inner

class SIORacket(racket.Racket):
  '''
  socketio-based racket for gameplay.

  This class includes many different events for actual gameplay!
  '''

  COLORS = {
      psmoveapi.Button.SQUARE:   (255.0 / 255.0, 105.0 / 255.0, 180.0 / 255.0),
      psmoveapi.Button.TRIANGLE: ( 64.0 / 255.0, 255.0 / 255.0, 64.0 / 255.0),
      psmoveapi.Button.CROSS:    (24.0 / 255.0, 135.0 / 255.0, 189.0 / 255.0),
      psmoveapi.Button.CIRCLE:   (255.0 / 255.0,  168.0 / 255.0,  24.0 / 255.0)
    }

  # Base colors
  COLOR_BAD   = (1.0, 0, 0)
  COLOR_GOOD  = (0, 1.0, 0)
  COLOR_CLEAR = (1.0, 1.0, 1.0)

  # Colors for game outcomes
  COLOR_LOSE  = COLOR_BAD
  COLOR_WIN   = COLOR_GOOD

  # Times for animations
  COLOR_TRANS_TIME   = 0.2
  COLOR_WAIT_TIME    = 0.1
  COLOR_CONFIRM_TIME = 0.5
  COLOR_REJECT_TIME  = 0.25
  SERVER_TIME        = 1.0
  HIT_TIME           = 0.5
  WON_RALLY_TIME     = 1.0
  LOST_RALLY_TIME    = 1.0
  OVER_TIME          = 5.0

  def __init__(self, sio_host, sio_port, player_num):
    super(SIORacket, self).__init__()

    # Save parameters
    self.sio_host = sio_host
    self.sio_port = sio_port
    self.player_num = player_num

    # socketio config
    self._sio = sio.SocketIO(self.sio_host, self.sio_port)

    # socketio callbacks
    # Basic
    self._sio.on('connect', self.on_sio_connect)
    self._sio.on('disconnect', self.on_sio_disconnect)

    # Game-based - Listening
    self._sio.on('init_color_reject', self.on_sio_init_color_reject)
    self._sio.on('init_color_confirm', self.on_sio_init_color_confirm)
    self._sio.on('game_is_server', self.on_sio_game_is_server)
    self._sio.on('game_missed_ball', self.on_sio_game_missed_ball)
    self._sio.on('game_hit_ball', self.on_sio_game_hit_ball)
    self._sio.on('game_won_rally', self.on_sio_game_won_rally)
    self._sio.on('game_over', self.on_sio_game_over)

    print 'socketio: init'

    # Other parameters
    self.state = GameState.COLOR_SELECTION
    self.state_data = None
    self.color_choice = None
    self.enable_swings = False

    print 'racket: init'

  ################################ Helpers #####################################

  def generic_flash(self, freq = 1, rumble = True, color = True,
      invert_color = False, invert_rumble = False, scale = 1.0,
      color_scale = 1.0, rumble_scale = 1.0, color_min = 0.0,
      rumble_min = 0.0):
    # Generate a function which produces a 'flashing' effect on the rumble
    # colors for the controller

    def flash(time, controller, color_rgb):
      # Given a color to flash around and the controller, flash based on the
      # time argument (assumed to go from [0, 1])

      # Get base power
      power = (1 - math.cos(time * (2 * math.pi) * freq))/2
      power = min(1.0, max(0.0, power * scale))

      # Get color power
      color_power = min(1.0, max(0.0, power * color_scale))
      color_power = color_power if(invert_color) else (1 - color_power)

      # Get rumble power
      rumble_power = min(1.0, max(0.0, power * rumble_scale))
      rumble_power = (1 - rumble_power) if(invert_rumble) else rumble_power

      # Get the color
      color_flash = tuple(map(lambda x: x * color_power, list(color_rgb)))

      if(color):
        controller.color = psmoveapi.RGB(*color_flash)

      if(rumble):
        controller.rumble = rumble_power

    return flash

  def generic_color_trans(self, source, target):
    # Generate a function which produces a simple linear transition between
    # two colors

    def trans(time, controller, _):
      # If the source is None, we consider this to actually be the user-chosen
      # color (from the start)
      source_rgb = source
      if(source_rgb is None):
        source_rgb = self.color_choice

      # Similar for the target
      target_rgb = target
      if(target_rgb is None):
        target_rgb = self.color_choice

      # Unpack
      (sr, sg, sb) = source_rgb
      (tr, tg, tb) = target_rgb

      # Scale and color
      scale = lambda a, b: a + (b - a) * time
      color = (scale(sr, tr), scale(sg, tg), scale(sb, tb))
      controller.color = psmoveapi.RGB(*color)

    return trans

  ######################## socketio Housekeeping ###############################

  def on_sio_connect(self):
    # Log the connection
    print 'socketio: Connected'

  def on_sio_disconnect(self):
    # Log the drop
    print 'socketio: Disconnected'

  ######################### socketio Listeners #################################

  # @filter_player
  def on_sio_init_color_confirm(self):
    # Callback for a color confirmation event
    print 'socketio: init_color_confirm'

    # Ready for swings!
    self.enable_swings = True

    # Parameterize the transition with animations
    self.state = GameState.START_WAIT
    self.state_data = {
        'events': [
            (event.Event(SIORacket.COLOR_CONFIRM_TIME,
                self.generic_flash(freq = 3, color_scale = 0.75)), None),
            (clear_event.ClearEvent(), None)
          ]
      }

  # @filter_player
  def on_sio_init_color_reject(self):
    # Callback for a color rejection event
    print 'socketio: init_color_reject'

    # Disable swings (not at the game yet)
    self.enable_swings = False

    # Parameterize the transition with animations
    self.state = GameState.COLOR_SELECTION
    self.state_data = {
        'events': [
            (event.Event(SIORacket.COLOR_TRANS_TIME,
                self.generic_color_trans(None, SIORacket.COLOR_BAD)), None),
            (event.Event(SIORacket.COLOR_REJECT_TIME,
                self.generic_flash()), SIORacket.COLOR_BAD),
            (clear_event.ClearEvent(clear_color = True), SIORacket.COLOR_BAD),
            (event.Event(SIORacket.COLOR_TRANS_TIME,
                self.generic_color_trans(SIORacket.COLOR_BAD, None)), None)
          ]
      }

  # @filter_player
  def on_sio_game_is_server(self):
    # Callback for when the player becomes the person serving the ball
    print 'socketio: game_is_server'

    # Keep swings enabled
    self.enable_swings = True

    # Parameterize the transition with animations
    self.state = GameState.SERVER
    self.state_data = {
        'events': [
            (event.Event(SIORacket.SERVER_TIME,
                self.generic_flash(freq = 2)), None),
            (clear_event.ClearEvent(), None)
          ]
      }

  # @filter_player
  def on_sio_game_missed_ball(self):
    # Callback for a missed ball event
    print 'socketio: game_missed_ball'

    # Keep swings enabled
    self.enable_swings = True

    # Parameterize the transition with animations
    self.state = GameState.LOST_RALLY
    self.state_data = {
        'events': [
            (event.Event(SIORacket.COLOR_TRANS_TIME,
                self.generic_color_trans(None, SIORacket.COLOR_LOSE)), None),
            (event.Event(SIORacket.LOST_RALLY_TIME,
                self.generic_flash(freq = 2)), SIORacket.COLOR_LOSE),
            (clear_event.ClearEvent(clear_color = True), SIORacket.COLOR_LOSE),
            (event.Event(SIORacket.COLOR_TRANS_TIME,
                self.generic_color_trans(SIORacket.COLOR_LOSE, None)), None)
          ]
      }

  # @filter_player
  def on_sio_game_hit_ball(self, data):
    # Callback for a hit ball event
    print 'socketio: game_hit_ball'

    # Parse parameters
    strength = data['strength']

    # Keep swings enabled
    self.enable_swings = True

    # Parameterize the transition with animations
    self.state = GameState.HIT_BALL
    self.state_data = {
        'events': [
            (event.Event(SIORacket.HIT_TIME,
                self.generic_flash(color_scale = strength)), None),
            (clear_event.ClearEvent(), None)
          ]
      }

  # @filter_player
  def on_sio_game_won_rally(self):
    # Callback for when a player wins the rally
    print 'socketio: game_won_rally'

    # Keep swings enabled
    self.enable_swings = True

    # Parameterize the transition with animations
    self.state = GameState.WON_RALLY
    self.state_data = {
        'events': [
            (event.Event(SIORacket.COLOR_TRANS_TIME,
                self.generic_color_trans(None, SIORacket.COLOR_WIN)), None),
            (event.Event(SIORacket.WON_RALLY_TIME,
                self.generic_flash(freq = 2)), SIORacket.COLOR_WIN),
            (clear_event.ClearEvent(clear_color = True), SIORacket.COLOR_WIN),
            (event.Event(SIORacket.COLOR_TRANS_TIME,
                self.generic_color_trans(SIORacket.COLOR_WIN, None)), None),
          ]
      }

  # @filter_player
  def on_sio_game_over(self, data):
    # Callback for when the game ends
    print 'socketio: game_over'

    # Parse parameters
    is_winner = data['is_winner']

    # Disable swings
    self.enable_swings = False

    # Chose which color and which end-state
    color = SIORacket.COLOR_WIN
    if(is_winner):
      self.state = GameState.END_GAME_WIN
    else:
      color = SIORacket.COLOR_LOSE
      self.state = GameState.END_GAME_LOST

    # Parameterize the transition with animations
    self.state_data = {
        'events': [
            (event.Event(SIORacket.COLOR_TRANS_TIME,
                self.generic_color_trans(None, color)), None),
            (event.Event(SIORacket.OVER_TIME,
                self.generic_flash(freq = 5)), color),
            (clear_event.ClearEvent(clear_color = True), color),
            (event.Event(SIORacket.COLOR_TRANS_TIME,
                self.generic_color_trans(color, SIORacket.COLOR_CLEAR)), None)
          ]
      }

  ########################### socketio Emits ###################################

  def sio_init_color_choice(self, color):
    # Method to communicate the color choice
    self._sio.emit('init_color_choice', {
        'player_num': self.player_num,
        'color': color,
      })

  def sio_game_swing(self, hand, strength):
    # Method to communicate the swing event

    self._sio.emit('game_swing', {
        'player_num': self.player_num,
        'hand': (0 if(hand == racket.Handedness.LEFT) else 1),
        'strength': strength
      })

  ############################ Racket Events ###################################

  def on_idle(self, controller, hand):
    # On idle, the player should see a white ball and have no rumble
    controller.color = psmoveapi.RGB(*self.color_choice)
    controller.rumble = 0

  def on_backswing(self, controller, hand):
    # On a backswing, the player should see a red ball and have some rumble
    controller.rumble = 0.33

  def on_swing(self, controller, hand, strength):
    # On a transition, the player should see a blue ball and have max rumble
    controller.rumble = 1.0

    # Send the swing
    self.sio_game_swing(hand, strength)
    print 'racket: Swing, %f' % strength

  ############################# Button Events ##################################

  def on_button(self, controller, buttons):
    # Method to parse button presses

    # Temporary to cycle through animations
    # Pressing the PS button simulates an in-order server event
    if(psmoveapi.Button.PS in buttons):
      if(self.state == GameState.COLOR_WAIT):
        if(bool(random.randint(0, 1))):
          self.on_sio_init_color_reject()
        else:
          self.on_sio_init_color_confirm()

      elif(self.state == GameState.START_WAIT):
        self.on_sio_game_is_server()

      elif(self.state == GameState.GAMEPLAY):
        end_rally = False

        if(bool(random.randint(0, 3))):
          self.on_sio_game_hit_ball({'strength': 0.75})
          if(not bool(random.randint(0, 5))):
            self.on_sio_game_won_rally()
            end_rally = True
        else:
          self.on_sio_game_missed_ball()
          end_rally = True

        if(end_rally and not bool(random.randint(0, 5))):
          if(bool(random.randint(0, 1))):
            self.on_sio_game_over({'is_winner': False})
          else:
            self.on_sio_game_over({'is_winner': True})

      return

    # Color choosing logic
    if(self.state == GameState.COLOR_SELECTION):
      choices = (psmoveapi.Button.SQUARE, psmoveapi.Button.TRIANGLE,
        psmoveapi.Button.CROSS, psmoveapi.Button.CIRCLE)

      # Cycle through button options
      for button in choices:
        if(button in buttons):
          self.color_choice = SIORacket.COLORS[button]
          controller.color = psmoveapi.RGB(*self.color_choice)
          return

    # Color confirmation logic
    if((self.color_choice is not None) and (psmoveapi.Button.MOVE in buttons)):
      self.sio_init_color_choice(self.color_choice)

      # Signal a transition to the next state
      self.state = GameState.COLOR_WAIT
      self.state_data = {
          'events': [
              (event.Event(SIORacket.COLOR_WAIT_TIME,
                  self.generic_flash(rumble_scale = 0.75,
                      color_scale = 0.75)), None),
              (clear_event.ClearEvent(), None)
            ]
        }

  ######################### Housekeeping Events ################################

  def on_init(self, controller):
    # Method for initialization
    print 'psmove:', controller, 'connected!'

    # Set the controller to be blank
    controller.color = psmoveapi.RGB(*SIORacket.COLOR_CLEAR)
    controller.rumble = 0

  def on_leave(self, controller):
    # Method for when a controller is dropped
    print 'psmove:', controller, 'disconnected!'

  def on_refresh(self, controller, swing_state):
    # To be changed below
    next_state = None
    enable_swings = False

    # Do nothing special if we are in the color selection / confirmation stage
    if(self.state == GameState.COLOR_SELECTION
        or self.state == GameState.COLOR_WAIT
        or self.state == GameState.START_WAIT):
      enable_swings = self.enable_swings

    else:
      # The following should allow swings and transition back to GAMEPLAY
      if(self.state == GameState.SERVER
          or self.state == GameState.GAMEPLAY
          or self.state == GameState.HIT_BALL):
        next_state = GameState.GAMEPLAY
        enable_swings = True

      # These should also transition to GAMEPLAY, but without swings
      elif(self.state == GameState.WON_RALLY
          or self.state == GameState.LOST_RALLY):
        next_state = GameState.GAMEPLAY

      # These should make the game end
      elif(self.state == GameState.END_GAME_WIN
          or self.state == GameState.END_GAME_LOST):
        next_state = GameState.COLOR_SELECTION
        enable_swings = False

    # Work through pending animations
    if(self.state_data is not None):
      if('events' in self.state_data):
        events = self.state_data['events']

        # Remove events if there are none left
        if(len(events) == 0):
          if(next_state is not None):
            self.state = next_state
            del self.state_data['events']

        else:
          # Execute the event at the front of the queue
          (event, color) = events[0]
          color = self.color_choice if(color is None) else color

          event.do(controller, color)
          if(event.done()):
            events.pop(0)

      # Clean up the state data if no more exists
      elif(len(self.state_data) == 0):
        self.state_data = None

    return enable_swings

  def exit(self):
    # Clean-up method
    self.sio.disconnect()


text:
var when = require("when");
var argument = require("./argument");

function detectDuplicates(options) {
    options.forEach(function (option, i) {
        if (options.slice(i + 1).some(function (o) { return option === o; })) {
            throw new Error("Duplicate option (" + option + ")");
        }
    });
}

function unexpectedValueError(option) {
    return new Error(option.signature + " does not take a value.");
}

function missingValueError(option) {
    return new Error("No value specified for " + option.signature);
}

function validateOption(option) {
    if (module.exports.isShortOption(option) && option.length > 2) {
        throw new Error("A short option can only be one dash and " +
                        "one character (" + option + ").");
    }
    return option;
}

function getTransform(properties) {
    if (!properties.transform) { return; }
    if (typeof properties.transform !== "function") {
        throw new Error("transform must be function");
    }
    return properties.transform;
}

function getRequiresValue(properties) {
    if (!properties.hasOwnProperty("requiresValue")) { return true; }
    return properties.requiresValue;
}

function Option(validators) {
    var prop, arg = argument.create(validators);
    for (prop in arg) {
        this[prop] = arg[prop];
    }
}

Option.prototype = module.exports = {
    create: function (opts, props) {
        if (opts.length === 0) {
            throw new Error("Option must have at least one name, e.g. --help");
        }
        detectDuplicates(opts);
        props = props || {};
        var options = opts.map(validateOption);
        var opt = new Option(props.validators);
        opt.options = options;
        opt.signature = options.join("/");
        opt.hasValue = !!props.hasValue || props.hasOwnProperty("defaultValue");
        opt.requiresValue = getRequiresValue(props);
        opt.transform = getTransform(props);
        opt.defaultValue = props.defaultValue;
        opt.description = props.description;
        return opt;
    },

    valueRequired: function () {
        return this.hasValue && this.requiresValue;
    },

    handle: function (data, value) {
        var hasValue = typeof value === "string";
        if (hasValue && !this.hasValue) { throw unexpectedValueError(this); }
        if (!hasValue && this.valueRequired()) { throw missingValueError(this); }
        if (hasValue) { data.value = value; }
        data.isSet = true;
        data.timesSet++;
    },

    intersects: function (o) {
        return this.options.some(function (opt) { return o.recognizes(opt); });
    },

    recognizes: function (option, data) {
        var shortOpt = option.slice(0, 2);
        var longOpt = option.split("=")[0];
        return this.options.indexOf(shortOpt) >= 0 ||
            this.options.indexOf(longOpt) >= 0;
    },

    keys: function () {
        return this.options;
    },

    isLongOption: function (option) {
        return (/^\-\-./).test(option);
    },

    isShortOption: function (option) {
        return (/^\-[^\-]/).test(option);
    },

    isOption: function (opt) {
        return this.isLongOption(opt) || this.isShortOption(opt);
    }
};


text:
package filodb.http

import akka.actor.ActorRef
import akka.http.scaladsl.server.Directives._
import de.heikoseeberger.akkahttpcirce.FailFastCirceSupport

import filodb.coordinator.{ShardEvent, StatusActor}
import filodb.core.DatasetRef
import filodb.http.apiv1.HttpSchema

final case class DatasetEvents(dataset: String, shardEvents: Seq[String])

class HealthRoute(coordinatorActor: ActorRef) extends FiloRoute {
  import FailFastCirceSupport._
  import io.circe.generic.auto._
  import filodb.coordinator.client.Client._
  import HttpSchema._

  val route = {
    // Returns the local dataset/shard status as JSON
    path ("__health") {
      get {
        onSuccess(asyncAsk(coordinatorActor, StatusActor.GetCurrentEvents)) {
          case m: collection.Map[DatasetRef, Seq[ShardEvent]] @unchecked =>
            complete(httpList(m.toSeq.map { case (ref, ev) => DatasetEvents(ref.toString, ev.map(_.toString)) }))
        }
      }
    }
  }
}


text:
#include <string>
#include <vector>
#include "paddle/fluid/framework/op_registry.h"
#ifdef PADDLE_WITH_CUDA
#include "paddle/fluid/platform/cudnn_helper.h"
#endif
#include "paddle/fluid/platform/cudnn_workspace_helper.h"

namespace paddle {
namespace operators {

class ConvInceptionFusionOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;
  void InferShape(framework::InferShapeContext* ctx) const override {
    // 1 x
    auto in_dims = ctx->GetInputDim("Input");
    // 4 filters
    auto w_dims = ctx->GetInputsDim("Filter");

    PADDLE_ENFORCE(in_dims.size(), 4, "Conv intput should be 4-D tensor.");
    PADDLE_ENFORCE_EQ(w_dims.size(), 4, "There should be 4 filters");
    PADDLE_ENFORCE_EQ(w_dims[0][1], in_dims[1]);
    PADDLE_ENFORCE_EQ(w_dims[1][1], in_dims[1]);

    int n = in_dims[0];
    // compute output channel
    // 1st channel
    int c = w_dims[0][0];
    // add 2nd channel
    c += (w_dims[1][0] - w_dims[2][1] * 2);
    // add 3rd channel
    c += (w_dims[2][0] - w_dims[3][1]);
    // add 4-th channel
    c += w_dims[3][0];

    int h = in_dims[2];
    int w = in_dims[3];

    ctx->SetOutputDim("Output", {n, c, h, w});
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "Input"),
        ctx.device_context());
  }
};

class ConvInceptionFusionOpMaker : public framework::OpProtoAndCheckerMaker {
 protected:
  void Make() override {
    AddInput("Input", "(Tensor) NCHW layout.");
    AddInput("Filter", "(vector<Tensor>) 4 aggregated filters").AsDuplicable();
    AddInput("Bias", "(vector<Tensor>) it's length is equal to Filter")
        .AsDuplicable();
    AddOutput("Output",
              "(Tensor) The output tensor of convolution operator. "
              "The format of output tensor is also NCHW.");
    AddOutput("TempOutput", "").AsDuplicable();
    AddAttr<std::string>(
        "pooling_type",
        "(string), pooling type, can be \"max\" for max-pooling "
        "and \"avg\" for average-pooling.")
        .InEnum({"max", "avg"});
    AddAttr<bool>(
        "exclusive",
        "(bool, default True) When true, will exclude the zero-padding in the "
        "averaging calculating, otherwise, include the zero-padding. Note, it "
        "is only used when pooling_type is avg. The default is True.")
        .SetDefault(true);
    AddAttr<std::string>(
        "activation",
        "The activation type can be 'identity', 'sigmoid', 'relu', 'relu6' "
        "'relux' , 'tanh', 'band_pass'")
        .SetDefault("relu");
    AddAttr<int>("workspace_size_MB",
                 "Only used in cudnn kernel. Need set use_cudnn to true."
                 "workspace size for cudnn, in MB, "
                 "workspace is a section of GPU memory which will be "
                 "allocated/freed each time the operator runs, larger "
                 "workspace size can increase performance but also requires "
                 "better hardware. This size should be chosen carefully.")
        .SetDefault(platform::GetDefaultConvWorkspaceSizeLimitMB());
    AddComment(R"DOC(
)DOC");
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
REGISTER_OPERATOR(conv2d_inception_fusion, ops::ConvInceptionFusionOp,
                  ops::ConvInceptionFusionOpMaker,
                  paddle::framework::EmptyGradOpMaker);


text:
Manage Box users
This integration was integrated and tested with API version 2.0 of Box v2

## Configure the Box Application to Interface with XSOAR
1. Navigate to [the developer console](https://app.box.com/developers/console) for Box.
2. Click **Create a New App**.
3. Select **Custom App** and when prompted, select **Server Authentication (with JWT)**
4. Enter your desired App Name.
5. In the Configuration menu under Application Access, select **Enterprise**.
6. Under the Advanced Features option, enable both **Perform Actions as Users** and **Generate User Access Tokens**.
7. In the Add and Manage Public Keys section, click **Generate a Public/Private Keypair** and follow the prompts.
8. Click **Save Changes** in the upper right-hand corner.
9. Navigate to the bottom of the page and select **Download as a JSON**.

Once you have obtained the JSON file, copy and paste its contents into the *Credentials JSON* parameter.

Before testing the integration, navigate to the General Settings for your app in the developer console and click
**Review and Submit**. Your enterprise admin will need to approve the app before your integration will start working.

From the General Settings menu, you can obtain your *User ID* for the service account.

## Configure Box v2 on Cortex XSOAR

1. Navigate to **Settings** > **Integrations** > **Servers & Services**.
2. Search for Box v2.
3. Click **Add instance** to create and configure a new integration instance.

    | **Parameter** | **Description** | **Required** |
    | --- | --- | --- |
    | insecure | Trust any certificate \(not secure\) | False |
    | credentials_json | Credentials JSON | True |
    | as_user | As User for Fetching Incidents | False |
    | event_type |  | False |
    | default_user | Default User | False |
    | search_user_id | Auto-detect user IDs based on their email address. | False |
    | incidentType | Incident type | False |
    | isFetch | Fetch incidents | False |
    | first_fetch | First fetch timestamp \(<number> <time unit>, e.g., 12 hours, 7 days\) | False |
    | max_fetch |  | False |

4. Click **Test** to validate the URLs, token, and connection.

## Differences between Box \(Deprecated\) and Box v2
- Context outputs were changed to be nested under the entity type for each command. For example, user outputs
used to be stored under the context root, Box. In this version they are stored under the entity Box.Users.
- Authentication is handled via JSON Web Tokens \(JWT\) and no longer requires each command to retrieve an authentication
token manually.
- All results given via the Box API is returned into the context.


text:
import sbt._
import Keys._

object ApplicationBuild extends Build {
  val main = Project("basic", file(".")).settings(
  scalaVersion := "2.11.4",
  resolvers += Resolver.bintrayRepo("boldradiussolutions", "maven"),
  libraryDependencies ++= Seq("com.boldradius" %% "total-map" % "0.2.3-SNAPSHOT"),
  scalacOptions ++= Seq("-feature", "-deprecation"))
}


text:
/* TyTools - public domain
   Niels Martignène <niels.martignene@protonmail.com>
   https://koromix.dev/tytools

   This software is in the public domain. Where that dedication is not
   recognized, you are granted a perpetual, irrevocable license to copy,
   distribute, and modify this file as you see fit.

   See the LICENSE file for more details. */

#include <QBrush>
#include <QIcon>

#include "board.hpp"
#include "database.hpp"
#include "descriptor_notifier.hpp"
#include "monitor.hpp"
#include "../libhs/platform.h"
#include "../libty/task.h"

using namespace std;

Monitor::Monitor(QObject *parent)
    : QAbstractListModel(parent)
{
    int r = ty_pool_new(&pool_);
    if (r < 0)
        throw bad_alloc();

    loadSettings();
}

Monitor::~Monitor()
{
    stop();

    ty_pool_free(pool_);
    ty_monitor_free(monitor_);
}

void Monitor::loadSettings()
{
    auto max_tasks = db_.get("maxTasks").toUInt();
    if (!max_tasks) {
#ifdef _WIN32
        if (hs_win32_version() >= HS_WIN32_VERSION_10) {
            /* Windows 10 is much faster to load drivers and make the device available, we
               can probably afford that. */
            max_tasks = 2;
        } else {
            max_tasks = 1;
        }
#else
        max_tasks = 4;
#endif
    }
    ty_pool_set_max_threads(pool_, max_tasks);
    ignore_generic_ = db_.get("ignoreGeneric", false).toBool();
    default_serial_ = db_.get("serialByDefault", true).toBool();
    serial_log_size_ = db_.get("serialLogSize", 20000000ull).toULongLong();
    serial_log_dir_ = db_.get("serialLogDir", "").toString();

    emit settingsChanged();

    if (started_) {
        stop();
        start();
    }
}

void Monitor::setMaxTasks(unsigned int max_tasks)
{
    if (max_tasks == ty_pool_get_max_threads(pool_))
        return;

    ty_pool_set_max_threads(pool_, max_tasks);

    db_.put("maxTasks", max_tasks);
    emit settingsChanged();
}

void Monitor::setIgnoreGeneric(bool ignore_generic)
{
    if (ignore_generic == ignore_generic_)
        return;

    ignore_generic_ = ignore_generic;

    if (ignore_generic) {
        for (size_t i = 0; i < boards_.size(); i++) {
            auto &board = boards_[i];
            if (board->model() == TY_MODEL_GENERIC) {
                beginRemoveRows(QModelIndex(), static_cast<int>(i), static_cast<int>(i));
                boards_.erase(boards_.begin() + static_cast<int>(i));
                endRemoveRows();
                i--;
            }
        }
    } else {
        ty_monitor_list(monitor_, handleEvent, this);
    }

    db_.put("ignoreGeneric", ignore_generic);
    emit settingsChanged();
}

unsigned int Monitor::maxTasks() const
{
    return ty_pool_get_max_threads(pool_);
}

void Monitor::setSerialByDefault(bool default_serial)
{
    if (default_serial == default_serial_)
        return;

    default_serial_ = default_serial;

    for (auto &board: boards_) {
        auto db = board->database();

        if (!db.get("enableSerial").isValid()) {
            board->setEnableSerial(default_serial);
            db.remove("enableSerial");
        }
    }

    db_.put("serialByDefault", default_serial);
    emit settingsChanged();
}

void Monitor::setSerialLogSize(size_t default_size)
{
    if (default_size == serial_log_size_)
        return;

    serial_log_size_ = default_size;

    for (auto &board: boards_) {
        auto db = board->database();

        if (!db.get("serialLogSize").isValid()) {
            board->setSerialLogSize(default_size);
            board->updateSerialLogState(false);
            db.remove("serialLogSize");
        }
    }

    db_.put("serialLogSize", static_cast<qulonglong>(default_size));
    emit settingsChanged();
}

void Monitor::setSerialLogDir(const QString &dir)
{
    if (dir == serial_log_dir_)
        return;

    serial_log_dir_ = dir;

    for (auto &board: boards_) {
        board->serial_log_dir_ = dir;
        board->updateSerialLogState(true);
        emit board->settingsChanged();
    }

    db_.put("serialLogDir", dir);
    emit settingsChanged();
}

bool Monitor::start()
{
    if (started_)
        return true;

    int r;

    if (!monitor_) {
        ty_monitor *monitor;

        r = ty_monitor_new(&monitor);
        if (r < 0)
            return false;
        unique_ptr<ty_monitor, decltype(&ty_monitor_free)> monitor_ptr(monitor, ty_monitor_free);

        r = ty_monitor_register_callback(monitor, handleEvent, this);
        if (r < 0)
            return false;

        ty_descriptor_set set = {};
        ty_monitor_get_descriptors(monitor, &set, 1);
        monitor_notifier_.setDescriptorSet(&set);
        connect(&monitor_notifier_, &DescriptorNotifier::activated, this, &Monitor::refresh);

        monitor_ = monitor_ptr.release();
    }

    serial_thread_.start();

    r = ty_monitor_start(monitor_);
    if (r < 0)
        return false;
    monitor_notifier_.setEnabled(true);

    started_ = true;
    return true;
}

void Monitor::stop()
{
    if (!started_)
        return;

    serial_thread_.quit();
    serial_thread_.wait();

    if (!boards_.empty()) {
        beginRemoveRows(QModelIndex(), 0, static_cast<int>(boards_.size()));
        boards_.clear();
        endRemoveRows();
    }

    monitor_notifier_.setEnabled(false);
    ty_monitor_stop(monitor_);

    started_ = false;
}

vector<shared_ptr<Board>> Monitor::boards()
{
    return boards_;
}

shared_ptr<Board> Monitor::board(unsigned int i)
{
    if (i >= boards_.size())
        return nullptr;

    return boards_[i];
}

unsigned int Monitor::boardCount() const
{
    return static_cast<unsigned int>(boards_.size());
}

shared_ptr<Board> Monitor::boardFromModel(const QAbstractItemModel *model,
                                          const QModelIndex &index)
{
    auto board = model->data(index, Monitor::ROLE_BOARD).value<Board *>();
    return board ? board->shared_from_this() : nullptr;
}

vector<shared_ptr<Board>> Monitor::find(function<bool(Board &board)> filter)
{
    auto boards = boards_;

    vector<shared_ptr<Board>> matches;
    matches.reserve(boards_.size());
    for (auto &board: boards_) {
        if (filter(*board))
            matches.push_back(board);
    }

    return matches;
}

int Monitor::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    return static_cast<int>(boards_.size());
}

int Monitor::columnCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    return COLUMN_COUNT;
}

QVariant Monitor::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (orientation == Qt::Vertical || role != Qt::DisplayRole)
        return QVariant();

    switch (section) {
    case COLUMN_BOARD:
        return tr("Board");
    case COLUMN_STATUS:
        return tr("Status");
    case COLUMN_IDENTITY:
        return tr("Identity");
    case COLUMN_LOCATION:
        return tr("Location");
    case COLUMN_SERIAL_NUMBER:
        return tr("Serial Number");
    case COLUMN_DESCRIPTION:
        return tr("Description");
    }

    return QVariant();
}

QVariant Monitor::data(const QModelIndex &index, int role) const
{
    if (!index.isValid() || index.row() >= static_cast<int>(boards_.size()))
        return QVariant();

    auto board = boards_[index.row()];
    if (role == ROLE_BOARD)
        return QVariant::fromValue(board.get());

    if (index.column() == 0) {
        switch (role) {
            case Qt::ToolTipRole:
                return tr("%1\n+ Location: %2\n+ Serial Number: %3\n+ Status: %4\n+ Capabilities: %5")
                       .arg(board->modelName())
                       .arg(board->location())
                       .arg(board->serialNumber())
                       .arg(board->statusText())
                       .arg(Board::makeCapabilityString(board->capabilities(), tr("(none)")));
            case Qt::DecorationRole:
                return board->statusIcon();
            case Qt::EditRole:
                return board->tag();
        }
    }

    if (role == Qt::DisplayRole) {
        switch (index.column()) {
        case COLUMN_BOARD:
            return board->tag();
        case COLUMN_MODEL:
            return board->modelName();
        case COLUMN_STATUS:
            return board->statusText();
        case COLUMN_IDENTITY:
            return board->id();
        case COLUMN_LOCATION:
            return board->location();
        case COLUMN_SERIAL_NUMBER:
            return board->serialNumber();
        case COLUMN_DESCRIPTION:
            return board->description();
        }
    }

    return QVariant();
}

Qt::ItemFlags Monitor::flags(const QModelIndex &index) const
{
    Q_UNUSED(index);
    return Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsEnabled;
}

bool Monitor::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if (role != Qt::EditRole || !index.isValid() || index.row() >= static_cast<int>(boards_.size()))
        return false;

    auto board = boards_[index.row()];
    board->setTag(value.toString());

    return true;
}

void Monitor::refresh(ty_descriptor desc)
{
    Q_UNUSED(desc);
    ty_monitor_refresh(monitor_);
}

int Monitor::handleEvent(ty_board *board, ty_monitor_event event, void *udata)
{
    auto self = static_cast<Monitor *>(udata);

    switch (event) {
    case TY_MONITOR_EVENT_ADDED:
        self->handleAddedEvent(board);
        break;

    case TY_MONITOR_EVENT_CHANGED:
    case TY_MONITOR_EVENT_DISAPPEARED:
    case TY_MONITOR_EVENT_DROPPED:
        self->handleChangedEvent(board);
        break;
    }

    return 0;
}

Monitor::iterator Monitor::findBoardIterator(ty_board *board)
{
    return find_if(boards_.begin(), boards_.end(),
                   [=](std::shared_ptr<Board> &ptr) { return ptr->board() == board; });
}

void Monitor::handleAddedEvent(ty_board *board)
{
    if (ignore_generic_ && ty_board_get_model(board) == TY_MODEL_GENERIC)
        return;
    if (findBoardIterator(board) != boards_.end())
        return;

    // Work around the private constructor for make_shared()
    struct BoardSharedEnabler : public Board {
        BoardSharedEnabler(ty_board *board)
            : Board(board) {}
    };
    auto board_wrapper_ptr = make_shared<BoardSharedEnabler>(board);
    auto board_wrapper = board_wrapper_ptr.get();

    if (board_wrapper->hasCapability(TY_BOARD_CAPABILITY_UNIQUE))
        configureBoardDatabase(*board_wrapper);
    board_wrapper->serial_log_dir_ = serial_log_dir_;
    board_wrapper->loadSettings(this);

    board_wrapper->setThreadPool(pool_);
    board_wrapper->serial_notifier_.moveToThread(&serial_thread_);

    connect(board_wrapper, &Board::infoChanged, this, [=]() {
        refreshBoardItem(findBoardIterator(board));
    });
    // Don't capture board_wrapper_ptr, this should be obvious but I made the mistake once
    connect(board_wrapper, &Board::interfacesChanged, this, [=]() {
        if (db_.isValid() && !board_wrapper->database().isValid() &&
                board_wrapper->hasCapability(TY_BOARD_CAPABILITY_UNIQUE)) {
            configureBoardDatabase(*board_wrapper);
            board_wrapper->loadSettings(this);
        }
        refreshBoardItem(findBoardIterator(board));
    });
    connect(board_wrapper, &Board::statusChanged, this, [=]() {
        refreshBoardItem(findBoardIterator(board));
    });
    connect(board_wrapper, &Board::progressChanged, this, [=]() {
        refreshBoardItem(findBoardIterator(board));
    });
    connect(board_wrapper, &Board::dropped, this, [=]() {
        removeBoardItem(findBoardIterator(board));
    });

    beginInsertRows(QModelIndex(), static_cast<int>(boards_.size()),
                    static_cast<int>(boards_.size()));
    boards_.push_back(board_wrapper_ptr);
    endInsertRows();

    emit boardAdded(board_wrapper);
}

void Monitor::handleChangedEvent(ty_board *board)
{
    auto it = findBoardIterator(board);
    if (it == boards_.end())
        return;
    auto ptr = *it;

    ptr->refreshBoard();
}

void Monitor::refreshBoardItem(iterator it)
{
    auto index = createIndex(it - boards_.begin(), 0);
    dataChanged(index, index);
}

void Monitor::removeBoardItem(iterator it)
{
    beginRemoveRows(QModelIndex(), it - boards_.begin(), it - boards_.begin());
    boards_.erase(it);
    endRemoveRows();
}

void Monitor::configureBoardDatabase(Board &board)
{
    board.setDatabase(db_.subDatabase(board.id()));
    board.setCache(cache_.subDatabase(board.id()));
}


text:
package others.ood;

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

/**
 */
public class RPNCalculator {

    public static void main(String[] args) {
        String[] tokens = {"2", "3", "+", "1", "-", "4", "!", "+"};
        RPNCalculator calc = new RPNCalculator();
        calc.calculate(tokens);
    }

    public void calculate(String[] tokens) {
        Factory factory = new Factory();
        Stack<Token> stack = new Stack<>();
        for (String t : tokens) {
            factory.create(t).evaluate(stack);
        }
        System.out.println(((Operand) stack.peek()).getValue());
    }

}

class Factory {
    private Map<String, Operator> map = new HashMap<>();
    public Factory() {
        map.put("!", new Fact());
        map.put("+", new Add());
        map.put("-", new Sub());
        map.put("*", new Mul());
    }

    public Token create(String s) {
        if (map.containsKey(s)) return map.get(s);
        else return new IntOperand(s);
    }
}

interface Token {
    public void evaluate(Stack<Token> stack);
}

abstract class Operator implements Token {
    @Override
    public void evaluate(Stack<Token> stack) {}
}

class Add extends Operator {
    @Override
    public void evaluate(Stack<Token> stack) {
        Operand op1 = (Operand) stack.pop();
        Operand op2 = (Operand) stack.pop();
        stack.push(op1.add(op2));
    }
}

class Sub extends Operator {
    @Override
    public void evaluate(Stack<Token> stack) {
        Operand op1 = (Operand) stack.pop();
        Operand op2 = (Operand) stack.pop();
        stack.push(op1.sub(op2));
    }
}

class Mul extends Operator {
    @Override
    public void evaluate(Stack<Token> stack) {
        Operand op1 = (Operand) stack.pop();
        Operand op2 = (Operand) stack.pop();
        stack.push(op1.mul(op2));
    }
}

class Fact extends Operator {
    @Override
    public void evaluate(Stack<Token> stack) {
        Operand op = (Operand) stack.pop();
        stack.push(op.fact());
    }
}

abstract class Operand<T> implements Token {
    protected T val;

    public Operand(T val) {
        this.val = val;
    }

    public T getValue() {
        return val;
    }

    @Override
    public void evaluate(Stack<Token> stack) {
        stack.push(this);
    }

    public abstract Operand<T> fact();
    public abstract Operand<T> add(Operand<T> op2);
    public abstract Operand<T> sub(Operand<T> op2);
    public abstract Operand<T> mul(Operand<T> op2);
}

class IntOperand extends Operand<Integer> {

    public IntOperand(int val) {
        super(val);
    }

    public IntOperand(String val) {
        super(Integer.parseInt(val));
    }

    @Override
    public Operand<Integer> fact() {
        int fact = 1;
        for (int i = val; i >= 1; i--) {
            fact *= i;
        }
        return new IntOperand(fact);
    }

    @Override
    public Operand<Integer> add(Operand<Integer> op2) {
        return new IntOperand(val + op2.val);
    }

    @Override
    public Operand<Integer> sub(Operand<Integer> op2) {
        return new IntOperand(val - op2.val);
    }

    @Override
    public Operand<Integer> mul(Operand<Integer> op2) {
        return new IntOperand(val * op2.val);
    }
}