<commit_before>/*global describe, it, afterEach*/
'use strict';

var chai          = require('chai'),
    constants     = require('../lib/constants'),
    expect        = chai.expect,
    _             = require('lodash'),
    path          = require('path');

chai.use(require('sinon-chai'));
require('mocha-sinon');

var msbuildFinder = require('../lib/msbuild-finder');

describe('msbuild-finder', function () {

  it('should use xbuild on linux', function () {
    var result = msbuildFinder.find({ platform: 'linux' });

    expect(result).to.be.equal('xbuild');
  });

  it('should use xbuild on darwin', function () {
    var result = msbuildFinder.find({ platform: 'darwin' });

    expect(result).to.be.equal('xbuild');
  });

  it('should use xbuild on unknown platform', function () {
    var result = msbuildFinder.find({ platform: 'xyz' });

    expect(result).to.be.equal('xbuild');
  });

  it('should use msbuild on windows', function () {
    var windir = 'WINDIR';
    var toolsVersion = 3.5;
    var result = msbuildFinder.find({ platform: 'win32', toolsVersion: toolsVersion, windir: windir });

    var expectMSBuildVersion = constants.MSBUILD_VERSIONS[toolsVersion];
    var expectedResult = path.join(windir, 'Microsoft.Net', 'Framework', expectMSBuildVersion, 'MSBuild.exe');

    expect(result).to.be.equal(expectedResult);
  });

  it('should use 64bit msbuild on 64bit windows', function () {
    var defaults = JSON.parse(JSON.stringify(constants.DEFAULTS));

    var windir = 'WINDIR';
    var toolsVersion = 3.5;
    var result = msbuildFinder.find(_.extend(defaults, { platform: 'win32', toolsVersion: toolsVersion, windir: windir }));

    var expectMSBuildVersion = constants.MSBUILD_VERSIONS[toolsVersion];
    var expectedResult = path.join(windir, 'Microsoft.Net', 'Framework64', expectMSBuildVersion, 'MSBuild.exe');

    expect(result).to.be.equal(expectedResult);
  });

  it('should use 64bit msbuild on windows with provided x64 architecture', function () {
    var windir = 'WINDIR';
    var toolsVersion = 3.5;
    var result = msbuildFinder.find({ platform: 'win32', toolsVersion: toolsVersion, windir: windir, architecture: 'x64' });

    var expectMSBuildVersion = constants.MSBUILD_VERSIONS[toolsVersion];
    var expectedResult = path.join(windir, 'Microsoft.Net', 'Framework64', expectMSBuildVersion, 'MSBuild.exe');

    expect(result).to.be.equal(expectedResult);
  });

  it('should use msbuild 12 on windows with visual studio 2013 project', function () {
    var toolsVersion = 12.0;
    var result = msbuildFinder.find({ platform: 'win32', toolsVersion: toolsVersion, architecture: 'x86' });

    var expectMSBuildVersion = constants.MSBUILD_VERSIONS[toolsVersion];

    var pathRoot = process.env['ProgramFiles'] || path.join('C:', 'Program Files');
    var expectedResult = path.join(pathRoot, 'MSBuild', expectMSBuildVersion, 'Bin', 'MSBuild.exe');

    expect(result).to.be.equal(expectedResult);
  });

  it('should use 64bit msbuild 12 on windows x64 with visual studio 2013 project', function () {
    var toolsVersion = 12.0;
    var result = msbuildFinder.find({ platform: 'win32', toolsVersion: toolsVersion, architecture: 'x64' });

    var expectMSBuildVersion = constants.MSBUILD_VERSIONS[toolsVersion];
    var pathRoot = process.env['ProgramFiles(x86)'] || path.join('C:', 'Program Files (x86)');
    var expectedResult = path.join(pathRoot, 'MSBuild', expectMSBuildVersion, 'Bin/amd64', 'MSBuild.exe');

    expect(result).to.be.equal(expectedResult);
  });

  it('should use msbuild 14 on windows with visual studio 2015 project', function () {
    var toolsVersion = 14.0;
    var result = msbuildFinder.find({ platform: 'win32', toolsVersion: toolsVersion, architecture: 'x86' });

    var expectMSBuildVersion = constants.MSBUILD_VERSIONS[toolsVersion];

    var pathRoot = process.env['ProgramFiles'] || path.join('C:', 'Program Files');
    var expectedResult = path.join(pathRoot, 'MSBuild', expectMSBuildVersion, 'Bin', 'MSBuild.exe');

    expect(result).to.be.equal(expectedResult);
  });

  it('should use 64bit msbuild 14 on windows x64 with visual studio 2015 project', function () {
    var toolsVersion = 14.0;
    var result = msbuildFinder.find({ platform: 'win32', toolsVersion: toolsVersion, architecture: 'x64' });

    var expectMSBuildVersion = constants.MSBUILD_VERSIONS[toolsVersion];
    var pathRoot = process.env['ProgramFiles(x86)'] || path.join('C:', 'Program Files (x86)');
    var expectedResult = path.join(pathRoot, 'MSBuild/', expectMSBuildVersion, 'Bin/amd64', 'MSBuild.exe');

    expect(result).to.be.equal(expectedResult);
  });

  it('should throw error with invalid toolsVersion', function () {
    var func = function () {
      return msbuildFinder.find({ platform: 'win32', toolsVersion: -1 });
    };

    expect(func).to.throw('No MSBuild Version was supplied!');
  });

  describe('when toolsVersion is \'auto\'', function() {
    var fs = require('fs');
    var mock;

    it('should fall back to 4.0 when Visual Studio 2013 and 2015 are not installed', function() {
      var windir = 'WINDIR';
      var toolsVersion = 'auto';

      var expectMSBuildVersion = constants.MSBUILD_VERSIONS[4.0];
      var expectedResult = path.join(windir, 'Microsoft.Net', 'Framework', expectMSBuildVersion, 'MSBuild.exe');

      mock = this.sinon.mock(fs);
      mock.expects('statSync').throws();

      var result = msbuildFinder.find({ platform: 'win32', toolsVersion: toolsVersion, windir: windir });

      expect(result).to.be.equal(expectedResult);
    });

    it('should fall back to 4.0 when MSBuild dir exists in Program Files, but no versions installed', function () {
      var windir = 'WINDIR';
      var toolsVersion = 'auto';
      var expectMSBuildVersion = constants.MSBUILD_VERSIONS[4.0];
      var pathRoot = process.env['ProgramFiles'] || path.join('C:', 'Program Files');
      var msbuildDir = path.join(pathRoot, 'MSBuild');
      var expectedResult = path.join(windir, 'Microsoft.Net', 'Framework', expectMSBuildVersion, 'MSBuild.exe');

      mock = this.sinon.mock(fs);
      mock.expects('readdirSync').withArgs(msbuildDir).returns(['padding', 'dir']);

      var result = msbuildFinder.find({ platform: 'win32', toolsVersion: toolsVersion, windir: windir });

      expect(result).to.be.equal(expectedResult);
    });

    it('should use msbuild 14 on windows with visual studio 2015 project', function () {
      var toolsVersion = 'auto';
      var expectMSBuildVersion = constants.MSBUILD_VERSIONS[14.0];
      var pathRoot = process.env['ProgramFiles'] || path.join('C:', 'Program Files');
      var msbuildDir = path.join(pathRoot, 'MSBuild');
      var expectedResult = path.join(pathRoot, 'MSBuild', expectMSBuildVersion, 'Bin', 'MSBuild.exe');

      mock = this.sinon.mock(fs);
      mock.expects('readdirSync').withArgs(msbuildDir).returns(['padding', 'dir', '14.0']);
      mock.expects('statSync').withArgs(msbuildDir).returns({});
      mock.expects('statSync').withArgs(path.join(msbuildDir, '14.0', 'Bin')).returns({});

      var result = msbuildFinder.find({ platform: 'win32', toolsVersion: toolsVersion, architecture: 'x86' });

      expect(result).to.be.equal(expectedResult);
    });

    it('should use msbuild 12 on windows with visual studio 2013 project and an incomplete visual studio 2015 install', function () {
      var toolsVersion = 'auto';
      var expectMSBuildVersion = constants.MSBUILD_VERSIONS[12.0];
      var pathRoot = process.env['ProgramFiles'] || path.join('C:', 'Program Files');
      var msbuildDir = path.join(pathRoot, 'MSBuild');
      var expectedResult = path.join(pathRoot, 'MSBuild', expectMSBuildVersion, 'Bin', 'MSBuild.exe');

      mock = this.sinon.mock(fs);
      mock.expects('readdirSync').withArgs(msbuildDir).returns(['padding', 'dir', '12.0', '14.0']);
      mock.expects('statSync').withArgs(msbuildDir).returns({});
      mock.expects('statSync').withArgs(path.join(msbuildDir, '12.0', 'Bin')).returns({});
      mock.expects('statSync').withArgs(path.join(msbuildDir, '14.0', 'Bin')).throws();

      var result = msbuildFinder.find({ platform: 'win32', toolsVersion: toolsVersion, architecture: 'x86' });

      expect(result).to.be.equal(expectedResult);
    });

    afterEach(function() {
      mock.restore();
    });
  });

});
<commit_msg>Fixes for CI<commit_after>/*global describe, it, afterEach, before*/
'use strict';

var chai          = require('chai'),
    constants     = require('../lib/constants'),
    expect        = chai.expect,
    _             = require('lodash'),
    path          = require('path');

chai.use(require('sinon-chai'));
require('mocha-sinon');

var msbuildFinder = require('../lib/msbuild-finder');

describe('msbuild-finder', function () {

  it('should use xbuild on linux', function () {
    var result = msbuildFinder.find({ platform: 'linux' });

    expect(result).to.be.equal('xbuild');
  });

  it('should use xbuild on darwin', function () {
    var result = msbuildFinder.find({ platform: 'darwin' });

    expect(result).to.be.equal('xbuild');
  });

  it('should use xbuild on unknown platform', function () {
    var result = msbuildFinder.find({ platform: 'xyz' });

    expect(result).to.be.equal('xbuild');
  });

  it('should use msbuild on windows', function () {
    var windir = 'WINDIR';
    var toolsVersion = 3.5;
    var result = msbuildFinder.find({ platform: 'win32', toolsVersion: toolsVersion, windir: windir });

    var expectMSBuildVersion = constants.MSBUILD_VERSIONS[toolsVersion];
    var expectedResult = path.join(windir, 'Microsoft.Net', 'Framework', expectMSBuildVersion, 'MSBuild.exe');

    expect(result).to.be.equal(expectedResult);
  });

  it('should use 64bit msbuild on 64bit windows', function () {
    var defaults = JSON.parse(JSON.stringify(constants.DEFAULTS));

    var windir = 'WINDIR';
    var toolsVersion = 3.5;
    var result = msbuildFinder.find(_.extend(defaults, { platform: 'win32', toolsVersion: toolsVersion, windir: windir }));

    var expectMSBuildVersion = constants.MSBUILD_VERSIONS[toolsVersion];
    var expectedResult = path.join(windir, 'Microsoft.Net', 'Framework64', expectMSBuildVersion, 'MSBuild.exe');

    expect(result).to.be.equal(expectedResult);
  });

  it('should use 64bit msbuild on windows with provided x64 architecture', function () {
    var windir = 'WINDIR';
    var toolsVersion = 3.5;
    var result = msbuildFinder.find({ platform: 'win32', toolsVersion: toolsVersion, windir: windir, architecture: 'x64' });

    var expectMSBuildVersion = constants.MSBUILD_VERSIONS[toolsVersion];
    var expectedResult = path.join(windir, 'Microsoft.Net', 'Framework64', expectMSBuildVersion, 'MSBuild.exe');

    expect(result).to.be.equal(expectedResult);
  });

  it('should use msbuild 12 on windows with visual studio 2013 project', function () {
    var toolsVersion = 12.0;
    var result = msbuildFinder.find({ platform: 'win32', toolsVersion: toolsVersion, architecture: 'x86' });

    var expectMSBuildVersion = constants.MSBUILD_VERSIONS[toolsVersion];

    var pathRoot = process.env['ProgramFiles'] || path.join('C:', 'Program Files');
    var expectedResult = path.join(pathRoot, 'MSBuild', expectMSBuildVersion, 'Bin', 'MSBuild.exe');

    expect(result).to.be.equal(expectedResult);
  });

  it('should use 64bit msbuild 12 on windows x64 with visual studio 2013 project', function () {
    var toolsVersion = 12.0;
    var result = msbuildFinder.find({ platform: 'win32', toolsVersion: toolsVersion, architecture: 'x64' });

    var expectMSBuildVersion = constants.MSBUILD_VERSIONS[toolsVersion];
    var pathRoot = process.env['ProgramFiles(x86)'] || path.join('C:', 'Program Files (x86)');
    var expectedResult = path.join(pathRoot, 'MSBuild', expectMSBuildVersion, 'Bin/amd64', 'MSBuild.exe');

    expect(result).to.be.equal(expectedResult);
  });

  it('should use msbuild 14 on windows with visual studio 2015 project', function () {
    var toolsVersion = 14.0;
    var result = msbuildFinder.find({ platform: 'win32', toolsVersion: toolsVersion, architecture: 'x86' });

    var expectMSBuildVersion = constants.MSBUILD_VERSIONS[toolsVersion];

    var pathRoot = process.env['ProgramFiles'] || path.join('C:', 'Program Files');
    var expectedResult = path.join(pathRoot, 'MSBuild', expectMSBuildVersion, 'Bin', 'MSBuild.exe');

    expect(result).to.be.equal(expectedResult);
  });

  it('should use 64bit msbuild 14 on windows x64 with visual studio 2015 project', function () {
    var toolsVersion = 14.0;
    var result = msbuildFinder.find({ platform: 'win32', toolsVersion: toolsVersion, architecture: 'x64' });

    var expectMSBuildVersion = constants.MSBUILD_VERSIONS[toolsVersion];
    var pathRoot = process.env['ProgramFiles(x86)'] || path.join('C:', 'Program Files (x86)');
    var expectedResult = path.join(pathRoot, 'MSBuild/', expectMSBuildVersion, 'Bin/amd64', 'MSBuild.exe');

    expect(result).to.be.equal(expectedResult);
  });

  it('should throw error with invalid toolsVersion', function () {
    var func = function () {
      return msbuildFinder.find({ platform: 'win32', toolsVersion: -1 });
    };

    expect(func).to.throw('No MSBuild Version was supplied!');
  });

  describe('when toolsVersion is \'auto\'', function() {
    var fs = require('fs');
    var mock;

    before(function() {
      process.env['ProgramFiles'] = path.join('C:', 'Program Files');
    });

    it('should fall back to 4.0 when Visual Studio 2013 and 2015 are not installed', function() {
      var windir = 'WINDIR';
      var toolsVersion = 'auto';

      var expectMSBuildVersion = constants.MSBUILD_VERSIONS[4.0];
      var expectedResult = path.join(windir, 'Microsoft.Net', 'Framework', expectMSBuildVersion, 'MSBuild.exe');

      mock = this.sinon.mock(fs);
      mock.expects('statSync').throws();

      var result = msbuildFinder.find({ platform: 'win32', toolsVersion: toolsVersion, windir: windir });

      expect(result).to.be.equal(expectedResult);
    });

    it('should fall back to 4.0 when MSBuild dir exists in Program Files, but no versions installed', function () {
      var windir = 'WINDIR';
      var toolsVersion = 'auto';
      var expectMSBuildVersion = constants.MSBUILD_VERSIONS[4.0];
      var pathRoot = process.env['ProgramFiles'] || path.join('C:', 'Program Files');
      var msbuildDir = path.join(pathRoot, 'MSBuild');
      var expectedResult = path.join(windir, 'Microsoft.Net', 'Framework', expectMSBuildVersion, 'MSBuild.exe');

      mock = this.sinon.mock(fs);
      mock.expects('statSync').returns({});
      mock.expects('readdirSync').withArgs(msbuildDir).returns(['padding', 'dir']);

      var result = msbuildFinder.find({ platform: 'win32', toolsVersion: toolsVersion, windir: windir });

      expect(result).to.be.equal(expectedResult);
    });

    it('should use msbuild 14 on windows with visual studio 2015 project', function () {
      var toolsVersion = 'auto';
      var expectMSBuildVersion = constants.MSBUILD_VERSIONS[14.0];
      var pathRoot = process.env['ProgramFiles'] || path.join('C:', 'Program Files');
      var msbuildDir = path.join(pathRoot, 'MSBuild');
      var expectedResult = path.join(pathRoot, 'MSBuild', expectMSBuildVersion, 'Bin', 'MSBuild.exe');

      mock = this.sinon.mock(fs);
      mock.expects('readdirSync').withArgs(msbuildDir).returns(['padding', 'dir', '14.0']);
      mock.expects('statSync').withArgs(msbuildDir).returns({});
      mock.expects('statSync').withArgs(path.join(msbuildDir, '14.0', 'Bin')).returns({});

      var result = msbuildFinder.find({ platform: 'win32', toolsVersion: toolsVersion, architecture: 'x86' });

      expect(result).to.be.equal(expectedResult);
    });

    it('should use msbuild 12 on windows with visual studio 2013 project and an incomplete visual studio 2015 install', function () {
      var toolsVersion = 'auto';
      var expectMSBuildVersion = constants.MSBUILD_VERSIONS[12.0];
      var pathRoot = process.env['ProgramFiles'] || path.join('C:', 'Program Files');
      var msbuildDir = path.join(pathRoot, 'MSBuild');
      var expectedResult = path.join(pathRoot, 'MSBuild', expectMSBuildVersion, 'Bin', 'MSBuild.exe');

      mock = this.sinon.mock(fs);
      mock.expects('readdirSync').withArgs(msbuildDir).returns(['padding', 'dir', '12.0', '14.0']);
      mock.expects('statSync').withArgs(msbuildDir).returns({});
      mock.expects('statSync').withArgs(path.join(msbuildDir, '12.0', 'Bin')).returns({});
      mock.expects('statSync').withArgs(path.join(msbuildDir, '14.0', 'Bin')).throws();

      var result = msbuildFinder.find({ platform: 'win32', toolsVersion: toolsVersion, architecture: 'x86' });

      expect(result).to.be.equal(expectedResult);
    });

    afterEach(function() {
      mock.restore();
    });
  });

});
<|endoftext|>


<commit_before>/*jslint node: true */
"use strict";

var H = require('../index').EventEmitter;
var _ = require('underscore');
var assert = require('assert');

describe('HevEmitter on', function () {

    describe('explicit promise', function () {

        it('should wait for callback when provided', function (done) {
            var h = new H();
            var wait = true;
            h.on(['james'], function (msg, cb) {});
            h.on(['heroes'], function (msg, cb) {
                return cb();
            });
            h.emit(['james'])
                .then(function () {
                    wait = false;
                });
            h.emit(['heroes'])
                .then(function () {
                    assert(wait);
                    done();
                });
        });

        it('two star error should short circuit one level', function (done) {
            var h = new H();
            var twoStarShort = true;
            h.on(['**'], function (msg, cb) {
                return cb('block');
            });
            h.on(['gross'], function (msg, cb) {
                twoStarShort = false;
                cb();
            });
            h.emit(['gross'])
            .catch(function (err) {
                assert.equal(err.message, 'block');
                assert(twoStarShort);
                done();
            });
        });

        it('two star error should short circuit one star', function (done) {
            var h = new H();
            var blocked = true;
            h.on(['**'], function (msg, cb) {
                return cb('block');
            });
            h.on(['*'], function (msg, cb) {
                blocked = false;
            });
            h.emit(['gross']).then(function() {
                blocked = false;
            })
            .catch(function (err) {
                assert.equal(err.message, 'block');
                assert(blocked);
                done();
            });
        });

        it('one star error should short circuit one level', function (done) {
            var h = new H();
            var blocked = true;
            h.on(['*'], function (msg, cb) {
                return cb('block');
            });
            h.on(['gross'], function (msg, cb) {
                blocked = false;
            });
            h.emit(['gross']).then(function() {
                blocked = false;
            })
            .catch(function (err) {
                assert.equal(err.message, 'block');
                assert(blocked);
                done();
            });
        });

        it('one level should short circuit one level', function (done) {
            var h = new H();
            var blocked = true;
            h.on(['baby'], function (msg, cb) {
                return cb('block');
            });
            h.on(['baby'], function (msg, cb) {
                blocked = false;
            });
            h.emit(['baby']).then(function() {
                blocked = false;
            })
            .catch(function (err) {
                assert.equal(err.message, 'block');
                assert(blocked);
                done();
            });
        });

        it('one level should short circuit one level even if deferred', function (done) {
            var h = new H();
            var blocked = true;
            h.on(['baby'], function (msg, cb) {
                process.nextTick(function () {
                    cb('block');
                });
            });
            h.on(['baby'], function (msg, cb) {
                blocked = false;
            });
            h.emit(['baby']).then(function() {
                blocked = false;
            })
            .catch(function (err) {
                assert.equal(err.message, 'block');
                assert(blocked);
                done();
            });
        });

    });

});
<commit_msg>Add two star deferred test, and clarify test messages.<commit_after>/*jslint node: true */
"use strict";

var H = require('../index').EventEmitter;
var _ = require('underscore');
var assert = require('assert');

describe('HevEmitter on', function () {

    describe('explicit promise', function () {

        it('should wait for callback when provided', function (done) {
            var h = new H();
            var wait = true;
            h.on(['james'], function (msg, cb) {});
            h.on(['heroes'], function (msg, cb) {
                return cb();
            });
            h.emit(['james'])
                .then(function () {
                    wait = false;
                });
            h.emit(['heroes'])
                .then(function () {
                    assert(wait);
                    done();
                });
        });

        it('two star error should short circuit one named event on same level', function (done) {
            var h = new H();
            var twoStarShort = true;
            h.on(['**'], function (msg, cb) {
                return cb('block');
            });
            h.on(['gross'], function (msg, cb) {
                twoStarShort = false;
                cb();
            });
            h.emit(['gross'])
            .catch(function (err) {
                assert.equal(err.message, 'block');
                assert(twoStarShort);
                done();
            });
        });

        it('two star error should short circuit one named event on same level even if deferred', function (done) {
            var h = new H();
            var twoStarShort = true;
            h.on(['**'], function (msg, cb) {
                process.nextTick(function () {
                    return cb('block');
                });
            });
            h.on(['gross'], function (msg, cb) {
                twoStarShort = false;
                cb();
            });
            h.emit(['gross'])
            .catch(function (err) {
                assert.equal(err.message, 'block');
                assert(twoStarShort);
                done();
            });
        });

        it('two star error should short circuit one star', function (done) {
            var h = new H();
            var blocked = true;
            h.on(['**'], function (msg, cb) {
                return cb('block');
            });
            h.on(['*'], function (msg, cb) {
                blocked = false;
            });
            h.emit(['gross']).then(function() {
                blocked = false;
            })
            .catch(function (err) {
                assert.equal(err.message, 'block');
                assert(blocked);
                done();
            });
        });

        it('one star error should short circuit named event at same level', function (done) {
            var h = new H();
            var blocked = true;
            h.on(['*'], function (msg, cb) {
                return cb('block');
            });
            h.on(['gross'], function (msg, cb) {
                blocked = false;
            });
            h.emit(['gross']).then(function() {
                blocked = false;
            })
            .catch(function (err) {
                assert.equal(err.message, 'block');
                assert(blocked);
                done();
            });
        });

        it('named event should short circuit named event', function (done) {
            var h = new H();
            var blocked = true;
            h.on(['baby'], function (msg, cb) {
                return cb('block');
            });
            h.on(['baby'], function (msg, cb) {
                blocked = false;
            });
            h.emit(['baby']).then(function() {
                blocked = false;
            })
            .catch(function (err) {
                assert.equal(err.message, 'block');
                assert(blocked);
                done();
            });
        });

        it('one level should short circuit one level even if deferred', function (done) {
            var h = new H();
            var blocked = true;
            h.on(['baby'], function (msg, cb) {
                process.nextTick(function () {
                    cb('block');
                });
            });
            h.on(['baby'], function (msg, cb) {
                blocked = false;
            });
            h.emit(['baby']).then(function() {
                blocked = false;
            })
            .catch(function (err) {
                assert.equal(err.message, 'block');
                assert(blocked);
                done();
            });
        });

    });

});
<|endoftext|>


<commit_before>oFC = null;
function updateDataTable() {
	height = $(window).height() - 185;
	scrollHeight = height + 10;
//    console.log(index_column);
//    console.log(order_column);
	if ($('#records').length > 0)
	{
		oTable =
		$('#records').dataTable(
		{

			"bProcessing": true,
			"bServerSide": true,
			"sAjaxSource": tableSource,
			"fnServerData": function (sSource, aoData, fnCallback) {

				jQuery.getJSON(sSource, aoData, function (json) {

					fnCallback(json);

				});
			},
		});

	}
}

function getColumnOrder()
{
	var orderString = new Array;
	$('#records th').each(function (index)
	{
		if (index == 0)
		{
			orderString[index] = this.id;
		}
		else
		{
			if (!in_array(this.id, orderString, true))
			{
				orderString[index] = this.id;
			}
		}
	});

	return orderString;
}

function reOrderDropDown(columnArray)
{

	var columnNames = {
		checkbox_col: {english: 'checkbox_col', dutch: 'checkbox_col'},
		Organization: {english: 'Organization', dutch: 'Organisatie'},
		PID: {english: 'PID', dutch: 'PID'},
		Barcode: {english: 'Barcode', dutch: 'Barcode'},
		Title: {english: 'Title', dutch: 'Titel'},
		Creation_Date: {english: 'Creation Date', dutch: 'Datum'},
		Created_On: {english: 'Created On', dutch: 'Aangemaakt op'},
		Media_Duration: {english: 'Media Duration', dutch: 'Duur'},
		Status: {english: 'Status', dutch: 'Status'},
		Carrier_Type: {english: 'Carrier Type', dutch: 'Dragertype'},
		Carrier_Format: {english: 'Carrier Format', dutch: 'Dragerformaat'},
		Abraham_ID: {english: 'Abraham ID', dutch: 'Abraham ID'},
		Edition: {english: 'Edition', dutch: 'Edition'},
		Number: {english: 'Number', dutch: 'Number'},
		Number_Of_Pages: {english: 'Number of Pages', dutch: 'Aantal Pagina\'s '},
		Collection_Box_Barcode: {english: 'Collection Box Barcode', dutch: 'Barcode verzameldoos'},
		Carrier_Original_ID: {english: 'Carrier Original ID', dutch: 'Oorspronkelijk dragernummer'},
		Shipment: {english: 'Shipment', dutch: 'Verzending'},
		Batch: {english: 'Batch', dutch: 'Batch'},
		Imported: {english: 'Imported', dutch: 'Geïmporteerd'}

	}

//	var columnShowHide = new Array();
//	$('#show_hide_li a').each(function(index, id)
//	{
//		if ($('#' + this.id + ' i').css('display') == "none")
//		{
//			columnShowHide[index] = str_replace(' ', '_', $(this).data().text);
//		}
//
//	});
//
//	$('#show_hide_li').html('');
//	for (cnt in columnArray)
//	{
//		display = '';
//		if (in_array(columnArray[cnt], columnShowHide, true))
//		{
//			display = 'style="display:none;"';
//		}
//		hide = '';
//		if (columnArray[cnt] == 'checkbox_col')
//			hide = 'style="display:none;"'
//		if (ReadCookieValue('app_language') == 'dutch')
//			name = columnNames[columnArray[cnt]].dutch;
//		else
//			name = columnNames[columnArray[cnt]].english;
//		$('#show_hide_li').append('
' + name + '
');
//
//	}
}

function in_array(needle, haystack, argStrict) {
	var key = '',
	strict = !!argStrict;

	if (strict) {
		for (key in haystack) {
			if (haystack[key] === needle) {
				return true;
			}
		}
	} else {
		for (key in haystack) {
			if (haystack[key] == needle) {
				return true;
			}
		}
	}

	return false;
}<commit_msg>added event listener and subscriber<commit_after>oFC = null;
function updateDataTable() {
	height = $(window).height() - 185;
	scrollHeight = height + 10;
//    console.log(index_column);
//    console.log(order_column);
	if ($('#records').length > 0)
	{
		oTable =
		$('#records').dataTable(
		{
			"dom": 'lftipr',
			"bProcessing": true,
			"bServerSide": true,
			"sAjaxSource": tableSource,
			"fnServerData": function (sSource, aoData, fnCallback) {

				jQuery.getJSON(sSource, aoData, function (json) {

					fnCallback(json);

				});
			},
		});

	}
}

function getColumnOrder()
{
	var orderString = new Array;
	$('#records th').each(function (index)
	{
		if (index == 0)
		{
			orderString[index] = this.id;
		}
		else
		{
			if (!in_array(this.id, orderString, true))
			{
				orderString[index] = this.id;
			}
		}
	});

	return orderString;
}

function reOrderDropDown(columnArray)
{

	var columnNames = {
		checkbox_col: {english: 'checkbox_col', dutch: 'checkbox_col'},
		Organization: {english: 'Organization', dutch: 'Organisatie'},
		PID: {english: 'PID', dutch: 'PID'},
		Barcode: {english: 'Barcode', dutch: 'Barcode'},
		Title: {english: 'Title', dutch: 'Titel'},
		Creation_Date: {english: 'Creation Date', dutch: 'Datum'},
		Created_On: {english: 'Created On', dutch: 'Aangemaakt op'},
		Media_Duration: {english: 'Media Duration', dutch: 'Duur'},
		Status: {english: 'Status', dutch: 'Status'},
		Carrier_Type: {english: 'Carrier Type', dutch: 'Dragertype'},
		Carrier_Format: {english: 'Carrier Format', dutch: 'Dragerformaat'},
		Abraham_ID: {english: 'Abraham ID', dutch: 'Abraham ID'},
		Edition: {english: 'Edition', dutch: 'Edition'},
		Number: {english: 'Number', dutch: 'Number'},
		Number_Of_Pages: {english: 'Number of Pages', dutch: 'Aantal Pagina\'s '},
		Collection_Box_Barcode: {english: 'Collection Box Barcode', dutch: 'Barcode verzameldoos'},
		Carrier_Original_ID: {english: 'Carrier Original ID', dutch: 'Oorspronkelijk dragernummer'},
		Shipment: {english: 'Shipment', dutch: 'Verzending'},
		Batch: {english: 'Batch', dutch: 'Batch'},
		Imported: {english: 'Imported', dutch: 'Geïmporteerd'}

	}

//	var columnShowHide = new Array();
//	$('#show_hide_li a').each(function(index, id)
//	{
//		if ($('#' + this.id + ' i').css('display') == "none")
//		{
//			columnShowHide[index] = str_replace(' ', '_', $(this).data().text);
//		}
//
//	});
//
//	$('#show_hide_li').html('');
//	for (cnt in columnArray)
//	{
//		display = '';
//		if (in_array(columnArray[cnt], columnShowHide, true))
//		{
//			display = 'style="display:none;"';
//		}
//		hide = '';
//		if (columnArray[cnt] == 'checkbox_col')
//			hide = 'style="display:none;"'
//		if (ReadCookieValue('app_language') == 'dutch')
//			name = columnNames[columnArray[cnt]].dutch;
//		else
//			name = columnNames[columnArray[cnt]].english;
//		$('#show_hide_li').append('
' + name + '
');
//
//	}
}

function in_array(needle, haystack, argStrict) {
	var key = '',
	strict = !!argStrict;

	if (strict) {
		for (key in haystack) {
			if (haystack[key] === needle) {
				return true;
			}
		}
	} else {
		for (key in haystack) {
			if (haystack[key] == needle) {
				return true;
			}
		}
	}

	return false;
}<|endoftext|>


<commit_before>/**
 * Class of managing Filtering and displaying of records.
 *
 * @returns {Records}
 */
function Records() {
    /**
     * Object of datatable.
     */
//	this.oTable = null;
    /**
     * URL for managing calls of datatable
     * @type {string}
     */
    var ajaxSource = null;
    var pageUrl = null;
    var selfObj = this;
    var Filters = new Object();
    var customFieldName = 'All';
    var customColumnName = 'all';
    var ajaxSaveStateUrl = null;
    /**
     * Set the ajax URL of datatable.
     * @param {string} source
     *
     */
    this.setAjaxSource = function (source) {
        ajaxSource = source;

    }
    /**
     * Set the ajax URL for selected rows of datatable.
     * @param {string} source
     *
     */
    this.setAjaxSaveStateUrl = function (source) {
        ajaxSaveStateUrl = source;

    }
    /**
     * Set the page url.
     * @param {string} url
     *
     */
    this.setPageUrl = function (url) {
        pageUrl = url;

    }
    /**
     * Initialize the datatable.
     *
     */
    this.initDataTable = function () {
        // check the existence of table on which we are going to apply datatable.
        if ($('#records').length > 0)
        {
            // Modify css for managing view.
//			$('#container').removeClass('container');
//			$('#container').css('margin', '20px');
            var selected = [];
            oTable =
                    $('#records').dataTable(
                    {
                        "dom": '<"top"p><"clear">tir<"bottom"p>',
                        "bProcessing": true,
                        "bServerSide": true,
                        retrieve: true,
                        destroy: true,
                        "language": {
                            "info": "Showing _START_ - _END_ of _MAX_",
                            "infoFiltered": ''
                        },
                        "aoColumnDefs": [
                            {"bSortable": false, "aTargets": [0]}
                        ],
                        "aaSorting": [],
                        "sAjaxSource": ajaxSource,
                        "bStateSave": true,
//				"fnInitComplete": function () {
//					this.oTable.fnAdjustColumnSizing();
//				},
                        "fnServerData": function (sSource, aoData, fnCallback) {
                            jQuery.getJSON(sSource, aoData, function (json) {
                                fnCallback(json);

                            });
                        },
                        "createdRow": function (row, data, index) {
                            var input = $(row).find("td:first").html();
                            row.id = "row-" + $(input).attr('value');
                        },
                        "ajax": ajaxSource,
                        "rowCallback": function (row, data) {
                            if ($.inArray(row.id, selected) !== -1) {
                                $(row).addClass('selected');
                                var input = $(row).find("td:first").html();
                                $(input).prop('checked', true);
//                                $(input).attr('checked','checked');
                            }
                        }
                    });
            $('#records tbody').on('click', 'tr', function () {
                var id = this.id;
                var index = $.inArray(id, selected);
                if (index === -1) {
                    selected.push(id);
                } else {
                    selected.splice(index, 1);
                }
                $(this).toggleClass('selected');
                var input = $(id).find("td:first").html();
                console.log(input);
                $(input).attr('checked', 'checked');
            });
        }

    }
    /**
     *
     * @returns {Boolean}
     */
    this.bindEvents = function () {
        selfObj.isAnySearch();
        $('input[name="mediaType[]"]').click(function () {
            checkParentFacet('media_type', $(this).prop("checked"));
        });
        $('input[name="commercial[]"]').click(function () {
            checkParentFacet('commercial', $(this).prop('checked'));
        });
        $('input[name="format[]"]').click(function () {
            checkParentFacet('format', $(this).prop('checked'));
        });
        $('input[name="base[]"]').click(function () {
            checkParentFacet('base', $(this).prop('checked'));
        });
        $('input[name="recordingStandard[]"]').click(function () {
            checkParentFacet('recordingStandard', $(this).prop('checked'));
        });
        $('input[name="printType[]"]').click(function () {
            checkParentFacet('printType', $(this).prop('checked'));
        });
        $('input[name="project[]"]').click(function () {
            checkParentFacet('project', $(this).prop('checked'));
        });
        $('input[name="reelDiameter[]"]').click(function () {
            checkParentFacet('reelDiameter', $(this).prop('checked'));
        });
        $('input[name="discDiameter[]"]').click(function () {
            checkParentFacet('discDiameter', $(this).prop('checked'));
        });
        $('input[name="acidDetection[]"]').click(function () {
            checkParentFacet('acidDetection', $(this).prop('checked'));
        });
        $('input[name="collectionName[]"]').click(function () {
            checkParentFacet('collectionName', $(this).prop('checked'));
        });
        initTriStateCheckBox('is_review_check', 'is_review_check_state', true);
        $('#is_review_check').click(function () {
            var totalChecked = $('#total_checked').val();
            var containerId = $(this).attr('id');
            var currentVal = $('#' + containerId + '_state').val();
            if (currentVal > 0 && totalChecked == 0)
            {
                totalChecked++;
                $('#parent_facet').val(containerId);
                $('#total_checked').val(totalChecked);
            }
            if (currentVal == 0 && $('#parent_facet').val() == containerId) {
                totalChecked--;
                $('#parent_facet').val('');
                $('#total_checked').val(totalChecked);
            }
            filterRecords();
        });
        $('#reset_all').click(function () {
            selfObj.resetAll();
        });

        selfObj.addCustomToken();
        $('#addKeyword').click(function () {
            selfObj.addKeyword();
        });
        $('#keywordSearch').keypress(function (e) {
            if (e.which == 13) {
                selfObj.addKeyword();
            }
        });

        selfObj.removeFilter();
        selfObj.removeKeywordFilter();
        return true;
    }
    /**
     *
     * @param {type} type
     * @param {type} isChecked
     * @returns {undefined}
     */
    var checkParentFacet = function (type, isChecked) {
        //todo need to update function
        var totalChecked = $('#total_checked').val();
        var total = $('#facet_sidebar input:checked').length;
        if (total == 0)
            totalChecked = 0;
        if (isChecked)
            totalChecked++;
        else
            totalChecked--;
        if (totalChecked < 0)
            totalChecked = 0;
        $('#total_checked').val(totalChecked);

        if ($('#parent_facet').val() == '' && totalChecked == 1)
            $('#parent_facet').val(type);
        else if (totalChecked == 0)
            $('#parent_facet').val('');
        filterRecords();
    }
    /**
     *
     * @returns {undefined}
     */
    var filterRecords = function () {
        $.blockUI({
            message: 'Please wait...',
            css: {
                border: 'none',
                padding: '15px',
                backgroundColor: '#000',
                '-webkit-border-radius': '10px',
                '-moz-border-radius': '10px',
                opacity: .5,
                color: '#fff',
                zIndex: 999999
            }
        });
        $.ajax({
            type: 'GET',
            url: pageUrl,
            data: $('#formSearch').serialize(),
            dataType: 'json',
            success: function (response)
            {
                $("#recordsContainer").html(response.html);
                var source = $('#metro-js').attr('src');
                var script = document.createElement("script");
                script.type = "text/javascript";
                script.src = source;
                script.id = "metro-js";
                $("#recordsContainer").append(script);
                selfObj.initDataTable();
                selfObj.bindEvents();
                $('body').scrollTop(0);
                $.unblockUI();
            }

        });
    }

    /**
     *
     * @returns {undefined}
     */
    this.addCustomToken = function () {
        $('.customToken').click(function () {
            customFieldName = $(this).attr('data-fieldName');
            customColumnName = $(this).attr('data-columnName');
            $('#limit_field_text').html(customFieldName);
        });
    }

    this.addKeyword = function () {

        if ($('#keywordSearch').val() != '') {
            if ($('#facet_keyword_search').val() != '' && $('#facet_keyword_search').val() != '""') {
                Filters = JSON.parse($('#facet_keyword_search').val());
            }
            else {
                Filters = new Array();
            }
            for (x in Filters) {
                if (Filters[x].value == $('#keywordSearch').val()) {
                    alert($('#keywordSearch').val() + " filter is already applied.");
                    return false;
                }
            }
            var temp = {};
            temp.value = $('#keywordSearch').val();
            temp.type = customColumnName;
            Filters.push(temp);

            $('#facet_keyword_search').val(JSON.stringify(Filters));
            customFieldName = 'All';
            customColumnName = 'all';
            filterRecords();
        }
    }

    this.removeFilter = function () {
        $('.delFilter').click(function () {
            elementID = $(this).attr('data-elementId');
            type = $(this).attr('data-type');
            $('#' + elementID).prop('checked', false);
            checkParentFacet(type);
        });
    }
    this.removeKeywordFilter = function () {
        $('.deleteKeyword').click(function () {
            var index = $.trim($(this).data().index);
            Filters = JSON.parse($('#facet_keyword_search').val());
            delete (Filters[index]);
            Filters.splice(index, 1);
            $('#facet_keyword_search').val(JSON.stringify(Filters));
            filterRecords();
        });

    }
    this.resetAll = function () {
        $('#formSearch').find('input:hidden, input:text, select').val('');
        $('#formSearch').find('input:radio, input:checkbox')
                .removeAttr('checked').removeAttr('selected');
        filterRecords();
    }
    this.isAnySearch = function () {
        if ($('.search_keys').length > 0) {
            $('#reset_all').show();
        }
        else {
            $('#reset_all').hide();

        }

    }
}

<commit_msg>keyword input box<commit_after>/**
 * Class of managing Filtering and displaying of records.
 *
 * @returns {Records}
 */
function Records() {
    /**
     * Object of datatable.
     */
//	this.oTable = null;
    /**
     * URL for managing calls of datatable
     * @type {string}
     */
    var ajaxSource = null;
    var pageUrl = null;
    var selfObj = this;
    var Filters = new Object();
    var customFieldName = 'All';
    var customColumnName = 'all';
    var ajaxSaveStateUrl = null;
    /**
     * Set the ajax URL of datatable.
     * @param {string} source
     *
     */
    this.setAjaxSource = function (source) {
        ajaxSource = source;

    }
    /**
     * Set the ajax URL for selected rows of datatable.
     * @param {string} source
     *
     */
    this.setAjaxSaveStateUrl = function (source) {
        ajaxSaveStateUrl = source;

    }
    /**
     * Set the page url.
     * @param {string} url
     *
     */
    this.setPageUrl = function (url) {
        pageUrl = url;

    }
    /**
     * Initialize the datatable.
     *
     */
    this.initDataTable = function () {
        // check the existence of table on which we are going to apply datatable.
        if ($('#records').length > 0)
        {
            // Modify css for managing view.
//			$('#container').removeClass('container');
//			$('#container').css('margin', '20px');
            var selected = [];
            oTable =
                    $('#records').dataTable(
                    {
                        "dom": '<"top"p><"clear">tir<"bottom"p>',
                        "bProcessing": true,
                        "bServerSide": true,
                        retrieve: true,
                        destroy: true,
                        "language": {
                            "info": "Showing _START_ - _END_ of _MAX_",
                            "infoFiltered": ''
                        },
                        "aoColumnDefs": [
                            {"bSortable": false, "aTargets": [0]}
                        ],
                        "aaSorting": [],
                        "sAjaxSource": ajaxSource,
                        "bStateSave": true,
//				"fnInitComplete": function () {
//					this.oTable.fnAdjustColumnSizing();
//				},
                        "fnServerData": function (sSource, aoData, fnCallback) {
                            jQuery.getJSON(sSource, aoData, function (json) {
                                fnCallback(json);

                            });
                        },
                        "createdRow": function (row, data, index) {
                            var input = $(row).find("td:first").html();
                            row.id = "row-" + $(input).attr('value');
                        },
                        "ajax": ajaxSource,
                        "rowCallback": function (row, data) {
                            if ($.inArray(row.id, selected) !== -1) {
                                $(row).addClass('selected');
                                var input = $(row).find("td:first").html();
                                $(input).prop('checked', true);
//                                $(input).attr('checked','checked');
                            }
                        }
                    });
            $('#records tbody').on('click', 'tr', function () {
                var id = this.id;
                var index = $.inArray(id, selected);
                if (index === -1) {
                    selected.push(id);
                } else {
                    selected.splice(index, 1);
                }
                $(this).toggleClass('selected');
                var input = $(id +" td:first").html();
                console.log(input);
                $(input).attr('checked', 'checked');
            });
        }

    }
    /**
     *
     * @returns {Boolean}
     */
    this.bindEvents = function () {
        selfObj.isAnySearch();
        $('input[name="mediaType[]"]').click(function () {
            checkParentFacet('media_type', $(this).prop("checked"));
        });
        $('input[name="commercial[]"]').click(function () {
            checkParentFacet('commercial', $(this).prop('checked'));
        });
        $('input[name="format[]"]').click(function () {
            checkParentFacet('format', $(this).prop('checked'));
        });
        $('input[name="base[]"]').click(function () {
            checkParentFacet('base', $(this).prop('checked'));
        });
        $('input[name="recordingStandard[]"]').click(function () {
            checkParentFacet('recordingStandard', $(this).prop('checked'));
        });
        $('input[name="printType[]"]').click(function () {
            checkParentFacet('printType', $(this).prop('checked'));
        });
        $('input[name="project[]"]').click(function () {
            checkParentFacet('project', $(this).prop('checked'));
        });
        $('input[name="reelDiameter[]"]').click(function () {
            checkParentFacet('reelDiameter', $(this).prop('checked'));
        });
        $('input[name="discDiameter[]"]').click(function () {
            checkParentFacet('discDiameter', $(this).prop('checked'));
        });
        $('input[name="acidDetection[]"]').click(function () {
            checkParentFacet('acidDetection', $(this).prop('checked'));
        });
        $('input[name="collectionName[]"]').click(function () {
            checkParentFacet('collectionName', $(this).prop('checked'));
        });
        initTriStateCheckBox('is_review_check', 'is_review_check_state', true);
        $('#is_review_check').click(function () {
            var totalChecked = $('#total_checked').val();
            var containerId = $(this).attr('id');
            var currentVal = $('#' + containerId + '_state').val();
            if (currentVal > 0 && totalChecked == 0)
            {
                totalChecked++;
                $('#parent_facet').val(containerId);
                $('#total_checked').val(totalChecked);
            }
            if (currentVal == 0 && $('#parent_facet').val() == containerId) {
                totalChecked--;
                $('#parent_facet').val('');
                $('#total_checked').val(totalChecked);
            }
            filterRecords();
        });
        $('#reset_all').click(function () {
            selfObj.resetAll();
        });

        selfObj.addCustomToken();
        $('#addKeyword').click(function () {
            selfObj.addKeyword();
        });
        $('#keywordSearch').keypress(function (e) {
            if (e.which == 13) {
                selfObj.addKeyword();
            }
        });

        selfObj.removeFilter();
        selfObj.removeKeywordFilter();
        return true;
    }
    /**
     *
     * @param {type} type
     * @param {type} isChecked
     * @returns {undefined}
     */
    var checkParentFacet = function (type, isChecked) {
        //todo need to update function
        var totalChecked = $('#total_checked').val();
        var total = $('#facet_sidebar input:checked').length;
        if (total == 0)
            totalChecked = 0;
        if (isChecked)
            totalChecked++;
        else
            totalChecked--;
        if (totalChecked < 0)
            totalChecked = 0;
        $('#total_checked').val(totalChecked);

        if ($('#parent_facet').val() == '' && totalChecked == 1)
            $('#parent_facet').val(type);
        else if (totalChecked == 0)
            $('#parent_facet').val('');
        filterRecords();
    }
    /**
     *
     * @returns {undefined}
     */
    var filterRecords = function () {
        $.blockUI({
            message: 'Please wait...',
            css: {
                border: 'none',
                padding: '15px',
                backgroundColor: '#000',
                '-webkit-border-radius': '10px',
                '-moz-border-radius': '10px',
                opacity: .5,
                color: '#fff',
                zIndex: 999999
            }
        });
        $.ajax({
            type: 'GET',
            url: pageUrl,
            data: $('#formSearch').serialize(),
            dataType: 'json',
            success: function (response)
            {
                $("#recordsContainer").html(response.html);
                var source = $('#metro-js').attr('src');
                var script = document.createElement("script");
                script.type = "text/javascript";
                script.src = source;
                script.id = "metro-js";
                $("#recordsContainer").append(script);
                selfObj.initDataTable();
                selfObj.bindEvents();
                $('body').scrollTop(0);
                $.unblockUI();
            }

        });
    }

    /**
     *
     * @returns {undefined}
     */
    this.addCustomToken = function () {
        $('.customToken').click(function () {
            customFieldName = $(this).attr('data-fieldName');
            customColumnName = $(this).attr('data-columnName');
            $('#limit_field_text').html(customFieldName);
        });
    }

    this.addKeyword = function () {

        if ($('#keywordSearch').val() != '') {
            if ($('#facet_keyword_search').val() != '' && $('#facet_keyword_search').val() != '""') {
                Filters = JSON.parse($('#facet_keyword_search').val());
            }
            else {
                Filters = new Array();
            }
            for (x in Filters) {
                if (Filters[x].value == $('#keywordSearch').val()) {
                    alert($('#keywordSearch').val() + " filter is already applied.");
                    return false;
                }
            }
            var temp = {};
            temp.value = $('#keywordSearch').val();
            temp.type = customColumnName;
            Filters.push(temp);

            $('#facet_keyword_search').val(JSON.stringify(Filters));
            customFieldName = 'All';
            customColumnName = 'all';
            filterRecords();
        }
    }

    this.removeFilter = function () {
        $('.delFilter').click(function () {
            elementID = $(this).attr('data-elementId');
            type = $(this).attr('data-type');
            $('#' + elementID).prop('checked', false);
            checkParentFacet(type);
        });
    }
    this.removeKeywordFilter = function () {
        $('.deleteKeyword').click(function () {
            var index = $.trim($(this).data().index);
            Filters = JSON.parse($('#facet_keyword_search').val());
            delete (Filters[index]);
            Filters.splice(index, 1);
            $('#facet_keyword_search').val(JSON.stringify(Filters));
            filterRecords();
        });

    }
    this.resetAll = function () {
        $('#formSearch').find('input:hidden, input:text, select').val('');
        $('#formSearch').find('input:radio, input:checkbox')
                .removeAttr('checked').removeAttr('selected');
        filterRecords();
    }
    this.isAnySearch = function () {
        if ($('.search_keys').length > 0) {
            $('#reset_all').show();
        }
        else {
            $('#reset_all').hide();

        }

    }
}

<|endoftext|>


<commit_before>if (typeof pistol88 == "undefined" || !pistol88) {
    var pistol88 = {};
}

pistol88.promocode = {
    init: function() {
        $(document).on('click', '.promo-code-enter-btn', this.enter);
        $(document).on('change', '.promo-code-enter input', this.enter);
        $(document).on('click', '.promo-code-clear-btn', this.clear);

        return true;
    },
    clear: function() {
        var form = $(this).parents('form');
        var data = $(form).serialize();
        data = data+'&clear=1';

        jQuery.post($(form).attr('action'), data,
            function(json) {
                if(json.result == 'success') {
                    $(form).find('input[type=text]').css({'border': '1px solid #ccc'}).val('');
                    $(form).find('.promo-code-discount').show().html(json.message);
                    if(json.newCost) {
                        $('.pistol88-cart-price').html(json.newCost);
                    }
                }
                else {
                    $(form).find('input[type=text]').css({'border': '1px solid red'});
                    console.log(json.errors);
                }

                return true;

            }, "json");

        return false;
    },
    enter: function() {
        var form = $(this).parents('form');
        var data = $(form).serialize();

        jQuery.post($(form).attr('action'), data,
            function(json) {
                if(json.result == 'success') {
                    $(form).find('input[type=text]').css({'border': '1px solid green'});

                    if(json.newCost) {
                        $('.pistol88-cart-price').html(json.newCost);
                    }
                }
                else {
                    $(form).find('input[type=text]').css({'border': '1px solid red'});
                    console.log(json.errors);
                }
                $(form).find('.promo-code-discount').show().html(json.message);

                return true;

            }, "json");

        return false;
    }
};

pistol88.promocode.init();<commit_msg>hide info message<commit_after>if (typeof pistol88 == "undefined" || !pistol88) {
    var pistol88 = {};
}

pistol88.promocode = {
    init: function() {
        $(document).on('click', '.promo-code-enter-btn', this.enter);
        $(document).on('change', '.promo-code-enter input', this.enter);
        $(document).on('click', '.promo-code-clear-btn', this.clear);

        return true;
    },
    clear: function() {
        var form = $(this).parents('form');
        var data = $(form).serialize();
        data = data+'&clear=1';

        jQuery.post($(form).attr('action'), data,
            function(json) {
                if(json.result == 'success') {
                    $(form).find('input[type=text]').css({'border': '1px solid #ccc'}).val('');
                    $(form).find('.promo-code-discount').show('slow').html(json.message);

                    setTimeout(function() { $('.promo-code-discount').hide('slow'); }, 2300);

                    if(json.newCost) {
                        $('.pistol88-cart-price').html(json.newCost);
                    }
                }
                else {
                    $(form).find('input[type=text]').css({'border': '1px solid red'});
                    console.log(json.errors);
                }

                return true;

            }, "json");

        return false;
    },
    enter: function() {
        var form = $(this).parents('form');
        var data = $(form).serialize();

        jQuery.post($(form).attr('action'), data,
            function(json) {
                if(json.result == 'success') {
                    $(form).find('input[type=text]').css({'border': '1px solid green'});

                    if(json.newCost) {
                        $('.pistol88-cart-price').html(json.newCost);
                    }
                }
                else {
                    $(form).find('input[type=text]').css({'border': '1px solid red'});
                    console.log(json.errors);
                }
                $(form).find('.promo-code-discount').show().html(json.message);

                return true;

            }, "json");

        return false;
    }
};

pistol88.promocode.init();<|endoftext|>


<commit_before>var fs = require('fs');

var mock = require('./mock');
var WebsiteOutput = require('../lib/output/website');

describe('Website Output', function() {

    describe('Sample Book', function() {
        var output;

        before(function() {
            return mock.outputDefaultBook(WebsiteOutput)
            .then(function(_output) {
                output = _output;
            });
        });

        it('should correctly generate an index.html', function() {
            output.should.have.file('index.html');
        });

        it('should correctly copy assets', function() {
            output.should.have.file('gitbook/app.js');
            output.should.have.file('gitbook/images/favicon.ico');
        });

        it('should correctly copy plugins', function() {
            output.should.have.file('gitbook/gitbook-plugin-highlight/website.css');
        });
    });

    describe('Book with chapters', function() {
        var output;

        before(function() {
            return mock.outputDefaultBook(WebsiteOutput, {
                'hello/README.md': '# Hello',
                'hello/test.md': '# Test'
            }, [
                {
                    title: 'Hello',
                    path: 'hello/README.md'
                },
                {
                    title: 'Test',
                    path: 'hello/test.md'
                }
            ])
            .then(function(_output) {
                output = _output;
            });
        });

        it('should correctly generate an index.html', function() {
            output.should.have.file('index.html');
        });

        it('should correctly generate files in folder', function() {
            output.should.have.file('hello/index.html');
            output.should.have.file('hello/test.html');
        });
    });

    describe('Multilingual Book', function() {
        var output;

        before(function() {
            return mock.outputBook(WebsiteOutput, {
                'LANGS.md': '# Languages\n\n'
                    + '* [en](./en)\n'
                    + '* [fr](./fr)\n\n',
                'en/README.md': '# Hello',
                'fr/README.md': '# Bonjour'

            })
            .then(function(_output) {
                output = _output;
            });
        });

        it('should correctly generate an index.html for each language', function() {
            output.should.have.file('en/index.html');
            output.should.have.file('fr/index.html');
        });

        it('should correctly copy assets', function() {
            output.should.have.file('gitbook/app.js');
        });

        it('should not copy assets for each language', function() {
            output.should.have.not.file('en/gitbook/app.js');
            output.should.have.not.file('fr/gitbook/app.js');
        });

        it('should correctly generate an index.html', function() {
            output.should.have.file('index.html');
        });
    });

    describe('Theming', function() {
        var output;

        before(function() {
            return mock.outputDefaultBook(WebsiteOutput, {
                '_layouts/website/page.html': '{% extends "website/page.html" %}{% block body %}{{ super() }}

{% endblock %}'

            })
            .then(function(_output) {
                output = _output;
            });
        });

        it('should extend default theme', function() {
            var readme = fs.readFileSync(output.resolve('index.html'), 'utf-8');

            readme.should.be.html({
                '#theming-added': {
                    count: 1
                }
            });
        });
    });
});

<commit_msg>Fix tests for copy of website theme<commit_after>var fs = require('fs');

var mock = require('./mock');
var WebsiteOutput = require('../lib/output/website');

describe('Website Output', function() {

    describe('Sample Book', function() {
        var output;

        before(function() {
            return mock.outputDefaultBook(WebsiteOutput)
            .then(function(_output) {
                output = _output;
            });
        });

        it('should correctly generate an index.html', function() {
            output.should.have.file('index.html');
        });

        it('should correctly copy assets', function() {
            output.should.have.file('gitbook/gitbook.js');
            output.should.have.file('gitbook/theme.js');
            output.should.have.file('gitbook/images/favicon.ico');
        });

        it('should correctly copy plugins', function() {
            output.should.have.file('gitbook/gitbook-plugin-highlight/website.css');
        });
    });

    describe('Book with chapters', function() {
        var output;

        before(function() {
            return mock.outputDefaultBook(WebsiteOutput, {
                'hello/README.md': '# Hello',
                'hello/test.md': '# Test'
            }, [
                {
                    title: 'Hello',
                    path: 'hello/README.md'
                },
                {
                    title: 'Test',
                    path: 'hello/test.md'
                }
            ])
            .then(function(_output) {
                output = _output;
            });
        });

        it('should correctly generate an index.html', function() {
            output.should.have.file('index.html');
        });

        it('should correctly generate files in folder', function() {
            output.should.have.file('hello/index.html');
            output.should.have.file('hello/test.html');
        });
    });

    describe('Multilingual Book', function() {
        var output;

        before(function() {
            return mock.outputBook(WebsiteOutput, {
                'LANGS.md': '# Languages\n\n'
                    + '* [en](./en)\n'
                    + '* [fr](./fr)\n\n',
                'en/README.md': '# Hello',
                'fr/README.md': '# Bonjour'

            })
            .then(function(_output) {
                output = _output;
            });
        });

        it('should correctly generate an index.html for each language', function() {
            output.should.have.file('en/index.html');
            output.should.have.file('fr/index.html');
        });

        it('should correctly copy assets', function() {
            output.should.have.file('gitbook/gitbook.js');
            output.should.have.file('gitbook/theme.js');
        });

        it('should not copy assets for each language', function() {
            output.should.have.not.file('en/gitbook/gitbook.js');
            output.should.have.not.file('fr/gitbook/gitbook.js');

            output.should.have.not.file('en/gitbook/theme.js');
            output.should.have.not.file('fr/gitbook/theme.js');
        });

        it('should correctly generate an index.html', function() {
            output.should.have.file('index.html');
        });
    });

    describe('Theming', function() {
        var output;

        before(function() {
            return mock.outputDefaultBook(WebsiteOutput, {
                '_layouts/website/page.html': '{% extends "website/page.html" %}{% block body %}{{ super() }}

{% endblock %}'

            })
            .then(function(_output) {
                output = _output;
            });
        });

        it('should extend default theme', function() {
            var readme = fs.readFileSync(output.resolve('index.html'), 'utf-8');

            readme.should.be.html({
                '#theming-added': {
                    count: 1
                }
            });
        });
    });
});

<|endoftext|>


<commit_before>import React from 'react'
import graphqlApi from '../graphql-api'
import lodash from 'lodash'

export default class Group extends React.Component {
  state = {
    group: null
  }

  componentWillMount = async () => {
    const query = `{
                	group(name: "${this.props.name}") {
                    name
                    serviceAccessRules {
                      service {
                        id
                        displayName
                        roles
                      }
                      accessRules {
                        asset
                        role
                      }
                    }
                  }
                }`
    const response = await graphqlApi.request(query)

    this.setState({
      group: response.data.group
    })
  }

  removeService = (serviceId) => {
    console.log("todo: remove servcie")
  }

  isRoleEnabled = (role, accessRules) => {
    return !!lodash.find(accessRules, (rule) => rule.asset === "*" && (rule.role === "*" || rule.role === role))
  }

  render() {
    return (

{this.props.name}

      { this.state.group &&

Access Rules

                Service
                Roles
                Options

              {
                this.state.group.serviceAccessRules.map((serviceAccessRule) => (

                    {serviceAccessRule.service.displayName}

                        {serviceAccessRule.service.roles.map((role) => (

                            <button className={`button is-primary ${this.isRoleEnabled(role, serviceAccessRule.accessRules) ? '' : 'is-outlined'}`}>{role}</button>

                        ))}

                          <button className='button is-danger is-small' onClick={() => this.removeService(serviceAccessRule.service.id)}>Remove Service</button>

                ) )
              }

      }

)
  }
}
<commit_msg>make roles toggleable in group settings<commit_after>import React from 'react'
import graphqlApi from '../graphql-api'
import lodash from 'lodash'
import MessagesContainer from './messages-container'

export default class Group extends React.Component {
  state = {
    group: null
  }

  componentWillMount = async () => {
    const query = `{
                	group(name: "${this.props.name}") {
                    name
                    serviceAccessRules {
                      service {
                        id
                        displayName
                        roles
                      }
                      accessRules {
                        asset
                        role
                      }
                    }
                  }
                }`
    const response = await graphqlApi.request(query)

    this.setState({
      group: response.data.group
    })
  }

  removeService = (serviceId) => {
    console.log("todo: remove servcie")
  }

  isRoleEnabled = (role, accessRules) => {
    return !!lodash.find(accessRules, (rule) => rule.asset === "*" && (rule.role === role))
  }

  onRoleClicked = (event, role, serviceId) => {
    event.target.blur()
    const group = this.state.group
    const serviceAccessRule = lodash.find(group.serviceAccessRules, (sar) => sar.service.id === serviceId)
    const accessRules = serviceAccessRule.accessRules

    if (this.isRoleEnabled(role, accessRules)) {
      lodash.remove(accessRules, (rule) => rule.role === role)
    } else {
      accessRules.push({asset: "*", role: role})
    }

    this.save(group)
  }

  mapGroupToMutation = (group) => {
    return `mutation { setGroupAccessRules(
        name:"${group.name}",
        serviceAccessRules:[${group.serviceAccessRules.map(this.mapServiceAccessRuleToMutation).join(',')}]
      )
    }`
  }

  mapServiceAccessRuleToMutation = (serviceAccessRule) => {
    return `{
      serviceId:"${serviceAccessRule.service.id}",
      accessRules: [${serviceAccessRule.accessRules.map(this.mapAccessRuleToMutation).join(',')}]
    }`
  }

  mapAccessRuleToMutation = (accessRule) => {
    return `{
      asset: "${accessRule.asset}",
      role: "${accessRule.role}"
    }`
  }

  save = async (group) => {
    const query = this.mapGroupToMutation(group)
    let response = await graphqlApi.request(query)

    if (response.error) {
      this.messagesContainer.push({
        title: "Error Saving Group",
        body: response.error.message
      })
    } else {
      this.setState({ group: group })
    }
  }

  render() {
    return (

{this.props.name}

      { this.state.group &&

Access Rules

                Service
                Roles
                Options

              {
                this.state.group.serviceAccessRules.map((serviceAccessRule) => (

                    {serviceAccessRule.service.displayName}

                        {serviceAccessRule.service.roles.map((role) => (

                            <button
                              className={`button is-primary ${this.isRoleEnabled(role, serviceAccessRule.accessRules) ? '' : 'is-outlined'}`}
                              onClick={(e) => this.onRoleClicked(e, role, serviceAccessRule.service.id)}>
                              {role}
                            </button>

                        ))}

                          <button className='button is-danger is-small'
                            onClick={() => this.removeService(serviceAccessRule.service.id)}>Remove Service</button>

                ) )
              }

      }
      <MessagesContainer ref={(container) => { this.messagesContainer = container }} />

)
  }
}
<|endoftext|>


<commit_before>$(function() {
	socket = io.connect('https://api.misskey.xyz:1207/streaming/talk', { port: 1207 });

	socket.on('connected', function() {
		console.log('Connected');
		socket.json.emit('init', {
			'otherparty_id': $("html").attr("data-otherpartyId")
		});
	});

	socket.on('disconnect', function(client) {
	});

	socket.on('otherpartyMessage', function(message) {
		console.log('otherpartyMessage', message);
		$message.prependTo($('#stream > .messages')).show(200);
	});

	$('#postForm').find('.imageAttacher input[name=image]').change(function() {
		var $input = $(this);
		var file = $(this).prop('files')[0];
		if (!file.type.match('image.*')) return;
		var reader = new FileReader();
		reader.onload = function() {
			var $img = $('').attr('src', reader.result);
			$input.parent('.imageAttacher').find('p, img').remove();
			$input.parent('.imageAttacher').append($img);
		};
		reader.readAsDataURL(file);
	});

	$('#postForm').submit(function(event) {
		event.preventDefault();
		var $form = $(this);
		var $submitButton = $form.find('[type=submit]');

		$submitButton.attr('disabled', true);
		$submitButton.text('Updating...');

		$.ajax('https://api.misskey.xyz/talk/say', {
			type: 'post',
			processData: false,
			contentType: false,
			data: new FormData($form[0]),
			dataType: 'json',
			xhrFields: {
				withCredentials: true
			}
		}).done(function(data) {
			$form[0].reset();
			$form.find('textarea').focus();
			$form.find('.imageAttacher').find('p, img').remove();
			$form.find('.imageAttacher').append($('

'));
			$submitButton.attr('disabled', false);
			$submitButton.text('Update');
		}).fail(function(data) {
			$form[0].reset();
			$form.find('textarea').focus();
			/*alert('error');*/
			$submitButton.attr('disabled', false);
			$submitButton.text('Update');
		});
	});

	setInterval(function() {
		var now = new Date();
		$('time').each(function() {
			function pad2(n) { return n < 10 ? '0' + n : n }
			var date = new Date($(this).attr('datetime'));
			var ago = ~~((now - date) / 1000);
			var timeText =
				ago >= 31536000 ? ~~(ago / 31536000) + "年前" :
				ago >= 2592000 ? ~~(ago / 2592000) + "ヶ月前" :
				ago >= 604800 ? ~~(ago / 604800) + "週間前" :
				ago >= 86400 ? ~~(ago / 86400) + "日前" :
				ago >= 3600 ? ~~(ago / 3600) + "時間前" :
				ago >= 60 ? ~~(ago / 60) + "分前" :
				ago >= 5 ? ~~(ago % 60) + "秒前" :
				ago < 5 ? 'いま' : "";
			$(this).text(timeText);
		});
	}, 1000);
});

<commit_msg>Log disconnect message<commit_after>$(function() {
	socket = io.connect('https://api.misskey.xyz:1207/streaming/talk', { port: 1207 });

	socket.on('connected', function() {
		console.log('Connected');
		socket.json.emit('init', {
			'otherparty_id': $("html").attr("data-otherpartyId")
		});
	});

	socket.on('disconnect', function(client) {
		console.log('Disconnected');
	});

	socket.on('otherpartyMessage', function(message) {
		console.log('otherpartyMessage', message);
		$message.prependTo($('#stream > .messages')).show(200);
	});

	$('#postForm').find('.imageAttacher input[name=image]').change(function() {
		var $input = $(this);
		var file = $(this).prop('files')[0];
		if (!file.type.match('image.*')) return;
		var reader = new FileReader();
		reader.onload = function() {
			var $img = $('').attr('src', reader.result);
			$input.parent('.imageAttacher').find('p, img').remove();
			$input.parent('.imageAttacher').append($img);
		};
		reader.readAsDataURL(file);
	});

	$('#postForm').submit(function(event) {
		event.preventDefault();
		var $form = $(this);
		var $submitButton = $form.find('[type=submit]');

		$submitButton.attr('disabled', true);
		$submitButton.text('Updating...');

		$.ajax('https://api.misskey.xyz/talk/say', {
			type: 'post',
			processData: false,
			contentType: false,
			data: new FormData($form[0]),
			dataType: 'json',
			xhrFields: {
				withCredentials: true
			}
		}).done(function(data) {
			$form[0].reset();
			$form.find('textarea').focus();
			$form.find('.imageAttacher').find('p, img').remove();
			$form.find('.imageAttacher').append($('

'));
			$submitButton.attr('disabled', false);
			$submitButton.text('Update');
		}).fail(function(data) {
			$form[0].reset();
			$form.find('textarea').focus();
			/*alert('error');*/
			$submitButton.attr('disabled', false);
			$submitButton.text('Update');
		});
	});

	setInterval(function() {
		var now = new Date();
		$('time').each(function() {
			function pad2(n) { return n < 10 ? '0' + n : n }
			var date = new Date($(this).attr('datetime'));
			var ago = ~~((now - date) / 1000);
			var timeText =
				ago >= 31536000 ? ~~(ago / 31536000) + "年前" :
				ago >= 2592000 ? ~~(ago / 2592000) + "ヶ月前" :
				ago >= 604800 ? ~~(ago / 604800) + "週間前" :
				ago >= 86400 ? ~~(ago / 86400) + "日前" :
				ago >= 3600 ? ~~(ago / 3600) + "時間前" :
				ago >= 60 ? ~~(ago / 60) + "分前" :
				ago >= 5 ? ~~(ago % 60) + "秒前" :
				ago < 5 ? 'いま' : "";
			$(this).text(timeText);
		});
	}, 1000);
});

<|endoftext|>


<commit_before>$(document).ready(function() {

    var qst = [
        "中华文明历史悠久，中华文化博大精深。在中国一草一木皆有神。那么，请问，从2000前至今的中国美女中，谁最美？",
        "有一种信仰叫做，我只信你。那么，请问，对于逗逗王国中，这个‘你’指的是谁？",
        "晴对雨，霞对虹，大漠对苍穹。那么，牛对什么？",
        "如果逗逗王国的新晋驾驶员必须要买一辆车送给国王，那么你认为逗逗国王会喜欢哪一辆？"
    ];

    var ans = [
        {"A":"杨玉环", "B":"樊灵洁", "C":"西施", "D":"彭丽媛"},
        {"A":"樊灵洁", "B":"逗逗", "C":"国王", "D":"妈妈"},
        {"A":"羊", "B":"草", "C":"琴", "D":"月亮"},
        {"A":"飞鸽牌自行车", "B":"艾玛电动车", "C":"smart", "D":"法拉利"}
    ];

    // 第几个题目的下标
    var index = 0;

    // 判断答题结果
    //标准答案
    var sta = ["B","D","C","A"];

    // 你的答案
    // var yourAnswer;
    var yours = [];

    // 分数
    var score = 0;

    // 给 radio添加点击事件
    $(':radio').click(function(index) {
        // 获得选中答案的 val
        // yourAnswer = $("input[name='a']:checked").val();
        yours[index] = $(this).val();
    });

    for (var i = 0; i < sta.length; i++) {
        if (sta[i] == yours[i]) {
            score = score + 25;
        }
    }

    function showQue(index) {
        $('#question').text((index+1) + "、" + qst[index]);
        // 答案的下标
        var i = 0;
        var x = ["A","B","C","D"];
        var radioSpan = $('#answer input + span');
        for (x[i] in ans[index]) {
            radioSpan.eq(i).text(x[i] + '、' + ans[index][x[i]]);
            i++;
        }

    }

    // 可以在CSS中设置这些样式，在这里用 removeAttr 移除 display 的属性
    $('.start').click(function() {
        $('.content').css('display', 'block');
        $('.btn').css('display', 'inline-block');
        $('.btn').css('position', 'fixed');
        $('.btn').css('bottom', '70px');
        $('.btn').css('margin-left', '450px');
        $('.btn').css('margin-bottom', '40px');
        $('#last').css('margin-right', '150px');
        $('#next').css('margin-right', '150px');
        $('.chu').css('display', 'none');

        showQue(index);

    });

    $('#last').click(function() {
        index--;
        if (index < 0) {
            alert("已经到第一题了！");
            index = 0;
        }
        showQue(index);
    });

    $('#next').click(function() {
        index++;
        if (index > 3) {
            alert("没有更多题目了！");
            index = 3;
        }
        showQue(index);
    });

    $('#subm').click(function() {
        $('#answer').css('display', 'none');
        $('#question').css('display', 'none');
        $('.btn').css('display', 'none');
        $('.result').css('display', 'block');
        $('#staderd').append(sta);
        $('#yours').append(yours);
        $('#score').append(score);
    });

    $('#again').click(function() {
        self.location='apple.html';
    });

    $('#out').click(function() {
        self.location='out.html';
    });

});
<commit_msg>追加了测试者的答案，并计算出最后得分结果<commit_after>$(document).ready(function() {

    var qst = [
        "中华文明历史悠久，中华文化博大精深。在中国一草一木皆有神。那么，请问，从2000前至今的中国美女中，谁最美？",
        "有一种信仰叫做，我只信你。那么，请问，对于逗逗王国中，这个‘你’指的是谁？",
        "晴对雨，霞对虹，大漠对苍穹。那么，牛对什么？",
        "如果逗逗王国的新晋驾驶员必须要买一辆车送给国王，那么你认为逗逗国王会喜欢哪一辆？"
    ];

    var ans = [
        {"A":"杨玉环", "B":"樊灵洁", "C":"西施", "D":"彭丽媛"},
        {"A":"樊灵洁", "B":"逗逗", "C":"国王", "D":"妈妈"},
        {"A":"羊", "B":"草", "C":"琴", "D":"月亮"},
        {"A":"飞鸽牌自行车", "B":"艾玛电动车", "C":"smart", "D":"法拉利"}
    ];

    // 第几个题目的下标
    var index = 0;

    // 判断答题结果
    //标准答案
    var sta = ["B","D","C","A"];

    // 你的答案
    // var yourAnswer;
    var yours = [];

    // 分数
    var score = 0;

    // 给 radio添加点击事件
    function choose() {
        $(':radio').click(function() {
            // 获得选中答案的 val
            // yourAnswer = $("input[name='a']:checked").val();
            yours[index] = $(this).val();
            //测试数据是否存入yours【】
            // alert (yours[index]);
        });
    }

    //计算最后成绩
    function result() {
        for (var i = 0; i < sta.length; i++) {
            if (sta[i] == yours[i]) {
                score = score + 25;
            }
        }
    }

    // 显示题目和答案
    function showQue(index) {
        $('#question').text((index+1) + "、" + qst[index]);
        // 答案的下标
        var i = 0;
        var x = ["A","B","C","D"];
        var radioSpan = $('#answer input + span');
        for (x[i] in ans[index]) {
            radioSpan.eq(i).text(x[i] + '、' + ans[index][x[i]]);
            i++;
        }

        choose(index);

    }

    // 可以在CSS中设置这些样式，在这里用 removeAttr 移除 display 的属性
    $('.start').click(function() {
        $('.content').css('display', 'block');
        $('.btn').css('display', 'inline-block');
        $('.btn').css('position', 'fixed');
        $('.btn').css('bottom', '70px');
        $('.btn').css('margin-left', '450px');
        $('.btn').css('margin-bottom', '40px');
        $('#last').css('margin-right', '150px');
        $('#next').css('margin-right', '150px');
        $('.chu').css('display', 'none');

        showQue(index);
        choose(index);
    });

    $('#last').click(function() {
        index--;
        if (index < 0) {
            alert("已经到第一题了！");
            index = 0;
        }
        showQue(index);
        choose(index);
    });

    $('#next').click(function() {
        index++;
        if (index > 3) {
            alert("没有更多题目了！");
            index = 3;
        }
        showQue(index);
        choose(index);
    });

    $('#subm').click(function() {
        $('#answer').css('display', 'none');
        $('#question').css('display', 'none');
        $('.btn').css('display', 'none');
        $('.result').css('display', 'block');

        result();

        $('#staderd').append(sta);
        $('#yours').append(yours);
        $('#score').append(score);
    });

    $('#again').click(function() {
        self.location='apple.html';
    });

    $('#out').click(function() {
        self.location='out.html';
    });

});
<|endoftext|>


<commit_before>const roles = require("const.roles");

const clearCreepsMemory = require("func.clearCreepsMemory");
const buildCreepsIfNeeded = require("func.buildCreepsIfNeeded");

const actions = new Map([
    [roles.HARVESTER, require("action.harvest")],
    [roles.UPGRADER, require("action.upgrade")]
]);

module.exports.loop = () => {

    clearCreepsMemory();

    Object.keys(Game.spawns).forEach((spawnName) => {
        const spawn = Game.spawns[spawnName];
        buildCreepsIfNeeded(spawn, new Map([
            [roles.BUILDER, 1],
            [roles.HARVESTER, 1],
            [roles.UPGRADER, 1]
        ]));
    });

    Object.keys(Game.creeps).forEach((creepName) => {
        const creep = Game.creeps[creepName];
        const creepRole = creep.memory.role;
        if (!creepRole) {
            console.log("no role assigned to creep: " + creepName);
            return;
        }

        const action = actions.get(creepRole);

        if (!action) {
            console.log("no action for role: " + creepRole);
            return;
        }

        action(creep);
    });
};<commit_msg>Adds the building action to the main loop.<commit_after>const roles = require("const.roles");

const clearCreepsMemory = require("func.clearCreepsMemory");
const buildCreepsIfNeeded = require("func.buildCreepsIfNeeded");

const actions = new Map([
    [roles.BUILDER, require("action.build")],
    [roles.HARVESTER, require("action.harvest")],
    [roles.UPGRADER, require("action.upgrade")]
]);

module.exports.loop = () => {

    clearCreepsMemory();

    Object.keys(Game.spawns).forEach((spawnName) => {
        const spawn = Game.spawns[spawnName];
        buildCreepsIfNeeded(spawn, new Map([
            [roles.BUILDER, 1],
            [roles.HARVESTER, 1],
            [roles.UPGRADER, 1]
        ]));
    });

    Object.keys(Game.creeps).forEach((creepName) => {
        const creep = Game.creeps[creepName];
        const creepRole = creep.memory.role;
        if (!creepRole) {
            console.log("no role assigned to creep: " + creepName);
            return;
        }

        const action = actions.get(creepRole);

        if (!action) {
            console.log("no action for role: " + creepRole);
            return;
        }

        action(creep);
    });
};<|endoftext|>


<commit_before>/* wim -- modal text editor
   Haskell-inspired type signatures/comments
   Rust-inspired type names:  (uN: unsigned N-bit int), (s: string), (f: float)
 */
'use strict';
/* Utils */
/* zip : [(x,y)] -> ([x],[y]) */
const zip=xs=>xs[0].map((_,y)=>xs.map(x=>x[y]));
/* curry : ((x,y) -> z) -> (x -> y -> z) */
const curry=(f,...x)=>f.length>x.length?(...y)=>curry(f,...x,...y):f(...x);

const testwrite=c=>{
    c.clearRect(0,0,c.canvas.width,c.canvas.height);
    c.font='16px monospace';
    const lines=[
        'TODO keyboard input',
        '- inputs accumulate until they can be recognized as \'operations\', then are pushed to history stack',
        '- \'insert mode\' inputs aren\'t saved.'
    ];
    c.fillText(lines.reduce((x,y)=>x+y+'\n',''),20,30);
};

/* TODO keyboard input
   - inputs accumulate until they can be recognized as 'operations', then are pushed to history stack
   - 'insert mode' inputs aren't saved */
/* key_transform : KeyboardEvent -> [UnicodeKey, MillisecondTimestamp, IsKeyDown, ModifierCode]
   key_transform : o -> [s, u64, u1, u4] */
const key_transform=key_event=>[
    key_event.key,
    key_event.timeStamp|0,
    key_event.type=='keydown'|0,
    ['altKey','ctrlKey','metaKey','shiftKey']
        .map(y=>key_event[y]|0)
        .reduce((x,y,i,arr)=>x+y*Math.pow(2,arr.length-1-i),0)
];

/* down_keys : [s, u64, u1, u4] -> u1 */
const down_keys=keys=>keys.filter(x=>x[2]);

let Keys=[];
window.addEventListener('keydown',x=>Keys.push(key_transform(x)));
window.addEventListener('keyup',x=>Keys.push(key_transform(x)));

const DEBUG=1;
const resize_handler=c=>{
    const dpr=window.devicePixelRatio, h=window.innerHeight, w=window.innerWidth;
    [c.canvas.height,c.canvas.width]=[h,w].map(x=>dpr*x);
    [c.canvas.style.height,c.canvas.style.width]=[h,w].map(x=>x+'px');
    c.scale(dpr,dpr);
    if(DEBUG){
        //console.log(`DEBUG: ${DEBUG}`);
        testwrite(c);
    }
};
const ctx=document.getElementById('c').getContext('2d');
window.addEventListener('resize',()=>resize_handler(ctx));
window.addEventListener('DOMContentLoaded',()=>resize_handler(ctx));
<commit_msg>filtering some keys<commit_after>/* wim -- modal text editor
   Haskell-inspired type signatures/comments
   Rust-inspired type names:  (uN: unsigned N-bit int), (s: string), (f: float)
*/
'use strict';
/* Utils */
/* zip : [(x,y)] -> ([x],[y]) */
const zip=xs=>xs[0].map((_,y)=>xs.map(x=>x[y]));
/* curry : ((x,y) -> z) -> (x -> y -> z) */
const curry=(f,...x)=>f.length>x.length?(...y)=>curry(f,...x,...y):f(...x);

const testwrite=c=>{
    c.clearRect(0,0,c.canvas.width,c.canvas.height);
    c.font='16px monospace';
    const lines=[
        'TODO keyboard input',
        '- inputs accumulate until they can be recognized as \'operations\', then are pushed to history stack',
        '- \'insert mode\' inputs aren\'t saved.'
    ];
    c.fillText(lines.reduce((x,y)=>x+y+'\n',''),20,30);
};

/* keyboard input -- RawKeys accumulate until:
   - an editing operation occurs (push op to history stack, clear RawKeys)
   - a mode change (normal -> insert) occurs (accumulate string instead of RawKeys)
   - macro recording begins
   - there are 100+ of them
*/

/* RawKeys : [s, u64, u1, u4] */
/* key_transform : KeyboardEvent -> [UnicodeKey, MillisecondTimestamp, IsKeyDown, ModifierCode]
   key_transform : o -> RawKeys */
const key_transform=key_event=>[
    key_event.key,
    key_event.timeStamp|0,
    key_event.type=='keydown'|0,
    ['altKey','ctrlKey','metaKey','shiftKey']
        .map(y=>key_event[y]|0)
        .reduce((x,y,i,arr)=>x+y*Math.pow(2,arr.length-1-i),0)
];

/* pressed_keys : RawKeys -> RawKeys */
const pressed_keys=keys=>keys.filter(x=>x[2]);

const Commands={
    //    Escape: escape,
    //    Tab: insert_tab,
};
const get_command=keys=>{
    // parse escape codes
    return keys;
};

let RawKeys=[];
window.addEventListener('keydown',x=>{
    const kt=key_transform(x),
          pd=[ /* prevent defaults for these chords */
              ['Escape',-1],
              ['l',2],
              ['l',4],
          ].find(i=>i[0]===kt[0]&&(i[1]<0||i[1]===kt[3]));
    if(pd!=null){x.preventDefault();console.log(`prevented ${pd}`)}
    RawKeys.push(kt);

    const pk=pressed_keys(RawKeys);
    console.table(get_command(pk).slice(-4));
});
window.addEventListener('keyup',x=>RawKeys.push(key_transform(x)));

const DEBUG=1;
const resize_handler=c=>{
    const dpr=window.devicePixelRatio, h=window.innerHeight, w=window.innerWidth;
    [c.canvas.height,c.canvas.width]=[h,w].map(x=>dpr*x);
    [c.canvas.style.height,c.canvas.style.width]=[h,w].map(x=>x+'px');
    c.scale(dpr,dpr);
    if(DEBUG){
        testwrite(c);
    }
};
const ctx=document.getElementById('c').getContext('2d');
window.addEventListener('resize',()=>resize_handler(ctx));
window.addEventListener('DOMContentLoaded',()=>resize_handler(ctx));
<|endoftext|>