text:
import warnings
from abc import ABCMeta, abstractmethod
from .ast import TemplateClazzSpecialization, Function, Param, Method

class Specializer(object):
    """Convert templates to specializations for specific types."""
    __metaclass__ = ABCMeta
    def __init__(self, config):
        self.config = config

    def specialize(self, general):
        try:
            specs = self._lookup_specification(general)
        except LookupError as e:
            warnings.warn(e.message)
            general.ignored = True
            return []

        return self._specialize(general, specs)

    def _lookup_specification(self, general):
        key = self._key(general)
        if key not in self.config.registered_template_specializations:
            raise LookupError(
                "No template specialization registered for template with key "
                "'%s' with the following template types: %s"
                % (key, ", ".join(general.template_types)))
        return self.config.registered_template_specializations[key]

    def _key(self, general):
        if general.namespace != "":
            return "%s::%s" % (general.namespace, general.name)
        else:
            return general.name

    def _replace_specification(self, tipe, spec):
        return spec.get(tipe, tipe)

    @abstractmethod
    def _specialize(self, general, specs):
        """Specialize the given template."""

class ClassSpecializer(Specializer):
    """Convert a template class to a class."""
    def __init__(self, config):
        super(ClassSpecializer, self).__init__(config)

    def _specialize(self, general, specs):
        specialized_classes = []

        for name, spec in specs:
            types = [spec[t] for t in general.template_types]
            cppname = "%s[%s]" % (general.name, ", ".join(types))
            specialized = TemplateClazzSpecialization(
                general.filename, general.namespace, name, cppname, spec,
                general.comment)
            specialized_classes.append(specialized)

        return specialized_classes

class FunctionSpecializer(Specializer):
    """Convert a template function to a function."""
    def __init__(self, config):
        super(FunctionSpecializer, self).__init__(config)

    def _specialize(self, general, specs):
        specialized_functions = []
        for name, spec in specs:
            result_type = self._replace_specification(general.result_type, spec)

            specialized = Function(general.filename, general.namespace, name,
                                   result_type, general.comment)

            for arg in general.nodes:
                tipe = self._replace_specification(arg.tipe, spec)
                specialized.nodes.append(Param(arg.name, tipe))

            specialized_functions.append(specialized)
        return specialized_functions

class MethodSpecializer(Specializer):
    """Convert a template method to a method."""
    def __init__(self, config):
        super(MethodSpecializer, self).__init__(config)

    def _key(self, general):
        return "%s::%s" % (general.class_name, general.name)

    def _specialize(self, general, specs):
        specialized_methods = []
        for name, spec in specs:
            result_type = self._replace_specification(general.result_type, spec)

            specialized = Method(name, result_type, general.class_name,
                                 general.comment)

            for arg in general.nodes:
                tipe = self._replace_specification(arg.tipe, spec)
                specialized.nodes.append(Param(arg.name, tipe))

            specialized_methods.append(specialized)
        return specialized_methods


text:
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Rutt.Logging;
using Rutt.Messaging;
using Rutt.Messaging.TestAdapters;
using Rutt.TestAdapters.Execution;
using Rutt.TestAdapters.Models;

namespace Rutt.TestAdapters
{
    public class ExecutorClient : IExecutorClient, IAdapterExecutorEventListener
    {
        bool _disposed;
        static readonly ConcurrentDictionary<string, IAdapterTCollExecutor> QueuedTasks = new ConcurrentDictionary<string, IAdapterTCollExecutor>();
        protected readonly IAdapterEvents ExecutorEvents;
        protected readonly ILogger Logger;
        protected readonly IAdapterMessagingClient ExecutorMessagingClient;

        public int TestCollectionCount { get { return QueuedTasks.Count; } }

        public ExecutorClient(IAdapterMessagingClient executorMessagingClient, IAdapterEvents executorEvents, ILogger logger)
        {
            ExecutorMessagingClient = executorMessagingClient;
            ExecutorMessagingClient.Initialise(this);
            ExecutorMessagingClient.Start();
            ExecutorEvents = executorEvents;
            Logger = logger;
        }

        ~ExecutorClient()
        {
            Dispose(false);
        }

        #region TestAdapter Executor methods

        public void TestProjectCollectionStarting(TestProjectInfo testProjectInfo)
        {
            ExecutorEvents.TestProjectCollectionStarting(testProjectInfo);
        }

        public async Task CancelA()
        {
            foreach (var queuedTask in QueuedTasks)
            {
                await ExecutorMessagingClient.CancelA(queuedTask.Key);
            }
            while (!QueuedTasks.IsEmpty) { }
        }

        public virtual Task<TestSummary> ExecuteTestCollectionA(TestProject testProject, TestProjectReference[] projectReferences, TestCollection collection,
            CancellationToken cancellationToken)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                CancelA().Wait(cancellationToken);
                return Task.Run(()=>new TestSummary(), cancellationToken);
            }
            IAdapterTCollExecutor tce = new TestCollectionExecutor(testProject, collection, ExecutorEvents);
            if (!QueuedTasks.TryAdd(tce.Id, tce))
            {
                var message = "Unable to queue TestCollection " + collection.Name;
                Logger.Log(LogMessageType.Error, message);
                tce.Faulted(new TestExceptionMessage{ExceptionType = TestExceptionType.ExecutorClientException,Message = "Unable to Queue TestCollection " + tce.Id});
                return tce.Task;
            }
            ExecutorMessagingClient.ExecuteTestCollection(tce.Id, testProject, projectReferences, collection);
            ExecutorMessagingClient.CanExecuteTestCollection(ExecutorMessagingClient.ClientInfo.Id, tce.Id, CreateExecuteData(testProject, collection));
            return tce.Task;
        }

        public async Task TestProjectCollectionCompletedA(TestProjectInfo testProjectInfo)
        {
            await ExecutorMessagingClient.TestProjectCollectionCompletedA(testProjectInfo.Name);
            ExecutorEvents.TestProjectCollectionCompleted(testProjectInfo);
        }
        #endregion
        #region TestAdapter Event methods

        public void OnExecutorMessage(string testCollectionExecutorId, string message)
        {
            if (!QueuedTasks.ContainsKey(testCollectionExecutorId)) return;
            QueuedTasks[testCollectionExecutorId].Message(message);
        }

        public void OnCanExecuteTestCollection(string testCollectionExecutorId, CanExecuteResponse canExecute)
        {
            if (!QueuedTasks.ContainsKey(testCollectionExecutorId)) return;
            QueuedTasks[testCollectionExecutorId].TestCollectionCanExecute(canExecute);
            if (canExecute.IsValidTestAgent) return;
            // fail all testcases
            IAdapterTCollExecutor tcExecutor;
            if (QueuedTasks.TryRemove(testCollectionExecutorId, out tcExecutor))
            {
                tcExecutor.Faulted(
                    new TestExceptionMessage
                    {
                        ExceptionType = TestExceptionType.TestAgentException,
                        Message = "No Valid TestAgent for "+ testCollectionExecutorId
                    });
            }
        }

        public void OnTestCollectionStarted(string testCollectionExecutorId)
        {
            if (!QueuedTasks.ContainsKey(testCollectionExecutorId)) return;
            QueuedTasks[testCollectionExecutorId].Started();
        }

        public void OnTestCollectionCancelled(string testCollectionExecutorId)
        {
            if (!QueuedTasks.ContainsKey(testCollectionExecutorId)) return;
            IAdapterTCollExecutor tcExecutor;
            if (QueuedTasks.TryRemove(testCollectionExecutorId, out tcExecutor))
            {
                tcExecutor.Cancelled();
            }
        }

        public void OnTestCollectionFaulted(string testCollectionExecutorId, TestExceptionMessage[] executorResultMessages)
        {
            if (!QueuedTasks.ContainsKey(testCollectionExecutorId)) return;
            IAdapterTCollExecutor tcExecutor;
            if (QueuedTasks.TryRemove(testCollectionExecutorId, out tcExecutor))
            {
                tcExecutor.Faulted(executorResultMessages);
            }
        }

        public void OnTestCollectionFinished(string testCollectionExecutorId)
        {
            if (!QueuedTasks.ContainsKey(testCollectionExecutorId)) return;
            IAdapterTCollExecutor tcExecutor;
            if (QueuedTasks.TryRemove(testCollectionExecutorId, out tcExecutor))
            {
                tcExecutor.Finished();
            }
        }

        public void OnTestGroupStarted(string testCollectionExecutorId, string testGroupName)
        {
            if (!QueuedTasks.ContainsKey(testCollectionExecutorId)) return;
            QueuedTasks[testCollectionExecutorId].TestGroupStarted(testGroupName);
        }

        public void OnTestGroupCancelled(string testCollectionExecutorId, string testGroupName)
        {
            if (!QueuedTasks.ContainsKey(testCollectionExecutorId)) return;
            QueuedTasks[testCollectionExecutorId].TestGroupCancelled(testGroupName);
        }

        public void OnTestGroupFinished(string testCollectionExecutorId, string testGroupName)
        {
            if (!QueuedTasks.ContainsKey(testCollectionExecutorId)) return;
            QueuedTasks[testCollectionExecutorId].TestGroupFinished(testGroupName);
        }

        public void OnTestCaseStarted(string testCollectionExecutorId, string testCaseName)
        {
            if (!QueuedTasks.ContainsKey(testCollectionExecutorId)) return;
            QueuedTasks[testCollectionExecutorId].TestCaseStarted(testCaseName);
        }

        public void OnTestCaseCancelled(string testCollectionExecutorId, string testCaseName)
        {
            if (!QueuedTasks.ContainsKey(testCollectionExecutorId)) return;
            QueuedTasks[testCollectionExecutorId].TestCaseCancelled(testCaseName);
        }

        public void OnTestCaseResult(string testCollectionExecutorId, string testCaseName, TestCaseResult testCaseResult)
        {
            if (!QueuedTasks.ContainsKey(testCollectionExecutorId)) return;
            QueuedTasks[testCollectionExecutorId].TestCaseResult(testCaseName, testCaseResult);
        }

        public void OnTestCaseFinished(string testCollectionExecutorId, string testCaseName, TestCaseResult testCaseResult)
        {
            if (!QueuedTasks.ContainsKey(testCollectionExecutorId)) return;
            QueuedTasks[testCollectionExecutorId].TestCaseFinished(testCaseName, testCaseResult);
        }

        #endregion

        /// <summary>
        /// Determine constraints for which a TestAgent will use to determine if it can run a particular TestCollection
        /// </summary>
        /// <param name="testProject"></param>
        /// <param name="collection"></param>
        /// <returns></returns>
        CanExecuteData CreateExecuteData(TestProject testProject, TestCollection collection)
        {
            var canex = new CanExecuteData
            {
                TestProjectId = testProject.Name,
                ExecutorName = collection.ExecutorName,
                ExecutorSource = collection.ExecutorSource,
                DataConstraints = collection.Data.ToArray()
            };
            return canex;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected void Dispose(bool dispose)
        {
            if (_disposed) return;
            // Dispose managed resources.
            CancelA().Wait(2000);
            ExecutorMessagingClient.Stop();
            ExecutorMessagingClient.Dispose();
            // Dispose unmanaged resources.
            _disposed = true;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
/**
 * @for p5
 * @requires core
 */

'use strict';

var p5 = require('./core');
var doFriendlyWelcome = false; // TEMP until we get it all working LM

// -- Borrowed from jQuery 1.11.3 --
var class2type = {};
var toString = class2type.toString;
var names = ['Boolean', 'Number', 'String', 'Function',
             'Array', 'Date', 'RegExp', 'Object', 'Error'];
for (var n=0; n<names.length; n++) {
  class2type[ '[object ' + names[n] + ']' ] = names[n].toLowerCase();
}
var getType = function( obj ) {
  if ( obj == null ) {
    return obj + '';
  }
  return typeof obj === 'object' || typeof obj === 'function' ?
    class2type[ toString.call(obj) ] || 'object' :
    typeof obj;
};
var isArray = Array.isArray || function( obj ) {
  return getType(obj) === 'array';
};
var isNumeric =function( obj ) {
  // parseFloat NaNs numeric-cast false positives (null|true|false|"")
  // ...but misinterprets leading-number strings, particularly hex literals
  // subtraction forces infinities to NaN
  // adding 1 corrects loss of precision from parseFloat (#15100)
  return !isArray( obj ) && (obj - parseFloat( obj ) + 1) >= 0;
};
// -- End borrow --

/**
 * Checks the definition type against the argument type
 * If any of these passes (in order), it matches:
 *
 * - p5.* definitions are checked with instanceof
 * - Booleans are let through (everything is truthy or falsey)
 * - Lowercase of the definition is checked against the js type
 * - Number types are checked to see if they are numerically castable
 */
var numberTypes = ['Number', 'Integer', 'Number/Constant'];
function typeMatches(defType, argType, arg) {
  if(defType.match(/^p5\./)) {
    var parts = defType.split('.');
    return arg instanceof p5[parts[1]];
  }
  return defType === 'Boolean' || // Anything is truthy, cover in Debug Guide
    (defType.toLowerCase() === argType) ||
    (numberTypes.indexOf(defType) > -1 && isNumeric(arg));
}

/**
 * Prints out a fancy, colorful message to the console log
 *
 * @param  {String}               message the words to be said
 * @param  {String}               func    the name of the function to link
 * @param  {Integer/Color String} color   CSS color string or error type
 *
 * @return console logs
 */
// Wrong number of params, undefined param, wrong type
var PARAM_COUNT = 0;
var EMPTY_VAR = 1;
var WRONG_TYPE = 2;
var FILE_LOAD = 3;
// p5.js blue, p5.js orange, auto dark green; fallback p5.js darkened magenta
// See testColors below for all the color codes and names
var typeColors = ['#2D7BB6', '#EE9900', '#4DB200', '#C83C00'];
function report(message, func, color) {
  if(doFriendlyWelcome){
    friendlyWelcome();
    doFriendlyWelcome =false;
  }
  if ('undefined' === getType(color)) {
    color   = '#B40033'; // dark magenta
  } else if (getType(color) === 'number') { // Type to color
    color = typeColors[color];
  }
  // LM TEMP commenting this out until we get the whole system working
  // if (func.substring(0,4) === 'load'){
  //   console.log(
  //     '%c> p5.js says: '+message+'%c'+
  //     '[https://github.com/processing/p5.js/wiki/Local-server]',
  //     'background-color:' + color + ';color:#FFF;',
  //     'background-color:transparent;color:' + color +';',
  //     'background-color:' + color + ';color:#FFF;',
  //     'background-color:transparent;color:' + color +';'
  //   );
  // }
  // else{
  //   console.log(
  //     '%c> p5.js says: '+message+'%c [http://p5js.org/reference/#p5/'+func+
  //     ']', 'background-color:' + color + ';color:#FFF;',
  //     'background-color:transparent;color:' + color +';'
  //   );
  // }
}

/**
 * Validate all the parameters of a function for number and type
 * NOTE THIS FUNCTION IS TEMPORARILY DISABLED UNTIL FURTHER WORK
 * AND UPDATES ARE IMPLEMENTED. -LMCCART
 *
 * @param  {String} func  name of function we're checking
 * @param  {Array}  args  pass of the JS default arguments array
 * @param  {Array}  types List of types accepted ['Number', 'String, ...] OR
 *                        a list of lists for each format: [
 *                          ['String', 'Number', 'Number'],
 *                          ['String', 'Number', 'Number', 'Number', 'Number'
 *                        ]
 *
 * @return console logs
 */
p5.prototype._validateParameters = function(func, args, types) {
  if (!isArray(types[0])) {
    types = [types];
  }
  // Check number of parameters
  // Example: "You wrote ellipse(X,X,X). ellipse was expecting 4
  //          parameters. Try ellipse(X,X,X,X)."
  var diff = Math.abs(args.length-types[0].length);
  var message, tindex = 0;
  for (var i=1, len=types.length; i<len; i++) {
    var d = Math.abs(args.length-types[i].length);
    if (d <= diff) {
      tindex = i;
      diff = d;
    }
  }
  var symbol = 'X'; // Parameter placeholder
  if(diff > 0) {
    message = 'You wrote ' + func + '(';
    // Concat an appropriate number of placeholders for call
    if (args.length > 0) {
      message += symbol + Array(args.length).join(',' + symbol);
    }
    message += '). ' + func + ' was expecting ' + types[tindex].length +
      ' parameters. Try ' + func + '(';
    // Concat an appropriate number of placeholders for definition
    if (types[tindex].length > 0) {
      message += symbol + Array(types[tindex].length).join(',' + symbol);
    }
    message += ').';
    // If multiple definitions
    if (types.length > 1) {
      message += ' ' + func + ' takes different numbers of parameters ' +
        'depending on what you want to do. Click this link to learn more: ';
    }
    report(message, func, PARAM_COUNT);
  }
  // Type checking
  // Example: "It looks like ellipse received an empty variable in spot #2."
  // Example: "ellipse was expecting a number for parameter #1,
  //           received "foo" instead."
  for (var format=0; format<types.length; format++) {
    for (var p=0; p < types[format].length && p < args.length; p++) {
      var defType = types[format][p];
      var argType = getType(args[p]);
      if ('undefined' === argType || null === argType) {
        report('It looks like ' + func +
          ' received an empty variable in spot #' + (p+1) +
          '. If not intentional, this is often a problem with scope: ' +
          '[link to scope].', func, EMPTY_VAR);
      } else if (defType !== '*' && !typeMatches(defType, argType, args[p])) {
        message = func + ' was expecting a ' + defType.toLowerCase() +
          ' for parameter #' + (p+1) + ', received ';
        // Wrap strings in quotes
        message += 'string' === argType ? '"' + args[p] + '"' : args[p];
        message += ' instead.';
        // If multiple definitions
        if (types.length > 1) {
          message += ' ' + func + ' takes different numbers of parameters ' +
            'depending on what you want to do. ' +
            'Click this link to learn more:';
        }
        report(message, func, WRONG_TYPE);
      }
    }
  }
};
/*
 * NOTE THIS FUNCTION IS TEMPORARILY DISABLED UNTIL FURTHER WORK
 * AND UPDATES ARE IMPLEMENTED. -LMCCART
 */
p5.prototype._validateParameters = function() {
  return true;
};

var errorCases = {
  '0': {
    fileType: 'image',
    method: 'loadImage',
    message: ' hosting the image online,'
  },
  '1': {
    fileType: 'XML file',
    method: 'loadXML'
  },
  '2': {
    fileType: 'table file',
    method: 'loadTable'
  },
  '3': {
    fileType: 'text file',
    method: 'loadStrings'
  }
};
p5._friendlyFileLoadError = function (errorType, filePath) {
  var errorInfo = errorCases[ errorType ];
  var message = 'It looks like there was a problem' +
  ' loading your ' + errorInfo.fileType + '.' +
  ' Try checking if the file path%c [' + filePath + '] %cis correct,' +
  (errorInfo.message || '') + ' or running a local server.';
  report(message, errorInfo.method, FILE_LOAD);
};

function friendlyWelcome() {
  // p5.js brand - magenta: #ED225D
  var astrixBgColor = 'transparent';
  var astrixTxtColor = '#ED225D';
  var welcomeBgColor = '#ED225D';
  var welcomeTextColor = 'white';
  console.log(
  '%c    _ \n'+
  ' /\\| |/\\ \n'+
  ' \\ ` \' /  \n'+
  ' / , . \\  \n'+
  ' \\/|_|\\/ '+
  '\n\n%c> p5.js says: Welcome! '+
  'This is your friendly debugger. ' +
  'To turn me off switch to using "p5.min.js".',
  'background-color:'+astrixBgColor+';color:' + astrixTxtColor +';',
  'background-color:'+welcomeBgColor+';color:' + welcomeTextColor +';'
  );
}

/**
 * Prints out all the colors in the color pallete with white text.
 * For color blindness testing.
 */
/* function testColors() {
  var str = 'A box of biscuits, a box of mixed biscuits and a biscuit mixer';
  report(str, 'println', '#ED225D'); // p5.js magenta
  report(str, 'println', '#2D7BB6'); // p5.js blue
  report(str, 'println', '#EE9900'); // p5.js orange
  report(str, 'println', '#A67F59'); // p5.js light brown
  report(str, 'println', '#704F21'); // p5.js gold
  report(str, 'println', '#1CC581'); // auto cyan
  report(str, 'println', '#FF6625'); // auto orange
  report(str, 'println', '#79EB22'); // auto green
  report(str, 'println', '#B40033'); // p5.js darkened magenta
  report(str, 'println', '#084B7F'); // p5.js darkened blue
  report(str, 'println', '#945F00'); // p5.js darkened orange
  report(str, 'println', '#6B441D'); // p5.js darkened brown
  report(str, 'println', '#2E1B00'); // p5.js darkened gold
  report(str, 'println', '#008851'); // auto dark cyan
  report(str, 'println', '#C83C00'); // auto dark orange
  report(str, 'println', '#4DB200'); // auto dark green
} */

// This is a lazily-defined list of p5 symbols that may be
// misused by beginners at top-level code, outside of setup/draw. We'd like
// to detect these errors and help the user by suggesting they move them
// into setup/draw.
//
// For more details, see https://github.com/processing/p5.js/issues/1121.
var misusedAtTopLevelCode = null;
var FAQ_URL = 'https://github.com/processing/p5.js/wiki/' +
              'Frequently-Asked-Questions' +
              '#why-cant-i-assign-variables-using-p5-functions-and-' +
              'variables-before-setup';

function defineMisusedAtTopLevelCode() {
  var uniqueNamesFound = {};

  var getSymbols = function(obj) {
    return Object.getOwnPropertyNames(obj).filter(function(name) {
      if (name[0] === '_') {
        return false;
      }
      if (name in uniqueNamesFound) {
        return false;
      }

      uniqueNamesFound[name] = true;

      return true;
    }).map(function(name) {
      var type;

      if (typeof(obj[name]) === 'function') {
        type = 'function';
      } else if (name === name.toUpperCase()) {
        type = 'constant';
      } else {
        type = 'variable';
      }

      return {name: name, type: type};
    });
  };

  misusedAtTopLevelCode = [].concat(
    getSymbols(p5.prototype),
    // At present, p5 only adds its constants to p5.prototype during
    // construction, which may not have happened at the time a
    // ReferenceError is thrown, so we'll manually add them to our list.
    getSymbols(require('./constants'))
  );

  // This will ultimately ensure that we report the most specific error
  // possible to the user, e.g. advising them about HALF_PI instead of PI
  // when their code misuses the former.
  misusedAtTopLevelCode.sort(function(a, b) {
    return b.name.length - a.name.length;
  });
}

function helpForMisusedAtTopLevelCode(e, log) {
  if (!log) {
    log = console.log.bind(console);
  }

  if (!misusedAtTopLevelCode) {
    defineMisusedAtTopLevelCode();
  }

  // If we find that we're logging lots of false positives, we can
  // uncomment the following code to avoid displaying anything if the
  // user's code isn't likely to be using p5's global mode. (Note that
  // setup/draw are more likely to be defined due to JS function hoisting.)
  //
  //if (!('setup' in window || 'draw' in window)) {
  //  return;
  //}

  misusedAtTopLevelCode.some(function(symbol) {
    // Note that while just checking for the occurrence of the
    // symbol name in the error message could result in false positives,
    // a more rigorous test is difficult because different browsers
    // log different messages, and the format of those messages may
    // change over time.
    //
    // For example, if the user uses 'PI' in their code, it may result
    // in any one of the following messages:
    //
    //   * 'PI' is undefined                           (Microsoft Edge)
    //   * ReferenceError: PI is undefined             (Firefox)
    //   * Uncaught ReferenceError: PI is not defined  (Chrome)

    if (e.message && e.message.indexOf(symbol.name) !== -1) {
      log('%cDid you just try to use p5.js\'s ' + symbol.name +
          (symbol.type === 'function' ? '() ' : ' ') + symbol.type +
          '? If so, you may want to ' +
          'move it into your sketch\'s setup() function.\n\n' +
          'For more details, see: ' + FAQ_URL,
          'color: #B40033' /* Dark magenta */);
      return true;
    }
  });
}

// Exposing this primarily for unit testing.
p5.prototype._helpForMisusedAtTopLevelCode = helpForMisusedAtTopLevelCode;

if (document.readyState !== 'complete') {
  window.addEventListener('error', helpForMisusedAtTopLevelCode, false);

  // Our job is only to catch ReferenceErrors that are thrown when
  // global (non-instance mode) p5 APIs are used at the top-level
  // scope of a file, so we'll unbind our error listener now to make
  // sure we don't log false positives later.
  window.addEventListener('load', function() {
    window.removeEventListener('error', helpForMisusedAtTopLevelCode, false);
  });
}

module.exports = p5;


text:
layout: post
title: Android JNI
category: Android
tags: android
keywords: jni android
description: mark
---

1、 JNI 系列博客
http://blog.csdn.net/xyang81/article/details/41777471


text: Live code reloader for any projects


text:
package chav1961.purelib.streams.char2byte.asm;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import chav1961.purelib.basic.interfaces.SyntaxTreeInterface;
import chav1961.purelib.cdb.CompilerUtils;

class InternalUtils {
	static final char[]				FALSE = "false".toCharArray();
	static final char[]				TRUE = "true".toCharArray();

	static final char[]				TYPE_INT = "int".toCharArray();
	static final char[]				TYPE_REAL = "real".toCharArray();
	static final char[]				TYPE_STRING = "str".toCharArray();
	static final char[]				TYPE_BOOLEAN = "bool".toCharArray();

	static final int				ORDER_TERM = 0;
	static final int				ORDER_UNARY = 1;
	static final int				ORDER_MUL = 2;
	static final int				ORDER_ADD = 3;
	static final int				ORDER_CAT = 4;
	static final int				ORDER_TERNARY = 5;
	static final int				ORDER_COMPARE = 6;
	static final int				ORDER_NOT = 7;
	static final int				ORDER_AND = 8;
	static final int				ORDER_OR = 9;

	/**
	 *
Build field signature by it's description

	 * @param tree name tree containing names
	 * @param item name id in the tree
	 * @return signature
	 */
	static final String buildFieldSignature(final SyntaxTreeInterface<?> tree, final long item) {
		if (tree == null) {
			throw new IllegalArgumentException("Names tree can't be null");
		}
		else if (!tree.contains(item)) {
			throw new IllegalArgumentException("Item ["+item+"] is missing in the names tree");
		}
		else {
			return fieldSignature(tree.getName(item));
		}
	}

	/**
	 *
Build method signature by description of it's parameters and returned type

	 * @param tree name tree containing names
	 * @param retType method returned type id
	 * @param parameters method parameter type ids
	 * @return signature
	 */
	static final String buildMethodSignature(final SyntaxTreeInterface<?> tree, final boolean staticMethod, final long retType, final long... parameters) {
		if (tree == null) {
			throw new IllegalArgumentException("Names tree can't be null");
		}
		else if (parameters == null) {
			throw new IllegalArgumentException("Parameters can't be null");
		}
		else if (!tree.contains(retType)) {
			throw new IllegalArgumentException("Returned type item ["+retType+"] is missing in the names tree");
		}
		else {
			final StringBuilder	sb = new StringBuilder("(");

			for (int index = staticMethod ? 0 : 1; index < parameters.length; index++) {
				if (!tree.contains(parameters[index])) {
					throw new IllegalArgumentException("Parameter["+index+"] = "+parameters[index]+" is missing in the names tree");
				}
				else {
					sb.append(fieldSignature(tree.getName(parameters[index])));
				}
			}
			return sb.append(')').append(fieldSignature(tree.getName(retType))).toString();
		}
	}

	static int methodSignature2Stack(final String methodSignature, int[] result) {
		int		toStore = 0, currentType;

		for (int index = 1, maxIndex = methodSignature.length(); index < maxIndex; index++) {
			char	currentChar = methodSignature.charAt(index);

			if (currentChar == ')') {
				break;
			}
			else {
				currentType = signatureByLetter(currentChar);
				while (currentChar == '[') {
					currentChar = methodSignature.charAt(++index);
				}
				if (currentChar == 'L') {
					while (currentChar != ';') {
						currentChar = methodSignature.charAt(++index);
					}
				}
				if (currentType == CompilerUtils.CLASSTYPE_DOUBLE || currentType == CompilerUtils.CLASSTYPE_LONG) {
					if (toStore < result.length) {
						result[toStore] = currentType;
					}
					toStore++;
					if (toStore < result.length) {
						result[toStore] = StackAndVarRepo.SPECIAL_TYPE_TOP;
					}
					toStore++;
				}
				else {
					if (toStore < result.length) {
						result[toStore] = currentType;
					}
					toStore++;
				}
			}
		}
		return toStore >= result.length ? -toStore : toStore;
	}

	static int methodSignature2Type(final String methodSignature) {
		int from = 0;

		while (methodSignature.charAt(from) != ')') {
			from++;
		}
		return signatureByLetter(methodSignature.charAt(from+1));
	}

	static int fieldSignature2Type(final String fieldSignature) {
		return signatureByLetter(fieldSignature.charAt(0));
	}

	static int methodSignature2Stack(final Method method, int[] result) {
		return methodSignature2Stack(CompilerUtils.buildMethodSignature(method),result);
	}

	static int constructorSignature2Stack(final Constructor<?> constructor, int[] result) {
		return methodSignature2Stack(CompilerUtils.buildConstructorSignature(constructor),result);
	}

	static int methodSignature2Type(final Method method) {
		return methodSignature2Type(CompilerUtils.buildMethodSignature(method));
	}

	static int constructorSignature2Type(final Constructor<?> constructor) {
		return methodSignature2Type(CompilerUtils.buildConstructorSignature(constructor));
	}

	private static int signatureByLetter(final char letter) {
		switch(letter) {
			case '[' : case 'L' :
				return CompilerUtils.CLASSTYPE_REFERENCE;
			case 'B' :
				return CompilerUtils.CLASSTYPE_BYTE;
			case 'C' :
				return CompilerUtils.CLASSTYPE_CHAR;
			case 'D' :
				return CompilerUtils.CLASSTYPE_DOUBLE;
			case 'F' :
				return CompilerUtils.CLASSTYPE_FLOAT;
			case 'I' :
				return CompilerUtils.CLASSTYPE_INT;
			case 'J' :
				return CompilerUtils.CLASSTYPE_LONG;
			case 'S' :
				return CompilerUtils.CLASSTYPE_SHORT;
			case 'V' :
				return CompilerUtils.CLASSTYPE_VOID;
			case 'Z' :
				return CompilerUtils.CLASSTYPE_BOOLEAN;
			default :
				throw new UnsupportedOperationException();
		}
	}

	private static String fieldSignature(final String name) {
		final int	trunc = name.lastIndexOf("[]");

		if (trunc >= 0) {
			return "["+fieldSignature(name.substring(0,trunc));
		}
		else {
			switch (name) {
				case "boolean"	: return "Z";
				case "byte"		: return "B";
				case "char"		: return "C";
				case "double"	: return "D";
				case "float"	: return "F";
				case "int"		: return "I";
				case "long"		: return "J";
				case "short"	: return "S";
				case "void"		: return "V";
				default :
					if (name.startsWith("[")) {
						return name.replace('.','/');
					}
					else {
						return "L"+name.replace('.','/')+";";
					}
			}
		}
	}

	static int skipBlank(final char[] data, int from) {
		char	symbol;

		while ((symbol = data[from]) <= ' ' && symbol != '\n') {
			from++;
		}
		if (symbol == '/' && data[from+1] == '/') {
			from += 2;
			while (data[from] != '\n') {
				from++;
			}
		}
		return from;
	}

	static int skipNonBlank(final char[] data, int from) {
		while (data[from] > ' ') {
			from++;
		}
		return from;
	}

}


text:
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.refactoring.changeSignature;

import com.intellij.psi.*;
import com.intellij.psi.util.MethodSignature;
import com.intellij.refactoring.util.RefactoringUIUtil;
import com.intellij.util.containers.MultiMap;
import org.jetbrains.plugins.groovy.lang.documentation.GroovyPresentationUtil;
import org.jetbrains.plugins.groovy.lang.psi.api.signatures.GrSignature;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrAccessorMethod;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod;
import org.jetbrains.plugins.groovy.lang.psi.api.types.GrClosureParameter;
import org.jetbrains.plugins.groovy.lang.psi.impl.GrClosureType;
import org.jetbrains.plugins.groovy.lang.psi.impl.signatures.GrClosureSignatureUtil;
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil;
import org.jetbrains.plugins.groovy.lang.psi.util.GroovyPropertyUtils;
import org.jetbrains.plugins.groovy.refactoring.GroovyRefactoringBundle;

import java.util.List;

/**
 * @author Maxim.Medvedev
 */
public final class GrMethodConflictUtil {
  private GrMethodConflictUtil() {
  }

  public static void checkMethodConflicts(PsiClass clazz,
                                          GrMethod prototype,
                                          GrMethod refactoredMethod,
                                          final MultiMap<PsiElement, String> conflicts, boolean excludeJavaConflicts) {
    List<MethodSignature> prototypeSignatures = GrClosureSignatureUtil.generateAllSignaturesForMethod(prototype, PsiSubstitutor.EMPTY);
    checkForClosurePropertySignatureOverload(clazz, prototype, refactoredMethod, conflicts, prototypeSignatures);
    checkForMethodSignatureOverload(clazz, prototype, refactoredMethod, conflicts, excludeJavaConflicts, prototypeSignatures);

    checkForAccessorOverloading(clazz, prototype, conflicts);
  }

  private static void checkForClosurePropertySignatureOverload(PsiClass clazz,
                                                               GrMethod prototype,
                                                               final GrMethod refactoredMethod,
                                                               final MultiMap<PsiElement, String> conflicts,
                                                               final List<MethodSignature> prototypeSignatures) {
    final boolean isStatic = prototype.hasModifierProperty(PsiModifier.STATIC);
    final String name = prototype.getName();
    if (!GroovyPropertyUtils.isProperty(clazz, name, isStatic)) return;

    final PsiMethod getter = GroovyPropertyUtils.findPropertyGetter(clazz, name, isStatic, true);

    final PsiType returnType;
    if (getter instanceof GrMethod) {
      returnType = ((GrMethod)getter).getInferredReturnType();
    }
    else if (getter instanceof GrAccessorMethod) {
      returnType = ((GrAccessorMethod)getter).getInferredReturnType();
    }
    else {
      return;
    }
    if (!(returnType instanceof GrClosureType)) return;

    final List<GrSignature> signatures = ((GrClosureType)returnType).getSignatures();
    for (GrSignature signature : signatures) {
      NextSignature:
      for (MethodSignature prototypeSignature : prototypeSignatures) {
        final GrClosureParameter[] params = signature.getParameters();
        final PsiType[] types = prototypeSignature.getParameterTypes();
        if (types.length != params.length) continue;
        for (int i = 0; i < types.length; i++) {
          if (!TypesUtil.isAssignableByMethodCallConversion(types[i], params[i].getType(), refactoredMethod.getParameterList())) {
            continue NextSignature;
          }
        }
        conflicts.putValue(getter, GroovyRefactoringBundle.message("refactored.method.will.cover.closure.property", name, RefactoringUIUtil.getDescription(getter.getContainingClass(), false)));
      }
    }
  }

  private static void checkForMethodSignatureOverload(PsiClass clazz,
                                                      GrMethod prototype,
                                                      GrMethod refactoredMethod,
                                                      MultiMap<PsiElement, String> conflicts,
                                                      boolean excludeJavaConflicts,
                                                      List<MethodSignature> prototypeSignatures) {
    if (excludeJavaConflicts) {
      prototypeSignatures.remove(prototype.getSignature(PsiSubstitutor.EMPTY));
    }

    String newName = prototype.getName();
    PsiMethod[] methods = clazz.findMethodsByName(newName, false);
    MultiMap<MethodSignature, PsiMethod> signatures = GrClosureSignatureUtil.findRawMethodSignatures(methods, clazz);
    for (MethodSignature prototypeSignature : prototypeSignatures) {
      for (PsiMethod method : signatures.get(prototypeSignature)) {
        if (method != refactoredMethod) {
          String signaturePresentation = GroovyPresentationUtil.getSignaturePresentation(prototypeSignature);
          conflicts.putValue(method, GroovyRefactoringBundle.message("method.duplicate", signaturePresentation,
                                                                     RefactoringUIUtil.getDescription(clazz, false)));
          break;
        }
      }
    }
  }

  private static void checkForAccessorOverloading(PsiClass clazz,
                                                  GrMethod prototype,
                                                  MultiMap<PsiElement, String> conflicts) {
    if (GroovyPropertyUtils.isSimplePropertySetter(prototype)) {
      String propertyName = GroovyPropertyUtils.getPropertyNameBySetter(prototype);
      PsiMethod setter =
        GroovyPropertyUtils.findPropertySetter(clazz, propertyName, prototype.hasModifierProperty(PsiModifier.STATIC), false);
      if (setter instanceof GrAccessorMethod) {
        conflicts.putValue(setter, GroovyRefactoringBundle.message("replace.setter.for.property", propertyName));
      }
    }
    else if (GroovyPropertyUtils.isSimplePropertyGetter(prototype)) {
      boolean isStatic = prototype.hasModifierProperty(PsiModifier.STATIC);
      String propertyName = GroovyPropertyUtils.getPropertyNameByGetter(prototype);
      PsiMethod getter = GroovyPropertyUtils.findPropertyGetter(clazz, propertyName, isStatic, false);
      if (getter instanceof GrAccessorMethod) {
        conflicts.putValue(getter, GroovyRefactoringBundle.message("replace.getter.for.property", propertyName));
      }
    }
  }
}


text:
package org.firstinspires.ftc.teamcode;

import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;

@TeleOp(name = "Test_TableLookup", group = "")
public class Test_TableLookup extends LinearOpMode {

  Periodic periodic = new Periodic(50.0);
  long i=0;
  oldA
  double input=0.0;
  double output=0.0;
  double table[][]={
      {0.0, 0.0},
      {1.0, 2.0},
      {3.0, 3.0},
      {6.0, 6.0},
      {10.0, 10.0}};
  TableLookup lookup = new TableLookup(table);
  @Override
  public void runOpMode() {

    waitForStart();

    while (opModeIsActive()){
      output = lookup.calc(input);

      if ((boolean)gamepad1.a == true and gamepad1_a_old == false){
         input = input + 1.0;
      }
      gamepad1_a_old = (boolean)gamepad1.a;
      if (input > 10.0) input = 0.0;

      telemetry.addData("X_In", input);
      telemetry.addData("Y_Out", output);
      telemetry.addData("Count",i++);
      telemetry.update();
      periodic.Wait();
    }
  }
}


text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
//using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Xml.Serialization;
using System.ComponentModel;
using System.Threading;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;

namespace Central_Control.AD
{
    /// <summary>
    /// Interaction logic for Users.xaml
    /// </summary>
    public partial class Users : Page
    {
        public Users()
        {
            InitializeComponent();
        }

        #region Page Events
        /// <summary>
        /// Do this when the page loades
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Users_Loaded(object sender, RoutedEventArgs e)
        {
            BackgroundBlur(false);

            if (GlobalConfig.Settings.OST_Integration == true)
            {
                ImportUserButton.IsEnabled = true;
                ImportUserButton.Visibility = Visibility.Visible;
            }
            else
            {
                ImportUserButton.IsEnabled = false;
                ImportUserButton.Visibility = Visibility.Collapsed;
            }

            ActiveDirectory.Connector.RunWorkerCompleted += User_Fetcher_Completed;
            ActiveDirectory.Connector.ProgressChanged += User_Fetcher_ProgressChanged;
            ActiveDirectory.User_Fetcher.RunWorkerCompleted += User_Fetcher_Completed;
            ActiveDirectory.User_Fetcher.ProgressChanged += User_Fetcher_ProgressChanged;
            UpdateUserButtons();

            if (!ReferenceEquals(ActiveDirectory.Users, null) && ActiveDirectory.IsConnected)
            {
                UserList.ItemsSource = ActiveDirectory.Users;

                OUBox.ItemsSource = ActiveDirectory.OUs;
                OUBox.SelectedValuePath = "Path";

                SearchBox.Focus();

                ICollectionView UserView = CollectionViewSource.GetDefaultView(ActiveDirectory.Users);
                new TextSearchFilter(UserView, SearchBox);
            }
            else
            {
                ExitAD();
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void User_Fetcher_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (e.UserState.ToString() == "Retrieving User")
            {
                RefreshProgress.IsIndeterminate = false;
                RefreshProgress.Maximum = ActiveDirectory.UserCount;
                RefreshProgress.Value = ActiveDirectory.Users.Count;
            }
            else if (e.UserState.ToString() == "Retrieving User Properties")
            {
                RefreshProgress.IsIndeterminate = false;
                RefreshProgress.Maximum = ActiveDirectory.Users.Count;
                RefreshProgress.Value = ActiveDirectory.UserCount;
            }
            else
            {
                RefreshProgress.IsIndeterminate = true;
            }
        }

        /// <summary>
        /// When the AD Updater_Users background worker is finished, notify the user or exit the page if disconnected
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void User_Fetcher_Completed(object sender, RunWorkerCompletedEventArgs e)
        {
            UpdateUserButtons();

            if (ActiveDirectory.IsConnected)
            {
                ResultMessage.Text = "User List Updated";
                ResultBox.Visibility = Visibility.Visible;

                string tmp = SearchBox.Text;
                SearchBox.Text = " ";
                SearchBox.Text = null;
                SearchBox.Text = tmp;
            }
            else
            {
                ExitAD();
            }
        }
        /// <summary>
        /// Remove event handler watchers when the page is unloaded
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Users_Unloaded(object sender, RoutedEventArgs e)
        {
            ActiveDirectory.Connector.RunWorkerCompleted -= User_Fetcher_Completed;
            ActiveDirectory.Connector.ProgressChanged -= User_Fetcher_ProgressChanged;
            ActiveDirectory.User_Fetcher.RunWorkerCompleted -= User_Fetcher_Completed;
            ActiveDirectory.User_Fetcher.ProgressChanged -= User_Fetcher_ProgressChanged;
        }
        #endregion Page Events

        #region Common Functions
        /// <summary>
        ///
        /// </summary>
        private void ClearSelection()
        {
            UserList.SelectedIndex = -1;

            string tmp = SearchBox.Text;
            SearchBox.Text = " ";
            SearchBox.Text = null;
            SearchBox.Text = tmp;
        }
        /// <summary>
        /// Reset the user action buttons with the appropriate actions for the selected user
        /// </summary>
        private void ClearInfoGrid()
        {
            Name.Text = string.Empty;
            Username.Text = string.Empty;
            Email.Text = string.Empty;
            Title.Text = string.Empty;
            Department.Text = string.Empty;
            Company.Text = string.Empty;
            CreatedDate.Text = string.Empty;
            ExpiryDate.Text = string.Empty;
            LastLogonDate.Text = string.Empty;
            LastBadPasswordAttempt.Text = string.Empty;
            LockedOut.Text = string.Empty;
            AccountLockoutTime.Text = string.Empty;
            DistinguishedName.Text = string.Empty;

            GroupList.ItemsSource = null;
        }
        /// <summary>
        /// Set the selected user to the selected user variable
        /// </summary>
        private void UpdateSelectedUser()
        {
            if ((UserList.SelectedItem != null) && (UserList.SelectedIndex != -1))
            {
                ActiveDirectory.SelectedUser = UserList.Items[UserList.SelectedIndex] as ActiveDirectory.UserPrincipalEx;
            }
            else
            {
                ActiveDirectory.SelectedUser = null;
            }
        }
        /// <summary>
        /// Reset the user action buttons with the appropriate actions for the selected user
        /// </summary>
        private void UpdateUserButtons()
        {
            if (ActiveDirectory.Connector.IsBusy)
            {
                RefreshButton.IsEnabled = false;
                RefreshButton.Content = null;

                RefreshProgress.Visibility = Visibility.Visible;
                RefreshProgressMessage.Visibility = Visibility.Visible;
                RefreshProgressMessage.Text = "Fetching...";
            }
            else if(ActiveDirectory.User_Fetcher.IsBusy)
            {
                RefreshButton.IsEnabled = false;
                RefreshButton.Content = null;

                RefreshProgress.Visibility = Visibility.Visible;
                RefreshProgressMessage.Visibility = Visibility.Visible;
                RefreshProgressMessage.Text = "Refreshing...";
            }
            else
            {
                RefreshButton.IsEnabled = true;
                RefreshButton.Content = "Refresh Users";

                RefreshProgressMessage.Visibility = Visibility.Hidden;
                RefreshProgress.Visibility = Visibility.Hidden;
            }

            if (ActiveDirectory.SelectedUser != null)
            {
                /* Account Buttons */

                DeleteUserButton.IsEnabled = true;

                if (!ActiveDirectory.SelectedUser.Enabled.Value)
                {
                    EnableUserButton.IsEnabled = true;
                    DisableUserButton.IsEnabled = false;
                }
                else
                {
                    EnableUserButton.IsEnabled = false;
                    DisableUserButton.IsEnabled = true;
                }

                if (ActiveDirectory.SelectedUser.Expiring)
                {
                    ExtendUserButton.Content = "Extend";
                    ExtendUserButton.IsEnabled = true;
                }
                else if (ActiveDirectory.SelectedUser.AccountExpirationDate == null)
                {
                    ExtendUserButton.Content = "Set Expiry";
                    ExtendUserButton.IsEnabled = true;
                }
                else
                {
                    ExtendUserButton.Content = "Remove Expiry";
                    ExtendUserButton.IsEnabled = true;
                }

                if (ActiveDirectory.SelectedUser.LockedOut)
                {
                    UnlockUserButton.IsEnabled = true;
                }
                else
                {
                    UnlockUserButton.IsEnabled = false;
                }

                /* Password Buttons */

                if (ActiveDirectory.SelectedUser.PasswordNeverExpires)
                {
                    ExpiryPasswordButton.Content = "Set Expiry";
                    ExpiryPasswordButton.IsEnabled = true;

                    RefreshPasswordButton.IsEnabled = false;

                    ExpirePasswordButton.IsEnabled = false;
                }
                else
                {
                    ExpiryPasswordButton.Content = "Remove Expiry";
                    ExpiryPasswordButton.IsEnabled = true;

                    RefreshPasswordButton.IsEnabled = true;

                    ExpirePasswordButton.IsEnabled = true;
                }

                ResetPasswordButton.IsEnabled = true;
            }
            else
            {
                /* Account Buttons */
                DeleteUserButton.IsEnabled = false;

                EnableUserButton.IsEnabled = false;
                ExtendUserButton.Content = "Extend";
                ExtendUserButton.IsEnabled = false;
                UnlockUserButton.IsEnabled = false;
                DisableUserButton.IsEnabled = false;

                /* Password Buttons */
                ExpiryPasswordButton.IsEnabled = false;
                RefreshPasswordButton.IsEnabled = false;
                ExpirePasswordButton.IsEnabled = false;
                ResetPasswordButton.IsEnabled = false;
            }
        }
        /// <summary>
        /// Reset the user info for the selected user
        /// </summary>
        private void UpdateUserInfo()
        {
            if (ActiveDirectory.SelectedUser != null)
            {
                Name.Text = ActiveDirectory.SelectedUser.Name;

                Username.Text = ActiveDirectory.SelectedUser.SamAccountName;

                if (!ReferenceEquals(ActiveDirectory.SelectedUser.EmailAddress, null))
                    Email.Text = ActiveDirectory.SelectedUser.EmailAddress;
                else
                    Email.Text = " ";

                if (!ReferenceEquals(ActiveDirectory.SelectedUser.Title, null))
                    Title.Text = ActiveDirectory.SelectedUser.Title;
                else
                    Title.Text = " ";

                if (!ReferenceEquals(ActiveDirectory.SelectedUser.Department, null))
                    Department.Text = ActiveDirectory.SelectedUser.Department;
                else
                    Department.Text = " ";

                if (!ReferenceEquals(ActiveDirectory.SelectedUser.Company, null))
                    Company.Text = ActiveDirectory.SelectedUser.Company;
                else
                    Company.Text = " ";

                if (!ReferenceEquals(ActiveDirectory.SelectedUser.CreatedDate, null))
                    CreatedDate.Text = ActiveDirectory.SelectedUser.CreatedDate;
                else
                    CreatedDate.Text = " ";

                if (!ReferenceEquals(ActiveDirectory.SelectedUser.AccountExpirationDate, null))
                    ExpiryDate.Text = ActiveDirectory.SelectedUser.AccountExpirationDate.ToString();
                else
                    ExpiryDate.Text = " ";

                if (!ReferenceEquals(ActiveDirectory.SelectedUser.LastLogon, null))
                    LastLogonDate.Text = ActiveDirectory.SelectedUser.LastLogon.ToString();
                else
                    LastLogonDate.Text = " ";

                if (!ReferenceEquals(ActiveDirectory.SelectedUser.LastBadPasswordAttempt, null))
                    LastBadPasswordAttempt.Text = ActiveDirectory.SelectedUser.LastBadPasswordAttempt.ToString();
                else
                    LastBadPasswordAttempt.Text = " ";

                if (!ReferenceEquals(ActiveDirectory.SelectedUser.LockedOut, null))
                    LockedOut.Text = ActiveDirectory.SelectedUser.LockedOut.ToString();
                else
                    LockedOut.Text = " ";

                if (!ReferenceEquals(ActiveDirectory.SelectedUser.AccountLockoutTime, null))
                    AccountLockoutTime.Text = ActiveDirectory.SelectedUser.AccountLockoutTime.ToString();
                else
                    AccountLockoutTime.Text = " ";

                if (!ReferenceEquals(ActiveDirectory.SelectedUser.DistinguishedName, null))
                    DistinguishedName.Text = ActiveDirectory.SelectedUser.DistinguishedName.ToString();
                else
                    DistinguishedName.Text = " ";

                GroupList.ItemsSource = ActiveDirectory.SelectedUser.Groups;
            }
            else
            {
                ClearInfoGrid();
            }

        }
        /// <summary>
        /// Toggle the blur on the main content
        /// </summary>
        /// <param name="BlurOn"></param>
        private void BackgroundBlur(bool BlurOn)
        {
            if (BlurOn)
            {
                MainContent.Style = FindResource("Blur") as Style;
                MainContent.IsEnabled = false;
            }
            else
            {
                MainContent.Style = FindResource("NoBlur") as Style;
                MainContent.IsEnabled = true;
            }
        }
        /// <summary>
        /// Action to perform when the confirm button is clicked
        /// </summary>
        private string Action;
        /// <summary>
        ///
        /// </summary>
        /// <param name="NewUserTicket"></param>
        private void AddTicketInfo(osTicket.NewUserTicket NewUserTicket)
        {
            DockPanel Ticket = new DockPanel();
            Ticket.Name = "Ticket_" + Ticket_Count;

            Label TicketNumber = new Label();
            TicketNumber.Name = "TicketNumber_" + Ticket_Count;
            TicketNumber.Style = FindResource("TicketMetaGrid") as Style;
            if (NewUserTicket.TicketNumber != null) TicketNumber.Content = NewUserTicket.TicketNumber;

            Label TicketStatus = new Label();
            TicketStatus.Name = "TicketStatus_" + Ticket_Count;
            TicketStatus.Style = FindResource("TicketMetaGrid") as Style;
            if (NewUserTicket.TicketStatus != null) TicketStatus.Content = NewUserTicket.TicketStatus;

            Label NewUserName = new Label();
            NewUserName.Name = "NewUserName_" + Ticket_Count;
            NewUserName.Style = FindResource("TicketMetaGrid") as Style;
            if (NewUserTicket.NewUserName != null) NewUserName.Content = NewUserTicket.NewUserName;

            Label CreatedBy = new Label();
            CreatedBy.Name = "CreatedBy_" + Ticket_Count;
            CreatedBy.Style = FindResource("TicketMetaGrid") as Style;
            if (NewUserTicket.CreatedBy != null) CreatedBy.Content = NewUserTicket.CreatedBy;

            Label Import = new Label();
            Import.Name = "Import_" + Ticket_Count;
            Import.Style = FindResource("TicketMetaGrid") as Style;
            Import.BorderThickness = new Thickness(1,0,1,1);

            Button ImportButton = new Button();
            ImportButton.Name = "ImportButton_" + Ticket_Count;
            ImportButton.Style = FindResource("SmallButton") as Style;
            ImportButton.Margin = new Thickness(0);
            ImportButton.HorizontalAlignment = HorizontalAlignment.Right;
            ImportButton.Content = "Import";
            ImportButton.Click += TicketImportButton_Click;

            Import.Content = ImportButton;

            TicketList.Children.Add(Ticket);
            Ticket.Children.Add(TicketNumber);
            Ticket.Children.Add(TicketStatus);
            Ticket.Children.Add(NewUserName);
            Ticket.Children.Add(CreatedBy);
            Ticket.Children.Add(Import);

            Ticket_Count++;
        }
        private int Ticket_Count = 0;

        /// <summary>
        /// Check and save the new user form, create the user if it all checks out.
        /// </summary>
        private void CreateUser()
        {
            ResultBox.Visibility = Visibility.Hidden;
            string ErrorMessage = null;

            FirstNameText.Style = FindResource("TextBox") as Style;
            UserNameText.Style = FindResource("TextBox") as Style;
            Password.Style = FindResource("PasswordBox") as Style;
            Password_Confirm.Style = FindResource("PasswordBox") as Style;

            bool ChecksOut = true;

            if (Password.Password != Password_Confirm.Password)
            {
                ChecksOut = false;
                Password_Confirm.Style = FindResource("PasswordBox_Error") as Style;
                ErrorMessage = "Passewords don't match";
            }
            if (string.IsNullOrEmpty(Password_Confirm.Password))
            {
                ChecksOut = false;
                Password_Confirm.Style = FindResource("PasswordBox_Error") as Style;
                ErrorMessage = "Please confirm the password";
            }
            if (Password.Password.Length < 8)
            {
                ChecksOut = false;
                Password.Style = FindResource("PasswordBox_Error") as Style;
                ErrorMessage = "Password is less than 8 characters";
            }
            if (string.IsNullOrEmpty(Password.Password))
            {
                ChecksOut = false;
                Password.Style = FindResource("PasswordBox_Error") as Style;
                ErrorMessage = "Password is required";
            }
            if (string.IsNullOrEmpty(UserNameText.Text))
            {
                ChecksOut = false;
                UserNameText.Style = FindResource("TextBox_Error") as Style;
                ErrorMessage = "Username is required";
            }
            if (OUBox.SelectedIndex == -1)
            {
                ChecksOut = false;
                ErrorMessage = "Select an OU";
            }
            if (string.IsNullOrEmpty(FullNameText.Text))
            {
                ChecksOut = false;
                FullNameText.Style = FindResource("TextBox_Error") as Style;
                ErrorMessage = "Full name is required";
            }
            if (string.IsNullOrEmpty(FirstNameText.Text))
            {
                ChecksOut = false;
                FirstNameText.Style = FindResource("TextBox_Error") as Style;
                ErrorMessage = "First name is required";
            }

            if (!ChecksOut)
            {
                if (ErrorMessage != null)
                {
                    ResultMessage.Text = ErrorMessage;
                    ResultBox.Visibility = Visibility.Visible;
                }
                return;
            }
            else
            {
                ActiveDirectory.NewUser.GivenName = FirstNameText.Text;
                ActiveDirectory.NewUser.Surname = LastNameText.Text;
                ActiveDirectory.NewUser.Name = FullNameText.Text;
                ActiveDirectory.NewUser.EmailAddress = EmailText.Text;
                ActiveDirectory.NewUser.Title = TitleText.Text;

                foreach (osTicket.NewUserTicket ticket in osTicket.Tickets)
                {
                    if (ticket.TicketNumber == TicketNumber)
                    {
                        ActiveDirectory.NewUser.Department = ticket.Department;
                    }
                }

                ActiveDirectory.NewUser.DistinguishedName = OUBox.SelectedValue.ToString();
                ActiveDirectory.NewUser.SamAccountName = UserNameText.Text;
                ActiveDirectory.NewUser.Password = Password.Password;
                Report(ActiveDirectory.NewUser.CreateUser(), "User Create Successfully");

                BackgroundBlur(false);
                NewUserBox.Visibility = Visibility.Hidden;

                FirstNameText.Text = null;
                LastNameText.Text = null;
                FullNameText.Text = null;
                EmailText.Text = null;
                Title.Text = null;
                OUBox.SelectedIndex = -1;
                UserNameText.Text = null;
                Password.Password = null;
                Password_Confirm.Password = null;
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="Result"></param>
        /// <param name="SuccessMessage"></param>
        /// <returns></returns>
        private bool Report(bool Result, string SuccessMessage)
        {
            ResultBox.Visibility = Visibility.Hidden;

            if (Result)
            {
                ResultMessage.Text = SuccessMessage;
                ResultBox.Visibility = Visibility.Visible;

                if (Action == "ReallyDelete")
                {
                    ClearSelection();
                }

                UpdateSelectedUser();
                UpdateUserButtons();

                return true;
            }
            else
            {
                ResultMessage.Text = ActiveDirectory.ConnectionError;
                ResultBox.Visibility = Visibility.Visible;

                RefreshButton.IsEnabled = false;
                ActiveDirectory.Connect();

                return false;
            }
        }
        #endregion Common Functions

        #region Control Actions
        /// <summary>
        /// Pressing Enter in searchbox invokes fullLookup
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SearchBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
            {
                SearchBox.Text = string.Empty;
                ClearSelection();
            }
        }
        /// <summary>
        /// Displays more info on the selected item
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            UserList.ScrollIntoView(UserList.SelectedItem);

            UpdateSelectedUser();
            UpdateUserInfo();
            UpdateUserButtons();
        }
        /// <summary>
        /// Clear the selection when {ESC} is pressed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserList_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
            {
                SearchBox.Text = string.Empty;
                ClearSelection();
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Password_Confirm_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                CreateUser();
            }
        }

        #region User Buttons
        /// <summary>
        /// User refresh button action
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RefreshButton_Click(object sender, RoutedEventArgs e)
        {
            ResultBox.Visibility = Visibility.Hidden;

            RefreshButton.IsEnabled = false;
            RefreshButton.Content = null;

            RefreshProgress.Visibility = Visibility.Visible;
            RefreshProgressMessage.Visibility = Visibility.Visible;
            RefreshProgressMessage.Text = "Refreshing...";

            ActiveDirectory.Refresh("Users");
        }
        /// <summary>
        /// Button action to create a new user
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NewUserButton_Click(object sender, RoutedEventArgs e)
        {
            BackgroundBlur(true);
            NewUserBox.Visibility = Visibility.Visible;
        }
        /// <summary>
        /// Button action to import a user from an OSticket ticket
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ImportUserButton_Click(object sender, RoutedEventArgs e)
        {
            BackgroundBlur(true);
            TicketImportBox.Visibility = Visibility.Visible;

            TicketList.Children.Clear();

            osTicket.GetTickets();
            foreach(osTicket.NewUserTicket ticket in osTicket.Tickets)
            {
                AddTicketInfo(ticket);
            }
        }
        /// <summary>
        /// Button action to delete the selected user
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DeleteUserButton_Click(object sender, RoutedEventArgs e)
        {
            BackgroundBlur(true);
            WarningBox.Visibility = Visibility.Visible;

            WarningMessage.Text = "Are you sure you want to delete " + ActiveDirectory.SelectedUser.Name + "?";
            ConfirmButton.Content = "Delete " + ActiveDirectory.SelectedUser.SamAccountName;
            ConfirmButton.IsEnabled = true;
            CancelButton.IsEnabled = true;

            Action = "Delete";
        }
        /// <summary>
        /// Button action to enable the selected user
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void EnableUserButton_Click(object sender, RoutedEventArgs e)
        {
            Report(ActiveDirectory.SelectedUser.EnableUser(), "User Enabled Successfully");
        }
        /// <summary>
        /// Button action to extend expiration on the selected user
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ExtendUserButton_Click(object sender, RoutedEventArgs e)
        {
            if (ActiveDirectory.SelectedUser.Expiring)
            {
                Report(ActiveDirectory.SelectedUser.AddExpiry(30), "Account Extended Successfully (30 Days)");
            }
            else if (ActiveDirectory.SelectedUser.AccountExpirationDate == null)
            {
                Report(ActiveDirectory.SelectedUser.AddExpiry(30), "Account Expiration Set Successfully (30 Days)");
            }
            else
            {
                Report(ActiveDirectory.SelectedUser.RemoveExpiry(), "Account Expiration Removed Successfully");
            }
        }
        /// <summary>
        /// Button action to unlock the selected user
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UnlockUserButton_Click(object sender, RoutedEventArgs e)
        {
            Report(ActiveDirectory.SelectedUser.UnlockUser(), "User Unlocked Successfully");
        }
        /// <summary>
        /// Button action to disable the selected user
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DisableUserButton_Click(object sender, RoutedEventArgs e)
        {
            BackgroundBlur(true);
            WarningBox.Visibility = Visibility.Visible;

            WarningMessage.Text = "Are you sure you want to disable " + ActiveDirectory.SelectedUser.Name + "?";
            ConfirmButton.Content = "Disable " + ActiveDirectory.SelectedUser.SamAccountName;
            ConfirmButton.IsEnabled = true;
            CancelButton.IsEnabled = true;

            Action = "Disable";
        }
        #endregion User Buttons

        #region Password Buttons
        /// <summary>
        /// Button action to refresh the selected user's password
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ExpiryPasswordButton_Click(object sender, RoutedEventArgs e)
        {
            if (ActiveDirectory.SelectedUser.PasswordNeverExpires)
            {
                Report(ActiveDirectory.SelectedUser.AddPasswordExpiry(), "Account Password Expiration Added Successfully");
            }
            else
            {
                Report(ActiveDirectory.SelectedUser.RemovePasswordExpiry(), "Account Password Expiration Removed Successfully");
            }
        }
        /// <summary>
        /// Button action to refresh the selected user's password
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RefreshPasswordButton_Click(object sender, RoutedEventArgs e)
        {
            Report(ActiveDirectory.SelectedUser.RefreshPassword(), "User Password Refreshed Successfully");
        }
        /// <summary>
        /// Button action to expire the selected user's password
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ExpirePasswordButton_Click(object sender, RoutedEventArgs e)
        {
            Report(ActiveDirectory.SelectedUser.ExpirePassword(), "User Password Expired Succcessfully");
        }
        /// <summary>
        /// Button action to reset the selected user's password
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ResetPasswordButton_Click(object sender, RoutedEventArgs e)
        {
            BackgroundBlur(true);
            WarningBox.Visibility = Visibility.Visible;
            WarningMessage.Text = "Enter a new password for " + ActiveDirectory.SelectedUser.Name + ":";

            PasswordInput.Visibility = Visibility.Visible;

            ConfirmButton.Content = "Reset Password";
            ConfirmButton.IsEnabled = true;
            CancelButton.IsEnabled = true;

            Action = "Reset";
        }
        #endregion Password Buttons

        #region Ticket Import Form

        private string TicketNumber = null;
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TicketImportButton_Click(object sender, RoutedEventArgs e)
        {
            BackgroundBlur(true);
            NewUserBox.Visibility = Visibility.Visible;
            TicketImportBox.Visibility = Visibility.Hidden;

            Button thisButton = sender as Button;
            Label ParentLabel = thisButton.Parent as Label;
            DockPanel ParentPanel = ParentLabel.Parent as DockPanel;
            Label Ticket = ParentPanel.Children[0] as Label;
            TicketNumber = Ticket.Content.ToString();

            foreach(osTicket.NewUserTicket ticket in osTicket.Tickets)
            {
                if (ticket.TicketNumber == TicketNumber)
                {
                    ticket.NewUserName = ticket.NewUserName.Trim();
                    string[] Name = ticket.NewUserName.Split(' ');
                    FirstNameText.Text = Name[0];
                    LastNameText.Text = Name[ticket.NewUserName.Split(' ').Length - 1];

                    TitleText.Text = ticket.Title;

                    string OUtree = GlobalConfig.Settings.OST_OU[GlobalConfig.Settings.OST_Dept.FindIndex(p => p == ticket.Department)];
                    OUBox.SelectedValue = Central_Control.ActiveDirectory.OUs.Find(p => p.Tree == OUtree).Path;
                }
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TicketCancelButton_Click(object sender, RoutedEventArgs e)
        {
            BackgroundBlur(false);
            TicketImportBox.Visibility = Visibility.Hidden;
            ResultBox.Visibility = Visibility.Hidden;

            FirstNameText.Text = null;
            LastNameText.Text = null;
            FullNameText.Text = null;
            EmailText.Text = null;
            Title.Text = null;
            OUBox.SelectedIndex = -1;
            UserNameText.Text = null;
            Password.Password = null;
            Password_Confirm.Password = null;
        }
        #endregion Ticket Import Form

        #region New User Form
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FirstNameText_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (FirstNameText.Text.Length > 0 || LastNameText.Text.Length > 0)
            {
                FullNameText.Text = FirstNameText.Text + " " + LastNameText.Text;

                if (FirstNameText.Text.Length > 0)
                    UserNameText.Text = FirstNameText.Text[0] + LastNameText.Text;
                else
                    UserNameText.Text = LastNameText.Text;

                EmailText.Text = UserNameText.Text + "@" + ActiveDirectory.Domain.Name;
            }
            else
            {
                FullNameText.Text = null;
                UserNameText.Text = null;
                EmailText.Text = null;
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LastNameText_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (FirstNameText.Text.Length > 0 || LastNameText.Text.Length > 0)
            {
                FullNameText.Text = FirstNameText.Text + " " + LastNameText.Text;

                if (FirstNameText.Text.Length > 0)
                    UserNameText.Text = FirstNameText.Text[0] + LastNameText.Text;
                else
                    UserNameText.Text = LastNameText.Text;

                EmailText.Text = UserNameText.Text + "@" + ActiveDirectory.Domain.Name;
            }
            else
            {
                FullNameText.Text = null;
                UserNameText.Text = null;
                EmailText.Text = null;
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NewUserSaveButton_Click(object sender, RoutedEventArgs e)
        {
            CreateUser();
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NewUserCancelButton_Click(object sender, RoutedEventArgs e)
        {
            BackgroundBlur(false);
            NewUserBox.Visibility = Visibility.Hidden;
            ResultBox.Visibility = Visibility.Hidden;

            FirstNameText.Text = null;
            LastNameText.Text = null;
            FullNameText.Text = null;
            EmailText.Text = null;
            Title.Text = null;
            OUBox.SelectedIndex = -1;
            UserNameText.Text = null;
            Password.Password = null;
            Password_Confirm.Password = null;
        }
        #endregion New User Form

        #region Warning Message
        /// <summary>
        /// Confirm the action and continue
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ConfirmButton_Click(object sender, RoutedEventArgs e)
        {
            switch (Action)
            {
                case "Delete":
                    BackgroundBlur(true);
                    WarningBox.Visibility = Visibility.Visible;

                    WarningMessage.Text = "This cannot be undone! Are you super sure to DELETE " + ActiveDirectory.SelectedUser.Name + "?";
                    ConfirmButton.Content = "DELETE " + ActiveDirectory.SelectedUser.SamAccountName;
                    ConfirmButton.IsEnabled = true;
                    CancelButton.IsEnabled = true;

                    Action = "ReallyDelete";
                    return;
                case "ReallyDelete":
                    Report(ActiveDirectory.SelectedUser.DeleteUser(), "User Deleted Successfully");
                    break;
                case "Reset":
                    NewPassword.Style = FindResource("PasswordBox") as Style;
                    NewPassword_Confirm.Style = FindResource("PasswordBox") as Style;

                    if ((string.IsNullOrEmpty(NewPassword.Password) ^ string.IsNullOrEmpty(NewPassword_Confirm.Password)) || (string.IsNullOrEmpty(NewPassword.Password) && string.IsNullOrEmpty(NewPassword_Confirm.Password)))
                    {
                        if (string.IsNullOrEmpty(NewPassword.Password))
                        {
                            NewPassword.Style = FindResource("PasswordBox_Error") as Style;
                        }
                        if (string.IsNullOrEmpty(NewPassword_Confirm.Password))
                        {
                            NewPassword_Confirm.Style = FindResource("PasswordBox_Error") as Style;
                        }
                        return;
                    }
                    else
                    {
                        if (NewPassword.Password == NewPassword_Confirm.Password)
                        {
                            Report(ActiveDirectory.SelectedUser.ResetUser(NewPassword.Password), "User Password Reset Successfully");
                        }
                        else
                        {
                            NewPassword_Confirm.Style = FindResource("PasswordBox_Error") as Style;
                            return;
                        }
                    }

                    NewPassword.Password = null;
                    NewPassword_Confirm.Password = null;
                    break;
                case "Disable":
                    Report(ActiveDirectory.SelectedUser.DisableUser(), "User Disabled Successfully");
                    break;
                default:
                    break;
            }

            BackgroundBlur(false);
            WarningBox.Visibility = Visibility.Hidden;
            ConfirmButton.IsEnabled = false;
            CancelButton.IsEnabled = false;

            PasswordInput.Visibility = Visibility.Collapsed;
            Action = null;
        }
        /// <summary>
        /// Cancel the action and return to the default stage
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            BackgroundBlur(false);
            WarningBox.Visibility = Visibility.Hidden;

            ConfirmButton.IsEnabled = false;
            CancelButton.IsEnabled = false;

            PasswordInput.Visibility = Visibility.Collapsed;

            Action = null;
        }
        #endregion Warning Message
        #endregion Control Actions

        #region Event Handlers and Triggers
        /// <summary>
        /// Event handler when AD is no longer connected
        /// </summary>
        public event EventHandler Disconnected;
        /// <summary>
        /// Trigger the Disconnected event handler
        /// </summary>
        private void ExitAD()
        {
            Disconnected(this, new EventArgs());
        }
        #endregion Event Handlers and Triggers
    }
}


text:
#pragma once

/**
 * @file ConverterFunctions.h
 * @ingroup respec
 * Defines several conversion functions between different sample formats.
 */

#include "Audaspace.h"

#include <cstring>

AUD_NAMESPACE_BEGIN

/**
 * The function template for functions converting from one sample format
 * to another, having the same parameter order as std::memcpy.
 */
typedef void (*convert_f)(data_t* target, data_t* source, int length);

/**
 * The copy conversion function simply calls std::memcpy.
 * @param target The target buffer.
 * @param source The source buffer.
 * @param length The amount of samples to be converted.
 */
template <class T>
void convert_copy(data_t* target, data_t* source, int length)
{
	std::memcpy(target, source, length*sizeof(T));
}

/**
 * @brief Converts from FORMAT_U8 to FORMAT_S16.
 * @param target The target buffer.
 * @param source The source buffer.
 * @param length The amount of samples to be converted.
 */
void AUD_API convert_u8_s16(data_t* target, data_t* source, int length);

/**
 * @brief Converts from FORMAT_U8 to FORMAT_S24 big endian.
 * @param target The target buffer.
 * @param source The source buffer.
 * @param length The amount of samples to be converted.
 */
void AUD_API convert_u8_s24_be(data_t* target, data_t* source, int length);

/**
 * @brief Converts from FORMAT_U8 to FORMAT_S24 little endian.
 * @param target The target buffer.
 * @param source The source buffer.
 * @param length The amount of samples to be converted.
 */
void AUD_API convert_u8_s24_le(data_t* target, data_t* source, int length);

/**
 * @brief Converts from FORMAT_U8 to FORMAT_S32.
 * @param target The target buffer.
 * @param source The source buffer.
 * @param length The amount of samples to be converted.
 */
void AUD_API convert_u8_s32(data_t* target, data_t* source, int length);

/**
 * @brief Converts from FORMAT_U8 to FORMAT_FLOAT32.
 * @param target The target buffer.
 * @param source The source buffer.
 * @param length The amount of samples to be converted.
 */
void AUD_API convert_u8_float(data_t* target, data_t* source, int length);

/**
 * @brief Converts from FORMAT_U8 to FORMAT_FLOAT64.
 * @param target The target buffer.
 * @param source The source buffer.
 * @param length The amount of samples to be converted.
 */
void AUD_API convert_u8_double(data_t* target, data_t* source, int length);

/**
 * @brief Converts from FORMAT_S16 to FORMAT_U8.
 * @param target The target buffer.
 * @param source The source buffer.
 * @param length The amount of samples to be converted.
 */
void AUD_API convert_s16_u8(data_t* target, data_t* source, int length);

/**
 * @brief Converts from FORMAT_S16 to FORMAT_S24 big endian.
 * @param target The target buffer.
 * @param source The source buffer.
 * @param length The amount of samples to be converted.
 */
void AUD_API convert_s16_s24_be(data_t* target, data_t* source, int length);

/**
 * @brief Converts from FORMAT_S16 to FORMAT_S24 little endian.
 * @param target The target buffer.
 * @param source The source buffer.
 * @param length The amount of samples to be converted.
 */
void AUD_API convert_s16_s24_le(data_t* target, data_t* source, int length);

/**
 * @brief Converts from FORMAT_S16 to FORMAT_S32.
 * @param target The target buffer.
 * @param source The source buffer.
 * @param length The amount of samples to be converted.
 */
void AUD_API convert_s16_s32(data_t* target, data_t* source, int length);

/**
 * @brief Converts from FORMAT_S16 to FORMAT_FLOAT32.
 * @param target The target buffer.
 * @param source The source buffer.
 * @param length The amount of samples to be converted.
 */
void AUD_API convert_s16_float(data_t* target, data_t* source, int length);

/**
 * @brief Converts from FORMAT_S16 to FORMAT_FLOAT64.
 * @param target The target buffer.
 * @param source The source buffer.
 * @param length The amount of samples to be converted.
 */
void AUD_API convert_s16_double(data_t* target, data_t* source, int length);

/**
 * @brief Converts from FORMAT_S24 big endian to FORMAT_U8.
 * @param target The target buffer.
 * @param source The source buffer.
 * @param length The amount of samples to be converted.
 */
void AUD_API convert_s24_u8_be(data_t* target, data_t* source, int length);

/**
 * @brief Converts from FORMAT_S24 little endian to FORMAT_U8.
 * @param target The target buffer.
 * @param source The source buffer.
 * @param length The amount of samples to be converted.
 */
void AUD_API convert_s24_u8_le(data_t* target, data_t* source, int length);

/**
 * @brief Converts from FORMAT_S24 big endian to FORMAT_S16.
 * @param target The target buffer.
 * @param source The source buffer.
 * @param length The amount of samples to be converted.
 */
void AUD_API convert_s24_s16_be(data_t* target, data_t* source, int length);

/**
 * @brief Converts from FORMAT_S24 little endian to FORMAT_S16.
 * @param target The target buffer.
 * @param source The source buffer.
 * @param length The amount of samples to be converted.
 */
void AUD_API convert_s24_s16_le(data_t* target, data_t* source, int length);

/**
 * @brief Converts from FORMAT_S24 to FORMAT_S24 simply using std::memcpy.
 * @param target The target buffer.
 * @param source The source buffer.
 * @param length The amount of samples to be converted.
 */
void AUD_API convert_s24_s24(data_t* target, data_t* source, int length);

/**
 * @brief Converts from FORMAT_S24 big endian to FORMAT_S32.
 * @param target The target buffer.
 * @param source The source buffer.
 * @param length The amount of samples to be converted.
 */
void AUD_API convert_s24_s32_be(data_t* target, data_t* source, int length);

/**
 * @brief Converts from FORMAT_S24 little endian to FORMAT_S32.
 * @param target The target buffer.
 * @param source The source buffer.
 * @param length The amount of samples to be converted.
 */
void AUD_API convert_s24_s32_le(data_t* target, data_t* source, int length);

/**
 * @brief Converts from FORMAT_S24 big endian to FORMAT_FLOAT32.
 * @param target The target buffer.
 * @param source The source buffer.
 * @param length The amount of samples to be converted.
 */
void AUD_API convert_s24_float_be(data_t* target, data_t* source, int length);

/**
 * @brief Converts from FORMAT_S24 little endian to FORMAT_FLOAT32.
 * @param target The target buffer.
 * @param source The source buffer.
 * @param length The amount of samples to be converted.
 */
void AUD_API convert_s24_float_le(data_t* target, data_t* source, int length);

/**
 * @brief Converts from FORMAT_S24 big endian to FORMAT_FLOAT64.
 * @param target The target buffer.
 * @param source The source buffer.
 * @param length The amount of samples to be converted.
 */
void AUD_API convert_s24_double_be(data_t* target, data_t* source, int length);

/**
 * @brief Converts from FORMAT_S24 little endian to FORMAT_FLOAT64.
 * @param target The target buffer.
 * @param source The source buffer.
 * @param length The amount of samples to be converted.
 */
void AUD_API convert_s24_double_le(data_t* target, data_t* source, int length);

/**
 * @brief Converts from FORMAT_S32 to FORMAT_U8.
 * @param target The target buffer.
 * @param source The source buffer.
 * @param length The amount of samples to be converted.
 */
void AUD_API convert_s32_u8(data_t* target, data_t* source, int length);

/**
 * @brief Converts from FORMAT_S32 to FORMAT_S16.
 * @param target The target buffer.
 * @param source The source buffer.
 * @param length The amount of samples to be converted.
 */
void AUD_API convert_s32_s16(data_t* target, data_t* source, int length);

/**
 * @brief Converts from FORMAT_S32 to FORMAT_S24 big endian.
 * @param target The target buffer.
 * @param source The source buffer.
 * @param length The amount of samples to be converted.
 */
void AUD_API convert_s32_s24_be(data_t* target, data_t* source, int length);

/**
 * @brief Converts from FORMAT_S32 to FORMAT_S24 little endian.
 * @param target The target buffer.
 * @param source The source buffer.
 * @param length The amount of samples to be converted.
 */
void AUD_API convert_s32_s24_le(data_t* target, data_t* source, int length);

/**
 * @brief Converts from FORMAT_S32 to FORMAT_FLOAT32.
 * @param target The target buffer.
 * @param source The source buffer.
 * @param length The amount of samples to be converted.
 */
void AUD_API convert_s32_float(data_t* target, data_t* source, int length);

/**
 * @brief Converts from FORMAT_S32 to FORMAT_FLOAT64.
 * @param target The target buffer.
 * @param source The source buffer.
 * @param length The amount of samples to be converted.
 */
void AUD_API convert_s32_double(data_t* target, data_t* source, int length);

/**
 * @brief Converts from FORMAT_FLOAT32 to FORMAT_U8.
 * @param target The target buffer.
 * @param source The source buffer.
 * @param length The amount of samples to be converted.
 */
void AUD_API convert_float_u8(data_t* target, data_t* source, int length);

/**
 * @brief Converts from FORMAT_FLOAT32 to FORMAT_S16.
 * @param target The target buffer.
 * @param source The source buffer.
 * @param length The amount of samples to be converted.
 */
void AUD_API convert_float_s16(data_t* target, data_t* source, int length);

/**
 * @brief Converts from FORMAT_FLOAT32 to FORMAT_S24 big endian.
 * @param target The target buffer.
 * @param source The source buffer.
 * @param length The amount of samples to be converted.
 */
void AUD_API convert_float_s24_be(data_t* target, data_t* source, int length);

/**
 * @brief Converts from FORMAT_FLOAT32 to FORMAT_S24 little endian.
 * @param target The target buffer.
 * @param source The source buffer.
 * @param length The amount of samples to be converted.
 */
void AUD_API convert_float_s24_le(data_t* target, data_t* source, int length);

/**
 * @brief Converts from FORMAT_FLOAT32 to FORMAT_S32.
 * @param target The target buffer.
 * @param source The source buffer.
 * @param length The amount of samples to be converted.
 */
void AUD_API convert_float_s32(data_t* target, data_t* source, int length);

/**
 * @brief Converts from FORMAT_FLOAT32 to FORMAT_FLOAT64.
 * @param target The target buffer.
 * @param source The source buffer.
 * @param length The amount of samples to be converted.
 */
void AUD_API convert_float_double(data_t* target, data_t* source, int length);

/**
 * @brief Converts from FORMAT_FLOAT64 to FORMAT_U8.
 * @param target The target buffer.
 * @param source The source buffer.
 * @param length The amount of samples to be converted.
 */
void AUD_API convert_double_u8(data_t* target, data_t* source, int length);

/**
 * @brief Converts from FORMAT_FLOAT64 to FORMAT_S16.
 * @param target The target buffer.
 * @param source The source buffer.
 * @param length The amount of samples to be converted.
 */
void AUD_API convert_double_s16(data_t* target, data_t* source, int length);

/**
 * @brief Converts from FORMAT_FLOAT64 to FORMAT_S24 big endian.
 * @param target The target buffer.
 * @param source The source buffer.
 * @param length The amount of samples to be converted.
 */
void AUD_API convert_double_s24_be(data_t* target, data_t* source, int length);

/**
 * @brief Converts from FORMAT_FLOAT64 to FORMAT_S24 little endian.
 * @param target The target buffer.
 * @param source The source buffer.
 * @param length The amount of samples to be converted.
 */
void AUD_API convert_double_s24_le(data_t* target, data_t* source, int length);

/**
 * @brief Converts from FORMAT_FLOAT64 to FORMAT_S32.
 * @param target The target buffer.
 * @param source The source buffer.
 * @param length The amount of samples to be converted.
 */
void AUD_API convert_double_s32(data_t* target, data_t* source, int length);

/**
 * @brief Converts from FORMAT_FLOAT64 to FORMAT_FLOAT32.
 * @param target The target buffer.
 * @param source The source buffer.
 * @param length The amount of samples to be converted.
 */
void AUD_API convert_double_float(data_t* target, data_t* source, int length);

AUD_NAMESPACE_END


text:
NPC::~NPC()
{
    if (m_pAnimation)
    {
        m_pAnimation->clear();
        m_pAnimation->removeFromParentAndCleanup(true);
    }
}

NPC::NPC(int id)
{
    m_pAnimation = NULL;
    m_NpcId = id;
    m_Active = false;
}

int NPC::getId()
{
    return m_NpcId;
}

void NPC::showOnMap(const cocos2d::CCPoint &tilePosition)
{
    if (m_pAnimation)
    {
        m_pAnimation->clear();
        m_pAnimation->removeFromParentAndCleanup(true);
    }

    m_pAnimation = NpcAnimation::create(m_NpcId);
    m_pAnimation->setScale(0.6f);

    CCPoint realTilePos = ccp(tilePosition.x + 0.5, tilePosition.y + 0.5);
    StageMap* pGroundMap = GameScene::getInstance()->sharedGameStage->getGroundMap();
    CCPoint mapGroundPos = MapHelper::tilePosToGroundMapPos(realTilePos);
    m_CurrentMapPosition = MapHelper::tilePosToMapPos(realTilePos.x, realTilePos.y, pGroundMap);
    m_CurrentTilePosition = realTilePos;
    m_GroundMapPosition = MapHelper::tilePosToGroundMapPos(realTilePos);

    m_pAnimation->setPosition(mapGroundPos);
    this->addChild(m_pAnimation);
    m_pAnimation->scheduleUpdate();

    m_pAnimation->setAnimation(ENUM_NPC_ANIMATION_STAND_DOWN);

    m_Active = true;

    this->scheduleUpdate();
}

NPC* NPC::create(int id)
{
    NPC* npc = new NPC(id);

    if (npc && npc->init(id))
    {
        npc->autorelease();
        return npc;
    }

    CC_SAFE_DELETE(npc);

    return NULL;

}

bool NPC::init(int id)
{
    m_pSetting = GameData::getNpcSetting(id);
    m_MaxHp = m_pSetting->maxHp;
    m_Hp = m_pSetting->maxHp;

    return true;
}

CCPoint NPC::getShootPosition()
{
    return m_GroundMapPosition;
}

CCPoint NPC::getAttackablePosition()
{
    return m_GroundMapPosition;
}

void NPC::reduceHp(float damage, bool ignoreDefense)
{
    if (isDead())
    {
        return;
    }

    m_Hp-=damage;
    if (m_Hp < 0)
    {
        m_Hp = 0;
    }
}

void NPC::actWhenAttacked(AttackableObject* pTarget)
{

}

bool NPC::isDead()
{
    return m_Hp <= 0;
}

void NPC::remove()
{

}

bool NPC::isActive()
{
    return m_Active;
}

const CCPoint& NPC::getAttackableMapPosition()
{
    return m_CurrentMapPosition;
}

void NPC::destroy()
{
    if (!isActive())
    {
        return;
    }

    if (m_pAnimation)
    {
        m_pAnimation->clear();
        m_pAnimation->removeFromParentAndCleanup(true);
        m_pAnimation = NULL;
    }

    m_Active = false;
}

bool NPC::ableToAttack()
{
    return false;
}

void NPC::finishAttack()
{

}

float NPC::getDamage()
{
    return 0;
}

float NPC::getAttackRange()
{
    return 0;
}

float NPC::getAttackRate()
{
    return 0;
}

float NPC::getBaseSpeed()
{
    return 0;
}

CCNode* NPC::getAnimationPart()
{
    return m_pAnimation;
}

void NPC::setSpeed(float speed)
{
}