code
stringlengths
2
1.05M
/** * Auth * * check to Backend is credentials OK */ (function() { 'use strict'; angular.module('frontend.core.services') .factory('Auth', [ '$http', 'Storage', 'BackendConfig', function ($http, Storage, BackendConfig) { function check() { return login(Storage.get('username'), Storage.get('password')); } function login(username, password) { return $http .post(BackendConfig.url + '/api/auth', {}, { headers: { username: username, password: password } }); } return { 'isAuthenticated': function() { return Boolean(Storage.get('isAuthenticated')); }, 'user': function() { var user = JSON.parse(Storage.get('user')); if (Boolean(user)) { return user; } else { return null; } }, 'check': check, 'login': login, 'logout': function() { Storage.unset('username'); Storage.unset('password'); Storage.unset('isAuthenticated'); } }; }]); }());
var _ = require('src/util') var Vue = require('src') // unset jQuery to bypass jQuery check for normal test cases jQuery = null /** * Mock event helper */ function trigger (target, event, process) { var e = document.createEvent('HTMLEvents') e.initEvent(event, true, true) if (process) process(e) target.dispatchEvent(e) } /** * setting <select>'s value in IE9 doesn't work * we have to manually loop through the options */ function updateSelect (el, value) { var options = el.options var i = options.length while (i--) { /* eslint-disable eqeqeq */ if (options[i].value == value) { /* eslint-enable eqeqeq */ options[i].selected = true break } } } describe('v-model', function () { var el beforeEach(function () { el = document.createElement('div') el.style.display = 'none' document.body.appendChild(el) }) it('radio buttons', function (done) { var vm = new Vue({ el: el, data: { test: '1' }, template: '<input type="radio" value="1" v-model="test" name="test" number>' + '<input type="radio" value="2" v-model="test" name="test">' }) expect(el.childNodes[0].checked).toBe(true) expect(el.childNodes[1].checked).toBe(false) vm.test = '2' _.nextTick(function () { expect(el.childNodes[0].checked).toBe(false) expect(el.childNodes[1].checked).toBe(true) el.childNodes[0].click() expect(el.childNodes[0].checked).toBe(true) expect(el.childNodes[1].checked).toBe(false) expect(vm.test).toBe(1) vm._directives[1]._teardown() el.childNodes[1].click() expect(vm.test).toBe(1) done() }) }) it('radio default value', function () { var vm = new Vue({ el: el, data: {}, template: '<input type="radio" checked value="a" v-model="test">' }) expect(vm.test).toBe('a') }) it('radio expression', function (done) { var vm = new Vue({ el: el, data: { test: false, test2: 'string1', expression1: 'string1', expression2: 'string2' }, template: '<input type="radio" value="1" v-model="test" name="test" :value="true">' + '<input type="radio" value="0" v-model="test" name="test" :value="false">' + '<input type="radio" value="1" v-model="test2" name="test2" :value="expression1">' + '<input type="radio" value="0" v-model="test2" name="test2" :value="expression2">' }) expect(el.childNodes[0].checked).toBe(false) expect(el.childNodes[1].checked).toBe(true) expect(el.childNodes[2].checked).toBe(true) expect(el.childNodes[3].checked).toBe(false) _.nextTick(function () { el.childNodes[0].click() expect(vm.test).toBe(true) el.childNodes[3].click() expect(vm.test2).toBe('string2') done() }) }) it('checkbox', function (done) { var vm = new Vue({ el: el, data: { test: true }, template: '<input type="checkbox" v-model="test">' }) expect(el.firstChild.checked).toBe(true) vm.test = false _.nextTick(function () { expect(el.firstChild.checked).toBe(false) expect(vm.test).toBe(false) el.firstChild.click() expect(el.firstChild.checked).toBe(true) expect(vm.test).toBe(true) vm._directives[0]._teardown() el.firstChild.click() expect(el.firstChild.checked).toBe(false) expect(vm.test).toBe(true) done() }) }) it('checkbox default value', function () { var vm = new Vue({ el: el, data: {}, template: '<input type="checkbox" checked v-model="test">' }) expect(vm.test).toBe(true) }) it('checkbox expression', function (done) { var vm = new Vue({ el: el, data: { test: '', expression1: 'aTrueValue', expression2: 'aFalseValue' }, template: '<input type="checkbox" v-model="test" :true-value="expression1" :false-value="expression2">' }) expect(vm.test).toBe('') el.firstChild.click() expect(vm.test).toBe('aTrueValue') expect(el.firstChild.checked).toBe(true) el.firstChild.click() expect(vm.test).toBe('aFalseValue') expect(el.firstChild.checked).toBe(false) _.nextTick(function () { vm.test = 'aTrueValue' _.nextTick(function () { expect(el.firstChild.checked).toBe(true) done() }) }) }) it('checkbox + array model', function (done) { var vm = new Vue({ el: el, data: { list: [1], a: {} }, template: '<input type="checkbox" v-model="list" number value="1">' + '<input type="checkbox" v-model="list" :value="a">' }) expect(el.firstChild.checked).toBe(true) expect(el.lastChild.checked).toBe(false) el.firstChild.click() expect(vm.list.length).toBe(0) el.lastChild.click() expect(vm.list.length).toBe(1) expect(vm.list[0]).toBe(vm.a) el.firstChild.click() expect(vm.list.length).toBe(2) expect(vm.list[1]).toBe(1) vm.list = [vm.a] _.nextTick(function () { expect(el.firstChild.checked).toBe(false) expect(el.lastChild.checked).toBe(true) done() }) }) it('checkbox + array model default value', function () { var vm = new Vue({ el: el, data: { list: [], a: {} }, template: '<input type="checkbox" v-model="list" number value="1">' + '<input type="checkbox" checked v-model="list" :value="a">' }) expect(vm.list.length).toBe(1) expect(vm.list[0]).toBe(vm.a) }) it('select', function (done) { var vm = new Vue({ el: el, data: { test: 'b' }, template: '<select v-model="test">' + '<option>a</option>' + '<option>b</option>' + '<option>c</option>' + '</select>' }) expect(vm.test).toBe('b') expect(el.firstChild.value).toBe('b') expect(el.firstChild.childNodes[1].selected).toBe(true) vm.test = 'c' _.nextTick(function () { expect(el.firstChild.value).toBe('c') expect(el.firstChild.childNodes[2].selected).toBe(true) updateSelect(el.firstChild, 'a') trigger(el.firstChild, 'change') expect(vm.test).toBe('a') done() }) }) it('select persist non-selected on append', function (done) { var vm = new Vue({ el: el, data: { test: null }, replace: true, template: '<select v-model="test">' + '<option>a</option>' + '<option>b</option>' + '<option>c</option>' + '</select>' }) _.nextTick(function () { expect(vm.$el.value).toBe('') expect(vm.$el.selectedIndex).toBe(-1) vm.$remove() vm.$appendTo(document.body) _.nextTick(function () { expect(vm.$el.value).toBe('') expect(vm.$el.selectedIndex).toBe(-1) done() }) }) }) it('select template default value', function () { var vm = new Vue({ el: el, data: { test: 'a' }, template: '<select v-model="test">' + '<option>a</option>' + '<option selected>b</option>' + '</select>' }) expect(vm.test).toBe('b') expect(el.firstChild.value).toBe('b') expect(el.firstChild.childNodes[1].selected).toBe(true) }) it('select + empty default value', function () { var vm = new Vue({ el: el, template: '<select v-model="test"><option value="" selected>null</option><<option value="1">1</option></select>' }) expect(vm.test).toBe('') trigger(vm.$el.firstChild, 'change') expect(vm.test).toBe('') }) it('select + multiple', function (done) { var vm = new Vue({ el: el, data: { test: [2] // test number soft equal }, template: '<select v-model="test" multiple>' + '<option>1</option>' + '<option>2</option>' + '<option>3</option>' + '</select>' }) var opts = el.firstChild.options expect(opts[0].selected).toBe(false) expect(opts[1].selected).toBe(true) expect(opts[2].selected).toBe(false) vm.test = [1, '3'] // mix of number/string _.nextTick(function () { expect(opts[0].selected).toBe(true) expect(opts[1].selected).toBe(false) expect(opts[2].selected).toBe(true) opts[0].selected = false opts[1].selected = true trigger(el.firstChild, 'change') expect(vm.test[0]).toBe('2') expect(vm.test[1]).toBe('3') done() }) }) it('select + multiple default value', function () { var vm = new Vue({ el: el, data: {}, template: '<select v-model="test" multiple>' + '<option>a</option>' + '<option selected>b</option>' + '<option selected>c</option>' + '</select>' }) expect(vm.test[0]).toBe('b') expect(vm.test[1]).toBe('c') }) it('select + number', function () { var vm = new Vue({ el: el, data: { test: '1' }, template: '<select v-model="test" number><option value="1">1</option></select>' }) expect(vm.test).toBe('1') trigger(vm.$el.firstChild, 'change') expect(vm.test).toBe(1) }) it('select + number + multiple', function () { var vm = new Vue({ el: el, data: { test: [] }, template: '<select v-model="test" multiple number><option>1</option><option>2</option></select>' }) ;[].forEach.call(el.querySelectorAll('option'), function (o) { o.selected = true }) trigger(el.firstChild, 'change') expect(vm.test[0]).toBe(1) expect(vm.test[1]).toBe(2) }) it('select + number initial value', function () { var vm = new Vue({ el: el, data: { test: '1' }, template: '<select v-model="test" number><option value="1" selected>1</option></select>' }) expect(vm.test).toBe(1) }) it('select + v-for', function (done) { var vm = new Vue({ el: el, data: { test: { msg: 'A' }, opts: [ { text: 'a', value: { msg: 'A' }}, { text: 'b', value: { msg: 'B' }} ] }, template: '<select v-model="test">' + '<option v-for="op in opts" :value="op.value">{{op.text}}</option>' + '</select>' }) var select = el.firstChild var opts = select.options expect(opts[0].selected).toBe(true) expect(opts[1].selected).toBe(false) expect(vm.test.msg).toBe('A') opts[1].selected = true trigger(select, 'change') _.nextTick(function () { expect(opts[0].selected).toBe(false) expect(opts[1].selected).toBe(true) expect(vm.test.msg).toBe('B') vm.test = { msg: 'A' } _.nextTick(function () { expect(opts[0].selected).toBe(true) expect(opts[1].selected).toBe(false) vm.test = { msg: 'C' } vm.opts.push({text: 'c', value: vm.test}) _.nextTick(function () { // updating the opts array should force the // v-model to update expect(opts[0].selected).toBe(false) expect(opts[1].selected).toBe(false) expect(opts[2].selected).toBe(true) done() }) }) }) }) it('text', function (done) { var vm = new Vue({ el: el, data: { test: 'b' }, template: '<input v-model="test">' }) expect(el.firstChild.value).toBe('b') vm.test = 'a' _.nextTick(function () { expect(el.firstChild.value).toBe('a') el.firstChild.value = 'c' trigger(el.firstChild, 'input') expect(vm.test).toBe('c') vm._directives[0]._teardown() el.firstChild.value = 'd' trigger(el.firstChild, 'input') expect(vm.test).toBe('c') done() }) }) it('text default value', function () { var vm = new Vue({ el: el, data: { test: 'b' }, template: '<input v-model="test | test" value="a">', filters: { test: { read: function (v) { return v.slice(0, -1) }, write: function (v) { return v + 'c' } } } }) expect(vm.test).toBe('ac') expect(el.firstChild.value).toBe('a') }) it('text lazy', function () { var vm = new Vue({ el: el, data: { test: 'b' }, template: '<input v-model="test" lazy>' }) expect(el.firstChild.value).toBe('b') expect(vm.test).toBe('b') el.firstChild.value = 'c' trigger(el.firstChild, 'input') expect(vm.test).toBe('b') trigger(el.firstChild, 'change') expect(vm.test).toBe('c') }) it('text with filters', function (done) { var vm = new Vue({ el: el, data: { test: 'b' }, filters: { test: { write: function (val) { return val.toLowerCase() } } }, template: '<input v-model="test | uppercase | test">' }) expect(el.firstChild.value).toBe('B') trigger(el.firstChild, 'focus') el.firstChild.value = 'cc' trigger(el.firstChild, 'input') _.nextTick(function () { expect(el.firstChild.value).toBe('cc') expect(vm.test).toBe('cc') trigger(el.firstChild, 'change') trigger(el.firstChild, 'blur') _.nextTick(function () { expect(el.firstChild.value).toBe('CC') expect(vm.test).toBe('cc') done() }) }) }) it('text with only write filter', function (done) { var vm = new Vue({ el: el, data: { test: 'b' }, filters: { test: { write: function (val) { return val.toUpperCase() } } }, template: '<input v-model="test | test">' }) trigger(el.firstChild, 'focus') el.firstChild.value = 'cc' trigger(el.firstChild, 'input') _.nextTick(function () { expect(el.firstChild.value).toBe('cc') expect(vm.test).toBe('CC') trigger(el.firstChild, 'change') trigger(el.firstChild, 'blur') _.nextTick(function () { expect(el.firstChild.value).toBe('CC') expect(vm.test).toBe('CC') done() }) }) }) it('number', function () { var vm = new Vue({ el: el, data: { test: 1 }, template: '<input v-model="test" value="2" number>' }) expect(vm.test).toBe(2) el.firstChild.value = 3 trigger(el.firstChild, 'input') expect(vm.test).toBe(3) }) it('IE9 cut and delete', function (done) { var ie9 = _.isIE9 _.isIE9 = true var vm = new Vue({ el: el, data: { test: 'foo' }, template: '<input v-model="test">' }) var input = el.firstChild input.value = 'bar' trigger(input, 'cut') _.nextTick(function () { expect(vm.test).toBe('bar') input.value = 'a' trigger(input, 'keyup', function (e) { e.keyCode = 8 }) expect(vm.test).toBe('a') // teardown vm._directives[0]._teardown() input.value = 'bar' trigger(input, 'keyup', function (e) { e.keyCode = 8 }) expect(vm.test).toBe('a') _.isIE9 = ie9 done() }) }) if (!_.isAndroid) { it('text + compositionevents', function (done) { var vm = new Vue({ el: el, data: { test: 'foo', test2: 'bar' }, template: '<input v-model="test"><input v-model="test2 | uppercase">' }) var input = el.firstChild var input2 = el.childNodes[1] trigger(input, 'compositionstart') trigger(input2, 'compositionstart') input.value = input2.value = 'baz' // input before composition unlock should not call set trigger(input, 'input') trigger(input2, 'input') expect(vm.test).toBe('foo') expect(vm.test2).toBe('bar') // after composition unlock it should work trigger(input, 'compositionend') trigger(input2, 'compositionend') trigger(input, 'input') trigger(input2, 'input') expect(vm.test).toBe('baz') expect(vm.test2).toBe('baz') // IE complains about "unspecified error" when calling // setSelectionRange() on an input element that's been // removed from the DOM, so we wait until the // selection range callback has fired to end this test. _.nextTick(done) }) } it('textarea', function () { var vm = new Vue({ el: el, data: { test: 'foo', b: 'bar' }, template: '<textarea v-model="test">foo {{b}} baz</textarea>' }) expect(vm.test).toBe('foo bar baz') expect(el.firstChild.value).toBe('foo bar baz') }) it('warn invalid tag', function () { new Vue({ el: el, template: '<div v-model="test"></div>' }) expect('does not support element type').toHaveBeenWarned() }) it('warn read-only filters', function () { new Vue({ el: el, template: '<input v-model="abc | test">', filters: { test: function (v) { return v } } }) expect('read-only filter').toHaveBeenWarned() }) it('support jQuery change event', function (done) { // restore jQuery jQuery = $ var vm = new Vue({ el: el, data: { test: 'b' }, template: '<input v-model="test">' }) expect(el.firstChild.value).toBe('b') vm.test = 'a' _.nextTick(function () { expect(el.firstChild.value).toBe('a') el.firstChild.value = 'c' jQuery(el.firstChild).trigger('change') expect(vm.test).toBe('c') vm._directives[0]._teardown() el.firstChild.value = 'd' jQuery(el.firstChild).trigger('change') expect(vm.test).toBe('c') // unset jQuery jQuery = null done() }) }) it('support debounce', function (done) { var spy = jasmine.createSpy() var vm = new Vue({ el: el, data: { test: 'a' }, watch: { test: spy }, template: '<input v-model="test" debounce="100">' }) el.firstChild.value = 'b' trigger(el.firstChild, 'input') setTimeout(function () { el.firstChild.value = 'c' trigger(el.firstChild, 'input') }, 10) setTimeout(function () { el.firstChild.value = 'd' trigger(el.firstChild, 'input') }, 20) setTimeout(function () { expect(spy.calls.count()).toBe(0) expect(vm.test).toBe('a') }, 30) setTimeout(function () { expect(spy.calls.count()).toBe(1) expect(spy).toHaveBeenCalledWith('d', 'a') expect(vm.test).toBe('d') setTimeout(function () { el.firstChild.value = 'e' // change should trigger change instantly without debounce trigger(el.firstChild, 'change') trigger(el.firstChild, 'blur') _.nextTick(function () { expect(spy.calls.count()).toBe(2) expect(spy).toHaveBeenCalledWith('e', 'd') expect(vm.test).toBe('e') done() }) }, 10) }, 200) }) it('update on bind value change', function (done) { var vm = new Vue({ el: el, template: '<input type="radio" v-model="a" checked :value="b">' + '<input type="radio" v-model="a" :value="c">', data: { a: 0, b: 1, c: 2 } }) // should sync inline-checked value to a expect(vm.a).toBe(1) vm.b = 3 _.nextTick(function () { expect(vm.a).toBe(3) expect(el.firstChild.checked).toBe(true) expect(el.lastChild.checked).toBe(false) vm.a = 2 _.nextTick(function () { expect(el.firstChild.checked).toBe(false) expect(el.lastChild.checked).toBe(true) done() }) }) }) it('should not sync value on blur when parent fragment is removed', function (done) { el.style.display = '' var vm = new Vue({ el: el, replace: false, template: '<form v-if="ok" @submit.prevent="save">' + '<input v-model="msg">' + '</form>', data: { ok: true, msg: 'foo' }, methods: { save: function () { this.ok = false this.msg = '' } } }) el.querySelector('input').focus() trigger(el.querySelector('form'), 'submit') _.nextTick(function () { expect(vm.msg).toBe('') done() }) }) })
import React from 'react'; let Login = React.createClass({ render() { return(<div>Welcome to login</div>); } }); export default Login;
const describe = require('mocha').describe; const it = require('mocha').it; const assert = require('assert'); class Sample1 { constructor(name) { this._name = name; this._children = []; } /** * @param {Sample1} child */ addChild(child) { this._children.push(child); } } describe('class json handling', () => { it('single class', () => { const sample1 = new Sample1('foo'); const jsonString = JSON.stringify(sample1); const expected = { _name: 'foo', _children: [], }; assert.deepStrictEqual(JSON.parse(jsonString), expected); }); it('array of classes', () => { const sample1List = [ new Sample1('foo'), new Sample1('bar'), ]; const jsonString = JSON.stringify(sample1List); const expected = [ { _name: 'foo', _children: [], }, { _name: 'bar', _children: [], }, ]; assert.deepStrictEqual(JSON.parse(jsonString), expected); }); it('nest of classes', () => { const parent = new Sample1('a'); parent.addChild(new Sample1('b')); parent.addChild(new Sample1('c')); const jsonString = JSON.stringify(parent); const expected = { _name: 'a', _children: [ { _name: 'b', _children: [], }, { _name: 'c', _children: [], }, ], }; assert.deepStrictEqual(JSON.parse(jsonString), expected); }); });
'use strict'; // Assertions and testing utilities var chai = require('chai'); var chaiAsPromised = require('chai-as-promised'); chai.use(chaiAsPromised); GLOBAL.AssertionError = chai.AssertionError; GLOBAL.expect = chai.expect;
"use strict"; let datafire = require('datafire'); let openapi = require('./openapi.json'); module.exports = datafire.Integration.fromOpenAPI(openapi, "azure_security_operations");
import type from 'type-of'; import uniques from 'uniques'; /** * Returns all values for a given object or array recursively. * * @example * let x = { * a: 1, * b: 2, * c: 3 * } * * ob.values(x) * // → [1, 2, 3] * * @example * let x = { * a: 1, * b: 2, * c: 3, * d: [4] * } * * ob.values(x) * // → [1, 2, 3, 4] * * @param {object|any[]} subject The object or array of objects to get the values of * @param {boolean} [unique=true] Whether the result should contain duplicates or not * @returns {any[]} */ let values = (subject, unique=true) => { let localValues = []; if(type(subject) === 'array') { for(let i of subject){ localValues = localValues.concat(values(i)); } } else if(type(subject) === 'object') { for(let k in subject) { localValues = localValues.concat(values(subject[k])); }; } else { localValues.push(subject); } if(unique) { return uniques(localValues); } else { return localValues; } }; export default values;
import sinon from 'sinon'; export default { dataLoading: false, appInfo: { userDetails: { firstName: null, lastName: null, id: null, token: null, email: null, phone: null }, authState: { signedIn: false, message: null }, loadedMessages: { groupId: null } }, match: { params: { groupId: 'abcde' } }, groups: { meta: { count: 0 }, userGroups: { } }, allUserGroups: { meta: { count: 0 }, userGroups: {} }, resetLoadingState: sinon.spy(), resetRedirect: sinon.spy(), getGroupsForUser: sinon.spy(), getAllGroupsForUser: sinon.spy(), propsWithGroups: { dataLoading: false, appInfo: { userDetails: { firstName: null, lastName: null, id: null, token: null, email: null, phone: null }, authState: { signedIn: false, message: null }, loadedMessages: { groupId: null } }, match: { params: { groupId: 'abcde' } }, groups: { meta: { count: 1 }, userGroups: { abcde: { info: { id: 'abcde' } } } }, allUserGroups: { meta: { count: 1 }, userGroups: {} }, resetLoadingState: sinon.spy(), resetRedirect: sinon.spy(), getGroupsForUser: sinon.spy(), getAllGroupsForUser: sinon.spy(), } };
'use strict'; var React = require('react'), onClickOutside = require('react-onclickoutside') ; var DOM = React.DOM; var DateTimeSlotPickerYears = onClickOutside( React.createClass({ render: function() { var viewDate = this.props.start? this.props.viewStartDate : this.props.viewEndDate var year = parseInt( viewDate.year() / 10, 10 ) * 10; return DOM.div({ className: 'rdtYears' }, [ DOM.table({ key: 'a' }, DOM.thead({}, DOM.tr({}, [ DOM.th({ key: 'prev', className: 'rdtPrev' }, DOM.span({ onClick: this.props.subtractTime( 10, 'years', this.props.start )}, '‹' )), DOM.th({ key: 'year', className: 'rdtSwitch', onClick: this.props.showView( 'years' ), colSpan: 2 }, year + '-' + ( year + 9 ) ), DOM.th({ key: 'next', className: 'rdtNext' }, DOM.span({ onClick: this.props.addTime( 10, 'years', this.props.start )}, '›' )) ]))), DOM.table({ key: 'years' }, DOM.tbody( {}, this.renderYears( year ))) ]); }, renderYears: function( year ) { var years = [], i = -1, rows = [], renderer = this.props.renderYear || this.renderYear, selectedDate = this.props.start? this.props.selectedStartDate : this.props.selectedEndDate, viewDate = this.props.start? this.props.viewStartDate : this.props.viewEndDate, isValid = this.props.isValidDate || this.alwaysValidDate, classes, props, currentYear, isDisabled, noOfDaysInYear, daysInYear, validDay, // Month and date are irrelevant here because // we're only interested in the year irrelevantMonth = 0, irrelevantDate = 1 ; year--; while (i < 11) { classes = 'rdtYear'; currentYear = viewDate.clone().set( { year: year, month: irrelevantMonth, date: irrelevantDate } ); // Not sure what 'rdtOld' is for, commenting out for now as it's not working properly // if ( i === -1 | i === 10 ) // classes += ' rdtOld'; noOfDaysInYear = currentYear.endOf( 'year' ).format( 'DDD' ); daysInYear = Array.from({ length: noOfDaysInYear }, function( e, i ) { return i + 1; }); validDay = daysInYear.find(function( d ) { var day = currentYear.clone().dayOfYear( d ); return isValid( day ); }); isDisabled = ( validDay === undefined ); if ( selectedDate && selectedDate.year() === year ) { classes += ' rdtActive'; } else { if ( isDisabled ) { classes += ' rdtDisabled'; } } props = { key: year, 'data-value': year, className: classes }; if ( !isDisabled ) props.onClick = ( this.props.viewMode === 'years' ? this.updateSelectedYear : this.props.setDate('year', this.props.start) ); years.push( renderer( props, year, selectedDate && selectedDate.clone() )); if ( years.length === 4 ) { rows.push( DOM.tr({ key: i }, years ) ); years = []; } year++; i++; } return rows; }, updateSelectedYear: function( event ) { if (this.props.start) { this.props.updateSelectedDate( event, 'start' ); } else { this.props.updateSelectedDate( event, 'end' ); } }, renderYear: function( props, year ) { return DOM.td( props, year ); }, alwaysValidDate: function() { return 1; }, handleClickOutside: function() { // this.props.handleClickOutside(); } })); module.exports = DateTimeSlotPickerYears;
var app = require('./../../app'), browser, Browser = require('zombie'), http = require('http'), port = (process.env.PORT || 1337), should = require('should'); Browser.dns.localhost('pay-legalisation-drop-off.test.gov.uk'); describe("Pay to legalise documents using the premium service", function(){ beforeEach(function(done){ browser = new Browser(); browser.site = "http://pay-legalisation-drop-off.test.gov.uk:"+port; done(); }); describe("start", function(){ it("render the transaction intro page and generate the payment form when 'Calculate total' is clicked", function(done){ browser.visit("/start", {}, function(err){ // testing re-direct browser.text("title").should.equal('Get your document legalised - GOV.UK'); done(); }); }); }); });
'use strict'; module.exports = (driver, spec) => { spec.shouldBehaveLikeMusicSite(driver, { url: 'https://www.emusic.com/album/94085593/Godspeed-You-Black-Emperor/Luciferian-Towers', playButtonSelector: '.play__all__wrapper' }); };
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var store = {}; function hold(key, value) { return this[key] = value; } function release(key) { var value = this[key]; delete this[key]; return value; } function keyFor(value) { for (var key in this) { if (this[key] == value) { return key; } } } _extends(store, { hold: hold, release: release, keyFor: keyFor }); exports.default = store;
/** * Main Application Module */ //=require_self //=require_tree ./ angular.module("scape", ['ngCookies', 'ngResource', 'ngRoute', 'ui.bootstrap', 'ui.codemirror']);
import resaga, { CONFIG, sagas, reducer } from '../index'; describe('Test Export', () => { describe('resaga', () => { it('should exists', () => { expect(resaga).toBeDefined(); expect(typeof resaga).toBe('function'); }); }); describe('CONFIG', () => { it('should exists', () => { expect(CONFIG).toBeDefined(); expect(typeof CONFIG).toBe('object'); }); }); describe('sagas', () => { it('should exists', () => { expect(sagas).toBeDefined(); expect(typeof sagas).toBe('object'); }); }); describe('reducer', () => { it('should exists', () => { expect(reducer).toBeDefined(); expect(typeof reducer).toBe('function'); }); }); });
describe("typingSkillTraining panel tests", function() { var sh = specHelper() , panel ; beforeEach(function() { $("#sandbox") .append("<div class='panel'></div>") .find(".panel") .append("<ul><li class='lastTimeSpan'></li></ul>"); sh.defaultOpt.panel = $(".panel"); sh.enablePlugin(); panel = $(sh.global).data("typingSkillTraining").panel; }); afterEach(function(){ sh.disablePlugin(); sh.clearSandbox(); }); it("initial text of lastTimeLabel is 0.000 seconds", function() { expect(panel).toBeDefined(); expect(panel.find(".lastTimeSpan").text()).toBe("0.000 seconds"); }); });
/*jshint node:true, mocha:true*/ /** * @author kecso / https://github.com/kecso */ var testFixture = require('../../_globals.js'); describe('ServerWorkerManager', function () { 'use strict'; var logger = testFixture.logger.fork('workermanager.spec'), expect = testFixture.expect, Q = testFixture.Q, gmeConfig = testFixture.getGmeConfig(), agent = testFixture.superagent.agent(), guestAccount = gmeConfig.authentication.guestAccount, storage, webGMESessionId, server, workerConstants = require('../../../src/server/worker/constants'), ServerWorkerManager = require('../../../src/server/worker/serverworkermanager'), workerManagerParameters = { globConf: gmeConfig, logger: logger, }, projectName = 'SWMProject', projectId = testFixture.projectName2Id(projectName), gmeAuth; gmeConfig.server.maxWorkers = 3; gmeConfig.addOn.enable = true; before(function (done) { //adding some project to the database server = testFixture.WebGME.standaloneServer(gmeConfig); server.start(function (err) { expect(err).to.equal(null); testFixture.clearDBAndGetGMEAuth(gmeConfig, projectName) .then(function (gmeAuth_) { gmeAuth = gmeAuth_; storage = testFixture.getMongoStorage(logger, gmeConfig, gmeAuth); return storage.openDatabase(); }) .then(function () { return testFixture.forceDeleteProject(storage, gmeAuth, projectName); }) .then(function () { return testFixture.importProject(storage, { projectSeed: 'test/server/worker/workermanager/basicProject.json', projectName: projectName, branchName: 'master', gmeConfig: gmeConfig, logger: logger }); }) .then(function (/*result*/) { return testFixture.openSocketIo(server, agent, guestAccount, guestAccount); }) .then(function (result) { webGMESessionId = result.webGMESessionId; }) .nodeify(done); }); }); after(function (done) { server.stop(function (err) { if (err) { logger.error(err); } testFixture.forceDeleteProject(storage, gmeAuth, projectName) .then(function () { return Q.allSettled([ storage.closeDatabase(), gmeAuth.unload() ]); }) .nodeify(done); }); }); describe('open-close handling', function () { var swm; before(function () { swm = new ServerWorkerManager(workerManagerParameters); }); it.skip('should reserve a worker when starts', function (/*done*/) { }); it('should handle multiple stop gracefully', function (done) { swm.start(); swm.stop(function (err) { expect(err).to.equal(null); swm.stop(function (err) { expect(err).to.equal(null); done(); }); }); }); it('should handle multiple start gracefully', function (done) { swm.start(); swm.start(); swm.start(); swm.start(); swm.stop(function (err) { expect(err).to.equal(null); done(); }); }); it('should handle start stop start stop', function (done) { swm.start(); swm.stop(function (err) { expect(err).to.equal(null); swm.start(); swm.stop(function (err) { expect(err).to.equal(null); done(); }); }); }); }); describe('bad request handling', function () { var swm, ownGmeConfig = JSON.parse(JSON.stringify(gmeConfig)), managerParameters = { globConf: ownGmeConfig, logger: logger, }; ownGmeConfig.addOn.enable = false; before(function () { swm = new ServerWorkerManager(managerParameters); swm.start(); }); after(function (done) { swm.stop(done); }); it('should respond with error to unknown request', function (done) { swm.request({command: 'unknown command'}, function (err/*, resultId*/) { expect(err).not.to.equal(null); done(); }); }); it('should fail to start addOn as it is disabled', function (done) { var addOnRequest = { command: 'connectedWorkerStart', workerName: 'TestAddOn', projectId: projectId, webGMESessionId: webGMESessionId, branch: 'master' }; swm.request(addOnRequest, function (err/*, id*/) { expect(err).not.to.equal(null); expect(err).to.include('not enabled'); done(); }); }); it('should fail to proxy query to an unknown id', function (done) { swm.query('no id', {}, function (err/*, result*/) { expect(err).not.to.equal(null); expect(err).to.contain('identification'); done(); }); }); }); describe('simple request-result handling', function () { function exportLibrary(next) { swm.request({ command: workerConstants.workerCommands.exportLibrary, branchName: 'master', webGMESessionId: webGMESessionId, projectId: projectId, path: '/323573539' }, function (err, resultId) { expect(err).to.equal(null); swm.result(resultId, function (err, result) { expect(err).to.equal(null); expect(result).to.include.keys('bases', 'root', 'relids', 'containment', 'nodes', 'metaSheets'); next(); }); }); } var swm; before(function (done) { swm = new ServerWorkerManager(workerManagerParameters); swm.start(); setTimeout(done, 100); }); after(function (done) { swm.stop(done); }); it('should handle a single request', function (done) { exportLibrary(done); }); it('should handle multiple requests', function (done) { var needed = 3, i, requestHandled = function () { needed -= 1; if (needed === 0) { done(); } }; for (i = 0; i < needed; i += 1) { exportLibrary(requestHandled); } }); it('should handle more requests simultaneously than workers allowed', function (done) { var needed = gmeConfig.server.maxWorkers + 1, i, requestHandled = function () { needed -= 1; if (needed === 0) { done(); } }; for (i = 0; i < needed; i += 1) { exportLibrary(requestHandled); } }); }); describe('connected worker handling', function () { var swm, getConnectedWorkerStartRequest = function () { return { command: workerConstants.workerCommands.connectedWorkerStart, workerName: 'TestAddOn', projectId: projectId, webGMESessionId: webGMESessionId, branch: 'master' }; }; before(function () { swm = new ServerWorkerManager(workerManagerParameters); }); beforeEach(function (done) { swm.start(); setTimeout(done, 100); }); afterEach(function (done) { swm.stop(done); }); it('should start and stop connected worker', function (done) { swm.request(getConnectedWorkerStartRequest(), function (err, id) { expect(err).to.equal(null); swm.result(id, function (err) { expect(err).to.equal(null); done(); }); }); }); it('should proxy the query to the connected worker', function (done) { swm.request(getConnectedWorkerStartRequest(), function (err, id) { expect(err).to.equal(null); swm.query(id, {}, function (err/*, result*/) { expect(err).to.equal(null); swm.result(id, function (err) { expect(err).to.equal(null); done(); }); }); }); }); it('should fail to proxy queries after swm stop', function (done) { swm.request(getConnectedWorkerStartRequest(), function (err, id) { expect(err).to.equal(null); swm.query(id, {}, function (err/*, result*/) { expect(err).to.equal(null); swm.stop(function () { swm.query(id, {}, function (err/*, result*/) { expect(err).not.to.equal(null); expect(err).to.contain('handler cannot be found'); done(); }); }); }); }); }); it('should fail to proxy connected worker close after swm stop', function (done) { swm.request(getConnectedWorkerStartRequest(), function (err, id) { expect(err).to.equal(null); swm.query(id, {}, function (err/*, result*/) { expect(err).to.equal(null); swm.stop(function () { swm.result(id, function (err) { expect(err).not.to.equal(null); expect(err).to.contain('handler cannot be found'); done(); }); }); }); }); }); }); });
//You need an anonymous function to wrap around your function to avoid conflict // USAGE: $('#element').slideShow({ option: optionval }); (function($){ //Attach this new method to jQuery $.fn.extend({ //This is where you write your plugin's name slideShow: function(options){ // Defaults values for settings var defaults = { panelClass: ".panel", //class of the panels in the slideshow initialFadeIn: 1000, //initial fade-in time (in milliseconds) itemInterval: 5000, //interval between items (in milliseconds) fadeTime: 2500 //cross-fade time (in milliseconds) }; // overwrite defaults with passed options var options = $.extend(defaults, options); //Iterate over the current set of matched elements return this.each(function(){ var o = options; //code to be inserted here var obj = $(this); // obj is the element the plugin is applied to var numberOfItems = $(o.panelClass).length; //count number of items var currentItem = 0; //set current item // cycle through each panel and hide all but the first $(o.panelClass).each(function(index){ if(index > 0){ $(this).hide(); } }); $(o.panelClass).eq(currentItem).fadeIn(o.initialFadeIn); //show first item if(numberOfItems > 1){ var infiniteLoop = setInterval(function(){ //loop through the items $(o.panelClass).eq(currentItem).fadeOut(o.fadeTime); if(currentItem == numberOfItems -1){ currentItem = 0; } else { currentItem++; } $(o.panelClass).eq(currentItem).fadeIn(o.fadeTime); }, o.itemInterval); } }); } }); //pass jQuery to the function, //So that we will able to use any valid Javascript variable name //to replace "$" SIGN. But, we'll stick to $ (I like dollar sign: ) ) })(jQuery);
/** * Created by duoyi on 2017/1/23. */ const statuses = require('../controllers/statuses'); module.exports = function (router) { router.get('*', statuses.friends_timeline); }
define("bootstrap.wysihtml5.commands", ["wysihtml5"], function(wysihtml5) { (function(wysihtml5) { wysihtml5.commands.small = { exec: function(composer, command) { return wysihtml5.commands.formatInline.exec(composer, command, "small"); }, state: function(composer, command) { return wysihtml5.commands.formatInline.state(composer, command, "small"); } }; })(wysihtml5); });
var gulp = require('gulp'); var less = require('gulp-less'); /** * Gulp errors */ function swallowError (error) { console.log(error.toString()); this.emit('end'); } /** * Task custom normalize */ gulp.task('normalize', function () { var less_src_import = 'normalize.less'; var less_dest_folder = 'dist/'; return gulp.src(less_src_import) .pipe(less()) .on('error', swallowError) .pipe(gulp.dest(less_dest_folder)) });
var page = require('webpage').create(); var args = require('system').args; var data = {}; page.open(args[1], function(status) { data.title = page.evaluate(function() { document.querySelector('.download').click(); var title = document.title; if(title.indexOf(' - JAV') != -1) title = title.split(' - JAV')[0]; return title; }); data.img = page.evaluate(function() { return document.querySelector('.thumbnail img').src; }); setTimeout(getUrl, 5000); }); function getUrl() { data.url = page.evaluate(function() { return document.querySelector('#download a').href; }); var cmd = 'wget -q -U "Mozilla" -O - "URL" | ./gdrive -c wei upload - -p "FID" "TITLE.mp4"'; cmd = cmd.replace('URL', data.url); cmd = cmd.replace('TITLE', data.title.replace(/"/g, '\\"')); console.log(cmd); phantom.exit(); }
smcom.controller('HomeController',['$scope','ContactService',function($scope,ContactService){ $scope.contact = ContactService; }]);
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M12 4C7.31 4 3.07 5.9 0 8.98L12 21 24 8.98C20.93 5.9 16.69 4 12 4z" /> , 'SignalWifiStatusbar4BarOutlined');
import _$ from 'jquery'; import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; import jsdom from 'jsdom'; import chai, { expect } from 'chai'; import chaiJquery from 'chai-jquery'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import reducers from '../src/reducers'; global.document = jsdom.jsdom('<!doctype html><html><body></body></html>'); global.window = global.document.defaultView; global.navigator = global.window.navigator; const $ = _$(window); chaiJquery(chai, chai.util, $); function renderComponent(ComponentClass, props = {}, state = {}) { const componentInstance = TestUtils.renderIntoDocument( <Provider store={createStore(reducers, state)}> <ComponentClass {...props} /> </Provider> ); return $(ReactDOM.findDOMNode(componentInstance)); } $.fn.simulate = function(eventName, value) { if (value) { this.val(value); } TestUtils.Simulate[eventName](this[0]); }; export { renderComponent, expect };
// @flow import ObjectProxy from '@ember/object/proxy'; import { get } from '@ember/object'; import { assert } from '@ember/debug'; import { isPresent } from '@ember/utils'; import { RELAY } from 'ember-changeset/utils/is-relay'; /*:: import type { ChangesetDef } from 'ember-changeset'; */ /*:: export type RelayDef = {| changeset: ChangesetDef | null, key: string, content: Object | null, _changedKeys: Object, __relay__: typeof RELAY, _super: () => void, init: () => void, unknownProperty: (string) => mixed, setUnknownProperty: (string, mixed) => mixed, rollback: () => void, destroy: () => void, notifyPropertyChange: (string) => void, isEqual: (RelayDef) => boolean, |}; */ /** * A Relay delegates property accesses to its changeset. The property * may optionally be prefixed by `key`. * * This is done as a workaround for Ember's `unknownProperty` behavior. * Given the key "foo.bar.baz", Ember breaks the key into "foo", "bar", * and "baz", then feeds each string into `unknownProperty`. However, we * need the entire key "foo.bar.baz" in order to look up the change on * the changeset. A Relay will hold the key "foo.bar", and let us look * up "foo.bar.baz" on the changeset when "baz" is requested. */ export default ObjectProxy.extend(({ /*:: _super() {}, notifyPropertyChange() {}, _changedKeys: {}, */ /** * Internal descriptor for relay identification. */ __relay__: RELAY, changeset: null, key: '', content: null, init() { let r /*: RelayDef */ = this; r._super(...arguments); r._changedKeys = {}; assert('changeset must be present.', isPresent(get(this, 'changeset'))); assert('content must be present.', isPresent(get(this, 'content'))); assert('key must be present.', isPresent(get(this, 'key'))); }, unknownProperty(key) { let r /*: RelayDef */ = this; if (!r.changeset) throw new Error('Relay has no changeset.'); return r.changeset._valueFor(`${r.key}.${key}`); }, setUnknownProperty(key, value) { let r /*: RelayDef */ = this; r._changedKeys[key] = null; if (!r.changeset) throw new Error('Relay has no changeset.'); r.changeset._validateAndSet(`${r.key}.${key}`, value); r.notifyPropertyChange(key); return value; }, rollback() { let r /*: RelayDef */ = this; r._super(...arguments); for (let k of Object.keys(r._changedKeys)) r.notifyPropertyChange(k); r._changedKeys = {}; }, destroy() { let r /*: RelayDef */ = this; r._super(...arguments); r.changeset = null; r.content = null; }, isEqual(other) { let r /*: RelayDef */ = this; let original = get(r, 'content'); return r === other || original === other; }, } /*: RelayDef */));
define([ 'jquery', 'underscore', 'mage/template', 'mage/translate', 'priceUtils', 'select2' ], function ($, _, mageTemplate, $t, priceUtils, select2) { 'use strict'; return function (widget) { $.widget('mage.SwatchRenderer', widget, { options: { classes: { attributeClass: 'swatch', attributeLabelClass: 'swatch__title product-view__swatch-option-title', attributeSelectedOptionLabelClass: 'swatch__selected-option', attributeOptionsWrapper: 'swatch__wrapper', attributeInput: 'swatch__input', optionClass: 'swatch__option', optionContainerClass: 'swatch__option-container', selectClass: 'select__field', moreButton: 'swatch-more', loader: 'swatch-option-loading', initLoader: 'loader' }, // option's json config jsonConfig: {}, // swatch's json config jsonSwatchConfig: {}, // selector of parental block of prices and swatches (need to know where to seek for price block) selectorProduct: '.product-info-main', // selector of price wrapper (need to know where set price) selectorProductPrice: '[data-role=priceBox]', //selector of product images gallery wrapper mediaGallerySelector: '[data-gallery-role=gallery-placeholder]', // selector of category product tile wrapper selectorProductTile: '[class*="-item__swatches"]', // number of controls to show (false or zero = show all) numberToShow: false, // show only swatch controls onlySwatches: false, // enable label for control enableControlLabel: true, // control label id controlLabelId: '', // text for more button moreButtonText: $t('More'), // Callback url for media mediaCallback: '', // Local media cache mediaCache: {}, // Cache for BaseProduct images. Needed when option unset mediaGalleryInitial: [{}], // Use ajax to get image data useAjax: false, /** * Defines the mechanism of how images of a gallery should be * updated when user switches between configurations of a product. * * As for now value of this option can be either 'replace' or 'prepend'. * * @type {String} */ gallerySwitchStrategy: 'replace', // whether swatches are rendered in product list or on product page inProductList: false, // special price wrapper selector specialPriceWrapper: '.price__wrapper', // sly-final-price block selector slyFinalPriceSelector: '.sly-final-price', // sly-old-price block selector slyOldPriceSelector: '.sly-old-price', // tier prise selectors start tierPriceTemplateSelector: '#tier-prices-template', tierPriceBlockSelector: '[data-role="tier-price-block"]', tierPriceTemplate: '', // tier prise selectors end // A price label selector normalPriceLabelSelector: '.product-info-main .normal-price .price-label', // option for select2 lib select2options: { minimumResultsForSearch: Infinity, width: null, position: 'bottom', }, }, /** * Callback for product media * * @param {Object} $this * * @param {Object} response * @param {String} response.large * @param {String} response.medium * @param {String} response.small * @param {String=} response.large_webp * @param {String=} response.medium_webp * @param {String=} response.small_webp * @param {Boolean} isInProductView * @private */ _ProductMediaCallback: function ($this, response, isInProductView) { var $main = isInProductView ? $this.parents('.column.main') : $this.parents('.product-item-info'), $widget = this, images = [], /** * Check whether object supported or not * * @param {Object} e * @returns {*|Boolean} */ support = function (e) { return e.hasOwnProperty('large') && e.hasOwnProperty('medium') && e.hasOwnProperty('small'); }; if (_.size($widget) < 1 || !support(response)) { this.updateBaseImage(this.options.mediaGalleryInitial, $main, isInProductView); return; } // SNOWDOG CHANGES START // With yireo/webp-images response is also // returning .webp files images.push({ full: response.large, img: response.medium, thumb: response.small, isMain: true, full_webp: response.large_webp, img_webp: response.medium_webp, thumb_webp: response.small_webp }); if (response.hasOwnProperty('gallery')) { $.each(response.gallery, function () { if (!support(this) || response.large === this.large) { return; } images.push({ full: this.large, img: this.medium, thumb: this.small, full_webp: this.large_webp, img_webp: this.medium_webp, thumb_webp: this.small_webp }); }); } // SNOWDOG CHANGES END this.updateBaseImage(images, $main, isInProductView); }, /** * Update [gallery-placeholder] or [product-image-photo] * @param {Array} images * @param {jQuery} context * @param {Boolean} isInProductView */ updateBaseImage: function (images, context, isInProductView) { var justAnImage = images[0], initialImages = this.options.mediaGalleryInitial, imagesToUpdate, gallery = context.find(this.options.mediaGallerySelector).data('gallery'), isInitial; if (isInProductView) { if (_.isUndefined(gallery)) { context.find(this.options.mediaGallerySelector).on('gallery:loaded', function () { this.updateBaseImage(images, context, isInProductView); }.bind(this)); return; } imagesToUpdate = images.length ? this._setImageType($.extend(true, [], images)) : []; isInitial = _.isEqual(imagesToUpdate, initialImages); if (this.options.gallerySwitchStrategy === 'prepend' && !isInitial) { imagesToUpdate = imagesToUpdate.concat(initialImages); } imagesToUpdate = this._setImageIndex(imagesToUpdate); gallery.updateData(imagesToUpdate); this._addFotoramaVideoEvents(isInitial); } else if (justAnImage && (justAnImage.img)) { // SNOWDOG CHANGES START // When swatch was loading an image it only loaded .jpg // so we need add basic support for .webp images context.find('img.product-image-photo').attr( { 'src': justAnImage.img_webp ? justAnImage.img_webp : justAnImage.img, 'data-src': justAnImage.img_webp ? justAnImage.img_webp : justAnImage.img, 'srcset': justAnImage.img_webp ? justAnImage.img_webp : justAnImage.img, } ); if (justAnImage.img_webp) { context .find('picture.product-image-photo source[type="image/webp"]') .attr( { 'data-src': justAnImage.img_webp, 'srcset': justAnImage.img_webp, } ) } // SNOWDOG CHANGES END } }, _determineProductData: function () { // Check if product is in a list of products. var productId, isInProductView = false; productId = this.element .parents('[class*="-item__swatches"]') .find('.price-box.price-final_price') .attr('data-product-id'); if (!productId) { // Check individual product. productId = $('[name=product]').val(); isInProductView = productId > 0; } return { productId: productId, isInProductView: isInProductView, }; }, _RenderControls: function () { var $widget = this, container = this.element, classes = this.options.classes, chooseText = this.options.jsonConfig.chooseText, showTooltip = this.options.showTooltip, $product = $widget.element.parents($widget.options.selectorProduct), prices = $widget._getNewPrices(), productData = this._determineProductData(); $widget.optionsMap = {}; $.each(this.options.jsonConfig.attributes, function () { var item = this, controlLabelId = 'option-label-' + productData.productId + '-' + item.code + '-' + item.id, options = $widget._RenderSwatchOptions(item, controlLabelId), select = $widget._RenderSwatchSelect(item, chooseText), input = $widget._RenderFormInput(item, productData), listLabel = '', label = '', initLoader = container.find($('.' + $widget.options.classes.initLoader)) ; // Show only swatch controls if ($widget.options.onlySwatches && !$widget.options.jsonSwatchConfig.hasOwnProperty(item.id)) { return; } if ($widget.options.enableControlLabel) { label += '<span id="' + controlLabelId + '" class="' + classes.attributeLabelClass + '">' + $('<i></i>').text(item.label).html() + '</span>' + '<span class="' + classes.attributeSelectedOptionLabelClass + '"></span>'; } if ($widget.inProductList) { $widget.productForm.append(input); input = ''; listLabel = 'aria-label="' + $('<i></i>').text(item.label).html() + '"'; } else { listLabel = 'aria-labelledby="' + controlLabelId + '"'; } // Create new control if (initLoader.hasClass('loader--visible')) { initLoader.removeClass('loader--visible'); } container.append( '<div class="swatch-attribute ' + classes.attributeClass + ' ' + item.code + '" ' + 'data-attribute-code="' + item.code + '" ' + 'data-attribute-id="' + item.id + '">' + label + '<div aria-activedescendant="" ' + 'tabindex="0" ' + 'aria-invalid="false" ' + 'aria-required="true" ' + 'role="listbox" ' + listLabel + 'class="' + classes.attributeOptionsWrapper + ' clearfix">' + options + select + '</div>' + input + '</div>' ); $widget.optionsMap[item.id] = {}; // Aggregate options array to hash (key => value) $.each(item.options, function () { if (this.products.length > 0) { $widget.optionsMap[item.id][this.id] = { price: parseInt( $widget.options.jsonConfig.optionPrices[this.products[0]].finalPrice.amount, 10 ), products: this.products }; } }); }); if (showTooltip === 1) { // Connect Tooltip container .find('[data-option-type="1"], [data-option-type="2"],' + ' [data-option-type="0"], [data-option-type="3"]') .SwatchRendererTooltip(); } // Hide all elements below more button $('.' + classes.moreButton).nextAll().hide(); // Display special price $widget._updateSpecialPrice(prices); $product.find(this.options.specialPriceWrapper).removeClass('display-none'); // Handle events like click or change $widget._EventListener(); // Rewind options $widget._Rewind(container); //Emulate click on all swatches from Request $widget._EmulateSelected($.parseQuery()); $widget._EmulateSelected($widget._getSelectedAttributes()); var selectSwatch = $(container.find('.' + $widget.options.classes.selectClass)); $(selectSwatch).select2($widget.options.select2options); }, _RenderSwatchOptions: function (config, controlId) { var optionConfig = this.options.jsonSwatchConfig[config.id], optionClass = this.options.classes.optionClass, optionContainerClass = this.options.classes.optionContainerClass, moreLimit = parseInt(this.options.numberToShow, 10), moreClass = this.options.classes.moreButton, moreText = this.options.moreButtonText, countAttributes = 0, html = ''; if (!this.options.jsonSwatchConfig.hasOwnProperty(config.id)) { return ''; } $.each(config.options, function (index) { var id, type, value, thumb, label, attr; if (!optionConfig.hasOwnProperty(this.id)) { return ''; } // Add more button if (moreLimit === countAttributes++) { html += '<a href="#" class="' + moreClass + '">' + moreText + '</a>'; } id = this.id; type = parseInt(optionConfig[id].type, 10); value = optionConfig[id].hasOwnProperty('value') ? optionConfig[id].value : ''; thumb = optionConfig[id].hasOwnProperty('thumb') ? optionConfig[id].thumb : ''; label = this.label ? this.label : ''; attr = ' id="' + controlId + '-item-' + id + '"' + ' index="' + index + '"' + ' aria-selected="false"' + ' aria-checked="false"' + ' tabindex="0"' + ' data-option-type="' + type + '"' + ' data-option-id="' + id + '"' + ' data-option-label="' + label + '"' + ' aria-label="' + config.code + ' ' + label + '"' + ' role="option"'; attr += thumb !== '' ? ' data-option-tooltip-thumb="' + thumb + '"' : ''; attr += value !== '' ? ' data-option-tooltip-value="' + value + '"' : ''; if (!this.hasOwnProperty('products') || this.products.length <= 0) { attr += ' data-option-empty="true"'; } html += '<div class="swatch-option ' + optionContainerClass + '" ' + attr + '><div class="' + optionClass; if (type === 0) { // Text html += '">' + (value ? value : label); } else if (type === 1) { // Color if (value === '#ffffff') { html += ' ' + optionClass + '--white'; } html += '" style="background-color: ' + value + '">'; } else if (type === 2) { // Image html += ' ' + optionClass + '--image"' + ' style="background-image: url(' + value + ')">'; } else if (type === 3) { // Clear html += '">'; } else { // Default html += '">' + label; } html += '</div></div>'; }); return html; }, _RenderSwatchSelect: function (config, chooseText) { var html; if (this.options.jsonSwatchConfig.hasOwnProperty(config.id)) { return ''; } html = '<select class="' + this.options.classes.selectClass + ' ' + config.code + '">' + '<option value="0" data-option-id="0">' + chooseText + '</option>'; $.each(config.options, function () { var label = this.label, attr = ' value="' + this.id + '" data-option-id="' + this.id + '"'; if (!this.hasOwnProperty('products') || this.products.length <= 0) { attr += ' data-option-empty="true"'; } html += '<option ' + attr + '>' + label + '</option>'; }); html += '</select>'; return html; }, /** * Input for submit form. * This control shouldn't have "type=hidden", "display: none" for validation work :( * * @param {Object} config * @private */ _RenderFormInput: function (config, productData) { return '<input class="swatch-input ' + this.options.classes.attributeInput + ' super-attribute-select" ' + 'name="super_attribute[' + config.id + ']" ' + 'type="text" ' + 'value="" ' + 'data-selector="super_attribute[' + config.id + ']" ' + 'data-validate="{required: true}" ' + 'data-product="' + productData.productId + '"' + 'aria-required="true" ' + 'aria-invalid="false" ' + 'aria-hidden="true" ' + 'tabindex="-1">'; }, _EventListener: function () { var $widget = this, options = this.options.classes, target; $widget.element.on('click', '.' + options.optionContainerClass, function () { return $widget._OnClick($(this), $widget); }); $widget.element.on('change', '.' + options.selectClass, function () { return $widget._OnChange($(this), $widget); }); $widget.element.on('click', '.' + options.moreButton, function (e) { e.preventDefault(); return $widget._OnMoreClick($(this)); }); $widget.element.on('keydown', function (e) { if (e.which === 13) { target = $(e.target); if (target.is('.' + options.optionContainerClass)) { return $widget._OnClick(target, $widget); } else if (target.is('.' + options.selectClass)) { return $widget._OnChange(target, $widget); } else if (target.is('.' + options.moreButton)) { e.preventDefault(); return $widget._OnMoreClick(target); } } }); }, _OnClick: function ($this, $widget) { var $parent = $this.parents('.' + $widget.options.classes.attributeClass), $wrapper = $this.parents('.' + $widget.options.classes.attributeOptionsWrapper), $label = $parent.find('.' + $widget.options.classes.attributeSelectedOptionLabelClass), attributeId = $parent.data('attribute-id'), $input = $parent.find('.' + $widget.options.classes.attributeInput), $priceBox = $widget.element.parents($widget.options.selectorProduct) .find(this.options.selectorProductPrice); if ($widget.inProductList) { $input = $widget.productForm.find( '.' + $widget.options.classes.attributeInput + '[name="super_attribute[' + attributeId + ']"]' ); } if ($this.hasClass('disabled')) { return; } if ($this.hasClass('selected')) { $parent.removeAttr('data-option-selected').find('.selected').removeClass('selected'); $input.val(''); $label.text(''); $this.attr('aria-selected', false); } else { $parent.attr('data-option-selected', $this.data('option-id')).find('.selected').removeClass('selected'); $label.text($this.data('option-label')); $input.val($this.data('option-id')); $input.attr('data-attr-name', this._getAttributeCodeById(attributeId)); $this.addClass('selected'); $widget._toggleCheckedAttributes($this, $wrapper); } $widget._Rebuild(); if ($priceBox.is(':data(mage-priceBox)')) { $widget._UpdatePrice(); } $(document).trigger('updateMsrpPriceBlock', [ this._getSelectedOptionPriceIndex(), $widget.options.jsonConfig.optionPrices, $priceBox ] ); $widget._loadMedia(); $input.trigger('change'); }, _toggleCheckedAttributes: function ($this, $wrapper) { $wrapper.attr('aria-activedescendant', $this.attr('id')) .find('.' + this.options.classes.optionContainerClass).attr('aria-selected', false); $this.attr('aria-selected', true); }, _Rebuild: function () { var $widget = this, controls = $widget.element.find('.' + $widget.options.classes.attributeClass + '[data-attribute-id]'), selected = controls.filter('[data-option-selected]'); // Enable all options $widget._Rewind(controls); // done if nothing selected if (selected.length <= 0) { return; } // Disable not available options controls.each(function () { var $this = $(this), id = $this.data('attribute-id'), products = $widget._CalcProducts(id); if (selected.length === 1 && selected.first().data('attribute-id') === id) { return; } $this.find('[data-option-id]').each(function () { var $element = $(this), option = $element.data('option-id'); if (!$widget.optionsMap.hasOwnProperty(id) || !$widget.optionsMap[id].hasOwnProperty(option) || $element.hasClass('selected') || $element.is(':selected')) { return; } if (_.intersection(products, $widget.optionsMap[id][option].products).length <= 0) { $element.attr('disabled', true).addClass('disabled'); // rebuild select with select2 lib to set disabled options var selectSwatch = $widget.element.find('.' + $widget.options.classes.selectClass); $(selectSwatch).select2($widget.options.select2options); } }); }); }, _UpdatePrice: function () { var $widget = this, $product = $widget.element.parents($widget.options.selectorProduct), $productPrice = $product.find(this.options.selectorProductPrice), options = _.object(_.keys($widget.optionsMap), {}), newPrices, result, tierPriceHtml; $widget.element.find('.' + $widget.options.classes.attributeClass + '[data-option-selected]').each(function () { var attributeId = $(this).data('attribute-id'); options[attributeId] = $(this).attr('data-option-selected'); }); newPrices = $widget.options.jsonConfig.optionPrices[_.findKey($widget.options.jsonConfig.index, options)]; $productPrice.trigger( 'updatePrice', { 'prices': $widget._getPrices(newPrices, $productPrice.priceBox('option').prices) } ); result = newPrices ? newPrices : $widget._getNewPrices(); $widget._updateSpecialPrice(result); if (typeof newPrices != 'undefined' && result.tierPrices.length) { if (this.options.tierPriceTemplate) { tierPriceHtml = mageTemplate( this.options.tierPriceTemplate, { 'tierPrices': result.tierPrices, '$t': $t, 'currencyFormat': this.options.jsonConfig.currencyFormat, 'priceUtils': priceUtils } ); $(this.options.tierPriceBlockSelector).html(tierPriceHtml).show(); } } else { $(this.options.tierPriceBlockSelector).hide(); } $(this.options.normalPriceLabelSelector).hide(); _.each($('.' + this.options.classes.attributeOptionsWrapper), function (attribute) { if ($(attribute).find('.' + this.options.classes.optionContainerClass + '.selected').length === 0) { if ($(attribute).find('.' + this.options.classes.selectClass).length > 0) { _.each($(attribute).find('.' + this.options.classes.selectClass), function (dropdown) { if ($(dropdown).val() === '0') { $(this.options.normalPriceLabelSelector).show(); } }.bind(this)); } else { $(this.options.normalPriceLabelSelector).show(); } } }.bind(this)); }, _updateSpecialPrice: function(result) { var $widget = this, $product = $widget.element.parents($widget.options.selectorProduct), $productSlyOldPriceSelector = $product.find(this.options.slyOldPriceSelector), $productSlyFinalPriceSelector = $product.find(this.options.slyFinalPriceSelector); if (result.oldPrice.amount !== result.finalPrice.amount) { $productSlyOldPriceSelector.show(); $productSlyFinalPriceSelector.addClass('price__value--special'); $productSlyFinalPriceSelector.removeClass('price__value--normal'); } else { $productSlyOldPriceSelector.hide(); $productSlyFinalPriceSelector.removeClass('price__value--special'); $productSlyFinalPriceSelector.addClass('price__value--normal'); } }, _EnableProductMediaLoader: function ($this) { var $widget = this; if ($('body.catalog-product-view').length > 0) { $this.parents('.column.main').find('.photo.image') .addClass($widget.options.classes.loader); } else { //Category View $this.parents('.product-item-details') .find('.lazyload-wrapper') .append('<div class="loader loader--visible"><div class="loader__circle"></div></div>'); } }, _DisableProductMediaLoader: function ($this) { var $widget = this; if ($('body.catalog-product-view').length > 0) { $this.parents('.column.main').find('.photo.image') .removeClass($widget.options.classes.loader); } else { //Category View $this.parents('.product-item-details').find('.loader').remove(); } } }); return $.mage.SwatchRenderer; } });
const { expect } = require('chai'); /** * @param {string} s * @param {string} t * @param {number} maxCost * @return {number} */ let equalSubstring = function(s, t, maxCost) { const costs = []; for (let i = 0; i < s.length; i++) costs.push(Math.abs(s[i].charCodeAt() - t[i].charCodeAt())); let result = 0; let pre, sum = 0; for (let i = 0; i < costs.length; i++) { const cost = costs[i]; if (cost > maxCost) { pre = undefined; sum = 0; continue; } sum += cost; if (sum <= maxCost) { if (pre === undefined) pre = i; result = Math.max(result, i - pre + 1); } else { while (sum > maxCost) { sum -= costs[pre]; pre++; } } } return result; }; it('get-equal-substrings-within-budget', () => { expect(equalSubstring('abcd', 'bcdf', 3)).to.eq(3); expect(equalSubstring('abcd', 'cdef', 3)).to.eq(1); expect(equalSubstring('krrgw', 'zjxss', 19)).to.eq(2); expect(equalSubstring('anryddgaqpjdw','zjhotgdlmadcf', 5)).to.eq(1); expect(equalSubstring('ujteygggjwxnfl', 'nstsenrzttikoy', 43)).to.eq(5); });
import React, { useState } from 'react' import styled from '@emotion/styled' import { FadeBottomAnimation } from './styles/styled' import Moment from 'react-moment' import { ThemeProvider } from 'emotion-theming' import theme from './textEditor/theme' import DraftRenderer from './textEditor/draftRenderer' import DanteContainer from './textEditor/editorStyles' import Loader from './loader' import { Trans, withTranslation } from 'react-i18next' import i18n from './i18n' const DanteContainerExtend = styled(DanteContainer)` margin-top: 1.2em; ` const Panel = styled.div` position: fixed; top: 0px; bottom: 0px; left: 0px; right: 0px; overflow: scroll; width: 100%; height: 100%; ` const ContentWrapper = styled.div` padding: 2em; ${(props) => FadeBottomAnimation(props)} ` const ArticleTitle = styled.h1` margin-bottom: .3em; margin-top: .3em; ` const CollectionLabel = styled.strong` border: 1px solid; padding: 5px; ` const ArticleMeta = styled.span` margin-bottom: 1em; ` const Article = () => { const domain = window.domain const [article, _setArticle] = useState(window.articleJson) const [loading, _setLoading] = useState(false) function renderDate () { return <Moment format="MMM Do, YYYY"> {article.updatedAt} </Moment> } return ( <Panel> { loading && <Loader sm /> } { article && <ContentWrapper > { article.collection && <CollectionLabel> {article.collection.title} </CollectionLabel> } <ArticleTitle> {article.title} </ArticleTitle> <ArticleMeta> <Trans i18nKey="article_meta" i18n={i18n} values={{ name: article.author.name }} components={[ renderDate() ]} /> </ArticleMeta> <ThemeProvider theme={ { ...theme, palette: { primary: '#121212', secondary: '#121212' } } }> <DanteContainerExtend> <DraftRenderer domain={domain} raw={article.serialized_content} /> </DanteContainerExtend> </ThemeProvider> </ContentWrapper> } </Panel> ) } const TranslatedArticle = withTranslation()(Article) export default TranslatedArticle
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends2 = require('babel-runtime/helpers/extends'); var _extends3 = _interopRequireDefault(_extends2); var _defineProperty2 = require('babel-runtime/helpers/defineProperty'); var _defineProperty3 = _interopRequireDefault(_defineProperty2); var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck'); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = require('babel-runtime/helpers/createClass'); var _createClass3 = _interopRequireDefault(_createClass2); var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn'); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = require('babel-runtime/helpers/inherits'); var _inherits3 = _interopRequireDefault(_inherits2); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _propTypes = require('prop-types'); var _propTypes2 = _interopRequireDefault(_propTypes); var _classnames = require('classnames'); var _classnames2 = _interopRequireDefault(_classnames); var _request = require('./request'); var _request2 = _interopRequireDefault(_request); var _uid = require('./uid'); var _uid2 = _interopRequireDefault(_uid); var _attrAccept = require('attr-accept'); var _attrAccept2 = _interopRequireDefault(_attrAccept); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /* eslint react/no-is-mounted:0 react/sort-comp:0 */ var AjaxUploader = function (_Component) { (0, _inherits3['default'])(AjaxUploader, _Component); function AjaxUploader() { var _ref; var _temp, _this, _ret; (0, _classCallCheck3['default'])(this, AjaxUploader); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = (0, _possibleConstructorReturn3['default'])(this, (_ref = AjaxUploader.__proto__ || Object.getPrototypeOf(AjaxUploader)).call.apply(_ref, [this].concat(args))), _this), _this.state = { uid: (0, _uid2['default'])() }, _this.reqs = {}, _this.onChange = function (e) { var files = e.target.files; _this.uploadFiles(files); _this.reset(); }, _this.onClick = function () { var el = _this.refs.file; if (!el) { return; } el.click(); }, _this.onKeyDown = function (e) { if (e.key === 'Enter') { _this.onClick(); } }, _this.onFileDrop = function (e) { if (e.type === 'dragover') { e.preventDefault(); return; } var files = Array.prototype.slice.call(e.dataTransfer.files).filter(function (file) { return (0, _attrAccept2['default'])(file, _this.props.accept); }); _this.uploadFiles(files); e.preventDefault(); }, _temp), (0, _possibleConstructorReturn3['default'])(_this, _ret); } (0, _createClass3['default'])(AjaxUploader, [{ key: 'componentDidMount', value: function componentDidMount() { this._isMounted = true; } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this._isMounted = false; this.abort(); } }, { key: 'uploadFiles', value: function uploadFiles(files) { var _this2 = this; var postFiles = Array.prototype.slice.call(files); postFiles.forEach(function (file) { file.uid = (0, _uid2['default'])(); _this2.upload(file, postFiles); }); } }, { key: 'upload', value: function upload(file, fileList) { var _this3 = this; var props = this.props; if (!props.beforeUpload) { // always async in case use react state to keep fileList return setTimeout(function () { return _this3.post(file); }, 0); } var before = props.beforeUpload(file, fileList); if (before && before.then) { before.then(function (processedFile) { var processedFileType = Object.prototype.toString.call(processedFile); if (processedFileType === '[object File]' || processedFileType === '[object Blob]') { _this3.post(processedFile); } else { _this3.post(file); } })['catch'](function (e) { console && console.log(e); // eslint-disable-line }); } else if (before !== false) { setTimeout(function () { return _this3.post(file); }, 0); } } }, { key: 'post', value: function post(file) { var _this4 = this; if (!this._isMounted) { return; } var props = this.props; var data = props.data; var onStart = props.onStart, onProgress = props.onProgress; if (typeof data === 'function') { data = data(file); } var uid = file.uid; var request = props.customRequest || _request2['default']; this.reqs[uid] = request({ action: props.action, filename: props.name, file: file, data: data, headers: props.headers, withCredentials: props.withCredentials, onProgress: onProgress ? function (e) { onProgress(e, file); } : null, onSuccess: function onSuccess(ret, xhr) { delete _this4.reqs[uid]; props.onSuccess(ret, file, xhr); }, onError: function onError(err, ret) { delete _this4.reqs[uid]; props.onError(err, ret, file); } }); onStart(file); } }, { key: 'reset', value: function reset() { this.setState({ uid: (0, _uid2['default'])() }); } }, { key: 'abort', value: function abort(file) { var reqs = this.reqs; if (file) { var uid = file; if (file && file.uid) { uid = file.uid; } if (reqs[uid]) { reqs[uid].abort(); delete reqs[uid]; } } else { Object.keys(reqs).forEach(function (uid) { if (reqs[uid]) { reqs[uid].abort(); } delete reqs[uid]; }); } } }, { key: 'render', value: function render() { var _classNames; var _props = this.props, Tag = _props.component, prefixCls = _props.prefixCls, className = _props.className, disabled = _props.disabled, style = _props.style, multiple = _props.multiple, accept = _props.accept, children = _props.children; var cls = (0, _classnames2['default'])((_classNames = {}, (0, _defineProperty3['default'])(_classNames, prefixCls, true), (0, _defineProperty3['default'])(_classNames, prefixCls + '-disabled', disabled), (0, _defineProperty3['default'])(_classNames, className, className), _classNames)); var events = disabled ? {} : { onClick: this.onClick, onKeyDown: this.onKeyDown, onDrop: this.onFileDrop, onDragOver: this.onFileDrop, tabIndex: '0' }; return _react2['default'].createElement( Tag, (0, _extends3['default'])({}, events, { className: cls, role: 'button', style: style }), _react2['default'].createElement('input', { type: 'file', ref: 'file', key: this.state.uid, style: { display: 'none' }, accept: accept, multiple: multiple, onChange: this.onChange }), children ); } }]); return AjaxUploader; }(_react.Component); AjaxUploader.propTypes = { component: _propTypes2['default'].string, style: _propTypes2['default'].object, prefixCls: _propTypes2['default'].string, className: _propTypes2['default'].string, multiple: _propTypes2['default'].bool, disabled: _propTypes2['default'].bool, accept: _propTypes2['default'].string, children: _propTypes2['default'].any, onStart: _propTypes2['default'].func, data: _propTypes2['default'].oneOfType([_propTypes2['default'].object, _propTypes2['default'].func]), headers: _propTypes2['default'].object, beforeUpload: _propTypes2['default'].func, customRequest: _propTypes2['default'].func, onProgress: _propTypes2['default'].func, withCredentials: _propTypes2['default'].bool }; exports['default'] = AjaxUploader; module.exports = exports['default'];
function radioChange() { if (document.getElementById("inSchoolRadio").checked) { document.querySelector(".inSchool").className = "inSchool"; document.querySelector(".outSchool").className = "outSchool hide"; } else { document.querySelector(".inSchool").className = "inSchool hide"; document.querySelector(".outSchool").className = "outSchool"; } } function selectDistrict() { var data = { bj: ["北京大学", "清华大学", "北京邮电大学"], sh: ["复旦大学", "上海交通大学", "同济大学"], hz: ["浙江大学", "杭州电子科技大学", "浙江工业大学"] } var source = document.getElementById("select1"); var target = document.getElementById("select2"); var selected = source.options[source.selectedIndex].value; target.innerHTML = ""; for (var i = 0; i < data[selected].length; i++) { var opt = document.createElement('option'); opt.value = data[selected][i]; opt.innerHTML = data[selected][i]; document.getElementById('select2').appendChild(opt); } }
version https://git-lfs.github.com/spec/v1 oid sha256:7ef74a68b4238c14e309e07a0461f8749e4abe44f2b58bb74ee9d60fd5458814 size 147687
import _jsx from "@babel/runtime/helpers/builtin/jsx"; import _objectWithoutProperties from "@babel/runtime/helpers/builtin/objectWithoutProperties"; import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { createStructuredSelector } from 'reselect'; import { MuiThemeProvider, createMuiTheme } from "@material-ui/core/es/styles"; import { I18nextProvider } from 'react-i18next'; import { resetPassword } from '../actions'; import ErrorArea from '../../containers/ErrorArea'; import PasswordResetPage from '../components/PasswordResetPage'; import PasswordResetSuccessPage from '../components/PasswordResetSuccessPage'; import theme from '../../theme'; var mapStateToProps = createStructuredSelector({ success: function success(state) { return state.passwordReset.success; } }); var mapDispatchToProps = { onSubmit: resetPassword }; var enhance = connect(mapStateToProps, mapDispatchToProps); var muiTheme = createMuiTheme(theme); var _ref2 = /*#__PURE__*/ _jsx(PasswordResetSuccessPage, {}); var _ref3 = /*#__PURE__*/ _jsx(ErrorArea, {}); var PasswordResetApp = function PasswordResetApp(_ref) { var locale = _ref.locale, success = _ref.success, props = _objectWithoutProperties(_ref, ["locale", "success"]); return _jsx(MuiThemeProvider, { theme: muiTheme }, void 0, _jsx(I18nextProvider, { i18n: locale }, void 0, _jsx("div", {}, void 0, success ? _ref2 : React.createElement(PasswordResetPage, props), _ref3))); }; PasswordResetApp.propTypes = process.env.NODE_ENV !== "production" ? { locale: PropTypes.object.isRequired, success: PropTypes.bool } : {}; export default enhance(PasswordResetApp); //# sourceMappingURL=PasswordResetApp.js.map
import s from './Legend.css'; import React, { PropTypes } from 'react'; class Legend extends React.Component { render() { return ( <div> <div><strong>Legend</strong></div> <div> <div className="col-sm-2"> <div className={s.percentageCohortFTrans}>0% &ge; diversity &lt; 10%</div> </div> <div className="col-sm-2"> <div className={s.percentageCohortETrans}>10% &ge; diversity &lt; 20%</div> </div> <div className="col-sm-2"> <div className={s.percentageCohortDTrans}>20% &ge; diversity &lt; 30%</div> </div> <div className="col-sm-2"> <div className={s.percentageCohortCTrans}>30% &ge; diversity &lt; 40%</div> </div> <div className="col-sm-2"> <div className={s.percentageCohortBTrans}>40% &ge; diversity &lt; 50%</div> </div> <div className="col-sm-2"> <div className={s.percentageCohortATrans}>&ge; 50% diversity &le; 100%</div> </div> </div> <hr></hr> </div> ); } } export default Legend;
/* 21. Implement the following: 1. Define a Shape constructor. Objects created with Shape should have a `type` property and a `getType` method. 2. Define a Triangle constructor. Objects created with Triangle should inherit from Shape and have three own properties: a, b and c representing the sides of a triangle. 3. Add a new method to the prototype called `getPerimeter`. Test your implementation with this code: var t = new Triangle(1, 2, 3); t.constructor; // Triangle(a, b, c) t instanceof Shape // true t.getPerimeter(); // 6 t.getType(); // "triangle" */ function Shape() { this.type = 'triangle' } Shape.prototype.getType = function() { return this.type; } function Triangle( a, b, c ) { this.a = a, this.b = b, this.c = c } Triangle.prototype = new Shape(); Triangle.prototype.constructor = Triangle; Triangle.prototype.getPerimeter = function() { return this.a + this.b + this.c; } var triangle = new Triangle( 1, 2, 3 ); console.log( triangle.constructor ); console.log( triangle instanceof Shape ); console.log( triangle.getPerimeter() ); console.log( triangle.getType() );
// var ngSanitize = require('angular-sanitize') var app = require('angular').module('app'); var template = require('./template'); // require('./style'); app.directive('xmallDynamicComponent', function ($compile) { return { restrict: 'E', scope: { props: '=props', class: '@' }, templateUrl: template, link: function ($scope, $el, attrs, controller) { var template = $scope.props.template; $scope.data = $scope.props.data; $el.append($compile(template)($scope)); } }; });
/** * Created by Téo on 11/04/2016. */ 'use strict'; controllers.controller('ModifyProfilCtrl',['$rootScope','$scope', '$location','ModifyProfilServ','ProfilServ','$cookies','$http', function($rootScope,$scope, $location,ModifyProfilServ,ProfilServ,$cookies,$http) { $scope.return = function() { $location.path('/profil'); }; ProfilServ.getProfil( function success(response) { $scope.id = response.id; $scope.name = response.name; $scope.firstName = response.firstName; $scope.pseudo = response.pseudo; }, function error(errorResponse) { if(errorResponse.status==401){ alert("Session interrompue"); console.log("Utilisateur non authentifié."); } console.log("Error:" + JSON.stringify(errorResponse)); $location.path('/'); } ); $scope.submit = function () { var userModification; if ($scope.password == null) { userModification = { id: $scope.id, name: $scope.name, firstName: $scope.firstName, avatar: "" }; } else { userModification = { id: $scope.id, name: $scope.name, firstName: $scope.firstName, avatar: "", password : $scope.password }; } var pseudo = $scope.pseudo; var password = $scope.password; ModifyProfilServ.modifyProfil(userModification, function success(response) { //alert($scope.challenge.question); console.log("Success:" + JSON.stringify(response)); if ($scope.password != null) { delete $http.defaults.headers.common['Authorization']; $http.defaults.headers.common['Authorization'] = "Basic " + btoa(pseudo + ":" + $scope.password); } $location.path('/profil'); }, function error(errorResponse) { console.log(errorResponse); if(errorResponse.status==401){ alert("Session interrompue"); console.log("Utilisateur non authentifié."); $location.path('/'); } else { $scope.errorMessage = "Erreur côté serveur."; console.log("Error:" + JSON.stringify(errorResponse)); $location.path('/'); } } ); }; }]);
const environment = { development: { isProduction: false }, production: { isProduction: true } }[process.env.NODE_ENV || 'development']; module.exports = Object.assign({ host: process.env.HOST || 'localhost', port: process.env.PORT, apiHost: process.env.APIHOST || 'localhost', apiPort: process.env.APIPORT, app: { title: 'React Redux Example', description: 'All the modern best practices in one example.', head: { titleTemplate: 'React Redux Example: %s', meta: [ {name: 'description', content: 'All the modern best practices in one example.'}, {charset: 'utf-8'}, {property: 'og:site_name', content: 'React Redux Example'}, {property: 'og:image', content: 'https://react-redux.herokuapp.com/logo.jpg'}, {property: 'og:locale', content: 'en_US'}, {property: 'og:title', content: 'React Redux Example'}, {property: 'og:description', content: 'All the modern best practices in one example.'}, {property: 'og:card', content: 'summary'}, {property: 'og:site', content: '@erikras'}, {property: 'og:creator', content: '@erikras'}, {property: 'og:image:width', content: '200'}, {property: 'og:image:height', content: '200'} ] } }, }, environment);
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. <<<<<<< HEAD <<<<<<< HEAD ======= >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 ======= >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 ;(function (factory) { var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; var root = (objectTypes[typeof window] && window) || this, freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, freeModule = objectTypes[typeof module] && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports && freeExports, freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } // Because of build optimizers if (typeof define === 'function' && define.amd) { define(['rx-lite-compat'], function (Rx, exports) { return factory(root, exports, Rx); }); } else if (typeof module === 'object' && module && module.exports === freeExports) { module.exports = factory(root, module.exports, require('rx-lite-compat')); } else { root.Rx = factory(root, {}, root.Rx); } }.call(this, function (root, exp, Rx, undefined) { <<<<<<< HEAD <<<<<<< HEAD ======= >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 ======= >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 // References var Observable = Rx.Observable, observableProto = Observable.prototype, observableNever = Observable.never, observableThrow = Observable.throwException, AnonymousObservable = Rx.AnonymousObservable, AnonymousObserver = Rx.AnonymousObserver, notificationCreateOnNext = Rx.Notification.createOnNext, notificationCreateOnError = Rx.Notification.createOnError, notificationCreateOnCompleted = Rx.Notification.createOnCompleted, Observer = Rx.Observer, Subject = Rx.Subject, internals = Rx.internals, helpers = Rx.helpers, ScheduledObserver = internals.ScheduledObserver, SerialDisposable = Rx.SerialDisposable, SingleAssignmentDisposable = Rx.SingleAssignmentDisposable, CompositeDisposable = Rx.CompositeDisposable, RefCountDisposable = Rx.RefCountDisposable, disposableEmpty = Rx.Disposable.empty, immediateScheduler = Rx.Scheduler.immediate, defaultKeySerializer = helpers.defaultKeySerializer, addRef = Rx.internals.addRef, identity = helpers.identity, isPromise = helpers.isPromise, inherits = internals.inherits, bindCallback = internals.bindCallback, noop = helpers.noop, isScheduler = Rx.Scheduler.isScheduler, observableFromPromise = Observable.fromPromise, ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError; <<<<<<< HEAD <<<<<<< HEAD ======= >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 ======= >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 function ScheduledDisposable(scheduler, disposable) { this.scheduler = scheduler; this.disposable = disposable; this.isDisposed = false; } function scheduleItem(s, self) { if (!self.isDisposed) { self.isDisposed = true; self.disposable.dispose(); } } ScheduledDisposable.prototype.dispose = function () { this.scheduler.scheduleWithState(this, scheduleItem); }; <<<<<<< HEAD <<<<<<< HEAD ======= >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 ======= >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 var CheckedObserver = (function (__super__) { inherits(CheckedObserver, __super__); function CheckedObserver(observer) { __super__.call(this); this._observer = observer; this._state = 0; // 0 - idle, 1 - busy, 2 - done } var CheckedObserverPrototype = CheckedObserver.prototype; CheckedObserverPrototype.onNext = function (value) { this.checkAccess(); var res = tryCatch(this._observer.onNext).call(this._observer, value); this._state = 0; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.onError = function (err) { this.checkAccess(); var res = tryCatch(this._observer.onError).call(this._observer, err); this._state = 2; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.onCompleted = function () { this.checkAccess(); var res = tryCatch(this._observer.onCompleted).call(this._observer); this._state = 2; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.checkAccess = function () { if (this._state === 1) { throw new Error('Re-entrancy detected'); } if (this._state === 2) { throw new Error('Observer completed'); } if (this._state === 0) { this._state = 1; } }; return CheckedObserver; }(Observer)); <<<<<<< HEAD <<<<<<< HEAD ======= >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 ======= >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 var ObserveOnObserver = (function (__super__) { inherits(ObserveOnObserver, __super__); function ObserveOnObserver(scheduler, observer, cancel) { __super__.call(this, scheduler, observer); this._cancel = cancel; } ObserveOnObserver.prototype.next = function (value) { __super__.prototype.next.call(this, value); this.ensureActive(); }; ObserveOnObserver.prototype.error = function (e) { __super__.prototype.error.call(this, e); this.ensureActive(); }; ObserveOnObserver.prototype.completed = function () { __super__.prototype.completed.call(this); this.ensureActive(); }; ObserveOnObserver.prototype.dispose = function () { __super__.prototype.dispose.call(this); this._cancel && this._cancel.dispose(); this._cancel = null; }; return ObserveOnObserver; })(ScheduledObserver); <<<<<<< HEAD <<<<<<< HEAD ======= >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 ======= >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 /** * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. * If a violation is detected, an Error is thrown from the offending observer method call. * * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. */ Observer.prototype.checked = function () { return new CheckedObserver(this); }; /** * Schedules the invocation of observer methods on the given scheduler. * @param {Scheduler} scheduler Scheduler to schedule observer messages on. * @returns {Observer} Observer whose messages are scheduled on the given scheduler. */ Observer.notifyOn = function (scheduler) { return new ObserveOnObserver(scheduler, this); }; /** * Creates an observer from a notification callback. * @param {Function} handler Action that handles a notification. * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. */ Observer.fromNotifier = function (handler, thisArg) { var handlerFunc = bindCallback(handler, thisArg, 1); return new AnonymousObserver(function (x) { return handlerFunc(notificationCreateOnNext(x)); }, function (e) { return handlerFunc(notificationCreateOnError(e)); }, function () { return handlerFunc(notificationCreateOnCompleted()); }); }; /** * Creates a notification callback from an observer. * @returns The action that forwards its input notification to the underlying observer. */ Observer.prototype.toNotifier = function () { var observer = this; return function (n) { return n.accept(observer); }; }; /** * Hides the identity of an observer. * @returns An observer that hides the identity of the specified observer. */ Observer.prototype.asObserver = function () { var source = this; return new AnonymousObserver( function (x) { source.onNext(x); }, function (e) { source.onError(e); }, function () { source.onCompleted(); } ); }; <<<<<<< HEAD <<<<<<< HEAD ======= >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 ======= >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 /** * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. * * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects * that require to be run on a scheduler, use subscribeOn. * * @param {Scheduler} scheduler Scheduler to notify observers on. * @returns {Observable} The source sequence whose observations happen on the specified scheduler. */ observableProto.observeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(new ObserveOnObserver(scheduler, observer)); }, source); }; <<<<<<< HEAD <<<<<<< HEAD ======= >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 ======= >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 /** * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; * see the remarks section for more information on the distinction between subscribeOn and observeOn. * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer * callbacks on a scheduler, use observeOn. * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); d.setDisposable(m); m.setDisposable(scheduler.schedule(function () { d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); })); return d; }, source); }; <<<<<<< HEAD <<<<<<< HEAD ======= >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 ======= >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 /** * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. * @returns {Observable} The generated sequence. */ Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (o) { var first = true; return scheduler.scheduleRecursiveWithState(initialState, function (state, self) { var hasResult, result; try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); hasResult && (result = resultSelector(state)); } catch (e) { return o.onError(e); } if (hasResult) { o.onNext(result); self(state); } else { o.onCompleted(); } }); }); }; <<<<<<< HEAD <<<<<<< HEAD ======= >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 ======= >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 /** * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. * @param {Function} resourceFactory Factory function to obtain a resource object. * @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource. * @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object. */ Observable.using = function (resourceFactory, observableFactory) { return new AnonymousObservable(function (observer) { var disposable = disposableEmpty, resource, source; try { resource = resourceFactory(); resource && (disposable = resource); source = observableFactory(resource); } catch (exception) { return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable); } return new CompositeDisposable(source.subscribe(observer), disposable); }); }; <<<<<<< HEAD <<<<<<< HEAD ======= >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 ======= >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 /** * Propagates the observable sequence or Promise that reacts first. * @param {Observable} rightSource Second observable sequence or Promise. * @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first. */ observableProto.amb = function (rightSource) { var leftSource = this; return new AnonymousObservable(function (observer) { var choice, leftChoice = 'L', rightChoice = 'R', leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(rightSource) && (rightSource = observableFromPromise(rightSource)); function choiceL() { if (!choice) { choice = leftChoice; rightSubscription.dispose(); } } function choiceR() { if (!choice) { choice = rightChoice; leftSubscription.dispose(); } } leftSubscription.setDisposable(leftSource.subscribe(function (left) { choiceL(); if (choice === leftChoice) { observer.onNext(left); } }, function (err) { choiceL(); if (choice === leftChoice) { observer.onError(err); } }, function () { choiceL(); if (choice === leftChoice) { observer.onCompleted(); } })); rightSubscription.setDisposable(rightSource.subscribe(function (right) { choiceR(); if (choice === rightChoice) { observer.onNext(right); } }, function (err) { choiceR(); if (choice === rightChoice) { observer.onError(err); } }, function () { choiceR(); if (choice === rightChoice) { observer.onCompleted(); } })); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; <<<<<<< HEAD <<<<<<< HEAD ======= >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 ======= >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 /** * Propagates the observable sequence or Promise that reacts first. * * @example * var = Rx.Observable.amb(xs, ys, zs); * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first. */ Observable.amb = function () { var acc = observableNever(), items = []; if (Array.isArray(arguments[0])) { items = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); } } function func(previous, current) { return previous.amb(current); } for (var i = 0, len = items.length; i < len; i++) { acc = func(acc, items[i]); } return acc; }; <<<<<<< HEAD <<<<<<< HEAD ======= >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 ======= >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. */ observableProto.onErrorResumeNext = function (second) { if (!second) { throw new Error('Second observable is required'); } return onErrorResumeNext([this, second]); }; <<<<<<< HEAD <<<<<<< HEAD ======= >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 ======= >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. */ var onErrorResumeNext = Observable.onErrorResumeNext = function () { var sources = []; if (Array.isArray(arguments[0])) { sources = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { sources.push(arguments[i]); } } return new AnonymousObservable(function (observer) { var pos = 0, subscription = new SerialDisposable(), cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, d; if (pos < sources.length) { current = sources[pos++]; isPromise(current) && (current = observableFromPromise(current)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe(observer.onNext.bind(observer), self, self)); } else { observer.onCompleted(); } }); return new CompositeDisposable(subscription, cancelable); }); }; <<<<<<< HEAD <<<<<<< HEAD ======= >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 ======= >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 /** * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. * * @example * var res = xs.bufferWithCount(10); * var res = xs.bufferWithCount(10, 1); * @param {Number} count Length of each buffer. * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithCount = function (count, skip) { if (typeof skip !== 'number') { skip = count; } return this.windowWithCount(count, skip).selectMany(function (x) { return x.toArray(); }).where(function (x) { return x.length > 0; }); }; <<<<<<< HEAD <<<<<<< HEAD ======= >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 ======= >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 /** * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. * * var res = xs.windowWithCount(10); * var res = xs.windowWithCount(10, 1); * @param {Number} count Length of each window. * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithCount = function (count, skip) { var source = this; +count || (count = 0); Math.abs(count) === Infinity && (count = 0); if (count <= 0) { throw new ArgumentOutOfRangeError(); } skip == null && (skip = count); +skip || (skip = 0); Math.abs(skip) === Infinity && (skip = 0); if (skip <= 0) { throw new ArgumentOutOfRangeError(); } return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), refCountDisposable = new RefCountDisposable(m), n = 0, q = []; function createWindow () { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); } createWindow(); m.setDisposable(source.subscribe( function (x) { for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } var c = n - count + 1; c >= 0 && c % skip === 0 && q.shift().onCompleted(); ++n % skip === 0 && createWindow(); }, function (e) { while (q.length > 0) { q.shift().onError(e); } observer.onError(e); }, function () { while (q.length > 0) { q.shift().onCompleted(); } observer.onCompleted(); } )); return refCountDisposable; }, source); }; <<<<<<< HEAD <<<<<<< HEAD ======= >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 ======= >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 /** * Returns an array with the specified number of contiguous elements from the end of an observable sequence. * * @description * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the * source sequence, this buffer is produced on the result sequence. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. */ observableProto.takeLastBuffer = function (count) { var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, function (e) { o.onError(e); }, function () { o.onNext(q); o.onCompleted(); }); }, source); }; <<<<<<< HEAD <<<<<<< HEAD ======= >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 ======= >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 /** * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. * * var res = obs = xs.defaultIfEmpty(); * 2 - obs = xs.defaultIfEmpty(false); * * @memberOf Observable# * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. */ observableProto.defaultIfEmpty = function (defaultValue) { var source = this; defaultValue === undefined && (defaultValue = null); return new AnonymousObservable(function (observer) { var found = false; return source.subscribe(function (x) { found = true; observer.onNext(x); }, function (e) { observer.onError(e); }, function () { !found && observer.onNext(defaultValue); observer.onCompleted(); }); }, source); }; <<<<<<< HEAD <<<<<<< HEAD ======= >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 ======= >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 // Swap out for Array.findIndex function arrayIndexOfComparer(array, item, comparer) { for (var i = 0, len = array.length; i < len; i++) { if (comparer(array[i], item)) { return i; } } return -1; } function HashSet(comparer) { this.comparer = comparer; this.set = []; } HashSet.prototype.push = function(value) { var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1; retValue && this.set.push(value); return retValue; }; /** * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. * * @example * var res = obs = xs.distinct(); * 2 - obs = xs.distinct(function (x) { return x.id; }); * 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; }); * @param {Function} [keySelector] A function to compute the comparison key for each element. * @param {Function} [comparer] Used to compare items in the collection. * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. */ observableProto.distinct = function (keySelector, comparer) { var source = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (o) { var hashSet = new HashSet(comparer); return source.subscribe(function (x) { var key = x; if (keySelector) { try { key = keySelector(x); } catch (e) { o.onError(e); return; } } hashSet.push(key) && o.onNext(x); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; <<<<<<< HEAD <<<<<<< HEAD ======= >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 ======= >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 return Rx; }));
$(document).ready(function () { /* init jquery validation */ $('form').validate({ errorPlacement: function(label, element) { label.addClass('inline text-error'); label.insertAfter(element); }, wrapper: 'span' }); $( "#vtype_passengers" ).rules( "add", { required: true, digits: true, min: 1, max: 60 }); $('.name-part').change(function () { var vtype = $('#vtype_type').val(); var count = $('#vtype_passengers').val(); $('#display_name').prop('value', count + '-passenger ' + vtype); var display_name = $('#display_name').val(); $('#vtype_name').val(display_name); }); });
pmb_im.services.factory('locationAPI', ['$http', '$q', 'ApiImEndpoint', 'ApiDataEndpoint', function($http, $q, ApiImEndpoint, ApiDataEndpoint) { var restPreffix = "ubicacionesRestProd"; var locationAPI = {}; locationAPI.searchLocationByStr = function(_location) { return $http.get(ApiImEndpoint.url + '/' + restPreffix + '/calles', { method: 'GET', params: { nombre: _location } }); }; locationAPI.searchEsquinaByStr = function(_location) { //console.log("searchEsquinaByStr = " + JSON.stringify(_location)); //return $http.get(ApiImEndpoint.url + '/' + restPreffix + '/esquina/' + _location.calle + '/' + _location.esquina, { return $http.get(ApiImEndpoint.url + '/' + restPreffix + '/cruces/' + _location.calle + '/', { params: { nombre: _location.esquina } }); }; locationAPI.getLocationGeom = function(_location) { var url = ApiImEndpoint.url + '/' + restPreffix + locationAPI.getParamPathByTipo(_location.tipo); for (var i = 0; i < _location.pathParams.length; i++) { url += '/' + _location.pathParams[i]; } return $http.get(url).then(function(response){ return response.data; }); }; locationAPI.getParamPathByTipo = function(_tipo) { var restGeoDataServicePath = { 'ESQUINA':"/esquina", 'DIRECCION':"/direccion" }; return restGeoDataServicePath[_tipo]; }; return locationAPI; }]);
console.info('>>> cercal.io'); console.info('>>> What are you looking for? :D'); console.info('>>> If you want, you can send us a message using our social network profiles.');
angular.module('food-coop').controller('contactCtrl', function($mdToast, $reactive, $scope) { $reactive(this).attach($scope) var vm = this; vm.disabled = false; vm.content = {} vm.send = function () { vm.disabled = true; vm.call('/email/contactForm', vm.content, function (err, result) { vm.disabled = false; if (err) { vm.error = err.message return $mdToast.show( $mdToast.simple().content(err.message).position('bottom right').hideDelay(4000) ); } return $mdToast.show( $mdToast.simple().content("Poof! Message sent thank you.").position('bottom right').hideDelay(4000) ); }); }; ; })
var http = require('http'), path = require('path'), fs = require('fs'), swig = require('swig'), socket = require('socket.io'), deleteKey = require('key-del'); gu = require('./gameutils.js'); var domain = 'localhost:8080'; // change this var room, ongoing = {}; // function defs function randomString(length) { chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; var result = ''; for (var i = length; i > 0; --i) result += chars[Math.round(Math.random() * (chars.length - 1))]; return result; } // route var server = http.createServer(function(req, res) { var content = '', fileName = path.basename(req.url), pathName = path.dirname(req.url), localFolder = __dirname; // serve static files if (path.dirname(pathName) == '/static') { content = localFolder + req.url; fs.readFile(content, function(err, contents) { if(!err) { // write proper header if (path.basename(pathName) == 'css') res.writeHead(200, {'Content-Type': 'text/css'}); else if (path.basename(pathName) == 'js') res.writeHead(200, {'Content-Type': 'text/javascript'}); // write contents res.end(contents); } else { console.dir(err); } }); } else if (fileName == 'favicon.ico') { } else if (fileName == '' && pathName == '/'){ // serve intro page res.writeHead(200, {'Content-Type': 'text/html'}); tpl = swig.compileFile('templates/index.html'); res.write(tpl({ 'quickroom': randomString(6), 'rooms': Object.keys(ongoing), 'domain': domain })); res.end(); } else if (pathName == '/') { // serve board page room = fileName; // temporary res.writeHead(200, {'Content-Type': 'text/html'}); tpl = swig.compileFile('templates/gameboard.html'); res.write(tpl()); res.end(); } else { res.writeHead(404, {'Content-Type': 'text/html'}); res.write(':('); res.end(); } }); // sockets var io = socket.listen(server); io.sockets.on('connection', function(client) { // connect to room client.room = room; client.join(client.room); // initialize game client_list = io.sockets.adapter.rooms[client.room]; client_list_length = Object.keys(client_list).length; // initialize room if (!(client.room in ongoing)) { ongoing[client.room] = {}; ongoing[client.room]['player1'] = client.id; ongoing[client.room]['player2'] = false; ongoing[client.room]['spectators'] = 0; ongoing[client.room]['nextMove'] = 1; ongoing[client.room]['board'] = JSON.parse(JSON.stringify(gu.emptyBoard)); // feels dirty client.pn = 1; console.log('[NEW] room: ' + client.room + ' | player1: ' + ongoing[client.room]['player1'] + ' | player2: ' + ongoing[room]['player2']); //FIXME logging } else if (!ongoing[client.room]['player1']) { ongoing[room]['player1'] = client.id; client.pn = 1; } else if (!ongoing[client.room]['player2']) { ongoing[room]['player2'] = client.id; client.pn = 2; } else { ongoing[room]['spectators'] += 1; client.pn = 3; } // send connection data client.emit('new-connect', {'pn': client.pn , 'board': ongoing[client.room]['board'], 'nextPlayer': ongoing[client.room]['nextMove'] }); // display message to opponent if (client.pn < 3) { client.broadcast.to(client.room).emit( 'display-message', {'to': [1, 2], 'message': 'Opponnent connected.'} ); client.broadcast.to(client.room).emit( 'display-message', {'to': [3], 'message': 'Player ' + client.pn + ' connected.'} ); } else { client.broadcast.to(client.room).emit( 'display-message', {'to': [1, 2, 3], 'message': 'Spectator connected.'} ); } console.log('[CON] room: ' + client.room + ' | pn: ' + client.pn + ' | id: ' + client.id); //FIXME logging // on disconnect client.on('disconnect', function(data) { console.log('[DCN] room: ' + client.room + ' | pn: ' + client.pn + ' | id: ' + client.id); //FIXME logging // log player disconnect if (client.pn == 1) { ongoing[client.room]['player1'] = false; } else if (client.pn == 2) { ongoing[client.room]['player2'] = false; } else { ongoing[client.room]['spectators'] -= 1; } // destroy room if nobody left if (!ongoing[client.room]['player1'] && !ongoing[client.room]['player2'] && !ongoing[client.room]['spectators']) { console.log('[DEL] room: ' + client.room + ' | player1: ' + ongoing[client.room]['player1'] + ' | player2: ' + ongoing[client.room]['player2'] + ' | spectators: ' + ongoing[client.room]['spectators']); //FIXME logging ongoing = deleteKey(ongoing, [client.room]); } if (client.pn < 3) { client.broadcast.to(client.room).emit( 'display-message', {'to': [1, 2], 'message': 'Opponnent disconnected.'} ); client.broadcast.to(client.room).emit( 'display-message', {'to': [3], 'message': 'Player ' + client.pn + ' disconnected.'} ); } else { client.broadcast.to(client.room).emit( 'display-message', {'to': [1, 2, 3], 'message': 'Spectator disconnected.'} ); } }); // sending moves client.on('send-move', function(data) { // validate move if (client.pn == ongoing[client.room]['nextMove'] && ongoing[client.room]['board'][data['outer']][data['inner']] != 'e') return; if (ongoing[client.room]['nextMove'] == 0) return; ongoing[client.room]['nextMove'] = (ongoing[client.room]['nextMove'] == 1) ? 2 : 1; // update board ongoing[client.room]['board'][data['outer']][data['inner']] = data['player']['symbol']; gu.disableAll(ongoing[client.room]['board']); // check for captures if (gu.isCaptured(ongoing[client.room]['board'], data['outer'])) { for (inner = 0; inner < 9; inner++) ongoing[client.room]['board'][data['outer']][inner] = client.pn; if (gu.isWon(ongoing[client.room]['board'])) { io.in(client.room).emit('game-over', {'winner': client.pn}); ongoing[client.room]['nextMove'] = 0; console.log('[WIN] room: ' + client.room + ' | player: ' + client.pn); //FIXME logging } else if (gu.isTie(ongoing[client.room]['board'])) { io.in(client.room).emit('game-over', {'winner': 0}); ongoing[client.room]['nextMove'] = 0; console.log('[TIE] room: ' + client.room); //FIXME logging } } // enable moves if (ongoing[client.room]['board'][data['inner']][0] == '1' || ongoing[client.room]['board'][data['inner']][0] == '2' || gu.isFull(ongoing[client.room]['board'], data['inner'])) { gu.enableAll(ongoing[client.room]['board']); } else { gu.enableBlock(ongoing[client.room]['board'], data['inner']); } // send move data['nextPlayer'] = ongoing[client.room]['nextMove']; data['board'] = JSON.parse(JSON.stringify(ongoing[client.room]['board'])); client.broadcast.to(client.room).emit('push-move', data); }); }); server.listen(8080);
define([ 'jquery', 'underscore', 'backbone', 'jqueryui', 'jqueryuiwidget', 'jtable' ], function($, _, Backbone){ var VotingsTableView = Backbone.View.extend({ el: $("#votings-table"), render: function(){ $('#votings-table').jtable({ title: 'The Votings List', paging: true, //Enable paging pageSize: 10, //Set page size (default: 10) sorting: true, //Enable sorting defaultSorting: 'Name ASC', //Set default sorting actions: { listAction: '/Demo/StudentList', deleteAction: '/Demo/DeleteStudent', updateAction: '/Demo/UpdateStudent', createAction: 'http://192.168.1.101:7777/VotingService.aspx/AddVoting' }, fields: { id: { title: 'Id', key: true, create: false, edit: false, list: true }, name: { title: 'Name', width: '80%' }, userId: { title: 'UserId' }, sessionId: { title: 'SessionId' } } }); //Load student list from server $('#votings-table').jtable('load'); } }); return VotingsTableView; });
var path = require("path"); module.exports = { entry: "./index.imba", output: { path: path.resolve(__dirname), filename: './index.js', publicPath: "/assets/" } };
import Ember from 'ember'; export default Ember.Route.extend({ seq: null, model: function(params) { this.set("seq", params.seq); }, actions: { didTransition: function() { this.replaceWith("seq.wordset.index", "en", this.get("seq")); } } });
define(["../core"],function(jQuery){return jQuery.swap=function(elem,options,callback,args){var ret,name,old={};for(name in options)old[name]=elem.style[name],elem.style[name]=options[name];ret=callback.apply(elem,args||[]);for(name in options)elem.style[name]=old[name];return ret},jQuery.swap});
export default function conditionalArray (valueToCompare, arrayToCompareWith, operator, type) { let isAllow type = type || 'or' operator = operator || '===' arrayToCompareWith.forEach((v, index) => { if (index === 0) { isAllow = operatorTextToCondition(v, operator, valueToCompare) } else { if (type === 'and') { isAllow && operatorTextToCondition(v, operator, valueToCompare) } else { isAllow || operatorTextToCondition(v, operator, valueToCompare) } } }) return isAllow } /*eslint-disable */ function operatorTextToCondition (value1, operator, value2) { let output switch (operator) { case '==': output = value1 == value2 break case '===': output = value1 === value2 break case '!=': output = value1 != value2 break case '!==': output = value1 !== value2 break case '>': output = value1 > value2 break case '>=': output = value1 >= value2 break case '<': output = value1 < value2 break case '<=': output = value1 <= value2 break default: console.log('Err : \'' + operator + '\' This operator doesn\'t exist !') break } return output }
import gulp from 'gulp'; import del from 'del'; import config from '../config'; gulp.task('clean-release', () => { return del.sync([config.common.releaseDir]); });
this.NesDb = this.NesDb || {}; NesDb[ '445EF49C918183F17EEF3D80C6FAF6E0CA8AC19E' ] = { "$": { "name": "Choujin: Ultra Baseball", "altname": "超人ウルトラベースボール", "class": "Licensed", "catalog": "CBF-UB", "publisher": "Culture Brain", "developer": "Culture Brain", "region": "Japan", "players": "2", "date": "1989-10-27" }, "cartridge": [ { "$": { "system": "Famicom", "crc": "078CED30", "sha1": "445EF49C918183F17EEF3D80C6FAF6E0CA8AC19E", "dump": "ok", "dumper": "bootgod", "datedumped": "2007-04-28" }, "board": [ { "$": { "type": "HVC-SKROM", "pcb": "HVC-SKROM-05", "mapper": "1" }, "prg": [ { "$": { "name": "CBF-UB-0 PRG", "size": "128k", "crc": "BD2269AD", "sha1": "F1EB3DE1770A3BAC47BBBBCC88F037B4B6587DD1" } } ], "chr": [ { "$": { "name": "CBF-UB-0 CHR", "size": "128k", "crc": "F6B3F87C", "sha1": "32D00480A29EEBA2DB4E3AE7F1F0B7492A133947" } } ], "wram": [ { "$": { "size": "8k", "battery": "1" } } ], "chip": [ { "$": { "type": "MMC1B2" } } ] } ] } ] };
"use strict"; namespace('Zen'); /** * Zen.Tabs is a Mootools class for rendering tab based navigation menus. Tabs * managed by this class can be activated by both clicking on the various tabs * or by changing the URL hash (clicking a tab actually does the latter). * * The use of URL hashes (stored in ``window.location.hash``) also make it * possible for non default tabs to be set as the active tab whenever a page is * reloaded. If no URL hash is set then a CSS selector will be used to * determine the default tab field to activate. If there is a URL hash present * that will be used instead. * * For example, take the following URL: * * * http://hello.com/admin/extensions/ * * and the following tab fields (where each item is the ID of the field): * * * packages * * themes * * languages * * These fields could be activated by navigating to one of the following URLs * (or just by clicking the corresponding tab which will then do this for you): * * * http://hello.com/admin/extensions#packages * * http://hello.com/admin/extensions#themes * * http://hello.com/admin/extensions#languages * * ## General Usage * * Using this class is pretty straight forward, just create a new instance of it * and pass a CSS selector to the constructor: * * new Zen.Tabs('.tabs ul'); * * If you want to change any options you can set these as the second parameter: * * new Zen.Tabs('.tabs ul', {'default': 'li:last-child'}); * * ## Options * * * default: a CSS selector that should result in a ``<li>`` element to * activate by default if no ID is specified in the URL hash. */ Zen.Tabs = new Class( { Implements: Options, /** * Object containing all options for each tab instance. * * @since 0.1 */ options: { // The default tab/field to display 'default': 'li:first-child', }, /** * Contains the element that contains all the tab items. * * @since 0.1 */ element: null, /** * Constructor method called upon initialization. Options can be * set as a JSON object in the first argument. * * @since 0.1 * @param {string} selector A CSS selector that should result in a ``<ul>`` * element containing various tabs. * @param {object} options Custom options used when creating the tabs */ initialize: function(selector, options) { this.setOptions(options); var found = $$(selector); if ( found.length <= 0 ) { throw new Error( 'No elements could be found for the selector ' + selector ); } this.element = found[0]; this.displayDefault(); this.addEvents(); }, /** * Binds various events to show the right tab fields when a tab is clicked * or when the URL hash is changed. * * @since 2011-12-21 */ addEvents: function() { var _this = this; // Only bind the event if the browser doesn't support the onhashchange // event. if ( !"onhashchange" in window ) { this.element.getElements('a').addEvent('click', function(e) { e.stop(); window.location.hash = this.get('href'); window.fireEvent('hashchange'); }); } window.addEvent('hashchange', function() { var id = new Zen.Hash(window.location.hash).segments[0]; if ( id && $(id) ) { _this.toggleTab(id); } }); }, /** * Determines the default tab field to display based on the option * ``this.options.default`` or the current hash URL. * * @since 2011-12-21 */ displayDefault: function() { var id = null; // Don't bother parsing the URL hash if there is none to begin with. if ( window.location.hash && window.location.hash.length > 0 ) { id = new Zen.Hash(window.location.hash).segments[0]; } if ( !id || id.length <= 0 ) { var active = this.element.getElements(this.options['default']); if ( active.length > 0 ) { active[0].addClass('active'); id = active[0].getElement('a').get('href').replace(/^#/, ''); } } this.toggleTab(id); }, /** * Activates the tab field for the given ID. * * @since 2011-12-21 * @param {string} id The ID of the tab field to show. */ toggleTab: function(id) { this.element.getElements('a').each(function(el) { var el_id = el.get('href').replace(/^#/, ''); if ( el_id === id ) { el.getParent().addClass('active'); var found = $(id); if ( found ) found.show(); } else { el.getParent().removeClass('active'); var found = $(el_id); if ( found ) found.hide(); } }); }, });
import Component from 'ember-component' import computed from 'ember-computed-decorators' /** * User alias component * * Show 'Anonymous' and on click a popover containing * the users identifier * * @class UserAliasComponent * @extends Ember.Component * @public */ const UserAliasComponent = Component.extend({ /** * HTML tag name of the component * * @property {String} tagName * @default 'span' * @public */ tagName: 'span', /** * Bind title to property * * @property {String[]} attributeBindings * @public */ attributeBindings: [ 'title' ], /** * The title of the component * * @property {String} title * @public */ @computed('popoverVisible') title(visible) { let verb = visible ? 'hide' : 'show' return `Click to ${verb} users identifier` }, /** * The user to alias * * @property {User} user * @default null * @public */ user: null, /** * Is the popover visible? * * @property {Boolean} popoverVisible * @default false * @public */ popoverVisible: false, /** * Toggle popover on click * * @event click * @param {jQuery.Event} e The event * @return {void} * @public */ click(e) { this.toggleProperty('popoverVisible') }, /** * Hide popover on mouse enter * * @event mouseLeave * @param {jQuery.Event} e The event * @return {void} * @public */ mouseLeave(e) { this.set('popoverVisible', false) } }) UserAliasComponent.reopenClass({ positionalParams: [ 'user' ] }) export default UserAliasComponent
var searchData= [ ['executecommand',['executeCommand',['../class_ts3_api_1_1_server.html#a3ea16dc4a1a611c444c17b0be04d4f45',1,'Ts3Api::Server']]] ];
'use strict'; angular.module('suitApp.parts') .factory('ContatosComponenteService', [function(){ var self = this; self.contatosComponentes = [ {id:'0',description:'01'}, {id:'1',description:'10'}, {id:'2',description:'11'}, {id:'3',description:'02'}, {id:'4',description:'20'}, {id:'5',description:'22'}, {id:'6',description:'21'}, {id:'7',description:'12'}, {id:'8',description:'31'}, {id:'9',description:'13'}, {id:'A',description:'IN1220'}, {id:'B',description:'IN2220'}, {id:'C',description:'IN3220'}, {id:'D',description:'IN4220'}, {id:'E',description:'RS1220'}, {id:'F',description:'RS2220'}, {id:'G',description:'RS3220'}, {id:'H',description:'RC1320'}, {id:'I',description:'RC2320'}, {id:'J',description:'RC3320'}, {id:'K',description:'RIE1320'}, {id:'L',description:'RIE2320'}, {id:'M',description:'SS1320'}, {id:'N',description:'SS2320'}, {id:'O',description:'SS1420'}, {id:'P',description:'RS1220'}, {id:'Q',description:'SS1520'}, {id:'R',description:'RP1320'}, {id:'S',description:'RP2320'}, {id:'T',description:'SC1320'}, {id:'U',description:'SC2320'}, {id:'V',description:'SC1420'}, {id:'W',description:'SC1620'}, {id:'Y',description:'IN3232'}, {id:'Z',description:'IN4232'}, ]; self.contatoComponente = {}; return { list: function() { return self.contatosComponentes; }, set: function(contatoComponente) { self.contatoComponente = contatoComponente; }, get: function() { return self.contatoComponente; } }; }]);
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "PG", "PTG" ], "DAY": [ "Ahad", "Isnin", "Selasa", "Rabu", "Khamis", "Jumaat", "Sabtu" ], "ERANAMES": [ "S.M.", "TM" ], "ERAS": [ "S.M.", "TM" ], "FIRSTDAYOFWEEK": 0, "MONTH": [ "Januari", "Februari", "Mac", "April", "Mei", "Jun", "Julai", "Ogos", "September", "Oktober", "November", "Disember" ], "SHORTDAY": [ "Ahd", "Isn", "Sel", "Rab", "Kha", "Jum", "Sab" ], "SHORTMONTH": [ "Jan", "Feb", "Mac", "Apr", "Mei", "Jun", "Jul", "Ogo", "Sep", "Okt", "Nov", "Dis" ], "WEEKENDRANGE": [ 5, 6 ], "fullDate": "dd MMMM y", "longDate": "d MMMM y", "medium": "d MMM y h:mm:ss a", "mediumDate": "d MMM y", "mediumTime": "h:mm:ss a", "short": "d/MM/yy h:mm a", "shortDate": "d/MM/yy", "shortTime": "h:mm a" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "$", "DECIMAL_SEP": ",", "GROUP_SEP": ".", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "\u00a4\u00a0-", "negSuf": "", "posPre": "\u00a4\u00a0", "posSuf": "" } ] }, "id": "ms-latn-bn", "pluralCat": function(n, opt_precision) { return PLURAL_CATEGORY.OTHER;} }); }]);
'use strict' const TrailsApp = require('trails') before(() => { global.app = new TrailsApp(require('../')) return global.app.start() }) after(() => { return global.app.stop() })
(function() { L.Control.PanelLayers = L.Control.Layers.extend({ options: { button: false, collapsed: false, autoZIndex: true, position: 'topright', collapsibleGroups: false, buildItem: null //function that return row item html node(or html string) }, initialize: function (baseLayers, overlays, options) { L.setOptions(this, options); this._layers = {}; this._groups = {}; this._items = {}; this._layersActives = []; this._lastZIndex = 0; this._handlingClick = false; var i, n; for (i in baseLayers) { if (baseLayers[i].group && baseLayers[i].layers) for(n in baseLayers[i].layers) { this._addLayer(baseLayers[i].layers[n], false, baseLayers[i].group); } else this._addLayer(baseLayers[i], false); } for (i in overlays) { if(overlays[i].group && overlays[i].layers) for(n in overlays[i].layers) this._addLayer(overlays[i].layers[n], true, overlays[i].group); else this._addLayer(overlays[i], true); } }, onAdd: function (map) { for(var i in this._layersActives) { map.addLayer(this._layersActives[i]); } L.Control.Layers.prototype.onAdd.call(this, map); return this._container; }, //TODO addBaseLayerGroup //TODO addOverlayGroup addBaseLayer: function (layer, name, group) { layer.name = name || layer.name || ''; this._addLayer(layer, false, group); this._update(); return this; }, addOverlay: function (layer, name, group) { layer.name = name || layer.name || ''; this._addLayer(layer, true, group); this._update(); return this; }, removeLayer: function (layerDef) { var layer = layerDef.hasOwnProperty('layer') ? this._layerFromDef(layerDef) : layerDef; this._map.removeLayer(layer); L.Control.Layers.prototype.removeLayer.call(this, layer); return this; }, clearLayers: function() { for (var id in this._layers) { this.removeLayer( this._layers[id] ); } }, _layerFromDef: function(layerDef) { for (var id in this._layers) { //TODO add more conditions to comaparing definitions if(this._layers[id].name === layerDef.name) return this._layers[id].layer; } }, _update: function() { this._groups = {}; this._items = {}; L.Control.Layers.prototype._update.call(this); }, _instantiateLayer: function(layerDef) { if(layerDef instanceof L.Class) return layerDef; else if(layerDef.type && layerDef.args) return this._getPath(L, layerDef.type).apply(L, layerDef.args); }, _addLayer: function (layerDef, overlay, group) { var layer = layerDef.hasOwnProperty('layer') ? this._instantiateLayer(layerDef.layer) : layerDef; var id = L.stamp(layer); if(layerDef.active) this._layersActives.push(layer); this._layers[ id ] = L.Util.extend(layerDef, { overlay: overlay, group: group, layer: layer }); if (this.options.autoZIndex && layer.setZIndex) { this._lastZIndex++; layer.setZIndex(this._lastZIndex); } }, _createItem: function(obj) { var className = 'leaflet-panel-layers', label, input, checked; label = L.DomUtil.create('label', className + '-item'); checked = this._map.hasLayer(obj.layer); if (obj.overlay) { input = document.createElement('input'); input.type = 'checkbox'; input.className = 'leaflet-control-layers-selector'; input.defaultChecked = checked; } else { input = this._createRadioElement('leaflet-base-layers', checked); } input.value = L.stamp(obj.layer); L.DomEvent.on(input, 'click', this._onInputClick, this); label.appendChild(input); if(obj.icon) { var icon = L.DomUtil.create('i', className+'-icon'); icon.innerHTML = obj.icon || ''; label.appendChild(icon); } var item = document.createElement('span'); if(this.options.buildItem) { var node = this.options.buildItem.call(this, obj); //custom node node or html string if(typeof node === 'string') { var tmpNode = L.DomUtil.create('div'); tmpNode.innerHTML = node; item = tmpNode.firstChild; } else item = node; } else item.innerHTML = obj.name || ''; label.appendChild(item); this._items[ input.value ] = label; return label; }, _addItem: function (obj) { var self = this, className = 'leaflet-panel-layers', label, input, icon, checked; var list = obj.overlay ? this._overlaysList : this._baseLayersList; if(obj.group) { if(!obj.group.hasOwnProperty('name')) obj.group = { name: obj.group }; if(!this._groups[ obj.group.name ]) this._groups[ obj.group.name ] = this._createGroup( obj.group ); list.appendChild(this._groups[obj.group.name]); list = this._groups[obj.group.name]; } label = this._createItem(obj); list.appendChild(label); // pdr: turned of this resizing bit // if(obj.group) { // setTimeout(function() { // self._container.style.width = (self._container.clientWidth-8)+'px'; // },100); // } return label; }, _createGroup: function ( groupdata ) { var className = 'leaflet-panel-layers', groupdiv = L.DomUtil.create('div', className + '-group'), grouplabel, groupexp; if(this.options.collapsibleGroups) { L.DomUtil.addClass(groupdiv, 'collapsible'); groupexp = L.DomUtil.create('i', className + '-icon', groupdiv); groupexp.innerHTML = ' - '; L.DomEvent.on(groupexp, 'click', function() { if ( L.DomUtil.hasClass(groupdiv, 'expanded') ) { L.DomUtil.removeClass(groupdiv, 'expanded'); groupexp.innerHTML = ' + '; } else { L.DomUtil.addClass(groupdiv, 'expanded'); groupexp.innerHTML = ' - '; } }); L.DomUtil.addClass(groupdiv, 'expanded'); } grouplabel = L.DomUtil.create('label', className + '-grouplabel', groupdiv); grouplabel.innerHTML = '<span>'+groupdata.name+'</span>'; return groupdiv; }, _onInputClick: function () { var i, input, obj, inputs = this._form.getElementsByTagName('input'), inputsLen = inputs.length; this._handlingClick = true; for (i = 0; i < inputsLen; i++) { input = inputs[i]; obj = this._layers[ input.value ]; if (input.checked && !this._map.hasLayer(obj.layer)) { this._map.addLayer(obj.layer); } else if (!input.checked && this._map.hasLayer(obj.layer)) { this._map.removeLayer(obj.layer); } } this._handlingClick = false; this._refocusOnMap(); }, _initLayout: function () { var className = 'leaflet-panel-layers', layerControlClassName = 'leaflet-control-layers', container = this._container = L.DomUtil.create('div', className); //Makes this work on IE10 Touch devices by stopping it from firing a mouseout event when the touch is released container.setAttribute('aria-haspopup', true); if (!L.Browser.touch) { L.DomEvent .disableClickPropagation(container) .disableScrollPropagation(container); } else L.DomEvent.on(container, 'click', L.DomEvent.stopPropagation); var form = this._form = L.DomUtil.create('form', className + '-list'); this._map.on('resize', function(e) { form.style.height = e.newSize.y+'px'; }); form.style.height = this._map.getSize().y+'px'; if (this.options.button) { this.options.collapsed = true; L.DomUtil.addClass(container, className+'-button-collapse'); } if (this.options.collapsed) { if (!L.Browser.android) { L.DomEvent .on(container, 'mouseover', this._expand, this) .on(container, 'mouseout', this._collapse, this); } var link = this._layersLink = L.DomUtil.create('a', layerControlClassName+'-toggle', container); link.href = '#'; link.title = 'Layers'; if (L.Browser.touch) { L.DomEvent .on(link, 'click', L.DomEvent.stop) .on(link, 'click', this._expand, this); } else { L.DomEvent.on(link, 'focus', this._expand, this); } this._map.on('click', this._collapse, this); // TODO keyboard accessibility } else { this._expand(); } this._baseLayersList = L.DomUtil.create('div', className + '-base', form); this._separator = L.DomUtil.create('div', className + '-separator', form); this._overlaysList = L.DomUtil.create('div', className + '-overlays', form); L.DomUtil.create('div', className + '-margin', form); // No need to store it container.appendChild(form); }, _expand: function () { L.DomUtil.addClass(this._container, 'leaflet-panel-layers-expanded'); }, _collapse: function () { this._container.className = this._container.className.replace(' leaflet-panel-layers-expanded', ''); }, _getPath: function(obj, prop) { var parts = prop.split('.'), last = parts.pop(), len = parts.length, cur = parts[0], i = 1; if(len > 0) while((obj = obj[cur]) && i < len) cur = parts[i++]; if(obj) return obj[last]; } }); L.control.panelLayers = function (baseLayers, overlays, options) { return new L.Control.PanelLayers(baseLayers, overlays, options); }; }).call(this);
(function ($, Typer) { 'use strict'; var activeToolbar; function nativePrompt(message, value) { value = window.prompt(message, value); if (value !== null) { return $.when(value); } return $.Deferred().reject().promise(); } function detectClipboardInaccessible(callback) { if (detectClipboardInaccessible.value === false) { callback(); } else if (!detectClipboardInaccessible.value) { var handler = function () { detectClipboardInaccessible.value = true; }; $(document).one('paste', handler); setTimeout(function () { $(document).off('paste', handler); if (!detectClipboardInaccessible.value) { detectClipboardInaccessible.value = false; callback(); } }); } } function positionToolbar(toolbar, position) { var height = $(toolbar.element).height(); if (position) { toolbar.position = 'fixed'; } else if (toolbar.position !== 'fixed') { var rect = Typer.getRect(toolbar.widget || toolbar.typer); if (rect.left === 0 && rect.top === 0 && rect.width === 0 && rect.height === 0) { // invisible element or IE bug related - https://connect.microsoft.com/IE/feedback/details/881970 return; } position = { position: 'fixed', left: rect.left, top: Math.max(0, rect.top - height - 10) }; } if (position) { var r = toolbar.typer.getSelection().extendCaret.getRect(); if (r.top >= position.top && r.top <= position.top + height) { position.top = r.bottom + 10; } $(toolbar.element).css(position); } } function showToolbar(toolbar, position) { toolbar.update(); if (toolbar.widget || !toolbar.options.container) { if (activeToolbar !== toolbar) { hideToolbar(); activeToolbar = toolbar; $(toolbar.element).appendTo(document.body); Typer.ui.setZIndex(toolbar.element, toolbar.typer.element); } positionToolbar(toolbar, position); } } function hideToolbar(typer) { if (activeToolbar && (!typer || activeToolbar.typer === typer)) { $(activeToolbar.element).detach(); activeToolbar.position = ''; activeToolbar = null; } } function createToolbar(typer, options, widget, type) { var toolbar = Typer.ui({ type: type || 'toolbar', typer: typer, widget: widget || null, theme: options.theme, defaultNS: 'typer', controls: type === 'contextmenu' ? 'contextmenu' : widget ? 'widget' : 'toolbar', options: options, showButtonLabel: type === 'contextmenu', executed: function (ui, control) { if (!control.is('textbox')) { ui.typer.getSelection().focus(); } } }); var $elm = $(toolbar.element); if (options.container) { $elm.appendTo(options.container); } else { $elm.addClass('typer-ui-float'); $elm.mousedown(function (e) { var pos = $elm.position(); if (e.target === toolbar.element) { var handler = function (e1) { showToolbar(toolbar, { top: pos.top + (e1.clientY - e.clientY), left: pos.left + (e1.clientX - e.clientX) }); }; $(document.body).mousemove(handler); $(document.body).mouseup(function () { $(document.body).off('mousemove', handler); }); } }); } if (type === 'contextmenu') { $(typer.element).on('contextmenu', function (e) { e.preventDefault(); toolbar.update(); toolbar.show({ x: e.clientX, y: e.clientY }); setTimeout(function () { // fix IE11 rendering issue when mousedown on contextmenu // without moving focus beforehand toolbar.element.focus(); }); }); $(typer.element).on('click', function (e) { if (e.which === 1) { toolbar.hide(); } }); } return toolbar; } Typer.widgets.toolbar = { inline: true, options: { container: '', theme: 'material', formattings: { p: 'Paragraph', h1: 'Heading 1', h2: 'Heading 2', h3: 'Heading 3', h4: 'Heading 4' }, inlineClasses: {} }, init: function (e) { e.widget.toolbar = createToolbar(e.typer, e.widget.options); e.widget.contextmenu = createToolbar(e.typer, e.widget.options, null, 'contextmenu'); e.widget.toolbars = {}; }, focusin: function (e) { showToolbar(e.widget.toolbar); }, focusout: function (e) { hideToolbar(e.typer); }, stateChange: function (e) { if (activeToolbar && activeToolbar.typer === e.typer) { var toolbar = e.widget.toolbar; var selection = e.typer.getSelection(); var currentWidget = selection.focusNode.widget; if (currentWidget.id !== '__root__' && selection.focusNode.element === currentWidget.element) { if (Typer.ui.controls['typer:widget:' + currentWidget.id]) { toolbar = e.widget.toolbars[currentWidget.id] || (e.widget.toolbars[currentWidget.id] = createToolbar(e.typer, e.widget.options, currentWidget)); toolbar.widget = currentWidget; } } showToolbar(toolbar); } } }; $(window).scroll(function () { if (activeToolbar) { positionToolbar(activeToolbar); } }); /* ******************************** * Built-in Controls * ********************************/ Typer.ui.addControls('typer', { 'contextmenu': Typer.ui.group('history selection clipboard insert *'), 'contextmenu:history': Typer.ui.group('typer:history:* *'), 'contextmenu:selection': Typer.ui.group('typer:selection:* *'), 'contextmenu:clipboard': Typer.ui.group('typer:clipboard:* *'), 'contextmenu:insert': Typer.ui.group('typer:toolbar:insert *'), 'toolbar': Typer.ui.group(), 'toolbar:insert': Typer.ui.callout({ before: '*', controls: 'typer:insert:*', requireChildControls: true }), 'widget': Typer.ui.group({ requireWidget: true, controls: function (toolbar, self) { return toolbar.widget.id + ' delete'; } }), 'history:undo': Typer.ui.button({ before: '*', shortcut: 'ctrlZ', execute: function (toolbar) { toolbar.typer.undo(); }, enabled: function (toolbar) { return toolbar.typer.canUndo(); } }), 'history:redo': Typer.ui.button({ before: '*', shortcut: 'ctrlShiftZ', execute: function (toolbar) { toolbar.typer.redo(); }, enabled: function (toolbar) { return toolbar.typer.canRedo(); } }), 'widget:delete': Typer.ui.button({ after: '*', requireWidget: true, execute: function (toolbar) { toolbar.widget.remove(); } }), 'selection:selectAll': Typer.ui.button({ before: '*', shortcut: 'ctrlA', execute: function (toolbar) { var selection = toolbar.typer.getSelection(); selection.selectAll(); selection.focus(); } }), 'selection:selectParagraph': Typer.ui.button({ before: '*', hiddenWhenDisabled: true, execute: function (toolbar) { var selection = toolbar.typer.getSelection(); selection.select(selection.startNode.element, 'contents'); selection.focus(); }, enabled: function (toolbar) { return toolbar.typer.getSelection().isCaret; } }), 'clipboard:cut': Typer.ui.button({ before: '*', shortcut: 'ctrlX', execute: function (toolbar) { toolbar.typer.getSelection().focus(); document.execCommand('cut'); } }), 'clipboard:copy': Typer.ui.button({ before: '*', shortcut: 'ctrlC', execute: function (toolbar) { toolbar.typer.getSelection().focus(); document.execCommand('copy'); } }), 'clipboard:paste': Typer.ui.button({ before: '*', shortcut: 'ctrlV', execute: function (toolbar) { toolbar.typer.getSelection().focus(); document.execCommand('paste'); detectClipboardInaccessible(function () { Typer.ui.alert('typer:clipboard:inaccessible'); }); } }) }); Typer.ui.addLabels('en', 'typer', { 'toolbar:insert': 'Insert widget', 'history:undo': 'Undo', 'history:redo': 'Redo', 'selection:selectAll': 'Select all', 'selection:selectParagraph': 'Select paragraph', 'clipboard:cut': 'Cut', 'clipboard:copy': 'Copy', 'clipboard:paste': 'Paste', 'clipboard:inaccessible': 'Unable to access clipboard due to browser security. Please use Ctrl+V or [Paste] from browser\'s menu.', 'widget:delete': 'Delete' }); Typer.ui.addIcons('material', 'typer', { 'toolbar:insert': '\ue1bd', // widgets 'history:undo': '\ue166', // undo 'history:redo': '\ue15a', // redo 'selection:selectAll': '\ue162', // select_all 'clipboard:cut': '\ue14e', // content_cut 'clipboard:copy': '\ue14d', // content_copy 'clipboard:paste': '\ue14f', // content_paste 'widget:delete': '\ue872' // delete }); }(jQuery, Typer));
// @flow import defineType, { arrayOfType, assertOneOf, assertValueType, validate, validateOptional, validateOptionalType, validateType, } from "./utils"; const defineInterfaceishType = ( name: string, typeParameterType: string = "TypeParameterDeclaration", ) => { defineType(name, { builder: ["id", "typeParameters", "extends", "body"], visitor: [ "id", "typeParameters", "extends", "mixins", "implements", "body", ], aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], fields: { id: validateType("Identifier"), typeParameters: validateOptionalType(typeParameterType), extends: validateOptional(arrayOfType("InterfaceExtends")), mixins: validateOptional(arrayOfType("InterfaceExtends")), implements: validateOptional(arrayOfType("ClassImplements")), body: validateType("ObjectTypeAnnotation"), }, }); }; defineType("AnyTypeAnnotation", { aliases: ["Flow", "FlowType", "FlowBaseAnnotation"], }); defineType("ArrayTypeAnnotation", { visitor: ["elementType"], aliases: ["Flow", "FlowType"], fields: { elementType: validateType("FlowType"), }, }); defineType("BooleanTypeAnnotation", { aliases: ["Flow", "FlowType", "FlowBaseAnnotation"], }); defineType("BooleanLiteralTypeAnnotation", { builder: ["value"], aliases: ["Flow", "FlowType"], fields: { value: validate(assertValueType("boolean")), }, }); defineType("NullLiteralTypeAnnotation", { aliases: ["Flow", "FlowType", "FlowBaseAnnotation"], }); defineType("ClassImplements", { visitor: ["id", "typeParameters"], aliases: ["Flow"], fields: { id: validateType("Identifier"), typeParameters: validateOptionalType("TypeParameterInstantiation"), }, }); defineInterfaceishType("DeclareClass"); defineType("DeclareFunction", { visitor: ["id"], aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], fields: { id: validateType("Identifier"), predicate: validateOptionalType("DeclaredPredicate"), }, }); defineInterfaceishType("DeclareInterface"); defineType("DeclareModule", { builder: ["id", "body", "kind"], visitor: ["id", "body"], aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], fields: { id: validateType(["Identifier", "StringLiteral"]), body: validateType("BlockStatement"), kind: validateOptional(assertOneOf("CommonJS", "ES")), }, }); defineType("DeclareModuleExports", { visitor: ["typeAnnotation"], aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], fields: { typeAnnotation: validateType("TypeAnnotation"), }, }); defineType("DeclareTypeAlias", { visitor: ["id", "typeParameters", "right"], aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], fields: { id: validateType("Identifier"), typeParameters: validateOptionalType("TypeParameterDeclaration"), right: validateType("FlowType"), }, }); defineType("DeclareOpaqueType", { visitor: ["id", "typeParameters", "supertype"], aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], fields: { id: validateType("Identifier"), typeParameters: validateOptionalType("TypeParameterDeclaration"), supertype: validateOptionalType("FlowType"), }, }); defineType("DeclareVariable", { visitor: ["id"], aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], fields: { id: validateType("Identifier"), }, }); defineType("DeclareExportDeclaration", { visitor: ["declaration", "specifiers", "source"], aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], fields: { declaration: validateOptionalType("Flow"), specifiers: validateOptional( arrayOfType(["ExportSpecifier", "ExportNamespaceSpecifier"]), ), source: validateOptionalType("StringLiteral"), default: validateOptional(assertValueType("boolean")), }, }); defineType("DeclareExportAllDeclaration", { visitor: ["source"], aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], fields: { source: validateType("StringLiteral"), exportKind: validateOptional(assertOneOf(["type", "value"])), }, }); defineType("DeclaredPredicate", { visitor: ["value"], aliases: ["Flow", "FlowPredicate"], fields: { value: validateType("Flow"), }, }); defineType("ExistsTypeAnnotation", { aliases: ["Flow", "FlowType"], }); defineType("FunctionTypeAnnotation", { visitor: ["typeParameters", "params", "rest", "returnType"], aliases: ["Flow", "FlowType"], fields: { typeParameters: validateOptionalType("TypeParameterDeclaration"), params: validate(arrayOfType("FunctionTypeParam")), rest: validateOptionalType("FunctionTypeParam"), returnType: validateType("FlowType"), }, }); defineType("FunctionTypeParam", { visitor: ["name", "typeAnnotation"], aliases: ["Flow"], fields: { name: validateOptionalType("Identifier"), typeAnnotation: validateType("FlowType"), optional: validateOptional(assertValueType("boolean")), }, }); defineType("GenericTypeAnnotation", { visitor: ["id", "typeParameters"], aliases: ["Flow", "FlowType"], fields: { id: validateType(["Identifier", "QualifiedTypeIdentifier"]), typeParameters: validateOptionalType("TypeParameterInstantiation"), }, }); defineType("InferredPredicate", { aliases: ["Flow", "FlowPredicate"], }); defineType("InterfaceExtends", { visitor: ["id", "typeParameters"], aliases: ["Flow"], fields: { id: validateType(["Identifier", "QualifiedTypeIdentifier"]), typeParameters: validateOptionalType("TypeParameterInstantiation"), }, }); defineInterfaceishType("InterfaceDeclaration"); defineType("InterfaceTypeAnnotation", { visitor: ["extends", "body"], aliases: ["Flow", "FlowType"], fields: { extends: validateOptional(arrayOfType("InterfaceExtends")), body: validateType("ObjectTypeAnnotation"), }, }); defineType("IntersectionTypeAnnotation", { visitor: ["types"], aliases: ["Flow", "FlowType"], fields: { types: validate(arrayOfType("FlowType")), }, }); defineType("MixedTypeAnnotation", { aliases: ["Flow", "FlowType", "FlowBaseAnnotation"], }); defineType("EmptyTypeAnnotation", { aliases: ["Flow", "FlowType", "FlowBaseAnnotation"], }); defineType("NullableTypeAnnotation", { visitor: ["typeAnnotation"], aliases: ["Flow", "FlowType"], fields: { typeAnnotation: validateType("FlowType"), }, }); defineType("NumberLiteralTypeAnnotation", { builder: ["value"], aliases: ["Flow", "FlowType"], fields: { value: validate(assertValueType("number")), }, }); defineType("NumberTypeAnnotation", { aliases: ["Flow", "FlowType", "FlowBaseAnnotation"], }); defineType("ObjectTypeAnnotation", { visitor: ["properties", "indexers", "callProperties", "internalSlots"], aliases: ["Flow", "FlowType"], builder: [ "properties", "indexers", "callProperties", "internalSlots", "exact", ], fields: { properties: validate( arrayOfType(["ObjectTypeProperty", "ObjectTypeSpreadProperty"]), ), indexers: validateOptional(arrayOfType("ObjectTypeIndexer")), callProperties: validateOptional(arrayOfType("ObjectTypeCallProperty")), internalSlots: validateOptional(arrayOfType("ObjectTypeInternalSlot")), exact: { validate: assertValueType("boolean"), default: false, }, // If the inexact flag is present then this is an object type, and not a // declare class, declare interface, or interface. If it is true, the // object uses ... to express that it is inexact. inexact: validateOptional(assertValueType("boolean")), }, }); defineType("ObjectTypeInternalSlot", { visitor: ["id", "value", "optional", "static", "method"], aliases: ["Flow", "UserWhitespacable"], fields: { id: validateType("Identifier"), value: validateType("FlowType"), optional: validate(assertValueType("boolean")), static: validate(assertValueType("boolean")), method: validate(assertValueType("boolean")), }, }); defineType("ObjectTypeCallProperty", { visitor: ["value"], aliases: ["Flow", "UserWhitespacable"], fields: { value: validateType("FlowType"), static: validate(assertValueType("boolean")), }, }); defineType("ObjectTypeIndexer", { visitor: ["id", "key", "value", "variance"], aliases: ["Flow", "UserWhitespacable"], fields: { id: validateOptionalType("Identifier"), key: validateType("FlowType"), value: validateType("FlowType"), static: validate(assertValueType("boolean")), variance: validateOptionalType("Variance"), }, }); defineType("ObjectTypeProperty", { visitor: ["key", "value", "variance"], aliases: ["Flow", "UserWhitespacable"], fields: { key: validateType(["Identifier", "StringLiteral"]), value: validateType("FlowType"), kind: validate(assertOneOf("init", "get", "set")), static: validate(assertValueType("boolean")), proto: validate(assertValueType("boolean")), optional: validate(assertValueType("boolean")), variance: validateOptionalType("Variance"), }, }); defineType("ObjectTypeSpreadProperty", { visitor: ["argument"], aliases: ["Flow", "UserWhitespacable"], fields: { argument: validateType("FlowType"), }, }); defineType("OpaqueType", { visitor: ["id", "typeParameters", "supertype", "impltype"], aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], fields: { id: validateType("Identifier"), typeParameters: validateOptionalType("TypeParameterDeclaration"), supertype: validateOptionalType("FlowType"), impltype: validateType("FlowType"), }, }); defineType("QualifiedTypeIdentifier", { visitor: ["id", "qualification"], aliases: ["Flow"], fields: { id: validateType("Identifier"), qualification: validateType(["Identifier", "QualifiedTypeIdentifier"]), }, }); defineType("StringLiteralTypeAnnotation", { builder: ["value"], aliases: ["Flow", "FlowType"], fields: { value: validate(assertValueType("string")), }, }); defineType("StringTypeAnnotation", { aliases: ["Flow", "FlowType", "FlowBaseAnnotation"], }); defineType("ThisTypeAnnotation", { aliases: ["Flow", "FlowType", "FlowBaseAnnotation"], }); defineType("TupleTypeAnnotation", { visitor: ["types"], aliases: ["Flow", "FlowType"], fields: { types: validate(arrayOfType("FlowType")), }, }); defineType("TypeofTypeAnnotation", { visitor: ["argument"], aliases: ["Flow", "FlowType"], fields: { argument: validateType("FlowType"), }, }); defineType("TypeAlias", { visitor: ["id", "typeParameters", "right"], aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], fields: { id: validateType("Identifier"), typeParameters: validateOptionalType("TypeParameterDeclaration"), right: validateType("FlowType"), }, }); defineType("TypeAnnotation", { aliases: ["Flow"], visitor: ["typeAnnotation"], fields: { typeAnnotation: validateType("FlowType"), }, }); defineType("TypeCastExpression", { visitor: ["expression", "typeAnnotation"], aliases: ["Flow", "ExpressionWrapper", "Expression"], fields: { expression: validateType("Expression"), typeAnnotation: validateType("TypeAnnotation"), }, }); defineType("TypeParameter", { aliases: ["Flow"], visitor: ["bound", "default", "variance"], fields: { name: validate(assertValueType("string")), bound: validateOptionalType("TypeAnnotation"), default: validateOptionalType("FlowType"), variance: validateOptionalType("Variance"), }, }); defineType("TypeParameterDeclaration", { aliases: ["Flow"], visitor: ["params"], fields: { params: validate(arrayOfType("TypeParameter")), }, }); defineType("TypeParameterInstantiation", { aliases: ["Flow"], visitor: ["params"], fields: { params: validate(arrayOfType("FlowType")), }, }); defineType("UnionTypeAnnotation", { visitor: ["types"], aliases: ["Flow", "FlowType"], fields: { types: validate(arrayOfType("FlowType")), }, }); defineType("Variance", { aliases: ["Flow"], builder: ["kind"], fields: { kind: validate(assertOneOf("minus", "plus")), }, }); defineType("VoidTypeAnnotation", { aliases: ["Flow", "FlowType", "FlowBaseAnnotation"], });
grocery_list = {} function addItem(item, quantity){ //update item quantity if exist if (grocery_list.hasOwnProperty(item)){ new_quantity = grocery_list[item]; console.log(new_quantity) grocery_list[item] = new_quantity + quantity; } //add new entry else grocery_list[item] = quantity; } //remove item function removeItem(item){ delete grocery_list[item]; } console.log(grocery_list) item = "eggs" quantity = 2 addItem(item, quantity) console.log(grocery_list) addItem(item, 3) addItem("milk", 3) console.log(grocery_list) removeItem(item) console.log(grocery_list) //formatted output for (var x in grocery_list){ console.log("Your list includes "+x +" "+grocery_list[x]); } /* Reflection answer the following questions: 1. What concepts did you solidify in working on this challenge? (reviewing the passing of information, objects, constructors, etc.) # It was good revision on JS objects, inserting and updating data. 2. What was the most difficult part of this challenge? # It was not that difficult this time 3. Did an array or object make more sense to use and why? # I used objects to store grocery items and their values. */
'use strict'; describe('Formations E2E Tests:', function() { describe('Test Formations page', function() { it('Should not include new Formations', function() { browser.get('http://localhost:3000/#!/formations'); expect(element.all(by.repeater('formation in formations')).count()).toEqual(0); }); }); });
/*eslint-env node*/ //------------------------------------------------------------------------------ // node.js starter application for Bluemix //------------------------------------------------------------------------------ // This application uses express as its web server // for more info, see: http://expressjs.com var express = require('express'); // cfenv provides access to your Cloud Foundry environment // for more info, see: https://www.npmjs.com/package/cfenv var cfenv = require('cfenv'); // create a new express server var app = express(); var path = require("path"); // serve the files out of ./public as our main files app.use(express.static(__dirname + '/public')); // get the app environment from Cloud Foundry var appEnv = cfenv.getAppEnv(); /* app.get('/', function(req,res){ res.sendFile(path.join(__dirname+'/index.html')); }); */ // start server on the specified port and binding host app.listen(appEnv.port, '0.0.0.0', function() { // print a message when the server starts listening console.log("server starting on " + appEnv.url); });
QUnit.module('TDP.constructors.Tile item tile'); var item_tile = TestData.item_tile; QUnit.test( 'should have a type of "item"', function (assert) { assert.equal(item_tile.type, 'item', 'tile type should be item'); assert.ok(item_tile.is('item'), 'is function should return true'); assert.notOk(item_tile.is('car'), 'is function should return false (when type is wrong)'); } ); QUnit.test( 'should be not passable', function (assert) { assert.notOk(item_tile.impassable, 'should not be impassable'); assert.ok(item_tile.passable, 'should be passable'); } ); QUnit.test( 'should have an interaction', function (assert) { assert.ok(TestData.item_tile.hasInteraction, 'should have an interaction'); } ); QUnit.test( 'should have a function as its interaction', function (assert) { assert.ok( jQuery.isFunction(item_tile.interaction), 'should have an interaction' ); } ); QUnit.test( 'should run the deafult interaction, gain points.', function(assert) { var item = TDP.field.tileAt(12, 0); var starting_score = TDP.score; TDP.UI.readout.html(''); item.interaction(item, TDP.player); assert.equal( TDP.score, starting_score + item.score_value, 'should have increased the score' ); var major_message = TDP.emoji.get("You picked up the " + item.source); var minor_message = TDP.emoji.get("You scored " + item.score_value + " points."); assert.ok( TDP.UI.readout.html().indexOf(major_message) >= 0, 'should say the picked up thing.' ); assert.ok( TDP.UI.readout.html().indexOf(minor_message) >= 0, 'should tell you about the points.' ); TDP.fieldInit(TestData.source); } );
import { connect } from 'react-redux' import Archives from 'com/archives' export default connect()(Archives)
Ext.define('Packt.view.reports.SalesFilmCategoryPie', { extend: 'Ext.chart.Chart', alias: 'widget.salesfilmcategorypie', animate: true, store: 'reports.SalesFilmCategory', shadow: true, legend: { position: 'right' }, insetPadding: 60, theme: 'Base:gradients', series: [{ type: 'pie', field: 'total_sales', showInLegend: true, tips: { trackMouse: true, width: 140, height: 28, renderer: function(storeItem, item) { this.setTitle(storeItem.get('category') + ': ' + storeItem.get('total_sales')); } }, highlight: { segment: { margin: 20 } }, label: { field: 'category', display: 'rotate', contrast: true, font: '18px Arial' } }] });
$('html').on('click', 'a[href="#"]', function (e) { e.preventDefault(); }); // responsive $('html').on('click', '#links a.admin-links-expand', function () { var height = 0; $("#links li").each(function() { height += $(this).outerHeight(); }); $('#links li').removeClass('mobile-hide').slideDown(100); $(this).removeClass('admin-links-expand').addClass('admin-links-collapse').find('i').removeClass('fa-caret-left').addClass('fa-caret-down'); $('#main').animate({ 'marginTop': '+' + height }, 100); }); $('html').on('click', '#links a.admin-links-collapse', function () { $('#links li:not(.selected)').slideUp(100, function () { $(this).addClass('mobile-hide').attr('style', ''); }); $(this).removeClass('admin-links-collapse').addClass('admin-links-expand').find('i').removeClass('fa-caret-down').addClass('fa-caret-left'); $('#main').animate({ 'marginTop': '+' + $('#links li.selected').height() + 'px' }, 100); }); function positionMenu() { var h1 = $('h1'); var scrollY = window.scrollY || document.documentElement.scrollTop; $('#links').css('top', Math.max(33, h1.position().top + h1.outerHeight(true) - scrollY) + 'px'); } $(window).scroll(function () { if ($('#links').css('position') === 'fixed') { positionMenu(); } }); $(window).resize(function () { if ($('#links').css('position') !== 'fixed') { if ($('#links').css('top') !== '') { $('#links').css('top', ''); $('#main').css('marginTop', ''); $('#links li:not(.selected)').addClass('mobile-hide').attr('style', ''); $('#links a.admin-links-collapse').removeClass('admin-links-collapse').addClass('admin-links-expand').find('i').removeClass('fa-caret-down').addClass('fa-caret-left'); } } else { positionMenu(); } }); // dropdown $('html').click(function () { $('.dropdown-menu').fadeOut(100); }); $('html').on('click', '.dropdown-menu', function (e) { e.stopPropagation(); }); $('html').on('click', '.dropdown-toggle', function (e) { e.stopPropagation(); var dropdown = $(this).parent(); $('.dropdown-menu').not($('.dropdown-menu', dropdown)).hide(150); $('.dropdown-menu', dropdown).toggle(); if ($('.dropdown-menu', dropdown).is(':visible')) { $('.dropdown-menu', dropdown).css({ overflow: 'visible' }); } }); // halt $('html').on('click', 'a.halt', function (e) { e.preventDefault(); var display = $(this).css('display'); $(this).hide(); $(this).parent().find('a.sure').show().css('display', display); }); $('html').on('mouseleave', 'a.sure', function (e) { e.preventDefault(); $(this).fadeOut(100, function() { $(this).parent().find('a.halt').fadeIn(100); }); }); // inline form function inlineFormError(element, error) { element.addClass('invalid'); var inlineError = element.find('.inline-error-' + element.attr('data-error-position')); if (!inlineError.length) { inlineError = $('<div class="inline-error-' + element.attr('data-error-position') + '">\ <div class="box">\ <div class="arrow"></div>\ <div class="arrow-border"></div>\ <p>\ <i class="fa fa-exclamation-circle"></i>&ensp;<span></span>\ </p>\ </div>\ </div>').appendTo(element.parent()); } if (inlineError.find('span').text() != error) { inlineError.hide(); inlineError.find('span').text(error); } inlineError.fadeIn(); } function hideInlineFormErrors(element) { element.find('.inline-error-left, .inline-error-right, .inline-error-above, .inline-error-below').hide().parent().find('.invalid').removeClass('invalid'); } $('html').on('click', '.inline-error-left, .inline-error-right, .inline-error-above, .inline-error-below', function () { $(this).hide(); }); function titleToUrl(title) { var url = title.toLowerCase().replace(/[^a-z0-9\-_\s]+/g, '').trim().replace(/\s/g, '-'); if (url.length) { url += '/'; } return url; } function escapeHtml(s) { return s .replace(/&/g, "&amp;") .replace(/</g, "&lt;") .replace(/>/g, "&gt;") .replace(/"/g, "&quot;") .replace(/'/g, "&#039;"); }
'use strict'; var React = require('react'); var IconBase = require(__dirname + 'components/IconBase/IconBase'); var FilmMarker = React.createClass({ displayName: 'FilmMarker', render: function render() { return React.createElement( IconBase, null, React.createElement('path', { d: 'M448.4,208h-344l341.2-68c8.5-1.6,14-9.7,12.4-18.1l-8.9-45.4c-1.6-8.4-9.8-13.8-18.3-12.2L60.7,137.9 c-8.5,1.6-14,9.7-12.4,18l8.9,45.4c0.6,2.8,2.1,5.2,3.9,7.2c-7.4,1.2-13.1,7.2-13.1,14.9v209.2c0,8.5,7,15.4,15.6,15.4h384.8 c8.6,0,15.6-6.9,15.6-15.4V223.4C464,214.9,457,208,448.4,208z M305,402.4l-50.7-36.3l-50.7,36.3l19.5-58.4l-50.8-36H235l19.2-58.4 l19.3,58.4h62.7l-50.8,36L305,402.4z' }) ); } });
var searchData= [ ['blockedtill',['BlockedTill',['../class_kluster_kite_1_1_node_manager_1_1_client_1_1_o_r_m_1_1_user_description.html#a6b42d29f5c706e72191eab05b693295c',1,'KlusterKite::NodeManager::Client::ORM::UserDescription']]] ];
"use strict"; var LocalizedString = (function () { function LocalizedString() { } LocalizedString.prototype.Equals = function (obj) { throw new Error("LocalizedString.ts - Equals : Not implemented."); }; //Equals(obj: LocalizedString): boolean{ throw new Error("LocalizedString.ts - Equals : Not implemented.");} LocalizedString.prototype.GetHashCode = function () { throw new Error("LocalizedString.ts - GetHashCode : Not implemented."); }; LocalizedString.prototype.Join = function (separator, value) { throw new Error("LocalizedString.ts - Join : Not implemented."); }; LocalizedString.prototype.ToString = function () { throw new Error("LocalizedString.ts - ToString : Not implemented."); }; //ToString(formatProvider: System.IFormatProvider): string{ throw new Error("LocalizedString.ts - ToString : Not implemented.");} LocalizedString.prototype.TranslateObject = function (badObject, formatProvider /*System.IFormatProvider */) { throw new Error("LocalizedString.ts - TranslateObject : Not implemented."); }; return LocalizedString; }()); exports.LocalizedString = LocalizedString;
'use strict'; /** * Module dependencies. */ var users = require('../../app/controllers/users'), requests = require('../../app/controllers/requests'); module.exports = function(app) { // Request Routes app.route('/requests') .get(users.requiresLogin, requests.list) .post(users.requiresLogin, requests.create); app.route('/requests/:requestId') .get(users.requiresLogin, requests.read) .put(users.requiresLogin, requests.update) .delete(users.requiresLogin, requests.delete); // Finish by binding the request middleware app.param('requestId', requests.requestByID); };
'use strict'; var app = angular.module('velo-app', ['ngRoute']); app.config(function ($routeProvider) { L.mapbox.accessToken = 'pk.eyJ1Ijoiam9yZGFuYWJkZXJyYWNoaWQiLCJhIjoiY2loZG56MDlqMDAzOXY0a3FxYW55OXplZSJ9.lEgruWmyCm-E-300PG7XuA'; $routeProvider.when('/', { controller: 'MainCtrl', templateUrl: '/views/main.html' }); });
define(['../TrulyRelative2'], function(TrulyRelative2) { var module = function() { }; var dep = new TrulyRelative2(); module.prototype.TrulyRelative1 = function() { return 'TrulyRelative1_' + dep.TrulyRelative2(); }; return module; });
$(document).ready(function() { getLocation(); // add a spinner icon to areas where data will be populated $('#condition').html('<i class="fa fa-spinner fa-pulse fa-3x"></i>'); $('#wind-speed').html('<i class="fa fa-spinner fa-pulse fa-3x"></i>'); }); function getLocation() { // Using the GEO IP API due to HTTP restrictions from OpenWeatherMap $.getJSON('https://freegeoip.net/json/?callback=?', function(loc) { $('#city').text(loc.city + ', ' + loc.region_name + ', ' + loc.country_name); getWeather(loc.latitude, loc.longitude, loc.country_code); }) .fail(function(err) { getWeather(); }); } function getWeather(lat, lon, countryCode) { var weatherAPI = 'http://api.openweathermap.org/data/2.5/weather?lat=' + lat + '&lon=' + lon + '&units=imperial' + '&type=accurate' + callback; if(window.location.protocol === 'https:') weatherAPI = 'https://cors-anywhere.herokuapp.com/' + weatherAPI $.getJSON(weatherAPI, function(weatherData) { // Also used by convert(); temp = weatherData.main.temp.toFixed(0); tempC = ((temp - 32) * (5 / 9)).toFixed(0); var condition = weatherData.weather[0].description, id = weatherData.weather[0].id, speed = Number((weatherData.wind.speed * 0.86897624190816).toFixed(1)), deg = weatherData.wind.deg, windDir, iconClass, bgIndex, backgroundId = [299, 499, 599, 699, 799, 800], backgroundIcon = [ 'thunderstorm', 'sprinkle', 'rain', 'snow', 'fog', 'night-clear', 'cloudy', ], backgroundImg = [ 'http://tylermoeller.github.io/local-weather-app/assets/img/thunderstorm.jpg', 'https://tylermoeller.github.io/local-weather-app/assets/img/sprinkle.jpg', 'https://tylermoeller.github.io/local-weather-app/assets/img/rain.jpg', 'https://tylermoeller.github.io/local-weather-app/assets/img/snow.jpg', 'https://tylermoeller.github.io/local-weather-app/assets/img/fog.jpg', 'https://tylermoeller.github.io/local-weather-app/assets/img/clear.jpg', 'https://tylermoeller.github.io/local-weather-app/assets/img/cloudy.jpg', ]; backgroundId.push(id); bgIndex = backgroundId.sort().indexOf(id); $('body').css('background-image', 'url(' + backgroundImg[bgIndex] + ')'); iconClass = backgroundIcon[bgIndex]; //Get wind compass direction. If API returns null, assume 0 degrees. if (deg) { var index = Math.floor((deg / 22.5) + 0.5) % 16, compassDirections = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW', ], windDir = compassDirections[index]; } else { windDir = 'N'; } //determine F or C based on country and add temperature to the page. var fahrenheit = ['US', 'BS', 'BZ', 'KY', 'PL']; if (fahrenheit.indexOf(countryCode) > -1) { $('#temperature').text(temp + '° F'); } else { $('#temperature').text(tempC + '° C'); } //write final weather conditions and wind information to the page $('#wind-speed').html( '<i class="wi wi-wind wi-from-' + windDir.toLowerCase() + '"></i><br>' + windDir + ' ' + speed + ' knots'); $('#condition').html( '<i class="wi wi-' + iconClass + '"></i><br>' + condition); }) .fail(function(err) { alert('There was an error retrieving your weather data. \n' + 'Please try again later.'); }); } //toggle between celsius / fahrenheit $('#convert-button').click(function() { if ($('#temperature').text().indexOf('F') > -1) { $('#temperature').text(tempC + '° C'); } else { $('#temperature').text(temp + '° F'); } this.blur(); // remove focus from the button }); var callback = '&APPID=9b67d777fb8343a987c5f7c6a2ed149b';
var Game = function (game) {}; //Whatever you touch here touch // socket.on('requestedPlayer') // server function player //game player = function var Player = (function () { function Player(x, y, uuid, scale, spritetype) { this.x = x; this.y = y; this.uuid = uuid; this.scale = scale; this.skin = 0; this.name = "defaultClient"; this.health = 0; } return Player; }()); var text; //Player coordinates DEBUG var coordString; //Player object var mPlayer = {}; //Arrays for players and sprites var players = []; var playerSprites = []; //Array for item collection var collectables = []; var collectableUpdates = []; var collectablesInit = false; var playerInitLocation = false; var rightAttack , leftAttack; var isAttackingRight = false; var isAttackingLeft = false; var gameWidth = 800; var gameHeight = 600; ///////////////////////////////////////// // SOCKET.IO // //////////////////////////////////////// /* * @params player object from server * Get intial player obejct */ //Whatever you touch here touch // socket.on('requestedPlayer') // server function player //game player = function socket.on('requestedPlayer', function (data) { mPlayer.x = data.x; mPlayer.y = data.y; mPlayer.scale = data.scale; mPlayer.uuid = data.uuid; mPlayer.skin = data.skin; mPlayer.name = data.name; mPlayer.health = data.health; console.log("Should have received my player data"); console.log(mPlayer.x); console.log(mPlayer.y); console.log(mPlayer.scale); console.log(mPlayer.name); }); /* * @params Get array of current players on server */ socket.on('requestedServerPlayers' , function(v){ //Assign array value from server players = v; console.log('Players in the server: '); for (var i = 0 ; i < players.length ; i++) { console.log(players[i].uuid); } }); /* * Receive initial collectables */ socket.on('requestedCollectables' , function(data) { collectables = data; }); /* * @params player object from server * new player joins add user to array add spriteRef */ socket.on('newUser' , function(join) { players.push(join); var i = playerSprites.length; if (players[i].skin == 1) { var newPlayer = game.add.sprite(players[i].x, players[i].y, 'knight'); newPlayer.animations.add('idle', Phaser.Animation.generateFrameNames('RightIdle', 1, 4), 2, true); newPlayer.animations.play('idle'); } if (players[i].skin == 2) { var newPlayer = game.add.sprite(players[i].x, players[i].y, 'knight' , 'RightIdle1.png'); newPlayer.animations.add('idle', Phaser.Animation.generateFrameNames('RightIdle', 1, 4), 2, true); newPlayer.animations.play('idle'); } playerSprites.push(newPlayer); playerSprites[i].anchor.setTo(0.5); players[players.length - 1].spriteRef = i; console.log('Player Joined, UUID: ' + join.uuid); //this.obstacleGroup.add(newPlayer); }); /* * @params updatesArray from server * Get all update events (locations/ probably change for more events * velocity attacking) ? */ socket.on('updateEvents' , function(updates) { //console.log('updates'); for (var i = 0 ; i < updates.length ; i++) { //Get User's position from server and checks against self if (updates[i].uuid == mPlayer.uuid) { mPlayer.x = updates[i].x; mPlayer.y = updates[i].y; mPlayer.scale = updates[i].scale; } // If not self update players array else { for (v = 0 ; v < players.length ; v++ ) { if (updates[i].uuid == players[v].uuid) { players[v].x = updates[i].x; players[v].y = updates[i].y; players[v].scale = updates[i].scale; } } } } //wipe updates updates = []; }); //kill player socket.on('playerKilled', function(data) { //on death kill and wipe all data //send to gamveover }); /* * @params socketId * Handle players disconnect */ socket.on('disconnect', function(socketId){ for (i = 0 ; i < players.length ; i++) { //Check socketId with array of socketIds if (players[i].uuid == socketId) { //Get ref to sprite and kill it from array playerSprites[players[i].spriteRef].body = null; playerSprites[players[i].spriteRef].destroy(); playerSprites.splice(players[i].spriteRef , 1); players.splice(i ,1); } } }); /* * Get updates of collectable items */ socket.on('collectableUpdates' , function(inCollectableUpdate) { collectableUpdates = inCollectableUpdate; }); /* * Game goodies */ Game.prototype = { preload: function () { //this.game.plugins.add(new Phaser.Plugin.Isometric(this.game)); game.physics.startSystem(Phaser.Physics.ARCADE); //this.game.anchor.setTo(0.5); //this.game.scale.refresh(); game.scale.minWidth = 240; game.scale.minHeight = 170; game.scale.maxWidth = 7000; game.scale.maxHeight = 4000; game.world.setBounds(0, 0, 20000, 20000); game.time.advancedTiming = true; //game.time.desiredFps = 60; game.renderer.renderSession.roundPixels = true; /* while (collectables.length == 0) { this.sleep(3000); } */ //setInterval(function() { if (collectables.length == 0) { console.log('waiting'); } }, 3000); /* do{ console.log("Waiting..."); }while (players.length == 0); */ console.log("spriteSelector: " + spriteSelector); }, create: function () { game.stage.backgroundColor = "0xde6712"; cursors = game.input.keyboard.createCursorKeys(); var tileSprites = game.add.tileSprite(100 , 100 , 19500, 19500, 'tile'); ////////////////////////// /// GUI /// ////////////////////////// var healthbar = game.add.sprite(20 , 20 , 'UI_HealthBar'); var expbar = game.add.sprite(20 , healthbar.height * 2 , 'UI_ExpBar' ); healthbar.fixedToCamera = true; expbar.fixedToCamera = true; var style = { font: 'bold 15pt Arial', fill: 'black', align: 'center'}; var startGame = game.add.text ( 0 , (window.innerHeight / 2) ,"Leaderboard" , style ); startGame.fixedToCamera = true; startGame.cameraOffset.x = 100; obstacleGroup = game.add.group(); playerGroup = game.add.group(); //FOLLOW LEGEND FOR SPRITE NUMBERS IN TitleScreen if (spriteSelector == 1){ //charSprite = game.add.sprite(0, 0, 'dragon' , playerGroup); charSprite = game.add.sprite(0, 0, 'knight' , 'RightIdle1'); charSprite.animations.add('right_idle', Phaser.Animation.generateFrameNames('RightIdle', 1, 4), 20, true); charSprite.animations.add('left_idle', Phaser.Animation.generateFrameNames('LeftIdle', 1, 4), 20, true); charSprite.animations.add('right_walk', Phaser.Animation.generateFrameNames('RightWalk', 1, 4), 20, true); charSprite.animations.add('left_walk', Phaser.Animation.generateFrameNames('LeftWalk', 1, 4), 20, true); charSprite.animations.play('right_idle'); } if (spriteSelector == 2){ //charSprite = game.add.sprite(0, 0, 'dragon' , playerGroup); charSprite = game.add.sprite(0, 0, 'knight' , 'RightIdle1'); charSprite.animations.add('right_idle', Phaser.Animation.generateFrameNames('RightIdle', 1, 4), 20, true); charSprite.animations.add('left_idle', Phaser.Animation.generateFrameNames('LeftIdle', 1, 4), 20, true); charSprite.animations.add('right_walk', Phaser.Animation.generateFrameNames('RightWalk', 1, 4), 20, true); charSprite.animations.add('left_walk', Phaser.Animation.generateFrameNames('LeftWalk', 1, 4), 20, true); charSprite.animations.play('right_idle'); } charSprite.anchor.setTo( 0.5 ); game.physics.enable(charSprite, Phaser.Physics.ARCADE); charSprite.enableBody = true; charSprite.body.moves = false; charSprite.body.collideWorldBounds = true; //to ensure that socket game has received initial players from server check if array is empty //if so give em life! if (playerSprites.length == 0 ) { this.createLivePlayers(); } //init collectables to ensure they do not draw before loaded //change after game state is impl if (collectablesInit == false) { collectablesInit = true; temp = collectables; collectables = []; for (var i = 0 ; i < temp.length ; i++) { var collectable = game.add.sprite(temp[i].x , temp[i].y, 'gem', obstacleGroup); collectable.anchor.setTo(0.5); game.physics.enable(collectable, Phaser.Physics.ARCADE); collectable.body.moves = false; collectables.push(collectable); obstacleGroup.add(collectables[i]); } } if (playerInitLocation == false) { charSprite.position.setTo(mPlayer.x , mPlayer.y , 0); playerInitLocation = true; } this.createAttackButtons(); coordString = "( " + mPlayer.x + " , " + mPlayer.y + ")"; text = game.add.text(0, 20, coordString, { font: "14px Arial", fill: "#00ff00", align: "center" }); GUI_PlayerHealth = game.add.text(window.innerWidth / 2, window.innerHeight / 2, mPlayer.health, { font: "15px Arial", fill: "#ffffff", align: "center" }); text.fixedToCamera = true; game.camera.follow(charSprite, Phaser.Camera.FOLLOW_LOCKON); }, update: function () { //game.world.bringToTop(obstacleGroup); if (game.physics.arcade.collide(charSprite, obstacleGroup, this.collisionHandler, null, this.game)) { console.log('boom'); } //collision with mPlayer hitboxes and /* if (game.physics.arcade.collide(charSprite, obstacleGroup, this.collisionHandler, null, this.game)) { console.log('boom'); } */ //game.scale.setGameSize((gameWidth + (mPlayer.scale * 500)) , (gameHeight + (mPlayer.scale * 500))); /* * INPUT DETECTION */ game.input.update(); if (cursors.down.isDown) { this.down(); charSprite.y += 3; charSprite.x += 3; } if (cursors.up.isDown) { this.up(); charSprite.y -= 3; charSprite.x -= 3; } if (cursors.left.isDown) { this.left(); charSprite.x -= 3; charSprite.y += 3; charSprite.animations.play('left_walk'); } if (cursors.right.isDown) { this.right(); charSprite.x += 3; charSprite.y -= 3; charSprite.animations.play('right_walk'); } if (isAttackingRight) { rightAttack.exists = false; } if (isAttackingLeft) { leftAttack.exists = false; } if (attackbutton.isDown && cursors.right.isDown) { console.log('ATTACK FUCKER!!!'); rightAttack.exists = true; isAttackingRight = true; } if (attackbutton.isDown && cursors.left.isDown) { console.log('ATTACK FUCKER!!!'); leftAttack.exists = true; isAttackingLeft = true; } /* if hitbox.exists { if (game.physics.arcade.collide(charSprite, hitboxes, this.collisionHandler, null, this.game)) { console.log('boom'); } } */ //Handle directional idling after movement is complete. if ((cursors.right.isDown != true && cursors.left.isDown != true) && charSprite.animations.currentAnim.name == 'left_walk'){ charSprite.animations.play('left_idle'); } if ((cursors.right.isDown != true && cursors.left.isDown != true) && charSprite.animations.currentAnim.name == 'right_walk'){ charSprite.animations.play('right_idle'); } if (cursors.down.isDown == true && charSprite.animations.currentAnim.name == 'left_idle'){ charSprite.animations.play('left_walk'); } if (cursors.down.isDown == true && charSprite.animations.currentAnim.name == 'right_idle'){ charSprite.animations.play('right_walk'); } if (playerSprites.length > 0) { //Possibly throttle data by only working with changes from previous states for (var p = 0 ; p < players.length ; p++) { /* Do i need to check for undefined? if (typeof playerSprites[p] != 'undefined'){ playerSprites[p].isoPosition.setTo(players[p].x , players[p].y, 0); } */ playerSprites[players[p].spriteRef].position.setTo(players[p].x, players[p].y, 0); playerSprites[players[p].spriteRef].scale.setTo(players[p].scale, players[p].scale); } } charSprite.scale.setTo(mPlayer.scale, mPlayer.scale); text.setText("( " + mPlayer.x + " , " + mPlayer.y + ")" ); GUI_PlayerHealth.x = charSprite.x - (charSprite.width / 2); GUI_PlayerHealth.y = charSprite.y + 16;; }, render: function () { game.debug.text('render FPS: ' + (game.time.fps || '--') , 2, 14, "#00ff00"); //game.debug.body(charSprite); //this.obstacleGroup.forEach(function (tile) { // game.debug.body(tile, 'rgba(189, 221, 235, 0.6)', false); // }); //debug attack boxes /* if (leftAttack.exists = true) { game.debug.body(leftAttack); } if (rightAttack.exists = true) { game.debug.body(rightAttack); } */ }, collisionHandler: function (colChar, colCollectable) { var collectableCollisionEvent = {playerX: colChar.x, playerY: colChar.y, uuid: mPlayer.uuid, collectableX: colCollectable.x, collectableY: colCollectable.y} console.log(colCollectable.x + " " + colCollectable.y); socket.emit('collectableCollision' , collectableCollisionEvent); colCollectable.destroy(); }, // ADD TO OBSTACLE GROUP // MAKE OBSTACLE GROUP FOR JUST PLAYERS createLivePlayers: function() { if (players.length != 0) { for (i = 0 ; i < players.length ; i++) { if (players[i].skin == 1) { var newPlayer = game.add.sprite(players[i].x, players[i].y, 'knight'); newPlayer.animations.add('idle', Phaser.Animation.generateFrameNames('RightIdle', 1, 4), 2, true); newPlayer.animations.play('idle'); } if (players[i].skin == 2) { var newPlayer = game.add.sprite(players[i].x, players[i].y, 'knight'); newPlayer.animations.add('idle', Phaser.Animation.generateFrameNames('RightIdle', 1, 4), 2, true); newPlayer.animations.play('idle'); } tempChar.anchor.setTo(0.5); playerSprites[i] = tempChar; //Assign the sprite ref to keep track of index in SpriteRef [] players[i].spriteRef = i; } } }, createAttackButtons: function () { hitboxes = game.add.group(); hitboxes.enableBody = true; charSprite.addChild(hitboxes); rightAttack = hitboxes.create(0,0,'rightAttack' , 0, false); rightAttack.body.setSize(50, 50, charSprite.width, charSprite.height / 2); rightAttack.name = "rightAttack"; leftAttack = hitboxes.create(0,0,'leftAttack' , 0, false); leftAttack.body.setSize(50, 50, charSprite.width, charSprite.height / 2); leftAttack.name = "leftAttack"; attackbutton = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR); }, ///////////////////////////////// /// /// /// /// /// MOVEMENT /// /// /// /// /// ///////////////////////////////// left: function () { socket.emit('update' , 'moveLeft'); }, right: function () { socket.emit('update' , 'moveRight'); }, up: function () { socket.emit('update' , 'moveUp'); }, down: function () { socket.emit('update' , 'moveDown'); }, };
var optimist = require('optimist'); var fs = require('fs'); var path = require('path'); var merge = require('deepmerge'); module.exports = function (configFile, argv) { if (Array.isArray(argv)) { argv = optimist.parse(argv); } else if (argv === undefined) { argv = optimist.argv; } delete argv.$0; delete argv._; if (!path.existsSync(configFile)) { return argv; } else { var body = fs.readFileSync(configFile); var config = JSON.parse(body); return merge(config, argv); } };
/** * @author Eberhard Graether / http://egraether.com/ * @author Mark Lundin / http://mark-lundin.com */ THREE.TrackballControls = function(object, domElement) { var _this = this; var STATE = { NONE: -1, ROTATE: 0, ZOOM: 1, PAN: 2, TOUCH_ROTATE: 3, TOUCH_ZOOM_PAN: 4 }; this.object = object; this.domElement = (domElement !== undefined) ? domElement : document; // API this.enabled = true; this.screen = { left: 0, top: 0, width: 0, height: 0 }; this.rotateSpeed = 1.0; this.zoomSpeed = 1.2; this.panSpeed = 0.3; this.noRotate = false; this.noZoom = false; this.noPan = false; this.noRoll = false; this.staticMoving = false; this.dynamicDampingFactor = 0.2; this.minDistance = 0; this.maxDistance = Infinity; this.keys = [65 /*A*/ , 83 /*S*/ , 68 /*D*/ ]; // internals this.target = new THREE.Vector3(); var EPS = 0.000001; var lastPosition = new THREE.Vector3(); var _state = STATE.NONE, _prevState = STATE.NONE, _eye = new THREE.Vector3(), _rotateStart = new THREE.Vector3(), _rotateEnd = new THREE.Vector3(), _zoomStart = new THREE.Vector2(), _zoomEnd = new THREE.Vector2(), _touchZoomDistanceStart = 0, _touchZoomDistanceEnd = 0, _panStart = new THREE.Vector2(), _panEnd = new THREE.Vector2(); // for reset this.target0 = this.target.clone(); this.position0 = this.object.position.clone(); this.up0 = this.object.up.clone(); // events var changeEvent = { type: 'change' }; var startEvent = { type: 'start' }; var endEvent = { type: 'end' }; // methods this.handleResize = function() { if (this.domElement === document) { this.screen.left = 0; this.screen.top = 0; this.screen.width = window.innerWidth; this.screen.height = window.innerHeight; } else { var box = this.domElement.getBoundingClientRect(); // adjustments come from similar code in the jquery offset() function var d = this.domElement.ownerDocument.documentElement; this.screen.left = box.left + window.pageXOffset - d.clientLeft; this.screen.top = box.top + window.pageYOffset - d.clientTop; this.screen.width = box.width; this.screen.height = box.height; } }; this.handleEvent = function(event) { if (typeof this[event.type] == 'function') { this[event.type](event); } }; var getMouseOnScreen = (function() { var vector = new THREE.Vector2(); return function(pageX, pageY) { vector.set( (pageX - _this.screen.left) / _this.screen.width, (pageY - _this.screen.top) / _this.screen.height ); return vector; }; }()); var getMouseProjectionOnBall = (function() { var vector = new THREE.Vector3(); var objectUp = new THREE.Vector3(); var mouseOnBall = new THREE.Vector3(); return function(pageX, pageY) { mouseOnBall.set( (pageX - _this.screen.width * 0.5 - _this.screen.left) / (_this.screen.width * .5), (_this.screen.height * 0.5 + _this.screen.top - pageY) / (_this.screen.height * .5), 0.0 ); var length = mouseOnBall.length(); if (_this.noRoll) { if (length < Math.SQRT1_2) { mouseOnBall.z = Math.sqrt(1.0 - length * length); } else { mouseOnBall.z = .5 / length; } } else if (length > 1.0) { mouseOnBall.normalize(); } else { mouseOnBall.z = Math.sqrt(1.0 - length * length); } _eye.copy(_this.object.position).sub(_this.target); vector.copy(_this.object.up).setLength(mouseOnBall.y) vector.add(objectUp.copy(_this.object.up).cross(_eye).setLength(mouseOnBall.x)); vector.add(_eye.setLength(mouseOnBall.z)); return vector; }; }()); this.rotateCamera = (function() { var axis = new THREE.Vector3(), quaternion = new THREE.Quaternion(); return function() { var angle = Math.acos(_rotateStart.dot(_rotateEnd) / _rotateStart.length() / _rotateEnd.length()); if (angle) { axis.crossVectors(_rotateStart, _rotateEnd).normalize(); angle *= _this.rotateSpeed; quaternion.setFromAxisAngle(axis, -angle); _eye.applyQuaternion(quaternion); _this.object.up.applyQuaternion(quaternion); _rotateEnd.applyQuaternion(quaternion); if (_this.staticMoving) { _rotateStart.copy(_rotateEnd); } else { quaternion.setFromAxisAngle(axis, angle * (_this.dynamicDampingFactor - 1.0)); _rotateStart.applyQuaternion(quaternion); } } } }()); this.zoomCamera = function() { if (_state === STATE.TOUCH_ZOOM_PAN) { var factor = _touchZoomDistanceStart / _touchZoomDistanceEnd; _touchZoomDistanceStart = _touchZoomDistanceEnd; _eye.multiplyScalar(factor); } else { var factor = 1.0 + (_zoomEnd.y - _zoomStart.y) * _this.zoomSpeed; if (factor !== 1.0 && factor > 0.0) { _eye.multiplyScalar(factor); if (_this.staticMoving) { _zoomStart.copy(_zoomEnd); } else { _zoomStart.y += (_zoomEnd.y - _zoomStart.y) * this.dynamicDampingFactor; } } } }; this.panCamera = (function() { var mouseChange = new THREE.Vector2(), objectUp = new THREE.Vector3(), pan = new THREE.Vector3(); return function() { mouseChange.copy(_panEnd).sub(_panStart); if (mouseChange.lengthSq()) { mouseChange.multiplyScalar(_eye.length() * _this.panSpeed); pan.copy(_eye).cross(_this.object.up).setLength(mouseChange.x); pan.add(objectUp.copy(_this.object.up).setLength(mouseChange.y)); _this.object.position.add(pan); _this.target.add(pan); if (_this.staticMoving) { _panStart.copy(_panEnd); } else { _panStart.add(mouseChange.subVectors(_panEnd, _panStart).multiplyScalar(_this.dynamicDampingFactor)); } } } }()); this.checkDistances = function() { if (!_this.noZoom || !_this.noPan) { if (_eye.lengthSq() > _this.maxDistance * _this.maxDistance) { _this.object.position.addVectors(_this.target, _eye.setLength(_this.maxDistance)); } if (_eye.lengthSq() < _this.minDistance * _this.minDistance) { _this.object.position.addVectors(_this.target, _eye.setLength(_this.minDistance)); } } }; this.update = function() { _eye.subVectors(_this.object.position, _this.target); if (!_this.noRotate) { _this.rotateCamera(); } if (!_this.noZoom) { _this.zoomCamera(); } if (!_this.noPan) { _this.panCamera(); } _this.object.position.addVectors(_this.target, _eye); _this.checkDistances(); _this.object.lookAt(_this.target); if (lastPosition.distanceToSquared(_this.object.position) > EPS) { _this.dispatchEvent(changeEvent); lastPosition.copy(_this.object.position); } }; this.reset = function() { _state = STATE.NONE; _prevState = STATE.NONE; _this.target.copy(_this.target0); _this.object.position.copy(_this.position0); _this.object.up.copy(_this.up0); _eye.subVectors(_this.object.position, _this.target); _this.object.lookAt(_this.target); _this.dispatchEvent(changeEvent); lastPosition.copy(_this.object.position); }; // listeners function keydown(event) { if (_this.enabled === false) return; window.removeEventListener('keydown', keydown); _prevState = _state; if (_state !== STATE.NONE) { return; } else if (event.keyCode === _this.keys[STATE.ROTATE] && !_this.noRotate) { _state = STATE.ROTATE; } else if (event.keyCode === _this.keys[STATE.ZOOM] && !_this.noZoom) { _state = STATE.ZOOM; } else if (event.keyCode === _this.keys[STATE.PAN] && !_this.noPan) { _state = STATE.PAN; } } function keyup(event) { if (_this.enabled === false) return; _state = _prevState; window.addEventListener('keydown', keydown, false); } function mousedown(event) { if (_this.enabled === false) return; event.preventDefault(); event.stopPropagation(); if (_state === STATE.NONE) { _state = event.button; } if (_state === STATE.ROTATE && !_this.noRotate) { _rotateStart.copy(getMouseProjectionOnBall(event.pageX, event.pageY)); _rotateEnd.copy(_rotateStart); } else if (_state === STATE.ZOOM && !_this.noZoom) { _zoomStart.copy(getMouseOnScreen(event.pageX, event.pageY)); _zoomEnd.copy(_zoomStart); } else if (_state === STATE.PAN && !_this.noPan) { _panStart.copy(getMouseOnScreen(event.pageX, event.pageY)); _panEnd.copy(_panStart) } document.addEventListener('mousemove', mousemove, false); document.addEventListener('mouseup', mouseup, false); _this.dispatchEvent(startEvent); } function mousemove(event) { if (_this.enabled === false) return; event.preventDefault(); event.stopPropagation(); if (_state === STATE.ROTATE && !_this.noRotate) { _rotateEnd.copy(getMouseProjectionOnBall(event.pageX, event.pageY)); } else if (_state === STATE.ZOOM && !_this.noZoom) { _zoomEnd.copy(getMouseOnScreen(event.pageX, event.pageY)); } else if (_state === STATE.PAN && !_this.noPan) { _panEnd.copy(getMouseOnScreen(event.pageX, event.pageY)); } } function mouseup(event) { if (_this.enabled === false) return; event.preventDefault(); event.stopPropagation(); _state = STATE.NONE; document.removeEventListener('mousemove', mousemove); document.removeEventListener('mouseup', mouseup); _this.dispatchEvent(endEvent); } function mousewheel(event) { if (_this.enabled === false) return; event.preventDefault(); event.stopPropagation(); var delta = 0; if (event.wheelDelta) { // WebKit / Opera / Explorer 9 delta = event.wheelDelta / 40; } else if (event.detail) { // Firefox delta = -event.detail / 3; } _zoomStart.y += delta * 0.01; _this.dispatchEvent(startEvent); _this.dispatchEvent(endEvent); } function touchstart(event) { if (_this.enabled === false) return; switch (event.touches.length) { case 1: _state = STATE.TOUCH_ROTATE; _rotateStart.copy(getMouseProjectionOnBall(event.touches[0].pageX, event.touches[0].pageY)); _rotateEnd.copy(_rotateStart); break; case 2: _state = STATE.TOUCH_ZOOM_PAN; var dx = event.touches[0].pageX - event.touches[1].pageX; var dy = event.touches[0].pageY - event.touches[1].pageY; _touchZoomDistanceEnd = _touchZoomDistanceStart = Math.sqrt(dx * dx + dy * dy); var x = (event.touches[0].pageX + event.touches[1].pageX) / 2; var y = (event.touches[0].pageY + event.touches[1].pageY) / 2; _panStart.copy(getMouseOnScreen(x, y)); _panEnd.copy(_panStart); break; default: _state = STATE.NONE; } _this.dispatchEvent(startEvent); } function touchmove(event) { if (_this.enabled === false) return; event.preventDefault(); event.stopPropagation(); switch (event.touches.length) { case 1: _rotateEnd.copy(getMouseProjectionOnBall(event.touches[0].pageX, event.touches[0].pageY)); break; case 2: var dx = event.touches[0].pageX - event.touches[1].pageX; var dy = event.touches[0].pageY - event.touches[1].pageY; _touchZoomDistanceEnd = Math.sqrt(dx * dx + dy * dy); var x = (event.touches[0].pageX + event.touches[1].pageX) / 2; var y = (event.touches[0].pageY + event.touches[1].pageY) / 2; _panEnd.copy(getMouseOnScreen(x, y)); break; default: _state = STATE.NONE; } } function touchend(event) { if (_this.enabled === false) return; switch (event.touches.length) { case 1: _rotateEnd.copy(getMouseProjectionOnBall(event.touches[0].pageX, event.touches[0].pageY)); _rotateStart.copy(_rotateEnd); break; case 2: _touchZoomDistanceStart = _touchZoomDistanceEnd = 0; var x = (event.touches[0].pageX + event.touches[1].pageX) / 2; var y = (event.touches[0].pageY + event.touches[1].pageY) / 2; _panEnd.copy(getMouseOnScreen(x, y)); _panStart.copy(_panEnd); break; } _state = STATE.NONE; _this.dispatchEvent(endEvent); } this.domElement.addEventListener('contextmenu', function(event) { event.preventDefault(); }, false); this.domElement.addEventListener('mousedown', mousedown, false); this.domElement.addEventListener('mousewheel', mousewheel, false); this.domElement.addEventListener('DOMMouseScroll', mousewheel, false); // firefox this.domElement.addEventListener('touchstart', touchstart, false); this.domElement.addEventListener('touchend', touchend, false); this.domElement.addEventListener('touchmove', touchmove, false); window.addEventListener('keydown', keydown, false); window.addEventListener('keyup', keyup, false); this.handleResize(); // force an update at start this.update(); }; THREE.TrackballControls.prototype = Object.create(THREE.EventDispatcher.prototype); THREE.TrackballControls.prototype.constructor = THREE.TrackballControls;
// instafake.js // the hip way to to be.... var instafake = instafake || {}; instafake.blueprints = instafake.blueprints || {}; //classes and constructors instafake.active = instafake.active || {}; //instantiated objects // blueprints for models and collections instafake.blueprints.model = Backbone.Model.extend({ initialize: function() { console.log("a model is ready"); } }); instafake.blueprints.collection = Backbone.Collection.extend({ url: '/api/instafake', model: instafake.blueprints.model, initialize: function() { console.log("a collection is ready"); // first fetch once this is loaded this.fetch(); this.on('change', function() { // keeping my collection up to date with the server this.fetch(); }); } }); // Create (CRUD) instafake.create = function(username, post, description, hashtags) { if (!username || !post || !description || !hashtags) return false; instafake.active.photosCollection.create({ username: username, post: post, description: description, hashtags: hashtags }); return true; }; // blueprints for views instafake.blueprints.collectionView = Backbone.View.extend({ initialize: function() { this.$el = $('.instafakes'); this.render(); var that = this; this.collection.on('sync', function() { that.render(); }); }, render: function() { this.$el.html(''); var models = this.collection.models; for (var m in models) { var data = models[m]; new instafake.blueprints.modelView({ model: data }); } } }); instafake.blueprints.modelView = Backbone.View.extend({ initialize: function() { this.$el = $('.instafakes'); this.template = _.template($('#table-row-template').html()); this.render(); }, render: function() { var data = this.model.attributes; this.$el.append(this.template(data)); } }); // events/trigger/everything else $(document).ready(function() { instafake.active.photosCollection = new instafake.blueprints.collection(); instafake.active.photosCollectionView = new instafake.blueprints.collectionView({ collection: instafake.active.photosCollection }); $('#add-instafake').on('click', function(event) { event.preventDefault(); // grab real-time variables var username = $('#username').val(); var post = $('#post').val(); var description = $('#description').val(); var hashtags = $('#hashtags').val(); // use backbone collection to add to instafake.create(username, post, description, hashtags); }); $('#refresh-instafake').on('click', function() { instafake.active.photosCollection.fetch(); }) });
(function () { 'use strict'; /** * @ngdoc service * @name Api * @description * Service that contains the services which communicate with the server, which are automatically created from the endpoint schema received from the server */ function Api(Settings, $q, $http) { var loadingPromise, cachedPromises = {}; var service = { /** * @ngdoc property * @name Api#services * @propertyOf Api * @description * The individual services in an associative array * @var {Object} */ services: {}, /** * @ngdoc method * @name Api#load * @methodOf Api * @description * Load the endpoint schema from the server and create the services * * @returns {promise} */ load: function () { if (!loadingPromise) { var deferred = $q.defer(), originalPromise = $http({method: 'get', url: Settings.get('api.url') + 'schema/endpoints'}); originalPromise.then(function (response) { addSchemaEndpoints(response.data); deferred.resolve(); }, deferred.reject); loadingPromise = deferred.promise; } return loadingPromise; } }; /** * @ngdoc method * @name Api#injectSortingFromProperties * @methodOf Api * @access private * @description * Inject the variables required for sortable into the request array from the properties array passed by the user to the endpoint * * @param {Object} request * @param {Object} properties * @returns {void} */ function injectSortingFromProperties(request, properties) { if (properties.sortBy) { request.sortBy = properties.sortBy; if (properties.order) { request.order = properties.order; } } } /** * @ngdoc method * @name Api#injectPaginationFromProperties * @methodOf Api * @access private * @description * Inject the variables required for pagination into the request array from the properties array passed by the user to the endpoint * * @param {Object} request * @param {Object} properties * @returns {void} */ function injectPaginationFromProperties(request, properties) { if (properties.offset) { request.offset = properties.offset; } if (properties.limit) { request.limit = properties.limit; } } /** * @ngdoc method * @name Api#injectFiltersFromProperties * @methodOf Api * @access private * @description * Inject the variables required for adding filters into the request array from the properties array passed by the user to the endpoint * * @param {Object} request * @param {Object} properties * @returns {void} */ function injectFiltersFromProperties(request, properties) { var filterName, filterKey; if (properties.filters) { for (filterName in properties.filters) { filterKey = 'filters[' + filterName + ']'; request[filterKey] = properties.filters[filterName]; } } } /** * @ngdoc method * @name Api#parseUrlWithParameters * @methodOf Api * @access private * @description * Given an associative array with parameters passed by the user, parse the url for required variables and add them if they exist in the parameters. Remove them * from the parameters thereafter so that the remaining parameters may be passed in the data parameter of the http request * * @param {string} url * @param {Object} parameters * @returns {string} */ function parseUrlWithParameters(url, parameters) { var name, pattern, apiUrl = document.createElement('a'); for (name in parameters) { pattern = new RegExp('\:' + name, 'g'); if (url.match(pattern)) { url = url.replace(pattern, parameters[name]); delete parameters[name]; } } apiUrl.href = Settings.get('api.url'); return apiUrl.origin + url; } /** * @ngdoc method * @name Api#createCacheKey * @methodOf Api * @access private * @description * Create a unique cache key for the given endpoint name, using any number of name-value pairs passed as additional parameters to this function * * @param {string} name * @param {...} * @returns {string} */ function createCacheKey(name) { var index, argumentNumber, cacheKey = name; if (arguments.length > 1) { for (argumentNumber = 1; argumentNumber < arguments.length; argumentNumber++) { for (index in arguments[argumentNumber]) { cacheKey += '_' + index + ':' + arguments[argumentNumber][index]; } } } return cacheKey; } /** * @ngdoc method * @name Api#addEndpoint * @methodOf Api * @access private * @description * Add an endpoint function to the given schema object with the given name using the configuration provided. The following are the configuration keys that * are understood: * * - route: The route to use * - method: The method to use to communicate with the server (get) * - paginatable: Whether the endpoint allows for automatic paginating (undefined, falsy) * - sortable: Whether the endpoint allows for automatic sorting (undefined, falsy) * - filterable: Whether the endpoint allows for automatic filtering (undefined, falsy) * - cachable: Whether the endpoint may re-use the promise in order to provide a cache to prevent additional server calls (undefined, falsy) * * The result of this function is that the service will have a public method added with the requested name, of signature * parameters (object) - Request data * properties (object) - Endpoint-specific configuration * The method also contains a child method called clearCache() * * @param {string} schemaObject * @param {string} name * @param {Object} configuration * @returns {void} */ function addEndpoint(schemaObject, name, configuration) { service.services[schemaObject][name] = function(parameters, properties) { properties = properties || {}; parameters = parameters || {}; var cacheKey, method, request = {}, force = properties.force, translatedUrl; method = (configuration.method) ? configuration.method : 'get'; if (configuration.paginatable) { injectPaginationFromProperties(request, properties); } if (configuration.sortable) { injectSortingFromProperties(request, properties); } if (configuration.filterable && properties.filters) { injectFiltersFromProperties(request, properties); } cacheKey = createCacheKey(name, request, parameters); translatedUrl = parseUrlWithParameters(configuration.route, parameters); if (!cachedPromises[schemaObject] || !cachedPromises[schemaObject][cacheKey] || !configuration.cachable || force) { var originalPromise = $http({method: method, url: translatedUrl, params: request, data: parameters}); var deferred = $q.defer(); originalPromise.then(function (response) { var responseObject = {}; if (configuration.paginatable) { responseObject = { items: response.data.items, pagination: { offset: response.data.offset, limit: response.data.limit, total: response.data.total } }; } else { responseObject = response.data; } deferred.resolve(responseObject); }, deferred.reject); if (!cachedPromises[schemaObject]) { cachedPromises[schemaObject] = {}; } cachedPromises[schemaObject][cacheKey] = deferred.promise; } return cachedPromises[schemaObject][cacheKey]; }; service.services[schemaObject][name].clearCache = function () { var key; if (cachedPromises.hasOwnProperty(schemaObject)) { for (key in cachedPromises[schemaObject]) { if (key.indexOf(name) === 0) { delete cachedPromises[schemaObject][key]; return true; } } } return false; } } /** * @ngdoc method * @name Api#addSchemaEndpoints * @methodOf Api * @access private * @description * Add the endpoints received from the server to the service, to be parsed into services. Each individual service also receives a clearCaches function * to clear the future caches for all functions * * @param {Object} schemaEndpoints * @returns {void} */ function addSchemaEndpoints (schemaEndpoints) { var schemaObject, action, configuration; for (schemaObject in schemaEndpoints) { service.services[schemaObject] = {}; for (action in schemaEndpoints[schemaObject]) { configuration = schemaEndpoints[schemaObject][action]; addEndpoint(schemaObject, action, configuration); } service.services[schemaObject].clearCaches = function () { cachedPromises[schemaObject] = {}; } } } return service; } Api.$inject = [ 'Settings', '$q', '$http' ]; angular .module('angular-utilities') .service('Api', Api); })();
/** @constructor */ ScalaJS.c.scala_Predef$$eq$colon$eq$ = (function() { ScalaJS.c.java_lang_Object.call(this) }); ScalaJS.c.scala_Predef$$eq$colon$eq$.prototype = new ScalaJS.inheritable.java_lang_Object(); ScalaJS.c.scala_Predef$$eq$colon$eq$.prototype.constructor = ScalaJS.c.scala_Predef$$eq$colon$eq$; ScalaJS.c.scala_Predef$$eq$colon$eq$.prototype.tpEquals__Lscala_Predef$$eq$colon$eq = (function() { return ScalaJS.modules.scala_Predef().scala$Predef$$singleton$und$eq$colon$eq$f }); ScalaJS.c.scala_Predef$$eq$colon$eq$.prototype.readResolve__p1__O = (function() { return ScalaJS.modules.scala_Predef$$eq$colon$eq() }); ScalaJS.c.scala_Predef$$eq$colon$eq$.prototype.tpEquals__ = (function() { return this.tpEquals__Lscala_Predef$$eq$colon$eq() }); /** @constructor */ ScalaJS.inheritable.scala_Predef$$eq$colon$eq$ = (function() { /*<skip>*/ }); ScalaJS.inheritable.scala_Predef$$eq$colon$eq$.prototype = ScalaJS.c.scala_Predef$$eq$colon$eq$.prototype; ScalaJS.is.scala_Predef$$eq$colon$eq$ = (function(obj) { return (!(!((obj && obj.$classData) && obj.$classData.ancestors.scala_Predef$$eq$colon$eq$))) }); ScalaJS.as.scala_Predef$$eq$colon$eq$ = (function(obj) { if ((ScalaJS.is.scala_Predef$$eq$colon$eq$(obj) || (obj === null))) { return obj } else { ScalaJS.throwClassCastException(obj, "scala.Predef$$eq$colon$eq") } }); ScalaJS.isArrayOf.scala_Predef$$eq$colon$eq$ = (function(obj, depth) { return (!(!(((obj && obj.$classData) && (obj.$classData.arrayDepth === depth)) && obj.$classData.arrayBase.ancestors.scala_Predef$$eq$colon$eq$))) }); ScalaJS.asArrayOf.scala_Predef$$eq$colon$eq$ = (function(obj, depth) { if ((ScalaJS.isArrayOf.scala_Predef$$eq$colon$eq$(obj, depth) || (obj === null))) { return obj } else { ScalaJS.throwArrayCastException(obj, "Lscala.Predef$$eq$colon$eq;", depth) } }); ScalaJS.data.scala_Predef$$eq$colon$eq$ = new ScalaJS.ClassTypeData({ scala_Predef$$eq$colon$eq$: 0 }, false, "scala.Predef$$eq$colon$eq$", ScalaJS.data.java_lang_Object, { scala_Predef$$eq$colon$eq$: 1, scala_Serializable: 1, java_io_Serializable: 1, java_lang_Object: 1 }); ScalaJS.c.scala_Predef$$eq$colon$eq$.prototype.$classData = ScalaJS.data.scala_Predef$$eq$colon$eq$; ScalaJS.moduleInstances.scala_Predef$$eq$colon$eq = undefined; ScalaJS.modules.scala_Predef$$eq$colon$eq = (function() { if ((!ScalaJS.moduleInstances.scala_Predef$$eq$colon$eq)) { ScalaJS.moduleInstances.scala_Predef$$eq$colon$eq = new ScalaJS.c.scala_Predef$$eq$colon$eq$().init___() }; return ScalaJS.moduleInstances.scala_Predef$$eq$colon$eq }); //@ sourceMappingURL=Predef$$eq$colon$eq$.js.map
"use strict"; module.exports = { production: { options: { base: "./", css: [ "build/assets/css/main.css", ], dimensions: [ { width: 320, height: 480 }, { width: 768, height: 1024 }, { width: 1280, height: 960 } ], cache: false, inline: true, // @todo: research why extract does not work extract: true, minify: true, include: [ /^\.loader/, ], ignore: [ /select/, /.writing/, ".index .back-to-top" ], }, src: "build/index.html", dest: "build/index.html", } };
{ while (true) { let let_x = "let x"; return let_x; } }
import webpack from 'webpack'; import cssnano from 'cssnano'; import HtmlWebpackPlugin from 'html-webpack-plugin'; import ExtractTextPlugin from 'extract-text-webpack-plugin'; import config from '../config'; import _debug from 'debug'; const debug = _debug('app:webpack:config'); const paths = config.utils_paths; const { __DEV__, __PROD__, __TEST__ } = config.globals; debug('Create configuration.'); const webpackConfig = { name: 'client', target: 'web', devtool: config.compiler_devtool, resolve: { root: paths.client(), extensions: ['', '.js', '.jsx', '.json', '.css', '.scss', '.sass', '.svg'], }, module: {}, }; // ------------------------------------ // Entry Points // ------------------------------------ const APP_ENTRY_PATHS = [ paths.client('main.js'), ]; webpackConfig.entry = { app: __DEV__ ? APP_ENTRY_PATHS.concat(`webpack-hot-middleware/client?path=${config.compiler_public_path}__webpack_hmr`) : APP_ENTRY_PATHS, vendor: config.compiler_vendor, }; // ------------------------------------ // Bundle Output // ------------------------------------ webpackConfig.output = { filename: `[name].[${config.compiler_hash_type}].js`, path: paths.dist(), publicPath: config.compiler_public_path, }; // ------------------------------------ // Plugins // ------------------------------------ webpackConfig.plugins = [ new webpack.DefinePlugin(config.globals), new HtmlWebpackPlugin({ template: paths.client('index.html'), hash: false, favicon: paths.client('static/favicon.ico'), filename: 'index.html', inject: 'body', minify: { collapseWhitespace: true, }, }), ]; if (__DEV__) { debug('Enable plugins for live development (HMR, NoErrors).'); webpackConfig.plugins.push( new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin(), ); } else if (__PROD__) { debug('Enable plugins for production (OccurenceOrder, Dedupe & UglifyJS).'); webpackConfig.plugins.push( new webpack.optimize.OccurrenceOrderPlugin(), new webpack.optimize.DedupePlugin(), new webpack.optimize.UglifyJsPlugin({ compress: { unused: true, dead_code: true, warnings: false, }, }) ); } // Don't split bundles during testing, since we only want import one bundle if (!__TEST__) { webpackConfig.plugins.push( new webpack.optimize.CommonsChunkPlugin({ names: ['vendor'], }) ); } // ------------------------------------ // Pre-Loaders // ------------------------------------ /* [ NOTE ] We no longer use eslint-loader due to it severely impacting build times for larger projects. `npm run lint` still exists to aid in deploy processes (such as with CI), and it's recommended that you use a linting plugin for your IDE in place of this loader. If you do wish to continue using the loader, you can uncomment the code below and run `npm i --save-dev eslint-loader`. This code will be removed in a future release. webpackConfig.module.preLoaders = [{ test: /\.(js|jsx)$/, loader: 'eslint', exclude: /node_modules/ }] webpackConfig.eslint = { configFile: paths.base('.eslintrc'), emitWarning: __DEV__ } */ // ------------------------------------ // Loaders // ------------------------------------ // JavaScript / JSON webpackConfig.module.loaders = [ { test: /\.(js|jsx)$/, exclude: /node_modules/, loader: 'babel', query: { cacheDirectory: true, plugins: ['transform-runtime', 'flow-react-proptypes'], presets: ['es2015', 'react', 'stage-0'], }, }, { test: /\.json$/, loader: 'json', }, ]; // ------------------------------------ // Style Loaders // ------------------------------------ // We use cssnano with the postcss loader, so we tell // css-loader not to duplicate minimization. const BASE_CSS_LOADER = 'css?sourceMap&-minimize'; // Add any packge names here whose styles need to be treated as CSS modules. // These paths will be combined into a single regex. const PATHS_TO_TREAT_AS_CSS_MODULES = [ // 'react-toolbox', (example) ]; // If config has CSS modules enabled, treat this project's styles as CSS modules. if (config.compiler_css_modules) { PATHS_TO_TREAT_AS_CSS_MODULES.push( paths .client() .replace(/[\^\$\.\*\+\-\?\=\!\:\|\\\/\(\)\[\]\{\}\,]/g, '\\$&') // eslint-disable-line ); } const isUsingCSSModules = !!PATHS_TO_TREAT_AS_CSS_MODULES.length; const cssModulesRegex = new RegExp(`(${PATHS_TO_TREAT_AS_CSS_MODULES.join('|')})`); // Loaders for styles that need to be treated as CSS modules. if (isUsingCSSModules) { const cssModulesLoader = [ BASE_CSS_LOADER, 'modules', 'importLoaders=1', 'localIdentName=[name]__[local]___[hash:base64:5]', ].join('&'); webpackConfig.module.loaders.push({ test: /\.scss$/, include: cssModulesRegex, loaders: [ 'style', cssModulesLoader, 'postcss', 'sass?sourceMap', ], }); webpackConfig.module.loaders.push({ test: /\.css$/, include: cssModulesRegex, loaders: [ 'style', cssModulesLoader, 'postcss', ], }); } // Loaders for files that should not be treated as CSS modules. const excludeCSSModules = isUsingCSSModules ? cssModulesRegex : false; webpackConfig.module.loaders.push({ test: /\.scss$/, exclude: excludeCSSModules, loaders: [ 'style', BASE_CSS_LOADER, 'postcss', 'sass?sourceMap', ], }); webpackConfig.module.loaders.push({ test: /\.css$/, exclude: excludeCSSModules, loaders: [ 'style', BASE_CSS_LOADER, 'postcss', ], }); // ------------------------------------ // Style Configuration // ------------------------------------ webpackConfig.sassLoader = { includePaths: paths.client('styles'), }; webpackConfig.postcss = [ cssnano({ autoprefixer: { add: true, remove: true, browsers: ['last 2 versions'], }, discardComments: { removeAll: true, }, discardUnused: false, mergeIdents: false, reduceIdents: false, safe: true, sourcemap: true, }), ]; // File loaders /* eslint-disable */ webpackConfig.module.loaders.push( { test: /\.woff(\?.*)?$/, loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/font-woff', }, { test: /\.woff2(\?.*)?$/, loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/font-woff2', }, { test: /\.otf(\?.*)?$/, loader: 'file?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=font/opentype', }, { test: /\.ttf(\?.*)?$/, loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/octet-stream', }, { test: /\.eot(\?.*)?$/, loader: 'file?prefix=fonts/&name=[path][name].[ext]', }, { test: /\.svg(\?.*)?$/, loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=image/svg+xml', }, { test: /\.(png|jpg|gif)$/, loader: 'url?limit=8192', }, ); /* eslint-enable */ // ------------------------------------ // Finalize Configuration // ------------------------------------ // when we don't know the public path (we know it only when HMR is enabled [in development]) we // need to use the extractTextPlugin to fix this issue: // http://stackoverflow.com/questions/34133808/webpack-ots-parsing-error-loading-fonts/34133809#34133809 if (!__DEV__) { debug('Apply ExtractTextPlugin to CSS loaders.'); webpackConfig.module.loaders.filter((loader) => loader.loaders && loader.loaders.find((name) => /css/.test(name.split('?')[0])) ).forEach((loader) => { const [first, ...rest] = loader.loaders; loader.loader = ExtractTextPlugin.extract(first, rest.join('!')); Reflect.deleteProperty(loader, 'loaders'); }); webpackConfig.plugins.push( new ExtractTextPlugin('[name].[contenthash].css', { allChunks: true, }) ); } export default webpackConfig;
"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); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.BancoTransacao = void 0; const sequelize_typescript_1 = require("sequelize-typescript"); const BancoConta_1 = require("./BancoConta"); const BancoTipoTransacao_1 = require("./BancoTipoTransacao"); let BancoTransacao = class BancoTransacao extends sequelize_typescript_1.Model { }; __decorate([ sequelize_typescript_1.Column, __metadata("design:type", Number) ], BancoTransacao.prototype, "valor", void 0); __decorate([ sequelize_typescript_1.BelongsTo(() => BancoConta_1.BancoConta, { foreignKey: { allowNull: false, name: 'conta' } }), __metadata("design:type", BancoConta_1.BancoConta) ], BancoTransacao.prototype, "bancoTransacaoConta", void 0); __decorate([ sequelize_typescript_1.BelongsTo(() => BancoTipoTransacao_1.BancoTipoTransacao, { foreignKey: { allowNull: false, name: 'tipo' } }), __metadata("design:type", BancoTipoTransacao_1.BancoTipoTransacao) ], BancoTransacao.prototype, "bancoTransacaoTipo", void 0); BancoTransacao = __decorate([ sequelize_typescript_1.Table({ timestamps: true, createdAt: 'dataCriado', deletedAt: 'dataExcluido', updatedAt: 'dataAtualizado', paranoid: true, }) ], BancoTransacao); exports.BancoTransacao = BancoTransacao; //# sourceMappingURL=BancoTransacao.js.map
'use strict'; const app = require('./app'); const port = app.get('port'); const server = app.listen(process.env.PORT || 5000); server.on('listening', () => console.log(`Application started on http://${app.get('host')}:${port}`) );
var WindowManager = require('helper/WindowManager'); var Utils = require('helper/Utils'); var Cloud = require('ti.cloud'); exports['Create Checkin'] = function(evt) { var win = WindowManager.createWindow({ backgroundColor: 'white' }); var table = Ti.UI.createTableView({ backgroundColor: '#fff', top: 0, bottom: 0, color: 'black' }); table.addEventListener('click', function(evt) { if (evt.row.id) { var oldTitle = evt.row.title; evt.row.title = 'Checking in, please wait...'; Cloud.Checkins.create({ place_id: evt.row.id }, function(e) { evt.row.title = oldTitle; if (e.success) { alert('Checked in to ' + oldTitle + '!'); } else { Utils.error(e); } }); } }); win.add(table); function findPlaces(lat, lon) { Cloud.Places.search({ latitude: lat, longitude: lon }, function(e) { if (e.success) { if (e.places.length == 0) { table.setData([{ title: 'No Results!' }]); } else { var data = []; for (var i = 0, l = e.places.length; i < l; i++) { data.push(Ti.UI.createTableViewRow({ color: 'black', title: e.places[i].name, id: e.places[i].id })); } table.setData(data); } } else { Utils.error(e); } }); } function findMe() { table.setData([{ title: 'Geolocating...', color: 'black' }]); if (Ti.Geolocation) { Ti.Geolocation.purpose = 'To find nearby places.'; Ti.Geolocation.accuracy = Ti.Geolocation.ACCURACY_BEST; Ti.Geolocation.distanceFilter = 0; Ti.Geolocation.getCurrentPosition(function(e) { if (!e.success || e.error) { findPlaces(null, null); table.setData([{ title: 'GPS lost, looking nearby...' }]); } else { table.setData([{ title: 'Located, looking nearby...', color: 'black' }]); findPlaces(e.coords.latitude, e.coords.longitude); } }); } else { Cloud.Clients.geolocate(function(e) { if (e.success) { table.setData([{ title: 'Located, looking nearby...', color: 'black' }]); findPlaces(e.location.latitude, e.location.longitude); } else { findPlaces(null, null); table.setData([{ title: 'GPS lost, looking nearby...' }]); } }); } } win.addEventListener('open', findMe); return win; };
/* eslint-disable no-lonely-if */ let cx, cy, px, py, sx, sy; cx = cy = px = py = sx = sy = 0; // parseDataPath copy pasted from svgo // https://github.com/svg/svgo/blob/e4918ccdd1a2b5831defe0f00c1286744b479448/lib/path.js const argsCountPerCommand = { M: 2, m: 2, Z: 0, z: 0, L: 2, l: 2, H: 1, h: 1, V: 1, v: 1, C: 6, c: 6, S: 4, s: 4, Q: 4, q: 4, T: 2, t: 2, A: 7, a: 7 }; /** * @type {(c: string) => c is PathDataCommand} */ const isCommand = c => { return c in argsCountPerCommand; }; /** * @type {(c: string) => boolean} */ const isWsp = c => { const codePoint = c.codePointAt(0); return ( (codePoint === 0x20 || codePoint === 0x9 || codePoint === 0xd || codePoint === 0xa) ); }; /** * @type {(c: string) => boolean} */ const isDigit = c => { const codePoint = c.codePointAt(0); if (codePoint == null) { return false; } return 48 <= codePoint && codePoint <= 57; }; /** * @typedef {'none' | 'sign' | 'whole' | 'decimal_point' | 'decimal' | 'e' | 'exponent_sign' | 'exponent'} ReadNumberState */ /** * @type {(string: string, cursor: number) => [number, number | null]} */ const readNumber = (string, cursor) => { let i = cursor; let value = ''; let state = /** @type {ReadNumberState} */ ('none'); for (; i < string.length; i += 1) { const c = string[i]; if (c === '+' || c === '-') { if (state === 'none') { state = 'sign'; value += c; continue; } if (state === 'e') { state = 'exponent_sign'; value += c; continue; } } if (isDigit(c)) { if (state === 'none' || state === 'sign' || state === 'whole') { state = 'whole'; value += c; continue; } if (state === 'decimal_point' || state === 'decimal') { state = 'decimal'; value += c; continue; } if (state === 'e' || state === 'exponent_sign' || state === 'exponent') { state = 'exponent'; value += c; continue; } } if (c === '.') { if (state === 'none' || state === 'sign' || state === 'whole') { state = 'decimal_point'; value += c; continue; } } if (c === 'E' || c === 'e') { if ( state === 'whole' || state === 'decimal_point' || state === 'decimal' ) { state = 'e'; value += c; continue; } } break; } const number = Number.parseFloat(value); if (Number.isNaN(number)) { return [cursor, null]; } else { // step back to delegate iteration to parent loop return [i - 1, number]; } }; /** * @type {(string: string) => Array<PathDataItem>} */ const parsePathData = string => { /** * @type {Array<PathDataItem>} */ const pathData = []; /** * @type {null | PathDataCommand} */ let command = null; let args = /** @type {number[]} */ ([]); let argsCount = 0; let canHaveComma = false; let hadComma = false; for (let i = 0; i < string.length; i += 1) { const c = string.charAt(i); if (isWsp(c)) { continue; } // allow comma only between arguments if (canHaveComma && c === ',') { if (hadComma) { break; } hadComma = true; continue; } if (isCommand(c)) { if (hadComma) { return pathData; } if (command == null) { // moveto should be leading command if (c !== 'M' && c !== 'm') { return pathData; } } else { // stop if previous command arguments are not flushed if (args.length !== 0) { return pathData; } } command = c; args = []; argsCount = argsCountPerCommand[command]; canHaveComma = false; // flush command without arguments if (argsCount === 0) { pathData.push({ command, args }); } continue; } // avoid parsing arguments if no command detected if (command == null) { return pathData; } // read next argument let newCursor = i; let number = null; if (command === 'A' || command === 'a') { const position = args.length; if (position === 0 || position === 1) { // allow only positive number without sign as first two arguments if (c !== '+' && c !== '-') { [newCursor, number] = readNumber(string, i); } } if (position === 2 || position === 5 || position === 6) { [newCursor, number] = readNumber(string, i); } if (position === 3 || position === 4) { // read flags if (c === '0') { number = 0; } if (c === '1') { number = 1; } } } else { [newCursor, number] = readNumber(string, i); } if (number == null) { return pathData; } args.push(number); canHaveComma = true; hadComma = false; i = newCursor; // flush arguments when necessary count is reached if (args.length === argsCount) { pathData.push({ command, args }); // subsequent moveto coordinates are threated as implicit lineto commands if (command === 'M') { command = 'L'; } if (command === 'm') { command = 'l'; } args = []; } } return pathData; }; const apply = function(commands, doc) { // current point, control point, and subpath starting point cx = cy = px = py = sx = sy = 0; // run the commands for (let i = 0; i < commands.length; i++) { const { command, args } = commands[i]; if (typeof runners[command] === 'function') { runners[command](doc, args); } } }; const runners = { M(doc, a) { cx = a[0]; cy = a[1]; px = py = null; sx = cx; sy = cy; return doc.moveTo(cx, cy); }, m(doc, a) { cx += a[0]; cy += a[1]; px = py = null; sx = cx; sy = cy; return doc.moveTo(cx, cy); }, C(doc, a) { cx = a[4]; cy = a[5]; px = a[2]; py = a[3]; return doc.bezierCurveTo(...a); }, c(doc, a) { doc.bezierCurveTo( a[0] + cx, a[1] + cy, a[2] + cx, a[3] + cy, a[4] + cx, a[5] + cy ); px = cx + a[2]; py = cy + a[3]; cx += a[4]; return (cy += a[5]); }, S(doc, a) { if (px === null) { px = cx; py = cy; } doc.bezierCurveTo(cx - (px - cx), cy - (py - cy), a[0], a[1], a[2], a[3]); px = a[0]; py = a[1]; cx = a[2]; return (cy = a[3]); }, s(doc, a) { if (px === null) { px = cx; py = cy; } doc.bezierCurveTo( cx - (px - cx), cy - (py - cy), cx + a[0], cy + a[1], cx + a[2], cy + a[3] ); px = cx + a[0]; py = cy + a[1]; cx += a[2]; return (cy += a[3]); }, Q(doc, a) { px = a[0]; py = a[1]; cx = a[2]; cy = a[3]; return doc.quadraticCurveTo(a[0], a[1], cx, cy); }, q(doc, a) { doc.quadraticCurveTo(a[0] + cx, a[1] + cy, a[2] + cx, a[3] + cy); px = cx + a[0]; py = cy + a[1]; cx += a[2]; return (cy += a[3]); }, T(doc, a) { if (px === null) { px = cx; py = cy; } else { px = cx - (px - cx); py = cy - (py - cy); } doc.quadraticCurveTo(px, py, a[0], a[1]); px = cx - (px - cx); py = cy - (py - cy); cx = a[0]; return (cy = a[1]); }, t(doc, a) { if (px === null) { px = cx; py = cy; } else { px = cx - (px - cx); py = cy - (py - cy); } doc.quadraticCurveTo(px, py, cx + a[0], cy + a[1]); cx += a[0]; return (cy += a[1]); }, A(doc, a) { solveArc(doc, cx, cy, a); cx = a[5]; return (cy = a[6]); }, a(doc, a) { a[5] += cx; a[6] += cy; solveArc(doc, cx, cy, a); cx = a[5]; return (cy = a[6]); }, L(doc, a) { cx = a[0]; cy = a[1]; px = py = null; return doc.lineTo(cx, cy); }, l(doc, a) { cx += a[0]; cy += a[1]; px = py = null; return doc.lineTo(cx, cy); }, H(doc, a) { cx = a[0]; px = py = null; return doc.lineTo(cx, cy); }, h(doc, a) { cx += a[0]; px = py = null; return doc.lineTo(cx, cy); }, V(doc, a) { cy = a[0]; px = py = null; return doc.lineTo(cx, cy); }, v(doc, a) { cy += a[0]; px = py = null; return doc.lineTo(cx, cy); }, Z(doc) { doc.closePath(); cx = sx; return (cy = sy); }, z(doc) { doc.closePath(); cx = sx; return (cy = sy); } }; const solveArc = function(doc, x, y, coords) { const [rx, ry, rot, large, sweep, ex, ey] = coords; const segs = arcToSegments(ex, ey, rx, ry, large, sweep, rot, x, y); for (let seg of segs) { const bez = segmentToBezier(...seg); doc.bezierCurveTo(...bez); } }; // from Inkscape svgtopdf, thanks! const arcToSegments = function(x, y, rx, ry, large, sweep, rotateX, ox, oy) { const th = rotateX * (Math.PI / 180); const sin_th = Math.sin(th); const cos_th = Math.cos(th); rx = Math.abs(rx); ry = Math.abs(ry); px = cos_th * (ox - x) * 0.5 + sin_th * (oy - y) * 0.5; py = cos_th * (oy - y) * 0.5 - sin_th * (ox - x) * 0.5; let pl = (px * px) / (rx * rx) + (py * py) / (ry * ry); if (pl > 1) { pl = Math.sqrt(pl); rx *= pl; ry *= pl; } const a00 = cos_th / rx; const a01 = sin_th / rx; const a10 = -sin_th / ry; const a11 = cos_th / ry; const x0 = a00 * ox + a01 * oy; const y0 = a10 * ox + a11 * oy; const x1 = a00 * x + a01 * y; const y1 = a10 * x + a11 * y; const d = (x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0); let sfactor_sq = 1 / d - 0.25; if (sfactor_sq < 0) { sfactor_sq = 0; } let sfactor = Math.sqrt(sfactor_sq); if (sweep === large) { sfactor = -sfactor; } const xc = 0.5 * (x0 + x1) - sfactor * (y1 - y0); const yc = 0.5 * (y0 + y1) + sfactor * (x1 - x0); const th0 = Math.atan2(y0 - yc, x0 - xc); const th1 = Math.atan2(y1 - yc, x1 - xc); let th_arc = th1 - th0; if (th_arc < 0 && sweep === 1) { th_arc += 2 * Math.PI; } else if (th_arc > 0 && sweep === 0) { th_arc -= 2 * Math.PI; } const segments = Math.ceil(Math.abs(th_arc / (Math.PI * 0.5 + 0.001))); const result = []; for (let i = 0; i < segments; i++) { const th2 = th0 + (i * th_arc) / segments; const th3 = th0 + ((i + 1) * th_arc) / segments; result[i] = [xc, yc, th2, th3, rx, ry, sin_th, cos_th]; } return result; }; const segmentToBezier = function(cx, cy, th0, th1, rx, ry, sin_th, cos_th) { const a00 = cos_th * rx; const a01 = -sin_th * ry; const a10 = sin_th * rx; const a11 = cos_th * ry; const th_half = 0.5 * (th1 - th0); const t = ((8 / 3) * Math.sin(th_half * 0.5) * Math.sin(th_half * 0.5)) / Math.sin(th_half); const x1 = cx + Math.cos(th0) - t * Math.sin(th0); const y1 = cy + Math.sin(th0) + t * Math.cos(th0); const x3 = cx + Math.cos(th1); const y3 = cy + Math.sin(th1); const x2 = x3 + t * Math.sin(th1); const y2 = y3 - t * Math.cos(th1); return [ a00 * x1 + a01 * y1, a10 * x1 + a11 * y1, a00 * x2 + a01 * y2, a10 * x2 + a11 * y2, a00 * x3 + a01 * y3, a10 * x3 + a11 * y3 ]; }; class SVGPath { static apply(doc, path) { const commands = parsePathData(path); apply(commands, doc); } } export default SVGPath;
import {ref} from '../config/constants' export const request = (props,type="add") => { ref.child(`request/${props.sellerId}`) .transaction(data => { data = JSON.parse(data); if (data === null) data = {} if (type === 'add') { if (typeof data.tot === 'undefined') data.tot = 1; else data.tot = (data.tot || 0) + 1; if (typeof data.props === 'undefined') data.props = [props]; else data.props.push(props); } else { data.props = []; data.tot = 0; } // return data; return JSON.stringify(data) }) } export const listenRequest = (_sellerId, callback) => { ref.child(`request/${_sellerId}`) .on('value', callback); }
'use strict' //===================================// //========== Export Module ==========// //===================================// module.exports = { setDirection: (direction, negate) => { let n = negate ? -1 : 1; switch (direction) { case 'center': pilot.dx = 0.0; pilot.dy = 0.0; break; case 'up': pilot.dx = 0.0; pilot.dy = PILOT_DELTA_XY * n; break; case 'right': pilot.dx = -PILOT_DELTA_XY * n; pilot.dy = 0.0; break; case 'down': pilot.dx = 0.0; pilot.dy = -PILOT_DELTA_XY * n; break; case 'left': pilot.dx = PILOT_DELTA_XY * n; pilot.dy = 0.0; break; default: break; } }, onEnergy: energy => { let currentSpeed = (targetSpeed - PILOT_DELTA_Z_MIN) / (PILOT_DELTA_Z_MAX - PILOT_DELTA_Z_MIN); if (energy !== 0) { currentSpeed += (energy === jumpEnergyList[progress] ? 1 : -1) * 0.33; if (currentSpeed < 0) currentSpeed = 0; if (currentSpeed > 1) currentSpeed = 1; } else { currentSpeed *= 0.95; } targetSpeed = currentSpeed * (PILOT_DELTA_Z_MAX - PILOT_DELTA_Z_MIN) + PILOT_DELTA_Z_MIN; }, tryToJump: onProgressChange => { if (PILOT_MAX_Z - pilot.z > PILOT_JUMP_Z) { progress++; onProgressChange(progress); resetVariables(); } } } //=======================================// //========== Pilot Phaser Game ==========// //=======================================// // Require Phaser window.PIXI = require('phaser-ce/build/custom/pixi'); window.p2 = require('phaser-ce/build/custom/p2'); window.Phaser = require('phaser-ce/build/custom/phaser-split'); // Create the game const game = new Phaser.Game( { parent: 'game-element', renderer: Phaser.AUTO, scaleMode: Phaser.ScaleManager.SHOW_ALL, width: 256, height: 192, crisp: true, roundPixels: true, antialias: false, transparent: false, state: { preload: preload, create: create, update: update, render: render } }); // Game constants const TWO_PI = 2.0 * Math.PI; const PILOT_DELTA_Z_MIN = 0.1; const PILOT_DELTA_Z_MAX = 4; const PILOT_DELTA_XY = 120; const PILOT_MAX_Z = 1000; const PILOT_JUMP_Z = 100; const PILOT_TUNNEL_ATTRACTION = 4; const PILOT_TUNNEL_FRICTION = 1; const PILOT_CROSS_WIDTH = 30; const PILOT_CROSS_HEIGHT = 20; const TUNNEL_RADIUS = 120; const TUNNEL_DELTA_Z = 2; const TUNNEL_CURVE_DEPTH = 2; const TUNNEL_NUM_OF_CIRCLES = 15; // Game variables let graphics; let previousFrameTime; let targetSpeed = 0; let progress = 0; let jumpEnergyList = [2, 5, 6]; let jumpColorList = jumpEnergyList.map(energy => Array(3).fill(null).map((bit, index) => (energy >> index) % 2)); let jumpText = null; let lowOnEnergyText = null; let pilot = { // Position x: 0, y: 0, z: 0, // Speed dx: 0, dy: 0, dz: 0 }; let tunnel = { // Position x: 0, y: 0, // Curve phase px: 0, py: 0 }; // Reset variables to beginning of the tunnel function resetVariables() { targetSpeed = PILOT_DELTA_Z_MIN; pilot.x = pilot.y = pilot.z = 0; pilot.dx = pilot.dy = 0; pilot.dz = PILOT_DELTA_Z_MIN; tunnel.x = 3; tunnel.y = 2; tunnel.px = tunnel.py = 0; } /* * The preload method is called first. Normally you'd use this to load your game assets * (or those needed for the current State). You shouldn't create any objects in this method * that require assets that you're also loading in this method, as they won't yet be available. */ function preload() { } /* * The create method is called once preload has completed, this includes the loading of any assets from the Loader. * If you don't have a preload method then create is the first method called in your State. */ function create() { // Create graphics instance graphics = game.add.graphics(0, 0); // Set previous frame time in seconds previousFrameTime = Date.now() / 1000.0; // Reset remaining game variables resetVariables(); } /* * The update method is left empty for your own use. It is called during the core game loop AFTER debug, * physics, plugins and the Stage have had their preUpdate methods called. It is called BEFORE Stage, * Tweens, Sounds, Input, Physics, Particles and Plugins have had their postUpdate methods called. */ function update() { // Clear graphics graphics.clear(); // Update times in seconds let currentTime = Date.now() / 1000.0; let frameTime = currentTime - previousFrameTime; previousFrameTime = currentTime; // Update pilot position (x,y) and forward speed (delta-z) { let tunnelAttraction = PILOT_TUNNEL_ATTRACTION * pilot.dz * frameTime; let nx = pilot.x + pilot.dx * frameTime + tunnel.x * tunnelAttraction; let ny = pilot.y + pilot.dy * frameTime + tunnel.y * tunnelAttraction; let absPos = Math.sqrt(nx * nx + ny * ny); let acceleration = 1.0 + PILOT_TUNNEL_FRICTION * frameTime; if (absPos < TUNNEL_RADIUS) { pilot.x = nx; pilot.y = ny; if (pilot.dz !== targetSpeed) { if (pilot.dz > targetSpeed) pilot.dz /= acceleration; else pilot.dz *= acceleration; if (pilot.dz < PILOT_DELTA_Z_MIN) pilot.dz = PILOT_DELTA_Z_MIN; if (pilot.dz > PILOT_DELTA_Z_MAX) pilot.dz = PILOT_DELTA_Z_MAX; } } else { if (pilot.dz > PILOT_DELTA_Z_MIN) pilot.dz /= acceleration; } } // Update pilot forward position (z) and tunnel position (x,y) { let deltaZ = pilot.dz * frameTime / Math.sqrt(TUNNEL_DELTA_Z); pilot.z = (pilot.z - deltaZ + PILOT_MAX_Z) % PILOT_MAX_Z; tunnel.px = (tunnel.px + 0.023 * deltaZ) % TWO_PI; tunnel.py = (tunnel.py + 0.029 * deltaZ) % TWO_PI; tunnel.x = Math.sin(tunnel.px) * TUNNEL_CURVE_DEPTH; tunnel.y = Math.sin(tunnel.py) * TUNNEL_CURVE_DEPTH; } // Draw tunnel circles { let modPilotZ = pilot.z % 1.0; let amplitudeZ = TUNNEL_DELTA_Z * TUNNEL_NUM_OF_CIRCLES; let centerX = game.world.centerX; let centerY = game.world.centerY; let jumpColor = jumpColorList[progress]; for (let i = TUNNEL_NUM_OF_CIRCLES - 1; i >= 0; --i) { let f = (i + modPilotZ) / TUNNEL_NUM_OF_CIRCLES; let z = f * f * amplitudeZ; let c = 1.0 - f; let range = pilot.z >= i && pilot.z < i + PILOT_MAX_Z - PILOT_JUMP_Z; let color = range ? jumpColor.map(e => e * c) : [c, c, c]; let x = centerX + pilot.x / z + tunnel.x * z; let y = centerY + pilot.y / z + tunnel.y * z; let d = TUNNEL_RADIUS * 2.0 / z; graphics.lineStyle(1 + 3 / z, Phaser.Color.RGBArrayToHex(color), 1); graphics.drawCircle(x, y, d); } } // Draw pilot cross { let x = game.world.centerX; let y = game.world.centerY; let c = pilot.dz / PILOT_DELTA_Z_MAX * 0.7 + 0.3; graphics.lineStyle(2, Phaser.Color.RGBArrayToHex([c, c, c]), 1); graphics.moveTo(x - PILOT_CROSS_WIDTH, y); graphics.lineTo(x + PILOT_CROSS_WIDTH, y); graphics.moveTo(x, y - PILOT_CROSS_HEIGHT); graphics.lineTo(x, y + PILOT_CROSS_HEIGHT); } // Draw text { if (PILOT_MAX_Z - pilot.z > PILOT_JUMP_Z) { if (jumpText == null) { jumpText = game.add.text(game.world.centerX, game.world.centerY - 30, "JUMP!", { font: "32px Arial", fill: "#fff", align: "center" }); jumpText.anchor.setTo(0.5, 0.5); } } else { if (jumpText != null) { jumpText.destroy(); jumpText = null; } } if (targetSpeed < 0.5) { if (lowOnEnergyText == null) { lowOnEnergyText = game.add.text(game.world.centerX, game.world.centerY + 35, "LOW ENERGY!", { font: "24px Arial", fill: "#fff", align: "center" }); lowOnEnergyText.anchor.setTo(0.5, 0.5); } } else { if (lowOnEnergyText != null) { lowOnEnergyText.destroy(); lowOnEnergyText = null; } } } } /* * Nearly all display objects in Phaser render automatically, you don't need to tell them to render. * However the render method is called AFTER the game renderer and plugins have rendered, * so you're able to do any final post-processing style effects here. * Note that this happens before plugins postRender takes place. */ function render() { }
import React from 'react'; import {shallow} from 'enzyme'; import Wrapper from '../Wrapper'; describe('<Wrapper />', () => { it('should render an <li> tag', () => { const renderedComponent = shallow(<Wrapper />); expect(renderedComponent.type()).toEqual('li'); }); it('should have a className attribute', () => { const renderedComponent = shallow(<Wrapper />); expect(renderedComponent.prop('className')).toBeDefined(); }); it('should adopt a valid attribute', () => { const id = 'test'; const renderedComponent = shallow(<Wrapper id={id} />); expect(renderedComponent.prop('id')).toEqual(id); }); it('should not adopt an invalid attribute', () => { const renderedComponent = shallow(<Wrapper attribute={'test'} />); expect(renderedComponent.prop('attribute')).toBeUndefined(); }); });
import React, { Component } from "react"; import { connect } from "react-redux"; import { bindActionCreators } from "redux"; import * as actions from "../actions"; import { Link } from "react-router-dom"; import Logo2 from "../svgs/Logo2"; import Styles from "./nav.css"; const timeouts = []; class Nav extends Component { toggleFixedMobileNav() { const nav = document.querySelector(".nav").style; const dimmerStyle = document.querySelector(".mobile-dimmer-modal").style; const listWrapStyle = document.querySelector(".mobile-list-modal").style; const lis = document.querySelectorAll(".mobile-list-modal li"); if (window.innerWidth <= 700) { if (dimmerStyle.opacity === "0.8") { nav.position = "initial"; dimmerStyle.top = "-10rem"; dimmerStyle.height = "1vh"; dimmerStyle.opacity = "0"; listWrapStyle.display = "none"; lis.forEach(li => { li.style.color = "transparent"; li.style.height = "0rem"; li.style.padding = "0rem"; }); } else { nav.position = "fixed"; dimmerStyle.top = "8rem"; dimmerStyle.height = "100vh"; dimmerStyle.opacity = "0.8"; listWrapStyle.display = "initial"; lis.forEach(li => { li.style.color = "#ffffff"; li.style.height = "initial"; li.style.padding = "1.5rem"; }); } } } renderIcon() { if (this.props.auth) { if (this.props.auth) { const name = this.props.auth.displayName || "guest"; return ( <div className="guest-fa-wrap"> <i className="fa fa-user-o" aria-hidden="true" /> </div> ); } else { return <div />; } } else { return ( <div className="guest-fa-wrap"> <i className="fa fa-user-o" aria-hidden="true" /> </div> ); } if (this.props.auth) { const name = this.props.auth.displayName || "guest"; if (this.props.auth) { return ( <div className="identicon-wrap"> <div /> </div> ); } else { return <div>Ok There</div>; } } else { return <div />; } } render() { return ( <nav className={`nav nav-${this.props.for}`}> <div className="left-side"> <Link to={"/play"}> <div className="left-side-option play-option">PLAY</div> </Link> <Link to={"/help"}> <div className="left-side-option help-option">HELP</div> </Link> <Link to={"/cheat-sheet"}> <div className="left-side-option help-option">CHEAT</div> </Link> </div> <div className="right-side"> <Link to={"/dashboard"}> <div className="nav-image-wrap"> <img src="https://jytr-fullstack.herokuapp.com/splash.png" /> </div> </Link> </div> </nav> ); } } function mapStateToProps({ auth }) { return { auth }; } export default connect(mapStateToProps, actions)(Nav);
exports.random4 = function() { return 4; // Chosen by fair dice roll - Guaranteed to be random - http://xkcd.com/221/ };
/* global Meals:true */ /* global Calendars:true */ /* global SimpleSchema:true */ import { Mongo } from 'meteor/mongo'; Meals = new Mongo.Collection('meals'); Calendars = new Mongo.Collection('calendars'); // calendar schema Calendars.attachSchema(new SimpleSchema({ name: { type: String, max: 20, label: 'Calendar Name', }, description: { type: String, label: 'Calendar Description', max: 1000, autoform: { rows: 4, }, }, owner: { type: String, optional: true, autoform: { omit: true, }, }, })); // meals schema Meals.attachSchema(new SimpleSchema({ name: { type: String, max: 20, label: 'Meal Name', }, description: { type: String, label: 'Meal Description', max: 1000, autoform: { rows: 4, }, }, owner: { type: String, optional: true, autoform: { omit: true, }, }, }));
if (Posts.find().count() === 0) { var now = new Date().getTime(); // create admin user Meteor.users.insert({ "_id" : "5bvb7XXQX7NZHMxTB", "createdAt" : now - 24 * 3600 * 1000, "profile" : { "name" : "Administrator", "role" : "admin", "addresses": [ {street1:'Av Rio Branco, 18', street2:'SL 1801', city:'Rio de Janeiro', state:'RJ', zip:'24000-000', country:'Brazil'}, {street1:'55 East 52nd Street', street2:'21st Floor', city:'New York', state:'NY', zip:'10022', country:'USA' } ] }, "services" : { "password" : { "srp" : { "identity" : "hXLv4ETaXditKz9vu", "salt" : "c4SY7pCiCTXZLJSeh", "verifier" : "762ead155f6b9f1fce6a0f2736ec00966778ad0ab04187dff0b08e683fa1a4d0bfff00a01af93d80b741e" + "6e95e0f5d50539e42b6ff5cf9c9b43020c155565866e44987933a70173482b9fef96ad0800b2cf45c9a5d" + "96ebee3af8569ca548587012d7fe4f9560b2406d323e433eba237389e90caba761cd64ef1fea6dfd2bff9f" } } }, "username" : "admin" }); Meteor.users.insert({ "_id" : "6bvb8XnQX8NZHMx0C", "createdAt" : now - 23 * 3600 * 1000, "profile" : { "name" : "Staff", "role" : "staff" }, "services" : { "password" : { "srp" : { "identity" : "hXLv4ETaXditKz9vu", "salt" : "c4SY7pCiCTXZLJSeh", "verifier" : "762ead155f6b9f1fce6a0f2736ec00966778ad0ab04187dff0b08e683fa1a4d0bfff00a01af93d80b741e" + "6e95e0f5d50539e42b6ff5cf9c9b43020c155565866e44987933a70173482b9fef96ad0800b2cf45c9a5d" + "96ebee3af8569ca548587012d7fe4f9560b2406d323e433eba237389e90caba761cd64ef1fea6dfd2bff9f" } } }, "username" : "staff" }); Meteor.users.insert({ "_id" : "7bfb9Xn2X9NZHMx1q", "createdAt" : now - 22 * 3600 * 1000, "profile" : { "name" : "User", "role" : "user" }, "services" : { "password" : { "srp" : { "identity" : "hXLv4ETaXditKz9vu", "salt" : "c4SY7pCiCTXZLJSeh", "verifier" : "762ead155f6b9f1fce6a0f2736ec00966778ad0ab04187dff0b08e683fa1a4d0bfff00a01af93d80b741e" + "6e95e0f5d50539e42b6ff5cf9c9b43020c155565866e44987933a70173482b9fef96ad0800b2cf45c9a5d" + "96ebee3af8569ca548587012d7fe4f9560b2406d323e433eba237389e90caba761cd64ef1fea6dfd2bff9f" } } }, "username" : "user" }); // create two users var tomId = Meteor.users.insert({ profile: { name: 'Tom', role: 'staff' }, username: 'tcoleman' }); var tom = Meteor.users.findOne(tomId); var sachaId = Meteor.users.insert({ profile: { name: 'Sacha', role: 'staff' }, username: 'sgreif' }); var sacha = Meteor.users.findOne(sachaId); var telescopeId = Posts.insert({ title: 'Introducing Telescope', userId: sacha._id, author: sacha.profile.name, url: 'http://sachagreif.com/introducing-telescope/', submitted: now - 7 * 3600 * 1000, commentsCount: 2 }); Comments.insert({ postId: telescopeId, userId: tom._id, author: tom.profile.name, submitted: now - 5 * 3600 * 1000, body: 'Interesting project Sacha, can I get involved?' }); Comments.insert({ postId: telescopeId, userId: sacha._id, author: sacha.profile.name, submitted: now - 3 * 3600 * 1000, body: 'You sure can Tom!' }); Posts.insert({ title: 'Meteor', userId: tom._id, author: tom.profile.name, url: 'http://meteor.com', submitted: now - 10 * 3600 * 1000, commentsCount: 0 }); Posts.insert({ title: 'The Meteor Book', userId: tom._id, author: tom.profile.name, url: 'http://themeteorbook.com', submitted: now - 12 * 3600 * 1000, commentsCount: 0 }); // Products and categories Categories.insert({ name: 'Software', description: 'Software', }); Categories.insert({ name: 'Hardware', description: 'Hardware', }); Products.insert({ category: ['Software'], name: 'Linux', description: 'Lorem ipsum dolor sit amet, eget molestie vestibulum, elit lobortis.', image: '/img/linux.jpg', price: 0.00 }); Products.insert({ category: ['Hardware'], name: 'Motherboard', description: 'Sed vitae, et aut doloremque. Vivamus egestas ut, sed eleifend, proin mi.', image: '/img/motherboard.jpg', price: 25.00 }); Products.insert({ category: ['Hardware'], name: 'Arduino', description: 'Lorem ipsum dolor sit amet, eget molestie vestibulum, elit lobortis.', image: '/img/arduino.jpg', price: 17.00 }); for (var i = 0; i < 10; i++) { Products.insert({ category: ['Hardware'], name: 'Hardware ' + i, description: 'Lorem ipsum dolor sit amet, eget molestie vestibulum, elit lobortis.', image: '/img/hardware' + i + '.jpg', price: i * 10 }); } for (var i = 9; i >= 0; i--) { Products.insert({ category: ['Software'], name: 'Software ' + i, description: 'Lorem ipsum dolor sit amet, eget molestie vestibulum, elit lobortis.', image: '/img/software' + i + '.jpg', price: i * 10 }); } }
var loggly = require('loggly'); function logger(tag) { return loggly.createClient({ token: process.env.LOGGLY_TOKEN, subdomain: "katyjustiss", tags: ["NodeJS", tag], json:true }); } module.exports = logger;
var cv = require('opencv'); var camera = new cv.VideoCapture(0); var videoStream = new cv.VideoStream(camera); var app = require('express')() , server = require('http').createServer(app) , io = require('socket.io').listen(server, {log:false}); server.listen(8080); app.get('/', function (req, res) { res.sendfile(__dirname + '/index.html'); }); io.sockets.on('connection', function (socket) { // socket.emit('news', { hello: 'world' }); socket.on('my other event', function (data) { console.log(data); }); }); function move_th(){ lowThresh+=20 highThresh+=20 console.log('threshold', highThresh) } // setInterval(move_th,2000) var lowThresh = 220; var highThresh = 240; var nIters = 50; var maxArea = 2500; var GREEN = [0, 255, 0]; //B, G, R var WHITE = [255, 255, 255]; //B, G, R var RED = [0, 0, 255]; //B, G, R var WHITE = [255, 255, 255]; //B, G, R processing = false; var last = Date.now() videoStream.on('data', function(matrix) { if (!processing) { processing = true; cv.readImage(matrix.toBuffer(), function(error, im) { var big = new cv.Matrix(im.height(), im.width()); var all = new cv.Matrix(im.height(), im.width()); var blend = new cv.Matrix(im.height(), im.width()); blend.convertGrayscale(); im.convertGrayscale(); im_canny = im.copy(); im_canny.canny(lowThresh, highThresh); im_canny.dilate(nIters); // im.save('./out/orig' + Date.now() + '.png') // console.log('img dimensions', im.width(), im.height(), 'img chan', im.channels()) // console.log('img dimensions', blend.width(), blend.height(), 'img chan', blend.channels()) contours = im_canny.findContours(); for (i = 0; i < contours.size(); i++) { if (contours.area(i) > maxArea) { var moments = contours.moments(i); var cgx = Math.round(moments.m10 / moments.m00); var cgy = Math.round(moments.m01 / moments.m00); big.drawContour(contours, i, GREEN); im.drawContour(contours, i, WHITE); big.line([cgx - 5, cgy], [cgx + 5, cgy], RED); im.line([cgx - 5, cgy], [cgx + 5, cgy], WHITE); big.line([cgx, cgy - 5], [cgx, cgy + 5], RED); im.line([cgx, cgy - 5], [cgx, cgy + 5], WHITE); } } all.drawAllContours(contours, WHITE); im.drawAllContours(contours, WHITE); // big.save('./out/big' + Date.now() + '.png'); // all.save('./out/all' + Date.now() + '.png'); // im.save('./out/orig' + Date.now() + '.png') // console.log('orig is ') base64data = new Buffer(im.toBuffer()).toString('base64'); io.sockets.emit('image', base64data); // big.convertGrayscale(); // console.log(blend.channels(), big.channels(), im.channels()) // blend.addWeighted(im,0.7, big, 0.9) // blend.save('./out/blend' + Date.now() + '.png') processing = false; // console.log('last was time ago', Date.now() - last) last = Date.now() }); } }); videoStream.read();
// MODULES ------------------------------------ express = require('express'); colors = require('colors'); // SETUP ------------------------------------ app = express(); server = require('http').createServer(app); io = require('socket.io').listen(server); logger = function(req, res, next) { console.log(" info (backend) - ".cyan+req.method+" "+req.url); next(); } app.configure(function () { app.set('views', __dirname + '/client/views'); app.set('view engine', 'jade'); app.use(express.cookieParser()); app.use(express.json()); app.use(express.urlencoded()); app.use(express.methodOverride()); app.use(logger); app.use(app.router); app.use(express.static(__dirname + '/client')); app.use(function (req,res) { res.send('404 - Not found'); console.log(' error(backend) - '.red+'client requested an undefined route :('); }); }); io.configure(function () { io.set("transports", ["xhr-polling"]); io.set("polling duration", 10); }); app.configure('development', function () { app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); }); onlineUsers = []; // PAGE ROUTES ------------------------------------ app.get('/', function (req,res) { res.render("index"); }); app.post('/data', function (req,res) { res.send(req.body.data+" was your data."); }); server.listen(process.env.PORT || 5000);
var config = require('../../../config/config'), baseTest = require('../base'); var testSuite = baseTest('Event type resource') .createUser('Register first user') .createUser('Register second user', { lastName: 'Dutoit', email: 'henri.dutoit@localhost.localdomain' }) .signinUser('Signing first user') .signinUser('Signing first user', { email: 'henri.dutoit@localhost.localdomain' }) .createOrganization('Create new organization for first user', { name: 'Orga 1' }, 1) .createOrganization('Create second organization for first user', { name: 'Orga 2' }, 1) .createOrganization('Create new organization for second user', { name: 'Orga 3' }, 2); testSuite .describe('Create ET1 (public) event type in organization with missing type') .jwtAuthentication(function() { return this.getData('token1'); }) .post({ url: '/v1/eventTypes' }, function() { return { body: { name: 'ET1', description: 'Represent an increase in the temperature.', public: true, organizationId: this.getData('organizationId1'), schema: { $schema: "http://json-schema.org/draft-04/schema#", type: "object", properties: { sensorId: { type: "string" }, temperature: { type: "object", properties: { old: { type: "number" }, new: { type: "number" } } } } } } }; }) .expectStatusCode(422) .expectJsonToHavePath('type.0') .expectJsonToBe({ type: [ 'Type is mandatory.' ]}); testSuite .describe('Create ET1 (public) event type in organization with invalid type') .post({ url: '/v1/eventTypes' }, function() { return { body: { name: 'ET1', description: 'Represent an increase in the temperature.', public: true, type: '1234', organizationId: this.getData('organizationId1'), schema: { $schema: "http://json-schema.org/draft-04/schema#", type: "object", properties: { sensorId: { type: "string" }, temperature: { type: "object", properties: { old: { type: "number" }, new: { type: "number" } } } } } } }; }) .expectStatusCode(422) .expectJsonToHavePath('type.0') .expectJsonToBe({ type: [ 'Type must be a valid URL.' ]}); testSuite .describe('Create ET1 event type with too short name') .post({ url: '/v1/eventTypes' }, function() { return { body: { name: 'ET', description: 'Represent an increase in the temperature.', public: true, type: 'http://iflux.io/schemas/eventTypes/1', organizationId: this.getData('organizationId1'), schema: { $schema: "http://json-schema.org/draft-04/schema#", type: "object", properties: { sensorId: { type: "string" }, temperature: { type: "object", properties: { old: { type: "number" }, new: { type: "number" } } } } } } }; }) .expectStatusCode(422) .expectJsonToHavePath('name.0') .expectJsonToBe({ name: [ 'The name must be at least 3 characters long' ]}); testSuite .describe('Create ET1 (public) event type in organization where user does not have access') .post({ url: '/v1/eventTypes' }, function() { return { body: { name: 'ET1', description: 'Represent an increase in the temperature.', public: true, type: 'http://iflux.io/schemas/eventTypes/1', organizationId: this.getData('organizationId3'), schema: { $schema: "http://json-schema.org/draft-04/schema#", type: "object", properties: { sensorId: { type: "string" }, temperature: { type: "object", properties: { old: { type: "number" }, new: { type: "number" } } } } } } }; }) .expectStatusCode(422) .expectJsonToHavePath('organizationId.0') .expectJsonToBe({ organizationId: [ 'No organization found.' ]}); testSuite .describe('Create ET1 event type for first user in his first organization') .post({ url: '/v1/eventTypes' }, function() { return { body: { name: 'ET1', description: 'Represent an increase in the temperature.', public: true, type: 'http://' + config.host + ':' + config.port + '/v1/schemas/eventTypes/1', organizationId: this.getData('organizationId1'), schema: { $schema: "http://json-schema.org/draft-04/schema#", type: "object", properties: { sensorId: { type: "string" }, temperature: { type: "object", properties: { old: { type: "number" }, new: { type: "number" } } } } } } }; }) .storeLocationAs('eventType', 1) .expectStatusCode(201) .expectLocationHeader('/v1/eventTypes/:id') .expectHeaderToBePresent('x-iflux-generated-id'); testSuite .describe('Try to re-create ET1 event type for first user in his first organization') .post({ url: '/v1/eventTypes' }, function() { return { body: { name: 'ET1', description: 'Represent an increase in the temperature.', public: true, type: 'http://' + config.host + ':' + config.port + '/v1/schemas/eventTypes/1/duplicated', organizationId: this.getData('organizationId1'), schema: { $schema: "http://json-schema.org/draft-04/schema#", type: "object", properties: { sensorId: { type: "string" }, temperature: { type: "object", properties: { old: { type: "number" }, new: { type: "number" } } } } } } }; }) .expectStatusCode(422) .expectJsonToBe({ name: [ 'Name is already taken in this organization.' ]}); testSuite .describe('Re-create ET1 event type for first user in his second organization with the same name from one the first organization') .post({ url: '/v1/eventTypes' }, function() { return { body: { name: 'ET1', description: 'Represent an increase in the temperature.', public: true, type: 'http://' + config.host + ':' + config.port + '/v1/schemas/eventTypes/1/duplicated', organizationId: this.getData('organizationId2'), schema: { $schema: "http://json-schema.org/draft-04/schema#", type: "object", properties: { sensorId: { type: "string" }, temperature: { type: "object", properties: { old: { type: "number" }, new: { type: "number" } } } } } } }; }) .storeLocationAs('eventType', 100) .expectStatusCode(201) .expectLocationHeader('/v1/eventTypes/:id'); testSuite .describe('Try to create ET1 event type for first user in his first organization with type already taken.') .post({ url: '/v1/eventTypes' }, function() { return { body: { name: 'ET1', description: 'Represent an increase in the temperature.', public: true, type: 'http://' + config.host + ':' + config.port + '/v1/schemas/eventTypes/1', organizationId: this.getData('organizationId1'), schema: { $schema: "http://json-schema.org/draft-04/schema#", type: "object", properties: { sensorId: { type: "string" }, temperature: { type: "object", properties: { old: { type: "number" }, new: { type: "number" } } } } } } }; }) .expectStatusCode(422) .expectJsonToHavePath('type.0') .expectJsonToBe({ type: [ 'Type must be unique.' ]}); testSuite .describe('Create ET2 (private) event type for first user in his first organization') .post({ url: '/v1/eventTypes' }, function() { return { body: { name: 'ET2', description: 'Represent an decrease in the temperature.', public: false, type: 'http://iflux.io/schemas/eventTypes/2', organizationId: this.getData('organizationId1'), schema: { $schema: "http://json-schema.org/draft-04/schema#", type: "object", properties: { sensorId: { type: "string" }, temperature: { type: "object", properties: { old: { type: "number" }, new: { type: "number" } } } } } } }; }) .storeLocationAs('eventType', 2) .expectStatusCode(201) .expectLocationHeader('/v1/eventTypes/:id'); testSuite .describe('Create ET3 event type for first user in his second organization') .post({ url: '/v1/eventTypes' }, function() { return { body: { name: 'ET3', description: 'Represent an increase in the temperature.', public: true, type: 'http://iflux.io/schemas/eventTypes/3', organizationId: this.getData('organizationId2'), schema: { $schema: "http://json-schema.org/draft-04/schema#", type: "object", properties: { sensorId: { type: "string" }, temperature: { type: "object", properties: { old: { type: "number" }, new: { type: "number" } } } } } } }; }) .storeLocationAs('eventType', 3) .expectStatusCode(201) .expectLocationHeader('/v1/eventTypes/:id'); testSuite .describe('Create ET4 (public) event type for second user in his first organization') .jwtAuthentication(function() { return this.getData('token2'); }) .post({ url: '/v1/eventTypes' }, function() { return { body: { name: 'ET4', description: 'Represent a modification in the temperature.', public: true, type: 'http://iflux.io/schemas/eventTypes/4', organizationId: this.getData('organizationId3'), schema: { $schema: "http://json-schema.org/draft-04/schema#", type: "object", properties: { sensorId: { type: "string" }, temperature: { type: "object", properties: { old: { type: "number" }, new: { type: "number" } } } } } } }; }) .storeLocationAs('eventType', 4) .expectStatusCode(201) .expectLocationHeader('/v1/eventTypes/:id'); testSuite .describe('Create ET5 (private) event type for second user in his first organization') .jwtAuthentication(function() { return this.getData('token2'); }) .post({ url: '/v1/eventTypes' }, function() { return { body: { name: 'ET5', description: 'Represent a modification in the temperature.', public: false, type: 'http://iflux.io/schemas/eventTypes/5', organizationId: this.getData('organizationId3'), schema: { $schema: "http://json-schema.org/draft-04/schema#", type: "object", properties: { sensorId: { type: "string" }, temperature: { type: "object", properties: { old: { type: "number" }, new: { type: "number" } } } } } } }; }) .storeLocationAs('eventType', 5) .expectStatusCode(201) .expectLocationHeader('/v1/eventTypes/:id'); testSuite .describe('Create ET6 (private) event type for second user in his first organization without schema') .post({ url: '/v1/eventTypes' }, function() { return { body: { name: 'ET6', description: 'Event type without schema to validate this is not mandatory.', public: false, type: 'http://iflux.io/schemas/eventTypes/6', organizationId: this.getData('organizationId3'), } }; }) .storeLocationAs('eventType', 6) .expectStatusCode(201) .expectLocationHeader('/v1/eventTypes/:id'); testSuite .describe('Create ET7 (public) event type for second user in his first organization without schema') .post({ url: '/v1/eventTypes' }, function() { return { body: { name: 'ET7', description: 'Public event type', public: true, type: 'http://iflux.io/schemas/eventTypes/7', organizationId: this.getData('organizationId3') } }; }) .storeLocationAs('eventType', 7) .expectStatusCode(201) .expectLocationHeader('/v1/eventTypes/:id'); testSuite .describe('Retrieve all the public event types for first user') .jwtAuthentication(function() { return this.getData('token1'); }) .get({ url: '/v1/eventTypes?public' }) .expectStatusCode(200) .expectJsonToHavePath([ '0.id', '0.name', '0.public', '0.organizationId', '1.id', '1.name', '1.public', '1.organizationId' ]) .expectJsonCollectionToHaveSize(5) .expectJsonToBeAtLeast(function() { return [{ name: 'ET1', description: 'Represent an increase in the temperature.', public: true, type: 'http://' + config.host + ':' + config.port + '/v1/schemas/eventTypes/1', organizationId: this.getData('organizationId1') }, { name: 'ET3', description: 'Represent an increase in the temperature.', public: true, type: 'http://iflux.io/schemas/eventTypes/3', organizationId: this.getData('organizationId2') }, { name: 'ET4', description: 'Represent a modification in the temperature.', public: true, type: 'http://iflux.io/schemas/eventTypes/4', organizationId: this.getData('organizationId3') }, { name: 'ET1', description: 'Represent an increase in the temperature.', public: true, type: 'http://' + config.host + ':' + config.port + '/v1/schemas/eventTypes/1/duplicated', organizationId: this.getData('organizationId2') }, { name: 'ET7', description: 'Public event type', public: true, type: 'http://iflux.io/schemas/eventTypes/7', organizationId: this.getData('organizationId3') }]; }); testSuite .describe('Retrieve all the event types for first user filtered by name') .get({ url: '/v1/eventTypes?public=true&name=%4' }) .expectStatusCode(200) .expectJsonCollectionToHaveSize(1) .expectJsonToBeAtLeast(function() { return [{ name: 'ET4', description: 'Represent a modification in the temperature.', public: true, type: 'http://iflux.io/schemas/eventTypes/4', organizationId: this.getData('organizationId3') }]; }); testSuite .describe('Retrieve all the event types for first user') .get({ url: '/v1/eventTypes?allOrganizations' }) .expectStatusCode(200) .expectJsonToHavePath([ '0.id', '1.id', '2.id', '0.name', '1.name', '2.name', '0.public', '1.public', '2.public', '0.organizationId' ]) .expectJsonCollectionToHaveSize(4) .expectJsonToBeAtLeast(function() { return [{ name: 'ET1', description: 'Represent an increase in the temperature.', public: true, type: 'http://' + config.host + ':' + config.port + '/v1/schemas/eventTypes/1', organizationId: this.getData('organizationId1'), schema: { $schema: "http://json-schema.org/draft-04/schema#", type: "object", properties: { sensorId: { type: "string" }, temperature: { type: "object", properties: { old: { type: "number" }, new: { type: "number" } } } } } }, { name: 'ET2', description: 'Represent an decrease in the temperature.', public: false, type: 'http://iflux.io/schemas/eventTypes/2', organizationId: this.getData('organizationId1'), schema: { $schema: "http://json-schema.org/draft-04/schema#", type: "object", properties: { sensorId: { type: "string" }, temperature: { type: "object", properties: { old: { type: "number" }, new: { type: "number" } } } } } }, { name: 'ET3', description: 'Represent an increase in the temperature.', public: true, type: 'http://iflux.io/schemas/eventTypes/3', organizationId: this.getData('organizationId2'), schema: { $schema: "http://json-schema.org/draft-04/schema#", type: "object", properties: { sensorId: { type: "string" }, temperature: { type: "object", properties: { old: { type: "number" }, new: { type: "number" } } } } } }, { name: 'ET1', description: 'Represent an increase in the temperature.', public: true, type: 'http://' + config.host + ':' + config.port + '/v1/schemas/eventTypes/1/duplicated', organizationId: this.getData('organizationId2'), schema: { $schema: "http://json-schema.org/draft-04/schema#", type: "object", properties: { sensorId: { type: "string" }, temperature: { type: "object", properties: { old: { type: "number" }, new: { type: "number" } } } } } }]; }); testSuite .describe('Retrieve all the event types for first user filtered by name') .get({ url: '/v1/eventTypes?allOrganizations&name=%2' }) .expectStatusCode(200) .expectJsonCollectionToHaveSize(1) .expectJsonToBeAtLeast(function() { return [{ name: 'ET2', description: 'Represent an decrease in the temperature.', public: false, type: 'http://iflux.io/schemas/eventTypes/2', organizationId: this.getData('organizationId1') }]; }); testSuite .describe('Retrieve all the event types for first user for the first organization') .get({}, function() { return { url: '/v1/eventTypes?organizationId=' + this.getData('organizationId1') }; }) .expectStatusCode(200) .expectJsonToHavePath([ '0.id', '1.id', '0.name', '1.name', '0.public', '1.public', '0.organizationId', '1.organizationId' ]) .expectJsonCollectionToHaveSize(2) .expectJsonToBeAtLeast(function() { return [{ name: 'ET1', description: 'Represent an increase in the temperature.', public: true, type: 'http://' + config.host + ':' + config.port + '/v1/schemas/eventTypes/1', organizationId: this.getData('organizationId1') }, { name: 'ET2', description: 'Represent an decrease in the temperature.', public: false, type: 'http://iflux.io/schemas/eventTypes/2', organizationId: this.getData('organizationId1') }]; }); testSuite .describe('Retrieve all the event types for first user for the first organization filtered by name') .get({}, function() { return { url: '/v1/eventTypes?organizationId=' + this.getData('organizationId1') + '&name=%2'}; }) .expectStatusCode(200) .expectJsonCollectionToHaveSize(1) .expectJsonToBeAtLeast(function() { return [{ name: 'ET2', description: 'Represent an decrease in the temperature.', public: false, type: 'http://iflux.io/schemas/eventTypes/2', organizationId: this.getData('organizationId1') }]; }); testSuite .describe('Retrieve all the event types for first user for the second organization') .get({}, function() { return { url: '/v1/eventTypes?organizationId=' + this.getData('organizationId2') }; }) .expectStatusCode(200) .expectJsonToHavePath([ '0.id', '0.name', '0.public', '0.organizationId' ]) .expectJsonCollectionToHaveSize(2) .expectJsonToBeAtLeast(function() { return [{ name: 'ET3', description: 'Represent an increase in the temperature.', public: true, type: 'http://iflux.io/schemas/eventTypes/3', organizationId: this.getData('organizationId2') }, { name: 'ET1', description: 'Represent an increase in the temperature.', public: true, type: 'http://' + config.host + ':' + config.port + '/v1/schemas/eventTypes/1/duplicated', organizationId: this.getData('organizationId2') }]; }); testSuite .describe('Retrieve all the event types for second user') .jwtAuthentication(function() { return this.getData('token2'); }) .get({ url: '/v1/eventTypes' }) .expectStatusCode(200) .expectJsonToHavePath([ '0.id', '0.name', '0.public', '0.organizationId', '1.id', '1.name', '1.public', '1.organizationId' ]) .expectJsonCollectionToHaveSize(7) .expectJsonToBeAtLeast(function() { return [{ name: 'ET1', description: 'Represent an increase in the temperature.', public: true, type: 'http://' + config.host + ':' + config.port + '/v1/schemas/eventTypes/1', organizationId: this.getData('organizationId1') }, { name: 'ET3', description: 'Represent an increase in the temperature.', public: true, type: 'http://iflux.io/schemas/eventTypes/3', organizationId: this.getData('organizationId2') }, { name: 'ET4', description: 'Represent a modification in the temperature.', public: true, type: 'http://iflux.io/schemas/eventTypes/4', organizationId: this.getData('organizationId3') }, { name: 'ET5', description: 'Represent a modification in the temperature.', public: false, type: 'http://iflux.io/schemas/eventTypes/5', organizationId: this.getData('organizationId3') }, { name: 'ET1', description: 'Represent an increase in the temperature.', public: true, type: 'http://' + config.host + ':' + config.port + '/v1/schemas/eventTypes/1/duplicated', organizationId: this.getData('organizationId2') }, { name: 'ET6', description: 'Event type without schema to validate this is not mandatory.', public: false, type: 'http://iflux.io/schemas/eventTypes/6', organizationId: this.getData('organizationId3'), }, { name: 'ET7', description: 'Public event type', public: true, type: 'http://iflux.io/schemas/eventTypes/7', organizationId: this.getData('organizationId3') }]; }); testSuite .describe('Retrieve all the event types for second user filtered by name') .get({ url: '/v1/eventTypes?name=%4' }) .expectStatusCode(200) .expectJsonCollectionToHaveSize(1) .expectJsonToBeAtLeast(function() { return [{ name: 'ET4', description: 'Represent a modification in the temperature.', public: true, type: 'http://iflux.io/schemas/eventTypes/4', organizationId: this.getData('organizationId3') }]; }); testSuite .describe('Retrieve all the public event types for second user') .get({ url: '/v1/eventTypes?public' }) .expectStatusCode(200) .expectJsonToHavePath([ '0.id', '0.name', '0.public', '0.organizationId', '1.id', '1.name', '1.public', '1.organizationId' ]) .expectJsonCollectionToHaveSize(5) .expectJsonToBeAtLeast(function() { return [{ name: 'ET1', description: 'Represent an increase in the temperature.', public: true, type: 'http://' + config.host + ':' + config.port + '/v1/schemas/eventTypes/1', organizationId: this.getData('organizationId1') }, { name: 'ET3', description: 'Represent an increase in the temperature.', public: true, type: 'http://iflux.io/schemas/eventTypes/3', organizationId: this.getData('organizationId2') }, { name: 'ET4', description: 'Represent a modification in the temperature.', public: true, type: 'http://iflux.io/schemas/eventTypes/4', organizationId: this.getData('organizationId3') }, { }, { name: 'ET1', description: 'Represent an increase in the temperature.', public: true, type: 'http://' + config.host + ':' + config.port + '/v1/schemas/eventTypes/1/duplicated', organizationId: this.getData('organizationId2') }, { name: 'ET7', description: 'Public event type', public: true, type: 'http://iflux.io/schemas/eventTypes/7', organizationId: this.getData('organizationId3') }]; }); testSuite .describe('Retrieve all the event types for second user filtered by name') .get({ url: '/v1/eventTypes?public=true&name=%4' }) .expectStatusCode(200) .expectJsonCollectionToHaveSize(1) .expectJsonToBeAtLeast(function() { return [{ name: 'ET4', description: 'Represent a modification in the temperature.', public: true, type: 'http://iflux.io/schemas/eventTypes/4', organizationId: this.getData('organizationId3') }]; }); testSuite .describe('Try to retrieve all event types and all for a specific organization, only the specific organization is taken into account.') .jwtAuthentication(function() { return this.getData('token1'); }) .get({}, function() { return { url: '/v1/eventTypes?allOrganizations&organizationId=' + this.getData('organizationId2') }; }) .expectStatusCode(200) .expectJsonToHavePath([ '0.id', '0.name', '0.public', '0.organizationId' ]) .expectJsonCollectionToHaveSize(2) .expectJsonToBeAtLeast(function() { return [{ name: 'ET3', description: 'Represent an increase in the temperature.', public: true, type: 'http://iflux.io/schemas/eventTypes/3', organizationId: this.getData('organizationId2') }, { name: 'ET1', description: 'Represent an increase in the temperature.', public: true, type: 'http://' + config.host + ':' + config.port + '/v1/schemas/eventTypes/1/duplicated', organizationId: this.getData('organizationId2') }]; }); testSuite .describe('First user retrieves public event type where the user is not member of the organization') .get({}, function() { return { url: this.getData('locationEventType7') }; }) .expectStatusCode(200); testSuite .describe('First user tries to retrieve private event type where the user is not member of the organization') .get({}, function() { return { url: this.getData('locationEventType6') }; }) .expectStatusCode(403); testSuite .describe('Try to retrieve event type where the user is not member of the organization') .get({}, function() { return { url: this.getData('locationEventType1') + '100' }; }) .expectStatusCode(403); testSuite .describe('First user updates ET1 event type') .jwtAuthentication(function() { return this.getData('token1'); }) .patch({}, function() { return { url: this.getData('locationEventType1'), body: { name: 'ET1 renamed' } }; }) .expectStatusCode(201) .expectLocationHeader('/v1/eventTypes/:id') .expectHeaderToBePresent('x-iflux-generated-id'); testSuite .describe('No update sent must let the resource unchanged') .patch({}, function() { return { url: this.getData('locationEventType1'), body: {} }; }) .expectStatusCode(304) .expectLocationHeader('/v1/eventTypes/:id') .expectHeaderToBePresent('x-iflux-generated-id'); testSuite .describe('First user updates ET1 event type with the same type') .patch({}, function() { return { url: this.getData('locationEventType1'), body: { type: 'http://' + config.host + ':' + config.port + '/v1/schemas/eventTypes/1' } }; }) .expectStatusCode(304) .expectLocationHeader('/v1/eventTypes/:id') .expectHeaderToBePresent('x-iflux-generated-id'); testSuite .describe('First user updates ET1 event type with invalid type') .patch({}, function() { return { url: this.getData('locationEventType1'), body: { type: '1234' } }; }) .expectStatusCode(422) .expectJsonToBe({ type: [ 'Type must be a valid URL.' ]}); testSuite .describe('First user updates ET1 event type with different type but not unique') .patch({}, function() { return { url: this.getData('locationEventType1'), body: { type: 'http://iflux.io/schemas/eventTypes/2' } }; }) .expectStatusCode(422) .expectJsonToBe({ type: [ 'Type must be unique.' ]}); testSuite .describe('First user updates ET1 event type with valid and unique different type') .patch({}, function() { return { url: this.getData('locationEventType1'), body: { type: 'http://' + config.host + ':' + config.port + '/v1/schemas/eventTypes/11' } }; }) .expectStatusCode(201) .expectLocationHeader('/v1/eventTypes/:id') .expectHeaderToBePresent('x-iflux-generated-id'); testSuite .describe('First user updates ET1 event type with a name used in a different organization') .patch({}, function() { return { url: this.getData('locationEventType1'), body: { name: 'ET3' } }; }) .expectStatusCode(201) .expectLocationHeader('/v1/eventTypes/:id') .expectHeaderToBePresent('x-iflux-generated-id'); testSuite .describe('First user updates ET1 action type with a name used in the same organization') .patch({}, function() { return { url: this.getData('locationEventType1'), body: { name: 'ET2' } }; }) .expectStatusCode(422) .expectJsonToBe({ name: [ 'Name is already taken in this organization.' ]}); testSuite .describe('Second user tries to update ET1 event type of first user') .jwtAuthentication(function() { return this.getData('token2'); }) .patch({}, function() { return { url: this.getData('locationEventType1'), body: { name: 'Temperature Increase renamed by second user' } }; }) .expectStatusCode(403); testSuite .describe('Retrieve an event type schema from its type (url).') .get({ url: '/v1/schemas/eventTypes/11' }) .expectStatusCode(200); testSuite .describe('Retrieve an event type schema from its type (url) but nothing is found.') .get({ url: '/v1/schemas/eventTypes/111' }) .expectStatusCode(404); testSuite .describe('First user remove ET1.') .jwtAuthentication(function() { return this.getData('token1'); }) .delete({}, function() { return { url: this.getData('locationEventType1') }; }) .expectStatusCode(204); testSuite .describe('First user tries to retrieve ET1.') .get({}, function() { return { url: this.getData('locationEventType1') }; }) .expectStatusCode(403); testSuite .describe('First user tries to delete ET4 in an organization where he is not a member.') .delete({}, function() { return { url: this.getData('locationEventType4') }; }) .expectStatusCode(403); module.exports = testSuite;
import {AbstractField} from './AbstractField' /** * Class: CustomField * @see: Yeah... I use _var to keep the distance between private and public vars */ export class Field extends AbstractField { constructor (name, value, label) { super(name, value) this._name = name this._value = value this._label = label } get name () { return this._name } set name (value) { this._name = value } get value () { return this._value } set value (value) { this._value = value } get label () { return this._label || this._name } set label (value) { this._label = value } getFieldType () { return 'Field' } }
var should = require('should'); var proxyquire = require('proxyquire'); var pathStub = { normalize: function(){ return __dirname+"/waterlock.config.js"; } }; var wl = proxyquire.noCallThru().load('../lib/waterlock-vkontakte-auth', { 'path': pathStub}); describe('waterlock-vkontakte-auth', function(){ it('should export actions', function(done){ wl.should.have.property('actions'); done(); }); it('should export a model', function(done){ wl.should.have.property('model'); done(); }); it('should export a vk instance', function(done){ wl.should.have.property('vk'); done(); }); })
var express = require('express'), router = express.Router(), moment = require('moment'), Pclog = require('../models/pclog.js'); /* GET statistics page. */ var auth = require('./auth'); router.all('/', auth.requireLogin); router.get('/', function(req, res, next){ var weekago = new Date(Date.now() - 30*24*60*60*1000); //var weekagoDay = new Date(weekago.getFullYear()+"-"+(weekago.getMonth()+1)+"-"+weekago.getDate()); weekago.setHours(0,0,0,0); Pclog.aggregate([{$match:{created:{$gte:weekago}}},{$group:{_id:{month:{$month:"$created"},day:{$dayOfMonth:"$created"}, action:"$action"},total:{$sum:1}}}]) .exec(function(err, docs){ if(err){console.log(err)} res.render('logs', {docs: JSON.stringify(docs),title: "Logs"}); }) }) router.post('/', function(req, res, next){ var today = new Date(); today.setHours(8,0,0,0); //console.log(today); Pclog.find({created:{$gt: today}}) .exec(function(err, docs){ if(err){res.send('error'); return;} //console.log(docs); var data = docs.map(function(item){ return {_id:{ DateTime: moment(item.created).format("YYYY-MM-DD HH:mm:ss"), ComputerName: item.ComputerName, LogonName: item.LogonName, displayName: item.displayName, action: item.action}} }) res.json(data); }); }) module.exports = router;