code
stringlengths 2
1.05M
|
---|
/**
* The MIT License (MIT)
*
* Copyright (c) 2015 Mickael Jeanroy
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
describe('Grid', () => {
let jq, oldDocumentMode;
beforeEach(() => {
jq = $.fn || $.prototype;
// Spy ie version
oldDocumentMode = document.documentMode;
document.documentMode = undefined;
});
afterEach(() => document.documentMode = oldDocumentMode);
it('should define custom options', () => {
expect(Grid.options).toEqual(jasmine.objectContaining({
columns: null,
data: null,
sortBy: null,
async: false,
scrollable: false,
sortable: true,
dnd: false,
editable: false,
selection: {
enable: true,
checkbox: true,
multi: false
},
view: {
thead: true,
tfoot: false
},
size: {
width: null,
height: null
},
events: {
onInitialized: null,
onUpdated: null,
onRendered: null,
onDataSpliced: null,
onDataUpdated: null,
onDataChanged: null,
onColumnsSpliced: null,
onColumnsUpdated: null,
onSelectionChanged: null,
onFilterUpdated: null,
onSorted: null,
onAttached: null,
onDetached: null
}
}));
const key = Grid.options.key;
expect(key).toBeDefined();
// Key is not the same for angular wrapper or others
if (typeof angular !== 'undefined') {
expect(key).toBeAFunction();
} else {
expect(key).toBe('id');
}
});
it('should create grid using default options', () => {
const columns = [
{ id: 'foo', title: 'Foo' },
{ id: 'bar', title: 'Boo' }
];
const table = document.createElement('table');
const grid = new Grid(table, {
columns: columns
});
expect(grid.options).toBeDefined();
expect(grid.options).not.toBe(Grid.options);
const defaultOptions = jasmine.util.clone(Grid.options);
// We should ignore these properties
delete defaultOptions.columns;
delete defaultOptions.data;
expect(grid.options).toEqual(jasmine.objectContaining(defaultOptions));
});
it('should create grid with custom options', () => {
class Model {
constructor(o) {
this.id = o.id;
}
}
const table = document.createElement('table');
const onInitialized = jasmine.createSpy('onInitialized');
const onDataSpliced = jasmine.createSpy('onDataSpliced');
const grid = new Grid(table, {
key: 'title',
model: Model,
async: true,
scrollable: true,
selection: {
multi: false
},
size: {
width: 100,
height: 200
},
events: {
onInitialized: onInitialized,
onDataSpliced: onDataSpliced
},
columns: [
{ id: 'bar' },
{ id: 'foo' }
]
});
expect(grid.options).toBeDefined();
expect(grid.options).not.toBe(Grid.options);
expect(grid.options).not.toEqual(jasmine.objectContaining(Grid.options));
expect(grid.options).toEqual(jasmine.objectContaining({
key: 'title',
model: Model,
scrollable: true,
selection: {
enable: true,
checkbox: true,
multi: false
},
async: true,
size: {
width: 100,
height: 200
},
events: {
onInitialized: onInitialized,
onUpdated: null,
onRendered: null,
onDataSpliced: onDataSpliced,
onDataUpdated: null,
onDataChanged: null,
onColumnsSpliced: null,
onColumnsUpdated: null,
onSelectionChanged: null,
onFilterUpdated: null,
onSorted: null,
onAttached: null,
onDetached: null
}
}));
});
it('should create grid with custom options', () => {
class Model {
constructor(o) {
this.id = o.id;
}
}
const table = document.createElement('table');
const onInitialized = jasmine.createSpy('onInitialized');
const onDataSpliced = jasmine.createSpy('onDataSpliced');
const grid = new Grid(table, {
key: 'title',
model: Model,
async: true,
scrollable: true,
selection: {
multi: false
},
size: {
width: 100,
height: 200
},
events: {
onInitialized: onInitialized,
onDataSpliced: onDataSpliced
},
columns: [
{ id: 'bar' },
{ id: 'foo' }
]
});
expect(grid.options).toBeDefined();
expect(grid.options).not.toBe(Grid.options);
expect(grid.options).not.toEqual(jasmine.objectContaining(Grid.options));
expect(grid.options).toEqual(jasmine.objectContaining({
key: 'title',
model: Model,
scrollable: true,
selection: {
enable: true,
checkbox: true,
multi: false
},
async: true,
size: {
width: 100,
height: 200
},
events: {
onInitialized: onInitialized,
onUpdated: null,
onRendered: null,
onDataSpliced: onDataSpliced,
onDataUpdated: null,
onDataChanged: null,
onColumnsSpliced: null,
onColumnsUpdated: null,
onSelectionChanged: null,
onFilterUpdated: null,
onSorted: null,
onAttached: null,
onDetached: null
}
}));
});
it('should create grid without table element', () => {
class Model {
constructor(o) {
this.id = o.id;
}
}
const grid = new Grid({
key: 'title',
model: Model,
async: true,
scrollable: true,
selection: {
multi: false
},
size: {
width: 100,
height: 200
},
columns: [
{ id: 'bar' },
{ id: 'foo' }
]
});
expect(grid.options).toBeDefined();
expect(grid.options).not.toBe(Grid.options);
expect(grid.options).not.toEqual(jasmine.objectContaining(Grid.options));
expect(grid.options).toEqual(jasmine.objectContaining({
key: 'title',
model: Model,
scrollable: true,
selection: {
enable: true,
checkbox: true,
multi: false
},
async: true,
size: {
width: 100,
height: 200
},
events: {
onInitialized: null,
onUpdated: null,
onRendered: null,
onDataSpliced: null,
onDataUpdated: null,
onDataChanged: null,
onColumnsSpliced: null,
onColumnsUpdated: null,
onSelectionChanged: null,
onFilterUpdated: null,
onSorted: null,
onAttached: null,
onDetached: null
}
}));
});
it('should create grid using factory', () => {
const table = document.createElement('table');
const grid = Grid.create(table);
expect(grid).toBeInstanceOf(Grid);
});
it('should detach grid', () => {
const table = document.createElement('table');
const grid = new Grid(table, {
scrollable: true,
sortable: true,
selection: {
multi: false
},
columns: [
{ id: 'bar' },
{ id: 'foo' }
]
});
expect(grid).toBeDefined();
expect(grid.$table).toBeDefined();
expect(grid.$tbody).toBeDefined();
expect(table.className).toContain('waffle-grid');
expect(table.className).toContain('waffle-fixedheader');
expect(table.className).toContain('waffle-selectable');
spyOn(grid, 'dispatchEvent').and.callThrough();
spyOn(grid, 'clearChanges').and.callThrough();
spyOn(grid.$data, 'unobserve').and.callThrough();
spyOn(grid.$columns, 'unobserve').and.callThrough();
spyOn(grid.$selection, 'unobserve').and.callThrough();
spyOn(GridDomBinders, 'unbindSort').and.callThrough();
spyOn(GridDomBinders, 'unbindSelection').and.callThrough();
spyOn(GridDomBinders, 'unbindEdition').and.callThrough();
spyOn(GridDomBinders, 'unbindDragDrop').and.callThrough();
spyOn(GridDomBinders, 'unbindResize').and.callThrough();
expect(grid.$data.$$observers).not.toBeEmpty();
expect(grid.$columns.$$observers).not.toBeEmpty();
expect(grid.$selection.$$observers).not.toBeEmpty();
const result = grid.detach();
expect(result).toBe(grid);
expect(grid.$table).toBeNull();
expect(grid.$tbody).toBeNull();
expect(grid.$thead).toBeNull();
expect(grid.$tfoot).toBeNull();
expect(table.className).not.toContain('waffle-grid');
expect(table.className).not.toContain('waffle-fixedheader');
expect(table.className).not.toContain('waffle-selectable');
expect(grid.clearChanges).toHaveBeenCalled();
expect(grid.dispatchEvent).toHaveBeenCalledWith('detached');
expect(grid.$data.unobserve).toHaveBeenCalledWith(GridDataObserver.on, grid);
expect(grid.$columns.unobserve).toHaveBeenCalledWith(GridColumnsObserver.on, grid);
expect(grid.$selection.unobserve).toHaveBeenCalledWith(GridSelectionObserver.on, grid);
expect(grid.$data.$$observers).toEqual([]);
expect(grid.$columns.$$observers).toEqual([]);
expect(grid.$selection.$$observers).toEqual([]);
expect(GridDomBinders.unbindSort).toHaveBeenCalledWith(grid);
expect(GridDomBinders.unbindSelection).toHaveBeenCalledWith(grid);
expect(GridDomBinders.unbindEdition).toHaveBeenCalledWith(grid);
expect(GridDomBinders.unbindDragDrop).toHaveBeenCalledWith(grid);
expect(GridDomBinders.unbindResize).toHaveBeenCalledWith(grid);
});
it('should re-attach dom node', () => {
const table1 = document.createElement('table');
const table2 = document.createElement('table');
const grid = new Grid(table1, {
scrollable: true,
sortable: true,
dnd: true,
view: {
thead: true,
tfoot: true
},
size: {
width: 100,
height: 200
},
selection: {
multi: false
},
columns: [
{ id: 'bar', editable: true },
{ id: 'foo' }
]
});
spyOn(grid, 'dispatchEvent').and.callThrough();
spyOn(grid, 'detach').and.callThrough();
spyOn(grid, 'render').and.callThrough();
spyOn(grid, 'resize').and.callThrough();
spyOn(grid, 'clearChanges').and.callThrough();
spyOn(grid.$data, 'observe').and.callThrough();
spyOn(grid.$columns, 'observe').and.callThrough();
spyOn(grid.$selection, 'observe').and.callThrough();
spyOn(GridDomBinders, 'bindSort').and.callThrough();
spyOn(GridDomBinders, 'bindSelection').and.callThrough();
spyOn(GridDomBinders, 'bindEdition').and.callThrough();
spyOn(GridDomBinders, 'bindDragDrop').and.callThrough();
spyOn(GridDomBinders, 'bindResize').and.callThrough();
const result = grid.attach(table2);
expect(result).toBe(grid);
expect(grid.$table).not.toBeNull();
expect(grid.$table[0]).toBe(table2);
expect(table2.className).toContain('waffle-grid');
expect(table2.className).toContain('waffle-fixedheader');
expect(table2.className).toContain('waffle-selectable');
expect(grid.$tbody).not.toBeNull();
expect(grid.$tbody[0]).toBe(table2.getElementsByTagName('tbody')[0]);
expect(grid.$thead).not.toBeNull();
expect(grid.$thead[0]).toBe(table2.getElementsByTagName('thead')[0]);
expect(grid.$tfoot).not.toBeNull();
expect(grid.$tfoot[0]).toBe(table2.getElementsByTagName('tfoot')[0]);
expect(grid.render).toHaveBeenCalled();
expect(grid.resize).toHaveBeenCalled();
expect(grid.clearChanges).toHaveBeenCalled();
expect(GridDomBinders.bindSort).toHaveBeenCalledWith(grid);
expect(GridDomBinders.bindSelection).toHaveBeenCalledWith(grid);
expect(GridDomBinders.bindEdition).toHaveBeenCalledWith(grid);
expect(GridDomBinders.bindDragDrop).toHaveBeenCalledWith(grid);
expect(GridDomBinders.bindResize).toHaveBeenCalledWith(grid);
expect(grid.$data.observe).toHaveBeenCalledWith(GridDataObserver.on, grid);
expect(grid.$columns.observe).toHaveBeenCalledWith(GridColumnsObserver.on, grid);
expect(grid.$selection.observe).toHaveBeenCalledWith(GridSelectionObserver.on, grid);
expect(grid.$data.$$observers).toHaveLength(1);
expect(grid.$columns.$$observers).toHaveLength(1);
expect(grid.$selection.$$observers).toHaveLength(1);
expect(grid.dispatchEvent).toHaveBeenCalledWith('attached');
});
it('should initialize grid and clear changes', () => {
spyOn(Grid.prototype, 'clearChanges');
const columns = [
{ id: 'foo', title: 'Foo' },
{ id: 'bar', title: 'Boo' }
];
const table = document.createElement('table');
const grid = new Grid(table, {
columns: columns
});
expect(grid.clearChanges).toHaveBeenCalled();
});
it('should create grid with columns set using html options', () => {
const table = document.createElement('table');
table.setAttribute('data-columns', '[{"id": "bar"}, {"id": "foo"}]');
const grid = new Grid(table, {
key: 'title',
});
expect(grid.options).toBeDefined();
expect(grid.options.columns).toBeDefined();
expect(grid.options.columns.length).toBe(2);
expect(grid.$columns).toBeDefined();
expect(grid.$columns.length).toBe(2);
expect(grid.$columns[0]).toEqual(jasmine.objectContaining({
id: 'bar'
}));
expect(grid.$columns[1]).toEqual(jasmine.objectContaining({
id: 'foo'
}));
});
it('should create grid with columns set using data-waffle html options', () => {
const table = document.createElement('table');
table.setAttribute('data-waffle-columns', '[{"id": "bar"}, {"id": "foo"}]');
const grid = new Grid(table, {
key: 'title',
});
expect(grid.options).toBeDefined();
expect(grid.options.columns).toBeDefined();
expect(grid.options.columns.length).toBe(2);
expect(grid.$columns).toBeDefined();
expect(grid.$columns.length).toBe(2);
expect(grid.$columns[0]).toEqual(jasmine.objectContaining({
id: 'bar'
}));
expect(grid.$columns[1]).toEqual(jasmine.objectContaining({
id: 'foo'
}));
});
it('should create grid with columns set using waffle html options', () => {
const table = document.createElement('table');
table.setAttribute('waffle-columns', '[{"id": "bar"}, {"id": "foo"}]');
const grid = new Grid(table, {
key: 'title',
});
expect(grid.options).toBeDefined();
expect(grid.options.columns).toBeDefined();
expect(grid.options.columns.length).toBe(2);
expect(grid.$columns).toBeDefined();
expect(grid.$columns.length).toBe(2);
expect(grid.$columns[0]).toEqual(jasmine.objectContaining({
id: 'bar'
}));
expect(grid.$columns[1]).toEqual(jasmine.objectContaining({
id: 'foo'
}));
});
it('should initialize grid and set key value using html options', () => {
const table = document.createElement('table');
table.setAttribute('data-key', 'title');
const grid = new Grid(table);
expect(grid.options).toBeDefined();
expect(grid.options.key).toBeDefined();
expect(grid.options.key).toBe('title');
});
it('should initialize grid and set scrollable value using html options', () => {
const table = document.createElement('table');
table.setAttribute('data-scrollable', 'true');
const grid = new Grid(table);
expect(grid.options).toBeDefined();
expect(grid.options.scrollable).toBeDefined();
expect(grid.options.scrollable).toBe(true);
});
it('should initialize grid and set sortable value using html options', () => {
const table = document.createElement('table');
table.setAttribute('data-sortable', 'false');
const grid = new Grid(table);
expect(grid.options).toBeDefined();
expect(grid.options.sortable).toBeDefined();
expect(grid.options.sortable).toBe(false);
});
it('should create grid with size values as numbers', () => {
const table = document.createElement('table');
const grid = new Grid(table, {
size: {
width: '100px',
height: '200px'
}
});
expect(grid.options).toEqual(jasmine.objectContaining({
size: {
width: '100px',
height: '200px'
}
}));
});
it('should create selectable grid', () => {
const table = document.createElement('table');
const grid = new Grid(table, {
selection: {
multi: true
}
});
expect(table.className).toContain('waffle-selectable');
});
it('should not create selectable grid', () => {
const table1 = document.createElement('table');
const grid1 = new Grid(table1, {
selection: false
});
expect(table1.className).not.toContain('waffle-selectable');
const table2 = document.createElement('table');
const grid2 = new Grid(table2, {
selection: {
enable: false
}
});
expect(table2.className).not.toContain('waffle-selectable');
});
it('should not create sortable grid', () => {
const table = document.createElement('table');
const grid = new Grid(table, {
sortable: false,
columns: [
{ id: 'foo', title: 'Foo' },
{ id: 'bar', title: 'Boo' }
]
});
expect(grid.$columns).toVerify(function(column) {
return !column.sortable;
});
});
it('should add default css to grid', () => {
const table = document.createElement('table');
const grid = new Grid(table, {
size: {
height: 300
}
});
expect(table.className).toContain('waffle-grid');
});
it('should create scrollable grid', () => {
const table = document.createElement('table');
const grid = new Grid(table, {
scrollable: true
});
expect(table.className).toContain('waffle-fixedheader');
});
it('should create draggable grid', () => {
const table = document.createElement('table');
const columns = [
{ id: 'id' },
{ id: 'foo' },
{ id: 'bar' }
];
const grid = new Grid(table, {
dnd: true
});
expect(grid.$columns).toVerify(function(column) {
return column.draggable;
});
});
it('should create scrollable grid using size', () => {
const table = document.createElement('table');
const grid = new Grid(table, {
size: {
height: 300
}
});
expect(table.className).toContain('waffle-fixedheader');
});
it('should not override draggable flags of columns', () => {
const table = document.createElement('table');
const columns = [
{ id: 'id', draggable: false },
{ id: 'foo', draggable: true },
{ id: 'bar' }
];
const grid = new Grid(table, {
dnd: true,
columns: columns
});
expect(grid.$columns.at(0).draggable).toBeFalse();
expect(grid.$columns.at(1).draggable).toBeTrue();
expect(grid.$columns.at(2).draggable).toBeTrue();
});
it('should not create scrollable grid', () => {
const table = document.createElement('table');
const grid = new Grid(table);
expect(table.className).not.toContain('waffle-fixedheader');
});
it('should retrieve thead, tfoot and tbody element', () => {
const table = document.createElement('table');
const thead = document.createElement('thead');
const tfoot = document.createElement('tfoot');
const tbody = document.createElement('tbody');
table.appendChild(thead);
table.appendChild(tfoot);
table.appendChild(tbody);
const grid = new Grid(table, {
data: [],
columns: [
{ id: 'foo', title: 'Foo' },
{ id: 'bar', title: 'Boo' }
],
view: {
thead: true,
tfoot: true
}
});
expect(grid.$table).toBeDefined();
expect(grid.$table[0].childNodes.length).toBe(3);
expect(grid.$thead).toBeDefined();
expect(grid.$tfoot).toBeDefined();
expect(grid.$tbody).toBeDefined();
expect(grid.$tbody[0]).toBe(tbody);
expect(grid.$thead[0]).toBe(thead);
expect(grid.$tfoot[0]).toBe(tfoot);
});
it('should create thead, tfoot and tbody element', () => {
const table = document.createElement('table');
const grid = new Grid(table, {
data: [],
columns: [
{ id: 'foo', title: 'Foo' },
{ id: 'bar', title: 'Boo' }
],
view: {
thead: true,
tfoot: true
}
});
expect(grid.$table).toBeDefined();
expect(grid.$thead).toBeDefined();
expect(grid.$tfoot).toBeDefined();
expect(grid.$tbody).toBeDefined();
expect(grid.$tbody[0]).toBeDOMElement('tbody');
expect(grid.$thead[0]).toBeDOMElement('thead');
expect(grid.$tfoot[0]).toBeDOMElement('tfoot');
const childs = table.childNodes;
expect(childs.length).toBe(3);
expect(childs[0]).toBe(grid.$thead[0]);
expect(childs[1]).toBe(grid.$tbody[0]);
expect(childs[2]).toBe(grid.$tfoot[0]);
});
it('should create only unknown nodes', () => {
const table = document.createElement('table');
const tbody = document.createElement('tbody');
table.appendChild(tbody);
const grid = new Grid(table, {
data: [],
columns: [
{ id: 'foo', title: 'Foo' },
{ id: 'bar', title: 'Boo' }
],
view: {
thead: true,
tfoot: true
}
});
expect(grid.$table).toBeDefined();
expect(grid.$thead).toBeDefined();
expect(grid.$tfoot).toBeDefined();
expect(grid.$tbody[0]).toBeDOMElement('tbody');
expect(grid.$thead[0]).toBeDOMElement('thead');
expect(grid.$tfoot[0]).toBeDOMElement('tfoot');
const childs = table.childNodes;
expect(childs.length).toBe(3);
expect(childs[0]).toBe(grid.$thead[0]);
expect(childs[1]).toBe(grid.$tbody[0]);
expect(childs[2]).toBe(grid.$tfoot[0]);
});
it('should create grid with fixed size', () => {
const table = document.createElement('table');
const grid = new Grid(table, {
columns: [
{ id: 'id' },
{ id: 'foo' }
],
size: {
width: '100px',
height: '200px'
}
});
expect(grid.options).toEqual(jasmine.objectContaining({
size: {
width: '100px',
height: '200px'
}
}));
expect(grid.$columns[0].computedWidth).toBeANumber();
expect(grid.$columns[1].computedWidth).toBeANumber();
const w1 = grid.$columns[0].computedWidth + 'px';
const w2 = grid.$columns[1].computedWidth + 'px';
expect(w1).toBe(w2);
const theads = grid.$thead[0].childNodes[0].childNodes;
expect(theads[1].style.maxWidth).toBe(w1);
expect(theads[1].style.minWidth).toBe(w1);
expect(theads[1].style.width).toBe(w1);
expect(theads[2].style.maxWidth).toBe(w2);
expect(theads[2].style.minWidth).toBe(w2);
expect(theads[2].style.width).toBe(w2);
});
it('should create grid with fixed size and compute size with functions', () => {
const width = jasmine.createSpy('width').and.returnValue('100px');
const height = jasmine.createSpy('height').and.returnValue('200px');
const table = document.createElement('table');
const grid = new Grid(table, {
columns: [
{ id: 'id' },
{ id: 'foo' }
],
size: {
width: width,
height: height
}
});
expect(grid.options).toEqual(jasmine.objectContaining({
size: {
width: width,
height: height
}
}));
expect(grid.$columns[0].computedWidth).toBeANumber();
expect(grid.$columns[1].computedWidth).toBeANumber();
const w1 = grid.$columns[0].computedWidth + 'px';
const w2 = grid.$columns[0].computedWidth + 'px';
expect(w1).toBe(w2);
const theads = grid.$thead[0].childNodes[0].childNodes;
expect(theads[1].style.maxWidth).toBe(w1);
expect(theads[1].style.minWidth).toBe(w1);
expect(theads[1].style.width).toBe(w1);
expect(theads[2].style.maxWidth).toBe(w2);
expect(theads[2].style.minWidth).toBe(w2);
expect(theads[2].style.width).toBe(w2);
expect(width).toHaveBeenCalled();
expect(height).toHaveBeenCalled();
});
it('should create grid with fixed size with percentages', () => {
const width = jasmine.createSpy('width').and.returnValue('100px');
const height = jasmine.createSpy('height').and.returnValue('200px');
const table = document.createElement('table');
const grid = new Grid(table, {
columns: [
{ id: 'id', width: '20%' },
{ id: 'foo', width: 'auto' }
],
size: {
width: width,
height: height
}
});
expect(grid.options).toEqual(jasmine.objectContaining({
size: {
width: width,
height: height
}
}));
expect(grid.$columns[0].computedWidth).toBeANumber();
expect(grid.$columns[1].computedWidth).toBeANumber();
const w1 = grid.$columns[0].computedWidth + 'px';
const w2 = grid.$columns[1].computedWidth + 'px';
expect(w1).not.toBe(w2);
const theads = grid.$thead[0].childNodes[0].childNodes;
expect(theads[1].style.maxWidth).toBe(w1);
expect(theads[1].style.minWidth).toBe(w1);
expect(theads[1].style.width).toBe(w1);
expect(theads[2].style.maxWidth).toBe(w2);
expect(theads[2].style.minWidth).toBe(w2);
expect(theads[2].style.width).toBe(w2);
expect(width).toHaveBeenCalled();
expect(height).toHaveBeenCalled();
});
it('should create and destroy resizable grid', () => {
spyOn(jq, 'on').and.callThrough();
spyOn(jq, 'off').and.callThrough();
const table = document.createElement('table');
const grid = new Grid(table, {
size: {
width: 100,
height: 200
},
view: {
thead: true,
tfoot: true
}
});
spyOn(GridDomBinders, 'unbindResize').and.callThrough();
expect(grid.$window).toBeDefined();
const $window = grid.$window;
grid.destroy();
expect(GridDomBinders.unbindResize).toHaveBeenCalledWith(grid);
expect($window.off).toHaveBeenCalledWith('resize', jasmine.any(Function));
expect(grid.$window).toBeNull();
});
it('should bind click on header and body when grid is initialized', () => {
spyOn(jq, 'on').and.callThrough();
const table = document.createElement('table');
const grid = new Grid(table, {
data: [],
columns: [
{ id: 'foo', title: 'Foo' },
{ id: 'bar', title: 'Boo' }
],
view: {
thead: true,
tfoot: true
}
});
const onCalls = jq.on.calls.all();
expect(onCalls).toHaveLength(3);
expect(onCalls[0].args).toContain('click', Function);
expect(onCalls[1].args).toContain('click', Function);
expect(onCalls[2].args).toContain('click', Function);
});
it('should bind input on body when grid is initialized if grid is editable and input event is available', () => {
spyOn(jq, 'on').and.callThrough();
spyOn($sniffer, 'hasEvent').and.returnValue(true);
const table = document.createElement('table');
const grid = new Grid(table, {
data: [],
columns: [
{ id: 'foo', title: 'Foo', editable: true },
{ id: 'bar', title: 'Boo' }
],
view: {
thead: true,
tfoot: true
}
});
const onCalls = jq.on.calls.all();
expect(onCalls).toHaveLength(4);
expect(onCalls[0].args).toContain('click', Function);
expect(onCalls[1].args).toContain('click', Function);
expect(onCalls[2].args).toContain('input change', Function);
expect(onCalls[3].args).toContain('click', Function);
});
it('should bind input on body when grid is initialized if grid option is editable', () => {
spyOn(jq, 'on').and.callThrough();
spyOn($sniffer, 'hasEvent').and.returnValue(true);
const table = document.createElement('table');
const grid = new Grid(table, {
data: [],
editable: true,
columns: [
{ id: 'foo', title: 'Foo', editable: true },
{ id: 'bar', title: 'Boo' }
],
view: {
thead: true,
tfoot: true
}
});
const onCalls = jq.on.calls.all();
expect(onCalls).toHaveLength(4);
expect(onCalls[0].args).toContain('click', Function);
expect(onCalls[1].args).toContain('click', Function);
expect(onCalls[2].args).toContain('input change', Function);
expect(onCalls[3].args).toContain('click', Function);
});
it('should bind keyup and change events on body when grid is initialized if grid is editable and input event is not available', () => {
spyOn(jq, 'on').and.callThrough();
spyOn($sniffer, 'hasEvent').and.returnValue(false);
const table = document.createElement('table');
const grid = new Grid(table, {
data: [],
columns: [
{ id: 'foo', title: 'Foo', editable: true },
{ id: 'bar', title: 'Boo' }
],
view: {
thead: true,
tfoot: true
}
});
expect(grid.$$events).toEqual({
onClickThead: {
events: 'click',
handler: jasmine.any(Function)
},
onClickTfoot: {
events: 'click',
handler: jasmine.any(Function)
},
onClickTbody: {
events: 'click',
handler: jasmine.any(Function)
},
onInputTbody: {
events: 'keyup change',
handler: jasmine.any(Function)
}
});
const onCalls = jq.on.calls.all();
expect(onCalls).toHaveLength(4);
expect(onCalls[0].args).toContain('click', grid.$$events.onClickThead);
expect(onCalls[1].args).toContain('click', grid.$$events.onClickTfoot);
expect(onCalls[2].args).toContain('keyup change', grid.$$events.onInputTbody);
expect(onCalls[3].args).toContain('click', grid.$$events.onClickTbody);
});
it('should bind click on header and footer if grid is not selectable and not sortable', () => {
spyOn(jq, 'on').and.callThrough();
const table = document.createElement('table');
const grid = new Grid(table, {
data: [],
selection: false,
sortable: false,
columns: [
{ id: 'foo', title: 'Foo' },
{ id: 'bar', title: 'Boo' }
],
view: {
thead: true,
tfoot: true
}
});
expect(jq.on).not.toHaveBeenCalled();
});
it('should bind click on header and footer only if grid is not selectable', () => {
spyOn(jq, 'on').and.callThrough();
const table = document.createElement('table');
const grid = new Grid(table, {
data: [],
selection: false,
columns: [
{ id: 'foo', title: 'Foo' },
{ id: 'bar', title: 'Boo' }
],
view: {
thead: true,
tfoot: true
}
});
expect(grid.$$events).toEqual({
onClickThead: {
events: 'click',
handler: jasmine.any(Function)
},
onClickTfoot: {
events: 'click',
handler: jasmine.any(Function)
}
});
const onCalls = jq.on.calls.all();
expect(onCalls).toHaveLength(2);
expect(onCalls[0].args).toContain('click', grid.$$events.onClickThead);
expect(onCalls[1].args).toContain('click', grid.$$events.onClickTfoot);
});
it('should bind drag & drop events', () => {
spyOn(jq, 'on').and.callThrough();
const table = document.createElement('table');
const grid = new Grid(table, {
data: [],
selection: false,
sortable: false,
dnd: true,
columns: [
{ id: 'foo', title: 'Foo' },
{ id: 'bar', title: 'Boo' }
],
view: {
thead: true,
tfoot: true
}
});
expect(grid.$$events).toEqual({
onDragStart: {
events: 'dragstart',
handler: jasmine.any(Function)
},
onDragOver: {
events: 'dragover',
handler: jasmine.any(Function)
},
onDragEnd: {
events: 'dragend',
handler: jasmine.any(Function)
},
onDragLeave: {
events: 'dragleave',
handler: jasmine.any(Function)
},
onDragEnter: {
events: 'dragenter',
handler: jasmine.any(Function)
},
onDragDrop: {
events: 'drop',
handler: jasmine.any(Function)
}
});
const onCalls = jq.on.calls.all();
expect(onCalls).toHaveLength(6);
expect(onCalls[0].args).toContain('dragstart', grid.$$events.onDragStart);
expect(onCalls[1].args).toContain('dragover', grid.$$events.onDragOver);
expect(onCalls[2].args).toContain('dragend', grid.$$events.onDragEnd);
expect(onCalls[3].args).toContain('dragleave', grid.$$events.onDragLeave);
expect(onCalls[4].args).toContain('dragenter', grid.$$events.onDragEnter);
expect(onCalls[5].args).toContain('drop', grid.$$events.onDragDrop);
});
it('should bind drag & drop workaround event for IE <= 9', () => {
spyOn(jq, 'on').and.callThrough();
// Spy IE9
document.documentMode = 9;
const table = document.createElement('table');
const grid = new Grid(table, {
data: [],
selection: false,
sortable: false,
dnd: true,
columns: [
{ id: 'foo', title: 'Foo' },
{ id: 'bar', title: 'Boo' }
],
view: {
thead: true,
tfoot: true
}
});
expect(grid.$$events).toEqual({
onDragStart: {
events: 'dragstart',
handler: jasmine.any(Function)
},
onDragOver: {
events: 'dragover',
handler: jasmine.any(Function)
},
onDragEnd: {
events: 'dragend',
handler: jasmine.any(Function)
},
onDragLeave: {
events: 'dragleave',
handler: jasmine.any(Function)
},
onDragEnter: {
events: 'dragenter',
handler: jasmine.any(Function)
},
onDragDrop: {
events: 'drop',
handler: jasmine.any(Function)
},
onSelectStart: {
events: 'selectstart',
handler: jasmine.any(Function)
}
});
const onCalls = jq.on.calls.all();
expect(onCalls).toHaveLength(7);
expect(onCalls[0].args).toContain('dragstart', grid.$$events.onDragStart);
expect(onCalls[1].args).toContain('dragover', grid.$$events.onDragOver);
expect(onCalls[2].args).toContain('dragend', grid.$$events.onDragEnd);
expect(onCalls[3].args).toContain('dragleave', grid.$$events.onDragLeave);
expect(onCalls[4].args).toContain('dragenter', grid.$$events.onDragEnter);
expect(onCalls[5].args).toContain('drop', grid.$$events.onDragDrop);
expect(onCalls[6].args).toContain('selectstart', grid.$$events.onSelectStart);
});
it('should destroy grid', () => {
const table = document.createElement('table');
const grid = new Grid(table, {
data: [],
columns: [
{ id: 'foo', title: 'Foo' },
{ id: 'bar', title: 'Boo' }
],
view: {
thead: true,
tfoot: true
}
});
expect(grid.$table).toBeDefined();
expect(grid.$thead).toBeDefined();
expect(grid.$tbody).toBeDefined();
expect(grid.$data).toBeDefined();
expect(grid.$selection).toBeDefined();
expect(grid.$columns).toBeDefined();
const $data = grid.$data;
const $selection = grid.$selection;
spyOn($data, 'unobserve').and.callThrough();
spyOn($selection, 'unobserve').and.callThrough();
grid.destroy();
expect(grid.$table).toBeNull();
expect(grid.$thead).toBeNull();
expect(grid.$tbody).toBeNull();
expect(grid.$data).toBeNull();
expect(grid.$selection).toBeNull();
expect(grid.$columns).toBeNull();
expect($data.unobserve).toHaveBeenCalled();
expect($selection.unobserve).toHaveBeenCalled();
});
it('should destroy without footer', () => {
const table = document.createElement('table');
const grid = new Grid(table, {
data: [],
columns: [
{ id: 'foo', title: 'Foo' },
{ id: 'bar', title: 'Boo' }
],
view: {
thead: true,
tfoot: false
}
});
expect(grid.$tfoot).not.toBeDefined();
grid.destroy();
expect(grid.$tfoot).toBeNull();
});
it('should destroy without header', () => {
const table = document.createElement('table');
const grid = new Grid(table, {
data: [],
columns: [
{ id: 'foo', title: 'Foo' },
{ id: 'bar', title: 'Boo' }
],
view: {
thead: false,
tfoot: true
}
});
expect(grid.$thead).not.toBeDefined();
grid.destroy();
expect(grid.$thead).toBeNull();
});
it('should unobserve collections when grid is destroyed', () => {
const table = document.createElement('table');
const grid = new Grid(table, {
data: [],
columns: [
{ id: 'foo', title: 'Foo' },
{ id: 'bar', title: 'Boo' }
]
});
const $data = grid.$data;
const $selection = grid.$selection;
spyOn($data, 'unobserve').and.callThrough();
spyOn($selection, 'unobserve').and.callThrough();
grid.destroy();
expect($data.unobserve).toHaveBeenCalled();
expect($selection.unobserve).toHaveBeenCalled();
});
it('should clear event bus when grid is destroyed', () => {
const table = document.createElement('table');
const grid = new Grid(table, {
data: [],
columns: [
{ id: 'foo', title: 'Foo' },
{ id: 'bar', title: 'Boo' }
]
});
const $bus = grid.$bus;
spyOn($bus, 'clear').and.callThrough();
grid.destroy();
expect($bus.clear).toHaveBeenCalled();
});
it('should unbind events when grid is destroyed', () => {
spyOn(jq, 'on').and.callThrough();
spyOn(jq, 'off').and.callThrough();
const table = document.createElement('table');
const grid = new Grid(table, {
data: [],
columns: [
{ id: 'foo', title: 'Foo' },
{ id: 'bar', title: 'Boo' }
],
view: {
thead: true,
tfoot: true
}
});
expect(grid.$table).toBeDefined();
expect(grid.$thead).toBeDefined();
expect(grid.$tbody).toBeDefined();
expect(grid.$data).toBeDefined();
expect(grid.$selection).toBeDefined();
expect(grid.$columns).toBeDefined();
const $table = grid.$table;
const $thead = grid.$thead;
const $tbody = grid.$tbody;
const $tfoot = grid.$tfoot;
spyOn(GridDomBinders, 'unbindSort');
spyOn(GridDomBinders, 'unbindEdition');
spyOn(GridDomBinders, 'unbindSelection');
spyOn(GridDomBinders, 'unbindResize');
spyOn(GridDomBinders, 'unbindDragDrop');
grid.destroy();
expect(grid.$table).toBeNull();
expect(grid.$thead).toBeNull();
expect(grid.$tbody).toBeNull();
expect(grid.$data).toBeNull();
expect(grid.$selection).toBeNull();
expect(grid.$columns).toBeNull();
expect(GridDomBinders.unbindSort).toHaveBeenCalledWith(grid);
expect(GridDomBinders.unbindEdition).toHaveBeenCalledWith(grid);
expect(GridDomBinders.unbindSelection).toHaveBeenCalledWith(grid);
expect(GridDomBinders.unbindResize).toHaveBeenCalledWith(grid);
expect(GridDomBinders.unbindDragDrop).toHaveBeenCalledWith(grid);
});
describe('once initialized', () => {
let columns, data, table, grid;
beforeEach(() => {
columns = [
{ id: 'id', sortable: false },
{ id: 'firstName' },
{ id: 'lastName' }
];
data = [
{ id: 2, firstName: 'foo2', lastName: 'bar2' },
{ id: 1, firstName: 'foo1', lastName: 'bar1' },
{ id: 3, firstName: 'foo2', lastName: 'bar3' }
];
table = document.createElement('table');
fixtures.appendChild(table);
grid = new Grid(table, {
data: data,
columns: columns
});
});
it('should get rows', () => {
const rows = grid.rows();
const expectedRows = [];
const tbody = grid.$tbody[0];
const childNodes = tbody.childNodes;
for (let i = 0; i < childNodes.length; i++) {
expectedRows.push(childNodes[i]);
}
expect(rows).toEqual(rows);
});
it('should get data collection', () => {
expect(grid.data()).toBe(grid.$data);
});
it('should get selection collection', () => {
expect(grid.selection()).toBe(grid.$selection);
});
it('should get column collection', () => {
expect(grid.columns()).toBe(grid.$columns);
});
it('should get css classes', () => {
spyOn(grid, 'isSelectable').and.returnValue(false);
spyOn(grid, 'isScrollable').and.returnValue(false);
expect(grid.cssClasses()).toEqual(['waffle-grid']);
grid.isSelectable.and.returnValue(true);
expect(grid.cssClasses()).toEqual(['waffle-grid', 'waffle-selectable']);
grid.isScrollable.and.returnValue(true);
expect(grid.cssClasses()).toEqual(['waffle-grid', 'waffle-selectable', 'waffle-fixedheader']);
});
it('should resize grid', () => {
spyOn(GridResizer, 'resize');
grid.resize();
expect(GridResizer.resize).toHaveBeenCalled();
});
it('should clear changes', () => {
spyOn(grid.$data, 'clearChanges');
spyOn(grid.$columns, 'clearChanges');
spyOn(grid.$selection, 'clearChanges');
grid.clearChanges();
expect(grid.$data.clearChanges).toHaveBeenCalled();
expect(grid.$columns.clearChanges).toHaveBeenCalled();
expect(grid.$selection.clearChanges).toHaveBeenCalled();
});
it('should clear changes without selection', () => {
spyOn(grid.$data, 'clearChanges');
spyOn(grid.$columns, 'clearChanges');
grid.$selection = undefined;
grid.clearChanges();
expect(grid.$data.clearChanges).toHaveBeenCalled();
expect(grid.$columns.clearChanges).toHaveBeenCalled();
});
it('should render grid', () => {
spyOn(grid, 'renderHeader').and.callThrough();
spyOn(grid, 'renderFooter').and.callThrough();
spyOn(grid, 'renderBody').and.callThrough();
spyOn(grid, 'clearChanges').and.callThrough();
const result = grid.render();
expect(result).toBe(grid);
expect(grid.renderHeader).toHaveBeenCalled();
expect(grid.renderFooter).toHaveBeenCalled();
expect(grid.renderBody).toHaveBeenCalled();
expect(grid.clearChanges).toHaveBeenCalled();
});
it('should render grid asynchronously', () => {
spyOn(grid, 'renderHeader').and.callThrough();
spyOn(grid, 'renderFooter').and.callThrough();
spyOn(grid, 'renderBody').and.callThrough();
spyOn(grid, 'clearChanges').and.callThrough();
const result = grid.render(true);
expect(result).toBe(grid);
expect(grid.renderHeader).toHaveBeenCalled();
expect(grid.renderFooter).toHaveBeenCalled();
expect(grid.renderBody).toHaveBeenCalledWith(true);
expect(grid.clearChanges).toHaveBeenCalled();
});
it('should check if data is selectable', () => {
const data1 = {
id: 1
};
const data2 = {
id: 2
};
const fn = jasmine.createSpy('fn').and.callFake(data => data.id === 1);
grid.options.selection = false;
expect(grid.isSelectable(data1)).toBe(false);
expect(grid.isSelectable(data2)).toBe(false);
grid.options.selection = {
enable: false
};
expect(grid.isSelectable(data1)).toBe(false);
expect(grid.isSelectable(data2)).toBe(false);
grid.options.selection = {
enable: fn
};
expect(grid.isSelectable(data1)).toBe(true);
expect(grid.isSelectable(data2)).toBe(false);
});
it('should check if grid is editable', () => {
grid.options.editable = true;
grid.$columns.forEach(column => column.editable = false);
expect(grid.isEditable()).toBe(true);
grid.options.editable = false;
grid.$columns.forEach(function(column) {
column.editable = {
enable: true,
type: 'text',
css: null
};
});
expect(grid.isEditable()).toBe(true);
grid.options.editable = false;
grid.$columns.forEach(function(column) {
column.editable = false;
});
expect(grid.isEditable()).toBe(false);
});
});
});
|
import React, { PureComponent } from 'react';
import autobind from 'class-autobind';
import { connect } from '../../../store';
import getClassMethods from '../../../helpers/get-class-methods';
import Settings from '../components/Settings';
class SettingsContainer extends PureComponent {
constructor (props) {
super(...arguments);
autobind(this);
}
handleClickSaveSettings (values) {
this.props.clearSettingsHistory({
persistedCollection: values.clearPersistedCollection,
persistedHistory: values.clearPersistedHistory,
queryCollection: values.clearRequestCollection,
queryHistory: values.clearRequestHistory
});
values.clearPersistedCollection &&
this.props.persistedCollectionAllToInitialState();
values.clearPersistedHistory &&
this.props.persistedHistoryAllToInitialState();
values.clearRequestCollection && this.props.queryCollectionAllToInitialState();
values.clearRequestHistory && this.props.queryHistoryAllToInitialState({});
this.props.resetForm('settingsForm');
this.props.setSettingsModal(false);
}
setSettingsModal (bool) {
this.props.setSettingsModal(bool);
}
validation (data) {
const errors = {};
const { name } = data;
if (this.query.collection == null || this.query.collection.trim() === '') {
errors.collection = 'Please enter a collection name';
}
if (name == null || name.trim() === '') {
errors.name = 'Please enter a query name';
}
return Object.keys(errors).length !== 0 ? errors : null;
}
render () {
return <Settings {...getClassMethods(this)} />;
}
}
export default connect(SettingsContainer);
|
/*!
* Benchmark.js <http://benchmarkjs.com/>
* Copyright 2010-2011 Mathias Bynens <http://mths.be/>
* Based on JSLitmus.js, copyright Robert Kieffer <http://broofa.com/>
* Modified by John-David Dalton <http://allyoucanleet.com/>
* Available under MIT license <http://mths.be/mit>
*/
;(function(window, undefined) {
/** Detect free variable `define` */
var freeDefine = typeof define == 'function' &&
typeof define.amd == 'object' && define.amd && define,
/** Detect free variable `exports` */
freeExports = typeof exports == 'object' && exports &&
(typeof global == 'object' && global && global == global.global && (window = global), exports),
/** Detect free variable `require` */
freeRequire = typeof require == 'function' && require,
/** Used to assign each benchmark an incrimented id */
counter = 0,
/** Used to crawl all properties regardless of enumerability */
getAllKeys = Object.getOwnPropertyNames,
/** Used to get property descriptors */
getDescriptor = Object.getOwnPropertyDescriptor,
/** Used in case an object doesn't have its own method */
hasOwnProperty = {}.hasOwnProperty,
/** Used to check if an object is extensible */
isExtensible = Object.isExtensible || function() { return true; },
/** Used to check if an own property is enumerable */
propertyIsEnumerable = {}.propertyIsEnumerable,
/** Used to set property descriptors */
setDescriptor = Object.defineProperty,
/** Used to resolve a value's internal [[Class]] */
toString = {}.toString,
/** Used to integrity check compiled tests */
uid = 'uid' + (+new Date),
/** Used to avoid infinite recursion when methods call each other */
calledBy = {},
/** Used to avoid hz of Infinity */
divisors = {
'1': 4096,
'2': 512,
'3': 64,
'4': 8,
'5': 0
},
/**
* T-Distribution two-tailed critical values for 95% confidence
* http://www.itl.nist.gov/div898/handbook/eda/section3/eda3672.htm
*/
distribution = {
'1': 12.706,'2': 4.303, '3': 3.182, '4': 2.776, '5': 2.571, '6': 2.447,
'7': 2.365, '8': 2.306, '9': 2.262, '10': 2.228, '11': 2.201, '12': 2.179,
'13': 2.16, '14': 2.145, '15': 2.131, '16': 2.12, '17': 2.11, '18': 2.101,
'19': 2.093, '20': 2.086, '21': 2.08, '22': 2.074, '23': 2.069, '24': 2.064,
'25': 2.06, '26': 2.056, '27': 2.052, '28': 2.048, '29': 2.045, '30': 2.042,
'infinity': 1.96
},
/** Used to flag environments/features */
has = {
/** Detect Adobe AIR */
'air': isClassOf(window.runtime, 'ScriptBridgingProxyObject'),
/** Detect if `arguments` objects have the correct internal [[Class]] value */
'argumentsClass': isClassOf(arguments, 'Arguments'),
/** Detect if in a browser environment */
'browser': isHostType(window, 'document') && isHostType(window, 'navigator'),
/** Detect if strings support accessing characters by index */
'charByIndex':
// IE 8 supports indexes on string literals but not string objects
('x'[0] + Object('x')[0]) == 'xx',
/** Detect if strings have indexes as own properties */
'charByOwnIndex':
// Narwhal, Rhino, RingoJS, IE 8*, and Opera < 10.52 support indexes on
// strings but don't detect them as own properties
'x'[0] == 'x' && hasKey('x', '0'),
/** Detect if functions support decompilation */
'decompilation': !!(function() {
try {
// Safari 2.x removes commas in object literals
// from Function#toString results
// http://webk.it/11609
// Firefox 3.6 and Opera 9.25 strip grouping
// parentheses from Function#toString results
// http://bugzil.la/559438
return Function(
'return (' + (function(x) { return { 'x': '' + (1 + x) + '', 'y': 0 }; }) + ')'
)()(0).x === '1';
} catch(e) { }
}()),
/** Detect ES5+ property descriptor API */
'descriptors' : !!(function() {
try {
var o = {};
return (setDescriptor(o, o, o), 'value' in getDescriptor(o, o));
} catch(e) { }
}()),
/** Detect ES5+ Object.getOwnPropertyNames() */
'getAllKeys': !!(function() {
try {
return /\bvalueOf\b/.test(getAllKeys(Object.prototype));
} catch(e) { }
}()),
/** Detect if Java is enabled/exposed */
'java': isClassOf(window.java, 'JavaPackage'),
/** Detect if the Timers API exists */
'timeout': isHostType(window, 'setTimeout') && isHostType(window, 'clearTimeout')
},
/**
* Timer utility object used by `clock()` and `Deferred#resolve`.
* @private
* @type Object
*/
timer = {
/**
* The timer namespace object or constructor.
* @private
* @memberOf timer
* @type Function|Object
*/
'ns': Date,
/**
* Starts the deferred timer.
* @private
* @memberOf timer
* @param {Object} deferred The deferred instance.
*/
'start': null, // lazy defined in `clock()`
/**
* Stops the deferred timer.
* @private
* @memberOf timer
* @param {Object} deferred The deferred instance.
*/
'stop': null // lazy defined in `clock()`
},
/** Shortcut for inverse results */
noArgumentsClass = !has.argumentsClass,
noCharByIndex = !has.charByIndex,
noCharByOwnIndex = !has.charByOwnIndex,
/** Math shortcuts */
abs = Math.abs,
floor = Math.floor,
max = Math.max,
min = Math.min,
pow = Math.pow,
sqrt = Math.sqrt;
/*--------------------------------------------------------------------------*/
/**
* Benchmark constructor.
* @constructor
* @param {String} name A name to identify the benchmark.
* @param {Function|String} fn The test to benchmark.
* @param {Object} [options={}] Options object.
* @example
*
* // basic usage (the `new` operator is optional)
* var bench = new Benchmark(fn);
*
* // or using a name first
* var bench = new Benchmark('foo', fn);
*
* // or with options
* var bench = new Benchmark('foo', fn, {
*
* // displayed by Benchmark#toString if `name` is not available
* 'id': 'xyz',
*
* // called when the benchmark starts running
* 'onStart': onStart,
*
* // called after each run cycle
* 'onCycle': onCycle,
*
* // called when aborted
* 'onAbort': onAbort,
*
* // called when a test errors
* 'onError': onError,
*
* // called when reset
* 'onReset': onReset,
*
* // called when the benchmark completes running
* 'onComplete': onComplete,
*
* // compiled/called before the test loop
* 'setup': setup,
*
* // compiled/called after the test loop
* 'teardown': teardown
* });
*
* // or name and options
* var bench = new Benchmark('foo', {
*
* // a flag to indicate the benchmark is deferred
* 'deferred': true,
*
* // benchmark test function
* 'fn': function(deferred) {
* // call resolve() when the deferred test is finished
* deferred.resolve();
* }
* });
*
* // or options only
* var bench = new Benchmark({
*
* // benchmark name
* 'name': 'foo',
*
* // benchmark test as a string
* 'fn': '[1,2,3,4].sort()'
* });
*
* // a test's `this` binding is set to the benchmark instance
* var bench = new Benchmark('foo', function() {
* 'My name is '.concat(this.name); // My name is foo
* });
*/
function Benchmark(name, fn, options) {
var me = this;
// allow instance creation without the `new` operator
if (me && me.constructor != Benchmark) {
return new Benchmark(name, fn, options);
}
// juggle arguments
if (isClassOf(name, 'Object')) {
// 1 argument (options)
options = name;
}
else if (isClassOf(name, 'Function')) {
// 2 arguments (fn, options)
options = fn;
fn = name;
}
else if (isClassOf(fn, 'Object')) {
// 2 arguments (name, options)
options = fn;
fn = null;
me.name = name;
}
else {
// 3 arguments (name, fn [, options])
me.name = name;
}
setOptions(me, options);
me.id || (me.id = ++counter);
me.fn == null && (me.fn = fn);
me.stats = extend({}, me.stats);
me.times = extend({}, me.times);
}
/**
* Deferred constructor.
* @constructor
* @memberOf Benchmark
* @param {Object} bench The benchmark instance.
*/
function Deferred(bench) {
var me = this;
if (me && me.constructor != Deferred) {
return new Deferred(bench);
}
me.benchmark = bench;
clock(me);
}
/**
* Event constructor.
* @constructor
* @memberOf Benchmark
* @param {String|Object} type The event type.
*/
function Event(type) {
var me = this;
return (me && me.constructor != Event)
? new Event(type)
: (type instanceof Event)
? type
: extend(me, typeof type == 'string' ? { 'type': type } : type);
}
/**
* Suite constructor.
* @constructor
* @memberOf Benchmark
* @param {String} name A name to identify the suite.
* @param {Object} [options={}] Options object.
* @example
*
* // basic usage (the `new` operator is optional)
* var suite = new Benchmark.Suite;
*
* // or using a name first
* var suite = new Benchmark.Suite('foo');
*
* // or with options
* var suite = new Benchmark.Suite('foo', {
*
* // called when the suite starts running
* 'onStart': onStart,
*
* // called between running benchmarks
* 'onCycle': onCycle,
*
* // called when aborted
* 'onAbort': onAbort,
*
* // called when a test errors
* 'onError': onError,
*
* // called when reset
* 'onReset': onReset,
*
* // called when the suite completes running
* 'onComplete': onComplete
* });
*/
function Suite(name, options) {
var me = this;
// allow instance creation without the `new` operator
if (me && me.constructor != Suite) {
return new Suite(name, options);
}
// juggle arguments
if (isClassOf(name, 'Object')) {
// 1 argument (options)
options = name;
} else {
// 2 arguments (name [, options])
me.name = name;
}
setOptions(me, options);
}
/*--------------------------------------------------------------------------*/
/**
* Note: Some array methods have been implemented in plain JavaScript to avoid
* bugs in IE, Opera, Rhino, and Mobile Safari.
*
* IE compatibility mode and IE < 9 have buggy Array `shift()` and `splice()`
* functions that fail to remove the last element, `object[0]`, of
* array-like-objects even though the `length` property is set to `0`.
* The `shift()` method is buggy in IE 8 compatibility mode, while `splice()`
* is buggy regardless of mode in IE < 9 and buggy in compatibility mode in IE 9.
*
* In Opera < 9.50 and some older/beta Mobile Safari versions using `unshift()`
* generically to augment the `arguments` object will pave the value at index 0
* without incrimenting the other values's indexes.
* https://github.com/documentcloud/underscore/issues/9
*
* Rhino and environments it powers, like Narwhal and RingoJS, may have
* buggy Array `concat()`, `reverse()`, `shift()`, `slice()`, `splice()` and
* `unshift()` functions that make sparse arrays non-sparse by assigning the
* undefined indexes a value of undefined.
* https://github.com/mozilla/rhino/commit/702abfed3f8ca043b2636efd31c14ba7552603dd
*/
/**
* Creates an array containing the elements of the host array followed by the
* elements of each argument in order.
* @memberOf Benchmark.Suite
* @returns {Array} The new array.
*/
function concat() {
var value,
j = -1,
length = arguments.length,
result = slice.call(this),
index = result.length;
while (++j < length) {
value = arguments[j];
if (isClassOf(value, 'Array')) {
for (var k = 0, l = value.length; k < l; k++, index++) {
if (k in value) {
result[index] = value[k];
}
}
} else {
result[index] = value;
}
}
return result;
}
/**
* Utility function used by `shift()`, `splice()`, and `unshift()`.
* @private
* @param {Number} start The index to start inserting elements.
* @param {Number} deleteCount The number of elements to delete from the insert point.
* @param {Array} elements The elements to insert.
* @returns {Array} An array of deleted elements.
*/
function insert(start, deleteCount, elements) {
var deleteEnd = start + deleteCount,
elementCount = elements ? elements.length : 0,
index = start - 1,
length = start + elementCount,
object = this,
result = [],
tail = slice.call(object, deleteEnd);
// delete elements from the array
while (++index < deleteEnd) {
if (index in object) {
result[index - start] = object[index];
delete object[index];
}
}
// insert elements
index = start - 1;
while (++index < length) {
object[index] = elements[index - start];
}
// append tail elements
start = index--;
length = (object.length >>> 0) - deleteCount + elementCount;
while (++index < length) {
if ((index - start) in tail) {
object[index] = tail[index - start];
} else {
delete object[index];
}
}
// delete excess elements
deleteCount = deleteCount > elementCount ? deleteCount - elementCount : 0;
while (deleteCount--) {
delete object[length + deleteCount];
}
object.length = length;
return result;
}
/**
* Rearrange the host array's elements in reverse order.
* @memberOf Benchmark.Suite
* @returns {Array} The reversed array.
*/
function reverse() {
var upperIndex,
value,
index = -1,
object = Object(this),
length = object.length >>> 0,
middle = floor(length / 2);
if (length > 1) {
while (++index < middle) {
upperIndex = length - index - 1;
value = upperIndex in object ? object[upperIndex] : uid;
if (index in object) {
object[upperIndex] = object[index];
} else {
delete object[upperIndex];
}
if (value != uid) {
object[index] = value;
} else {
delete object[index];
}
}
}
return object;
}
/**
* Removes the first element of the host array and returns it.
* @memberOf Benchmark.Suite
* @returns {Mixed} The first element of the array.
*/
function shift() {
return insert.call(this, 0, 1)[0];
}
/**
* Creates an array of the host array's elements from the start index up to,
* but not including, the end index.
* @memberOf Benchmark.Suite
* @returns {Array} The new array.
*/
function slice(start, end) {
var index = -1,
object = Object(this),
length = object.length >>> 0,
result = [];
start = toInteger(start);
start = start < 0 ? max(length + start, 0) : min(start, length);
start--;
end = end == null ? length : toInteger(end);
end = end < 0 ? max(length + end, 0) : min(end, length);
while ((++index, ++start) < end) {
if (start in object) {
result[index] = object[start];
}
}
return result;
}
/**
* Allows removing a range of elements and/or inserting elements into the host array.
* @memberOf Benchmark.Suite
* @returns {Array} An array of removed elements.
*/
function splice(start, deleteCount) {
var object = Object(this),
length = object.length >>> 0;
start = toInteger(start);
start = start < 0 ? max(length + start, 0) : min(start, length);
deleteCount = min(max(toInteger(deleteCount), 0), length - start);
return insert.call(object, start, deleteCount, slice.call(arguments, 2));
}
/**
* Converts the specified `value` to an integer.
* @private
* @param {Mixed} value The value to convert.
* @returns {Number} The resulting integer.
*/
function toInteger(value) {
value = +value;
return value === 0 || !isFinite(value) ? value || 0 : value - (value % 1);
}
/**
* Appends arguments to the host array.
* @memberOf Benchmark.Suite
* @returns {Number} The new length.
*/
function unshift() {
var object = Object(this);
insert.call(object, 0, 0, arguments);
return object.length;
}
/*--------------------------------------------------------------------------*/
/**
* Executes a function, associated with a benchmark, synchronously or asynchronously.
* @private
* @param {Object} options The options object.
*/
function call(options) {
options || (options = {});
var fn = options.fn;
(!options.async && fn || function() {
var bench = options.benchmark,
ids = bench._timerIds || (bench._timerIds = []),
index = ids.length;
// under normal use there should only be one id at any time per benchmark
ids.push(setTimeout(function() {
ids.splice(index, 1);
ids.length || delete bench._timerIds;
fn();
}, bench.delay * 1e3));
})();
}
/**
* Creates a function from the given arguments string and body.
* @private
* @param {String} args The comma separated function arguments.
* @param {String} body The function body.
* @returns {Function} The new function.
*/
function createFunction() {
// lazy define
createFunction = function(args, body) {
var anchor = freeDefine ? define.amd : Benchmark,
prop = uid + 'createFunction';
runScript((freeDefine ? 'define.amd.' : 'Benchmark.') + prop + '=function(' + args + '){' + body + '}');
return [anchor[prop], delete anchor[prop]][0];
};
// fix JaegerMonkey bug
// http://bugzil.la/639720
createFunction = has.browser && (createFunction('', 'return"' + uid + '"') || noop)() == uid ? createFunction : Function;
return createFunction.apply(null, arguments);
}
/**
* Iterates over an object's properties, executing the `callback` for each.
* Callbacks may terminate the loop by explicitly returning `false`.
* @private
* @param {Object} object The object to iterate over.
* @param {Function} callback The function executed per own property.
* @param {Object} options The options object.
* @returns {Object} Returns the object iterated over.
*/
function forProps() {
var forShadowed,
skipSeen,
forArgs = true,
shadowed = ['constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf'];
(function(enumFlag, key) {
// must use a non-native constructor to catch the Safari 2 issue
function Klass() { this.valueOf = 0; };
Klass.prototype.valueOf = 0;
// check various for-in bugs
for (key in new Klass) {
enumFlag += key == 'valueOf' ? 1 : 0;
}
// check if `arguments` objects have non-enumerable indexes
for (key in arguments) {
key == '0' && (forArgs = false);
}
// Safari 2 iterates over shadowed properties twice
// http://replay.waybackmachine.org/20090428222941/http://tobielangel.com/2007/1/29/for-in-loop-broken-in-safari/
skipSeen = enumFlag == 2;
// IE < 9 incorrectly makes an object's properties non-enumerable if they have
// the same name as other non-enumerable properties in its prototype chain.
forShadowed = !enumFlag;
}(0));
// lazy define
forProps = function(object, callback, options) {
options || (options = {});
var ctor,
key,
keys,
skipCtor,
done = !object,
result = [object, object = Object(object)][0],
which = options.which,
allFlag = which == 'all',
fn = callback,
index = -1,
iteratee = object,
length = object.length,
ownFlag = allFlag || which == 'own',
seen = {},
skipProto = isClassOf(object, 'Function'),
thisArg = options.bind;
object = Object(object);
if (thisArg !== undefined) {
callback = function(value, key, object) {
return fn.call(thisArg, value, key, object);
};
}
// iterate all properties
if (allFlag && has.getAllKeys) {
for (index = 0, keys = getAllKeys(object), length = keys.length; index < length; index++) {
key = keys[index];
if (callback(object[key], key, object) === false) {
break;
}
}
}
// else iterate only enumerable properties
else {
for (key in object) {
// Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1
// (if the prototype or a property on the prototype has been set)
// incorrectly set a function's `prototype` property [[Enumerable]] value
// to `true`. Because of this we standardize on skipping the `prototype`
// property of functions regardless of their [[Enumerable]] value.
if ((done =
!(skipProto && key == 'prototype') &&
!(skipSeen && (hasKey(seen, key) || !(seen[key] = true))) &&
(!ownFlag || ownFlag && hasKey(object, key)) &&
callback(object[key], key, object) === false)) {
break;
}
}
// in IE < 9 strings don't support accessing characters by index
if (!done && (
forArgs && isArguments(object) ||
((noCharByIndex || noCharByOwnIndex) && isClassOf(object, 'String') &&
(iteratee = noCharByIndex ? object.split('') : object)))) {
while (++index < length) {
if ((done =
callback(iteratee[index], String(index), object) === false)) {
break;
}
}
}
if (!done && forShadowed) {
// Because IE < 9 can't set the `[[Enumerable]]` attribute of an existing
// property and the `constructor` property of a prototype defaults to
// non-enumerable, we manually skip the `constructor` property when we
// think we are iterating over a `prototype` object.
ctor = object.constructor;
skipCtor = ctor && ctor.prototype && ctor.prototype.constructor === ctor;
for (index = 0; index < 7; index++) {
key = shadowed[index];
if (!(skipCtor && key == 'constructor') &&
hasKey(object, key) &&
callback(object[key], key, object) === false) {
break;
}
}
}
}
return result;
};
return forProps.apply(null, arguments);
}
/**
* Gets the critical value for the specified degrees of freedom.
* @private
* @param {Number} df The degrees of freedom.
* @returns {Number} The critical value.
*/
function getCriticalValue(df) {
return distribution[Math.round(df) || 1] || distribution.infinity;
}
/**
* Gets the name of the first argument from a function's source.
* @private
* @param {Function} fn The function.
* @param {String} altName A string used when the name of the first argument is unretrievable.
* @returns {String} The argument name.
*/
function getFirstArgument(fn, altName) {
return (!hasKey(fn, 'toString') &&
(/^[\s(]*function[^(]*\(([^\s,)]+)/.exec(fn) || 0)[1]) || altName || '';
}
/**
* Computes the arithmetic mean of a sample.
* @private
* @param {Array} sample The sample.
* @returns {Number} The mean.
*/
function getMean(sample) {
return reduce(sample, function(sum, x) {
return sum + x;
}) / sample.length || 0;
}
/**
* Gets the source code of a function.
* @private
* @param {Function} fn The function.
* @param {String} altSource A string used when a function's source code is unretrievable.
* @returns {String} The function's source code.
*/
function getSource(fn, altSource) {
var result = altSource;
if (isStringable(fn)) {
result = String(fn);
} else if (has.decompilation) {
// escape the `{` for Firefox 1
result = (/^[^{]+\{([\s\S]*)}\s*$/.exec(fn) || 0)[1];
}
return (result || '').replace(/^\s+|\s+$/g, '');
}
/**
* Checks if a value is an `arguments` object.
* @private
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true` if the value is an `arguments` object, else `false`.
*/
function isArguments() {
// lazy define
isArguments = function(value) {
return toString.call(value) == '[object Arguments]';
};
if (noArgumentsClass) {
isArguments = function(value) {
return hasKey(value, 'callee') &&
!(propertyIsEnumerable && propertyIsEnumerable.call(value, 'callee'));
};
}
return isArguments(arguments[0]);
}
/**
* Checks if an object is of the specified class.
* @private
* @param {Mixed} value The value to check.
* @param {String} name The name of the class.
* @returns {Boolean} Returns `true` if the value is of the specified class, else `false`.
*/
function isClassOf(value, name) {
return value != null && toString.call(value) == '[object ' + name + ']';
}
/**
* Host objects can return type values that are different from their actual
* data type. The objects we are concerned with usually return non-primitive
* types of object, function, or unknown.
* @private
* @param {Mixed} object The owner of the property.
* @param {String} property The property to check.
* @returns {Boolean} Returns `true` if the property value is a non-primitive, else `false`.
*/
function isHostType(object, property) {
var type = object != null ? typeof object[property] : 'number';
return !/^(?:boolean|number|string|undefined)$/.test(type) &&
(type == 'object' ? !!object[property] : true);
}
/**
* Checks if the specified `value` is an object created by the `Object` constructor.
* @private
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true` if `value` is an object, else `false`.
*/
function isObject(value) {
var ctor,
result = !!value && toString.call(value) == '[object Object]';
if (result && noArgumentsClass) {
// avoid false positives for `arguments` objects in IE < 9
result = !isArguments(value);
}
if (result) {
// IE < 9 presents nodes like `Object` objects:
// IE < 8 are missing the node's constructor property
// IE 8 node constructors are typeof "object"
ctor = value.constructor;
// check if the constructor is `Object` as `Object instanceof Object` is `true`
if ((result = isClassOf(ctor, 'Function') && ctor instanceof ctor)) {
// assume objects created by the `Object` constructor have no inherited enumerable properties
// (we assume there are no `Object.prototype` extensions)
forProps(value, function(subValue, subKey) {
result = subKey;
});
// An object's own properties are iterated before inherited properties.
// If the last iterated key belongs to an object's own property then
// there are no inherited enumerable properties.
result = result === true || hasKey(value, result);
}
}
return result;
}
/**
* Checks if a value can be safely coerced to a string.
* @private
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true` if the value can be coerced, else `false`.
*/
function isStringable(value) {
return hasKey(value, 'toString') || isClassOf(value, 'String');
}
/**
* Wraps a function and passes `this` to the original function as the first argument.
* @private
* @param {Function} fn The function to be wrapped.
* @returns {Function} The new function.
*/
function methodize(fn) {
return function() {
var args = [this];
args.push.apply(args, arguments);
return fn.apply(null, args);
};
}
/**
* A no-operation function.
* @private
*/
function noop() {
// no operation performed
}
/**
* A wrapper around require() to suppress `module missing` errors.
* @private
* @param {String} id The module id.
* @returns {Mixed} The exported module or `null`.
*/
function req(id) {
try {
return freeExports && freeRequire(id);
} catch(e) { }
return null;
}
/**
* Runs a snippet of JavaScript via script injection.
* @private
* @param {String} code The code to run.
*/
function runScript(code) {
var anchor = freeDefine ? define.amd : Benchmark,
script = document.createElement('script'),
sibling = document.getElementsByTagName('script')[0],
parent = sibling.parentNode,
prop = uid + 'runScript',
prefix = '(' + (freeDefine ? 'define.amd.' : 'Benchmark.') + prop + '||function(){})();';
// Firefox 2.0.0.2 cannot use script injection as intended because it executes
// asynchronously, but that's OK because script injection is only used to avoid
// the previously commented JaegerMonkey bug.
try {
// remove the inserted script *before* running the code to avoid differences
// in the expected script element count/order of the document.
script.appendChild(document.createTextNode(prefix + code));
anchor[prop] = function() { parent.removeChild(script); };
} catch(e) {
parent = parent.cloneNode(false);
sibling = null;
script.text = code;
}
parent.insertBefore(script, sibling);
delete anchor[prop];
}
/**
* A helper function for setting options/event handlers.
* @private
* @param {Object} bench The benchmark instance.
* @param {Object} [options={}] Options object.
*/
function setOptions(bench, options) {
options = extend({}, bench.constructor.options, options);
bench.options = forOwn(options, function(value, key) {
if (value != null) {
// add event listeners
if (/^on[A-Z]/.test(key)) {
forEach(key.split(' '), function(key) {
bench.on(key.slice(2).toLowerCase(), value);
});
} else {
bench[key] = deepClone(value);
}
}
});
}
/*--------------------------------------------------------------------------*/
/**
* Handles cycling/completing the deferred benchmark.
* @memberOf Benchmark.Deferred
*/
function resolve() {
var me = this,
bench = me.benchmark;
if (++me.cycles < bench.count) {
// continue the test loop
(bench._host || bench).compiled.call(me, timer);
} else {
timer.stop(me);
call({
'async': true,
'benchmark': bench,
'fn': function() {
cycle({ 'benchmark': bench, 'deferred': me });
}
});
}
}
/*--------------------------------------------------------------------------*/
/**
* A deep clone utility.
* @static
* @memberOf Benchmark
* @param {Mixed} value The value to clone.
* @returns {Mixed} The cloned value.
*/
function deepClone(value) {
var accessor,
circular,
clone,
ctor,
descriptor,
extensible,
key,
length,
markerKey,
parent,
result,
source,
subIndex,
data = { 'value': value },
index = 0,
marked = [],
queue = { 'length': 0 },
unmarked = [];
/**
* An easily detectable decorator for cloned values.
*/
function Marker(object) {
this.raw = object;
}
/**
* Gets an available marker key for the given object.
*/
function getMarkerKey(object) {
// avoid collisions with existing keys
var result = uid;
while (object[result] && object[result].constructor != Marker) {
result += 1;
}
return result;
}
/**
* The callback used by `forProps()`.
*/
function propCallback(subValue, subKey) {
// exit early to avoid cloning the marker
if (subValue && subValue.constructor == Marker) {
return;
}
// add objects to the queue
if (subValue === Object(subValue)) {
queue[queue.length++] = { 'key': subKey, 'parent': clone, 'source': value };
}
// assign non-objects
else {
clone[subKey] = subValue;
}
}
do {
key = data.key;
parent = data.parent;
source = data.source;
clone = value = source ? source[key] : data.value;
accessor = circular = descriptor = false;
// create a basic clone to filter out functions, DOM elements, and
// other non `Object` objects
if (value === Object(value)) {
// use custom deep clone function if available
if (isClassOf(value.deepClone, 'Function')) {
clone = value.deepClone();
} else {
ctor = value.constructor;
switch (toString.call(value)) {
case '[object Array]':
clone = new ctor(value.length);
break;
case '[object Boolean]':
clone = new ctor(value == true);
break;
case '[object Date]':
clone = new ctor(+value);
break;
case '[object Object]':
isObject(value) && (clone = new ctor);
break;
case '[object Number]':
case '[object String]':
clone = new ctor(value);
break;
case '[object RegExp]':
clone = ctor(value.source,
(value.global ? 'g' : '') +
(value.ignoreCase ? 'i' : '') +
(value.multiline ? 'm' : ''));
}
}
// continue clone if `value` doesn't have an accessor descriptor
// http://es5.github.com/#x8.10.1
if (clone && clone != value &&
!(descriptor = source && has.descriptors && getDescriptor(source, key),
accessor = descriptor && (descriptor.get || descriptor.set))) {
// use an existing clone (circular reference)
if ((extensible = isExtensible(value))) {
markerKey = getMarkerKey(value);
if (value[markerKey]) {
circular = clone = value[markerKey].raw;
}
} else {
// for frozen/sealed objects
for (subIndex = 0, length = unmarked.length; subIndex < length; subIndex++) {
data = unmarked[subIndex];
if (data.object === value) {
circular = clone = data.clone;
break;
}
}
}
if (!circular) {
// mark object to allow quickly detecting circular references and tie it to its clone
if (extensible) {
value[markerKey] = new Marker(clone);
marked.push({ 'key': markerKey, 'object': value });
} else {
// for frozen/sealed objects
unmarked.push({ 'clone': clone, 'object': value });
}
// iterate over object properties
forProps(value, propCallback, { 'which': 'all' });
}
}
}
if (parent) {
// for custom property descriptors
if (accessor || (descriptor &&
!(descriptor.configurable && descriptor.enumerable && descriptor.writable))) {
descriptor.value && (descriptor.value = clone);
setDescriptor(parent, key, descriptor);
}
// for default property descriptors
else {
parent[key] = clone;
}
} else {
result = clone;
}
} while ((data = queue[index++]));
// remove markers
for (index = 0, length = marked.length; index < length; index++) {
data = marked[index];
delete data.object[data.key];
}
return result;
}
/**
* An iteration utility for arrays and objects.
* Callbacks may terminate the loop by explicitly returning `false`.
* @static
* @memberOf Benchmark
* @param {Array|Object} object The object to iterate over.
* @param {Function} callback The function called per iteration.
* @param {Object} thisArg The `this` binding for the callback function.
* @returns {Array|Object} Returns the object iterated over.
*/
function each(object, callback, thisArg) {
var fn = callback,
index = -1,
result = [object, object = Object(object)][0],
origObject = object,
length = object.length,
isSnapshot = !!(object.snapshotItem && (length = object.snapshotLength)),
isSplittable = (noCharByIndex || noCharByOwnIndex) && isClassOf(object, 'String'),
isConvertable = isSnapshot || isSplittable || 'item' in object;
// in Opera < 10.5 `hasKey(object, 'length')` returns `false` for NodeLists
if (length === length >>> 0) {
if (isConvertable) {
// the third argument of the callback is the original non-array object
callback = function(value, index) {
return fn.call(this, value, index, origObject);
};
// in IE < 9 strings don't support accessing characters by index
if (isSplittable) {
object = object.split('');
} else {
object = [];
while (++index < length) {
// in Safari 2 `index in object` is always `false` for NodeLists
object[index] = isSnapshot ? result.snapshotItem(index) : result[index];
}
}
}
forEach(object, callback, thisArg);
} else {
forOwn(object, callback, thisArg);
}
return result;
}
/**
* Copies own/inherited properties of a source object to the destination object.
* @static
* @memberOf Benchmark
* @param {Object} destination The destination object.
* @param {Object} [source={}] The source object.
* @returns {Object} The destination object.
*/
function extend(destination, source) {
// Chrome < 14 incorrectly sets `destination` to `undefined` when we `delete arguments[0]`
// http://code.google.com/p/v8/issues/detail?id=839
destination = [destination, delete arguments[0]][0];
forEach(arguments, function(source) {
forProps(source, function(value, key) {
destination[key] = value;
});
});
return destination;
}
/**
* A generic `Array#filter` like method.
* @static
* @memberOf Benchmark
* @param {Array} array The array to iterate over.
* @param {Function|String} callback The function/alias called per iteration.
* @param {Object} thisArg The `this` binding for the callback function.
* @returns {Array} A new array of values that passed callback filter.
* @example
*
* // get odd numbers
* Benchmark.filter([1, 2, 3, 4, 5], function(n) {
* return n % 2;
* }); // -> [1, 3, 5];
*
* // get fastest benchmarks
* Benchmark.filter(benches, 'fastest');
*
* // get slowest benchmarks
* Benchmark.filter(benches, 'slowest');
*
* // get benchmarks that completed without erroring
* Benchmark.filter(benches, 'successful');
*/
function filter(array, callback, thisArg) {
var result;
if (callback == 'successful') {
// callback to exclude those that are errored, unrun, or have hz of Infinity
callback = function(bench) { return bench.cycles && isFinite(bench.hz); };
}
else if (callback == 'fastest' || callback == 'slowest') {
// get successful, sort by period + margin of error, and filter fastest/slowest
result = filter(array, 'successful').sort(function(a, b) {
a = a.stats; b = b.stats;
return (a.mean + a.moe > b.mean + b.moe ? 1 : -1) * (callback == 'fastest' ? 1 : -1);
});
result = filter(result, function(bench) {
return result[0].compare(bench) == 0;
});
}
return result || reduce(array, function(result, value, index) {
return callback.call(thisArg, value, index, array) ? (result.push(value), result) : result;
}, []);
}
/**
* A generic `Array#forEach` like method.
* Callbacks may terminate the loop by explicitly returning `false`.
* @static
* @memberOf Benchmark
* @param {Array} array The array to iterate over.
* @param {Function} callback The function called per iteration.
* @param {Object} thisArg The `this` binding for the callback function.
* @returns {Array} Returns the array iterated over.
*/
function forEach(array, callback, thisArg) {
var fn = callback,
index = -1,
length = (array = Object(array)).length >>> 0;
if (thisArg !== undefined) {
callback = function(value, index, array) {
return fn.call(thisArg, value, index, array);
};
}
while (++index < length) {
if (index in array &&
callback(array[index], index, array) === false) {
break;
}
}
return array;
}
/**
* Iterates over an object's own properties, executing the `callback` for each.
* Callbacks may terminate the loop by explicitly returning `false`.
* @static
* @memberOf Benchmark
* @param {Object} object The object to iterate over.
* @param {Function} callback The function executed per own property.
* @param {Object} thisArg The `this` binding for the callback function.
* @returns {Object} Returns the object iterated over.
*/
function forOwn(object, callback, thisArg) {
return forProps(object, callback, { 'bind': thisArg, 'which': 'own' });
}
/**
* Converts a number to a more readable comma-separated string representation.
* @static
* @memberOf Benchmark
* @param {Number} number The number to convert.
* @returns {String} The more readable string representation.
*/
function formatNumber(number) {
number = String(number).split('.');
return number[0].replace(/(?=(?:\d{3})+$)(?!\b)/g, ',') +
(number[1] ? '.' + number[1] : '');
}
/**
* Checks if an object has the specified key as a direct property.
* @static
* @memberOf Benchmark
* @param {Object} object The object to check.
* @param {String} key The key to check for.
* @returns {Boolean} Returns `true` if key is a direct property, else `false`.
*/
function hasKey() {
// lazy define for worst case fallback (not as accurate)
hasKey = function(object, key) {
var parent = object != null && (object.constructor || Object).prototype;
return !!parent && key in Object(object) && !(key in parent && object[key] === parent[key]);
};
// for modern browsers
if (isClassOf(hasOwnProperty, 'Function')) {
hasKey = function(object, key) {
return object != null && hasOwnProperty.call(object, key);
};
}
// for Safari 2
else if ({}.__proto__ == Object.prototype) {
hasKey = function(object, key) {
var result = false;
if (object != null) {
object = Object(object);
object.__proto__ = [object.__proto__, object.__proto__ = null, result = key in object][0];
}
return result;
};
}
return hasKey.apply(this, arguments);
}
/**
* A generic `Array#indexOf` like method.
* @static
* @memberOf Benchmark
* @param {Array} array The array to iterate over.
* @param {Mixed} value The value to search for.
* @param {Number} [fromIndex=0] The index to start searching from.
* @returns {Number} The index of the matched value or `-1`.
*/
function indexOf(array, value, fromIndex) {
var index = toInteger(fromIndex),
length = (array = Object(array)).length >>> 0;
index = (index < 0 ? max(0, length + index) : index) - 1;
while (++index < length) {
if (index in array && value === array[index]) {
return index;
}
}
return -1;
}
/**
* Modify a string by replacing named tokens with matching object property values.
* @static
* @memberOf Benchmark
* @param {String} string The string to modify.
* @param {Object} object The template object.
* @returns {String} The modified string.
*/
function interpolate(string, object) {
forOwn(object, function(value, key) {
string = string.replace(RegExp('#\\{' + key + '\\}', 'g'), value);
});
return string;
}
/**
* Invokes a method on all items in an array.
* @static
* @memberOf Benchmark
* @param {Array} benches Array of benchmarks to iterate over.
* @param {String|Object} name The name of the method to invoke OR options object.
* @param {Mixed} [arg1, arg2, ...] Arguments to invoke the method with.
* @returns {Array} A new array of values returned from each method invoked.
* @example
*
* // invoke `reset` on all benchmarks
* Benchmark.invoke(benches, 'reset');
*
* // invoke `emit` with arguments
* Benchmark.invoke(benches, 'emit', 'complete', listener);
*
* // invoke `run(true)`, treat benchmarks as a queue, and register invoke callbacks
* Benchmark.invoke(benches, {
*
* // invoke the `run` method
* 'name': 'run',
*
* // pass a single argument
* 'args': true,
*
* // treat as queue, removing benchmarks from front of `benches` until empty
* 'queued': true,
*
* // called before any benchmarks have been invoked.
* 'onStart': onStart,
*
* // called between invoking benchmarks
* 'onCycle': onCycle,
*
* // called after all benchmarks have been invoked.
* 'onComplete': onComplete
* });
*/
function invoke(benches, name) {
var args,
bench,
queued,
index = -1,
options = { 'onStart': noop, 'onCycle': noop, 'onComplete': noop },
result = map(benches, function(bench) { return bench; });
/**
* Checks if invoking `run` with asynchronous cycles.
*/
function isAsync(object) {
var async = args[0] && args[0].async;
return isRun(object) && (async == null ? object.options.async : async) && has.timeout;
}
/**
* Checks if invoking `run` on a benchmark instance.
*/
function isRun(object) {
// avoid using `instanceof` here because of IE memory leak issues with host objects
return Object(object).constructor == Benchmark && name == 'run';
}
/**
* Checks if invoking `run` with synchronous cycles.
*/
function isSync(object) {
// if not asynchronous or deferred
return !isAsync(object) && !(isRun(object) && object.defer);
}
/**
* Executes the method and if synchronous, fetches the next bench.
*/
function execute() {
var listeners,
sync = isSync(bench);
if (!sync) {
// use `getNext` as a listener
bench.on('complete', getNext);
listeners = bench.events.complete;
listeners.splice(0, 0, listeners.pop());
}
// execute method
result[index] = isClassOf(bench && bench[name], 'Function') ? bench[name].apply(bench, args) : undefined;
// if synchronous return true until finished
return sync && getNext();
}
/**
* Fetches the next bench or executes `onComplete` callback.
*/
function getNext() {
var last = bench,
sync = isSync(last);
if (!sync) {
last.removeListener('complete', getNext);
last.emit('complete');
}
// choose next benchmark if not exiting early
if (options.onCycle.call(benches, Event('cycle'), last) !== false && raiseIndex() !== false) {
bench = queued ? benches[0] : result[index];
if (!isSync(bench)) {
call({ 'async': isAsync(bench), 'benchmark': bench, 'fn': execute });
}
else if (!sync) {
// resume synchronous execution
while (execute()) { }
}
else {
// continue synchronous execution
return true;
}
} else {
options.onComplete.call(benches, Event('complete'), last);
}
// when async the `return false` will cancel the rest of the "complete"
// listeners because they were called above and when synchronous it will
// exit the while-loop
return false;
}
/**
* Raises `index` to the next defined index or returns `false`.
*/
function raiseIndex() {
var length = result.length;
// if queued then remove the previous bench and subsequent skipped non-entries
if (queued) {
do {
++index > 0 && shift.call(benches);
} while ((length = benches.length) && !('0' in benches));
}
else {
while (++index < length && !(index in result)) { }
}
// if we reached the last index then return `false`
return (queued ? length : index < length) ? index : (index = false);
}
// juggle arguments
if (isClassOf(name, 'String')) {
// 2 arguments (array, name)
args = slice.call(arguments, 2);
} else {
// 2 arguments (array, options)
options = extend(options, name);
name = options.name;
args = isClassOf(args = 'args' in options ? options.args : [], 'Array') ? args : [args];
queued = options.queued;
}
// start iterating over the array
if (raiseIndex() !== false) {
bench = result[index];
options.onStart.call(benches, Event('start'), bench);
// end early if the suite was aborted in an "onStart" listener
if (benches.aborted && benches.constructor == Suite && name == 'run') {
options.onCycle.call(benches, Event('cycle'), bench);
options.onComplete.call(benches, Event('complete'), bench);
}
// else start
else {
if (isAsync(bench)) {
call({ 'async': true, 'benchmark': bench, 'fn': execute });
} else {
while (execute()) { }
}
}
}
return result;
}
/**
* Creates a string of joined array values or object key-value pairs.
* @static
* @memberOf Benchmark
* @param {Array|Object} object The object to operate on.
* @param {String} [separator1=','] The separator used between key-value pairs.
* @param {String} [separator2=': '] The separator used between keys and values.
* @returns {String} The joined result.
*/
function join(object, separator1, separator2) {
var result = [],
length = (object = Object(object)).length,
arrayLike = length === length >>> 0;
separator2 || (separator2 = ': ');
each(object, function(value, key) {
result.push(arrayLike ? value : key + separator2 + value);
});
return result.join(separator1 || ',');
}
/**
* A generic `Array#map` like method.
* @static
* @memberOf Benchmark
* @param {Array} array The array to iterate over.
* @param {Function} callback The function called per iteration.
* @param {Object} thisArg The `this` binding for the callback function.
* @returns {Array} A new array of values returned by the callback.
*/
function map(array, callback, thisArg) {
return reduce(array, function(result, value, index) {
result[index] = callback.call(thisArg, value, index, array);
return result;
}, Array(Object(array).length >>> 0));
}
/**
* Retrieves the value of a specified property from all items in an array.
* @static
* @memberOf Benchmark
* @param {Array} array The array to iterate over.
* @param {String} property The property to pluck.
* @returns {Array} A new array of property values.
*/
function pluck(array, property) {
return map(array, function(object) {
return object == null ? undefined : object[property];
});
}
/**
* A generic `Array#reduce` like method.
* @static
* @memberOf Benchmark
* @param {Array} array The array to iterate over.
* @param {Function} callback The function called per iteration.
* @param {Mixed} accumulator Initial value of the accumulator.
* @returns {Mixed} The accumulator.
*/
function reduce(array, callback, accumulator) {
var noaccum = arguments.length < 3;
forEach(array, function(value, index) {
accumulator = noaccum ? (noaccum = 0, value) : callback(accumulator, value, index, array);
});
return accumulator;
}
/*--------------------------------------------------------------------------*/
/**
* Aborts all benchmarks in the suite.
* @name abort
* @memberOf Benchmark.Suite
* @returns {Object} The suite instance.
*/
function abortSuite() {
var me = this;
if (me.running) {
calledBy.abortSuite = true;
me.reset();
delete calledBy.abortSuite;
me.aborted = true;
!calledBy.resetSuite && invoke(me, 'abort');
me.emit('abort');
}
return me;
}
/**
* Adds a test to the benchmark suite.
* @memberOf Benchmark.Suite
* @param {String} name A name to identify the benchmark.
* @param {Function|String} fn The test to benchmark.
* @param {Object} [options={}] Options object.
* @returns {Object} The benchmark instance.
* @example
*
* // basic usage
* suite.add(fn);
*
* // or using a name first
* suite.add('foo', fn);
*
* // or with options
* suite.add('foo', fn, {
* 'onCycle': onCycle,
* 'onComplete': onComplete
* });
*/
function add(name, fn, options) {
var me = this,
bench = Benchmark(name, fn, options);
me.push(bench);
me.emit('add', bench);
return me;
}
/**
* Creates a new suite with cloned benchmarks.
* @name clone
* @memberOf Benchmark.Suite
* @param {Object} options Options object to overwrite cloned options.
* @returns {Object} The new suite instance.
*/
function cloneSuite(options) {
var me = this,
result = new me.constructor(extend({}, me.options, options));
// copy own properties
forOwn(me, function(value, key) {
if (!hasKey(result, key)) {
result[key] = value && isClassOf(value.clone, 'Function') ? value.clone() : deepClone(value);
}
});
return result;
}
/**
* An `Array#filter` like method.
* @name filter
* @memberOf Benchmark.Suite
* @param {Function|String} callback The function/alias called per iteration.
* @returns {Object} A new suite of benchmarks that passed callback filter.
*/
function filterSuite(callback) {
var me = this,
result = new me.constructor;
result.push.apply(result, filter(me, callback));
return result;
}
/**
* Resets all benchmarks in the suite.
* @name reset
* @memberOf Benchmark.Suite
* @returns {Object} The suite instance.
*/
function resetSuite() {
var me = this,
notAborting = !calledBy.abortSuite;
if (me.running && notAborting) {
calledBy.resetSuite = true;
me.abort();
delete calledBy.resetSuite;
me.aborted = false;
}
else if (me.aborted !== false || me.running !== false) {
me.aborted = me.running = false;
notAborting && invoke(me, 'reset');
me.emit('reset');
}
return me;
}
/**
* Runs the suite.
* @name run
* @memberOf Benchmark.Suite
* @param {Object} [options={}] Options object.
* @returns {Object} The suite instance.
* @example
*
* // basic usage
* suite.run();
*
* // or with options
* suite.run({ 'async': true, 'queued': true });
*/
function runSuite(options) {
var me = this,
benches = [];
me.reset();
me.running = true;
options || (options = {});
invoke(me, {
'name': 'run',
'args': options,
'queued': options.queued,
'onStart': function(event, bench) {
me.emit('start', bench);
},
'onCycle': function(event, bench) {
if (bench.error) {
me.emit('error', bench);
} else if (bench.cycles) {
benches.push(bench);
}
return !me.aborted && me.emit('cycle', bench);
},
'onComplete': function(event, bench) {
me.running = false;
me.emit('complete', bench);
}
});
return me;
}
/*--------------------------------------------------------------------------*/
/**
* Registers a single listener for the specified event type(s).
* @memberOf Benchmark, Benchmark.Suite
* @param {String} type The event type.
* @param {Function} listener The function called when the event occurs.
* @returns {Object} The benchmark instance.
* @example
*
* // register a listener for an event type
* bench.addListener('cycle', listener);
*
* // register a listener for multiple event types
* bench.addListener('start cycle', listener);
*/
function addListener(type, listener) {
var me = this,
events = me.events || (me.events = {});
forEach(type.split(' '), function(type) {
(events[type] || (events[type] = [])).push(listener);
});
return me;
}
/**
* Executes all registered listeners of the specified event type.
* @memberOf Benchmark, Benchmark.Suite
* @param {String|Object} type The event type or object.
* @returns {Boolean} Returns `true` if all listeners were executed, else `false`.
*/
function emit(type) {
var me = this,
event = Event(type),
args = (arguments[0] = event, arguments),
events = me.events,
listeners = events && events[event.type] || [],
result = true;
forEach(listeners.slice(), function(listener) {
return (result = listener.apply(me, args) !== false);
});
return result;
}
/**
* Unregisters a single listener for the specified event type(s).
* @memberOf Benchmark, Benchmark.Suite
* @param {String} type The event type.
* @param {Function} listener The function to unregister.
* @returns {Object} The benchmark instance.
* @example
*
* // unregister a listener for an event type
* bench.removeListener('cycle', listener);
*
* // unregister a listener for multiple event types
* bench.removeListener('start cycle', listener);
*/
function removeListener(type, listener) {
var me = this,
events = me.events;
forEach(type.split(' '), function(type) {
var listeners = events && events[type] || [],
index = indexOf(listeners, listener);
if (index > -1) {
listeners.splice(index, 1);
}
});
return me;
}
/**
* Unregisters all listeners or those for the specified event type(s).
* @memberOf Benchmark, Benchmark.Suite
* @param {String} type The event type.
* @returns {Object} The benchmark instance.
* @example
*
* // unregister all listeners
* bench.removeAllListeners();
*
* // unregister all listeners for an event type
* bench.removeAllListeners('cycle');
*
* // unregister all listeners for multiple event types
* bench.removeAllListeners('start cycle complete');
*/
function removeAllListeners(type) {
var me = this,
events = me.events;
forEach(type ? type.split(' ') : events, function(type) {
(events && events[type] || []).length = 0;
});
return me;
}
/*--------------------------------------------------------------------------*/
/**
* Aborts the benchmark without recording times.
* @memberOf Benchmark
* @returns {Object} The benchmark instance.
*/
function abort() {
var me = this;
if (me.running) {
if (has.timeout) {
forEach(me._timerIds || [], clearTimeout);
delete me._timerIds;
}
// avoid infinite recursion
calledBy.abort = true;
me.reset();
delete calledBy.abort;
me.aborted = true;
me.emit('abort');
}
return me;
}
/**
* Creates a new benchmark using the same test and options.
* @memberOf Benchmark
* @param {Object} options Options object to overwrite cloned options.
* @returns {Object} The new benchmark instance.
* @example
*
* var bizarro = bench.clone({
* 'name': 'doppelganger'
* });
*/
function clone(options) {
var me = this,
result = new me.constructor(extend({}, me, options));
// correct the `options` object
result.options = extend({}, me.options, options);
// copy own custom properties
forOwn(me, function(value, key) {
if (!hasKey(result, key)) {
result[key] = deepClone(value);
}
});
return result;
}
/**
* Determines if a benchmark is faster than another.
* @memberOf Benchmark
* @param {Object} other The benchmark to compare.
* @returns {Number} Returns `-1` if slower, `1` if faster, and `0` if indeterminate.
*/
function compare(other) {
// unpaired two-sample t-test assuming equal variance
// http://en.wikipedia.org/wiki/Student's_t-test
// http://www.chem.utoronto.ca/coursenotes/analsci/StatsTutorial/12tailed.html
var a = this.stats,
b = other.stats,
df = a.size + b.size - 2,
pooled = (((a.size - 1) * a.variance) + ((b.size - 1) * b.variance)) / df,
tstat = (a.mean - b.mean) / sqrt(pooled * (1 / a.size + 1 / b.size)),
near = abs(1 - a.mean / b.mean) < 0.055 && a.rme < 3 && b.rme < 3;
// check if the means aren't close and the t-statistic is significant
// (a larger `mean` indicates a slower benchmark)
return !near && abs(tstat) > getCriticalValue(df) ? (tstat > 0 ? -1 : 1) : 0;
}
/**
* Reset properties and abort if running.
* @memberOf Benchmark
* @returns {Object} The benchmark instance.
*/
function reset() {
var changed,
pair,
me = this,
source = extend({}, me.constructor.prototype, me.options),
pairs = [[source, me]];
if (me.running && !calledBy.abort) {
// no worries, `reset()` is called within `abort()`
me.abort();
me.aborted = source.aborted;
}
else {
// a non-recursive solution to check if properties have changed
// http://www.jslab.dk/articles/non.recursive.preorder.traversal.part4
while ((pair = pairs.pop())) {
forOwn(pair[0], function(value, key) {
var other = pair[1][key];
if (value && isClassOf(value, 'Object')) {
pairs.push([value, other]);
}
else if (value !== other && !(value == null || isClassOf(value, 'Function'))) {
pair[1][key] = value;
changed = true;
}
});
}
if (changed) {
me.emit('reset');
}
}
return me;
}
/**
* Displays relevant benchmark information when coerced to a string.
* @name toString
* @memberOf Benchmark
* @returns {String} A string representation of the benchmark instance.
*/
function toStringBench() {
var me = this,
error = me.error,
hz = me.hz,
id = me.id,
stats = me.stats,
size = stats.size,
pm = has.java ? '+/-' : '\xb1',
result = me.name || (typeof id == 'number' ? '<Test #' + id + '>' : id);
if (error) {
result += ': ' + join(error);
} else {
result += ' x ' + formatNumber(hz.toFixed(hz < 100 ? 2 : 0)) + ' ops/sec ' + pm +
stats.rme.toFixed(2) + '% (' + size + ' run' + (size == 1 ? '' : 's') + ' sampled)';
}
return result;
}
/*--------------------------------------------------------------------------*/
/**
* Clocks the time taken to execute a test per cycle (secs).
* @private
* @param {Object} bench The benchmark instance.
* @returns {Number} The time taken.
*/
function clock() {
var applet,
options = Benchmark.options,
template = { 'begin': 's$=new n$', 'end': 'r$=(new n$-s$)/1e3', 'uid': uid },
timers = [{ 'ns': timer.ns, 'res': max(0.0015, getRes('ms')), 'unit': 'ms' }];
// lazy define for hi-res timers
clock = function(bench) {
var deferred = bench instanceof Deferred && [bench, bench = bench.benchmark][0],
host = bench._host || bench,
fn = host.fn,
fnArg = deferred ? getFirstArgument(fn, 'deferred') : '',
stringable = isStringable(fn),
decompilable = has.decompilation || stringable,
source = {
'setup': getSource(host.setup, preprocess('m$.setup()')),
'fn': getSource(fn, preprocess('f$(' + fnArg + ')')),
'fnArg': fnArg,
'teardown': getSource(host.teardown, preprocess('m$.teardown()'))
},
compiled = host.compiled,
count = host.count = bench.count,
id = host.id,
isEmpty = !(source.fn || stringable),
name = host.name || (typeof id == 'number' ? '<Test #' + id + '>' : id),
ns = timer.ns,
result = 0;
// init `minTime` if needed
bench.minTime = host.minTime || (host.minTime = host.options.minTime = options.minTime);
// repair nanosecond timer
// (some Chrome builds erase the `ns` variable after millions of executions)
if (applet) {
try {
ns.nanoTime();
} catch(e) {
// use non-element to avoid issues with libs that augment them
ns = timer.ns = new applet.Packages.nano;
}
}
if(!compiled) {
// compile in setup/teardown functions and the test loop
compiled = host.compiled = createFunction(preprocess('t$'), interpolate(
preprocess(deferred
? 'var d$=this,#{fnArg}=d$,r$=d$.resolve,m$=(m$=d$.benchmark)._host||m$,f$=m$.fn;' +
'if(!d$.cycles){d$.resolve=function(){d$.resolve=r$;r$.call(d$);' +
'if(d$.cycles==m$.count){#{teardown}\n}};#{setup}\nt$.start(d$);}#{fn}\nreturn{}'
: 'var r$,s$,m$=this,f$=m$.fn,i$=m$.count,n$=t$.ns;#{setup}\n#{begin};' +
'while(i$--){#{fn}\n}#{end};#{teardown}\nreturn{elapsed:r$,uid:"#{uid}"}'),
source
));
try {
if (isEmpty) {
// Firefox may remove dead code from Function#toString results
// http://bugzil.la/536085
throw new Error('The test, ' + name + ', is empty. This may be the result of dead code removal.');
}
else if (!deferred) {
// pretest to determine if compiled code is exits early, usually by a
// rogue `return` statement, by checking for a return object with the uid
host.count = 1;
compiled = (compiled.call(host, timer) || {}).uid == uid && compiled;
host.count = count;
}
} catch(e) {
compiled = false;
bench.error = e || new Error(String(e));
host.count = count;
}
// fallback when a test exits early or errors during pretest
if (decompilable && !compiled && !deferred && !isEmpty) {
compiled = createFunction(preprocess('t$'), interpolate(
preprocess((bench.error && !stringable
? 'var r$,s$,m$=this,f$=m$.fn,i$=m$.count'
: 'function f$(){#{fn}\n}var r$,s$,i$=this.count'
) + ',n$=t$.ns;#{setup}\n#{begin};while(i$--){f$()}#{end};#{teardown}\nreturn{elapsed:r$}'),
source
));
try {
// pretest one more time to check for errors
host.count = 1;
compiled.call(host, timer);
host.compiled = compiled;
host.count = count;
delete bench.error;
}
catch(e) {
host.count = count;
if (!bench.error) {
host.compiled = compiled;
bench.error = e || new Error(String(e));
}
}
}
}
// if no errors run the full test loop
if (!bench.error) {
result = compiled.call(deferred || host, timer).elapsed;
}
return result;
};
/*------------------------------------------------------------------------*/
/**
* Gets the current timer's minimum resolution (secs).
*/
function getRes(unit) {
var measured,
begin,
count = 30,
divisor = 1e3,
ns = timer.ns,
sample = [];
// get average smallest measurable time
while (count--) {
if (unit == 'us') {
divisor = 1e6;
if (ns.stop) {
ns.start();
while (!(measured = ns.microseconds())) { }
} else {
begin = timer.ns();
while (!(measured = ns() - begin)) { }
}
}
else if (unit == 'ns') {
divisor = 1e9;
begin = ns.nanoTime();
while (!(measured = ns.nanoTime() - begin)) { }
}
else {
begin = new ns;
while (!(measured = new ns - begin)) { }
}
// check for broken timers (nanoTime may have issues)
// http://alivebutsleepy.srnet.cz/unreliable-system-nanotime/
if (measured > 0) {
sample.push(measured);
} else {
sample.push(Infinity);
break;
}
}
// convert to seconds
return getMean(sample) / divisor;
}
/**
* Replaces all occurrences of `$` with a unique number and
* template tokens with content.
*/
function preprocess(code) {
return interpolate(code, template).replace(/\$/g, /\d+/.exec(uid));
}
/*------------------------------------------------------------------------*/
// detect nanosecond support from a Java applet
each(window.document && document.applets || [], function(element) {
return !(timer.ns = applet = 'nanoTime' in element && element);
});
// check type in case Safari returns an object instead of a number
try {
if (typeof timer.ns.nanoTime() == 'number') {
timers.push({ 'ns': timer.ns, 'res': getRes('ns'), 'unit': 'ns' });
}
} catch(e) { }
// detect Chrome's microsecond timer:
// enable benchmarking via the --enable-benchmarking command
// line switch in at least Chrome 7 to use chrome.Interval
try {
if ((timer.ns = new (window.chrome || window.chromium).Interval)) {
timers.push({ 'ns': timer.ns, 'res': getRes('us'), 'unit': 'us' });
}
} catch(e) { }
// detect Node's microtime module:
// npm install microtime
if ((timer.ns = (req('microtime') || { 'now': 0 }).now)) {
timers.push({ 'ns': timer.ns, 'res': getRes('us'), 'unit': 'us' });
}
// pick timer with highest resolution
timer = reduce(timers, function(timer, other) {
return other.res < timer.res ? other : timer;
});
// remove unused applet
if (timer.unit != 'ns' && applet) {
applet = (applet.parentNode.removeChild(applet), null);
}
// error if there are no working timers
if (timer.res == Infinity) {
throw new Error('Benchmark.js was unable to find a working timer.');
}
// use API of chosen timer
if (timer.unit == 'ns') {
extend(template, {
'begin': 's$=n$.nanoTime()',
'end': 'r$=(n$.nanoTime()-s$)/1e9'
});
}
else if (timer.unit == 'us') {
extend(template, timer.ns.stop ? {
'begin': 's$=n$.start()',
'end': 'r$=n$.microseconds()/1e6'
} : {
'begin': 's$=n$()',
'end': 'r$=(n$()-s$)/1e6'
});
}
// define `timer` methods
timer.start = createFunction(preprocess('o$'),
preprocess('var n$=this.ns,#{begin};o$.timeStamp=s$'));
timer.stop = createFunction(preprocess('o$'),
preprocess('var n$=this.ns,s$=o$.timeStamp,#{end};o$.elapsed=r$'));
// resolve time span required to achieve a percent uncertainty of at most 1%
// http://spiff.rit.edu/classes/phys273/uncert/uncert.html
options.minTime || (options.minTime = max(timer.res / 2 / 0.01, 0.05));
return clock.apply(null, arguments);
}
/**
* Computes stats on benchmark results.
* @private
* @param {Object} options The options object.
*/
function compute(options) {
options || (options = {});
var async = options.async,
bench = options.benchmark,
elapsed = 0,
queue = [],
sample = [],
initCount = bench.initCount;
/**
* Adds a number of clones to the queue.
*/
function enqueue(count) {
while (count--) {
queue.push(bench.clone({
'_host': bench,
'events': { 'start': [update], 'cycle': [update] }
}));
}
}
/**
* Updates the clone/host benchmarks to keep their data in sync.
*/
function update(event) {
var clone = this,
cycles = clone.cycles,
type = event.type;
if (bench.running) {
if (type == 'cycle') {
if (clone.error) {
bench.abort();
bench.error = clone.error;
bench.emit('error');
}
else {
// Note: the host's bench.count prop is updated in `clock()`
bench.hz = clone.hz;
bench.initCount = clone.initCount;
bench.times.period = clone.times.period;
if (cycles > bench.cycles) {
bench.cycles = cycles;
}
}
bench.emit(type);
}
else {
// reached in clone's onStart
// Note: clone.minTime prop is inited in `clock()`
clone.count = bench.initCount;
}
} else if (bench.aborted) {
clone.abort();
}
}
/**
* Determines if more clones should be queued or if cycling should stop.
*/
function evaluate(event, clone) {
var mean,
moe,
rme,
sd,
sem,
variance,
now = +new Date,
times = bench.times,
done = bench.aborted,
maxedOut = (elapsed += now - clone.times.timeStamp) / 1e3 > bench.maxTime,
size = sample.push(clone.times.period),
varOf = function(sum, x) { return sum + pow(x - mean, 2); };
// exit early for aborted or unclockable tests
if (done || clone.hz == Infinity) {
maxedOut = !(size = sample.length = queue.length = 0);
}
// set host values
if (!done) {
// sample mean (estimate of the population mean)
mean = getMean(sample);
// sample variance (estimate of the population variance)
variance = reduce(sample, varOf, 0) / (size - 1) || 0;
// sample standard deviation (estimate of the population standard deviation)
sd = sqrt(variance);
// standard error of the mean (a.k.a. the standard deviation of the sampling distribution of the sample mean)
sem = sd / sqrt(size);
// margin of error
moe = sem * getCriticalValue(size - 1);
// relative margin of error
rme = (moe / mean) * 100 || 0;
extend(bench.stats, {
'moe': moe,
'rme': rme,
'sem': sem,
'deviation': sd,
'mean': mean,
'size': size,
'variance': variance
});
// Exit early when the elapsed time exceeds the maximum time allowed
// per benchmark. To prevent massive wait times, we do this even if the
// minimum sample size has not been reached. We don't count cycle delays
// toward the max time because delays may be increased by browsers that
// clamp timeouts in inactive tabs.
// https://developer.mozilla.org/en/window.setTimeout#Inactive_tabs
if (maxedOut) {
done = true;
bench.running = false;
bench.initCount = initCount;
times.elapsed = (now - times.timeStamp) / 1e3;
}
if (bench.hz != Infinity) {
times.period = mean;
times.cycle = mean * bench.count;
bench.hz = 1 / mean;
}
}
// if time permits, increase sample size to reduce the margin of error
if (queue.length < 2 && !maxedOut) {
enqueue(1);
}
// stop the invoke cycle when done
return !done;
}
// init queue and begin
enqueue(bench.minSamples);
invoke(queue, {
'name': 'run',
'args': { 'async': async },
'queued': true,
'onCycle': evaluate,
'onComplete': function() {
bench.emit('complete');
}
});
}
/**
* Cycles a benchmark until a run `count` can be established.
* @private
* @param {Object} options The options object.
*/
function cycle(options) {
options || (options = {});
var clocked,
divisor,
minTime,
period,
async = options.async,
bench = options.benchmark,
count = bench.count,
deferred = options.deferred,
times = bench.times;
// continue, if not aborted between cycles
if (bench.running) {
// host `minTime` is set to `Benchmark.options.minTime` in `clock()`
bench.cycles++;
clocked = deferred ? deferred.elapsed : clock(bench);
minTime = bench.minTime;
if (bench.error) {
bench.abort();
bench.emit('error');
}
}
// continue, if not errored
if (bench.running) {
// time taken to complete last test cycle
times.cycle = clocked;
// seconds per operation
period = times.period = clocked / count;
// ops per second
bench.hz = 1 / period;
// do we need to do another cycle?
bench.running = clocked < minTime;
// avoid working our way up to this next time
bench.initCount = count;
if (bench.running) {
// tests may clock at `0` when `initCount` is a small number,
// to avoid that we set its count to something a bit higher
if (!clocked && (divisor = divisors[bench.cycles]) != null) {
count = floor(4e6 / divisor);
}
// calculate how many more iterations it will take to achive the `minTime`
if (count <= bench.count) {
count += Math.ceil((minTime - clocked) / period);
}
bench.running = count != Infinity;
}
}
// should we exit early?
if (bench.emit('cycle') === false) {
bench.abort();
}
// figure out what to do next
if (bench.running) {
// start a new cycle
bench.count = count;
if (deferred) {
(bench._host || bench).compiled.call(deferred, timer);
} else {
call({
'async': async,
'benchmark': bench,
'fn': function() {
cycle({ 'async': async, 'benchmark': bench });
}
});
}
} else {
// fix TraceMonkey bug associated with clock fallbacks
// http://bugzil.la/509069
if (has.browser) {
runScript(uid + '=1;delete ' + uid);
}
// done
bench.emit('complete');
}
}
/**
* Runs the benchmark.
* @memberOf Benchmark
* @param {Object} [options={}] Options object.
* @returns {Object} The benchmark instance.
* @example
*
* // basic usage
* bench.run();
*
* // or with options
* bench.run({ 'async': true });
*/
function run(options) {
var me = this,
async = ((async = options && options.async) == null ? me.async : async) && has.timeout;
// set running to false so reset() won't call abort()
me.running = false;
me.reset();
me.running = true;
me.count = me.initCount;
me.times.timeStamp = +new Date;
me.emit('start');
if (me._host) {
if (me.defer) {
Deferred(me);
} else {
cycle({ 'async': async, 'benchmark': me });
}
} else {
compute({ 'async': async, 'benchmark': me });
}
return me;
}
/*--------------------------------------------------------------------------*/
// Firefox 1 erroneously defines variable and argument names of functions on
// the function itself as non-configurable properties with `undefined` values.
// The bugginess continues as the `Benchmark` constructor has an argument
// named `options` and Firefox 1 will not assign a value to `Benchmark.options`,
// making it non-writable in the process, unless it is the first property
// assigned by for-in loop of `extend()`.
extend(Benchmark, {
/**
* The default options copied by benchmark instances.
* @static
* @memberOf Benchmark
* @type Object
*/
'options': {
/**
* A flag to indicate that benchmark cycles will execute asynchronously by default.
* @memberOf Benchmark.options
* @type Boolean
*/
'async': false,
/**
* A flag to indicate that the benchmark clock is deferred.
* @memberOf Benchmark.options
* @type Boolean
*/
'defer': false,
/**
* The delay between test cycles (secs).
* @memberOf Benchmark.options
* @type Number
*/
'delay': 0.005,
/**
* Displayed by Benchmark#toString when a `name` is not available (auto-generated if `null`).
* @memberOf Benchmark.options
* @type String|Null
*/
'id': null,
/**
* The default number of times to execute a test on a benchmark's first cycle.
* @memberOf Benchmark.options
* @type Number
*/
'initCount': 1,
/**
* The maximum time a benchmark is allowed to run before finishing (secs).
* Note: Cycle delays aren't counted toward the maximum time.
* @memberOf Benchmark.options
* @type Number
*/
'maxTime': 5,
/**
* The minimum sample size required to perform statistical analysis.
* @memberOf Benchmark.options
* @type Number
*/
'minSamples': 5,
/**
* The time needed to reduce the percent uncertainty of measurement to 1% (secs).
* @memberOf Benchmark.options
* @type Number
*/
'minTime': 0,
/**
* The name of the benchmark.
* @memberOf Benchmark.options
* @type String|Null
*/
'name': null
},
/**
* Platform object with properties describing things like browser name,
* version, and operating system.
* @static
* @memberOf Benchmark
* @type Object
*/
'platform': req('platform') || window.platform || {
/**
* The platform description.
* @memberOf Benchmark.platform
* @type String
*/
'description': window.navigator && navigator.userAgent || null,
/**
* The name of the browser layout engine.
* @memberOf Benchmark.platform
* @type String|Null
*/
'layout': null,
/**
* The name of the product hosting the browser.
* @memberOf Benchmark.platform
* @type String|Null
*/
'product': null,
/**
* The name of the browser/environment.
* @memberOf Benchmark.platform
* @type String|Null
*/
'name': null,
/**
* The name of the product's manufacturer.
* @memberOf Benchmark.platform
* @type String|Null
*/
'manufacturer': null,
/**
* The name of the operating system.
* @memberOf Benchmark.platform
* @type String|Null
*/
'os': null,
/**
* The alpha/beta release indicator.
* @memberOf Benchmark.platform
* @type String|Null
*/
'prerelease': null,
/**
* The browser/environment version.
* @memberOf Benchmark.platform
* @type String|Null
*/
'version': null,
/**
* Return platform description when the platform object is coerced to a string.
* @memberOf Benchmark.platform
* @type Function
* @returns {String} The platform description.
*/
'toString': function() {
return this.description || '';
}
},
/**
* The version number.
* @static
* @memberOf Benchmark
* @type String
*/
'version': '0.3.0',
// clone objects
'deepClone': deepClone,
// iteration utility
'each': each,
// augment objects
'extend': extend,
// generic Array#filter
'filter': filter,
// generic Array#forEach
'forEach': forEach,
// generic own property iteration utility
'forOwn': forOwn,
// converts a number to a comma-separated string
'formatNumber': formatNumber,
// generic Object#hasOwnProperty
// (trigger hasKey's lazy define before assigning it to Benchmark)
'hasKey': (hasKey(Benchmark, ''), hasKey),
// generic Array#indexOf
'indexOf': indexOf,
// template utility
'interpolate': interpolate,
// invokes a method on each item in an array
'invoke': invoke,
// generic Array#join for arrays and objects
'join': join,
// generic Array#map
'map': map,
// retrieves a property value from each item in an array
'pluck': pluck,
// generic Array#reduce
'reduce': reduce
});
/*--------------------------------------------------------------------------*/
extend(Benchmark.prototype, {
/**
* The number of times a test was executed.
* @memberOf Benchmark
* @type Number
*/
'count': 0,
/**
* The number of cycles performed while benchmarking.
* @memberOf Benchmark
* @type Number
*/
'cycles': 0,
/**
* The number of executions per second.
* @memberOf Benchmark
* @type Number
*/
'hz': 0,
/**
* The compiled test function.
* @memberOf Benchmark
* @type Function|String
*/
'compiled': null,
/**
* The error object if the test failed.
* @memberOf Benchmark
* @type Object|Null
*/
'error': null,
/**
* The test to benchmark.
* @memberOf Benchmark
* @type Function|String
*/
'fn': null,
/**
* A flag to indicate if the benchmark is aborted.
* @memberOf Benchmark
* @type Boolean
*/
'aborted': false,
/**
* A flag to indicate if the benchmark is running.
* @memberOf Benchmark
* @type Boolean
*/
'running': false,
/**
* Alias of [`Benchmark#addListener`](#Benchmark:addListener).
* @memberOf Benchmark, Benchmark.Suite
* @type Function
*/
'on': addListener,
/**
* Compiled into the test and executed immediately **before** the test loop.
* @memberOf Benchmark
* @type Function|String
* @example
*
* // basic usage
* var bench = Benchmark({
* 'setup': function() {
* var c = this.count,
* element = document.getElementById('container');
* while (c--) {
* element.appendChild(document.createElement('div'));
* }
* },
* 'fn': function() {
* element.removeChild(element.lastChild);
* }
* });
*
* // compiles to something like:
* var c = this.count,
* element = document.getElementById('container');
* while (c--) {
* element.appendChild(document.createElement('div'));
* }
* var start = new Date;
* while (count--) {
* element.removeChild(element.lastChild);
* }
* var end = new Date - start;
*
* // or using strings
* var bench = Benchmark({
* 'setup': '\
* var a = 0;\n\
* (function() {\n\
* (function() {\n\
* (function() {',
* 'fn': 'a += 1;',
* 'teardown': '\
* }())\n\
* }())\n\
* }())'
* });
*
* // compiles to something like:
* var a = 0;
* (function() {
* (function() {
* (function() {
* var start = new Date;
* while (count--) {
* a += 1;
* }
* var end = new Date - start;
* }())
* }())
* }())
*/
'setup': noop,
/**
* Compiled into the test and executed immediately **after** the test loop.
* @memberOf Benchmark
* @type Function|String
*/
'teardown': noop,
/**
* An object of stats including mean, margin or error, and standard deviation.
* @memberOf Benchmark
* @type Object
*/
'stats': {
/**
* The margin of error.
* @memberOf Benchmark#stats
* @type Number
*/
'moe': 0,
/**
* The relative margin of error (expressed as a percentage of the mean).
* @memberOf Benchmark#stats
* @type Number
*/
'rme': 0,
/**
* The standard error of the mean.
* @memberOf Benchmark#stats
* @type Number
*/
'sem': 0,
/**
* The sample standard deviation.
* @memberOf Benchmark#stats
* @type Number
*/
'deviation': 0,
/**
* The sample arithmetic mean.
* @memberOf Benchmark#stats
* @type Number
*/
'mean': 0,
/**
* The sample size.
* @memberOf Benchmark#stats
* @type Number
*/
'size': 0,
/**
* The sample variance.
* @memberOf Benchmark#stats
* @type Number
*/
'variance': 0
},
/**
* An object of timing data including cycle, elapsed, period, start, and stop.
* @memberOf Benchmark
* @type Object
*/
'times': {
/**
* The time taken to complete the last cycle (secs).
* @memberOf Benchmark#times
* @type Number
*/
'cycle': 0,
/**
* The time taken to complete the benchmark (secs).
* @memberOf Benchmark#times
* @type Number
*/
'elapsed': 0,
/**
* The time taken to execute the test once (secs).
* @memberOf Benchmark#times
* @type Number
*/
'period': 0,
/**
* A timestamp of when the benchmark started (ms).
* @memberOf Benchmark#times
* @type Number
*/
'timeStamp': 0
},
// aborts benchmark (does not record times)
'abort': abort,
// registers a single listener
'addListener': addListener,
// creates a new benchmark using the same test and options
'clone': clone,
// compares benchmark's hertz with another
'compare': compare,
// executes listeners of a specified type
'emit': emit,
// removes all listeners of a specified type
'removeAllListeners': removeAllListeners,
// removes a single listener
'removeListener': removeListener,
// reset benchmark properties
'reset': reset,
// runs the benchmark
'run': run,
// pretty print benchmark info
'toString': toStringBench
});
/*--------------------------------------------------------------------------*/
/**
* The default options copied by suite instances.
* @static
* @memberOf Benchmark.Suite
* @type Object
*/
Suite.options = {
/**
* The name of the suite.
* @memberOf Benchmark.Suite.options
* @type String|Null
*/
'name': null
};
/*--------------------------------------------------------------------------*/
extend(Suite.prototype, {
/**
* The number of benchmarks in the suite.
* @memberOf Benchmark.Suite
* @type Number
*/
'length': 0,
/**
* A flag to indicate if the suite is aborted.
* @memberOf Benchmark.Suite
* @type Boolean
*/
'aborted': false,
/**
* A flag to indicate if the suite is running.
* @memberOf Benchmark.Suite
* @type Boolean
*/
'running': false,
/**
* An `Array#forEach` like method.
* Callbacks may terminate the loop by explicitly returning `false`.
* @memberOf Benchmark.Suite
* @param {Function} callback The function called per iteration.
* @returns {Object} The suite iterated over.
*/
'forEach': methodize(forEach),
/**
* An `Array#indexOf` like method.
* @memberOf Benchmark.Suite
* @param {Mixed} value The value to search for.
* @returns {Number} The index of the matched value or `-1`.
*/
'indexOf': methodize(indexOf),
/**
* Invokes a method on all benchmarks in the suite.
* @memberOf Benchmark.Suite
* @param {String|Object} name The name of the method to invoke OR options object.
* @param {Mixed} [arg1, arg2, ...] Arguments to invoke the method with.
* @returns {Array} A new array of values returned from each method invoked.
*/
'invoke': methodize(invoke),
/**
* Converts the array to a string.
* @memberOf Benchmark.Suite
* @param {String} [separator=','] A string to separate each element of the array.
* @returns {String} The removed element.
*/
'join': [].join,
/**
* An `Array#map` like method.
* @memberOf Benchmark.Suite
* @param {Function} callback The function called per iteration.
* @returns {Array} A new array of values returned by the callback.
*/
'map': methodize(map),
/**
* Retrieves the value of a specified property from all benchmarks in the suite.
* @memberOf Benchmark.Suite
* @param {String} property The property to pluck.
* @returns {Array} A new array of property values.
*/
'pluck': methodize(pluck),
/**
* Removes the last element of the host array and returns it.
* @memberOf Benchmark.Suite
* @returns {Mixed} The removed element.
*/
'pop': [].pop,
/**
* Appends arguments to the end of the array.
* @memberOf Benchmark.Suite
* @returns {Number} The array length.
*/
'push': [].push,
/**
* Sorts the elements of the host array.
* @memberOf Benchmark.Suite
* @param {Function} [compareFn=null] A function that defines the sort order.
* @returns {Array} The sorted host array.
*/
'sort': [].sort,
/**
* An `Array#reduce` like method.
* @memberOf Benchmark.Suite
* @param {Function} callback The function called per iteration.
* @param {Mixed} accumulator Initial value of the accumulator.
* @returns {Mixed} The accumulator.
*/
'reduce': methodize(reduce),
// aborts all benchmarks in the suite
'abort': abortSuite,
// adds a benchmark to the suite
'add': add,
// registers a single listener
'addListener': addListener,
// creates a new suite with cloned benchmarks
'clone': cloneSuite,
// executes listeners of a specified type
'emit': emit,
// creates a new suite of filtered benchmarks
'filter': filterSuite,
// alias of addListener
'on': addListener,
// removes all listeners of a specified type
'removeAllListeners': removeAllListeners,
// removes a single listener
'removeListener': removeListener,
// resets all benchmarks in the suite
'reset': resetSuite,
// runs all benchmarks in the suite
'run': runSuite,
// array methods
'concat': concat,
'reverse': reverse,
'shift': shift,
'slice': slice,
'splice': splice,
'unshift': unshift
});
/*--------------------------------------------------------------------------*/
extend(Deferred.prototype, {
/**
* The deferred benchmark instance.
* @memberOf Benchmark.Deferred
* @type Object
*/
'benchmark': null,
/**
* The number of deferred cycles performed while benchmarking.
* @memberOf Benchmark.Deferred
* @type Number
*/
'cycles': 0,
/**
* The time taken to complete the deferred benchmark (secs).
* @memberOf Benchmark.Deferred
* @type Number
*/
'elapsed': 0,
/**
* A timestamp of when the deferred benchmark started (ms).
* @memberOf Benchmark.Deferred
* @type Number
*/
'timeStamp': 0,
// cycles/completes the deferred benchmark
'resolve': resolve
});
/*--------------------------------------------------------------------------*/
/**
* The event type.
* @memberOf Benchmark.Event
* @type String
*/
Event.prototype.type = '';
/*--------------------------------------------------------------------------*/
// expose Deferred, Event and Suite
extend(Benchmark, {
'Deferred': Deferred,
'Event': Event,
'Suite': Suite
});
// expose Benchmark
if (freeExports) {
// in Node.js or RingoJS v0.8.0+
if (typeof module == 'object' && module && module.exports == freeExports) {
(module.exports = Benchmark).Benchmark = Benchmark;
}
// in Narwhal or RingoJS v0.7.0-
else {
freeExports.Benchmark = Benchmark;
}
}
// via curl.js or RequireJS
else if (freeDefine) {
define('benchmark', function() {
return Benchmark;
});
}
// in a browser or Rhino
else {
// use square bracket notation so Closure Compiler won't munge `Benchmark`
// http://code.google.com/closure/compiler/docs/api-tutorial3.html#export
window['Benchmark'] = Benchmark;
}
// trigger clock's lazy define early to avoid a security error
if (has.air) {
clock({ 'fn': noop, 'count': 1, 'options': {} });
}
}(this));
|
var chai = require('chai-jasmine');
chai.use(require('./src/kahlan'));
module.exports = chai;
|
export { default } from 'ember-horizon/utils/workflow';
|
var gulp = require('gulp');
var Server = require('karma').Server;
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var inSequence = require('run-sequence');
var sourceFiles = [
'build/module.js',
'build/helpers.js',
'build/collection.js',
'build/model.js',
'build/sync.js'
];
/**
* Run test once and exit
*/
gulp.task('test', function (done) {
new Server({
configFile: __dirname + '/karma.conf.js',
singleRun: true
}, done).start();
});
/**
* Watch for file changes and re-run tests on each change
*/
gulp.task('test:tdd', function (done) {
new Server({
configFile: __dirname + '/karma.conf.js'
}, done).start();
});
gulp.task('test:dist', function(done) {
new Server({
configFile: __dirname + '/karmaDist.conf.js',
singleRun: true
}, done).start();
})
gulp.task('dist', function(done) {
inSequence(['unminified', 'minified', 'test:dist']);
});
gulp.task('unminified', function(done) {
return gulp.src(sourceFiles)
.pipe(concat('angular-models.js'))
.pipe(gulp.dest('./dist'));
});
gulp.task('minified', function(done) {
return gulp.src(sourceFiles)
.pipe(concat('angular-models.min.js'))
.pipe(uglify())
.pipe(gulp.dest('./dist'));
});
gulp.task('default', ['test:tdd']);
|
var mine = require('../');
var string = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.';
mine.parseText(string, { order: true }, function(err, stats) {
if(err) {
console.log(err);
}
console.log(stats);
});
|
var Comment = React.createClass({
propTypes: {
author: React.PropTypes.string.isRequired,
},
getDefaultProps: function() {
return {
author: 'default author'
};
},
render: function() {
return (
<div>
<span className='author'>{this.props.author}</span>
<span className='content'>{this.props.children}</span>
</div>
);
}
});
ReactDOM.render(
<Comment>
<p style={{
color:'red'
}}>
this is just a demo
</p>
</Comment>,
document.getElementById('example')
);
|
(function() {
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) {
for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; }
function ctor() { this.constructor = child; }
ctor.prototype = parent.prototype;
child.prototype = new ctor;
child.__super__ = parent.prototype;
return child;
};
Phallanxpress.Author = (function() {
__extends(Author, Phallanxpress.Model);
function Author() {
Author.__super__.constructor.apply(this, arguments);
}
return Author;
})();
}).call(this);
|
/** @namespace hubb */
ECMAScript.Extend('hubb', function (ecma) {
var CXFR = ecma.data.XFR;
var proto = ecma.lang.createPrototype(CXFR);
/**
* @class XFR
*/
this.XFR = function (encoding) {
CXFR.apply(this, arguments);
};
this.XFR.prototype = proto;
/**
* @function symbolToClass
*/
proto.symbolToClass = function (symbol) {
return symbol == '%' ? ecma.hubb.HashNode :
symbol == '@' ? ecma.hubb.ArrayNode :
symbol == '$' ? ecma.hubb.ScalarNode :
// symbol == '#' ? ecma.hubb.NumberNode :
// symbol == '~' ? ecma.hubb.DateNode :
// symbol == '?' ? ecma.hubb.BooleanNode :
null;
};
/**
* @function createValue
*/
proto.createValue = function (symbol, value) {
var klass = this.symbolToClass(symbol);
if (klass === String) return value;
return new klass(value);
};
});
|
/*
* PLUGIN TRAFFIC
*
* Danish language file.
*
* Author:
*/
theUILang.traf = "Traffic";
theUILang.perDay = "Per day";
theUILang.perMonth = "Per month";
theUILang.perYear = "Per year";
theUILang.allTrackers = "All trackers";
theUILang.ClearButton = "Clear";
theUILang.ClearQuest = "Do you really want to clear statistics for selected tracker(s)?";
theUILang.selectedTorrent = "Selected torrent";
theUILang.ratioDay = "Ratio/day";
theUILang.ratioWeek = "Ratio/week";
theUILang.ratioMonth = "Ratio/month";
|
export function addClass(el, className) {
if (hasClass(el, className)) {
return;
}
let newClass = el.className.split(' ');
newClass.push(className);
el.className = newClass.join(' ');
}
export function hasClass(el, className) {
let reg = new RegExp('(^|\\s)' + className + '(\\s|$)');
return reg.test(el.className);
}
|
var path = require('path');
module.exports = {
appPath: function () {
switch (process.platform) {
case 'darwin':
return path.join(__dirname, '..', '.tmp', 'Jam-darwin-x64', 'Jam.app', 'Contents', 'MacOS', 'Jam');
case 'linux':
return path.join(__dirname, '..', '.tmp', 'Jam-linux-x64', 'Jam');
default:
throw new Error('Unsupported platform');
}
}
};
|
exports.seed = (knex) => {
return knex('favorites').del()
.then(() => {
return knex('favorites')
.insert([{
id: 1,
book_id: 1,
user_id: 1,
created_at: new Date('2016-06-29 14:26:16 UTC'),
updated_at: new Date('2016-06-29 14:26:16 UTC')
}]);
}).then(() => {
return knex.raw("select setval('favorites_id_seq', (select max(id) from favorites));")
});
};
|
/*global define*/
define([
'jquery',
'../views/about.js'
], function ($, AboutView) {
'use strict';
var FetchUserController = function() {
this.view = new AboutView();
this.view.render();
};
return FetchUserController;
});
|
var current_codepage = 1200;
/*:: declare var cptable:any; */
/*global cptable:true */
if(typeof module !== "undefined" && typeof require !== 'undefined') {
if(typeof cptable === 'undefined') global.cptable = require('./dist/cpexcel.js');
}
function reset_cp() { set_cp(1200); }
var set_cp = function(cp) { current_codepage = cp; };
function char_codes(data) { var o = []; for(var i = 0, len = data.length; i < len; ++i) o[i] = data.charCodeAt(i); return o; }
function utf16leread(data/*:string*/)/*:string*/ {
var o = [];
for(var i = 0; i < (data.length>>1); ++i) o[i] = String.fromCharCode(data.charCodeAt(2*i) + (data.charCodeAt(2*i+1)<<8));
return o.join("");
}
function utf16beread(data/*:string*/)/*:string*/ {
var o = [];
for(var i = 0; i < (data.length>>1); ++i) o[i] = String.fromCharCode(data.charCodeAt(2*i+1) + (data.charCodeAt(2*i)<<8));
return o.join("");
}
var debom = function(data/*:string*/)/*:string*/ {
var c1 = data.charCodeAt(0), c2 = data.charCodeAt(1);
if(c1 == 0xFF && c2 == 0xFE) return utf16leread(data.substr(2));
if(c1 == 0xFE && c2 == 0xFF) return utf16beread(data.substr(2));
if(c1 == 0xFEFF) return data.substr(1);
return data;
};
var _getchar = function _gc1(x) { return String.fromCharCode(x); };
if(typeof cptable !== 'undefined') {
set_cp = function(cp) { current_codepage = cp; };
debom = function(data) {
if(data.charCodeAt(0) === 0xFF && data.charCodeAt(1) === 0xFE) { return cptable.utils.decode(1200, char_codes(data.substr(2))); }
return data;
};
_getchar = function _gc2(x) {
if(current_codepage === 1200) return String.fromCharCode(x);
return cptable.utils.decode(current_codepage, [x&255,x>>8])[0];
};
}
|
import React, {Component, PropTypes} from 'react'
class SearchResults extends Component {
static propTypes = {
show: PropTypes.bool,
tracksList: PropTypes.array
}
renderTracksList = tracksList => (
tracksList.map(track => (
<div key={track.id}>
<img src={track.artwork_url}/>
{track.title}
</div>)
)
)
render() {
const {tracksList, show} = this.props
return (
<div>
{show
? this.renderTracksList(tracksList)
: null
}
</div>
)
}
}
export default SearchResults
|
/*! easytree - v0.0.0 - 2016-05-18 - */
;
(function (d3, $) {
// This file is used in the build process to enable or disable features in the
// compiled binary. Here's how it works: If you have a const defined like so:
//
// const MY_AWESOME_FEATURE_IS_ENABLED = false;
//
// ...And the compiler (UglifyJS) sees this in your code:
//
// if (MY_AWESOME_FEATURE_IS_ENABLED) {
// doSomeStuff();
// }
//
// ...Then the if statement (and everything in it) is removed - it is
// considered dead code. If it's set to a truthy value:
//
// const MY_AWESOME_FEATURE_IS_ENABLED = true;
//
// ...Then the compiler leaves the if (and everything in it) alone.
var DEBUG = false;
// If you add more consts here, you need to initialize them in library.core.js
// to true. So if you add:
//
// const MY_AWESOME_FEATURE_IS_ENABLED = /* any value */;
//
// Then in library.core.js you need to add:
//
// if (typeof MY_AWESOME_FEATURE_IS_ENABLED === 'undefined') {
// MY_AWESOME_FEATURE_IS_ENABLED = true;
// }
// Compiler directive for UglifyJS. See library.const.js for more info.
if (typeof DEBUG === 'undefined') {
DEBUG = true;
}
// LIBRARY-GLOBAL CONSTANTS
//
// These constants are exposed to all library modules.
// GLOBAL is a reference to the global Object.
var Fn = Function, GLOBAL = new Fn('return this')();
// LIBRARY-GLOBAL METHODS
//
// The methods here are exposed to all library modules. Because all of the
// source files are wrapped within a closure at build time, they are not
// exposed globally in the distributable binaries.
/**
* A no-op function. Useful for passing around as a default callback.
*/
function noop() {
}
/**
* Init wrapper for the core module.
* @param {Object} The Object that the library gets attached to in
* library.init.js. If the library was not loaded with an AMD loader such as
* require.js, this is the global Object.
*/
function initEasyTreeCore(context) {
// It is recommended to use strict mode to help make mistakes easier to find.
'use strict';
// PRIVATE MODULE CONSTANTS
//
// An example of a CONSTANT variable;
var CORE_CONSTANT = true;
// PRIVATE MODULE METHODS
//
// These do not get attached to a prototype. They are private utility
// functions.
/**
* An example of a private method. Feel free to remove this.
* @param {number} aNumber This is a parameter description.
* @returns {number} This is a return value description.
*/
function corePrivateMethod(aNumber) {
return aNumber;
}
function copyToClipboard(elem) {
// create hidden text element, if it doesn't already exist
var targetId = "_hiddenCopyText_";
var isInput = elem.tagName === "INPUT" || elem.tagName === "TEXTAREA";
var origSelectionStart, origSelectionEnd;
if (isInput) {
// can just use the original source element for the selection and copy
target = elem;
origSelectionStart = elem.selectionStart;
origSelectionEnd = elem.selectionEnd;
} else {
// must use a temporary form element for the selection and copy
target = document.getElementById(targetId);
if (!target) {
var target = document.createElement("textarea");
target.style.position = "absolute";
target.style.left = "-9999px";
target.style.top = "0";
target.id = targetId;
document.body.appendChild(target);
}
target.textContent = elem.textContent;
}
// select the content
var currentFocus = document.activeElement;
target.focus();
target.setSelectionRange(0, target.value.length);
// copy the selection
var succeed;
try {
succeed = document.execCommand("copy");
} catch (e) {
succeed = false;
}
// restore original focus
if (currentFocus && typeof currentFocus.focus === "function") {
currentFocus.focus();
}
if (isInput) {
// restore prior selection
elem.setSelectionRange(origSelectionStart, origSelectionEnd);
} else {
// clear temporary content
target.textContent = "";
}
return succeed;
}
/**
* This is the constructor for the EasyTree Object. Please rename it to
* whatever your library's name is. Note that the constructor is also being
* attached to the context that the library was loaded in.
* @param {Object} opt_config Contains any properties that should be used to
* configure this instance of the library.
* @constructor
*/
var EasyTree = context.EasyTree = function (opt_config) {
opt_config = opt_config || {};
var width = opt_config.width || "100%";
var height = opt_config.height || "100%";
var json = opt_config.data || {};
var container = opt_config.container || "body";
var mouseover_cb = opt_config.points.mouseover || noop;
var mouseout_cb = opt_config.points.mouseout || noop;
var click_cb = opt_config.points.clicked || noop;
var show_top_scroll = opt_config.show_top_scroll || false;
var type = opt_config.type || "anova";
var defaultOpen = opt_config.type || true;
var depth = opt_config.type || 1;
var nodeDetails = opt_config.nodeDetails;
var zoom = d3.behavior.zoom().translate([100, 50]).scale(.25);
var reset = opt_config.reset || false;
if(reset) {
$("#easyTree").removeClass("col-md-8");
$("#easyTree").addClass("col-md-10");
}
var root,
i = 0,
duration = 750,
rectW = 180,
rectH = 110;
//d3.json(data, function (json) {
root = json;
root.x0 = 0;
root.y0 = height / 2;
var scale = 1;
var tree = d3.layout.tree()
.nodeSize([rectW + 20, rectH + 20]);
var diagonal = d3.svg.diagonal()
.projection(function (d) {
return [d.x + rectW / 2, d.y + rectH / 2];
});
$(container).empty();
if (show_top_scroll == true) {
var wrapper = d3.select(container).append("div")
.attr("class", "aligner wrapper-1 custom-scroll scrollbar-x custom-scroll-x")
.append("div")
.attr("class", "topscroll");
}
var outer_container = d3.select(container).append("div")
.attr("class", "aligner outer")
.append("div")
.attr("class", "inner");
function zooming(d) {
svg.attr("transform",
"translate(" + d3.event.translate + ")" + " scale(" + d3.event.scale + ")");
}
var svg = d3.select("div.inner").append("svg")
.attr("id", "easytree-svg")
.attr("class", "aligner-item")
.call(zoom.on("zoom", zooming))
.on("dblclick.zoom", null)
.append("svg:g")
.attr("transform", "translate(100,50)scale(.25,.25)");
var panCanvas = svg.append("g")
.attr("class", "svg-child");
// add the tool tip
var tooltip = d3.select("body").append("div")
// .attr("class", "et-tooltip")
.style("opacity", 1);
$("div.et-tooltip").hide();
function collapse(d) {
if (d.children) {
d._children = d.children;
d._children.forEach(collapse);
d.children = null;
}
}
//root.children.forEach(collapse);
if (!defaultOpen) {
collapse(root);
}
update(root, true);
centerNode(root);
function centerNode(source) {
var x = -source.y0;
var y = -source.x0;
var rectObject = document.getElementById("easytree-svg").getBoundingClientRect();
x = x * scale + rectObject["width"] / 2 - 90;
y = 20;
// d3.select('g').transition()
// .duration(duration)
// .attr("transform", "translate(" + x + "," + y + ")");
}
function update(source, option) {
// Compute the new tree layout.
var nodes = tree.nodes(root).reverse(),
links = tree.links(nodes);
// Normalize for fixed-depth.
nodes.forEach(function (d) {
d.y = d.depth * 150;
});
// Update the nodes…
var node = panCanvas.selectAll("g.node")
.data(nodes, function (d) {
//console.log(d);
//console.log(nodeDetails);
return d.id || (d.id = ++i);
});
function close_popup() {
tooltip.transition()
.duration(500)
.style("opacity", 0);
}
function showToolTip(parents, parentsData) {
// Tooltip
tooltip.transition()
.duration(200)
.style("opacity", .95);
for (var i = 0; i < parents.length; i++) {
d3.select("path#id" + parents[i]).classed("active", true);
}
$("div.hover-popover").remove();
$("div.et-tooltip").empty();
// for(var i in parentsData) {
// console.log(i);
// for(var k in nodeDetails ) {
// if(nodeDetails[k]['id'] == i) {
// console.log("comes in");
// console.log(nodeDetails[k]['id']);
// $("div.hover-popover ").append('<p class="marginB5"><span class="canvas-label">' + 'Impurity' + ' :' + '</span>' + '<span class="canvas-value"> ' + nodeDetails[k]['impurity'].toFixed(4) + '</span>' + '</p>');
// $("div.hover-popover ").append('<p class="marginB5"><span class="canvas-label">' + 'Gain' + ' :' + '</span>' + '<span class="canvas-value"> ' + nodeDetails[k]['gain'].toFixed(4) + '</span>' + '</p>');
//
//
// }
// }
// break;
// }
// $("div.et-tooltip").append('<div class="hover-popover"><h3>Prediction path</h3><div class="icons-popover"></span><span class="glyphicon glyphicon-copy" aria-hidden="true"></span><span class="glyphicon glyphicon-export" aria-hidden="true"></span><span class="glyphicon glyphicon-remove-sign icon-close" aria-hidden="true"></span></div></div>');
$("div.et-tooltip").append('<div class="hover-popover"><h3>Prediction path</h3><ul></ul></div>');
for (var i = parentsData.length-1; i>=0 ; i--) {
if (parentsData[i] != undefined) {
if (parentsData[i]["id"] == 1) {
$("div.hover-popover ul").append('<li class="path-init">' + parentsData[i]["name"] + '</li>');
}
else {
if (parentsData[i]["children_cnt"] != undefined && parentsData[i]["children_cnt"] > 0) {
$("div.hover-popover ul").append('<li class="path-mid">' + parentsData[i]["name"] + '</li>');
}
else {
$("div.hover-popover ul").append('<li class="path-end">' + parentsData[i]["name"] + '</li>');
}
}
}
}
tooltip.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY - 28) + "px");
$("div.et-tooltip").show();
}
function mouseover(d) {
$("#easyTree").removeClass("col-md-10");
$("#easyTree").addClass("col-md-8");
svg.selectAll(".active").classed("active", false);
var parents = [];
var parentsData = [];
var obj = {};
obj["id"] = d.id;
obj["name"] = d.name;
if (d.children != undefined) {
obj["children_cnt"] = d.children.length;
}
else if (d._children != undefined) {
obj["children_cnt"] = d._children.length;
}
if (type == 'classification') {
obj["category"] = d.category;
}
else {
obj["size"] = d.size;
obj["value"] = d.value;
}
parentsData[d.id] = obj;
parents.push(d.id);
getUptoParent(d, parents, parentsData, type);
for (var i = 0; i < parents.length; i++) {
d3.select("path#id" + parents[i]).classed("active", true);
}
showToolTip(parents, parentsData);
mouseover_cb(d);
}
function mouseout(d) {
close_popup()
mouseout_cb(d);
}
// Toggle children on click.
function click(d) {
if (d.children) {
d._children = d.children;
d.children = null;
} else {
d.children = d._children;
d._children = null;
}
update(d, false);
var parents = [];
var parentsData = [];
var obj = {};
obj["id"] = d.id;
obj["name"] = d.name;
//obj["children_cnt"] = d.children.length;
if (type == 'classification') {
obj["category"] = d.category;
}
else {
obj["size"] = d.size;
obj["value"] = d.value;
}
parentsData[d.id] = obj;
parents.push(d.id)
getUptoParent(d, parents, parentsData, type);
close_popup();
click_cb(d, parents, parentsData, tooltip);
}
function getUptoParent(d, parents, parentsData, type) {
var obj = {};
if (d["parent"] != undefined) {
obj["id"] = d["parent"]["id"];
obj["name"] = d["parent"]["name"];
obj["children_cnt"] = d["parent"]["children"].length;
if (type == "classification") {
obj["category"] = d["parent"]["category"];
}
else {
obj["size"] = d["parent"]["size"];
obj["value"] = d["parent"]["value"];
}
parentsData[d["parent"]["id"]] = obj;
parents.push(d["parent"]["id"]);
if (d["parent"] != undefined && d["parent"]["parent_id"] != null) {
var q = d["parent"];
getUptoParent(q, parents, parentsData);
}
}
}
// Enter any new nodes at the parent's previous position.
var nodeEnter = node.enter().append("g")
.attr("class", "node")
.attr("transform", function (d) {
if (!isNaN(source.y0))
return "translate(" + source.x0 + "," + source.y0 + ")";
})
.on("dblclick", click)
.on("mouseover", mouseover)
.on("mouseout", mouseout);
nodeEnter.append("rect")
.attr("width", rectW)
.attr("height", rectH)
.attr("class", "node-body");
nodeEnter
.append("text")
.attr("x", (rectW / 2))
.attr("y", -12)
.attr("class", "node-title")
.text(function (d) {
return "Node: " + d.id;
}).call(getBB);
nodeEnter.insert("rect", "text")
.attr("x", -0)
.attr("y", -30)
.attr("width", function (d) {
return rectW;
})
.attr("height", function (d) {
return "30"
})
.attr("class", "node-heading")
.attr("shape-rendering", "crispEdges")
.attr("stroke", function (d) {
if (d.parent_id == null) {
return "#00725d";
}
else {
if ((d.children != undefined && d.children.length > 0 ) || (d._children != undefined && d._children.length > 0)) {
return "#3B78E7";
}
else {
return "#f04d4c";
}
}
})
.attr("stroke-width", 1)
.attr("fill", function (d) {
if (d.parent_id == null) {
return "#00725d";
}
else {
if ((d.children != undefined && d.children.length > 0 ) || (d._children != undefined && d._children.length > 0)) {
return "#3B78E7";
}
else {
return "#f04d4c";
}
}
});
function getBB(selection) {
selection.each(function (d) {
d.bbox = this.getBBox();
})
}
nodeEnter.append("foreignObject")
.attr('x', 0)
.attr('y', 0)
.attr("font-size", "5")
.attr("font-weight", 100)
.attr("style", "width :" + rectW + "px; height :" + rectH + "px; padding-top: 7px")
.attr("class", "content")
.html(function (d) {
var htmlText = '';
var color = ['green', 'red', 'blue', 'orange', 'purple'];
if (type == 'classification') {
var catLen = d["category"].length;
if (catLen > 3)
catLen = 3;
htmlText = htmlText + '<p class="node-rule text-ellipsis"><span class="canvas-label">' + d.name + '</span></p>';
// console.log(d);
//console.log(d.name);
for (var j = 0; j < catLen; j++) {
htmlText = htmlText + '<p class="marginB5"><span class="canvas-label">' + 'Predicted Value' + ' :' + '</span>' + '<span class="canvas-value"> ' + d["category"][j]["value"] + '</span>' + '</p>';
}
for(var k in nodeDetails ) {
if(nodeDetails[k]['id'] == d.id) {
htmlText = htmlText + '<p class="marginB5"><span class="canvas-label">' + 'Impurity' + ' :' + '</span>' + '<span class="canvas-value"> ' + nodeDetails[k]['impurity'].toFixed(4) + '</span>' + '</p>';
htmlText = htmlText + '<p class="marginB5"><span class="canvas-label">' + 'Gain' + ' :' + '</span>' + '<span class="canvas-value"> ' + nodeDetails[k]['gain'].toFixed(4) + '</span>' + '</p>';
}
}
var xcod = 0;
var ycod = 0;
// for (var j = 0; j < d["category"].length; j++) {
//
// var width = 150;
// if (j == 0) {
// htmlText = htmlText + '<svg width="' + width + '" height="10"><rect x="0" y="' + ycod + '" height="5" style="fill:' + color[j] + '" width="' + d["category"][j]["percent"] + '%" ></rect>';
// }
// else {
// xcod = xcod + (width * (d["category"][j - 1]["percent"] / 100));
//
// htmlText = htmlText + '<rect x="' + xcod + '" y="' + ycod + '" height="5" style="fill:' + color[j] + '" width="' + d["category"][j]["percent"] + '%" ></rect>';
// }
// if (j == d["category"].length - 1) {
// htmlText = htmlText + "</svg>"
// }
//
// }for (var j = 0; j < d["category"].length; j++) {
//
// var width = 150;
// if (j == 0) {
// htmlText = htmlText + '<svg width="' + width + '" height="10"><rect x="0" y="' + ycod + '" height="5" style="fill:' + color[j] + '" width="' + d["category"][j]["percent"] + '%" ></rect>';
// }
// else {
// xcod = xcod + (width * (d["category"][j - 1]["percent"] / 100));
//
// htmlText = htmlText + '<rect x="' + xcod + '" y="' + ycod + '" height="5" style="fill:' + color[j] + '" width="' + d["category"][j]["percent"] + '%" ></rect>';
// }
// if (j == d["category"].length - 1) {
// htmlText = htmlText + "</svg>"
// }
//
// }
}
else {
htmlText = htmlText + '<p class="node-rule text-ellipsis"><span class="canvas-label">' + d.name + '</span></p>';
htmlText = htmlText + '<p class="marginB5"><span class="canvas-label">' + 'DV Name' + ' :' + '</span>' + '<span class="canvas-value"> ' + d.var_name + '</span>' + '</p>';
htmlText = htmlText + '<p class="marginB5"><span class="canvas-label">' + 'Value' + ' :' + '</span>' + '<span class="canvas-value"> ' + d3.format(".3n")(d.value) + '</span>' + '</p>';
htmlText = htmlText + '<p class="marginB5"><span class="canvas-label">' + 'Size' + ' :' + '</span>' + '<span class="canvas-value"> ' + d.size + '</span>' + '</p>';
}
return htmlText;
});
// Transition nodes to their new position.
var nodeUpdate = node.transition()
.duration(duration)
.attr("transform", function (d) {
if (!isNaN(d.y))
return "translate(" + d.x + "," + d.y + ")";
});
nodeUpdate.select("rect")
.attr("width", rectW)
.attr("height", rectH)
.attr("shape-rendering", "crispEdges")
.attr("stroke", function (d) {
if (d.parent_id == null) {
return "#00725d";
}
else {
if ((d.children != undefined && d.children.length > 0 ) || (d._children != undefined && d._children.length > 0)) {
return "#3B78E7";
}
else {
return "#f04d4c";
}
}
})
.attr("stroke-width", 1)
.style("fill", function (d) {
if (d.parent_id == null) {
return "#e5f5f2";
}
else {
if ((d.children != undefined && d.children.length > 0 ) || (d._children != undefined && d._children.length > 0)) {
return "#d7e4fa";
}
else {
return "#fdeded";
}
}
});
nodeUpdate.select("text")
.style("fill-opacity", 1);
// Transition exiting nodes to the parent's new position.
var nodeExit = node.exit().transition()
.duration(duration)
.attr("transform", function (d) {
return "translate(" + source.x + "," + source.y + ")";
})
.remove();
nodeExit.select("rect")
.attr("width", rectW)
.attr("height", rectH)
.attr("stroke", "black")
.attr("stroke-width", 0.5);
nodeExit.select("text");
// Update the links…
var link = panCanvas.selectAll("path.link")
.data(links, function (d) {
return d.target.id;
});
// Enter any new links at the parent's previous position.
link.enter().insert("path", "g")
.attr("class", "link")
.attr("id", function (d) {
return ("id" + d.target.id);
})
.attr("x", rectW / 2)
.attr("y", rectH / 2)
.attr("stroke-width", function (d) {
var w = parseFloat(d.target.weight);
if (w > 1) {
w = 1;
}
if (w < 0.009) {
w = w * 5;
}
//console.log(w);
return (w * 50) + "px";
})
.attr("d", function (d) {
if (!isNaN(source.y0)) {
var o = {
x: source.x0,
y: source.y0
};
return diagonal({
source: o,
target: o
});
}
});
// Transition links to their new position.
link.transition()
.duration(duration)
.attr("d", diagonal);
// Transition exiting nodes to the parent's new position.
link.exit().transition()
.duration(duration)
.attr("d", function (d) {
var o = {
x: source.x,
y: source.y
};
return diagonal({
source: o,
target: o
});
})
.remove();
// Stash the old positions for transition.
nodes.forEach(function (d) {
d.x0 = d.x;
d.y0 = d.y;
});
var x = [];
var y = [];
for (var node in nodes) {
x.push(nodes[node]["x"]);
y.push(nodes[node]["y"]);
}
var xMin = Math.min.apply(null, x), xMax = Math.max.apply(null, x);
var yMin = Math.min.apply(null, y), yMax = Math.max.apply(null, y);
var w = ((xMax - xMin) + 200);
var h = ((yMax - yMin) + 200);
var xOffset = -(xMin);
$("div.inner").attr("style", "width:" + 100 + "%;height:" + 400 + "px");
if (show_top_scroll == true) {
$("div.topscroll").attr("style", "width:" + w + "px");
$(".wrapper-1").scroll(function () {
$(".outer").scrollLeft($(".wrapper-1").scrollLeft());
});
$(".outer").scroll(function () {
$(".wrapper-1").scrollLeft($(".outer").scrollLeft());
});
}
$(".svg-child").attr("transform", "translate(" + xOffset + ", 20)");
}
//Redraw for zoom
function redraw() {
//console.log("here", d3.event.translate, d3.event.scale);
svg.attr("transform",
"translate(" + d3.event.translate + ")"
+ " scale(" + d3.event.scale + ")");
}
// });
// INSTANCE PROPERTY SETUP
//
// Your library likely has some instance-specific properties. The value of
// these properties can depend on any number of things, such as properties
// passed in via opt_config or global state. Whatever the case, the values
// should be set in this constructor.
// Instance variables that have a leading underscore mean that they should
// not be modified outside of the library. They can be freely modified
// internally, however. If an instance variable will likely be accessed
// outside of the library, consider making a public getter function for it.
this._readOnlyVar = 'read only';
// Instance variables that do not have an underscore prepended are
// considered to be part of the library's public API. External code may
// change the value of these variables freely.
this.readAndWrite = 'read and write';
return this;
};
// LIBRARY PROTOTYPE METHODS
//
// These methods define the public API.
/**
* An example of a protoype method.
* @return {string}
*/
EasyTree.prototype.getReadOnlyVar = function () {
return this._readOnlyVar;
};
/**
* This is an example of a chainable method. That means that the return
* value of this function is the library instance itself (`this`). This lets
* you do chained method calls like this:
*
* var myEasyTree = new EasyTree();
* myEasyTree
* .chainableMethod()
* .chainableMethod();
*
* @return {EasyTree}
*/
EasyTree.prototype.chainableMethod = function () {
return this;
};
// DEBUG CODE
//
// With compiler directives, you can wrap code in a conditional check to
// ensure that it does not get included in the compiled binaries. This is
// useful for exposing certain properties and methods that are needed during
// development and testing, but should be private in the compiled binaries.
if (DEBUG) {
GLOBAL.corePrivateMethod = corePrivateMethod;
}
}
// Your library may have many modules. How you organize the modules is up to
// you, but generally speaking it's best if each module addresses a specific
// concern. No module should need to know about the implementation details of
// any other module.
// Note: You must name this function something unique. If you end up
// copy/pasting this file, the last function defined will clobber the previous
// one.
function initEasyTreeModule(context) {
'use strict';
var EasyTree = context.EasyTree;
// A library module can do two things to the EasyTree Object: It can extend
// the prototype to add more methods, and it can add static properties. This
// is useful if your library needs helper methods.
// PRIVATE MODULE CONSTANTS
//
var MODULE_CONSTANT = true;
// PRIVATE MODULE METHODS
//
/**
* An example of a private method. Feel free to remove this.
*/
function modulePrivateMethod() {
return;
}
// LIBRARY STATIC PROPERTIES
//
/**
* An example of a static EasyTree property. This particular static property
* is also an instantiable Object.
* @constructor
*/
EasyTree.EasyTreeHelper = function () {
return this;
};
// LIBRARY PROTOTYPE EXTENSIONS
//
// A module can extend the prototype of the EasyTree Object.
/**
* An example of a prototype method.
* @return {string}
*/
EasyTree.prototype.alternateGetReadOnlyVar = function () {
// Note that a module can access all of the EasyTree instance variables with
// the `this` keyword.
return this._readOnlyVar;
};
if (DEBUG) {
// DEBUG CODE
//
// Each module can have its own debugging section. They all get compiled
// out of the binary.
}
}
/**
* Submodules are similar to modules, only they do not use the same namespace as
* the Core, but defined a sub-namespace of their own.
* @param {Object} The Object that the library gets attached to in
* library.init.js. If the library was not loaded with an AMD loader such as
* require.js, this is the global Object.
*/
function initEasyTreeSubmodule(context) {
'use strict';
var EasyTree = context.EasyTree;
/*
* The submodule constructor
* @param {Object} opt_config Contains any properties that should be used to
* configure this instance of the library.
* @constructor
*/
var submodule = EasyTree.Submodule = function (opt_config) {
// defines a temporary variable,
// living only as long as the constructor runs.
var constructorVariable = "Constructor Variable";
// set an instance variable
// will be available after constructor has run.
this.instanceVariable = null;
// an optional call to the private method
// at the end of the construction process
this._privateMethod(constructorVariable);
};
// LIBRARY PROTOTYPE EXTENSIONS
/**
* A public method of the submodule
* @param {object} a variable to be set to the instance variable
* @returns {object} the final value of the instance variable
*/
submodule.prototype.publicMethod = function (value) {
if (value !== undefined) {
this._privateMethod(value);
}
return this.instanceVariable;
};
/**
* a private instance method
* @param {object} a variable to be set to the instance variable
* @returns {object} the final value of the instance variable
*/
submodule.prototype._privateMethod = function (value) {
return this.instanceVariable = value;
};
}
/*global initEasyTreeCore initEasyTreeModule initEasyTreeSubmodule */
var initEasyTree = function (context) {
initEasyTreeCore(context);
initEasyTreeModule(context);
initEasyTreeSubmodule(context);
// Add a similar line as above for each module that you have. If you have a
// module named "Awesome Module," it should live in the file
// "src/library.awesome-module.js" with a wrapper function named
// "initAwesomeModule". That function should then be invoked here with:
//
// initAwesomeModule(context);
return context.EasyTree;
};
if (typeof define === 'function' && define.amd) {
// Expose EasyTree as an AMD module if it's loaded with RequireJS or
// similar.
define(function () {
return initEasyTree({});
});
} else {
// Load EasyTree normally (creating a EasyTree global) if not using an AMD
// loader.
initEasyTree(this);
}
}(d3, $));
|
import 'react';
import PropTypes from 'prop-types';
import { INITIAL, PENDING, OK, ERROR } from 'app-constants';
export const status = PropTypes.oneOf([INITIAL, PENDING, OK, ERROR]);
|
// autoComplete1.js
//
// This is a simple test script that does the following tests:
// open a website
// validate title
// enter first 2 letter 'Be' to input
// wait for autocomplete to open
// click on entry 'Bengals'
// verify input is 'Cincinnati Bengals'
//
//
// To Run:
// $ mocha autoComplete1.js
// Updated to support version >4 of webdriverio
// required libraries
var webdriverio = require('webdriverio'),
should = require('should');
// a test script block or suite
describe('Autocomplete test for Web Driver IO - Tutorial Test Page Website', function() {
// set timeout to 10 seconds
this.timeout(10000);
var driver = {};
// hook to run before tests
before( function () {
// check for global browser (grunt + grunt-webdriver)
if(typeof browser === "undefined") {
// load the driver for browser
driver = webdriverio.remote({ desiredCapabilities: {browserName: 'firefox'} });
return driver.init();
} else {
// grunt will load the browser driver
driver = browser;
return;
}
});
// a test spec - "specification"
it('should be load correct page and title', function () {
// load page, then call function()
return driver
.url('http://tlkeith.com/WebDriverIOTutorialTest.html')
// get title, then pass title to function()
.getTitle().then( function (title) {
// verify title
(title).should.be.equal("Web Driver IO - Tutorial Test Page");
// uncomment for console debug
// console.log('Current Page Title: ' + title);
});
});
// Set the input to "Be"
it('should set input to Be', function () {
return driver
.setValue("#autocomplete", "Be")
.getValue("#autocomplete").then( function (e) {
console.log("Set input to: " + e);
(e).should.be.equal("Be");
});
});
// Select from auto completion list
it('should select auto completion', function () {
// wait for auto complete to open
return driver
.waitForVisible("#ui-id-1", 5000)
// there should be 2 autocomplete items: Bears, Bengals
// select the second entry: Bengals
.getText("//ul[@id='ui-id-1']/li[2]").then( function(e) {
console.log('Text: ' + e);
})
.click("//ul[@id='ui-id-1']/li[2]")
.getValue("#autocomplete").then( function (e) {
// the autocomplete will add the city name to the
console.log("Input: " + e);
(e).should.be.equal("Cincinnati Bengals");
});
});
// a "hook" to run after all tests in this block
after(function() {
if(typeof browser === "undefined") {
return driver.end();
} else {
return;
}
});
});
|
export default () => ({
error: '',
isLoading: false,
retrieved: null,
updated: null,
violations: null,
});
|
var path = require("path");
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var webpack = require("webpack");
module.exports = {
entry: {
app: './js/main.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['env']
// plugins: [require('babel-plugin-transform-object-rest-spread')]
}
}
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: 'css-loader?importLoaders=1!postcss-loader'
})
},
{
test: /\.woff$/,
loader: 'file-loader',
options: {
limit: 50000,
// Output below fonts directory
name: 'fonts/[name].[ext]',
},
},
]
},
output: {
path: path.join(__dirname, "./../static/dist/"),
filename: 'js/[name].bundle.[hash].js',
},
resolve: {
modules: [path.resolve(__dirname, 'src'), 'node_modules'],
},
plugins: [
new ExtractTextPlugin({
filename: (getPath) => {
return getPath('css/[name].[contenthash].css');
},
allChunks: true
})],
watchOptions: {
watch: true
}
}
|
(()=>{var e=document.getElementById("statusEnabled"),n=document.getElementById("statusDisabled"),c=function(e){chrome.storage.sync.set({pluginEnabled:e}),chrome.tabs.query({active:!0,currentWindow:!0},(function(e){chrome.tabs.executeScript(e[0].id,{code:"window.location.reload()"}),window.close()}))};chrome.storage.sync.get("pluginEnabled",(function(c){c.pluginEnabled?e.checked=!0:n.checked=!0})),e.onchange=function(e){c(e.target.checked)},n.onchange=function(e){c(!e.target.checked)}})();
|
const fetch = require("node-fetch");
fetch("http://jsonplaceholder.typicode.com/posts/1")
.then(response => response.json())
.then(post => post.title)
.then(x => console.log("Title", x) )
|
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var User = require('./user.js');
var Role = new Schema({
name: {
required: true,
type: String,
trim: true,
unique: true
},
pretty_name: {
required: true,
type: String,
trim: true,
unique: true
},
created_by: {
type: Schema.Types.ObjectId,
ref: 'User'
}
}, {
timestamps: true
});
module.exports = mongoose.model('Role', Role);
|
import test from 'ava';
test.todo("user profile route");
test.todo("repo contributes route");
test.todo("not found route");
|
import toDate from '../toDate/index.js'
import isLeapYear from '../isLeapYear/index.js'
/**
* @name getDaysInYear
* @category Year Helpers
* @summary Get the number of days in a year of the given date.
*
* @description
* Get the number of days in a year of the given date.
*
* @param {Date|String|Number} date - the given date
* @param {Options} [options] - the object with options. See [Options]{@link https://date-fns.org/docs/Options}
* @param {0|1|2} [options.additionalDigits=2] - passed to `toDate`. See [toDate]{@link https://date-fns.org/docs/toDate}
* @returns {Number} the number of days in a year
* @throws {TypeError} 1 argument required
* @throws {RangeError} `options.additionalDigits` must be 0, 1 or 2
*
* @example
* // How many days are in 2012?
* var result = getDaysInYear(new Date(2012, 0, 1))
* //=> 366
*/
export default function getDaysInYear (dirtyDate, dirtyOptions) {
if (arguments.length < 1) {
throw new TypeError('1 argument required, but only ' + arguments.length + ' present')
}
var date = toDate(dirtyDate, dirtyOptions)
if (isNaN(date)) {
return NaN
}
return isLeapYear(date, dirtyOptions) ? 366 : 365
}
|
//jshint esversion: 6
Package.describe({
name: 'elmarti:video-chat',
version: '2.3.2',
summary: 'Simple WebRTC Video Chat for your app.',
git: 'https://github.com/elmarti/meteor-video-chat',
documentation: 'README.md'
});
Package.onUse(api => {
Npm.depends({
"rtcfly": "0.1.8"
});
api.versionsFrom('1.5');
api.use('ecmascript');
api.use('reactive-var');
api.use("rocketchat:streamer@0.6.2");
api.use("mizzao:user-status@0.6.7");
api.addFiles(['lib/publish.js'], "server");
api.addFiles(['lib/index.server.js'], 'server');
api.mainModule('meteor.js', 'client');
api.mainModule('lib/server.interface.js', 'server');
});
|
(function() {
var EPOCHS, MONTHS, SLIDE_DURATION, coverage_data, make_graph, options, relative_date, slide;
EPOCHS = [["second", 1000], ["minute", 60 * 1000], ["hour", 60 * 60 * 1000], ["day", 24 * 60 * 60 * 1000], ["month", 30.4 * 24 * 60 * 60 * 1000], ["year", 12 * 30.4 * 24 * 60 * 60 * 1000]];
MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
relative_date = function(date) {
var difference, epoch, last, now, num, plural, time, _i, _len, _ref;
now = (new Date()).getTime();
difference = Math.abs(now - date);
if (difference < EPOCHS[0][1]) {
return "now";
} else {
last = EPOCHS[0];
}
_ref = EPOCHS.slice(1, EPOCHS.length);
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
epoch = _ref[_i];
num = Math.round(difference / last[1]);
if ((last[1] <= difference && difference <= epoch[1])) {
break;
} else {
last = epoch;
}
}
plural = num !== 1 ? "s" : "";
time = now > date ? " ago" : " from now";
return num + " " + last[0] + plural + time;
};
$.plot.formatDate = function(date, formatString, monthNames) {
return relative_date(date);
};
coverage_data = function(clogs) {
var clog, data, date, dta, file, lbl, name, _i, _j, _len, _len2, _ref, _results;
data = {};
for (_i = 0, _len = clogs.length; _i < _len; _i++) {
clog = clogs[_i];
date = clog["date"];
_ref = clog["coverage"];
for (_j = 0, _len2 = _ref.length; _j < _len2; _j++) {
file = _ref[_j];
name = file["name"];
if (!(data[name] != null)) {
data[name] = [];
}
data[name].push([date, parseInt(file["percent_coverage"])]);
}
}
_results = [];
for (lbl in data) {
dta = data[lbl];
_results.push({
label: lbl,
data: dta
});
}
return _results;
};
options = function(legend_selector) {
return {
colors: ["#0A3A4A", "#196674", "#33A6B2", "#9AC836", "#D0E64B"],
grid: {
borderWidth: 0,
clickable: true,
hoverable: true,
labelMargin: 30,
markings: []
},
legend: {
container: legend_selector,
noColumns: 3
},
selection: {
mode: "xy"
},
series: {
lines: {
show: true
},
points: {
show: true
},
threshold: {
below: 95,
color: "#E65042"
}
},
xaxis: {
mode: "time",
monthNames: MONTHS,
tickLength: 5
},
yaxis: {
max: 100,
position: "right"
}
};
};
make_graph = function(selector) {
var data;
data = $.parseJSON(json_clogs);
return $.plot($(selector), coverage_data(data), options("#graph-legend"));
};
SLIDE_DURATION = 500;
slide = function(slider, slide_in, slide_over, width) {
var shift;
$(slide_in).css("width", width);
shift = width - 60;
return $(slider).click(function() {
if ($(slide_in).is(":visible")) {
$(slide_over).animate({
left: "+=" + shift
});
return $(slide_in).hide(SLIDE_DURATION);
} else {
$(slide_in).show(SLIDE_DURATION);
return $(slide_over).animate({
left: "-=" + shift
});
}
});
};
$(document).ready(function() {
make_graph("#graph");
return slide("#settings-toggle", "#settings", "#content", 450);
});
}).call(this);
|
// flow-typed signature: e35304b0ba540c047de7886a8cd474a2
// flow-typed version: 9bd052d952/node-fetch_v1.x.x/flow_>=v0.25.x
declare module 'node-fetch' {
declare module.exports: (input: string | Request, init?: RequestOptions) => Promise<Response>;
}
|
'use strict';
(function() {
// Ideas Controller Spec
describe('Ideas Controller Tests', function() {
// Initialize global variables
var IdeasController,
scope,
$httpBackend,
$stateParams,
$location;
// The $resource service augments the response object with methods for updating and deleting the resource.
// If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
// the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
// When the toEqualData matcher compares two objects, it takes only object properties into
// account and ignores methods.
beforeEach(function() {
jasmine.addMatchers({
toEqualData: function(util, customEqualityTesters) {
return {
compare: function(actual, expected) {
return {
pass: angular.equals(actual, expected)
};
}
};
}
});
});
// Then we can start by loading the main application module
beforeEach(module(ApplicationConfiguration.applicationModuleName));
// The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
// This allows us to inject a service but then attach it to a variable
// with the same name as the service.
beforeEach(inject(function($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_) {
// Set a new global scope
scope = $rootScope.$new();
// Point global variables to injected services
$stateParams = _$stateParams_;
$httpBackend = _$httpBackend_;
$location = _$location_;
// Initialize the Ideas controller.
IdeasController = $controller('IdeasController', {
$scope: scope
});
}));
it('$scope.find() should create an array with at least one Idea object fetched from XHR', inject(function(Ideas) {
// Create sample Idea using the Ideas service
var sampleIdea = new Ideas({
name: 'New Idea'
});
// Create a sample Ideas array that includes the new Idea
var sampleIdeas = [sampleIdea];
// Set GET response
$httpBackend.expectGET('ideas').respond(sampleIdeas);
// Run controller functionality
scope.find();
$httpBackend.flush();
// Test scope value
expect(scope.ideas).toEqualData(sampleIdeas);
}));
it('$scope.findOne() should create an array with one Idea object fetched from XHR using a ideaId URL parameter', inject(function(Ideas) {
// Define a sample Idea object
var sampleIdea = new Ideas({
name: 'New Idea'
});
// Set the URL parameter
$stateParams.ideaId = '525a8422f6d0f87f0e407a33';
// Set GET response
$httpBackend.expectGET(/ideas\/([0-9a-fA-F]{24})$/).respond(sampleIdea);
// Run controller functionality
scope.findOne();
$httpBackend.flush();
// Test scope value
expect(scope.idea).toEqualData(sampleIdea);
}));
it('$scope.create() with valid form data should send a POST request with the form input values and then locate to new object URL', inject(function(Ideas) {
// Create a sample Idea object
var sampleIdeaPostData = new Ideas({
name: 'New Idea'
});
// Create a sample Idea response
var sampleIdeaResponse = new Ideas({
_id: '525cf20451979dea2c000001',
name: 'New Idea'
});
// Fixture mock form input values
scope.name = 'New Idea';
// Set POST response
$httpBackend.expectPOST('ideas', sampleIdeaPostData).respond(sampleIdeaResponse);
// Run controller functionality
scope.create();
$httpBackend.flush();
// Test form inputs are reset
expect(scope.name).toEqual('');
// Test URL redirection after the Idea was created
expect($location.path()).toBe('/ideas/' + sampleIdeaResponse._id);
}));
it('$scope.update() should update a valid Idea', inject(function(Ideas) {
// Define a sample Idea put data
var sampleIdeaPutData = new Ideas({
_id: '525cf20451979dea2c000001',
name: 'New Idea'
});
// Mock Idea in scope
scope.idea = sampleIdeaPutData;
// Set PUT response
$httpBackend.expectPUT(/ideas\/([0-9a-fA-F]{24})$/).respond();
// Run controller functionality
scope.update();
$httpBackend.flush();
// Test URL location to new object
expect($location.path()).toBe('/ideas/' + sampleIdeaPutData._id);
}));
it('$scope.remove() should send a DELETE request with a valid ideaId and remove the Idea from the scope', inject(function(Ideas) {
// Create new Idea object
var sampleIdea = new Ideas({
_id: '525a8422f6d0f87f0e407a33'
});
// Create new Ideas array and include the Idea
scope.ideas = [sampleIdea];
// Set expected DELETE response
$httpBackend.expectDELETE(/ideas\/([0-9a-fA-F]{24})$/).respond(204);
// Run controller functionality
scope.remove(sampleIdea);
$httpBackend.flush();
// Test array after successful delete
expect(scope.ideas.length).toBe(0);
}));
});
}());
|
import { compile } from "../htmlbars-compiler/compiler";
import { forEach } from "../htmlbars-util/array-utils";
import defaultHooks from "../htmlbars-runtime/hooks";
import { merge } from "../htmlbars-util/object-utils";
import DOMHelper from "../dom-helper";
import { normalizeInnerHTML, getTextContent, equalTokens } from "../htmlbars-test-helpers";
var xhtmlNamespace = "http://www.w3.org/1999/xhtml",
svgNamespace = "http://www.w3.org/2000/svg";
var hooks, helpers, partials, env;
// IE8 doesn't correctly handle these html strings
var innerHTMLSupportsCustomTags = (function() {
var div = document.createElement('div');
div.innerHTML = '<x-bar></x-bar>';
return normalizeInnerHTML(div.innerHTML) === '<x-bar></x-bar>';
})();
// IE8 doesn't handle newlines in innerHTML correctly
var innerHTMLHandlesNewlines = (function() {
var div = document.createElement('div');
div.innerHTML = 'foo\n\nbar';
return div.innerHTML.length === 8;
})();
function registerHelper(name, callback) {
helpers[name] = callback;
}
function registerPartial(name, html) {
partials[name] = compile(html);
}
function compilesTo(html, expected, context) {
var template = compile(html);
var fragment = template.render(context, env, { contextualElement: document.body }).fragment;
equalTokens(fragment, expected === undefined ? html : expected);
return fragment;
}
function commonSetup() {
hooks = merge({}, defaultHooks);
helpers = {};
partials = {};
env = {
dom: new DOMHelper(),
hooks: hooks,
helpers: helpers,
partials: partials,
useFragmentCache: true
};
}
QUnit.module("HTML-based compiler (output)", {
beforeEach: commonSetup
});
test("Simple content produces a document fragment", function() {
var template = compile("content");
var fragment = template.render({}, env).fragment;
equalTokens(fragment, "content");
});
test("Simple elements are created", function() {
var template = compile("<h1>hello!</h1><div>content</div>");
var fragment = template.render({}, env).fragment;
equalTokens(fragment, "<h1>hello!</h1><div>content</div>");
});
test("Simple elements can be re-rendered", function() {
var template = compile("<h1>hello!</h1><div>content</div>");
var result = template.render({}, env);
var fragment = result.fragment;
var oldFirstChild = fragment.firstChild;
result.revalidate();
strictEqual(fragment.firstChild, oldFirstChild);
equalTokens(fragment, "<h1>hello!</h1><div>content</div>");
});
test("Simple elements can have attributes", function() {
var template = compile("<div class='foo' id='bar'>content</div>");
var fragment = template.render({}, env).fragment;
equalTokens(fragment, '<div class="foo" id="bar">content</div>');
});
test("Simple elements can have an empty attribute", function() {
var template = compile("<div class=''>content</div>");
var fragment = template.render({}, env).fragment;
equalTokens(fragment, '<div class="">content</div>');
});
test("presence of `disabled` attribute without value marks as disabled", function() {
var template = compile('<input disabled>');
var inputNode = template.render({}, env).fragment.firstChild;
ok(inputNode.disabled, 'disabled without value set as property is true');
});
test("Null quoted attribute value calls toString on the value", function() {
var template = compile('<input disabled="{{isDisabled}}">');
var inputNode = template.render({isDisabled: null}, env).fragment.firstChild;
ok(inputNode.disabled, 'string of "null" set as property is true');
});
test("Null unquoted attribute value removes that attribute", function() {
var template = compile('<input disabled={{isDisabled}}>');
var inputNode = template.render({isDisabled: null}, env).fragment.firstChild;
equalTokens(inputNode, '<input>');
});
test("unquoted attribute string is just that", function() {
var template = compile('<input value=funstuff>');
var inputNode = template.render({}, env).fragment.firstChild;
equal(inputNode.tagName, 'INPUT', 'input tag');
equal(inputNode.value, 'funstuff', 'value is set as property');
});
test("unquoted attribute expression is string", function() {
var template = compile('<input value={{funstuff}}>');
var inputNode = template.render({funstuff: "oh my"}, env).fragment.firstChild;
equal(inputNode.tagName, 'INPUT', 'input tag');
equal(inputNode.value, 'oh my', 'string is set to property');
});
test("unquoted attribute expression works when followed by another attribute", function() {
var template = compile('<div foo={{funstuff}} name="Alice"></div>');
var divNode = template.render({funstuff: "oh my"}, env).fragment.firstChild;
equalTokens(divNode, '<div foo="oh my" name="Alice"></div>');
});
test("Unquoted attribute value with multiple nodes throws an exception", function () {
expect(4);
QUnit.throws(function() { compile('<img class=foo{{bar}}>'); }, expectedError(1));
QUnit.throws(function() { compile('<img class={{foo}}{{bar}}>'); }, expectedError(1));
QUnit.throws(function() { compile('<img \nclass={{foo}}bar>'); }, expectedError(2));
QUnit.throws(function() { compile('<div \nclass\n=\n{{foo}}&bar ></div>'); }, expectedError(4));
function expectedError(line) {
return new Error("Unquoted attribute value must be a single string or mustache (on line " + line + ")");
}
});
test("Simple elements can have arbitrary attributes", function() {
var template = compile("<div data-some-data='foo'>content</div>");
var divNode = template.render({}, env).fragment.firstChild;
equalTokens(divNode, '<div data-some-data="foo">content</div>');
});
test("checked attribute and checked property are present after clone and hydrate", function() {
var template = compile("<input checked=\"checked\">");
var inputNode = template.render({}, env).fragment.firstChild;
equal(inputNode.tagName, 'INPUT', 'input tag');
equal(inputNode.checked, true, 'input tag is checked');
});
function shouldBeVoid(tagName) {
var html = "<" + tagName + " data-foo='bar'><p>hello</p>";
var template = compile(html);
var fragment = template.render({}, env).fragment;
var div = document.createElement("div");
div.appendChild(fragment.cloneNode(true));
var tag = '<' + tagName + ' data-foo="bar">';
var closing = '</' + tagName + '>';
var extra = "<p>hello</p>";
html = normalizeInnerHTML(div.innerHTML);
QUnit.push((html === tag + extra) || (html === tag + closing + extra), html, tag + closing + extra, tagName + " should be a void element");
}
test("Void elements are self-closing", function() {
var voidElements = "area base br col command embed hr img input keygen link meta param source track wbr";
forEach(voidElements.split(" "), function(tagName) {
shouldBeVoid(tagName);
});
});
test("The compiler can handle nesting", function() {
var html = '<div class="foo"><p><span id="bar" data-foo="bar">hi!</span></p></div> More content';
var template = compile(html);
var fragment = template.render({}, env).fragment;
equalTokens(fragment, html);
});
test("The compiler can handle quotes", function() {
compilesTo('<div>"This is a title," we\'re on a boat</div>');
});
test("The compiler can handle backslashes", function() {
compilesTo('<div>This is a backslash: \\</div>');
});
if (innerHTMLHandlesNewlines) {
test("The compiler can handle newlines", function() {
compilesTo("<div>common\n\nbro</div>");
});
}
test("The compiler can handle comments", function() {
compilesTo("<div>{{! Better not break! }}content</div>", '<div>content</div>', {});
});
test("The compiler can handle HTML comments", function() {
compilesTo('<div><!-- Just passing through --></div>');
});
test("The compiler can handle HTML comments with mustaches in them", function() {
compilesTo('<div><!-- {{foo}} --></div>', '<div><!-- {{foo}} --></div>', { foo: 'bar' });
});
test("The compiler can handle HTML comments with complex mustaches in them", function() {
compilesTo('<div><!-- {{foo bar baz}} --></div>', '<div><!-- {{foo bar baz}} --></div>', { foo: 'bar' });
});
test("The compiler can handle HTML comments with multi-line mustaches in them", function() {
compilesTo('<div><!-- {{#each foo as |bar|}}\n{{bar}}\n\n{{/each}} --></div>');
});
test('The compiler can handle comments with no parent element', function() {
compilesTo('<!-- {{foo}} -->');
});
// TODO: Revisit partial syntax.
// test("The compiler can handle partials in handlebars partial syntax", function() {
// registerPartial('partial_name', "<b>Partial Works!</b>");
// compilesTo('<div>{{>partial_name}} Plaintext content</div>', '<div><b>Partial Works!</b> Plaintext content</div>', {});
// });
test("The compiler can handle partials in helper partial syntax", function() {
registerPartial('partial_name', "<b>Partial Works!</b>");
compilesTo('<div>{{partial "partial_name"}} Plaintext content</div>', '<div><b>Partial Works!</b> Plaintext content</div>', {});
});
test("The compiler can handle simple handlebars", function() {
compilesTo('<div>{{title}}</div>', '<div>hello</div>', { title: 'hello' });
});
test("The compiler can handle escaping HTML", function() {
compilesTo('<div>{{title}}</div>', '<div><strong>hello</strong></div>', { title: '<strong>hello</strong>' });
});
test("The compiler can handle unescaped HTML", function() {
compilesTo('<div>{{{title}}}</div>', '<div><strong>hello</strong></div>', { title: '<strong>hello</strong>' });
});
test("The compiler can handle top-level unescaped HTML", function() {
compilesTo('{{{html}}}', '<strong>hello</strong>', { html: '<strong>hello</strong>' });
});
test("The compiler can handle top-level unescaped tr", function() {
var template = compile('{{{html}}}');
var context = { html: '<tr><td>Yo</td></tr>' };
var fragment = template.render(context, env, { contextualElement: document.createElement('table') }).fragment;
equal(
fragment.firstChild.nextSibling.tagName, 'TR',
"root tr is present" );
});
test("The compiler can handle top-level unescaped td inside tr contextualElement", function() {
var template = compile('{{{html}}}');
var context = { html: '<td>Yo</td>' };
var fragment = template.render(context, env, { contextualElement: document.createElement('tr') }).fragment;
equal(
fragment.firstChild.nextSibling.tagName, 'TD',
"root td is returned" );
});
test("The compiler can handle unescaped tr in top of content", function() {
registerHelper('test', function() {
return this.yield();
});
var template = compile('{{#test}}{{{html}}}{{/test}}');
var context = { html: '<tr><td>Yo</td></tr>' };
var fragment = template.render(context, env, { contextualElement: document.createElement('table') }).fragment;
equal(
fragment.firstChild.nextSibling.nextSibling.tagName, 'TR',
"root tr is present" );
});
test("The compiler can handle unescaped tr inside fragment table", function() {
registerHelper('test', function() {
return this.yield();
});
var template = compile('<table>{{#test}}{{{html}}}{{/test}}</table>');
var context = { html: '<tr><td>Yo</td></tr>' };
var fragment = template.render(context, env, { contextualElement: document.createElement('div') }).fragment;
var tableNode = fragment.firstChild;
equal(
tableNode.firstChild.nextSibling.tagName, 'TR',
"root tr is present" );
});
test("The compiler can handle simple helpers", function() {
registerHelper('testing', function(params) {
return params[0];
});
compilesTo('<div>{{testing title}}</div>', '<div>hello</div>', { title: 'hello' });
});
test("Helpers propagate the owner render node", function() {
registerHelper('id', function() {
return this.yield();
});
var template = compile('<div>{{#id}}<p>{{#id}}<span>{{#id}}{{name}}{{/id}}</span>{{/id}}</p>{{/id}}</div>');
var context = { name: "Tom Dale" };
var result = template.render(context, env);
equalTokens(result.fragment, '<div><p><span>Tom Dale</span></p></div>');
var root = result.root;
strictEqual(root, root.childNodes[0].ownerNode);
strictEqual(root, root.childNodes[0].childNodes[0].ownerNode);
strictEqual(root, root.childNodes[0].childNodes[0].childNodes[0].ownerNode);
});
test("The compiler can handle sexpr helpers", function() {
registerHelper('testing', function(params) {
return params[0] + "!";
});
compilesTo('<div>{{testing (testing "hello")}}</div>', '<div>hello!!</div>', {});
});
test("The compiler can handle multiple invocations of sexprs", function() {
registerHelper('testing', function(params) {
return "" + params[0] + params[1];
});
compilesTo('<div>{{testing (testing "hello" foo) (testing (testing bar "lol") baz)}}</div>', '<div>helloFOOBARlolBAZ</div>', { foo: "FOO", bar: "BAR", baz: "BAZ" });
});
test("The compiler passes along the hash arguments", function() {
registerHelper('testing', function(params, hash) {
return hash.first + '-' + hash.second;
});
compilesTo('<div>{{testing first="one" second="two"}}</div>', '<div>one-two</div>');
});
test("second render respects whitespace", function () {
var template = compile('Hello {{ foo }} ');
template.render({}, env, { contextualElement: document.createElement('div') });
var fragment = template.render({}, env, { contextualElement: document.createElement('div') }).fragment;
equal(fragment.childNodes.length, 3, 'fragment contains 3 text nodes');
equal(getTextContent(fragment.childNodes[0]), 'Hello ', 'first text node ends with one space character');
equal(getTextContent(fragment.childNodes[2]), ' ', 'last text node contains one space character');
});
test("Morphs are escaped correctly", function() {
registerHelper('testing-unescaped', function(params) {
return params[0];
});
registerHelper('testing-escaped', function(params) {
if (this.yield) {
return this.yield();
}
return params[0];
});
compilesTo('<div>{{{testing-unescaped "<span>hi</span>"}}}</div>', '<div><span>hi</span></div>');
compilesTo('<div>{{testing-escaped "<hi>"}}</div>', '<div><hi></div>');
compilesTo('<div>{{#testing-escaped}}<em></em>{{/testing-escaped}}</div>', '<div><em></em></div>');
compilesTo('<div><testing-escaped><em></em></testing-escaped></div>', '<div><em></em></div>');
});
test("Attributes can use computed values", function() {
compilesTo('<a href="{{url}}">linky</a>', '<a href="linky.html">linky</a>', { url: 'linky.html' });
});
test("Mountain range of nesting", function() {
var context = { foo: "FOO", bar: "BAR", baz: "BAZ", boo: "BOO", brew: "BREW", bat: "BAT", flute: "FLUTE", argh: "ARGH" };
compilesTo('{{foo}}<span></span>', 'FOO<span></span>', context);
compilesTo('<span></span>{{foo}}', '<span></span>FOO', context);
compilesTo('<span>{{foo}}</span>{{foo}}', '<span>FOO</span>FOO', context);
compilesTo('{{foo}}<span>{{foo}}</span>{{foo}}', 'FOO<span>FOO</span>FOO', context);
compilesTo('{{foo}}<span></span>{{foo}}', 'FOO<span></span>FOO', context);
compilesTo('{{foo}}<span></span>{{bar}}<span><span><span>{{baz}}</span></span></span>',
'FOO<span></span>BAR<span><span><span>BAZ</span></span></span>', context);
compilesTo('{{foo}}<span></span>{{bar}}<span>{{argh}}<span><span>{{baz}}</span></span></span>',
'FOO<span></span>BAR<span>ARGH<span><span>BAZ</span></span></span>', context);
compilesTo('{{foo}}<span>{{bar}}<a>{{baz}}<em>{{boo}}{{brew}}</em>{{bat}}</a></span><span><span>{{flute}}</span></span>{{argh}}',
'FOO<span>BAR<a>BAZ<em>BOOBREW</em>BAT</a></span><span><span>FLUTE</span></span>ARGH', context);
});
// test("Attributes can use computed paths", function() {
// compilesTo('<a href="{{post.url}}">linky</a>', '<a href="linky.html">linky</a>', { post: { url: 'linky.html' }});
// });
/*
test("It is possible to use RESOLVE_IN_ATTR for data binding", function() {
var callback;
registerHelper('RESOLVE_IN_ATTR', function(parts, options) {
return boundValue(function(c) {
callback = c;
return this[parts[0]];
}, this);
});
var object = { url: 'linky.html' };
var fragment = compilesTo('<a href="{{url}}">linky</a>', '<a href="linky.html">linky</a>', object);
object.url = 'clippy.html';
callback();
equalTokens(fragment, '<a href="clippy.html">linky</a>');
object.url = 'zippy.html';
callback();
equalTokens(fragment, '<a href="zippy.html">linky</a>');
});
*/
test("Attributes can be populated with helpers that generate a string", function() {
registerHelper('testing', function(params) {
return params[0];
});
compilesTo('<a href="{{testing url}}">linky</a>', '<a href="linky.html">linky</a>', { url: 'linky.html'});
});
/*
test("A helper can return a stream for the attribute", function() {
registerHelper('testing', function(path, options) {
return streamValue(this[path]);
});
compilesTo('<a href="{{testing url}}">linky</a>', '<a href="linky.html">linky</a>', { url: 'linky.html'});
});
*/
test("Attribute helpers take a hash", function() {
registerHelper('testing', function(params, hash) {
return hash.path;
});
compilesTo('<a href="{{testing path=url}}">linky</a>', '<a href="linky.html">linky</a>', { url: 'linky.html' });
});
/*
test("Attribute helpers can use the hash for data binding", function() {
var callback;
registerHelper('testing', function(path, hash, options) {
return boundValue(function(c) {
callback = c;
return this[path] ? hash.truthy : hash.falsy;
}, this);
});
var object = { on: true };
var fragment = compilesTo('<div class="{{testing on truthy="yeah" falsy="nope"}}">hi</div>', '<div class="yeah">hi</div>', object);
object.on = false;
callback();
equalTokens(fragment, '<div class="nope">hi</div>');
});
*/
test("Attributes containing multiple helpers are treated like a block", function() {
registerHelper('testing', function(params) {
return params[0];
});
compilesTo('<a href="http://{{foo}}/{{testing bar}}/{{testing "baz"}}">linky</a>', '<a href="http://foo.com/bar/baz">linky</a>', { foo: 'foo.com', bar: 'bar' });
});
test("Attributes containing a helper are treated like a block", function() {
expect(2);
registerHelper('testing', function(params) {
deepEqual(params, [123]);
return "example.com";
});
compilesTo('<a href="http://{{testing 123}}/index.html">linky</a>', '<a href="http://example.com/index.html">linky</a>', { person: { url: 'example.com' } });
});
/*
test("It is possible to trigger a re-render of an attribute from a child resolution", function() {
var callback;
registerHelper('RESOLVE_IN_ATTR', function(path, options) {
return boundValue(function(c) {
callback = c;
return this[path];
}, this);
});
var context = { url: "example.com" };
var fragment = compilesTo('<a href="http://{{url}}/index.html">linky</a>', '<a href="http://example.com/index.html">linky</a>', context);
context.url = "www.example.com";
callback();
equalTokens(fragment, '<a href="http://www.example.com/index.html">linky</a>');
});
test("A child resolution can pass contextual information to the parent", function() {
var callback;
registerHelper('RESOLVE_IN_ATTR', function(path, options) {
return boundValue(function(c) {
callback = c;
return this[path];
}, this);
});
var context = { url: "example.com" };
var fragment = compilesTo('<a href="http://{{url}}/index.html">linky</a>', '<a href="http://example.com/index.html">linky</a>', context);
context.url = "www.example.com";
callback();
equalTokens(fragment, '<a href="http://www.example.com/index.html">linky</a>');
});
test("Attribute runs can contain helpers", function() {
var callbacks = [];
registerHelper('RESOLVE_IN_ATTR', function(path, options) {
return boundValue(function(c) {
callbacks.push(c);
return this[path];
}, this);
});
registerHelper('testing', function(path, options) {
return boundValue(function(c) {
callbacks.push(c);
if (options.paramTypes[0] === 'id') {
return this[path] + '.html';
} else {
return path;
}
}, this);
});
var context = { url: "example.com", path: 'index' };
var fragment = compilesTo('<a href="http://{{url}}/{{testing path}}/{{testing "linky"}}">linky</a>', '<a href="http://example.com/index.html/linky">linky</a>', context);
context.url = "www.example.com";
context.path = "yep";
forEach(callbacks, function(callback) { callback(); });
equalTokens(fragment, '<a href="http://www.example.com/yep.html/linky">linky</a>');
context.url = "nope.example.com";
context.path = "nope";
forEach(callbacks, function(callback) { callback(); });
equalTokens(fragment, '<a href="http://nope.example.com/nope.html/linky">linky</a>');
});
*/
test("A simple block helper can return the default document fragment", function() {
registerHelper('testing', function() { return this.yield(); });
compilesTo('{{#testing}}<div id="test">123</div>{{/testing}}', '<div id="test">123</div>');
});
// TODO: NEXT
test("A simple block helper can return text", function() {
registerHelper('testing', function() { return this.yield(); });
compilesTo('{{#testing}}test{{else}}not shown{{/testing}}', 'test');
});
test("A block helper can have an else block", function() {
registerHelper('testing', function(params, hash, options) {
return options.inverse.yield();
});
compilesTo('{{#testing}}Nope{{else}}<div id="test">123</div>{{/testing}}', '<div id="test">123</div>');
});
test("A block helper can pass a context to be used in the child", function() {
registerHelper('testing', function(params, hash, options) {
var context = { title: 'Rails is omakase' };
return options.template.render(context);
});
compilesTo('{{#testing}}<div id="test">{{title}}</div>{{/testing}}', '<div id="test">Rails is omakase</div>');
});
test("Block helpers receive hash arguments", function() {
registerHelper('testing', function(params, hash) {
if (hash.truth) {
return this.yield();
}
});
compilesTo('{{#testing truth=true}}<p>Yep!</p>{{/testing}}{{#testing truth=false}}<p>Nope!</p>{{/testing}}', '<p>Yep!</p><!---->');
});
test("Node helpers can modify the node", function() {
registerHelper('testing', function(params, hash, options) {
options.element.setAttribute('zomg', 'zomg');
});
compilesTo('<div {{testing}}>Node helpers</div>', '<div zomg="zomg">Node helpers</div>');
});
test("Node helpers can modify the node after one node appended by top-level helper", function() {
registerHelper('top-helper', function() {
return document.createElement('span');
});
registerHelper('attr-helper', function(params, hash, options) {
options.element.setAttribute('zomg', 'zomg');
});
compilesTo('<div {{attr-helper}}>Node helpers</div>{{top-helper}}', '<div zomg="zomg">Node helpers</div><span></span>');
});
test("Node helpers can modify the node after one node prepended by top-level helper", function() {
registerHelper('top-helper', function() {
return document.createElement('span');
});
registerHelper('attr-helper', function(params, hash, options) {
options.element.setAttribute('zomg', 'zomg');
});
compilesTo('{{top-helper}}<div {{attr-helper}}>Node helpers</div>', '<span></span><div zomg="zomg">Node helpers</div>');
});
test("Node helpers can modify the node after many nodes returned from top-level helper", function() {
registerHelper('top-helper', function() {
var frag = document.createDocumentFragment();
frag.appendChild(document.createElement('span'));
frag.appendChild(document.createElement('span'));
return frag;
});
registerHelper('attr-helper', function(params, hash, options) {
options.element.setAttribute('zomg', 'zomg');
});
compilesTo(
'{{top-helper}}<div {{attr-helper}}>Node helpers</div>',
'<span></span><span></span><div zomg="zomg">Node helpers</div>' );
});
test("Node helpers can be used for attribute bindings", function() {
registerHelper('testing', function(params, hash, options) {
var value = hash.href,
element = options.element;
element.setAttribute('href', value);
});
var object = { url: 'linky.html' };
var template = compile('<a {{testing href=url}}>linky</a>');
var result = template.render(object, env);
equalTokens(result.fragment, '<a href="linky.html">linky</a>');
object.url = 'zippy.html';
result.dirty();
result.revalidate();
equalTokens(result.fragment, '<a href="zippy.html">linky</a>');
});
test('Components - Called as helpers', function () {
registerHelper('x-append', function(params, hash) {
QUnit.deepEqual(hash, { text: "de" });
this.yield();
});
var object = { bar: 'e', baz: 'c' };
compilesTo('a<x-append text="d{{bar}}">b{{baz}}</x-append>f','abcf', object);
});
if (innerHTMLSupportsCustomTags) {
test('Components - Unknown helpers fall back to elements', function () {
var object = { size: 'med', foo: 'b' };
compilesTo('<x-bar class="btn-{{size}}">a{{foo}}c</x-bar>','<x-bar class="btn-med">abc</x-bar>', object);
});
test('Components - Text-only attributes work', function () {
var object = { foo: 'qux' };
compilesTo('<x-bar id="test">{{foo}}</x-bar>','<x-bar id="test">qux</x-bar>', object);
});
test('Components - Empty components work', function () {
compilesTo('<x-bar></x-bar>','<x-bar></x-bar>', {});
});
test('Components - Text-only dashed attributes work', function () {
var object = { foo: 'qux' };
compilesTo('<x-bar aria-label="foo" id="test">{{foo}}</x-bar>','<x-bar aria-label="foo" id="test">qux</x-bar>', object);
});
}
test('Repaired text nodes are ensured in the right place', function () {
var object = { a: "A", b: "B", c: "C", d: "D" };
compilesTo('{{a}} {{b}}', 'A B', object);
compilesTo('<div>{{a}}{{b}}{{c}}wat{{d}}</div>', '<div>ABCwatD</div>', object);
compilesTo('{{a}}{{b}}<img><img><img><img>', 'AB<img><img><img><img>', object);
});
test("Simple elements can have dashed attributes", function() {
var template = compile("<div aria-label='foo'>content</div>");
var fragment = template.render({}, env).fragment;
equalTokens(fragment, '<div aria-label="foo">content</div>');
});
test("Block params", function() {
registerHelper('a', function() {
this.yieldIn(compile("A({{yield 'W' 'X1'}})"));
});
registerHelper('b', function() {
this.yieldIn(compile("B({{yield 'X2' 'Y'}})"));
});
registerHelper('c', function() {
this.yieldIn(compile("C({{yield 'Z'}})"));
});
var t = '{{#a as |w x|}}{{w}},{{x}} {{#b as |x y|}}{{x}},{{y}}{{/b}} {{w}},{{x}} {{#c as |z|}}{{x}},{{z}}{{/c}}{{/a}}';
compilesTo(t, 'A(W,X1 B(X2,Y) W,X1 C(X1,Z))', {});
});
test("Block params - Helper should know how many block params it was called with", function() {
expect(4);
registerHelper('count-block-params', function(params, hash, options) {
equal(options.template.arity, hash.count, 'Helpers should receive the correct number of block params in options.template.blockParams.');
});
compile('{{#count-block-params count=0}}{{/count-block-params}}').render({}, env, { contextualElement: document.body });
compile('{{#count-block-params count=1 as |x|}}{{/count-block-params}}').render({}, env, { contextualElement: document.body });
compile('{{#count-block-params count=2 as |x y|}}{{/count-block-params}}').render({}, env, { contextualElement: document.body });
compile('{{#count-block-params count=3 as |x y z|}}{{/count-block-params}}').render({}, env, { contextualElement: document.body });
});
test('Block params in HTML syntax', function () {
var layout = compile("BAR({{yield 'Xerxes' 'York' 'Zed'}})");
registerHelper('x-bar', function() {
this.yieldIn(layout);
});
compilesTo('<x-bar as |x y zee|>{{zee}},{{y}},{{x}}</x-bar>', 'BAR(Zed,York,Xerxes)', {});
});
test('Block params in HTML syntax - Throws exception if given zero parameters', function () {
expect(2);
QUnit.throws(function() {
compile('<x-bar as ||>foo</x-bar>');
}, /Cannot use zero block parameters: 'as \|\|'/);
QUnit.throws(function() {
compile('<x-bar as | |>foo</x-bar>');
}, /Cannot use zero block parameters: 'as \| \|'/);
});
test('Block params in HTML syntax - Works with a single parameter', function () {
registerHelper('x-bar', function() {
return this.yield(['Xerxes']);
});
compilesTo('<x-bar as |x|>{{x}}</x-bar>', 'Xerxes', {});
});
test('Block params in HTML syntax - Works with other attributes', function () {
registerHelper('x-bar', function(params, hash) {
deepEqual(hash, {firstName: 'Alice', lastName: 'Smith'});
});
compile('<x-bar firstName="Alice" lastName="Smith" as |x y|></x-bar>').render({}, env, { contextualElement: document.body });
});
test('Block params in HTML syntax - Ignores whitespace', function () {
expect(3);
registerHelper('x-bar', function() {
return this.yield(['Xerxes', 'York']);
});
compilesTo('<x-bar as |x y|>{{x}},{{y}}</x-bar>', 'Xerxes,York', {});
compilesTo('<x-bar as | x y|>{{x}},{{y}}</x-bar>', 'Xerxes,York', {});
compilesTo('<x-bar as | x y |>{{x}},{{y}}</x-bar>', 'Xerxes,York', {});
});
test('Block params in HTML syntax - Helper should know how many block params it was called with', function () {
expect(4);
registerHelper('count-block-params', function(params, hash, options) {
equal(options.template.arity, parseInt(hash.count, 10), 'Helpers should receive the correct number of block params in options.template.blockParams.');
});
compile('<count-block-params count="0"></count-block-params>').render({ count: 0 }, env, { contextualElement: document.body });
compile('<count-block-params count="1" as |x|></count-block-params>').render({ count: 1 }, env, { contextualElement: document.body });
compile('<count-block-params count="2" as |x y|></count-block-params>').render({ count: 2 }, env, { contextualElement: document.body });
compile('<count-block-params count="3" as |x y z|></count-block-params>').render({ count: 3 }, env, { contextualElement: document.body });
});
test("Block params in HTML syntax - Throws an error on invalid block params syntax", function() {
expect(3);
QUnit.throws(function() {
compile('<x-bar as |x y>{{x}},{{y}}</x-bar>');
}, /Invalid block parameters syntax: 'as |x y'/);
QUnit.throws(function() {
compile('<x-bar as |x| y>{{x}},{{y}}</x-bar>');
}, /Invalid block parameters syntax: 'as \|x\| y'/);
QUnit.throws(function() {
compile('<x-bar as |x| y|>{{x}},{{y}}</x-bar>');
}, /Invalid block parameters syntax: 'as \|x\| y\|'/);
});
test("Block params in HTML syntax - Throws an error on invalid identifiers for params", function() {
expect(3);
QUnit.throws(function() {
compile('<x-bar as |x foo.bar|></x-bar>');
}, /Invalid identifier for block parameters: 'foo\.bar' in 'as \|x foo\.bar|'/);
QUnit.throws(function() {
compile('<x-bar as |x "foo"|></x-bar>');
}, /Invalid identifier for block parameters: '"foo"' in 'as \|x "foo"|'/);
QUnit.throws(function() {
compile('<x-bar as |foo[bar]|></x-bar>');
}, /Invalid identifier for block parameters: 'foo\[bar\]' in 'as \|foo\[bar\]\|'/);
});
QUnit.module("HTML-based compiler (invalid HTML errors)", {
beforeEach: commonSetup
});
test("A helpful error message is provided for unclosed elements", function() {
expect(2);
QUnit.throws(function() {
compile('\n<div class="my-div" \n foo={{bar}}>\n<span>\n</span>\n');
}, /Unclosed element `div` \(on line 2\)\./);
QUnit.throws(function() {
compile('\n<div class="my-div">\n<span>\n');
}, /Unclosed element `span` \(on line 3\)\./);
});
test("A helpful error message is provided for unmatched end tags", function() {
expect(2);
QUnit.throws(function() {
compile("</p>");
}, /Closing tag `p` \(on line 1\) without an open tag\./);
QUnit.throws(function() {
compile("<em>{{ foo }}</em> \n {{ bar }}\n</div>");
}, /Closing tag `div` \(on line 3\) without an open tag\./);
});
test("A helpful error message is provided for end tags for void elements", function() {
expect(2);
QUnit.throws(function() {
compile("<input></input>");
}, /Invalid end tag `input` \(on line 1\) \(void elements cannot have end tags\)./);
QUnit.throws(function() {
compile("\n\n</br>");
}, /Invalid end tag `br` \(on line 3\) \(void elements cannot have end tags\)./);
});
test("A helpful error message is provided for end tags with attributes", function() {
QUnit.throws(function() {
compile('<div>\nSomething\n\n</div foo="bar">');
}, /Invalid end tag: closing tag must not have attributes, in `div` \(on line 4\)\./);
});
test("A helpful error message is provided for missing whitespace when self-closing a tag", function () {
QUnit.throws(function() {
compile('<div foo=bar/>');
}, /A space is required between an unquoted attribute value and `\/`, in `div` \(on line 1\)\./);
QUnit.throws(function() {
compile('<span\n foo={{bar}}/>');
}, /A space is required between an unquoted attribute value and `\/`, in `span` \(on line 2\)\./);
});
test("A helpful error message is provided for mismatched start/end tags", function() {
QUnit.throws(function() {
compile("<div>\n<p>\nSomething\n\n</div>");
}, /Closing tag `div` \(on line 5\) did not match last open tag `p` \(on line 2\)\./);
});
// These skipped tests don't actually have anything to do with innerHTML,
// but are related to IE8 doing Bad Things with newlines. This should
// likely have its own feature detect instead of using this one.
if (innerHTMLHandlesNewlines) {
test("error line numbers include comment lines", function() {
QUnit.throws(function() {
compile("<div>\n<p>\n{{! some comment}}\n\n</div>");
}, /Closing tag `div` \(on line 5\) did not match last open tag `p` \(on line 2\)\./);
});
test("error line numbers include mustache only lines", function() {
QUnit.throws(function() {
compile("<div>\n<p>\n{{someProp}}\n\n</div>");
}, /Closing tag `div` \(on line 5\) did not match last open tag `p` \(on line 2\)\./);
});
test("error line numbers include block lines", function() {
QUnit.throws(function() {
compile("<div>\n<p>\n{{#some-comment}}\n{{/some-comment}}\n</div>");
}, /Closing tag `div` \(on line 5\) did not match last open tag `p` \(on line 2\)\./);
});
test("error line numbers include whitespace control mustaches", function() {
QUnit.throws(function() {
compile("<div>\n<p>\n{{someProp~}}\n\n</div>{{some-comment}}");
}, /Closing tag `div` \(on line 5\) did not match last open tag `p` \(on line 2\)\./);
});
test("error line numbers include multiple mustache lines", function() {
QUnit.throws(function() {
compile("<div>\n<p>\n{{some-comment}}</div>{{some-comment}}");
}, /Closing tag `div` \(on line 3\) did not match last open tag `p` \(on line 2\)\./);
});
}
if (document.createElement('div').namespaceURI) {
QUnit.module("HTML-based compiler (output, svg)", {
beforeEach: commonSetup
});
test("Simple elements can have namespaced attributes", function() {
var template = compile("<svg xlink:title='svg-title'>content</svg>");
var svgNode = template.render({}, env).fragment.firstChild;
equalTokens(svgNode, '<svg xlink:title="svg-title">content</svg>');
equal(svgNode.attributes[0].namespaceURI, 'http://www.w3.org/1999/xlink');
});
test("Simple elements can have bound namespaced attributes", function() {
var template = compile("<svg xlink:title={{title}}>content</svg>");
var svgNode = template.render({title: 'svg-title'}, env).fragment.firstChild;
equalTokens(svgNode, '<svg xlink:title="svg-title">content</svg>');
equal(svgNode.attributes[0].namespaceURI, 'http://www.w3.org/1999/xlink');
});
test("SVG element can have capitalized attributes", function() {
var template = compile("<svg viewBox=\"0 0 0 0\"></svg>");
var svgNode = template.render({}, env).fragment.firstChild;
equalTokens(svgNode, '<svg viewBox=\"0 0 0 0\"></svg>');
});
test("The compiler can handle namespaced elements", function() {
var html = '<svg><path stroke="black" d="M 0 0 L 100 100"></path></svg>';
var template = compile(html);
var svgNode = template.render({}, env).fragment.firstChild;
equal(svgNode.namespaceURI, svgNamespace, "creates the svg element with a namespace");
equalTokens(svgNode, html);
});
test("The compiler sets namespaces on nested namespaced elements", function() {
var html = '<svg><path stroke="black" d="M 0 0 L 100 100"></path></svg>';
var template = compile(html);
var svgNode = template.render({}, env).fragment.firstChild;
equal( svgNode.childNodes[0].namespaceURI, svgNamespace,
"creates the path element with a namespace" );
equalTokens(svgNode, html);
});
test("The compiler sets a namespace on an HTML integration point", function() {
var html = '<svg><foreignObject>Hi</foreignObject></svg>';
var template = compile(html);
var svgNode = template.render({}, env).fragment.firstChild;
equal( svgNode.namespaceURI, svgNamespace,
"creates the svg element with a namespace" );
equal( svgNode.childNodes[0].namespaceURI, svgNamespace,
"creates the foreignObject element with a namespace" );
equalTokens(svgNode, html);
});
test("The compiler does not set a namespace on an element inside an HTML integration point", function() {
var html = '<svg><foreignObject><div></div></foreignObject></svg>';
var template = compile(html);
var svgNode = template.render({}, env).fragment.firstChild;
equal( svgNode.childNodes[0].childNodes[0].namespaceURI, xhtmlNamespace,
"creates the div inside the foreignObject without a namespace" );
equalTokens(svgNode, html);
});
test("The compiler pops back to the correct namespace", function() {
var html = '<svg></svg><svg></svg><div></div>';
var template = compile(html);
var fragment = template.render({}, env).fragment;
equal( fragment.childNodes[0].namespaceURI, svgNamespace,
"creates the first svg element with a namespace" );
equal( fragment.childNodes[1].namespaceURI, svgNamespace,
"creates the second svg element with a namespace" );
equal( fragment.childNodes[2].namespaceURI, xhtmlNamespace,
"creates the div element without a namespace" );
equalTokens(fragment, html);
});
test("The compiler pops back to the correct namespace even if exiting last child", function () {
var html = '<div><svg></svg></div><div></div>';
var fragment = compile(html).render({}, env).fragment;
equal(fragment.firstChild.namespaceURI, xhtmlNamespace, "first div's namespace is xhtmlNamespace");
equal(fragment.firstChild.firstChild.namespaceURI, svgNamespace, "svg's namespace is svgNamespace");
equal(fragment.lastChild.namespaceURI, xhtmlNamespace, "last div's namespace is xhtmlNamespace");
});
test("The compiler preserves capitalization of tags", function() {
var html = '<svg><linearGradient id="gradient"></linearGradient></svg>';
var template = compile(html);
var fragment = template.render({}, env).fragment;
equalTokens(fragment, html);
});
test("svg can live with hydration", function() {
var template = compile('<svg></svg>{{name}}');
var fragment = template.render({ name: 'Milly' }, env, { contextualElement: document.body }).fragment;
equal(
fragment.childNodes[0].namespaceURI, svgNamespace,
"svg namespace inside a block is present" );
});
test("top-level unsafe morph uses the correct namespace", function() {
var template = compile('<svg></svg>{{{foo}}}');
var fragment = template.render({ foo: '<span>FOO</span>' }, env, { contextualElement: document.body }).fragment;
equal(getTextContent(fragment), 'FOO', 'element from unsafe morph is displayed');
equal(fragment.childNodes[1].namespaceURI, xhtmlNamespace, 'element from unsafe morph has correct namespace');
});
test("nested unsafe morph uses the correct namespace", function() {
var template = compile('<svg>{{{foo}}}</svg><div></div>');
var fragment = template.render({ foo: '<path></path>' }, env, { contextualElement: document.body }).fragment;
equal(fragment.childNodes[0].childNodes[0].namespaceURI, svgNamespace,
'element from unsafe morph has correct namespace');
});
test("svg can take some hydration", function() {
var template = compile('<div><svg>{{name}}</svg></div>');
var fragment = template.render({ name: 'Milly' }, env).fragment;
equal(
fragment.firstChild.childNodes[0].namespaceURI, svgNamespace,
"svg namespace inside a block is present" );
equalTokens( fragment.firstChild, '<div><svg>Milly</svg></div>',
"html is valid" );
});
test("root svg can take some hydration", function() {
var template = compile('<svg>{{name}}</svg>');
var fragment = template.render({ name: 'Milly' }, env).fragment;
var svgNode = fragment.firstChild;
equal(
svgNode.namespaceURI, svgNamespace,
"svg namespace inside a block is present" );
equalTokens( svgNode, '<svg>Milly</svg>',
"html is valid" );
});
test("Block helper allows interior namespace", function() {
var isTrue = true;
registerHelper('testing', function(params, hash, options) {
if (isTrue) {
return this.yield();
} else {
return options.inverse.yield();
}
});
var template = compile('{{#testing}}<svg></svg>{{else}}<div><svg></svg></div>{{/testing}}');
var fragment = template.render({ isTrue: true }, env, { contextualElement: document.body }).fragment;
equal(
fragment.firstChild.nextSibling.namespaceURI, svgNamespace,
"svg namespace inside a block is present" );
isTrue = false;
fragment = template.render({ isTrue: false }, env, { contextualElement: document.body }).fragment;
equal(
fragment.firstChild.nextSibling.namespaceURI, xhtmlNamespace,
"inverse block path has a normal namespace");
equal(
fragment.firstChild.nextSibling.firstChild.namespaceURI, svgNamespace,
"svg namespace inside an element inside a block is present" );
});
test("Block helper allows namespace to bleed through", function() {
registerHelper('testing', function() {
return this.yield();
});
var template = compile('<div><svg>{{#testing}}<circle />{{/testing}}</svg></div>');
var fragment = template.render({ isTrue: true }, env).fragment;
var svgNode = fragment.firstChild.firstChild;
equal( svgNode.namespaceURI, svgNamespace,
"svg tag has an svg namespace" );
equal( svgNode.childNodes[0].namespaceURI, svgNamespace,
"circle tag inside block inside svg has an svg namespace" );
});
test("Block helper with root svg allows namespace to bleed through", function() {
registerHelper('testing', function() {
return this.yield();
});
var template = compile('<svg>{{#testing}}<circle />{{/testing}}</svg>');
var fragment = template.render({ isTrue: true }, env).fragment;
var svgNode = fragment.firstChild;
equal( svgNode.namespaceURI, svgNamespace,
"svg tag has an svg namespace" );
equal( svgNode.childNodes[0].namespaceURI, svgNamespace,
"circle tag inside block inside svg has an svg namespace" );
});
test("Block helper with root foreignObject allows namespace to bleed through", function() {
registerHelper('testing', function() {
return this.yield();
});
var template = compile('<foreignObject>{{#testing}}<div></div>{{/testing}}</foreignObject>');
var fragment = template.render({ isTrue: true }, env, { contextualElement: document.createElementNS(svgNamespace, 'svg') }).fragment;
var svgNode = fragment.firstChild;
equal( svgNode.namespaceURI, svgNamespace,
"foreignObject tag has an svg namespace" );
equal( svgNode.childNodes[0].namespaceURI, xhtmlNamespace,
"div inside morph and foreignObject has xhtml namespace" );
});
}
|
module.exports = function() {
'use strict';
this.title = element(by.model('movie.title'));
this.description = element(by.model('movie.description'));
this.save = element(by.css('.btn-primary'));
this.open = function() {
browser.get('/movies/add');
};
this.addActor = function(title, description) {
this.open();
this.title.clear();
this.title.sendKeys(title);
this.description.clear();
this.description.sendKeys(description);
this.save.click();
};
};
|
/*
Copyright (c) 2011 Cimaron Shanahan
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
(function(cnvgl) {
cnvgl.program = (function() {
function var_set() {
this.bound = {};
this.active = [];
this.names = {};
}
function Initializer() {
this.name = 0;
this.attached_shaders = [];
//link status
this.delete_status = 0;
this.link_status = 0;
this.validate_status = 0;
this.information_log = "";
//variable information
this.uniforms = null;
this.attributes = null;
this.varying = null;
this.program = null;
}
var cnvgl_program = jClass('cnvgl_program', Initializer);
cnvgl_program.cnvgl_program = function() {
this.reset();
};
cnvgl_program.reset = function() {
var bound_attr;
this.delete_status = 0;
this.link_status = 0;
this.validate_status = 0;
this.information_log = "";
bound_attr = this.attributes ? this.attributes.bound : {};
this.uniforms = new var_set();
this.attributes = new var_set();
this.varying = new var_set();
this.attributes.bound = bound_attr;
};
cnvgl_program.getOpenSlot = function(set) {
//active should be in order
if (set.active.length == 0) {
return 0;
}
last = set.active[set.active.length - 1];
return last.location + last.slots;
};
cnvgl_program.addActiveAttribute = function(attr) {
this.attributes.active.push(attr);
this.attributes.names[attr.name] = attr;
};
cnvgl_program.addActiveUniform = function(uniform) {
this.uniforms.active.push(uniform);
this.uniforms.names[uniform.name] = uniform;
};
cnvgl_program.addActiveVarying = function(varying) {
this.varying.active.push(varying);
this.varying.names[varying.name] = varying;
};
cnvgl_program.getActiveAttribute = function(name) {
return this.attributes.names[name];
};
cnvgl_program.getActiveUniform = function(name) {
return this.uniforms.names[name];
};
cnvgl_program.getActiveVarying = function(name) {
return this.varying.names[name];
};
return cnvgl_program.Constructor;
}());
cnvgl.program_var = function(name, type, location, slots, components) {
this.name = name;
this.type = type;
this.location = location;
this.slots = slots;
this.components = components;
this.basetype = cnvgl.FLOAT;
this.value = [0,0,0,0];
};
}(cnvgl));
|
'use strict';
// Articles controller
angular.module('projects').controller('ProjectsController', ['$scope', '$stateParams', '$location', 'Menus', 'Authentication', 'Projects', '$mdSidenav', '$mdDialog', '$window', 'Upload', '$timeout', '$q',
function ($scope, $stateParams, $location, Menus, Authentication, Projects, $mdSidenav, $mdDialog, $window, Upload, $timeout, $q) {
$scope.authentication = Authentication;
var self = this;
//instantiate variables
self.topicsArray = [];
var survey = {};
self.title;
self.date;
$scope.Math = window.Math;
var type = '';
//SideMenu toggle
this.menu = Menus.getMenu('settings').items;
$scope.toggleSidenav = function (menu) {
$mdSidenav(menu).toggle();
}
$scope.submit = function () {
if ($stateParams.projectId) {
var confirm = $mdDialog.confirm()
.title('Você tem certeza que deseja alterar esse projeto?')
.textContent('Essa ação não poderá ser revertida')
.ok('Sim')
.cancel('Não');
$mdDialog.show(confirm).then(function () {
if ($scope.form.file.$valid && $scope.file && valido()) {
$scope.uploadVideo($scope.file);
}
})
} else
if ($scope.form.file.$valid && $scope.file && valido()) {
$scope.uploadVideo($scope.file);
}
};
$scope.uploadVideo = function (file) {
if (file) {
Upload.upload({
url: 'upload/',
data: { file: file, 'username': $scope.username }
}).then(function (resp) {
console.log('Success ' + resp.config.data.file.name + 'uploaded. Response: ' + resp.data);
$timeout(function () {
type = 'video';
if (!$stateParams.projectId) {
create(resp.data);
console.log('entrou');
}
else {
update(resp.data);
}
})
}, function (resp) {
console.log('Error status: ' + resp.status);
}, function (evt) {
self.progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
});
}
if (!$stateParams.projectId) {
create();
console.log('entrou video')
}
else {
update();
}
};
// upload on file select or drop
$scope.uploadPhoto = function (dataUrl, name, file) {
if (!valido()) {
return;
}
if ($stateParams.projectId) {
var confirm = $mdDialog.confirm()
.title('Você tem certeza que deseja alterar esse projeto?')
.textContent('Essa ação não poderá ser revertida')
.ok('Sim')
.cancel('Não');
$mdDialog.show(confirm).then(function () {
if (name) {
var resposta = uploadPhotoThumb(dataUrl, name);
resposta.then(function (res) {
uploadPhoto(file, res);
})
return;
}
update();
})
}
if (!$stateParams.projectId) {
var resposta = uploadPhotoThumb(dataUrl, name);
resposta.then(function (res) {
uploadPhoto(file, res);
})
return;
}
};
var valido = function () {
if (!$scope.project.title || !$scope.project.description) {
$scope.error = 'Campo(s) sem preencher'
return false;
}
else return true;
}
// Create new Article
function create(url, thumb) {
// Create new Article object
console.log(url)
var article = new Projects({
title: $scope.project.title,
description: $scope.project.description,
url: url,
mediaType: type,
mediaThumbnail: thumb
});
// Redirect after save
article.$save(function (response) {
$location.path('/settings/project');
// Clear form fields
$scope.project.title = '';
$scope.project.description = '';
}, function (errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Remove existing Article
$scope.remove = function (article) {
if (article) {
article.$remove();
for (var i in $scope.articles) {
if ($scope.articles[i] === article) {
$scope.articles.splice(i, 1);
}
}
} else {
$scope.article.$remove(function () {
$location.path('articles');
});
}
};
// Update existing Article
var update = function (file, thumb) {
if (file) {
$scope.project.url = file;
$scope.project.mediaType = type;
$scope.project.mediaThumbnail = thumb;
console.log('tentou alterar a media')
}
var survey = $scope.project;
survey.$update(function (response) {
console.log(response)
}, function (response) {
console.log(response)
});
};
// Find a list of Articles
$scope.find = function () {
self.projects = Projects.query();
};
// Find existing Article
$scope.findOne = function () {
$scope.project = Projects.get({
projectId: $stateParams.projectId
});
};
$scope.showPrerenderedDialog = function (ev,url) {
self.url = url;
console.log(self.url)
$mdDialog.show({
contentElement: '#myDialog',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose: true
});
};
function uploadPhoto(file, thumb) {
Upload.upload({
url: 'upload/',
data: { file: file }
}).then(function (resp) {
console.log('Success ' + resp.config.data.file.name + 'uploaded. Response: ' + resp.data);
type = 'image';
if (!$stateParams.projectId) {
create(resp.data, thumb);
}
else {
update(resp.data, thumb);
}
}, function (resp) {
deferred.reject(resp.status);
}, function (evt) {
self.progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
});
}
function uploadPhotoThumb(dataUrl, name, file) {
var deferred = $q.defer();
Upload.upload({
url: 'upload/',
data: { file: Upload.dataUrltoBlob(dataUrl, name) }
}).then(function (resp) {
console.log('Success ' + resp.config.data.file.name + 'uploaded. Response: ' + resp.data);
type = 'image';
if (!$stateParams.projectId) {
//create(resp.data);
deferred.resolve(resp.data);
}
else {
//update(resp.data);
deferred.resolve(resp.data);
}
}, function (resp) {
deferred.reject(resp.status);
}, function (evt) {
self.progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
});
return deferred.promise;
}
}
]);
|
/*
* jQuery File Upload User Interface Plugin
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2010, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*/
/* jshint nomen:false */
/* global define, require, window */
(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define([
'jquery',
'tmpl',
'./jquery.fileupload-image',
'./jquery.fileupload-audio',
'./jquery.fileupload-video',
'./jquery.fileupload-validate'
], factory);
} else if (typeof exports === 'object') {
// Node/CommonJS:
factory(
require('jquery'),
require('tmpl')
);
} else {
// Browser globals:
factory(
window.jQuery,
window.tmpl
);
}
}(function ($, tmpl) {
'use strict';
$.blueimp.fileupload.prototype._specialOptions.push(
'filesContainer',
'uploadTemplateId',
'downloadTemplateId'
);
// The UI version extends the file upload widget
// and adds complete user interface interaction:
$.widget('blueimp.fileupload', $.blueimp.fileupload, {
options: {
// By default, files added to the widget are uploaded as soon
// as the user clicks on the start buttons. To enable automatic
// uploads, set the following option to true:
autoUpload: false,
// The ID of the upload template:
uploadTemplateId: 'template-upload',
// The ID of the download template:
downloadTemplateId: 'template-download',
// The container for the list of files. If undefined, it is set to
// an element with class "files" inside of the widget element:
filesContainer: undefined,
// By default, files are appended to the files container.
// Set the following option to true, to prepend files instead:
prependFiles: false,
// The expected data type of the upload response, sets the dataType
// option of the $.ajax upload requests:
dataType: 'json',
// Error and info messages:
messages: {
unknownError: 'Unknown error'
},
/* previewCanvas: false,
*/
disableImagePreview: false,
previewMaxWidth: 220,
previewMaxHeight: 220,
previewMinHeight: 220,
// Function returning the current number of files,
// used by the maxNumberOfFiles validation:
getNumberOfFiles: function () {
return this.filesContainer.children()
.not('.processing').length;
},
// Callback to retrieve the list of files from the server response:
getFilesFromResponse: function (data) {
if (data.result && $.isArray(data.result.files)) {
return data.result.files;
}
return [];
},
// The add callback is invoked as soon as files are added to the fileupload
// widget (via file input selection, drag & drop or add API call).
// See the basic file upload widget for more information:
add: function (e, data) {
if (e.isDefaultPrevented()) {
return false;
}
var $this = $(this),
that = $this.data('blueimp-fileupload') ||
$this.data('fileupload'),
options = that.options;
data.context = that._renderUpload(data.files)
.data('data', data)
.addClass('processing');
options.filesContainer[
options.prependFiles ? 'prepend' : 'append'
](data.context);
that._forceReflow(data.context);
that._transition(data.context);
data.process(function () {
return $this.fileupload('process', data);
}).always(function () {
data.context.each(function (index) {
$(this).find('.size').text(
that._formatFileSize(data.files[index].size)
);
}).removeClass('processing');
that._renderPreviews(data);
}).done(function () {
data.context.find('.start').prop('disabled', false);
if ((that._trigger('added', e, data) !== false) &&
(options.autoUpload || data.autoUpload) &&
data.autoUpload !== false) {
data.submit();
}
}).fail(function () {
if (data.files.error) {
data.context.each(function (index) {
var error = data.files[index].error;
if (error) {
$(this).find('.error').text(error);
}
});
}
});
},
// Callback for the start of each file upload request:
send: function (e, data) {
if (e.isDefaultPrevented()) {
return false;
}
var that = $(this).data('blueimp-fileupload') ||
$(this).data('fileupload');
if (data.context && data.dataType &&
data.dataType.substr(0, 6) === 'iframe') {
// Iframe Transport does not support progress events.
// In lack of an indeterminate progress bar, we set
// the progress to 100%, showing the full animated bar:
data.context
.find('.progress').addClass(
!$.support.transition && 'progress-animated'
)
.attr('aria-valuenow', 100)
.children().first().css(
'width',
'100%'
);
}
return that._trigger('sent', e, data);
},
// Callback for successful uploads:
done: function (e, data) {
if (e.isDefaultPrevented()) {
return false;
}
var that = $(this).data('blueimp-fileupload') ||
$(this).data('fileupload'),
getFilesFromResponse = data.getFilesFromResponse ||
that.options.getFilesFromResponse,
files = getFilesFromResponse(data),
template,
deferred;
if (data.context) {
data.context.each(function (index) {
var file = files[index] ||
{error: 'Empty file upload result'};
deferred = that._addFinishedDeferreds();
that._transition($(this)).done(
function () {
var node = $(this);
template = that._renderDownload([file])
.replaceAll(node);
that._forceReflow(template);
that._transition(template).done(
function () {
data.context = $(this);
that._trigger('completed', e, data);
that._trigger('finished', e, data);
deferred.resolve();
}
);
}
);
});
} else {
template = that._renderDownload(files)[
that.options.prependFiles ? 'prependTo' : 'appendTo'
](that.options.filesContainer);
that._forceReflow(template);
deferred = that._addFinishedDeferreds();
that._transition(template).done(
function () {
data.context = $(this);
that._trigger('completed', e, data);
that._trigger('finished', e, data);
deferred.resolve();
}
);
}
},
// Callback for failed (abort or error) uploads:
fail: function (e, data) {
if (e.isDefaultPrevented()) {
return false;
}
var that = $(this).data('blueimp-fileupload') ||
$(this).data('fileupload'),
template,
deferred;
if (data.context) {
data.context.each(function (index) {
if (data.errorThrown !== 'abort') {
var file = data.files[index];
file.error = file.error || data.errorThrown ||
data.i18n('unknownError');
deferred = that._addFinishedDeferreds();
that._transition($(this)).done(
function () {
var node = $(this);
template = that._renderDownload([file])
.replaceAll(node);
that._forceReflow(template);
that._transition(template).done(
function () {
data.context = $(this);
that._trigger('failed', e, data);
that._trigger('finished', e, data);
deferred.resolve();
}
);
}
);
} else {
deferred = that._addFinishedDeferreds();
that._transition($(this)).done(
function () {
$(this).remove();
that._trigger('failed', e, data);
that._trigger('finished', e, data);
deferred.resolve();
}
);
}
});
} else if (data.errorThrown !== 'abort') {
data.context = that._renderUpload(data.files)[
that.options.prependFiles ? 'prependTo' : 'appendTo'
](that.options.filesContainer)
.data('data', data);
that._forceReflow(data.context);
deferred = that._addFinishedDeferreds();
that._transition(data.context).done(
function () {
data.context = $(this);
that._trigger('failed', e, data);
that._trigger('finished', e, data);
deferred.resolve();
}
);
} else {
that._trigger('failed', e, data);
that._trigger('finished', e, data);
that._addFinishedDeferreds().resolve();
}
},
// Callback for upload progress events:
progress: function (e, data) {
if (e.isDefaultPrevented()) {
return false;
}
var progress = Math.floor(data.loaded / data.total * 100);
if (data.context) {
data.context.each(function () {
$(this).find('.progress')
.attr('aria-valuenow', progress)
.children().first().css(
'width',
progress + '%'
);
});
}
},
// Callback for global upload progress events:
progressall: function (e, data) {
if (e.isDefaultPrevented()) {
return false;
}
var $this = $(this),
progress = Math.floor(data.loaded / data.total * 100),
globalProgressNode = $this.find('.fileupload-progress'),
extendedProgressNode = globalProgressNode
.find('.progress-extended');
if (extendedProgressNode.length) {
extendedProgressNode.html(
($this.data('blueimp-fileupload') || $this.data('fileupload'))
._renderExtendedProgress(data)
);
}
globalProgressNode
.find('.progress')
.attr('aria-valuenow', progress)
.children().first().css(
'width',
progress + '%'
);
},
// Callback for uploads start, equivalent to the global ajaxStart event:
start: function (e) {
if (e.isDefaultPrevented()) {
return false;
}
var that = $(this).data('blueimp-fileupload') ||
$(this).data('fileupload');
that._resetFinishedDeferreds();
that._transition($(this).find('.fileupload-progress')).done(
function () {
that._trigger('started', e);
}
);
},
// Callback for uploads stop, equivalent to the global ajaxStop event:
stop: function (e) {
if (e.isDefaultPrevented()) {
return false;
}
var that = $(this).data('blueimp-fileupload') ||
$(this).data('fileupload'),
deferred = that._addFinishedDeferreds();
$.when.apply($, that._getFinishedDeferreds())
.done(function () {
that._trigger('stopped', e);
});
that._transition($(this).find('.fileupload-progress')).done(
function () {
$(this).find('.progress')
.attr('aria-valuenow', '0')
.children().first().css('width', '0%');
$(this).find('.progress-extended').html(' ');
deferred.resolve();
}
);
},
processstart: function (e) {
if (e.isDefaultPrevented()) {
return false;
}
$(this).addClass('fileupload-processing');
},
processstop: function (e) {
if (e.isDefaultPrevented()) {
return false;
}
$(this).removeClass('fileupload-processing');
},
// Callback for file deletion:
destroy: function (e, data) {
if (e.isDefaultPrevented()) {
return false;
}
var that = $(this).data('blueimp-fileupload') ||
$(this).data('fileupload'),
removeNode = function () {
that._transition(data.context).done(
function () {
$(this).remove();
that._trigger('destroyed', e, data);
}
);
};
if (data.url) {
data.dataType = data.dataType || that.options.dataType;
$.ajax(data).done(removeNode).fail(function () {
alert("Có lỗi khi xóa ảnh");
that._trigger('destroyfailed', e, data);
});
} else {
removeNode();
}
}
},
_resetFinishedDeferreds: function () {
this._finishedUploads = [];
},
_addFinishedDeferreds: function (deferred) {
if (!deferred) {
deferred = $.Deferred();
}
this._finishedUploads.push(deferred);
return deferred;
},
_getFinishedDeferreds: function () {
return this._finishedUploads;
},
// Link handler, that allows to download files
// by drag & drop of the links to the desktop:
_enableDragToDesktop: function () {
var link = $(this),
url = link.prop('href'),
name = link.prop('download'),
type = 'application/octet-stream';
link.bind('dragstart', function (e) {
try {
e.originalEvent.dataTransfer.setData(
'DownloadURL',
[type, name, url].join(':')
);
} catch (ignore) {}
});
},
_formatFileSize: function (bytes) {
if (typeof bytes !== 'number') {
return '';
}
if (bytes >= 1000000000) {
return (bytes / 1000000000).toFixed(2) + ' GB';
}
if (bytes >= 1000000) {
return (bytes / 1000000).toFixed(2) + ' MB';
}
return (bytes / 1000).toFixed(2) + ' KB';
},
_formatBitrate: function (bits) {
if (typeof bits !== 'number') {
return '';
}
if (bits >= 1000000000) {
return (bits / 1000000000).toFixed(2) + ' Gbit/s';
}
if (bits >= 1000000) {
return (bits / 1000000).toFixed(2) + ' Mbit/s';
}
if (bits >= 1000) {
return (bits / 1000).toFixed(2) + ' kbit/s';
}
return bits.toFixed(2) + ' bit/s';
},
_formatTime: function (seconds) {
var date = new Date(seconds * 1000),
days = Math.floor(seconds / 86400);
days = days ? days + 'd ' : '';
return days +
('0' + date.getUTCHours()).slice(-2) + ':' +
('0' + date.getUTCMinutes()).slice(-2) + ':' +
('0' + date.getUTCSeconds()).slice(-2);
},
_formatPercentage: function (floatValue) {
return (floatValue * 100).toFixed(2) + ' %';
},
_renderExtendedProgress: function (data) {
return this._formatBitrate(data.bitrate) + ' | ' +
this._formatTime(
(data.total - data.loaded) * 8 / data.bitrate
) + ' | ' +
this._formatPercentage(
data.loaded / data.total
) + ' | ' +
this._formatFileSize(data.loaded) + ' / ' +
this._formatFileSize(data.total);
},
_renderTemplate: function (func, files) {
if (!func) {
return $();
}
var result = func({
files: files,
formatFileSize: this._formatFileSize,
options: this.options
});
if (result instanceof $) {
return result;
}
return $(this.options.templatesContainer).html(result).children();
},
_renderPreviews: function (data) {
$('.upload-area').css("display", "none");
$('.right-upload').css("display", "block");
data.context.find('.preview').each(function (index, elm) {
var canvas = data.files[index].preview;
var image = new Image();
image.src = canvas.toDataURL("image/png/jpeg");
data.files[index].preview = image;
$(elm).append(data.files[index].preview);
$('.add-more').css("display", "inline-block");
});
},
_renderUpload: function (files) {
return this._renderTemplate(
this.options.uploadTemplate,
files
);
},
_renderDownload: function (files) {
return this._renderTemplate(
this.options.downloadTemplate,
files
).find('a[download]').each(this._enableDragToDesktop).end();
},
_startHandler: function (e) {
e.preventDefault();
var button = $(e.currentTarget),
template = button.closest('.template-upload'),
data = template.data('data');
button.prop('disabled', true);
if (data && data.submit) {
data.submit();
}
},
_cancelHandler: function (e) {
e.preventDefault();
var template = $(e.currentTarget)
.closest('.template-upload,.template-download'),
data = template.data('data') || {};
data.context = data.context || template;
if (data.abort) {
data.abort();
} else {
data.errorThrown = 'abort';
this._trigger('fail', e, data);
}
},
_deleteHandler: function (e) {
e.preventDefault();
var button = $(e.currentTarget);
this._trigger('destroy', e, $.extend({
context: button.closest('.template-download'),
type: 'DELETE'
}, button.data()));
},
_forceReflow: function (node) {
return $.support.transition && node.length &&
node[0].offsetWidth;
},
_transition: function (node) {
var dfd = $.Deferred();
if ($.support.transition && node.hasClass('fade') && node.is(':visible')) {
node.bind(
$.support.transition.end,
function (e) {
// Make sure we don't respond to other transitions events
// in the container element, e.g. from button elements:
if (e.target === node[0]) {
node.unbind($.support.transition.end);
dfd.resolveWith(node);
}
}
).toggleClass('in');
} else {
node.toggleClass('in');
dfd.resolveWith(node);
}
return dfd;
},
_initButtonBarEventHandlers: function () {
var fileUploadButtonBar = this.element.find('.fileupload-buttonbar'),
filesList = this.options.filesContainer;
this._on(fileUploadButtonBar.find('.start'), {
click: function (e) {
e.preventDefault();
filesList.find('.start').click();
}
});
this._on(fileUploadButtonBar.find('.cancel'), {
click: function (e) {
e.preventDefault();
filesList.find('.cancel').click();
}
});
this._on(fileUploadButtonBar.find('.delete'), {
click: function (e) {
e.preventDefault();
filesList.find('.toggle:checked')
.closest('.template-download')
.find('.delete').click();
fileUploadButtonBar.find('.toggle')
.prop('checked', false);
}
});
this._on(fileUploadButtonBar.find('.toggle'), {
change: function (e) {
filesList.find('.toggle').prop(
'checked',
$(e.currentTarget).is(':checked')
);
}
});
},
_destroyButtonBarEventHandlers: function () {
this._off(
this.element.find('.fileupload-buttonbar')
.find('.start, .cancel, .delete'),
'click'
);
this._off(
this.element.find('.fileupload-buttonbar .toggle'),
'change.'
);
},
_initEventHandlers: function () {
this._super();
this._on(this.options.filesContainer, {
'click .start': this._startHandler,
'click .cancel': this._cancelHandler,
'click .delete': this._deleteHandler
});
this._initButtonBarEventHandlers();
},
_destroyEventHandlers: function () {
this._destroyButtonBarEventHandlers();
this._off(this.options.filesContainer, 'click');
this._super();
},
_enableFileInputButton: function () {
this.element.find('.fileinput-button input')
.prop('disabled', false)
.parent().removeClass('disabled');
},
_disableFileInputButton: function () {
this.element.find('.fileinput-button input')
.prop('disabled', true)
.parent().addClass('disabled');
},
_initTemplates: function () {
var options = this.options;
options.templatesContainer = this.document[0].createElement(
options.filesContainer.prop('nodeName')
);
if (tmpl) {
if (options.uploadTemplateId) {
options.uploadTemplate = tmpl(options.uploadTemplateId);
}
if (options.downloadTemplateId) {
options.downloadTemplate = tmpl(options.downloadTemplateId);
}
}
},
_initFilesContainer: function () {
var options = this.options;
if (options.filesContainer === undefined) {
options.filesContainer = this.element.find('.files');
} else if (!(options.filesContainer instanceof $)) {
options.filesContainer = $(options.filesContainer);
}
},
_initSpecialOptions: function () {
this._super();
this._initFilesContainer();
this._initTemplates();
},
_create: function () {
this._super();
this._resetFinishedDeferreds();
if (!$.support.fileInput) {
this._disableFileInputButton();
}
},
enable: function () {
var wasDisabled = false;
if (this.options.disabled) {
wasDisabled = true;
}
this._super();
if (wasDisabled) {
this.element.find('input, button').prop('disabled', false);
this._enableFileInputButton();
}
},
disable: function () {
if (!this.options.disabled) {
this.element.find('input, button').prop('disabled', true);
this._disableFileInputButton();
}
this._super();
}
});
}));
|
'use strict';
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Pick Schema
*/
var PickSchema = new Schema({
user: { type: mongoose.Schema.Types.ObjectId, ref: 'User', index: true },
match: { type: mongoose.Schema.Types.ObjectId, ref: 'Match', index: true },
choice: String,
points: Number,
round: {
type: String,
default: 'first'
}
});
mongoose.model('Pick', PickSchema);
|
/*
skeleton adapted from former strategy:
RSI Bull and Bear + ADX modifier
1. Use different RSI-strategies depending on a longer trend
2. But modify this slighly if shorter BULL/BEAR is detected
-
12 feb 2017
-
(CC-BY-SA 4.0) Tommie Hansen
https://creativecommons.org/licenses/by-sa/4.0/
*/
// req's
var log = require ('../../core/log.js');
var config = require ('../../core/util.js').getConfig();
// strategy
var strat = {
/* INIT */
init: function()
{
this.name = 'RSI Bull and Bear ADX';
this.requiredHistory = 10//config.tradingAdvisor.historySize;
this.resetTrend();
// debug? set to flase to disable all logging/messages/stats (improves performance)
this.debug = true;
// performance
//config.backtest.batchSize = 1000; // increase performance
//config.silent = true;
//config.debug = false;
//JAPONICUS:BULLMOM|MOMENTUM,BEARMOM|MOMENTUM,SECMOM|MOMENTUM;
// SMA
this.addIndicator('maSlow', 'SMA', this.settings.SMA_long );
this.addIndicator('maFast', 'SMA', this.settings.SMA_short );
// RSI
this.addIndicator('BULL_momentum', 'BULLMOM', this.settings['BULLMOM'] );
this.addIndicator('BEAR_momentum', 'BEARMOM', this.settings['BEARMOM'] );
// ADX
this.addIndicator('secondary_momentum', 'SECMOM', this.settings['SECMOM'] )
// debug stuff
this.startTime = new Date();
// add min/max if debug
if( this.debug ){
this.stat = {
adx: { min: 1000, max: 0 },
bear: { min: 1000, max: 0 },
bull: { min: 1000, max: 0 }
};
}
}, // init()
/* RESET TREND */
resetTrend: function()
{
var trend = {
duration: 0,
direction: 'none',
longPos: false,
};
this.trend = trend;
},
/* CHECK */
check: function()
{
// get all indicators
let ind = this.indicators,
maSlow = ind.maSlow.result,
maFast = ind.maFast.result,
sec = this.indicators.secondary_momentum.result;
// BEAR TREND
if( maFast < maSlow )
{
var momentum = ind.BEAR_momentum.result;
let momentum_hi = this.settings['BEARMOM'].thresholds.up,
momentum_low = this.settings['BEARMOM'].thresholds.down;
// ADX trend strength?
if( sec > this.settings['SECMOM'].thresholds.up ) momentum_hi = momentum_hi + 15;
else if( sec < this.settings['SECMOM'].thresholds.down ) momentum_low = momentum_low -5;
if( momentum > momentum_hi ) this.short();
else if( momentum < momentum_low ) this.long();
}
// BULL TREND
else
{
var momentum = ind.BULL_momentum.result;
let momentum_hi = this.settings['BULLMOM'].thresholds.up,
momentum_low = this.settings['BULLMOM'].thresholds.down;
// ADX trend strength?
if( sec > this.settings['SECMOM'].thresholds.up ) momentum_hi = momentum_hi + 5;
else if( sec < this.settings['SECMOM'].thresholds.down ) momentum_low = momentum_low -5;
if( momentum > momentum_hi ) this.short();
else if( momentum < momentum_low ) this.long();
}
// add adx low/high if debug
}, // check()
/* LONG */
long: function()
{
if( this.trend.direction !== 'up' ) // new trend? (only act on new trends)
{
this.resetTrend();
this.trend.direction = 'up';
this.advice('long');
if( this.debug ) log.info('Going long');
}
if( this.debug )
{
this.trend.duration++;
log.info('Long since', this.trend.duration, 'candle(s)');
}
},
/* SHORT */
short: function()
{
// new trend? (else do things)
if( this.trend.direction !== 'down' )
{
this.resetTrend();
this.trend.direction = 'down';
this.advice('short');
if( this.debug ) log.info('Going short');
}
if( this.debug )
{
this.trend.duration++;
log.info('Short since', this.trend.duration, 'candle(s)');
}
},
/* END backtest */
end: function()
{
let seconds = ((new Date()- this.startTime)/1000),
minutes = seconds/60,
str;
minutes < 1 ? str = seconds.toFixed(2) + ' seconds' : str = minutes.toFixed(2) + ' minutes';
log.info('====================================');
log.info('Finished in ' + str);
log.info('====================================');
// print stats and messages if debug
if(this.debug)
{
let stat = this.stat;
log.info('BEAR RSI low/high: ' + stat.bear.min + ' / ' + stat.bear.max);
log.info('BULL RSI low/high: ' + stat.bull.min + ' / ' + stat.bull.max);
log.info('ADX min/max: ' + stat.adx.min + ' / ' + stat.adx.max);
}
}
};
module.exports = strat;
|
import { both, complement, flip, T } from 'ramda';
import {
ACTION_GUARD_NONE, ACTION_REQUEST_NONE, checkActionResponseIsSuccess, EV_GUARD_NONE,
INIT_EVENT_NAME, INIT_STATE, makeDefaultActionResponseProcessing, modelUpdateIdentity
} from '@rxcc/components';
import { STEP_ABOUT, STEP_APPLIED, STEP_QUESTION, STEP_REVIEW, STEP_TEAMS } from './properties';
import {
makeRequestToUpdateUserApplication, makeRequestToUpdateUserApplicationWithHasApplied,
makeRequestToUpdateUserApplicationWithHasReviewed
} from './processApplicationActions';
import {
initializeModel, initializeModelAndStepReview, updateModelWithAboutData,
updateModelWithAboutDataAndStepQuestion, updateModelWithAboutDataAndStepReview,
updateModelWithAboutValidationMessages, updateModelWithAppliedData,
updateModelWithJoinedOrUnjoinedTeamData, updateModelWithQuestionData,
updateModelWithQuestionDataAndStepReview, updateModelWithQuestionDataAndTeamsStep,
updateModelWithQuestionValidationMessages, updateModelWithSelectedTeamData,
updateModelWithSkippedTeamData, updateModelWithStepAndError, updateModelWithStepAndHasReviewed,
updateModelWithStepOnly, updateModelWithTeamDetailAnswerAndNextStep,
updateModelWithTeamDetailValidationMessages
} from './processApplicationModelUpdates';
import {
aboutContinueEventFactory, applicationCompletedEventFactory, backTeamClickedEventFactory,
changeAboutEventFactory, changeQuestionEventFactory, changeTeamsEventFactory, hasApplied,
hasJoinedAtLeastOneTeam, hasReachedReviewStep, isFormValid, isStep, joinTeamClickedEventFactory,
questionContinueEventFactory, skipTeamClickedEventFactory, teamClickedEventFactory,
teamContinueEventFactory
} from './processApplicationEvents';
import { fetchUserApplicationModelData } from './processApplicationFetch';
import { DOM_SINK } from "@rxcc/utils"
import { processApplicationRenderInit } from "./processApplicationRenderInit";
import { processApplicationRenderAboutScreen } from "./processApplicationRenderAboutScreen";
import { processApplicationRenderQuestionScreen } from "./processApplicationRenderQuestionScreen";
import { processApplicationRenderTeamsScreen } from "./processApplicationRenderTeamsScreen";
import { processApplicationRenderTeamDetailScreen } from "./processApplicationRenderTeamDetailScreen";
import { processApplicationRenderReviewScreen } from "./processApplicationRenderReviewScreen";
import { processApplicationRenderApplied } from "./processApplicationRenderApplied";
const INIT_S = 'INIT';
const STATE_ABOUT = 'About';
const STATE_QUESTION = 'Question';
const STATE_TEAMS = 'Teams';
const STATE_TEAM_DETAIL = 'Team Detail';
const STATE_REVIEW = 'Review';
const STATE_APPLIED = 'State Applied';
const FETCH_EV = 'fetch';
const ABOUT_CONTINUE = 'about_continue';
const QUESTION_CONTINUE = 'question_continue';
const TEAM_CLICKED = 'team_clicked';
const SKIP_TEAM_CLICKED = 'skip_team_clicked';
const JOIN_OR_UNJOIN_TEAM_CLICKED = 'join_team_clicked';
const BACK_TEAM_CLICKED = 'back_team_clicked';
const TEAM_CONTINUE = 'team_continue';
const CHANGE_ABOUT = 'change_about';
const CHANGE_QUESTION = 'change_question';
const CHANGE_TEAMS = 'change_teams';
const APPLICATION_COMPLETED = 'application_completed';
const sinkNames = [DOM_SINK, 'domainAction$'];
// NOTE : we have different events and event factories for each continue button, because the event
// data for those events are different
// NOTE : we have different selectors for the continue button because otherwise we would fire
// all continue events which would correctly advance the state machine for the good event, but
// display warning for the rest of the events. To suppress the warning, we decide to have
// different selectors
export const events = {
[FETCH_EV]: fetchUserApplicationModelData,
[ABOUT_CONTINUE]: aboutContinueEventFactory,
[QUESTION_CONTINUE]: questionContinueEventFactory,
[TEAM_CLICKED]: teamClickedEventFactory,
[SKIP_TEAM_CLICKED]: skipTeamClickedEventFactory,
[JOIN_OR_UNJOIN_TEAM_CLICKED]: joinTeamClickedEventFactory,
[BACK_TEAM_CLICKED]: backTeamClickedEventFactory,
[TEAM_CONTINUE]: teamContinueEventFactory,
[CHANGE_ABOUT]: changeAboutEventFactory,
[CHANGE_QUESTION]: changeQuestionEventFactory,
[CHANGE_TEAMS]: changeTeamsEventFactory,
[APPLICATION_COMPLETED]: applicationCompletedEventFactory
};
// If there is an error updating the model, keep in the same state
// It is important to update the model locally even if the update could not go in the
// remote repository, so that when the view is shown the already entered
// values are shown
export const transitions = {
T_INIT: {
origin_state: INIT_STATE,
event: INIT_EVENT_NAME,
target_states: [
{
event_guard: EV_GUARD_NONE,
re_entry: true, // necessary as INIT is both target and current state in the beginning
action_request: ACTION_REQUEST_NONE,
transition_evaluation: [
{
action_guard: ACTION_GUARD_NONE,
target_state: INIT_S,
model_update: modelUpdateIdentity
}
]
}
]
},
dispatch: {
origin_state: INIT_S,
event: FETCH_EV,
target_states: [
{
// whatever step the application is in, if the user has applied, we start with the review
event_guard: hasApplied,
action_request: ACTION_REQUEST_NONE,
transition_evaluation: [
{
action_guard: ACTION_GUARD_NONE,
target_state: STATE_REVIEW,
// Business rule
// if the user has applied, then he starts the app process route with the review stage
model_update: initializeModelAndStepReview
}
]
},
{
event_guard: isStep(STEP_ABOUT),
action_request: ACTION_REQUEST_NONE,
transition_evaluation: [
{
action_guard: ACTION_GUARD_NONE,
target_state: STATE_ABOUT,
model_update: initializeModel // with event data which is read from repository
}
]
},
{
event_guard: isStep(STEP_QUESTION),
action_request: ACTION_REQUEST_NONE,
transition_evaluation: [
{
action_guard: ACTION_GUARD_NONE,
target_state: STATE_QUESTION,
model_update: initializeModel // with event data which is read from repository
}
]
},
{
event_guard: isStep(STEP_TEAMS),
action_request: ACTION_REQUEST_NONE,
transition_evaluation: [
{
action_guard: ACTION_GUARD_NONE,
target_state: STATE_TEAMS,
model_update: initializeModel // with event data which is read from repository
}
]
},
{
event_guard: isStep(STEP_REVIEW),
action_request: ACTION_REQUEST_NONE,
transition_evaluation: [
{
action_guard: ACTION_GUARD_NONE,
target_state: STATE_REVIEW,
model_update: initializeModel // with event data which is read from repository
}
]
}
]
},
fromAboutScreen: {
origin_state: STATE_ABOUT,
event: ABOUT_CONTINUE,
target_states: [
{
// Case form has only valid fields AND has NOT reached the review stage of the app
event_guard: both(isFormValid, complement(hasReachedReviewStep)),
action_request: {
driver: 'domainAction$',
request: makeRequestToUpdateUserApplication(STEP_QUESTION)
},
transition_evaluation: makeDefaultActionResponseProcessing({
success: {
target_state: STATE_QUESTION,
model_update: updateModelWithAboutDataAndStepQuestion
},
error: {
target_state: STATE_ABOUT,
model_update: updateModelWithStepAndError(updateModelWithAboutData, STEP_ABOUT)
}
})
},
{
// Case form has only valid fields AND has reached the review stage of the app
event_guard: both(isFormValid, hasReachedReviewStep),
re_entry: true,
action_request: {
driver: 'domainAction$',
request: makeRequestToUpdateUserApplication(STEP_REVIEW)
},
transition_evaluation: makeDefaultActionResponseProcessing({
success: {
target_state: STATE_REVIEW,
model_update: updateModelWithAboutDataAndStepReview
},
error: {
target_state: STATE_ABOUT,
model_update: updateModelWithStepAndError(updateModelWithAboutData, STEP_ABOUT)
}
})
},
{
// Case form has invalid fields
event_guard: T,
re_entry: true,
action_request: ACTION_REQUEST_NONE,
transition_evaluation: [
{
action_guard: T,
target_state: STATE_ABOUT,
// keep model in sync with repository
model_update: updateModelWithAboutValidationMessages
},
]
}
]
},
fromQuestionScreen: {
origin_state: STATE_QUESTION,
event: QUESTION_CONTINUE,
target_states: [
{
// Case form has only valid fields AND has NOT reached the review stage of the app
event_guard: both(isFormValid, complement(hasReachedReviewStep)),
action_request: {
driver: 'domainAction$',
request: makeRequestToUpdateUserApplication(STEP_TEAMS)
},
transition_evaluation: [
{
action_guard: checkActionResponseIsSuccess,
target_state: STATE_TEAMS,
// keep model in sync with repository
model_update: updateModelWithQuestionDataAndTeamsStep
},
{
action_guard: T,
target_state: STATE_QUESTION,
model_update: updateModelWithStepAndError(updateModelWithQuestionData, STEP_QUESTION)
}
]
},
{
// Case form has only valid fields AND has reached the review stage of the app
event_guard: both(isFormValid, hasReachedReviewStep),
re_entry: true,
action_request: {
driver: 'domainAction$',
request: makeRequestToUpdateUserApplication(STEP_REVIEW)
},
transition_evaluation: [
{
action_guard: checkActionResponseIsSuccess,
target_state: STATE_REVIEW,
// keep model in sync with repository
model_update: updateModelWithQuestionDataAndStepReview
},
{
action_guard: T,
target_state: STATE_QUESTION,
model_update: updateModelWithStepAndError(updateModelWithQuestionData, STEP_QUESTION)
}
]
},
{
// Case form has invalid fields
event_guard: T,
re_entry: true,
action_request: ACTION_REQUEST_NONE,
transition_evaluation: [
{
action_guard: T,
target_state: STATE_QUESTION,
// keep model in sync with repository
model_update: updateModelWithQuestionValidationMessages
},
]
}
]
},
fromTeamsScreenEventTeamClick: {
origin_state: STATE_TEAMS,
event: TEAM_CLICKED,
target_states: [
{
event_guard: T,
action_request: ACTION_REQUEST_NONE,
transition_evaluation: [
{
action_guard: T,
target_state: STATE_TEAM_DETAIL,
model_update: updateModelWithSelectedTeamData
},
]
},
]
},
fromTeamDetailScreenSkipClick: {
origin_state: STATE_TEAM_DETAIL,
event: SKIP_TEAM_CLICKED,
target_states: [
{
event_guard: T,
re_entry: true,
action_request: ACTION_REQUEST_NONE,
transition_evaluation: [
{
action_guard: T,
target_state: STATE_TEAM_DETAIL,
model_update: updateModelWithSkippedTeamData
},
]
},
]
},
fromTeamDetailScreenJoinOrUnjoinClick: {
origin_state: STATE_TEAM_DETAIL,
event: JOIN_OR_UNJOIN_TEAM_CLICKED,
target_states: [
{
// Case form has only valid fields
event_guard: isFormValid,
re_entry: true,
action_request: ACTION_REQUEST_NONE,
transition_evaluation: [
{
action_guard: T,
target_state: STATE_TEAM_DETAIL,
model_update: updateModelWithJoinedOrUnjoinedTeamData
},
]
},
{
// Case form has some invalid field(s)
event_guard: T,
re_entry: true,
action_request: ACTION_REQUEST_NONE,
transition_evaluation: [
{
action_guard: T,
target_state: STATE_TEAM_DETAIL,
model_update: updateModelWithTeamDetailValidationMessages
},
]
},
]
},
fromTeamDetailScreenBackClick: {
origin_state: STATE_TEAM_DETAIL,
event: BACK_TEAM_CLICKED,
target_states: [
{
event_guard: T,
action_request: ACTION_REQUEST_NONE,
transition_evaluation: [
{
action_guard: T,
target_state: STATE_TEAMS,
model_update: updateModelWithTeamDetailAnswerAndNextStep
},
]
},
]
},
fromTeamsScreenToReview: {
origin_state: STATE_TEAMS,
event: TEAM_CONTINUE,
target_states: [
{
event_guard: hasJoinedAtLeastOneTeam,
re_entry: true,
action_request: {
driver: 'domainAction$',
request: makeRequestToUpdateUserApplicationWithHasReviewed
},
transition_evaluation: makeDefaultActionResponseProcessing({
success: {
target_state: STATE_REVIEW,
model_update: updateModelWithStepAndHasReviewed
},
error: {
target_state: STATE_TEAMS,
model_update: updateModelWithStepAndError(modelUpdateIdentity, STEP_TEAMS)
}
})
},
]
},
fromReviewScreenToAbout: {
origin_state: STATE_REVIEW,
event: CHANGE_ABOUT,
target_states: [
{
event_guard: EV_GUARD_NONE,
re_entry: true,
action_request: ACTION_REQUEST_NONE,
transition_evaluation: [
{
action_guard: T,
target_state: STATE_ABOUT,
model_update: updateModelWithStepOnly(STEP_ABOUT)
},
]
},
]
},
fromReviewScreenToQuestion: {
origin_state: STATE_REVIEW,
event: CHANGE_QUESTION,
target_states: [
{
event_guard: T,
re_entry: true,
action_request: ACTION_REQUEST_NONE,
transition_evaluation: [
{
action_guard: T,
target_state: STATE_QUESTION,
model_update: updateModelWithStepOnly(STEP_QUESTION)
},
]
},
]
},
fromReviewScreenToTeams: {
origin_state: STATE_REVIEW,
event: CHANGE_TEAMS,
target_states: [
{
event_guard: T,
re_entry: true,
action_request: ACTION_REQUEST_NONE,
transition_evaluation: [
{
action_guard: T,
target_state: STATE_TEAMS,
model_update: updateModelWithStepOnly(STEP_TEAMS)
},
]
},
]
},
fromReviewScreenToApplied: {
origin_state: STATE_REVIEW,
event: APPLICATION_COMPLETED,
target_states: [
{
// Case form has only valid fields AND has NOT reached the review stage of the app
event_guard: T,
re_entry: true,
action_request: {
driver: 'domainAction$',
request: makeRequestToUpdateUserApplicationWithHasApplied
},
transition_evaluation: [
{
action_guard: checkActionResponseIsSuccess,
target_state: STATE_APPLIED,
// keep model in sync with repository
model_update: updateModelWithAppliedData
},
{
action_guard: T,
target_state: STATE_ABOUT,
model_update: updateModelWithStepAndError(updateModelWithAppliedData, STEP_APPLIED)
}
]
},
]
},
};
export const entryComponents = {
[INIT_S]: function showInitView(model) {
return processApplicationRenderInit
},
[STATE_ABOUT]: function showViewStateAbout(model) {
console.info(`entering entry component ABOUT`, model);
return flip(processApplicationRenderAboutScreen)({ model })
},
[STATE_QUESTION]: function showViewStateQuestion(model) {
console.info(`entering entry component QUESTION`, model);
return flip(processApplicationRenderQuestionScreen)({ model })
},
[STATE_TEAMS]: function showViewStateTeams(model) {
console.info(`entering entry component TEAMS`, model);
return flip(processApplicationRenderTeamsScreen)({ model })
},
[STATE_TEAM_DETAIL]: function showViewStateTeamDetail(model) {
console.info(`entering entry component TEAM DETAIL`, model);
return flip(processApplicationRenderTeamDetailScreen)({ model })
},
[STATE_REVIEW]: function showViewStateReview(model) {
console.info(`entering entry component REVIEW`, model);
return flip(processApplicationRenderReviewScreen)({ model })
},
[STATE_APPLIED]: function showViewStateApplied(model) {
console.info(`entering entry component APPLIED`, model);
return processApplicationRenderApplied
},
};
export const fsmSettings = {
initial_model: {},
init_event_data: {},
sinkNames: sinkNames,
debug: true
};
|
(function(angular){
"use strict";
angular.module('main')
.config([
'$routeProvider',
function ($routeProvider) {
$routeProvider
.when('/users', {controller: 'usersCtrl', templateUrl: 'main/users'});
}
])
.controller('usersCtrl', ['$scope', 'apUserCollection',
function($scope, apUserCollection){
apUserCollection.find().success(function (data) {
$scope.users = data;
});
}])
;
})(angular);
|
var chai = require("chai");
var _ = require("underscore");
_.mixin(require('../src/underscore.parse'));
describe("underscore.parse", function() {
it("should parse boolean", function() {
chai.expect(_.parse("true")).to.equal(true);
chai.expect(_.parse("false")).to.equal(false);
});
it("should parse null", function() {
chai.expect(_.parse("null")).to.equal(null);
});
it("should parse undefined", function() {
chai.expect(_.parse("undefined")).to.equal(undefined);
});
it("should parse integer", function() {
chai.expect(_.parse("10")).to.equal(10);
});
it("should parse float", function() {
chai.expect(_.parse("10.5")).to.equal(10.5);
});
it("should parse array", function() {
chai.expect(_.parse("[1, true, null]")).to.be.an("array");
});
it("should parse object", function() {
chai.expect(_.parse('{"foo": {"bar": 123}}')).to.be.an("object");
});
it("should parse string", function() {
chai.expect(_.parse("foo")).to.equal("foo");
});
});
|
module.exports = `MARKDOWN:
Studentenes Kameraklubb is a meeting point for students who are
intereseted in photography in Trondheim. The club has a long history reaching
back to 1938. Our facilities are situated at Moholt Studentby, where all members
have access. You can chill on the couch, converse about photography, utilize our
studio or edit images in our computer room. In addition, we are very proud of
our own darkroom with all the nessescary equipment to develop analog film for
those of you who are so inclined.
`;
|
// make the editting groups box less wide
// and add alternating row colors
$("#edit_group_href").click(function () {
var groupTable = $("#group_list");
groupTable.width(300);
groupTable.find("th:first").attr("colspan", "3");
var mod = 0;
groupTable.find("tr:gt(0)").each(function () {
mod++;
$(this).addClass("row_" + (mod % 2 == 0 ? "a" : "b"));
});
});
// change troops overview link to active sangu page
if (user_data.command.changeTroopsOverviewLink) {
var troopsOverviewLink = $("#overview_menu a[href*='mode=units']");
troopsOverviewLink.attr("href", troopsOverviewLink.attr("href") + "&type=own_home");
}
if (user_data.overviews.addFancyImagesToOverviewLinks) {
var overviewLinks = $("#overview_menu a");
overviewLinks.each(function(index) {
var overviewLink = $(this),
imageToAdd = "";
switch (index) {
case 0:
// overviewLink.parent()
// .css("background-image", 'url("https://www.tribalwars.vodka/graphic/icons/header.png")')
// .css("background-repeat", "no-repeat")
// .css("background-position", "-324px 0px")
// .css("background-size", "200px Auto");
//
// overviewLink.prepend(" ");
break;
case 1:
imageToAdd = "graphic/buildings/storage.png";
break;
case 2:
imageToAdd = "graphic/buildings/market.png";
break;
case 3:
if (overviewLink.parent().hasClass("selected")) {
$("table.modemenu:last a", content_value).each(function(index) {
imageToAdd = "";
switch (index) {
case 1:
imageToAdd = "graphic/buildings/place.png";
break;
case 2:
imageToAdd = "graphic/pfeil.png";
break;
case 3:
case 4:
$(this).css("opacity", "0.5");
break;
case 5:
imageToAdd = "graphic/command/support.png";
break;
case 6:
imageToAdd = "graphic/rechts.png";
break;
}
if (imageToAdd !== "") {
$(this).prepend("<img src='https://www.tribalwars.vodka/"+imageToAdd+"' title='"+overviewLink.text() + " > " + $(this).text()+"' /> ");
}
});
}
imageToAdd = "graphic/unit/unit_knight.png";
break;
case 4:
if (overviewLink.parent().hasClass("selected")) {
$("table.modemenu:last a", content_value).each(function(index) {
imageToAdd = "";
switch (index) {
case 1:
imageToAdd = "graphic/command/attack.png";
break;
case 2:
imageToAdd = "graphic/command/support.png";
break;
case 3:
imageToAdd = "graphic/command/return.png";
break;
}
if (imageToAdd !== "") {
$(this).prepend("<img src='https://www.tribalwars.vodka/"+imageToAdd+"' title='"+overviewLink.text() + " > " + $(this).text()+"' /> ");
}
});
}
imageToAdd = "graphic/command/attack.png";
break;
case 5:
if (overviewLink.parent().hasClass("selected")) {
$("table.modemenu:last a", content_value).each(function(index) {
imageToAdd = "";
switch (index) {
case 1:
imageToAdd = "graphic/command/attack.png";
break;
case 2:
imageToAdd = "graphic/command/support.png";
break;
}
if (imageToAdd !== "") {
$(this).prepend("<img src='https://www.tribalwars.vodka/"+imageToAdd+"' title='"+overviewLink.text() + " > " + $(this).text()+"' /> ");
}
});
}
imageToAdd = "graphic/unit/att.png";
break;
case 6:
imageToAdd = "graphic/buildings/main.png";
break;
case 7:
imageToAdd = "graphic/buildings/smith.png";
break;
case 8:
imageToAdd = "graphic/group_right.png";
overviewLink.prepend("<img src='https://www.tribalwars.vodka/"+imageToAdd+"' title='"+overviewLink.text()+"' /> ");
imageToAdd = "graphic/group_left.png";
break;
case 9:
imageToAdd = "graphic/premium/coinbag_14x14.png";
overviewLink.parent().width(150);
break;
}
if (imageToAdd !== "") {
overviewLink.prepend("<img src='https://www.tribalwars.vodka/"+imageToAdd+"' title='"+overviewLink.text()+"' /> ");
}
});
}
|
import React from 'react'
import styled from 'styled-components'
const ReactIcon = () => {
return (
<span>
<Icon
src="https://d1xwtr0qwr70yv.cloudfront.net/assets/tech/react-6c1ac47e0329377f8fe4f71455cefb51.svg"
alt="ReactIcon"
/>
</span>
)
}
const Icon = styled.img`
/* overwrite react-slick */
display: unset !important;
/* animation */
animation: ReactIcon-logo-spin 30s linear infinite;
@keyframes ReactIcon-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
`
export default ReactIcon
|
/**
* SVGInjector v1.1.3 - Fast, caching, dynamic inline SVG DOM injection library
* https://github.com/iconic/SVGInjector
*
* Copyright (c) 2014-2015 Waybury <hello@waybury.com>
* @license MIT
*/
(function(window, document) {
'use strict';
// Environment
var isLocal = window.location.protocol === 'file:';
var hasSvgSupport = document.implementation.hasFeature('http://www.w3.org/TR/SVG11/feature#BasicStructure', '1.1');
function uniqueClasses(list) {
list = list.split(' ');
var hash = {};
var i = list.length;
var out = [];
while (i--) {
if (!hash.hasOwnProperty(list[i])) {
hash[list[i]] = 1;
out.unshift(list[i]);
}
}
return out.join(' ');
}
/**
* cache (or polyfill for <= IE8) Array.forEach()
* source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
*/
var forEach = Array.prototype.forEach || function(fn, scope) {
if (this === void 0 || this === null || typeof fn !== 'function') {
throw new TypeError();
}
/* jshint bitwise: false */
var i, len = this.length >>> 0;
/* jshint bitwise: true */
for (i = 0; i < len; ++i) {
if (i in this) {
fn.call(scope, this[i], i, this);
}
}
};
// SVG Cache
var svgCache = {};
var injectCount = 0;
var injectedElements = [];
// Request Queue
var requestQueue = [];
// Script running status
var ranScripts = {};
var cloneSvg = function(sourceSvg) {
return sourceSvg.cloneNode(true);
};
var queueRequest = function(url, callback) {
requestQueue[url] = requestQueue[url] || [];
requestQueue[url].push(callback);
};
var processRequestQueue = function(url) {
for (var i = 0, len = requestQueue[url].length; i < len; i++) {
// Make these calls async so we avoid blocking the page/renderer
/* jshint loopfunc: true */
(function(index) {
setTimeout(function() {
requestQueue[url][index](cloneSvg(svgCache[url]));
}, 0);
})(i);
/* jshint loopfunc: false */
}
};
var loadSvg = function(url, callback) {
if (svgCache[url] !== undefined) {
if (svgCache[url] instanceof SVGSVGElement) {
// We already have it in cache, so use it
callback(cloneSvg(svgCache[url]));
} else {
// We don't have it in cache yet, but we are loading it, so queue this request
queueRequest(url, callback);
}
} else {
if (!window.XMLHttpRequest) {
callback('Browser does not support XMLHttpRequest');
return false;
}
// Seed the cache to indicate we are loading this URL already
svgCache[url] = {};
queueRequest(url, callback);
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
// readyState 4 = complete
if (httpRequest.readyState === 4) {
// Handle status
if (httpRequest.status === 404 || httpRequest.responseXML === null) {
callback('Unable to load SVG file: ' + url);
if (isLocal) callback('Note: SVG injection ajax calls do not work locally without adjusting security setting in your browser. Or consider using a local webserver.');
callback();
return false;
}
// 200 success from server, or 0 when using file:// protocol locally
if (httpRequest.status === 200 || (isLocal && httpRequest.status === 0)) {
/* globals Document */
if (httpRequest.responseXML instanceof Document) {
// Cache it
svgCache[url] = httpRequest.responseXML.documentElement;
}
/* globals -Document */
// IE9 doesn't create a responseXML Document object from loaded SVG,
// and throws a "DOM Exception: HIERARCHY_REQUEST_ERR (3)" error when injected.
//
// So, we'll just create our own manually via the DOMParser using
// the the raw XML responseText.
//
// :NOTE: IE8 and older doesn't have DOMParser, but they can't do SVG either, so...
else if (DOMParser && (DOMParser instanceof Function)) {
var xmlDoc;
try {
var parser = new DOMParser();
xmlDoc = parser.parseFromString(httpRequest.responseText, 'text/xml');
} catch (e) {
xmlDoc = undefined;
}
if (!xmlDoc || xmlDoc.getElementsByTagName('parsererror').length) {
callback('Unable to parse SVG file: ' + url);
return false;
} else {
// Cache it
svgCache[url] = xmlDoc.documentElement;
}
}
// We've loaded a new asset, so process any requests waiting for it
processRequestQueue(url);
} else {
callback('There was a problem injecting the SVG: ' + httpRequest.status + ' ' + httpRequest.statusText);
return false;
}
}
};
httpRequest.open('GET', url);
// Treat and parse the response as XML, even if the
// server sends us a different mimetype
if (httpRequest.overrideMimeType) httpRequest.overrideMimeType('text/xml');
httpRequest.send();
}
};
// Inject a single element
var injectElement = function(el, evalScripts, pngFallback, callback) {
// Grab the src or data-src attribute
var imgUrl = el.getAttribute('data-src') || el.getAttribute('src');
// We can only inject SVG
if (!(/\.svg/i).test(imgUrl)) {
callback('Attempted to inject a file with a non-svg extension: ' + imgUrl);
return;
}
// If we don't have SVG support try to fall back to a png,
// either defined per-element via data-fallback or data-png,
// or globally via the pngFallback directory setting
if (!hasSvgSupport) {
var perElementFallback = el.getAttribute('data-fallback') || el.getAttribute('data-png');
// Per-element specific PNG fallback defined, so use that
if (perElementFallback) {
el.setAttribute('src', perElementFallback);
callback(null);
}
// Global PNG fallback directoriy defined, use the same-named PNG
else if (pngFallback) {
el.setAttribute('src', pngFallback + '/' + imgUrl.split('/').pop().replace('.svg', '.png'));
callback(null);
}
// um...
else {
callback('This browser does not support SVG and no PNG fallback was defined.');
}
return;
}
// Make sure we aren't already in the process of injecting this element to
// avoid a race condition if multiple injections for the same element are run.
// :NOTE: Using indexOf() only _after_ we check for SVG support and bail,
// so no need for IE8 indexOf() polyfill
if (injectedElements.indexOf(el) !== -1) {
return;
}
// Remember the request to inject this element, in case other injection
// calls are also trying to replace this element before we finish
injectedElements.push(el);
// Try to avoid loading the orginal image src if possible.
el.setAttribute('src', '');
// Load it up
loadSvg(imgUrl, function(svg) {
if (typeof svg === 'undefined' || typeof svg === 'string') {
callback(svg);
return false;
}
var imgId = el.getAttribute('id');
if (imgId) {
svg.setAttribute('id', imgId);
}
var imgTitle = el.getAttribute('title');
if (imgTitle) {
svg.setAttribute('title', imgTitle);
}
// Concat the SVG classes + 'injected-svg' + the img classes
var classMerge = [].concat(svg.getAttribute('class') || [], 'injected-svg', el.getAttribute('class') || []).join(' ');
svg.setAttribute('class', uniqueClasses(classMerge));
var imgStyle = el.getAttribute('style');
if (imgStyle) {
svg.setAttribute('style', imgStyle);
}
// Copy all the data elements to the svg
var imgData = [].filter.call(el.attributes, function(at) {
return (/^data-\w[\w\-]*$/).test(at.name);
});
forEach.call(imgData, function(dataAttr) {
if (dataAttr.name && dataAttr.value) {
svg.setAttribute(dataAttr.name, dataAttr.value);
}
});
// Make sure any internally referenced clipPath ids and their
// clip-path references are unique.
//
// This addresses the issue of having multiple instances of the
// same SVG on a page and only the first clipPath id is referenced.
//
// Browsers often shortcut the SVG Spec and don't use clipPaths
// contained in parent elements that are hidden, so if you hide the first
// SVG instance on the page, then all other instances lose their clipping.
// Reference: https://bugzilla.mozilla.org/show_bug.cgi?id=376027
// Handle all defs elements that have iri capable attributes as defined by w3c: http://www.w3.org/TR/SVG/linking.html#processingIRI
// Mapping IRI addressable elements to the properties that can reference them:
var iriElementsAndProperties = {
'clipPath': ['clip-path'],
'color-profile': ['color-profile'],
'cursor': ['cursor'],
'filter': ['filter'],
'linearGradient': ['fill', 'stroke'],
'marker': ['marker', 'marker-start', 'marker-mid', 'marker-end'],
'mask': ['mask'],
'pattern': ['fill', 'stroke'],
'radialGradient': ['fill', 'stroke']
};
var element, elementDefs, properties, currentId, newId;
Object.keys(iriElementsAndProperties).forEach(function(key) {
element = key;
properties = iriElementsAndProperties[key];
elementDefs = svg.querySelectorAll('defs ' + element + '[id]');
for (var i = 0, elementsLen = elementDefs.length; i < elementsLen; i++) {
currentId = elementDefs[i].id;
newId = currentId + '-' + injectCount;
// All of the properties that can reference this element type
var referencingElements;
forEach.call(properties, function(property) {
// :NOTE: using a substring match attr selector here to deal with IE "adding extra quotes in url() attrs"
referencingElements = svg.querySelectorAll('[' + property + '*="' + currentId + '"]');
for (var j = 0, referencingElementLen = referencingElements.length; j < referencingElementLen; j++) {
referencingElements[j].setAttribute(property, 'url(#' + newId + ')');
}
});
elementDefs[i].id = newId;
}
});
// Remove any unwanted/invalid namespaces that might have been added by SVG editing tools
svg.removeAttribute('xmlns:a');
// Post page load injected SVGs don't automatically have their script
// elements run, so we'll need to make that happen, if requested
// Find then prune the scripts
var scripts = svg.querySelectorAll('script');
var scriptsToEval = [];
var script, scriptType;
for (var k = 0, scriptsLen = scripts.length; k < scriptsLen; k++) {
scriptType = scripts[k].getAttribute('type');
// Only process javascript types.
// SVG defaults to 'application/ecmascript' for unset types
if (!scriptType || scriptType === 'application/ecmascript' || scriptType === 'application/javascript') {
// innerText for IE, textContent for other browsers
script = scripts[k].innerText || scripts[k].textContent;
// Stash
scriptsToEval.push(script);
// Tidy up and remove the script element since we don't need it anymore
svg.removeChild(scripts[k]);
}
}
// Run/Eval the scripts if needed
if (scriptsToEval.length > 0 && (evalScripts === 'always' || (evalScripts === 'once' && !ranScripts[imgUrl]))) {
for (var l = 0, scriptsToEvalLen = scriptsToEval.length; l < scriptsToEvalLen; l++) {
// :NOTE: Yup, this is a form of eval, but it is being used to eval code
// the caller has explictely asked to be loaded, and the code is in a caller
// defined SVG file... not raw user input.
//
// Also, the code is evaluated in a closure and not in the global scope.
// If you need to put something in global scope, use 'window'
new Function(scriptsToEval[l])(window); // jshint ignore:line
}
// Remember we already ran scripts for this svg
ranScripts[imgUrl] = true;
}
// :WORKAROUND:
// IE doesn't evaluate <style> tags in SVGs that are dynamically added to the page.
// This trick will trigger IE to read and use any existing SVG <style> tags.
//
// Reference: https://github.com/iconic/SVGInjector/issues/23
var styleTags = svg.querySelectorAll('style');
forEach.call(styleTags, function(styleTag) {
styleTag.textContent += '';
});
// Replace the image with the svg
el.parentNode.replaceChild(svg, el);
// Now that we no longer need it, drop references
// to the original element so it can be GC'd
delete injectedElements[injectedElements.indexOf(el)];
el = null;
// Increment the injected count
injectCount++;
callback(svg);
});
};
/**
* SVGInjector
*
* Replace the given elements with their full inline SVG DOM elements.
*
* :NOTE: We are using get/setAttribute with SVG because the SVG DOM spec differs from HTML DOM and
* can return other unexpected object types when trying to directly access svg properties.
* ex: "className" returns a SVGAnimatedString with the class value found in the "baseVal" property,
* instead of simple string like with HTML Elements.
*
* @param {mixes} Array of or single DOM element
* @param {object} options
* @param {function} callback
* @return {object} Instance of SVGInjector
*/
var SVGInjector = function(elements, options, done) {
// Options & defaults
options = options || {};
// Should we run the scripts blocks found in the SVG
// 'always' - Run them every time
// 'once' - Only run scripts once for each SVG
// [false|'never'] - Ignore scripts
var evalScripts = options.evalScripts || 'always';
// Location of fallback pngs, if desired
var pngFallback = options.pngFallback || false;
// Callback to run during each SVG injection, returning the SVG injected
var eachCallback = options.each;
// Do the injection...
if (elements.length !== undefined) {
var elementsLoaded = 0;
forEach.call(elements, function(element) {
injectElement(element, evalScripts, pngFallback, function(svg) {
if (eachCallback && typeof eachCallback === 'function') eachCallback(svg);
if (done && elements.length === ++elementsLoaded) done(elementsLoaded);
});
});
} else {
if (elements) {
injectElement(elements, evalScripts, pngFallback, function(svg) {
if (eachCallback && typeof eachCallback === 'function') eachCallback(svg);
if (done) done(1);
elements = null;
});
} else {
if (done) done(0);
}
}
};
/* global module, exports: true, define */
// Node.js or CommonJS
if (typeof module === 'object' && typeof module.exports === 'object') {
module.exports = exports = SVGInjector;
}
// AMD support
else if (typeof define === 'function' && define.amd) {
define(function() {
return SVGInjector;
});
}
// Otherwise, attach to window as global
else if (typeof window === 'object') {
window.SVGInjector = SVGInjector;
}
/* global -module, -exports, -define */
}(window, document));
|
M.spinner = {
show: function(miracle) {
if (typeof Spinner != 'undefined' && miracle.spinner.use) {
var spinnerStyle, spinnerStyleName;
/* (trick) Because we can't make opaque spinner inside transparent miracle
we need to make miracle opaque until miracle show starts */
miracle.$.css('opacity', '1');
miracle.$.css('visibility', 'hidden');
/* Check for custom spinner style */
if (miracle.spinner.style) {
spinnerStyleName = miracle.spinner.style;
if (M.settings.spinner.style[spinnerStyleName]) {
spinnerStyle = M.settings.spinner.style[spinnerStyleName];
} else {
spinnerStyle = M.settings.spinner.style.def;
}
} else {
spinnerStyle = M.settings.spinner.style.def;
}
/* Create spinner */
miracle.spinner.this = new Spinner(spinnerStyle).spin();
/* Get spinner element */
miracle.spinner.$ = $(miracle.spinner.this.el);
/* Styles to center spinner inside miracle */
miracle.spinner.$.css({
top: '50%',
left: '50%',
visibility: 'visible'
});
/* Add spinner inside miracle */
miracle.$[0].appendChild(miracle.spinner.this.el)
}
},
hide: function(miracle) {
if (typeof Spinner != 'undefined' && miracle.spinner.use) {
var spinnerFadeTimeout = M.settings.spinnerFadeTimeout;
/* (trick) Remove styles which made spinner visible. See M.showSpinner */
miracle.$.css('opacity', '');
miracle.$.css('visibility', '');
/* make spinner fade out smooth */
var transition = 'opacity ' + M.settings.spinnerFadeTimeout + 'ms ' + ' ease-in-out';
miracle.spinner.$.css({
transition: transition,
opacity : 0
});
setTimeout(function() {
/* timeout for smooth spinner fade out before spinner stopping */
miracle.spinner.this.stop();
}, spinnerFadeTimeout);
}
}
}
|
angular.module('genome.about', [])
.controller('AboutController', function ($scope, $rootScope, $location) {
var whichView = function() {
$rootScope.view = $location.$$path;
}
whichView();
$scope.images = [{
name: 'Gar Lee',
pic: '../../../static/assets/gar.png',
link: 'https://github.com/LeeGar'
},
{
name: 'Peter Lollo',
pic: '../../static/assets/peterGit.jpeg',
link: 'https://github.com/peterlollo'
},
{
name: 'Alex Anthony',
pic: '../../static/assets/alexGit.jpeg',
link: 'https://github.com/alexanthony813'
},
{
name: 'Chris Bassano',
pic: '../../static/assets/chrisGit.jpeg',
link: 'https://github.com/christo4b'
}];
})
|
import { getTimeOfDay } from './get-time-of-day';
export function greet(name = 'friend') {
const timeOfDay = getTimeOfDay();
return `Good ${timeOfDay}, ${name}!`;
}
|
/**
* Created by daiyingheng on 16/9/9.
*/
import React from 'react';
import {Link} from 'react-router';
import SearchActions from '../actions/SearchActions';
import SearchStore from '../stores/SearchStore';
class Search extends React.Component {
constructor(props) {
super(props);
this.state = SearchStore.getState();
this.onChange = this.onChange.bind(this);
}
componentDidMount() {
SearchStore.listen(this.onChange);
SearchActions.search(this.props.params.search);
}
componentWillUnmount() {
SearchStore.unlisten(this.onChange);
}
componentDidUpdate(prevProps) {
if (prevProps.params.search !== this.props.params.search) {
SearchActions.search(this.props.params.search)
}
}
onChange(state) {
this.setState(state);
}
render() {
var animes = this.state.animes.map((anime, index) => {
return (
<tr key={ anime._id } id={"animeList"+index}>
<td><img src={anime.post.small} alt=""/></td>
<td>{ anime.title} </td>
<td>{ anime.score }</td>
<td>{ anime.director }</td>
<td>{ anime.date}</td>
<td>{ anime.country }</td>
</tr>
)
});
var articles = this.state.articles.map((article, index) => {
return (
<tr key={article.articleId}>
<td><Link to={'/article/'+ article.articleId}>{article.title}</Link></td>
<td>{article.date.date}</td>
<td>{article.cate1}/{article.cate2}/{article.cate3}</td>
<td>
<div className='summary' dangerouslySetInnerHTML={{__html: article.summary}}></div>
</td>
</tr>
)
});
return (
<div className="admin_right col-md-10 col-xs-10 col-sm-10">
{ articles.length != 0 ? <div>
<h2>文章: </h2><br/>
<table className="table table-striped table-bordered">
<tr>
<td>标题</td>
<td>日期</td>
<td>分类</td>
<td>摘要</td>
</tr>
<tbody>
{articles}
</tbody>
</table>
</div>:'' }
{ animes.length != 0 ? <div>
<h2>动漫: </h2><br/>
<table className="table table-striped table-bordered">
<tr>
<td>缩略图</td>
<td>名字</td>
<td>评分</td>
<td>导演</td>
<td>年份</td>
<td>国家</td>
</tr>
<tbody>
{animes}
</tbody>
</table>
</div>:'' }
{animes.length == 0 && articles.length == 0 ?'没有搜到相关结果':''}
</div>
);
}
}
export default Search;
|
$(function () {
navigator.geolocation.getCurrentPosition(
function(e) { //成功回调
console.log(e.coords.accuracy); //准确度
console.log(e.coords.latitude); //纬度
console.log(e.coords.longitude); //经度
console.log(e.coords.altitude); //海拔高度
console.log(e.coords.altitudeAccuracy); //海拔高度的精确度
console.log(e.coords.heading); //行进方向
console.log(e.coords.speed); //地面的速度
console.log(new Date(e.timestamp).toLocaleDateString());//采集日期
console.log(new Date(e.timestamp).toLocaleTimeString());//采集时间
//调用百度api
translatePoint(e.coords.longitude, e.coords.latitude);
},
function(e) { //失败回调
console.log(e.message); //错误信息
console.log(e.code); //错误代码
},
{//可选参数 JSON格式
"enableHighAcuracy": false, //是否启用高精确度模
"timeout": 100, //在指定的时间内获取位置信息
"maximumAge": 0//浏览器重新获取位置信息的时间间隔
}
);
});
// function locationSuccess(point, AddressComponent){
// }
var map;
function translatePoint(longitude, latitude){
var gpsPoint = new BMap.Point(longitude, latitude);
BMap.Convertor.translate(gpsPoint, 0, initMap); //转换坐标
// var point = new BMap.Point(longitude, latitude);
}
function initMap(point) {
map = new BMap.Map("baidumap");
map.centerAndZoom(point, 15);
map.setCurrentCity("上海");
map.addControl(new BMap.GeolocationControl());
var marker = new BMap.Marker(point); // 创建标注
map.addOverlay(marker);
map.addControl(new BMap.GeolocationControl());
var opts = {
width : 250, // 信息窗口宽度
height: 100, // 信息窗口高度
title : "Hello" // 信息窗口标题
}
var infoWindow = new BMap.InfoWindow("这是您目前的位置", opts); // 创建信息窗口对象
map.openInfoWindow(infoWindow, map.getCenter());
}
// function searchCurrent(address){
// var options = {
// onSearchComplete: function(results){
// if (local.getStatus() == BMAP_STATUS_SUCCESS){
// // 判断状态是否正确
// var s = [];
// for (var i = 0; i < results.getCurrentNumPois(); i ++){
// s.push("<div class='log-d'>"+results.getPoi(i).title + " - " + results.getPoi(i).address +"<input type='button' value='Go' onclick='searchTransit()'/> </div>");
// }
// document.getElementById("log").innerHTML = s;
// }
// },
// renderOptions:{map: map}
// };
// var local = new BMap.LocalSearch(map, options);
// // var local = new BMap.LocalSearch(map, {
// // renderOptions:{map: map}
// // });
// local.searchInBounds(address,map.getBounds());
// }
// function goseach(){
// console.log($('.seachinput').val())
// if($('.seachinput').val()){
// searchCurrent($('.seachinput').val());
// }
// }
// function searchTransit(){
// // alert('a');
// var transit = new BMap.TransitRoute(map, {
// renderOptions: {map: map, panel: "log"}
// });
// transit.search("国定路69号", map.getBounds());
// }
// var map = new BMap.Map("baidumap"); // 创建地图实例
// var point = new BMap.Point(116.404, 39.915); // 创建点坐标
// map.centerAndZoom(point, 15);
|
window.pdfMake = window.pdfMake || {}; window.pdfMake.fonts = {"Miniver":{"normal":"Miniver-Regular.ttf","bold":"Miniver-Regular.ttf","italics":"Miniver-Regular.ttf","bolditalics":"Miniver-Regular.ttf"}};
|
/**
* Created by meiqiyuan on 2017/9/20.
*/
require('runkoa')(__dirname + '/entry.js');
|
var path = require('path');
var fs = require('fs');
var gulp = require('gulp');
var utils = require('gulp-util');
var log = utils.log; // Can be used for logging
gulp.task('vendors', function () {
// Get all bower components, but use the minified file
// if it already exists
var bowerFiles = require('main-bower-files');
var files = bowerFiles().map(convertFile);
// Create a filter for files that are not minified
var filter = require('gulp-filter');
var unminified = filter(function (file) {
var basename = path.basename(file.path);
var min = basename.indexOf('.min') === -1;
return min;
});
var concat = require('gulp-concat');
//var uglify = require('gulp-uglify');
gulp.src(files)
//.pipe(unminified) // Filter out minified files
//.pipe(uglify()) // Minify unminified files
//.pipe(unminified.restore()) // Restore minified files
.pipe(concat('vendors.js')) // Concat all files into one file
.pipe(gulp.dest('dist')); // Write to destination folder
});
/**
* Convert the path to a JS file to the minified version, if it exists.
*
* @param file {String} The full path to the JS file
* @returns {String} The minified file path if it exists, otherwise the
* original file path
*/
function convertFile(file) {
var ext = path.extname(file);
var min = file.substr(0, file.length - ext.length);
min += '.min' + ext;
return fs.existsSync(min) ? min : file;
}
|
$(function() {
function ArticleViewModel(article) {
var self = this;
$.extend(this, article)
self.summaryTextTruncated = window.AppUtils.cropText(article.summaryText, 100);
// add / before image url to make it relative to site root
self.images = self.images.map(function(image) {
return "/" + image;
});
self.timeString = window.AppUtils.computeTimeString(article.publishedOn);
self.highlights = !!self.highlights ? self.highlights.slice(0, 4) : [];
}
window.ArticleViewModel = ArticleViewModel;
});
|
/* global module:false */
module.exports = function (grunt) {
'use strict';
// Project configuration
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
meta: {
banner:
'/*!\n' +
' * Perimeter.js <%= pkg.version %> (<%= grunt.template.today("yyyy-mm-dd, HH:MM") %>)\n' +
' * https://github.com/e-sites/perimeter.js\n' +
' * MIT licensed\n' +
' *\n' +
' * Copyright (C) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>, <%= pkg.author.web %>\n' +
' */'
},
concat: {
options: {
separator: "\n\n"
},
// used to copy to dist folder
dist: {
files: {
'dist/perimeter.debug.js': ['src/perimeter.js', 'src/monitor.js', 'src/boundary.js'],
'dist/perimeter.js': ['src/perimeter.js', 'src/monitor.js']
}
}
},
jshint: {
options: {
jshintrc: '.jshintrc',
force: true
},
files: ['dist/perimeter.debug.js', 'dist/perimeter.js']
},
uglify: {
options: {
banner: '<%= meta.banner %>\n'
},
build: {
files: {
'dist/perimeter.debug.min.js': ['dist/perimeter.debug.js'],
'dist/perimeter.min.js': ['dist/perimeter.js']
}
}
},
qunit: {
all: {
options: {
timeout: 7000,
urls: [
'tests/index.html'
]
}
}
}
});
// Dependencies
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-qunit');
// Default task
grunt.registerTask( 'default', [ 'concat', 'jshint', 'uglify', 'qunit'] );
};
|
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require('@angular/core');
var router_1 = require('@angular/router');
var authentication_service_1 = require('../_services/authentication.service');
var app_container_component_1 = require('../app-container.component');
var GoogleLoginComponent = (function () {
function GoogleLoginComponent(router, authenticationService, appContainer, appRef) {
this.router = router;
this.authenticationService = authenticationService;
this.appContainer = appContainer;
this.appRef = appRef;
}
// Angular hook that allows for interaction with elements inserted by the rendering of a view
GoogleLoginComponent.prototype.ngAfterViewInit = function () {
var that = this;
// Signout if already signed in
gapi.load('auth2', function () {
// Retrieve the singleton for the GoogleAuth library and set up the client.
var auth2 = gapi.auth2.init({
client_id: '60286824468-tiuo7kh57c7e2ja6hvsobirjpst714n1.apps.googleusercontent.com',
cookiepolicy: 'single_host_origin',
})
.then(function () { return that.logout(); });
});
};
GoogleLoginComponent.prototype.logout = function () {
var _this = this;
var auth2 = gapi.auth2.getAuthInstance().signOut().then(function () {
_this.renderLogin();
});
};
GoogleLoginComponent.prototype.renderLogin = function () {
var _this = this;
// console.log('gapi.signin2.render');
gapi.signin2.render('gdbtn', {
'scope': 'profile',
'longtitle': true,
'width': 240,
'theme': 'light',
'onsuccess': function (resp) { return _this.onGoogleLoginSuccess(resp); },
'onfailure': function () { return _this.onGoogleLoginFailed(); }
});
};
// Triggered after a user successfully logs in using the Google external login provider.
GoogleLoginComponent.prototype.onGoogleLoginSuccess = function (resp) {
var _this = this;
// console.log('onGoogleLoginSuccess');
var source = 'google';
var token = resp.Zi.access_token;
this.authenticationService.login(source, token)
.subscribe(function (result) {
if (result === true) {
// login successful
_this.appContainer.reload();
_this.router.navigate(['/']);
_this.appRef.tick();
}
else {
}
});
};
GoogleLoginComponent.prototype.onGoogleLoginFailed = function () {
console.log('onGoogleLoginFailed');
};
GoogleLoginComponent = __decorate([
core_1.Component({
moduleId: module.id,
selector: 'google-login',
templateUrl: 'googlelogin.component.html'
}),
__metadata('design:paramtypes', [router_1.Router, authentication_service_1.AuthenticationService, app_container_component_1.AppContainerComponent, core_1.ApplicationRef])
], GoogleLoginComponent);
return GoogleLoginComponent;
}());
exports.GoogleLoginComponent = GoogleLoginComponent;
//# sourceMappingURL=googlelogin.component.js.map
|
'use strict';
var express = require('express'),
passport = require('passport'),
auth = require('../lib/auth'),
userLib = require('./user')(),
db = require('../lib/database'),
crypto = require('../lib/crypto');
module.exports = function spec(app) {
app.on('middleware:after:session', function configPassport(eventargs) {
//Tell passport to use our newly created local strategy for authentication
passport.use(auth.localStrategy());
//Give passport a way to serialize and deserialize a user. In this case, by the user's id.
passport.serializeUser(userLib.serialize);
passport.deserializeUser(userLib.deserialize);
app.use(passport.initialize());
app.use(passport.session());
});
return {
onconfig: function(config, next) {
var dbConfig = config.get('databaseConfig'),
cryptConfig = config.get('bcrypt');
crypto.setCryptLevel(cryptConfig.difficulty);
db.config(dbConfig);
userLib.addUsers();
next(null, config);
}
};
};
|
/**
* Created by uqybarta on 25/09/2014.
*/
'use strict';
angular.module('uql')
.controller('uqlCtrl', ['$rootScope', '$window', 'UQL_CONFIG', function ($rootScope, $window, UQL_CONFIG) {
$rootScope.appClass = '';
$rootScope.$on('$stateChangeSuccess', function (event, toState) {
if (toState.data && toState.data.hasOwnProperty('pageTitle')) {
$window.document.title = toState.data.pageTitle;
} else if (UQL_CONFIG.defaultPageTitle) {
$window.document.title = UQL_CONFIG.defaultPageTitle;
}
if (toState.data && toState.data.hasOwnProperty('appClass')) {
$rootScope.appClass = toState.data.appClass;
} else {
$rootScope.appClass = '';
}
});
}]);
|
/* Particle */
function setParticle() {
if($('#particles-js').length != 0){
particlesJS.load('particles-js', 'http://127.0.0.1/luc2017/web/js/particle/particlesjs-config.json');
}
if($('#particles-light-js').length != 0){
particlesJS.load('particles-light-js', 'http://127.0.0.1/luc2017/web/js/particle/particlesjs-config-light.json');
}
if($('#particles-forme-js').length != 0){
particlesJS.load('particles-forme-js', 'http://127.0.0.1/luc2017/web/js/particle/particlesjs-config-contact.json');
}
}
function navAnimate(elem){
var url = (elem.attr('data-url') != undefined) ? elem.attr('data-url') : elem.attr('href') ;
$('.main').removeClass('current');
setTimeout(function(){
window.location.href = url;
}, 450);
}
/* Ouverture menu */
function reveal_board() {
$('.menuContenu ul li a').each(function(index) {
var that = this;
var t = setTimeout(function() {
$(that).addClass('current');
}, 100 * index);
});
}
$(function(){
BrowserDetect.init();
var bv= BrowserDetect.browser;
if(bv == "Explorer"){
$("body").addClass("ie");
}
/* Animation */
var controller = new ScrollMagic.Controller();
if($('.section1').length != 0) {
new ScrollMagic.Scene({triggerElement: ".section1", duration: $(window).height() + 75 })
.setTween(TweenMax.fromTo(".section1 .section1LogoLeft", 1, {top: $('.section1').height()}, {top: 0}))
.addTo(controller)
.on("progress", function (e) {
var objTop = $('.section1LogoLeft').offset().top;
var scrollTop = $(window).scrollTop()
var menu = $('.menu');
if ((objTop - scrollTop) < 0) {
$('.menu').addClass('current');
} else {
$('.menu').removeClass('current');
}
});
new ScrollMagic.Scene({triggerElement: ".section1", duration:$('.section1').height()})
.setTween(TweenMax.fromTo(".section1 .section1Right img", 1, {scale:0.8}, {scale:1}))
.addTo(controller);
}
if($('.section3').length != 0) {
new ScrollMagic.Scene({triggerElement: ".section3", duration: 500})
.setTween(TweenMax.fromTo(".section3All", 1, {y: 60}, {y: 0}))
.addTo(controller);
new ScrollMagic.Scene({triggerElement: ".section3", duration: 800})
.setTween(TweenMax.fromTo(".section3Nom", 1, {y: -200}, {y: 0}))
.addTo(controller);
new ScrollMagic.Scene({triggerElement: ".section3", duration: $('.section3').height()})
.setTween(TweenMax.fromTo(".section3Competence", 1, {scale: 0.6}, {scale: 1}))
.addTo(controller);
}
if($('.section4').length != 0) {
new ScrollMagic.Scene({triggerElement: ".section4", duration: $('.section4').height()})
.setTween(TweenMax.fromTo(".section4Background", 1, {scale:0}, {scale:1}))
.addTo(controller);
}
$(document).on('click','.menuBtn',function(){
var btn = $(this);
var menu = $('.menuContenu');
if(btn.hasClass('current')){
btn.removeClass('current');
menu.addClass('out');
setTimeout(function() {
menu.removeClass('current out');
menu.find('ul li a').removeClass('current');
},200);
}else{
menu.removeClass('current out');
menu.find('ul li a').removeClass('current');
btn.addClass('current');
menu.addClass('current');
reveal_board();
}
});
/* Position du SVG pinelli */
if($('.section3Nom').length){
$('.section3Nom').css({left:($('.section3 .inner h2').offset().left - 62)});
}
/* Formulaire de contact */
$(document).on('focusin','.form-elem',function(){
var elem = $(this);
var group = elem.parent('.form-group');
$.each($('.form-group'), function(key, value) {
var group = $(value);
if(group.find('.form-elem').val() == '') group.removeClass('current');
});
group.addClass('current');
});
$(document).on('focusout','.form-elem',function(){
$.each($('.form-group'), function(key, value) {
var group = $(value);
if(group.find('.form-elem').val() == '') group.removeClass('current');
});
});
/* Soumission du formulaire */
$(document).on('click','.section5Right button',function(e){
e.preventDefault();
var button = $(this);
var url = $('.section5Right form').attr('action');
var html = '';
if(!button.hasClass('currentModule')){
var fd = new FormData(document.getElementById("contactFormJs"));
button.prepend('<i class="fa fa-refresh fa-spin"></i>');
button.addClass('currentModule');
$.ajax(url,{
type: 'POST',
data: fd,
processData: false,
contentType: false,
dataType: 'json',
cache:false
})
.done(function(data){
button.find('.fa').remove();
button.removeClass('currentModule');
/* Supprimer le message si il éxiste déjà */
if($('.message').length) $('.message').remove();
/* Afficher le résultat */
if(data.succes != undefined){
html = '<div class="message" id="succes"><span class="messageCouleur"></span><p>';
html += data.succes;
html += '</p></div>';
/* Reset des champs */
$('input[name="contactbundle_contact[nom]"]').val('');
$('input[name="contactbundle_contact[email]"]').val('');
$('textarea[name="contactbundle_contact[contenu]"]').val('');
$('.form-group').removeClass('current');
}
else{
var label = Object.keys(data.error);
html = '<div class="message" id="erreur"><span class="messageCouleur"></span><p>';
for (var i = 0; i < label.length; i++) {
html += data.error[label[i]][0]+'<br>';
}
html += '</p></div>';
}
/* Afficher le contenu des messages */
$(html).hide().prependTo($('.section5Right')).fadeIn();
})
.fail(function(){
alert('Erreur ajax');
});
}
});
/* navigation */
$(document).on('click','.navAnimate',function(e){
e.preventDefault();
navAnimate($(this));
});
/* Navigation en cliquant sur le menu */
$(document).on('click','.menu li a',function(e){
e.preventDefault();
var elem = $(this);
var ancre = elem.attr('data-ancre');
var home = (!$('body').hasClass('noHome')) ? true : false;
if(home){
if(ancre == undefined) navAnimate(elem);
else{
var offset = $('#'+ancre).offset();
var top = offset.top;
$('body, html').stop().animate({scrollTop:top}, 1200);
}
}else{
navAnimate(elem);
}
});
/* navigation en cliquant sur le logo */
$(document).on('click','.menuLogo a',function(e){
e.preventDefault();
var elem = $(this);
var home = (!$('body').hasClass('noHome')) ? true : false;
if(home){
$('body, html').stop().animate({scrollTop:0}, 1200);
}else{
navAnimate(elem);
}
});
if($('.projetsListe').length != 0){
$('.projetsListe').isotope({
itemSelector: '.projetListe',
percentPosition: true,
filter: '*',
masonery: {
columnWidth: '.projetListe'
}
});
}
/* Changement de catégorie pour la liste des projets */
$(document).on('click','.projetsListeCategorie p',function(e){
var lien = $(this);
var categorie = lien.attr('data-filter');
$('.projetsListe').isotope({
filter: categorie,
});
$('.projetsListeCategorie p').removeClass('current');
lien.addClass('current');
});
/* Navigation extérieur */
$(document).on('click','.navExt',function(e){
e.preventDefault();
var elem = $(this);
var url = elem.attr('data-url');
window.open(url);
});
});
$(window).scroll(function(){
var scroll = $(document).scrollTop();
if(scroll > 10){
if($('.menuContenu.current').length != 0) {
$('.menuBtn').removeClass('current');
$('.menuContenu').addClass('out');
setTimeout(function () {
$('.menuContenu').removeClass('current out');
$('.menuContenu').find('ul li a').removeClass('current');
}, 200);
}
}
});
$(window).on('load', function() {
if($('.projetsListe').length != 0){
$('.projetsListe').isotope({
itemSelector: '.projetListe',
percentPosition: true,
filter: '*',
masonery: {
columnWidth: '.projetListe'
}
});
}
/* Chargement */
if($('.noLoader').length == 0) {
if (sessionStorage.getItem('loader') == null) {
var loaderTime = 3000;
var fadeTime = 800;
sessionStorage.setItem('loader', true);
$('.loaderInner').fadeIn(600);
new Vivus('loaderSvg', {type: 'oneByOne', duration: 280}).play();
} else {
var loaderTime = 1000;
var fadeTime = 400;
$('.loaderInnerPage').fadeIn('fast');
new Vivus('loaderSvgPage', {type: 'oneByOne', duration: 100}).play();
}
setTimeout(function () {
setParticle();
$('.loader').fadeOut(fadeTime);
}, loaderTime);
}else{
$('.loader').hide();
}
/* Zoom sur le titre début de page */
$('.main').addClass('current');
});
$(window).on('resize',function(){
/* Position du SVG pinelli */
if($('.section3Nom').length){
$('.section3Nom').css({left:($('.section3 .inner h2').offset().left - 62)});
}
})
|
'use strict';
var React = require('react'),
ContestantActions = require('../actions/ContestantActions');
var ContestantForm = React.createClass({
propTypes: {
name: React.PropTypes.string
},
getInitialState() {
return {
name: ''
};
},
createContestant(state) {
ContestantActions.create(state);
},
render() {
return (
<div>
<label htmlFor="name">Name</label>
<input id="name" type="text" value={this.state.name} onChange={this._onNameChange}/>
<button onClick={this._onButtonClick}>Add</button>
</div>
);
},
_onButtonClick(event) {
this.createContestant(this.state);
this.setState({name: ''});
},
_onNameChange(event) {
this.setState({
name: event.target.value
});
},
});
module.exports = ContestantForm;
|
// Phantomjs odoo helper
// jshint evil: true, loopfunc: true
/* eslint-disable */
/*
Modified phantomtest.js from odoo ( https://github.com/odoo/odoo/blob/8.0/openerp/tests/phantomtest.js ). It accepts following extra parameters:
* ``sessions`` is dictonary of sessions::
{"session1": {
"url_path": "/web"
"ready": "window",
"login": "admin",
"password": "admin", # by default is the same as login
"timeout": 10, # page loading timeout
}
}
* ``commands`` is a list of commands::
[{"session": "session1",
"extra": "connection_on" | "connection_off" | "connection_slow"
"screenshot": screenshot_name,
"code": "console.log('ok')",
"ready": false, # wait before calling next command
"timeout": 60000, # code execution timeout
}]
* code:
* to communicate between commands, variable ``share`` can be used. It's saved right after execution finish. It's not save in async code (e.g. inside setTimeout function)
* screenshot:
* make screenshot before execution of the code
* filename is /tmp/SESSION-SCREENSHOT-NUM.png
*/
var system = require("system");
function waitFor(condition, callback, timeout, timeoutMessageCallback) {
timeout = timeout || 10000;
var start = new Date();
var prev_result = -1;
(function waitLoop() {
result = condition();
if (result !== prev_result) {
prev_result = result;
console.log("page.evaluate eval result:", result);
}
if (new Date() - start > timeout) {
console.log(
"error",
timeoutMessageCallback
? timeoutMessageCallback()
: "Timeout after " + timeout + " ms"
);
phantom.exit(1);
} else if (result) {
callback();
} else {
setTimeout(waitLoop, 250);
}
})();
}
function waitForReady(page, ready, callback, timeout) {
console.log("PhantomTest: wait for condition:", ready);
waitFor(
function() {
return page.evaluate(function(ready) {
var r = false;
try {
r = Boolean(eval(ready));
} catch (ex) {}
return r;
}, ready);
},
callback,
timeout
);
}
function timeoutMessage() {
return (
"Timeout\nhref: " +
window.location.href +
"\nreferrer: " +
document.referrer +
"\n\n" +
(document.body && document.body.innerHTML)
).replace(/[^a-z0-9\s~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, "*");
}
function blockConnection(requestData, networkRequest) {
console.log("Blocked request:", requestData.url);
networkRequest.abort();
}
function slowConnection(requestData, networkRequest) {
console.log("Request marked as slowConnection:", requestData.url);
networkRequest.setHeader("phantomtest", "slowConnection");
}
var tools = {timeoutMessage: timeoutMessage};
var share = {};
function PhantomTest() {
var self = this;
this.options = JSON.parse(system.args[system.args.length - 1]);
this.inject = this.options.inject || [];
this.origin = "http://" + this.options.host;
this.origin += this.options.port ? ":" + this.options.port : "";
// ----------------------------------------------------
// configure phantom and page
// ----------------------------------------------------
this.pages = {}; // sname -> page
for (var sname in self.options.sessions) {
session = self.options.sessions[sname];
session.timeout = session.timeout
? Math.round(parseFloat(session.timeout) * 1000 - 5000)
: 10000;
var jar = require("cookiejar").create();
this.page = require("webpage").create();
this.page.name = sname;
this.page.cookieJar = jar;
this.pages[sname] = this.page;
jar.addCookie({
domain: this.options.host,
name: "session_id",
value: session.session_id,
});
this.page.viewportSize = {width: 1366, height: 768};
this.page.onError = function(message, trace) {
var msg = [message];
if (trace && trace.length) {
msg.push.apply(
msg,
trace.map(function(frame) {
var result = [" at ", frame.file, ":", frame.line];
if (frame.function) {
result.push(" (in ", frame.function, ")");
}
return result.join("");
})
);
msg.push("(leaf frame on top)");
}
console.log("error", JSON.stringify(msg.join("\n")));
phantom.exit(1);
};
this.page.onAlert = function(message) {
console.log("error", message);
phantom.exit(1);
};
this.page.onConsoleMessage = function(message) {
console.log(message);
};
var pagesLoaded = false;
(function() {
// put it in function to have new variables scope
// (self.page is changed)
var page = self.page;
setTimeout(function() {
if (pagesLoaded) {
return;
}
page.evaluate(function(timeoutMessage) {
var message = timeoutMessage();
console.log("error", message);
}, timeoutMessage);
phantom.exit(1);
}, session.timeout);
var inject = session.inject;
page.onLoadFinished = function(status) {
if (status === "success") {
for (var k in inject) {
var found = false;
var v = inject[k];
var need = v;
var src = v;
if (v[0]) {
need = v[0];
src = v[1];
found = page.evaluate(function(code) {
try {
return Boolean(eval(code));
} catch (e) {
return false;
}
}, need);
}
if (!found) {
console.log("Injecting", src, "needed for", need);
if (!page.injectJs(src)) {
console.log("error", "Cannot inject " + src);
phantom.exit(1);
}
}
}
}
};
})();
} // for (var sname in self.options.sessions){
// ----------------------------------------------------
// run test
// ----------------------------------------------------
this.run = function() {
// load pages and then call runCommands
pages_count = 0;
onPageReady = function() {
pages_count--;
console.log("onPageReady", pages_count);
if (pages_count === 0) {
pagesLoaded = true;
self.runCommands();
}
};
for (var sname in self.pages) {
page = self.pages[sname];
session = self.options.sessions[sname];
var url = self.origin + session.url_path;
// open page
ready = session.ready || "true";
pages_count++;
(function(currentPage, currentSName) {
console.log(
currentSName,
currentPage.name,
"START LOADING",
url,
JSON.stringify(currentPage.cookieJar.cookies)
);
currentPage.open(url, function(status) {
if (status !== "success") {
console.log("error", "failed to load " + url);
phantom.exit(1);
} else {
console.log(
currentSName,
currentPage.name,
"LOADED",
url,
status,
JSON.stringify(currentPage.cookieJar.cookies)
);
// clear localstorage leftovers
currentPage.evaluate(function() {
localStorage.clear();
});
// process ready
waitForReady(currentPage, ready, onPageReady, session.timeout);
}
});
})(page, sname);
} //for (var sname in self.pages){
};
this.runCommands = function() {
console.log("runCommands", JSON.stringify(self.options.commands));
var i = -1;
var timer = null;
function nextCommand() {
if (timer) {
clearTimeout(timer);
}
i++;
if (i == self.options.commands.length) {
return;
}
var command = self.options.commands[i];
var sname = command.session;
var page = self.pages[sname];
var extra = command.extra;
var screenshot = command.screenshot;
var code = command.code || "true";
var ready = command.ready || "true";
if (screenshot) {
console.log("Make screenshot", screenshot);
page.render("/tmp/" + sname + "-" + screenshot + "-" + i + ".png");
}
console.log(
"PhantomTest.runCommands: executing as " +
sname +
" " +
page.name +
": " +
code
);
(function() {
var commandNum = i;
timer = setTimeout(function() {
if (commandNum != i) {
return;
}
page.evaluate(function(tools) {
var message = tools.timeoutMessage();
console.log("error", message);
}, tools);
phantom.exit(1);
}, command.timeout || 60333);
})();
if (extra == "connection_off") {
console.log("Connection is off for", sname);
page.onResourceRequested = blockConnection;
} else if (extra == "connection_on") {
console.log("Connection is reset for", sname);
page.onResourceRequested = null;
} else if (extra == "connection_slow") {
console.log("Request will be marked as slowConnection for", sname);
page.onResourceRequested = slowConnection;
}
share = page.evaluate(
function(code, tools, share) {
eval(code);
return share;
},
code,
tools,
share
);
waitForReady(page, ready, nextCommand, command.timeout);
}
nextCommand();
};
}
// js mode or jsfile mode
if (system.args.length === 2) {
pt = new PhantomTest();
pt.run();
}
// vim:et:
|
const BodyParser = require('./middlewares/body_parser')
class MiddlewareStack{
constructor(router){
this.stack = []
this.router = router
this.use(BodyParser)
}
use(klass, options = {}){
var position = options['position']
delete options.position
if(position){
this.stack.splice(index, 0, new klass(this.app, options))
}else{
this.stack.push(new klass(this.app, options))
}
}
remove(...middlewares){
for(let m of middlewares){
let index = this.stack.indexOf(m)
if(index > -1){
this.stack.splice(index, 1)
}
}
}
go(req, res){
var index = 0, stack = this.stack, router = this.router
req.originalUrl = req.url
function next(){
var middleware = stack[index++]
if(!middleware){
router.handle(req, res)
return
}
middleware.call(req, res, next)
}
next()
}
}
module.exports = MiddlewareStack
|
import Model from 'Engine/Model';
class Skybox extends Model {
constructor() {
const position = new Float32Array([
/* Front */
1.0, -1.0, 1.0,
-1.0, -1.0, 1.0,
-1.0, 1.0, 1.0,
1.0, 1.0, 1.0,
/* Back */
-1.0, -1.0, -1.0,
1.0, -1.0, -1.0,
1.0, 1.0, -1.0,
-1.0, 1.0, -1.0,
/* Left */
-1.0, -1.0, 1.0,
-1.0, -1.0, -1.0,
-1.0, 1.0, -1.0,
-1.0, 1.0, 1.0,
/* Right */
1.0, -1.0, -1.0,
1.0, -1.0, 1.0,
1.0, 1.0, 1.0,
1.0, 1.0, -1.0,
/* Top */
-1.0, 1.0, -1.0,
1.0, 1.0, -1.0,
1.0, 1.0, 1.0,
-1.0, 1.0, 1.0,
/* Bottom */
-1.0, -1.0, 1.0,
1.0, -1.0, 1.0,
1.0, -1.0, -1.0,
-1.0, -1.0, -1.0
]);
const indices = new Uint16Array([
0,1,2, 2,3,0,
4,5,6, 6,7,4,
8,9,10, 10,11,8,
12,13,14, 14,15,12,
16,17,18, 18,19,16,
20,21,22, 22,23,20
]);
const bounds = false;
super({position, indices, bounds});
}
};
export default Skybox;
|
import axios from "axios"
export function fetchTracks(){
return function(dispatch){
dispatch({type:"FETCH_TRACKS_INIT"});
axios.get("https://api.soundcloud.com/tracks?client_id=1AVHvmUbJVx9PaAcjaMka6XvKv2F8eQw")
.then((response)=>{
dispatch({type:"FETCH_TRACKS_FULFILLED", payload: response.data})
})
.catch((err)=>{
dispatch({type:"FETCH_TRACKS_REJECTED",payload: err})
})
}
}
|
import ScrollTrigger from '../src/ScrollTrigger'
// Setup ScrollTrigger with default trigger options
const scroll = new ScrollTrigger({
trigger: {
once: false
},
scroll: {
callback: (position, direction) => {
console.log(position)
}
}
})
// Add all sections to the scroll trigger colllection
scroll.add('.Block')
|
import meta from './form-select.json'
import template from './form-select.html'
import snippet from './snippet.html'
import vsFormSelect from '../../components/form-select'
import docsDemo from '../../components/vuestrap/demo'
import {sizes, states} from '../../utils'
export default {
route: {
path: '/form-select',
name: 'form-select',
meta: {
title: 'Form select',
}
},
template: template,
data() {
return {
meta: meta,
snippet: snippet,
model: 'male',
options: [
{
text: 'Male',
value: 'male',
}, {
text: 'Female',
value: 'female',
},
],
size: 'md',
sizes: sizes,
state: 'default',
states: states,
}
},
components: {
vsFormSelect,
docsDemo,
},
}
|
define(function (require) {
'use strict';
var TestObject = require('lib/test-object');
describe('Testing TestObject', function () {
var testObject = new TestObject();
describe('Test testMethod', function () {
it('returns "test class"', function () {
expect(testObject.testMethod()).to.equal('test class');
});
});
});
});
|
import assign from 'object-assign'
/*
* Build a more dynamic dot path interface for a registry or collection
* that is capable of rebuilding itself when one of the members
* changes, and only lazy loads the paths that are traversed
*/
function reflector (host, startProp, getIdPaths) {
invariant(host, 'provide a host')
invariant(host.type, 'host needs a type')
invariant(idPaths, 'idPaths should be a function')
invariant(startProp, 'provide startProp')
let Interface = class {
}
}
|
const daysMap = {
"0": "Sunday",
"1": "Monday",
"2": "Tuesday",
"3": "Wednesday",
"4": "Thursday",
"5": "Friday",
"6": "Saturday"
};
const monthsMap = {
"0": "Jan",
"1": "Feb",
"2": "Mar",
"3": "Apr",
"4": "May",
"5": "June",
"6": "July",
"7": "Aug",
"8": "Sept",
"9": "Oct",
"10": "Nov",
"11": "Dec"
};
export function convertTemp(kelvin) {
return parseInt(((kelvin - 273.15) * 1.8000 + 32.00), 10)
}
export function getDate(unixTimestmap) {
const date = new Date(unixTimestmap * 1000);
const day = daysMap[date.getDay()]
const month = monthsMap[date.getMonth()] + ' ' + date.getDate();
return day + ', ' + month;
}
|
{
var x = scale
.scaleTime()
.domain([date.local(2009, 0, 1, 0, 17), date.local(2009, 0, 1, 23, 42)]);
test.deepEqual(x.nice().domain(), [
date.local(2009, 0, 1),
date.local(2009, 0, 2)
]);
test.end();
}
|
{
wrapperConstructor.prototype[name] = function() {
return wrapNodeList(
unsafeUnwrap(this)[name].apply(unsafeUnwrap(this), arguments)
);
};
}
|
/**
* @Author: Hao Chen <clovemac>
* @Date: 2017-03-10T00:45:52-05:00
* @Email: hao@genm.co
* @Project: GenmMobile
* @Last modified by: clovemac
* @Last modified time: 2017-03-10T00:46:35-05:00
*/
import thunk from 'redux-thunk';
import { applyMiddleware, compose, createStore } from 'redux';
import { routerMiddleware } from 'react-router-redux';
import rootReducer from '../reducers';
export default function configureStore(initialState, history) {
// Add so dispatched route actions to the history
const reduxRouterMiddleware = routerMiddleware(history);
const middleware = applyMiddleware(thunk, reduxRouterMiddleware);
const createStoreWithMiddleware = compose(
middleware
);
return createStoreWithMiddleware(createStore)(rootReducer, initialState);
}
|
import Helper from '@ember/component/helper';
export default Helper.helper(function ([arg1 = '']) {
return arg1.toLowerCase();
});
|
import { getOwner, setOwner } from '@ember/-internals/owner';
import { get, set, observer } from '@ember/-internals/metal';
import CoreObject from '../../lib/system/core_object';
import {
moduleFor,
AbstractTestCase,
buildOwner,
runDestroy,
runLoopSettled,
} from 'internal-test-helpers';
import { track } from '@glimmer/validator';
import { destroy } from '@glimmer/destroyable';
import { run } from '@ember/runloop';
moduleFor(
'Ember.CoreObject',
class extends AbstractTestCase {
['@test toString should be not be added as a property when calling toString()'](assert) {
let obj = CoreObject.create({
firstName: 'Foo',
lastName: 'Bar',
});
obj.toString();
assert.notOk(
Object.prototype.hasOwnProperty.call(obj, 'toString'),
'Calling toString() should not create a toString class property'
);
}
['@test should not trigger proxy assertion when retrieving a proxy with (GH#16263)'](assert) {
let someProxyishThing = CoreObject.extend({
unknownProperty() {
return true;
},
}).create();
let obj = CoreObject.create({
someProxyishThing,
});
let proxy = get(obj, 'someProxyishThing');
assert.equal(get(proxy, 'lolol'), true, 'should be able to get data from a proxy');
}
['@test should not trigger proxy assertion when retrieving a re-registered proxy (GH#16610)'](
assert
) {
let owner = buildOwner();
let someProxyishThing = CoreObject.extend({
unknownProperty() {
return true;
},
}).create();
// emulates ember-engines's process of registering services provided
// by the host app down to the engine
owner.register('thing:one', someProxyishThing, { instantiate: false });
assert.equal(owner.lookup('thing:one'), someProxyishThing);
runDestroy(owner);
}
['@test should not trigger proxy assertion when probing for a "symbol"'](assert) {
let proxy = CoreObject.extend({
unknownProperty() {
return true;
},
}).create();
assert.equal(get(proxy, 'lolol'), true, 'should be able to get data from a proxy');
// should not trigger an assertion
getOwner(proxy);
}
['@test can use getOwner in a proxy init GH#16484'](assert) {
let owner = {};
let options = {};
setOwner(options, owner);
CoreObject.extend({
init() {
this._super(...arguments);
let localOwner = getOwner(this);
assert.equal(localOwner, owner, 'should be able to `getOwner` in init');
},
unknownProperty() {
return undefined;
},
}).create(options);
}
async ['@test observed properties are enumerable when set GH#14594'](assert) {
let callCount = 0;
let Test = CoreObject.extend({
myProp: null,
anotherProp: undefined,
didChangeMyProp: observer('myProp', function () {
callCount++;
}),
});
let test = Test.create();
set(test, 'id', '3');
set(test, 'myProp', { id: 1 });
assert.deepEqual(Object.keys(test).sort(), ['id', 'myProp']);
set(test, 'anotherProp', 'nice');
assert.deepEqual(Object.keys(test).sort(), ['anotherProp', 'id', 'myProp']);
await runLoopSettled();
assert.equal(callCount, 1);
test.destroy();
}
['@test native getters/setters do not cause rendering invalidation during init'](assert) {
let objectMeta = Object.create(null);
class TestObject extends CoreObject {
get hiddenValue() {
let v = get(objectMeta, 'hiddenValue');
return v !== undefined ? v : false;
}
set hiddenValue(v) {
set(objectMeta, 'hiddenValue', v);
}
}
track(() => {
TestObject.create({ hiddenValue: true });
assert.ok(true, 'We did not error');
});
}
'@test destroy method is called when being destroyed by @ember/destroyable'(assert) {
assert.expect(1);
class TestObject extends CoreObject {
destroy() {
assert.ok(true, 'destroy was invoked');
}
}
let instance = TestObject.create();
run(() => {
destroy(instance);
});
}
}
);
|
/*
* grunt-sauce-tunnel
* https://github.com/civitaslearning/grunt-sauce-tunnel
*
* Copyright (c) 2013 Dan Harbin
* Licensed under the MIT license.
*/
'use strict';
(function () {
var SauceTunnel = require('sauce-tunnel'),
tunnels = {};
module.exports = function (grunt) {
function configureLogEvents(tunnel) {
var methods = ['write', 'writeln', 'error', 'ok', 'debug'];
methods.forEach(function (method) {
tunnel.on('log:' + method, function (text) {
grunt.log[method](text);
});
tunnel.on('verbose:' + method, function (text) {
grunt.verbose[method](text);
});
});
}
grunt.registerMultiTask('sauce_tunnel_stop', 'Stop the Sauce Labs tunnel', function () {
// Merge task-specific and/or target-specific options with these defaults.
var options = this.options({
username: process.env.SAUCE_USERNAME,
key: process.env.SAUCE_ACCESS_KEY
});
var done = null,
tunnel = null;
// try to find active tunnel
tunnel = tunnels[options.identifier];
if(!tunnel){
tunnel = new SauceTunnel(
options.username,
options.key,
options.identifier,
false, // tunneled = true
['-v']
);
}
else
{
delete tunnels[options.identifier];
}
done = grunt.task.current.async();
var finished = function(err){
if(err){
grunt.fail.warn(err);
}
if (done) {
done();
done = null;
}
};
tunnel.stop(finished);
});
grunt.registerMultiTask('sauce_tunnel', 'Runs the Sauce Labs tunnel', function () {
// Merge task-specific and/or target-specific options with these defaults.
var options = this.options({
username: process.env.SAUCE_USERNAME,
key: process.env.SAUCE_ACCESS_KEY
});
var done = null,
tunnel = null;
var finished = function () {
if (done) {
done();
done = null;
}
};
function start(options) {
if (tunnel) {
stop();
if (grunt.task.current.flags.stop) {
finished();
return;
}
}
done = grunt.task.current.async();
tunnel = new SauceTunnel(
options.username,
options.key,
options.identifier,
true, // tunneled = true
['-v']
);
// keep actives tunnel in memory for stop task
tunnels[tunnel.identifier] = tunnel;
configureLogEvents(tunnel);
grunt.log.writeln('Open'.cyan + ' Sauce Labs tunnel: ' + tunnel.identifier.cyan);
tunnel.start(function (status) {
if (status === false) {
grunt.fatal('Failed'.red + ' to open Sauce Labs tunnel: ' + tunnel.identifier.cyan);
}
grunt.log.ok('Successfully'.green + ' opened Sauce Labs tunnel: ' + tunnel.identifier.cyan);
finished();
});
tunnel.on('exit', finished);
tunnel.on('exit', stop);
}
function stop() {
if (tunnel && tunnel.stop) {
grunt.log.writeln('Stopping'.cyan + 'Sauce Labs tunnel: ' + tunnel.identifier.cyan);
tunnel.stop(function () {
grunt.log.writeln('Stopped'.red + 'Sauce Labs tunnel: ' + tunnel.identifier.cyan);
tunnel = null;
finished();
});
} else {
finished();
}
}
start(options);
});
};
})();
|
'use strict';
(function (app) {
app.controller('trainings', ['$scope',
function ($scope) {
}]);
app.controller('editTraining', ['$scope', '$routeParams',
function ($scope, $routeParams) {
$scope.assaultTopics = [];
$scope.justiceSystemTopics = [];
$scope.underservedPopulationTopics = [];
$scope.communityResponseTopics = [];
$scope.types = [
{ name: 'Training',
value: 'training',
categories: [
{ name: "Advocacy organization staff (NAACP, AARP)", value: "Advocacy organization staff (NAACP, AARP)"},
{ name: "Attorneys/law students", value: "Attorneys/law students"},
{ name: "Batterer intervention program staff", value: "Batterer intervention program staff"},
{ name: "Child care staff", value: "Child care staff"},
{ name: "Child protective service workers", value: "Child protective service workers"},
{ name: "Children’s advocates (not affi liated with CPS)", value: "Children’s advocates (not affi liated with CPS)"},
{ name: "Correction personnel (probation, parole, and correctional facilities)", value: "Correction personnel (probation, parole, and correctional facilities)"},
{ name: "Court personnel (tribal)", value: "Court personnel (tribal)"},
{ name: "Court personnel (non-tribal)", value: "Court personnel (non-tribal)"},
{ name: "Educators (teachers, administrators, etc.)", value: "Educators (teachers, administrators, etc.)"},
{ name: "Faith-based organization staff", value: "Faith-based organization staff"},
{ name: "Government agency staff (vocational rehabilitation, food stamps, TANF)", value: "Government agency staff (vocational rehabilitation, food stamps, TANF)"},
{ name: "Health professionals (doctors, nurses--does not include SAFE/SANE)", value: "Health professionals (doctors, nurses--does not include SAFE/SANE)"},
{ name: "Immigrant organization staff (non-governmental)", value: "Immigrant organization staff (non-governmental)"},
{ name: "Interpreters/translators", value: "Interpreters/translators"},
{ name: "Law enforcement offi cers (tribal)", value: "Law enforcement offi cers (tribal)"},
{ name: "Law enforcement offi cers (non-tribal)", value: "Law enforcement offi cers (non-tribal)"},
{ name: "Legal services staff (does not include attorneys)", value: "Legal services staff (does not include attorneys)"},
{ name: "Mental health professionals", value: "Mental health professionals"},
{ name: "Military command staff", value: "Military command staff"},
{ name: "Multidisciplinary (various disciplines at same training)", value: "Multidisciplinary (various disciplines at same training)"},
{ name: "Prosecutors (tribal)", value: "Prosecutors (tribal)"},
{ name: "Prosecutors (non-tribal)", value: "Prosecutors (non-tribal)"},
{ name: "Sexual assault forensic examiner/sexual assault nurse examiner (SAFE/SANE)", value: "Sexual assault forensic examiner/sexual assault nurse examiner (SAFE/SANE)"},
{ name: "Social service organization staff (non-governmental—food bank, homeless shelter)", value: "Social service organization staff (non-governmental—food bank, homeless shelter)"},
{ name: "State or tribal domestic violence coalition staff (includes sexual assault, domestic violence, and dual)", value: "State or tribal domestic violence coalition staff (includes sexual assault, domestic violence, and dual)"},
{ name: "Tribal government/Tribal government agency staff", value: "Tribal government/Tribal government agency staff"},
{ name: "Victim advocates (tribal, includes sexual assault, domestic violence, and dual)", value: "Victim advocates (tribal, includes sexual assault, domestic violence, and dual)"},
{ name: "Victim advocates (non-tribal, non-governmental, includes sexual assault, domestic violence, and dual)", value: "Victim advocates (non-tribal, non-governmental, includes sexual assault, domestic violence, and dual)"},
{ name: "Victim assistants (tribal, includes victim-witness specialists/coordinators)", value: "Victim assistants (tribal, includes victim-witness specialists/coordinators)"},
{ name: "Victim assistants (non-tribal, governmental, includes victim-witness specialists/coordinators)", value: "Victim assistants (non-tribal, governmental, includes victim-witness specialists/coordinators)"},
{ name: "Volunteers", value: "Volunteers"},
{ name: "Other", value: "" }
],
assaultTopics: [
"Advocate response",
"Child witnesses",
"Child sexual abuse overview, dynamics, and services",
"Child development",
"Confidentiality",
"Dating violence overview, dynamics, and services",
"Domestic violence overview, dynamics, and services",
"Mandatory reporting requirements",
"Parenting issues",
"Response to victims/survivors who are incarcerated",
"Response to victims/survivors who have been trafficked",
"Safety planning for victims/survivors",
"Sexual assault overview, dynamics, and services",
"Stalking overview, dynamics, and services"
],
justiceSystemTopics: [
"Civil court procedures",
"Child sexual abuse statutes/codes",
"Criminal court procedures",
"Domestic violence statutes/codes",
"Family court procedures",
"Firearms and domestic violence",
"Decreasing dual arrests/identifying predominant aggressor",
"Immigration",
"Judicial response",
"Juvenile court procedures",
"Law enforcement response",
"Pro-arrest policies",
"Probation response",
"Prosecution response",
"Protection orders (including full faith and credit)",
"Sexual assault forensic examination",
"Sexual assault statutes/codes",
"Stalking statutes/codes",
"Tribal jurisdiction and Public Law"
],
underservedPopulationTopics: [
"are American Indian or Alaska Native",
"are Asian",
"are black or African American",
"are elderly",
"are geographically isolated",
"are Hispanic or Latino",
"are homeless or living in poverty",
"are immigrants, refugees, or asylum seekers",
"are lesbian, gay, bisexual, transgender, or intersex",
"are Native Hawaiian or other Pacifi c Islander",
"have disabilities",
"have limited English profi ciency",
"have mental health issues",
"have substance abuse issues"
],
communityResponseTopics: [
"Community response to sexual assault",
"Coordinated community response",
"Response teams (DART, DVRT, SART)",
"Technology"
]
},
{ name: 'Educational', value: 'educational', categories: [
{ name: "Child care providers", value: "Child care providers" },
{ name: "Community advocacy groups (NAACP, AARP)", value: "Community advocacy groups (NAACP, AARP)" },
{ name: "Community businesses (retail stores, pharmacies)", value: "Community businesses (retail stores, pharmacies)" },
{ name: "Community groups (service or social groups)", value: "Community groups (service or social groups)" },
{ name: "Community members (unaffi liated adults)", value: "Community members (unaffi liated adults)" },
{ name: "Educators (teachers, administrators, etc.)", value: "Educators (teachers, administrators, etc.)" },
{ name: "Elementary school students", value: "Elementary school students" },
{ name: "Faith-based groups", value: "Faith-based groups" },
{ name: "Middle and high school students", value: "Middle and high school students" },
{ name: "Parents or guardians", value: "Parents or guardians" },
{ name: "University or college students", value: "University or college students" },
{ name: "Victims/survivors (do not count psychoeducation groups)", value: "Victims/survivors (do not count psychoeducation groups)" },
{ name: "Other", value: "" }
]}
];
if ($routeParams.id === 'new') {
$scope.training = {
occurredAt: new Date(),
type: $scope.types[0]
};
$scope.title = 'New Training';
} else {
$scope.title = 'Update Training';
}
$scope.toggleSelection = function toggleSelection(item, collection) {
var idx = $scope[collection].indexOf(item);
if (idx > -1) {
$scope[collection].splice(idx, 1);
} else {
$scope[collection].push(item);
}
};
}]);
app.controller('roles', ['$scope',
function ($scope) {
}]);
app.controller('editRole', ['$scope', '$routeParams',
function ($scope, $routeParams) {
}]);
})(angular.module('app'));
|
!function($){
"use strict"
/* CLASS NOTICE DEFINITION
* ======================= */
var Popup = function (elem, options) {
this.Status = 'off'
this.$elem = $(elem)
this.options = options
this.init()
}
Popup.prototype = {
init: function(){
var options = this.options
options.shade == null ? this.$elemBox = this.$elem : this.$elemBox = this.$elem.wrap("<div class='popup-box'></div>").after("<div class='popup-shade'></div>")
var $self = this
, $clone = this.$elem.clone().css({display:'block',position:'absolute',top:'-100000px'}).appendTo("body")
, $cloneWidth = $clone.width()
, $cloneHeight = $clone.height()
, $window = $(window)
$clone.remove()
options.elemTop === null ? $cloneHeight = $window.height() / 2 - $cloneHeight / 2 : $cloneHeight = options.elemTop
options.elemLeft === null ? $cloneWidth = $window.width() / 2 - $cloneWidth / 2 : $cloneWidth = options.elemLeft
this.$elem.css({
position:"absolute",top:$cloneHeight,left:$cloneWidth
})
options.showElem != null && $(document).on('click', function (event) {
if (event.target != $self.$elem[0] && $self.Status == 'on') {
$self.hide()
}
})
options.showElem != null && $(options.showElem).on('click', function (event) {
if ($self.Status == 'off') {
$self.show()
return false
}
})
return this
}
, show: function (timeout) {
this.Status = 'on'
this.$elemBox.show()
timeout && this.hide(timeout)
return this
}
, hide: function (timeout) {
this.Status = 'off'
var $self = this
, timeout = timeout || 0
setTimeout(function(){
$self.$elemBox.hide()
},timeout)
return this
}
}
$.fn.popup = function (option) {
return this.each(function () {
var $this = $(this)
, data = $this.data('popup')
, options = $.extend({}, $.fn.popup.defaults, typeof option == 'object' && option)
if(!data) $this.data('popup', (data = new Popup(this, options)))
})
}
$.fn.popup.defaults = {
shade : null
, elemTop : null
, elemLeft : null
, showElem : null
, hideElem : null
}
}(window.jQuery);
|
// points.
var g_points = [];
// on mouse down event.
function click(ev, gl, canvas, position, size, color) {
var x = ev.clientX;
var y = ev.clientY;
var rect = ev.target.getBoundingClientRect();
x = ((x - rect.left) - canvas.width / 2) / (canvas.width / 2);
y = (canvas.height / 2 - (y - rect.top)) / (canvas.height/ 2);
g_points.push(x);
g_points.push(y);
var r = Math.random();
var g = Math.random();
var b = Math.random();
var a = Math.random();
clearBuffer(gl);
gl.vertexAttrib1f(size, Math.random() * 20 + 2);
gl.uniform4f(color, r, g, b, a);
// write to buffer.
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(g_points), gl.DYNAMIC_DRAW);
// draw with buffer.
gl.drawArrays(gl.POINTS, 0, g_points.length / 2);
}
// main function.
function main() {
var VSHADER_SOURCE =
'attribute vec4 a_Position;\n' +
'attribute float a_PointSize;\n' +
'void main() {\n' +
' gl_Position = a_Position;\n' +
' gl_PointSize = a_PointSize;\n' +
'}\n';
var FSHADER_SOURCE =
'precision mediump float;\n' +
'uniform vec4 u_FragColor;\n' +
'void main() {\n' +
' gl_FragColor = u_FragColor;\n' +
'}\n';
var canvas = document.getElementById("webgl");
var gl = getWebGLContext(canvas);
if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
alert("Fail to initialize shaders!");
return;
}
// get attributes.
var a_position = gl.getAttribLocation(gl.program, 'a_Position');
checkAttribute(a_position);
var a_pointsize = gl.getAttribLocation(gl.program, 'a_PointSize');
checkAttribute(a_pointsize);
// get uniforms.
var u_fragcolor = gl.getUniformLocation(gl.program, 'u_FragColor');
checkUniform(u_fragcolor);
// create buffer.
var vertex_buffer = gl.createBuffer();
if (!vertex_buffer) {
alert("Fail to create vertex buffer!");
return;
}
// bind buffer.
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
// dispatch attribute to buffer and enable it.
gl.vertexAttribPointer(a_position, 2, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(a_position);
canvas.onmousedown = function (ev) {
click(ev, gl, canvas, a_position, a_pointsize, u_fragcolor);
};
clearBuffer(gl);
};
|
var Manager = require('../');
var expect = require('expect.js');
describe('inter-tab', function(){
var tab1, tab2;
beforeEach(function(){
tab1 = new Manager();
tab2 = new Manager();
});
afterEach(function(){
tab1.destroy();
tab2.destroy();
});
it('should create tab id', function(){
expect(tab1.id).to.be.a('number');
});
it('should yield same tabs array', function(){
var tabIds1 = tab1.getTabs();
var tabIds2 = tab2.getTabs();
expect(tabIds1).to.eql(tabIds2);
});
it('should contain right keys in tabs array', function(){
var tabIds = tab1.getTabs();
expect(tabIds).to.only.have.keys(tab1.id.toString(), tab2.id.toString());
});
it('should correctly destroy a tab', function(){
tab1.destroy();
var tabIds = tab2.getTabs();
expect(tabIds).to.only.have.keys(tab2.id.toString());
});
it('should correctly set key-value pairs', function(){
tab2.set(tab1.id, 'test', 'Hello World');
var attr = tab2.get(tab1.id, 'test');
expect(attr).to.be('Hello World');
});
});
|
/*! jQuery UI - v1.9.2 - 2017-10-08
* http://jqueryui.com
* Copyright jQuery Foundation and other contributors; Licensed MIT */
jQuery(function(t){t.datepicker.regional.sl={closeText:"Zapri",prevText:"<Prejšnji",nextText:"Naslednji>",currentText:"Trenutni",monthNames:["Januar","Februar","Marec","April","Maj","Junij","Julij","Avgust","September","Oktober","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","Maj","Jun","Jul","Avg","Sep","Okt","Nov","Dec"],dayNames:["Nedelja","Ponedeljek","Torek","Sreda","Četrtek","Petek","Sobota"],dayNamesShort:["Ned","Pon","Tor","Sre","Čet","Pet","Sob"],dayNamesMin:["Ne","Po","To","Sr","Če","Pe","So"],weekHeader:"Teden",dateFormat:"dd.mm.yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},t.datepicker.setDefaults(t.datepicker.regional.sl)});
|
/**
* Created by vestnik on 27/03/16.
*/
import models from './../src/database'
import drivers from './../src/database/driver'
models.BaseModel.db = new drivers.LocalDb()
|
var map=require("map-stream"),fs=require("graceful-fs");module.exports=function(e){return map(function(e,t){fs.stat(e.path,function(n,r){r&&(e.stat=r);t(n,e)})})};
|
class GenderModifier {
getName() {
return 'gender';
}
execute(value, parameters) {
return value === 'male' ? parameters[0] : parameters[1];
}
}
export default GenderModifier;
|
class Selector extends EventEmitter {
constructor() {
super();
this.dragEventOrigin = null;
this.dragEventCurrently = null;
this.isMouseDragging = false;
this.clickEvent = null;
var that = this;
this.on('mousedrag', function (e) {
if (!that.isMouseDragging) {
that.dragEventOrigin = e;
that.isMouseDragging = true;
} else {
that.dragEventCurrently = e;
}
that.clickEvent = null;
});
this.on('mouseup', function (e) {
if (that.isMouseDragging) {
that.dragEventOrigin = null;
that.dragEventCurrently = null;
that.isMouseDragging = false;
that.clickEvent = null;
}
});
this.on('mouseclick', function (e) {
that.clickEvent = e;
that.isMouseDragging = false;
});
}
isActive() {
return this.isMouseDragging || this.clickEvent !== null;
}
getSelectedRect() {
if (!this.isActive())
return undefined;
// in case that there is a click event return that point
if (this.clickEvent !== null && !this.isMouseDragging) {
return new Rectangle(this.clickEvent.clientX,
this.clickEvent.clientY, 0, 0);
}
if (this.dragEventCurrently === null || this.dragEventOrigin === null)
return undefined;
// in case of mouse drag calculate the area of dragging
var x, y, w, h;
if (this.dragEventCurrently.clientX > this.dragEventOrigin.clientX
&& this.dragEventCurrently.clientY > this.dragEventOrigin.clientY) {
x = this.dragEventOrigin.clientX;
y = this.dragEventOrigin.clientY;
w = this.dragEventCurrently.clientX - this.dragEventOrigin.clientX;
h = this.dragEventCurrently.clientY - this.dragEventOrigin.clientY;
}
if (this.dragEventCurrently.clientX > this.dragEventOrigin.clientX
&& this.dragEventCurrently.clientY < this.dragEventOrigin.clientY) {
x = this.dragEventOrigin.clientX;
y = this.dragEventCurrently.clientY;
w = this.dragEventCurrently.clientX - this.dragEventOrigin.clientX;
h = this.dragEventOrigin.clientY - this.dragEventCurrently.clientY;
}
if (this.dragEventCurrently.clientX < this.dragEventOrigin.clientX
&& this.dragEventCurrently.clientY < this.dragEventOrigin.clientY) {
x = this.dragEventCurrently.clientX;
y = this.dragEventCurrently.clientY;
w = this.dragEventOrigin.clientX - this.dragEventCurrently.clientX;
h = this.dragEventOrigin.clientY - this.dragEventCurrently.clientY;
}
if (this.dragEventCurrently.clientX < this.dragEventOrigin.clientX
&& this.dragEventCurrently.clientY > this.dragEventOrigin.clientY) {
x = this.dragEventCurrently.clientX;
y = this.dragEventOrigin.clientY;
w = this.dragEventOrigin.clientX - this.dragEventCurrently.clientX;
h = this.dragEventCurrently.clientY - this.dragEventOrigin.clientY;
}
var rect = new Rectangle(x, y, w, h);
this.emit('multiselect', rect);
return rect;
}
}
// if it is not in the list with the selected items add it
Selector.addSelected = function (item) {
if (Selector.selectedEntities.indexOf(item) === -1)
Selector.selectedEntities.push(item);
}
Selector.removeDeselected = function (item) {
var index = Selector.selectedEntities.indexOf(item);
if (index > -1)
Selector.selectedEntities.splice(index, 1);
}
/* @static */
Selector.selectedEntities = [];
Selector.getSelectedItems = function () {
return Selector.selectedEntities;
}
|
var gulp = require('gulp');
var elixir = require('laravel-elixir');
var sass_options = {
includePaths: [
'node_modules/bootstrap-sass/assets/stylesheets',
require('bourbon').includePaths,
'node_modules/bourbon-neat/app/assets/stylesheets',
'node_modules/hint.css/src',
]
};
/*
|--------------------------------------------------------------------------
| Elixir Asset Management
|--------------------------------------------------------------------------
|
| Elixir provides a clean, fluent API for defining some basic Gulp tasks
| for your Laravel application. By default, we are compiling the Sass
| file for our application, as well as publishing vendor resources.
|
*/
elixir(function(mix) {
mix.sass([
'app.scss'
], 'public/assets/css', sass_options);
mix.scripts([
'jquery/**/*.js',
'lib/**/*.js',
'app/Application.js',
'app/**/*.js',
'app.js'
], 'public/assets/js/app.js');
});
|
'use strict';
var BaseQuery = require('../../query/base');
var Transaction = require('../../query/mixins/transaction');
/**
* @class RenameTableQuery
* @extends BaseQuery
* @mixes Transaction
* @classdesc
*
* A query that allows renaming tables.
*/
var RenameTableQuery = BaseQuery.extend();
RenameTableQuery.reopen(Transaction);
RenameTableQuery.reopen(/** @lends RenameTableQuery# */ {
/**
* You will not create this query object directly. Instead, you will
* receive it via {@link Schema#renameTable}.
*
* @protected
* @constructor RenameTableQuery
*/
init: function() { throw new Error('RenameTableQuery must be spawned.'); },
/**
* Override of {@link BaseQuery#_create}.
*
* @method
* @private
* @see {@link BaseQuery#_create}
* @see {@link Schema#renameTable} for parameter details.
*/
_create: function(from, to) {
this._super();
this._from = from;
this._to = to;
},
/**
* Duplication implementation.
*
* @method
* @protected
* @see {@link BaseQuery#_take}
*/
_take: function(orig) {
this._super(orig);
this._from = orig._from;
this._to = orig._to;
},
/**
* Override of {@link BaseQuery#statement}.
*
* @method
* @protected
* @see {@link BaseQuery#statement}
*/
_statement: function() {
return this._adapter.phrasing.renameTable({
from: this._from,
to: this._to,
});
},
});
module.exports = RenameTableQuery.reopenClass({
__name__: 'RenameTableQuery',
});
|
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { getVisibleImages, getImage } from '../reducers/images';
import { routeActions } from 'react-router-redux';
import ImageItem from '../components/ImageComponents/ImageItem';
import ImagesList from '../components/ImageComponents/ImagesList';
import { selectImage, getAllImages } from '../actions/imagesActions';
const loadData = (props) => {
props.getAllImages();
}
export default class ImagesContianer extends Component {
constructor(props) {
super(props)
}
componentWillMount() {
loadData(this.props);
}
componentWillReceiveProps(nextProps) {
if(nextProps.images === null) {
debugger;
loadData(nextProps)
}
}
render() {
const { images, selectImage, push } = this.props;
return (
<ImagesList>
{images.map(image =>
<ImageItem key={image.id}
image={image} />
)}
</ImagesList>
);
}
}
ImagesContianer.propTypes = {
images: PropTypes.arrayOf(PropTypes.shape({
id: PropTypes.number.isRequired,
desc: PropTypes.string.isRequired,
src: PropTypes.string.isRequired,
price: PropTypes.number.isRequired
})).isRequired
}
function mapStateToProps(state) {
const { pathname } = state.routing.location;
return {
images: getVisibleImages(state)
}
}
export default connect(mapStateToProps, {
getAllImages
})(ImagesContianer);
/** WEBPACK FOOTER **
** D:/Code/Reactjs-Projects/clymer-metal-crafts/containers/ImagesContainer.js
**/
/** WEBPACK FOOTER **
** D:/Code/Reactjs-Projects/clymer-metal-crafts/containers/ImagesContainer.js
**/
/** WEBPACK FOOTER **
** D:/Code/Reactjs-Projects/clymer-metal-crafts/containers/ImagesContainer.js
**/
/** WEBPACK FOOTER **
** D:/Code/Reactjs-Projects/clymer-metal-crafts/containers/ImagesContainer.js
**/
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.NullableBooleanInput = undefined;
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _SelectInput = require('./SelectInput');
var _SelectInput2 = _interopRequireDefault(_SelectInput);
var _translate = require('../../i18n/translate');
var _translate2 = _interopRequireDefault(_translate);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var NullableBooleanInput = exports.NullableBooleanInput = function NullableBooleanInput(_ref) {
var input = _ref.input,
meta = _ref.meta,
label = _ref.label,
source = _ref.source,
elStyle = _ref.elStyle,
resource = _ref.resource,
translate = _ref.translate;
return _react2.default.createElement(_SelectInput2.default, {
input: input,
label: label,
source: source,
resource: resource,
choices: [{ id: null, name: '' }, { id: false, name: translate('aor.boolean.false') }, { id: true, name: translate('aor.boolean.true') }],
meta: meta,
style: elStyle
});
};
NullableBooleanInput.propTypes = {
addField: _react.PropTypes.bool.isRequired,
elStyle: _react.PropTypes.object,
input: _react.PropTypes.object,
label: _react.PropTypes.string,
meta: _react.PropTypes.object,
resource: _react.PropTypes.string,
source: _react.PropTypes.string,
translate: _react.PropTypes.func.isRequired
};
NullableBooleanInput.defaultProps = {
addField: true
};
exports.default = (0, _translate2.default)(NullableBooleanInput);
|
var fs = require('fs');
var slugify = require('../app/scripts/slugify');
var dataSource = '../app/data/data.tsv';
var publications = fs.read(dataSource).toString().trim().split("\n");
var headers = publications.shift().split("\t");
publications = publications.map(function (p) {
p = p.split("\t");
var r = {}
headers.forEach(function (header, i) {
r[header] = p[i];
});
r.slug = slugify(r);
return r;
});
var page = require('webpage').create();
page.zoomFactor = 2;
page.viewportSize = { width: 560, height: 300 };
page.open('http://localhost:9000', function () {
window.setInterval(next, 300);
});
var ready = true;
function next () {
if (publications.length <= 0) phantom.exit();
if (!ready) return;
ready = false;
var publication = publications.shift();
console.log(publication.title, '('+publications.length+')');
page.evaluate(function (publicationTitle) {
window.photogenic = true;
document.getElementById('tf-publication').value = publicationTitle;
window.jQuery('body').addClass('photogenic');
window.jQuery('form').triggerHandler('submit');
}, publication.title);
window.setTimeout(function () {
page.render('../screenshots/'+publication.slug+'.png');
ready = true;
}, 100);
}
|
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var http = require('http');
var routes = require('./routes/index');
var app = express();
var port = 8124;
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')))
app.use('/', routes);
app.use(function(req, res, next)
{
var err = new Error('Not Found');
err.status = 404;
next(err);
});
http.createServer(app).listen(port, function()
{
console.log('Listening on port.' + port);
});
|
import 'selectize';
import { action } from '@ember/object';
import { observes, on } from '@ember-decorators/object';
import classic from 'ember-classic-decorator';
import $ from 'jquery';
import uniq from 'lodash-es/uniq';
import BaseField from './base-field';
@classic
export default class SelectizeField extends BaseField {
optionValuePath = 'id';
optionLabelPath = 'id';
init() {
super.init(...arguments);
this.defaultOptions = [];
this.set('selectizeTextInputId', this.inputId + '-selectize_text_input');
// eslint-disable-next-line ember/no-observers
this.addObserver('model.' + this.fieldName, this, this.valueDidChange);
}
@action
didInsert(element) {
this.$input = $(element).find('#' + this.inputId).selectize({
plugins: ['restore_on_backspace', 'remove_button'],
delimiter: ',',
options: this.defaultOptions,
valueField: 'id',
labelField: 'label',
searchField: 'label',
sortField: 'label',
create: true,
// Add to body so it doesn't get clipped by parent div containers.
dropdownParent: 'body',
});
this.selectize = this.$input[0].selectize;
this.selectize.$control_input.attr('id', this.selectizeTextInputId);
this.selectize.$control_input.attr('data-raw-input-id', this.inputId);
let controlId = this.inputId + '-selectize_control';
this.selectize.$control.attr('id', controlId);
this.selectize.$control_input.attr('data-selectize-control-id', controlId);
}
@on('init')
// eslint-disable-next-line ember/no-observers
@observes('options.@each')
defaultOptionsDidChange() {
this.set('defaultOptions', this.options.map((item) => {
return {
id: item.get(this.optionValuePath),
label: item.get(this.optionLabelPath),
};
}));
if(this.selectize) {
this.defaultOptions.forEach((option) => {
this.selectize.addOption(option);
});
this.selectize.refreshOptions(false);
}
}
// Sync the selectize input with the value binding if the value changes
// externally.
valueDidChange() {
if(this.selectize) {
let valueString = this.get('model.' + this.fieldName)
if(valueString !== this.selectize.getValue()) {
let values = valueString;
if(values) {
values = uniq(values.split(','));
// Ensure the selected value is available as an option in the menu.
// This takes into account the fact that the default options may not
// be loaded yet, or they may not contain this specific option.
for(let i = 0; i < values.length; i++) {
let option = {
id: values[i],
label: values[i],
};
this.selectize.addOption(option);
}
this.selectize.refreshOptions(false);
}
this.selectize.setValue(values);
}
}
}
willDestroyElement() {
super.willDestroyElement(...arguments);
if(this.selectize) {
this.selectize.destroy();
}
}
}
|
/// <reference path="../App.js" />
(function () {
"use strict";
// The Office initialize function must be run each time a new page is loaded
Office.initialize = function (reason) {
$(document).ready(function () {
// Initialize Office UI Fabric components (spinner)
if (typeof fabric !== "") {
if ('Spinner' in fabric) {
var element = document.querySelector('.ms-Spinner');
if (element) {
var component = new fabric['Spinner'](element);
}
}
}
// Initialize input fields
$('#username').val('#Office365Dev');
$('#password').val('#Office365Dev');
// Add event handlers
$('#sign-in').click(signIn);
$('#dialog-ok').click(hideDialog);
// Authenticate silently (without credentials)
authenticate(null, function (response) {
// Hide spinner and show button
$('#sign-in').show();
$('#spinner').hide();
if (!response) {
// Enable sign-in
$('#sign-in').removeAttr('disabled');
$('#username').removeAttr('disabled');
$('#password').removeAttr('disabled');
}
else {
// Display user data
showDialog('Hi developer!', 'Office 365 user ' + '(' +
Office.context.mailbox.userProfile.emailAddress + ') ' +
'has automatically signed in as user: ' +
response.displayName + ' (' +
response.credentials.username + ').');
}
});
});
};
// Try to authenticate, if credentials for a user is provided - we
// will try to map it with the Office 365 user in the backend
function authenticate(credentials, callback) {
Office.context.mailbox.getUserIdentityTokenAsync(function (asyncResult) {
if (asyncResult.status !== Office.AsyncResultStatus.Succeeded) {
// TODO: Handle error
callback();
}
else {
var token = asyncResult.value;
// POST the credentials to the Web API
$.ajax({
type: 'POST',
url: '../../api/sso',
data: JSON.stringify({
identityToken: token,
hostUri: window.location.href.split('?')[0],
credentials: credentials
}),
contentType: 'application/json;charset=utf-8'
}).done(function (response) {
// TODO: Validate response
callback(response);
}).fail(function (error) {
// TODO: Handle error
callback();
});
}
});
}
// Sign in using the provided credentials
function signIn() {
// Show spinner and hide button
$('#sign-in').hide();
$('#spinner').show();
// Disable input fields
$('#username').attr('disabled', 'disabled');
$('#password').attr('disabled', 'disabled');
// Get credentials
var credentials = {
username: $('#username').val(),
password: $('#password').val(),
}
// Authenticate
authenticate(credentials, function (response) {
if (!response) {
// Hide spinner and show button
$('#sign-in').show();
$('#spinner').hide();
// Enable input fields
$('#username').removeAttr('disabled');
$('#password').removeAttr('disabled');
// Display error
showDialog('Oops!', 'Something happened... make sure that ' +
'the credentials are valid (for an entry in the user service).');
}
else {
// Reload page and try SSO
location.reload();
}
});
}
// Show the dialog
function showDialog(title, text) {
// Set the dialog title and text
$('#dialog-title').text(title);
$('#dialog-text').text(text);
$('#dialog').show();
}
// Hide the dialog
function hideDialog() {
$('#dialog').hide();
}
})();
|
'use strict';
const stampit = require('stampit');
const ObjectKey = require('./object-key');
module.exports = stampit()
.methods({
notEmpty,
transform,
validate
})
.compose(ObjectKey);
/**
* Describe validation rule for non-empty string
*
* @param {String} [msg] - Optional. Error message. Defaults to the empty string
*
* @return {Object} - Validation schema (this)
*
* @public
*/
function notEmpty (msg = '') {
this.isNotEmpty = true;
this.isNotEmptyMsg = String(msg);
return this;
}
/**
* Describe custom transformation function
*
* @param {Function} fn
*
* @return {Object} - Validation schema (this)
*
* @public
*/
function transform (fn) {
const transformFn = typeof fn === 'function' ? fn : val => val;
this.transformFn = transformFn;
return this;
}
/**
* Describe custom validation function
*
* @param {Function} fn The function is passed the value and must return a Boolean value
* @param {String} [msg] Optional. Error message. Defaults to the empty string
*
* @return {Object} - Validation schema (this)
*
* @public
*/
function validate (fn, msg = '') {
const validatorFn = typeof fn === 'function' ? fn : () => true;
this.validatorFn = validatorFn;
this.validateMsg = msg;
return this;
}
|
var express = require('express');
var app = express();
app.set('view engine', 'ejs');
app.set('views', __dirname + '/../public/views');
app.use(express.static(__dirname + '/../public'));
require('./database');
require('./routes')(app);
module.exports = app;
|
#! /usr/bin/env node
const colors = require('colors');
const Vorpal = require('vorpal');
const DenonClient = require('./lib/DenonClient');
const setupToolCommands = require('./lib/toolCommands');
const setupDenonCommands = require('./lib/denonCommands');
const denon = new DenonClient();
const cli = Vorpal();
denon.on('connect', ()=> {
const address = denon.socket.remoteAddress;
const port = denon.socket.remotePort;
cli.log(colors.green(`Successfully connected to ${address}:${port}`));
});
denon.on('error', err => {
cli.log(colors.red('Something went wrong'), err);
denon.end();
});
denon.on('close', ()=> {
cli.log(colors.red('Connection closed'));
});
denon.on('data', buffer => {
cli.log(colors.magenta(buffer.toString().trim()));
});
cli
.localStorage('denon-remote-v1')
.history('denon-remote-v1')
.delimiter('denon$')
.show();
setupToolCommands(cli, denon);
setupDenonCommands(cli, denon);
cli.execSync('connect');
|
import { createLogger, Level } from '@17media/node-logger';
import EnvConfig from '../env.config.json';
import project from '../package.json';
const loggerConfig = {
base: {
logLevel: Level.INFO,
project: project.name,
environment: process.env.NODE_ENV || 'development',
},
Slack: {
slackToken: EnvConfig.Slack.BOT_TOKEN,
slackChannel: '@hsuan',
},
Console: true,
};
export default createLogger(loggerConfig);
|
define(
[
'controls/view',
'plugins/buddhalow/datasources/posttabledatasource'
], function (
SPViewElement,
SPPostTableDataSource
) {
return class SPNewsFeedViewElement extends SPViewElement {
createdCallback() {
this.innerHTML = '<sp-divider>Feed</sp-divider>';
this.classList.add('sp-view');
this.list = document.createElement('sp-list');
this.list.dataSource = new SPPostTableDataSource();
this.list.setAttribute('interact', true);
this.appendChild(this.list);
this.attributeChangedCallback('uri', null, 'buddhalow:post');
}
attributeChangedCallback(attrName, oldVal, newVal) {
if (attrName === 'uri') {
this.list.type = 'sp-post';
this.list.setAttribute('uri', newVal);
}
}
}
});
|
client.on('open', function(stream) {
var stream = client.createStream(
{event: 'run', params: {'url':app.pipeline.wsurl}});
stream.on('data', function(data, options) {
console.log(JSON.parse(data))});
})
var client = new BinaryClient();
// Received new stream from server!
client.on('stream', function(stream, meta){
// Buffer for parts
var parts = [];
// Got new data
stream.on('data', function(data){
parts.push(data);
});
stream.on('end', function(){
// Display new data in browser!
img.src = (window.URL || window.webkitURL).createObjectURL(new Blob(parts));
document.body.appendChild(img);
});
});
|
import { auth } from '../firebase';
import { signIn, signOut, createUser } from '../user';
jest.mock('../firebase', () => ({
auth: jest.fn().mockReturnValue({
signInWithEmailAndPassword: jest.fn(),
signOut: jest.fn(),
createUserWithEmailAndPassword: jest.fn()
})
}));
describe('signIn', () => {
it('should call signInWithEmailAndPassword()', () => {
const email = 'mockEmail';
const password = 'mockPassword';
signIn(email, password);
expect(auth().signInWithEmailAndPassword).toBeCalled();
});
});
describe('signOut', () => {
it('should call signOut()', () => {
signOut();
expect(auth().signOut).toBeCalled();
});
});
describe('createUser', () => {
it('should call createUserWithEmailAndPassword()', () => {
const email = 'mockEmail';
const password = 'mockPassword';
createUser(email, password);
expect(auth().createUserWithEmailAndPassword).toBeCalled();
});
});
|
define("controllers/main", ["app"], function (app) {
return app.controller("main", ["$scope","$translate","$translatePartialLoader"/*,"$socket"*/, function ($scope,$translate,$translatePartialLoader/*,$socket*/) {
$translatePartialLoader.deletePart("main",true);
$translatePartialLoader.addPart("main");
$translate.refresh();
// $socket.on('realtime:broadcast', function(data) {
// $scope.messages.push(data);
// });
// $socket.emit('realtime:connect', {});
angular.extend($scope, {
// messages:[],
// send: function (message) {
// $socket.emit('realtime:message', {message:message});
// }
});
}]);
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.