<?php

namespace FOS\UserBundle\Command;

use FOS\UserBundle\Util\UserManipulator;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\Question;

/**
 * @author Antoine Hérault <antoine.herault@gmail.com>
 *
 * @internal
 *
 * @final
 */
#[AsCommand(name: 'fos:user:deactivate', description: 'Deactivate a user')]
class DeactivateUserCommand extends Command
{
    // BC with Symfony <5.3
    protected static $defaultName = 'fos:user:deactivate';

    private $userManipulator;

    public function __construct(UserManipulator $userManipulator)
    {
        parent::__construct();

        $this->userManipulator = $userManipulator;
    }

    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            // BC with Symfony <5.3
            ->setName('fos:user:deactivate')
            ->setDescription('Deactivate a user')
            ->setDefinition([
                new InputArgument('username', InputArgument::REQUIRED, 'The username'),
            ])
            ->setHelp(<<<'EOT'
The <info>fos:user:deactivate</info> command deactivates a user (will not be able to log in)

  <info>php %command.full_name% matthieu</info>
EOT
            );
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $username = $input->getArgument('username');

        $this->userManipulator->deactivate($username);

        $output->writeln(sprintf('User "%s" has been deactivated.', $username));

        return 0;
    }

    /**
     * {@inheritdoc}
     */
    protected function interact(InputInterface $input, OutputInterface $output)
    {
        if (!$input->getArgument('username')) {
            $question = new Question('Please choose a username:');
            $question->setValidator(function ($username) {
                if (empty($username)) {
                    throw new \Exception('Username can not be empty');
                }

                return $username;
            });
            $answer = $this->getHelper('question')->ask($input, $output, $question);

            $input->setArgument('username', $answer);
        }
    }
}


Helium
======

A small 64 bit OS with a micro-kernel.

## Done

1. Read Multiboot Info
    - memory map
    - module table

## Partially Done

2. Setup Page Frame Allocator
    - watermark
    - revisit for more sophisticated implementation

## TODO

3. Setup Virtual Memory Allocator
    - decide where to map paging structures
4. CPU features like I/O Ports, MSRs, etc.
    - may be needed be earlier steps too
5. Parse ACPI and SMP Tables
    - needs virtual memory management (at least for ACPI)
6. Enable I/O APICs and Local APIC of BSP
7. Boot Application Processors
8. Keyboard
9. User Mode processes
10. Virtual Consoles


@implementation PriceBar

@synthesize date = _date;
@synthesize open = _open;
@synthesize high = _high;
@synthesize low = _low;
@synthesize close = _close;
@synthesize volume = _volume;

- (instancetype)initWithOpen:(double)open high:(double)high low:(double)low close:(double)close volume:(long)volume {
    self = [super init];
    if (self) {
        _date = [[NSDate alloc] init];
        _open = open;
        _high = high;
        _low = low;
        _close = close;
        _volume = volume;
    }
    return self;
}

- (instancetype)initWithDate:(NSDate *)date open:(double)open high:(double)high low:(double)low close:(double)close volume:(long)volume {
    self = [super init];
    if (self) {
        _date = date;
        _open = open;
        _high = high;
        _low = low;
        _close = close;
        _volume = volume;
    }
    return self;
}

@end


(function() {
  'use strict';
  if (!navigator.geolocation) { alert('Cannot use geolocation'); return; }

  var success = function(pos) {
    console.log(pos.coords);
    var info = '緯度:' + pos.coords.latitude + '
' +
               '経度:' + pos.coords.longitude + '
';
    console.log(info);
    document.getElementById('current_info').innerHTML = info;
  };

  var error = function(err) {
    alert('ERROR! (' + err.code + ' : ' + err.message + ')');
  };

  navigator.geolocation.getCurrentPosition(success, error);

}).call(this);


import { SessionApitype } from './../apitypes/Session.apitype';
import { Injectable } from '@angular/core';

@Injectable()
export class StateService {

    private _isLoggedIn = false;
    get isLoggedIn(): boolean {
        return this._isLoggedIn;
    }
    set isLoggedIn(_isLoggedIn: boolean) {
        this._isLoggedIn = _isLoggedIn;
        this.saveLocalStorage();
    }

    private _isAdmin = false;
    get isAdmin(): boolean {
        return this._isAdmin;
    }
    set isAdmin(_isAdmin: boolean) {
        this._isAdmin = _isAdmin;
        this.saveLocalStorage();
    }

    private _apiToken: string = null;
    get apiToken(): string {
        return this._apiToken;
    }
    set apiToken(_apiToken: string) {
        this._apiToken = _apiToken;
        this.saveLocalStorage();
    }

    private _isNative = false;
    get isNative(): boolean {
        return this._isNative;
    }
    set isNative(_isNative: boolean) {
        this._isNative = _isNative;
        this.saveLocalStorage();
    }

    private _pageSize = 25;
    get pageSize(): number {
        return this._pageSize;
    }
    set pageSize(_pageSize: number) {
        this._pageSize = _pageSize;
        this.saveLocalStorage();
    }

    private _pageSizes = [5, 10, 25, 50, 100];
    get pageSizes(): Array<number> {
        return this._pageSizes;
    }

    private _recordTypes = [
        'A', 'A6', 'AAAA', 'AFSDB', 'ALIAS', 'CAA', 'CDNSKEY', 'CDS', 'CERT', 'CNAME', 'DHCID',
        'DLV', 'DNAME', 'DNSKEY', 'DS', 'EUI48', 'EUI64', 'HINFO',
        'IPSECKEY', 'KEY', 'KX', 'LOC', 'LUA', 'MAILA', 'MAILB', 'MINFO', 'MR',
        'MX', 'NAPTR', 'NS', 'NSEC', 'NSEC3', 'NSEC3PARAM', 'OPENPGPKEY',
        'OPT', 'PTR', 'RKEY', 'RP', 'RRSIG', 'SIG', 'SPF',
        'SRV', 'TKEY', 'SSHFP', 'TLSA', 'TSIG', 'TXT', 'WKS', 'MBOXFW', 'URL'
    ];
    get recordTypes(): Array<string> {
        return this._recordTypes;
    }

    constructor() {
        this.loadLocalStorage();
    }

    private saveLocalStorage() {
        localStorage.setItem('pdnsmanagerstate', JSON.stringify(this));
    }

    private loadLocalStorage() {
        Object.assign(this, JSON.parse(localStorage.getItem('pdnsmanagerstate')));
    }
}


using System.IO;
using Goedel.Mesh.Shell;
using Goedel.Cryptography;
using MT=Microsoft.VisualStudio.TestTools.UnitTesting;
using Goedel.Test;

namespace Goedel.Catalog.Test {
    [MT.TestClass]
    public partial class CatalogTests {
        static string ResultDirectory;
        static string ContainerDirectory = "Shells";

        const string DirectorySource = "Files";
        const string DirectoryEncrypted = "Encrypted";
        const string DirectoryDecrypted = "Decrypted";

        const string DirectoryTarget = "Target";
        string Target(string File) => DirectoryTarget + @"\" + File;

        const string DirectoryArchive = "Archive";
        const string DirectoryArchiveCopy = "ArchiveCopy";
        string Archive(string File) => DirectoryArchive + @"\" + File;

        const string FileTest1 = @"PHBLogo1.svg";
        const string FileTest2 = @"PHBLogo1.svg";
        const string FileTest3 = @"PHBLogo180.png";
        const string FileTest4 = @"PHBLogo256.ico";
        const string FileTest5 = @"PHBLogo256.png";

        /// <summary>
        ///
        /// </summary>
        public static void TestDirect() {
            InitializeClass();
            var Instance = new CatalogTests();
            //Instance.TestBasicCalendar();
            //Instance.TestContainerSerial();
            Instance.TestContainerArchiveBase();
            //Instance.TestBasicBookMark();
            //Instance.TestBasicCredential();
            }

        static ShellDispatch ShellDispatchCommon;

        [MT.AssemblyInitialize]
        public static void InitializeClass(MT.TestContext Context) {
            ResultDirectory = Context.TestRunDirectory;
            Directory.SetCurrentDirectory(Directories.RunDirectoryFramework);

            InitializeClass();
            }

        public static void InitializeClass() {

            Directory.CreateDirectory(ContainerDirectory);
            Directory.CreateDirectory(DirectoryEncrypted);
            Directory.CreateDirectory(DirectoryDecrypted);
            Directory.CreateDirectory(DirectoryTarget);
            Directory.CreateDirectory(DirectoryArchive);
            CryptographyWindows.Initialize();

            ShellDispatchCommon = GetShell("TestFile.dcon");
            // OK so here create ourselves a set of test keys for encryption and signature

            }

        static ShellDispatch GetShell(string Filename) {
            Filename = ContainerDirectory + @"\" + Filename;

            File.Delete(Filename);
            return new ShellDispatch(Catalog: Filename);
            }
        }

    }


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<title>Minim : : AudioSample : : mute</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link href="stylesheet.css" rel="stylesheet" type="text/css">

    	Minim

    		core |
    		ugens |
    		analysis

Controller

mute

Description

    	Mutes the sound.

Signature

void mute()

Returns

None

Related

    	unmute ( )

isMuted ( )

Example

None available

Usage

    	Web & Application


// This code is auto-generated, do not modify
package com.spectralogic.ds3client.commands.parsers;

import com.spectralogic.ds3client.commands.parsers.interfaces.AbstractResponseParser;
import com.spectralogic.ds3client.commands.parsers.utils.ResponseParserUtils;
import com.spectralogic.ds3client.commands.spectrads3.notifications.GetPoolFailureNotificationRegistrationSpectraS3Response;
import com.spectralogic.ds3client.models.PoolFailureNotificationRegistration;
import com.spectralogic.ds3client.networking.WebResponse;
import com.spectralogic.ds3client.serializer.XmlOutput;
import java.io.IOException;
import java.io.InputStream;

public class GetPoolFailureNotificationRegistrationSpectraS3ResponseParser extends AbstractResponseParser<GetPoolFailureNotificationRegistrationSpectraS3Response> {
    private final int[] expectedStatusCodes = new int[]{200};

    @Override
    public GetPoolFailureNotificationRegistrationSpectraS3Response parseXmlResponse(final WebResponse response) throws IOException {
        final int statusCode = response.getStatusCode();
        if (ResponseParserUtils.validateStatusCode(statusCode, expectedStatusCodes)) {
            switch (statusCode) {
            case 200:
                try (final InputStream inputStream = response.getResponseStream()) {
                    final PoolFailureNotificationRegistration result = XmlOutput.fromXml(inputStream, PoolFailureNotificationRegistration.class);
                    return new GetPoolFailureNotificationRegistrationSpectraS3Response(result, this.getChecksum(), this.getChecksumType());
                }

            default:
                assert false: "validateStatusCode should have made it impossible to reach this line";
            }
        }

        throw ResponseParserUtils.createFailedRequest(response, expectedStatusCodes);
    }
}


package com.google.errorprone.refaster;

import com.google.auto.value.AutoValue;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.collect.Iterables;
import com.google.errorprone.refaster.ControlFlowVisitor.Result;
import com.sun.source.tree.IfTree;
import com.sun.source.tree.StatementTree;
import com.sun.source.tree.TreeVisitor;
import com.sun.tools.javac.tree.JCTree.JCStatement;
import com.sun.tools.javac.util.List;
import javax.annotation.Nullable;

/**
 * {@link UTree} representation of an {@link IfTree}.
 *
 * @author lowasser@google.com (Louis Wasserman)
 */
@AutoValue
abstract class UIf implements UStatement, IfTree {
  public static UIf create(
      UExpression condition, UStatement thenStatement, UStatement elseStatement) {
    return new AutoValue_UIf(condition, thenStatement, elseStatement);
  }

  @Override
  public abstract UExpression getCondition();

  @Override
  public abstract UStatement getThenStatement();

  @Override
  @Nullable
  public abstract UStatement getElseStatement();

  @Override
  public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
    return visitor.visitIf(this, data);
  }

  @Override
  public Kind getKind() {
    return Kind.IF;
  }

  private static Function<Unifier, Choice<Unifier>> unifyUStatementWithSingleStatement(
      @Nullable final UStatement toUnify, @Nullable final StatementTree target) {
    return (Unifier unifier) -> {
      if (toUnify == null) {
        return (target == null) ? Choice.of(unifier) : Choice.<Unifier>none();
      }
      List<StatementTree> list = (target == null) ? List.<StatementTree>nil() : List.of(target);
      return toUnify
          .apply(UnifierWithUnconsumedStatements.create(unifier, list))
          .condition(s -> s.unconsumedStatements().isEmpty())
          .transform(UnifierWithUnconsumedStatements::unifier);
    };
  }

  @Override
  @Nullable
  public Choice<UnifierWithUnconsumedStatements> apply(UnifierWithUnconsumedStatements state) {
    java.util.List<? extends StatementTree> unconsumedStatements = state.unconsumedStatements();
    if (unconsumedStatements.isEmpty()) {
      return Choice.none();
    }
    final java.util.List<? extends StatementTree> unconsumedStatementsTail =
        unconsumedStatements.subList(1, unconsumedStatements.size());
    StatementTree firstStatement = unconsumedStatements.get(0);
    if (firstStatement.getKind() != Kind.IF) {
      return Choice.none();
    }
    final IfTree ifTree = (IfTree) firstStatement;
    Unifier unifier = state.unifier();
    Choice<UnifierWithUnconsumedStatements> forwardMatch =
        getCondition()
            .unify(ifTree.getCondition(), unifier.fork())
            .thenChoose(
                unifyUStatementWithSingleStatement(getThenStatement(), ifTree.getThenStatement()))
            .thenChoose(
                unifierAfterThen -> {
                  if (getElseStatement() != null
                      && ifTree.getElseStatement() == null
                      && ControlFlowVisitor.INSTANCE.visitStatement(ifTree.getThenStatement())
                          == Result.ALWAYS_RETURNS) {
                    Choice<UnifierWithUnconsumedStatements> result =
                        getElseStatement()
                            .apply(
                                UnifierWithUnconsumedStatements.create(
                                    unifierAfterThen.fork(), unconsumedStatementsTail));
                    if (getElseStatement() instanceof UBlock) {
                      Choice<UnifierWithUnconsumedStatements> alternative =
                          Choice.of(
                              UnifierWithUnconsumedStatements.create(
                                  unifierAfterThen.fork(), unconsumedStatementsTail));
                      for (UStatement stmt : ((UBlock) getElseStatement()).getStatements()) {
                        alternative = alternative.thenChoose(stmt);
                      }
                      result = result.or(alternative);
                    }
                    return result;
                  } else {
                    return unifyUStatementWithSingleStatement(
                            getElseStatement(), ifTree.getElseStatement())
                        .apply(unifierAfterThen)
                        .transform(
                            unifierAfterElse ->
                                UnifierWithUnconsumedStatements.create(
                                    unifierAfterElse, unconsumedStatementsTail));
                  }
                });
    Choice<UnifierWithUnconsumedStatements> backwardMatch =
        getCondition()
            .negate()
            .unify(ifTree.getCondition(), unifier.fork())
            .thenChoose(
                unifierAfterCond -> {
                  if (getElseStatement() == null) {
                    return Choice.none();
                  }
                  return getElseStatement()
                      .apply(
                          UnifierWithUnconsumedStatements.create(
                              unifierAfterCond, List.of(ifTree.getThenStatement())))
                      .thenOption(
                          (UnifierWithUnconsumedStatements stateAfterThen) ->
                              stateAfterThen.unconsumedStatements().isEmpty()
                                  ? Optional.of(stateAfterThen.unifier())
                                  : Optional.<Unifier>absent());
                })
            .thenChoose(
                unifierAfterThen -> {
                  if (ifTree.getElseStatement() == null
                      && ControlFlowVisitor.INSTANCE.visitStatement(ifTree.getThenStatement())
                          == Result.ALWAYS_RETURNS) {
                    Choice<UnifierWithUnconsumedStatements> result =
                        getThenStatement()
                            .apply(
                                UnifierWithUnconsumedStatements.create(
                                    unifierAfterThen.fork(), unconsumedStatementsTail));
                    if (getThenStatement() instanceof UBlock) {
                      Choice<UnifierWithUnconsumedStatements> alternative =
                          Choice.of(
                              UnifierWithUnconsumedStatements.create(
                                  unifierAfterThen.fork(), unconsumedStatementsTail));
                      for (UStatement stmt : ((UBlock) getThenStatement()).getStatements()) {
                        alternative = alternative.thenChoose(stmt);
                      }
                      result = result.or(alternative);
                    }
                    return result;
                  } else {
                    return unifyUStatementWithSingleStatement(
                            getThenStatement(), ifTree.getElseStatement())
                        .apply(unifierAfterThen)
                        .transform(
                            unifierAfterElse ->
                                UnifierWithUnconsumedStatements.create(
                                    unifierAfterElse, unconsumedStatementsTail));
                  }
                });
    return forwardMatch.or(backwardMatch);
  }

  @Override
  public List<JCStatement> inlineStatements(Inliner inliner) throws CouldNotResolveImportException {
    return List.<JCStatement>of(
        inliner
            .maker()
            .If(
                getCondition().inline(inliner),
                Iterables.getOnlyElement(getThenStatement().inlineStatements(inliner)),
                (getElseStatement() == null)
                    ? null
                    : Iterables.getOnlyElement(getElseStatement().inlineStatements(inliner))));
  }
}


'use strict';

const expect        = require('../../helpers/expect');

const WriteImages   = require('../../../src/utils/write-images');

const fs            = require('fs');
const sizeOf        = require('image-size');
const _forOwn       = require('lodash').forOwn;

describe('WriteImages', function() {
  // Hitting the file system is slow
  this.timeout(0);

  before(() => {
    if (!fs.existsSync('tmp')) fs.mkdirSync('tmp');
  });

  context('when source, projectPath, dest, and platformSizes', () => {
    const source = 'node-tests/fixtures/icon.svg';
    const projectPath = 'tmp';
    const dest = 'icons';
    const platformSizes = {
      ios: {
        sizeKey: 'width',
        sizes: [
          {
            size: 57,
            id: 'icon'
          }
        ]
      }
    };
    let subject;

    before(() => {
      subject = WriteImages({
        source: source,
        projectPath: projectPath,
        dest: dest,
        platformSizes: platformSizes
      });
    });

    after(() => {
      platformSizes['ios'].sizes.forEach((rasterize) =>  {
        fs.unlinkSync(`${projectPath}/${rasterize.path}`);
      });
    });

    it('resolves to platform sizes updated with paths', (done) => {
      subject.then((updatedPlatformSizes) => {
        try {
          _forOwn(updatedPlatformSizes, (icons, platform) => {
            icons.sizes.map((size) => {
              const path = `${dest}/${platform}/${size.id}.png`;
              expect(size.path).to.equal(path);
            });
          });
          done();
        } catch(e) {
          done(e);
        }
      });
    });

    it('writes the files to rasterize at the right size', (done) => {
      subject.then((updatedPlatformSizes) => {
        try {
          updatedPlatformSizes['ios'].sizes.forEach((rasterize) => {
            const writePath = `${projectPath}/${rasterize.path}`;
            expect(fs.existsSync(writePath)).to.equal(true);
            expect(sizeOf(writePath).width).to.equal(rasterize.size);
            expect(sizeOf(writePath).height).to.equal(rasterize.size);
          });
          done();
        } catch(e) {
          done(e);
        }
      });
    });
  });
});


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sun-web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Application Server 9.0 Servlet 2.5//EN" "http://www.sun.com/software/appserver/dtds/sun-web-app_2_5-0.dtd">
<sun-web-app error-url="">
  <context-root>/Gateway/AdminDistribution/2_0</context-root>
  <class-loader delegate="false"/>
  <jsp-config>
    <property name="keepgenerated" value="true">
      <description>Keep a copy of the generated servlet class' java code.</description>
    </property>
  </jsp-config>
</sun-web-app>


//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace GRA.SRP.ControlRoom.Modules.Setup {

    public partial class SurveyEmbedCode {

        /// <summary>
        /// SID control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.DropDownList SID;

        /// <summary>
        /// DDSourceType control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.DropDownList DDSourceType;

        /// <summary>
        /// IWidth control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox IWidth;

        /// <summary>
        /// revIWidth control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.RegularExpressionValidator revIWidth;

        /// <summary>
        /// rvIWidth control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.RangeValidator rvIWidth;

        /// <summary>
        /// DDSourceID control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.DropDownList DDSourceID;

        /// <summary>
        /// IHeight control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox IHeight;

        /// <summary>
        /// RegularExpressionValidator1 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.RegularExpressionValidator RegularExpressionValidator1;

        /// <summary>
        /// RangeValidator1 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.RangeValidator RangeValidator1;

        /// <summary>
        /// btnFilter control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button btnFilter;

        /// <summary>
        /// btnFilter0 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button btnFilter0;

        /// <summary>
        /// odsDDSurveys control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.ObjectDataSource odsDDSurveys;

        /// <summary>
        /// pnlResults control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Panel pnlResults;

        /// <summary>
        /// lblInfo control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label lblInfo;

        /// <summary>
        /// txtResults control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox txtResults;
    }
}


/**
 * Module dependencies
 */

var _ = require('lodash')
  , util = require('util');

/**
 * Sort the tuples in `data` using `comparator`.
 *
 * @param  { Object[] }  data
 * @param  { Object }    comparator
 * @return { Object[] }
 */
module.exports = function (data, comparator) {
  if( !comparator || !data ) return data;
  return sortData(_.clone(data), comparator);
};

//////////////////////////
///
/// private methods   ||
///                   \/
///
//////////////////////////

/**
 * Sort `data` (tuples) using `sortCriteria` (comparator)
 *
 * Based on method described here:
 * http://stackoverflow.com/a/4760279/909625
 *
 * @param  { Object[] } data         [tuples]
 * @param  { Object }   sortCriteria [mongo-style comparator object]
 * @return { Object[] }
 */

function sortData(data, sortCriteria) {

  function dynamicSort(property) {
    var sortOrder = 1;
    if(property[0] === '-') {
      sortOrder = -1;
      property = property.substr(1);
    }

    return function (a,b) {
      var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
      return result * sortOrder;
    };
  }

  function dynamicSortMultiple() {
    var props = arguments;
    return function (obj1, obj2) {
      var i = 0, result = 0, numberOfProperties = props.length;

      while(result === 0 && i < numberOfProperties) {
        result = dynamicSort(props[i])(obj1, obj2);
        i++;
      }
      return result;
    };
  }

  // build sort criteria in the format ['firstName', '-lastName']
  var sortArray = [];
  _.each(_.keys(sortCriteria), function(key) {
    if(sortCriteria[key] === -1) sortArray.push('-' + key.toLowerCase());
    else sortArray.push(key.toLowerCase());
  });

  data.sort(dynamicSortMultiple.apply(null, sortArray));
  return data;
}


module Typingtutor
  class Stats
    FILE = File.expand_path('~/.typingtutor')

    def initialize
      @stats = {}
      @stats.merge!(YAML.load(IO.read(FILE))) if File.exists?(FILE)
      @stats[:created_at] ||= Time.now
      @stats[:total] ||= {}
      @stats[:exercises]  ||= {}
      @stats[:words] ||= {}
      @stats[:letters] ||= {}
    end

    def save
      @stats[:updated_at] = Time.now
      IO.write(FILE, YAML.dump(@stats))
    end

    def record_exercise(exercise)
      @stats[:exercises][exercise.name] ||= {}
      @stats[:exercises][exercise.name][:runs] ||= 0
      @stats[:exercises][exercise.name][:runs] += 1
      @stats[:exercises][exercise.name][:last_run] = Time.now
      @stats[:exercises][exercise.name][:last_run_results] = exercise.results

      # update totals
      @stats[:total][:runs] ||= 0
      @stats[:total][:runs] += 1

      [:time, :chars, :correct_chars, :words, :keystrokes].each do |metric|
        @stats[:total][metric] ||= 0
        @stats[:total][metric] += exercise.results[metric]
      end

      @stats[:total][:max_wpm] ||= 0
      @stats[:total][:max_wpm] = [@stats[:total][:max_wpm], exercise.results[:gross_wpm]].max
      @stats[:total][:avg_wpm] = @stats[:total][:words] / (@stats[:total][:time] / 60)
    end

    def record_word(word)
      # TODO
    end

    def record_letter(letter, ok)
      return if letter == ' '
      @stats[:letters][letter] ||= {}
      @stats[:letters][letter][:total] ||= {}
      @stats[:letters][letter][:total][:count] ||= 0
      @stats[:letters][letter][:total][:count] += 1
      @stats[:letters][letter][:total][:correct] ||= 0
      @stats[:letters][letter][:total][:correct] += 1 if ok
      @stats[:letters][letter][:total][:accuracy] = (@stats[:letters][letter][:total][:correct].to_f / @stats[:letters][letter][:total][:count].to_f * 100).round
    end

    def print
      puts "------------------------"
      puts "Your avg speed: #{@stats[:total][:avg_wpm].round} wpm"
      puts "Your max speed: #{@stats[:total][:max_wpm].round} wpm"
    end

    def print_full
      puts "Accuracy per letter:"
      worst_letters.each {|letter, accuracy| puts "#{letter}: #{accuracy.round}%"}

      if @stats[:exercises].size > 0
        puts
        puts "Exercises:"
        @stats[:exercises].each do |name, data|
          puts "- #{name}: #{data[:runs]} runs, #{data[:last_run_results][:gross_wpm].round} wpm"
        end
      end
      puts
      puts "Exercises played: #{@stats[:total][:runs] || 0}"
      puts "Time played: #{(@stats[:total][:time] || 0).round.divmod(60).join('m ')}s"
      puts "Avg speed: #{(@stats[:total][:avg_wpm] || 0).round} wpm"
      puts "Max speed: #{(@stats[:total][:max_wpm] || 0).round} wpm"
    end

    def worst_letters
      accuracy = @stats[:letters].map {|letter, data| [letter, data[:total][:accuracy]]}.to_h # { "a" => 100, "b" => 98 }
      accuracy.reject! {|key, value| value == 100}
      accuracy.reject! {|key, value| key !~ /\w/ }
      accuracy = accuracy.sort_by {|key, value| value }.to_h
      accuracy
    end
  end
end


require 'cloud_formation/bridge/request'
require 'cloud_formation/bridge/names'
require 'cloud_formation/bridge/resources/elasti_cache_replication_group'

describe CloudFormation::Bridge::Resources::ElastiCacheReplicationGroup do

  include FileSupport

  FIELDS = CloudFormation::Bridge::Names::FIELDS
  ELASTI_CACHE = CloudFormation::Bridge::Names::ELASTI_CACHE

  let(:replication_group_id) { "dev-redis-rep" }

  def stub_describe_replication_group
    expect(subject.client).to receive(:describe_replication_groups).
                                with(replication_group_id: replication_group_id).
                                and_return(parse_json("describe-replication-group-primary-only"))
  end

  context "#create" do

    let(:request) { CloudFormation::Bridge::Request.new(parse_json("create-replication-group-message", false)) }

    it 'creates the replication group' do
      expect(subject.client).to receive(:create_replication_group).with(
                                  replication_group_id: replication_group_id,
                                  primary_cluster_id: "cluster-id-here",
                                  replication_group_description: "Sample replication group for the redis instances",
                                )

      stub_describe_replication_group

      outputs = subject.create(request)

      expect(outputs).to eq(
                           FIELDS::DATA => {
                             ELASTI_CACHE::REPLICATION_GROUP_ID => replication_group_id,
                           },
                           FIELDS::PHYSICAL_RESOURCE_ID => replication_group_id,
                         )
    end

  end

  context "#delete" do

    let(:request) { CloudFormation::Bridge::Request.new(parse_json("delete-replication-group-message", false)) }

    it 'should delete the group' do
      stub_describe_replication_group
      expect(subject.client).to receive(:delete_replication_group).with(
                                  replication_group_id: replication_group_id,
                                  retain_primary_cluster: true,
                                )
      subject.delete(request)
    end

    it 'should ignore if the replication group does not exist' do
      expect(subject).to receive(:replication_group_available?).and_raise(AWS::ElastiCache::Errors::ReplicationGroupNotFoundFault)
      expect { subject.delete(request) }.not_to raise_error
    end

  end

end


package com.thoughtworks.go.config;

import com.thoughtworks.go.config.helper.ValidationContextMother;
import com.thoughtworks.go.config.policy.Allow;
import com.thoughtworks.go.config.policy.Policy;
import com.thoughtworks.go.config.policy.SupportedAction;
import com.thoughtworks.go.domain.config.ConfigurationKey;
import com.thoughtworks.go.domain.config.ConfigurationProperty;
import com.thoughtworks.go.domain.config.ConfigurationValue;
import com.thoughtworks.go.plugin.access.authorization.AuthorizationMetadataStore;
import com.thoughtworks.go.plugin.api.info.PluginDescriptor;
import com.thoughtworks.go.plugin.domain.authorization.AuthorizationPluginInfo;
import com.thoughtworks.go.plugin.domain.authorization.SupportedAuthType;
import com.thoughtworks.go.plugin.domain.common.Metadata;
import com.thoughtworks.go.plugin.domain.common.PluggableInstanceSettings;
import com.thoughtworks.go.plugin.domain.common.PluginConfiguration;
import com.thoughtworks.go.security.CryptoException;
import com.thoughtworks.go.security.GoCipher;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;

import static com.thoughtworks.go.config.policy.SupportedEntity.ENVIRONMENT;
import static java.util.Arrays.asList;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class PluginRoleConfigTest {
    @AfterEach
    public void teardown() {
        AuthorizationMetadataStore.instance().clear();
    }

    @Test
    public void validate_shouldValidatePresenceOfRoleName() {
        validatePresenceOfRoleName(new Validator() {
            @Override
            public void validate(PluginRoleConfig pluginRoleConfig, ValidationContext context) {
                pluginRoleConfig.validate(context);
            }
        });
    }

    @Test
    public void validate_shouldValidateNullRoleName() {
        validateNullRoleName(new Validator() {
            @Override
            public void validate(PluginRoleConfig pluginRoleConfig, ValidationContext context) {
                pluginRoleConfig.validate(context);
            }
        });
    }

    @Test
    public void validate_presenceAuthConfigId() {
        validatePresenceAuthConfigId(new Validator() {
            @Override
            public void validate(PluginRoleConfig pluginRoleConfig, ValidationContext context) {
                pluginRoleConfig.validate(context);
            }
        });
    }

    @Test
    public void validate_presenceOfAuthConfigIdInSecurityConfig() throws Exception {
        validatePresenceOfAuthConfigIdInSecurityConfig(new Validator() {
            @Override
            public void validate(PluginRoleConfig pluginRoleConfig, ValidationContext context) {
                pluginRoleConfig.validate(context);
            }
        });
    }

    @Test
    public void validate_uniquenessOfRoleName() throws Exception {
        validateUniquenessOfRoleName(new Validator() {
            @Override
            public void validate(PluginRoleConfig pluginRoleConfig, ValidationContext context) {
                pluginRoleConfig.validate(context);
            }
        });
    }

    @Test
    public void validateTree_shouldValidatePresenceOfRoleName() {
        validatePresenceOfRoleName(new Validator() {
            @Override
            public void validate(PluginRoleConfig pluginRoleConfig, ValidationContext context) {
                assertFalse(pluginRoleConfig.validateTree(context));
            }
        });
    }

    @Test
    public void validateTree_shouldValidateNullRoleName() {
        validateNullRoleName(new Validator() {
            @Override
            public void validate(PluginRoleConfig pluginRoleConfig, ValidationContext context) {
                pluginRoleConfig.validateTree(context);
            }
        });
    }

    @Test
    public void validateTree_presenceAuthConfigId() {
        validatePresenceAuthConfigId(new Validator() {
            @Override
            public void validate(PluginRoleConfig pluginRoleConfig, ValidationContext context) {
                assertFalse(pluginRoleConfig.validateTree(context));
            }
        });
    }

    @Test
    public void validateTree_presenceOfAuthConfigIdInSecurityConfig() throws Exception {
        validatePresenceOfAuthConfigIdInSecurityConfig(new Validator() {
            @Override
            public void validate(PluginRoleConfig pluginRoleConfig, ValidationContext context) {
                assertFalse(pluginRoleConfig.validateTree(context));
            }
        });
    }

    @Test
    public void validateTree_uniquenessOfRoleName() throws Exception {
        validateUniquenessOfRoleName(new Validator() {
            @Override
            public void validate(PluginRoleConfig pluginRoleConfig, ValidationContext context) {
                assertFalse(pluginRoleConfig.validateTree(context));
            }
        });
    }

    @Test
    public void hasErrors_shouldBeTrueIfRoleHasErrors() throws Exception {
        Role role = new PluginRoleConfig("", "auth_config_id");

        SecurityConfig securityConfig = new SecurityConfig();
        securityConfig.securityAuthConfigs().add(new SecurityAuthConfig("auth_config_id", "plugin_id"));

        role.validate(ValidationContextMother.validationContext(securityConfig));

        assertTrue(role.hasErrors());
    }

    @Test
    public void hasErrors_shouldBeTrueIfConfigurationPropertiesHasErrors() throws Exception {
        ConfigurationProperty property = new ConfigurationProperty(new ConfigurationKey("username"), new ConfigurationValue("view"));
        PluginRoleConfig roleConfig = new PluginRoleConfig("admin", "auth_id", property);

        property.addError("username", "username format is incorrect");

        assertTrue(roleConfig.hasErrors());
        assertTrue(roleConfig.errors().isEmpty());
    }

    @Test
    public void shouldAnswerWhetherItHasPermissionsForGivenEntityOfTypeAndName() {
        final Policy directives = new Policy();
        directives.add(new Allow("view", ENVIRONMENT.getType(), "env_1"));
        RoleConfig role = new RoleConfig(new CaseInsensitiveString(""), new Users(), directives);

        assertTrue(role.hasPermissionsFor(SupportedAction.VIEW, EnvironmentConfig.class, "env_1"));
        assertFalse(role.hasPermissionsFor(SupportedAction.VIEW, EnvironmentConfig.class, "env_2"));
        assertFalse(role.hasPermissionsFor(SupportedAction.VIEW, PipelineConfig.class, "*"));
    }

    private void validatePresenceOfRoleName(Validator v) {
        PluginRoleConfig role = new PluginRoleConfig("", "auth_config_id");

        SecurityConfig securityConfig = new SecurityConfig();
        securityConfig.securityAuthConfigs().add(new SecurityAuthConfig("auth_config_id", "plugin_id"));

        v.validate(role, ValidationContextMother.validationContext(securityConfig));

        assertTrue(role.hasErrors());
        assertThat(role.errors().size(), is(1));
        assertThat(role.errors().get("name").get(0), is("Invalid role name name ''. This must be alphanumeric and can" +
                " contain underscores and periods (however, it cannot start with a period). The maximum allowed length is 255 characters."));
    }

    private void validateNullRoleName(Validator v) {
        PluginRoleConfig role = new PluginRoleConfig("", "auth_config_id");
        role.setName(null);

        SecurityConfig securityConfig = new SecurityConfig();
        securityConfig.securityAuthConfigs().add(new SecurityAuthConfig("auth_config_id", "plugin_id"));

        v.validate(role, ValidationContextMother.validationContext(securityConfig));

        assertTrue(role.hasErrors());
        assertThat(role.errors().size(), is(1));
        assertThat(role.errors().get("name").get(0), is("Invalid role name name 'null'. This must be alphanumeric and can" +
                " contain underscores and periods (however, it cannot start with a period). The maximum allowed length is 255 characters."));
    }

    public void validatePresenceAuthConfigId(Validator v) {
        PluginRoleConfig role = new PluginRoleConfig("admin", "");

        SecurityConfig securityConfig = new SecurityConfig();

        v.validate(role, ValidationContextMother.validationContext(securityConfig));

        assertThat(role.errors().size(), is(1));
        assertThat(role.errors().get("authConfigId").size(), is(1));
        assertThat(role.errors().get("authConfigId").get(0), is("Invalid plugin role authConfigId name ''. This must be alphanumeric and can" +
                " contain underscores and periods (however, it cannot start with a period). The maximum allowed length is 255 characters."));
    }

    public void validatePresenceOfAuthConfigIdInSecurityConfig(Validator v) throws Exception {
        PluginRoleConfig role = new PluginRoleConfig("admin", "auth_config_id");
        SecurityConfig securityConfig = new SecurityConfig();

        v.validate(role, ValidationContextMother.validationContext(securityConfig));

        assertThat(role.errors().size(), is(1));
        assertThat(role.errors().get("authConfigId").size(), is(1));
        assertThat(role.errors().get("authConfigId").get(0), is("No such security auth configuration present for id: `auth_config_id`"));
    }

    public void validateUniquenessOfRoleName(Validator v) throws Exception {
        PluginRoleConfig role = new PluginRoleConfig("admin", "auth_config_id");
        SecurityConfig securityConfig = new SecurityConfig();
        ValidationContext validationContext = ValidationContextMother.validationContext(securityConfig);

        securityConfig.securityAuthConfigs().add(new SecurityAuthConfig("auth_config_id", "plugin_id"));
        securityConfig.getRoles().add(new RoleConfig(new CaseInsensitiveString("admin")));
        securityConfig.getRoles().add(role);

        v.validate(role, validationContext);

        assertThat(role.errors().size(), is(1));
        assertThat(role.errors().get("name").get(0), is("Role names should be unique. Role with the same name exists."));
    }

    @Test
    public void shouldEncryptSecurePluginProperties() throws CryptoException {
        setAuthorizationPluginInfo();
        String authConfigId = "auth_config_id";
        String pluginId = "cd.go.github";

        BasicCruiseConfig basicCruiseConfig = new BasicCruiseConfig();
        basicCruiseConfig.server().security().securityAuthConfigs().add(new SecurityAuthConfig(authConfigId, pluginId));
        PluginRoleConfig role = new PluginRoleConfig("admin", authConfigId);
        role.addConfigurations(asList(
                new ConfigurationProperty(new ConfigurationKey("k1"), new ConfigurationValue("pub_v1")),
                new ConfigurationProperty(new ConfigurationKey("k2"), new ConfigurationValue("pub_v2")),
                new ConfigurationProperty(new ConfigurationKey("k3"), new ConfigurationValue("pub_v3"))));

        GoCipher goCipher = new GoCipher();

        assertThat(role.getProperty("k1").getEncryptedValue(), is(nullValue()));
        assertThat(role.getProperty("k1").getConfigValue(), is("pub_v1"));
        assertThat(role.getProperty("k1").getValue(), is("pub_v1"));
        assertThat(role.getProperty("k2").getEncryptedValue(), is(nullValue()));
        assertThat(role.getProperty("k2").getConfigValue(), is("pub_v2"));
        assertThat(role.getProperty("k2").getValue(), is("pub_v2"));
        assertThat(role.getProperty("k3").getEncryptedValue(), is(nullValue()));
        assertThat(role.getProperty("k3").getConfigValue(), is("pub_v3"));
        assertThat(role.getProperty("k3").getValue(), is("pub_v3"));

        role.encryptSecureProperties(basicCruiseConfig);

        assertThat(role.getProperty("k1").getEncryptedValue(), is(goCipher.encrypt("pub_v1")));
        assertThat(role.getProperty("k1").getConfigValue(), is(nullValue()));
        assertThat(role.getProperty("k1").getValue(), is("pub_v1"));
        assertThat(role.getProperty("k2").getEncryptedValue(), is(nullValue()));
        assertThat(role.getProperty("k2").getConfigValue(), is("pub_v2"));
        assertThat(role.getProperty("k2").getValue(), is("pub_v2"));
        assertThat(role.getProperty("k3").getEncryptedValue(), is(goCipher.encrypt("pub_v3")));
        assertThat(role.getProperty("k3").getConfigValue(), is(nullValue()));
        assertThat(role.getProperty("k3").getValue(), is("pub_v3"));
    }

    @Test
    public void shouldNotEncryptSecurePluginProperties_WhenPluginInfosIsAbsent() throws CryptoException {
        String authConfigId = "auth_config_id";
        String pluginId = "cd.go.github";

        BasicCruiseConfig basicCruiseConfig = new BasicCruiseConfig();
        basicCruiseConfig.server().security().securityAuthConfigs().add(new SecurityAuthConfig(authConfigId, pluginId));
        PluginRoleConfig role = new PluginRoleConfig("admin", authConfigId);
        role.addConfigurations(asList(
                new ConfigurationProperty(new ConfigurationKey("k1"), new ConfigurationValue("pub_v1")),
                new ConfigurationProperty(new ConfigurationKey("k2"), new ConfigurationValue("pub_v2")),
                new ConfigurationProperty(new ConfigurationKey("k3"), new ConfigurationValue("pub_v3"))));

        assertThat(role.getProperty("k1").getEncryptedValue(), is(nullValue()));
        assertThat(role.getProperty("k1").getConfigValue(), is("pub_v1"));
        assertThat(role.getProperty("k1").getValue(), is("pub_v1"));
        assertThat(role.getProperty("k2").getEncryptedValue(), is(nullValue()));
        assertThat(role.getProperty("k2").getConfigValue(), is("pub_v2"));
        assertThat(role.getProperty("k2").getValue(), is("pub_v2"));
        assertThat(role.getProperty("k3").getEncryptedValue(), is(nullValue()));
        assertThat(role.getProperty("k3").getConfigValue(), is("pub_v3"));
        assertThat(role.getProperty("k3").getValue(), is("pub_v3"));

        role.encryptSecureProperties(basicCruiseConfig);

        assertThat(role.getProperty("k1").getEncryptedValue(), is(nullValue()));
        assertThat(role.getProperty("k1").getConfigValue(), is("pub_v1"));
        assertThat(role.getProperty("k1").getValue(), is("pub_v1"));
        assertThat(role.getProperty("k2").getEncryptedValue(), is(nullValue()));
        assertThat(role.getProperty("k2").getConfigValue(), is("pub_v2"));
        assertThat(role.getProperty("k2").getValue(), is("pub_v2"));
        assertThat(role.getProperty("k3").getEncryptedValue(), is(nullValue()));
        assertThat(role.getProperty("k3").getConfigValue(), is("pub_v3"));
        assertThat(role.getProperty("k3").getValue(), is("pub_v3"));
    }

    @Test
    public void shouldNotEncryptSecurePluginProperties_WhenReferencedAuthConfigDoesNotExists() throws CryptoException {
        setAuthorizationPluginInfo();
        String authConfigId = "auth_config_id";

        BasicCruiseConfig basicCruiseConfig = new BasicCruiseConfig();
        PluginRoleConfig role = new PluginRoleConfig("admin", authConfigId);
        role.addConfigurations(asList(
                new ConfigurationProperty(new ConfigurationKey("k1"), new ConfigurationValue("pub_v1")),
                new ConfigurationProperty(new ConfigurationKey("k2"), new ConfigurationValue("pub_v2")),
                new ConfigurationProperty(new ConfigurationKey("k3"), new ConfigurationValue("pub_v3"))));

        assertThat(role.getProperty("k1").getEncryptedValue(), is(nullValue()));
        assertThat(role.getProperty("k1").getConfigValue(), is("pub_v1"));
        assertThat(role.getProperty("k1").getValue(), is("pub_v1"));
        assertThat(role.getProperty("k2").getEncryptedValue(), is(nullValue()));
        assertThat(role.getProperty("k2").getConfigValue(), is("pub_v2"));
        assertThat(role.getProperty("k2").getValue(), is("pub_v2"));
        assertThat(role.getProperty("k3").getEncryptedValue(), is(nullValue()));
        assertThat(role.getProperty("k3").getConfigValue(), is("pub_v3"));
        assertThat(role.getProperty("k3").getValue(), is("pub_v3"));

        role.encryptSecureProperties(basicCruiseConfig);

        assertThat(role.getProperty("k1").getEncryptedValue(), is(nullValue()));
        assertThat(role.getProperty("k1").getConfigValue(), is("pub_v1"));
        assertThat(role.getProperty("k1").getValue(), is("pub_v1"));
        assertThat(role.getProperty("k2").getEncryptedValue(), is(nullValue()));
        assertThat(role.getProperty("k2").getConfigValue(), is("pub_v2"));
        assertThat(role.getProperty("k2").getValue(), is("pub_v2"));
        assertThat(role.getProperty("k3").getEncryptedValue(), is(nullValue()));
        assertThat(role.getProperty("k3").getConfigValue(), is("pub_v3"));
        assertThat(role.getProperty("k3").getValue(), is("pub_v3"));
    }

    interface Validator {
        void validate(PluginRoleConfig pluginRoleConfig, ValidationContext context);
    }

    private void setAuthorizationPluginInfo() {
        PluginDescriptor pluginDescriptor = mock(PluginDescriptor.class);

        PluginConfiguration k1 = new PluginConfiguration("k1", new Metadata(false, true));
        PluginConfiguration k2 = new PluginConfiguration("k2", new Metadata(false, false));
        PluginConfiguration k3 = new PluginConfiguration("k3", new Metadata(false, true));

        PluggableInstanceSettings authConfigSettins = new PluggableInstanceSettings(asList(k1, k2, k3));
        PluggableInstanceSettings roleConfigSettings = new PluggableInstanceSettings(asList(k1, k2, k3));

        com.thoughtworks.go.plugin.domain.authorization.Capabilities capabilities = new com.thoughtworks.go.plugin.domain.authorization.Capabilities(SupportedAuthType.Web, true, true, true);
        AuthorizationPluginInfo artifactPluginInfo = new AuthorizationPluginInfo(pluginDescriptor, authConfigSettins, roleConfigSettings, null, capabilities);
        when(pluginDescriptor.id()).thenReturn("cd.go.github");
        AuthorizationMetadataStore.instance().setPluginInfo(artifactPluginInfo);
    }
}


export interface Serializable {
  serialize(): any;
  deserialize(obj: any): Serializable;
}


Helixcoin 0.8.5 BETA
====================

Copyright (c) 2009-2013 Bitcoin Developers
Copyright (c) 2014		Helixcoin Developers

Distributed under the MIT/X11 software license, see the accompanying
file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the [OpenSSL Toolkit](http://www.openssl.org/). This product includes
cryptographic software written by Eric Young ([eay@cryptsoft.com](mailto:eay@cryptsoft.com)), and UPnP software written by Thomas Bernard. This product also includes software developed by [Crypto++](http://www.cryptopp.com/) which is released under the Boost Software License 1.0.

Intro
---------------------
Helixcoin is a free open source peer-to-peer electronic cash system that is
completely decentralized, without the need for a central server or trusted
parties.  Users hold the crypto keys to their own money and transact directly
with each other, with the help of a P2P network to check for double-spending.

Setup
---------------------
You need the Qt4 run-time libraries to run Helixcoin-Qt. On Debian or Ubuntu:
	`sudo apt-get install libqtgui4`

Unpack the files into a directory and run:

- bin/32/helixcoin-qt (GUI, 32-bit)
- bin/32/helixcoind (headless, 32-bit)
- bin/64/helixcoin-qt (GUI, 64-bit)
- bin/64/helixcoind (headless, 64-bit)

See the documentation at the [Bitcoin Wiki](https://en.bitcoin.it/wiki/Main_Page)
for help and more information.

Other Pages
---------------------
- [Unix Build Notes](build-unix.md)
- [OSX Build Notes](build-osx.md)
- [Windows Build Notes](build-msw.md)
- [Coding Guidelines](coding.md)
- [Release Process](release-process.md)
- [Release Notes](release-notes.md)
- [Multiwallet Qt Development](multiwallet-qt.md)
- [Unit Tests](unit-tests.md)
- [Translation Process](translation_process.md)


<?php
$strQuery = sprintf("select s.*,sp.seq as publish_seq,sp.start_date,sp.finish_date,unix_timestamp(sp.start_date) as start_time,unix_timestamp(sp.finish_date) as finish_time from test_published as sp join test as s on sp.test_seq=s.seq where sp.seq=%d",$intPublishedSeq);
?>


package org.wso2.siddhi.core.table;

import org.apache.hadoop.util.bloom.CountingBloomFilter;
import org.apache.hadoop.util.bloom.Key;
import org.apache.hadoop.util.hash.Hash;
import org.apache.log4j.Logger;
import org.wso2.siddhi.core.config.SiddhiContext;
import org.wso2.siddhi.core.event.*;
import org.wso2.siddhi.core.event.in.InEvent;
import org.wso2.siddhi.core.event.in.InStateEvent;
import org.wso2.siddhi.core.executor.conditon.ConditionExecutor;
import org.wso2.siddhi.core.table.cache.CachingTable;
import org.wso2.siddhi.core.table.predicate.PredicateToken;
import org.wso2.siddhi.core.table.predicate.PredicateTreeNode;
import org.wso2.siddhi.core.table.predicate.sql.SQLPredicateBuilder;
import org.wso2.siddhi.query.api.definition.Attribute;
import org.wso2.siddhi.query.api.definition.TableDefinition;
import org.wso2.siddhi.query.api.query.QueryEventSource;

import javax.sql.DataSource;
import java.nio.ByteBuffer;
import java.sql.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class RDBMSEventTable implements EventTable {
    static final String PARAM_TABLE_NAME = "table.name";
    static final String PARAM_DATASOURCE_NAME = "datasource.name";
    static final String PARAM_CREATE_QUERY = "create.query";
    static final String PARAM_CACHING_ALGORITHM = "caching.algorithm";
    static final String PARAM_CACHE_SIZE = "cache.size";
    static final String PARAM_CACHE_LOADING = "cache.loading";
    static final String PARAM_BLOOM_FILTERS = "bloom.filters";

    public static final int BLOOM_FILTER_SIZE = 10000;
    public static final int BLOOM_FILTER_HASH_FUNCTIONS = 4;

    static final Logger log = Logger.getLogger(RDBMSEventTable.class);

    private TableDefinition tableDefinition;
    private QueryEventSource queryEventSource;
    // attribute list used for accessing the table.
    private List<Attribute> attributeList;  // full attribute list of the table
    private boolean eagerCacheLoading;

    private DataSource dataSource;
    private String databaseName;
    private String tableName;
    private String fullTableName;  // schema.tableName
    private String tableColumnList;   // for insertion queries.

    private boolean isInitialized;  // db connection init status

    private String insertQuery;
    private boolean bloomFiltersEnabled;

    private CachingTable cachedTable;
    //    private BloomFilter[] bloomFilters;   // bloom filters for each column
    private CountingBloomFilter[] bloomFilters;

    public RDBMSEventTable( ) {
    }

    public void init(TableDefinition tableDefinition, SiddhiContext siddhiContext) {
        this.tableDefinition = tableDefinition;
        this.queryEventSource = new QueryEventSource(tableDefinition.getExternalTable().getParameter(PARAM_TABLE_NAME), tableDefinition.getTableId(), tableDefinition, null, null, null);
        this.dataSource = siddhiContext.getDataSource(tableDefinition.getExternalTable().getParameter(PARAM_DATASOURCE_NAME));
        this.attributeList = new ArrayList<Attribute>();

        // caching is enabled by default.
        if ((tableDefinition.getExternalTable().getParameter(PARAM_CACHING_ALGORITHM) != null) && (!tableDefinition.getExternalTable().getParameter(PARAM_CACHING_ALGORITHM).equalsIgnoreCase("disable"))) {
            this.cachedTable = new CachingTable(tableDefinition.getTableId(), tableDefinition.getExternalTable().getParameter(PARAM_CACHING_ALGORITHM), tableDefinition.getExternalTable().getParameter(PARAM_CACHE_SIZE), siddhiContext);
        }

        // cache is by default loaded Lazily
        if (cachedTable != null && (tableDefinition.getExternalTable().getParameter(PARAM_CACHE_LOADING) != null) && (tableDefinition.getExternalTable().getParameter(PARAM_CACHE_LOADING).equalsIgnoreCase("eager"))) {
            this.eagerCacheLoading = true;
        }

        // bloom filters are disabled by default
        if ((tableDefinition.getExternalTable().getParameter(PARAM_BLOOM_FILTERS) != null) && (tableDefinition.getExternalTable().getParameter(PARAM_BLOOM_FILTERS).equalsIgnoreCase("enabled"))) {
            this.bloomFiltersEnabled = true;
        }

        try {
            initializeConnection();
            createPreparedStatementQueries();
            if (eagerCacheLoading) {
                preloadCache();
            }
            if (bloomFiltersEnabled) {
                buildBloomFilters();
            }
        } catch (ClassNotFoundException e) {
            log.error("Class not found. Can't continue to initialize the table.", e);
            throw new RuntimeException(e);
        } catch (Exception e) {
            log.error("Unable to connect to the database.", e);
        }
    }

    private void initializeConnection() throws SQLException, ClassNotFoundException {
        if (!isInitialized) {
            synchronized (this) {
                // synchronized double checking to ensure this doesn't get hit when there are concurrent calls
                if (!isInitialized) {

                    Connection con = null;
                    Statement statement = null;
                    try {
                        tableName = tableDefinition.getExternalTable().getParameter(PARAM_TABLE_NAME);

                        if (dataSource == null) {
                            throw new RuntimeException("Data source doesn't exist: " + tableDefinition.getExternalTable().getParameter(PARAM_DATASOURCE_NAME));
                        }
                        con = dataSource.getConnection();

                        // default mysql jdbc driver
                        databaseName = con.getCatalog();
                        fullTableName = databaseName + "." + tableName;

                        statement = con.createStatement();

                        String createQuery = tableDefinition.getExternalTable().getParameter(PARAM_CREATE_QUERY);

                        // table creation.
                        if (createQuery == null || createQuery.length() < 1) {
                            StringBuilder stringBuilder = new StringBuilder("CREATE TABLE IF NOT EXISTS ");
                            stringBuilder.append(fullTableName);
                            stringBuilder.append(" (");
                            boolean appendComma = false;
                            for (Attribute column : tableDefinition.getAttributeList()) {
                                if (appendComma) {
                                    stringBuilder.append(", ");
                                } else {
                                    appendComma = true;
                                }
                                stringBuilder.append(column.getName());
                                stringBuilder.append("  ");
                                switch (column.getType()) {
                                    case INT:
                                        stringBuilder.append("INT");
                                        break;
                                    case LONG:
                                        stringBuilder.append("BIGINT");
                                        break;
                                    case FLOAT:
                                        stringBuilder.append("DECIMAL(30,10)");
                                        break;
                                    case DOUBLE:
                                        stringBuilder.append("DECIMAL(40,15)");
                                        break;
                                    case BOOL:
                                        stringBuilder.append("BOOL");
                                        break;
                                    default:
                                        stringBuilder.append("VARCHAR(255)");
                                        break;
                                }
                            }
                            stringBuilder.append(");");
                            createQuery = stringBuilder.toString();
                            statement.execute(createQuery);

                        } else {
                            // users may not use 'IF NOT EXISTS' clause, so need to check whether the table exists before
                            // executing their create queries.
                            try {
                                statement.execute("SELECT 1 FROM " + fullTableName + " LIMIT 1");
                            } catch (SQLException e) {
                                statement.execute(createQuery);
                            }
                        }

                        StringBuilder builder = new StringBuilder("(");
                        boolean appendComma = false;
                        for (Attribute att : tableDefinition.getAttributeList()) {
                            attributeList.add(att);
                            if (appendComma) {
                                builder.append(",");
                            }
                            builder.append(att.getName());
                            appendComma = true;
                        }
                        builder.append(")");
                        tableColumnList = builder.toString();
                        isInitialized = true;
                    } finally {
                        cleanUpConnections(statement, con);
                    }
                }
            }
        }
    }

    private synchronized void buildBloomFilters() {
        this.bloomFilters = new CountingBloomFilter[tableDefinition.getAttributeList().size()];
        for (int i = 0; i < bloomFilters.length; i++) {
            // number of hashes: 4
            bloomFilters[i] = new CountingBloomFilter(BLOOM_FILTER_SIZE, BLOOM_FILTER_HASH_FUNCTIONS, Hash.MURMUR_HASH);
        }
        Connection con = null;
        Statement stmt = null;
        try {
            con = dataSource.getConnection();
            stmt = con.createStatement();
            ResultSet results = stmt.executeQuery("SELECT * FROM " + fullTableName);
            int count = 0;
            while (results.next()) {
                count++;
                for (int i = 0; i < bloomFilters.length; i++) {
                    switch (tableDefinition.getAttributeList().get(i).getType()) {
                        case INT:
                            bloomFilters[i].add(new Key(Integer.toString(results.getInt(i + 1)).getBytes()));
                            break;
                        case LONG:
                            bloomFilters[i].add(new Key(Long.toString(results.getLong(i + 1)).getBytes()));
                            break;
                        case FLOAT:
                            bloomFilters[i].add(new Key(Float.toString(results.getFloat(i + 1)).getBytes()));
                            break;
                        case DOUBLE:
                            bloomFilters[i].add(new Key(Double.toString(results.getDouble(i + 1)).getBytes()));
                            break;
                        case STRING:
                            bloomFilters[i].add(new Key(results.getString(i + 1).getBytes()));
                            break;
                        case BOOL:
                            bloomFilters[i].add(new Key(Boolean.toString(results.getBoolean(i + 1)).getBytes()));
                            break;

                    }
                }
            }
            results.close();

        } catch (Exception ex) {
            log.error(ex);
        } finally {
            cleanUpConnections(stmt, con);
        }
    }

    @Override
    public TableDefinition getTableDefinition() {
        return tableDefinition;
    }

    @Override
    public void add(StreamEvent streamEvent) {

        Connection con = null;
        PreparedStatement statement = null;
        try {
            initializeConnection();
            con = dataSource.getConnection();
            con.setAutoCommit(false);

            statement = con.prepareStatement(insertQuery);
            ArrayList<Event> bloomFilterInsertionList = null;
            if (bloomFiltersEnabled) {
                bloomFilterInsertionList = new ArrayList<Event>();
            }
            if (streamEvent instanceof AtomicEvent) {
                populateInsertQuery((Event) streamEvent, statement);
                statement.executeUpdate();
                if (bloomFiltersEnabled) {
                    bloomFilterInsertionList.add((Event) streamEvent);
                }
            } else {
                ListEvent listEvent = ((ListEvent) streamEvent);
                for (int i = 0, size = listEvent.getActiveEvents(); i < size; i++) {
                    populateInsertQuery(listEvent.getEvent(i), statement);
                    statement.addBatch();
                    if (bloomFiltersEnabled) {
                        bloomFilterInsertionList.add(listEvent.getEvent(i));
                    }
                }
                statement.executeBatch();
            }
            con.commit();

            if (cachedTable != null) {
                cachedTable.add(streamEvent);
            }
            if (bloomFiltersEnabled) {
                addToBloomFilters(bloomFilterInsertionList);
            }

        } catch (SQLException e) {
            log.error("Unable to insert the records to the table", e);
        } catch (Exception e) {
            log.error("Error while inserting data.", e);
        } finally {
            cleanUpConnections(statement, con);
        }
    }

    private void addToBloomFilters(List<Event> eventList) {
        for (Event event : eventList) {
            for (int i = 0; i < attributeList.size(); i++) {
                Attribute at = attributeList.get(i);
                switch (at.getType()) {
                    case INT:
                        bloomFilters[i].add(new Key(Integer.toString((Integer) event.getData(i)).getBytes()));
                        break;
                    case LONG:
                        bloomFilters[i].add(new Key(Long.toString((Long) event.getData(i)).getBytes()));
                        break;
                    case FLOAT:
                        bloomFilters[i].add(new Key(Float.toString((Float) event.getData(i)).getBytes()));
                        break;
                    case DOUBLE:
                        bloomFilters[i].add(new Key(Double.toString((Double) event.getData(i)).getBytes()));
                        break;
                    case STRING:
                        bloomFilters[i].add(new Key(event.getData(i).toString().getBytes()));
                        break;
                    case BOOL:
                        bloomFilters[i].add(new Key(Boolean.toString((Boolean) event.getData(i)).getBytes()));
                        break;
                }
            }
        }
    }

    private void removeFromBloomFilters(List<Event> eventList) {
        for (Event event : eventList) {
            for (int i = 0; i < attributeList.size(); i++) {
                Attribute at = attributeList.get(i);
                switch (at.getType()) {
                    case INT:
                        bloomFilters[i].delete(new Key(ByteBuffer.allocate(4).putInt((Integer) event.getData(i)).array()));
                        break;
                    case LONG:
                        bloomFilters[i].delete(new Key(ByteBuffer.allocate(8).putLong((Long) event.getData(i)).array()));
                        break;
                    case FLOAT:
                        bloomFilters[i].delete(new Key(ByteBuffer.allocate(4).putFloat((Float) event.getData(i)).array()));
                        break;
                    case DOUBLE:
                        bloomFilters[i].delete(new Key(ByteBuffer.allocate(8).putDouble((Double) event.getData(i)).array()));
                        break;
                    case STRING:
                        bloomFilters[i].delete(new Key(event.getData(i).toString().getBytes()));
                        break;
                    case BOOL:
                        bloomFilters[i].delete(new Key(Boolean.toString((Boolean) event.getData(i)).getBytes()));
                        break;
                }
            }
        }
    }

    private void preloadCache() {
        Connection con = null;
        Statement statement = null;
        try {
            con = dataSource.getConnection();
            statement = con.createStatement();
            ResultSet resultSet = statement.executeQuery("SELECT * FROM " + fullTableName +
                    " LIMIT 0, " + cachedTable.getCacheLimit());
            resultSet.setFetchSize(cachedTable.getCacheLimit());
            List<StreamEvent> eventList = new ArrayList<StreamEvent>();
            long timestamp = System.currentTimeMillis();
            while (resultSet.next()) {
                Object[] data = new Object[attributeList.size()];
                for (int i = 0; i < attributeList.size(); i++) {
                    switch (attributeList.get(i).getType()) {
                        case BOOL:
                            data[i] = resultSet.getBoolean(attributeList.get(i).getName());
                            break;
                        case DOUBLE:
                            data[i] = resultSet.getDouble(attributeList.get(i).getName());
                            break;
                        case FLOAT:
                            data[i] = resultSet.getFloat(attributeList.get(i).getName());
                            break;
                        case INT:
                            data[i] = resultSet.getInt(attributeList.get(i).getName());
                            break;
                        case LONG:
                            data[i] = resultSet.getLong(attributeList.get(i).getName());
                            break;
                        case STRING:
                            data[i] = resultSet.getString(attributeList.get(i).getName());
                            break;
                        default:
                            data[i] = resultSet.getObject(attributeList.get(i).getName());

                    }
                }
                Event event = new InEvent(tableDefinition.getExternalTable().getParameter(PARAM_TABLE_NAME), timestamp, data);
                eventList.add(event);
            }
            if (cachedTable != null) {
                cachedTable.addAll(eventList);
                // checking whether the table size is equal to the current cache size
                ResultSet resultCount = statement.executeQuery("SELECT COUNT(*) FROM " + fullTableName);
                int rowCount = 0;
                while (resultCount.next()) {
                    rowCount = resultCount.getInt(1);
                }
                if (rowCount <= cachedTable.getCacheLimit()) {
                    // this is later used for optimizations when reading
                    cachedTable.setFullyLoaded(true);
                }
                resultCount.close();
            }
            resultSet.close();
        } catch (SQLException e) {
            log.error("Unable to read the table: " + tableDefinition.getExternalTable().getParameter(PARAM_TABLE_NAME), e);
        } finally {
            cleanUpConnections(statement, con);
        }
    }

    private void populateInsertQuery(Event event, PreparedStatement statement) throws SQLException {
        for (int i = 0; i < attributeList.size(); i++) {
            switch (attributeList.get(i).getType()) {
                case INT:
                    statement.setInt(i + 1, ((Number) event.getData(i)).intValue());
                    break;
                case LONG:
                    statement.setLong(i + 1, ((Number) event.getData(i)).longValue());
                    break;
                case FLOAT:
                    statement.setFloat(i + 1, ((Number) event.getData(i)).floatValue());
                    break;
                case DOUBLE:
                    statement.setDouble(i + 1, ((Number) event.getData(i)).doubleValue());
                    break;
                case BOOL:
                    statement.setBoolean(i + 1, (Boolean) event.getData(i));
                    break;
                default:
                    statement.setString(i + 1, event.getData(i).toString());
                    break;
            }
        }
    }

    private void createPreparedStatementQueries() {
        // only the insert query can be created since update, delete have query-specific predicates
        StringBuilder builder = new StringBuilder("INSERT INTO ");
        builder.append(fullTableName);
        builder.append(tableColumnList);

        builder.append(" VALUES (");
        for (int i = 0; i < attributeList.size(); i++) {
            if (i > 0) {
                builder.append(", ");
            }

            builder.append("?");
        }
        builder.append(")");
        insertQuery = builder.toString();
    }

    @Override
    public void delete(StreamEvent streamEvent, ConditionExecutor conditionExecutor) {
        PreparedStatement statement = null;
        Connection con = null;
        try {
            initializeConnection();
            con = dataSource.getConnection();
            con.setAutoCommit(false);
            StringBuilder statementBuilder = new StringBuilder("DELETE FROM ");
            statementBuilder.append(fullTableName);
            statementBuilder.append(" WHERE ");
            ArrayList<Event> bloomFilterDeletionList = null;
            if (bloomFiltersEnabled) {
                bloomFilterDeletionList = new ArrayList<Event>();
            }
            if (streamEvent instanceof AtomicEvent) {
                PredicateTreeNode predicate = conditionExecutor.constructPredicate((Event) streamEvent, tableDefinition, new SQLPredicateBuilder());
                statementBuilder.append(predicate.buildPredicateString());
                statement = con.prepareStatement(statementBuilder.toString());
                ArrayList paramList = new ArrayList();
                predicate.populateParameters(paramList);
                for (int i = 0; i < paramList.size(); i++) {
                    populateStatement(statement, i + 1, paramList.get(i));
                }
                if (bloomFiltersEnabled) {
                    bloomFilterDeletionList.add((Event) streamEvent);
                }
                statement.executeUpdate();
            } else {
                for (int i = 0, size = ((ListEvent) streamEvent).getActiveEvents(); i < size; i++) {
                    // deleting the entire event set using an aggregate query with OR conditions
                    if (i > 0) {
                        statementBuilder.append(" OR ");
                    }
                    statementBuilder.append("(");
                    statementBuilder.append(conditionExecutor.constructPredicate(((ListEvent) streamEvent).getEvent(i), tableDefinition, new SQLPredicateBuilder()).buildPredicateString());
                    statementBuilder.append(")");
                    if (bloomFiltersEnabled) {
                        bloomFilterDeletionList.add(((ListEvent) streamEvent).getEvent(i));
                    }
                }
                statement = con.prepareStatement(statementBuilder.toString());
                statement.executeUpdate();
            }
            con.commit();
            if (cachedTable != null) {
                cachedTable.delete(streamEvent, conditionExecutor);
            }
            if (bloomFiltersEnabled) {
                removeFromBloomFilters(bloomFilterDeletionList);
            }

        } catch (SQLException e) {
            log.error("Unable to execute deletion.", e);
        } catch (ClassNotFoundException e) {
            log.error("Unable to load the database driver.", e);
        } finally {
            cleanUpConnections(statement, con);
        }

    }

    @Override
    public void update(StreamEvent streamEvent, ConditionExecutor conditionExecutor,
                       int[] attributeUpdateMappingPosition) {
        Connection con = null;
        PreparedStatement statement = null;

        try {
            initializeConnection();
            con = dataSource.getConnection();
            con.setAutoCommit(false);
            Event atomicEvent = null;
            SQLPredicateBuilder predicateBuilder = new SQLPredicateBuilder();
            if (streamEvent instanceof AtomicEvent) {
                atomicEvent = (Event) streamEvent;  // used to execute the condition executor
            } else {
                if (((ListEvent) streamEvent).getActiveEvents() > 0) {
                    atomicEvent = ((ListEvent) streamEvent).getEvent(0);
                }
            }

            PredicateTreeNode predicate = conditionExecutor.constructPredicate(atomicEvent, tableDefinition, predicateBuilder);
            String query = createUpdateQuery(predicate.buildPredicateString(), attributeUpdateMappingPosition);
            statement = con.prepareStatement(query);
            ArrayList paramList = new ArrayList();

            if (streamEvent instanceof AtomicEvent) {

                for (int i = 0; i < attributeUpdateMappingPosition.length; i++) {
                    populateStatement(statement, i + 1, atomicEvent.getData(i));
                }

                predicate.populateParameters(paramList);
                for (int i = 0; i < paramList.size(); i++) {
                    populateStatement(statement, attributeUpdateMappingPosition.length + i + 1, paramList.get(i));
                }
                statement.executeUpdate();

            } else {      // streamEvent instanceof ListEvent
                statement.clearParameters();

                for (int j = 0, size = ((ListEvent) streamEvent).getActiveEvents(); j < size; j++) {
                    Event event = ((ListEvent) streamEvent).getEvent(j);
                    predicate = conditionExecutor.constructPredicate(event, tableDefinition, predicateBuilder);
                    paramList.clear();
                    predicate.populateParameters(paramList);
                    for (int i = 0; i < attributeList.size(); i++) {
                        populateStatement(statement, i + 1, event.getData(i));
                    }
                    for (int i = 0; i < paramList.size(); i++) {
                        populateStatement(statement, attributeList.size() + i + 1, paramList.get(i));
                    }
                    statement.addBatch();
                }
                statement.executeBatch();
            }
            con.commit();
            if (cachedTable != null) {
                cachedTable.update(streamEvent, conditionExecutor, attributeUpdateMappingPosition);
            }
            if (bloomFiltersEnabled) {
                buildBloomFilters();
            }

        } catch (SQLException e) {
            log.error("Unable to execute update on " + streamEvent, e);
        } catch (ClassNotFoundException e) {
            log.error("Unable to load the database driver for " + tableDefinition.getExternalTable().getParameter(PARAM_TABLE_NAME), e);
        } finally {
            cleanUpConnections(statement, con);
        }

    }

    @Override
    public boolean contains(AtomicEvent atomicEvent, ConditionExecutor conditionExecutor) {

        PredicateTreeNode predicate = null;

        if (bloomFiltersEnabled) {
            // bloom filters used only for the equal conditions.
            predicate = conditionExecutor.constructPredicate(atomicEvent, tableDefinition, new SQLPredicateBuilder());
            ArrayList<PredicateToken> tokenList = new ArrayList<PredicateToken>(3);
            predicate.populateTokens(tokenList);

            // looking for two sided equals conditions (operators) only.
            if (tokenList.size() < 4) {
                // not using bloom filters for complex conditions
                for (int operatorIndex = 1; operatorIndex < tokenList.size() - 1; operatorIndex++) {

                    // at this level the operator becomes '=' instead of '=='
                    if (tokenList.get(operatorIndex).getGetTokenType() == PredicateToken.Type.OPERATOR &&
                            tokenList.get(operatorIndex).getTokenValue().trim().equals("=")) {

                        // param and value can be in any order i.e. price = 3 or 1 = price. this is to handle such scenarios.
                        String param = tokenList.get(operatorIndex - 1).getGetTokenType() == PredicateToken.Type.VARIABLE ? tokenList.get(operatorIndex - 1).getTokenValue().trim() :
                                tokenList.get(operatorIndex + 1).getTokenValue().toString().trim();
                        String value = tokenList.get(operatorIndex - 1).getGetTokenType() == PredicateToken.Type.VARIABLE ? tokenList.get(operatorIndex + 1).getTokenValue().toString().trim() :
                                tokenList.get(operatorIndex - 1).getTokenValue().trim();

                        for (int i = 0; i < attributeList.size(); i++) {
                            if (attributeList.get(i).getName().equals(param)) {
                                boolean mightContain = bloomFilters[i].membershipTest(new Key(value.getBytes()));

                                if (!mightContain) {
                                    return false;
                                }
                            }
                        }
                    }
                }
            }
        }

        if ((cachedTable != null) && cachedTable.contains(atomicEvent, conditionExecutor)) {
            return true;
        } else {
            Connection con = null;
            PreparedStatement statement = null;
            try {
                initializeConnection();

                if (predicate == null) {
                    predicate = conditionExecutor.constructPredicate(atomicEvent, tableDefinition, new SQLPredicateBuilder());
                }
                con = dataSource.getConnection();
                // need to construct this each time since there are multiple queries and their predicates differ.
                statement = con.prepareStatement("SELECT * FROM " + fullTableName + " WHERE " + predicate.buildPredicateString() + " LIMIT 0,1");
                ArrayList paramList = new ArrayList();
                predicate.populateParameters(paramList);
                for (int i = 0; i < paramList.size(); i++) {
                    populateStatement(statement, i + 1, paramList.get(i));
                }
                ResultSet resultSet = statement.executeQuery();

                boolean contains = false;
                long timestamp = System.currentTimeMillis();

                while (resultSet.next()) {
                    contains = true;
                    if (cachedTable != null) {

                        Object[] data = new Object[attributeList.size()];
                        for (int i = 0; i < attributeList.size(); i++) {
                            switch (attributeList.get(i).getType()) {
                                case BOOL:
                                    data[i] = resultSet.getBoolean(attributeList.get(i).getName());
                                    break;
                                case DOUBLE:
                                    data[i] = resultSet.getDouble(attributeList.get(i).getName());
                                    break;
                                case FLOAT:
                                    data[i] = resultSet.getFloat(attributeList.get(i).getName());
                                    break;
                                case INT:
                                    data[i] = resultSet.getInt(attributeList.get(i).getName());
                                    break;
                                case LONG:
                                    data[i] = resultSet.getLong(attributeList.get(i).getName());
                                    break;
                                case STRING:
                                    data[i] = resultSet.getString(attributeList.get(i).getName());
                                    break;
                                default:
                                    data[i] = resultSet.getObject(attributeList.get(i).getName());

                            }
                        }
                        // lazy loading caches since we've already read the event
                        Event event = new InEvent(tableDefinition.getExternalTable().getParameter(PARAM_TABLE_NAME), timestamp, data);
                        cachedTable.add(event);
                    } else {
                        break;
                    }
                }
                resultSet.close();
                return contains;
            } catch (SQLException e) {
                log.error("Can't read the database table: " + tableDefinition.getExternalTable().getParameter(PARAM_TABLE_NAME), e);
            } catch (Exception e) {
                log.error("Can't connect to the database.", e);
            } finally {
                cleanUpConnections(statement, con);
            }
            return false;
        }
    }

    private String createUpdateQuery(String predicate, int[] attributeMappingPositions) {
        StringBuilder statementBuilder = new StringBuilder("UPDATE ");
        statementBuilder.append(fullTableName);
        statementBuilder.append(" SET ");

        for (int i = 0; i < attributeMappingPositions.length; i++) {
            if (i > 0) {
                statementBuilder.append(", ");
            }
            statementBuilder.append(attributeList.get(attributeMappingPositions[i]).getName());
            statementBuilder.append(" = ?");
        }
        statementBuilder.append(" WHERE ");
        if (predicate != null) {
            statementBuilder.append(predicate);
        }
        return statementBuilder.toString();
    }

    @Override
    public QueryEventSource getQueryEventSource() {
        return queryEventSource;
    }

    @Override
    public Iterator<StreamEvent> iterator(StreamEvent event, ConditionExecutor conditionExecutor) {
        if (cachedTable != null && cachedTable.isFullyLoaded()) {
            if (event instanceof AtomicEvent) {
                synchronized (this) {
                    ArrayList<StreamEvent> resultEvents = new ArrayList<StreamEvent>();
                    Iterator<StreamEvent> iterator = cachedTable.iterator();
                    StateEvent stateEvent = new InStateEvent(new StreamEvent[2]);
                    stateEvent.setStreamEvent(0, event);
                    while (iterator.hasNext()) {
                        StreamEvent cachedEvent = iterator.next();
                        stateEvent.setStreamEvent(1, cachedEvent);
                        if (conditionExecutor.execute(stateEvent)) {
                            resultEvents.add(cachedEvent);
                        }
                    }
                    return resultEvents.iterator();
                }

            }
        }
        PredicateTreeNode predicate = conditionExecutor.constructPredicate((AtomicEvent) event, tableDefinition, new SQLPredicateBuilder());
        String sqlPredicate = predicate.buildPredicateString();
        if (sqlPredicate.trim().equals("?")) {
            return iterator();
        }
        ArrayList paramList = new ArrayList();
        predicate.populateParameters(paramList);
        for (int i = 0; i < paramList.size(); i++) {
            Object value = paramList.get(i);
            if (value != null) {
                value = value.toString().replaceAll("'", "''");
            }
            sqlPredicate = sqlPredicate.replaceFirst("\\?", "'" + value.toString() + "'");  // populate one by one.
        }
        return iterator(sqlPredicate);
    }

    @Override
    public Iterator<StreamEvent> iterator(String sqlPredicate) {
        Connection con = null;
        Statement statement = null;
        try {
            con = dataSource.getConnection();
            statement = con.createStatement();
            ResultSet resultSet = statement.executeQuery("SELECT * FROM " + fullTableName +
                    ((sqlPredicate == null) ? "" : (" WHERE " + sqlPredicate)));
            resultSet.setFetchSize(10000);
            ArrayList<StreamEvent> eventList = new ArrayList<StreamEvent>();
            long timestamp = System.currentTimeMillis();
            while (resultSet.next()) {
                Object[] data = new Object[attributeList.size()];
                for (int i = 0; i < attributeList.size(); i++) {
                    switch (attributeList.get(i).getType()) {
                        case BOOL:
                            data[i] = resultSet.getBoolean(attributeList.get(i).getName());
                            break;
                        case DOUBLE:
                            data[i] = resultSet.getDouble(attributeList.get(i).getName());
                            break;
                        case FLOAT:
                            data[i] = resultSet.getFloat(attributeList.get(i).getName());
                            break;
                        case INT:
                            data[i] = resultSet.getInt(attributeList.get(i).getName());
                            break;
                        case LONG:
                            data[i] = resultSet.getLong(attributeList.get(i).getName());
                            break;
                        case STRING:
                            data[i] = resultSet.getString(attributeList.get(i).getName());
                            break;
                        default:
                            data[i] = resultSet.getObject(attributeList.get(i).getName());

                    }
                }
                Event event = new InEvent(tableDefinition.getExternalTable().getParameter(PARAM_TABLE_NAME), timestamp, data);
                eventList.add(event);
            }
            resultSet.close();
            return eventList.iterator();
        } catch (SQLException e) {
            log.error("Unable to read the table: " + tableDefinition.getExternalTable().getParameter(PARAM_TABLE_NAME), e);
        } finally {
            cleanUpConnections(statement, con);
        }
        return null;
    }

    @Override
    public Iterator<StreamEvent> iterator() {
        return iterator(null);
    }

    private void cleanUpConnections(Statement stmt, Connection con) {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                log.error("unable to release statement", e);
            }
        }

        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                log.error("unable to release connection", e);
            }
        }
    }

    private void populateStatement(PreparedStatement stmt, int index, Object value)
            throws SQLException {
        if (value instanceof String) {
            stmt.setString(index, (String) value);
        } else if (value instanceof Integer) {
            stmt.setInt(index, (Integer) value);
        } else if (value instanceof Double) {
            stmt.setDouble(index, (Double) value);
        } else if (value instanceof Boolean) {
            stmt.setBoolean(index, (Boolean) value);
        } else if (value instanceof Float) {
            stmt.setFloat(index, (Float) value);
        } else if (value instanceof Long) {
            stmt.setLong(index, (Long) value);
        } else {
            stmt.setString(index, (String) value);
        }
    }
}


4.0 Functional Description
==========================

.. toctree::
    :glob:

    digital
    tri_state_1
    tri_state_2
    input_only
    analog
    power


package com.innovez.sample;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages="com.innovez.sample.web")
public class WebappConfiguration extends WebMvcConfigurerAdapter {
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("/assets/**").addResourceLocations("/WEB-INF/assets/**");
	}

	@Override
	public void addViewControllers(ViewControllerRegistry registry) {
		registry.addViewController("/").setViewName("/WEB-INF/templates/index.html");
		registry.addViewController("/employee").setViewName("/WEB-INF/views/employees.html");
	}

	@Override
	public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
		configurer.enable();
	}
}


class Announcement < ActiveRecord::Base

  named_scope :active, lambda { { :conditions => ['starts_at <= ? AND ends_at >= ?', Time.now.utc, Time.now.utc] } }
  named_scope :since, lambda { |hide_time| { :conditions => (hide_time ? ['updated_at > ? OR starts_at > ?', hide_time.utc, hide_time.utc] : nil) } }

  def self.display(hide_time)
    active.since(hide_time)
  end

end


tinymce.dom.TreeWalker = function(start_node, root_node) {
	var node = start_node;

	function findSibling(node, start_name, sibling_name, shallow) {
		var sibling, parent;

		if (node) {
			// Walk into nodes if it has a start
			if (!shallow && node[start_name])
				return node[start_name];

			// Return the sibling if it has one
			if (node != root_node) {
				sibling = node[sibling_name];
				if (sibling)
					return sibling;

				// Walk up the parents to look for siblings
				for (parent = node.parentNode; parent && parent != root_node; parent = parent.parentNode) {
					sibling = parent[sibling_name];
					if (sibling)
						return sibling;
				}
			}
		}
	};

	/**
	 * Returns the current node.
	 *
	 * @return {Node} Current node where the walker is.
	 */
	this.current = function() {
		return node;
	};

	/**
	 * Walks to the next node in tree.
	 *
	 * @return {Node} Current node where the walker is after moving to the next node.
	 */
	this.next = function(shallow) {
		return (node = findSibling(node, 'firstChild', 'nextSibling', shallow));
	};

	/**
	 * Walks to the previous node in tree.
	 *
	 * @return {Node} Current node where the walker is after moving to the previous node.
	 */
	this.prev = function(shallow) {
		return (node = findSibling(node, 'lastChild', 'lastSibling', shallow));
	};
};