text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
public class CutSceneManger : MonoBehaviour {

	public List< GameObject> Characters;
	public int CharacterNumber;
	public Transform CharacterGroup;
	public float RotateSpeed;
	public List< Transform >PlanetList;
	public int NowPlanet;
	public GameObject Explosion;
	public AudioSource ExplosionSound;
	public Transform ExplosionSpawnPoint;
	public GameObject SpeedEffect;
	// Use this for initialization
	void Start () {
		Characters [CharacterNumber].SetActive (true);

		StartCoroutine (PlanetChange());

	}

	// Update is called once per frame
	void Update () {
		CharacterGroup.eulerAngles += Vector3.forward*Time.deltaTime*RotateSpeed;
	}

	IEnumerator PlanetChange(){

		PlanetList [NowPlanet].DOLocalMoveZ (3f, 2).SetEase (Ease.OutBounce);

		yield return new WaitForSeconds(2f);

		if (NowPlanet != PlanetList.Count - 1) {
			PlanetList [NowPlanet].DOLocalMoveX (3, 1).SetEase (Ease.InOutExpo);

			NowPlanet++;
			StartCoroutine (PlanetChange ());

		} else {

			CharacterGroup.DOScale (Vector3.zero, 0.5f).OnComplete(CharacterGone);
			SpeedEffect.SetActive (false);
		}

	}

	void CharacterGone(){

		ExplosionSound.Play ();
		Instantiate (Explosion,ExplosionSpawnPoint.position,Quaternion.identity);

	}

}


text:
Unknown.

```csharp
public static readonly Answer Maybe;
```

## See Also

* struct [Answer](../Answer.md)
* namespace [Facility.ConformanceApi](../../Facility.ConformanceApi.md)

<!-- DO NOT EDIT: generated by xmldocmd for Facility.ConformanceApi.dll -->

redpajama_set_name: RedPajamaGithub


text:
package com.brilapps.core.exceptions;

/**
 * This exception class is used to handle application or system errors in the
 * application
 *
 * @author Pradeep
 *
 */
public class SystemException extends ApplicationException {

	private static final long serialVersionUID = -7459803588866142666L;

	public SystemException(final Throwable cause) {
		super(cause);
	}

	public SystemException(final String message) {
		super(message);
	}

}


text:
using Lucene.Net.Support;
using NUnit.Framework;
using System.Collections;
using System.Collections.Generic;

namespace Lucene.Net.Util
{

    [Ignore]
    [TestFixture]
    public class TestWAH8DocIdSet : BaseDocIdSetTestCase<WAH8DocIdSet>
    {
        public override WAH8DocIdSet CopyOf(BitArray bs, int length)
        {
            int indexInterval = TestUtil.NextInt(Random(), 8, 256);
            WAH8DocIdSet.Builder builder = (WAH8DocIdSet.Builder)(new WAH8DocIdSet.Builder()).SetIndexInterval(indexInterval);
            for (int i = bs.NextSetBit(0); i != -1; i = bs.NextSetBit(i + 1))
            {
                builder.Add(i);
            }
            return builder.Build();
        }

        public override void AssertEquals(int numBits, BitArray ds1, WAH8DocIdSet ds2)
        {
            base.AssertEquals(numBits, ds1, ds2);
            Assert.AreEqual(ds1.Cardinality(), ds2.Cardinality());
        }

        [Ignore]
        [Test]
        public virtual void TestUnion()
        {
            int numBits = TestUtil.NextInt(Random(), 100, 1 << 20);
            int numDocIdSets = TestUtil.NextInt(Random(), 0, 4);
            IList<BitArray> fixedSets = new List<BitArray>(numDocIdSets);
            for (int i = 0; i < numDocIdSets; ++i)
            {
                fixedSets.Add(RandomSet(numBits, (float)Random().NextDouble() / 16));
            }
            IList<WAH8DocIdSet> compressedSets = new List<WAH8DocIdSet>(numDocIdSets);
            foreach (BitArray set in fixedSets)
            {
                compressedSets.Add(CopyOf(set, numBits));
            }

            WAH8DocIdSet union = WAH8DocIdSet.Union(compressedSets);
            BitArray expected = new BitArray(numBits);
            foreach (BitArray set in fixedSets)
            {
                for (int doc = set.NextSetBit(0); doc != -1; doc = set.NextSetBit(doc + 1))
                {
                    expected.SafeSet(doc, true);
                }
            }
            AssertEquals(numBits, expected, union);
        }

        [Ignore]
        [Test]
        public virtual void TestIntersection()
        {
            int numBits = TestUtil.NextInt(Random(), 100, 1 << 20);
            int numDocIdSets = TestUtil.NextInt(Random(), 1, 4);
            IList<BitArray> fixedSets = new List<BitArray>(numDocIdSets);
            for (int i = 0; i < numDocIdSets; ++i)
            {
                fixedSets.Add(RandomSet(numBits, (float)Random().NextDouble()));
            }
            IList<WAH8DocIdSet> compressedSets = new List<WAH8DocIdSet>(numDocIdSets);
            foreach (BitArray set in fixedSets)
            {
                compressedSets.Add(CopyOf(set, numBits));
            }

            WAH8DocIdSet union = WAH8DocIdSet.Intersect(compressedSets);
            BitArray expected = new BitArray(numBits);
            expected.SetAll(true);
            foreach (BitArray set in fixedSets)
            {
                for (int previousDoc = -1, doc = set.NextSetBit(0); ; previousDoc = doc, doc = set.NextSetBit(doc + 1))
                {
                    int startIdx = previousDoc + 1;
                    int endIdx;
                    if (doc == -1)
                    {
                        endIdx = startIdx + set.Count;
                        //expected.Clear(previousDoc + 1, set.Count);
                        for (int i = startIdx; i < endIdx; i++)
                        {
                            expected[i] = false;
                        }
                        break;
                    }
                    else
                    {
                        endIdx = startIdx + doc;
                        for (int i = startIdx; i > endIdx; i++)
                        {
                            expected[i] = false;
                        }
                        //expected.Clear(previousDoc + 1, doc);
                    }
                }
            }
            AssertEquals(numBits, expected, union);
        }
    }
}


text:
packing-list
============

Packing list android App


text:
import {calculateErrors, calculateCollisions} from './token';

/**
 * Throw where the object[field] is not a function.
 *
 * @throws Error on object does not contain a function
 * @param {object} obj An object that should contain a function member
 * @param {string} field The name of the member expected to be a function
 * @param {string} message A title for the error
 */
export const assertGettextInstance = (obj, field, message) => {
  const isValid = (obj !== null) && (typeof obj === 'object') &&
    (field in obj) && (typeof obj[field] === 'function');
  if (!isValid) {
    throw new Error(`${message}: Gettext instance is missing ${field}() member`);
  }
};

/**
 * Throws where the candidate is not an integer.
 *
 * @throws Error on non integer
 * @param {*} candidate Possible integer
 * @param {string} message A title for the error
 */
export const assertQuantity = (candidate, message) => {
  const isValid = (typeof candidate === 'number') && !isNaN(candidate) && (candidate % 1 === 0);
  if (!isValid) {
    throw new Error(`${message}: Expected an integer quantity`);
  }
};

/**
 * Throws where the candidate is not an empty list.
 *
 * @throws Error on non-empty list
 * @param {Array} candidate List of additional arguments
 * @param {string} message A title for the error
 */
export const assertUnexpected = (candidate, message) => {
  const isValid = Array.isArray(candidate) && (candidate.length === 0);
  if (!isValid) {
    throw new Error(`${message}: Expected no additional arguments`);
  }
};

/**
 * Throw on token problems.
 *
 * @throws Error on token problems
 * @param {Array.<{name :string, value: *}>} tokens A number of tokens
 * @param {string} message A title for the error
 */
export const assertTokens = (tokens, message) => {
  const errors = calculateErrors(tokens);
  if (errors.length) {
    throw new Error(`${message}: ${errors[0]}`);
  }

  const collisions = calculateCollisions(tokens);
  if (collisions.length) {
    throw new Error(
      `${message}: substitution with the same name must have the same value: ${collisions}`);
  }
};

/**
 * Throw on incorrect number of plural forms.
 *
 * @throws Error on incorrect number of plural forms
 * @param {number|*} expected Expected number of plural forms, possibly non-numeric where disabled
 * @param {number} actual Actual number of plural forms found
 * @param {string} message A title for the error
 */
export const assertPluralForms = (expected, actual, message) => {
  if (!isNaN(expected) && (expected > 0) && (actual !== expected)) {
    throw new Error(`${message}: expected ${expected} plural forms, saw ${actual}`);
  }
};


text:
package org.apache.lucene.analysis.miscellaneous;

import org.apache.lucene.analysis.*;
import org.apache.lucene.analysis.core.KeywordTokenizer;
import org.apache.lucene.util.Version;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.BaseTokenStreamTestCase;
import org.apache.lucene.analysis.MockTokenizer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.core.KeywordTokenizer;
import org.junit.Test;

public class TestLengthFilter extends BaseTokenStreamTestCase {

  public void testFilterNoPosIncr() throws Exception {
    TokenStream stream = new MockTokenizer(
        new StringReader("short toolong evenmuchlongertext a ab toolong foo"), MockTokenizer.WHITESPACE, false);
    LengthFilter filter = new LengthFilter(Version.LUCENE_4_3, false, stream, 2, 6);
    assertTokenStreamContents(filter,
      new String[]{"short", "ab", "foo"},
      new int[]{1, 1, 1}
    );
  }

  public void testFilterWithPosIncr() throws Exception {
    TokenStream stream = new MockTokenizer(
        new StringReader("short toolong evenmuchlongertext a ab toolong foo"), MockTokenizer.WHITESPACE, false);
    LengthFilter filter = new LengthFilter(TEST_VERSION_CURRENT, stream, 2, 6);
    assertTokenStreamContents(filter,
      new String[]{"short", "ab", "foo"},
      new int[]{1, 4, 2}
    );
  }

  public void testEmptyTerm() throws IOException {
    Analyzer a = new Analyzer() {
      @Override
      protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
        Tokenizer tokenizer = new KeywordTokenizer(reader);
        return new TokenStreamComponents(tokenizer, new LengthFilter(TEST_VERSION_CURRENT, tokenizer, 0, 5));
      }
    };
    checkOneTerm(a, "", "");
  }

  /**
   * checking the validity of constructor arguments
   */
  @Test(expected = IllegalArgumentException.class)
  public void testIllegalArguments() throws Exception {
    new LengthFilter(TEST_VERSION_CURRENT, new MockTokenizer(new StringReader("accept only valid arguments")), -4, -1);
  }
}


text:
@extends('admin::layout.main')

@section('title')
	Article Categories
@stop

@section('page_title')
	 Article Categories
@stop

@section('breadcrumbs')
	@parent

 Article Categories

@stop

@section('sidebar')
	@parent
	@include('admin::article_categories.sidebar')
@stop

@section('content')

				Title
				Description
				Pages
				Articles

			@foreach ($article_categories as $key => $article_category)

					{{ $article_category->name }}
					{{ $article_category->description }}
					{{ $article_category->pages->count() }}
					{{ $article_category->articles->count() }}

						id) }}" class="btn btn-primary btn-xs"> Edit
						pageIds()) }}" data-id="{{ $article_category->id }}" class="btn btn-primary btn-xs" data-toggle="modal" href='#pagesModal'> Pages

			@endforeach

				<form method="post" action="{{route('admin-article_categories-pages')}}" role="form" accept-charset="UTF-8" enctype="multipart/form-data">

						<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Select Pages

						<select id="pages" name="pages[]" multiple class="selectpicker" data-size="5" data-width="100%" data-tick-icon="fa fa-check-square">
						@foreach (\Ogilo\Admin\Models\Page::all() as $key => $page)
							<option value="{{ $page->id }}">{{ $page->title }}</option>
						@endforeach
						</select>
						<input type="hidden" name="id" value="">
						<input type="hidden" name="_token" value="{{csrf_token()}}">

						<button type="button" class="btn btn-default" data-dismiss="modal">×Close</button>
						<button type="submit" class="btn btn-primary"> Save</button>

				</form>

@stop

@section('styles')

@stop
@section('scripts_top')

@stop

@section('scripts_bottom')

@stop


text:
'use strict';

var englishLanguage = {
  buttons: {
    learnMore: 'Have Questions? We don\'t bite',
    getStarted: 'Sign Me Up!',
    login: 'Login',
    register: 'Register',
    askQuestion: 'Ask A Question'
  },
  components: {
    callToAction: {
      header: 'Candid and Experienced Degree Knowledge',
      body: 'WhichDegree.co is a domain-based degree exploration platform designed to connect you to professionals. '+
      'Our mission is to deliver straight-talk from professionals, and we start with Information Technology;  '+
      'the domain which got us here. ',
      readMore: 'Read More',
      formTitle: 'Free Domain-Knowledge News'
    }
  },
  forms: {
    labels: {
      name: 'Name',
      email: 'Email',
      message: 'Message',
      question: 'Question',
      selectDomain: 'Domain',
      tellUsDomain: 'Tell Us Your Domain...'
    }
  },
  sr: {
    toggleNavigation: 'Toggle navigation'
  }
};

englishLanguage.components.navigation = {
  title: 'WebTech',
  backToApp: 'Back To App',
  domains: {
    title: 'Domains',
    moreToCome: 'More to Come!'
  },
  login: englishLanguage.buttons.login,
  register: englishLanguage.buttons.register,
  logout: 'Logout',
  myAccount: 'My Account'
};

module.exports = function(){
  return {
    name: 'english',
    lang: englishLanguage
  };
};


text:
"""Contains helper for appending user agent information."""

import six
import sys
import gslib
from gslib.utils import system_util
from gslib.storage_url import StorageUrlFromString
from gslib.exception import InvalidUrlError

def GetUserAgent(args, metrics_off=True):
  """Using the command arguments return a suffix for the UserAgent string.

  Args:
    args: str[], parsed set of arguments entered in the CLI.
    metrics_off: boolean, whether the MetricsCollector is disabled.

  Returns:
    str, A string value that can be appended to an existing UserAgent.
  """
  user_agent = ' gsutil/%s' % gslib.VERSION
  user_agent += ' (%s)' % sys.platform
  user_agent += ' analytics/%s' % ('disabled' if metrics_off else 'enabled')
  user_agent += ' interactive/%s' % system_util.IsRunningInteractively()

  if len(args) > 0:
    user_agent += ' command/%s' % args[0]

    if len(args) > 2:
      if args[0] in ['cp', 'mv', 'rsync']:
        # Any cp, mv or rsync commands that use daisy chain mode should be noted
        # as that represents a unique use case that may be better served by the
        # storage transfer service.
        try:
          src = StorageUrlFromString(six.ensure_text(args[-2]))
          dst = StorageUrlFromString(six.ensure_text(args[-1]))
          if src.IsCloudUrl() and dst.IsCloudUrl() and src.scheme != dst.scheme:
            user_agent += '-DaisyChain'
        except InvalidUrlError:
          pass
      elif args[0] == 'rewrite':
        if '-k' in args:
          # Rewrite encryption key.
          user_agent += '-k'
        if '-s' in args:
          # Rewrite storage class.
          user_agent += '-s'

  if system_util.InvokedViaCloudSdk():
    user_agent += ' google-cloud-sdk'
    if system_util.CloudSdkVersion():
      user_agent += '/%s' % system_util.CloudSdkVersion()

  return user_agent


text:
<?php

namespace Lexik\Bundle\JWTAuthenticationBundle\Security\Http\Authentication;

use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationFailureEvent;
use Lexik\Bundle\JWTAuthenticationBundle\Events;
use Lexik\Bundle\JWTAuthenticationBundle\Response\JWTAuthenticationFailureResponse;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface as ContractsEventDispatcherInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;

/**
 * AuthenticationFailureHandler.
 *
 * @author Dev Lexik <dev@lexik.fr>
 */
class AuthenticationFailureHandler implements AuthenticationFailureHandlerInterface
{
    /**
     * @var EventDispatcherInterface
     */
    protected $dispatcher;

    /**
     * @param EventDispatcherInterface $dispatcher
     */
    public function __construct(EventDispatcherInterface $dispatcher)
    {
        $this->dispatcher = $dispatcher;
    }

    /**
     * {@inheritdoc}
     */
    public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
    {
        $event = new AuthenticationFailureEvent(
            $exception,
            new JWTAuthenticationFailureResponse($exception->getMessageKey())
        );

        if ($this->dispatcher instanceof ContractsEventDispatcherInterface) {
            $this->dispatcher->dispatch($event, Events::AUTHENTICATION_FAILURE);
        } else {
            $this->dispatcher->dispatch(Events::AUTHENTICATION_FAILURE, $event);
        }

        return $event->getResponse();
    }
}


text:
siphash.js
==========

A pure Javascript implementation of
[SipHash-2-4](http://131002.net/siphash/siphash.pdf)

> SipHash is a family of pseudorandom functions optimized for short
> inputs. Target applications include network traffic authentication and
> hash-table lookups protected against hash-flooding denial-of-service
> attacks. SipHash has well-defined security goals and competitive
> performance.

Installation
------------

Server-side installation (nodejs):

    $ npm install siphash

Browser-side: use `lib/siphash.min.js`.

Usage
-----

```javascript
var siphash = require("siphash"),
    key = siphash.string16_to_key("0123456789ABCDEF"),
    message = "Short test message",
    hash_hex = siphash.hash_hex(key, message);
```

A key is an array of 4 integers, and each of them will be clamped to
32 bits in order to build a 128-bit key.
For a random key, just generate 4 random integers instead of calling
`string16_to_key()`.

```javascript
var siphash = require("siphash"),
    key = [ 0xdeadbeef, 0xcafebabe, 0x8badf00d, 0x1badb002 ],
    message = "Short test message",
    hash_hex = siphash.hash_hex(key, message);
```

The 64-bit hash can also be obtained as two 32-bit values with
`hash(key, message)`:

```javascript
var siphash = require("siphash"),
    key = [ 0xdeadbeef, 0xcafebabe, 0x8badf00d, 0x1badb002 ],
    message = "Short test message",
    hash = siphash.hash(key, message),
    hash_msb = hash.h,
    hash_lsb = hash.l;
```

A 53-bit unsigned integer can be obtained with `hash_uint(key, message)`:

```javascript
var siphash = require("siphash"),
    key = siphash.string16_to_key("0123456789ABCDEF"),
    message = "Short test message",
    index = siphash.hash_uint(key, message);
```


text:
using System.Collections.Generic;
using dto.endpoint.auth.session;

namespace dto.endpoint.accountbalance
{

public class AccountDetails{
	public enum AccountStatus {

      	///
	///Enabled
	///

      ENABLED,
      	///
	///Disabled
	///

      DISABLED,
      	///
	///Suspended from dealing
	///

      SUSPENDED_FROM_DEALING,}
	public enum AccountType {

      	///
	///CFD account
	///

      CFD,
      	///
	///Spread bet account
	///

      SPREADBET,
      	///
	///Physical account
	///

      PHYSICAL,}
	///
	///Account identifier
	///
	public string accountId { get; set; }
	///
	///Account name
	///
	public string accountName { get; set; }
	///
	///Account alias
	///
	public string accountAlias { get; set; }
	///
	///Account status
	///
	public string status { get; set; }
	///
	///Account type
	///
	public string accountType { get; set; }
	///
	///True if this the default login account
	///
	public bool preferred { get; set; }
	///
	///Account balances
	///
	public AccountBalance balance { get; set; }
	///
	///Account currency
	///
	public string currency { get; set; }
	///
	///True if account can be transferred to
	///
	public bool canTransferFrom { get; set; }
	///
	///True if account can be transferred from
	///
	public bool canTransferTo { get; set; }
}
}


text:
http = require('http')
robot = require('robotjs')

port = 3000
host = '127.0.0.1'
previous_health = 0

server = http.createServer( function(req, res) {

    if (req.method == 'POST') {

        res.writeHead(200, {'Content-Type': 'text/html'})

        var body=''
        req.on('error', function(err) {
            console.error(err)
        }).on('data', function (data) {
            body += data
        }).on('end', function () {
            res.end( '' )
            parsePlayerUpdate(JSON.parse(body))
        })
    }

}).listen(port, host)

// Takes the parsed json and plays/pauses the music when it should
function parsePlayerUpdate(update) {

    steamid = update.player.steamid
    activity = update.player.activity

    if(steamid == '76561198058071054' && activity !== 'menu') {
        try {
            health = update.player.state.health
            if((health > 0 && previous_health == 0) || (health == 0 && previous_health > 0)) {
                robot.keyTap('audio_pause')
                console.log('play/pause')
            }

            previous_health = update.player.state.health
        } catch(err) {
            console.error(err)
        }
    }
}

console.log('Listening at http://' + host + ':' + port)


text:
package com.elmakers.mine.bukkit.magic.listener;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.event.inventory.InventoryAction;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryCreativeEvent;
import org.bukkit.event.inventory.InventoryDragEvent;
import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.inventory.CraftingInventory;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryView;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.Plugin;

import com.elmakers.mine.bukkit.api.action.GUIAction;
import com.elmakers.mine.bukkit.api.spell.Spell;
import com.elmakers.mine.bukkit.magic.Mage;
import com.elmakers.mine.bukkit.magic.MagicController;
import com.elmakers.mine.bukkit.tasks.ActivateIconTask;
import com.elmakers.mine.bukkit.tasks.WandCastTask;
import com.elmakers.mine.bukkit.utility.CompatibilityLib;
import com.elmakers.mine.bukkit.utility.CompleteDragTask;
import com.elmakers.mine.bukkit.utility.CurrencyAmount;
import com.elmakers.mine.bukkit.utility.SafetyUtils;
import com.elmakers.mine.bukkit.wand.Wand;
import com.elmakers.mine.bukkit.wand.WandInventory;
import com.elmakers.mine.bukkit.wand.WandMode;

public class InventoryController implements Listener {
    private static final int DEBUG_LEVEL = 80;

    private final MagicController controller;
    private boolean enableItemHacks = true;
    private boolean dropChangesPages = false;
    private long openCooldown = 0;
    private boolean enableInventoryCasting = true;
    private boolean enableInventoryDropCasting = false;
    private boolean enableInventorySelection = true;
    private Set<InventoryType> unstashableTypes = new HashSet<>();

    // offhand, helmet, chestplate, leggings, boots
    private static final Integer[] armorSlotList = new Integer[] {39,38,37,36};
    private static final Set<Integer> armorSlots = new HashSet<>(Arrays.asList(armorSlotList));
    private static final int OFFHAND_SLOT = 40;

    public InventoryController(MagicController controller) {
        this.controller = controller;
    }

    public void loadProperties(ConfigurationSection properties) {
        enableItemHacks = properties.getBoolean("enable_custom_item_hacks", false);
        dropChangesPages = properties.getBoolean("drop_changes_pages", false);
        enableInventoryCasting = properties.getBoolean("allow_inventory_casting", true);
        enableInventoryDropCasting = properties.getBoolean("allow_inventory_drop_casting", false);
        enableInventorySelection = properties.getBoolean("allow_inventory_selection", true);
        openCooldown = properties.getInt("open_cooldown", 0);
        List<String> unstashableTypeKeys = properties.getStringList("unstashable_containers");
        unstashableTypes.clear();
        if (unstashableTypeKeys != null) {
            for (String typeKey : unstashableTypeKeys) {
                try {
                    InventoryType type = InventoryType.valueOf(typeKey.toUpperCase());
                    unstashableTypes.add(type);
                } catch (Exception ex) {
                    controller.getLogger().info("Unknown container type in unstashable_containers list: " + typeKey);
                }
            }
        }
    }

    @EventHandler(ignoreCancelled = true)
    public void onInventoryCreative(InventoryCreativeEvent event) {
        HumanEntity clicked = event.getWhoClicked();
        Mage mage = controller.getRegisteredMage(clicked);
        if (mage == null) return;
        if (mage.getDebugLevel() >= DEBUG_LEVEL) {
            ItemStack cursor = event.getCursor();
            ItemStack current = event.getCurrentItem();
            mage.sendDebugMessage("CREATIVE: " + event.getAction()  + " of " + event.getClick() + " cursor: "
                + (cursor == null ? "(Nothing)" : cursor.getType().name())
                + (current == null ? "(Current" : current.getType().name())
                );
        }
    }

    @EventHandler(ignoreCancelled = true)
    public void onInventoryDrag(InventoryDragEvent event) {
        HumanEntity clicked = event.getWhoClicked();
        Mage mage = controller.getMage(clicked);
        if (mage.getDebugLevel() >= DEBUG_LEVEL) {
            mage.sendDebugMessage("DRAG: " + event.getType()  + " in " + event.getInventory().getType() + " slots: " + StringUtils.join(event.getInventorySlots(), ",") +  " raw: " + StringUtils.join(event.getRawSlots(), ","));
        }
        GUIAction activeGUI = mage.getActiveGUI();
        if (activeGUI != null) {
            activeGUI.dragged(event);
            return;
        }
        // Not sure this actually happens in a way we care about, the drag event only seems to fire
        // on grindstones for inventory interaction, but just in case.
        if (event.getInventory().getType().name().equals("GRINDSTONE")) {
            ItemStack oldCursor = event.getOldCursor();
            oldCursor = oldCursor.hasItemMeta() ? CompatibilityLib.getItemUtils().makeReal(oldCursor) : oldCursor;
            if (Wand.isSpecial(oldCursor)) {
                for (int slot : event.getRawSlots()) {
                    if (slot == 1 || slot == 0) {
                        event.setCancelled(true);
                        return;
                    }
                }
            }
        }

        Wand activeWand = mage.getActiveWand();
        boolean isSpellInventory = activeWand != null && activeWand.isInventoryOpen() && activeWand.getMode() == WandMode.INVENTORY;
        if (isSpellInventory && event.getRawSlots().contains(45)) {
            event.setCancelled(true);
            return;
        }

        boolean isSkillInventory = activeWand != null && activeWand.isInventoryOpen() && activeWand.getMode() == WandMode.SKILLS;
        if (isSkillInventory) {
            // Unfortunately this event gives us a shallow copy of the item so we need to dig a little bit.
            ItemStack oldCursor = event.getOldCursor();
            oldCursor = oldCursor.hasItemMeta() ? CompatibilityLib.getItemUtils().makeReal(oldCursor) : oldCursor;
            boolean isSpell = Wand.isSpell(oldCursor);
            isSpellInventory = false;
            Set<Integer> slots = event.getRawSlots();
            int spellInventoryStart = event.getInventory().getSize();
            for (int slot : slots) {
                if (slot < spellInventoryStart) {
                    isSpellInventory = true;
                }
            }
            if (!isSpell && isSpellInventory) {
                event.setCancelled(true);
            }
            return;
        }

        // Only check if clicking an armor slot or the held item slot
        Set<Integer> slots = event.getInventorySlots();
        boolean isArmorSlot = !Collections.disjoint(slots, armorSlots);
        boolean isOffhandSlot = slots.contains(OFFHAND_SLOT);
        boolean isHeldSlot = slots.contains(clicked.getInventory().getHeldItemSlot());
        if (isArmorSlot || isOffhandSlot || isHeldSlot) {
            // This is intentionally copied from above to avoid doing it if we don't need to
            ItemStack oldCursor = event.getOldCursor();
            oldCursor = oldCursor.hasItemMeta() ? CompatibilityLib.getItemUtils().makeReal(oldCursor) : oldCursor;

            // Prevent wearing spells
            if (isArmorSlot && Wand.isSpell(oldCursor)) {
                event.setCancelled(true);
                return;
            }

            // Update armor if moving magic items around
            if (Wand.isWand(oldCursor)) {
                // Check to see if this wand is wearable in the target slot
                if (isArmorSlot) {
                    Wand wand = controller.getWand(oldCursor);
                    if (wand.hasWearable()) {
                        for (int slot : slots) {
                            if (!wand.isWearableInSlot(slot)) {
                                event.setCancelled(true);
                                return;
                            }
                        }
                    }
                }
                controller.onArmorUpdated(mage);
            }
        }

        if (!enableItemHacks) return;

        // this is a huge hack! :\
        // I apologize for any weird behavior this causes.
        // Bukkit, unfortunately, will blow away NBT data for anything you drag
        // Which will nuke a wand or spell.
        // To make matters worse, Bukkit passes a copy of the item in the event, so we can't
        // even check for metadata and only cancel the event if it involves one of our special items.
        // The best I can do is look for metadata at all, since Bukkit will retain the name and lore.

        // I have now decided to copy over the CB default handler for this, and cancel the event.
        // The only change I have made is that *real* ItemStack copies are made, instead of shallow Bukkit ones.
        ItemStack oldStack = event.getOldCursor();
        HumanEntity entity = event.getWhoClicked();
        if (oldStack != null && oldStack.hasItemMeta() && entity instanceof Player) {
            // Only do this if we're only dragging one item, since I don't
            // really know what happens or how you would drag more than one.
            Map<Integer, ItemStack> draggedSlots = event.getNewItems();
            if (draggedSlots.size() != 1) return;

            event.setCancelled(true);

            // Cancelling the event will put the item back on the cursor,
            // and skip updating the inventory.

            // So we will wait one tick and then fix this up using the original item.
            InventoryView view = event.getView();
            for (Integer dslot : draggedSlots.keySet()) {
                CompleteDragTask completeDrag = new CompleteDragTask((Player)entity, view, dslot);
                completeDrag.runTaskLater(controller.getPlugin(), 1);
            }
        }
    }

    @SuppressWarnings("deprecation")
    @EventHandler
    public void onInventoryClick(InventoryClickEvent event) {
        if (event.isCancelled()) return;
        if (!(event.getWhoClicked() instanceof Player)) return;

        Player player = (Player)event.getWhoClicked();
        final Mage mage = controller.getMage(player);
        InventoryType.SlotType slotType = event.getSlotType();
        Integer slot = event.getSlot();

        if (mage.getDebugLevel() >= DEBUG_LEVEL) {
            mage.sendDebugMessage("CLICK: " + event.getAction() + ", " + event.getClick() + " on " + slotType + " in " + event.getInventory().getType() + " slots: " + slot + ":" + event.getRawSlot());
        }

        GUIAction gui = mage.getActiveGUI();
        if (gui != null)
        {
            gui.clicked(event);
            return;
        }

        // Check for temporary items and skill items
        InventoryAction action = event.getAction();
        InventoryType inventoryType = event.getInventory().getType();
        boolean isPlayerInventory = inventoryType == InventoryType.CRAFTING || inventoryType == InventoryType.PLAYER;
        ItemStack clickedItem = event.getCurrentItem();

        // TODO: Use the enum
        boolean isSwap = event.getClick().name().equals("SWAP_OFFHAND");
        boolean isDrop = event.getClick() == ClickType.DROP || event.getClick() == ClickType.CONTROL_DROP;
        boolean isSkill = clickedItem != null && Wand.isSkill(clickedItem);

        // Check for right-click-to-use
        boolean isRightClick = action == InventoryAction.PICKUP_HALF;
        boolean isLeftClick = !isDrop && !isRightClick;
        if (isSkill && isRightClick)
        {
            mage.useSkill(clickedItem);
            player.closeInventory();
            event.setCancelled(true);
            return;
        }

        if (clickedItem != null && CompatibilityLib.getItemUtils().isTemporary(clickedItem)) {
            String message = CompatibilityLib.getItemUtils().getTemporaryMessage(clickedItem);
            if (message != null && message.length() > 1) {
                mage.sendMessage(message);
            }
            ItemStack replacement = CompatibilityLib.getItemUtils().getReplacement(clickedItem);
            event.setCurrentItem(replacement);
            event.setCancelled(true);
            mage.armorUpdated();
            return;
        }
        if (CompatibilityLib.getNBTUtils().getBoolean(clickedItem, "unmoveable", false)) {
            event.setCancelled(true);
            return;
        }

        // Look at the wand in hand
        ItemStack heldItem = event.getCursor();
        boolean heldWand = Wand.isWand(heldItem);
        boolean clickedWand = Wand.isWand(clickedItem);

        boolean isHotbar = action == InventoryAction.HOTBAR_SWAP || action == InventoryAction.HOTBAR_MOVE_AND_READD;
        // Pressing the swap hands button also looks like a hotbar_swap ... for some reason .. I guess the offhand is considered part of the hotbar?
        if (isSwap) {
            isHotbar = false;
        }

        // I'm not sure why or how this happens, but sometimes we can get a hotbar event without a slot number?
        int hotbarButton = event.getHotbarButton();
        if (isHotbar && hotbarButton < 0) return;

        // Check for putting wands in a grindstone since they will re-apply their enchantments
        boolean isGrindstone = inventoryType.name().equals("GRINDSTONE");
        if (isGrindstone && heldWand && (slot == 1 || slot == 0) && slotType == InventoryType.SlotType.CRAFTING) {
            event.setCancelled(true);
            return;
        }
        if (isGrindstone && clickedWand && action == InventoryAction.MOVE_TO_OTHER_INVENTORY && slotType != InventoryType.SlotType.CRAFTING) {
            event.setCancelled(true);
            return;
        }
        if (isGrindstone && isHotbar) {
            ItemStack item =  mage.getPlayer().getInventory().getItem(hotbarButton);
            if (Wand.isWand(item)) {
                event.setCancelled(true);
                return;
            }
        }

        // Check for wearing spells or wands
        boolean heldSpell = Wand.isSpell(heldItem);
        if (slotType == InventoryType.SlotType.ARMOR)
        {
            if (heldSpell) {
                event.setCancelled(true);
                return;
            }

            if (heldWand) {
                Wand wand = controller.getWand(heldItem);
                if (wand.hasWearable()) {
                    if (wand.isWearableInSlot(slot)) {
                        ItemStack existing = player.getInventory().getItem(slot);
                        player.getInventory().setItem(slot, heldItem);
                        event.setCursor(existing);
                        event.setCancelled(true);
                        controller.onArmorUpdated(mage);
                        return;
                    } else {
                        event.setCancelled(true);
                        return;
                    }
                }
            }

            // Notify mage that armor was updated, but wait one tick to do it
            controller.onArmorUpdated(mage);
        }

        boolean tryingToWear = action == InventoryAction.MOVE_TO_OTHER_INVENTORY && (inventoryType == InventoryType.PLAYER || inventoryType == InventoryType.CRAFTING) && (slotType == InventoryType.SlotType.CONTAINER || slotType == InventoryType.SlotType.QUICKBAR);
        if (clickedWand && tryingToWear) {
            Wand wand = null;
            if (slot == player.getInventory().getHeldItemSlot()) {
                wand = mage.getActiveWand();
            }
            if (wand == null) {
                wand = controller.getWand(clickedItem);
            }
            if (wand.tryToWear(mage)) {
                player.getInventory().setItem(slot, null);
                event.setCancelled(true);
                mage.checkWand();
                return;
            }
        }

        // Another check for wearing spells
        boolean clickedSpell = Wand.isSpell(clickedItem);
        boolean clickedBrush = Wand.isBrush(clickedItem);
        boolean clickedWearable = controller.isWearable(clickedItem);
        if (tryingToWear && clickedSpell && clickedWearable)
        {
            event.setCancelled(true);
            return;
        }

        if (isHotbar && slotType == InventoryType.SlotType.ARMOR)
        {
            ItemStack item =  mage.getPlayer().getInventory().getItem(hotbarButton);
            if (item != null && Wand.isSpell(item))
            {
                event.setCancelled(true);
                return;
            }
            controller.onArmorUpdated(mage);
        }

        Wand activeWand = mage.getActiveWand();
        boolean isWandInventoryOpen = activeWand != null && activeWand.isInventoryOpen();

        // Check to see if we just grabbed the active wand, we'll need to deactivate it so it saves
        if (activeWand != null && !isWandInventoryOpen && clickedWand && controller.isSameItem(clickedItem, activeWand.getItem())) {
            activeWand.deactivate();
            return;
        }

        // Preventing putting skills in containers
        if (isSkill && !isPlayerInventory && !isWandInventoryOpen) {
            if (!isDrop) {
                event.setCancelled(true);
            }
            return;
        }

        // Get rid of glitched spells and brushes
        if (!isWandInventoryOpen && !isSkill && (clickedBrush || clickedSpell) && !Wand.isAbsorbable(clickedItem)) {
            event.setCurrentItem(new ItemStack(Material.AIR));
            event.setCancelled(true);
            return;
        }

        boolean isFurnace = inventoryType == InventoryType.FURNACE;
        boolean isContainer = unstashableTypes.contains(inventoryType);
        boolean isEnderChest = inventoryType == InventoryType.ENDER_CHEST;
        boolean isChest = inventoryType == InventoryType.CHEST;
        boolean isContainerSlot = isChest && event.getSlot() == event.getRawSlot();
        boolean isWatchedSlot = !isChest || isContainerSlot;

        if (isWandInventoryOpen)
        {
            if (clickedSpell && clickedItem.getAmount() != 1) {
                clickedItem.setAmount(1);
            }

            // Check for swapping into the offhand, we have to prevent this in the wand inventory
            if (isSwap) {
                String spellName = Wand.getSpell(clickedItem);
                if (spellName != null && !activeWand.isManualQuickCastDisabled() && enableInventoryCasting) {
                    final Spell spell = mage.getSpell(spellName);
                    if (spell != null) {
                        // Delay this one tick because cancelling this event is going to mean the spell icon
                        // gets put back in the player inventory, and this can cause strange side effects with
                        // spells levelling up, or spells with GUIs or other inventories.
                        final Wand castWand = activeWand;
                        controller.getPlugin().getServer().getScheduler().runTaskLater(controller.getPlugin(),
                                new WandCastTask(castWand, spell), 1);
                    }
                }
                event.setCancelled(true);
            }

            // Check for page/hotbar cycling by clicking the active wand
            if (clickedWand) {
                event.setCancelled(true);
                if ((dropChangesPages && isDrop) || isLeftClick) {
                    activeWand.cycleInventory();
                } else {
                    activeWand.cycleHotbar(1);
                }
                return;
            }

            // Prevent certain things in inventory and chest mode, mainly to avoid
            // Players getting spell items out
            if (activeWand.getMode() == WandMode.INVENTORY) {
                // Don't allow the offhand slot to be messed with while the spell inventory is open
                if (event.getRawSlot() == 45)
                {
                    event.setCancelled(true);
                    return;
                }

                // Don't allow putting spells in a crafting slot
                if (slotType == InventoryType.SlotType.CRAFTING && heldSpell) {
                    event.setCancelled(true);
                    return;
                }

                // So many ways to try and move the wand around, that we have to watch for!
                if (isHotbar && Wand.isWand(player.getInventory().getItem(event.getHotbarButton()))) {
                    event.setCancelled(true);
                    return;
                }

                // Safety check for something that ought not to be possible
                // but perhaps happens with lag?
                if (Wand.isWand(event.getCursor())) {
                    activeWand.closeInventory();
                    event.setCursor(null);
                    event.setCancelled(true);
                    return;
                }
            } else {
                // Prevent moving items into the skill inventory via the hotbar buttons
                if (isHotbar && isWatchedSlot && !CompatibilityLib.getItemUtils().isEmpty(player.getInventory().getItem(event.getHotbarButton()))) {
                    event.setCancelled(true);
                    return;
                }
            }
        } else if (activeWand != null) {
            // Check for changes that could have been made to the active wand
            int activeSlot = player.getInventory().getHeldItemSlot();
            if (event.getSlot() == activeSlot || (isHotbar && event.getHotbarButton() == activeSlot))
            {
                mage.checkWand();
                activeWand = mage.getActiveWand();
            }
        }

        // Don't allow smelting wands
        if (isFurnace && clickedWand) {
            event.setCancelled(true);
            return;
        }

        if (isFurnace && isHotbar) {
            ItemStack destinationItem = player.getInventory().getItem(event.getHotbarButton());
            if (Wand.isWand(destinationItem)) {
                event.setCancelled(true);
                return;
            }
        }

        if (isHotbar) {
            ItemStack destinationItem = player.getInventory().getItem(event.getHotbarButton());
            if (CompatibilityLib.getNBTUtils().getBoolean(destinationItem, "unmoveable", false)) {
                event.setCancelled(true);
                return;
            }
            if (isContainer && CompatibilityLib.getNBTUtils().getBoolean(destinationItem, "unstashable", false) && !player.hasPermission("magic.wand.override_stash")) {
                event.setCancelled(true);
                return;
            }
        }

        // Check for unstashable wands
        if (isContainer && !isContainerSlot && !player.hasPermission("magic.wand.override_stash")) {
            if (CompatibilityLib.getNBTUtils().getBoolean(clickedItem, "unstashable", false)) {
                event.setCancelled(true);
                return;
            }
        }

        // Check for taking bound wands out of chests
        if (isContainer && isWatchedSlot && Wand.isBound(clickedItem)) {
            Wand testWand = controller.getWand(clickedItem);
            if (!testWand.canUse(player)) {
                event.setCancelled(true);
                return;
            }
        }

        // Check for armor changing
        if (tryingToWear && clickedItem != null)
        {
            if (clickedWearable) {
                controller.onArmorUpdated(mage);
            }
        }

        // Check for dropping items out of a wand's inventory
        // or dropping undroppable wands
        if (isDrop) {
            String dropAction = CompatibilityLib.getNBTUtils().getString(clickedItem, "drop");
            if (dropAction != null && !dropAction.isEmpty()) {
                if (dropAction.equals("destroy")) {
                    event.setCurrentItem(new ItemStack(Material.AIR));
                    mage.checkWand();
                    mage.armorUpdated();
                } else {
                    controller.info("Unknown wand drop action: " + dropAction, 5);
                }
                event.setCancelled(true);
                return;
            }
            if (CompatibilityLib.getNBTUtils().getBoolean(clickedItem, "undroppable", false)) {
                event.setCancelled(true);
                if (activeWand != null) {
                    if (activeWand.getHotbarCount() > 1) {
                        activeWand.cycleHotbar(1);
                    } else {
                        activeWand.closeInventory();
                    }
                }
                return;
            }
            if (isWandInventoryOpen) {
                ItemStack droppedItem = clickedItem;

                if (!Wand.isSpell(droppedItem)) {
                    mage.giveItem(droppedItem);
                    event.setCurrentItem(null);
                    event.setCancelled(true);
                    return;
                }

                // This is a hack to deal with spells on cooldown disappearing,
                // Since the event handler doesn't match the zero-count itemstacks
                int heldSlot = player.getInventory().getHeldItemSlot();
                WandInventory hotbar = activeWand.getHotbar();
                if (hotbar != null && slot >= 0 && slot <= hotbar.getSize() && slot != heldSlot && activeWand.getMode() == WandMode.INVENTORY)
                {
                    if (slot > heldSlot) slot--;
                    if (slot < hotbar.getSize())
                    {
                        droppedItem = hotbar.getItem(slot);
                    }
                    else
                    {
                        slot = null;
                    }
                }
                else
                {
                    slot = null;
                }

                if (!controller.isSpellDroppingEnabled()) {
                    player.closeInventory();
                    String spellName = Wand.getSpell(droppedItem);
                    if (spellName != null && !activeWand.isManualQuickCastDisabled() && enableInventoryDropCasting) {
                        final Spell spell = mage.getSpell(spellName);
                        if (spell != null) {
                            // Delay this one tick because cancelling this event is going to mean the spell icon
                            // gets put back in the player inventory, and this can cause strange side effects with
                            // spells levelling up, or spells with GUIs or other inventories.
                            final Wand castWand = activeWand;
                            // This will also fire an arm swing animation event which we want to ignore
                            // Sadly this didn't work because the animation event arrives first
                            mage.checkLastClick(0);
                            controller.getPlugin().getServer().getScheduler().runTaskLater(controller.getPlugin(),
                                new WandCastTask(castWand, spell), 1);
                        }
                    }
                    event.setCancelled(true);

                    // This is needed to avoid spells on cooldown disappearing from the hotbar
                    if (hotbar != null && slot != null && mage.getActiveGUI() == null)
                    {
                        player.getInventory().setItem(event.getSlot(), droppedItem);
                        CompatibilityLib.getDeprecatedUtils().updateInventory(player);
                    }

                    return;
                }
                ItemStack newDrop = controller.removeItemFromWand(activeWand, droppedItem);

                if (newDrop != null) {
                    Location location = player.getLocation();
                    Item item = location.getWorld().dropItem(location, newDrop);
                    SafetyUtils.setVelocity(item, location.getDirection().normalize());
                } else {
                    event.setCancelled(true);
                }
            }
            return;
        }

        // Check for wand cycling with active inventory
        if (activeWand != null) {
            WandMode wandMode = activeWand.getMode();
            boolean isChestInventory = wandMode == WandMode.CHEST || wandMode == WandMode.SKILLS;
            if ((wandMode == WandMode.INVENTORY && isPlayerInventory)
                    || (isChestInventory && inventoryType == InventoryType.CHEST)) {
                if (activeWand.isInventoryOpen()) {
                    if (event.getAction() == InventoryAction.NOTHING) {
                        int direction = event.getClick() == ClickType.LEFT ? 1 : -1;
                        activeWand.cycleInventory(direction);
                        event.setCancelled(true);
                        return;
                    }

                    if (event.getSlotType() == InventoryType.SlotType.ARMOR) {
                        event.setCancelled(true);
                        return;
                    }

                    // Chest mode falls back to selection from here.
                    boolean isInventoryQuickSelect = isRightClick && wandMode == WandMode.INVENTORY && enableInventorySelection;
                    if (isInventoryQuickSelect || wandMode == WandMode.CHEST) {
                        // Closing the inventory inside this event will make it look like we're dropping
                        // the item that was clicked on, which (due to some really @^%#4 stupid decision on Mojang's part)
                        // will send left-click animate packets and cause a spell cast.
                        // So delay the close one tick.
                        Plugin plugin = controller.getPlugin();
                        plugin.getServer().getScheduler().runTaskLater(plugin, new ActivateIconTask(mage, activeWand, clickedItem), 1);
                        event.setCancelled(true);
                    }

                    // Prevent putting any non-skill item back into a skill inventory
                    if (wandMode == WandMode.SKILLS && isWatchedSlot
                        && !CompatibilityLib.getItemUtils().isEmpty(heldItem) && !Wand.isSkill(heldItem)) {
                        event.setCancelled(true);
                    }
                }
            }
        }

        // Check for dropping upgrades onto a wand
        if (!isWandInventoryOpen && clickedWand && !isContainer && !isEnderChest
            && (Wand.isUpgrade(heldItem) || Wand.isSpell(heldItem) || Wand.isSP(heldItem) || Wand.isBrush(heldItem))) {
            if (activeWand != null) {
                activeWand.deactivate();
            }
            Wand wand = controller.createWand(clickedItem);
            wand.setMage(mage);
            CurrencyAmount currency = CompatibilityLib.getInventoryUtils().getCurrencyAmount(heldItem);
            if (wand.addItem(heldItem)) {
                event.setCancelled(true);
                // Currency items will always absorb the full stack
                if (heldItem.getAmount() > 1 && currency == null) {
                    heldItem.setAmount(heldItem.getAmount() - 1);
                    event.setCursor(heldItem);
                } else {
                    event.setCursor(null);
                }
                event.getClickedInventory().setItem(event.getSlot(), wand.getItem());
            }
            if (activeWand != null) {
                mage.checkWand();
            }
        }
    }

    @EventHandler
    public void onInventoryClosed(InventoryCloseEvent event) {
        if (!(event.getPlayer() instanceof Player)) return;

        // Update the active wand, it may have changed around
        Player player = (Player)event.getPlayer();
        Mage mage = controller.getRegisteredMage(player);
        if (mage == null) return;

        Wand previousWand = mage.getActiveWand();

        // Prevent spells getting smuggled out via crafting slots
        Inventory inventory = event.getInventory();
        if (inventory instanceof CraftingInventory && previousWand != null && previousWand.wasInventoryOpen()) {
            CraftingInventory craftingInventory = (CraftingInventory)inventory;
            ItemStack[] matrix = craftingInventory.getMatrix();
            for (int i = 0; i < matrix.length; i++) {
                matrix[i] = new ItemStack(Material.AIR);
            }
            craftingInventory.setMatrix(matrix);
        }

        GUIAction gui = mage.getActiveGUI();
        if (gui != null)
        {
            mage.onGUIDeactivate();
        }

        // Save the inventory state of the current wand if its spell inventory is open
        // This is just to make sure we don't lose changes made to the inventory
        if (previousWand != null && previousWand.isInventoryOpen()) {
            if (previousWand.getMode() == WandMode.INVENTORY) {
                previousWand.saveInventory();
                // Update hotbar names
                previousWand.updateHotbar();
            } else if (previousWand.getMode() == WandMode.CHEST || previousWand.getMode() == WandMode.SKILLS) {
                // Close and save an open chest mode inventory
                previousWand.closeInventory();
            }
        } else {
            if (previousWand != null && !previousWand.wasInventoryOpen() && previousWand.isAutoAbsorb()) {
                previousWand.checkInventoryForUpgrades();
            }
            mage.checkWand();
        }
    }

    @EventHandler
    public void onInventoryOpen(InventoryOpenEvent event) {
        Player player = (Player)event.getPlayer();
        Mage mage = controller.getRegisteredMage(player);
        if (mage == null) return;

        mage.setOpenCooldown(openCooldown);

        Wand wand = mage.getActiveWand();
        GUIAction gui = mage.getActiveGUI();
        if (wand != null && gui == null) {
            // NOTE: The type will never actually be CRAFTING, at least for now.
            // But we can hope for server-side player inventory open notification one day, right?
            // Anyway, check for opening another inventory and close the wand.
            if (event.getView().getType() != InventoryType.CRAFTING) {
                if (wand.getMode() == WandMode.INVENTORY || !wand.isInventoryOpen()) {
                    wand.deactivate(false);
                }
            }
        }
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
in Ferrer, Sivichai & Shearer, Mycologia 99(3): 458 (2007)

#### Original name
Megalohypha aqua-dulces A. Ferrer & Shearer, 2007

### Remarks
null


text:
```
docker run -i -t -p 8888:8888 continuumio/anaconda /bin/bash -c "/opt/conda/bin/conda install jupyter -y --quiet && mkdir /opt/notebooks && /opt/conda/bin/jupyter notebook --notebook-dir=/opt/notebooks --ip='*' --port=8888 --no-browser"
```

# 线性回归项目

欢迎来到线性回归项目,线性代数是很多机器学习算法的基础,在这个项目中,你将不借助任何库,用你之前所学来解决一个线性回归问题。

# 项目内容
所有需要完成的任务都在 `linear_regression_project.ipynb` 中,其中包括编程题和证明题。

**若项目中的题目有困难没完成也没关系,我们鼓励你带着问题提交项目,评审会给予你诸多帮助。**

# 单元测试
项目已经部署了自动化测试,你能在每个需要你完成的函数下面看到形如以下测试代码:
`%run -i -e test.py LinearRegressionTestCase.test_...`
Ctrl + Enter 运行即可。

如果你的实现有问题,会有断言错误`AssertionError`被抛出。
请重新检查你的实现,并且修正bug,直到通过测试为止。

以下是一些带有特定反馈的断言错误说明:

- AssertionError: Expected shape(M,N), but got shape(C,D)."
  + 返回的计算结果的形状不正确
- AssertionError: Matrix A shouldn't be modified.
  + 你在实现augmentMatrix时修改了矩阵A
- AssertionError: Matrix A is singular.
  + 你的gj_Solve实现在矩阵A是奇异矩阵时没有返回None
- AssertionError: Matrix A is not singular.
  + 你的gj_Solve实现会在矩阵A不是奇异矩阵时返回None
- AssertionError: Bad result.
  + 你的gj_Solve返回了不正确的计算结果

# 项目提交
请在提交前确认你的项目已经满足所有[评审标准](https://review.udacity.com/#!/rubrics/871/view), 项目评审人会根据这份标准来给你相应的审阅。

你需要提交以下4个文件, 请注意每个文件的文件名和文件格式。

1. `linear_regression_project.ipynb`: 写有你代码及答案的  ipynb 文件

2. `linear_regression_project.html`: 由 Jupyter notebook 导出的 html 文件

3. `linear_regression_project.py`: 由 Jupyter notebook 导出的 python 文件

4. `proof.pdf`: 写有你的证明的 pdf 文件 (如果你在 ipython notebook中使用 LATEX 完成证明,则不需要提交此文件。)

5. 请不要提交其他任何文件。

你可以使用 Github 或上传 zip 压缩文档的方式提交项目。如果使用 Github 请将所有提交的文件放在你提交的repo中。 如果上传压缩文档,请将所有提交的文件放在压缩文档中,并命名为 `submit.zip` 后提交。

---

# Linear Regression Project(in developing, not validable yet)

Welcome to linear regression project.  Linear regression is the basic of many machine learning algorithms. In this project, you will imply what you learn to solve a linear regression problem, without using any external libraries.

# What to do
All tasks are listed in  `linear_regression_project.ipynb`,including coding and proving tasks.

**You're encouragd to submit problem even if you haven't finished all tasks. You should submit with spefici questions and explain what you have tried and why it doesn't work. Reviewers will guide you accordingly.**

# Unit test
You can (and should) use unit tests to ensure all your implementations meet requirements. You can find the following code after every coding task.

`%run -i -e test.py LinearRegressionTestCase.test_...`

If there is an error in your implementation, the `AssertionError` will be thrown. Please modify your code accordingly, until you've passed all unit tests.

The following are some examples of the assersion error.

- AssertionError: Matrix A shouldn't be modified
  + Your augmentMatrix modifies matrix A.

- AssertionError: Matrix A is singular
  + Your gj_Solve doesn't return None when A is singular.
- AssertionError: Matrix A is not singular
  + Your gj_Solve returns None when A is not singular.
- AssertionError: x have to be a two-dimensional Python list
  + Your gj_Solve returns with incorrect data structure. X should be a two a list of lists.

- AssertionError: Regression result isn't good enough
  + Your gj_Solve has too much error.

# Project submission
Before submission, please ensure that your project meets all the requirements in this [rubric](https://review.udacity.com/#!/rubrics/854/view). Reviewer will give reviews according to this rubric.

You should submit the follow four files. Please pay attention to the file names and file types.

1. `linear_regression_project.ipynb`: the ipynb file with your code and answers.

3. `linear_regression_project.html`: the html file exported by Jupyter notebook.

3. `linear_regression_project.py`: the python file exported by Jupyter notebook.

2. `proof.pdf`: the pdf file with your proof. (If you use LATEX in ipython notebook to write the proof, you don't need to submit this file. )

5. Please DO NOT submit any other files.

You can use Github or upload zip file to submit the project. If you use Github, please include all your files in the repo. If you submit with zip file, please compress all your files in `submit.zip` and then upload.


text:
"""
Orientation.
The convention for vehicle axes is
z Vertical axis, vector points towards ground
x Axis towards the front of the vehicle, vector points in normal direction of travel
y Vector points left from pilot's point of view (I think)
Assuming the sensor is aligned such that it has one axis Vertical and another forward, the
transpose function enables axes to be swapped to achieve the conventional orientation.
The invert() function enables the sign of each axis to be corrected.

Note that it is the responsibilty of the driver to esnure that accelerometer, gyro and
magnetometer share the same coordinate system. In particular the MPU-9150's magnetometer is
rotated with respect to the other two sensors. The MicroPython driver transposes the magnetometer
axes to conform with those of the other two sensors.
"""

def invert(axes, vectors):  # Invert one or more axes on a list of vectors
    res = []
    for vector in vectors:
        res.append(tuple(map(lambda x, y: -y if x else y, axes, vector)))
    return res

def transpose(idx, vectors):# transpose axes in a list of vectors
    res = []                # e.g. swap x and y transpose((1, 0, 2), (accel, gyro, mag))
    for vector in vectors:
        res.append([vector[axis] for axis in idx])
    return res

# t: tuple of vectors to transpose (0, 1, 2) indicates do nothing
# i: tuple of booleans indicating any vectors to be inverted.
# folowed by accel, gyro and magnetometer vectors (x, y, z).
# Note inversion operates on conventional vectors i.e. after transposition.
# e.g. (False, False, True) invert vertical axis.
# Returns a list of vectors. Typical invocation:
# fuse.update(*orientate(T, I, imu.get_accel(), imu.get_gyro(), imu.get_mag()))

def orientate(t, i, *vecs):
    return invert(i, transpose(t, vecs))


text:
@interface recordingListView : UIViewController<UITableViewDataSource,UITableViewDelegate>

{
    UIAlertView *deletealert;
    UIAlertView *alert;
    bool isPlaying;
    IBOutlet UILabel *lbl_myplaylist;
    UIActivityIndicatorView *mySpinner;
    NSString *song_id;
    NSMutableArray *arrAddPlaylistName;
    NSString *song_idForPlaylist;
    NSMutableArray *arr_playlistAllsongs;
    NSMutableArray *arrDownloadAllsongs;
    NSMutableArray *arrfavoritelist;
    bool ischecked;

}
//==== player bar=====
@property (strong, nonatomic) IBOutlet UIButton *btn_favorite;
@property (strong, nonatomic) IBOutlet UIButton *btn_playlist;
@property (strong, nonatomic) IBOutlet UIButton *btn_download;
@property (strong, nonatomic) IBOutlet UIButton *btn_playpause;

@property(weak,nonatomic) IBOutlet UIView *viewPlayerBar;
@property(weak,nonatomic) IBOutlet UILabel *lblPlayerBarTitle;

-(IBAction)btnPlayerBarPressed:(id)sender;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *bottom_constraint_free;

//===end===

@property (strong, nonatomic) IBOutlet NSLayoutConstraint *search_width_layout;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *search_height_layout;
@property (strong, nonatomic) IBOutlet UIButton *btn_search;
@property(weak,nonatomic) IBOutlet UITableView *tblDetail;

@property(strong,nonatomic) NSMutableArray *arrSectionDetail;
@property(strong,nonatomic) NSString *sectionName;
@property (strong, nonatomic) UIWindow *window;
@property (nonatomic) CGFloat lastContentOffset;
@property(strong,nonatomic) NSString *playlist_id;

@property(weak,nonatomic) IBOutlet UIButton *btnBackNavigation;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *menuWconstraint;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *menuHconstraint;
-(IBAction)btnBackPressed:(id)sender;
@property(weak,nonatomic) IBOutlet NSLayoutConstraint *headerHeightConstraint;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *Tbl_Botm_constraint;
@end


text:
from __future__ import unicode_literals

from django.apps import AppConfig

class RkmusicConfig(AppConfig):
    name = 'rkmusic'


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

<recipeml version="0.5">
  <recipe>
    <head>
      <title>Barbequed Chicken</title>
      <categories>
        <cat>Main</cat></categories>
      <yield>1</yield></head>
    <ingredients>
      <ing>
        <amt>
          <qty>1</qty>
          <unit/></amt>
        <item>Split fryer chicken</item></ing>
      <ing>
        <amt>
          <qty/>
          <unit/></amt>
        <item>White vinegar</item></ing>
      <ing>
        <amt>
          <qty>5</qty>
          <unit>teaspoons</unit></amt>
        <item>Salt</item></ing>
      <ing>
        <amt>
          <qty>2</qty>
          <unit>teaspoons</unit></amt>
        <item>Dry mustard</item></ing>
      <ing>
        <amt>
          <qty>2</qty>
          <unit>teaspoons</unit></amt>
        <item>Coarse grind garlic powder</item></ing>
      <ing>
        <amt>
          <qty>2</qty>
          <unit>teaspoons</unit></amt>
        <item>Cracked black pepper</item></ing>
      <ing>
        <amt>
          <qty>2</qty>
          <unit>teaspoons</unit></amt>
        <item>MSG</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit>teaspoon</unit></amt>
        <item>Crushed thyme</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit>teaspoon</unit></amt>
        <item>Celery salt</item></ing>
      <ing>
        <amt>
          <qty>1/2</qty>
          <unit>teaspoons</unit></amt>
        <item>Dried ground lemon peel</item></ing></ingredients>
    <directions>
      <step>  I let the chicken stand in the fridge for a good hour before cooking on the
  Weber with a combination of charcoal and hickory (plain tap water in the
  drip pan.) I personally thought it was a tad bit on the salty side, but the
  family said it was fine. Must have been me. Next time I might back off some
  on the plain salt and the garlic powder and make up the difference with
  Lawry's (Coarse Ground with Parsley) Garlic Salt, which I happen to like a
  lot.

  NOTES : The weather finally warmed up around here (Eastern Nebraska) long
  enough to allow for barbequing some chicken this past Saturday. I let a
  split fryer sit in white vinegar for twenty minutes or so, turning a few
  times. Next I coated the halves with olive oil. Then I sprinkled on this
  rub (makes plenty for one split fryer):
  Recipe by: Craig Edmundson

  Posted to recipelu-digest by molony <molony@scsn.net> on Feb 04, 1998

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


text:
package main

import (
	"flag"

	"github.com/justsocialapps/holmes/analytics"
)

var (
	protocol     string
	host         string
	proxyPort    string
	proxyPath    string
	listenHost   string
	listenPort   string
	kafkaHost    string
	logfileName  string
	printVersion bool
	anonymizeIP  bool
)

func init() {
	flag.StringVar(&protocol, "protocol", "https", "The protocol used to serve Holmes resources ('http' or 'https')")
	flag.StringVar(&host, "host", "localhost", "The host name used to reach Holmes")
	flag.StringVar(&proxyPort, "proxyPort", "3001", "The TCP port for reaching Holmes if Holmes is operated behind a reverse proxy.")
	flag.StringVar(&proxyPath, "proxyPath", "", "The base path for reaching Holmes if Holmes is operated behind a reverse proxy.")
	flag.StringVar(&listenHost, "listenHost", "", "The host Holmes listens on.")
	flag.StringVar(&listenPort, "listenPort", "3001", "The TCP port that Holmes listens on")
	flag.StringVar(&kafkaHost, "kafkaHost", "localhost:9092", "The Kafka host to consume messages from")
	flag.StringVar(&logfileName, "logfile", "", "The file to log messages to")
	flag.BoolVar(&printVersion, "version", false, "Print Holmes version and exit")
	flag.BoolVar(&anonymizeIP, "anonIP", false, "Sets the last octet (IPv4) or the last 80 bits (IPv6) of the client's IP address to 0 in the tracking object before submitting it to Kafka.")

	flag.Parse()

	var baseURL string

	//only prepend the protocol when the user provided one
	if protocol != "" {
		baseURL = protocol + "://"
	}

	//only prepend the host when the user provided one
	if host != "" {
		baseURL = baseURL + host
	}

	//we only need to specify the port number when it's different than the
	//standard 80/443.
	if protocol != "" && !(protocol == "https" && proxyPort == "443") && !(protocol == "http" && proxyPort == "80") {
		baseURL = baseURL + ":" + proxyPort
	}

	baseURL = baseURL + proxyPath

	analytics.PrepareAnalytics(baseURL)
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Accidis.WebServices.Models;

namespace Accidis.Sjoslaget.WebService.Models
{
	public sealed class BookingSource
	{
		public string Reference { get; set; }
		public string FirstName { get; set; }
		public string LastName { get; set; }
		public string Email { get; set; }
		public string PhoneNo { get; set; }
		public string Lunch { get; set; }
		public int Discount { get; set; }
		public bool IsLocked { get; set; }
		public string InternalNotes { get; set; }
		public string SubCruise { get; set; }
		public List<Cabin> Cabins { get; set; }
		public List<Product> Products { get; set; }
		public PaymentSummary Payment { get; set; }

		public static BookingSource FromBooking(Booking booking, BookingCabinWithPax[] cabins, BookingProduct[] products, PaymentSummary payment)
		{
			return new BookingSource
			{
				Reference = booking.Reference,
				FirstName = booking.FirstName,
				LastName = booking.LastName,
				Email = booking.Email,
				PhoneNo = booking.PhoneNo,
				Lunch = booking.Lunch,
				Discount = booking.Discount,
				InternalNotes = booking.InternalNotes,
				SubCruise = booking.SubCruise.ToString(),
				IsLocked = booking.IsLocked,
				Cabins = cabins.Select(c => new Cabin
				{
					TypeId = c.CabinTypeId,
					Pax = c.Pax.Select(p => new Pax
					{
						Group = p.Group,
						FirstName = p.FirstName,
						LastName = p.LastName,
						Gender = p.Gender.ToString(),
						Dob = p.Dob.ToString(),
						Nationality = p.Nationality.ToUpperInvariant(),
						Years = p.Years
					}).ToList()
				}).ToList(),
				Products = products.Select(p => new Product
				{
					TypeId = p.ProductTypeId,
					Quantity = p.Quantity
				}).ToList(),
				Payment = payment
			};
		}

		public static void Validate(BookingSource bookingSource)
		{
			if(null == bookingSource)
				throw new ArgumentNullException(nameof(bookingSource), "Booking data not present.");

			bookingSource.ValidateDetails();
			bookingSource.ValidateCabins();
			bookingSource.ValidateProducts();
		}

		public static void ValidateCabins(BookingSource bookingSource)
		{
			if(null == bookingSource)
				throw new ArgumentNullException(nameof(bookingSource), "Booking data not present.");
			if(null == bookingSource.SubCruise)
				throw new BookingException("Sub-cruise must be set.");

			bookingSource.ValidateCabins();
		}

		public void ValidateDetails()
		{
			if(string.IsNullOrWhiteSpace(FirstName))
				throw new BookingException("First name must be set.");
			if(string.IsNullOrWhiteSpace(LastName))
				throw new BookingException("Last name must be set.");
			if(string.IsNullOrWhiteSpace(Email))
				throw new BookingException("E-mail must be set.");
			if(string.IsNullOrWhiteSpace(PhoneNo))
				throw new BookingException("Phone number must be set.");
			if(string.IsNullOrWhiteSpace(Lunch))
				throw new BookingException("Lunch preference must be set.");
		}

		void ValidateCabins()
		{
			if(null == Cabins || !Cabins.Any())
				throw new BookingException("List of cabins must not be empty.");

			bool isFirstCabin = true;
			string defaultGroup = string.Empty;
			foreach(Cabin cabin in Cabins)
			{
				cabin.Validate(isFirstCabin, ref defaultGroup);
				isFirstCabin = false;
			}
		}

		void ValidateProducts()
		{
			if(null == Products || !Products.Any())
				return; // No products on booking is just peachy

			foreach(Product product in Products)
				product.Validate();
		}

		public sealed class Cabin
		{
			public Guid TypeId { get; set; }
			public List<Pax> Pax { get; set; }

			public void Validate(bool isFirstCabin, ref string defaultGroup)
			{
				if(Guid.Empty.Equals(TypeId))
					throw new BookingException("Cabin type must be specified.");
				if(null == Pax || !Pax.Any())
					throw new BookingException("List of pax must not be empty.");

				BookingSource.Pax.ValidateAndSetDefaults(Pax, isFirstCabin, ref defaultGroup);
			}
		}

		public sealed class Pax
		{
			public string Group { get; set; }
			public string FirstName { get; set; }
			public string LastName { get; set; }
			public string Gender { get; set; }
			public string Dob { get; set; }
			public string Nationality { get; set; }
			public int Years { get; set; }

			internal static void ValidateAndSetDefaults(List<Pax> paxList, bool isFirstCabin, ref string defaultGroup)
			{
				bool isFirstPax = isFirstCabin;
				foreach(Pax pax in paxList)
				{
					if(isFirstPax)
					{
						if(string.IsNullOrWhiteSpace(pax.Group))
							throw new BookingException("Group must be set for the first pax.");
						defaultGroup = pax.Group;
					}
					else if(string.IsNullOrWhiteSpace(pax.Group))
						pax.Group = defaultGroup;

					isFirstPax = false;

					if(string.IsNullOrWhiteSpace(pax.FirstName))
						throw new BookingException("First name must be set.");
					if(string.IsNullOrWhiteSpace(pax.LastName))
						throw new BookingException("Last name must be set.");
					if(!DateOfBirth.IsValid(pax.Dob))
						throw new BookingException("Date of birth must be set and a valid date.");
					if(!IsoNationality.TryValidateOrSetDefault(pax.Nationality, out var nationality))
						throw new BookingException("Nationality must be a 2-letter ISO country code.");
					pax.Nationality = nationality;

					if(pax.Years < 0)
						throw new BookingException("Years must be greater than or equal to zero.");
				}
			}
		}

		public sealed class Product
		{
			public Guid TypeId { get; set; }
			public int Quantity { get; set; }

			public void Validate()
			{
				if(Guid.Empty.Equals(TypeId))
					throw new BookingException("Product type must be specified.");
				if(Quantity <= 0)
					throw new BookingException("Product quantity must be positive.");
			}
		}
	}
}


text:
package io.safedrive.payments.paymill.resources;

import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Date;
import lombok.Data;

@Data
public abstract class Resource {

    @JsonProperty("id")
    private String id;
    @JsonProperty("created_at")
    private Date createdAt;
    @JsonProperty("updated_at")
    private Date updatedAt;
    @JsonProperty("canceled_at")
    private Date canceled_at;
    @JsonProperty("app_id")
    private String applicationId;
}


text:
Press and hold on the map to create a reminder.  An account can be created to save your reminders in the cloud.

4-day individual project.  certainly a work in progress.


text:
<?php

namespace GingerPayments\Payment\Order;

use GingerPayments\Payment\Common\ChoiceBasedValueObject;

final class Status
{
    use ChoiceBasedValueObject;

    /**
     * Possible order statuses
     */
    const BRAND_NEW = 'new';
    const PROCESSING = 'processing';
    const ERROR = 'error';
    const COMPLETED = 'completed';
    const CANCELLED = 'cancelled';
    const EXPIRED = 'expired';
    const SEE_TRANSACTIONS = 'see-transactions';
    const DECLINED = 'declined';

    /**
     * @return array
     */
    public function possibleValues()
    {
        return [
            self::BRAND_NEW,
            self::PROCESSING,
            self::ERROR,
            self::COMPLETED,
            self::CANCELLED,
            self::EXPIRED,
            self::SEE_TRANSACTIONS,
            self::DECLINED
        ];
    }

    /**
     * @return bool
     */
    public function isNew()
    {
        return $this->value === self::BRAND_NEW;
    }

    /**
     * @return bool
     */
    public function isProcessing()
    {
        return $this->value === self::PROCESSING;
    }

    /**
     * @return bool
     */
    public function isError()
    {
        return $this->value === self::ERROR;
    }

    /**
     * @return bool
     */
    public function isCompleted()
    {
        return $this->value === self::COMPLETED;
    }

    /**
     * @return bool
     */
    public function isCancelled()
    {
        return $this->value === self::CANCELLED;
    }

    /**
     * @return bool
     */
    public function isExpired()
    {
        return $this->value === self::EXPIRED;
    }

    /**
     * @return bool
     */
    public function isSeeTransactions()
    {
        return $this->value === self::SEE_TRANSACTIONS;
    }

    /**
     * @return bool
     */
    public function isDeclined()
    {
        return $this->value === self::DECLINED;
    }
}


text:
import 'plugins/kbn_doc_views/views/table';
import 'plugins/kbn_doc_views/views/json';


text:
<?xml version="1.0" encoding="UTF-8"?>
<metadata>
  <groupId>com.squareup.spoon</groupId>
  <artifactId>spoon-sample-tests</artifactId>
  <versioning>
    <versions>
      <version>1.1.2.9-OG-SNAPSHOT</version>
    </versions>
    <lastUpdated>20141205232744</lastUpdated>
  </versioning>
</metadata>


text:
package webhook

import (
	"crypto/tls"
	"crypto/x509"
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"
	"testing"

	"k8s.io/api/admission/v1alpha1"
	registrationv1alpha1 "k8s.io/api/admissionregistration/v1alpha1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apiserver/pkg/admission"
	"k8s.io/apiserver/pkg/authentication/user"
	"k8s.io/kubernetes/pkg/api"

	_ "k8s.io/kubernetes/pkg/apis/admission/install"
)

type fakeHookSource struct {
	hooks []registrationv1alpha1.ExternalAdmissionHook
	err   error
}

func (f *fakeHookSource) ExternalAdmissionHooks() (*registrationv1alpha1.ExternalAdmissionHookConfiguration, error) {
	if f.err != nil {
		return nil, f.err
	}
	return &registrationv1alpha1.ExternalAdmissionHookConfiguration{ExternalAdmissionHooks: f.hooks}, nil
}

func (f *fakeHookSource) Run(stopCh <-chan struct{}) {}

type fakeServiceResolver struct {
	base url.URL
}

func (f fakeServiceResolver) ResolveEndpoint(namespace, name string) (*url.URL, error) {
	if namespace == "failResolve" {
		return nil, fmt.Errorf("couldn't resolve service location")
	}
	u := f.base
	u.Path = name
	return &u, nil
}

// TestAdmit tests that GenericAdmissionWebhook#Admit works as expected
func TestAdmit(t *testing.T) {
	// Create the test webhook server
	sCert, err := tls.X509KeyPair(serverCert, serverKey)
	if err != nil {
		t.Fatal(err)
	}
	rootCAs := x509.NewCertPool()
	rootCAs.AppendCertsFromPEM(caCert)
	testServer := httptest.NewUnstartedServer(http.HandlerFunc(webhookHandler))
	testServer.TLS = &tls.Config{
		Certificates: []tls.Certificate{sCert},
		ClientCAs:    rootCAs,
		ClientAuth:   tls.RequireAndVerifyClientCert,
	}
	testServer.StartTLS()
	defer testServer.Close()
	serverURL, err := url.ParseRequestURI(testServer.URL)
	if err != nil {
		t.Fatalf("this should never happen? %v", err)
	}
	wh, err := NewGenericAdmissionWebhook()
	if err != nil {
		t.Fatal(err)
	}
	wh.serviceResolver = fakeServiceResolver{*serverURL}
	wh.clientCert = clientCert
	wh.clientKey = clientKey

	// Set up a test object for the call
	kind := api.Kind("Pod").WithVersion("v1")
	name := "my-pod"
	namespace := "webhook-test"
	object := api.Pod{
		ObjectMeta: metav1.ObjectMeta{
			Labels: map[string]string{
				"pod.name": name,
			},
			Name:      name,
			Namespace: namespace,
		},
		TypeMeta: metav1.TypeMeta{
			APIVersion: "v1",
			Kind:       "Pod",
		},
	}
	oldObject := api.Pod{
		ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: namespace},
	}
	operation := admission.Update
	resource := api.Resource("pods").WithVersion("v1")
	subResource := ""
	userInfo := user.DefaultInfo{
		Name: "webhook-test",
		UID:  "webhook-test",
	}

	type test struct {
		hookSource    fakeHookSource
		expectAllow   bool
		errorContains string
	}
	ccfg := func(result string) registrationv1alpha1.AdmissionHookClientConfig {
		return registrationv1alpha1.AdmissionHookClientConfig{
			Service: registrationv1alpha1.ServiceReference{
				Name: result,
			},
			CABundle: caCert,
		}
	}
	matchEverythingRules := []registrationv1alpha1.RuleWithOperations{{
		Operations: []registrationv1alpha1.OperationType{registrationv1alpha1.OperationAll},
		Rule: registrationv1alpha1.Rule{
			APIGroups:   []string{"*"},
			APIVersions: []string{"*"},
			Resources:   []string{"*/*"},
		},
	}}

	table := map[string]test{
		"no match": {
			hookSource: fakeHookSource{
				hooks: []registrationv1alpha1.ExternalAdmissionHook{{
					Name:         "nomatch",
					ClientConfig: ccfg("disallow"),
					Rules: []registrationv1alpha1.RuleWithOperations{{
						Operations: []registrationv1alpha1.OperationType{registrationv1alpha1.Create},
					}},
				}},
			},
			expectAllow: true,
		},
		"match & allow": {
			hookSource: fakeHookSource{
				hooks: []registrationv1alpha1.ExternalAdmissionHook{{
					Name:         "allow",
					ClientConfig: ccfg("allow"),
					Rules:        matchEverythingRules,
				}},
			},
			expectAllow: true,
		},
		"match & disallow": {
			hookSource: fakeHookSource{
				hooks: []registrationv1alpha1.ExternalAdmissionHook{{
					Name:         "disallow",
					ClientConfig: ccfg("disallow"),
					Rules:        matchEverythingRules,
				}},
			},
			errorContains: "without explanation",
		},
		"match & disallow ii": {
			hookSource: fakeHookSource{
				hooks: []registrationv1alpha1.ExternalAdmissionHook{{
					Name:         "disallowReason",
					ClientConfig: ccfg("disallowReason"),
					Rules:        matchEverythingRules,
				}},
			},
			errorContains: "you shall not pass",
		},
		"match & fail (but allow because fail open)": {
			hookSource: fakeHookSource{
				hooks: []registrationv1alpha1.ExternalAdmissionHook{{
					Name:         "internalErr A",
					ClientConfig: ccfg("internalErr"),
					Rules:        matchEverythingRules,
				}, {
					Name:         "invalidReq B",
					ClientConfig: ccfg("invalidReq"),
					Rules:        matchEverythingRules,
				}, {
					Name:         "invalidResp C",
					ClientConfig: ccfg("invalidResp"),
					Rules:        matchEverythingRules,
				}},
			},
			expectAllow: true,
		},
	}

	for name, tt := range table {
		wh.hookSource = &tt.hookSource

		err = wh.Admit(admission.NewAttributesRecord(&object, &oldObject, kind, namespace, name, resource, subResource, operation, &userInfo))
		if tt.expectAllow != (err == nil) {
			t.Errorf("%q: expected allowed=%v, but got err=%v", name, tt.expectAllow, err)
		}
		// ErrWebhookRejected is not an error for our purposes
		if tt.errorContains != "" {
			if err == nil || !strings.Contains(err.Error(), tt.errorContains) {
				t.Errorf("%q: expected an error saying %q, but got %v", name, tt.errorContains, err)
			}
		}
	}
}

func webhookHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Printf("got req: %v\n", r.URL.Path)
	switch r.URL.Path {
	case "/internalErr":
		http.Error(w, "webhook internal server error", http.StatusInternalServerError)
		return
	case "/invalidReq":
		w.WriteHeader(http.StatusSwitchingProtocols)
		w.Write([]byte("webhook invalid request"))
		return
	case "/invalidResp":
		w.Header().Set("Content-Type", "application/json")
		w.Write([]byte("webhook invalid response"))
	case "/disallow":
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(&v1alpha1.AdmissionReview{
			Status: v1alpha1.AdmissionReviewStatus{
				Allowed: false,
			},
		})
	case "/disallowReason":
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(&v1alpha1.AdmissionReview{
			Status: v1alpha1.AdmissionReviewStatus{
				Allowed: false,
				Result: &metav1.Status{
					Message: "you shall not pass",
				},
			},
		})
	case "/allow":
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(&v1alpha1.AdmissionReview{
			Status: v1alpha1.AdmissionReviewStatus{
				Allowed: true,
			},
		})
	default:
		http.NotFound(w, r)
	}
}


text:
/* display.h
 * $Id: display.h,v 1.2 2004/09/23 11:11:55 becker Exp $
 * Ralf Becker <nctop@web.de>
 */

#ifndef _DISPLAY_H_

int display_init(void);

void display_kill(void);

void display(void);

void display_header(void);

void display_msg(int n);

void display_refresh(void);

void display_scroll(int n);

/* handle keyboard events */
int key_handler(void);

void sig_resize(int signal);

void printlist(void);

#define _DISPLAY_H_
#endif


text:
namespace artemis {

	ComponentType::ComponentType() {
		init();
	}

	void ComponentType::init() {
		bit = nextBit;
		nextBit = nextBit << 1;
		id = nextId++;
	}

	std::bitset<BITSIZE> ComponentType::getBit() const {
		return bit;
	}

	int ComponentType::getId() const {
		return id;
	}

	std::bitset<BITSIZE> ComponentType::nextBit(1);
	int ComponentType::nextId = 1;
};


text:
package com.github.jochenw.afw.core.crypt;

import java.io.InputStream;
import java.io.OutputStream;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.Certificate;

import com.github.jochenw.afw.core.util.Reflection;
import com.github.jochenw.afw.core.util.Tupel;

/**
 * Default implementation of {@link IKeyHandler}. Uses JCE, if possible,
 * otherwise Bouncycastle.
 */
public class DefaultKeyHandler implements IKeyHandler {
	final IKeyHandler keyHandler = newKeyHandler();

	private static IKeyHandler newKeyHandler() {
		try {
			Reflection.newObject("sun.security.x509.X509CertInfo");
			return new JceKeyHandler();
		} catch (Throwable t) {
			return new BcKeyHandler();
		}
	}
	@Override
	public KeyPair createKeyPair() {
		return keyHandler.createKeyPair();
	}

	@Override
	public Certificate generateCertificate(String pDn, KeyPair pKeyPair, int pValidity) {
		return keyHandler.generateCertificate(pDn, pKeyPair, pValidity);
	}

	@Override
	public KeyStore createKeyStore(PrivateKey pPrivateKey, Certificate pCertificate, String pAlias, String pStoreType,
			String pStorePass, String pKeyPass) {
		return keyHandler.createKeyStore(pPrivateKey, pCertificate, pAlias, pStoreType, pStorePass, pKeyPass);
	}

	@Override
	public void createKeyStore(OutputStream pOut, PrivateKey pPrivateKey, Certificate pCertificate, String pAlias,
			String pStoreType, String pStorePass, String pKeyPass) {
		keyHandler.createKeyStore(pOut, pPrivateKey, pCertificate, pAlias, pStoreType, pStorePass, pKeyPass);
	}

	@Override
	public Tupel<PrivateKey, Certificate> readPrivateKey(InputStream pIn, String pAlias, String pStorePass,
			String pKeyPass) {
		return keyHandler.readPrivateKey(pIn, pAlias, pStorePass, pKeyPass);
	}

	@Override
	public byte[] encrypt(Key pKey, byte[] pBytes) {
		return keyHandler.encrypt(pKey, pBytes);
	}

	@Override
	public byte[] decrypt(Key pKey, byte[] pBytes) {
		return keyHandler.decrypt(pKey, pBytes);
	}
}


text:
<mat-toolbar color="primary">

    <mat-toolbar-row>

{{leftHeader}}

{{rightHeader}}

            <mat-icon [matMenuTriggerFor]="menu"> <mat-icon>menu</mat-icon></mat-icon>
            <mat-menu #menu="matMenu">
                <button mat-menu-item [routerLink]="gamesPageLink">Games</button>
                <button mat-menu-item routerLink="/not-found">Stats</button>
                <button mat-menu-item routerLink="/not-found">Profile</button>
                <button mat-menu-item [routerLink]="sandBoxLink">Sandbox</button>
            </mat-menu>

    </mat-toolbar-row>

    <mat-toolbar-row *ngIf="!isMobile" style="max-height:20px">
        Games
        Stats
        Profile
        Sandbox
    </mat-toolbar-row>

</mat-toolbar>


text:
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('logger', '0017_auto_20171202_2306'),
    ]

    operations = [
        migrations.AlterField(
            model_name='httprequest',
            name='id',
            field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
        ),
    ]


text:
"""
Django Rest Framework serialization for the RSSNext project
"""

from django.core.exceptions import ObjectDoesNotExist

from rest_framework import serializers

from feedreader.models import Feed

from .models import Subscription

class SubscriptionSerializer(serializers.Serializer):
    """
    Django Rest Framework serialization for the Subscription model.
    """

    id = serializers.ReadOnlyField()
    url = serializers.URLField()

    title = serializers.SerializerMethodField()

    def create(self, validated_data):
        """
        Creates a subscription given a url, by creating the feed if it does
        not already exist.

        :param validated_data: the data supplied to this serializer
        :return: the new Subscription object
        """

        try:
            feed = Feed.objects.get(xml_url=validated_data["url"])
        except ObjectDoesNotExist:
            feed = Feed.objects.create(xml_url=validated_data["url"])

            if feed.title is None:
                feed.title = validated_data["url"]

        return Subscription.objects.create(feed=feed,
                                           user=validated_data["user"])

    def get_title(self, obj):
        """
        :return: the title of the feed to which this subscription relates
        """
        return obj.feed.title

class EntryRelationSerializer(serializers.Serializer):
    """
    Django Rest Framework serialization for the EntryRelation model.
    """

    link = serializers.SerializerMethodField()

    def get_link(self, obj):
        """
        :param obj: the object under serialization.
        :return: the link for the next entry under this entry relation
        """
        try:
            return obj.get_next_entry().link
        except AttributeError:
            return None


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jzh.dao.CommodityDao">

    <!-- Commodity集合申明 -->
    <resultMap id="CommodityMap" type="Commodity">
        <id property="id" column="commodity_id"/>
        <result property="typeId" column="commodity_type_id"/>
        <result property="name" column="commodity_name"/>
        <result property="price" column="price"/>
        <result property="shopId" column="shop_id"/>
        <result property="imgPrincipal" column="img_principal" />
        <result property="imgDrawing" column="img_drawing"/>
        <result property="imgShot" column="img_shot"/>
        <result property="imgSize" column="img_size"/>
        <result property="imgDetail" column="img_detail"/>
        <result property="imgMaterial" column="img_material"/>
        <result property="imgAdvantage" column="img_advantage"/>
        <result property="introduction" column="commodity_introduction"/>
        <result property="isSale" column="is_sale"/>
        <result property="isRecommend" column="is_recommend"/>
        <result property="isDeleted" column="is_deleted"/>
        <result property="updateTime" column="update_time"/>
    </resultMap>

    <!--把需要查询的字段写成公用列-->
    <sql id="base_column">
        commodity_id,commodity_type_id,commodity_name,price,shop_id,img_principal,img_drawing,img_shot,
        img_size,img_detail,img_material,img_advantage,commodity_introduction,is_sale,
        is_recommend,is_deleted,update_time
    </sql>

    <!-- 搜素所有未逻辑删除的Commodity-->
    <select id="listAll" resultMap="CommodityMap">
        select
        <include refid="base_column" />
        from commodity
    </select>

    <!-- 新增Commodity -->
    <insert id="insert" useGeneratedKeys="true" keyProperty="id" parameterType="Commodity" >
        insert into
        commodity
        (
          commodity_type_id,commodity_name,price,shop_id,img_principal,img_drawing,img_shot,
          img_size,img_detail,img_material,img_advantage,commodity_introduction,is_sale,
          is_recommend,is_deleted,update_time
        )
        values
        (
            #{typeId},#{name},#{price},#{shopId},#{imgPrincipal},#{imgDrawing},#{imgShot},#{imgSize},
            #{imgDetail},#{imgMaterial},#{imgAdvantage},#{introduction},#{isSale},
            #{isRecommend},1,NOW()
        )
    </insert>

    <!-- 更新Commodity -->
    <update id="update"  parameterType="Commodity">
        update commodity
        set
            commodity_type_id=#{typeId},
            commodity_name=#{name},
            price=#{price},
            shop_id=#{shopId},
            img_principal=#{imgPrincipal},
            img_drawing=#{imgDrawing},
            img_shot=#{imgShot},
            img_size=#{imgSize},
            img_detail=#{imgDetail},
            img_material=#{imgMaterial},
            img_advantage=#{imgAdvantage},
            commodity_introduction=#{introduction},
            is_sale=#{isSale},
            is_recommend=#{isRecommend},
            is_deleted=#{isDeleted},
            update_time=NOW()
        where commodity_id=#{id}
    </update>

    <!-- 删除Commodity -->
    <delete id="delete" parameterType="java.lang.Long">
        update commodity
        set
          is_deleted=0,
          update_time=NOW()
        where commodity_id=#{id}
    </delete>

    <!-- 查询Commodity -->
    <select id="get" parameterType="java.lang.Long" resultMap="CommodityMap">
        select
        <include refid="base_column" />
        from commodity
        where commodity_id=#{0}
    </select>

    <select id="getCommodityByType" parameterType="java.lang.Long" resultMap="CommodityMap">
        select
        <include refid="base_column" />
        from commodity
        where commodity_type_id=#{typeId}
    </select>

    <select id="getCommodityByShopAndType" parameterType="java.lang.Long" resultMap="CommodityMap">
        select
        <include refid="base_column" />
        from commodity
        where
          shop_id=#{0}
          <if test="#{1} != -1">
              AND commodity_type_id=#{1}
          </if>
    </select>
</mapper>