<commit_before>describe("Throttled observables", function() {

    it("Should notify subscribers asynchronously after writes stop for the specified timeout duration", function() {
        var observable = ko.observable('A').extend({ throttle: 50 });
        var notifiedValues = [];
        observable.subscribe(function(value) {
            notifiedValues.push(value);
        });

        // Mutate a few times
        observable('B');
        observable('C');
        observable('D');
        expect(notifiedValues.length).toEqual(0); // Should not notify synchronously

        // Wait
        waits(20);
        runs(function() {
            // Mutate more
            observable('E');
            observable('F');
            expect(notifiedValues.length).toEqual(0); // Should not notify until end of throttle timeout
        });

        // Wait until after timeout
        waitsFor(function() {
            return notifiedValues.length > 0;
        }, 60);
        runs(function() {
            expect(notifiedValues.length).toEqual(1);
            expect(notifiedValues[0]).toEqual("F");
        });
    });
});

describe("Throttled dependent observables", function() {

    it("Should notify subscribers asynchronously after dependencies stop updating for the specified timeout duration", function() {
        var underlying = ko.observable();
        var asyncDepObs = ko.dependentObservable(function() {
            return underlying();
        }).extend({ throttle: 100 });
        var notifiedValues = [];
        asyncDepObs.subscribe(function(value) {
            notifiedValues.push(value);
        });

        // Check initial state
        expect(asyncDepObs()).toBeUndefined();

        // Mutate
        underlying('New value');
        expect(asyncDepObs()).toBeUndefined(); // Should not update synchronously
        expect(notifiedValues.length).toEqual(0);

        // After 50ms, still shouldn't have evaluated
        waits(50);
        runs(function() {
            expect(asyncDepObs()).toBeUndefined(); // Should not update until throttle timeout
            expect(notifiedValues.length).toEqual(0);
        });

        // Now wait for throttle timeout
        waitsFor(function() {
            return notifiedValues.length > 0;
        }, 60);
        runs(function() {
            expect(asyncDepObs()).toEqual('New value');
            expect(notifiedValues.length).toEqual(1);
            expect(notifiedValues[0]).toEqual('New value');
        });
    });

    it("Should run evaluator only once when dependencies stop updating for the specified timeout duration", function() {
        var evaluationCount = 0;
        var someDependency = ko.observable();
        var asyncDepObs = ko.dependentObservable(function() {
            evaluationCount++;
            return someDependency();
        }).extend({ throttle: 100 });

        // Mutate a few times synchronously
        expect(evaluationCount).toEqual(1); // Evaluates synchronously when first created, like all dependent observables
        someDependency("A");
        someDependency("B");
        someDependency("C");
        expect(evaluationCount).toEqual(1); // Should not re-evaluate synchronously when dependencies update

        // Also mutate async
        waits(10);
        runs(function() {
            someDependency("D");
            expect(evaluationCount).toEqual(1);
        });

        // Now wait for throttle timeout
        waitsFor(function() {
            return evaluationCount > 1;
        }, 110);
        runs(function() {
            expect(evaluationCount).toEqual(2); // Finally, it's evaluated
            expect(asyncDepObs()).toEqual("D");
        });
    });
});<commit_msg>Workaround spurious failure in async test<commit_after>describe("Throttled observables", function() {

    it("Should notify subscribers asynchronously after writes stop for the specified timeout duration", function() {
        var observable, notifiedValues;

        waits(10); // Was getting spurious failures (blocks running out of order, mainly on IE) if the first item queued wasn't a "wait"
        runs(function() {
            observable = ko.observable('A').extend({ throttle: 50 });
            notifiedValues = [];
            observable.subscribe(function(value) {
                notifiedValues.push(value);
            });

            // Mutate a few times
            observable('B');
            observable('C');
            observable('D');
            expect(notifiedValues.length).toEqual(0); // Should not notify synchronously
        });

        // Wait
        waits(20);
        runs(function() {
            // Mutate more
            observable('E');
            observable('F');
            expect(notifiedValues.length).toEqual(0); // Should not notify until end of throttle timeout
        });

        // Wait until after timeout
        waitsFor(function() {
            return notifiedValues.length > 0;
        }, 60);
        runs(function() {
            expect(notifiedValues.length).toEqual(1);
            expect(notifiedValues[0]).toEqual("F");
        });
    });
});

describe("Throttled dependent observables", function() {

    it("Should notify subscribers asynchronously after dependencies stop updating for the specified timeout duration", function() {
        var underlying = ko.observable();
        var asyncDepObs = ko.dependentObservable(function() {
            return underlying();
        }).extend({ throttle: 100 });
        var notifiedValues = [];
        asyncDepObs.subscribe(function(value) {
            notifiedValues.push(value);
        });

        // Check initial state
        expect(asyncDepObs()).toBeUndefined();

        // Mutate
        underlying('New value');
        expect(asyncDepObs()).toBeUndefined(); // Should not update synchronously
        expect(notifiedValues.length).toEqual(0);

        // After 50ms, still shouldn't have evaluated
        waits(50);
        runs(function() {
            expect(asyncDepObs()).toBeUndefined(); // Should not update until throttle timeout
            expect(notifiedValues.length).toEqual(0);
        });

        // Now wait for throttle timeout
        waitsFor(function() {
            return notifiedValues.length > 0;
        }, 60);
        runs(function() {
            expect(asyncDepObs()).toEqual('New value');
            expect(notifiedValues.length).toEqual(1);
            expect(notifiedValues[0]).toEqual('New value');
        });
    });

    it("Should run evaluator only once when dependencies stop updating for the specified timeout duration", function() {
        var evaluationCount = 0;
        var someDependency = ko.observable();
        var asyncDepObs = ko.dependentObservable(function() {
            evaluationCount++;
            return someDependency();
        }).extend({ throttle: 100 });

        // Mutate a few times synchronously
        expect(evaluationCount).toEqual(1); // Evaluates synchronously when first created, like all dependent observables
        someDependency("A");
        someDependency("B");
        someDependency("C");
        expect(evaluationCount).toEqual(1); // Should not re-evaluate synchronously when dependencies update

        // Also mutate async
        waits(10);
        runs(function() {
            someDependency("D");
            expect(evaluationCount).toEqual(1);
        });

        // Now wait for throttle timeout
        waitsFor(function() {
            return evaluationCount > 1;
        }, 110);
        runs(function() {
            expect(evaluationCount).toEqual(2); // Finally, it's evaluated
            expect(asyncDepObs()).toEqual("D");
        });
    });
});<|endoftext|>


<commit_before>window.context = window.describe;

describe(".extend", function() {
	describe("the names you might specify", function() {
		var value = {};
	  context("passed a single identifier", function() {
			beforeEach(function() {
			  extend('panda',value);
			});
	    it("creates a single object on the window", function() {
	      expect(window.panda).toBe(value);
	    });
	  });
		context("passed period-delimited identifiers", function() {
			beforeEach(function() {
			  extend('code.retreat',value);
			});
		  it("creates an object for each identifier", function() {
		    expect(window.code.retreat).toBe(value);
		  });
		});
		context("passed a humorously deep number of identifiers", function() {
		  beforeEach(function() {
		    extend('a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p.q.r.$',value);
		  });

			it("still works", function() {
			  expect(a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p.q.r.$).toBe(value);
			});
		});
	});

	describe("the stuff you might pass it", function() {
		context("like functions", function() {
			var func = function() {}, result;
			context("passed a new function", function() {
				beforeEach(function() {
				  result = extend('blerg',func);
				});
				it("defines the function", function() {
				  expect(blerg).toBe(func);
				});
				it("returns the function too", function() {
				  expect(result).toBe(func);
				});
			});
			context("passed a function when one already exists ", function() {
				var thrown,name = 'panda';
				beforeEach(function() {
				  extend(name,func);
					try {
						extend(name,function() {});
					} catch(e) {
						thrown = e;
					}
				});
				it("throws an error", function() {
				  expect(thrown).toBe('Cannot define a new function "'+name+'", because one is already defined.');
				});
			});
			context("passed a function when the one that exists is the same function", function() {
			  it("doesn't throw anything", function() {

			  });
			});
		});

		context("passed a new object", function() {

		});

		context("passed an object when one already exists", function() {

		});
	});
});

describe(".noConflict", function() {
	var theExtendBeingSpecifiedHere,result;
	beforeEach(function() {
		theExtendBeingSpecifiedHere = window.extend;
	  result = extend.noConflict();
	});
	afterEach(function() {
	  window.extend = theExtendBeingSpecifiedHere;
	});
	it("relinquishes control of window.extend to its previous owner", function() {
	  expect(window.previousOwnerOfExtend).toBe(window.extend);
	});
	it("returns the .extend function", function() {
	  expect(result).toBe(theExtendBeingSpecifiedHere);
	});
});<commit_msg>doesn't throw needlessly on functions<commit_after>window.context = window.describe;

describe(".extend", function() {
	describe("the names you might specify", function() {
		var value = {};
	  context("passed a single identifier", function() {
			beforeEach(function() {
			  extend('panda',value);
			});
	    it("creates a single object on the window", function() {
	      expect(window.panda).toBe(value);
	    });
	  });
		context("passed period-delimited identifiers", function() {
			beforeEach(function() {
			  extend('code.retreat',value);
			});
		  it("creates an object for each identifier", function() {
		    expect(window.code.retreat).toBe(value);
		  });
		});
		context("passed a humorously deep number of identifiers", function() {
		  beforeEach(function() {
		    extend('a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p.q.r.$',value);
		  });

			it("still works", function() {
			  expect(a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p.q.r.$).toBe(value);
			});
		});
	});

	describe("the stuff you might pass it", function() {
		context("like functions", function() {
			var func = function() {},
					name = 'panda',
					result;
			afterEach(function() {
			  delete window[name];
			});
			context("passed a new function", function() {
				beforeEach(function() {
				  result = extend(name,func);
				});
				it("defines the function", function() {
				  expect(window[name]).toBe(func);
				});
				it("returns the function too", function() {
				  expect(result).toBe(func);
				});
			});
			context("passed a function when one already exists ", function() {
				var thrown;
				beforeEach(function() {
				  extend(name,func);
					try {
						extend(name,function() {});
					} catch(e) {
						thrown = e;
					}
				});
				it("throws an error", function() {
				  expect(thrown).toBe('Cannot define a new function "'+name+'", because one is already defined.');
				});
			});
			context("passed a function when the one that exists is the same function", function() {
				var thrown;
				beforeEach(function() {
				  extend(name,func);
					try {
						extend(name,func);
					} catch(e) {
						thrown = e;
					}
				});
			  it("doesn't throw anything", function() {
					expect(thrown).not.toBeDefined();
			  });
			});
		});

		context("passed a new object", function() {

		});

		context("passed an object when one already exists", function() {

		});
	});
});

describe(".noConflict", function() {
	var theExtendBeingSpecifiedHere,result;
	beforeEach(function() {
		theExtendBeingSpecifiedHere = window.extend;
	  result = extend.noConflict();
	});
	afterEach(function() {
	  window.extend = theExtendBeingSpecifiedHere;
	});
	it("relinquishes control of window.extend to its previous owner", function() {
	  expect(window.previousOwnerOfExtend).toBe(window.extend);
	});
	it("returns the .extend function", function() {
	  expect(result).toBe(theExtendBeingSpecifiedHere);
	});
});<|endoftext|>


<commit_before>describe('LinkedList', function() {
    var list;

    beforeEach(function() {
        list = new datastructs.LinkedList();
    });

    it('should insert an element into an empty list', function() {
        list.insert('1', 0);
        expect(list.length()).toEqual(1);
        expect(list.toString()).toEqual('[1]');
    });

    it('should insert at head of non-empty list', function() {
        list.insert('1', 0);
        list.insert('2', 0);
        expect(list.length()).toEqual(2);
        expect(list.toString()).toEqual('[2,1]')
    });

    it('should insert between existing nodes', function() {
        list.insert('1', 0);
        list.insert('2', 0);
        list.insert('3', 1);
        expect(list.length()).toEqual(3);
        expect(list.toString()).toEqual('[2,3,1]');
    });

    it('should insert at the end of a non-empty list', function() {
        list.insert('1', 0);
        list.insert('2', 1);
        expect(list.length()).toEqual(2);
        expect(list.toString()).toEqual('[1,2]');
    });

    it('should remove an element from a specific position', function() {
        list.insert('1', 0);
        list.remove(0);
        expect(list.length()).toEqual(0);
        expect(list.toString()).toEqual('[]');
    });

    it('should remove an element in between two items', function() {
        list.insert('1', 0);
        list.insert('2', 0);
        list.insert('3', 0);
        list.remove(1);
        expect(list.length()).toEqual(2);
        expect(list.toString()).toEqual('[3,1]');
    });

    it('should remove an element at the end', function() {
        list.insert('1', 0);
        list.insert('2', 0);
        list.insert('3', 0);
        list.remove(2);
        expect(list.length()).toEqual(2);
        expect(list.toString()).toEqual('[3,2]');
    });

    it('#should throw out of bounds exception with negative index', function() {
        expect(function() {
            list.insert('1', -1);
        }).toThrowError('Out of bounds');
    });

    it('#should throw out of bounds exception with index greater than length', function() {
        expect(function() {
            list.insert('1', 1);
        }).toThrowError('Out of bounds');
    });
});<commit_msg>Updated specs for exception conditions<commit_after>describe('LinkedList', function() {
    it('should insert an element into an empty list', function() {
        var list = new datastructs.LinkedList();
        list.insert('1', 0);
        expect(list.length()).toEqual(1);
        expect(list.toString()).toEqual('[1]');
    });

    it('should insert at head of non-empty list', function() {
        var list = new datastructs.LinkedList();
        list.insert('1', 0);
        list.insert('2', 0);
        expect(list.length()).toEqual(2);
        expect(list.toString()).toEqual('[2,1]')
    });

    it('should insert between existing nodes', function() {
        var list = new datastructs.LinkedList();
        list.insert('1', 0);
        list.insert('2', 0);
        list.insert('3', 1);
        expect(list.length()).toEqual(3);
        expect(list.toString()).toEqual('[2,3,1]');
    });

    it('should insert at the end of a non-empty list', function() {
        var list = new datastructs.LinkedList();
        list.insert('1', 0);
        list.insert('2', 1);
        expect(list.length()).toEqual(2);
        expect(list.toString()).toEqual('[1,2]');
    });

    it('should remove an element from a specific position', function() {
        var list = new datastructs.LinkedList();
        list.insert('1', 0);
        list.remove(0);
        expect(list.length()).toEqual(0);
        expect(list.toString()).toEqual('[]');
    });

    it('should remove an element in between two items', function() {
        var list = new datastructs.LinkedList();
        list.insert('1', 0);
        list.insert('2', 0);
        list.insert('3', 0);
        list.remove(1);
        expect(list.length()).toEqual(2);
        expect(list.toString()).toEqual('[3,1]');
    });

    it('should remove an element at the end', function() {
        var list = new datastructs.LinkedList();
        list.insert('1', 0);
        list.insert('2', 0);
        list.insert('3', 0);
        list.remove(2);
        expect(list.length()).toEqual(2);
        expect(list.toString()).toEqual('[3,2]');
    });

    it('#should throw out of bounds exception with negative index', function() {
        expect(function() {
            var list = new datastructs.LinkedList();
            list.insert('1', -1);
        }).toThrow(new Error('OutOfBoundsException: index -1 is not within 0 and 0'));
    });

    it('#should throw out of bounds exception with index greater than length', function() {
        expect(function() {
            var list = new datastructs.LinkedList();
            list.insert('1', 1);
        }).toThrow(new Error('OutOfBoundsException: index 1 is not within 0 and 0'));
    });
});<|endoftext|>


<commit_before>/* eslint-disable */
'use strict';

describe('Peeracle.Peer', function () {
  var pa = null;
  var pb = null;
  var pasdp = null;
  var pbsdp = null;
  var paice = [];
  var pbice = [];

  it('should create a new peer', function () {
    pa = new Peeracle.Peer();
    expect(pa).toBeDefined();
  });

  it('should have it\'s members defined', function () {
    expect(pa.subscribe).toBeDefined();
    expect(pa.unsubscribe).toBeDefined();
    expect(pa.createOffer).toBeDefined();
    expect(pa.createAnswer).toBeDefined();
    expect(pa.setAnswer).toBeDefined();
    expect(pa.addIceCandidate).toBeDefined();
  });

  it('should have function members', function () {
    expect(typeof pa.subscribe).toBe('function');
    expect(typeof pa.unsubscribe).toBe('function');
    expect(typeof pa.createOffer).toBe('function');
    expect(typeof pa.createAnswer).toBe('function');
    expect(typeof pa.setAnswer).toBe('function');
    expect(typeof pa.addIceCandidate).toBe('function');
  });

  it('should create an offer', function (done) {
    var subscriber = {
      onIceCandidate: function (ice) {
        if (ice == null) {
          pa.unsubscribe(subscriber);
          done();
          return;
        }
        paice.push(ice);
      },
      onConnectionStateChange: function (state) {

      }
    };

    pa.subscribe(subscriber);
    pa.createOffer(function (sdp) {
      expect(typeof sdp).toBe('string');
      pasdp = sdp;
    }, function (error) {
      console.error(error);
      pasdp = null;
      expect(typeof pasdp).toBe('string');
      done();
    });
  }, 10000);

  it('should create another peer', function () {
    pb = new Peeracle.Peer();
    expect(pb).toBeDefined();
  });

  it('should create an answer', function (done) {
    var subscriber = {
      onIceCandidate: function (ice) {
        if (ice == null) {
          pb.unsubscribe(subscriber);
          done();
          return;
        }
        pbice.push(ice);
      },

      onConnectionStateChange: function (state) {

      }
    };

    pb.subscribe(subscriber);
    pb.createAnswer(pasdp, function (sdp) {
      expect(typeof sdp).toBe('string');
      pbsdp = sdp;
    }, function (error) {
      console.error(error);
      pbsdp = null;
      expect(typeof pbsdp).toBe('string');
      done();
    });
  }, 10000);

  it('should set the answer', function (done) {
    pa.setAnswer(pbsdp, function () {
      done();
    }, function (error) {
      console.error(error);
      pbsdp = null;
      expect(typeof pbsdp).toBe('string');
      done();
    });
  });

  it('should add every ice candidates', function (done) {
    var pastate = false;
    var pbstate = false;

    var pasubscriber = {
      onIceCandidate: function (ice) {

      },
      onConnectionStateChange: function (state) {
        if (state === 'completed' || state === 'connected') {
          pastate = true;
        }
        if (pastate === true && pbstate === true) {
          pa.unsubscribe(pasubscriber);
          pb.unsubscribe(pbsubscriber);
          done();
        }
      }
    };
    pa.subscribe(pasubscriber);

    var pbsubscriber = {
      onIceCandidate: function (ice) {

      },
      onConnectionStateChange: function (state) {
        if (state === 'completed' || state === 'connected') {
          pbstate = true;
        }
        if (pastate === true && pbstate === true) {
          pa.unsubscribe(pasubscriber);
          pb.unsubscribe(pbsubscriber);
          done();
        }
      }
    };
    pb.subscribe(pbsubscriber);

    for (var i = 0; i < pbice.length; i++) {
      pa.addIceCandidate(pbice[i], function () {
      }, function (error) {
        console.error(error);
        done();
      });
    }

    for (var i = 0; i < paice.length; i++) {
      pb.addIceCandidate(paice[i], function () {
      }, function (error) {
        console.error(error);
        done();
      });
    }
  });

  it('should close everything', function () {
    pa.close();
    pb.close();
  });
});<commit_msg>Node is now properly detected during tests<commit_after>/* eslint-disable */
'use strict';

if (typeof Peeracle === 'undefined') {
  var Peeracle = require('../../src/peeracle.js');
}

describe('Peeracle.Peer', function () {
  var pa = null;
  var pb = null;
  var pasdp = null;
  var pbsdp = null;
  var paice = [];
  var pbice = [];

  it('should create a new peer', function () {
    pa = new Peeracle.Peer();
    expect(pa).toBeDefined();
  });

  it('should have it\'s members defined', function () {
    expect(pa.subscribe).toBeDefined();
    expect(pa.unsubscribe).toBeDefined();
    expect(pa.createOffer).toBeDefined();
    expect(pa.createAnswer).toBeDefined();
    expect(pa.setAnswer).toBeDefined();
    expect(pa.addIceCandidate).toBeDefined();
  });

  it('should have function members', function () {
    expect(typeof pa.subscribe).toBe('function');
    expect(typeof pa.unsubscribe).toBe('function');
    expect(typeof pa.createOffer).toBe('function');
    expect(typeof pa.createAnswer).toBe('function');
    expect(typeof pa.setAnswer).toBe('function');
    expect(typeof pa.addIceCandidate).toBe('function');
  });

  it('should create an offer', function (done) {
    var subscriber = {
      onIceCandidate: function (ice) {
        if (ice == null) {
          pa.unsubscribe(subscriber);
          done();
          return;
        }
        paice.push(ice);
      },
      onConnectionStateChange: function (state) {

      }
    };

    pa.subscribe(subscriber);
    pa.createOffer(function (sdp) {
      expect(typeof sdp).toBe('string');
      pasdp = sdp;
    }, function (error) {
      console.error(error);
      pasdp = null;
      expect(typeof pasdp).toBe('string');
      done();
    });
  }, 10000);

  it('should create another peer', function () {
    pb = new Peeracle.Peer();
    expect(pb).toBeDefined();
  });

  it('should create an answer', function (done) {
    var subscriber = {
      onIceCandidate: function (ice) {
        if (ice == null) {
          pb.unsubscribe(subscriber);
          done();
          return;
        }
        pbice.push(ice);
      },

      onConnectionStateChange: function (state) {

      }
    };

    pb.subscribe(subscriber);
    pb.createAnswer(pasdp, function (sdp) {
      expect(typeof sdp).toBe('string');
      pbsdp = sdp;
    }, function (error) {
      console.error(error);
      pbsdp = null;
      expect(typeof pbsdp).toBe('string');
      done();
    });
  }, 10000);

  it('should set the answer', function (done) {
    pa.setAnswer(pbsdp, function () {
      done();
    }, function (error) {
      console.error(error);
      pbsdp = null;
      expect(typeof pbsdp).toBe('string');
      done();
    });
  });

  it('should add every ice candidates', function (done) {
    var pastate = false;
    var pbstate = false;

    var pasubscriber = {
      onIceCandidate: function (ice) {

      },
      onConnectionStateChange: function (state) {
        if (state === 'completed' || state === 'connected') {
          pastate = true;
        }
        if (pastate === true && pbstate === true) {
          pa.unsubscribe(pasubscriber);
          pb.unsubscribe(pbsubscriber);
          done();
        }
      }
    };
    pa.subscribe(pasubscriber);

    var pbsubscriber = {
      onIceCandidate: function (ice) {

      },
      onConnectionStateChange: function (state) {
        if (state === 'completed' || state === 'connected') {
          pbstate = true;
        }
        if (pastate === true && pbstate === true) {
          pa.unsubscribe(pasubscriber);
          pb.unsubscribe(pbsubscriber);
          done();
        }
      }
    };
    pb.subscribe(pbsubscriber);

    for (var i = 0; i < pbice.length; i++) {
      pa.addIceCandidate(pbice[i], function () {
      }, function (error) {
        console.error(error);
        done();
      });
    }

    for (var i = 0; i < paice.length; i++) {
      pb.addIceCandidate(paice[i], function () {
      }, function (error) {
        console.error(error);
        done();
      });
    }
  });

  it('should close everything', function () {
    pa.close();
    pb.close();
  });
});<|endoftext|>


<commit_before>//= require jquery
//= require underscore-min
//= require parsley-config
//= require parsley.min

var messageOrigin = window.location.protocol + "//" + window.location.host;
//var messageOrigin = 'http://cdn.swarmize.com';

function emitHeight() {
  // get the height of this, and send it to the parent + 300 or something.
  var thisHeight = $(".container").height();

  parent.postMessage('setHeight|'+thisHeight, messageOrigin);
}

$(document).ready(function() {
  emitHeight();

  $.listen('parsley:form:validated', function() {
    emitHeight();
  });

  $( "form" ).on( "submit", function( event ) {
    var form = this;
    event.preventDefault();
    console.log( $( this ).serialize() );
    console.log( $( this ).attr('action'));
    $.ajax({
      url: $(form).attr('action'),
      data: $(form).serialize(),
      type: 'POST'
    }).done(function(data) {
      $(".embeddable-swarm form").remove();
      var resultDiv = $("<div>");
      resultDiv.addClass('result').addClass('success');
      resultDiv.text("Thank you for your submission.");
      $(".embeddable-swarm .feedback").append(resultDiv);
      emitHeight();
      parent.postMessage('formsuccess', messageOrigin);
    }).fail(function(data) {
      $("div.failure").remove();
      var resultDiv = $("<div>");
      resultDiv.addClass('result').addClass('failure');
      resultDiv.text("We're sorry: there was an error, and your results could not be submitted.");
      $(".embeddable-swarm form p.submit").prepend(resultDiv);
      emitHeight();
    });
  });
});
<commit_msg>Round and round we go.<commit_after>//= require jquery
//= require underscore-min
//= require parsley-config
//= require parsley.min

function emitHeight() {
  var messageOrigin = window.location.protocol + "//" + window.location.host;
  // get the height of this, and send it to the parent + 300 or something.
  var thisHeight = $(".container").height();

  parent.postMessage('setHeight|'+thisHeight, messageOrigin);
}

$(document).ready(function() {
  var messageOrigin = window.location.protocol + "//" + window.location.host;
  emitHeight();

  $.listen('parsley:form:validated', function() {
    emitHeight();
  });

  $( "form" ).on( "submit", function( event ) {
    var form = this;
    event.preventDefault();
    console.log( $( this ).serialize() );
    console.log( $( this ).attr('action'));
    $.ajax({
      url: $(form).attr('action'),
      data: $(form).serialize(),
      type: 'POST'
    }).done(function(data) {
      $(".embeddable-swarm form").remove();
      var resultDiv = $("<div>");
      resultDiv.addClass('result').addClass('success');
      resultDiv.text("Thank you for your submission.");
      $(".embeddable-swarm .feedback").append(resultDiv);
      emitHeight();
      parent.postMessage('formsuccess', messageOrigin);
    }).fail(function(data) {
      $("div.failure").remove();
      var resultDiv = $("<div>");
      resultDiv.addClass('result').addClass('failure');
      resultDiv.text("We're sorry: there was an error, and your results could not be submitted.");
      $(".embeddable-swarm form p.submit").prepend(resultDiv);
      emitHeight();
    });
  });
});
<|endoftext|>


<commit_before>'use strict';

//  ---------------------------------------------------------------------------

const Exchange = require ('./base/Exchange');

//  ---------------------------------------------------------------------------

module.exports = class bitmart extends Exchange {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'bitmart',
            'name': 'Bitmart',
            'countries': [ 'US', 'CN', 'HK', 'KR' ],
            'rateLimit': 1000,
            'version': 'v2',
            'has': {
                'CORS': false,
                'fetchMarkets': true,
                'fetchTicker': true,
                'fetchTickers': true,
                'fetchCurrencies': true,
                'fetchOrderBook': true,
                'fetchTrades': true,
                'fetchOHLCV': true,
            },
            'urls': {
                'logo': 'https://www.bitmart.com/_nuxt/img/ed5c199.png',
                'api': 'https://openapi.bitmart.com',
                'www': 'https://www.bitmart.com/',
                'doc': 'https://github.com/bitmartexchange/bitmart-official-api-docs/blob/master/REST.md',
            },
            'requiredCredentials': {
                'apiKey': true,
                'secret': true,
            },
            'api': {
                'public': {
                    'get': [
                        'currencies',
                        'ping',
                        'steps',
                        'symbols',
                        'symbols_details',
                        'symbols/{symbol}/kline',
                        'symbols/{symbol}/orders',
                        'symbols/{symbol}/trades',
                        'ticker',
                        'time',
                    ],
                },
            },
        });
    }

    async fetchMarkets (params = {}) {
        let markets = await this.publicGetSymbolsDetails ();
        let result = [];
        for (let i = 0; i < markets.length; i++) {
            let market = markets[i];
            let id = market['id'];
            let base = market['base_currency'];
            let quote = market['quote_currency'];
            let symbol = base + '/' + quote;
            let precision = {
                'amount': 8,
                'price': market['price_max_precision'],
            };
            result.push ({
                'id': id,
                'symbol': symbol,
                'base': base,
                'quote': quote,
                'precision': precision,
                'info': market,
            });
        }
        return result;
    }

    parseTicker (ticker, market = undefined) {
        let timestamp = this.milliseconds ();
        let symbol = ticker['symbol_id'];
        let last = this.safeFloat (ticker, 'current_price');
        let percentage = this.safeFloat (ticker, 'fluctuation');
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': this.safeFloat (ticker, 'highest_price'),
            'low': this.safeFloat (ticker, 'lowest_price'),
            'bid': this.safeFloat (ticker, 'bid_1'),
            'bidVolume': this.safeFloat (ticker, 'bid_1_amount'),
            'ask': this.safeFloat (ticker, 'ask_1'),
            'askVolume': this.safeFloat (ticker, 'ask_1_amount'),
            'vwap': undefined,
            'open': undefined,
            'close': last,
            'last': last,
            'previousClose': undefined,
            'change': undefined,
            'percentage': percentage * 100,
            'average': undefined,
            'baseVolume': this.safeFloat (ticker, 'base_volume'),
            'quoteVolume': this.safeFloat (ticker, 'volume'),
            'info': ticker,
        };
    }

    async fetchTicker (symbol, params = {}) {
        await this.loadMarkets ();
        let ticker = await this.publicGetTicker (this.extend ({
            'symbol': this.marketId (symbol),
        }, params));
        return this.parseTicker (ticker);
    }

    async fetchTickers (symbols = undefined, params = {}) {
        await this.loadMarkets ();
        let tickers = await this.publicGetTicker (params);
        let result = {};
        for (let i = 0; i < tickers.length; i++) {
            let ticker = this.parseTicker (tickers[i]);
            let symbol = ticker['symbol'];
            result[symbol] = ticker;
        }
        return result;
    }

    async fetchCurrencies (params = {}) {
        let currencies = await this.publicGetCurrencies (params);
        let result = {};
        for (let i = 0; i < currencies.length; i++) {
            let currency = currencies[i];
            let id = currency['id'];
            result[id] = {
                'id': id,
                'code': id,
                'name': currency['name'],
                'info': currency, // the original payload
                'active': true,
            };
        }
        return result;
    }

    async fetchOrderBook (symbol, limit = undefined, params = {}) {
        await this.loadMarkets ();
        //
        // order query parameters:
        //    precision : price precision whose range is defined in symbol details : [optional]
        //
        let response = await this.publicGetSymbolsSymbolOrders (this.extend ({
            'symbol': this.marketId (symbol),
        }, params));
        return this.parseOrderBook (response, undefined, 'buys', 'sells', 'price', 'amount');
    }

    parseTrade (trade, market) {
        let timestamp = parseInt (trade['order_time']);
        return {
            'info': trade,
            'id': trade['tid'].toString (),
            'order': undefined,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': market['symbol'],
            'type': undefined,
            'side': trade['type'].toLowerCase (),
            'price': this.safeFloat (trade, 'price'),
            'amount': this.safeFloat (trade, 'amount'),
        };
    }

    async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let response = await this.publicGetSymbolsSymbolTrades (this.extend ({
            'symbol': this.marketId (symbol),
        }, params));
        return this.parseTrades (response, market, since, limit);
    }

    parseOHLCV (ohlcv, market = undefined, timeframe = '1m', since = undefined, limit = undefined) {
        return [
            parseInt (ohlcv['timestamp']) * 100,
            this.safeFloat (ohlcv, 'open_price'),
            this.safeFloat (ohlcv, 'highest_price'),
            this.safeFloat (ohlcv, 'lowest_price'),
            this.safeFloat (ohlcv, 'current_price'),
            this.safeFloat (ohlcv, 'volume'),
        ];
    }

    async fetchOHLCV (symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        //
        // ohlcv query parameters:
        //    from : start time of k-line data (in milliseconds) : [required]
        //    to : end time of k-line data (in milliseconds) : [required]
        //    step : steps of sampling (in minutes, default 1 minute) : [optional]
        //
        let response = await this.publicGetSymbolsSymbolKline (this.extend ({
            'symbol': this.marketId (symbol),
        }, params));
        return this.parseOHLCVs (response, market, timeframe, since, limit);
    }

    nonce () {
        return this.milliseconds ();
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let url = this.urls['api'] + '/' + this.version + '/' + path;
        let query = this.omit (params, this.extractParams (path));
        if (api === 'public') {
            if (Object.keys (query).length)
                url += '?' + this.urlencode (query);
        } else {
            // FIXME: need to fetch bearer token before sending a request. params must be sorted a-z.
            this.checkRequiredCredentials ();
            let nonce = this.nonce ();
            body = this.urlencode (this.extend ({ 'timestamp': nonce }, params));
            headers = {
                'Content-Type': 'application/json',
                'X-BM-TIMESTAMP': nonce,
                'X-BM-AUTHORIZATION': 'Bearer: <token>',
                'X-BM-SIGNATURE': this.hmac (this.encode (body), this.encode (this.secret), 'sha256'),
            };
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }
};
<commit_msg>Adding signIn method, and first private method.<commit_after>'use strict';

//  ---------------------------------------------------------------------------

const Exchange = require ('./base/Exchange');
const { AuthenticationError } = require ('./base/errors');
//  ---------------------------------------------------------------------------

module.exports = class bitmart extends Exchange {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'bitmart',
            'name': 'Bitmart',
            'countries': [ 'US', 'CN', 'HK', 'KR' ],
            'rateLimit': 1000,
            'version': 'v2',
            'has': {
                'CORS': true,
                'fetchMarkets': true,
                'fetchTicker': true,
                'fetchTickers': true,
                'fetchCurrencies': true,
                'fetchOrderBook': true,
                'fetchTrades': true,
                'fetchOHLCV': true,
                'fetchBalance': true,
            },
            'urls': {
                'logo': 'https://www.bitmart.com/_nuxt/img/ed5c199.png',
                'api': 'https://openapi.bitmart.com',
                'www': 'https://www.bitmart.com/',
                'doc': 'https://github.com/bitmartexchange/bitmart-official-api-docs/blob/master/REST.md',
            },
            'requiredCredentials': {
                'apiKey': true,
                'secret': true,
                'uid': true,
            },
            'api': {
                'token': {
                    'post': [
                        'authentication',
                    ],
                },
                'public': {
                    'get': [
                        'currencies',
                        'ping',
                        'steps',
                        'symbols',
                        'symbols_details',
                        'symbols/{symbol}/kline',
                        'symbols/{symbol}/orders',
                        'symbols/{symbol}/trades',
                        'ticker',
                        'time',
                    ],
                },
                'private': {
                    'get': [
                        'wallet',
                    ],
                },
            },
        });
    }

    async signIn (params = {}) {
        let message = this.apiKey + ':' + this.secret + ':' + this.uid;
        let data = {
            'grant_type': 'client_credentials',
            'client_id': this.apiKey,
            'client_secret': this.hmac (this.encode (message), this.encode (this.secret), 'sha256'),
        };
        let response = await this.tokenPostAuthentication (this.extend (data, params));
        let accessToken = this.safeString (response, 'access_token');
        if (!accessToken) {
            throw new AuthenticationError (this.id + ' signIn() failed to authenticate. Access token missing from response.');
        }
        let expiresIn = this.safeInteger (response, 'expires_in');
        this.options['expires'] = this.sum (this.nonce (), expiresIn * 1000);
        this.options['accessToken'] = accessToken;
        return response;
    }

    async fetchMarkets (params = {}) {
        let markets = await this.publicGetSymbolsDetails ();
        let result = [];
        for (let i = 0; i < markets.length; i++) {
            let market = markets[i];
            let id = market['id'];
            let base = market['base_currency'];
            let quote = market['quote_currency'];
            let symbol = base + '/' + quote;
            let precision = {
                'amount': 8,
                'price': market['price_max_precision'],
            };
            result.push ({
                'id': id,
                'symbol': symbol,
                'base': base,
                'quote': quote,
                'precision': precision,
                'info': market,
            });
        }
        return result;
    }

    parseTicker (ticker, market = undefined) {
        let timestamp = this.milliseconds ();
        let symbol = ticker['symbol_id'];
        let last = this.safeFloat (ticker, 'current_price');
        let percentage = this.safeFloat (ticker, 'fluctuation');
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': this.safeFloat (ticker, 'highest_price'),
            'low': this.safeFloat (ticker, 'lowest_price'),
            'bid': this.safeFloat (ticker, 'bid_1'),
            'bidVolume': this.safeFloat (ticker, 'bid_1_amount'),
            'ask': this.safeFloat (ticker, 'ask_1'),
            'askVolume': this.safeFloat (ticker, 'ask_1_amount'),
            'vwap': undefined,
            'open': undefined,
            'close': last,
            'last': last,
            'previousClose': undefined,
            'change': undefined,
            'percentage': percentage * 100,
            'average': undefined,
            'baseVolume': this.safeFloat (ticker, 'base_volume'),
            'quoteVolume': this.safeFloat (ticker, 'volume'),
            'info': ticker,
        };
    }

    async fetchTicker (symbol, params = {}) {
        await this.loadMarkets ();
        let ticker = await this.publicGetTicker (this.extend ({
            'symbol': this.marketId (symbol),
        }, params));
        return this.parseTicker (ticker);
    }

    async fetchTickers (symbols = undefined, params = {}) {
        await this.loadMarkets ();
        let tickers = await this.publicGetTicker (params);
        let result = {};
        for (let i = 0; i < tickers.length; i++) {
            let ticker = this.parseTicker (tickers[i]);
            let symbol = ticker['symbol'];
            result[symbol] = ticker;
        }
        return result;
    }

    async fetchCurrencies (params = {}) {
        let currencies = await this.publicGetCurrencies (params);
        let result = {};
        for (let i = 0; i < currencies.length; i++) {
            let currency = currencies[i];
            let id = currency['id'];
            result[id] = {
                'id': id,
                'code': id,
                'name': currency['name'],
                'info': currency, // the original payload
                'active': true,
            };
        }
        return result;
    }

    async fetchOrderBook (symbol, limit = undefined, params = {}) {
        await this.loadMarkets ();
        //
        // order query parameters:
        //    precision : price precision whose range is defined in symbol details : [optional]
        //
        let response = await this.publicGetSymbolsSymbolOrders (this.extend ({
            'symbol': this.marketId (symbol),
        }, params));
        return this.parseOrderBook (response, undefined, 'buys', 'sells', 'price', 'amount');
    }

    parseTrade (trade, market) {
        let timestamp = parseInt (trade['order_time']);
        return {
            'info': trade,
            'id': trade['tid'].toString (),
            'order': undefined,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': market['symbol'],
            'type': undefined,
            'side': trade['type'].toLowerCase (),
            'price': this.safeFloat (trade, 'price'),
            'amount': this.safeFloat (trade, 'amount'),
        };
    }

    async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let response = await this.publicGetSymbolsSymbolTrades (this.extend ({
            'symbol': this.marketId (symbol),
        }, params));
        return this.parseTrades (response, market, since, limit);
    }

    parseOHLCV (ohlcv, market = undefined, timeframe = '1m', since = undefined, limit = undefined) {
        return [
            parseInt (ohlcv['timestamp']) * 100,
            this.safeFloat (ohlcv, 'open_price'),
            this.safeFloat (ohlcv, 'highest_price'),
            this.safeFloat (ohlcv, 'lowest_price'),
            this.safeFloat (ohlcv, 'current_price'),
            this.safeFloat (ohlcv, 'volume'),
        ];
    }

    async fetchOHLCV (symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        //
        // ohlcv query parameters:
        //    from : start time of k-line data (in milliseconds) : [required]
        //    to : end time of k-line data (in milliseconds) : [required]
        //    step : steps of sampling (in minutes, default 1 minute) : [optional]
        //
        let response = await this.publicGetSymbolsSymbolKline (this.extend ({
            'symbol': this.marketId (symbol),
        }, params));
        return this.parseOHLCVs (response, market, timeframe, since, limit);
    }

    async fetchBalance (params = {}) {
        await this.loadMarkets ();
        let balances = await this.privateGetWallet (params);
        let result = {};
        for (let i = 0; i < balances.length; i++) {
            let balance = balances[i];
            let id = this.safeString (balance, 'id');
            if (id in this.currencies_by_id) {
                id = this.currencies_by_id[id]['code'];
            }
            let free = this.safeFloat (balance, 'available');
            let used = this.safeFloat (balance, 'frozen');
            result[id] = {
                'free': free,
                'used': used,
                'total': this.sum (free, used),
            };
        }
        return result;
    }

    nonce () {
        return this.milliseconds ();
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let url = this.urls['api'] + '/' + this.version + '/' + path;
        let query = this.omit (params, this.extractParams (path));
        if (api === 'public') {
            if (Object.keys (query).length)
                url += '?' + this.urlencode (query);
        } else if (api === 'token') {
            this.checkRequiredCredentials ();
            body = this.urlencode (query);
            headers = {
                'Content-Type': 'application/x-www-form-urlencoded',
            };
        } else {
            this.checkRequiredCredentials ();
            let token = this.safeString (this.options, 'accessToken');
            if (token === undefined) {
                throw new AuthenticationError (this.id + ' ' + path + ' endpoint requires an accessToken option or a prior call to signIn() method');
            }
            let expires = this.safeInteger (this.options, 'expires');
            if (expires !== undefined) {
                if (this.nonce () >= expires) {
                    throw new AuthenticationError (this.id + ' accessToken expired, supply a new accessToken or call to signIn() method');
                }
            }
            headers = {
                'Content-Type': 'application/json',
                'X-BM-TIMESTAMP': this.nonce (),
                'X-BM-AUTHORIZATION': 'Bearer ' + token,
            };
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }
};
<|endoftext|>


<commit_before>/**
 * @file Entry-point script for the OpenAddresses import pipeline.
 */

'use strict';

var peliasConfig = require( 'pelias-config' ).generate(require('./schema'));

var logger = require( 'pelias-logger' ).get( 'openaddresses' );

var parameters = require( './lib/parameters' );
var importPipeline = require( './lib/importPipeline' );

const adminLookupStream = require('pelias-wof-admin-lookup');
var deduplicatorStream = require('./lib/streams/deduplicatorStream');

var addressDeduplicator = require('pelias-address-deduplicator');

// Pretty-print the total time the import took.
function startTiming() {
  var startTime = new Date().getTime();
  process.on( 'exit', function (){
    var totalTimeTaken = (new Date().getTime() - startTime).toString();
    var seconds = totalTimeTaken.slice(0, totalTimeTaken.length - 3);
    var milliseconds = totalTimeTaken.slice(totalTimeTaken.length - 3);
    logger.info( 'Total time taken: %s.%ss', seconds, milliseconds );
  });
}

var args = parameters.interpretUserArgs( process.argv.slice( 2 ) );

if( 'exitCode' in args ){
  ((args.exitCode > 0) ? console.error : console.info)( args.errMessage );
  process.exit( args.exitCode );
} else {
  startTiming();

  if (peliasConfig.imports.openaddresses.hasOwnProperty('adminLookup')) {
    logger.info('imports.openaddresses.adminLookup has been deprecated, ' +
                'enable adminLookup using imports.adminLookup.enabled = true');
  }

  var files = parameters.getFileList(peliasConfig, args);

  var deduplicator = deduplicatorStream.create(peliasConfig, addressDeduplicator);

  importPipeline.create( files, args.dirPath, deduplicator, adminLookupStream.create() );
}
<commit_msg>only start wof-admin-lookup with land-based layers<commit_after>/**
 * @file Entry-point script for the OpenAddresses import pipeline.
 */

'use strict';

var peliasConfig = require( 'pelias-config' ).generate(require('./schema'));

var logger = require( 'pelias-logger' ).get( 'openaddresses' );

var parameters = require( './lib/parameters' );
var importPipeline = require( './lib/importPipeline' );

const adminLookupStream = require('pelias-wof-admin-lookup');
var deduplicatorStream = require('./lib/streams/deduplicatorStream');

var addressDeduplicator = require('pelias-address-deduplicator');

// Pretty-print the total time the import took.
function startTiming() {
  var startTime = new Date().getTime();
  process.on( 'exit', function (){
    var totalTimeTaken = (new Date().getTime() - startTime).toString();
    var seconds = totalTimeTaken.slice(0, totalTimeTaken.length - 3);
    var milliseconds = totalTimeTaken.slice(totalTimeTaken.length - 3);
    logger.info( 'Total time taken: %s.%ss', seconds, milliseconds );
  });
}

var args = parameters.interpretUserArgs( process.argv.slice( 2 ) );

const adminLayers = ['neighbourhood', 'borough', 'locality', 'localadmin',
  'county', 'macrocounty', 'region', 'macroregion', 'dependency', 'country'];

if( 'exitCode' in args ){
  ((args.exitCode > 0) ? console.error : console.info)( args.errMessage );
  process.exit( args.exitCode );
} else {
  startTiming();

  if (peliasConfig.imports.openaddresses.hasOwnProperty('adminLookup')) {
    logger.info('imports.openaddresses.adminLookup has been deprecated, ' +
                'enable adminLookup using imports.adminLookup.enabled = true');
  }

  var files = parameters.getFileList(peliasConfig, args);

  var deduplicator = deduplicatorStream.create(peliasConfig, addressDeduplicator);

  importPipeline.create( files, args.dirPath, deduplicator, adminLookupStream.create(adminLayers) );
}
<|endoftext|>


<commit_before>/*
 ---

 name: Accordion

 script: accordion.js

 description: MUI.Accordion - Creates a generic accordion control.

 copyright: (c) 2011 Contributors in (/AUTHORS.txt).

 license: MIT-style license in (/MIT-LICENSE.txt).

 note:
 This documentation is taken directly from the javascript source files. It is built using Natural Docs.

 requires:
 - Core/Element
 - Core/Class
 - Core/Options
 - Core/Events
 - MUI
 - MUI.Core

 provides: [MUI.Accordion]

 ...
 */

MUI.Accordion = new NamedClass('MUI.Accordian', {

	Implements: [Events, Options],

	options: {
		id:					'',			// id of the primary element, and id os control that is registered with mocha
		container:			null,		// the parent control in the document to add the control to
		clearContainer:		true,		// should the control clear its parent container before it appends itself
		drawOnInit:			true,		// true to add accordion to container when control is initialized
		cssClass:			'mui-accordion',// the primary css tag

		panels:				[],			// the list of accordion panels

		textField:			'text',		// the name of the field that has the panels toggler text
		valueField:			'value',	// the name of the field that has the panels toggler values
		titleField:			'title',	// the name of the field that has the panels tip text
		contentField:		'html',		// the field that contains the name of the field that has the content for the panel

		value:				'',			// the currently selected panel's value
		selectedPanel:		null,		// the currently selected panel
		height:				false,		// If set, displayed elements will have a fixed height equal to the specified value.
		width:				false,		// If set, displayed elements will have a fixed width equal to the specified value.
		insertTitle:		true,		// If set, the title will be inserted into the panel html

		heightFx:			true,		// If set to true, a height transition effect will take place when switching between displayed e7lements.
		widthFx:			false,		// If set to true, it will add a width transition to the accordion when switching between displayed elements. Warning: CSS mastery is required to make this work!
		opacity:			false,		// If set to true, an opacity transition effect will take place when switching between displayed elements.
		alwaysHide:			false,		// If set to true, it will be possible to close all displayable elements. Otherwise, one will remain open at all time.
		initialDisplayFx:	true		// If set to false, the initial item displayed will not display with an effect but will just be shown immediately.

		//onPanelSelected:    null        // event: when a panel is opened
	},

	initialize: function(options){
		this.setOptions(options);
		this.el = {};

		// If accordion has no ID, give it one.
		this.id = this.options.id = this.options.id || 'accordion' + (++MUI.idCount);
		MUI.set(this.id, this);

		if (options.content){
			options.content.loadMethod = MUI.getDefaultJsonProvider(options.content.loadMethod);
			options.content.onLoaded = (function(element, options){
				this.options.panels = MUI.Content.getRecords(options);
				this.draw();
			}).bind(this);
			MUI.Content.update(options.content);
			return;
		}

		// create sub items if available
		if (this.options.drawOnInit && this.options.panels.length > 0) self.draw();
		else if (self.fromHTML){
			window.addEvent('domready', function(){
				var el = $(id);
				if (el != null) self.fromHTML();
			});
		}
	},

	draw: function(container){
		var o = this.options;
		if (!container) container = o.container;

		// determine element for this control
		var isNew = false;
		var div = o.element ? o.element : $(o.id);
		if (!div){
			div = new Element('div', {'id': o.id});
			isNew = true;
		}
		if (o.cssClass) div.set('class', o.cssClass);

		this.el.element = div.store('instance', this);		// assign instance to element

		// create main panel container
		this._panelsElement = new Element('div', {'class':'mui-panels'}).inject(div);

		// if no tab selected, then select first tab for them
		if (o.panels.length > 0 && (o.value == null || o.value == '')) o.value = MUI.getData(o.panels[0], o.valueField);

		// build all panels
		this._togglers = [];
		this._panels = [];
		for (var i = 0; i < o.panels.length; i++){
			this._buildPanel(o.panels[i], this._panelsElement, i);
		}
		if (this._panels.length > 1){
			this._togglers[0].addClass('first');
			this._togglers[this._panels.length - 1].addClass('last');
		}

		// add to container
		var addToContainer = function(){
			if (typeOf(container) == 'string') container = $(container);
			if (o.clearContainer) container.empty();
			if (!container) container = div.getParent();
			if (div.getParent() == null) div.inject(container);

			container.setStyle('overflow', 'hidden');
			container.setStyle('padding', 0);
			var parentHeight = this._getParentHeight(container);

			var instance = MUI.get(o.container);
			if (instance != null) instance.addEvent('resize', this._onParentResize.bind(this));

			this._accordion = new Fx.Accordion(this._togglers, this._panels, {
				'height':o.heightFx
				,'width':o.widthFx
				,'display':this._index
				,'opacity':o.opacity
				,'fixedHeight':o._height
				,'fixedWidth':o.width
				,'alwaysHide':o.alwaysHide
				,'initialDisplayFx':o.initialDisplayFx
				,onActive: (function(toggler, element){
					this.options.value = toggler.get('id');
					this._index = parseInt(toggler.get('index'));
					this._getParentHeight(container); // forces recalc of _height
					element.fullHeight = this.options._height;
					toggler.addClass('open');
					element.setStyle('overflow', 'auto');
				}).bind(this),
				onBackground: function(toggler, element){
					toggler.removeClass('open');
					element.setStyle('overflow', 'hidden');
				},
				onStart: function(){
					var instance = MUI.get(o.container);
					this.accordionResize = function(){
						if (instance && instance.dynamicResize) instance.dynamicResize(); // once more for good measure
					};
					this.accordionTimer = this.accordionResize.periodical(10);
				},
				onComplete: function(){
					var instance = MUI.get(o.container);
					this.accordionTimer = clearInterval(this.accordionTimer);
					if (instance && instance.dynamicResize) instance.dynamicResize(); // once more for good measure
				}
			});
		}.bind(this);
		if (!isNew || typeOf(container) == 'element') addToContainer();
		else window.addEvent('domready', addToContainer);

		return this;
	},

	_onParentResize:function(){
		var o = this.options;
		var div = o.element ? o.element : $(o.id);
		var h = this._getParentHeight(div.getParent());
		this._panelsElement.setStyle('height', h + 'px');
		this._accordion.previous = -1;
		this._accordion.display(this._index);
	},

	_getParentHeight: function(e){
		var o = this.options;
		var h = this._getElementHeight(e);
		if (e.hasClass('pad')) h = this._getElementHeight(e.getParent());

		if (!o.height){
			o._height = h;
			this._togglers.each(function(toggler){
				o._height -= toggler.getSize().y
			});
		} else o._height = o.height;
		this._panelsElement.setStyle('height', h + 'px');

		return h;
	},

	_getElementHeight:function(e){
		var h = e.getSize().y;
		h -= parseInt(e.getStyle('border-bottom-width'));
		h -= parseInt(e.getStyle('border-top-width'));
		h -= parseInt(e.getStyle('padding-bottom'));
		h -= parseInt(e.getStyle('padding-top'));
		return h;
	},

	_buildPanel: function(panel, div, idx){
		var self = this;
		var o = self.options;

		var value = MUI.getData(panel, o.valueField);
		if (!value) value = 'apanel' + (++MUI.idCount);
		var text = MUI.getData(panel, o.textField);
		var title = MUI.getData(panel, o.titleField);
		var html = MUI.getData(panel, o.contentField);

		if (o.value == value || (!o.value && idx == 0)) this._index = idx;

		panel._togglerEl = new Element('h3', {'id':value,'class':'toggler','text':text,'title':title, 'index':idx}).inject(div);
		panel._element = new Element('div', {'id':value + '_panel','class':'element', 'index':idx}).inject(div);
		panel._contentEl = new Element('div', {'class':'content'}).inject(panel._element);

		if (o.insertTitle){
			new Element('h3', {'html':title}).inject(panel._contentEl);
			new Element('div', {'html':html}).inject(panel._contentEl);
		} else panel._contentEl.set('html', html);

		self._togglers.push(panel._togglerEl);
		self._panels.push(panel._element);
	}

});
<commit_msg>fix for error durng extra event when the accordian is cleared<commit_after>/*
 ---

 name: Accordion

 script: accordion.js

 description: MUI.Accordion - Creates a generic accordion control.

 copyright: (c) 2011 Contributors in (/AUTHORS.txt).

 license: MIT-style license in (/MIT-LICENSE.txt).

 note:
 This documentation is taken directly from the javascript source files. It is built using Natural Docs.

 requires:
 - Core/Element
 - Core/Class
 - Core/Options
 - Core/Events
 - MUI
 - MUI.Core

 provides: [MUI.Accordion]

 ...
 */

MUI.Accordion = new NamedClass('MUI.Accordian', {

	Implements: [Events, Options],

	options: {
		id:					'',			// id of the primary element, and id os control that is registered with mocha
		container:			null,		// the parent control in the document to add the control to
		clearContainer:		true,		// should the control clear its parent container before it appends itself
		drawOnInit:			true,		// true to add accordion to container when control is initialized
		cssClass:			'mui-accordion',// the primary css tag

		panels:				[],			// the list of accordion panels

		textField:			'text',		// the name of the field that has the panels toggler text
		valueField:			'value',	// the name of the field that has the panels toggler values
		titleField:			'title',	// the name of the field that has the panels tip text
		contentField:		'html',		// the field that contains the name of the field that has the content for the panel

		value:				'',			// the currently selected panel's value
		selectedPanel:		null,		// the currently selected panel
		height:				false,		// If set, displayed elements will have a fixed height equal to the specified value.
		width:				false,		// If set, displayed elements will have a fixed width equal to the specified value.
		insertTitle:		true,		// If set, the title will be inserted into the panel html

		heightFx:			true,		// If set to true, a height transition effect will take place when switching between displayed e7lements.
		widthFx:			false,		// If set to true, it will add a width transition to the accordion when switching between displayed elements. Warning: CSS mastery is required to make this work!
		opacity:			false,		// If set to true, an opacity transition effect will take place when switching between displayed elements.
		alwaysHide:			false,		// If set to true, it will be possible to close all displayable elements. Otherwise, one will remain open at all time.
		initialDisplayFx:	true		// If set to false, the initial item displayed will not display with an effect but will just be shown immediately.

		//onPanelSelected:    null        // event: when a panel is opened
	},

	initialize: function(options){
		this.setOptions(options);
		this.el = {};

		// If accordion has no ID, give it one.
		this.id = this.options.id = this.options.id || 'accordion' + (++MUI.idCount);
		MUI.set(this.id, this);

		if (options.content){
			options.content.loadMethod = MUI.getDefaultJsonProvider(options.content.loadMethod);
			options.content.onLoaded = (function(element, options){
				this.options.panels = MUI.Content.getRecords(options);
				this.draw();
			}).bind(this);
			MUI.Content.update(options.content);
			return;
		}

		// create sub items if available
		if (this.options.drawOnInit && this.options.panels.length > 0) self.draw();
		else if (self.fromHTML){
			window.addEvent('domready', function(){
				var el = $(id);
				if (el != null) self.fromHTML();
			});
		}
	},

	draw: function(container){
		var o = this.options;
		if (!container) container = o.container;

		// determine element for this control
		var isNew = false;
		var div = o.element ? o.element : $(o.id);
		if (!div){
			div = new Element('div', {'id': o.id});
			isNew = true;
		}
		if (o.cssClass) div.set('class', o.cssClass);

		this.el.element = div.store('instance', this);		// assign instance to element

		// create main panel container
		this._panelsElement = new Element('div', {'class':'mui-panels'}).inject(div);

		// if no tab selected, then select first tab for them
		if (o.panels.length > 0 && (o.value == null || o.value == '')) o.value = MUI.getData(o.panels[0], o.valueField);

		// build all panels
		this._togglers = [];
		this._panels = [];
		for (var i = 0; i < o.panels.length; i++){
			this._buildPanel(o.panels[i], this._panelsElement, i);
		}
		if (this._panels.length > 1){
			this._togglers[0].addClass('first');
			this._togglers[this._panels.length - 1].addClass('last');
		}

		// add to container
		var addToContainer = function(){
			if (typeOf(container) == 'string') container = $(container);
			if (o.clearContainer) container.empty();
			if (!container) container = div.getParent();
			if (div.getParent() == null) div.inject(container);

			container.setStyle('overflow', 'hidden');
			container.setStyle('padding', 0);
			var parentHeight = this._getParentHeight(container);

			var instance = MUI.get(o.container);
			if (instance != null) instance.addEvent('resize', this._onParentResize.bind(this));

			this._accordion = new Fx.Accordion(this._togglers, this._panels, {
				'height':o.heightFx
				,'width':o.widthFx
				,'display':this._index
				,'opacity':o.opacity
				,'fixedHeight':o._height
				,'fixedWidth':o.width
				,'alwaysHide':o.alwaysHide
				,'initialDisplayFx':o.initialDisplayFx
				,onActive: (function(toggler, element){
					this.options.value = toggler.get('id');
					this._index = parseInt(toggler.get('index'));
					this._getParentHeight(container); // forces recalc of _height
					element.fullHeight = this.options._height;
					toggler.addClass('open');
					element.setStyle('overflow', 'auto');
				}).bind(this),
				onBackground: function(toggler, element){
					toggler.removeClass('open');
					element.setStyle('overflow', 'hidden');
				},
				onStart: function(){
					var instance = MUI.get(o.container);
					this.accordionResize = function(){
						if (instance && instance.dynamicResize) instance.dynamicResize(); // once more for good measure
					};
					this.accordionTimer = this.accordionResize.periodical(10);
				},
				onComplete: function(){
					var instance = MUI.get(o.container);
					this.accordionTimer = clearInterval(this.accordionTimer);
					if (instance && instance.dynamicResize) instance.dynamicResize(); // once more for good measure
				}
			});
		}.bind(this);
		if (!isNew || typeOf(container) == 'element') addToContainer();
		else window.addEvent('domready', addToContainer);

		return this;
	},

	_onParentResize:function(){
		var o = this.options;
		var div = o.element ? o.element : $(o.id);
		if (!div) return;
		var h = this._getParentHeight(div.getParent());
		this._panelsElement.setStyle('height', h + 'px');
		this._accordion.previous = -1;
		this._accordion.display(this._index);
	},

	_getParentHeight: function(e){
		var o = this.options;
		var h = this._getElementHeight(e);
		if (e.hasClass('pad')) h = this._getElementHeight(e.getParent());

		if (!o.height){
			o._height = h;
			this._togglers.each(function(toggler){
				o._height -= toggler.getSize().y
			});
		} else o._height = o.height;
		this._panelsElement.setStyle('height', h + 'px');

		return h;
	},

	_getElementHeight:function(e){
		var h = e.getSize().y;
		h -= parseInt(e.getStyle('border-bottom-width'));
		h -= parseInt(e.getStyle('border-top-width'));
		h -= parseInt(e.getStyle('padding-bottom'));
		h -= parseInt(e.getStyle('padding-top'));
		return h;
	},

	_buildPanel: function(panel, div, idx){
		var self = this;
		var o = self.options;

		var value = MUI.getData(panel, o.valueField);
		if (!value) value = 'apanel' + (++MUI.idCount);
		var text = MUI.getData(panel, o.textField);
		var title = MUI.getData(panel, o.titleField);
		var html = MUI.getData(panel, o.contentField);

		if (o.value == value || (!o.value && idx == 0)) this._index = idx;

		panel._togglerEl = new Element('h3', {'id':value,'class':'toggler','text':text,'title':title, 'index':idx}).inject(div);
		panel._element = new Element('div', {'id':value + '_panel','class':'element', 'index':idx}).inject(div);
		panel._contentEl = new Element('div', {'class':'content'}).inject(panel._element);

		if (o.insertTitle){
			new Element('h3', {'html':title}).inject(panel._contentEl);
			new Element('div', {'html':html}).inject(panel._contentEl);
		} else panel._contentEl.set('html', html);

		self._togglers.push(panel._togglerEl);
		self._panels.push(panel._element);
	}

});
<|endoftext|>


<commit_before>// -*- indent-tabs-mode: nil; js2-basic-offset: 2 -*-

var fs = require('fs');
var path = require('path');
var
 = require('mkdirp');
var rmRSync = require('../rm').rmRSync;
var crypto = require('crypto');

function FileStorage(args) {
  this.initialize(args);
}
FileStorage.prototype = {
  initialize: function(args) {
    this.name = args.name;
    this.basePath = args.basePath || '/tmp';
  },

  get directoryPath() {
    if (!this._directoryPath) {
      this._directoryPath = path.join(this.basePath, this.name);
    }
    return this._directoryPath;
  },

  // because document id can be too long, we should use a short hash
  // string instead of full id.
  idToFileName: function(id) {
    var shasum = crypto.createHash('sha1');
    shasum.update(String(id));
    return shasum.digest('hex');
  },

  idToFilePath: function(id) {
    var filename = this.idToFileName(id);
    return path.join(this.directoryPath, filename);
  },

  saveSync: function(document) {
    mkdirp.sync(this.directoryPath, 0700);

    var filePath = this.idToFilePath(document.id);
    if (path.existsSync(filePath))
      fs.unlinkSync(filePath);

    var contents = JSON.stringify(document);
    var file = fs.openSync(filePath, 'w', 0644);
    fs.writeSync(file, contents);
    fs.closeSync(file);
  },

  readSync: function(id) {
    if (!this.directoryExistsSync())
      return null;

    var filePath = this.idToFilePath(id);
    if (!path.existsSync(filePath))
      return null;

    var contents = fs.readFileSync(filePath, 'UTF-8');
    return JSON.parse(contents);
  },

  deleteSync: function(id) {
    if (!this.directoryExistsSync())
      return;

    var filePath = this.idToFilePath(id);
    if (path.existsSync(filePath))
      fs.unlinkSync(filePath);
  },

  clearSync: function() {
    if (this.directoryExistsSync())
      rmRSync(this.directoryPath);
  },

  directoryExistsSync: function() {
    return path.existsSync(this.directoryPath);
  }
};
exports.FileStorage = FileStorage;

function MemoryStorage() {
  this._storage = {};
}
MemoryStorage.prototype = {
  saveSync: function(document) {
    this._storage[document.id] = document;
  },

  readSync: function(id) {
    return this._storage[id] || null;
  },

  deleteSync: function(id) {
    delete this._storage[id];
  },

  clearSync: function() {
    this._storage = {};
  }
};
exports.MemoryStorage = MemoryStorage;
<commit_msg>Fix syntax error<commit_after>// -*- indent-tabs-mode: nil; js2-basic-offset: 2 -*-

var fs = require('fs');
var path = require('path');
var mkdirp = require('mkdirp');
var rmRSync = require('../rm').rmRSync;
var crypto = require('crypto');

function FileStorage(args) {
  this.initialize(args);
}
FileStorage.prototype = {
  initialize: function(args) {
    this.name = args.name;
    this.basePath = args.basePath || '/tmp';
  },

  get directoryPath() {
    if (!this._directoryPath) {
      this._directoryPath = path.join(this.basePath, this.name);
    }
    return this._directoryPath;
  },

  // because document id can be too long, we should use a short hash
  // string instead of full id.
  idToFileName: function(id) {
    var shasum = crypto.createHash('sha1');
    shasum.update(String(id));
    return shasum.digest('hex');
  },

  idToFilePath: function(id) {
    var filename = this.idToFileName(id);
    return path.join(this.directoryPath, filename);
  },

  saveSync: function(document) {
    mkdirp.sync(this.directoryPath, 0700);

    var filePath = this.idToFilePath(document.id);
    if (path.existsSync(filePath))
      fs.unlinkSync(filePath);

    var contents = JSON.stringify(document);
    var file = fs.openSync(filePath, 'w', 0644);
    fs.writeSync(file, contents);
    fs.closeSync(file);
  },

  readSync: function(id) {
    if (!this.directoryExistsSync())
      return null;

    var filePath = this.idToFilePath(id);
    if (!path.existsSync(filePath))
      return null;

    var contents = fs.readFileSync(filePath, 'UTF-8');
    return JSON.parse(contents);
  },

  deleteSync: function(id) {
    if (!this.directoryExistsSync())
      return;

    var filePath = this.idToFilePath(id);
    if (path.existsSync(filePath))
      fs.unlinkSync(filePath);
  },

  clearSync: function() {
    if (this.directoryExistsSync())
      rmRSync(this.directoryPath);
  },

  directoryExistsSync: function() {
    return path.existsSync(this.directoryPath);
  }
};
exports.FileStorage = FileStorage;

function MemoryStorage() {
  this._storage = {};
}
MemoryStorage.prototype = {
  saveSync: function(document) {
    this._storage[document.id] = document;
  },

  readSync: function(id) {
    return this._storage[id] || null;
  },

  deleteSync: function(id) {
    delete this._storage[id];
  },

  clearSync: function() {
    this._storage = {};
  }
};
exports.MemoryStorage = MemoryStorage;
<|endoftext|>


<commit_before>
function changeMenuStyle(obj, new_style) {
    obj.className = new_style;
}
function showCursor() {
    document.body.style.cursor = "hand";
}
function hideCursor() {
    document.body.style.cursor = "default";
}
function confirmDelete() {
    if (confirm("Are you sure you want to delete?")) {
        return true;
    } else {
        return false;
    }
}
function get_tree() {
    d = new dTree("d");
    d.config.target = "";
    d.add(0, -1, "Workflow");
    d.add(1, 0, "Pre-screening Assays", "javascript:void(0)", "", "", "");
    d.add(2, 1, "STE-1", "javascript:gotoPage('assayActionMenu.jsp')", "", "", "");
    d.add(3, 2, "run 1", "javascript:void(0)");
    d.add(4, 3, "In", "javascript:gotoPage('inputActionMenu.jsp')");
    d.add(5, 4, "NCL6-7105-1", "javascript:gotoPage('viewAliquot.do?aliquotId=NCL6-7105-1')", "", "", "");
    d.add(6, 4, "NCL6-7105-2", "javascript:void(0)", "", "", "");
    d.add(7, 3, "Out", "javascript:gotoPage('outputActionMenu.jsp')");
    d.add(8, 7, "NCL6.vaf", "doc/astra_5.doc");
    d.add(9, 2, "run 2", "javascript:void(0)");
    d.add(10, 9, "In", "javascript:gotoPage('inputActionMenu.jsp')");
    d.add(11, 9, "Out", "javascript:gotoPage('outputActionMenu.jsp')");
    d.add(12, 1, "STE-2", "javascript:gotoPage('assayActionMenu.jsp')");
    d.add(13, 1, "STE-3", "javascript:gotoPage('assayActionMenu.jsp')", "", "", "");
    d.add(14, 1, "PCC-1", "javascript:gotoPage('assayActionMenu.jsp')", "", "", "");
    d.add(15, 0, "In Vitro Assays", "javascript:void(0)", "", "", "");
    d.add(16, 0, "In Vivo Assays", "javascript:void(0)", "", "", "");
    d.add(17, 0, "Physical Characterization Assays", "javascript:void(0)", "", "", "");
    document.write(d);
}
function add_hist() {
    document.getElementById("hists").options[document.getElementById("hists").options.length] = new Option("new text", "new value");
}
function gotoPage(pageURL) {
    window.location.href = pageURL;
}
function openWindow(pageURL, name, width, height) {
    window.open(pageURL, name, "alwaysRaised,dependent,status,scrollbars,resizable,width=" + width + ",height=" + height);
}
function openHelpWindow(pageURL) {
    window.open(pageURL, "Help", "alwaysRaised,dependent,status,scrollbars,resizable,width=800,height=500");
}
/**
moveItems is a function used in moving items in one multiple select to the other.
*/
function moveItems(fbox, tbox) {
    var arrFbox = new Array();
    var arrTbox = new Array();
    var arrLookup = new Array();
    var i;
    for (i = 0; i < tbox.options.length; i++) {
        arrLookup[tbox.options[i].text] = tbox.options[i].value;
        arrTbox[i] = tbox.options[i].text;
    }
    var fLength = 0;
    var tLength = arrTbox.length;
    for (i = 0; i < fbox.options.length; i++) {
        arrLookup[fbox.options[i].text] = fbox.options[i].value;
        if (fbox.options[i].selected && fbox.options[i].value != "") {
            arrTbox[tLength] = fbox.options[i].text;
            tLength++;
        } else {
            arrFbox[fLength] = fbox.options[i].text;
            fLength++;
        }
    }
			//arrFbox.sort();
			//arrTbox.sort();
    fbox.length = 0;
    tbox.length = 0;
    var c;
    for (c = 0; c < arrFbox.length; c++) {
        var no = new Option();
        no.value = arrLookup[arrFbox[c]];
        no.text = arrFbox[c];
        fbox[c] = no;
    }
    for (c = 0; c < arrTbox.length; c++) {
        var no = new Option();
        no.value = arrLookup[arrTbox[c]];
        no.text = arrTbox[c];
        tbox[c] = no;
    }
}
function resetSelect(selectObj) {
   for (var i=0; i<selectObj.options.length; i++) {
      if (selectObj.options[i].selected) {
         selectObj.options[i].selected=false;
      }
   }
}

function removeSelectOptions(selectObj) {
   selectObj.options.length=0;
}
/* filter second drop-down by first drop-down selection*/
function doubleDropdown(selection1, selection2, value1ToValue2) {
    /* initialize selection2 options */
    selection2.options.length = 0;
    selection2.options[0]=new Option("", "");
    var value1 = selection1.options[selection1.selectedIndex].value;
    var value2Arr = value1ToValue2[value1];
    if (value2Arr != null) {
        for (i = 0; i < value2Arr.length; i++) {
            selection2.options[i] = value2Arr[i];
        }
    }
}

/* filter a drop-down by a value*/
function dynamicDropdown(value, selection, value1ToValue2) {
    /* initialize selection options */
    selection.options.length = 0;
    selection.options[0]=new Option("", "");
    var value2Arr = value1ToValue2[value];
    if (value2Arr != null) {
        for (i = 0; i < value2Arr.length; i++) {
            selection.options[i] = value2Arr[i];
        }
    }
}

/* filter second multi-box by first multi-box selections */
function doubleMultibox(selection1, selection2, value1ToValue2) {
    selection2.options.length = 0;
    selection2.options[0]=new Option("", "");
    var value1Arr = new Array();
    for (var i = 0; i < selection1.options.length; i++) {
        if (selection1.options[i].selected) {
            value1Arr.push(selection1[i].value);
        }
    }
    var value2Arr = new Array();
    for (var i = 0; i < value1Arr.length; i++) {
        var value2s = value1ToValue2[value1Arr[i]];
        for (var j = 0; j < value2s.length; j++) {
            value2Arr.push(value2s[j]);
        }
    }
    for (var i = 0; i < value2Arr.length; i++) {
        selection2.options[i] = value2Arr[i];
    }
}

function submitAction(form, actionName) {
   form.action=actionName;
   form.submit();
}

function updateComposition() {
  document.nanoparticleCompositionForm.action="nanoparticleComposition.do?dispatch=update&page=0";
  document.nanoparticleCompositionForm.submit();
}

function updateSize() {
  document.nanoparticleSizeForm.action="nanoparticleSize.do?dispatch=update&page=0";
  document.nanoparticleSizeForm.submit();
}

<commit_msg>added loadSizeFile<commit_after>
function changeMenuStyle(obj, new_style) {
    obj.className = new_style;
}
function showCursor() {
    document.body.style.cursor = "hand";
}
function hideCursor() {
    document.body.style.cursor = "default";
}
function confirmDelete() {
    if (confirm("Are you sure you want to delete?")) {
        return true;
    } else {
        return false;
    }
}
function get_tree() {
    d = new dTree("d");
    d.config.target = "";
    d.add(0, -1, "Workflow");
    d.add(1, 0, "Pre-screening Assays", "javascript:void(0)", "", "", "");
    d.add(2, 1, "STE-1", "javascript:gotoPage('assayActionMenu.jsp')", "", "", "");
    d.add(3, 2, "run 1", "javascript:void(0)");
    d.add(4, 3, "In", "javascript:gotoPage('inputActionMenu.jsp')");
    d.add(5, 4, "NCL6-7105-1", "javascript:gotoPage('viewAliquot.do?aliquotId=NCL6-7105-1')", "", "", "");
    d.add(6, 4, "NCL6-7105-2", "javascript:void(0)", "", "", "");
    d.add(7, 3, "Out", "javascript:gotoPage('outputActionMenu.jsp')");
    d.add(8, 7, "NCL6.vaf", "doc/astra_5.doc");
    d.add(9, 2, "run 2", "javascript:void(0)");
    d.add(10, 9, "In", "javascript:gotoPage('inputActionMenu.jsp')");
    d.add(11, 9, "Out", "javascript:gotoPage('outputActionMenu.jsp')");
    d.add(12, 1, "STE-2", "javascript:gotoPage('assayActionMenu.jsp')");
    d.add(13, 1, "STE-3", "javascript:gotoPage('assayActionMenu.jsp')", "", "", "");
    d.add(14, 1, "PCC-1", "javascript:gotoPage('assayActionMenu.jsp')", "", "", "");
    d.add(15, 0, "In Vitro Assays", "javascript:void(0)", "", "", "");
    d.add(16, 0, "In Vivo Assays", "javascript:void(0)", "", "", "");
    d.add(17, 0, "Physical Characterization Assays", "javascript:void(0)", "", "", "");
    document.write(d);
}
function add_hist() {
    document.getElementById("hists").options[document.getElementById("hists").options.length] = new Option("new text", "new value");
}
function gotoPage(pageURL) {
    window.location.href = pageURL;
}
function openWindow(pageURL, name, width, height) {
    window.open(pageURL, name, "alwaysRaised,dependent,status,scrollbars,resizable,width=" + width + ",height=" + height);
}
function openHelpWindow(pageURL) {
    window.open(pageURL, "Help", "alwaysRaised,dependent,status,scrollbars,resizable,width=800,height=500");
}
/**
moveItems is a function used in moving items in one multiple select to the other.
*/
function moveItems(fbox, tbox) {
    var arrFbox = new Array();
    var arrTbox = new Array();
    var arrLookup = new Array();
    var i;
    for (i = 0; i < tbox.options.length; i++) {
        arrLookup[tbox.options[i].text] = tbox.options[i].value;
        arrTbox[i] = tbox.options[i].text;
    }
    var fLength = 0;
    var tLength = arrTbox.length;
    for (i = 0; i < fbox.options.length; i++) {
        arrLookup[fbox.options[i].text] = fbox.options[i].value;
        if (fbox.options[i].selected && fbox.options[i].value != "") {
            arrTbox[tLength] = fbox.options[i].text;
            tLength++;
        } else {
            arrFbox[fLength] = fbox.options[i].text;
            fLength++;
        }
    }
			//arrFbox.sort();
			//arrTbox.sort();
    fbox.length = 0;
    tbox.length = 0;
    var c;
    for (c = 0; c < arrFbox.length; c++) {
        var no = new Option();
        no.value = arrLookup[arrFbox[c]];
        no.text = arrFbox[c];
        fbox[c] = no;
    }
    for (c = 0; c < arrTbox.length; c++) {
        var no = new Option();
        no.value = arrLookup[arrTbox[c]];
        no.text = arrTbox[c];
        tbox[c] = no;
    }
}
function resetSelect(selectObj) {
   for (var i=0; i<selectObj.options.length; i++) {
      if (selectObj.options[i].selected) {
         selectObj.options[i].selected=false;
      }
   }
}

function removeSelectOptions(selectObj) {
   selectObj.options.length=0;
}
/* filter second drop-down by first drop-down selection*/
function doubleDropdown(selection1, selection2, value1ToValue2) {
    /* initialize selection2 options */
    selection2.options.length = 0;
    selection2.options[0]=new Option("", "");
    var value1 = selection1.options[selection1.selectedIndex].value;
    var value2Arr = value1ToValue2[value1];
    if (value2Arr != null) {
        for (i = 0; i < value2Arr.length; i++) {
            selection2.options[i] = value2Arr[i];
        }
    }
}

/* filter a drop-down by a value*/
function dynamicDropdown(value, selection, value1ToValue2) {
    /* initialize selection options */
    selection.options.length = 0;
    selection.options[0]=new Option("", "");
    var value2Arr = value1ToValue2[value];
    if (value2Arr != null) {
        for (i = 0; i < value2Arr.length; i++) {
            selection.options[i] = value2Arr[i];
        }
    }
}

/* filter second multi-box by first multi-box selections */
function doubleMultibox(selection1, selection2, value1ToValue2) {
    selection2.options.length = 0;
    selection2.options[0]=new Option("", "");
    var value1Arr = new Array();
    for (var i = 0; i < selection1.options.length; i++) {
        if (selection1.options[i].selected) {
            value1Arr.push(selection1[i].value);
        }
    }
    var value2Arr = new Array();
    for (var i = 0; i < value1Arr.length; i++) {
        var value2s = value1ToValue2[value1Arr[i]];
        for (var j = 0; j < value2s.length; j++) {
            value2Arr.push(value2s[j]);
        }
    }
    for (var i = 0; i < value2Arr.length; i++) {
        selection2.options[i] = value2Arr[i];
    }
}

function submitAction(form, actionName) {
   form.action=actionName;
   form.submit();
}

function updateComposition() {
  document.nanoparticleCompositionForm.action="nanoparticleComposition.do?dispatch=update&page=0";
  document.nanoparticleCompositionForm.submit();
}

function updateSize() {
  document.nanoparticleSizeForm.action="nanoparticleSize.do?dispatch=update&page=0";
  document.nanoparticleSizeForm.submit();
}

function loadSizeFile(fileNumber) {
  document.nanoparticleSizeForm.action="nanoparticleSize.do?dispatch=loadFile&page=0&fileNumber="+fileNumber;
  document.nanoparticleSizeForm.submit();
}

<|endoftext|>


<commit_before>// Webflow code to submit form

const verification = (t, e, n, i) => {
	let r = null, k = /e(-)?mail/i, _ = /^\S+@\S+$/;
	return e === 'password' ? r = 'Passwords cannot be submitted.' : getAttribute(t,'required') && (i ? (k.test(n) || k.test(getAttribute(t,'type'))) && (_.test(i) || (r = 'Please enter a valid email address for: ' + n)) : r = 'Please fill out the required field: ' + n), r
}

const conversion = (e, n) => {
	let i = null
	for (r=0; r<e[0].elements.length; r++) {
		console.log('test #1')
		const o = e[0].elements[r][0]
		if (!o || !getValue(o)) continue
		console.log(o)
		let a = getElementById(o),
			s = getAttribute(a,'type'),
			u = getAttribute(a,'data-name') || getAttribute(a,'name') || 'Field ' + (r + 1),
			l = getValue(a)
		console.log('test #2')
		if (s === 'checkbox' && (l = isChecked(a)), s === 'radio') {
			if (n[u] === null || typeof n[u] == 'string' || s == 'submit') return;
			l = getValue(e.find('input[name="' + getAttribute(a,'name') + '"]:checked')) || null
		}
		console.log('test #3')
		typeof l == 'string' && (l = l.trim()), n[u] = l, i = i || verification(a, s, u, l)
		console.log('test #4')
	}
	return n = n || {}, i
}

const createForm = () => {
	let formData = {
		name: page() === 'Event' ? 'Event Registration' : 'Custom Charge',
		source: window.location.href,
		test: false,
		fields: {},
		dolphin: false
	}
	let error = conversion(page() === 'Event' ? getElementById(eventForm) : getElementById(customForm), formData.fields)
	if (error) {
		throw error
	}
	console.log(formData)
	return formData
}<commit_msg>Update.<commit_after>// Webflow code to submit form

const verification = (t, e, n, i) => {
	let r = null, k = /e(-)?mail/i, _ = /^\S+@\S+$/;
	return e === 'password' ? r = 'Passwords cannot be submitted.' : getAttribute(t,'required') && (i ? (k.test(n) || k.test(getAttribute(t,'type'))) && (_.test(i) || (r = 'Please enter a valid email address for: ' + n)) : r = 'Please fill out the required field: ' + n), r
}

const conversion = (e, n) => {
	let i = null
	for (r=0; r<e[0].elements.length; r++) {
		console.log('test #1')
		const a = e[0].elements[r][0]
		if (!a) continue
		console.log(a)
		let s = getAttribute(a,'type'),
			u = getAttribute(a,'data-name') || getAttribute(a,'name') || 'Field ' + (r + 1),
			l = getValue(a)
		console.log('test #2')
		if (s === 'checkbox' && (l = isChecked(a)), s === 'radio') {
			if (n[u] === null || typeof n[u] == 'string' || s == 'submit') return;
			l = getValue(e.find('input[name="' + getAttribute(a,'name') + '"]:checked')) || null
		}
		console.log('test #3')
		typeof l == 'string' && (l = l.trim()), n[u] = l, i = i || verification(a, s, u, l)
		console.log('test #4')
	}
	return n = n || {}, i
}

const createForm = () => {
	let formData = {
		name: page() === 'Event' ? 'Event Registration' : 'Custom Charge',
		source: window.location.href,
		test: false,
		fields: {},
		dolphin: false
	}
	let error = conversion(page() === 'Event' ? getElementById(eventForm) : getElementById(customForm), formData.fields)
	if (error) {
		throw error
	}
	console.log(formData)
	return formData
}<|endoftext|>


<commit_before>'use strict';

require('node-define');

const fs = require('fs');

const ROOT_DIR = '..';
const CONNECTORS_DIR = 'src/connectors/';

const SERVICE_FILES = [
	'dummy.js', '.eslintrc.js'
];
const DOM_INJECT_SUFFIX = 'dom-inject.js';

const connectors = require(`${ROOT_DIR}/src/core/connectors.js`);
const manifest = require(`${ROOT_DIR}/src/manifest.json`);

module.exports = (grunt) => {
	grunt.registerTask('unused_files', 'Find unused files', () => {
		const unusedFiles = [
			...findUnusedConnectors(),
			...findUnusedDomInjects(),
		];

		const unusedCount = unusedFiles.length;
		if (unusedCount > 0) {
			const unusedFilesStr = unusedFiles.join(', ');
			grunt.log.error(`Found ${unusedCount} unused files: ${unusedFilesStr}`);
		} else {
			grunt.log.ok('No unused files are found');
		}
	});
};

function findUnusedConnectors() {
	const files = fs.readdirSync(CONNECTORS_DIR).filter(isConnector).map(appendPrefix);
	const unusedFiles = [];

	for (const file of files) {
		let found = false;
		for (const entry of connectors) {
			if (entry.js === file) {
				found = true;
			}
		}

		if (!found) {
			unusedFiles.push(file);
		}
	}

	return unusedFiles;
}

function findUnusedDomInjects() {
	const files = fs.readdirSync(CONNECTORS_DIR).filter(isDomInject).map(appendPrefix);
	const resources = manifest.web_accessible_resources;
	const unusedFiles = [];

	for (const file of files) {
		let found = false;
		for (const resource of resources) {
			if (resource === file) {
				found = true;
			}
		}

		if (!found) {
			unusedFiles.push(file);
		}
	}

	return unusedFiles;
}

function appendPrefix(jsFile) {
	return `connectors/${jsFile}`;
}

function isConnector(file) {
	return !(SERVICE_FILES.includes(file) || isDomInject(file));
}

function isDomInject(file) {
	return file.endsWith(DOM_INJECT_SUFFIX);
}
<commit_msg>Fail if unused files are found<commit_after>'use strict';

require('node-define');

const fs = require('fs');

const ROOT_DIR = '..';
const CONNECTORS_DIR = 'src/connectors/';

const SERVICE_FILES = [
	'dummy.js', '.eslintrc.js'
];
const DOM_INJECT_SUFFIX = 'dom-inject.js';

const connectors = require(`${ROOT_DIR}/src/core/connectors.js`);
const manifest = require(`${ROOT_DIR}/src/manifest.json`);

module.exports = (grunt) => {
	grunt.registerTask('unused_files', 'Find unused files', () => {
		const unusedFiles = [
			...findUnusedConnectors(),
			...findUnusedDomInjects(),
		];

		const unusedCount = unusedFiles.length;
		if (unusedCount > 0) {
			const unusedFilesStr = unusedFiles.join(', ');
			grunt.fail.fatal(`Found ${unusedCount} unused files: ${unusedFilesStr}`);
		} else {
			grunt.log.ok('No unused files are found');
		}
	});
};

function findUnusedConnectors() {
	const files = fs.readdirSync(CONNECTORS_DIR).filter(isConnector).map(appendPrefix);
	const unusedFiles = [];

	for (const file of files) {
		let found = false;
		for (const entry of connectors) {
			if (entry.js === file) {
				found = true;
			}
		}

		if (!found) {
			unusedFiles.push(file);
		}
	}

	return unusedFiles;
}

function findUnusedDomInjects() {
	const files = fs.readdirSync(CONNECTORS_DIR).filter(isDomInject).map(appendPrefix);
	const resources = manifest.web_accessible_resources;
	const unusedFiles = [];

	for (const file of files) {
		let found = false;
		for (const resource of resources) {
			if (resource === file) {
				found = true;
			}
		}

		if (!found) {
			unusedFiles.push(file);
		}
	}

	return unusedFiles;
}

function appendPrefix(jsFile) {
	return `connectors/${jsFile}`;
}

function isConnector(file) {
	return !(SERVICE_FILES.includes(file) || isDomInject(file));
}

function isDomInject(file) {
	return file.endsWith(DOM_INJECT_SUFFIX);
}
<|endoftext|>