text:
package net.sf.webdav.methods;

import java.io.ByteArrayInputStream;

import net.sf.webdav.StoredObject;
import net.sf.webdav.WebdavStatus;
import net.sf.webdav.locking.ResourceLocks;
import net.sf.webdav.spi.ITransaction;
import net.sf.webdav.spi.IWebdavStore;
import net.sf.webdav.spi.WebdavRequest;
import net.sf.webdav.spi.WebdavResponse;
import net.sf.webdav.testutil.MockTest;

import org.jmock.Expectations;
import org.junit.Test;

public class DoMoveTest
    extends MockTest
{

    static IWebdavStore mockStore;

    static WebdavRequest mockReq;

    static WebdavResponse mockRes;

    static ITransaction mockTransaction;

    static byte[] resourceContent = new byte[] { '<', 'h', 'e', 'l', 'l', 'o', '/', '>' };

    static ByteArrayInputStream bais = new ByteArrayInputStream( resourceContent );

    //    static DelegatingServletInputStream dsis = new DelegatingServletInputStream(
    //            bais);

    static final String tmpFolder = "/tmp/tests";

    static final String sourceCollectionPath = tmpFolder + "/sourceFolder";

    static final String destCollectionPath = tmpFolder + "/destFolder";

    static final String sourceFilePath = sourceCollectionPath + "/sourceFile";

    static final String destFilePath = destCollectionPath + "/destFile";

    static final String overwritePath = destCollectionPath + "/sourceFolder";

    @Override
    public void setupFixtures()
        throws Exception
    {
        mockStore = _mockery.mock( IWebdavStore.class );
        mockReq = _mockery.mock( WebdavRequest.class );
        mockRes = _mockery.mock( WebdavResponse.class );
        mockTransaction = _mockery.mock( ITransaction.class );

    }

    @Test
    public void testMovingOfFileOrFolderIfReadOnlyIsTrue()
        throws Exception
    {

        _mockery.checking( new Expectations()
        {
            {
                one( mockRes ).sendError( WebdavStatus.SC_FORBIDDEN );
            }
        } );

        final ResourceLocks resLocks = new ResourceLocks();
        final DoDelete doDelete = new DoDelete( mockStore, resLocks, readOnly );
        final DoCopy doCopy = new DoCopy( mockStore, resLocks, doDelete, readOnly );

        final DoMove doMove = new DoMove( resLocks, doDelete, doCopy, readOnly );

        doMove.execute( mockTransaction, mockReq, mockRes );
    }

    @Test
    public void testMovingOfaFileIfDestinationNotPresent()
        throws Exception
    {

        _mockery.checking( new Expectations()
        {
            {
                one( mockReq ).getAttribute( "javax.servlet.include.request_uri" );
                will( returnValue( null ) );

                one( mockReq ).getPathInfo();
                will( returnValue( sourceFilePath ) );

                exactly( 2 ).of( mockReq )
                            .getHeader( "Destination" );
                will( returnValue( destFilePath ) );

                one( mockReq ).getServerName();
                will( returnValue( "serverName" ) );

                one( mockReq ).getContextPath();
                will( returnValue( "" ) );

                one( mockReq ).getPathInfo();
                will( returnValue( destFilePath ) );

                one( mockReq ).getServicePath();
                will( returnValue( "/servletPath" ) );

                one( mockReq ).getAttribute( "javax.servlet.include.request_uri" );
                will( returnValue( null ) );

                one( mockReq ).getPathInfo();
                will( returnValue( sourceFilePath ) );

                one( mockReq ).getHeader( "Overwrite" );
                will( returnValue( "F" ) );

                final StoredObject sourceFileSo = initFileStoredObject( resourceContent );

                one( mockStore ).getStoredObject( mockTransaction, sourceFilePath );
                will( returnValue( sourceFileSo ) );

                StoredObject destFileSo = null;

                one( mockStore ).getStoredObject( mockTransaction, destFilePath );
                will( returnValue( destFileSo ) );

                one( mockRes ).setStatus( WebdavStatus.SC_CREATED );

                one( mockStore ).getStoredObject( mockTransaction, sourceFilePath );
                will( returnValue( sourceFileSo ) );

                one( mockStore ).createResource( mockTransaction, destFilePath );

                one( mockStore ).getResourceContent( mockTransaction, sourceFilePath );
                will( returnValue( bais ) );

                one( mockStore ).setResourceContent( mockTransaction, destFilePath, bais, resourceLength );
                will( returnValue( 8L ) );

                destFileSo = initFileStoredObject( resourceContent );

                one( mockStore ).getStoredObject( mockTransaction, destFilePath );
                will( returnValue( destFileSo ) );

                one( mockRes ).setStatus( WebdavStatus.SC_NO_CONTENT );

                one( mockStore ).getStoredObject( mockTransaction, sourceFilePath );
                will( returnValue( sourceFileSo ) );

                one( mockStore ).removeObject( mockTransaction, sourceFilePath );
            }
        } );

        final ResourceLocks resLocks = new ResourceLocks();
        final DoDelete doDelete = new DoDelete( mockStore, resLocks, !readOnly );
        final DoCopy doCopy = new DoCopy( mockStore, resLocks, doDelete, !readOnly );

        final DoMove doMove = new DoMove( resLocks, doDelete, doCopy, !readOnly );

        doMove.execute( mockTransaction, mockReq, mockRes );
    }

    @Test
    public void testMovingOfaFileIfDestinationIsPresentAndOverwriteFalse()
        throws Exception
    {

        _mockery.checking( new Expectations()
        {
            {
                one( mockReq ).getAttribute( "javax.servlet.include.request_uri" );
                will( returnValue( null ) );

                one( mockReq ).getPathInfo();
                will( returnValue( sourceFilePath ) );

                exactly( 2 ).of( mockReq )
                            .getHeader( "Destination" );
                will( returnValue( destFilePath ) );

                one( mockReq ).getServerName();
                will( returnValue( "server_name" ) );

                one( mockReq ).getContextPath();
                will( returnValue( "" ) );

                one( mockReq ).getPathInfo();
                will( returnValue( destFilePath ) );

                one( mockReq ).getServicePath();
                will( returnValue( "servlet_path" ) );

                one( mockReq ).getAttribute( "javax.servlet.include.request_uri" );
                will( returnValue( null ) );

                one( mockReq ).getPathInfo();
                will( returnValue( sourceFilePath ) );

                one( mockReq ).getHeader( "Overwrite" );
                will( returnValue( "F" ) );

                final StoredObject sourceFileSo = initFileStoredObject( resourceContent );

                one( mockStore ).getStoredObject( mockTransaction, sourceFilePath );
                will( returnValue( sourceFileSo ) );

                final StoredObject destFileSo = initFileStoredObject( resourceContent );

                one( mockStore ).getStoredObject( mockTransaction, destFilePath );
                will( returnValue( destFileSo ) );

                one( mockRes ).sendError( WebdavStatus.SC_PRECONDITION_FAILED );

            }
        } );

        final ResourceLocks resLocks = new ResourceLocks();
        final DoDelete doDelete = new DoDelete( mockStore, resLocks, !readOnly );
        final DoCopy doCopy = new DoCopy( mockStore, resLocks, doDelete, !readOnly );

        final DoMove doMove = new DoMove( resLocks, doDelete, doCopy, !readOnly );

        doMove.execute( mockTransaction, mockReq, mockRes );
    }

    @Test
    public void testMovingOfaFileIfDestinationIsPresentAndOverwriteTrue()
        throws Exception
    {

        _mockery.checking( new Expectations()
        {
            {
                one( mockReq ).getAttribute( "javax.servlet.include.request_uri" );
                will( returnValue( null ) );

                one( mockReq ).getPathInfo();
                will( returnValue( sourceFilePath ) );

                exactly( 2 ).of( mockReq )
                            .getHeader( "Destination" );
                will( returnValue( destFilePath ) );

                one( mockReq ).getServerName();
                will( returnValue( "server_name" ) );

                one( mockReq ).getContextPath();
                will( returnValue( "" ) );

                one( mockReq ).getPathInfo();
                will( returnValue( destFilePath ) );

                one( mockReq ).getServicePath();
                will( returnValue( "servlet_path" ) );

                one( mockReq ).getAttribute( "javax.servlet.include.request_uri" );
                will( returnValue( null ) );

                one( mockReq ).getPathInfo();
                will( returnValue( sourceFilePath ) );

                one( mockReq ).getHeader( "Overwrite" );
                will( returnValue( "T" ) );

                final StoredObject sourceFileSo = initFileStoredObject( resourceContent );

                one( mockStore ).getStoredObject( mockTransaction, sourceFilePath );
                will( returnValue( sourceFileSo ) );

                final StoredObject destFileSo = initFileStoredObject( resourceContent );

                one( mockStore ).getStoredObject( mockTransaction, destFilePath );
                will( returnValue( destFileSo ) );

                one( mockRes ).setStatus( WebdavStatus.SC_NO_CONTENT );

                one( mockStore ).getStoredObject( mockTransaction, destFilePath );
                will( returnValue( destFileSo ) );

                one( mockStore ).removeObject( mockTransaction, destFilePath );

                one( mockStore ).getStoredObject( mockTransaction, sourceFilePath );
                will( returnValue( sourceFileSo ) );

                one( mockStore ).createResource( mockTransaction, destFilePath );

                one( mockStore ).getResourceContent( mockTransaction, sourceFilePath );
                will( returnValue( bais ) );

                one( mockStore ).setResourceContent( mockTransaction, destFilePath, bais, resourceLength );
                will( returnValue( 8L ) );

                one( mockStore ).getStoredObject( mockTransaction, destFilePath );
                will( returnValue( destFileSo ) );

                one( mockRes ).setStatus( WebdavStatus.SC_NO_CONTENT );

                one( mockStore ).getStoredObject( mockTransaction, sourceFilePath );
                will( returnValue( sourceFileSo ) );

                one( mockStore ).removeObject( mockTransaction, sourceFilePath );
            }
        } );

        final ResourceLocks resLocks = new ResourceLocks();
        final DoDelete doDelete = new DoDelete( mockStore, resLocks, !readOnly );
        final DoCopy doCopy = new DoCopy( mockStore, resLocks, doDelete, !readOnly );

        final DoMove doMove = new DoMove( resLocks, doDelete, doCopy, !readOnly );

        doMove.execute( mockTransaction, mockReq, mockRes );
    }

    @Test
    public void testMovingOfaFileIfSourceNotPresent()
        throws Exception
    {

        _mockery.checking( new Expectations()
        {
            {
                one( mockReq ).getAttribute( "javax.servlet.include.request_uri" );
                will( returnValue( null ) );

                one( mockReq ).getPathInfo();
                will( returnValue( sourceFilePath ) );

                exactly( 2 ).of( mockReq )
                            .getHeader( "Destination" );
                will( returnValue( destFilePath ) );

                one( mockReq ).getServerName();
                will( returnValue( "server_name" ) );

                one( mockReq ).getContextPath();
                will( returnValue( "" ) );

                one( mockReq ).getPathInfo();
                will( returnValue( destFilePath ) );

                one( mockReq ).getServicePath();
                will( returnValue( "servlet_path" ) );

                one( mockReq ).getAttribute( "javax.servlet.include.request_uri" );
                will( returnValue( null ) );

                one( mockReq ).getPathInfo();
                will( returnValue( sourceFilePath ) );

                one( mockReq ).getHeader( "Overwrite" );
                will( returnValue( "F" ) );

                final StoredObject sourceFileSo = null;

                one( mockStore ).getStoredObject( mockTransaction, sourceFilePath );
                will( returnValue( sourceFileSo ) );

                one( mockRes ).sendError( WebdavStatus.SC_NOT_FOUND );
            }
        } );

        final ResourceLocks resLocks = new ResourceLocks();
        final DoDelete doDelete = new DoDelete( mockStore, resLocks, !readOnly );
        final DoCopy doCopy = new DoCopy( mockStore, resLocks, doDelete, !readOnly );

        final DoMove doMove = new DoMove( resLocks, doDelete, doCopy, !readOnly );

        doMove.execute( mockTransaction, mockReq, mockRes );
    }

    @Test
    public void testMovingIfSourcePathEqualsDestinationPath()
        throws Exception
    {

        _mockery.checking( new Expectations()
        {
            {
                one( mockReq ).getAttribute( "javax.servlet.include.request_uri" );
                will( returnValue( null ) );

                one( mockReq ).getPathInfo();
                will( returnValue( destFilePath ) );

                exactly( 2 ).of( mockReq )
                            .getHeader( "Destination" );
                will( returnValue( destFilePath ) );

                one( mockReq ).getServerName();
                will( returnValue( "server_name" ) );

                one( mockReq ).getContextPath();
                will( returnValue( "" ) );

                one( mockReq ).getPathInfo();
                will( returnValue( destFilePath ) );

                one( mockReq ).getServicePath();
                will( returnValue( "servlet_path" ) );

                one( mockReq ).getAttribute( "javax.servlet.include.request_uri" );
                will( returnValue( null ) );

                one( mockReq ).getPathInfo();
                will( returnValue( destFilePath ) );

                one( mockRes ).sendError( WebdavStatus.SC_FORBIDDEN );
            }
        } );

        final ResourceLocks resLocks = new ResourceLocks();
        final DoDelete doDelete = new DoDelete( mockStore, resLocks, !readOnly );
        final DoCopy doCopy = new DoCopy( mockStore, resLocks, doDelete, !readOnly );

        final DoMove doMove = new DoMove( resLocks, doDelete, doCopy, !readOnly );

        doMove.execute( mockTransaction, mockReq, mockRes );
    }

    @Test
    public void testMovingOfaCollectionIfDestinationIsNotPresent()
        throws Exception
    {

        _mockery.checking( new Expectations()
        {
            {
                one( mockReq ).getAttribute( "javax.servlet.include.request_uri" );
                will( returnValue( null ) );

                one( mockReq ).getPathInfo();
                will( returnValue( sourceCollectionPath ) );

                exactly( 2 ).of( mockReq )
                            .getHeader( "Destination" );
                will( returnValue( destCollectionPath ) );

                one( mockReq ).getServerName();
                will( returnValue( "server_name" ) );

                one( mockReq ).getContextPath();
                will( returnValue( "" ) );

                one( mockReq ).getPathInfo();
                will( returnValue( destCollectionPath ) );

                one( mockReq ).getServicePath();
                will( returnValue( "servlet_path" ) );

                one( mockReq ).getAttribute( "javax.servlet.include.request_uri" );
                will( returnValue( null ) );

                one( mockReq ).getPathInfo();
                will( returnValue( sourceCollectionPath ) );

                one( mockReq ).getHeader( "Overwrite" );
                will( returnValue( "F" ) );

                final StoredObject sourceCollectionSo = initFolderStoredObject();

                one( mockStore ).getStoredObject( mockTransaction, sourceCollectionPath );
                will( returnValue( sourceCollectionSo ) );

                final StoredObject destCollectionSo = null;

                one( mockStore ).getStoredObject( mockTransaction, destCollectionPath );
                will( returnValue( destCollectionSo ) );

                one( mockRes ).setStatus( WebdavStatus.SC_CREATED );

                one( mockStore ).getStoredObject( mockTransaction, sourceCollectionPath );
                will( returnValue( sourceCollectionSo ) );

                one( mockStore ).createFolder( mockTransaction, destCollectionPath );

                one( mockReq ).getHeader( "Depth" );
                will( returnValue( null ) );

                String[] sourceChildren = new String[] { "sourceFile" };

                one( mockStore ).getChildrenNames( mockTransaction, sourceCollectionPath );
                will( returnValue( sourceChildren ) );

                final StoredObject sourceFileSo = initFileStoredObject( resourceContent );

                one( mockStore ).getStoredObject( mockTransaction, sourceCollectionPath + "/sourceFile" );
                will( returnValue( sourceFileSo ) );

                one( mockStore ).createResource( mockTransaction, destCollectionPath + "/sourceFile" );

                one( mockStore ).getResourceContent( mockTransaction, sourceCollectionPath + "/sourceFile" );
                will( returnValue( bais ) );

                one( mockStore ).setResourceContent( mockTransaction, destCollectionPath + "/sourceFile", bais, resourceLength );
                will( returnValue( 8L ) );

                final StoredObject movedSo = initFileStoredObject( resourceContent );

                one( mockStore ).getStoredObject( mockTransaction, destCollectionPath + "/sourceFile" );
                will( returnValue( movedSo ) );

                one( mockRes ).setStatus( WebdavStatus.SC_NO_CONTENT );

                one( mockStore ).getStoredObject( mockTransaction, sourceCollectionPath );
                will( returnValue( sourceCollectionSo ) );

                sourceChildren = new String[] { "sourceFile" };

                one( mockStore ).getChildrenNames( mockTransaction, sourceCollectionPath );
                will( returnValue( sourceChildren ) );

                one( mockStore ).getStoredObject( mockTransaction, sourceFilePath );
                will( returnValue( sourceFileSo ) );

                one( mockStore ).removeObject( mockTransaction, sourceFilePath );

                one( mockStore ).removeObject( mockTransaction, sourceCollectionPath );
            }
        } );

        final ResourceLocks resLocks = new ResourceLocks();
        final DoDelete doDelete = new DoDelete( mockStore, resLocks, !readOnly );
        final DoCopy doCopy = new DoCopy( mockStore, resLocks, doDelete, !readOnly );

        final DoMove doMove = new DoMove( resLocks, doDelete, doCopy, !readOnly );

        doMove.execute( mockTransaction, mockReq, mockRes );
    }

    @Test
    public void testMovingOfaCollectionIfDestinationIsPresentAndOverwriteFalse()
        throws Exception
    {

        _mockery.checking( new Expectations()
        {
            {
                one( mockReq ).getAttribute( "javax.servlet.include.request_uri" );
                will( returnValue( null ) );

                one( mockReq ).getPathInfo();
                will( returnValue( sourceCollectionPath ) );

                exactly( 2 ).of( mockReq )
                            .getHeader( "Destination" );
                will( returnValue( destCollectionPath ) );

                one( mockReq ).getServerName();
                will( returnValue( "server_name" ) );

                one( mockReq ).getContextPath();
                will( returnValue( "" ) );

                one( mockReq ).getPathInfo();
                will( returnValue( destCollectionPath ) );

                one( mockReq ).getServicePath();
                will( returnValue( "servlet_path" ) );

                one( mockReq ).getAttribute( "javax.servlet.include.request_uri" );
                will( returnValue( null ) );

                one( mockReq ).getPathInfo();
                will( returnValue( sourceCollectionPath ) );

                one( mockReq ).getHeader( "Overwrite" );
                will( returnValue( "F" ) );

                final StoredObject sourceCollectionSo = initFolderStoredObject();

                one( mockStore ).getStoredObject( mockTransaction, sourceCollectionPath );
                will( returnValue( sourceCollectionSo ) );

                final StoredObject destCollectionSo = initFolderStoredObject();

                one( mockStore ).getStoredObject( mockTransaction, destCollectionPath );
                will( returnValue( destCollectionSo ) );

                one( mockRes ).sendError( WebdavStatus.SC_PRECONDITION_FAILED );
            }
        } );

        final ResourceLocks resLocks = new ResourceLocks();
        final DoDelete doDelete = new DoDelete( mockStore, resLocks, !readOnly );
        final DoCopy doCopy = new DoCopy( mockStore, resLocks, doDelete, !readOnly );

        final DoMove doMove = new DoMove( resLocks, doDelete, doCopy, !readOnly );

        doMove.execute( mockTransaction, mockReq, mockRes );
    }

    @Test
    public void testMovingOfaCollectionIfDestinationIsPresentAndOverwriteTrue()
        throws Exception
    {

        _mockery.checking( new Expectations()
        {
            {
                one( mockReq ).getAttribute( "javax.servlet.include.request_uri" );
                will( returnValue( null ) );

                one( mockReq ).getPathInfo();
                will( returnValue( sourceCollectionPath ) );

                exactly( 2 ).of( mockReq )
                            .getHeader( "Destination" );
                will( returnValue( overwritePath ) );

                one( mockReq ).getServerName();
                will( returnValue( "server_name" ) );

                one( mockReq ).getContextPath();
                will( returnValue( "" ) );

                one( mockReq ).getPathInfo();
                will( returnValue( overwritePath ) );

                one( mockReq ).getServicePath();
                will( returnValue( "servlet_path" ) );

                one( mockReq ).getAttribute( "javax.servlet.include.request_uri" );
                will( returnValue( null ) );

                one( mockReq ).getPathInfo();
                will( returnValue( sourceCollectionPath ) );

                one( mockReq ).getHeader( "Overwrite" );
                will( returnValue( "T" ) );

                final StoredObject sourceCollectionSo = initFolderStoredObject();

                one( mockStore ).getStoredObject( mockTransaction, sourceCollectionPath );
                will( returnValue( sourceCollectionSo ) );

                final StoredObject destCollectionSo = initFolderStoredObject();

                one( mockStore ).getStoredObject( mockTransaction, overwritePath );
                will( returnValue( destCollectionSo ) );

                one( mockRes ).setStatus( WebdavStatus.SC_NO_CONTENT );

                one( mockStore ).getStoredObject( mockTransaction, overwritePath );
                will( returnValue( destCollectionSo ) );

                one( mockStore ).getChildrenNames( mockTransaction, overwritePath );
                will( returnValue( destChildren ) );

                final StoredObject destFileSo = initFileStoredObject( resourceContent );

                one( mockStore ).getStoredObject( mockTransaction, overwritePath + "/destFile" );
                will( returnValue( destFileSo ) );

                one( mockStore ).removeObject( mockTransaction, overwritePath + "/destFile" );

                one( mockStore ).removeObject( mockTransaction, overwritePath );

                one( mockStore ).getStoredObject( mockTransaction, sourceCollectionPath );
                will( returnValue( sourceCollectionSo ) );

                one( mockStore ).createFolder( mockTransaction, overwritePath );

                one( mockReq ).getHeader( "Depth" );
                will( returnValue( null ) );

                one( mockStore ).getChildrenNames( mockTransaction, sourceCollectionPath );
                will( returnValue( sourceChildren ) );

                final StoredObject sourceFileSo = initFileStoredObject( resourceContent );

                // failures start here...
                one( mockStore ).getStoredObject( mockTransaction, sourceFilePath );
                will( returnValue( sourceFileSo ) );

                one( mockStore ).createResource( mockTransaction, overwritePath + "/sourceFile" );

                one( mockStore ).getResourceContent( mockTransaction, sourceFilePath );
                will( returnValue( bais ) );

                one( mockStore ).setResourceContent( mockTransaction, overwritePath + "/sourceFile", bais, resourceLength );

                final StoredObject movedSo = initFileStoredObject( resourceContent );

                one( mockStore ).getStoredObject( mockTransaction, overwritePath + "/sourceFile" );
                will( returnValue( movedSo ) );

                one( mockRes ).setStatus( WebdavStatus.SC_NO_CONTENT );

                one( mockStore ).getStoredObject( mockTransaction, sourceCollectionPath );
                will( returnValue( sourceCollectionSo ) );

                sourceChildren = new String[] { "sourceFile" };

                one( mockStore ).getChildrenNames( mockTransaction, sourceCollectionPath );
                will( returnValue( sourceChildren ) );

                one( mockStore ).getStoredObject( mockTransaction, sourceFilePath );
                will( returnValue( sourceFileSo ) );

                one( mockStore ).removeObject( mockTransaction, sourceFilePath );

                one( mockStore ).removeObject( mockTransaction, sourceCollectionPath );
            }
        } );

        final ResourceLocks resLocks = new ResourceLocks();
        final DoDelete doDelete = new DoDelete( mockStore, resLocks, !readOnly );
        final DoCopy doCopy = new DoCopy( mockStore, resLocks, doDelete, !readOnly );

        final DoMove doMove = new DoMove( resLocks, doDelete, doCopy, !readOnly );

        doMove.execute( mockTransaction, mockReq, mockRes );
    }

}


text:
var EventEmitter = require('events').EventEmitter,
    assert = require('assert'),
    util = require('util'),
    _ = require('underscore'),
    extend = require('../lib/util').extend;

function Controller() {
  EventEmitter.call(this);
}
util.inherits(Controller, EventEmitter);

Controller.extend = extend;

MyController = Controller.extend({
  foo: 'bar'
});

controllerInstance = new MyController();

assert.equal(controllerInstance.foo, 'bar');
assert.equal(MyController.prototype.foo, 'bar');
assert.equal(controllerInstance.on, EventEmitter.prototype.on);

// // Can we access prototype functions defined to base class after
// // class has been defined?

// assert.throws(function() {
//   controllerInstance.getGlobal();
// });

// Controller.prototype.getGlobal = function() {return "bar";};

// assert.equal(controllerInstance.getGlobal(), 'bar');

// // Does extend handle the process of applying options to instance?

// instanceWithOptions = new Controller({resource: 'fig'});

// assert.notEqual(instanceWithOptions.resource, 'fig');

// // Are configuration options available to parent class in grand child

// function Parent() {
//   for (var i = this.constructor.uses.length - 1; i >= 0; i--) {
//     this.constructor.uses[i](this);
//   }
// }

// Parent.uses = [];
// Parent.use = function(pluginFn) {
//   this.uses.push(pluginFn);
// };

// Parent.use(function(i) {
//   i.visited = i.visited || '';
//   i.visited += ' parent';
// });

// Parent.extend = extend;

// Child = Parent.extend({});

// GrandChild = Child.extend({
//   foo: 'bar'
// });

// GrandChild.use(function(i) {
//   i.visited = i.visited || '';
//   i.visited += ' grand child';
// });

// // GrandChild.use = [function(i){ console.log('gradchild plugin'); }];

// var i = new GrandChild({});

// console.log(i.visited);

// ////

// var Foo = {};
// Foo.listen = function() { this.emit('listen'); };
// // util.inherits(Foo.prototype, EventEmitter);
// // Foo.prototype.__proto__ = EventEmitter.prototype;
// EventEmitter.call(Foo);
// _.extend(Foo, EventEmitter.prototype);

// assert.equal(Foo.on, EventEmitter.prototype.on);

// Foo.on('listen', function() {console.log('* listen');});
// Foo.listen();

redpajama_set_name: RedPajamaGithub


text:
using asi::runtimecommandengine::CommandWithoutParams;
using std::vector;
using std::string;
using ::testing::Return;
using ::testing::Values;
using ::testing::Value;

TEST(CommandWithoutParamsTests, Evaluate_NoParamsNoTokens_FalseUDUD)
{
	CallbackTester cbt;
	CommandWithoutParams cmd({"sig1"}, "description", cbt.GetCallback());
	vector<string> input_tokens;

	auto const return_val = cmd.Evaluate(input_tokens);

	EXPECT_EQ(false, std::get<0>(return_val));
	EXPECT_EQ(false, cbt.WasCallbackCalled());
}

TEST(CommandWithoutParamsTests, Evaluate_NoParamsWrongToken_FalseUDUD)
{
	CallbackTester cbt;
	CommandWithoutParams cmd({"sig1"}, "description", cbt.GetCallback());
	vector<string> input_tokens;
	input_tokens.push_back("wrong_token");

	auto const return_val = cmd.Evaluate(input_tokens);

	EXPECT_EQ(false, std::get<0>(return_val));
	EXPECT_EQ(false, cbt.WasCallbackCalled());
}

TEST(CommandWithoutParamsTests, Evaluate_NoParamsRightToken_CallbackCalledTrue0CorrectString)
{
	static string const method_name("sig1");
	CallbackTester cbt;
	CommandWithoutParams cmd({method_name}, "description", cbt.GetCallback());
	vector<string> input_tokens;
	input_tokens.push_back(method_name);
	CallbackTester ct;

	auto const return_val = cmd.Evaluate(input_tokens);

	EXPECT_EQ(true, std::get<0>(return_val));
	EXPECT_EQ(0, std::get<1>(return_val));
	EXPECT_STREQ(string("received command \"" + method_name + "\"").c_str(), std::get<2>(return_val).c_str());
	EXPECT_EQ(true, cbt.WasCallbackCalled());
}

TEST(CommandWithoutParamsTests, ConstructorWithVector_2Names_SignatureRetrievable)
{
	vector<string> method_names;
	method_names.push_back("a");
	method_names.push_back("b");
	CallbackTester cbt;
	CommandWithoutParams cmd(method_names, "description", cbt.GetCallback());

	string result0 = cmd.GetSignatureExpectation(0)[0];
	string result1 = cmd.GetSignatureExpectation(1)[0];
	EXPECT_STREQ("a", result0.c_str());
	EXPECT_STREQ("b", result1.c_str());
	EXPECT_EQ(false, cbt.WasCallbackCalled());
}


text:
//
//  RKDynamicMapping.m
//  RestKit
//
//  Created by Blake Watters on 7/28/11.
//  Copyright (c) 2009-2012 RestKit. All rights reserved.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//

#import <RestKit/ObjectMapping/RKDynamicMapping.h>
#import <RestKit/ObjectMapping/RKObjectMappingMatcher.h>
#import <RestKit/Support/RKLog.h>

// Set Logging Component
#undef RKLogComponent
#define RKLogComponent RKlcl_cRestKitObjectMapping

@interface RKDynamicMapping ()
@property (nonatomic, strong) NSMutableArray *mutableMatchers;
@property (nonatomic, strong) NSArray *possibleObjectMappings;
@property (nonatomic, copy) RKObjectMapping *(^objectMappingForRepresentationBlock)(id representation);
@end

@implementation RKDynamicMapping

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.mutableMatchers = [NSMutableArray new];
        self.possibleObjectMappings = [NSArray new];
    }

    return self;
}

- (NSArray *)matchers
{
    return [self.mutableMatchers copy];
}

- (NSArray *)objectMappings
{
    return self.possibleObjectMappings;
}

- (void)addMatcher:(RKObjectMappingMatcher *)matcher
{
    NSParameterAssert(matcher);
    if ([self.mutableMatchers containsObject:matcher]) {
        [self.mutableMatchers removeObject:matcher];
        [self.mutableMatchers insertObject:matcher atIndex:0];
    } else {
        [self.mutableMatchers addObject:matcher];

        NSArray *newPossibleMappings = [matcher possibleObjectMappings];
        if (newPossibleMappings.count > 0) {
            self.possibleObjectMappings = [self.possibleObjectMappings arrayByAddingObjectsFromArray:newPossibleMappings];
        }
    }
}

- (void)removeMatcher:(RKObjectMappingMatcher *)matcher
{
    NSParameterAssert(matcher);

    if ([self.mutableMatchers containsObject:matcher]) {
        NSMutableArray *mappings = [self.possibleObjectMappings mutableCopy];
        for (RKObjectMapping *mapping in [matcher possibleObjectMappings]) {
            /* removeObject will remove *all* instances; if we have dups we just want to remove one */
            NSUInteger idx = [mappings indexOfObject:mapping];
            if (idx != NSNotFound)
                [mappings removeObjectAtIndex:idx];
        }
        self.possibleObjectMappings = [mappings copy];
        [self.mutableMatchers removeObject:matcher];
    }
}

- (RKObjectMapping *)objectMappingForRepresentation:(id)representation
{
    RKObjectMapping *mapping = nil;

    RKLogTrace(@"Performing dynamic object mapping for object representation: %@", representation);

    // Consult the declarative matchers first
    for (RKObjectMappingMatcher *matcher in self.mutableMatchers) {
        if ([matcher matches:representation]) {
            RKLogTrace(@"Found declarative match for matcher: %@.", matcher);
            return matcher.objectMapping;
        }
    }

    // Otherwise consult the block
    if (self.objectMappingForRepresentationBlock) {
        mapping = self.objectMappingForRepresentationBlock(representation);
        if (mapping) RKLogTrace(@"Determined concrete `RKObjectMapping` using object mapping for representation block");
    }

    return mapping;
}

- (BOOL)isEqualToMapping:(RKMapping *)otherMapping
{
    return (self == otherMapping);
}

@end


text:
bool PApp::_Test_FindMSB ()
{
	const BytesU	buf_size = SizeOf< Pipelines::FindMSB_SSBO >;

	// create resources
	auto	factory	= ms->GlobalSystems()->modulesFactory;

	GpuMsg::CreateFence		fence_ctor;
	syncManager->Send( fence_ctor );

	ModulePtr	cmd_buffer;
	CHECK_ERR( factory->Create(
					gpuIDs.commandBuffer,
					gpuThread->GlobalSystems(),
					CreateInfo::GpuCommandBuffer{},
					OUT cmd_buffer ) );
	cmdBuilder->Send( ModuleMsg::AttachModule{ cmd_buffer });

	ModulePtr	buffer;
	CHECK_ERR( factory->Create(
					gpuIDs.buffer,
					gpuThread->GlobalSystems(),
					CreateInfo::GpuBuffer{
						BufferDescription{ buf_size, EBufferUsage::Storage },
						EGpuMemory::CoherentWithCPU },
					OUT buffer ) );

	CreateInfo::PipelineTemplate	pt_ci;
	Pipelines::Create_findmsb( OUT pt_ci.descr );

	ModulePtr	pipeline_template;
	CHECK_ERR( factory->Create(
					PipelineTemplateModuleID,
					gpuThread->GlobalSystems(),
					pt_ci,
					OUT pipeline_template ) );
	ModuleUtils::Initialize({ pipeline_template });

	GpuMsg::CreateComputePipeline	cppl_ctor{ gpuIDs.pipeline, gpuThread };
	pipeline_template->Send( cppl_ctor );

	ModulePtr	pipeline	= *cppl_ctor.result;

	ModulePtr	resource_table;
	CHECK_ERR( factory->Create(
					gpuIDs.resourceTable,
					gpuThread->GlobalSystems(),
					CreateInfo::PipelineResourceTable{},
					OUT resource_table ) );

	resource_table->Send( ModuleMsg::AttachModule{ "pipeline", pipeline });
	resource_table->Send( GpuMsg::PipelineAttachBuffer{ "ssb", buffer, 0_b, buf_size });

	ModuleUtils::Initialize({ cmd_buffer, buffer, pipeline, resource_table });

	// build command buffer
	cmdBuilder->Send( GpuMsg::CmdBegin{ cmd_buffer });

	cmdBuilder->Send( GpuMsg::CmdBindComputePipeline{ pipeline });
	cmdBuilder->Send( GpuMsg::CmdBindComputeResourceTable{ resource_table });
	cmdBuilder->Send( GpuMsg::CmdDispatch{ uint3(1) });

	GpuMsg::CmdEnd	cmd_end;
	cmdBuilder->Send( cmd_end );

	// submit and sync
	gpuThread->Send( GpuMsg::SubmitCommands{ *cmd_end.result }.SetFence( *fence_ctor.result ));

	syncManager->Send( GpuMsg::ClientWaitFence{ *fence_ctor.result });

	// read from buffer
	BinaryArray	dst_data;	dst_data.Resize( usize(buf_size) );

	GpuMsg::ReadFromGpuMemory	read_cmd{ dst_data };
	buffer->Send( read_cmd );

	auto* st = Cast<const Pipelines::FindMSB_SSBO *>( read_cmd.result->ptr() );

	CHECK_ERR( st->results[0] == 31 );
	CHECK_ERR( st->results[1] == 30 );
	CHECK_ERR( st->results[2] == 28 );
	CHECK_ERR( st->results[3] == 26 );
	CHECK_ERR( st->results[4] == 24 );
	CHECK_ERR( st->results[5] == 22 );
	CHECK_ERR( st->results[6] == 20 );
	CHECK_ERR( st->results[7] == 18 );
	CHECK_ERR( st->results[8] == 16 );
	CHECK_ERR( st->results[9] == 18 );
	CHECK_ERR( st->results[10] == 20 );
	CHECK_ERR( st->results[11] == 22 );
	CHECK_ERR( st->results[12] == 24 );
	CHECK_ERR( st->results[13] == 26 );
	CHECK_ERR( st->results[14] == 28 );
	CHECK_ERR( st->results[15] == 30 );

	LOG( "FindMSB - OK", ELog::Info );
	return true;
}


text:
package com.opengamma.financial.aggregation;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Lists;
import com.opengamma.core.exchange.Exchange;
import com.opengamma.core.exchange.ExchangeSource;
import com.opengamma.core.position.Position;
import com.opengamma.core.position.impl.SimplePositionComparator;
import com.opengamma.core.region.Region;
import com.opengamma.core.region.RegionSource;
import com.opengamma.core.security.Security;
import com.opengamma.core.security.SecuritySource;
import com.opengamma.financial.security.FinancialSecurityUtils;
import com.opengamma.id.ExternalId;
import com.opengamma.id.UniqueId;
import com.opengamma.util.CompareUtils;

/**
 * Function to classify positions by Currency.
 *
 */
public class RegionAggregationFunction implements AggregationFunction<String> {
  private boolean _useAttributes;
  private boolean _includeEmptyCategories;

  private static final Logger s_logger = LoggerFactory.getLogger(RegionAggregationFunction.class);
  private static final String NAME = "Region";
  private static final String OTHER = "Other";
  private static final String NO_REGION = "N/A";

  private static final List<String> s_topLevelRegions = Arrays.asList("Africa", "Asia", "South America", "Europe");
  private static final List<String> s_specialCountriesRegions = Arrays.asList("United States", "Canada");
  private static final List<String> s_requiredEntries = Lists.newArrayList();

  static {
    s_requiredEntries.addAll(s_topLevelRegions);
    s_requiredEntries.addAll(s_specialCountriesRegions);
    s_requiredEntries.add(OTHER);
    s_requiredEntries.add(NO_REGION);
  }

  private SecuritySource _secSource;
  private RegionSource _regionSource;
  private ExchangeSource _exchangeSource;
  private final Comparator<Position> _comparator = new SimplePositionComparator();

  public RegionAggregationFunction(SecuritySource secSource, RegionSource regionSource, ExchangeSource exchangeSource) {
    this(secSource, regionSource, exchangeSource, false);
  }

  public RegionAggregationFunction(SecuritySource secSource, RegionSource regionSource, ExchangeSource exchangeSource, boolean useAttributes) {
    this(secSource, regionSource, exchangeSource, useAttributes, true);
  }

  public RegionAggregationFunction(SecuritySource secSource, RegionSource regionSource, ExchangeSource exchangeSource, boolean useAttributes, boolean includeEmptyCategories) {
    _secSource = secSource;
    _regionSource = regionSource;
    _exchangeSource = exchangeSource;
    _useAttributes = useAttributes;
    _includeEmptyCategories = includeEmptyCategories;
  }

  /**
   * Can use this when no RegionSource available and will get the ISO code instead of the pretty string.
   */
  public RegionAggregationFunction() {
    _regionSource = null;
    _exchangeSource = null;
  }

  @Override
  public String classifyPosition(Position position) {
    if (_useAttributes) {
      Map<String, String> attributes = position.getAttributes();
      s_logger.warn("attributes on " + position + " = " + attributes.entrySet());
      if (attributes.containsKey(getName())) {
        return attributes.get(getName());
      } else {
        return NO_REGION;
      }
    } else {
      try {
        Security security = position.getSecurityLink().getTarget();
        if (security == null) {
          security = position.getSecurityLink().resolve(_secSource);
        }
        ExternalId id = FinancialSecurityUtils.getRegion(security);
        if (_regionSource != null) {
          if (id != null) {
            Region highestLevelRegion = _regionSource.getHighestLevelRegion(id);
            if (highestLevelRegion != null) {
              return highestLevelRegion.getName();
            } else {
              return id.getValue();
            }
          } else if (_exchangeSource != null) {
            ExternalId exchangeId = FinancialSecurityUtils.getExchange(security);
            if (exchangeId != null) {
              Exchange exchange = _exchangeSource.getSingle(exchangeId);
              if (exchange == null) {
                s_logger.info("No exchange could be found with ID {}", exchangeId);
                return NO_REGION;
              }
              if (exchange.getRegionIdBundle() == null) {
                s_logger.info("Exchange " + exchange.getName() + " region bundle was null");
                return NO_REGION;
              }
              Region highestLevelRegion = _regionSource.getHighestLevelRegion(exchange.getRegionIdBundle());
              if (s_specialCountriesRegions.contains(highestLevelRegion.getName())) {
                return highestLevelRegion.getName();
              } else {
                Set<UniqueId> parentRegionIds = highestLevelRegion.getParentRegionIds();
                s_logger.info("got " + highestLevelRegion + ", looking for parent");
                String parent = findTopLevelRegion(parentRegionIds);
                s_logger.info("parent was " + parent);
                return parent;
              }
            }
          }
          return NO_REGION;
        } else {
          if (id != null) {
            return id.getValue();
          } else {
            return NO_REGION;
          }
        }
      } catch (UnsupportedOperationException ex) {
        return NO_REGION;
      }
    }
  }

  private String findTopLevelRegion(Set<?> parentRegions) {
    for (Object parentRegion : parentRegions) {
      Region region;
      if (parentRegion instanceof String) {
        region = _regionSource.get(UniqueId.parse((String) parentRegion));
      } else {
        region = _regionSource.get((UniqueId) parentRegion);
      }
      if (region != null) {
        if (s_topLevelRegions.contains(region.getName())) {
          return region.getName();
        }
      }
    }
    return OTHER;
  }

  public String getName() {
    return NAME;
  }

  @Override
  public Collection<String> getRequiredEntries() {
    if (_includeEmptyCategories) {
      return s_requiredEntries;
    } else {
      return Collections.emptyList();
    }
  }

  @Override
  public int compare(String o1, String o2) {
    return CompareUtils.compareByList(s_requiredEntries, o1, o2);
  }

  @Override
  public Comparator<Position> getPositionComparator() {
    return _comparator;
  }
}


text:
from time import time
# Здесь необходимо реализовать
# контекстный менеджер timer
# Он не принимает аргументов, после выполнения блока он должен вывести время выполнения в секундах
# Пример использования
# with timer():
#   sleep(5.5)
#
# После завершения блока должно вывестись в консоль примерно 5.5

class timer:
    def __init__(self):
        pass

    def __enter__(self):
        self.time = time()

    def __exit__(self, type, value, traceback):
        print(time() - self.time)


text:
//
//  BBBBookContentDataProvider.h
//  BBBIosApp
//
//  Created by Owen Worley, Tomek Kuźma, Eric Yuan on 29/07/2014.
//

#import <Foundation/Foundation.h>

/**
 *  Protocol describing classes that can return data from a book.
 */
@protocol BBBBookContentDataProvider <NSObject>

@required

/**
 *  Return data from a book given its key
 *
 *  @param book  A book object
 *  @param key   A key for the item in the book. Implementations are free to choose what constitutes
 * a 'key'
 *  @param error An error may be returned if data cannot
 *
 *  @return The data for the books key value
 */
- (NSData *) dataForBookWithISBN:(NSString *)isbn
                           token:(NSData *)token
                         fileURL:(NSURL *)fileURL
                             key:(NSString *)key
                        embedded:(BOOL)embedded
                           error:(NSError *__autoreleasing *)error;

/**
 *  Return an array of all 'keys' in a book. Implementations are free to choose what constitutes
 *  a 'key'
 *
 *  @param book Book for which to return keys
 *
 *  @return An NSArray of keys
 */
- (NSArray *) allKeysForBookWithToken:(NSData *)token
                                atURL:(NSURL *)url;
@end


text:
package org.apache.tika.parser.pdf;

public class VisalloParserConfig extends PDFParserConfig {
    @Override
    public void configure(PDF2XHTML pdf2XHTML) {
        super.configure(pdf2XHTML);

        // Better paragraph detection
        pdf2XHTML.setDropThreshold(2.0f);
    }
}


text:
package org.apache.cassandra.db.streaming;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterators;
import org.apache.cassandra.db.TypeSizes;
import org.apache.cassandra.io.IVersionedSerializer;
import org.apache.cassandra.io.sstable.Component;
import org.apache.cassandra.io.sstable.Descriptor;
import org.apache.cassandra.io.util.DataInputPlus;
import org.apache.cassandra.io.util.DataOutputPlus;

import java.io.IOException;
import java.util.*;

/**
 * SSTable components and their sizes to be tranfered via entire-sstable-streaming
 */
import org.apache.cassandra.io.util.File;

public final class ComponentManifest implements Iterable<Component>
{
    private static final List<Component> STREAM_COMPONENTS = ImmutableList.of(Component.DATA, Component.PRIMARY_INDEX, Component.STATS,
                                                                             Component.COMPRESSION_INFO, Component.FILTER, Component.SUMMARY,
                                                                             Component.DIGEST, Component.CRC);

    private final LinkedHashMap<Component, Long> components;

    public ComponentManifest(Map<Component, Long> components)
    {
        this.components = new LinkedHashMap<>(components);
    }

    @VisibleForTesting
    public static ComponentManifest create(Descriptor descriptor)
    {
        LinkedHashMap<Component, Long> components = new LinkedHashMap<>(STREAM_COMPONENTS.size());

        for (Component component : STREAM_COMPONENTS)
        {
            File file = new File(descriptor.filenameFor(component));
            if (!file.exists())
                continue;

            components.put(component, file.length());
        }

        return new ComponentManifest(components);
    }

    public long sizeOf(Component component)
    {
        Long size = components.get(component);
        if (size == null)
            throw new IllegalArgumentException("Component " + component + " is not present in the manifest");
        return size;
    }

    public long totalSize()
    {
        long totalSize = 0;
        for (Long size : components.values())
            totalSize += size;
        return totalSize;
    }

    public List<Component> components()
    {
        return new ArrayList<>(components.keySet());
    }

    @Override
    public boolean equals(Object o)
    {
        if (this == o)
            return true;

        if (!(o instanceof ComponentManifest))
            return false;

        ComponentManifest that = (ComponentManifest) o;
        return components.equals(that.components);
    }

    @Override
    public int hashCode()
    {
        return components.hashCode();
    }

    @Override
    public String toString()
    {
        return "ComponentManifest{" +
               "components=" + components +
               '}';
    }

    public static final IVersionedSerializer<ComponentManifest> serializer = new IVersionedSerializer<ComponentManifest>()
    {
        public void serialize(ComponentManifest manifest, DataOutputPlus out, int version) throws IOException
        {
            out.writeUnsignedVInt(manifest.components.size());
            for (Map.Entry<Component, Long> entry : manifest.components.entrySet())
            {
                out.writeUTF(entry.getKey().name);
                out.writeUnsignedVInt(entry.getValue());
            }
        }

        public ComponentManifest deserialize(DataInputPlus in, int version) throws IOException
        {
            int size = (int) in.readUnsignedVInt();

            LinkedHashMap<Component, Long> components = new LinkedHashMap<>(size);

            for (int i = 0; i < size; i++)
            {
                Component component = Component.parse(in.readUTF());
                long length = in.readUnsignedVInt();
                components.put(component, length);
            }

            return new ComponentManifest(components);
        }

        public long serializedSize(ComponentManifest manifest, int version)
        {
            long size = TypeSizes.sizeofUnsignedVInt(manifest.components.size());
            for (Map.Entry<Component, Long> entry : manifest.components.entrySet())
            {
                size += TypeSizes.sizeof(entry.getKey().name);
                size += TypeSizes.sizeofUnsignedVInt(entry.getValue());
            }
            return size;
        }
    };

    @Override
    public Iterator<Component> iterator()
    {
        return Iterators.unmodifiableIterator(components.keySet().iterator());
    }
}


text:
<?php

return [
    'acls' => [
        'update'     => 'ACL has been updated.',
        'sync-roles' => 'Role has been synced to :name metric.',
    ],

    'roles' => [
        'create' => 'Role :name has been created.',
        'update' => 'Role :name has been updated.',
        'delete' => 'Role :name has been deleted.',

        'delete-default-failed' => 'Unable to delete default role.',
        'reserved-word'         => 'Unable to use following word as role.',
    ],

    'themes' => [
        'update' => ':type theme has been updated.',
    ],
];


text:
import actionTypes from "../action types/itemDetailsActionsTypes";
import itemsService from "../services/itemsService";
import localizeService from "../services/localizeService";

const itemDetailsActions = {
    editItem(item) {
        const itemData = {isFolder: item.isFolder, iconUrl: item.iconUrl, thumbnailAvailable: item.thumbnailAvailable, thumbnailUrl: item.thumbnailUrl};
        let getItemDetails = () => item.isFolder
            ? itemsService.getFolderDetails(item.itemId)
            : itemsService.getFileDetails(item.itemId);
        return dispatch => {
            getItemDetails()
            .then(
                response => dispatch({
                    type: actionTypes.EDIT_ITEM,
                    data: {...response, ...itemData}
                }),
                reason => dispatch({
                    type: actionTypes.EDIT_ITEM_ERROR,
                    data: reason.data && reason.data.message ? reason.data.message : localizeService.getString("GenericErrorMessage")
                })
            );
        };
    },
    cancelEditItem() {
        return {
            type: actionTypes.CANCEL_EDIT_ITEM
        };
    },
    moveItem(item) {
        const itemData = {isFolder: item.isFolder, iconUrl: item.iconUrl, thumbnailAvailable: item.thumbnailAvailable, thumbnailUrl: item.thumbnailUrl};
        let getItemDetails = () => item.isFolder
            ? itemsService.getFolderDetails(item.itemId)
            : itemsService.getFileDetails(item.itemId);
        return dispatch => {
            getItemDetails()
            .then(
                response => dispatch({
                    type: actionTypes.MOVE_ITEM,
                    data: {...response, ...itemData}
                }),
                reason => dispatch({
                    type: actionTypes.SAVE_ITEM_ERROR,
                    data: reason.data && reason.data.message ? reason.data.message : localizeService.getString("GenericErrorMessage")
                })
            );
        };
    },
    moveFolder(sourceFolderId, destinationFolderId) {
        return dispatch => {
            itemsService.moveFolder(sourceFolderId, destinationFolderId)
            .then(
                () => {
                    dispatch({
                        type: actionTypes.ITEM_MOVED,
                    });
                },
                reason => {
                    reason.data && reason.data.message ? reason.data.message : localizeService.getString("GenericErrorMessage")
                }
            )
        };
    },
    moveFile(sourceFileId, destinationFolderId) {
        return dispatch => {
            itemsService.moveFile(sourceFileId, destinationFolderId)
            .then(
                () => dispatch({
                    type: actionTypes.ITEM_MOVED
                }),
                reason => {
                    reason.data && reason.data.message ? reason.data.message : localizeService.getString("GenericErrorMessage")
                }
            )
        }
    },
    cancelMoveItem() {
        return {
            type: actionTypes.CANCEL_MOVE_ITEM
        };
    },
    changeName(event) {
        return {
            type: actionTypes.CHANGE_NAME,
            data: event.target.value
        };
    },
    changeTitle(event) {
        return {
            type: actionTypes.CHANGE_TITLE,
            data: event.target.value
        };
    },
    changeDescription(event) {
        return {
            type: actionTypes.CHANGE_DESCRIPTION,
            data: event.target.value
        };
    },
    changePermissions(permissions) {
        return {
            type: actionTypes.CHANGE_PERMISSIONS,
            data: permissions
        };
    },
    setValidationErrors(validationErrors) {
        return {
            type: actionTypes.SET_VALIDATION_ERRORS,
            data: validationErrors
        };
    },
    saveItem(item) {
        let saveFunction = () => item.isFolder
            ? itemsService.saveFolderDetails(item)
            : itemsService.saveFileDetails(item);
        return dispatch => {
            saveFunction()
                .then(
                    () => dispatch({
                        type: actionTypes.ITEM_SAVED,
                        data: {
                            isFolder: item.isFolder,
                            itemId: item.isFolder ? item.folderId : item.fileId,
                            itemName: item.isFolder ? item.folderName : item.fileName
                        }
                    }),
                    reason => dispatch({
                        type: actionTypes.SAVE_ITEM_ERROR,
                        data: reason.data && reason.data.message ? reason.data.message : localizeService.getString("GenericErrorMessage")
                    })
                );
        };
    }
};

export default itemDetailsActions;


text:
using System;
using De.Osthus.Ambeth.Ioc;

namespace De.Osthus.Ambeth.Xml
{
    public interface IXmlTypeKey
    {
        String Name { get; }

        String Namespace { get; }
    }
}


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Login extends JY_Controller {

	function __construct() {
		parent::__construct();
		$this->load->model( 'admin_model' );
	}

	public function index() {
		$this->session->set_userdata('username', '');
		$this->load->view('login');
	}

	public function doLogin() {

		$username = $this->input->post('username', TRUE);
		$password = $this->input->post('password', TRUE);

		$password = md5($password);

		$admin = $this->admin_model->get_admin_by_username($username);

		$data = array();

		if ($admin && !empty($admin)) {
			if ($admin->password === $password) { //登录成功
				$data['code'] = 1;
				$data['msg'] = "登录成功";
				$this->session->set_userdata('username', $username);
				$this->session->set_userdata('isAdmin', $admin->isAdmin);
			} else { //密码错误
				$data['code'] = 0;
				$data['msg'] = "密码错误";
			}
		} else { //用户不存在
				$data['code'] = -1;
				$data['msg'] = "用户不存在";
		}

		$this->renderJSON(json_encode($data));
	}

	public function logout() {
		$this->session->set_userdata('username', '');
		$this->renderJSON("ok");
	}
}

/* End of file login.php */
/* Location: ./application/controllers/login.php */


text: from binint import *


text:
<phpunit colors="true" bootstrap="vendor/autoload.php">
    <testsuites>
        <testsuite name="UnitTests">
            <directory>tests/UnitTests</directory>
        </testsuite>
    </testsuites>
</phpunit>


text:
require_relative 'player'
require_relative 'die'
require_relative 'game_turn'

module DemoGame
  class Game
    attr_reader :title

    def initialize(title)
      @title = title.capitalize
      @players = []
    end

    def high_score_entry(player)
      "#{player.name.ljust(20, ".")} #{player.score}"
    end

    def load(from_file)
      File.readlines(from_file).each do |line|
        add_player(Player.from_csv(line))
      end
    end

    def save(to_file="save_game.txt")
      File.open(to_file, "w") do |file|
        file.puts "\n#{@title} High Scores:"
        @players.sort.each do |player|
          file.puts high_score_entry(player)
        end
      end
    end

    def add_player(player)
      @players << player
    end

    def total_points
      @players.inject(0) { |sum, player| sum += player.points }
    end

    def play(rounds)
      puts "There are #{@players.size} players in #{@title}"

      @players.each do |player|
        puts player
      end

      treasures = TreasureTrove::TREASURES
      puts "\nThere are #{treasures.size} treasures to be found:"
      treasures.each do |treasure|
        puts "A #{treasure.name} is worth #{treasure.points} points"
      end

      1.upto(rounds) do |round|
        puts "\nRound: #{round}"
        if block_given?
          break if yield
        end
        @players.each do |player|
          GameTurn.take_turn(player)
        end
      end
    end

    def print_name_and_health(player)
      puts "#{player.name} (#{player.health})"
    end

    def print_stats
      puts "\n#{@title} statistics:"
      puts "#{total_points} total points from treasures found"

      @players.each do |player|
        puts "\n#{player.name}'s point totals:"
        player.each_treasure do |treasure|
          puts "#{treasure.points} total #{treasure.name} points"
        end
        puts "#{player.points} grand total points"
      end

      puts "\nStrong:"
      @players.each do |p|
        print_name_and_health(p) if p.strong?
      end
      puts "\nWimpy:"
      @players.each do |p|
        print_name_and_health(p) if !p.strong?
      end

      puts "\n#{@title} High Scores:"
      @players.sort.each do |player|
        puts high_score_entry(player)
      end
    end
  end
end


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.endgame.binarypig</groupId>
  <artifactId>binarypig</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>binarypig</name>
  <url>http://maven.apache.org</url>
  <repositories>
    <repository>
      <id>cloudera</id>
      <url>https://repository.cloudera.com/artifactory/cloudera-repos/</url>
    </repository>
  </repositories>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.easymock</groupId>
      <artifactId>easymock</artifactId>
      <version>3.0</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <version>12.0</version>
    </dependency>

    <dependency>
      <groupId>org.apache.pig</groupId>
      <artifactId>pig</artifactId>
      <version>0.12.1</version>
    </dependency>

    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20090211</version>
    </dependency>
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.4</version>
    </dependency>
    <dependency>
      <groupId>org.apache.hadoop</groupId>
      <artifactId>hadoop-core</artifactId>
      <version>1.2.1</version>
    </dependency>
    <dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-mapper-asl</artifactId>
      <version>1.9.3</version>
    </dependency>
    <dependency>
      <groupId>com.googlecode.json-simple</groupId>
      <artifactId>json-simple</artifactId>
      <version>1.1</version>
    </dependency>
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-exec</artifactId>
      <version>1.1</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.5.8</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.5.8</version>
    </dependency>
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-compress</artifactId>
      <version>1.4.1</version>
    </dependency>
    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.2.2</version>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <configuration>
          <archive>
          </archive>
          <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
          </descriptorRefs>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>

        <!--
           Ref: http://stackoverflow.com/questions/7010665/testng-emma-cobertura-coverage-and-jdk-7-result-in-classformaterror-and-verif
        -->
        <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.12</version>
                <configuration>
                    <argLine>-XX:-UseSplitVerifier</argLine>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>cobertura-maven-plugin</artifactId>
                <version>2.5.1</version>
                <configuration>
                    <formats>
                        <format>xml</format>
                    </formats>
                </configuration>
                <executions>
                    <execution>
                        <phase>cobertura</phase>
                        <goals>
                            <goal>cobertura</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

    </plugins>
  </build>
</project>


text:
<?php

namespace Nelmio\ApiDocBundle\Tests\Functional\Entity;

use Symfony\Component\Serializer\Annotation\Groups;

/**
 * @author Guilhem N. <guilhem.niot@gmail.com>
 */
class Article
{
    /**
     * @Groups({"light"})
     */
    public function setAuthor(User $author)
    {
    }

    public function setContent(string $content)
    {
    }
}


text:
import io from 'socket.io-client';
import React from 'react';

import RaisedButton from 'material-ui/lib/raised-button';
import TextField from 'material-ui/lib/text-field';

//Etat du textField
const TYPING = 'typing';
const NOT_VALID = 'not_valid';
const NO_EMAIL = 'no email';

const buttonStyle = {
    display: 'block',
    marginLeft: 'auto',
    marginRight: 'auto',
    width: '70%',
    marginTop: '5%',
    height: '10vmin'
};

const labelStyle = {
    fontSize: '5vmin'
};

var MailBoxUser = React.createClass({
    getInitialState: function() {
        return {email: '', textFieldStatus:TYPING};
    },
    updateMail: function(e){
        this.setState({email: e.target.value, textFieldStatus:TYPING});
    },
    handleSubmit: function() {
        var email = this.state.email;
        if(email==''){
            this.setState({textFieldStatus:NO_EMAIL});
            return;
        }
        var regex = /\S+@\S+\.\S+/;
        if(!regex.test(email)){
            this.setState({textFieldStatus:NOT_VALID});
            return;
        }
        this.props.socket.emit("mail", email);
        this.props.goToEnd();
    },
    _generateErrorText: function(){
        if(this.state.textFieldStatus == NO_EMAIL){
            return "Entrez une adresse email";
        } else if(this.state.textFieldStatus == NOT_VALID){
            return "Adresse non valide";
        } else {
            return '';
        }
    },
    render: function() {
        var errorText = this._generateErrorText();
        return(

Partagez votre adresse email

                    <TextField
                        hintText="Adresse email"
                        onEnterKeyDown={this.handleSubmit}
                        onChange={this.updateMail}
                        inputStyle={labelStyle}
                        style={buttonStyle}
                        errorText={errorText}/>

                    <RaisedButton
                        label="Envoyer"
                        onMouseDown={this.handleSubmit}
                        style={buttonStyle}
                        labelStyle={labelStyle}/>

        );
    }
});

export default MailBoxUser;


text:
package gb

import (
	"errors"
	"fmt"
	"io"
	"path/filepath"
	"reflect"
	"testing"
)

func TestExecuteBuildAction(t *testing.T) {
	tests := []struct {
		pkg string
		err error
	}{{
		pkg: "a",
		err: nil,
	}, {
		pkg: "b", // actually command
		err: nil,
	}, {
		pkg: "c",
		err: nil,
	}, {
		pkg: "d.v1",
		err: nil,
	}, {
		pkg: "x",
		err: errors.New("import cycle detected: x -> y -> x"),
	}, {
		pkg: "h", // imports "blank", which is blank, see issue #131
		err: fmt.Errorf("no buildable Go source files in %s", filepath.Join(getwd(t), "testdata", "src", "blank")),
	}}

	for _, tt := range tests {
		ctx := testContext(t)
		pkg, err := ctx.ResolvePackage(tt.pkg)
		if !sameErr(err, tt.err) {
			t.Errorf("ctx.ResolvePackage(%v): want %v, got %v", tt.pkg, tt.err, err)
			continue
		}
		if err != nil {
			continue
		}
		action, err := BuildPackages(pkg)
		if err != nil {
			t.Errorf("BuildAction(%v): ", tt.pkg, err)
			continue
		}
		if err := Execute(action); !sameErr(err, tt.err) {
			t.Errorf("Execute(%v): want: %v, got %v", action.Name, tt.err, err)
		}
		ctx.Destroy()
	}
}

var niltask = TaskFn(func() error { return nil })

var executorTests = []struct {
	action *Action // root action
	err    error   // expected error
}{{
	action: &Action{
		Name: "no error",
		Task: niltask,
	},
}, {
	action: &Action{
		Name: "root error",
		Task: TaskFn(func() error {
			return io.EOF
		}),
	},
	err: io.EOF,
}, {
	action: &Action{
		Name: "child, child, error",
		Task: TaskFn(func() error {
			return fmt.Errorf("I should not have been called")
		}),
		Deps: []*Action{&Action{
			Name: "child, error",
			Task: niltask,
			Deps: []*Action{&Action{
				Name: "error",
				Task: TaskFn(func() error {
					return io.EOF
				}),
			}},
		}},
	},
	err: io.EOF,
}, {
	action: &Action{
		Name: "once only",
		Task: TaskFn(func() error {
			if c1 != 1 || c2 != 1 || c3 != 1 {
				return fmt.Errorf("unexpected count, c1: %v, c2: %v, c3: %v", c1, c2, c3)
			}
			return nil
		}),
		Deps: []*Action{createDag()},
	},
}, {
	action: &Action{
		Name: "failure count",
		Task: TaskFn(func() error {
			return fmt.Errorf("I should not have been called")
		}),
		Deps: []*Action{createFailDag()},
	},
	err: fmt.Errorf("task3 called 1 time"),
}}

func createDag() *Action {
	task1 := TaskFn(func() error { c1++; return nil })
	task2 := TaskFn(func() error { c2++; return nil })
	task3 := TaskFn(func() error { c3++; return nil })

	action1 := Action{Name: "c1", Task: task1}
	action2 := Action{Name: "c2", Task: task2}
	action3 := Action{Name: "c3", Task: task3}

	action1.Deps = append(action1.Deps, &action2, &action3)
	action2.Deps = append(action2.Deps, &action3)
	return &action1
}

func createFailDag() *Action {
	task1 := TaskFn(func() error { c1++; return nil })
	task2 := TaskFn(func() error { c2++; return fmt.Errorf("task2 called %v time", c2) })
	task3 := TaskFn(func() error { c3++; return fmt.Errorf("task3 called %v time", c3) })

	action1 := Action{Name: "c1", Task: task1}
	action2 := Action{Name: "c2", Task: task2}
	action3 := Action{Name: "c3", Task: task3}

	action1.Deps = append(action1.Deps, &action2, &action3)
	action2.Deps = append(action2.Deps, &action3)
	return &action1
}

var c1, c2, c3 int

func executeReset() {
	c1 = 0
	c2 = 0
	c3 = 0
	// reset executor test variables
}

func TestExecute(t *testing.T) {
	for _, tt := range executorTests {
		executeReset()
		got := Execute(tt.action)
		if !reflect.DeepEqual(got, tt.err) {
			t.Errorf("Execute: %v: want err: %v, got err %v", tt.action.Name, tt.err, got)
		}
	}
}

func testExecuteConcurrentN(t *testing.T, n int) {
	for _, tt := range executorTests {
		executeReset()
		got := ExecuteConcurrent(tt.action, n)
		if !reflect.DeepEqual(got, tt.err) {
			t.Errorf("ExecuteConcurrent(%v): %v: want err: %v, got err %v", n, tt.action.Name, tt.err, got)
		}
	}
}

func TestExecuteConcurrent1(t *testing.T) { testExecuteConcurrentN(t, 1) }
func TestExecuteConcurrent2(t *testing.T) { testExecuteConcurrentN(t, 2) }
func TestExecuteConcurrent4(t *testing.T) { testExecuteConcurrentN(t, 4) }
func TestExecuteConcurrent7(t *testing.T) { testExecuteConcurrentN(t, 7) }


text:
package com.wo2b.tu123.ui.settings;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.wo2b.sdk.common.util.ViewUtils;
import com.wo2b.sdk.common.util.io.FileUtils;
import com.wo2b.tu123.R;
import com.wo2b.tu123.global.AppCacheFactory;
import com.wo2b.tu123.model.storage.FileInfo;
import com.wo2b.wrapper.app.BaseFragmentListActivity;
import com.wo2b.wrapper.component.security.SecurityTu123;
import com.wo2b.wrapper.view.dialog.DialogText;

/**
 * 图片缓存管理
 *
 * @author 笨鸟不乖
 * @email benniaobuguai@gmail.com
 * @version 2.0.0
 * @date 2015-4-11
 */
public class StorageManagerActivity extends BaseFragmentListActivity<FileInfo>
{

	/** 缓存文件总大小 */
	private long mTotalLength = 0;
	/** 缓存文件总数量 */
	private int mTotalCount = 0;

	private static final int MSG_DELETE_FILE = 2;
	private static final int MSG_DELETE_FILE_OK = 3;
	private static final int MSG_DELETE_FILE_FAIL = 4;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.uc_setting_storage_mgr);
		initView();

		realExecuteFirstTime(null);
	}

	@Override
	protected void initView()
	{
		setActionBarTitle(R.string.storage_manager);
	}

	@Override
	protected boolean uiHandlerCallback(Message msg)
	{
		switch (msg.what)
		{
			case MSG_DELETE_FILE_OK:
			{
				int position = msg.arg1;
				realRemoveItem(position);

				mTotalCount--;

				FileInfo fileInfo = (FileInfo) msg.obj;
				showToast(getString(R.string.delete_ok, fileInfo.getName()));
				return true;
			}
			case MSG_DELETE_FILE_FAIL:
			{
				FileInfo fileInfo = (FileInfo) msg.obj;
				showToast(getString(R.string.delete_fail, fileInfo.getName()));
				return true;
			}
		}

		return super.uiHandlerCallback(msg);
	}

	@SuppressLint("NewApi")
	@Override
	protected boolean subHandlerCallback(Message msg)
	{
		switch (msg.what)
		{
			case MSG_DELETE_FILE:
			{
				int position = msg.arg1;
				FileInfo fileInfo = (FileInfo) msg.obj;
				// execute delete cmd.
				File file = new File(fileInfo.getPath());
				boolean isOk = false;
				if (file.isDirectory())
				{
					isOk = FileUtils.deleteDirectory(file);
				}

				if (isOk)
				{
					Message newMsg = getUiHandler().obtainMessage(MSG_DELETE_FILE_OK);
					newMsg.obj = fileInfo;
					newMsg.arg1 = position;

					newMsg.sendToTarget();
				}
				else
				{
					Message newMsg = getUiHandler().obtainMessage(MSG_DELETE_FILE_FAIL);
					newMsg.obj = fileInfo;
					newMsg.arg1 = position;

					newMsg.sendToTarget();
				}

				return true;
			}
		}

		return super.subHandlerCallback(msg);
	}

	@Override
	protected void realOnItemClick(final AdapterView<?> parent, View view, final int position, final long id)
	{
		final FileInfo fileInfo = (FileInfo) parent.getItemAtPosition(position);

		DialogText dialog = new DialogText(mContext);
		dialog.setMessage(getString(R.string.hint_confirm_delete, fileInfo.getName()));
		dialog.setCanceledOnTouchOutside(false);
		dialog.setPositiveButtonListener(R.string.ok, new AlertDialog.OnClickListener()
		{

			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				Message msg = Message.obtain(getSubHandler(), MSG_DELETE_FILE);
				msg.arg1 = position;
				msg.obj = fileInfo;
				getSubHandler().sendMessage(msg);

				dialog.dismiss();
			}
		});
		dialog.setNegativeButtonListener(R.string.no, new AlertDialog.OnClickListener()
		{

			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				dialog.dismiss();
			}
		});
		dialog.show();
	}

	@SuppressLint("NewApi")
	@Override
	protected BaseFragmentListActivity.XModel<FileInfo> realOnPullDown(BaseFragmentListActivity.RockyParams params)
	{
		List<FileInfo> fileInfos = new ArrayList<FileInfo>();
		List<File> folders = FileUtils.getFolderList(new AppCacheFactory().getAppImageDir());

		if (folders != null && !folders.isEmpty())
		{
			final int folderCount = folders.size();
			int fileCount = 0;
			int totalLength = 0;

			File folder = null;
			FileInfo info = null;
			int[] array = null;
			String folderName = null;

			for (int i = 0; i < folderCount; i++)
			{
				info = new FileInfo();
				folder = folders.get(i);

				folderName = SecurityTu123.decodeText(folder.getName());

				info.setName(folderName);
				info.setSize(FileUtils.getFolderSize(folder));
				info.setDisplaySize(FileUtils.formatByte(info.getSize()));
				info.setPath(folder.getPath());
				info.setLastModified(folder.lastModified());

				if (VERSION.SDK_INT > 8)
				{
					info.setTotalSpace(folder.getTotalSpace());
					info.setFreeSpace(folder.getFreeSpace());
					info.setUsableSpace(folder.getUsableSpace());
				}

				array = FileUtils.fileAndFolderCount(folder.getPath());
				info.setFileCount(array[0]);
				info.setFolderCount(array[1]);

				fileCount += array[0];
				totalLength += info.getSize();

				fileInfos.add(info);
			}

			mTotalCount = fileCount;
			mTotalLength = totalLength;
		}

		return XModel.list(fileInfos);
	}

	@Override
	protected BaseFragmentListActivity.XModel<FileInfo> realOnPullUp(BaseFragmentListActivity.RockyParams params)
	{
		return null;
	}

	@Override
	protected View realGetView(int position, View convertView, ViewGroup parent)
	{
		if (convertView == null)
		{
			convertView = LayoutInflater.from(mContext).inflate(R.layout.uc_setting_storage_list_item, parent, false);
		}

		ImageView image = ViewUtils.get(convertView, R.id.image);
		TextView nameTV = (TextView) convertView.findViewById(R.id.name);
		TextView descTV = (TextView) convertView.findViewById(R.id.desc);
		TextView picnumTV = (TextView) convertView.findViewById(R.id.picnum);

		FileInfo info = realGetItem(position);

		nameTV.setText(info.getName());
		descTV.setText(getString(R.string.size_1, info.getDisplaySize()));
		picnumTV.setText(getString(R.string.file_count_1, info.getFileCount()));

		return convertView;
	}

}


text:
package nz.govt.natlib.adapter.flac;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;

import nz.govt.natlib.adapter.AdapterUtils;
import nz.govt.natlib.adapter.DataAdapter;
import nz.govt.natlib.fx.DataSource;
import nz.govt.natlib.fx.FXUtil;
import nz.govt.natlib.fx.FileDataSource;
import nz.govt.natlib.fx.ParserContext;
import nz.govt.natlib.meta.log.LogManager;
import nz.govt.natlib.meta.log.LogMessage;

import org.kc7bfi.jflac.FLACDecoder;
import org.kc7bfi.jflac.FrameListener;
import org.kc7bfi.jflac.frame.Frame;
import org.kc7bfi.jflac.metadata.Application;
import org.kc7bfi.jflac.metadata.CueIndex;
import org.kc7bfi.jflac.metadata.CueSheet;
import org.kc7bfi.jflac.metadata.CueTrack;
import org.kc7bfi.jflac.metadata.Metadata;
import org.kc7bfi.jflac.metadata.Padding;
import org.kc7bfi.jflac.metadata.Picture;
import org.kc7bfi.jflac.metadata.SeekPoint;
import org.kc7bfi.jflac.metadata.SeekTable;
import org.kc7bfi.jflac.metadata.StreamInfo;
import org.kc7bfi.jflac.metadata.VorbisComment;

/**
 * FlacAdapter is responsible for extracting metadata out of FLAC (Free Lossless Audio Codec) files.
 *
 * For specification of FLAC files, see the URL:
 * http://flac.sourceforge.net/format.html
 *
 * This class makes a heavy use of the jFLAC (Java FLAC decoder) library available from:
 * http://jflac.sourceforge.net/
 * http://sourceforge.net/projects/jflac/files/
 *
 * @author Raghu Pushpakath
 * @version 1.0
 */
public class FlacAdapter extends DataAdapter {
	private static final char[] HEX_CHARS = "0123456789ABCDEF".toCharArray();

	/*
	 * A combined list of all Vorbis comment field names as defined by:
	 * http://xiph.org/vorbis/doc/v-comment.html
	 * and
	 * http://age.hobba.nl/audio/mirroredpages/ogg-tagging.html
	 */
	private static final String[] vorbisCommentFieldNames = new String[] {
		"ALBUM",
		"ARRANGER",
		"ARTIST",
		"AUTHOR",
		"COMMENT",
		"COMPOSER",
		"CONDUCTOR",
		"CONTACT",
		"COPYRIGHT",
		"DATE",
		"DESCRIPTION",
		"DISCNUMBER",
		"EAN-UPN", // This one needs to be searched in Vorbis comments as "EAN/UPN"
		"ENCODED-BY",
		"ENCODING",
		"ENSEMBLE",
		"GENRE",
		"ISRC",
		"LABEL",
		"LABELNO",
		"LICENSE",
		"LOCATION",
		"LYRICIST",
		"OPUS",
		"ORGANIZATION",
		"PART",
		"PARTNUMBER",
		"PERFORMER",
		"PUBLISHER",
		"SOURCEMEDIA",
		"TITLE",
		"TRACKNUMBER",
		"VERSION",
	};

	public FlacAdapter() {
	}

	public boolean acceptsFile(File file) {
		boolean isFlac = false;
		DataSource ftk = null;

		try {
			/*
			 * Make sure that the first 4 bytes form the string "fLaC" which
			 * is the signature for a FLAC file
			 */
			ftk = new FileDataSource(file);
			String header = FXUtil.getFixedStringValue(ftk, 4);
			isFlac = header.equalsIgnoreCase("fLaC");
		} catch (Exception ex) {
			isFlac = false;
		} finally {
			if (ftk != null)
				AdapterUtils.close(ftk);
		}

		// Log a message if this isn't a real FLAC file.
		if (!isFlac) {
			LogManager.getInstance().logMessage(LogMessage.INFO,
					file.getName() + " is not a FLAC file");
		}
		// Return true if we believe this is a FLAC; otherwise false.
		return isFlac;
	}

	public String getOutputType() {
		return "flac.dtd";
	}

	public String getInputType() {
		return "audio/x-flac";
	}

	public String getName() {
		return "FLAC File Adapter";
	}

	public String getDescription() {
		return "Adapts FLAC files";
	}

	public String getVersion() {
		return "1.0";
	}

	public void adapt(File file, ParserContext ctx) throws IOException {
		FLACDecoder decoder = null;
		InputStream stream = null;
		try {
			stream = new FileInputStream(file);
			decoder = new FLACDecoder(stream);
			decoder.addFrameListener(new FlacFrameListener(ctx));
			ctx.fireStartParseEvent("FLAC");
			writeFileInfo(file, ctx);
			ctx.fireStartParseEvent("FLACMETADATA");
			try {
				decoder.decode();
			} finally {
				ctx.fireEndParseEvent("FLACMETADATA");
				ctx.fireEndParseEvent("FLAC");
			}
		} catch (Throwable ex) {
			ex.printStackTrace();
		} finally {
			try {
				stream.close();
			} catch (IOException e) {
			}
		}
	}

	private void populateStreamInfo(ParserContext ctx, StreamInfo streamInfo) {
		ctx.fireStartParseEvent("STREAMINFO");
		ctx.fireParseEvent("MINBLOCKSIZE", streamInfo.getMinBlockSize());
		ctx.fireParseEvent("MAXBLOCKSIZE", streamInfo.getMaxBlockSize());
		ctx.fireParseEvent("MINFRAMESIZE", streamInfo.getMinFrameSize());
		ctx.fireParseEvent("MAXFRAMESIZE", streamInfo.getMaxFrameSize());
		ctx.fireParseEvent("SAMPLE-RATE", streamInfo.getSampleRate());
		ctx.fireParseEvent("SAMPLE-RATE-UNIT", "Hz");
		ctx.fireParseEvent("CHANNELS", streamInfo.getChannels());
		ctx.fireParseEvent("BITSPERSAMPLE", streamInfo.getBitsPerSample());
		ctx.fireParseEvent("TOTALSAMPLES", streamInfo.getTotalSamples());
		ctx.fireParseEvent("MD5", getMD5(streamInfo));
		ctx.fireEndParseEvent("STREAMINFO");
	}

	private void populateApplicationData(ParserContext ctx, Application application) {
		ctx.fireStartParseEvent("APPLICATION");
		ctx.fireParseEvent("APPLICATION-ID", getStringFromByteArrayOfInaccessibleField("id", application));
		ctx.fireEndParseEvent("APPLICATION");
	}

	private void populatePaddingData(ParserContext ctx, Padding padding) {
		ctx.fireStartParseEvent("PADDING");
		ctx.fireParseEvent("LENGTH", getValueOfInaccessibleField("length", padding));
		ctx.fireEndParseEvent("PADDING");
	}

	private void populateSeekTableData(ParserContext ctx, SeekTable seekTable) {
		ctx.fireStartParseEvent("SEEKTABLE");
		int numSeekPoints = seekTable.numberOfPoints();
		if (numSeekPoints > 0) {
			for (int i = 0; i < numSeekPoints; i++) {
				SeekPoint seekPoint = seekTable.getSeekPoint(i);
				ctx.fireStartParseEvent("SEEKPOINT");
				ctx.fireParseEvent("SAMPLE-NUMBER", getValueOfInaccessibleField("sampleNumber", seekPoint));
				ctx.fireParseEvent("STREAM-OFFSET", getValueOfInaccessibleField("streamOffset", seekPoint));
				ctx.fireParseEvent("FRAME-SAMPLES", getValueOfInaccessibleField("frameSamples", seekPoint));
				ctx.fireEndParseEvent("SEEKPOINT");
			}
		}
		ctx.fireEndParseEvent("SEEKTABLE");
	}

	private void populateVorbisCommentData(ParserContext ctx, VorbisComment vorbisComment) {
		ctx.fireStartParseEvent("VORBIS-COMMENT");
		ctx.fireParseEvent("VENDOR-STRING", getStringFromByteArrayOfInaccessibleField("vendorString", vorbisComment));
		for (int i = 0; i < vorbisCommentFieldNames.length; i++) {
			String commentFieldName = vorbisCommentFieldNames[i];
			String commentFieldNameToSearch = "EAN-UPN".equals(commentFieldName) ? "EAN/UPN" : commentFieldName;
			String[] comments = null;
			try {
				// This could throw NullPointerException if there are no Vorbis comments
				comments = vorbisComment.getCommentByName(commentFieldNameToSearch);
			} catch (RuntimeException e) {
			}
			StringBuffer commentSb = new StringBuffer();
			if (comments != null && comments.length > 0) {
				for (int commentIndex = 0; commentIndex < comments.length; commentIndex++) {
					String aComment = comments[commentIndex];
					if (aComment != null) {
						commentSb.append(aComment.trim()).append(" ");
					}
				}
				ctx.fireParseEvent(commentFieldName, commentSb.toString().trim());
			}
		}
		ctx.fireEndParseEvent("VORBIS-COMMENT");
	}

	private void populateCueSheetData(ParserContext ctx, CueSheet cueSheet) {
		ctx.fireStartParseEvent("CUESHEET");
		ctx.fireParseEvent("MEDIA-CATALOG-NUMBER", getStringFromByteArrayOfInaccessibleField("mediaCatalogNumber", cueSheet));
		ctx.fireParseEvent("LEAD-IN-SAMPLES", getValueOfInaccessibleField("leadIn", cueSheet));

		ctx.fireParseEvent("IS-CD", getValueOfInaccessibleField("isCD", cueSheet));
		ctx.fireParseEvent("NUMBER-OF-TRACKS", getValueOfInaccessibleField("numTracks", cueSheet));
		Object obj = getValueOfInaccessibleField("tracks", cueSheet);
		if (obj != null && obj instanceof CueTrack[]) {
			CueTrack[] tracks = (CueTrack[]) obj;
			for (int i = 0; i < tracks.length; i++) {
				ctx.fireStartParseEvent("CUETRACK");
				CueTrack track = tracks[i];
				ctx.fireParseEvent("TRACK-OFFSET", getValueOfInaccessibleField("offset", track));

				ctx.fireParseEvent("TRACK-NUMBER", getValueOfInaccessibleField("number", track));
				ctx.fireParseEvent("ISRC", getStringFromByteArrayOfInaccessibleField("isrc", track));
				ctx.fireParseEvent("IS-AUDIO", getValueOfInaccessibleField("type", track));
				ctx.fireParseEvent("PRE-EMPHASIS", getValueOfInaccessibleField("preEmphasis", track));
				ctx.fireParseEvent("TRACK-INDEX-POINTS", getValueOfInaccessibleField("numIndices", track));
				Object indicesObj = getValueOfInaccessibleField("indices", track);
				if (indicesObj != null && indicesObj instanceof CueIndex[]) {
					CueIndex[] cueIndices = (CueIndex[]) indicesObj;
					for (int j = 0; j < cueIndices.length; j++) {
						ctx.fireStartParseEvent("CUETRACKINDEX");
						CueIndex cueIndex = cueIndices[j];
						ctx.fireParseEvent("OFFSET", getValueOfInaccessibleField("offset", cueIndex));
						ctx.fireParseEvent("NUMBER", getValueOfInaccessibleField("number", cueIndex));
						ctx.fireEndParseEvent("CUETRACKINDEX");
					}
				}
				ctx.fireEndParseEvent("CUETRACK");
			}
		}
		ctx.fireEndParseEvent("CUESHEET");
	}

	private void populatePictureData(ParserContext ctx, Picture picture) {
		ctx.fireStartParseEvent("PICTURE");
		ctx.fireParseEvent("PICTURE-TYPE", getValueOfInaccessibleField("pictureType", picture));
		ctx.fireParseEvent("MIME-TYPE", getValueOfInaccessibleField("mimeString", picture));
		ctx.fireParseEvent("DESCRIPTION", getValueOfInaccessibleField("descString", picture));
		ctx.fireParseEvent("WIDTH", getValueOfInaccessibleField("picPixelWidth", picture));
		ctx.fireParseEvent("HEIGHT", getValueOfInaccessibleField("picPixelHeight", picture));
		ctx.fireParseEvent("COLOUR-DEPTH", getValueOfInaccessibleField("picBitsPerPixel", picture));
		ctx.fireParseEvent("COLOUR-DEPTH-UNIT", "Bits Per Pixel");
		ctx.fireParseEvent("NUM-COLOURS", getValueOfInaccessibleField("picColorCount", picture));
		ctx.fireParseEvent("DATA-LENGTH", getValueOfInaccessibleField("picByteCount", picture));
		ctx.fireEndParseEvent("PICTURE");
	}

	private static String getStringFromByteArrayOfInaccessibleField(String fieldName, Object instance) {
		Object obj = getValueOfInaccessibleField(fieldName, instance);
		if (obj != null && obj instanceof byte[]) {
			return new String((byte[]) obj);
		}
		return "";
	}

	private static String getMD5(StreamInfo streamInfo) {
		Object obj = getValueOfInaccessibleField("md5sum", streamInfo);
		if (obj != null && obj instanceof byte[]) {
			return toHexadecimal((byte[]) obj);
		}
		return "";
	}

    private static String toHexadecimal(byte[] buf) {
		char[] chars = new char[2 * buf.length];
		for (int i = 0; i < buf.length; ++i) {
			chars[2 * i] = HEX_CHARS[(buf[i] & 0xF0) >>> 4];
			chars[2 * i + 1] = HEX_CHARS[buf[i] & 0x0F];
		}
		return new String(chars);
	}

	private static Object getValueOfInaccessibleField(String fieldName, Object instance) {
		try {
			Class theClass = instance.getClass();
			Field privateField = theClass.getDeclaredField(fieldName);
			privateField.setAccessible(true);
			return privateField.get(instance);
		} catch (Exception ex) {
			LogManager.getInstance().logMessage(LogMessage.ERROR, "Could not get value of the field "
					+ fieldName + " from instance " + instance + " through reflection" + ex);
			return null;
		}
	}

    private class FlacFrameListener implements FrameListener {
		private final ParserContext ctx;
		FlacFrameListener(ParserContext ctx) {
			this.ctx = ctx;
		}
		public void processError(String s) {
	        //System.out.println("Error: " + s);
		}
		public void processFrame(Frame frame) {
			// TODO: Do we need to extract the frame metadata?
	        //System.out.println("Frame: " + frame);
		}
		public void processMetadata(Metadata metadata) {
	        System.out.println("Metadata: " + metadata.toString());
	        if (metadata == null) return;
	        if (metadata instanceof StreamInfo) {
				populateStreamInfo(ctx, (StreamInfo) metadata);
	        } else if (metadata instanceof Application) {
				populateApplicationData(ctx, (Application) metadata);
	        } else if (metadata instanceof Padding) {
				populatePaddingData(ctx, (Padding) metadata);
	        } else if (metadata instanceof SeekTable) {
				populateSeekTableData(ctx, (SeekTable) metadata);
	        } else if (metadata instanceof VorbisComment) {
				populateVorbisCommentData(ctx, (VorbisComment) metadata);
	        } else if (metadata instanceof CueSheet) {
				populateCueSheetData(ctx, (CueSheet) metadata);
	        } else if (metadata instanceof Picture) {
				populatePictureData(ctx, (Picture) metadata);
	        }
		}
	}
}


text:
package im.actor.core.api.parser;
/*
 *  Generated by the Actor API Scheme generator.  DO NOT EDIT!
 */

import im.actor.runtime.bser.*;
import im.actor.runtime.collections.*;
import static im.actor.runtime.bser.Utils.*;
import im.actor.core.network.parser.*;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.NotNull;
import com.google.j2objc.annotations.ObjectiveCName;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
import im.actor.core.api.updates.*;

public class UpdatesParser extends BaseParser<Update> {
    @Override
    public Update read(int type, byte[] payload) throws IOException {
        switch(type) {
            case 16: return UpdateUserAvatarChanged.fromBytes(payload);
            case 32: return UpdateUserNameChanged.fromBytes(payload);
            case 51: return UpdateUserLocalNameChanged.fromBytes(payload);
            case 134: return UpdateUserContactsChanged.fromBytes(payload);
            case 209: return UpdateUserNickChanged.fromBytes(payload);
            case 210: return UpdateUserAboutChanged.fromBytes(payload);
            case 5: return UpdateContactRegistered.fromBytes(payload);
            case 40: return UpdateContactsAdded.fromBytes(payload);
            case 41: return UpdateContactsRemoved.fromBytes(payload);
            case 55: return UpdateMessage.fromBytes(payload);
            case 162: return UpdateMessageContentChanged.fromBytes(payload);
            case 163: return UpdateMessageDateChanged.fromBytes(payload);
            case 4: return UpdateMessageSent.fromBytes(payload);
            case 54: return UpdateMessageReceived.fromBytes(payload);
            case 19: return UpdateMessageRead.fromBytes(payload);
            case 50: return UpdateMessageReadByMe.fromBytes(payload);
            case 46: return UpdateMessageDelete.fromBytes(payload);
            case 47: return UpdateChatClear.fromBytes(payload);
            case 48: return UpdateChatDelete.fromBytes(payload);
            case 36: return UpdateGroupInvite.fromBytes(payload);
            case 21: return UpdateGroupUserInvited.fromBytes(payload);
            case 23: return UpdateGroupUserLeave.fromBytes(payload);
            case 24: return UpdateGroupUserKick.fromBytes(payload);
            case 44: return UpdateGroupMembersUpdate.fromBytes(payload);
            case 38: return UpdateGroupTitleChanged.fromBytes(payload);
            case 213: return UpdateGroupTopicChanged.fromBytes(payload);
            case 214: return UpdateGroupAboutChanged.fromBytes(payload);
            case 39: return UpdateGroupAvatarChanged.fromBytes(payload);
            case 6: return UpdateTyping.fromBytes(payload);
            case 7: return UpdateUserOnline.fromBytes(payload);
            case 8: return UpdateUserOffline.fromBytes(payload);
            case 9: return UpdateUserLastSeen.fromBytes(payload);
            case 33: return UpdateGroupOnline.fromBytes(payload);
            case 131: return UpdateParameterChanged.fromBytes(payload);
            case 215: return UpdateCountersChanged.fromBytes(payload);
            case 42: return UpdateConfig.fromBytes(payload);
        }
        throw new IOException();
    }
}


text:
import org.mozilla.javascript.Context
import org.mozilla.javascript.Scriptable
import org.mozilla.javascript.ScriptableObject

/**
 * RunScript2: Like RunScript, but reflects the System.out into JavaScript.
 */
object RunScript2 extends App {
  val cx: Context = Context.enter
  try {
    val scope: Scriptable = cx.initStandardObjects()

    // Add a global variable "out" that is a JavaScript reflection
    // of System.out
    val jsOut: AnyRef = Context.javaToJS(System.out, scope)
    ScriptableObject.putProperty(scope, "out", jsOut)

    val s = args.mkString

    val result: AnyRef = cx.evaluateString(scope, s, "<cmd>", 1, null)
    System.err.println(Context.toString(result))
  } finally {
    Context.exit()
  }
}


text:
@extends('layouts.app')

@section('links')
    @include('imports.select2_links')
@endsection

@section('content')

    {{--Seção de erros--}}
    @if (count($errors) > 0)

                @foreach ($errors->all() as $error)

{{ $error }}

                @endforeach

    @endif
    {{--Cabeçalho--}}

Alimento

Cadastro
                        Insira as informações conforme solicitadas

                    {{--Form--}}
                    {!! Form::open(['route'=>'alimentos.store', 'class'=>'form-horizontal form-label-left',
                    'id'=> 'cadastro-form', 'data-parsley-validate', 'files' => 'true' ]) !!}

                        {!! Form::label('descricaoAlimento', 'Alimento', ['class'=>'control-label col-md-3 col-sm-3 col-xs-12']) !!}

                            {!! Form::text('descricaoAlimento', null, ['class'=>'form-control col-md-7 col-xs-12',
                             'data-parsley-required', 'data-parsley-required-message' => "Preencha este campo" ]) !!}

                        {!! Form::label('idGPiramide', 'Grupo Piramide', ['class'=>'control-label col-md-3 col-sm-3 col-xs-12']) !!}

                            {!! Form::select('idGPiramide', \App\Models\Grupo\GrupoPiramide::pluck('descricaoGP', 'idGPiramide'), null, ['class'=>'form-control']) !!}

                        {!! Form::label('idGAlimentar', 'Grupo', ['class'=>'control-label col-md-3 col-sm-3 col-xs-12']) !!}

                            {!! Form::select('idGAlimentar', \App\Models\Grupo\GrupoAlimentar::pluck('descricaoGA', 'idGAlimentar'), null, ['class'=>'form-control']) !!}

                        {!! Form::label('idTACO', 'ID TACO', ['class'=>'control-label col-md-3 col-sm-3 col-xs-12']) !!}

                            {!! Form::text('idTACO', null, ['class'=>'form-control', 'data-parsley-type'=>"number",
                             'data-parsley-type-message' => "Preencha com um valor númerico", 'data-parsley-required', 'data-parsley-required-message' => "Preencha este campo"]) !!}

                        {!! Form::label('nutrientes', 'Nutrientes', ['class'=>'control-label col-md-3 col-sm-3 col-xs-12']) !!}

                            {!! Form::select('nutrientes[]', \App\Models\Nutriente\Nutriente::pluck('nomeNutriente', 'idNutriente'), null,
                            ['id'=>'nutrienteSelect', 'class'=>'form-control select2_multiple', 'multiple'=>true, 'multiple'=>'multiple']) !!}

                        {!! Form::label('medidas_caseiras', 'Medidas Caseiras', ['class'=>'control-label col-md-3 col-sm-3 col-xs-12']) !!}

                            {!! Form::select('medidas_caseiras[]', \App\Models\Medida\TipoMedidaCaseira::pluck('nomeTMC', 'idTMCaseira'), null,
                            ['id'=>'medidaCaseiraSelect', 'class'=>'form-control select2_multiple', 'multiple'=>true, 'multiple'=>'multiple']) !!}

                        {!! Form::label('image', 'Imagem do Alimento', ['class'=>'control-label col-md-3 col-sm-3 col-xs-12']) !!}

                            {!! Form::file('image', ['class' => 'btn btn-primary', 'accept' => 'image/*']) !!}

                    {{--Nutrientes--}}

Nutrientes
                        Insira as quantidades

                            <button type="button" class="close" data-dismiss="alert" aria-label="Close">×
                            </button>
                            Atenção! Você ainda não inseriu nenhum Nutriente ao alimento.

                    {{--Medidas Caseiras--}}

Medidas Caseiras
                        Insira as quantidades

                                <button type="button" class="close" data-dismiss="alert" aria-label="Close">×
                                </button>
                                Atenção! Você ainda não inseriu nenhuma medida caseira.

                    {!! Form::submit('Cadastrar', ['class'=>'btn btn-primary pull-right']) !!}
                    {!! Form::close() !!}

@endsection

@section('scripts')
    {{--@include('imports.validator_script')--}}
    @include('imports.select2_script')
    @include('imports.parsley_script')

@endsection