text:
<?php
/**
 * Author: Pavel Naumenko
 */

namespace app\modules\store\forms;

use app\modules\certificate\models\Certificate;
use app\modules\store\models\StoreOrderProduct;
use app\modules\store\models\StoreProductCartPosition;
use backend\components\BackModel;
use common\models\StoreOrder;
use common\models\User;
use frontend\components\PokuponChecker;
use rmrevin\yii\postman\ViewLetter;
use yii\base\Exception;
use yii\base\Model;
use yz\shoppingcart\CartPositionInterface;

/**
 * Class OrderForm
 * @package app\modules\store\forms
 */
class OrderForm extends Model
{
    /**
     * @var string $name
     */
    public $name;

    public $city;

    /**
     * @var string $name
     */
    public $phone;

    /**
     * @var string $name
     */
    public $email;

    /**
     * @var integer $paymentType
     */
    public $paymentType;

    /**
     * @var integer $deliveryType
     */
    public $deliveryType;

    /**
     * @var string $street
     */
    public $street;

    /**
     * @var string $address
     */
    public $address;

    /**
     * @var string $house
     */
    public $house;

    /**
     * @var string $apartment
     */
    public $apartment;

    /**
     * @var integer $deliveryTime
     */
    public $deliveryTime;

    /**
     * @var string $novaPoshtaStorage
     */
    public $novaPoshtaStorage;

    /**
     * @var string $comment
     */
    public $comment;

    /**
     * @var string $discountCard
     */
    public $discountCard;

    /**
     * @var string $promoCode
     */
    public $promoCode;

    /**
     * @var
     */
    protected $createdOrder;

    public function init()
    {
        if (!$this->paymentType) {
            $this->paymentType = 1;
        }

        if (!$this->deliveryType) {
            $this->deliveryType = 1;
        }

        $this->fillUserData();
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'name' => \Yii::t('frontend', 'Name'),
            'city' => \Yii::t('frontend', 'Order_form_city'),
            'email' => \Yii::t('frontend', 'Order_form_email'),
            'phone' => \Yii::t('frontend', 'Phone'),
            'paymentType' => \Yii::t('frontend', 'Order_form_paymentType'),
            'deliveryType' => \Yii::t('frontend', 'Order_form_deliveryType'),
            'street' => \Yii::t('frontend', 'Order_form_street'),
            'address' => \Yii::t('frontend', 'Order_form_addres'),
            'house' => \Yii::t('frontend', 'Order_form_house'),
            'apartment' => \Yii::t('frontend', 'Order_form_apartment'),
            'deliveryTime' => \Yii::t('frontend', 'Order_form_deliveryTime'),
            'novaPoshtaStorage' => \Yii::t('frontend', 'Order_form_novaPoshtaStorage'),
            'comment' => \Yii::t('frontend', 'Order_form_comment'),
            'discountCard' => \Yii::t('frontend', 'Order_form_discountCard'),
            'promoCode' => \Yii::t('frontend', 'Order_form_promoCode'),
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name', 'phone'], 'required'],
            [['paymentType', 'deliveryType', 'deliveryTime'], 'integer'],
            [['name', 'phone', 'street', 'house', 'apartment', 'novaPoshtaStorage', 'city', 'comment', 'address', 'discountCard', 'promoCode'], 'string'],
            ['email', 'email'],
            [['phone'], 'common\components\validator\PhoneValidator', 'country' => 'UA'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function save()
    {
        if (\Yii::$app->cart->getIsEmpty()) {
            return false;
        }

        $orderItems = [];

        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $array = [];
            if ($this->city) {
                $array[] = 'г. ' . $this->city;
            }
            if ($this->street) {
                $array[] = $this->street;
            }
            if ($this->house) {
                $array[] = 'д. ' . $this->house;
            }
            if ($this->apartment) {
                $array[] = 'кв. ' . $this->apartment;
            }
            $address = implode(' ', $array);
            $order = new \app\modules\store\models\StoreOrder();
            $order->user_id = User::getUserIdForOrder($this);
            $order->name = $this->name;
            $order->phone = $this->phone;
            $order->email = $this->email;
            $order->payment_type = $this->paymentType;
            $order->delivery_type = $this->deliveryType;
            $order->address = $address;
            $order->city = $this->city;
            $order->street = $this->street;
            $order->house = $this->house;
            $order->apartment = $this->apartment;
            $order->delivery_time = $this->deliveryTime;
            $order->nova_poshta_storage = $this->novaPoshtaStorage;
            $order->comment = $this->comment;
            $order->sum = \Yii::$app->cart->getCost();
            $order->discount_card = $this->discountCard;
//            $order->promo_code = $this->promoCode;

            if (!$order->save()) {
                $this->addErrors($order->getErrors());
                return false;
            } else {
                foreach (\Yii::$app->cart->getPositions() as $position) {
                    $orderProduct = ($position instanceof StoreProductCartPosition)
                        ? $this->createStoreProduct($position, $order)
                        : $this->createCertifcateProduct($position, $order);

                    $orderItems[] = $orderProduct;
                }
            }

            \Yii::$app->cart->removeAll();

            $transaction->commit();

            $this->sendEmail($order, $orderItems);

            //Info about order for Pokupon
            //PokuponChecker::setPokuponInfoAfterOrderDone($order->id, $order->sum);

            //StoreOrder::createOrderInRetailCrm($order->id);

            $this->createdOrder = $order;
            return true;
        } catch (Exception $e) {
            $transaction->rollBack();

            $this->addError('name', $e->getMessage());

            return false;
        }
    }

    /**
     * @param CartPositionInterface $pos
     * @param \app\modules\store\models\StoreOrder $order
     *
     * @return StoreOrderProduct
     */
    public function createStoreProduct(CartPositionInterface $pos, \app\modules\store\models\StoreOrder $order)
    {
        /**
         * @var StoreProductCartPosition $pos
         */
        $product = $pos->getProduct();
        $orderProduct = new StoreOrderProduct();
        $orderProduct->order_id = $order->id;
        $orderProduct->product_id = $product->id;
        $orderProduct->sku = /*$pos->variant ? $pos->getVariant()['sku'] :*/ $product->sku;
        $orderProduct->size_id = $pos->sizeId;
        $orderProduct->qnt = $pos->getQuantity();
        $orderProduct->save(false);

        return $orderProduct;
    }

    /**
     * @param array $params
     *
     * @return string
     */
    public static function getOrderDoneUrl($params = [])
    {
        return BackModel::createUrl('/store/cart/order-done', $params);
    }

    /**
     * @return mixed
     */
    public function getOrder()
    {
        return $this->createdOrder;
    }

    /**
     * @return bool
     */
    public function isExternalPayment()
    {
        return $this->paymentType == \common\models\StoreOrder::PAYMENT_TYPE_VISA;
    }

    /**
     * @param $order
     * @param $orderItems
     */
    protected function sendEmail($order, $orderItems)
    {
        $adminEmails = \Yii::$app->config->get('admin_email');

        if ($adminEmails) {
            $mail = (new ViewLetter())
                ->setSubject('Новый заказ')
                ->setBodyFromView('order', [
                    'order' => $order,
                    'orderItems' => $orderItems
                ]);

            $emails = explode(',', $adminEmails);
            foreach ($emails as $email) {
                $mail->addAddress($email);
            }

            $mail->send();
        }
    }

    protected function fillUserData()
    {
        if (!\Yii::$app->user->isGuest) {
            /**
             * @var User $user
             */
            $user = \Yii::$app->user->identity;

            $this->email = $user->email;
            $this->phone = str_replace('+380 ', '', $user->phone);
            $this->name = $user->name . ' '. $user->surname;
            //$this->discountCard = $user->discount_card;
            $this->address = $user->address;
        }
    }
}


text:
console.log(process.env.NODE_ENV);
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var Sequelize = require('sequelize');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local');
var flash = require('express-flash');
var fileUpload = require('express-fileupload');

var passportConfig = require('./config/passport')(passport);

var index = require('./controllers/index');
var users = require('./controllers/users')(passport);
var drafts = require('./controllers/drafts');
var picks = require('./controllers/picks');
var config = require('./config/config.js')(process.env.NODE_ENV);
var allCards = require('./config/allCards');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

//================ MIDDLEWARE ========================
// uncomment after placing your favicon in /public
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
// app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
  secret: 'buddysystem',
  resave: false,
  saveUninitialized: false
}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use(fileUpload());

var db = new Sequelize(
  config.dbName,
  config.dbUser,
  config.dbPassword, {
    host: config.dbHost,
    port: 3306,
    dialect: 'mysql',
    define: {
      freezeTableName: true
    },
    logging: true
  });

//===================== DATABASE MODELS ===============
// Set up database models and relationships
db.draft = require('./models/draft')(db);
db.picker = require('./models/picker')(db);
db.user = require('./models/user')(db);
db.cardpool = require('./models/cardpool')(db);
db.pick = require('./models/pick')(db);
db.user.hasMany(db.picker, { sourceKey: 'id', foreignKey: 'userId' });
db.picker.belongsTo(db.user, { sourceKey: 'id', foreignKey: 'userId' });
db.draft.hasMany(db.user, { sourceKey: 'ownerId', foreignKey: 'id', constraints: false });
db.draft.hasMany(db.pick, { sourceKey: 'draftId', foreignKey: 'draftId' });
db.draft.hasMany(db.picker, { sourceKey: 'draftId', foreignKey: 'draftId' });
db.picker.belongsTo(db.draft, { targetKey: 'draftId' });
db.pick.belongsTo(db.cardpool, { sourceKey: 'cardId', foreignKey: 'cardId' });
db.draft.hasMany(db.cardpool, { sourceKey: 'draftId', foreignKey: 'draftId' });

db.authenticate().then(function (err) {
  if (err) {
    console.log('There was an error connecting to the DB');
  } else {
    console.log('Connected to DB successfully!');
    db.sync({ force: false });
  }
});

app.use(function (req, res, next) {
  req.db = db;
  next();
});

app.use(function (req, res, next) {
  req.passport = passport;
  next();
});

var paywall = function (req, res, next) {
  if (req.isAuthenticated()) {
    next();
  } else {
    req.flash('error', 'You need to log in to do that');
    res.redirect('/users/login');
  }
}

//==================== ROUTES ===============
app.use('/', index);
app.use('/users', users);
app.use('/drafts', paywall, drafts);
// app.use('/picks', paywall, picks);
app.use('/picks', picks);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

app.use(express.static('public'));

module.exports = app;

redpajama_set_name: RedPajamaGithub


text:
FROM base/archlinux:latest
MAINTAINER "Johann Weging <johann@weging.com>"

RUN set -x \
&& pacman --noconfirm -Syy \
&& pacman --noconfirm -S curl openssl reflector \
&& curl -o /etc/pacman.d/mirrorlist https://www.archlinux.org/mirrorlist/all/ \
&& reflector --verbose -l 5 --sort rate --save /etc/pacman.d/mirrorlist \
&& pacman --noconfirm -S pacman archlinux-keyring \
&& pacman-db-upgrade \
&& pacman --noconfirm -Suy \
&& pacman --noconfirm -S expect arch-install-scripts

ADD mkimage-arch.sh /
ADD mkimage-arch-pacman.conf /


text:
package fredboat.testutil;

import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.TestExecutionExceptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by napster on 21.01.18.
 */
public class LogExceptionExtension implements TestExecutionExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(LogExceptionExtension.class);

    @Override
    public void handleTestExecutionException(ExtensionContext context, Throwable throwable)
            throws Throwable {
        log.error("Uncaught exception during test execution", throwable);
        throw throwable;
    }
}


text:
<?php
namespace OnlineConvert\Endpoint;

use OnlineConvert\Client\OnlineConvertClient;
use OnlineConvert\Exception\OnlineConvertSdkException;

/**
 * Manage Information endpoint
 * Provide some extra methods to get information about the api
 *
 * @package OnlineConvert\Endpoint
 *
 * @author Andrés Cevallos <a.cevallos@qaamgo.com>
 */
class InformationEndpoint extends Abstracted
{
    /**
     * Get API schema
     *
     * @api
     *
     * @throws OnlineConvertSdkException when error on the request
     *
     * @return array
     */
    public function getSchema()
    {
        return $this->responseToArray(
            $this->client->sendRequest(Resources::GET_SCHEMA, OnlineConvertClient::METHOD_GET)
        );
    }

    /**
     * Get list of valid statuses in api
     *
     * @api
     *
     * @throws OnlineConvertSdkException when error on the request
     *
     * @return array
     */
    public function getStatusesList()
    {
        return $this->responseToArray(
            $this->client->sendRequest(Resources::STATUSES, OnlineConvertClient::METHOD_GET)
        );
    }

    /**
     * Get list of all the possibles conversions
     *
     * @api
     *
     * @throws OnlineConvertSdkException when error on the request
     *
     * @return array
     */
    public function getConversionsList()
    {
        return $this->responseToArray(
            $this->client->sendRequest(Resources::CONVERSIONS, OnlineConvertClient::METHOD_GET)
        );
    }

    /**
     * Return schema for a specific conversion
     *
     * @api
     *
     * @throws OnlineConvertSdkException when error on the request
     *
     * @param string      $target
     * @param null|string $category
     *
     * @return array
     */
    public function getConversionSchema($target, $category = null)
    {
        $query['target'] = $target;

        if ($category) {
            $query['category'] = $category;
        }

        $url = $this->client->generateUrl(Resources::CONVERSIONS, [], $query);

        return $this->responseToArray($this->client->sendRequest($url, OnlineConvertClient::METHOD_GET))[0];
    }
}


text:
from abc import ABCMeta
from twisted.mail.smtp import ESMTPSender

class myESMTPSender(ESMTPSender, metaclass=ABCMeta):
    def _getContextFactory(self):
        if self.context is not None:
            return self.context
        try:
            from twisted.internet import ssl
        except ImportError:
            return None
        else:
            try:
                context = ssl.ClientContextFactory()
                return context
            except AttributeError:
                return None


text:
package org.drools.repository;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.PathNotFoundException;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
import javax.jcr.Workspace;

import org.drools.repository.RulesRepository.DateQuery;
import org.drools.repository.migration.MigrateDroolsPackage;

import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.fail;

public class RulesRepositoryTest extends RepositoryTestCase {
    int running = 0;

    @Test
    public void testDefaultPackage() throws Exception {
        RulesRepository repo = getRepo();

        Iterator it = repo.listPackages();
        boolean foundDefault = false;
        while ( it.hasNext() ) {
            PackageItem item = (PackageItem) it.next();
            if ( item.getName().equals( RulesRepository.DEFAULT_PACKAGE ) ) {
                foundDefault = true;
            }
        }
        assertTrue( foundDefault );

        PackageItem def = repo.loadDefaultPackage();
        assertNotNull( def );
        assertEquals( RulesRepository.DEFAULT_PACKAGE,
                      def.getName() );

        String userId = repo.getSession().getUserID();
        assertNotNull( userId );
        assertFalse( userId.equals( "" ) );

        MigrateDroolsPackage mig = new MigrateDroolsPackage();
        assertFalse( mig.needsMigration( repo ) );
        assertTrue( repo.initialized );

    }

    @Test
    public void testCategoryRename() throws Exception {
        RulesRepository repo = getRepo();

        CategoryItem root = repo.loadCategory( "/" );
        root.addCategory( "testCatRename",
                          "" );
        repo.loadCategory( "testCatRename" ).addCategory( "testRename",
                                                          "" );

        repo.renameCategory( "testCatRename/testRename",
                             "testAnother" );

        CategoryItem cat = repo.loadCategory( "testCatRename/testAnother" );
        assertNotNull( cat );
        try {
            repo.loadCategory( "testCatRename/testRename" );
            fail( "should not exist." );
        } catch ( RulesRepositoryException e ) {
            assertNotNull( e.getMessage() );
        }

        PackageItem pkg = repo.createPackage( "testCategoryRename",
                                              "" );
        AssetItem asset = pkg.addAsset( "fooBar",
                                        "" );
        asset.addCategory( "testCatRename" );
        asset.addCategory( "testCatRename/testAnother" );
        asset.checkin( "" );

        cat = repo.loadCategory( "testCatRename/testAnother" );
        AssetItemPageResult as = repo.findAssetsByCategory( "testCatRename/testAnother",
                                                      0,
                                                      -1 );
        assertEquals( "fooBar",
                      ((AssetItem) as.assets.get( 0 )).getName() );

        repo.renameCategory( "testCatRename/testAnother",
                             "testYetAnother" );
        as = repo.findAssetsByCategory( "testCatRename/testYetAnother",
                                        0,
                                        -1 );
        assertEquals( "fooBar",
                      ((AssetItem) as.assets.get( 0 )).getName() );

    }

    @Test
    public void testAddVersionARule() throws Exception {
        RulesRepository repo = getRepo();
        PackageItem pack = repo.createPackage( "testAddVersionARule",
                                               "description" );
        repo.save();

        AssetItem rule = pack.addAsset( "my rule",
                                        "foobar" );
        assertEquals( "my rule",
                      rule.getName() );

        rule.updateContent( "foo foo" );
        rule.checkin( "version0" );

        pack.addAsset( "other rule",
                       "description" );

        rule.updateContent( "foo bar" );
        rule.checkin( "version1" );

        PackageItem pack2 = repo.loadPackage( "testAddVersionARule" );

        Iterator it = pack2.getAssets();

        it.next();
        it.next();

        assertFalse( it.hasNext() );

        AssetItem prev = (AssetItem) rule.getPrecedingVersion();

        assertEquals( "foo bar",
                      rule.getContent() );
        assertEquals( "foo foo",
                      prev.getContent() );

    }

    @Test
    public void testFindByState() throws Exception {
        RulesRepository repo = getRepo();
        PackageItem pkg = repo.createPackage( "testFindByStatePackage",
                                              "heheheh" );
        AssetItem asset1 = pkg.addAsset( "asset1",
                                         "" );
        AssetItem asset2 = pkg.addAsset( "asset2",
                                         "" );
        repo.createState( "testFindByState" );
        repo.save();
        asset1.updateState( "testFindByState" );
        asset2.updateState( "testFindByState" );
        asset1.checkin( "" );
        asset2.checkin( "" );

        AssetItemPageResult result = repo.findAssetsByState( "testFindByState",
                                                     true,
                                                     0,
                                                     -1 );
        assertEquals( 2,
                      result.assets.size() );

    }

    @Test
    public void testFindRulesByName() throws Exception {
        RulesRepository repo = getRepo();

        repo.loadDefaultPackage().addAsset( "findRulesByNamex1",
                                            "X" );
        repo.loadDefaultPackage().addAsset( "findRulesByNamex2",
                                            "X" );
        repo.save();

        List list = iteratorToList( repo.findAssetsByName( "findRulesByNamex1" ) );
        assertEquals( 1,
                      list.size() );

        list = iteratorToList( repo.findAssetsByName( "findRulesByNamex2" ) );
        assertEquals( 1,
                      list.size() );

        list = iteratorToList( repo.findAssetsByName( "findRulesByNamex%" ) );
        assertEquals( 2,
                      list.size() );

        repo.createPackageSnapshot( RulesRepository.DEFAULT_PACKAGE,
                                    "testFindRulesByName" );
        repo.save();

        list = iteratorToList( repo.findAssetsByName( "findRulesByNamex2" ) );
        AssetItem item = (AssetItem) list.get( 0 );
        assertEquals( "findRulesByNamex2",
                      item.getName() );
        assertEquals( "X",
                      item.getDescription() );
        assertEquals( 1,
                      list.size() );

        list = iteratorToList( repo.findAssetsByName( "findRulesByNamex%" ) );
        assertEquals( 2,
                      list.size() );

    }

    @Test
    public void testQueryText() throws Exception {
        RulesRepository repo = getRepo();
        PackageItem pkg = repo.createPackage( "testQueryTest",
                                              "" );
        AssetItem asset = pkg.addAsset( "asset1",
                                        "testQueryText1" );
        asset.updateSubject( "testQueryText42" );
        asset.checkin( "firstCheckintestQueryTest" );
        asset.updateFormat( "drl" );
        asset.checkin( "firstCheckintestQueryTest2" );
        pkg.addAsset( "asset2",
                      "testQueryText2" );
        repo.save();

        List<AssetItem> ls = iteratorToList( repo.queryFullText( "testQueryText*",
                                                                 false ) );
        assertEquals( 2,
                      ls.size() );

        ls = iteratorToList( repo.queryFullText( "firstCheckintestQueryTest2",
                                                 false ) );
        assertEquals( 1,
                      ls.size() );

        ls = iteratorToList( repo.queryFullText( "firstCheckintestQueryTest",
                                                 false ) );
        assertEquals( 0,
                      ls.size() );

        ls = iteratorToList( repo.queryFullText( "testQueryText*",
                                                 false ) );
        assertEquals( 2,
                      ls.size() );

        asset.archiveItem( true );
        asset.checkin( "" );

        ls = iteratorToList( repo.queryFullText( "testQueryText*",
                                                 false ) );
        assertEquals( 1,
                      ls.size() );

        ls = iteratorToList( repo.queryFullText( "testQueryText*",
                                                 true ) );
        assertEquals( 2,
                      ls.size() );

    }

    @Test
    public void testQuery() throws Exception {
        RulesRepository repo = getRepo();

        AssetItem asset = repo.loadDefaultPackage().addAsset( "testQuery",
                                                              "wanklerotaryengine1cc" );

        //asset.updateBinaryContentAttachment(new ByteArrayInputStream("testingSearchWankle".getBytes()));
        asset.updateContent( "testingSearchWankle" );
        asset.updateSubject( "testQueryXXX42" );
        asset.checkin( "" );

        Map<String, String[]> q = new HashMap<String, String[]>();
        q.put( "drools:subject",
               new String[]{"testQueryXXX42"} );

        AssetItemIterator asit = repo.query( q,
                                             false,
                                             null );
        List<AssetItem> results = iteratorToList( asit );
        assertEquals( 1,
                      results.size() );
        AssetItem as = results.get( 0 );
        assertEquals( "testQuery",
                      as.getName() );

        asset.updateExternalSource( "database" );
        asset.checkin( "" );

        q = new HashMap<String, String[]>();
        q.put( "drools:subject",
               new String[]{"testQueryXXX42"} );
        q.put( AssetItem.SOURCE_PROPERTY_NAME,
               new String[]{"database"} );
        results = iteratorToList( repo.query( q,
                                              true,
                                              null ) );
        assertEquals( 1,
                      results.size() );
        as = results.get( 0 );
        assertEquals( "testQuery",
                      as.getName() );

        q = new HashMap<String, String[]>();
        q.put( "drools:subject",
               new String[]{"testQueryXXX42", "wankle"} );
        q.put( AssetItem.SOURCE_PROPERTY_NAME,
               new String[]{"database", "wankle"} );
        results = iteratorToList( repo.query( q,
                                              false,
                                              null ) );
        assertEquals( 1,
                      results.size() );
        as = results.get( 0 );
        assertEquals( "testQuery",
                      as.getName() );

        q = new HashMap<String, String[]>();
        q.put( "drools:subject",
               null );
        q.put( "cruddy",
               new String[0] );
        q.put( AssetItem.SOURCE_PROPERTY_NAME,
               new String[]{"database", "wankle"} );
        results = iteratorToList( repo.query( q,
                                              false,
                                              null ) );
        assertEquals( 1,
                      results.size() );

        //now dates
        q = new HashMap<String, String[]>();
        q.put( "drools:subject",
               new String[]{"testQueryXXX42", "wankle"} );
        q.put( AssetItem.SOURCE_PROPERTY_NAME,
               new String[]{"database", "wankle"} );
        results = iteratorToList( repo.query( q,
                                              false,
                                              new DateQuery[]{new DateQuery( "jcr:created",
                                                                             "1974-07-10T00:00:00.000-05:00",
                                                                             "3074-07-10T00:00:00.000-05:00" )} ) );
        assertEquals( 1,
                      results.size() );
        as = results.get( 0 );
        assertEquals( "testQuery",
                      as.getName() );

        q = new HashMap<String, String[]>();
        q.put( "drools:subject",
               new String[]{"testQueryXXX42", "wankle"} );
        q.put( AssetItem.SOURCE_PROPERTY_NAME,
               new String[]{"database", "wankle"} );
        results = iteratorToList( repo.query( q,
                                              false,
                                              new DateQuery[]{new DateQuery( "jcr:created",
                                                                             "1974-07-10T00:00:00.000-05:00",
                                                                             null )} ) );
        assertEquals( 1,
                      results.size() );
        as = results.get( 0 );
        assertEquals( "testQuery",
                      as.getName() );

        q = new HashMap<String, String[]>();
        q.put( "drools:subject",
               new String[]{"testQueryXXX42", "wankle"} );
        q.put( AssetItem.SOURCE_PROPERTY_NAME,
               new String[]{"database", "wankle"} );
        results = iteratorToList( repo.query( q,
                                              false,
                                              new DateQuery[]{new DateQuery( "jcr:created",
                                                                             null,
                                                                             "3074-07-10T00:00:00.000-05:00" )} ) );
        assertEquals( 1,
                      results.size() );
        as = results.get( 0 );
        assertEquals( "testQuery",
                      as.getName() );

        //should return nothing:
        q = new HashMap<String, String[]>();
        q.put( "drools:subject",
               new String[]{"testQueryXXX42", "wankle"} );
        q.put( AssetItem.SOURCE_PROPERTY_NAME,
               new String[]{"database", "wankle"} );
        results = iteratorToList( repo.query( q,
                                              false,
                                              new DateQuery[]{new DateQuery( "jcr:created",
                                                                             "3074-07-10T00:00:00.000-05:00",
                                                                             null )} ) );
        assertEquals( 0,
                      results.size() );

        q = new HashMap<String, String[]>();
        q.put( "drools:subject",
               new String[]{"testQueryXXX42", "wankle"} );
        q.put( AssetItem.SOURCE_PROPERTY_NAME,
               new String[]{"database", "wankle"} );
        results = iteratorToList( repo.query( q,
                                              false,
                                              new DateQuery[]{new DateQuery( "jcr:created",
                                                                             null,
                                                                             "1974-07-10T00:00:00.000-05:00" )} ) );
        assertEquals( 0,
                      results.size() );

    }

    @Test
    public void testLoadRuleByUUIDWithConcurrentSessions() throws Exception {
        RulesRepository repo = getRepo();

        PackageItem rulePackageItem = repo.loadDefaultPackage();
        AssetItem rule = rulePackageItem.addAsset( "testLoadRuleByUUID",
                                                   "this is a description" );

        repo.save();

        String uuid = rule.getNode().getIdentifier();

        AssetItem loaded = repo.loadAssetByUUID( uuid );
        assertNotNull( loaded );
        assertEquals( "testLoadRuleByUUID",
                      loaded.getName() );
        assertEquals( "this is a description",
                      loaded.getDescription() );

        long oldVersionNumber = loaded.getVersionNumber();

        loaded.updateContent( "xxx" );
        loaded.checkin( "woo" );

        AssetItem reload = repo.loadAssetByUUID( uuid );
        assertEquals( "testLoadRuleByUUID",
                      reload.getName() );
        assertEquals( "xxx",
                      reload.getContent() );
        System.out.println( reload.getVersionNumber() );
        System.out.println( loaded.getVersionNumber() );
        assertFalse( reload.getVersionNumber() == oldVersionNumber );

        // try loading rule package that was not created
        try {
            repo.loadAssetByUUID( "01010101-0101-0101-0101-010101010101" );
            fail( "Exception not thrown loading rule package that was not created." );
        } catch ( RulesRepositoryException e ) {
            // that is OK!
            assertNotNull( e.getMessage() );
        }

        //now test concurrent session access...

        AssetItem asset1 = repo.loadDefaultPackage().addAsset( "testMultiSession",
                                                               "description" );
        asset1.updateContent( "yeah" );
        asset1.checkin( "boo" );
        uuid = asset1.getUUID();
        asset1.updateState( "Draft" );
        repo.save();

        Session s2 = repo.getSession().getRepository().login( new SimpleCredentials( "fdd",
                                                                                "password".toCharArray() ) );

        RulesRepository repo2 = new RulesRepository( s2 );

        AssetItem asset2 = repo2.loadAssetByUUID( uuid );
        asset2.updateContent( "yeah 42" );
        asset2.checkin( "yeah" );

        asset1 = repo.loadAssetByUUID( uuid );
        assertEquals( "yeah 42",
                      asset1.getContent() );
        asset1.updateContent( "yeah 43" );
        asset1.checkin( "la" );

        asset2 = repo2.loadAssetByUUID( uuid );
        assertEquals( "yeah 43",
                      asset2.getContent() );
    }

    @Test
    public void testAddRuleCalendarWithDates() {
        RulesRepository rulesRepository = getRepo();

        Calendar effectiveDate = Calendar.getInstance();
        Calendar expiredDate = Calendar.getInstance();
        expiredDate.setTimeInMillis( effectiveDate.getTimeInMillis() + (1000 * 60 * 60 * 24) );
        AssetItem ruleItem1 = rulesRepository.loadDefaultPackage().addAsset( "testAddRuleCalendarCalendar",
                                                                             "desc" );
        ruleItem1.updateDateEffective( effectiveDate );
        ruleItem1.updateDateExpired( expiredDate );

        assertNotNull( ruleItem1 );
        assertNotNull( ruleItem1.getNode() );
        assertEquals( effectiveDate,
                      ruleItem1.getDateEffective() );
        assertEquals( expiredDate,
                      ruleItem1.getDateExpired() );

        ruleItem1.checkin( "ho " );
    }

    @Test
    public void testGetState() {
        RulesRepository rulesRepository = getRepo();

        StateItem state0 = rulesRepository.createState( "testGetState" );
        assertNotNull( state0 );
        assertEquals( "testGetState",
                      state0.getName() );
        StateItem stateItem1 = rulesRepository.getState( "testGetState" );
        assertNotNull( stateItem1 );
        assertEquals( "testGetState",
                      stateItem1.getName() );

        StateItem stateItem2 = rulesRepository.getState( "testGetState" );
        assertNotNull( stateItem2 );
        assertEquals( "testGetState",
                      stateItem2.getName() );
        assertEquals( stateItem1,
                      stateItem2 );
    }

    @Test
    public void testGetTag() {
        RulesRepository rulesRepository = getRepo();

        CategoryItem root = rulesRepository.loadCategory( "/" );
        CategoryItem tagItem1 = root.addCategory( "testGetTag",
                                                  "ho" );
        assertNotNull( tagItem1 );
        assertEquals( "testGetTag",
                      tagItem1.getName() );
        assertEquals( "testGetTag",
                      tagItem1.getFullPath() );

        CategoryItem tagItem2 = rulesRepository.loadCategory( "testGetTag" );
        assertNotNull( tagItem2 );
        assertEquals( "testGetTag",
                      tagItem2.getName() );
        assertEquals( tagItem1,
                      tagItem2 );

        //now test getting a tag down in the tag hierarchy
        CategoryItem tagItem3 = tagItem2.addCategory( "TestChildTag1",
                                                      "ka" );
        assertNotNull( tagItem3 );
        assertEquals( "TestChildTag1",
                      tagItem3.getName() );
        assertEquals( "testGetTag/TestChildTag1",
                      tagItem3.getFullPath() );
    }

    @Test
    public void testListPackages() {
        RulesRepository rulesRepository = getRepo();
        rulesRepository.createPackage( "testListPackages",
                                       "desc" );

        assertTrue( rulesRepository.containsPackage( "testListPackages" ) );
        assertFalse( rulesRepository.containsPackage( "XXXXXXX" ) );

        Iterator it = rulesRepository.listPackages();
        assertTrue( it.hasNext() );

        boolean found = false;
        //listPackages() should not return the global area even though the global area is a package.
        boolean foundGlobalArea = false;
        while ( it.hasNext() ) {
            PackageItem element = (PackageItem) it.next();
            if ( element.getName().equals( "testListPackages" ) ) {
                found = true;
            }

            if ( element.getName().equals(RulesRepository.RULE_GLOBAL_AREA) ) {
                foundGlobalArea = true;
            }
         }
        assertTrue( found );
        assertFalse( foundGlobalArea );
    }

    @Test
    public void testFindAssetsByState() throws Exception {
        RulesRepository repo = getRepo();
        repo.loadCategory( "/" ).addCategory( "testFindAssetsByStateCat",
                                              "X" );

        PackageItem pkg = repo.createPackage( "testFindAssetsByStatePac",
                                              "" );
        pkg.addAsset( "testCat1",
                      "x",
                      "/testFindAssetsByStateCat",
                      "drl" );
        pkg.addAsset( "testCat2",
                      "x",
                      "/testFindAssetsByStateCat",
                      "drl" );

        repo.save();

        AssetItemPageResult apl = repo.findAssetsByState( "Draft",
                                                    false,
                                                    0,
                                                    -1,
                                                    new RepositoryFilter() {
                                                        public boolean accept(Object artifact,
                                                                              String action) {
                                                            if ( !(artifact instanceof AssetItem) ) return false;

                                                            if ( ((AssetItem) artifact).getName().equalsIgnoreCase( "testCat1" ) ) {
                                                                return true;
                                                            } else {
                                                                return false;
                                                            }
                                                        }
                                                    } );

        assertEquals( 1,
                      apl.assets.size() );
        assertEquals( "testCat1",
                      ((AssetItem) apl.assets.get( 0 )).getName() );
    }

    @Test
    public void testFindAssetsByCategory() throws Exception {
        RulesRepository repo = getRepo();
        repo.loadCategory( "/" ).addCategory( "testFindAssetsByCategoryUsingFilterCat",
                                              "X" );

        PackageItem pkg = repo.createPackage( "testFindAssetsByCategoryUsingFilterPack",
                                              "" );
        pkg.addAsset( "testCat1",
                      "x",
                      "/testFindAssetsByCategoryUsingFilterCat",
                      "drl" );
        pkg.addAsset( "testCat2",
                      "x",
                      "/testFindAssetsByCategoryUsingFilterCat",
                      "drl" );

        repo.save();

        List items = repo.findAssetsByCategory( "/testFindAssetsByCategoryUsingFilterCat",
                                                0,
                                                -1 ).assets;
        assertEquals( 2,
                      items.size() );

        AssetItemPageResult apl = repo.findAssetsByCategory( "/testFindAssetsByCategoryUsingFilterCat",
                                                       false,
                                                       0,
                                                       -1,
                                                       new RepositoryFilter() {
                                                           public boolean accept(Object artifact,
                                                                                String action) {
                                                               if ( !(artifact instanceof AssetItem) ) return false;

                                                               if ( ((AssetItem) artifact).getName().equalsIgnoreCase( "testCat1" ) ) {
                                                                   return true;
                                                               } else {
                                                                   return false;
                                                               }
                                                           }
                                                       } );

        assertEquals( 1,
                      apl.assets.size() );
        assertEquals( "testCat1",
                      ((AssetItem) apl.assets.get( 0 )).getName() );

        pkg.addAsset( "testCat3",
                      "x",
                      "/testFindAssetsByCategoryUsingFilterCat",
                      "drl" );
        pkg.addAsset( "testCat4",
                      "x",
                      "/testFindAssetsByCategoryUsingFilterCat",
                      "drl" );
        pkg.addAsset( "testCat5",
                      "x",
                      "/testFindAssetsByCategoryUsingFilterCat",
                      "drl" );
        pkg.addAsset( "testCat6",
                      "x",
                      "/testFindAssetsByCategoryUsingFilterCat",
                      "drl" );
        pkg.addAsset( "testCat7",
                      "x",
                      "/testFindAssetsByCategoryUsingFilterCat",
                      "drl" );
        pkg.addAsset( "testCat8",
                      "x",
                      "/testFindAssetsByCategoryUsingFilterCat",
                      "drl" );

        pkg.loadAsset( "testCat1" ).archiveItem( true ).checkin( "" );
        pkg.loadAsset( "testCat2" ).archiveItem( true ).checkin( "" );
        pkg.loadAsset( "testCat3" ).archiveItem( true ).checkin( "" );
        pkg.loadAsset( "testCat4" ).archiveItem( true ).checkin( "" );

        //        apl = repo.findAssetsByCategory( "/testFindAssetsByCategoryUsingFilterCat", 0, 2 );
        //        assertEquals(2, apl.assets.size());
        //        assertTrue(apl.hasNext);
        //
        //        assertEquals(5, apl.currentPosition);
        //        //assertEquals("testCat5", apl.assets.get(0).getName());
        //
        //        apl = repo.findAssetsByCategory( "/testFindAssetsByCategoryUsingFilterCat", 7, 2 );
        //        assertEquals(2, apl.assets.size());
        //        assertFalse(apl.hasNext);
        //        //assertEquals("testCat7", apl.assets.get(0).getName());

        repo.save();

        apl = repo.findAssetsByCategory( "/testFindAssetsByCategoryUsingFilterCat",
                                         0,
                                         -1 );

        assertEquals( 4,
                      apl.assets.size() );
        List<String> names = new ArrayList<String>();

        for ( AssetItem as : apl.assets ) {
            if ( names.contains( as.getName() ) ) {
                fail( "dupe returned." );
            }
            names.add( as.getName() );
        }

        names = new ArrayList<String>();

        boolean hasNext = true;
        int skip = 0;
        while ( hasNext ) {
            apl = repo.findAssetsByCategory( "/testFindAssetsByCategoryUsingFilterCat",
                                             skip,
                                             2 );
            for ( AssetItem as : apl.assets ) {
                if ( names.contains( as.getName() ) ) {
                    fail( "dupe returned" );
                }
                names.add( as.getName() );
            }
            //we add the num of results returned, and sub 2 to work out where to start next
            skip = (int) (apl.currentPosition + apl.assets.size() - 2);
            hasNext = apl.hasNext;
        }
        assertEquals( 4,
                      names.size() );
        assertTrue( names.contains( "testCat5" ) );
        assertTrue( names.contains( "testCat6" ) );
        assertTrue( names.contains( "testCat7" ) );
        assertTrue( names.contains( "testCat8" ) );

    }

    @Test
    public void testFunnyOrdering() throws Exception {

    }

    /**
     * Here we are testing to make sure that category links don't pick up stuff in snapshots area.
     */
    @Test
    public void testCategoriesAndSnapshots() throws Exception {
        RulesRepository repo = getRepo();
        repo.loadCategory( "/" ).addCategory( "testCategoriesAndSnapshots",
                                              "X" );

        PackageItem pkg = repo.createPackage( "testCategoriesAndSnapshots",
                                              "" );
        pkg.addAsset( "testCat1",
                      "x",
                      "/testCategoriesAndSnapshots",
                      "drl" );
        pkg.addAsset( "testCat2",
                      "x",
                      "/testCategoriesAndSnapshots",
                      "drl" );
        repo.save();

        List items = repo.findAssetsByCategory( "/testCategoriesAndSnapshots",
                                                0,
                                                -1 ).assets;
        assertEquals( 2,
                      items.size() );

        repo.createPackageSnapshot( "testCategoriesAndSnapshots",
                                    "SNAP 1" );
        items = repo.findAssetsByCategory( "testCategoriesAndSnapshots",
                                           0,
                                           -1 ).assets;
        assertEquals( 2,
                      items.size() );

        assertTrue( repo.containsSnapshot( "testCategoriesAndSnapshots",
                                           "SNAP 1" ) );
        assertFalse( repo.containsSnapshot( "testCategoriesAndSnapshots",
                                            "SNAP XXXX" ) );

        assertFalse( repo.containsSnapshot( "gooberWhhewasssllllelelelelele",
                                            "SNAP" ) );

    }

    @Test
    public void testMoveRulePackage() throws Exception {
        RulesRepository repo = getRepo();
        PackageItem pkg = repo.createPackage( "testMove",
                                              "description" );
        AssetItem r = pkg.addAsset( "testMove",
                                    "description" );
        r.checkin( "version0" );
        String uuid = r.getUUID();
        assertEquals( "testMove",
                      r.getPackageName() );

        repo.save();

        assertEquals( 1,
                      iteratorToList( pkg.getAssets() ).size() );

        repo.createPackage( "testMove2",
                            "description" );
        repo.moveRuleItemPackage( "testMove2",
                                  r.node.getIdentifier(),
                                  "explanation" );

        pkg = repo.loadPackage( "testMove" );
        assertEquals( 0,
                      iteratorToList( pkg.getAssets() ).size() );

        pkg = repo.loadPackage( "testMove2" );
        assertEquals( 1,
                      iteratorToList( pkg.getAssets() ).size() );

        r = (AssetItem) pkg.getAssets().next();
        assertEquals( "testMove",
                      r.getName() );
        assertEquals( "testMove2",
                      r.getPackageName() );
        assertEquals( "explanation",
                      r.getCheckinComment() );

        AssetItem p = (AssetItem) r.getPrecedingVersion();
        assertEquals( "testMove",
                      p.getPackageName() );
        assertEquals( "version0",
                      p.getCheckinComment() );
        assertEquals( uuid,
                      r.getUUID() );
    }

    @Test
    public void testCopyAsset() throws Exception {
        RulesRepository repo = getRepo();
        repo.createPackage( "testCopyAsset",
                            "asset" );
        AssetItem item = repo.loadDefaultPackage().addAsset( "testCopyAssetSource",
                                                             "desc" );
        item.updateContent( "la" );
        item.checkin( "" );
        item.updateDescription( "mmm" );
        item.checkin( "again" );
        assertEquals( 2,
                      item.getVersionNumber() );

        String uuid = repo.copyAsset( item.getUUID(),
                                      "testCopyAsset",
                                      "testCopyAssetDestination" );
        AssetItem dest = repo.loadAssetByUUID( uuid );
        assertEquals( dest.getName(),
                      dest.getTitle() );
        assertEquals( "la",
                      dest.getContent() );
        assertEquals( "testCopyAsset",
                      dest.getPackageName() );
        assertFalse( uuid.equals( item.getUUID() ) );
        assertEquals( 1,
                      dest.getVersionNumber() );
    }

    @Test
    public void testRenameAsset() throws Exception {
        RulesRepository repo = getRepo();
        repo.createPackage( "testRenameAsset",
                            "asset" );
        AssetItem item = repo.loadPackage( "testRenameAsset" ).addAsset( "testRenameAssetSource",
                                                                         "desc" );
        item.updateContent( "la" );
        item.checkin( "" );

        String uuid = repo.renameAsset( item.getUUID(),
                                        "testRename2" );
        item = repo.loadAssetByUUID( uuid );
        assertEquals( "testRename2",
                      item.getName() );
        assertEquals( "testRename2",
                      item.getTitle() );

        List assets = iteratorToList( repo.loadPackage( "testRenameAsset" ).getAssets() );
        assertEquals( 1,
                      assets.size() );
        item = (AssetItem) assets.get( 0 );
        assertEquals( "testRename2",
                      item.getName() );
        assertEquals( "la",
                      item.getContent() );

    }

    @Test
    public void testRenamePackage() throws Exception {
        RulesRepository repo = getRepo();
        PackageItem original = repo.createPackage( "testRenamePackage",
                                                   "asset" );
        List packagesOriginal = iteratorToList( repo.listPackages() );
        AssetItem item = repo.loadPackage( "testRenamePackage" ).addAsset( "testRenameAssetSource",
                                                                           "desc" );
        item.updateContent( "la" );
        item.checkin( "" );

        String uuid = repo.renamePackage( original.getUUID(),
                                          "testRenamePackage2" );

        PackageItem pkg = repo.loadPackageByUUID( uuid );
        assertEquals( "testRenamePackage2",
                      pkg.getName() );

        List assets = iteratorToList( repo.loadPackage( "testRenamePackage2" ).getAssets() );
        assertEquals( 1,
                      assets.size() );
        item = (AssetItem) assets.get( 0 );
        assertEquals( "testRenameAssetSource",
                      item.getName() );
        assertEquals( "la",
                      item.getContent() );
        assertEquals( "testRenamePackage2",
                      item.getPackageName() );

        List packageFinal = iteratorToList( repo.listPackages() );
        assertEquals( packagesOriginal.size(),
                      packageFinal.size() );

    }

    @Test
    public void testCopyPackage() throws Exception {
        RulesRepository repo = getRepo();
        PackageItem source = repo.createPackage( "testCopyPackage",
                                                 "asset" );
        AssetItem item = source.addAsset( "testCopyPackage",
                                          "desc" );
        item.updateContent( "la" );
        item.checkin( "" );
        repo.save();

        repo.copyPackage( "testCopyPackage",
                          "testCopyPackage2" );
        PackageItem dest = repo.loadPackage( "testCopyPackage2" );
        assertNotNull( dest );
        assertFalse( source.getUUID().equals( dest.getUUID() ) );

        assertEquals( 1,
                      iteratorToList( dest.getAssets() ).size() );
        AssetItem item2 = (AssetItem) dest.getAssets().next();

        assertEquals( "testCopyPackage",
                      item.getPackageName() );
        assertEquals( "testCopyPackage2",
                      item2.getPackageName() );

        item2.updateContent( "goober choo" );
        item2.checkin( "yeah" );

        assertEquals( "la",
                      item.getContent() );

        try {
            repo.copyPackage( "testCopyPackage",
                              "testCopyPackage2" );
            fail( "should not be able to copy when existing." );

        } catch ( RulesRepositoryException e ) {
            assertNotNull( e.getMessage() );
        }

    }

    @Test
    public void testListStates() {
        RulesRepository repo = getRepo();
        StateItem[] items = repo.listStates();
        assertTrue( items.length > 0 );

        repo.createState( "testListStates" );

        StateItem[] items2 = repo.listStates();
        assertEquals( items.length + 1,
                      items2.length );
    }

    @Test
    public void testRenameState() {
        RulesRepository repo = getRepo();
        StateItem[] items = repo.listStates();
        assertTrue( items.length > 0 );

        final String oldName = "stateThatHasALongNameAndWillBeRenamed";
        repo.createState( oldName );

        StateItem[] items2 = repo.listStates();
        assertEquals( items.length + 1,
                      items2.length );

        final String newName = "stateThatHasALongNameAndWillBeRenamedNameAfterTheRenaming";
        repo.renameState( oldName,
                          newName );

        StateItem[] items3 = repo.listStates();
        assertEquals( items2.length,
                      items3.length );
        try {
            repo.loadState( oldName );
            fail( "Should never be here. Old name is still used." );
        } catch ( RulesRepositoryException e ) {
            // Works
        }

        assertNotNull( repo.loadState( newName ) );
    }

    @Test
    public void testRemoveState() {
        RulesRepository repo = getRepo();
        StateItem[] items = repo.listStates();
        assertTrue( items.length > 0 );

        final String name = "stateThatHasALongNameAndWillBeRenamed";
        repo.createState( name );

        StateItem[] items2 = repo.listStates();
        assertEquals( items.length + 1,
                      items2.length );

        repo.loadState( name ).remove();
        repo.save();

        StateItem[] items3 = repo.listStates();
        assertEquals( items2.length -1,
                      items3.length );
        try {
            repo.loadState( name );
            fail( "Should never be here. Removed state still exists." );
        } catch ( RulesRepositoryException e ) {
            // Works
        }

    }
    /*
     * http://jira.jboss.org/browse/MODE-882
     */
    @Test
    public void testSimpleImportExport() throws PathNotFoundException, IOException, RepositoryException {
        RulesRepository repo = getRepo();

        byte[] repository_backup;

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        Session session = getRepo().getSession();
        session.refresh( false );
        session.exportSystemView( "/" + "drools:repository", bout, false, false );
        repository_backup = bout.toByteArray();
        repo.importRulesRepositoryFromStream(new ByteArrayInputStream(
                repository_backup));
    }

    @Test
    public void testImportExport() {
        RulesRepository repo = getRepo();
        byte[] repository_unitest;
        byte[] repository_backup;

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        repo.exportRulesRepositoryToStream(bout);
        repository_backup = bout.toByteArray();
        assertNotNull(repository_backup);

        repo.createPackage("testImportExport", "nodescription");
        bout = new ByteArrayOutputStream();
        repo.exportRulesRepositoryToStream(bout);

        repository_unitest = bout.toByteArray();

        repo.importRulesRepositoryFromStream(new ByteArrayInputStream(
                repository_backup));
        assertFalse(repo.containsPackage("testImportExport"));

        repo.importRulesRepositoryFromStream(new ByteArrayInputStream(
                repository_unitest));

        assertTrue(repo.containsPackage("testImportExport"));

        repo.importRepository(new ByteArrayInputStream(repository_unitest));
        assertTrue(repo.containsPackage("testImportExport"));
    }

     /*
     * https://jira.jboss.org/browse/MODE-883
     */
    @Test
    public void testSimpleShareableNodes() throws Exception {

        Node node = getRepo().getSession().getNode("/drools:repository/drools:package_area/globalArea/");
        Node assetNode = node.getNode("assets").addNode("testKurt","drools:assetNodeType");
        //Adding some required properties
        assetNode.setProperty("drools:packageName", "one");
        assetNode.setProperty("drools:title", "title");
        assetNode.setProperty("drools:format", "format");
        assetNode.setProperty("drools:description", "description");
        Calendar lastModified = Calendar.getInstance();
        assetNode.setProperty("drools:lastModified", lastModified);
        getRepo().getSession().save();
        assetNode.checkin();

        //Creating a shared Node
        assetNode.checkout();
        assetNode.addMixin("mix:shareable");
        getRepo().getSession().save();
        assetNode.checkin();
        Workspace workspace = getRepo().getSession().getWorkspace();
        String srcPath   = "/drools:repository/drools:package_area/globalArea/assets/testKurt";
        String path    = "/drools:repository/drools:package_area/defaultPackage/assets/testKurt";
        workspace.clone(workspace.getName(), srcPath, path, false);

        assetNode.remove();

    }

    @Test
    public void testShareableNodes() throws Exception {
        RulesRepository repo = getRepo();
        AssetItem item = repo.loadDefaultPackage().addAsset("testShareableNodeOriginal", "desc");
        item.updateContent("la");
        item.getNode().addMixin("mix:shareable");
        PackageItem source = repo.createPackage("testShareableNodesPackage", "desc");
        repo.save();

        source.checkout();

        Session session = repo.getSession();
        Workspace workspace = session.getWorkspace();
        String path = "/drools:repository/drools:package_area/testShareableNodesPackage/assets/testShareableNodeShared";
        workspace.clone(workspace.getName(), item.getNode().getPath(), path, false);
        repo.save();

        AssetItem originalItem = repo.loadDefaultPackage().loadAsset("testShareableNodeOriginal");
        AssetItem sharedItem = repo.loadPackage("testShareableNodesPackage").loadAsset("testShareableNodeShared");

        assertTrue( originalItem.getContent().equals("la"));
        assertTrue( sharedItem.getContent().equals("la"));

        originalItem.remove();
    }

    @Test
    public void testShareableNodesWithQuery() throws Exception {
        RulesRepository repo = getRepo();
        AssetItem item = repo.loadGlobalArea().addAsset("testShareableNodesWithQueryOriginal", "desc");
        item.updateFormat("xyz");
        item.getNode().addMixin("mix:shareable");
        PackageItem source = repo.createPackage("testShareableNodesWithQueryPackage", "desc");
        repo.save();

        AssetItemIterator it = repo.loadGlobalArea().queryAssets( "drools:format='xyz'" );
        List list = iteratorToList( it );
        assertEquals(1, list.size());
        assertTrue(list.get( 0 ) instanceof AssetItem);

        source.checkout();

        Session session = repo.getSession();
        Workspace workspace = session.getWorkspace();
        String path = "/drools:repository/drools:package_area/testShareableNodesWithQueryPackage/assets/testShareableNodesWithQueryShared";
        workspace.clone(workspace.getName(), item.getNode().getPath(), path, false);
        repo.save();

        AssetItem originalItem = repo.loadGlobalArea().loadAsset("testShareableNodesWithQueryOriginal");
        AssetItem sharedItem = repo.loadPackage("testShareableNodesWithQueryPackage").loadAsset("testShareableNodesWithQueryShared");

        assertTrue( originalItem.getFormat().equals("xyz"));
        assertTrue( sharedItem.getFormat().equals("xyz"));

        it = repo.loadGlobalArea().queryAssets( "drools:format='xyz'" );
        list = iteratorToList( it );
        assertEquals(1, list.size());
        assertTrue(list.get( 0 ) instanceof AssetItem);
    }

    @Test
    @Ignore("This test is broken. Suspect changes for new Workspaces and versionable packages could have broken.")
    public void testImportExportWithShareableNodes() throws Exception {
        RulesRepository repo = getRepo();
        AssetItem item = repo.loadDefaultPackage().addAsset("testImportExportShareableNodeOriginal", "desc");
        item.updateContent("la");
        item.getNode().addMixin("mix:shareable");
        PackageItem source = repo.createPackage("testImportExportShareableNodesPackage", "desc");
        repo.save();

        source.checkout();

        Session session = repo.getSession();
        Workspace workspace = session.getWorkspace();
        String path = "/drools:repository/drools:package_area/testImportExportShareableNodesPackage/assets/testImportExportShareableNodeShared";
        workspace.clone(workspace.getName(), item.getNode().getPath(), path, false);
        repo.save();

        byte[] repository_backup;

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        repo.exportRulesRepositoryToStream(bout);
        repository_backup = bout.toByteArray();
        assertNotNull(repository_backup);

        repo.importRulesRepositoryFromStream(new ByteArrayInputStream(
                repository_backup));
        assertTrue(repo.containsPackage("testImportExportShareableNodesPackage"));
        assertTrue(repo.loadPackage("testImportExportShareableNodesPackage").containsAsset("testImportExportShareableNodeOriginal"));
    }

    //In this test case we expect an ItemExistException from the second thread,
    //other than ending up with two packages with same name.
    //https://jira.jboss.org/jira/browse/GUVNOR-346
    @Test
    public void testConcurrentCopyPackage() throws Exception {
       // set up testing data
       RulesRepository repo = RepositorySessionUtil.getMultiThreadedRepository();
       PackageItem source = repo.createPackage("testConcurrentCopyPackage",
               "asset");
       AssetItem item = source.addAsset("testCopyPackage", "desc");
       item.updateContent("la");
       item.checkin("");
       repo.save();

       int NUM_ITERATIONS = 40;
       int NUM_SESSIONS = 2;
       for (int n = 0; n < NUM_ITERATIONS; n++) {
           Node folderNode = repo.getAreaNode(RulesRepository.RULE_PACKAGE_AREA);
           // cleanup
           while (folderNode.hasNode("testConcurrentCopyPackage2")) {
               folderNode.getNode("testConcurrentCopyPackage2").remove();
               repo.save();
           }

           Thread[] threads = new Thread[NUM_SESSIONS];
           for (int i = 0; i < threads.length; i++) {
               String id = "session#" + i;
               ConcurrentCopySession ts = new ConcurrentCopySession(id);
               Thread t = new Thread(ts);
               t.setName(id);
               t.start();
               threads[i] = t;
           }
           for (int i = 0; i < threads.length; i++) {
               threads[i].join();
           }

           //Node folderNode = repo.getAreaNode(RulesRepository.RULE_PACKAGE_AREA);
           folderNode.refresh(true);
           NodeIterator results = folderNode.getNodes("testConcurrentCopyPackage2");
           assertEquals(1, results.getSize());
       }        }

      class ConcurrentCopySession implements Runnable {
       String identity;
       Random r;
       RulesRepository localRepo;
       ConcurrentCopySession(String identity) {
           this.identity = identity;
           r = new Random();
           localRepo = RepositorySessionUtil.getMultiThreadedRepository();
       }

       private void randomSleep() {
           long l = r.nextInt(90) + 20;
           try {
               Thread.sleep(l);
           } catch (InterruptedException ie) {
           }
       }

       public void run() {
           try {
               //This returns different repository instances for different threads
               localRepo.copyPackage("testConcurrentCopyPackage",
                       "testConcurrentCopyPackage2");
               PackageItem dest = localRepo.loadPackage("testConcurrentCopyPackage2");
               assertNotNull(dest);
               randomSleep();
           } catch (RulesRepositoryException rre) {
               //expected
               System.out.println("Expected");
           } finally {
           }
       }
    }

    private static boolean deleteDir(File dir) {

        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }

        // The directory is now empty so delete it
        return dir.delete();
    }

    public static <T> List<T> iteratorToList(Iterator<T> it) {
        List<T> list = new ArrayList<T>();
        while ( it.hasNext() ) {
            list.add( it.next() );
        }
        return list;
    }
}


text:
.navbar-default .navbar-brand {
    color: #0047B2;
}

.navDropDown {
    background-color: rgba(0, 0, 0, 0.6);
}

.navbar-default.transparent .navbar-brand {
    color: white;
}

.navbar-default i {
    color: #0047B2;
}

.navbar-default.transparent i {
    color: white;
}

.navbar-default .navbar-nav>li>a {
    color: #0047B2;
}

.navbar-default.transparent .navbar-nav>li>a{
    color: white;
}

.navbar-default.transparent{
    background-color: transparent;
}

.navbar-default {
    background-color: white;
}

.jumbotron {
    position: relative;
    color: white;
    height: 60%;
}

#contact {
    position: absolute;
    bottom: 0px;
    width: 100%;
}

.container .jumbotron, .container-fluid .jumbotron {
    padding-left: 0;
    padding-right: 0;
}

#credit {
    position: absolute;
    bottom: 100px;
    right: 0px;
}

h3:hover {
    text-decoration: none;
}

#mainJumbotron {
    background-position: center center;
    background-size: cover;
}

/* coursel styling */
.right.carousel-control, .left.carousel-control {
    display: none;
}

.carousel-indicators {
    display:none;
}


text:
package opennlp.tools.stemmer;

import org.junit.Assert;
import org.junit.Test;

public class PorterStemmerTest {

  private PorterStemmer stemmer = new PorterStemmer();

  @Test
  public void testNotNull() {
    Assert.assertNotNull(stemmer);
  }

  @Test
  public void testStemming() {
    Assert.assertEquals(stemmer.stem("deny"), "deni" );
    Assert.assertEquals(stemmer.stem("declining"), "declin" );
    Assert.assertEquals(stemmer.stem("diversity"), "divers" );
    Assert.assertEquals(stemmer.stem("divers"), "diver" );
    Assert.assertEquals(stemmer.stem("dental"), "dental" );
  }
}


text:
if (!String.prototype.format) {
  String.prototype.format = function() {
    var args = arguments;
    return this.replace(/{(\d+)}/g, function(match, number) {
      return typeof args[number] != 'undefined'
        ? args[number]
        : match
      ;
    });
  };
  Object.defineProperty(String.prototype, "format", {enumerable: false});
}

DiabloCalc = {
  TAB_BUILDINFO: 0,
  TAB_EQUIPMENT: 1,
  TAB_PARAGON: 2,
  TAB_SKILLS: 3,
  TAB_IMPORT: 4,

  relPath: "/",
  options: {},
  optionPerProfile: {},
  pageTitle: document.title,
  ptr: false,//(location.hostname.toLowerCase().indexOf("ptr") >= 0),
  addOption: function(name, get, set, profile) {
    Object.defineProperty(this.options, name, {get: get, set: set, enumerable: true});
    if (profile) this.optionPerProfile[name] = true;
  },
  localeTable: {},
  locale: function() {
    var tables = [];
    for (var i = 0; i < arguments.length; ++i) {
      var tbl = DiabloCalc.localeTable[arguments[i]];
      if (tbl) tables.push(tbl);
    }
    tables.push(DiabloCalc.localeTable);
    var res = function(str) {
      for (var i = 0; i < tables.length; ++i) {
        if (tables[i][str]) return tables[i][str];
      }
      return str;
    };
    res.fixkey = _L.fixkey;
    res.fixval = _L.fixval;
    return res;
  },
  patch: {},
  session: {
    uid: MD5("" + Date.now() + Math.random()),
    start: Math.floor(Date.now() / 1000),
    activity: {},
  },
  activity: function(action) {
    this.session.activity[action] = (this.session.activity[action] || 0) + 1;
  },
  report: function() {
    this.session.duration = Math.floor(Date.now() / 1000) - this.session.start;
    $.ajax({
      url: "activity",
      type: "POST",
      data: JSON.stringify(this.session),
      global: false,
      processData: false,
      contentType: "application/json",
      dataType: "json",
    });
  },
};
DiabloCalc.season = 21;
//setInterval(function() {
//  DiabloCalc.report();
//}, 180000);
(function() {
  var m = location.pathname.match(/^(\/.*\/)[^/]*$/);
  if (m) {
    DiabloCalc.relPath = m[1];
  }
})();

_L = function(str) {
  if (!DiabloCalc.localeTable[str]) {
    return str;
  }
  return DiabloCalc.localeTable[str];
};
_L.fixkey = function(data) {
  var list = Object.keys(data);
  for (var i = 0; i < list.length; ++i) {
    var tr = this(list[i]);
    if (tr !== list[i]) {
      data[tr] = data[list[i]];
      delete data[list[i]];
    }
  }
  return data;
};
_L.fixval = function(data) {
  var list = Object.keys(data);
  for (var i = 0; i < list.length; ++i) {
    data[list[i]] = this(data[list[i]]);
  }
  return data;
};
_L.add = function(data) {
  $.extend(true, DiabloCalc.localeTable, data);
};
_L.patch = DiabloCalc.patch;
_L.patch.add = function(data) {
  $.extend(true, _L.patch, data);
};
_L.patch.apply = function(to) {
  function _myExtend(dst, src) {
    for (var key in src) {
      if (typeof src[key] === "object" && typeof dst[key] === "object") {
        _myExtend(dst[key], src[key]);
      } else {
        dst[key] = src[key];
      }
    }
  }
  _myExtend(to, this);
};
Object.defineProperty(_L, "fixkey", {enumerable: false});
Object.defineProperty(_L, "fixval", {enumerable: false});
Object.defineProperty(_L, "add", {enumerable: false});
Object.defineProperty(_L, "patch", {enumerable: false});
Object.defineProperty(_L.patch, "add", {enumerable: false});
Object.defineProperty(_L.patch, "apply", {enumerable: false});

DiabloCalc.translateMainPage = function() {
  var _L = DiabloCalc.locale("title");
  document.title = _L("Diablo III Character Planner");
  DiabloCalc.pageTitle = document.title;
  var label = $("#char-info label");
  var input = label.find("input").detach();
  label.text(_L("Level") + " ").append(input);
  if (document.styleSheets) {
    var ss = document.styleSheets[0];
    var tmp = $("

");
    tmp.text(_L("Equipment") + _L("Paragon") + _L("Skills/Effects") +
      _L("Import/Save") + _L("Simulate"));
    $("body").append(tmp);
    var fontSize = 16;
    do {
      --fontSize;
      tmp.css("font-size", fontSize + "px");
    } while (fontSize > 12 && tmp.width() > 420);
    fontSize = "font-size: " + fontSize + "px !important";
    if (ss.addRule) ss.addRule(".main-tab", fontSize, 0);
    else ss.insertRule(".main-tab {" + fontSize + ";}", 0);
    tmp.remove();
  }
  $("a[href=\"#tab-equipment\"]").text(_L("Equipment"));
  $("a[href=\"#tab-paragon\"]").text(_L("Paragon"));
  $("a[href=\"#tab-skills\"]").text(_L("Skills/Effects"));
  $("a[href=\"#tab-import\"]").text(_L("Import/Save"));
  $("a[href=\"#tab-buildinfo\"]").text(_L("Build Info"));
  //$(".theme-select option[value=\"light\"]").text(_L("Light Theme"));
  //$(".theme-select option[value=\"dark\"]").text(_L("Dark Theme"));
};

DiabloCalc.showPrivacy = function() {
  if (!this.privacyDlg) {
    this.privacyDlg = $("

");
    this.privacyDlg.load("/privacy.html", null, function() {
      DiabloCalc.privacyDlg.find("a").addClass("link-like");
    });
    this.privacyDlg.css({overflow: "auto"});
  }

  this.privacyDlg.dialog({
    resizable: true,
    title: _L("Privacy Policy"),
    height: 800,
    width: 1000,
    modal: true,
//    close: function() { dlg.remove(); },
//    open: function() {
//      dlg.parent().css("overflow", "visible");
//    },
  });
};

$(function() {
  $(".editframe").tabs({heightStyle: "fill"});
  $(window).resize(function() {
    $(".editframe").tabs("refresh");
  });

/*  $(".scroll-x").mCustomScrollbar({
    axis: "x",
    live: "on",
  });
  $(".scroll-y").mCustomScrollbar({
    axis: "y",
    live: "on",
  });*/

  $.cookie.json = true;
  var mo = location.hostname.match(/([^.]*\.)?[^.]*$/);
  if (mo) {
    $.cookie.defaults.domain = mo[0];
  }

  var ajaxSpinner = new Spinner({
    lines: 13, // The number of lines to draw
    length: 20, // The length of each line
    width: 10, // The line thickness
    radius: 30, // The radius of the inner circle
    corners: 1, // Corner roundness (0..1)
    rotate: 0, // The rotation offset
    direction: 1, // 1: clockwise, -1: counterclockwise
    color: '#000', // #rgb or #rrggbb or array of colors
    speed: 1, // Rounds per second
    trail: 60, // Afterglow percentage
    shadow: false, // Whether to render a shadow
    hwaccel: false, // Whether to use hardware acceleration
    className: 'spinner', // The CSS class to assign to the spinner
    zIndex: 2e9, // The z-index (defaults to 2000000000)
    top: '50%', // Top position relative to parent
    left: '50%' // Left position relative to parent
  });

  var spinning = 0;
  DiabloCalc.spinStart = function() {
    if (spinning++ <= 0) {
      ajaxSpinner.spin($(".page")[0]);
    }
  };
  DiabloCalc.spinStop = function() {
    if (--spinning <= 0) {
      ajaxSpinner.stop();
      spinning = 0;
    }
  };

  $(document).ajaxStart(function() {
    DiabloCalc.spinStart();
  });
  $(document).ajaxStop(function() {
    DiabloCalc.spinStop();
  });

  $("#privacy-policy").click(function(e) {
    if (e.shiftKey || e.ctrlKey || e.altKey) {
      return;
    }
    DiabloCalc.showPrivacy();
    e.preventDefault();
    return false;
  });

  /*var themeSelect = $(".theme-select");
  var themeBox;
  var theme = ($.cookie("theme") || "dark");*/
  var theme = "dark";
  ajaxSpinner.opts.color = (theme === "light" ? "#000" : "#ccc");
  $("body").removeClass().addClass("theme-" + theme);
  /*themeSelect.val(theme).css("margin-left", 12);
  themeSelect.change(function() {
    var theme = $(this).val();
    $("body").removeClass().addClass("theme-" + theme);
    $.cookie("theme", theme, {expires: 365});
    ajaxSpinner.opts.color = (theme === "light" ? "#000" : "#ccc");
    if (themeBox) {
      themeBox.remove();
      themeBox = undefined;
    }
    if (DiabloCalc.trigger) DiabloCalc.trigger("changeTheme");
  });*/

  var localeSelect = $(".locale-select");
  var curLocale = ($.cookie("locale") || "enUS");
  localeSelect.val(curLocale).css("margin-left", 12);
  localeSelect.change(function() {
    $.cookie("locale", $(this).val(), {expires: 365});
    location.reload();
  });
  //$(".footer").append(themeSelect);

  DiabloCalc.spinStart();

  //if (DiabloCalc.ptr) {
  //  $("#ptr-link").append("" + _L("Switch to live version") + "");
  //  $("#ptr-link").find("a").click(function() {
  //    $(this).attr("href", "http://" + location.hostname.replace(/^[^.]*/, "www") + location.pathname);
  //  });
  //} else {
  //  $("#ptr-link").append("" + _L("PTR version is available!") + "");
  //  $("#ptr-link").find("a").click(function() {
  //    $(this).attr("href", "http://" + location.hostname.replace(/^[^.]*/, "ptr") + location.pathname);
  //  });
  //}

  DC_getScript("scripts/data.js", function() {
    DiabloCalc.loadData(function() {
      var optgroupMain = $("<optgroup></optgroup>").attr("label", _L("Characters"));
      var optgroupFollower = $("<optgroup></optgroup>").attr("label", _L("Followers"));
      $(".char-class").append(optgroupMain);//.append(optgroupFollower);
      for (var cls in DiabloCalc.classes) {
        var option = $("<option></option>").val(cls).text(DiabloCalc.classes[cls].name).addClass("class-" + cls).addClass("class-icon");
        if (DiabloCalc.classes[cls].follower) {
          optgroupFollower.append(option);
        } else {
          optgroupMain.append(option);
        }
      }
      var prevClass;
      DiabloCalc.updateClassIcon = function() {
        var span = $(".char-class").next().find("span").first();
        if (prevClass) {
          span.removeClass(prevClass);
        }
        prevClass = "class-" + $(".char-class").val() + " " + (DiabloCalc.gender || "female");
        span.addClass(prevClass);
        $("#char-info").removeClass().addClass(DiabloCalc.gender || "female");
      };
      $(".char-class").chosen({
        disable_search: true,
        inherit_select_classes: true,
      }).change(function() {
        DiabloCalc.updateClassIcon();
        DiabloCalc.importStart();
        DiabloCalc.triggerNow("changeClass");
        DiabloCalc.importEnd("class");
      });
      DiabloCalc.updateClassIcon();
      if (!$(".char-class").data("chosen")) {
        DiabloCalc.noChosen = true;
      }
      DiabloCalc.charClass = $(".char-class").val();
      $(".char-class").next().find("span").first().addClass("class-icon");
      $(".char-level").blur(DiabloCalc.validateNumber);

      var seasonalTip = null;
      if (DiabloCalc.season === 20) {
        var seasonalBox = $("<input type=\"checkbox\" checked=\"checked\"></input>").change(function() {
          DiabloCalc.trigger("updateSkills");
        });
        var seasonalLabel = $("").append(_L("Seasonal")).append(seasonalBox);
        $("#char-info").append($("

").append(seasonalLabel));
        DiabloCalc.addOption("seasonal", function() {return seasonalBox.prop("checked") ? 1 : 0;}, function(x) {
          seasonalBox.prop("checked", !!x);
          DiabloCalc.trigger("updateSkills");
        });
        seasonalTip = _L("Seasonal characters can equip any legendary power in any Kanai cube slot.");
      } else if (DiabloCalc.season === 18) {
        var seasonalBox = $("<select value=\"1\"><option value=\"0\">None</option><option value=\"1\">Damage</option><option value=\"2\">Resources</option></select>").change(function() {
          DiabloCalc.trigger("updateSkills");
        });
        var seasonalLabel = $("").append(_L("Seasonal Buff")).append(seasonalBox);
        $("#char-info").append($("

").append(seasonalLabel));
        DiabloCalc.addOption("seasonal", function() {return parseInt(seasonalBox.val());}, function(x) {
          seasonalBox.val(x | 0);
          DiabloCalc.trigger("updateSkills");
        });
      } else if (DiabloCalc.season === 17) {
        var seasonalBox = $("<input type=\"checkbox\" checked=\"checked\"></input>").change(function() {
          DiabloCalc.trigger("updateSkills");
        });
        var seasonalLabel = $("").append(seasonalBox).append(_L("Seasonal"));
        $("#char-info").append($("

").append(seasonalLabel));
        DiabloCalc.addOption("seasonal", function() {return seasonalBox.prop("checked");}, function(x) {
          seasonalBox.prop("checked", x);
          DiabloCalc.trigger("updateSkills");
        });
        seasonalTip = _L("Seasonal characters always have Legacy of Nightmares set bonus.");
      }

      function onLoaded() {
        if (seasonalTip) {
          DiabloCalc.addTip(seasonalBox, seasonalTip);
        }
        DiabloCalc.spinStop();
        DiabloCalc.importEnd("init");
        var m = location.pathname.match(/\/e?([0-9]+)$/);
        if (m) {
          DiabloCalc.loadProfile(undefined, m[1], location.pathname[1] === "e");
        } else if (window.localStorage) {
          var profile;
          try {
            profile = localStorage.getItem("profile");
            profile = JSON.parse(profile);
          } catch (e) {
            profile = undefined;
          }
          if (profile) {
            var restore = $("
" + _L("Restore last session?") + "
");
            restore.append($("" + _L("Yes") + "").click(function() {
              try {
                localStorage.removeItem("profile", "");
              } catch (e) {
              }
              DiabloCalc.setAllProfiles(profile, "load");
              setTimeout(function() {restore.remove();}, 0);
            }), " / ", $("" + _L("No") + "").click(function() {
              try {
                localStorage.removeItem("profile", "");
              } catch (e) {
              }
              setTimeout(function() {restore.remove();}, 0);
            }));
            $(".dollframe").prepend(restore);
          }
        }
        m = location.pathname.match(/\/reset=([0-9a-f]{32})$/);
        if (m && DiabloCalc.account) {
          DiabloCalc.account.reset(m[1]);
          var url = location.protocol + "//" + location.hostname + DiabloCalc.relPath;
          if (window.history && window.history.replaceState) {
            window.history.replaceState({}, "", url);
          }
        }

        /*if (!$.cookie("theme")) {
          themeBox = $("

" + _L("Select your theme:") + "

(" + _L("Click to dismiss") + ")

").css("visibility", "hidden");
          $("body").append(themeBox);
          var pos = themeSelect.offset();
          themeBox.css("left", pos.left + themeSelect.outerWidth() / 2 - themeBox.outerWidth() / 2).css("top", pos.top - themeBox.outerHeight() - 20);
          themeBox.css("visibility", "");
          themeBox.click(function() {
            $.cookie("theme", theme);
            themeBox.remove();
            themeBox = undefined;
          });
        } else {
          $.ajax({
            url: "changes",
            dataType: "json",
            success: function(data) {
              if (data instanceof Array && data.length) {
                var newBox = $("

" + _L("What's new?") + "

" + _L("Click to dismiss") + "

").css("visibility", "hidden");
                for (var i = 0; i < data.length; ++i) {
                  newBox.append("
" + (new Date(1000 * data[i].date)).toLocaleString() + ":
" + data[i].text + "
");
                }
                $("body").append(newBox);
                var page = $(".page");
                var left = page.offset().left + page.outerWidth();
                newBox.css("max-width", Math.max(250, $(window).width() - left - 32));
                newBox.css("left", Math.min(left + 24, $(window).width() - newBox.outerWidth() - 8)).css("top", 16);
                newBox.css("visibility", "");
                var maxDate = data[0].date;
                newBox.click(function() {
                  $.cookie.json = false;
                  $.cookie("lastchange", maxDate + 1);
                  $.cookie.json = true;
                  newBox.remove();
                });
              }
            },
          });
        }*/
      }

      DiabloCalc.onLoaded = onLoaded;
      DC_getScript("core.js");
    });
  });
});


text:
{% load metadataparsertags i18n %}

      {% if entity_category and entity_category != 'All' %}{{ entity_category }}{% else %}{% trans "Entity Categories" %}{% endif %}

    {% trans "All Categories" %}

    {% for category in categories %}

    {{ category }}

    {% endfor %}

{% for etype in entity_types %}

  {{ etype|display_etype }}

{% endfor %}


text:
from btc.main import *
#from btc.pyspecials import *

# get wordlists

def open_wordlist(wordlist):
    try:
        if wordlist in ('Electrum1', 'electrum1', 'electrum'):
            from btc._electrum1wordlist import ELECTRUM1_WORDLIST
            assert len(ELECTRUM1_WORDLIST) == 1626
            return ELECTRUM1_WORDLIST
        elif wordlist in ('bip39', 'BIP39'):
            from btc._bip39wordlist import BIP0039_WORDLIST
            assert len(BIP0039_WORDLIST) == 2048
            return BIP0039_WORDLIST
    except: return None

def download_wordlist(wordlist):
    try:
        from btc.bci import make_request
        if wordlist in ('Electrum1', 'electrum1', 'electrum'):
            ELECTRUM1WORDS = make_request("https://gist.githubusercontent.com/anonymous" \
                  + "/f58f57780245db3cafc4/raw/1b5a9e81c0a356373e9e13aa720baef89d8fa856" \
                  + "/electrum1_english_words").decode('utf-8').strip().split()
            assert len(ELECTRUM1WORDS) == 1626
            return ELECTRUM1WORDS
        elif wordlist in ('bip39', 'BIP39'):
            BIP0039_WORDLIST = make_request("https://raw.githubusercontent.com" \
                                            + "/btc/bips/master/bip-0039/english.txt"
                                            ).decode('utf-8').strip().split('\n')
            assert len(BIP0039_WORDLIST) == 2048
            return BIP0039_WORDLIST
    except: return None

def bip39_hex_to_mnemonic(hexvalue):
    """
    Convert hex seed to BIP39 mnemonic
    https://github.com/btc/bips/blob/master/bip-0039.mediawiki#generating-the-mnemonic

    Essentially converts hex value to binary (with appended checksum),
    and splits into 11-bit binary chunks, each indexing a 2048 (=2**11)
    word list (in BIP39WORDS)

    hexseed: hexadecimal bytes or bytearray object

    >>> bip39_hex_to_mnemonic('eaebabb2383351fd31d703840b32e9e2')
    'turtle front uncle idea crush write shrug there lottery flower risk shell'
    """
    try:    BIP39WORDS = open_wordlist('bip39')
    except: BIP39WORDS = download_wordlist('bip39')
    if isinstance(hexvalue, string_or_bytes_types) and re.match('^[0-9a-fA-F]*$', from_bytestring_to_string(hexvalue)):
        hexvalue = from_string_to_bytes(hexvalue)
    else:
        raise TypeError("Enter a hex seed!")

    if len(hexvalue) % 4 != 0:
        raise Exception("Value not a multiple of 4 bytes!")
    elif len(hexvalue) not in range(4, 125, 4):
        raise Exception("32 < entropy < 992 bits only!")

    hexvalue = safe_unhexlify(hexvalue)
    cs = hashlib.sha256(hexvalue).hexdigest() # sha256 hexdigest
    bstr = (changebase( safe_hexlify(hexvalue), 16, 2, len(hexvalue)*8) +
		    changebase( cs, 16, 2, 256)[ : len(hexvalue) * 8 // 32])

    return " ".join( [BIP39WORDS[int(x, 2)] for x in
                      [bstr[i:i+11] for i in range(0, len(bstr), 11)] ] )

def bip39_mnemonic_to_hex(mnemonic, saltpass=None):
    """
    Convert BIP39 mnemonic to hex seed
    https://github.com/btc/bips/blob/master/bip-0039.mediawiki#generating-the-mnemonic

    mnemonic: single spaced, lower-case words

    >>>bip39_mnemonic_to_hex("board flee heavy tunnel powder denial science ski answer betray cargo cat")
    '18ab19a9f54a9274f03e5209a2ac8a91'
    """
    if isinstance(mnemonic, string_or_bytes_types):
        try:
            mn_string = st(mnemonic)
            mn_array = mnemonic.lower().strip().split(" ")
        except:
            raise TypeError("Bad mnemonic input. Enter lower case, string of words")
    elif isinstance(mnemonic, list):
        mn_array = map(st, mnemonic)
    else:   raise TypeError("Enter a lower case, single-spaced mnemonic!!")

    if len(mn_array) not in range(3, 124, 3):
        raise TypeError("32 < entropy < 992 bits; Input too big or too small")
    if len(mn_array) % 3 != 0:
        raise TypeError("Too many or too few words")
    #assert all(map(lambda x: x in BIP39WORDS, mnemonic_array)) # check all words are in list
    mnem = ' '.join(mn_array)

    try:
        assert bip39_check_mnemonic(mnem)
        seed = pbkdf2(mnem, 'mnemonic'+saltpass)
        return safe_hexlify(seed)
    except:
        raise IOError("Mnemonic checksum is bad!")

def bip39_check_mnemonic(mnemonic):
    """
    Assert mnemonic is BIP39 standard
    """
    try:    BIP39WORDS = open_wordlist('bip39')
    except: BIP39WORDS = download_wordlist('bip39')
    if isinstance(mnemonic, string_types):
        try:
            mn_array = from_string_to_bytes(mnemonic).lower().strip().split(" ")
        except:
            raise TypeError("Enter a lower case, single-spaced mnemonic!")
    else:   raise TypeError("Enter a lower case, single-spaced mnemonic!!")

    if len(mn_array) not in range(3, 124, 3):
        raise TypeError("32 < entropy < 992 bits; Input too big or too small")
    # if len(mn_array) % 3 != 0:
    #     raise TypeError("Too many or too few words")
    assert all(map(lambda x: x in BIP39WORDS, mn_array)) # check all words are in list

    try:    binstr = ''.join([ changebase(str(BIP39WORDS.index(x)), 10, 2, 11) for x in mn_array])
    except: raise IOError("Are the words in the right order?")

    L = len(binstr)
    bd = binstr[:L // 33 * 32]
    cs = binstr[-L // 33:]
    hexd = safe_unhexlify(changebase(bd, 2, 16, L // 33 * 8))
    hexd_cs = changebase(hashlib.sha256(hexd).hexdigest(), 16, 2, 256)[:L // 33]
    return cs == hexd_cs

def bip39_generate(bits=128):
    """Generates a tuple of (hex seed, mnemonic)"""
    if bits % 32 != 0:
        raise Exception('Should be divisible by 32, but is .. %d' % bits)
    seed = safe_hexlify(by(random_string(bits // 8)))
    return (seed, bip39_hex_to_mnemonic(seed))

def random_bip39_seed(bits=128):
    return bip39_generate(bits=bits)[0]

def random_bip39_mnemonic(bits=128):
    return bip39_generate(bits=bits)[1]

def electrum1_mnemonic_decode(mnemonic):
    """Decodes Electrum 1.x mnemonic phrase to hex seed"""
    try:    ELECTRUM1WORDS = open_wordlist('electrum1')
    except: ELECTRUM1WORDS = download_wordlist('electrum1')
    if isinstance(mnemonic, string_or_bytes_types):
        try: mn_array = from_string_to_bytes(mnemonic).lower().strip().split(" ")
        except: raise TypeError("Enter the Electrum 1.x mnemonic as a string")
    elif isinstance(mnemonic, list):
        mn_array = mnemonic[:]
    else:   raise TypeError("Bad input type")
    wlist, words, n = mn_array, ELECTRUM1WORDS, len(ELECTRUM1WORDS)
    # https://github.com/spesmilo/electrum/blob/1b6abf6e028cbabd5e125784cff6d4ada665e722/lib/old_mnemonic.py#L1672
    output = ''
    for i in range(len(wlist)/3):
        word1, word2, word3 = wlist[3*i:3*i+3]
        w1 =  words.index(word1)
        w2 = (words.index(word2))%n
        w3 = (words.index(word3))%n
        x = w1 +n*((w2-w1)%n) +n*n*((w3-w2)%n)
        output += '%08x'%x
    return output

def electrum1_mnemonic_encode(hexvalue):
    """Encodes a hex seed as Electrum 1.x mnemonic phrase"""
    try:    ELECTRUM1WORDS = open_wordlist('electrum1')
    except: ELECTRUM1WORDS = download_wordlist('electrum1')
    if isinstance(hexvalue, string_or_bytes_types) and re.match('^[0-9a-fA-F]*$', from_bytes_to_string(hexvalue)):
        hexvalue = from_string_to_bytes(hexvalue)
    else: raise TypeError("Enter a hex value!")
    message, words, n = hexvalue, ELECTRUM1WORDS, len(ELECTRUM1WORDS)
    # https://github.com/spesmilo/electrum/blob/1b6abf6e028cbabd5e125784cff6d4ada665e722/lib/old_mnemonic.py#L1660
    assert len(message) % 8 == 0
    out = []
    for i in range(len(message)/8):
        word = message[8*i:8*i+8]
        x = int(word, 16)
        w1 = (x%n)
        w2 = ((x/n) + w1)%n
        w3 = ((x/n/n) + w2)%n
        out += [ words[w1], words[w2], words[w3] ]
    return out


text:
using IsolatedIslandGame.Protocol.Communication.EventCodes;
using IsolatedIslandGame.Protocol.Communication.EventParameters.Player;
using System;
using System.Collections.Generic;

namespace IsolatedIslandGame.Library.CommunicationInfrastructure.Events.Handlers.PlayerEventHandlers
{
    class StartTransactionHandler : EventHandler<Player, PlayerEventCode>
    {
        public StartTransactionHandler(Player subject) : base(subject, 3)
        {
        }

        internal override bool Handle(PlayerEventCode eventCode, Dictionary<byte, object> parameters)
        {
            if (base.Handle(eventCode, parameters))
            {
                try
                {
                    int transactionID = (int)parameters[(byte)StartTransactionParameterCode.TransactionID];
                    int requesterPlayerID = (int)parameters[(byte)StartTransactionParameterCode.RequesterPlayerID];
                    int accepterPlayerID = (int)parameters[(byte)StartTransactionParameterCode.AccepterPlayerID];

                    subject.AddTransaction(new Transaction(transactionID, requesterPlayerID, accepterPlayerID));
                    return true;
                }
                catch (InvalidCastException ex)
                {
                    LogService.Error("StartTransaction Parameter Cast Error");
                    LogService.Error(ex.Message);
                    LogService.Error(ex.StackTrace);
                    return false;
                }
                catch (Exception ex)
                {
                    LogService.Error(ex.Message);
                    LogService.Error(ex.StackTrace);
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
    }
}