text:
import { describe, it } from 'mocha';
import { expect } from 'chai';

import {
  GraphQLScalarType,
  GraphQLEnumType,
  GraphQLInputObjectType,
  GraphQLInterfaceType,
  GraphQLObjectType,
  GraphQLUnionType,
  GraphQLList,
  GraphQLNonNull,
  GraphQLString,
  isType,
  isScalarType,
  isObjectType,
  isInterfaceType,
  isUnionType,
  isEnumType,
  isInputObjectType,
  isListType,
  isNonNullType,
  isInputType,
  isOutputType,
  isLeafType,
  isCompositeType,
  isAbstractType,
  isWrappingType,
  isNullableType,
  isNamedType,
  isRequiredArgument,
  isRequiredInputField,
  assertType,
  assertScalarType,
  assertObjectType,
  assertInterfaceType,
  assertUnionType,
  assertEnumType,
  assertInputObjectType,
  assertListType,
  assertNonNullType,
  assertInputType,
  assertOutputType,
  assertLeafType,
  assertCompositeType,
  assertAbstractType,
  assertWrappingType,
  assertNullableType,
  assertNamedType,
  getNullableType,
  getNamedType,
} from '../';

const ObjectType = new GraphQLObjectType({ name: 'Object', fields: {} });
const InterfaceType = new GraphQLInterfaceType({
  name: 'Interface',
  fields: {},
});
const UnionType = new GraphQLUnionType({ name: 'Union', types: [ObjectType] });
const EnumType = new GraphQLEnumType({ name: 'Enum', values: { foo: {} } });
const InputObjectType = new GraphQLInputObjectType({
  name: 'InputObject',
  fields: {},
});
const ScalarType = new GraphQLScalarType({
  name: 'Scalar',
  serialize() {},
});

describe('Type predicates', () => {
  describe('isType', () => {
    it('returns true for unwrapped types', () => {
      expect(isType(GraphQLString)).to.equal(true);
      expect(() => assertType(GraphQLString)).not.to.throw();
      expect(isType(ObjectType)).to.equal(true);
      expect(() => assertType(ObjectType)).not.to.throw();
    });

    it('returns true for wrapped types', () => {
      expect(isType(GraphQLNonNull(GraphQLString))).to.equal(true);
      expect(() => assertType(GraphQLNonNull(GraphQLString))).not.to.throw();
    });

    it('returns false for type classes (rather than instances)', () => {
      expect(isType(GraphQLObjectType)).to.equal(false);
      expect(() => assertType(GraphQLObjectType)).to.throw();
    });

    it('returns false for random garbage', () => {
      expect(isType({ what: 'is this' })).to.equal(false);
      expect(() => assertType({ what: 'is this' })).to.throw();
    });
  });

  describe('isScalarType', () => {
    it('returns true for spec defined scalar', () => {
      expect(isScalarType(GraphQLString)).to.equal(true);
      expect(() => assertScalarType(GraphQLString)).not.to.throw();
    });

    it('returns true for custom scalar', () => {
      expect(isScalarType(ScalarType)).to.equal(true);
      expect(() => assertScalarType(ScalarType)).not.to.throw();
    });

    it('returns false for wrapped scalar', () => {
      expect(isScalarType(GraphQLList(ScalarType))).to.equal(false);
      expect(() => assertScalarType(GraphQLList(ScalarType))).to.throw();
    });

    it('returns false for non-scalar', () => {
      expect(isScalarType(EnumType)).to.equal(false);
      expect(() => assertScalarType(EnumType)).to.throw();
    });
  });

  describe('isObjectType', () => {
    it('returns true for object type', () => {
      expect(isObjectType(ObjectType)).to.equal(true);
      expect(() => assertObjectType(ObjectType)).not.to.throw();
    });

    it('returns false for wrapped object type', () => {
      expect(isObjectType(GraphQLList(ObjectType))).to.equal(false);
      expect(() => assertObjectType(GraphQLList(ObjectType))).to.throw();
    });

    it('returns false for non-object type', () => {
      expect(isObjectType(InterfaceType)).to.equal(false);
      expect(() => assertObjectType(InterfaceType)).to.throw();
    });
  });

  describe('isInterfaceType', () => {
    it('returns true for interface type', () => {
      expect(isInterfaceType(InterfaceType)).to.equal(true);
      expect(() => assertInterfaceType(InterfaceType)).not.to.throw();
    });

    it('returns false for wrapped interface type', () => {
      expect(isInterfaceType(GraphQLList(InterfaceType))).to.equal(false);
      expect(() => assertInterfaceType(GraphQLList(InterfaceType))).to.throw();
    });

    it('returns false for non-interface type', () => {
      expect(isInterfaceType(ObjectType)).to.equal(false);
      expect(() => assertInterfaceType(ObjectType)).to.throw();
    });
  });

  describe('isUnionType', () => {
    it('returns true for union type', () => {
      expect(isUnionType(UnionType)).to.equal(true);
      expect(() => assertUnionType(UnionType)).not.to.throw();
    });

    it('returns false for wrapped union type', () => {
      expect(isUnionType(GraphQLList(UnionType))).to.equal(false);
      expect(() => assertUnionType(GraphQLList(UnionType))).to.throw();
    });

    it('returns false for non-union type', () => {
      expect(isUnionType(ObjectType)).to.equal(false);
      expect(() => assertUnionType(ObjectType)).to.throw();
    });
  });

  describe('isEnumType', () => {
    it('returns true for enum type', () => {
      expect(isEnumType(EnumType)).to.equal(true);
      expect(() => assertEnumType(EnumType)).not.to.throw();
    });

    it('returns false for wrapped enum type', () => {
      expect(isEnumType(GraphQLList(EnumType))).to.equal(false);
      expect(() => assertEnumType(GraphQLList(EnumType))).to.throw();
    });

    it('returns false for non-enum type', () => {
      expect(isEnumType(ScalarType)).to.equal(false);
      expect(() => assertEnumType(ScalarType)).to.throw();
    });
  });

  describe('isInputObjectType', () => {
    it('returns true for input object type', () => {
      expect(isInputObjectType(InputObjectType)).to.equal(true);
      expect(() => assertInputObjectType(InputObjectType)).not.to.throw();
    });

    it('returns false for wrapped input object type', () => {
      expect(isInputObjectType(GraphQLList(InputObjectType))).to.equal(false);
      expect(() =>
        assertInputObjectType(GraphQLList(InputObjectType)),
      ).to.throw();
    });

    it('returns false for non-input-object type', () => {
      expect(isInputObjectType(ObjectType)).to.equal(false);
      expect(() => assertInputObjectType(ObjectType)).to.throw();
    });
  });

  describe('isListType', () => {
    it('returns true for a list wrapped type', () => {
      expect(isListType(GraphQLList(ObjectType))).to.equal(true);
      expect(() => assertListType(GraphQLList(ObjectType))).not.to.throw();
    });

    it('returns false for an unwrapped type', () => {
      expect(isListType(ObjectType)).to.equal(false);
      expect(() => assertListType(ObjectType)).to.throw();
    });

    it('returns false for a non-list wrapped type', () => {
      expect(isListType(GraphQLNonNull(GraphQLList(ObjectType)))).to.equal(
        false,
      );
      expect(() =>
        assertListType(GraphQLNonNull(GraphQLList(ObjectType))),
      ).to.throw();
    });
  });

  describe('isNonNullType', () => {
    it('returns true for a non-null wrapped type', () => {
      expect(isNonNullType(GraphQLNonNull(ObjectType))).to.equal(true);
      expect(() =>
        assertNonNullType(GraphQLNonNull(ObjectType)),
      ).not.to.throw();
    });

    it('returns false for an unwrapped type', () => {
      expect(isNonNullType(ObjectType)).to.equal(false);
      expect(() => assertNonNullType(ObjectType)).to.throw();
    });

    it('returns false for a not non-null wrapped type', () => {
      expect(isNonNullType(GraphQLList(GraphQLNonNull(ObjectType)))).to.equal(
        false,
      );
      expect(() =>
        assertNonNullType(GraphQLList(GraphQLNonNull(ObjectType))),
      ).to.throw();
    });
  });

  describe('isInputType', () => {
    function expectInputType(type) {
      expect(isInputType(type)).to.equal(true);
      expect(() => assertInputType(type)).not.to.throw();
    }

    it('returns true for an input type', () => {
      expectInputType(GraphQLString);
      expectInputType(EnumType);
      expectInputType(InputObjectType);
    });

    it('returns true for a wrapped input type', () => {
      expectInputType(GraphQLList(GraphQLString));
      expectInputType(GraphQLList(EnumType));
      expectInputType(GraphQLList(InputObjectType));

      expectInputType(GraphQLNonNull(GraphQLString));
      expectInputType(GraphQLNonNull(EnumType));
      expectInputType(GraphQLNonNull(InputObjectType));
    });

    function expectNonInputType(type) {
      expect(isInputType(type)).to.equal(false);
      expect(() => assertInputType(type)).to.throw();
    }

    it('returns false for an output type', () => {
      expectNonInputType(ObjectType);
      expectNonInputType(InterfaceType);
      expectNonInputType(UnionType);
    });

    it('returns false for a wrapped output type', () => {
      expectNonInputType(GraphQLList(ObjectType));
      expectNonInputType(GraphQLList(InterfaceType));
      expectNonInputType(GraphQLList(UnionType));

      expectNonInputType(GraphQLNonNull(ObjectType));
      expectNonInputType(GraphQLNonNull(InterfaceType));
      expectNonInputType(GraphQLNonNull(UnionType));
    });
  });

  describe('isOutputType', () => {
    function expectOutputType(type) {
      expect(isOutputType(type)).to.equal(true);
      expect(() => assertOutputType(type)).not.to.throw();
    }

    it('returns true for an output type', () => {
      expectOutputType(GraphQLString);
      expectOutputType(ObjectType);
      expectOutputType(InterfaceType);
      expectOutputType(UnionType);
      expectOutputType(EnumType);
    });

    it('returns true for a wrapped output type', () => {
      expectOutputType(GraphQLList(GraphQLString));
      expectOutputType(GraphQLList(ObjectType));
      expectOutputType(GraphQLList(InterfaceType));
      expectOutputType(GraphQLList(UnionType));
      expectOutputType(GraphQLList(EnumType));

      expectOutputType(GraphQLNonNull(GraphQLString));
      expectOutputType(GraphQLNonNull(ObjectType));
      expectOutputType(GraphQLNonNull(InterfaceType));
      expectOutputType(GraphQLNonNull(UnionType));
      expectOutputType(GraphQLNonNull(EnumType));
    });

    function expectNonOutputType(type) {
      expect(isOutputType(type)).to.equal(false);
      expect(() => assertOutputType(type)).to.throw();
    }

    it('returns false for an input type', () => {
      expectNonOutputType(InputObjectType);
    });

    it('returns false for a wrapped input type', () => {
      expectNonOutputType(GraphQLList(InputObjectType));
      expectNonOutputType(GraphQLNonNull(InputObjectType));
    });
  });

  describe('isLeafType', () => {
    it('returns true for scalar and enum types', () => {
      expect(isLeafType(ScalarType)).to.equal(true);
      expect(() => assertLeafType(ScalarType)).not.to.throw();
      expect(isLeafType(EnumType)).to.equal(true);
      expect(() => assertLeafType(EnumType)).not.to.throw();
    });

    it('returns false for wrapped leaf type', () => {
      expect(isLeafType(GraphQLList(ScalarType))).to.equal(false);
      expect(() => assertLeafType(GraphQLList(ScalarType))).to.throw();
    });

    it('returns false for non-leaf type', () => {
      expect(isLeafType(ObjectType)).to.equal(false);
      expect(() => assertLeafType(ObjectType)).to.throw();
    });

    it('returns false for wrapped non-leaf type', () => {
      expect(isLeafType(GraphQLList(ObjectType))).to.equal(false);
      expect(() => assertLeafType(GraphQLList(ObjectType))).to.throw();
    });
  });

  describe('isCompositeType', () => {
    it('returns true for object, interface, and union types', () => {
      expect(isCompositeType(ObjectType)).to.equal(true);
      expect(() => assertCompositeType(ObjectType)).not.to.throw();
      expect(isCompositeType(InterfaceType)).to.equal(true);
      expect(() => assertCompositeType(InterfaceType)).not.to.throw();
      expect(isCompositeType(UnionType)).to.equal(true);
      expect(() => assertCompositeType(UnionType)).not.to.throw();
    });

    it('returns false for wrapped composite type', () => {
      expect(isCompositeType(GraphQLList(ObjectType))).to.equal(false);
      expect(() => assertCompositeType(GraphQLList(ObjectType))).to.throw();
    });

    it('returns false for non-composite type', () => {
      expect(isCompositeType(InputObjectType)).to.equal(false);
      expect(() => assertCompositeType(InputObjectType)).to.throw();
    });

    it('returns false for wrapped non-composite type', () => {
      expect(isCompositeType(GraphQLList(InputObjectType))).to.equal(false);
      expect(() =>
        assertCompositeType(GraphQLList(InputObjectType)),
      ).to.throw();
    });
  });

  describe('isAbstractType', () => {
    it('returns true for interface and union types', () => {
      expect(isAbstractType(InterfaceType)).to.equal(true);
      expect(() => assertAbstractType(InterfaceType)).not.to.throw();
      expect(isAbstractType(UnionType)).to.equal(true);
      expect(() => assertAbstractType(UnionType)).not.to.throw();
    });

    it('returns false for wrapped abstract type', () => {
      expect(isAbstractType(GraphQLList(InterfaceType))).to.equal(false);
      expect(() => assertAbstractType(GraphQLList(InterfaceType))).to.throw();
    });

    it('returns false for non-abstract type', () => {
      expect(isAbstractType(ObjectType)).to.equal(false);
      expect(() => assertAbstractType(ObjectType)).to.throw();
    });

    it('returns false for wrapped non-abstract type', () => {
      expect(isAbstractType(GraphQLList(ObjectType))).to.equal(false);
      expect(() => assertAbstractType(GraphQLList(ObjectType))).to.throw();
    });
  });

  describe('isWrappingType', () => {
    it('returns true for list and non-null types', () => {
      expect(isWrappingType(GraphQLList(ObjectType))).to.equal(true);
      expect(() => assertWrappingType(GraphQLList(ObjectType))).not.to.throw();
      expect(isWrappingType(GraphQLNonNull(ObjectType))).to.equal(true);
      expect(() =>
        assertWrappingType(GraphQLNonNull(ObjectType)),
      ).not.to.throw();
    });

    it('returns false for unwrapped types', () => {
      expect(isWrappingType(ObjectType)).to.equal(false);
      expect(() => assertWrappingType(ObjectType)).to.throw();
    });
  });

  describe('isNullableType', () => {
    it('returns true for unwrapped types', () => {
      expect(isNullableType(ObjectType)).to.equal(true);
      expect(() => assertNullableType(ObjectType)).not.to.throw();
    });

    it('returns true for list of non-null types', () => {
      expect(isNullableType(GraphQLList(GraphQLNonNull(ObjectType)))).to.equal(
        true,
      );
      expect(() =>
        assertNullableType(GraphQLList(GraphQLNonNull(ObjectType))),
      ).not.to.throw();
    });

    it('returns false for non-null types', () => {
      expect(isNullableType(GraphQLNonNull(ObjectType))).to.equal(false);
      expect(() => assertNullableType(GraphQLNonNull(ObjectType))).to.throw();
    });
  });

  describe('getNullableType', () => {
    it('returns undefined for no type', () => {
      expect(getNullableType()).to.equal(undefined);
      expect(getNullableType(null)).to.equal(undefined);
    });

    it('returns self for a nullable type', () => {
      expect(getNullableType(ObjectType)).to.equal(ObjectType);
      const listOfObj = GraphQLList(ObjectType);
      expect(getNullableType(listOfObj)).to.equal(listOfObj);
    });

    it('unwraps non-null type', () => {
      expect(getNullableType(GraphQLNonNull(ObjectType))).to.equal(ObjectType);
    });
  });

  describe('isNamedType', () => {
    it('returns true for unwrapped types', () => {
      expect(isNamedType(ObjectType)).to.equal(true);
      expect(() => assertNamedType(ObjectType)).not.to.throw();
    });

    it('returns false for list and non-null types', () => {
      expect(isNamedType(GraphQLList(ObjectType))).to.equal(false);
      expect(() => assertNamedType(GraphQLList(ObjectType))).to.throw();
      expect(isNamedType(GraphQLNonNull(ObjectType))).to.equal(false);
      expect(() => assertNamedType(GraphQLNonNull(ObjectType))).to.throw();
    });
  });

  describe('getNamedType', () => {
    it('returns undefined for no type', () => {
      expect(getNamedType()).to.equal(undefined);
      expect(getNamedType(null)).to.equal(undefined);
    });

    it('returns self for a unwrapped type', () => {
      expect(getNamedType(ObjectType)).to.equal(ObjectType);
    });

    it('unwraps wrapper types', () => {
      expect(getNamedType(GraphQLNonNull(ObjectType))).to.equal(ObjectType);
      expect(getNamedType(GraphQLList(ObjectType))).to.equal(ObjectType);
    });

    it('unwraps deeply wrapper types', () => {
      expect(
        getNamedType(GraphQLNonNull(GraphQLList(GraphQLNonNull(ObjectType)))),
      ).to.equal(ObjectType);
    });
  });

  describe('isRequiredArgument', () => {
    it('returns true for required arguments', () => {
      const requiredArg = {
        name: 'someArg',
        type: GraphQLNonNull(GraphQLString),
      };
      expect(isRequiredArgument(requiredArg)).to.equal(true);
    });

    it('returns false for optional arguments', () => {
      const optArg1 = {
        name: 'someArg',
        type: GraphQLString,
      };
      expect(isRequiredArgument(optArg1)).to.equal(false);

      const optArg2 = {
        name: 'someArg',
        type: GraphQLString,
        defaultValue: null,
      };
      expect(isRequiredArgument(optArg2)).to.equal(false);

      const optArg3 = {
        name: 'someArg',
        type: GraphQLList(GraphQLNonNull(GraphQLString)),
      };
      expect(isRequiredArgument(optArg3)).to.equal(false);

      const optArg4 = {
        name: 'someArg',
        type: GraphQLNonNull(GraphQLString),
        defaultValue: 'default',
      };
      expect(isRequiredArgument(optArg4)).to.equal(false);
    });
  });

  describe('isRequiredInputField', () => {
    it('returns true for required input field', () => {
      const requiredField = {
        name: 'someField',
        type: GraphQLNonNull(GraphQLString),
      };
      expect(isRequiredInputField(requiredField)).to.equal(true);
    });

    it('returns false for optional input field', () => {
      const optField1 = {
        name: 'someField',
        type: GraphQLString,
      };
      expect(isRequiredInputField(optField1)).to.equal(false);

      const optField2 = {
        name: 'someField',
        type: GraphQLString,
        defaultValue: null,
      };
      expect(isRequiredInputField(optField2)).to.equal(false);

      const optField3 = {
        name: 'someField',
        type: GraphQLList(GraphQLNonNull(GraphQLString)),
      };
      expect(isRequiredInputField(optField3)).to.equal(false);

      const optField4 = {
        name: 'someField',
        type: GraphQLNonNull(GraphQLString),
        defaultValue: 'default',
      };
      expect(isRequiredInputField(optField4)).to.equal(false);
    });
  });
});


text:
<?php
/**
 * Apricot Exception Handler Console class file
 *
 * @package Apricot
 */

namespace Apricot\Exception;

use \Apricot\Kernel;
use \Apricot\KernelException;

/**
 * Exception Handler Console
 *
 * @uses ExceptionHandler
 * @package Apricot
 * @author Jansen Price <jansen.price@gmail.com>
 * @license http://www.opensource.org/licenses/mit-license.php MIT
 * @version ApricotVersion: 1.3b
 */
class ExceptionHandlerConsole extends ExceptionHandler
{
    /**
     * Init the error handlers
     *
     * @param Kernel $kernel Kernel object
     * @return void
     */
    public static function initHandlers(Kernel $kernel)
    {
        self::setKernel($kernel);

        set_exception_handler(
            array('\Apricot\Exception\ExceptionHandlerConsole', 'handleException')
        );

        set_error_handler(
            array('\Apricot\Exception\ExceptionHandlerConsole', 'handleError')
        );

        register_shutdown_function(
            array('\Apricot\Exception\ExceptionHandlerConsole', 'handleShutdown')
        );
    }

    /**
     * Handle an error
     *
     * @return void
     */
    public static function handleError()
    {
        list($errno, $message, $file, $line) = func_get_args();

        $message = self::_convertErrorCode($errno)
            . ": " . $message . " in " . $file . ":" . $line;

        if (self::$_kernel->getConfig('display_errors')) {
            $terminal = self::$_kernel->getTerminal();

            $terminal->setaf(1);
            print $message . "\n";
            $terminal->op();
        }

        self::$_kernel->log($message, 'errors');
    }

    /**
     * Handle a shutdown
     *
     * @return void
     */
    public static function handleShutdown()
    {
        $error = error_get_last();

        if (!empty($error)) {
            // This way fatal errors will get logged as well.
            self::handleError(
                $error['type'], $error['message'],
                $error['file'], $error['line']
            );
        }
    }

    /**
     * Handle thrown exceptions
     *
     * @param \Exception $exception The Exception object
     * @return void
     */
    public static function handleException(\Exception $exception)
    {
        $errorNumber = self::logException($exception);
        $terminal    = self::$_kernel->getTerminal();

        print "\n";
        $terminal->pretty_message(
            'Exception: ' . $exception->getMessage() . " (Logged as $errorNumber)", 7, 1
        );
        print "\n";
    }

    /**
     * Log an exception
     *
     * @param \Exception $exception The Exception object
     * @return void
     */
    public static function logException($exception)
    {
        $logFile = "exceptions-terminal";

        $logErrorNumber = self::_generateRandomString();

        $logMessage = "---------------------------------------\n"
            . "ERROR NUMBER: $logErrorNumber\n"
            . "DATE: " . date('Y-m-d H:i:s') . "\n"
            . "EXCEPTION TYPE: " . get_class($exception) . "\n"
            . "MESSAGE: " . $exception->getMessage() . "\n"
            . "CODE: " . $exception->getCode() . "\n"
            . "TRACE:\n" . self::renderTraceTextTable($exception->getTrace()) . "\n"
            ;

        self::$_kernel->log($logMessage, $logFile);

        return $logErrorNumber;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.plexobject.stock;

public class Quote {
    private long timestamp;
    private String company;
    private String symbol;
    private String quote;
    private float last;
    private float open;
    private float close;

    public long getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(long timestamp) {
        this.timestamp = timestamp;
    }

    public String getCompany() {
        return company;
    }

    public void setCompany(String company) {
        this.company = company;
    }

    public String getSymbol() {
        return symbol;
    }

    public void setSymbol(String symbol) {
        this.symbol = symbol;
    }

    public String getQuote() {
        return quote;
    }

    public void setQuote(String quote) {
        this.quote = quote;
    }

    public float getLast() {
        return last;
    }

    public void setLast(float last) {
        this.last = last;
    }

    public float getOpen() {
        return open;
    }

    public void setOpen(float open) {
        this.open = open;
    }

    public float getClose() {
        return close;
    }

    public void setClose(float close) {
        this.close = close;
    }

    @Override
    public String toString() {
        return "Quote [company=" + company + ", symbol=" + symbol + ", quote="
                + quote + ", last=" + last + ", open=" + open + ", close="
                + close + "]";
    }

}


text:
<?php

namespace app\controllers\Fregat;

use app\models\Fregat\Cabinet;
use Yii;
use app\models\Fregat\TrOsnov;
use yii\db\Exception;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use app\func\Proc;
use yii\filters\AccessControl;
use app\models\Fregat\Mattraffic;
use app\models\Fregat\Material;
use app\models\Fregat\Employee;
use app\models\Fregat\TrOsnovSearch;

/**
 * TrOsnovController implements the CRUD actions for TrOsnov model.
 */
class TrOsnovController extends Controller
{

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['selectinputfortrosnov', 'filltrosnov', 'matvid-count', 'forosmotrakt', 'selectinputforosmotrakt', 'assign-to-select2', 'fillinstalledmat'],
                        'allow' => true,
                        'roles' => ['FregatUserPermission'],
                    ],
                    [
                        'actions' => ['create', 'update', 'delete'],
                        'allow' => true,
                        'roles' => ['InstallEdit'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    public function actionForosmotrakt()
    {
        $searchModel = new TrOsnovSearch();
        $dataProvider = $searchModel->searchforosmotrakt(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    public function actionCreate()
    {
        $model = new TrOsnov();
        $Mattraffic = new Mattraffic;
        $Material = new Material;
        $Employee = new Employee;
        $mattraffic_number_max = NULL;

        // Если форма отправлена на сервер, получаем выбранную материальную ценность
        $id_mattraffic = isset(Yii::$app->request->post('TrOsnov')['id_mattraffic']) ? Yii::$app->request->post('TrOsnov')['id_mattraffic'] : '';

        $transaction = Yii::$app->db->beginTransaction();
        try {

            // Если форма отправлена на сервер, то создать запись перемещения мат цен-ти в mattraffic
            if (!empty($id_mattraffic)) {
                $Mattrafficcurrent = Mattraffic::findOne($id_mattraffic);

                $Mattraffic->attributes = $Mattrafficcurrent->attributes;

                $Mattraffic->mattraffic_date = date('Y-m-d');
                $Mattraffic->mattraffic_number = isset(Yii::$app->request->post('Mattraffic')['mattraffic_number']) ? Yii::$app->request->post('Mattraffic')['mattraffic_number'] : NULL;
                $Mattraffic->mattraffic_tip = 3;

                if (isset($Mattraffic->scenarios()['traffic']))
                    $Mattraffic->scenario = 'traffic';

                if ($Mattraffic->validate()) {
                    $Mattraffic->save(false);
                    $model->id_mattraffic = $Mattraffic->mattraffic_id;
                }

                //Акт установки уже создан и берется из URL параметра
                $model->id_installakt = (string)filter_input(INPUT_GET, 'idinstallakt');

                //Сохраняем кабинет в модель из отправленной формы
                $model->id_cabinet = isset(Yii::$app->request->post('TrOsnov')['id_cabinet']) ? Yii::$app->request->post('TrOsnov')['id_cabinet'] : NULL;
            }

            // Сохраняем модель с отправленными данными и сохраненным mattraffic
            if (!$Mattraffic->isNewRecord && $model->save()) {
                $transaction->commit();
                return $this->redirect(Proc::GetPreviousURLBreadcrumbsFromSession());
            } else { // иначе
                // Берет значение сначала из справочника (посредством перехода на страницу выбора), если нет, то вытаскивает из сессии (для простого обновления страницы)
                // выводит $PreviusBC - для последующей передачи в функцию Proc::SetSessionValuesFromAR, т.е. установить в последнюю сессию или предыдущую (хлебных крошек)
                $PreviusBC = Proc::GetValueForFillARs($id_mattraffic, 'TrOsnov', 'id_mattraffic');

                // Очистить ошибку id_mattraffic, если есть ошибка по mattraffic_number (Превышено допустимое кол-во для перемещения матер. цен-ти)
                //if (isset($Mattraffic->errors['mattraffic_number']))
                //    $model->clearErrors('id_mattraffic');

                // Если выбрана мат. цен-ть, то заполнить информацию для отображения на форме по мат. цен-ти и МОЛ
                if (!empty($id_mattraffic)) {
                    $Material = Material::find()->joinWith('mattraffics')->where(['mattraffic_id' => $id_mattraffic])->one();
                    $Employee = Employee::find()->joinWith('mattraffics')->where(['mattraffic_id' => $id_mattraffic])->one();
                    // GetMaxNumberMattrafficForInstallAkt - Определяем максимально допустимое кол-во материала для перемещения (Общее кол-во материала минус уже перемещенное кол-во)
                    $mattraffic_number_max = 'Не более ' . doubleval(Mattraffic::GetMaxNumberMattrafficForInstallAkt($id_mattraffic));

                    // Сохраняем модель мат. цен-ти и МОЛ'а в сессию (т.к. эти модели только для отображения)
                    Proc::SetSessionValuesFromAR($Material, $PreviusBC);
                    Proc::SetSessionValuesFromAR($Employee, $PreviusBC);
                }

                // Откатываем транзакцию
                $transaction->rollBack();

                return $this->render('create', [
                    'model' => $model,
                    'Mattraffic' => $Mattraffic,
                    'Material' => $Material, // Для просмотра
                    'Employee' => $Employee, // Для просмотра
                    'mattraffic_number_max' => $mattraffic_number_max, //максимально допустимое кол-во материала
                ]);
            }
        } catch (Exception $e) {
            $transaction->rollBack();
            throw new Exception($e->getMessage());
        }
    }

    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $Mattraffic = Mattraffic::findOne($model->id_mattraffic);
        $Material = Material::find()->joinWith('mattraffics')->where(['mattraffic_id' => $model->id_mattraffic])->one();
        $Employee = Employee::find()->joinWith('mattraffics')->where(['mattraffic_id' => $model->id_mattraffic])->one();
        $mattraffic_number_max = NULL;
        $id_mattraffic = isset(Yii::$app->request->post('TrOsnov')['id_mattraffic']) ? Yii::$app->request->post('TrOsnov')['id_mattraffic'] : '';

        $transaction = Yii::$app->db->beginTransaction();
        try {
            // Если форма отправлена на сервер, то создать запись перемещения мат цен-ти в mattraffic
            if (!empty($id_mattraffic)) {
                $Mattrafficcurrent = Mattraffic::findOne($id_mattraffic);

                $Mattraffic->mattraffic_date = $Mattrafficcurrent->mattraffic_date;
                $Mattraffic->id_mol = $Mattrafficcurrent->id_mol;
                $Mattraffic->id_material = $Mattrafficcurrent->id_material;
                $Mattraffic->mattraffic_number = isset(Yii::$app->request->post('Mattraffic')['mattraffic_number']) ? Yii::$app->request->post('Mattraffic')['mattraffic_number'] : NULL;
                if (isset($Mattraffic->scenarios()['traffic']))
                    $Mattraffic->scenario = 'traffic';

                //Сохраняем кабинет в модель из отправленной формы
                $model->id_cabinet = isset(Yii::$app->request->post('TrOsnov')['id_cabinet']) ? Yii::$app->request->post('TrOsnov')['id_cabinet'] : NULL;

                if ($Mattraffic->save() && $model->save()) {
                    $transaction->commit();
                    return $this->redirect(Proc::GetPreviousURLBreadcrumbsFromSession());
                } else {
                    $transaction->rollBack();

                    return $this->render('update', [
                        'model' => $model,
                        'Mattraffic' => $Mattraffic,
                        'Material' => $Material, // Для просмотра
                        'Employee' => $Employee, // Для просмотра
                        'mattraffic_number_max' => $mattraffic_number_max, //максимально допустимое кол-во материала

                    ]);
                }

            } else {
                $transaction->rollBack();

                return $this->render('update', [
                    'model' => $model,
                    'Mattraffic' => $Mattraffic,
                    'Material' => $Material, // Для просмотра
                    'Employee' => $Employee, // Для просмотра
                    'mattraffic_number_max' => $mattraffic_number_max, //максимально допустимое кол-во материала

                ]);
            }

        } catch (Exception $e) {
            $transaction->rollBack();
            throw new Exception($e->getMessage());
        }
    }

    // Действие наполнения списка Select2 при помощи ajax
    public function actionSelectinputfortrosnov($q = null, $idinstallakt = null)
    {
        if (Yii::$app->request->isAjax)
            return Proc::ResultSelect2([
                'model' => new Mattraffic,
                'q' => $q,
                'methodquery' => 'selectinputfortrosnov',
                'methodparams' => ['idinstallakt' => $idinstallakt],
            ]);
    }

    // Заполнение полей формы после выбора материальной ценности по инвентарнику
    public function actionFilltrosnov()
    {
        if (Yii::$app->request->isAjax) {
            \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            $mattraffic_id = Yii::$app->request->post('mattraffic_id');
            if (!empty($mattraffic_id)) {
                $query = Mattraffic::findOne($mattraffic_id);
                if (!empty($query)) {
                    return [
                        'material_tip' => $query->idMaterial->material_tip,
                        'material_name' => $query->idMaterial->material_name,
                        'material_writeoff' => $query->idMaterial->material_writeoff,
                        'material_install_cabinet' => $query->idMaterial->material_install_cabinet,
                        'auth_user_fullname' => $query->idMol->idperson->auth_user_fullname,
                        'dolzh_name' => $query->idMol->iddolzh->dolzh_name,
                        'podraz_name' => $query->idMol->idpodraz->podraz_name,
                        'build_name' => $query->idMol->idbuild->build_name,
                        'mattraffic_number' => doubleval(Mattraffic::GetMaxNumberMattrafficForInstallAkt($query->mattraffic_id)), // Максимльно возможное кол-во для перемещения
                    ];
                }
            }
        }
    }

    // Заполнение полей формы после выбора материальной ценности по инвентарнику
    public function actionMatvidCount()
    {
        if (Yii::$app->request->isAjax) {
            \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            $mattraffic_id = Yii::$app->request->post('mattraffic_id');
            $cabinet_id = Yii::$app->request->post('cabinet_id');
            $Mattraffic = Mattraffic::findOne($mattraffic_id);
            $matvid_id = $Mattraffic->idMaterial->id_matvid;
            $build_id = $Mattraffic->idMol->id_build;

            if (!(empty($mattraffic_id) || empty($cabinet_id) || empty($matvid_id) || empty($build_id))) {
                $sum = Mattraffic::find()
                    ->select('sum(mt1.mattraffic_number) as summ')
                    ->from('mattraffic mt1')
                    ->leftJoin('mattraffic mt2', 'mt1.id_material = mt2.id_material and (mt1.mattraffic_date < mt2.mattraffic_date or mt1.mattraffic_id < mt2.mattraffic_id)')
                    ->leftJoin('tr_osnov os', 'mt1.mattraffic_id = os.id_mattraffic')
                    ->leftJoin('material m', 'm.material_id = mt1.id_material')
                    ->leftJoin('employee e', 'e.employee_id = mt1.id_mol')
                    ->andWhere(['mt2.mattraffic_date' => null])
                    ->andWhere(['like', 'os.id_cabinet', $cabinet_id])
                    ->andWhere(['m.id_matvid' => $matvid_id])
                    ->andWhere(['e.id_build' => $build_id])
                    ->asArray()
                    ->one();

                if ($sum !== null) {
                    $sum['summ'] = $sum['summ'] === null ? 0 : $sum['summ'];
                    $cabinet = Cabinet::findOne($cabinet_id);

                    return [
                        'message' => "В кабинете \"{$cabinet->idbuild->build_name}, каб. {$cabinet->cabinet_name}\" уже имеется вид материальной ценности \"{$Mattraffic->idMaterial->idMatv->matvid_name}\" в количестве: {$sum['summ']}"
                    ];
                }
            } else {
                return [
                    'message' => "",
                ];
            }
        }
    }

    // Действие наполнения списка Select2 при помощи ajax
    public function actionSelectinputforosmotrakt($q = null)
    {
        if (Yii::$app->request->isAjax)
            return Proc::ResultSelect2([
                'model' => new TrOsnov,
                'q' => $q,
                'methodquery' => 'selectinputforosmotrakt',
            ]);
    }

    public function actionAssignToSelect2()
    {
        Proc::AssignToModelFromGrid();
    }

    // Заполнение полей формы после выбора материальной ценности по инвентарнику
    public function actionFillinstalledmat()
    {
        if (Yii::$app->request->isAjax) {
            \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            $id_tr_osnov = Yii::$app->request->post('id_tr_osnov');
            if (!empty($id_tr_osnov)) {
                $query = TrOsnov::findOne($id_tr_osnov);
                if (!empty($query)) {
                    return [
                        'material_name' => $query->idMattraffic->idMaterial->material_name,
                        'material_inv' => $query->idMattraffic->idMaterial->material_inv,
                        'material_serial' => $query->idMattraffic->idMaterial->material_serial,
                        'build_name' => $query->idMattraffic->idMol->idbuild->build_name,
                        'cabinet_name' => $query->idCabinet->cabinet_name,
                        'auth_user_fullname' => $query->idMattraffic->idMol->idperson->auth_user_fullname,
                        'dolzh_name' => $query->idMattraffic->idMol->iddolzh->dolzh_name,
                    ];
                }
            }
        }
    }

    // Удаление перемещаемой мат. цен-ти из акта установки
    public function actionDelete($id)
    {
        if (Yii::$app->request->isAjax) {
            $transaction = Yii::$app->db->beginTransaction();
            try {
                $tr_osnov = $this->findModel($id);
                $id_mattraffic = $tr_osnov->id_mattraffic;

                if ($tr_osnov->delete() === false)
                    throw new Exception('Не удалось удалить акт установки');

                $Mattraffic = Mattraffic::findOne($id_mattraffic)->delete();

                if ($Mattraffic === false)
                    throw new Exception('Не удалось удалить акт установки');

                echo $Mattraffic;

                $transaction->commit();
            } catch (Exception $e) {
                $transaction->rollBack();
                throw new Exception($e->getMessage());
            }
        }
    }

    /**
     * Finds the TrOsnov model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return TrOsnov the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = TrOsnov::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

}


text:
from functools import partial
import itertools

import numpy as np

from pandas._libs import algos as _algos, reshape as _reshape
from pandas._libs.sparse import IntIndex
from pandas.compat import PY2, range, text_type, u, zip

from pandas.core.dtypes.cast import maybe_promote
from pandas.core.dtypes.common import (
    ensure_platform_int, is_bool_dtype, is_extension_array_dtype,
    is_integer_dtype, is_list_like, is_object_dtype, needs_i8_conversion)
from pandas.core.dtypes.missing import notna

from pandas import compat
import pandas.core.algorithms as algos
from pandas.core.arrays import SparseArray
from pandas.core.arrays.categorical import _factorize_from_iterable
from pandas.core.frame import DataFrame
from pandas.core.index import Index, MultiIndex
from pandas.core.internals.arrays import extract_array
from pandas.core.series import Series
from pandas.core.sorting import (
    compress_group_index, decons_obs_group_ids, get_compressed_ids,
    get_group_index)

class _Unstacker(object):
    """
    Helper class to unstack data / pivot with multi-level index

    Parameters
    ----------
    values : ndarray
        Values of DataFrame to "Unstack"
    index : object
        Pandas ``Index``
    level : int or str, default last level
        Level to "unstack". Accepts a name for the level.
    value_columns : Index, optional
        Pandas ``Index`` or ``MultiIndex`` object if unstacking a DataFrame
    fill_value : scalar, optional
        Default value to fill in missing values if subgroups do not have the
        same set of labels. By default, missing values will be replaced with
        the default fill value for that data type, NaN for float, NaT for
        datetimelike, etc. For integer types, by default data will converted to
        float and missing values will be set to NaN.
    constructor : object
        Pandas ``DataFrame`` or subclass used to create unstacked
        response.  If None, DataFrame or SparseDataFrame will be used.

    Examples
    --------
    >>> index = pd.MultiIndex.from_tuples([('one', 'a'), ('one', 'b'),
    ...                                    ('two', 'a'), ('two', 'b')])
    >>> s = pd.Series(np.arange(1, 5, dtype=np.int64), index=index)
    >>> s
    one  a    1
         b    2
    two  a    3
         b    4
    dtype: int64

    >>> s.unstack(level=-1)
         a  b
    one  1  2
    two  3  4

    >>> s.unstack(level=0)
       one  two
    a    1    3
    b    2    4

    Returns
    -------
    unstacked : DataFrame
    """

    def __init__(self, values, index, level=-1, value_columns=None,
                 fill_value=None, constructor=None):

        if values.ndim == 1:
            values = values[:, np.newaxis]
        self.values = values
        self.value_columns = value_columns
        self.fill_value = fill_value

        if constructor is None:
            constructor = DataFrame
        self.constructor = constructor

        if value_columns is None and values.shape[1] != 1:  # pragma: no cover
            raise ValueError('must pass column labels for multi-column data')

        self.index = index.remove_unused_levels()

        self.level = self.index._get_level_number(level)

        # when index includes `nan`, need to lift levels/strides by 1
        self.lift = 1 if -1 in self.index.codes[self.level] else 0

        self.new_index_levels = list(self.index.levels)
        self.new_index_names = list(self.index.names)

        self.removed_name = self.new_index_names.pop(self.level)
        self.removed_level = self.new_index_levels.pop(self.level)
        self.removed_level_full = index.levels[self.level]

        # Bug fix GH 20601
        # If the data frame is too big, the number of unique index combination
        # will cause int32 overflow on windows environments.
        # We want to check and raise an error before this happens
        num_rows = np.max([index_level.size for index_level
                           in self.new_index_levels])
        num_columns = self.removed_level.size

        # GH20601: This forces an overflow if the number of cells is too high.
        num_cells = np.multiply(num_rows, num_columns, dtype=np.int32)

        if num_rows > 0 and num_columns > 0 and num_cells <= 0:
            raise ValueError('Unstacked DataFrame is too big, '
                             'causing int32 overflow')

        self._make_sorted_values_labels()
        self._make_selectors()

    def _make_sorted_values_labels(self):
        v = self.level

        codes = list(self.index.codes)
        levs = list(self.index.levels)
        to_sort = codes[:v] + codes[v + 1:] + [codes[v]]
        sizes = [len(x) for x in levs[:v] + levs[v + 1:] + [levs[v]]]

        comp_index, obs_ids = get_compressed_ids(to_sort, sizes)
        ngroups = len(obs_ids)

        indexer = _algos.groupsort_indexer(comp_index, ngroups)[0]
        indexer = ensure_platform_int(indexer)

        self.sorted_values = algos.take_nd(self.values, indexer, axis=0)
        self.sorted_labels = [l.take(indexer) for l in to_sort]

    def _make_selectors(self):
        new_levels = self.new_index_levels

        # make the mask
        remaining_labels = self.sorted_labels[:-1]
        level_sizes = [len(x) for x in new_levels]

        comp_index, obs_ids = get_compressed_ids(remaining_labels, level_sizes)
        ngroups = len(obs_ids)

        comp_index = ensure_platform_int(comp_index)
        stride = self.index.levshape[self.level] + self.lift
        self.full_shape = ngroups, stride

        selector = self.sorted_labels[-1] + stride * comp_index + self.lift
        mask = np.zeros(np.prod(self.full_shape), dtype=bool)
        mask.put(selector, True)

        if mask.sum() < len(self.index):
            raise ValueError('Index contains duplicate entries, '
                             'cannot reshape')

        self.group_index = comp_index
        self.mask = mask
        self.unique_groups = obs_ids
        self.compressor = comp_index.searchsorted(np.arange(ngroups))

    def get_result(self):
        values, _ = self.get_new_values()
        columns = self.get_new_columns()
        index = self.get_new_index()

        return self.constructor(values, index=index, columns=columns)

    def get_new_values(self):
        values = self.values

        # place the values
        length, width = self.full_shape
        stride = values.shape[1]
        result_width = width * stride
        result_shape = (length, result_width)
        mask = self.mask
        mask_all = mask.all()

        # we can simply reshape if we don't have a mask
        if mask_all and len(values):
            new_values = (self.sorted_values
                              .reshape(length, width, stride)
                              .swapaxes(1, 2)
                              .reshape(result_shape)
                          )
            new_mask = np.ones(result_shape, dtype=bool)
            return new_values, new_mask

        # if our mask is all True, then we can use our existing dtype
        if mask_all:
            dtype = values.dtype
            new_values = np.empty(result_shape, dtype=dtype)
        else:
            dtype, fill_value = maybe_promote(values.dtype, self.fill_value)
            new_values = np.empty(result_shape, dtype=dtype)
            new_values.fill(fill_value)

        new_mask = np.zeros(result_shape, dtype=bool)

        name = np.dtype(dtype).name
        sorted_values = self.sorted_values

        # we need to convert to a basic dtype
        # and possibly coerce an input to our output dtype
        # e.g. ints -> floats
        if needs_i8_conversion(values):
            sorted_values = sorted_values.view('i8')
            new_values = new_values.view('i8')
            name = 'int64'
        elif is_bool_dtype(values):
            sorted_values = sorted_values.astype('object')
            new_values = new_values.astype('object')
            name = 'object'
        else:
            sorted_values = sorted_values.astype(name, copy=False)

        # fill in our values & mask
        f = getattr(_reshape, "unstack_{name}".format(name=name))
        f(sorted_values,
          mask.view('u1'),
          stride,
          length,
          width,
          new_values,
          new_mask.view('u1'))

        # reconstruct dtype if needed
        if needs_i8_conversion(values):
            new_values = new_values.view(values.dtype)

        return new_values, new_mask

    def get_new_columns(self):
        if self.value_columns is None:
            if self.lift == 0:
                return self.removed_level

            lev = self.removed_level
            return lev.insert(0, lev._na_value)

        stride = len(self.removed_level) + self.lift
        width = len(self.value_columns)
        propagator = np.repeat(np.arange(width), stride)
        if isinstance(self.value_columns, MultiIndex):
            new_levels = self.value_columns.levels + (self.removed_level_full,)
            new_names = self.value_columns.names + (self.removed_name,)

            new_codes = [lab.take(propagator)
                         for lab in self.value_columns.codes]
        else:
            new_levels = [self.value_columns, self.removed_level_full]
            new_names = [self.value_columns.name, self.removed_name]
            new_codes = [propagator]

        # The two indices differ only if the unstacked level had unused items:
        if len(self.removed_level_full) != len(self.removed_level):
            # In this case, we remap the new codes to the original level:
            repeater = self.removed_level_full.get_indexer(self.removed_level)
            if self.lift:
                repeater = np.insert(repeater, 0, -1)
        else:
            # Otherwise, we just use each level item exactly once:
            repeater = np.arange(stride) - self.lift

        # The entire level is then just a repetition of the single chunk:
        new_codes.append(np.tile(repeater, width))
        return MultiIndex(levels=new_levels, codes=new_codes,
                          names=new_names, verify_integrity=False)

    def get_new_index(self):
        result_codes = [lab.take(self.compressor)
                        for lab in self.sorted_labels[:-1]]

        # construct the new index
        if len(self.new_index_levels) == 1:
            lev, lab = self.new_index_levels[0], result_codes[0]
            if (lab == -1).any():
                lev = lev.insert(len(lev), lev._na_value)
            return lev.take(lab)

        return MultiIndex(levels=self.new_index_levels, codes=result_codes,
                          names=self.new_index_names, verify_integrity=False)

def _unstack_multiple(data, clocs, fill_value=None):
    if len(clocs) == 0:
        return data

    # NOTE: This doesn't deal with hierarchical columns yet

    index = data.index

    clocs = [index._get_level_number(i) for i in clocs]

    rlocs = [i for i in range(index.nlevels) if i not in clocs]

    clevels = [index.levels[i] for i in clocs]
    ccodes = [index.codes[i] for i in clocs]
    cnames = [index.names[i] for i in clocs]
    rlevels = [index.levels[i] for i in rlocs]
    rcodes = [index.codes[i] for i in rlocs]
    rnames = [index.names[i] for i in rlocs]

    shape = [len(x) for x in clevels]
    group_index = get_group_index(ccodes, shape, sort=False, xnull=False)

    comp_ids, obs_ids = compress_group_index(group_index, sort=False)
    recons_codes = decons_obs_group_ids(comp_ids, obs_ids, shape, ccodes,
                                        xnull=False)

    if rlocs == []:
        # Everything is in clocs, so the dummy df has a regular index
        dummy_index = Index(obs_ids, name='__placeholder__')
    else:
        dummy_index = MultiIndex(levels=rlevels + [obs_ids],
                                 codes=rcodes + [comp_ids],
                                 names=rnames + ['__placeholder__'],
                                 verify_integrity=False)

    if isinstance(data, Series):
        dummy = data.copy()
        dummy.index = dummy_index

        unstacked = dummy.unstack('__placeholder__', fill_value=fill_value)
        new_levels = clevels
        new_names = cnames
        new_codes = recons_codes
    else:
        if isinstance(data.columns, MultiIndex):
            result = data
            for i in range(len(clocs)):
                val = clocs[i]
                result = result.unstack(val)
                clocs = [v if i > v else v - 1 for v in clocs]

            return result

        dummy = data.copy()
        dummy.index = dummy_index

        unstacked = dummy.unstack('__placeholder__', fill_value=fill_value)
        if isinstance(unstacked, Series):
            unstcols = unstacked.index
        else:
            unstcols = unstacked.columns
        new_levels = [unstcols.levels[0]] + clevels
        new_names = [data.columns.name] + cnames

        new_codes = [unstcols.codes[0]]
        for rec in recons_codes:
            new_codes.append(rec.take(unstcols.codes[-1]))

    new_columns = MultiIndex(levels=new_levels, codes=new_codes,
                             names=new_names, verify_integrity=False)

    if isinstance(unstacked, Series):
        unstacked.index = new_columns
    else:
        unstacked.columns = new_columns

    return unstacked

def unstack(obj, level, fill_value=None):
    if isinstance(level, (tuple, list)):
        if len(level) != 1:
            # _unstack_multiple only handles MultiIndexes,
            # and isn't needed for a single level
            return _unstack_multiple(obj, level, fill_value=fill_value)
        else:
            level = level[0]

    if isinstance(obj, DataFrame):
        if isinstance(obj.index, MultiIndex):
            return _unstack_frame(obj, level, fill_value=fill_value)
        else:
            return obj.T.stack(dropna=False)
    else:
        if is_extension_array_dtype(obj.dtype):
            return _unstack_extension_series(obj, level, fill_value)
        unstacker = _Unstacker(obj.values, obj.index, level=level,
                               fill_value=fill_value,
                               constructor=obj._constructor_expanddim)
        return unstacker.get_result()

def _unstack_frame(obj, level, fill_value=None):
    if obj._is_mixed_type:
        unstacker = partial(_Unstacker, index=obj.index,
                            level=level, fill_value=fill_value)
        blocks = obj._data.unstack(unstacker,
                                   fill_value=fill_value)
        return obj._constructor(blocks)
    else:
        unstacker = _Unstacker(obj.values, obj.index, level=level,
                               value_columns=obj.columns,
                               fill_value=fill_value,
                               constructor=obj._constructor)
        return unstacker.get_result()

def _unstack_extension_series(series, level, fill_value):
    """
    Unstack an ExtensionArray-backed Series.

    The ExtensionDtype is preserved.

    Parameters
    ----------
    series : Series
        A Series with an ExtensionArray for values
    level : Any
        The level name or number.
    fill_value : Any
        The user-level (not physical storage) fill value to use for
        missing values introduced by the reshape. Passed to
        ``series.values.take``.

    Returns
    -------
    DataFrame
        Each column of the DataFrame will have the same dtype as
        the input Series.
    """
    # Implementation note: the basic idea is to
    # 1. Do a regular unstack on a dummy array of integers
    # 2. Followup with a columnwise take.
    # We use the dummy take to discover newly-created missing values
    # introduced by the reshape.
    from pandas.core.reshape.concat import concat

    dummy_arr = np.arange(len(series))
    # fill_value=-1, since we will do a series.values.take later
    result = _Unstacker(dummy_arr, series.index,
                        level=level, fill_value=-1).get_result()

    out = []
    values = extract_array(series, extract_numpy=False)

    for col, indices in result.iteritems():
        out.append(Series(values.take(indices.values,
                                      allow_fill=True,
                                      fill_value=fill_value),
                          name=col, index=result.index))
    return concat(out, axis='columns', copy=False, keys=result.columns)

def stack(frame, level=-1, dropna=True):
    """
    Convert DataFrame to Series with multi-level Index. Columns become the
    second level of the resulting hierarchical index

    Returns
    -------
    stacked : Series
    """
    def factorize(index):
        if index.is_unique:
            return index, np.arange(len(index))
        codes, categories = _factorize_from_iterable(index)
        return categories, codes

    N, K = frame.shape

    # Will also convert negative level numbers and check if out of bounds.
    level_num = frame.columns._get_level_number(level)

    if isinstance(frame.columns, MultiIndex):
        return _stack_multi_columns(frame, level_num=level_num, dropna=dropna)
    elif isinstance(frame.index, MultiIndex):
        new_levels = list(frame.index.levels)
        new_codes = [lab.repeat(K) for lab in frame.index.codes]

        clev, clab = factorize(frame.columns)
        new_levels.append(clev)
        new_codes.append(np.tile(clab, N).ravel())

        new_names = list(frame.index.names)
        new_names.append(frame.columns.name)
        new_index = MultiIndex(levels=new_levels, codes=new_codes,
                               names=new_names, verify_integrity=False)
    else:
        levels, (ilab, clab) = zip(*map(factorize, (frame.index,
                                                    frame.columns)))
        codes = ilab.repeat(K), np.tile(clab, N).ravel()
        new_index = MultiIndex(levels=levels, codes=codes,
                               names=[frame.index.name, frame.columns.name],
                               verify_integrity=False)

    if frame._is_homogeneous_type:
        # For homogeneous EAs, frame.values will coerce to object. So
        # we concatenate instead.
        dtypes = list(frame.dtypes.values)
        dtype = dtypes[0]

        if is_extension_array_dtype(dtype):
            arr = dtype.construct_array_type()
            new_values = arr._concat_same_type([
                col._values for _, col in frame.iteritems()
            ])
            new_values = _reorder_for_extension_array_stack(new_values, N, K)
        else:
            # homogeneous, non-EA
            new_values = frame.values.ravel()

    else:
        # non-homogeneous
        new_values = frame.values.ravel()

    if dropna:
        mask = notna(new_values)
        new_values = new_values[mask]
        new_index = new_index[mask]

    return frame._constructor_sliced(new_values, index=new_index)

def stack_multiple(frame, level, dropna=True):
    # If all passed levels match up to column names, no
    # ambiguity about what to do
    if all(lev in frame.columns.names for lev in level):
        result = frame
        for lev in level:
            result = stack(result, lev, dropna=dropna)

    # Otherwise, level numbers may change as each successive level is stacked
    elif all(isinstance(lev, int) for lev in level):
        # As each stack is done, the level numbers decrease, so we need
        #  to account for that when level is a sequence of ints
        result = frame
        # _get_level_number() checks level numbers are in range and converts
        # negative numbers to positive
        level = [frame.columns._get_level_number(lev) for lev in level]

        # Can't iterate directly through level as we might need to change
        # values as we go
        for index in range(len(level)):
            lev = level[index]
            result = stack(result, lev, dropna=dropna)
            # Decrement all level numbers greater than current, as these
            # have now shifted down by one
            updated_level = []
            for other in level:
                if other > lev:
                    updated_level.append(other - 1)
                else:
                    updated_level.append(other)
            level = updated_level

    else:
        raise ValueError("level should contain all level names or all level "
                         "numbers, not a mixture of the two.")

    return result

def _stack_multi_columns(frame, level_num=-1, dropna=True):
    def _convert_level_number(level_num, columns):
        """
        Logic for converting the level number to something we can safely pass
        to swaplevel:

        We generally want to convert the level number into a level name, except
        when columns do not have names, in which case we must leave as a level
        number
        """
        if level_num in columns.names:
            return columns.names[level_num]
        else:
            if columns.names[level_num] is None:
                return level_num
            else:
                return columns.names[level_num]

    this = frame.copy()

    # this makes life much simpler
    if level_num != frame.columns.nlevels - 1:
        # roll levels to put selected level at end
        roll_columns = this.columns
        for i in range(level_num, frame.columns.nlevels - 1):
            # Need to check if the ints conflict with level names
            lev1 = _convert_level_number(i, roll_columns)
            lev2 = _convert_level_number(i + 1, roll_columns)
            roll_columns = roll_columns.swaplevel(lev1, lev2)
        this.columns = roll_columns

    if not this.columns.is_lexsorted():
        # Workaround the edge case where 0 is one of the column names,
        # which interferes with trying to sort based on the first
        # level
        level_to_sort = _convert_level_number(0, this.columns)
        this = this.sort_index(level=level_to_sort, axis=1)

    # tuple list excluding level for grouping columns
    if len(frame.columns.levels) > 2:
        tuples = list(zip(*[lev.take(level_codes) for lev, level_codes
                            in zip(this.columns.levels[:-1],
                                   this.columns.codes[:-1])]))
        unique_groups = [key for key, _ in itertools.groupby(tuples)]
        new_names = this.columns.names[:-1]
        new_columns = MultiIndex.from_tuples(unique_groups, names=new_names)
    else:
        new_columns = unique_groups = this.columns.levels[0]

    # time to ravel the values
    new_data = {}
    level_vals = this.columns.levels[-1]
    level_codes = sorted(set(this.columns.codes[-1]))
    level_vals_used = level_vals[level_codes]
    levsize = len(level_codes)
    drop_cols = []
    for key in unique_groups:
        try:
            loc = this.columns.get_loc(key)
        except KeyError:
            drop_cols.append(key)
            continue

        # can make more efficient?
        # we almost always return a slice
        # but if unsorted can get a boolean
        # indexer
        if not isinstance(loc, slice):
            slice_len = len(loc)
        else:
            slice_len = loc.stop - loc.start

        if slice_len != levsize:
            chunk = this.loc[:, this.columns[loc]]
            chunk.columns = level_vals.take(chunk.columns.codes[-1])
            value_slice = chunk.reindex(columns=level_vals_used).values
        else:
            if (frame._is_homogeneous_type and
                    is_extension_array_dtype(frame.dtypes.iloc[0])):
                dtype = this[this.columns[loc]].dtypes.iloc[0]
                subset = this[this.columns[loc]]

                value_slice = dtype.construct_array_type()._concat_same_type(
                    [x._values for _, x in subset.iteritems()]
                )
                N, K = this.shape
                idx = np.arange(N * K).reshape(K, N).T.ravel()
                value_slice = value_slice.take(idx)

            elif frame._is_mixed_type:
                value_slice = this[this.columns[loc]].values
            else:
                value_slice = this.values[:, loc]

        if value_slice.ndim > 1:
            # i.e. not extension
            value_slice = value_slice.ravel()

        new_data[key] = value_slice

    if len(drop_cols) > 0:
        new_columns = new_columns.difference(drop_cols)

    N = len(this)

    if isinstance(this.index, MultiIndex):
        new_levels = list(this.index.levels)
        new_names = list(this.index.names)
        new_codes = [lab.repeat(levsize) for lab in this.index.codes]
    else:
        new_levels = [this.index]
        new_codes = [np.arange(N).repeat(levsize)]
        new_names = [this.index.name]  # something better?

    new_levels.append(level_vals)
    new_codes.append(np.tile(level_codes, N))
    new_names.append(frame.columns.names[level_num])

    new_index = MultiIndex(levels=new_levels, codes=new_codes,
                           names=new_names, verify_integrity=False)

    result = frame._constructor(new_data, index=new_index, columns=new_columns)

    # more efficient way to go about this? can do the whole masking biz but
    # will only save a small amount of time...
    if dropna:
        result = result.dropna(axis=0, how='all')

    return result

def get_dummies(data, prefix=None, prefix_sep='_', dummy_na=False,
                columns=None, sparse=False, drop_first=False, dtype=None):
    """
    Convert categorical variable into dummy/indicator variables.

    Parameters
    ----------
    data : array-like, Series, or DataFrame
        Data of which to get dummy indicators.
    prefix : str, list of str, or dict of str, default None
        String to append DataFrame column names.
        Pass a list with length equal to the number of columns
        when calling get_dummies on a DataFrame. Alternatively, `prefix`
        can be a dictionary mapping column names to prefixes.
    prefix_sep : str, default '_'
        If appending prefix, separator/delimiter to use. Or pass a
        list or dictionary as with `prefix`.
    dummy_na : bool, default False
        Add a column to indicate NaNs, if False NaNs are ignored.
    columns : list-like, default None
        Column names in the DataFrame to be encoded.
        If `columns` is None then all the columns with
        `object` or `category` dtype will be converted.
    sparse : bool, default False
        Whether the dummy-encoded columns should be be backed by
        a :class:`SparseArray` (True) or a regular NumPy array (False).
    drop_first : bool, default False
        Whether to get k-1 dummies out of k categorical levels by removing the
        first level.

        .. versionadded:: 0.18.0

    dtype : dtype, default np.uint8
        Data type for new columns. Only a single dtype is allowed.

        .. versionadded:: 0.23.0

    Returns
    -------
    DataFrame
        Dummy-coded data.

    See Also
    --------
    Series.str.get_dummies : Convert Series to dummy codes.

    Examples
    --------
    >>> s = pd.Series(list('abca'))

    >>> pd.get_dummies(s)
       a  b  c
    0  1  0  0
    1  0  1  0
    2  0  0  1
    3  1  0  0

    >>> s1 = ['a', 'b', np.nan]

    >>> pd.get_dummies(s1)
       a  b
    0  1  0
    1  0  1
    2  0  0

    >>> pd.get_dummies(s1, dummy_na=True)
       a  b  NaN
    0  1  0    0
    1  0  1    0
    2  0  0    1

    >>> df = pd.DataFrame({'A': ['a', 'b', 'a'], 'B': ['b', 'a', 'c'],
    ...                    'C': [1, 2, 3]})

    >>> pd.get_dummies(df, prefix=['col1', 'col2'])
       C  col1_a  col1_b  col2_a  col2_b  col2_c
    0  1       1       0       0       1       0
    1  2       0       1       1       0       0
    2  3       1       0       0       0       1

    >>> pd.get_dummies(pd.Series(list('abcaa')))
       a  b  c
    0  1  0  0
    1  0  1  0
    2  0  0  1
    3  1  0  0
    4  1  0  0

    >>> pd.get_dummies(pd.Series(list('abcaa')), drop_first=True)
       b  c
    0  0  0
    1  1  0
    2  0  1
    3  0  0
    4  0  0

    >>> pd.get_dummies(pd.Series(list('abc')), dtype=float)
         a    b    c
    0  1.0  0.0  0.0
    1  0.0  1.0  0.0
    2  0.0  0.0  1.0
    """
    from pandas.core.reshape.concat import concat
    from itertools import cycle

    dtypes_to_encode = ['object', 'category']

    if isinstance(data, DataFrame):
        # determine columns being encoded
        if columns is None:
            data_to_encode = data.select_dtypes(
                include=dtypes_to_encode)
        else:
            data_to_encode = data[columns]

        # validate prefixes and separator to avoid silently dropping cols
        def check_len(item, name):
            len_msg = ("Length of '{name}' ({len_item}) did not match the "
                       "length of the columns being encoded ({len_enc}).")

            if is_list_like(item):
                if not len(item) == data_to_encode.shape[1]:
                    len_msg = len_msg.format(name=name, len_item=len(item),
                                             len_enc=data_to_encode.shape[1])
                    raise ValueError(len_msg)

        check_len(prefix, 'prefix')
        check_len(prefix_sep, 'prefix_sep')

        if isinstance(prefix, compat.string_types):
            prefix = cycle([prefix])
        if isinstance(prefix, dict):
            prefix = [prefix[col] for col in data_to_encode.columns]

        if prefix is None:
            prefix = data_to_encode.columns

        # validate separators
        if isinstance(prefix_sep, compat.string_types):
            prefix_sep = cycle([prefix_sep])
        elif isinstance(prefix_sep, dict):
            prefix_sep = [prefix_sep[col] for col in data_to_encode.columns]

        if data_to_encode.shape == data.shape:
            # Encoding the entire df, do not prepend any dropped columns
            with_dummies = []
        elif columns is not None:
            # Encoding only cols specified in columns. Get all cols not in
            # columns to prepend to result.
            with_dummies = [data.drop(columns, axis=1)]
        else:
            # Encoding only object and category dtype columns. Get remaining
            # columns to prepend to result.
            with_dummies = [data.select_dtypes(exclude=dtypes_to_encode)]

        for (col, pre, sep) in zip(data_to_encode.iteritems(), prefix,
                                   prefix_sep):
            # col is (column_name, column), use just column data here
            dummy = _get_dummies_1d(col[1], prefix=pre, prefix_sep=sep,
                                    dummy_na=dummy_na, sparse=sparse,
                                    drop_first=drop_first, dtype=dtype)
            with_dummies.append(dummy)
        result = concat(with_dummies, axis=1)
    else:
        result = _get_dummies_1d(data, prefix, prefix_sep, dummy_na,
                                 sparse=sparse,
                                 drop_first=drop_first,
                                 dtype=dtype)
    return result

def _get_dummies_1d(data, prefix, prefix_sep='_', dummy_na=False,
                    sparse=False, drop_first=False, dtype=None):
    from pandas.core.reshape.concat import concat
    # Series avoids inconsistent NaN handling
    codes, levels = _factorize_from_iterable(Series(data))

    if dtype is None:
        dtype = np.uint8
    dtype = np.dtype(dtype)

    if is_object_dtype(dtype):
        raise ValueError("dtype=object is not a valid dtype for get_dummies")

    def get_empty_frame(data):
        if isinstance(data, Series):
            index = data.index
        else:
            index = np.arange(len(data))
        return DataFrame(index=index)

    # if all NaN
    if not dummy_na and len(levels) == 0:
        return get_empty_frame(data)

    codes = codes.copy()
    if dummy_na:
        codes[codes == -1] = len(levels)
        levels = np.append(levels, np.nan)

    # if dummy_na, we just fake a nan level. drop_first will drop it again
    if drop_first and len(levels) == 1:
        return get_empty_frame(data)

    number_of_cols = len(levels)

    if prefix is None:
        dummy_cols = levels
    else:

        # PY2 embedded unicode, gh-22084
        def _make_col_name(prefix, prefix_sep, level):
            fstr = '{prefix}{prefix_sep}{level}'
            if PY2 and (isinstance(prefix, text_type) or
                        isinstance(prefix_sep, text_type) or
                        isinstance(level, text_type)):
                fstr = u(fstr)
            return fstr.format(prefix=prefix,
                               prefix_sep=prefix_sep,
                               level=level)

        dummy_cols = [_make_col_name(prefix, prefix_sep, level)
                      for level in levels]

    if isinstance(data, Series):
        index = data.index
    else:
        index = None

    if sparse:

        if is_integer_dtype(dtype):
            fill_value = 0
        elif dtype == bool:
            fill_value = False
        else:
            fill_value = 0.0

        sparse_series = []
        N = len(data)
        sp_indices = [[] for _ in range(len(dummy_cols))]
        mask = codes != -1
        codes = codes[mask]
        n_idx = np.arange(N)[mask]

        for ndx, code in zip(n_idx, codes):
            sp_indices[code].append(ndx)

        if drop_first:
            # remove first categorical level to avoid perfect collinearity
            # GH12042
            sp_indices = sp_indices[1:]
            dummy_cols = dummy_cols[1:]
        for col, ixs in zip(dummy_cols, sp_indices):
            sarr = SparseArray(np.ones(len(ixs), dtype=dtype),
                               sparse_index=IntIndex(N, ixs),
                               fill_value=fill_value,
                               dtype=dtype)
            sparse_series.append(Series(data=sarr, index=index, name=col))

        out = concat(sparse_series, axis=1, copy=False)
        return out

    else:
        dummy_mat = np.eye(number_of_cols, dtype=dtype).take(codes, axis=0)

        if not dummy_na:
            # reset NaN GH4446
            dummy_mat[codes == -1] = 0

        if drop_first:
            # remove first GH12042
            dummy_mat = dummy_mat[:, 1:]
            dummy_cols = dummy_cols[1:]
        return DataFrame(dummy_mat, index=index, columns=dummy_cols)

def make_axis_dummies(frame, axis='minor', transform=None):
    """
    Construct 1-0 dummy variables corresponding to designated axis
    labels

    Parameters
    ----------
    frame : DataFrame
    axis : {'major', 'minor'}, default 'minor'
    transform : function, default None
        Function to apply to axis labels first. For example, to
        get "day of week" dummies in a time series regression
        you might call::

            make_axis_dummies(panel, axis='major',
                              transform=lambda d: d.weekday())
    Returns
    -------
    dummies : DataFrame
        Column names taken from chosen axis
    """
    numbers = {'major': 0, 'minor': 1}
    num = numbers.get(axis, axis)

    items = frame.index.levels[num]
    codes = frame.index.codes[num]
    if transform is not None:
        mapped_items = items.map(transform)
        codes, items = _factorize_from_iterable(mapped_items.take(codes))

    values = np.eye(len(items), dtype=float)
    values = values.take(codes, axis=0)

    return DataFrame(values, columns=items, index=frame.index)

def _reorder_for_extension_array_stack(arr, n_rows, n_columns):
    """
    Re-orders the values when stacking multiple extension-arrays.

    The indirect stacking method used for EAs requires a followup
    take to get the order correct.

    Parameters
    ----------
    arr : ExtensionArray
    n_rows, n_columns : int
        The number of rows and columns in the original DataFrame.

    Returns
    -------
    taken : ExtensionArray
        The original `arr` with elements re-ordered appropriately

    Examples
    --------
    >>> arr = np.array(['a', 'b', 'c', 'd', 'e', 'f'])
    >>> _reorder_for_extension_array_stack(arr, 2, 3)
    array(['a', 'c', 'e', 'b', 'd', 'f'], dtype='<U1')

    >>> _reorder_for_extension_array_stack(arr, 3, 2)
    array(['a', 'd', 'b', 'e', 'c', 'f'], dtype='<U1')
    """
    # final take to get the order correct.
    # idx is an indexer like
    # [c0r0, c1r0, c2r0, ...,
    #  c0r1, c1r1, c2r1, ...]
    idx = np.arange(n_rows * n_columns).reshape(n_columns, n_rows).T.ravel()
    return arr.take(idx)


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
  <title>Test subject</title>

  <script type="text/javascript"
    src="closure-library-read-only/closure/goog/base.js">
  </script>
  <script type="text/javascript">
    goog.require('goog.events.EventHandler');
    goog.require('goog.events.EventTarget');
    goog.require('goog.testing.jsunit');
  </script>
  <script type="text/javascript" src="subject.js"></script>
  <script type="text/javascript" src="mocksubjects.js"></script>
</head>
<body class="body">
<script type="text/javascript">

function testOneRoot() {
  var treeModel = new lantern.subject.SubjectTreeModel();

  var root = new lantern.subject.SubjectItem('math', null);
  treeModel.addSubject(root, null);

  var subjects = treeModel.getChildSubjects(null);
  assertEquals(1, subjects.length);
  assertEquals('math', subjects[0].displayText);

  assertEquals(root, treeModel.getSubject('math'));
  assertUndefined(treeModel.getParent('math'));
}

function testNonexistentSubject() {
  var treeModel = new lantern.subject.SubjectTreeModel();

  var root = new lantern.subject.SubjectItem('math', null);
  treeModel.addSubject(root, null);

  assertUndefined(treeModel.getSubject('New math'));
}

function testRoots() {
  var treeModel = new lantern.subject.SubjectTreeModel();
  var roots = [
      new lantern.subject.SubjectItem('math', null),
      new lantern.subject.SubjectItem('technology', null),
      new lantern.subject.SubjectItem('communication', null)
      ];
  var numRoots = roots.length;
  for (var i = 0; i < numRoots; ++i) {
    treeModel.addSubject(roots[i], null);
  }

  var subjects = treeModel.getChildSubjects(null);
  assertEquals(3, subjects.length);
  assertEquals('math', subjects[0].displayText);
  assertEquals('communication', subjects[2].displayText);

  assertEquals(roots[2], treeModel.getSubject('communication'));
}

function testChildren() {
  var treeModel = new lantern.subject.SubjectTreeModel();
  var roots = [
      new lantern.subject.SubjectItem('math', null),
      new lantern.subject.SubjectItem('technology', null),
      new lantern.subject.SubjectItem('communication', null)
      ];

  var numRoots = roots.length;
  for (var i = 0; i < numRoots; ++i) {
    treeModel.addSubject(roots[i], null);
  }
  var techItems = [
      new lantern.subject.SubjectItem('physics', null),
      new lantern.subject.SubjectItem('chemistry', null),
      new lantern.subject.SubjectItem('medicine', null),
      new lantern.subject.SubjectItem('engineering', null)
      ];
  var numItems = techItems.length;
  for (var i = 0; i < numItems; ++i) {
    treeModel.addSubject(techItems[i], 'technology');
  }

  var engItems = [
      new lantern.subject.SubjectItem('mechanical', null),
      new lantern.subject.SubjectItem('electrical', null),
      new lantern.subject.SubjectItem('software/computation', null)
      ];
  numItems = engItems.length;
  for (var i = 0; i < numItems; ++i) {
    treeModel.addSubject(engItems[i], 'engineering');
  }
  assertEquals(10, treeModel.getCount());

  var subjects = treeModel.getChildSubjects(null);
  assertEquals(3, subjects.length);

  subjects = treeModel.getChildSubjects('technology');
  assertNotNullNorUndefined(subjects);
  assertEquals(4, subjects.length);

  subjects = treeModel.getChildSubjects('engineering');
  assertNotNullNorUndefined(subjects);
  assertEquals(3, subjects.length);

  assertEquals(engItems[1], treeModel.getSubject('electrical'));
   assertEquals(techItems[3], treeModel.getParent('electrical'));
  assertEquals('engineering', treeModel.getParent('electrical').id);
}

function testClear() {
  var treeModel = new lantern.subject.SubjectTreeModel();
  var roots = [
      new lantern.subject.SubjectItem('math', null),
      new lantern.subject.SubjectItem('technology', null),
      new lantern.subject.SubjectItem('communication', null)
      ];
  var numRoots = roots.length;
  for (var i = 0; i < numRoots; ++i) {
    treeModel.addSubject(roots[i], null);
  }
  assertEquals(3, treeModel.getCount());
  assertFalse(treeModel.isEmpty());

  treeModel.clear();
  assertEquals(0, treeModel.getCount());
  assertTrue(treeModel.isEmpty());
}

function testMockSubjectProvider() {
  var provider = new lantern.subject.MockSubjectProvider();

  var subject = provider.getSubject('technology');
  assertNotNullNorUndefined(subject);

  var subjects = provider.getChildSubjects('technology');
  assertEquals(6, subjects.length);
}

function testMockSubjectProviderLoad() {
  var provider = new lantern.subject.MockSubjectProvider();

  var eh = new goog.events.EventHandler(this);
  var wasCalled = false;
  eh.listen(provider, lantern.subject.SubjectProvider.EventType.DATA_READY,
            function(e) {
              var subjects = e.target.getChildSubjects('technology');
              assertEquals(6, subjects.length);
              wasCalled = true;
            });
  assertFalse(wasCalled);

  provider.loadSubjects(null);
  assertTrue(wasCalled);
}
</script>
</body>
</html>


text:
'use strict'

var inherits = require('inherits')
var EventEmitter = require('node-event-emitter')
var libxmljs = require('libxmljs')

function SaxLibxmljs () {
  EventEmitter.call(this)
  this.parser = new libxmljs.SaxPushParser()

  var that = this

  this.parser.on('startElementNS', function (name, attrs, prefix, uri, nss) {
    var a = {}
    attrs.forEach(function (attr) {
      var name = attr[0]
      if (attr[1]) name = attr[1] + ':' + name
      a[name] = attr[3]
    })
    nss.forEach(function (ns) {
      var name = 'xmlns'
      if (ns[0] !== null) {
        name += (':' + ns[0])
      }
      a[name] = ns[1]
    })
    that.emit('startElement', (prefix ? prefix + ':' : '') + name, a)
  })

  this.parser.on('endElementNS', function (name, prefix) {
    that.emit('endElement', (prefix ? prefix + ':' : '') + name)
  })

  this.parser.on('characters', function (str) {
    that.emit('text', str)
  })

  this.parser.on('cadata', function (str) {
    that.emit('text', str)
  })

  this.parser.on('error', function (err) {
    that.emit('error', err)
  })
}

inherits(SaxLibxmljs, EventEmitter)

SaxLibxmljs.prototype.write = function (data) {
  if (typeof data !== 'string') {
    data = data.toString()
  }
  this.parser.push(data)
}

SaxLibxmljs.prototype.end = function (data) {
  if (data) {
    this.write(data)
  }
}

module.exports = SaxLibxmljs


text:
  Plovan est
       un village
       localisé dans le département de Finistère en Bretagne. Elle totalisait 667 habitants en 2008.

À proximité de Plovan sont positionnées géographiquement les communes de
Peumérit localisée à 4 km, 771 habitants,
Saint-Jean-Trolimon localisée à 8 km, 954 habitants,
Pouldreuzic à 4 km, 1 814 habitants,
Landudec localisée à 9 km, 1 262 habitants,
Tréguennec localisée à 3 km, 338 habitants,
Tréogat située à 2 km, 492 habitants,
 entre autres. De plus, Plovan est située à seulement 21 km de Quimper.

À Plovan, le prix moyen à l'achat d'un appartement se situe à zero € du m² en vente. Le prix moyen d'une maison à l'achat se situe à 2 437 € du m². À la location la valorisation moyenne se situe à 6,34 € du m² par mois.

La ville propose quelques  équipements, elle propose entre autres un terrain de sport, une base nautique et une boucle de randonnée.

Le nombre d'habitations, à Plovan, se décomposait en 2011 en dix appartements et 561 maisons soit
 un marché plutôt équilibré.

Si vous envisagez de demenager à Plovan, vous pourrez aisément trouver une maison à vendre.


text:
package org.elasticsearch.xpack.ml.integration;

import org.apache.http.util.EntityUtils;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.ResponseException;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.test.SecuritySettingsSourceField;
import org.elasticsearch.test.rest.ESRestTestCase;
import org.elasticsearch.xpack.core.security.authc.support.UsernamePasswordToken;
import org.junit.Before;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;

public class ExplainDataFrameAnalyticsRestIT extends ESRestTestCase {

    private static String basicAuth(String user) {
        return UsernamePasswordToken.basicAuthHeaderValue(user, SecuritySettingsSourceField.TEST_PASSWORD_SECURE_STRING);
    }

    private static final String SUPER_USER = "x_pack_rest_user";
    private static final String ML_ADMIN = "ml_admin";
    private static final String BASIC_AUTH_VALUE_SUPER_USER = basicAuth(SUPER_USER);
    private static final String AUTH_KEY = "Authorization";
    private static final String SECONDARY_AUTH_KEY = "es-secondary-authorization";

    private static RequestOptions.Builder addAuthHeader(RequestOptions.Builder builder, String user) {
        builder.addHeader(AUTH_KEY, basicAuth(user));
        return builder;
    }

    private static RequestOptions.Builder addSecondaryAuthHeader(RequestOptions.Builder builder, String user) {
        builder.addHeader(SECONDARY_AUTH_KEY, basicAuth(user));
        return builder;
    }

    @Override
    protected Settings restClientSettings() {
        return Settings.builder().put(ThreadContext.PREFIX + ".Authorization", BASIC_AUTH_VALUE_SUPER_USER).build();
    }

    private void setupUser(String user, List<String> roles) throws IOException {
        String password = new String(SecuritySettingsSourceField.TEST_PASSWORD_SECURE_STRING.getChars());

        Request request = new Request("PUT", "/_security/user/" + user);
        request.setJsonEntity("{"
                + "  \"password\" : \"" + password + "\","
                + "  \"roles\" : [ " + roles.stream().map(unquoted -> "\"" + unquoted + "\"").collect(Collectors.joining(", ")) + " ]"
                + "}");
        client().performRequest(request);
    }

    @Before
    public void setUpData() throws Exception {
        // This user has admin rights on machine learning, but (importantly for the tests) no rights
        // on any of the data indexes
        setupUser(ML_ADMIN, Collections.singletonList("machine_learning_admin"));
        addAirlineData();
    }

    private void addAirlineData() throws IOException {
        StringBuilder bulk = new StringBuilder();

        // Create index with source = enabled, doc_values = enabled, stored = false + multi-field
        Request createAirlineDataRequest = new Request("PUT", "/airline-data");
        createAirlineDataRequest.setJsonEntity("{"
                + "  \"mappings\": {"
                + "    \"properties\": {"
                + "      \"time stamp\": { \"type\":\"date\"}," // space in 'time stamp' is intentional
                + "      \"airline\": {"
                + "        \"type\":\"keyword\""
                + "       },"
                + "      \"responsetime\": { \"type\":\"float\"}"
            + "    }"
                + "  }"
                + "}");
        client().performRequest(createAirlineDataRequest);

        bulk.append("{\"index\": {\"_index\": \"airline-data\", \"_id\": 1}}\n");
        bulk.append("{\"time stamp\":\"2016-06-01T00:00:00Z\",\"airline\":\"AAA\",\"responsetime\":135.22}\n");
        bulk.append("{\"index\": {\"_index\": \"airline-data\", \"_id\": 2}}\n");
        bulk.append("{\"time stamp\":\"2016-06-01T01:59:00Z\",\"airline\":\"AAA\",\"responsetime\":541.76}\n");

        bulkIndex(bulk.toString());
    }

    public void testExplain_GivenSecondaryHeadersAndConfig() throws IOException {
        String config = "{\n" +
            "  \"source\": {\n" +
            "    \"index\": \"airline-data\"\n" +
            "  },\n" +
            "  \"analysis\": {\n" +
            "    \"regression\": {\n" +
            "      \"dependent_variable\": \"responsetime\"\n" +
            "    }\n" +
            "  }\n" +
            "}";

        { // Request with secondary headers without perms
            Request explain = explainRequestViaConfig(config);
            RequestOptions.Builder options = explain.getOptions().toBuilder();
            addAuthHeader(options, SUPER_USER);
            addSecondaryAuthHeader(options, ML_ADMIN);
            explain.setOptions(options);
            // Should throw
            expectThrows(ResponseException.class, () -> client().performRequest(explain));
        }
        { // request with secondary headers with perms
            Request explain = explainRequestViaConfig(config);
            RequestOptions.Builder options = explain.getOptions().toBuilder();
            addAuthHeader(options, ML_ADMIN);
            addSecondaryAuthHeader(options, SUPER_USER);
            explain.setOptions(options);
            // Should not throw
            client().performRequest(explain);
        }
    }

    public void testExplain_GivenSecondaryHeadersAndPreviouslyStoredConfig() throws IOException {
        String config = "{\n" +
            "  \"source\": {\n" +
            "    \"index\": \"airline-data\"\n" +
            "  },\n" +
            "  \"dest\": {\n" +
            "    \"index\": \"response_prediction\"\n" +
            "  },\n" +
            "  \"analysis\":\n" +
            "    {\n" +
            "      \"regression\": {\n" +
            "        \"dependent_variable\": \"responsetime\"\n" +
            "      }\n" +
            "    }\n" +
            "}";

        String configId = "explain_test";

        Request storeConfig = new Request("PUT", "_ml/data_frame/analytics/" + configId);
        storeConfig.setJsonEntity(config);
        client().performRequest(storeConfig);

        { // Request with secondary headers without perms
            Request explain = explainRequestConfigId(configId);
            RequestOptions.Builder options = explain.getOptions().toBuilder();
            addAuthHeader(options, SUPER_USER);
            addSecondaryAuthHeader(options, ML_ADMIN);
            explain.setOptions(options);
            // Should throw
            expectThrows(ResponseException.class, () -> client().performRequest(explain));
        }
        { // request with secondary headers with perms
            Request explain = explainRequestConfigId(configId);
            RequestOptions.Builder options = explain.getOptions().toBuilder();
            addAuthHeader(options, ML_ADMIN);
            addSecondaryAuthHeader(options, SUPER_USER);
            explain.setOptions(options);
            // Should not throw
            client().performRequest(explain);
        }
    }

    private static Request explainRequestViaConfig(String config) {
        Request request = new Request("POST", "_ml/data_frame/analytics/_explain");
        request.setJsonEntity(config);
        return request;
    }

    private static Request explainRequestConfigId(String id) {
        return new Request("POST", "_ml/data_frame/analytics/" + id + "/_explain");
    }

    private void bulkIndex(String bulk) throws IOException {
        Request bulkRequest = new Request("POST", "/_bulk");
        bulkRequest.setJsonEntity(bulk);
        bulkRequest.addParameter("refresh", "true");
        bulkRequest.addParameter("pretty", null);
        String bulkResponse = EntityUtils.toString(client().performRequest(bulkRequest).getEntity());
        assertThat(bulkResponse, not(containsString("\"errors\": false")));
    }

}


text:
package com.ibm.icu.dev.test.compression;

import com.ibm.icu.dev.test.TestFmwk.TestGroup;

/**
 * Top level test used to run all other tests as a batch.
 */
public class TestAll extends TestGroup {
    public static void main(String[] args) throws Exception {
        new TestAll().run(args);
    }

    public TestAll() {
        super(new String[] {
            "DecompressionTest",
            "ExhaustiveTest",
        });
    }

    public static final String CLASS_TARGET_NAME = "Compression";
}


text:
import java.awt.Color;
import java.awt.Font;

import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

/* @test
 * @bug 7022041
 * @summary This test check the behaviour of getTitleFont() and getTitleColor()
 *          methods of the TitledBorder class.
 * @author Pavel Tisnovsky
 */
public class Test7022041 {

    public static void main(String[] args) throws Exception {
        UIManager.LookAndFeelInfo[] installedLookAndFeels = UIManager.getInstalledLookAndFeels();
        // try to test all installed Look and Feels
        for (UIManager.LookAndFeelInfo lookAndFeel : installedLookAndFeels) {
            String name = lookAndFeel.getName();
            System.out.println("Testing " + name);
            // Some Look and Feels work only when test is run in a GUI environment
            // (GTK+ LAF is an example)
            try {
                UIManager.setLookAndFeel(lookAndFeel.getClassName());
                checkTitleColor();
                System.out.println("    titleColor test ok");
                checkTitleFont();
                System.out.println("    titleFont test ok");
            }
            catch (UnsupportedLookAndFeelException e) {
                System.out.println("    Note: LookAndFeel " + name
                                 + " is not supported on this configuration");
            }
        }
    }

    /**
      * Check behaviour of method TitledBorder.getTitleColor()
      */
    private static void checkTitleColor() {
        TitledBorder titledBorder = new TitledBorder(new EmptyBorder(1, 1, 1, 1));
        Color defaultColor = UIManager.getLookAndFeelDefaults().getColor("TitledBorder.titleColor");
        Color titledBorderColor = titledBorder.getTitleColor();

        // check default configuration
        if (defaultColor == null) {
            if (titledBorderColor == null) {
                return;
            }
            else {
                throw new RuntimeException("TitledBorder default color should be null");
            }
        }
        if (!defaultColor.equals(titledBorderColor)) {
            throw new RuntimeException("L&F default color " + defaultColor.toString()
                                     + " differs from TitledBorder color " + titledBorderColor.toString());
        }

        // title color is explicitly specified
        Color color = Color.green;
        titledBorder.setTitleColor(color);
        if (!color.equals(titledBorder.getTitleColor())) {
            throw new RuntimeException("TitledBorder color should be " + color.toString());
        }

        // title color is unspecified
        titledBorder.setTitleColor(null);
        if (!defaultColor.equals(titledBorder.getTitleColor())) {
            throw new RuntimeException("L&F default color " + defaultColor.toString()
                                     + " differs from TitledBorder color " + titledBorderColor.toString());
        }
    }

    /**
      * Check behaviour of method TitledBorder.getTitleFont()
      */
    private static void checkTitleFont() {
        TitledBorder titledBorder = new TitledBorder(new EmptyBorder(1, 1, 1, 1));
        Font defaultFont = UIManager.getLookAndFeelDefaults().getFont("TitledBorder.font");
        Font titledBorderFont = titledBorder.getTitleFont();

        // check default configuration
        if (defaultFont == null) {
            if (titledBorderFont == null) {
                return;
            }
            else {
                throw new RuntimeException("TitledBorder default font should be null");
            }
        }
        if (!defaultFont.equals(titledBorderFont)) {
            throw new RuntimeException("L&F default font " + defaultFont.toString()
                                     + " differs from TitledBorder font " + titledBorderFont.toString());
        }

        // title font is explicitly specified
        Font font = new Font("Dialog", Font.PLAIN, 10);
        titledBorder.setTitleFont(font);
        if (!font.equals(titledBorder.getTitleFont())) {
            throw new RuntimeException("TitledBorder font should be " + font.toString());
        }

        // title Font is unspecified
        titledBorder.setTitleFont(null);
        if (!defaultFont.equals(titledBorder.getTitleFont())) {
            throw new RuntimeException("L&F default font " + defaultFont.toString()
                                     + " differs from TitledBorder font " + titledBorderFont.toString());
        }
    }
}