<commit_before>describe('customEvent', function() {

    it('on() 메서드로 이벤트를 구독할 수 있다', function() {
        function Animal(leg) {
            this.leg = leg;
            this.position = 0;
        }

        ne.CustomEvents.mixin(Animal); // 커스텀 이벤트 기능 부여

        Animal.prototype.move = function(to) {
            this.position = to;
            this.fire('move');
        };

        var lion = new Animal(4);

        var deer = new Animal(4);

        // 사자가 움직이면 사슴은 도망감
        lion.on('move', function() {
            this.position = 100;
        }, deer);

        lion.move(50); // 사자가 움직인다.

        expect(deer.position).toBe(100);
    });

    it('on() 메서드는 첫 번째 인자에 객체를 넘겨 다중 이벤트를 한번에 설정할수도 있다', function() {
        function Animal(leg) {
            this.leg = leg;
            this.position = 0;
        }
        ne.CustomEvents.mixin(Animal); // 커스텀 이벤트 기능 부여

        Animal.prototype.move = function(to) {
            this.position = to;
            this.fire('move');
        };
        Animal.prototype.growl = function() {
            this.fire('growl');
        };

        var lion = new Animal(4);
        var deer = new Animal(4);

        lion.on({
            // 사자가 움직이면 사슴은 도망간다
            'move': function() {
                this.position = 100;
            },
            // 사자가 울부짖으면 사슴은 더 멀리 도망간다
            'growl': function() {
                this.position = 1000;
            }
        }, deer);

        lion.move(10);
        lion.growl();

        expect(deer.position).toBe(1000);
    });

    it('on() 메서드는 context를 제공하지 않으면 옵저버를 배열에 등록하여 사용한다', function() {

        function Animal(leg) {
            this.leg = leg;
            this.position = 0;
        }

        ne.CustomEvents.mixin(Animal); // 커스텀 이벤트 기능 부여

        Animal.prototype.move = function(to) {
            this.position = to;
            this.fire('move');
        };

        var lion = new Animal(4),
            growlFn = ne.bind(function() {
                this.position = 0;
            }, lion);

        lion.on('move', growlFn);

        expect(ne.isArray(lion._events['move'])).toBeTruthy();
    });

    it('on() 메서드는 context를 제공할 경우 옵저버 패턴을 객체를 이용한다', function() {
        function Animal(leg) {
            this.leg = leg;
            this.position = 0;
        }

        ne.CustomEvents.mixin(Animal); // 커스텀 이벤트 기능 부여

        Animal.prototype.move = function(to) {
            this.position = to;
            this.fire('move');
        };

        var lion = new Animal(4),
            onMove = function() {
                this.moved = true;
            };

        var myObj = {};

        lion.on('move', onMove, myObj);

        lion.move(10);

        ne.stamp(onMove);

        expect(myObj.moved).toBeTruthy();
        expect(lion._events['move_len']).toBe(1);

    });

    it('off() 메서드로 구독했던 이벤트 관계를 해제할 수 있다', function() {
        function Animal(leg) {
            this.leg = leg;
            this.position = 0;
        }

        ne.CustomEvents.mixin(Animal); // 커스텀 이벤트 기능 부여

        Animal.prototype.move = function (to) {
            this.position = to;
            this.fire('move');
        };

        var lion = new Animal(4),
            deer = new Animal(4),
            runAwayFn = function () {
                this.position = 1000;
            };

        // 사자가 움직이면 사슴은 도망감
        lion.on('move', runAwayFn, deer);

        // 사슴은 더 이상 도망가지 않음
        lion.off('move', runAwayFn, deer);

        lion.move(100);

        expect(deer.position).toBe(0);
    });

    it('off() 는 이벤트명:함수를 넘겨 동시에 여러 이벤트를 구독 해제할 수 있다', function() {
        function Animal(leg) {
            this.leg = leg;
            this.position = 0;
        }

        ne.CustomEvents.mixin(Animal); // 커스텀 이벤트 기능 부여

        Animal.prototype.move = function (to) {
            this.position = to;
            this.fire('move');
        };
        Animal.prototype.growl = function () {
            this.fire('growl');
        };

        var lion = new Animal(4);
        var deer = new Animal(4);

        var runAwayFn = function() {
            this.position = 1000;
        };

        lion.on({
            // 사자가 움직이면 사슴은 도망간다
            'move': runAwayFn,
            // 사자가 울부짖으면 사슴은 더 멀리 도망간다
            'growl': runAwayFn
        }, deer);

        lion.off({
            'move': runAwayFn,
            'growl': runAwayFn
        }, deer);

        lion.move(10);
        lion.growl();

        expect(deer.position).toBe(0);
    });

    it('off() 는 아무 인자도 넘기지 않으면 모든 구독을 해제한다', function() {
        function Animal(leg) {
            this.leg = leg;
            this.position = 0;
        }

        ne.CustomEvents.mixin(Animal); // 커스텀 이벤트 기능 부여

        Animal.prototype.move = function (to) {
            this.position = to;
            this.fire('move');
        };
        Animal.prototype.growl = function () {
            this.fire('growl');
        };

        var lion = new Animal(4);
        var deer = new Animal(4);

        var runAwayFn = function () {
            this.position = 1000;
        };

        lion.on({
            // 사자가 움직이면 사슴은 도망간다
            'move': runAwayFn,
            // 사자가 울부짖으면 사슴은 더 멀리 도망간다
            'growl': runAwayFn
        }, deer);

        lion.off();

        lion.move(10);
        lion.growl();

        expect(deer.position).toBe(0);
    });

    it('once() 메서드로 단발성 커스텀 이벤트를 등록할 수 있다', function() {
        function Animal(leg) {
            this.leg = leg;
            this.position = 0;
        }

        ne.CustomEvents.mixin(Animal); // 커스텀 이벤트 기능 부여

        Animal.prototype.move = function(to) {
            this.position = to;
            this.fire('move');
        };

        var lion = new Animal(4);

        lion.moveDistance = 0;

        lion.once('move', function() {
            this.moveDistance += this.position;
        }, lion);

        lion.move(10);
        lion.move(10);

        expect(lion.moveDistance).toBe(10);
    });

    it('once() 도 마찬가지로 첫 번째 인자에 이벤트명:핸들러 객체로 한번헤 구독할 수 있다', function() {
        function Animal(leg) {
            this.leg = leg;
            this.position = 0;
        }

        ne.CustomEvents.mixin(Animal); // 커스텀 이벤트 기능 부여

        Animal.prototype.move = function(to) {
            this.position = to;
            this.fire('move');
        };
        Animal.prototype.back = function(distance) {
            this.fire('back', { distance: distance });
            this.position = -distance;
        };

        var lion = new Animal(4);

        lion.moveDistance = 0;

        lion.once({
            'move': function() {
                this.moveDistance += this.position;
            },
            'back': function(backEvent) {
                this.moveDistance -= backEvent.distance;
            }
        }, lion);

        lion.move(10);
        lion.move(10);
        lion.back(10);

        expect(lion.moveDistance).toBe(0);
    });

    describe('인스턴스로 사용하는 방법', function() {

        it('CustomEventss 자체를 인스턴스로 생성하여 사용할 수도 있다', function() {
            var spy = jasmine.createSpy('spy');

            var inst = new ne.CustomEvents();

            inst.on('move', spy);

            inst.fire('move', { test: 'a' });

            expect(spy).toHaveBeenCalledWith({ test: 'a', type: 'move', target: inst });
        });

    });

    describe('getListenerLength', function() {
        var customEvent,
            thisObj,
            spy,
            spyObj;

        beforeEach(function() {
            customEvent = new ne.CustomEvents();
            spy = jasmine.createSpy('zoom');
            spyObj = jasmine.createSpyObj('spy', ['pan', 'zoom']);

            thisObj = {};

            customEvent.on({
                'pan': spyObj.pan,
                'zoom': spyObj.zoom
            }, thisObj);

            customEvent.on('zoom', spy);
        });

        it('할당된 이벤트의 갯수를 알 수 있다', function() {
            expect(customEvent.getListenerLength('zoom')).toBe(2);
            expect(customEvent.getListenerLength('pan')).toBe(1);
        });

        it('이벤트가 해제되어도 갯수가 반영된다', function() {
            customEvent.off('zoom', spyObj.zoom, thisObj);

            expect(customEvent.getListenerLength('zoom')).toBe(1);
        });

        it('이벤트를 모두 삭제하면 0', function() {
            customEvent.off();

            expect(customEvent.getListenerLength('zoom')).toBe(0);
        });

    });
});
<commit_msg>customEvent 테스트 케이스 강화<commit_after>describe('customEvent', function() {

    it('on() 메서드로 이벤트를 구독할 수 있다', function() {
        function Animal(leg) {
            this.leg = leg;
            this.position = 0;
        }

        ne.CustomEvents.mixin(Animal); // 커스텀 이벤트 기능 부여

        Animal.prototype.move = function(to) {
            this.position = to;
            this.fire('move');
        };

        var lion = new Animal(4);

        var deer = new Animal(4);

        // 사자가 움직이면 사슴은 도망감
        lion.on('move', function() {
            this.position = 100;
        }, deer);

        lion.move(50); // 사자가 움직인다.

        expect(deer.position).toBe(100);
    });

    it('on() 메서드는 첫 번째 인자에 객체를 넘겨 다중 이벤트를 한번에 설정할수도 있다', function() {
        function Animal(leg) {
            this.leg = leg;
            this.position = 0;
        }
        ne.CustomEvents.mixin(Animal); // 커스텀 이벤트 기능 부여

        Animal.prototype.move = function(to) {
            this.position = to;
            this.fire('move');
        };
        Animal.prototype.growl = function() {
            this.fire('growl');
        };

        var lion = new Animal(4);
        var deer = new Animal(4);

        lion.on({
            // 사자가 움직이면 사슴은 도망간다
            'move': function() {
                this.position = 100;
            },
            // 사자가 울부짖으면 사슴은 더 멀리 도망간다
            'growl': function() {
                this.position = 1000;
            }
        }, deer);

        lion.move(10);
        lion.growl();

        expect(deer.position).toBe(1000);
    });

    it('on() 메서드는 context를 제공하지 않으면 옵저버를 배열에 등록하여 사용한다', function() {

        function Animal(leg) {
            this.leg = leg;
            this.position = 0;
        }

        ne.CustomEvents.mixin(Animal); // 커스텀 이벤트 기능 부여

        Animal.prototype.move = function(to) {
            this.position = to;
            this.fire('move');
        };

        var lion = new Animal(4),
            growlFn = ne.bind(function() {
                this.position = 0;
            }, lion);

        lion.on('move', growlFn);

        expect(ne.isArray(lion._events['move'])).toBeTruthy();
    });

    it('on() 메서드는 context를 제공할 경우 옵저버 패턴을 객체를 이용한다', function() {
        function Animal(leg) {
            this.leg = leg;
            this.position = 0;
        }

        ne.CustomEvents.mixin(Animal); // 커스텀 이벤트 기능 부여

        Animal.prototype.move = function(to) {
            this.position = to;
            this.fire('move');
        };

        var lion = new Animal(4),
            onMove = function() {
                this.moved = true;
            };

        var myObj = {};

        lion.on('move', onMove, myObj);

        lion.move(10);

        ne.stamp(onMove);

        expect(myObj.moved).toBeTruthy();
        expect(lion._events['move_len']).toBe(1);

    });

    it('off() 메서드로 구독했던 이벤트 관계를 해제할 수 있다', function() {
        function Animal(leg) {
            this.leg = leg;
            this.position = 0;
        }

        ne.CustomEvents.mixin(Animal); // 커스텀 이벤트 기능 부여

        Animal.prototype.move = function (to) {
            this.position = to;
            this.fire('move');
        };

        var lion = new Animal(4),
            deer = new Animal(4),
            runAwayFn = function () {
                this.position = 1000;
            };

        // 사자가 움직이면 사슴은 도망감
        lion.on('move', runAwayFn, deer);

        // 사슴은 더 이상 도망가지 않음
        lion.off('move', runAwayFn, deer);

        lion.move(100);

        expect(deer.position).toBe(0);
    });

    it('off() 는 이벤트명:함수를 넘겨 동시에 여러 이벤트를 구독 해제할 수 있다', function() {
        function Animal(leg) {
            this.leg = leg;
            this.position = 0;
        }

        ne.CustomEvents.mixin(Animal); // 커스텀 이벤트 기능 부여

        Animal.prototype.move = function (to) {
            this.position = to;
            this.fire('move');
        };
        Animal.prototype.growl = function () {
            this.fire('growl');
        };

        var lion = new Animal(4);
        var deer = new Animal(4);

        var runAwayFn = function() {
            this.position = 1000;
        };

        lion.on({
            // 사자가 움직이면 사슴은 도망간다
            'move': runAwayFn,
            // 사자가 울부짖으면 사슴은 더 멀리 도망간다
            'growl': runAwayFn
        }, deer);

        lion.off({
            'move': runAwayFn,
            'growl': runAwayFn
        }, deer);

        lion.move(10);
        lion.growl();

        expect(deer.position).toBe(0);
    });

    it('off() 는 아무 인자도 넘기지 않으면 모든 구독을 해제한다', function() {
        function Animal(leg) {
            this.leg = leg;
            this.position = 0;
        }

        ne.CustomEvents.mixin(Animal); // 커스텀 이벤트 기능 부여

        Animal.prototype.move = function (to) {
            this.position = to;
            this.fire('move');
        };
        Animal.prototype.growl = function () {
            this.fire('growl');
        };

        var lion = new Animal(4);
        var deer = new Animal(4);

        var runAwayFn = function () {
            this.position = 1000;
        };

        lion.on({
            // 사자가 움직이면 사슴은 도망간다
            'move': runAwayFn,
            // 사자가 울부짖으면 사슴은 더 멀리 도망간다
            'growl': runAwayFn
        }, deer);

        lion.off();

        lion.move(10);
        lion.growl();

        expect(deer.position).toBe(0);
    });

    it('once() 메서드로 단발성 커스텀 이벤트를 등록할 수 있다', function() {
        function Animal(leg) {
            this.leg = leg;
            this.position = 0;
        }

        ne.CustomEvents.mixin(Animal); // 커스텀 이벤트 기능 부여

        Animal.prototype.move = function(to) {
            this.position = to;
            this.fire('move');
        };

        var lion = new Animal(4);

        lion.moveDistance = 0;

        lion.once('move', function() {
            this.moveDistance += this.position;
        }, lion);

        lion.move(10);
        lion.move(10);

        expect(lion.moveDistance).toBe(10);
    });

    it('once() 도 마찬가지로 첫 번째 인자에 이벤트명:핸들러 객체로 한번헤 구독할 수 있다', function() {
        function Animal(leg) {
            this.leg = leg;
            this.position = 0;
        }

        ne.CustomEvents.mixin(Animal); // 커스텀 이벤트 기능 부여

        Animal.prototype.move = function(to) {
            this.position = to;
            this.fire('move');
        };
        Animal.prototype.back = function(distance) {
            this.fire('back', { distance: distance });
            this.position = -distance;
        };

        var lion = new Animal(4);

        lion.moveDistance = 0;

        lion.once({
            'move': function() {
                this.moveDistance += this.position;
            },
            'back': function(backEvent) {
                this.moveDistance -= backEvent.distance;
            }
        }, lion);

        lion.move(10);
        lion.move(10);
        lion.back(10);

        expect(lion.moveDistance).toBe(0);
    });

    describe('off 예외 테스트', function() {
        var customEvent;

        beforeEach(function() {
            customEvent = new ne.CustomEvents();
        });

        it('아무 이벤트도 등록하지 않았을 때 off를 호출해도 문제 없다', function() {
            expect(function() {
                customEvent.off();
            }).not.toThrow();
        });

    });

    describe('인스턴스로 사용하는 방법', function() {

        it('CustomEventss 자체를 인스턴스로 생성하여 사용할 수도 있다', function() {
            var spy = jasmine.createSpy('spy');

            var inst = new ne.CustomEvents();

            inst.on('move', spy);

            inst.fire('move', { test: 'a' });

            expect(spy).toHaveBeenCalledWith({ test: 'a', type: 'move', target: inst });
        });

    });

    describe('getListenerLength', function() {
        var customEvent,
            thisObj,
            spy,
            spyObj;

        describe('예외 테스트', function() {
            beforeEach(function() {
                customEvent = new ne.CustomEvents();
            });

            it('이벤트를 등록하지 않았을 경우 0', function() {
                expect(customEvent.getListenerLength('pan')).toBe(0);
            });

            describe('등록했다 해제할 경우', function() {
                var customEvent2;

                beforeEach(function() {
                    spy = jasmine.createSpy('zoom');
                    spyObj = jasmine.createSpyObj('test', ['zoom']);

                    customEvent.on('zoom', spyObj.zoom, thisObj);
                    customEvent.off('zoom', spyObj.zoom, thisObj);
                    customEvent2 = new ne.CustomEvents();
                    customEvent2.on('zoom', spy);
                    customEvent2.off('zoom', spy);
                });

                it('context 제공 시', function() {
                    expect(customEvent.getListenerLength('zoom')).toBe(0);
                });

                it('context 비 제공 시', function() {
                    expect(customEvent2.getListenerLength('zoom')).toBe(0);
                });
            });
        });

        describe('갯수 테스트', function() {
            beforeEach(function() {
                customEvent = new ne.CustomEvents();
                spy = jasmine.createSpy('zoom');
                spyObj = jasmine.createSpyObj('spy', ['pan', 'zoom']);

                thisObj = {};

                customEvent.on({
                    'pan': spyObj.pan,
                    'zoom': spyObj.zoom
                }, thisObj);

                customEvent.on('zoom', spy);
            });

            it('할당된 이벤트의 갯수를 알 수 있다', function() {
                expect(customEvent.getListenerLength('zoom')).toBe(2);
                expect(customEvent.getListenerLength('pan')).toBe(1);
            });

            it('이벤트가 해제되어도 갯수가 반영된다', function() {
                customEvent.off('zoom', spyObj.zoom, thisObj);

                expect(customEvent.getListenerLength('zoom')).toBe(1);
            });

            it('이벤트가 해제되면 갯수가 반영된다', function() {
                customEvent.off('zoom', spy);

                expect(customEvent.getListenerLength('zoom')).toBe(1);
            });

            it('이벤트를 모두 삭제하면 0', function() {
                customEvent.off();

                expect(customEvent.getListenerLength('zoom')).toBe(0);
            });
        });

    });
});
<|endoftext|>


<commit_before>/* Naïve implementation of web worker process model using HEROKU SCHEDULER */

// NOTE: first iteration -> update update complaints table with 10k/job results until 600k total

// Complaints will always update 10k results every 1 hour until reached max
// offset should increment by 10000 each query (start offset=0)
var offset = 0;
function complaintsOffset() {
  offset += 10000;
  return offset <= 600000 ? initComplaintsTable(Complaint, offset);
};

complaintsOffset();

// TODO: web worker handles message queue and stores recent queries
<commit_msg>(fix) Include module dependency for job<commit_after>/* Naïve implementation of web worker process model using HEROKU SCHEDULER */

// NOTE: first iteration -> update update complaints table with 10k/job results until 600k total
var Complaint = require('./db.config').Complaint;
var initComplaintsTable = require('./seed/complaint.seed').initComplaintsTable;

// Complaints will always update 10k results every 1 hour until reached max
// offset should increment by 10000 each query (start offset=0)
var offset = 0;
function complaintsOffset() {
  offset += 10000;
  return offset <= 600000 ? initComplaintsTable(Complaint, offset): false;
};

complaintsOffset();

// TODO: web worker handles message queue and stores recent queries
<|endoftext|>


<commit_before>var panelId;
function setPanelId(thisid)
{
  panelId = thisid;
}
function showHideDivBlock(hideDivisionNo, context)
{
  var tmpdiv = hideDivisionNo + "__hide_division_";
  var tmpimg = hideDivisionNo + "__img_hide_division_";
  var divisionNo = getTheElement(tmpdiv);
  var imgNo = getTheElement(tmpimg);
  if(divisionNo)
  {
    if(divisionNo.style.display =="block")
    {
      divisionNo.style.display="none";
      if (imgNo)
      {
        imgNo.src = context + "/images/right_arrow.gif";
       }
    }
    else
    {
      divisionNo.style.display="block";
      if(imgNo)
      {
        imgNo.src = context + "/images/down_arrow.gif";
      }
    }
    if(panelId != null)
    {
      setMainFrameHeight(panelId);
    }
  }
}
function showHideDiv(hideDivisionNo, context)
{
  var tmpdiv = hideDivisionNo + "__hide_division_";
  var tmpimg = hideDivisionNo + "__img_hide_division_";
  var divisionNo = getTheElement(tmpdiv);
  var imgNo = getTheElement(tmpimg);

  if(divisionNo)
  {
    if(divisionNo.style.display =="block" || divisionNo.style.display =="table-row")
    {
      divisionNo.style.display="none";
      if (imgNo)
      {
        imgNo.src = context + "/images/collapse.gif";
      }
    }
    else
    {
      if(navigator.product == "Gecko")
      {
        divisionNo.style.display="table-row";
      }
      else
      {
        divisionNo.style.display="block";
      }
      if(imgNo)
      {
        imgNo.src = context + "/images/expand.gif";
      }
    }
  }
}

function getTheElement(thisid)
{

  var thiselm = null;

  if (document.getElementById)
  {
    thiselm = document.getElementById(thisid);
  }
  else if (document.all)
  {
    thiselm = document.all[thisid];
  }
  else if (document.layers)
  {
    thiselm = document.layers[thisid];
  }

  if(thiselm)
  {
    if(thiselm == null)
    {
      return;
    }
    else
    {
      return thiselm;
    }
  }
}

function check(field)
 {
    for (i = 0; i < field.length; i++)
    {
        field[i].checked = true;
    }
 }
function unCheck(field)
{
    for (i = 0; i < field.length; i++)
    {
        field[i].checked = false;
    }
}

function toggleDisplay(obj) {
	resize();
	$("#" + obj).slideToggle("normal", resize);
	return;
}

function toggleHide(obj){
	if(obj.innerHTML.match(/hide/i)){
		obj.innerHTML = obj.innerHTML.replace('Hide ', '');
	} else {
		obj.innerHTML = obj.innerHTML.replace(/(<.+>)([^<>]+)/i, "$1 Hide $2");
	}
}
function getScrollDist(obj){
	var curtop = 0;
	if (obj.offsetParent) {
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curtop += obj.offsetTop
		}
	}
	return curtop;
}
function selectDeselectCheckboxes(mainCheckboxId, myForm) {
	var el = getTheElement(mainCheckboxId);
	var isChecked = el.checked;
	for ( i = 0; i < myForm.elements.length; i++ ) {
		if (myForm.elements[i].type == 'checkbox' ) {
			myForm.elements[i].checked  = isChecked;
		}
	}
}
function resetMainCheckbox(checkboxId) {
  mainCheckboxEl = getTheElement(checkboxId);
  if (mainCheckboxEl.checked = true) {
  	mainCheckboxEl.checked = false;
  }
}
// if the containing frame is small, then offsetHeight is pretty good for all but ie/xp.
// ie/xp reports clientHeight == offsetHeight, but has a good scrollHeight
function mySetMainFrameHeight(id)
{
	// run the script only if this window's name matches the id parameter
	// this tells us that the iframe in parent by the name of 'id' is the one who spawned us
	if (typeof window.name != "undefined" && id != window.name) return;

	var frame = parent.document.getElementById(id);
	if (frame)
	{

		var objToResize = (frame.style) ? frame.style : frame;

		var height;

		var scrollH = document.body.scrollHeight;
		var offsetH = document.body.offsetHeight;
		var clientH = document.body.clientHeight;
		var innerDocScrollH = null;

		if (typeof(frame.contentDocument) != 'undefined' || typeof(frame.contentWindow) != 'undefined')
		{
			// very special way to get the height from IE on Windows!
			// note that the above special way of testing for undefined variables is necessary for older browsers
			// (IE 5.5 Mac) to not choke on the undefined variables.
 			var innerDoc = (frame.contentDocument) ? frame.contentDocument : frame.contentWindow.document;
			innerDocScrollH = (innerDoc != null) ? innerDoc.body.scrollHeight : null;
		}

		if (document.all && innerDocScrollH != null)
		{
			// IE on Windows only
			height = innerDocScrollH;
		}
		else
		{
			// every other browser!
			height = offsetH;
		}

		// here we fudge to get a little bigger
		//gsilver: changing this from 50 to 10, and adding extra bottom padding to the portletBody
		var newHeight = height + 150;
		//contributed patch from hedrick@rutgers.edu (for very long documents)
		if (newHeight > 32760)
		newHeight = 32760;

		// no need to be smaller than...
		//if (height < 200) height = 200;
		objToResize.height=newHeight + "px";

		var s = " scrollH: " + scrollH + " offsetH: " + offsetH + " clientH: " + clientH + " innerDocScrollH: " + innerDocScrollH + " Read height: " + height + " Set height to: " + newHeight;

	}
}

function doAjax(messageId, topicId, self){
 	$(self).attr('src', '/library/image/sakai/spinner.gif');
	$.ajax({ type: "GET", url: "dfAjax", data: "action=markMessageAsRead&messageId=" + messageId + "&topicId=" + topicId,
      success: function(msg){
         if(msg.match(/SUCCESS/)){
     		setTimeout(function(){
              $(self).remove();
               $("#" + messageId).parents("tr:first").children("td").each(function(){this.innerHTML = this.innerHTML.replace(/unreadMsg/g, 'bogus'); });
            }, 500);
         } else {
            $(self).remove();
            $("#" + messageId).parents("tr:first").css("backgroundColor", "#ffD0DC");
         }
      },
      error: function(){
         $(self).remove();
         $("#" + messageId).parents("tr:first").css("backgroundColor", "#ffD0DC");
      }
   });
	$.ajax({type: "GET", url: location.href, data: ""});
	return false;
}

//fix for double click stack traces in IE - SAK-10625
//add Jquery if necessary
if(typeof($) == "undefined"){
   js = document.createElement('script');
   js.setAttribute('language', 'javascript');
   js.setAttribute('type', 'text/javascript');
   js.setAttribute('src','/library/js/jquery.js');
   document.getElementsByTagName('head').item(0).appendChild(js);
//document.write('<script type="text/javascript" src="/library/js/jquery.js"></script>');}
}
js = document.createElement('script');
js.setAttribute('language', 'javascript');
js.setAttribute('type', 'text/javascript');
js.setAttribute('src','/sakai-messageforums-tool/js/sak-10625.js');
document.getElementsByTagName('head').item(0).appendChild(js);<commit_msg>svn merge -r 36621:36622 https://source.sakaiproject.org/svn/msgcntr/branches/oncourse_2-4-x/           U    messageforums-app/src/webapp/js/forum.js in-143-146:~/tempspace/trunk admin$ svn log -r 36622 https://source.sakaiproject.org/svn/msgcntr/branches/oncourse_2-4-x/ ------------------------------------------------------------------------ r36622 | wagnermr@iupui.edu | 2007-10-09 16:05:48 -0400 (Tue, 09 Oct 2007) | 1 line<commit_after>var panelId;
function setPanelId(thisid)
{
  panelId = thisid;
}
function showHideDivBlock(hideDivisionNo, context)
{
  var tmpdiv = hideDivisionNo + "__hide_division_";
  var tmpimg = hideDivisionNo + "__img_hide_division_";
  var divisionNo = getTheElement(tmpdiv);
  var imgNo = getTheElement(tmpimg);
  if(divisionNo)
  {
    if(divisionNo.style.display =="block")
    {
      divisionNo.style.display="none";
      if (imgNo)
      {
        imgNo.src = context + "/images/right_arrow.gif";
       }
    }
    else
    {
      divisionNo.style.display="block";
      if(imgNo)
      {
        imgNo.src = context + "/images/down_arrow.gif";
      }
    }
    if(panelId != null)
    {
      setMainFrameHeight(panelId);
    }
  }
}
function showHideDiv(hideDivisionNo, context)
{
  var tmpdiv = hideDivisionNo + "__hide_division_";
  var tmpimg = hideDivisionNo + "__img_hide_division_";
  var divisionNo = getTheElement(tmpdiv);
  var imgNo = getTheElement(tmpimg);

  if(divisionNo)
  {
    if(divisionNo.style.display =="block" || divisionNo.style.display =="table-row")
    {
      divisionNo.style.display="none";
      if (imgNo)
      {
        imgNo.src = context + "/images/collapse.gif";
      }
    }
    else
    {
      if(navigator.product == "Gecko")
      {
        divisionNo.style.display="table-row";
      }
      else
      {
        divisionNo.style.display="block";
      }
      if(imgNo)
      {
        imgNo.src = context + "/images/expand.gif";
      }
    }
  }
}

function getTheElement(thisid)
{

  var thiselm = null;

  if (document.getElementById)
  {
    thiselm = document.getElementById(thisid);
  }
  else if (document.all)
  {
    thiselm = document.all[thisid];
  }
  else if (document.layers)
  {
    thiselm = document.layers[thisid];
  }

  if(thiselm)
  {
    if(thiselm == null)
    {
      return;
    }
    else
    {
      return thiselm;
    }
  }
}

function check(field)
 {
    for (i = 0; i < field.length; i++)
    {
        field[i].checked = true;
    }
 }
function unCheck(field)
{
    for (i = 0; i < field.length; i++)
    {
        field[i].checked = false;
    }
}

function toggleDisplay(obj) {
	resize();
	$("#" + obj).slideToggle("normal", resize);
	return;
}

function toggleHide(obj){
	if(obj.innerHTML.match(/hide/i)){
		obj.innerHTML = obj.innerHTML.replace('Hide ', '');
	} else {
		obj.innerHTML = obj.innerHTML.replace(/(<.+>)([^<>]+)/i, "$1 Hide $2");
	}
}
function getScrollDist(obj){
	var curtop = 0;
	if (obj.offsetParent) {
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curtop += obj.offsetTop
		}
	}
	return curtop;
}
function selectDeselectCheckboxes(mainCheckboxId, myForm) {
	var el = getTheElement(mainCheckboxId);
	var isChecked = el.checked;
	for ( i = 0; i < myForm.elements.length; i++ ) {
		if (myForm.elements[i].type == 'checkbox' ) {
			myForm.elements[i].checked  = isChecked;
		}
	}
}
function resetMainCheckbox(checkboxId) {
  mainCheckboxEl = getTheElement(checkboxId);
  if (mainCheckboxEl.checked = true) {
  	mainCheckboxEl.checked = false;
  }
}
// if the containing frame is small, then offsetHeight is pretty good for all but ie/xp.
// ie/xp reports clientHeight == offsetHeight, but has a good scrollHeight
function mySetMainFrameHeight(id)
{
	// run the script only if this window's name matches the id parameter
	// this tells us that the iframe in parent by the name of 'id' is the one who spawned us
	if (typeof window.name != "undefined" && id != window.name) return;

	var frame = parent.document.getElementById(id);
	if (frame)
	{

		var objToResize = (frame.style) ? frame.style : frame;

		var height;

		var scrollH = document.body.scrollHeight;
		var offsetH = document.body.offsetHeight;
		var clientH = document.body.clientHeight;
		var innerDocScrollH = null;

		if (typeof(frame.contentDocument) != 'undefined' || typeof(frame.contentWindow) != 'undefined')
		{
			// very special way to get the height from IE on Windows!
			// note that the above special way of testing for undefined variables is necessary for older browsers
			// (IE 5.5 Mac) to not choke on the undefined variables.
 			var innerDoc = (frame.contentDocument) ? frame.contentDocument : frame.contentWindow.document;
			innerDocScrollH = (innerDoc != null) ? innerDoc.body.scrollHeight : null;
		}

		if (document.all && innerDocScrollH != null)
		{
			// IE on Windows only
			height = innerDocScrollH;
		}
		else
		{
			// every other browser!
			height = offsetH;
		}

		// here we fudge to get a little bigger
		//gsilver: changing this from 50 to 10, and adding extra bottom padding to the portletBody
		var newHeight = height + 150;
		//contributed patch from hedrick@rutgers.edu (for very long documents)
		if (newHeight > 32760)
		newHeight = 32760;

		// no need to be smaller than...
		//if (height < 200) height = 200;
		objToResize.height=newHeight + "px";

		var s = " scrollH: " + scrollH + " offsetH: " + offsetH + " clientH: " + clientH + " innerDocScrollH: " + innerDocScrollH + " Read height: " + height + " Set height to: " + newHeight;

	}
}

function doAjax(messageId, topicId, self){
 	$(self).attr('src', '/library/image/sakai/spinner.gif');
	$.ajax({ type: "GET", url: "dfAjax", data: "action=markMessageAsRead&messageId=" + messageId + "&topicId=" + topicId,
      success: function(msg){
         if(msg.match(/SUCCESS/)){
     		setTimeout(function(){
              $(self).remove();
               $("#" + messageId).parents("tr:first").children("td").each(function(){this.innerHTML = this.innerHTML.replace(/unreadMsg/g, 'bogus'); });
            }, 500);
         } else {
            $(self).remove();
            $("#" + messageId).parents("tr:first").css("backgroundColor", "#ffD0DC");
         }
      },
      error: function(){
         $(self).remove();
         $("#" + messageId).parents("tr:first").css("backgroundColor", "#ffD0DC");
      }
   });
	$.ajax({type: "GET", url: location.href, data: ""});
	return false;
}

//fix for double click stack traces in IE - SAK-10625
//add Jquery if necessary
/*if(typeof($) == "undefined"){
   js = document.createElement('script');
   js.setAttribute('language', 'javascript');
   js.setAttribute('type', 'text/javascript');
   js.setAttribute('src','/library/js/jquery.js');
   document.getElementsByTagName('head').item(0).appendChild(js);
//document.write('<script type="text/javascript" src="/library/js/jquery.js"></script>');}
}
js = document.createElement('script');
js.setAttribute('language', 'javascript');
js.setAttribute('type', 'text/javascript');
js.setAttribute('src','/sakai-messageforums-tool/js/sak-10625.js');
document.getElementsByTagName('head').item(0).appendChild(js);*/
<|endoftext|>


<commit_before>import Ember from 'ember';
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';

export default Ember.Route.extend(AuthenticatedRouteMixin, {
  model: function() {
    return this.store.query('convention', {year__gte: 2015, year__lte: 2016});
  },
});
<commit_msg>Add convention restriction to Admin<commit_after>import Ember from 'ember';
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';

export default Ember.Route.extend(AuthenticatedRouteMixin, {
  model: function() {
    return this.store.query('convention', {year: 2016, season: 4});
  },
});
<|endoftext|>


<commit_before>/*
 * Uses CommonJS, Node, AMD or browser globals to create a module
 * per pattern of UMD
 * https://github.com/umdjs/umd/
 * */
(function (root, factory) {
  if (typeof exports === 'object') {
    //CommonJS
    factory(require('dustjs-linkedin'));
  } else if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['dustjs-linkedin'], factory);
  } else {
    // Browser globals (root is window)
    factory(root.dust);
  }
}(this, function(dust) {

  /*
   * A modules that adds secure filters to Dust
   * @module dustjs-filters-secure
   * @require dustjs-linkedin
   * @return undefined
   */
  var filters = {};

  if(!String.prototype.trim) {
    String.prototype.trim = function () {
      return this.replace(/^\s+|\s+$/g,'');
    };
  }

  /* private helper functions */

  /* setup escapeHTML and unescapeHTML */
  var escapeHTML, unescapeHTML;
  (function(undefined) {

    var index = {
      '\t': '\t',
      '\r': '\r',
      '\n': '\n',
      '\u00a0': ' ',
      '<': '<',
      '>': '>',
      '&': '&',
      '"': '"',
      '\u007f': '�', //map delete to unknown
      '\u2028': '
', //line separator
      '\u2029': '
' //paragraph separator
    },
    // reverseIndex = {
      // '\t': '\t',
      // '\r': '\r',
      // '\n': '\n',
      // ' ': '\u00a0',
      // '<': '<',
      // '>': '>',
      // '&': '&',
      // '"': '"',
      // '�': '\u007f',
      // '
': '\u2028',
      // '
': '\u2029'
    // },
    i, c;

    // replace all control chars with the unknown replacement character
    for (i = 0; i < 0x20; i++) {
      c = String.fromCharCode(i);
      if (index[c] === undefined) {
        index[c] = '�';
      }
    }

    // this range of chars with will be replaced with HTML entities, if add symbol with code more than 127, check that it in index table
    var re = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u00a0<>'"`\\\[\]+\-=.:(){};,\/&\u007f\u2028\u2029]/g;

    // precache index
    for (i = 0x20; i < 128; i++) {
      c = String.fromCharCode(i);
      if (index[c] === undefined && c.match(re)) {
        index[c] = '&#' + i + ';';
        // reverseIndex['&#'+i+';'] = c;
      }
    }

    escapeHTML = function(s) {
      if (s === null || s === undefined) {
        return null;
      }
      var type = typeof s;
      if (type === 'number' || type === 'boolean') {
        return s + '';
      }
      return (s + '').replace(re, function(c) {
        return index[c];
      });
    };

    unescapeHTML = function(s) {
      if (s === null || s === undefined) {
        return null;
      }
      var type = typeof s;
      if (type === 'number' || type === 'boolean') {
        return s + '';
      }
      return (s + '').
          replace( ' ', '\u00a0').
          replace('<', '<').
          replace('>', '>').
          replace('&', '&').
          replace('"', '"').
          replace('�', '\u007f').
          replace('
', '\u2028').
          replace('
', '\u2029').
          replace(''', '"').
          replace('(', '\'').
          replace(')', '(').
          replace('+', ')').
          replace(',', '+').
          replace('-', ',').
          replace('.', '-').
          replace('/', '.').
          replace(':', '/').
          replace(';', ':').
          replace('=', ';').
          replace('[', '=').
          replace('\', '[').
          replace(']', '\\').
          replace('`', ']').
          replace('{', '`').
          replace('}', '{');
    };
  }());

  /* setup both escapeJs and JSONStringify */
  var escapeJs, customJsonStringify = (JSON && JSON.stringify)? JSON.stringify : function() { throw new Error('JSON.stringify not found'); } ;
  (function(undefined) {
    // {}[],:-+. can be outside of JSON strings
    // \u2028\u2029 can break JavaScript strings: eval('("\u2028")')
    var jsonRE = /[\/<>&%\u0000\u2028\u2029*()'=!?`#]/g; // chars additionaly encoded by JSON.stringify
    var jsRE = /[^a-z0-9_\u0080-\u2027\u202a-\uffff]/ig; // chars encoded by jsEncode
    // if you change any of jsonRE or jsRE, check that this char in index
    var index = {
          '\t': '\\t',
          '\n': '\\n',
          '\r': '\\r',
          '\u2028': '\\u2028',
          '\u2029': '\\u2029'
        };

    // precache chars for jsRE
    // jsRE includes jsonRE
    for (var i = 0; i < 128; i++) {
      var c = String.fromCharCode(i);
      if (index[c] === undefined && c.match(jsRE)) {
        index[c] = '\\u' + ('000' + c.charCodeAt(0).toString(16)).slice(-4);
      }
    }

    /* escapeJS */
    escapeJs = function(s) {
      if (s === null || s === undefined) {
        return null;
      }
      var type = typeof s;
      if (type === 'number' || type === 'boolean') {
        return s + '';
      }
      return (s + '').replace(jsRE, function(c) {
        return index[c];
      });
    };

    /* custom Stringify */
    // check that JSON.stringify is native
    if (JSON && JSON.stringify && JSON.stringify('\\"\/<>&%\u0000\u2028\u2029*()\'=!?`#') === '"\\\\\\"/<>&%\\u0000\u2028\u2029*()\'=!?`#"') {
      var nativeStringify = JSON.stringify;
      customJsonStringify = function() {
        return nativeStringify.apply(this, arguments).replace(jsonRE, function(c) {
          return index[c];
        });
      };
    }
  })();

  /*
   * This function checks protocol of URL and if it's not safe adds ./ before like ./jAvascript:alert(1)
   * don't use HTML encoded URLs here
   * {website|h|url} is wrong
   * you can use it as website
   * or
   */
  var sanitizeURL = (function(undefined) {
    // symbols which will be replaced or encoded to URI
    var re = /[\u0000-\u0020\u001f`'"<>()\[\]{}\\,]/g,
        index = {
          '\t': '%09',
          '\r': '%0D',
          '\n': '%0A',
          '\u001f': '\ufffd'
        },
        i, c;

    // replace all control chars with safe one
    for (i = 0; i < 0x20; i++) {
      c = String.fromCharCode(i);
      if (index[c] === undefined) {
        index[c] = '\ufffd';
      }
    }

    for (i = 0x20; i < 128; i++) {
      c = String.fromCharCode(i);
      if (index[c] === undefined && c.match(re)) {
        index[c] = escape(c); // escape only receives ASCII chars here so it behaves well
      }
    }
    return function(url) {
      if (url === null || url === undefined) {
        return null;
      }
      url = url.trim()  // trim method has been shimmed for IE
        .replace(re, function(c) {
          return index[c];
        })
        .replace(/[\s\u2028\u2029]/g, '%20') // all custom spaces must be URI encoded
        .replace(/&#/g, '#') // in normals URLs this situation possible only for not URI encoded HTML entities http://w3.org/test?a=b<
        .replace(/(&[a-zA-Z]+);/g, '$1%3B') // we encode semi-colon if it looks like HTML entity  javascript
	:' but not &quot&lt&gt&amp
        .replace(/^([\s\S]{0,14});/g, '$1%3B') // https://;URL=javascript:alert(1)
        .replace(/(&[quolgQUOLG]{1,3})t/g, '$1%74') // &qUot, &lt, &Gt we encode t and T if it looks like HTML entity, because some of them can be used without semi-colon
        .replace(/(&[quolgQUOLG]{1,3})T/g, '$1%54') // &quoT, &LT, &gT
        .replace(/%(?=[^A-Fa-f0-9]|[A-Fa-f0-9][^A-Fa-f0-9]|[\s\S]?$)/g, '%25'); // encode all not correct URI encoded strings like %%1%g1

      var lc = url.toLowerCase();
      // if URL starts not from http, mailto, ftp and #hash, ?search, //UNC, /root, ../relative and have scheme:
      if (!/^(?:http|mailto|ftp|[#\/.?])/.test(lc) && /^[^?\/#:]+?:/.test(lc)) {
        // if URL starts from wrong scheme or have encoded entity
        if (/^(?:about|cdl|dvd|local|mhtml|mk|ms-help|ms-its|tv|res|its|javascript|data|vbs|vbscript|feed|java|jar|file|[a-z]):/.test(lc) || !/^[a-z0-1\-_.]+?:/.test(lc)) {
          url = './' + url;
        }
      }

      return url;
    };
  }());

  // http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Functions:encodeURIComponent
  // compatible with OAuth signature calculation
  var localEncodeURIComponent = function() {
    return encodeURIComponent.apply(this, arguments).replace(/[!'()]/g, escape).replace(/\*/g, '%2A');
  };

  filters = {
    temp: function(value) { return value; },
    h: function(value) { return escapeHTML(value); },
    j: function(value) { return escapeJs(value); },
    url: function(value) { return sanitizeURL(value); },
    uc: function(value) { return localEncodeURIComponent(value); },
    js: function(value) { return customJsonStringify(value); }
  };

  /* Be nice if filters is already defined, but not too nice ... clobber over what there */
  if (dust.filters){
    for (var filterName in filters){
      if (filters.hasOwnProperty(filterName)){
        dust.filters[filterName] = filters[filterName];
      }
    }
  } else {
    dust.filters = filters;
  }

  /* We are writing to the `dust` object so we don't need to return anything */
}));
<commit_msg>remove ugly code<commit_after>/*
 * Uses CommonJS, Node, AMD or browser globals to create a module
 * per pattern of UMD
 * https://github.com/umdjs/umd/
 * */
(function (root, factory) {
  if (typeof exports === 'object') {
    //CommonJS
    factory(require('dustjs-linkedin'));
  } else if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['dustjs-linkedin'], factory);
  } else {
    // Browser globals (root is window)
    factory(root.dust);
  }
}(this, function(dust) {

  /*
   * A modules that adds secure filters to Dust
   * @module dustjs-filters-secure
   * @require dustjs-linkedin
   * @return undefined
   */
  var filters = {};

  if(!String.prototype.trim) {
    String.prototype.trim = function () {
      return this.replace(/^\s+|\s+$/g,'');
    };
  }

  /* private helper functions */

  /* setup escapeHTML and unescapeHTML */
  var escapeHTML, unescapeHTML;
  (function(undefined) {

    var index = {
      '\t': '\t',
      '\r': '\r',
      '\n': '\n',
      '\u00a0': ' ',
      '<': '<',
      '>': '>',
      '&': '&',
      '"': '"',
      '\u007f': '�', //map delete to unknown
      '\u2028': '
', //line separator
      '\u2029': '
' //paragraph separator
    }, i, c;

    // replace all control chars with the unknown replacement character
    for (i = 0; i < 0x20; i++) {
      c = String.fromCharCode(i);
      if (index[c] === undefined) {
        index[c] = '�';
      }
    }

    // this range of chars with will be replaced with HTML entities, if add symbol with code more than 127, check that it in index table
    var re = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u00a0<>'"`\\\[\]+\-=.:(){};,\/&\u007f\u2028\u2029]/g;

    // precache index
    for (i = 0x20; i < 128; i++) {
      c = String.fromCharCode(i);
      if (index[c] === undefined && c.match(re)) {
        index[c] = '&#' + i + ';';
      }
    }

    escapeHTML = function(s) {
      if (s === null || s === undefined) {
        return null;
      }
      var type = typeof s;
      if (type === 'number' || type === 'boolean') {
        return s + '';
      }
      return (s + '').replace(re, function(c) {
        return index[c];
      });
    };

    unescapeHTML = function(s) {
      if (s === null || s === undefined) {
        return null;
      }
      var type = typeof s;
      if (type === 'number' || type === 'boolean') {
        return s + '';
      }
      return (s + '').
          replace( ' ', '\u00a0').
          replace('<', '<').
          replace('>', '>').
          replace('&', '&').
          replace('"', '"').
          replace('�', '\u007f').
          replace('
', '\u2028').
          replace('
', '\u2029').
          replace(''', '"').
          replace('(', '\'').
          replace(')', '(').
          replace('+', ')').
          replace(',', '+').
          replace('-', ',').
          replace('.', '-').
          replace('/', '.').
          replace(':', '/').
          replace(';', ':').
          replace('=', ';').
          replace('[', '=').
          replace('\', '[').
          replace(']', '\\').
          replace('`', ']').
          replace('{', '`').
          replace('}', '{');
    };
  }());

  /* setup both escapeJs and JSONStringify */
  var escapeJs, customJsonStringify = (JSON && JSON.stringify)? JSON.stringify : function() { throw new Error('JSON.stringify not found'); } ;
  (function(undefined) {
    // {}[],:-+. can be outside of JSON strings
    // \u2028\u2029 can break JavaScript strings: eval('("\u2028")')
    var jsonRE = /[\/<>&%\u0000\u2028\u2029*()'=!?`#]/g; // chars additionaly encoded by JSON.stringify
    var jsRE = /[^a-z0-9_\u0080-\u2027\u202a-\uffff]/ig; // chars encoded by jsEncode
    // if you change any of jsonRE or jsRE, check that this char in index
    var index = {
          '\t': '\\t',
          '\n': '\\n',
          '\r': '\\r',
          '\u2028': '\\u2028',
          '\u2029': '\\u2029'
        };

    // precache chars for jsRE
    // jsRE includes jsonRE
    for (var i = 0; i < 128; i++) {
      var c = String.fromCharCode(i);
      if (index[c] === undefined && c.match(jsRE)) {
        index[c] = '\\u' + ('000' + c.charCodeAt(0).toString(16)).slice(-4);
      }
    }

    /* escapeJS */
    escapeJs = function(s) {
      if (s === null || s === undefined) {
        return null;
      }
      var type = typeof s;
      if (type === 'number' || type === 'boolean') {
        return s + '';
      }
      return (s + '').replace(jsRE, function(c) {
        return index[c];
      });
    };

    /* custom Stringify */
    // check that JSON.stringify is native
    if (JSON && JSON.stringify && JSON.stringify('\\"\/<>&%\u0000\u2028\u2029*()\'=!?`#') === '"\\\\\\"/<>&%\\u0000\u2028\u2029*()\'=!?`#"') {
      var nativeStringify = JSON.stringify;
      customJsonStringify = function() {
        return nativeStringify.apply(this, arguments).replace(jsonRE, function(c) {
          return index[c];
        });
      };
    }
  })();

  /*
   * This function checks protocol of URL and if it's not safe adds ./ before like ./jAvascript:alert(1)
   * don't use HTML encoded URLs here
   * {website|h|url} is wrong
   * you can use it as website
   * or
   */
  var sanitizeURL = (function(undefined) {
    // symbols which will be replaced or encoded to URI
    var re = /[\u0000-\u0020\u001f`'"<>()\[\]{}\\,]/g,
        index = {
          '\t': '%09',
          '\r': '%0D',
          '\n': '%0A',
          '\u001f': '\ufffd'
        },
        i, c;

    // replace all control chars with safe one
    for (i = 0; i < 0x20; i++) {
      c = String.fromCharCode(i);
      if (index[c] === undefined) {
        index[c] = '\ufffd';
      }
    }

    for (i = 0x20; i < 128; i++) {
      c = String.fromCharCode(i);
      if (index[c] === undefined && c.match(re)) {
        index[c] = escape(c); // escape only receives ASCII chars here so it behaves well
      }
    }
    return function(url) {
      if (url === null || url === undefined) {
        return null;
      }
      url = url.trim()  // trim method has been shimmed for IE
        .replace(re, function(c) {
          return index[c];
        })
        .replace(/[\s\u2028\u2029]/g, '%20') // all custom spaces must be URI encoded
        .replace(/&#/g, '#') // in normals URLs this situation possible only for not URI encoded HTML entities http://w3.org/test?a=b<
        .replace(/(&[a-zA-Z]+);/g, '$1%3B') // we encode semi-colon if it looks like HTML entity  javascript
	:' but not &quot&lt&gt&amp
        .replace(/^([\s\S]{0,14});/g, '$1%3B') // https://;URL=javascript:alert(1)
        .replace(/(&[quolgQUOLG]{1,3})t/g, '$1%74') // &qUot, &lt, &Gt we encode t and T if it looks like HTML entity, because some of them can be used without semi-colon
        .replace(/(&[quolgQUOLG]{1,3})T/g, '$1%54') // &quoT, &LT, &gT
        .replace(/%(?=[^A-Fa-f0-9]|[A-Fa-f0-9][^A-Fa-f0-9]|[\s\S]?$)/g, '%25'); // encode all not correct URI encoded strings like %%1%g1

      var lc = url.toLowerCase();
      // if URL starts not from http, mailto, ftp and #hash, ?search, //UNC, /root, ../relative and have scheme:
      if (!/^(?:http|mailto|ftp|[#\/.?])/.test(lc) && /^[^?\/#:]+?:/.test(lc)) {
        // if URL starts from wrong scheme or have encoded entity
        if (/^(?:about|cdl|dvd|local|mhtml|mk|ms-help|ms-its|tv|res|its|javascript|data|vbs|vbscript|feed|java|jar|file|[a-z]):/.test(lc) || !/^[a-z0-1\-_.]+?:/.test(lc)) {
          url = './' + url;
        }
      }

      return url;
    };
  }());

  // http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Functions:encodeURIComponent
  // compatible with OAuth signature calculation
  var localEncodeURIComponent = function() {
    return encodeURIComponent.apply(this, arguments).replace(/[!'()]/g, escape).replace(/\*/g, '%2A');
  };

  filters = {
    temp: function(value) { return value; },
    h: function(value) { return escapeHTML(value); },
    j: function(value) { return escapeJs(value); },
    url: function(value) { return sanitizeURL(value); },
    uc: function(value) { return localEncodeURIComponent(value); },
    js: function(value) { return customJsonStringify(value); }
  };

  /* Be nice if filters is already defined, but not too nice ... clobber over what there */
  if (dust.filters){
    for (var filterName in filters){
      if (filters.hasOwnProperty(filterName)){
        dust.filters[filterName] = filters[filterName];
      }
    }
  } else {
    dust.filters = filters;
  }

  /* We are writing to the `dust` object so we don't need to return anything */
}));
<|endoftext|>


<commit_before>(function () {
    // Object.assign polyfill from https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Polyfill
    Object.assign||Object.defineProperty(Object,"assign",{enumerable:!1,configurable:!0,writable:!0,value:function(e){"use strict";if(void 0===e||null===e)throw new TypeError("Cannot convert first argument to object");for(var r=Object(e),t=1;t<arguments.length;t++){var n=arguments[t];if(void 0!==n&&null!==n){n=Object(n);for(var o=Object.keys(Object(n)),a=0,c=o.length;c>a;a++){var i=o[a],b=Object.getOwnPropertyDescriptor(n,i);void 0!==b&&b.enumerable&&(r[i]=n[i])}}}return r}});

    var sixpack = {
        base_url: "http://localhost:5000",
        ip_address: null,
        user_agent: null,
        timeout: 1000,
        persist: true
    };

    // check for node module loader
    var on_node = false;
    if (typeof module !== "undefined" && typeof require !== "undefined") {
        on_node = true;
        module.exports = sixpack;
    } else {
        window["sixpack"] = sixpack;
    }

    sixpack.generate_client_id = function () {
        // from http://stackoverflow.com/questions/105034
        var client_id = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
            var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
            return v.toString(16);
        });
        if (!on_node && this.persist) {
            document.cookie = "sixpack_client_id=" + client_id + "; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/";
        }
        return client_id;
    };

    sixpack.persisted_client_id = function() {
        // http://stackoverflow.com/questions/5639346/shortest-function-for-reading-a-cookie-in-javascript
        var result;
        return (result = new RegExp('(?:^|; )' + encodeURIComponent('sixpack_client_id') + '=([^;]*)').exec(document.cookie)) ? (result[1]) : null;
    }

    sixpack.Session = function (options) {
        Object.assign(this, sixpack, options);

        if (!this.client_id) {
            if (this.persist && !on_node) {
                this.client_id = this.persisted_client_id() || this.generate_client_id();
            } else {
                this.client_id = this.generate_client_id();
            }
        }
        if (!on_node) {
            this.user_agent = this.user_agent || (window && window.navigator && window.navigator.userAgent);
        }
    };

    sixpack.Session.prototype = {
        participate: function(experiment_name, alternatives, traffic_fraction, force, callback) {
            if (typeof traffic_fraction === "function") {
                callback = traffic_fraction;
                traffic_fraction = null;
                force = null;
            }
            else if (typeof traffic_fraction === "string") {
                callback = force;
                force = traffic_fraction;
                traffic_fraction = null;
            }
            if (typeof force === "function") {
                callback = force;
                force = null;
            }

            if (!(/^[a-z0-9][a-z0-9\-_ ]*$/).test(experiment_name)) {
                return callback(new Error("Bad experiment_name"));
            }

            if (alternatives.length < 2) {
                return callback(new Error("Must specify at least 2 alternatives"));
            }

            for (var i = 0; i < alternatives.length; i += 1) {
                if (!(/^[a-z0-9][a-z0-9\-_ ]*$/).test(alternatives[i])) {
                    return callback(new Error("Bad alternative name: " + alternatives[i]));
                }
            }
            var params = {client_id: this.client_id,
                          experiment: experiment_name,
                          alternatives: alternatives};
            if (!on_node && force == null) {
                var regex = new RegExp("[\\?&]sixpack-force-" + experiment_name + "=([^&#]*)");
                var results = regex.exec(window.location.search);
                if(results != null) {
                    force = decodeURIComponent(results[1].replace(/\+/g, " "));
                }
            }
            if (traffic_fraction !== null && !isNaN(traffic_fraction)) {
                params.traffic_fraction = traffic_fraction;
            }
            if (force != null && _in_array(alternatives, force)) {
                return callback(null, {"status": "ok", "alternative": {"name": force}, "experiment": {"version": 0, "name": experiment_name}, "client_id": this.client_id});
            }
            if (this.ip_address) {
                params.ip_address = this.ip_address;
            }
            if (this.user_agent) {
                params.user_agent = this.user_agent;
            }
            return _request(this.base_url + "/participate", params, this.timeout, function(err, res) {
                if (err) {
                    res = {status: "failed",
                           error: err,
                           alternative: {name: alternatives[0]}};
                }
                return callback(null, res);
            });
        },
        convert: function(experiment_name, kpi, callback) {
            if (typeof kpi === 'function') {
                callback = kpi;
                kpi = null;
            }
            if (!(/^[a-z0-9][a-z0-9\-_ ]*$/).test(experiment_name)) {
                return callback(new Error("Bad experiment_name"));
            }

            var params = {client_id: this.client_id,
                          experiment: experiment_name};
            if (this.ip_address) {
                params.ip_address = this.ip_address;
            }
            if (this.user_agent) {
                params.user_agent = this.user_agent;
            }
            if (kpi) {
                params.kpi = kpi;
            }
            return _request(this.base_url + "/convert", params, this.timeout, function(err, res) {
                if (err) {
                    res = {status: "failed",
                           error: err};
                }
                return callback(null, res);
            });
        }
    };

    var counter = 0;

    var _request = function(uri, params, timeout, callback) {
        var timed_out = false;
        var timeout_handle = setTimeout(function () {
            timed_out = true;
            return callback(new Error("request timed out"));
        }, timeout);

        if (!on_node) {
            var cb = "callback" + (++counter);
            params.callback = "sixpack." + cb
            sixpack[cb] = function (res) {
                if (!timed_out) {
                    clearTimeout(timeout_handle);
                    return callback(null, res);
                }
            }
        }
        var url = _request_uri(uri, params);
        if (!on_node) {
            script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = url;
            script.async = true;
            document.body.appendChild(script);
        } else {
            var http = require('http');
            var req = http.get(url, function(res) {
                var body = "";
                res.on('data', function(chunk) {
                    return body += chunk;
                });
                return res.on('end', function() {
                    var data;
                    if (res.statusCode == 500) {
                        data = {status: "failed", response: body};
                    } else {
                        data = JSON.parse(body);
                    }
                    if (!timed_out) {
                        clearTimeout(timeout_handle);
                        return callback(null, data);
                    }
                });
            });
            req.on('error', function(err) {
                if (!timed_out) {
                    clearTimeout(timeout_handle);
                    return callback(err);
                }
            });
        }
    };

    var _request_uri = function(endpoint, params) {
        var query_string = [];
        var e = encodeURIComponent;
        for (var key in params) {
            if (params.hasOwnProperty(key)) {
                var vals = params[key];
                if (Object.prototype.toString.call(vals) !== '[object Array]') {
                    vals = [vals];
                }
                for (var i = 0; i < vals.length; i += 1) {
                    query_string.push(e(key) + '=' + e(vals[i]));
                }
            }
        }
        if (query_string.length) {
            endpoint += '?' + query_string.join('&');
        }
        return endpoint;
    };

    var _in_array = function(a, v) {
        for(var i = 0; i < a.length; i++) {
            if(a[i] === v) {
                return true;
            }
        }
        return false;
    };
})();
<commit_msg>Use ternary expression instead of short-circuit.<commit_after>(function () {
    // Object.assign polyfill from https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Polyfill
    Object.assign||Object.defineProperty(Object,"assign",{enumerable:!1,configurable:!0,writable:!0,value:function(e){"use strict";if(void 0===e||null===e)throw new TypeError("Cannot convert first argument to object");for(var r=Object(e),t=1;t<arguments.length;t++){var n=arguments[t];if(void 0!==n&&null!==n){n=Object(n);for(var o=Object.keys(Object(n)),a=0,c=o.length;c>a;a++){var i=o[a],b=Object.getOwnPropertyDescriptor(n,i);void 0!==b&&b.enumerable&&(r[i]=n[i])}}}return r}});

    var sixpack = {
        base_url: "http://localhost:5000",
        ip_address: null,
        user_agent: null,
        timeout: 1000,
        persist: true
    };

    // check for node module loader
    var on_node = false;
    if (typeof module !== "undefined" && typeof require !== "undefined") {
        on_node = true;
        module.exports = sixpack;
    } else {
        window["sixpack"] = sixpack;
    }

    sixpack.generate_client_id = function () {
        // from http://stackoverflow.com/questions/105034
        var client_id = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
            var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
            return v.toString(16);
        });
        if (!on_node && this.persist) {
            document.cookie = "sixpack_client_id=" + client_id + "; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/";
        }
        return client_id;
    };

    sixpack.persisted_client_id = function() {
        // http://stackoverflow.com/questions/5639346/shortest-function-for-reading-a-cookie-in-javascript
        var result;
        return (result = new RegExp('(?:^|; )' + encodeURIComponent('sixpack_client_id') + '=([^;]*)').exec(document.cookie)) ? (result[1]) : null;
    }

    sixpack.Session = function (options) {
        Object.assign(this, sixpack, options);

        if (!this.client_id) {
            if (this.persist && !on_node) {
                var persisted_id = this.persisted_client_id();
                this.client_id = persisted_id !== null ? persisted_id : this.generate_client_id();
            } else {
                this.client_id = this.generate_client_id();
            }
        }
        if (!on_node) {
            this.user_agent = this.user_agent || (window && window.navigator && window.navigator.userAgent);
        }
    };

    sixpack.Session.prototype = {
        participate: function(experiment_name, alternatives, traffic_fraction, force, callback) {
            if (typeof traffic_fraction === "function") {
                callback = traffic_fraction;
                traffic_fraction = null;
                force = null;
            }
            else if (typeof traffic_fraction === "string") {
                callback = force;
                force = traffic_fraction;
                traffic_fraction = null;
            }
            if (typeof force === "function") {
                callback = force;
                force = null;
            }

            if (!(/^[a-z0-9][a-z0-9\-_ ]*$/).test(experiment_name)) {
                return callback(new Error("Bad experiment_name"));
            }

            if (alternatives.length < 2) {
                return callback(new Error("Must specify at least 2 alternatives"));
            }

            for (var i = 0; i < alternatives.length; i += 1) {
                if (!(/^[a-z0-9][a-z0-9\-_ ]*$/).test(alternatives[i])) {
                    return callback(new Error("Bad alternative name: " + alternatives[i]));
                }
            }
            var params = {client_id: this.client_id,
                          experiment: experiment_name,
                          alternatives: alternatives};
            if (!on_node && force == null) {
                var regex = new RegExp("[\\?&]sixpack-force-" + experiment_name + "=([^&#]*)");
                var results = regex.exec(window.location.search);
                if(results != null) {
                    force = decodeURIComponent(results[1].replace(/\+/g, " "));
                }
            }
            if (traffic_fraction !== null && !isNaN(traffic_fraction)) {
                params.traffic_fraction = traffic_fraction;
            }
            if (force != null && _in_array(alternatives, force)) {
                return callback(null, {"status": "ok", "alternative": {"name": force}, "experiment": {"version": 0, "name": experiment_name}, "client_id": this.client_id});
            }
            if (this.ip_address) {
                params.ip_address = this.ip_address;
            }
            if (this.user_agent) {
                params.user_agent = this.user_agent;
            }
            return _request(this.base_url + "/participate", params, this.timeout, function(err, res) {
                if (err) {
                    res = {status: "failed",
                           error: err,
                           alternative: {name: alternatives[0]}};
                }
                return callback(null, res);
            });
        },
        convert: function(experiment_name, kpi, callback) {
            if (typeof kpi === 'function') {
                callback = kpi;
                kpi = null;
            }
            if (!(/^[a-z0-9][a-z0-9\-_ ]*$/).test(experiment_name)) {
                return callback(new Error("Bad experiment_name"));
            }

            var params = {client_id: this.client_id,
                          experiment: experiment_name};
            if (this.ip_address) {
                params.ip_address = this.ip_address;
            }
            if (this.user_agent) {
                params.user_agent = this.user_agent;
            }
            if (kpi) {
                params.kpi = kpi;
            }
            return _request(this.base_url + "/convert", params, this.timeout, function(err, res) {
                if (err) {
                    res = {status: "failed",
                           error: err};
                }
                return callback(null, res);
            });
        }
    };

    var counter = 0;

    var _request = function(uri, params, timeout, callback) {
        var timed_out = false;
        var timeout_handle = setTimeout(function () {
            timed_out = true;
            return callback(new Error("request timed out"));
        }, timeout);

        if (!on_node) {
            var cb = "callback" + (++counter);
            params.callback = "sixpack." + cb
            sixpack[cb] = function (res) {
                if (!timed_out) {
                    clearTimeout(timeout_handle);
                    return callback(null, res);
                }
            }
        }
        var url = _request_uri(uri, params);
        if (!on_node) {
            script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = url;
            script.async = true;
            document.body.appendChild(script);
        } else {
            var http = require('http');
            var req = http.get(url, function(res) {
                var body = "";
                res.on('data', function(chunk) {
                    return body += chunk;
                });
                return res.on('end', function() {
                    var data;
                    if (res.statusCode == 500) {
                        data = {status: "failed", response: body};
                    } else {
                        data = JSON.parse(body);
                    }
                    if (!timed_out) {
                        clearTimeout(timeout_handle);
                        return callback(null, data);
                    }
                });
            });
            req.on('error', function(err) {
                if (!timed_out) {
                    clearTimeout(timeout_handle);
                    return callback(err);
                }
            });
        }
    };

    var _request_uri = function(endpoint, params) {
        var query_string = [];
        var e = encodeURIComponent;
        for (var key in params) {
            if (params.hasOwnProperty(key)) {
                var vals = params[key];
                if (Object.prototype.toString.call(vals) !== '[object Array]') {
                    vals = [vals];
                }
                for (var i = 0; i < vals.length; i += 1) {
                    query_string.push(e(key) + '=' + e(vals[i]));
                }
            }
        }
        if (query_string.length) {
            endpoint += '?' + query_string.join('&');
        }
        return endpoint;
    };

    var _in_array = function(a, v) {
        for(var i = 0; i < a.length; i++) {
            if(a[i] === v) {
                return true;
            }
        }
        return false;
    };
})();
<|endoftext|>


<commit_before>const elasticsearch = require('elasticsearch');
const esConfig = require('../../config/config').es;

const client = elasticsearch.Client({ host: `${esConfig.host}:${esConfig.port}` });
function getByIdQuery(id) {
  return {
    index: esConfig.index,
    type: 'gps',
    id,
  };
}

function notFound(error) {
  return error.message === 'Not Found';
}

function getGp(id) {
  return new Promise((resolve, reject) => {
    client.get(getByIdQuery(id), (error, result) => {
      if (!error) {
        // eslint-disable-next-line no-underscore-dangle
        resolve(result._source);
      } else {
        // eslint-disable-next-line no-unused-expressions
        notFound(error) ? resolve(undefined) : reject(error);
      }
    });
  });
}

function getHealth() {
  return new Promise((resolve, reject) => {
    client.cat.health({ format: 'json' }, (error, result) => {
      if (!error) {
        resolve(result);
      } else {
        reject(error);
      }
    });
  });
}

module.exports = {
  getGp,
  getHealth,
};
<commit_msg>:simple_smile: simplify esClient implementation<commit_after>const elasticsearch = require('elasticsearch');
const esConfig = require('../../config/config').es;

const client = elasticsearch.Client({ host: `${esConfig.host}:${esConfig.port}` });
function getByIdQuery(id) {
  return {
    index: esConfig.index,
    type: 'gps',
    id,
  };
}

function notFound(error) {
  return error.message === 'Not Found';
}

async function getGp(id) {
  try {
    const result = await client.get(getByIdQuery(id));
    // eslint-disable-next-line no-underscore-dangle
    return result._source;
  } catch (error) {
    if (notFound(error)) {
      return undefined;
    }
    throw error;
  }
}

function getHealth() {
  return client.cat.health({ format: 'json' });
}

module.exports = {
  getGp,
  getHealth,
};
<|endoftext|>


<commit_before>import React from 'react'

function Index(props) {
  return (

Cerebral

          {
            props.compile(`
> Declarative **state and side effects management** for popular JavaScript frameworks
`).tree
          }

              introduction

              api

              {
                props.compile(`
Writing **declaratively**:

\`\`\`js

Hello

\`\`\`
`).tree
              }

              {
                props.compile(`
Compared to **imperatively**:

\`\`\`js
const h1 = document.createElement('h1')
h1.className = 'header'
document.body.appendChild(h1)
\`\`\`
`).tree
              }

          {
            props.compile(`
It makes perfect sense for us to write our UIs in a declarative manner. The reason is that we need to reuse UI elements and compose them together in different configurations. One can also claim that declarative code reads better, not because it is less syntax, but because you only describe **what** you want, not **how** you want it.

But what about our business logic, can we get the same benefits there?

`).tree
          }

              {
                props.compile(`
Writing **declaratively**:

\`\`\`js
[
  set(state\`user.isLoading\`, true),
  httpGet('/user'), {
    success: set(state\`user.data\`, props\`user\`),
    error: set(state\`user.error\`, props\`error\`)
  },
  set(state\`user.isLoading\`, false),
]
\`\`\`
        `).tree
              }

              {
                props.compile(`
Compared to **imperatively**:

\`\`\`js
function getUser() {
  this.isLoading = true
  ajax.get('/user')
    .then((user) => {
      this.data = user
      this.isLoading = false
    })
    .catch((error) => {
      this.error = error
      this.isLoading = false
    })
}
\`\`\`
        `).tree
              }

          {
            props.compile(`
You might think this example tries to highlight "less lines of code", but it is actually about reaching for these properties:

- **Composability**
- **Readability**
- **Reusability**
- **Testability**

All these properties makes **better code** and **scalable code**. The declarative approach inherits all of these properties by default. In addition to this
it allows us to build developer tools:

![debugger](/images/debugger.gif)

> *Read on to learn more about how Cerebral enforces scalable code and gives you insight into the inner workings of your app*
`).tree
          }

              introduction

              api

            Released under the MIT License
            Copyright © 2017 Christian Alfoni

  )
}

export default Index
<commit_msg>docs(website): change declarative example to not use tags, confusing first impression<commit_after>import React from 'react'

function Index(props) {
  return (

Cerebral

          {
            props.compile(`
> Declarative **state and side effects management** for popular JavaScript frameworks
`).tree
          }

              introduction

              api

              {
                props.compile(`
Writing **declaratively**:

\`\`\`js

Hello

\`\`\`
`).tree
              }

              {
                props.compile(`
Compared to **imperatively**:

\`\`\`js
const h1 = document.createElement('h1')
h1.className = 'header'
document.body.appendChild(h1)
\`\`\`
`).tree
              }

          {
            props.compile(`
It makes perfect sense for us to write our UIs in a declarative manner. The reason is that we need to reuse UI elements and compose them together in different configurations. One can also claim that declarative code reads better, not because it is less syntax, but because you only describe **what** you want, not **how** you want it.

But what about our business logic, can we get the same benefits there?

`).tree
          }

              {
                props.compile(`
Writing **declaratively**:

\`\`\`js
[
  setLoading(true),
  getUser, {
    success: setUser,
    error: setError
  },
  setLoading(false),
]
\`\`\`
        `).tree
              }

              {
                props.compile(`
Compared to **imperatively**:

\`\`\`js
function getUser() {
  this.isLoading = true
  ajax.get('/user')
    .then((user) => {
      this.data = user
      this.isLoading = false
    })
    .catch((error) => {
      this.error = error
      this.isLoading = false
    })
}
\`\`\`
        `).tree
              }

          {
            props.compile(`
You might think this example tries to highlight "less lines of code", but it is actually about reaching for these properties:

- **Composability**
- **Readability**
- **Reusability**
- **Testability**

All these properties makes **better code** and **scalable code**. The declarative approach inherits all of these properties by default. In addition to this
it allows us to build developer tools:

![debugger](/images/debugger.gif)

> *Read on to learn more about how Cerebral enforces scalable code and gives you insight into the inner workings of your app*
`).tree
          }

              introduction

              api

            Released under the MIT License
            Copyright © 2017 Christian Alfoni

  )
}

export default Index
<|endoftext|>


<commit_before>QUnit.test("DoesntCollide", function(assert) {
    var triangle1 = new TameGame.Polygon([ { x:1, y:1 }, { x:2, y:2 }, { x:1, y:2 }]);
    var triangle2 = new TameGame.Polygon([ { x:4, y:4 }, { x:5, y:5 }, { x:4, y:5 }]);

    var collides = TameGame.satCollision(triangle1, triangle2);

    assert.ok(collides.collided === false);
});

QUnit.test("DoesntCollideCircle", function(assert) {
    var triangle1 = new TameGame.Polygon([ { x:1, y:1 }, { x:2, y:2 }, { x:1, y:2 }]);
    var circle2 = new TameGame.Circle({ x: 4.5, y: 4.5 }, 1);

    var collides = TameGame.satCollision(triangle1, circle2);

    assert.ok(collides.collided === false);
});

QUnit.test("DoesCollideWhenOnTopOfEachOther", function(assert) {
    var triangle1 = new TameGame.Polygon([ { x:1, y:1 }, { x:2, y:2 }, { x:1, y:2 }]);
    var triangle2 = new TameGame.Polygon([ { x:1, y:1 }, { x:2, y:2 }, { x:1, y:2 }]);

    var collides = TameGame.satCollision(triangle1, triangle2);

    assert.ok(collides.collided === true);
});

QUnit.test("DoesCollideWhenOnTopOfEachOtherCircle", function(assert) {
    var triangle1 = new TameGame.Polygon([ { x:1, y:1 }, { x:2, y:2 }, { x:1, y:2 }]);
    var circle2 = new TameGame.Circle({ x: 1.5, y: 1.5 }, 1);

    var collides = TameGame.satCollision(triangle1, circle2);

    assert.ok(collides.collided === true);
});

QUnit.test("DoesCollideSmallIntersection", function(assert) {
    var triangle1 = new TameGame.Polygon([ { x:1, y:1 }, { x:2, y:2 }, { x:1, y:2 }]);
    var triangle2 = new TameGame.Polygon([ { x:1.8, y:1.8 }, { x:2.8, y:2.8 }, { x:1.8, y:2.8 }]);

    var collides = TameGame.satCollision(triangle1, triangle2);

    assert.ok(collides.collided === true);
});

QUnit.test("DoesntCollideAfterTranslation", function(assert) {
    var triangle1 = new TameGame.Polygon([ { x:1, y:1 }, { x:2, y:2 }, { x:1, y:2 }]);
    var triangle2 = triangle1.transform(TameGame.translateMatrix({ x:3, y:3 }));

    var collides1 = TameGame.satCollision(triangle1, triangle2);
    var collides2 = TameGame.satCollision(triangle2, triangle1);

    assert.ok(collides1.collided === false);
    assert.ok(collides2.collided === false);
});

QUnit.test("DoesCollideAfterTranslation", function(assert) {
    var triangle1 = new TameGame.Polygon([ { x:1, y:1 }, { x:2, y:2 }, { x:1, y:2 }]);
    var triangle2 = triangle1.transform(TameGame.translateMatrix({ x:.5, y:.5 }));

    var collides1 = TameGame.satCollision(triangle1, triangle2);
    var collides2 = TameGame.satCollision(triangle2, triangle1);

    assert.ok(collides1.collided === true);
    assert.ok(collides2.collided === true);
});

QUnit.test("DoesNotCollideAfterMtv", function(assert) {
    var triangle1 = new TameGame.Polygon([ { x:1, y:1 }, { x:2, y:2 }, { x:1, y:2 }]);
    var triangle2 = triangle1.transform(TameGame.translateMatrix({ x:.5, y:.5 }));

    var collides1 = TameGame.satCollision(triangle2, triangle1);

    assert.ok(collides1.collided === true, 'Triangles are initially in collision');

    var triangle3 = triangle2.transform(TameGame.translateMatrix(collides1.getMtv()));
    var collides2 = TameGame.satCollision(triangle1, triangle3);

    if (collides2.collided) {
        console.log(triangle3.getVertices());
        console.log(collides1.getMtv());
        console.log(collides2.getMtv());
    }

    assert.ok(collides2.collided === false, 'Triangles are not in collision after translating along the MTV');
});

QUnit.test("DoesCollideJustInsideMtv", function(assert) {
    var triangle1 = new TameGame.Polygon([ { x:1, y:1 }, { x:2, y:2 }, { x:1, y:2 }]);
    var triangle2 = triangle1.transform(TameGame.translateMatrix({ x:.5, y:.5 }));

    var collides1 = TameGame.satCollision(triangle1, triangle2);

    assert.ok(collides1.collided === true, 'Triangles are initially in collision');

    var mtv = collides1.getMtv();
    var slightlyBackwards = { x: -mtv.x*0.0000001, y: -mtv.y*0.0000001 };
    var triangle3 = triangle2.transform(TameGame.multiplyMatrix(TameGame.translateMatrix(mtv), TameGame.translateMatrix(slightlyBackwards)));

    var collides2 = TameGame.satCollision(triangle1, triangle3);

    assert.ok(collides2.collided === true, 'Triangles are in collision slightly inside the MTV');
});

QUnit.test("AabbCollisionDuringPass", function (assert) {
    var someGame = new TameGame.StandardGame();
    var someScene = someGame.createScene();

    // Create two objects and move them into collision by changing their presence
    var objPos = { quad: { x1: -1, y1: -1, x2: 1, y2: -1, x3: 1, y3: 1, x4: -1, y4: 1 } };

    var obj1 = someGame.createObject();
    var obj2 = someGame.createObject();

    someScene.addObject(obj1);
    someScene.addObject(obj2);
    someGame.startScene(someScene);

    obj1.position = objPos;
    obj2.position = objPos;

    obj1.presence.location = { x: .5, y: .5 };
    obj2.presence.location = { x: -.5, y: -.5 };

    // Count the number of collisions
    var collideCount1 = 0;
    var collideCount2 = 0;
    obj1.behavior.aabbCollision = function () { ++collideCount1; };
    obj2.behavior.aabbCollision = function () { ++collideCount2; };

    // Run the pass
    someGame.tick(0);

    if (collideCount1 !== 1) {
        console.log('1 !==', collideCount1);
    }
    if (collideCount2 !== 1) {
        console.log('1 !==', collideCount2);
    }

    assert.ok(collideCount1 === 1, "Caused a single AABB collision on first object");
    assert.ok(collideCount2 === 1, "Caused a single AABB collision on second object");

    someGame.tick(1);               // Nothing moves, so no more collisions

    assert.ok(collideCount1 === 1 && collideCount2 === 1, "Collisions don't reoccur");
});

QUnit.test("NoCollisionIfNotOverlapping", function (assert) {
    var someGame = new TameGame.StandardGame();
    var someScene = someGame.createScene();

    // Create two objects and move them into collision by changing their presence
    var objPos = { quad: { x1: -1, y1: -1, x2: 1, y2: -1, x3: 1, y3: 1, x4: -1, y4: 1 } };

    var obj1 = someGame.createObject();
    var obj2 = someGame.createObject();

    someScene.addObject(obj1);
    someScene.addObject(obj2);
    someGame.startScene(someScene);

    obj1.position = objPos;
    obj2.position = objPos;

    obj1.presence.location = { x: 2, y: 2 };
    obj2.presence.location = { x: -2, y: -2 };

    // Count the number of collisions
    var collideCount1 = 0;
    var collideCount2 = 0;
    obj1.behavior.aabbCollision = function () { ++collideCount1; };
    obj2.behavior.aabbCollision = function () { ++collideCount2; };

    // Run the pass
    someGame.tick(0);
    someGame.tick(1);               // Nothing moves, so no more collisions

    if (collideCount1 !== 0) {
        console.log('0 !==', collideCount1);
    }
    if (collideCount2 !== 0) {
        console.log('0 !==', collideCount2);
    }

    assert.ok(collideCount1 === 0, "No collisions on first object");
    assert.ok(collideCount2 === 0, "No collisions on second object");
});
<commit_msg>Add some more tests for colliding with circles<commit_after>QUnit.test("DoesntCollide", function(assert) {
    var triangle1 = new TameGame.Polygon([ { x:1, y:1 }, { x:2, y:2 }, { x:1, y:2 }]);
    var triangle2 = new TameGame.Polygon([ { x:4, y:4 }, { x:5, y:5 }, { x:4, y:5 }]);

    var collides = TameGame.satCollision(triangle1, triangle2);

    assert.ok(collides.collided === false);
});

QUnit.test("DoesntCollideCircle", function(assert) {
    var triangle1 = new TameGame.Polygon([ { x:1, y:1 }, { x:2, y:2 }, { x:1, y:2 }]);
    var circle2 = new TameGame.Circle({ x: 4.5, y: 4.5 }, 1);

    var collides = TameGame.satCollision(triangle1, circle2);

    assert.ok(collides.collided === false);
});

QUnit.test("DoesntCollideTwoCircle", function(assert) {
    var circle1 = new TameGame.Circle({ x: 1.5, y: 1.5 }, 1);
    var circle2 = new TameGame.Circle({ x: 4.5, y: 4.5 }, 1);

    var collides = TameGame.satCollision(circle1, circle2);

    assert.ok(collides.collided === false);
});

QUnit.test("DoesCollideWhenOnTopOfEachOther", function(assert) {
    var triangle1 = new TameGame.Polygon([ { x:1, y:1 }, { x:2, y:2 }, { x:1, y:2 }]);
    var triangle2 = new TameGame.Polygon([ { x:1, y:1 }, { x:2, y:2 }, { x:1, y:2 }]);

    var collides = TameGame.satCollision(triangle1, triangle2);

    assert.ok(collides.collided === true);
});

QUnit.test("DoesCollideWhenOnTopOfEachOtherCircle", function(assert) {
    var triangle1 = new TameGame.Polygon([ { x:1, y:1 }, { x:2, y:2 }, { x:1, y:2 }]);
    var circle2 = new TameGame.Circle({ x: 1.5, y: 1.5 }, 1);

    var collides = TameGame.satCollision(triangle1, circle2);

    assert.ok(collides.collided === true);
});

QUnit.test("DoesCollideWhenOnTopOfEachOtherTwoCircle", function(assert) {
    var circle1 = new TameGame.Circle({ x: 1.5, y: 1.5 }, 1);;
    var circle2 = new TameGame.Circle({ x: 1.5, y: 1.5 }, 1);

    var collides = TameGame.satCollision(circle1, circle2);

    assert.ok(collides.collided === true);
});

QUnit.test("DoesntCollideWhenOnTopOfEachOtherTouchingCircle", function(assert) {
    var circle1 = new TameGame.Circle({ x: 1.5, y: 1.5 }, 1);;
    var circle2 = new TameGame.Circle({ x: 2.5, y: 1.5 }, 1);

    var collides = TameGame.satCollision(circle1, circle2);

    assert.ok(collides.collided === false);
});

QUnit.test("DoesCollideSmallIntersection", function(assert) {
    var triangle1 = new TameGame.Polygon([ { x:1, y:1 }, { x:2, y:2 }, { x:1, y:2 }]);
    var triangle2 = new TameGame.Polygon([ { x:1.8, y:1.8 }, { x:2.8, y:2.8 }, { x:1.8, y:2.8 }]);

    var collides = TameGame.satCollision(triangle1, triangle2);

    assert.ok(collides.collided === true);
});

QUnit.test("DoesCollideSmallIntersectionCircle", function(assert) {
    var triangle1 = new TameGame.Polygon([ { x:1, y:1 }, { x:2, y:2 }, { x:1, y:2 }]);
    var circle2 = new TameGame.Circle({ x:1.8, y:1.8 }, 1);

    var collides = TameGame.satCollision(triangle1, circle2);

    assert.ok(collides.collided === true);
});

QUnit.test("DoesntCollideAfterTranslation", function(assert) {
    var triangle1 = new TameGame.Polygon([ { x:1, y:1 }, { x:2, y:2 }, { x:1, y:2 }]);
    var triangle2 = triangle1.transform(TameGame.translateMatrix({ x:3, y:3 }));

    var collides1 = TameGame.satCollision(triangle1, triangle2);
    var collides2 = TameGame.satCollision(triangle2, triangle1);

    assert.ok(collides1.collided === false);
    assert.ok(collides2.collided === false);
});

QUnit.test("DoesCollideAfterTranslation", function(assert) {
    var triangle1 = new TameGame.Polygon([ { x:1, y:1 }, { x:2, y:2 }, { x:1, y:2 }]);
    var triangle2 = triangle1.transform(TameGame.translateMatrix({ x:.5, y:.5 }));

    var collides1 = TameGame.satCollision(triangle1, triangle2);
    var collides2 = TameGame.satCollision(triangle2, triangle1);

    assert.ok(collides1.collided === true);
    assert.ok(collides2.collided === true);
});

QUnit.test("DoesNotCollideAfterMtv", function(assert) {
    var triangle1 = new TameGame.Polygon([ { x:1, y:1 }, { x:2, y:2 }, { x:1, y:2 }]);
    var triangle2 = triangle1.transform(TameGame.translateMatrix({ x:.5, y:.5 }));

    var collides1 = TameGame.satCollision(triangle2, triangle1);

    assert.ok(collides1.collided === true, 'Triangles are initially in collision');

    var triangle3 = triangle2.transform(TameGame.translateMatrix(collides1.getMtv()));
    var collides2 = TameGame.satCollision(triangle1, triangle3);

    if (collides2.collided) {
        console.log(triangle3.getVertices());
        console.log(collides1.getMtv());
        console.log(collides2.getMtv());
    }

    assert.ok(collides2.collided === false, 'Triangles are not in collision after translating along the MTV');
});

QUnit.test("DoesCollideJustInsideMtv", function(assert) {
    var triangle1 = new TameGame.Polygon([ { x:1, y:1 }, { x:2, y:2 }, { x:1, y:2 }]);
    var triangle2 = triangle1.transform(TameGame.translateMatrix({ x:.5, y:.5 }));

    var collides1 = TameGame.satCollision(triangle1, triangle2);

    assert.ok(collides1.collided === true, 'Triangles are initially in collision');

    var mtv = collides1.getMtv();
    var slightlyBackwards = { x: -mtv.x*0.0000001, y: -mtv.y*0.0000001 };
    var triangle3 = triangle2.transform(TameGame.multiplyMatrix(TameGame.translateMatrix(mtv), TameGame.translateMatrix(slightlyBackwards)));

    var collides2 = TameGame.satCollision(triangle1, triangle3);

    assert.ok(collides2.collided === true, 'Triangles are in collision slightly inside the MTV');
});

QUnit.test("AabbCollisionDuringPass", function (assert) {
    var someGame = new TameGame.StandardGame();
    var someScene = someGame.createScene();

    // Create two objects and move them into collision by changing their presence
    var objPos = { quad: { x1: -1, y1: -1, x2: 1, y2: -1, x3: 1, y3: 1, x4: -1, y4: 1 } };

    var obj1 = someGame.createObject();
    var obj2 = someGame.createObject();

    someScene.addObject(obj1);
    someScene.addObject(obj2);
    someGame.startScene(someScene);

    obj1.position = objPos;
    obj2.position = objPos;

    obj1.presence.location = { x: .5, y: .5 };
    obj2.presence.location = { x: -.5, y: -.5 };

    // Count the number of collisions
    var collideCount1 = 0;
    var collideCount2 = 0;
    obj1.behavior.aabbCollision = function () { ++collideCount1; };
    obj2.behavior.aabbCollision = function () { ++collideCount2; };

    // Run the pass
    someGame.tick(0);

    if (collideCount1 !== 1) {
        console.log('1 !==', collideCount1);
    }
    if (collideCount2 !== 1) {
        console.log('1 !==', collideCount2);
    }

    assert.ok(collideCount1 === 1, "Caused a single AABB collision on first object");
    assert.ok(collideCount2 === 1, "Caused a single AABB collision on second object");

    someGame.tick(1);               // Nothing moves, so no more collisions

    assert.ok(collideCount1 === 1 && collideCount2 === 1, "Collisions don't reoccur");
});

QUnit.test("NoCollisionIfNotOverlapping", function (assert) {
    var someGame = new TameGame.StandardGame();
    var someScene = someGame.createScene();

    // Create two objects and move them into collision by changing their presence
    var objPos = { quad: { x1: -1, y1: -1, x2: 1, y2: -1, x3: 1, y3: 1, x4: -1, y4: 1 } };

    var obj1 = someGame.createObject();
    var obj2 = someGame.createObject();

    someScene.addObject(obj1);
    someScene.addObject(obj2);
    someGame.startScene(someScene);

    obj1.position = objPos;
    obj2.position = objPos;

    obj1.presence.location = { x: 2, y: 2 };
    obj2.presence.location = { x: -2, y: -2 };

    // Count the number of collisions
    var collideCount1 = 0;
    var collideCount2 = 0;
    obj1.behavior.aabbCollision = function () { ++collideCount1; };
    obj2.behavior.aabbCollision = function () { ++collideCount2; };

    // Run the pass
    someGame.tick(0);
    someGame.tick(1);               // Nothing moves, so no more collisions

    if (collideCount1 !== 0) {
        console.log('0 !==', collideCount1);
    }
    if (collideCount2 !== 0) {
        console.log('0 !==', collideCount2);
    }

    assert.ok(collideCount1 === 0, "No collisions on first object");
    assert.ok(collideCount2 === 0, "No collisions on second object");
});
<|endoftext|>