code
stringlengths
2
1.05M
import React from 'react'; import { shallow, mount, render } from 'enzyme'; import reducer from '../../src/reducers/finalReducer.js'; describe('actions', () => { const intialState = { splitTotal: '', totalTax: '', totalTip: '', splitName: '', splitter: { name: '', phone: '', items: [], total: null, tax: null, tip: null, debtTotal: null, }, debtors: [], picture: null }; it('should return the initial state', () => { expect(reducer(undefined, {})).toEqual(intialState); }); it('should update the split total property', () => { expect( reducer( intialState, {type: 'SET_SPLIT_TOTAL', payload: 15} )).toEqual( { splitTotal: 15, totalTax: '', totalTip: '', splitName: '', splitter: { name: '', phone: '', items: [], debtTotal: null, tax: null, tip: null, total: null, }, debtors: [], picture: null } ); }); it('should update the split tax', () => { expect( reducer( intialState, {type: 'SET_TOTAL_TAX', payload: 15} )).toEqual( { splitTotal: '', totalTax: 15, totalTip: '', splitName: '', splitter: { name: '', phone: '', items: [], debtTotal: null, tax: null, tip: null, total: null, }, debtors: [], picture: null } ); }); it('should update the split tip', () => { expect( reducer( intialState, {type: 'SET_TOTAL_TIP', payload: 15} )).toEqual( { splitTotal: '', totalTax: '', totalTip: 15, splitName: '', splitter: { name: '', phone: '', items: [], debtTotal: null, tax: null, tip: null, total: null, }, debtors: [], picture: null } ); }); it('should update the split name', () => { expect( reducer( intialState, {type: 'SET_SPLIT_NAME', payload: 'test'} )).toEqual( { splitTotal: '', totalTax: '', totalTip: '', splitName: 'test', splitter: { name: '', phone: '', items: [], debtTotal: null, tax: null, tip: null, total: null, }, debtors: [], picture: null } ); }); it('should update the splitter name', () => { expect( reducer( intialState, {type: 'SET_SPLITTER_NAME', payload: 'test'} )).toEqual( { splitTotal: '', totalTax: '', totalTip: '', splitName: '', splitter: { name: 'test', phone: '', items: [], debtTotal: null, tax: null, tip: null, total: null, }, debtors: [], picture: null } ); }); it('should update the splitter phone', () => { expect( reducer( intialState, {type: 'SET_SPLITTER_PHONE', payload: '1234567890'} )).toEqual( { splitTotal: '', totalTax: '', totalTip: '', splitName: '', splitter: { name: '', phone: '1234567890', items: [], debtTotal: null, tax: null, tip: null, total: null, }, debtors: [], picture: null } ); }); it('should update the splitter items', () => { expect( reducer( intialState, {type: 'SET_SPLITTER_ITEMS', payload: [{test: 'item'}]} )).toEqual( { splitTotal: '', totalTax: '', totalTip: '', splitName: '', splitter: { name: '', phone: '', items: [{test: 'item'}], debtTotal: null, tax: null, tip: null, total: null, }, debtors: [], picture: null } ); }); it('should update debtors', () => { expect( reducer( intialState, {type: 'SET_DEBTORS', payload: [{debtors: 'test'}]} )).toEqual( { splitTotal: '', totalTax: '', totalTip: '', splitName: '', splitter: { name: '', phone: '', items: [], debtTotal: null, tax: null, tip: null, total: null, }, debtors: [{debtors: 'test'}], picture: null } ); }); it('should update the splitter total', () => { expect( reducer( intialState, {type: 'SET_SPLITTER_DEBTTOTAL', payload: 15} )).toEqual( { splitTotal: '', totalTax: '', totalTip: '', splitName: '', splitter: { name: '', phone: '', items: [], debtTotal: 15, tax: null, tip: null, total: null, }, debtors: [], picture: null } ); }); it('should update the splitter tax', () => { expect( reducer( intialState, {type: 'SET_SPLITTER_TAX', payload: 15} )).toEqual( { splitTotal: '', totalTax: '', totalTip: '', splitName: '', splitter: { name: '', phone: '', items: [], debtTotal: null, tax: 15, tip: null, total: null, }, debtors: [], picture: null } ); }); it('should update the splitter tip', () => { expect( reducer( intialState, {type: 'SET_SPLITTER_TIP', payload: 15} )).toEqual( { splitTotal: '', totalTax: '', totalTip: '', splitName: '', splitter: { name: '', phone: '', items: [], debtTotal: null, tax: null, tip: 15, total: null, }, debtors: [], picture: null } ); }); it('should update the Debtors', () => { expect( reducer( intialState, {type: 'ADD_DEBTOR', payload: {username: 'newguy'}} )).toEqual( { splitTotal: '', totalTax: '', totalTip: '', splitName: '', splitter: { name: '', phone: '', items: [], debtTotal: null, tax: null, tip: null, total: null, }, debtors: [{username: 'newguy'}], picture: null } ); }); });
import { getLog } from '../../core/log'; const log = getLog('data/source/commentRepository'); import { Comment, Like, User } from '../models'; import sequelize from '../sequelize'; const getByUuid = async (uuid) => { const comment = await Comment.findOne({ where: { uuid }, include: { model: User, as: 'user' } }); if (!comment) { throw new Error('Comment not found'); } return comment; }; const getIdByUuid = async (uuid) => { const comment = await Comment.findOne({ attributes: [ 'id' ], where: { uuid } }); return comment.id; }; const getUuidById = async (id) => { const comment = await Comment.findOne({ attributes: [ 'uuid' ], where: { id } }); return comment.uuid; }; export default { getByUuid, getIdByUuid, getUuidById, create: async (comment) => { const created = await Comment.create(comment); if (!created) { throw new Error('failed to create a comment (null result)'); } return created; }, update: async (comment) => { const existing = await Comment.findOne({ where: { uuid: comment.uuid } }); if (!existing) { throw new Error('Could not update comment, original comment not found'); } delete comment.uuid; await Comment.update(comment, { where: { id: existing.id } }); return await Comment.findOne({ where: { id: existing.id } }); }, deleteComment: async (commentUuid) => { const comment = await Comment.findOne({ where: { uuid: commentUuid } }); if (!comment) throw new Error(`Could not find Comment uuid=${commentUuid} for deletion.`); await comment.destroy(); return comment; }, getComment: async (where, options) => { const comment = await Comment.findOne({ where, include: { model: User, as: 'user' }, ...options }); return comment; }, getComments: async (where, options) => { const comments = await Comment.findAll({ where, include: { model: User, as: 'user' }, order: [['createdAt', 'DESC']], ...options }); return comments; }, saveLike: async (like) => { const savedLike = await Like.create(like); return savedLike; }, deleteLike: async (userId, entityId, entityType) => { const like = await Like.findOne({ where: { userId, entityId, entityType } }); await like.destroy(); return like; }, deleteLikes: async (where) => { const deletedLikes = await Like.destroy({ where }); }, countLikes: async (where) => { let query = `SELECT COUNT(id) FROM "Like" WHERE`; const { userId, entityId, entityType } = where; const criteria = []; if (userId) { criteria.push(`"userId" = ${userId}`); } if (entityId) { criteria.push(`"entityId" = ${entityId}`); } if (entityType) { criteria.push(`"entityType" = '${entityType}'`); } query += ' ' + criteria.join(' AND '); const likeCount = await sequelize.query(query, { type: sequelize.QueryTypes.SELECT }); return likeCount[0].count; } };
const assert = require('assert'); const path = require('path'); const http = require('http'); const url = require('url'); describe('<webview> tag', function() { this.timeout(10000); var fixtures = path.join(__dirname, 'fixtures'); var webview = null; beforeEach(function() { webview = new WebView; }); afterEach(function() { if (document.body.contains(webview)) { document.body.removeChild(webview); } }); describe('src attribute', function() { it('specifies the page to load', function(done) { webview.addEventListener('console-message', function(e) { assert.equal(e.message, 'a'); done(); }); webview.src = "file://" + fixtures + "/pages/a.html"; document.body.appendChild(webview); }); it('navigates to new page when changed', function(done) { var listener = function() { webview.src = "file://" + fixtures + "/pages/b.html"; webview.addEventListener('console-message', function(e) { assert.equal(e.message, 'b'); done(); }); webview.removeEventListener('did-finish-load', listener); }; webview.addEventListener('did-finish-load', listener); webview.src = "file://" + fixtures + "/pages/a.html"; document.body.appendChild(webview); }); }); describe('nodeintegration attribute', function() { it('inserts no node symbols when not set', function(done) { webview.addEventListener('console-message', function(e) { assert.equal(e.message, 'undefined undefined undefined undefined'); done(); }); webview.src = "file://" + fixtures + "/pages/c.html"; document.body.appendChild(webview); }); it('inserts node symbols when set', function(done) { webview.addEventListener('console-message', function(e) { assert.equal(e.message, 'function object object'); done(); }); webview.setAttribute('nodeintegration', 'on'); webview.src = "file://" + fixtures + "/pages/d.html"; document.body.appendChild(webview); }); it('loads node symbols after POST navigation when set', function(done) { webview.addEventListener('console-message', function(e) { assert.equal(e.message, 'function object object'); done(); }); webview.setAttribute('nodeintegration', 'on'); webview.src = "file://" + fixtures + "/pages/post.html"; document.body.appendChild(webview); }); if (process.platform !== 'win32' || process.execPath.toLowerCase().indexOf('\\out\\d\\') === -1) { it('loads native modules when navigation happens', function(done) { var listener = function() { webview.removeEventListener('did-finish-load', listener); var listener2 = function(e) { assert.equal(e.message, 'function'); done(); }; webview.addEventListener('console-message', listener2); webview.reload(); }; webview.addEventListener('did-finish-load', listener); webview.setAttribute('nodeintegration', 'on'); webview.src = "file://" + fixtures + "/pages/native-module.html"; document.body.appendChild(webview); }); } }); describe('preload attribute', function() { it('loads the script before other scripts in window', function(done) { var listener = function(e) { assert.equal(e.message, 'function object object'); webview.removeEventListener('console-message', listener); done(); }; webview.addEventListener('console-message', listener); webview.setAttribute('preload', fixtures + "/module/preload.js"); webview.src = "file://" + fixtures + "/pages/e.html"; document.body.appendChild(webview); }); it('preload script can still use "process" in required modules when nodeintegration is off', function(done) { webview.addEventListener('console-message', function(e) { assert.equal(e.message, 'object undefined object'); done(); }); webview.setAttribute('preload', fixtures + "/module/preload-node-off.js"); webview.src = "file://" + fixtures + "/api/blank.html"; document.body.appendChild(webview); }); it('receives ipc message in preload script', function(done) { var message = 'boom!'; var listener = function(e) { assert.equal(e.channel, 'pong'); assert.deepEqual(e.args, [message]); webview.removeEventListener('ipc-message', listener); done(); }; var listener2 = function() { webview.send('ping', message); webview.removeEventListener('did-finish-load', listener2); }; webview.addEventListener('ipc-message', listener); webview.addEventListener('did-finish-load', listener2); webview.setAttribute('preload', fixtures + "/module/preload-ipc.js"); webview.src = "file://" + fixtures + "/pages/e.html"; document.body.appendChild(webview); }); }); describe('httpreferrer attribute', function() { it('sets the referrer url', function(done) { var referrer = 'http://github.com/'; var listener = function(e) { assert.equal(e.message, referrer); webview.removeEventListener('console-message', listener); done(); }; webview.addEventListener('console-message', listener); webview.setAttribute('httpreferrer', referrer); webview.src = "file://" + fixtures + "/pages/referrer.html"; document.body.appendChild(webview); }); }); describe('useragent attribute', function() { it('sets the user agent', function(done) { var referrer = 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko'; var listener = function(e) { assert.equal(e.message, referrer); webview.removeEventListener('console-message', listener); done(); }; webview.addEventListener('console-message', listener); webview.setAttribute('useragent', referrer); webview.src = "file://" + fixtures + "/pages/useragent.html"; document.body.appendChild(webview); }); }); describe('disablewebsecurity attribute', function() { it('does not disable web security when not set', function(done) { var src = "<script src='file://" + __dirname + "/static/jquery-2.0.3.min.js'></script> <script>console.log('ok');</script>"; var encoded = btoa(unescape(encodeURIComponent(src))); var listener = function(e) { assert(/Not allowed to load local resource/.test(e.message)); webview.removeEventListener('console-message', listener); done(); }; webview.addEventListener('console-message', listener); webview.src = "data:text/html;base64," + encoded; document.body.appendChild(webview); }); it('disables web security when set', function(done) { var src = "<script src='file://" + __dirname + "/static/jquery-2.0.3.min.js'></script> <script>console.log('ok');</script>"; var encoded = btoa(unescape(encodeURIComponent(src))); var listener = function(e) { assert.equal(e.message, 'ok'); webview.removeEventListener('console-message', listener); done(); }; webview.addEventListener('console-message', listener); webview.setAttribute('disablewebsecurity', ''); webview.src = "data:text/html;base64," + encoded; document.body.appendChild(webview); }); }); describe('partition attribute', function() { it('inserts no node symbols when not set', function(done) { webview.addEventListener('console-message', function(e) { assert.equal(e.message, 'undefined undefined undefined undefined'); done(); }); webview.src = "file://" + fixtures + "/pages/c.html"; webview.partition = 'test1'; document.body.appendChild(webview); }); it('inserts node symbols when set', function(done) { webview.addEventListener('console-message', function(e) { assert.equal(e.message, 'function object object'); done(); }); webview.setAttribute('nodeintegration', 'on'); webview.src = "file://" + fixtures + "/pages/d.html"; webview.partition = 'test2'; document.body.appendChild(webview); }); it('isolates storage for different id', function(done) { var listener = function(e) { assert.equal(e.message, " 0"); webview.removeEventListener('console-message', listener); done(); }; window.localStorage.setItem('test', 'one'); webview.addEventListener('console-message', listener); webview.src = "file://" + fixtures + "/pages/partition/one.html"; webview.partition = 'test3'; document.body.appendChild(webview); }); it('uses current session storage when no id is provided', function(done) { var listener = function(e) { assert.equal(e.message, "one 1"); webview.removeEventListener('console-message', listener); done(); }; window.localStorage.setItem('test', 'one'); webview.addEventListener('console-message', listener); webview.src = "file://" + fixtures + "/pages/partition/one.html"; document.body.appendChild(webview); }); }); describe('allowpopups attribute', function() { it('can not open new window when not set', function(done) { var listener = function(e) { assert.equal(e.message, 'null'); webview.removeEventListener('console-message', listener); done(); }; webview.addEventListener('console-message', listener); webview.src = "file://" + fixtures + "/pages/window-open-hide.html"; document.body.appendChild(webview); }); it('can open new window when set', function(done) { var listener = function(e) { assert.equal(e.message, 'window'); webview.removeEventListener('console-message', listener); done(); }; webview.addEventListener('console-message', listener); webview.setAttribute('allowpopups', 'on'); webview.src = "file://" + fixtures + "/pages/window-open-hide.html"; document.body.appendChild(webview); }); }); describe('new-window event', function() { it('emits when window.open is called', function(done) { webview.addEventListener('new-window', function(e) { assert.equal(e.url, 'http://host/'); assert.equal(e.frameName, 'host'); done(); }); webview.src = "file://" + fixtures + "/pages/window-open.html"; document.body.appendChild(webview); }); it('emits when link with target is called', function(done) { webview.addEventListener('new-window', function(e) { assert.equal(e.url, 'http://host/'); assert.equal(e.frameName, 'target'); done(); }); webview.src = "file://" + fixtures + "/pages/target-name.html"; document.body.appendChild(webview); }); }); describe('ipc-message event', function() { it('emits when guest sends a ipc message to browser', function(done) { webview.addEventListener('ipc-message', function(e) { assert.equal(e.channel, 'channel'); assert.deepEqual(e.args, ['arg1', 'arg2']); done(); }); webview.src = "file://" + fixtures + "/pages/ipc-message.html"; webview.setAttribute('nodeintegration', 'on'); document.body.appendChild(webview); }); }); describe('page-title-set event', function() { it('emits when title is set', function(done) { webview.addEventListener('page-title-set', function(e) { assert.equal(e.title, 'test'); assert(e.explicitSet); done(); }); webview.src = "file://" + fixtures + "/pages/a.html"; document.body.appendChild(webview); }); }); describe('page-favicon-updated event', function() { it('emits when favicon urls are received', function(done) { webview.addEventListener('page-favicon-updated', function(e) { assert.equal(e.favicons.length, 2); var pageUrl = process.platform === 'win32' ? 'file:///C:/favicon.png' : 'file:///favicon.png'; assert.equal(e.favicons[0], pageUrl); done(); }); webview.src = "file://" + fixtures + "/pages/a.html"; document.body.appendChild(webview); }); }); describe('will-navigate event', function() { it('emits when a url that leads to oustide of the page is clicked', function(done) { webview.addEventListener('will-navigate', function(e) { assert.equal(e.url, "http://host/"); done(); }); webview.src = "file://" + fixtures + "/pages/webview-will-navigate.html"; document.body.appendChild(webview); }); }); describe('did-navigate event', function() { var p = path.join(fixtures, 'pages', 'webview-will-navigate.html'); p = p.replace(/\\/g, '/'); var pageUrl = url.format({ protocol: 'file', slashes: true, pathname: p }); it('emits when a url that leads to outside of the page is clicked', function(done) { webview.addEventListener('did-navigate', function(e) { assert.equal(e.url, pageUrl); done(); }); webview.src = pageUrl; document.body.appendChild(webview); }); }); describe('did-navigate-in-page event', function() { it('emits when an anchor link is clicked', function(done) { var p = path.join(fixtures, 'pages', 'webview-did-navigate-in-page.html'); p = p.replace(/\\/g, '/'); var pageUrl = url.format({ protocol: 'file', slashes: true, pathname: p }); webview.addEventListener('did-navigate-in-page', function(e) { assert.equal(e.url, pageUrl + "#test_content"); done(); }); webview.src = pageUrl; document.body.appendChild(webview); }); it('emits when window.history.replaceState is called', function(done) { webview.addEventListener('did-navigate-in-page', function(e) { assert.equal(e.url, "http://host/"); done(); }); webview.src = "file://" + fixtures + "/pages/webview-did-navigate-in-page-with-history.html"; document.body.appendChild(webview); }); it('emits when window.location.hash is changed', function(done) { var p = path.join(fixtures, 'pages', 'webview-did-navigate-in-page-with-hash.html'); p = p.replace(/\\/g, '/'); var pageUrl = url.format({ protocol: 'file', slashes: true, pathname: p }); webview.addEventListener('did-navigate-in-page', function(e) { assert.equal(e.url, pageUrl + "#test"); done(); }); webview.src = pageUrl; document.body.appendChild(webview); }); }); describe('close event', function() { it('should fire when interior page calls window.close', function(done) { webview.addEventListener('close', function() { done(); }); webview.src = "file://" + fixtures + "/pages/close.html"; document.body.appendChild(webview); }); }); describe('devtools-opened event', function() { it('should fire when webview.openDevTools() is called', function(done) { var listener = function() { webview.removeEventListener('devtools-opened', listener); webview.closeDevTools(); done(); }; webview.addEventListener('devtools-opened', listener); webview.addEventListener('dom-ready', function() { webview.openDevTools(); }); webview.src = "file://" + fixtures + "/pages/base-page.html"; document.body.appendChild(webview); }); }); describe('devtools-closed event', function() { it('should fire when webview.closeDevTools() is called', function(done) { var listener2 = function() { webview.removeEventListener('devtools-closed', listener2); done(); }; var listener = function() { webview.removeEventListener('devtools-opened', listener); webview.closeDevTools(); }; webview.addEventListener('devtools-opened', listener); webview.addEventListener('devtools-closed', listener2); webview.addEventListener('dom-ready', function() { webview.openDevTools(); }); webview.src = "file://" + fixtures + "/pages/base-page.html"; document.body.appendChild(webview); }); }); describe('devtools-focused event', function() { it('should fire when webview.openDevTools() is called', function(done) { var listener = function() { webview.removeEventListener('devtools-focused', listener); webview.closeDevTools(); done(); }; webview.addEventListener('devtools-focused', listener); webview.addEventListener('dom-ready', function() { webview.openDevTools(); }); webview.src = "file://" + fixtures + "/pages/base-page.html"; document.body.appendChild(webview); }); }); describe('<webview>.reload()', function() { it('should emit beforeunload handler', function(done) { var listener = function(e) { assert.equal(e.channel, 'onbeforeunload'); webview.removeEventListener('ipc-message', listener); done(); }; var listener2 = function() { webview.reload(); webview.removeEventListener('did-finish-load', listener2); }; webview.addEventListener('ipc-message', listener); webview.addEventListener('did-finish-load', listener2); webview.setAttribute('nodeintegration', 'on'); webview.src = "file://" + fixtures + "/pages/beforeunload-false.html"; document.body.appendChild(webview); }); }); describe('<webview>.clearHistory()', function() { it('should clear the navigation history', function(done) { var listener = function(e) { assert.equal(e.channel, 'history'); assert.equal(e.args[0], 2); assert(webview.canGoBack()); webview.clearHistory(); assert(!webview.canGoBack()); webview.removeEventListener('ipc-message', listener); done(); }; webview.addEventListener('ipc-message', listener); webview.setAttribute('nodeintegration', 'on'); webview.src = "file://" + fixtures + "/pages/history.html"; document.body.appendChild(webview); }); }); describe('basic auth', function() { var auth = require('basic-auth'); it('should authenticate with correct credentials', function(done) { var message = 'Authenticated'; var server = http.createServer(function(req, res) { var credentials = auth(req); if (credentials.name === 'test' && credentials.pass === 'test') { res.end(message); } else { res.end('failed'); } server.close(); }); server.listen(0, '127.0.0.1', function() { var port = server.address().port; webview.addEventListener('ipc-message', function(e) { assert.equal(e.channel, message); done(); }); webview.src = "file://" + fixtures + "/pages/basic-auth.html?port=" + port; webview.setAttribute('nodeintegration', 'on'); document.body.appendChild(webview); }); }); }); describe('dom-ready event', function() { it('emits when document is loaded', function(done) { var server = http.createServer(function() {}); server.listen(0, '127.0.0.1', function() { var port = server.address().port; webview.addEventListener('dom-ready', function() { done(); }); webview.src = "file://" + fixtures + "/pages/dom-ready.html?port=" + port; document.body.appendChild(webview); }); }); it('throws a custom error when an API method is called before the event is emitted', function() { assert.throws(function () { webview.stop(); }, 'Cannot call stop because the webContents is unavailable. The WebView must be attached to the DOM and the dom-ready event emitted before this method can be called.'); }); }); describe('executeJavaScript', function() { it('should support user gesture', function(done) { if (process.env.TRAVIS !== 'true' || process.platform == 'darwin') return done(); var listener = function() { webview.removeEventListener('enter-html-full-screen', listener); done(); }; var listener2 = function() { var jsScript = "document.querySelector('video').webkitRequestFullscreen()"; webview.executeJavaScript(jsScript, true); webview.removeEventListener('did-finish-load', listener2); }; webview.addEventListener('enter-html-full-screen', listener); webview.addEventListener('did-finish-load', listener2); webview.src = "file://" + fixtures + "/pages/fullscreen.html"; document.body.appendChild(webview); }); it('can return the result of the executed script', function(done) { if (process.env.TRAVIS === 'true' && process.platform == 'darwin') return done(); var listener = function() { var jsScript = "'4'+2"; webview.executeJavaScript(jsScript, false, function(result) { assert.equal(result, '42'); done(); }); webview.removeEventListener('did-finish-load', listener); }; webview.addEventListener('did-finish-load', listener); webview.src = "about:blank"; document.body.appendChild(webview); }); }); describe('sendInputEvent', function() { it('can send keyboard event', function(done) { webview.addEventListener('ipc-message', function(e) { assert.equal(e.channel, 'keyup'); assert.deepEqual(e.args, [67, true, false]); done(); }); webview.addEventListener('dom-ready', function() { webview.sendInputEvent({ type: 'keyup', keyCode: 'c', modifiers: ['shift'] }); }); webview.src = "file://" + fixtures + "/pages/onkeyup.html"; webview.setAttribute('nodeintegration', 'on'); document.body.appendChild(webview); }); it('can send mouse event', function(done) { webview.addEventListener('ipc-message', function(e) { assert.equal(e.channel, 'mouseup'); assert.deepEqual(e.args, [10, 20, false, true]); done(); }); webview.addEventListener('dom-ready', function() { webview.sendInputEvent({ type: 'mouseup', modifiers: ['ctrl'], x: 10, y: 20 }); }); webview.src = "file://" + fixtures + "/pages/onmouseup.html"; webview.setAttribute('nodeintegration', 'on'); document.body.appendChild(webview); }); }); describe('media-started-playing media-paused events', function() { it('emits when audio starts and stops playing', function(done) { var audioPlayed = false; webview.addEventListener('media-started-playing', function() { audioPlayed = true; }); webview.addEventListener('media-paused', function() { assert(audioPlayed); done(); }); webview.src = "file://" + fixtures + "/pages/audio.html"; document.body.appendChild(webview); }); }); describe('found-in-page event', function() { it('emits when a request is made', function(done) { var requestId = null; var totalMatches = null; var activeMatchOrdinal = []; var listener = function(e) { assert.equal(e.result.requestId, requestId); if (e.result.finalUpdate) { assert.equal(e.result.matches, 3); totalMatches = e.result.matches; listener2(); } else { activeMatchOrdinal.push(e.result.activeMatchOrdinal); if (e.result.activeMatchOrdinal == totalMatches) { assert.deepEqual(activeMatchOrdinal, [1, 2, 3]); webview.stopFindInPage("clearSelection"); done(); } } }; var listener2 = function() { requestId = webview.findInPage("virtual"); }; webview.addEventListener('found-in-page', listener); webview.addEventListener('did-finish-load', listener2); webview.src = "file://" + fixtures + "/pages/content.html"; document.body.appendChild(webview); }); }); xdescribe('did-change-theme-color event', function() { it('emits when theme color changes', function(done) { webview.addEventListener('did-change-theme-color', function() { done(); }); webview.src = "file://" + fixtures + "/pages/theme-color.html"; document.body.appendChild(webview); }); }); describe('permission-request event', function() { function setUpRequestHandler(webview, requested_permission) { const session = require('electron').remote.session; var listener = function(webContents, permission, callback) { if (webContents.getId() === webview.getId() ) { assert.equal(permission, requested_permission); callback(false); } }; session.fromPartition(webview.partition).setPermissionRequestHandler(listener); } it('emits when using navigator.getUserMedia api', function(done) { webview.addEventListener('ipc-message', function(e) { assert(e.channel, 'message'); assert(e.args, ['PermissionDeniedError']); done(); }); webview.src = "file://" + fixtures + "/pages/permissions/media.html"; webview.partition = "permissionTest"; webview.setAttribute('nodeintegration', 'on'); setUpRequestHandler(webview, "media"); document.body.appendChild(webview); }); it('emits when using navigator.geolocation api', function(done) { webview.addEventListener('ipc-message', function(e) { assert(e.channel, 'message'); assert(e.args, ['ERROR(1): User denied Geolocation']); done(); }); webview.src = "file://" + fixtures + "/pages/permissions/geolocation.html"; webview.partition = "permissionTest"; webview.setAttribute('nodeintegration', 'on'); setUpRequestHandler(webview, "geolocation"); document.body.appendChild(webview); }); it('emits when using navigator.requestMIDIAccess api', function(done) { webview.addEventListener('ipc-message', function(e) { assert(e.channel, 'message'); assert(e.args, ['SecurityError']); done(); }); webview.src = "file://" + fixtures + "/pages/permissions/midi.html"; webview.partition = "permissionTest"; webview.setAttribute('nodeintegration', 'on'); setUpRequestHandler(webview, "midiSysex"); document.body.appendChild(webview); }); }); describe('<webview>.getWebContents', function() { it('can return the webcontents associated', function(done) { webview.addEventListener('did-finish-load', function() { const webviewContents = webview.getWebContents(); assert(webviewContents); assert.equal(webviewContents.getURL(), 'about:blank'); done(); }); webview.src = "about:blank"; document.body.appendChild(webview); }); }); });
"use strict"; /** * This class contains methods to build common {@link https://cs.cmu.edu/~kmcrane/Projects/DDG/paper.pdf discrete exterior calculus} operators. * @memberof module:Core */ class DEC { /** * Builds a sparse diagonal matrix encoding the Hodge operator on 0-forms. * By convention, the area of a vertex is 1. * @static * @param {module:Core.Geometry} geometry The geometry of a mesh. * @param {Object} vertexIndex A dictionary mapping each vertex of a mesh to a unique index. * @returns {module:LinearAlgebra.SparseMatrix} */ static buildHodgeStar0Form(geometry, vertexIndex) { let vertices = geometry.mesh.vertices; let V = vertices.length; let T = new Triplet(V, V); for (let v of vertices) { let i = vertexIndex[v]; let area = geometry.barycentricDualArea(v); T.addEntry(area, i, i); } return SparseMatrix.fromTriplet(T); } /** * Builds a sparse diagonal matrix encoding the Hodge operator on 1-forms. * @static * @param {module:Core.Geometry} geometry The geometry of a mesh. * @param {Object} edgeIndex A dictionary mapping each edge of a mesh to a unique index. * @returns {module:LinearAlgebra.SparseMatrix} */ static buildHodgeStar1Form(geometry, edgeIndex) { let edges = geometry.mesh.edges; let E = edges.length; let T = new Triplet(E, E); for (let e of edges) { let i = edgeIndex[e]; let w = (geometry.cotan(e.halfedge) + geometry.cotan(e.halfedge.twin)) / 2; T.addEntry(w, i, i); } return SparseMatrix.fromTriplet(T); } /** * Builds a sparse diagonal matrix encoding the Hodge operator on 2-forms. * By convention, the area of a vertex is 1. * @static * @param {module:Core.Geometry} geometry The geometry of a mesh. * @param {Object} faceIndex A dictionary mapping each face of a mesh to a unique index. * @returns {module:LinearAlgebra.SparseMatrix} */ static buildHodgeStar2Form(geometry, faceIndex) { let faces = geometry.mesh.faces; let F = faces.length; let T = new Triplet(F, F); for (let f of faces) { let i = faceIndex[f]; let area = geometry.area(f); T.addEntry(1 / area, i, i); } return SparseMatrix.fromTriplet(T); } /** * Builds a sparse matrix encoding the exterior derivative on 0-forms. * @static * @param {module:Core.Geometry} geometry The geometry of a mesh. * @param {Object} edgeIndex A dictionary mapping each edge of a mesh to a unique index. * @param {Object} vertexIndex A dictionary mapping each vertex of a mesh to a unique index. * @returns {module:LinearAlgebra.SparseMatrix} */ static buildExteriorDerivative0Form(geometry, edgeIndex, vertexIndex) { let edges = geometry.mesh.edges; let vertices = geometry.mesh.vertices; let E = edges.length; let V = vertices.length; let T = new Triplet(E, V); for (let e of edges) { let i = edgeIndex[e]; let j = vertexIndex[e.halfedge.vertex]; let k = vertexIndex[e.halfedge.twin.vertex]; T.addEntry(1, i, j); T.addEntry(-1, i, k); } return SparseMatrix.fromTriplet(T); } /** * Builds a sparse matrix encoding the exterior derivative on 1-forms. * @static * @param {module:Core.Geometry} geometry The geometry of a mesh. * @param {Object} faceIndex A dictionary mapping each face of a mesh to a unique index. * @param {Object} edgeIndex A dictionary mapping each edge of a mesh to a unique index. * @returns {module:LinearAlgebra.SparseMatrix} */ static buildExteriorDerivative1Form(geometry, faceIndex, edgeIndex) { let faces = geometry.mesh.faces; let edges = geometry.mesh.edges; let F = faces.length; let E = edges.length; let T = new Triplet(F, E); for (let f of faces) { let i = faceIndex[f]; for (let h of f.adjacentHalfedges()) { let j = edgeIndex[h.edge]; let sign = h.edge.halfedge === h ? 1 : -1; T.addEntry(sign, i, j); } } return SparseMatrix.fromTriplet(T); } }
var User = Ember.Object.extend({ isAnonymous: function () { return this.get("provider") === "anonymous"; }.property("email"), emailMD5: function () { return md5(this.getWithDefault("email", "")); }.property("email"), gravatarURL: function () { return "//www.gravatar.com/avatar/" + this.get("emailMD5") + "?d=mm"; }.property("emailMD5"), name: function () { return this.get("displayName") || this.get("email") || "Gość"; }.property("displayName", "email"), firebaseAuthTokenDidChange: function () { window.ENV.FIREBASE_AUTH_TOKEN = this.get("firebaseAuthToken"); }.observes("firebaseAuthToken").on("init"), idDidChange: function () { window.ENV.FIREBASE_USER_ID = this.get("id"); }.observes("id").on("init"), login: function (method) { var model = this, firebase = new window.Firebase(window.ENV.FIREBASE_URL); return new Ember.RSVP.Promise(function (resolve, reject) { new window.FirebaseSimpleLogin(firebase, function (error, user) { if (error) { reject(error); } else if (user && user.provider === method) { resolve(user); } }).login(method); }).then(function (user) { model.setProperties($.extend({}, model.constructor.blankProperties, user)); return model; }); }, logout: function () { var model = this, firebase = new window.Firebase(window.ENV.FIREBASE_URL); return new Ember.RSVP.Promise(function (resolve, reject) { new window.FirebaseSimpleLogin(firebase, function (error, user) { if (error) { reject(error); } else { resolve(user); } }).logout(); }).then(function (user) { return model.login("anonymous"); }); } }); User.reopenClass({ blankProperties: { displayName: null, email: null, firebaseAuthToken: null, id: null, md5_hash: null, provider: null, uid: null }, fetch: function () { var model = this.create(), firebase = new window.Firebase(window.ENV.FIREBASE_URL); return new Ember.RSVP.Promise(function (resolve, reject) { new window.FirebaseSimpleLogin(firebase, function (error, user) { if (error) { reject(error); } else { resolve(user); } }); }).then(function (user) { if (user) { model.setProperties(user); return model; } else { return model.login("anonymous"); } }); } }); export default User;
import { h } from 'omi'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(h("path", { d: "M4.49 4.21L3.43 5.27 7.85 16.4l1.48-1.48-.92-2.19 3.54-3.54 2.19.92 1.48-1.48L4.49 4.21zm3.09 6.8L5.36 6.14l4.87 2.23-2.65 2.64zm12.99-1.68h-4.24l1.41 1.41-8.84 8.84L10.32 21l8.84-8.84 1.41 1.41V9.33z" }), 'TextRotationAngleup');
'use strict'; const passport = require('passport'); const BasicStrategy = require('passport-http').BasicStrategy; const Logger = require('./logger')('debug', 'auth-basic'); const User = require('../models/user'); passport.use(new BasicStrategy((username, password, callback) => { Logger.info('Checking credentials for user: %s', username); User.findOne({ username: username }, (err, user) => { if (err) { Logger.error('Error', err); return callback(err); } // No user found with that username if (!user) { Logger.error('User not found'); return callback(null, false, {message: 'User not found'}); } // Make sure the password is correct if (!user.validPassword(password)) { Logger.error('Wrong password'); return callback(null, false), {message: 'Wrong password'}; } // Success Logger.info('Successfully authenticated'); return callback(null, user); }); })); module.exports = passport;
System.register(['angular2/core', 'angular2/router', './dashboard.component', './view.component', './add.component', './edit.component'], function(exports_1, context_1) { "use strict"; var __moduleName = context_1 && context_1.id; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var core_1, router_1, dashboard_component_1, view_component_1, add_component_1, edit_component_1; var EvaluationComponent; return { setters:[ function (core_1_1) { core_1 = core_1_1; }, function (router_1_1) { router_1 = router_1_1; }, function (dashboard_component_1_1) { dashboard_component_1 = dashboard_component_1_1; }, function (view_component_1_1) { view_component_1 = view_component_1_1; }, function (add_component_1_1) { add_component_1 = add_component_1_1; }, function (edit_component_1_1) { edit_component_1 = edit_component_1_1; }], execute: function() { EvaluationComponent = (function () { function EvaluationComponent() { } EvaluationComponent = __decorate([ core_1.Component({ templateUrl: 'templates/evaluation/evaluation.html', providers: [], directives: [router_1.ROUTER_DIRECTIVES] }), router_1.RouteConfig([ { path: '/', name: 'Evaluation', component: dashboard_component_1.EvaluationDashboardComponent, useAsDefault: true }, { path: '/view', name: 'EvaluationView', component: view_component_1.EvaluationViewComponent }, { path: '/add', name: 'EvaluationAdd', component: add_component_1.EvaluationAddComponent }, { path: '/edit', name: 'EvaluationEdit', component: edit_component_1.EvaluationEditComponent } ]), __metadata('design:paramtypes', []) ], EvaluationComponent); return EvaluationComponent; }()); exports_1("EvaluationComponent", EvaluationComponent); } } }); //# sourceMappingURL=evaluation.component.js.map
var fs = require( 'fs' ) var path = require( 'path' ) var assert = require( 'assert' ) var MBR = require( 'mbr' ) var GPT = require( '../' ) var inspect = require( './inspect' ) describe( 'GUID Partition Table', function() { // TODO: // - Add a test GPT blob with entries set to zero // (the thing that still crashes Windows due to division by zero) // - Add tests with different blocksize disks (512, 2048, 4096, 8192) describe( 'BOOTCAMP', function() { var data = fs.readFileSync( path.join( __dirname, 'data', 'bootcamp.bin' ) ) var backupData = fs.readFileSync( path.join( __dirname, 'data', 'bootcamp-backup.bin' ) ) it( 'should be able to parse a BootCamp GPT', function() { var gpt = GPT.parse( data ) assert.equal( gpt.tableSize, 32 * gpt.blockSize ) inspect.log( gpt ) }) it( 'in/out buffer equality', function() { var gpt = GPT.parse( data ) var buffer = gpt.write() assert.equal( data.length, buffer.length ) assert.deepEqual( data, buffer ) }) it( 'verifies', function() { var gpt = GPT.parse( data ) assert.ok( gpt.verify() ) }) it( 'should be able to parse a backup GPT', function() { var gpt = GPT.parseBackup( backupData ) inspect.log( gpt ) }) it( 'backup in/out buffer equality', function() { var gpt = GPT.parseBackup( backupData ) var buffer = gpt.writeBackup() assert.equal( backupData.length, buffer.length ) assert.deepEqual( backupData, buffer ) }) it( 'verifies a backup GPT', function() { var gpt = GPT.parseBackup( backupData ) assert.ok( gpt.verify() ) }) }) describe( 'ExFAT', function() { var blockSize = 512 var data = fs.readFileSync( path.join( __dirname, 'data', 'gpt-primary-exfat.bin' ) ) var backupData = fs.readFileSync( path.join( __dirname, 'data', 'gpt-backup-exfat.bin' ) ) it( 'should be able to parse a BootCamp GPT', function() { var mbr = MBR.parse( data ) var gpt = GPT.parse( data, mbr.getEFIPart().firstLBA * blockSize ) assert.equal( gpt.tableSize, 32 * gpt.blockSize ) inspect.log( gpt ) }) it( 'in/out buffer equality', function() { var mbr = MBR.parse( data ) var offset = mbr.getEFIPart().firstLBA * blockSize var gpt = GPT.parse( data, offset ) var buffer = gpt.write() assert.equal( data.length - offset, buffer.length ) assert.deepEqual( data.slice( offset ), buffer ) }) it( 'verifies', function() { var mbr = MBR.parse( data ) var offset = mbr.getEFIPart().firstLBA * blockSize var gpt = GPT.parse( data, offset ) assert.ok( gpt.verify() ) }) it( 'should be able to parse a backup GPT', function() { var gpt = GPT.parseBackup( backupData ) inspect.log( gpt ) }) it( 'backup in/out buffer equality', function() { var gpt = GPT.parseBackup( backupData ) var buffer = gpt.writeBackup() assert.equal( backupData.length, buffer.length ) assert.deepEqual( backupData, buffer ) }) it( 'verifies a backup GPT', function() { var gpt = GPT.parseBackup( backupData ) assert.ok( gpt.verify() ) }) it( 'writes a backup from primary', function() { var gpt = GPT.parse( data, 512 ) var buffer = gpt.writeBackupFromPrimary() assert.equal( backupData.length, buffer.length ) assert.deepEqual( backupData, buffer ) }) }) describe( 'RASPBERRY PI MBR', function() { const DATAPATH = __dirname + '/data/raspberry.bin' var data = fs.readFileSync( DATAPATH ) it( 'should throw "Invalid Signature"', function() { assert.throws( function() { GPT.parse( data ) }) }) }) })
function filterStatus(filter){ filtered = $("td[data-status]").filter(function(index) { return this.dataset.status !== filter; }); return filtered; } function getStatus(filter){ filtered = $("td[data-status]").filter(function(index) { return this.dataset.status === filter; }); return filtered; } function showAllResult(){ $("td").parent().show(); } function displayFiltered(filterString){ var filtered = filterStatus(filterString); $(filtered).parent().hide(); } var $filters = $('.filters'); $.each($filters, function(index, val) { var text = $(this).text(); text += "(" + countStatus(this.dataset.filter) + ")"; $(this).text(text); }); $filters.on('click', function(event) { event.preventDefault(); showAllResult(); displayFiltered($(this).data("filter")); }); function countStatus(filterString){ var count = getStatus(filterString).length; return count; } $("#showAll").on('click', function(e){ e.preventDefault(); showAllResult(); });
angular.module('app.controllers') .controller('overviewCtrl', function($scope,$state,$ionicModal,sharedInfo, Auth, User, currentAuth, $window) { $scope.hasAPlan=false; $scope.logout = function(){ Auth.$unauth(); } console.log(currentAuth); Auth.$onAuth(function(authData){ if(!authData){ $state.go('login'); } }); var user = User(currentAuth.uid); user.$loaded().then(function(){ console.log(user); if(user.$value === null){ console.log("plan not set"); }else{ $scope.info = user.info; $scope.hasAPlan = true; } }); $ionicModal.fromTemplateUrl('templates/info/modalPreSetPlan.html', { scope: $scope }).then(function(modal) { $scope.modal = modal; }); $scope.beginConfig = function(){ $state.go('tabs.info'); } $scope.editInfo = function(){ //retrieve information from server $state.go('tabs.info'); } $scope.preSetPlan = {}; $scope.savePreSetPlan = function(form,preSetPlan){ if(!preSetPlan.cycling){ preSetPlan.cycling = false; } preSetPlan.type = "preset"; //save the data var user = User(currentAuth.uid); user.info = preSetPlan; user.$save().then(function(){ alert('Your plan was saved with success!'); $scope.modal.hide(); $window.location.reload(true); }).catch(function(error){ alert('Error: '+error); }) } });
'use strict'; // Declare app level module which depends on views, and components var myApp = angular.module('myApp', [ 'ngRoute', 'myApp.view1', 'myApp.view2', 'myApp.version', 'todoList' ]).config(['$locationProvider', '$routeProvider', '$httpProvider', function ($locationProvider, $routeProvider, $httpProvider) { $httpProvider.defaults.headers.common = {}; $httpProvider.defaults.headers.post = {}; $httpProvider.defaults.headers.put = {}; $httpProvider.defaults.headers.patch = {}; }]); myApp.directive('fileModel', ['$parse', function ($parse) { return { restrict: 'A', link: function (scope, element, attrs) { var model = $parse(attrs.fileModel); var modelSetter = model.assign; element.bind('change', function () { scope.$apply(function () { modelSetter(scope, element[0].files[0]); }); }); } }; }]); myApp.service('fileUpload', ['$http', function ($http) { this.uploadFileToUrl = function (file, uploadUrl) { var fd = new FormData(); fd.append('file', file); $http.post(uploadUrl, fd, { transformRequest: angular.identity, headers: {'Content-Type': undefined} }).success(function () { }) .error(function () { }); } }]); var todoList = angular.module('todoList', []); todoList.controller('todoCtrl', ['$scope', '$http', function ($scope, $http) { var urls = $scope.urls = []; $scope.myFile; $scope.foundCollection = ""; $scope.informations = ""; $scope.category = ""; $scope.addUrl = function () { var newUrl = $scope.newUrl; var apiWatsonKey = "2bf3d9e76fed69e0c6309b47bc40760bb8936da3"; var detectFacesUrl = "https://watson-api-explorer.mybluemix.net/visual-recognition/api/v3/detect_faces?api_key=" + apiWatsonKey + "&url=" + newUrl + "&version=2016-05-20"; $http({ method: 'POST', url: detectFacesUrl, headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' } }).then(function successCallback(response) { console.log(response.data.images[0].faces[0]); $scope.informations = "Collected information: minimum age " + response.data.images[0].faces[0].age.min + " and maximum age " + response.data.images[0].faces[0].age.max + " with score " + response.data.images[0].faces[0].age.score + " and sexe " + response.data.images[0].faces[0].gender.gender + " with score " + response.data.images[0].faces[0].gender.score; if (response.data.images[0].faces[0].gender.gender == 'MALE') { if ((response.data.images[0].faces[0].age.min > 1 || typeof(response.data.images[0].faces[0].age.min) == 'undefined') && response.data.images[0].faces[0].age.max <= 17) { $scope.category = "Category: BATMAN"; } else if (response.data.images[0].faces[0].age.min < 90 && response.data.images[0].faces[0].age.min > 50) $scope.category = "Category: Trump"; } else if (response.data.images[0].faces[0].gender.gender == 'FEMALE') { if ((response.data.images[0].faces[0].age.min > 1 || typeof(response.data.images[0].faces[0].age.min) == 'undefined') && response.data.images[0].faces[0].age.max <= 17) { $scope.category = "Category: Nintendo"; } else if (response.data.images[0].faces[0].age.min < 90 && response.data.images[0].faces[0].age.max > 44) $scope.category = "Category: Hillary"; } $http({ method: 'POST', url: 'https://eu11.salesforce.com/services/apexrest/resAcc', data: { "uniqueID": "uniqueIdIdz", "sex": response.data.images[0].faces[0].gender.gender, "age": response.data.images[0].faces[0].age.min, "accuracy": response.data.images[0].faces[0].age.score }, headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': 'Bearer 00D0Y000000akoN!AREAQOEciwfejiEZBnqI3ho0_1op3OXEvGUaF.rSuMyEyLuC6rwgM8Xx.x2NGuwSSfSBF48mrHFTE26ueye1NOnuYDo20YZ7' } }).then(function successCallback(response) { }, function errorCallback(response) { }); }, function errorCallback(response) { }); if (!newUrl.length) { return; } urls.push({ title: newUrl, completed: false }); $scope.newUrl = ''; }; $scope.removeUrls = function (todo) { urls.splice(urls.indexOf(todo), 1); }; $scope.markAll = function (completed) { urls.forEach(function (todo) { todo.completed = !completed; }); }; $scope.clearCompletedUrls = function () { $scope.urls = urls = urls.filter(function (todo) { return !todo.completed; }); }; $scope.uploadFile = function () { var collectionUrl = "https://watson-api-explorer.mybluemix.net/visual-recognition/api/v3/collections?" + "api_key=2bf3d9e76fed69e0c6309b47bc40760bb8936da3&version=2016-05-20"; var findSimilarUrl = ""; var findSimilarUrlFirstPart = "https://watson-api-explorer.mybluemix.net/visual-recognition/api/v3/collections/" var findSimilarUrlSecondPart = "/find_similar?" + "api_key=2bf3d9e76fed69e0c6309b47bc40760bb8936da3" + "&limit=1" + "&version=2016-05-20"; var file = $scope.myFile; $http({ method: 'GET', url: collectionUrl, headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' } }).then(function successCallback(response) { if (response.data.collections.length > 0) { var createCollection = true; for (var i = 0; i < response.data.collections.length; i++) { console.log(response.data.collections[i]); findSimilarUrl = findSimilarUrlFirstPart + response.data.collections[i].collection_id + findSimilarUrlSecondPart; var data = new FormData(); var collection = response.data.collections[i].collection_id; data.append("image_file", file); $http({ method: 'POST', url: findSimilarUrl, data: data, headers: { 'Accept': 'application/json' } }).then(function successCallback(response) { console.log(response.data.similar_images.length); if (response.data.similar_images.length > 0) { console.log(response.data.similar_images); for (var j = 0; j < response.data.similar_images.length; j++) { if (response.data.similar_images[j].score > 0.5) { $scope.foundCollection = "Result: A collection is found for the image: " + collection; createCollection = false; var addImageToCollectionUrl = "https://watson-api-explorer.mybluemix.net/visual-recognition/api/v3/collections/" + collection + "/images?api_key=2bf3d9e76fed69e0c6309b47bc40760bb8936da3&version=2016-05-20"; var data = new FormData(); data.append("image_file", file); $http({ method: 'POST', url: addImageToCollectionUrl, data: data, headers: { 'Accept': 'application/json' } }).then(function successCallback(response) { }, function errorCallback(response) { }); break; } if (createCollection == true) { createCollection = false; var collectionName = new FormData(); collectionName.append("name", "test") $http({ method: 'POST', url: collectionUrl, data: collectionName, headers: { 'Accept': 'application/json' } }).then(function successCallback(response) { $scope.foundCollection = "Result: No collection found, the image is added to a new collection : " + response.data.collection_id; var addImageToCollectionUrl = "https://watson-api-explorer.mybluemix.net/visual-recognition/api/v3/collections/" + response.data.collection_id + "/images?api_key=2bf3d9e76fed69e0c6309b47bc40760bb8936da3&version=2016-05-20"; $http({ method: 'POST', url: addImageToCollectionUrl, data: data, headers: { 'Accept': 'application/json' } }).then(function successCallback(response) { }, function errorCallback(response) { }); }, function errorCallback(response) { }); break; } } } }, function errorCallback(response) { }); } } else { console.log("NO collections") var collectionName = new FormData(); collectionName.append("name", "test") $http({ method: 'POST', url: collectionUrl, data: collectionName, headers: { 'Accept': 'application/json' } }).then(function successCallback(response) { $scope.foundCollection = "Result: No collection found, the image is added to a new collection : " + response.data.collection_id; var addImageToCollectionUrl = "https://watson-api-explorer.mybluemix.net/visual-recognition/api/v3/collections/" + response.data.collection_id + "/images?api_key=2bf3d9e76fed69e0c6309b47bc40760bb8936da3&version=2016-05-20"; var data = new FormData(); data.append("image_file", file); $http({ method: 'POST', url: addImageToCollectionUrl, data: data, headers: { 'Accept': 'application/json' } }).then(function successCallback(response) { }, function errorCallback(response) { }); }, function errorCallback(response) { }); } }, function errorCallback(response) { }); }; } ]);
//Autogenerated by ../../build_app.js import provenance_entity_component from 'ember-fhir-adapter/models/provenance-entity-component'; export default provenance_entity_component;
import config from '../config'; import changed from 'gulp-changed'; import gulp from 'gulp'; import browserSync from 'browser-sync'; gulp.task('fonts', function () { return gulp.src(config.fonts.src) .pipe(changed(config.fonts.dest)) // Ignore unchanged files .pipe(gulp.dest(config.fonts.dest)) .pipe(browserSync.stream()); });
(function() { 'use strict'; angular .module('material-lite') .controller('ChartsController', ['$scope', ChartsController]); function ChartsController($scope) { var pattern = []; pattern.push('#4CAF50'); pattern.push('#2196F3'); pattern.push('#9c27b0'); pattern.push('#ff9800'); pattern.push('#F44336'); $scope.color_pattern = pattern.join(); } })();
version https://git-lfs.github.com/spec/v1 oid sha256:970259e146984753268ea62411a482bf6e89ddc12a0da22705aace8276a89f80 size 9774
function main(args) { return {text: args.text.reverse()}; }
$(document).ready(function () { var scrollTop = 0; // Datapicker settings var datepickerOptions = { format: "dd.mm.yyyy", language: "ua", orientation: "top auto", todayHighlight: true, daysOfWeekDisabled: "0" }; // Init datapicker $('.input-group.date').each(function () { var $textField = $(this).find('input[type="text"]'); if ($(this).hasClass('next')) { datepickerOptions['startDate'] = '+7d'; $textField.val(Service.getNextDatetime()); } else { datepickerOptions['startDate'] = '0d'; $textField.val(Service.getDatetime()); } $(this).datepicker(datepickerOptions); }); var $requestButton = $('button.btn-request'); // Autocomplete common function fillAutocomplete($label, $value, data) { $label.val(data.item.label); $value.val(data.item.value); } // Autocomplete groups var $grText = $('div.input-group.groups input[type="text"]'); var $grHidden = $('div.input-group.groups input[type="hidden"]'); var $grLoading = $('div.input-group.groups .loading'); var $grCleaner = $('div.input-group.groups a.clear-input'); var $grPlaceholder = $('a.group-placeholder'); $grText.on('change', function() { $grText.val(''); $grHidden.val(''); $grCleaner.hide(); }); $grText.autocomplete({ source: 'php/index.php?method=getGroups', minLength: 1, search: function () { $grHidden.val(''); $grLoading.fadeIn(); }, response: function () { $grLoading.promise().done(function () { $grLoading.fadeOut(); } ); }, select: function (event, ui) { fillAutocomplete($grText, $grHidden, ui); $grCleaner.show(); $requestButton.focus(); return false; }, focus: function (event, ui) { fillAutocomplete($grText, $grHidden, ui); return false; } }); // Autocomplete to hidden fields $('.paramSwitch').click(function () { var $params = $('div.params'); $params.toggle(); if ($params.hasClass('loaded')) return true; $params.addClass('loaded'); // Autocomplete teachers var $tchText = $('div.input-group.teacher input[type="text"]'); var $tchHidden = $('div.input-group.teacher input[type="hidden"]'); var $tchLoading = $('div.input-group.teacher .loading'); var $tchCleaner = $('div.input-group.teacher a.clear-input'); $tchText.on('change', function() { $tchText.val(''); $tchHidden.val(''); $grCleaner.hide(); }); $tchText.autocomplete({ source: 'php/index.php?method=getTeachers', minLength: 2, search: function () { $tchHidden.val(''); $tchLoading.fadeIn(); }, response: function () { $tchLoading.promise().done(function () { $tchLoading.fadeOut() } ); }, select: function (event, ui) { fillAutocomplete($tchText, $tchHidden, ui); $requestButton.focus(); $tchCleaner.show(); return false; }, focus: function (event, ui) { fillAutocomplete($tchText, $tchHidden, ui); return false; } }); // Autocomplete rooms var $rmText = $('div.input-group.auditorium input[type="text"]'); var $rmHidden = $('div.input-group.auditorium input[type="hidden"]'); var $rmLoading = $('div.input-group.auditorium .loading'); var $rmCleaner = $('div.input-group.auditorium a.clear-input'); $rmText.on('change', function() { $rmText.val(''); $rmHidden.val(''); $grCleaner.hide(); }); $rmText.autocomplete({ source: 'php/index.php?method=getAuditoriums', minLength: 1, search: function () { $rmLoading.fadeIn(); $rmHidden.val(''); }, response: function () { $rmLoading.promise().done(function () { $rmLoading.fadeOut() } ); }, select: function (event, ui) { fillAutocomplete($rmText, $rmHidden, ui); $requestButton.focus(); $rmCleaner.show(); return false; }, focus: function (event, ui) { fillAutocomplete($rmText, $rmHidden, ui); return false; } }); }); // Making request $requestButton.click(function () { if (($grText.val() == '' || $grHidden.val() == '') && ($('div.auditorium input[type="text"]').val() == '' || $('div.auditorium input[type="hidden"]').val() == '') && ($('div.teacher input[type="text"]').val() == '' || $('div.teacher input[type="hidden"]').val() == '')) { Service.alert("<strong>Помилка!</strong> Хоча б одне поле <strong>Група/Аудиторія/Викладач</strong> повинно бути обрано з випадаючого списку.") return; } Service.showCogWheel(); $.ajax({ url: "php/index.php?method=getSchedule", timeout: 8000, type: "GET", data: $("form.requestForm").serialize() }).done(function (data) { $("div.form.schedule div.panel-body").html(data); $("div.form.schedule").show(); scrollTop = $("div.form.schedule").offset().top - 20; $('html, body').scrollTop(scrollTop); }).fail(function (jqXHR, textStatus) { Service.alert("<strong>Помилка!</strong> Сервер розкладу часто глючить, тому спробуйте повторно відіслати запит. Текст помилки: <strong>" + textStatus + "</strong>"); }).always(function () { Service.hideCogWheel(); }); }); $('footer').click(function() { $('html, body').scrollTop(scrollTop); }); // Clear buttons var $clButtons = $('a.clear-input'); $clButtons.on('click', function (e) { e.preventDefault(); var $parent = $(this).closest('div.input-group'); $(this).hide(); $parent.find('input').val(''); }); // Loading group from cookies var $rem = $('input[name="remember"]'); if (Service.isCookiefied()) { $rem.prop('checked', true); $grText.val(Service.getCookiefiedGroupName()); $grHidden.val(Service.getCookiefiedGroupId()); $requestButton.click(); $grCleaner.show(); $grPlaceholder.html(Service.getCookiefiedGroupName()); $grPlaceholder.show(); } // Remember toggle event listener $rem.on('click', function() { var id = $grHidden.val(); var name = $grText.val(); if ($rem.is(':checked') && id && name) { Service.cookifyGroup($grHidden.val(), $grText.val()); $grPlaceholder.html($grText.val()); $grPlaceholder.show(); } else if (!$rem.is(':checked')) { $grPlaceholder.hide(); Service.decookifyGroup(); } }); // Placeholder click2paste group listener $grPlaceholder.on('click', function(e) { e.preventDefault(); $grText.val(Service.getCookiefiedGroupName()); $grHidden.val(Service.getCookiefiedGroupId()); $grCleaner.show(); }); });
//@flow import React, { Component } from "react"; import { Shaders, Node, GLSL } from "gl-react"; import { Surface } from "../../gl-react-implementation"; const shaders = Shaders.create({ DiamondCrop: { frag: GLSL` precision highp float; varying vec2 uv; uniform sampler2D t; void main() { gl_FragColor = mix( texture2D(t, uv), vec4(0.0), step(0.5, abs(uv.x - 0.5) + abs(uv.y - 0.5)) ); }`, }, }); export const DiamondCrop = ({ children: t }) => ( <Node shader={shaders.DiamondCrop} uniforms={{ t }} /> ); export default class Example extends Component { render() { const { width } = this.props; return ( <Surface style={{ width, height: width }}> <DiamondCrop>{{ uri: "https://i.imgur.com/5EOyTDQ.jpg" }}</DiamondCrop> </Surface> ); } }
{url:'stun:stun.12connect.com:3478'}, {url:'stun:stun.12voip.com:3478'}, {url:'stun:stun.1und1.de:3478'}, {url:'stun:stun.2talk.co.nz:3478'}, {url:'stun:stun.2talk.com:3478'}, {url:'stun:stun.3clogic.com:3478'}, {url:'stun:stun.3cx.com:3478'}, {url:'stun:stun.a-mm.tv:3478'}, {url:'stun:stun.aa.net.uk:3478'}, {url:'stun:stun.acrobits.cz:3478'}, {url:'stun:stun.actionvoip.com:3478'}, {url:'stun:stun.advfn.com:3478'}, {url:'stun:stun.aeta-audio.com:3478'}, {url:'stun:stun.aeta.com:3478'}, {url:'stun:stun.alltel.com.au:3478'}, {url:'stun:stun.altar.com.pl:3478'}, {url:'stun:stun.annatel.net:3478'}, {url:'stun:stun.antisip.com:3478'}, {url:'stun:stun.arbuz.ru:3478'}, {url:'stun:stun.avigora.com:3478'}, {url:'stun:stun.avigora.fr:3478'}, {url:'stun:stun.awa-shima.com:3478'}, {url:'stun:stun.awt.be:3478'}, {url:'stun:stun.b2b2c.ca:3478'}, {url:'stun:stun.bahnhof.net:3478'}, {url:'stun:stun.barracuda.com:3478'}, {url:'stun:stun.bluesip.net:3478'}, {url:'stun:stun.bmwgs.cz:3478'}, {url:'stun:stun.botonakis.com:3478'}, {url:'stun:stun.budgetphone.nl:3478'}, {url:'stun:stun.budgetsip.com:3478'}, {url:'stun:stun.cablenet-as.net:3478'}, {url:'stun:stun.callromania.ro:3478'}, {url:'stun:stun.callwithus.com:3478'}, {url:'stun:stun.cbsys.net:3478'}, {url:'stun:stun.chathelp.ru:3478'}, {url:'stun:stun.cheapvoip.com:3478'}, {url:'stun:stun.ciktel.com:3478'}, {url:'stun:stun.cloopen.com:3478'}, {url:'stun:stun.colouredlines.com.au:3478'}, {url:'stun:stun.comfi.com:3478'}, {url:'stun:stun.commpeak.com:3478'}, {url:'stun:stun.comtube.com:3478'}, {url:'stun:stun.comtube.ru:3478'}, {url:'stun:stun.cope.es:3478'}, {url:'stun:stun.counterpath.com:3478'}, {url:'stun:stun.counterpath.net:3478'}, {url:'stun:stun.cryptonit.net:3478'}, {url:'stun:stun.darioflaccovio.it:3478'}, {url:'stun:stun.datamanagement.it:3478'}, {url:'stun:stun.dcalling.de:3478'}, {url:'stun:stun.decanet.fr:3478'}, {url:'stun:stun.demos.ru:3478'}, {url:'stun:stun.develz.org:3478'}, {url:'stun:stun.dingaling.ca:3478'}, {url:'stun:stun.doublerobotics.com:3478'}, {url:'stun:stun.drogon.net:3478'}, {url:'stun:stun.duocom.es:3478'}, {url:'stun:stun.dus.net:3478'}, {url:'stun:stun.e-fon.ch:3478'}, {url:'stun:stun.easybell.de:3478'}, {url:'stun:stun.easycall.pl:3478'}, {url:'stun:stun.easyvoip.com:3478'}, {url:'stun:stun.efficace-factory.com:3478'}, {url:'stun:stun.einsundeins.com:3478'}, {url:'stun:stun.einsundeins.de:3478'}, {url:'stun:stun.ekiga.net:3478'}, {url:'stun:stun.epygi.com:3478'}, {url:'stun:stun.etoilediese.fr:3478'}, {url:'stun:stun.eyeball.com:3478'}, {url:'stun:stun.faktortel.com.au:3478'}, {url:'stun:stun.freecall.com:3478'}, {url:'stun:stun.freeswitch.org:3478'}, {url:'stun:stun.freevoipdeal.com:3478'}, {url:'stun:stun.fuzemeeting.com:3478'}, {url:'stun:stun.gmx.de:3478'}, {url:'stun:stun.gmx.net:3478'}, {url:'stun:stun.gradwell.com:3478'}, {url:'stun:stun.halonet.pl:3478'}, {url:'stun:stun.hellonanu.com:3478'}, {url:'stun:stun.hoiio.com:3478'}, {url:'stun:stun.hosteurope.de:3478'}, {url:'stun:stun.ideasip.com:3478'}, {url:'stun:stun.imesh.com:3478'}, {url:'stun:stun.infra.net:3478'}, {url:'stun:stun.internetcalls.com:3478'}, {url:'stun:stun.intervoip.com:3478'}, {url:'stun:stun.ipcomms.net:3478'}, {url:'stun:stun.ipfire.org:3478'}, {url:'stun:stun.ippi.fr:3478'}, {url:'stun:stun.ipshka.com:3478'}, {url:'stun:stun.iptel.org:3478'}, {url:'stun:stun.irian.at:3478'}, {url:'stun:stun.it1.hr:3478'}, {url:'stun:stun.ivao.aero:3478'}, {url:'stun:stun.jappix.com:3478'}, {url:'stun:stun.jumblo.com:3478'}, {url:'stun:stun.justvoip.com:3478'}, {url:'stun:stun.kanet.ru:3478'}, {url:'stun:stun.kiwilink.co.nz:3478'}, {url:'stun:stun.kundenserver.de:3478'}, {url:'stun:stun.l.google.com:19302'}, {url:'stun:stun.linea7.net:3478'}, {url:'stun:stun.linphone.org:3478'}, {url:'stun:stun.liveo.fr:3478'}, {url:'stun:stun.lowratevoip.com:3478'}, {url:'stun:stun.lugosoft.com:3478'}, {url:'stun:stun.lundimatin.fr:3478'}, {url:'stun:stun.magnet.ie:3478'}, {url:'stun:stun.manle.com:3478'}, {url:'stun:stun.mgn.ru:3478'}, {url:'stun:stun.mit.de:3478'}, {url:'stun:stun.mitake.com.tw:3478'}, {url:'stun:stun.miwifi.com:3478'}, {url:'stun:stun.modulus.gr:3478'}, {url:'stun:stun.mozcom.com:3478'}, {url:'stun:stun.myvoiptraffic.com:3478'}, {url:'stun:stun.mywatson.it:3478'}, {url:'stun:stun.nas.net:3478'}, {url:'stun:stun.neotel.co.za:3478'}, {url:'stun:stun.netappel.com:3478'}, {url:'stun:stun.netappel.fr:3478'}, {url:'stun:stun.netgsm.com.tr:3478'}, {url:'stun:stun.nfon.net:3478'}, {url:'stun:stun.noblogs.org:3478'}, {url:'stun:stun.noc.ams-ix.net:3478'}, {url:'stun:stun.node4.co.uk:3478'}, {url:'stun:stun.nonoh.net:3478'}, {url:'stun:stun.nottingham.ac.uk:3478'}, {url:'stun:stun.nova.is:3478'}, {url:'stun:stun.nventure.com:3478'}, {url:'stun:stun.on.net.mk:3478'}, {url:'stun:stun.ooma.com:3478'}, {url:'stun:stun.ooonet.ru:3478'}, {url:'stun:stun.oriontelekom.rs:3478'}, {url:'stun:stun.outland-net.de:3478'}, {url:'stun:stun.ozekiphone.com:3478'}, {url:'stun:stun.patlive.com:3478'}, {url:'stun:stun.personal-voip.de:3478'}, {url:'stun:stun.petcube.com:3478'}, {url:'stun:stun.phone.com:3478'}, {url:'stun:stun.phoneserve.com:3478'}, {url:'stun:stun.pjsip.org:3478'}, {url:'stun:stun.poivy.com:3478'}, {url:'stun:stun.powerpbx.org:3478'}, {url:'stun:stun.powervoip.com:3478'}, {url:'stun:stun.ppdi.com:3478'}, {url:'stun:stun.prizee.com:3478'}, {url:'stun:stun.qq.com:3478'}, {url:'stun:stun.qvod.com:3478'}, {url:'stun:stun.rackco.com:3478'}, {url:'stun:stun.rapidnet.de:3478'}, {url:'stun:stun.rb-net.com:3478'}, {url:'stun:stun.refint.net:3478'}, {url:'stun:stun.remote-learner.net:3478'}, {url:'stun:stun.rixtelecom.se:3478'}, {url:'stun:stun.rockenstein.de:3478'}, {url:'stun:stun.rolmail.net:3478'}, {url:'stun:stun.rounds.com:3478'}, {url:'stun:stun.rynga.com:3478'}, {url:'stun:stun.samsungsmartcam.com:3478'}, {url:'stun:stun.schlund.de:3478'}, {url:'stun:stun.services.mozilla.com:3478'}, {url:'stun:stun.sigmavoip.com:3478'}, {url:'stun:stun.sip.us:3478'}, {url:'stun:stun.sipdiscount.com:3478'}, {url:'stun:stun.sipgate.net:10000'}, {url:'stun:stun.sipgate.net:3478'}, {url:'stun:stun.siplogin.de:3478'}, {url:'stun:stun.sipnet.net:3478'}, {url:'stun:stun.sipnet.ru:3478'}, {url:'stun:stun.siportal.it:3478'}, {url:'stun:stun.sippeer.dk:3478'}, {url:'stun:stun.siptraffic.com:3478'}, {url:'stun:stun.skylink.ru:3478'}, {url:'stun:stun.sma.de:3478'}, {url:'stun:stun.smartvoip.com:3478'}, {url:'stun:stun.smsdiscount.com:3478'}, {url:'stun:stun.snafu.de:3478'}, {url:'stun:stun.softjoys.com:3478'}, {url:'stun:stun.solcon.nl:3478'}, {url:'stun:stun.solnet.ch:3478'}, {url:'stun:stun.sonetel.com:3478'}, {url:'stun:stun.sonetel.net:3478'}, {url:'stun:stun.sovtest.ru:3478'}, {url:'stun:stun.speedy.com.ar:3478'}, {url:'stun:stun.spokn.com:3478'}, {url:'stun:stun.srce.hr:3478'}, {url:'stun:stun.ssl7.net:3478'}, {url:'stun:stunprotocol.org:3478'}, {url:'stun:stun.symform.com:3478'}, {url:'stun:stun.symplicity.com:3478'}, {url:'stun:stun.sysadminman.net:3478'}, {url:'stun:stun.t-online.de:3478'}, {url:'stun:stun.tagan.ru:3478'}, {url:'stun:stun.tatneft.ru:3478'}, {url:'stun:stun.teachercreated.com:3478'}, {url:'stun:stun.tel.lu:3478'}, {url:'stun:stun.telbo.com:3478'}, {url:'stun:stun.telefacil.com:3478'}, {url:'stun:stun.tis-dialog.ru:3478'}, {url:'stun:stun.tng.de:3478'}, {url:'stun:stun.twt.it:3478'}, {url:'stun:stun.u-blox.com:3478'}, {url:'stun:stun.ucallweconn.net:3478'}, {url:'stun:stun.ucsb.edu:3478'}, {url:'stun:stun.ucw.cz:3478'}, {url:'stun:stun.uls.co.za:3478'}, {url:'stun:stun.unseen.is:3478'}, {url:'stun:stun.usfamily.net:3478'}, {url:'stun:stun.veoh.com:3478'}, {url:'stun:stun.vidyo.com:3478'}, {url:'stun:stun.vipgroup.net:3478'}, {url:'stun:stun.virtual-call.com:3478'}, {url:'stun:stun.viva.gr:3478'}, {url:'stun:stun.vivox.com:3478'}, {url:'stun:stun.vline.com:3478'}, {url:'stun:stun.vo.lu:3478'}, {url:'stun:stun.vodafone.ro:3478'}, {url:'stun:stun.voicetrading.com:3478'}, {url:'stun:stun.voip.aebc.com:3478'}, {url:'stun:stun.voip.blackberry.com:3478'}, {url:'stun:stun.voip.eutelia.it:3478'}, {url:'stun:stun.voiparound.com:3478'}, {url:'stun:stun.voipblast.com:3478'}, {url:'stun:stun.voipbuster.com:3478'}, {url:'stun:stun.voipbusterpro.com:3478'}, {url:'stun:stun.voipcheap.co.uk:3478'}, {url:'stun:stun.voipcheap.com:3478'}, {url:'stun:stun.voipfibre.com:3478'}, {url:'stun:stun.voipgain.com:3478'}, {url:'stun:stun.voipgate.com:3478'}, {url:'stun:stun.voipinfocenter.com:3478'}, {url:'stun:stun.voipplanet.nl:3478'}, {url:'stun:stun.voippro.com:3478'}, {url:'stun:stun.voipraider.com:3478'}, {url:'stun:stunt.com:3478'}, {url:'stun:stun.voipwise.com:3478'}, {url:'stun:stun.voipzoom.com:3478'}, {url:'stun:stun.vopium.com:3478'}, {url:'stun:stun.voxgratia.org:3478'}, {url:'stun:stun.voxox.com:3478'}, {url:'stun:stun.voys.nl:3478'}, {url:'stun:stun.voztele.com:3478'}, {url:'stun:stun.vyke.com:3478'}, {url:'stun:stun.webcalldirect.com:3478'}, {url:'stun:stun.whoi.edu:3478'}, {url:'stun:stun.wifirst.net:3478'}, {url:'stun:stun.wwdl.net:3478'}, {url:'stun:stun.xs4all.nl:3478'}, {url:'stun:stun.xtratelecom.es:3478'}, {url:'stun:stun.yesss.at:3478'}, {url:'stun:stun.zadarma.com:3478'}, {url:'stun:stun.zadv.com:3478'}, {url:'stun:stun.zoiper.com:3478'}, {url:'stun:stun1.faktortel.com.au:3478'}, {url:'stun:stun1.l.google.com:19302'}, {url:'stun:stun1.voiceeclipse.net:3478'}, {url:'stun:stun2.l.google.com:19302'}, {url:'stun:stun3.l.google.com:19302'}, {url:'stun:stun4.l.google.com:19302'}, {url:'stun:stunserver.org:3478'}
global.electron = require('electron'); global.BrowserWindow = electron.BrowserWindow; global.Dialog = electron.dialog; var Fs = require('fs'); var ipc = require("electron").ipcMain; var path = require('path'); var temp = require('temp'); var request = require('request'); var querystring = require('querystring'); var escape = require('escape-regexp'); var slug = require('slug'); var tmpdir = require('os-tmpdir')(); var file_formats = require('../renderer/file-actions.js').formats; var rootURL = process.env.NODE_ENV == 'development' ? 'http://git-data-publisher.dev' : 'https://octopub.io'; var loadWindow = function(githubWindow, apiKey, viewName) { githubWindow.loadURL('file://' + __dirname + '/../views/' + viewName + '.html'); githubWindow.webContents.on('dom-ready', function() { githubWindow.webContents.send('apiKey', apiKey); }); }; var checkForAPIKey = function(url) { regex = escape(rootURL + '/redirect?api_key=') + '([a-z0-9]+)'; match = url.match(new RegExp(regex)); return match; }; var writeData = function(csv, filename) { path = tmpdir + '/' + slug(filename, {lower: true}) + '.csv'; Fs.writeFileSync(path, csv, 'utf8'); return path; }; var postData = function(dataset, file, apiKey) { var opts = { url: rootURL + '/api/datasets', json: true, headers: { 'Authorization': apiKey }, formData: { 'dataset[name]': dataset.name, 'dataset[description]': dataset.description, 'dataset[publisher_name]': dataset['publisher_name'], 'dataset[publisher_url]': dataset['publisher_url'], 'dataset[license]': dataset.license, 'dataset[frequency]': dataset.frequency, 'file[title]': dataset.file_name, 'file[description]': dataset.file_description, 'file[file]': Fs.createReadStream(file), } }; request.post(opts, function(err, resp, body) { displayResult(body, apiKey); }); }; var putData = function(dataset, file, apiKey) { var opts = { url: rootURL + '/api/datasets/' + dataset.dataset + '/files', json: true, headers: { 'Authorization': apiKey }, formData: { 'file[title]': dataset.file_name, 'file[description]': dataset.file_description, 'file[file]': Fs.createReadStream(file), } }; request.post(opts, function(err, resp, body) { displayResult(body, apiKey); }); }; var displayResult = function(result, apiKey) { if (result.errors) { console.log(result.errors); githubWindow.webContents.send('errors', result.errors); } else { waitForDataset(result.job_url, apiKey, function(type, result) { if (type == 'error') { githubWindow.webContents.send('errors', result); } else { githubWindow.loadURL('file://' + __dirname + '/../views/github-success.html'); githubWindow.webContents.on('dom-ready', function() { githubWindow.webContents.send('ghPagesUrl', result); }); } }); } }; var waitForDataset = function(jobURL, apiKey, callback) { url = rootURL + jobURL; options = { json: true, headers: { 'Authorization': apiKey }, url: url }; var checkURL = setInterval(function(){ request.get(options, function(err, resp, body) { if (body.dataset_url) { options.url = rootURL + body.dataset_url; request.get(options, function(err, resp, body) { clearInterval(checkURL); callback('success', body.gh_pages_url); }); } else if(body.errors) { clearInterval(checkURL); callback('error', body.errors); } }); }, 5000); }; var uploadToGithub = function(parentWindow, data, apiKey) { parentWindow.webContents.send('getCSV', file_formats.csv); ipc.once('sendCSV', function(e, csv) { dataset = querystring.parse(data); file = writeData(csv, dataset.file_name); postData(dataset, file, apiKey); }); }; var exportToGithub = function() { authAndLoad('github'); ipc.once('sendToGithub', function(e, data, apiKey) { uploadToGithub(parentWindow, data, apiKey); }); }; var authAndLoad = function(viewName) { parentWindow = BrowserWindow.getFocusedWindow(); githubWindow = new BrowserWindow({width: 450, height: 600}); githubWindow.loadURL(rootURL + '/auth/github?referer=comma-chameleon'); githubWindow.webContents.on('did-get-redirect-request', function(event, oldUrl, newUrl){ match = checkForAPIKey(newUrl); if (match) { loadWindow(githubWindow, match[1], viewName); } }); githubWindow.on('closed', function() { githubWindow = null; }); }; var addFileToGithub = function() { authAndLoad('choose-repo'); ipc.on('addFileToExisting', function(e, data, apiKey) { parentWindow.webContents.send('getCSV', file_formats.csv); console.log(data); ipc.once('sendCSV', function(e, csv) { dataset = querystring.parse(data); file = writeData(csv, dataset.file_name); putData(dataset, file, apiKey); }); }); }; module.exports = { exportToGithub: exportToGithub, addFileToGithub: addFileToGithub }; if (process.env.NODE_ENV === 'test') { module.exports._private = { loadWindow: loadWindow, checkForAPIKey: checkForAPIKey, writeData: writeData, postData: postData, putData: putData, uploadToGithub: uploadToGithub, request: request }; }
'use strict'; var _ = require('underscore'), Irc = require('irc'); var IrcBot = function(config) { if (!(this instanceof IrcBot)) { return new IrcBot(config); } this.config = _.defaults(config, { server: 'irc.freenode.com', // IRC server username: 'slackbot', // Bot IRC nickname nick: 'slackbot', channels: {}, // Map of ircChannels : slackChannels users: {}, // Map of ircLogin : slackUsernames isSilent: false, isSystemSilent: true, isUsersTracking: true, isMapName: true, isMapAvatar: true }); this._configureClient(); this.client = new Irc.Client(this.config.server, this.config.nick, this.irc); this._handleErrors(); this._handleQueries(); return this; }; IrcBot.prototype._configureClient = function() { var nodeIrcOptions = [ 'floodProtection', 'port', 'debug', 'showErrors', 'autoRejoin', 'autoConnect', 'secure', 'selfSigned', 'certExpired', 'floodProtection', 'floodProtectionDelay', 'sasl', 'stripColors', 'channelPrefixes', 'messageSplit' ]; this.irc = { userName: this.config.username, password: this.config.password, channels: Object.keys(this.config.channels), floodProtection: true }; nodeIrcOptions.forEach(function(opt) { if (this.config[opt]) { this.irc[opt] = this.config[opt]; } }.bind(this)); }; IrcBot.prototype._handleQueries = function () { this.client.addListener('message', function (from, to, message) { var dest = to[0] == '#' ? to : from; if (message.indexOf(this.config.nick + ": ma cmima") == 0) { this.speak(dest, Object.keys(this.slackRes.userMap).map(function (a) { return this.slackRes.userMap[a] }.bind(this)).join(", ")); } }.bind(this)); } IrcBot.prototype._handleErrors = function() { this.client.addListener('error', function(message) { var channel = message.args[1], errorMessage = this.mapPronouns(message.args[2]||''); this.systemSpeak(channel, 'I don\'t feel so well because ' + errorMessage); }.bind(this)); }; IrcBot.prototype._trackUsers = function() { this._trackUserExisting(); this._trackUserEntering(); this._trackUserNicking(); }; IrcBot.prototype._trackUserExisting = function() { this.client.addListener('names', function(channel, nicks) { Object.keys(nicks).forEach(function(nick) { var botUsername = '~' + this.config.username; /* Not bothering with this, because it barfs on large channels this.client.whois(nick, function(whois) { if (whois.user === botUsername) { return; } var slackName = this.nameMap.getSlackNameByIrcWhoIs(whois.user); this.nameMap.setSlackNameByIrcNick(slackName, nick); }.bind(this)); */ var slackName = this.nameMap.getSlackNameByIrcWhoIs(nick); this.nameMap.setSlackNameByIrcNick(slackName, nick); }.bind(this)); this.systemSpeak(channel, 'I\'m all over you slackers'); }.bind(this)); }; IrcBot.prototype._trackUserEntering = function() { this.client.addListener('join', function(channel, nick, whois) { var botUsername = '~' + this.config.username; if (whois.user === botUsername) { return; } else { var slackName = this.nameMap.getSlackNameByIrcWhoIs(whois.user); this.nameMap.setSlackNameByIrcNick(slackName, nick); this.systemSpeak(channel, 'i\'m watching you slacker @' + slackName); } }.bind(this)); }; IrcBot.prototype._trackUserNicking = function() { this.client.addListener('nick', function(oldNick, newNick, channels) { if (newNick === this.config.nick) { return; } var slackName = this.nameMap.getSlackNameByIrcNick(oldNick); this.nameMap.replaceIrcNick(oldNick, newNick); channels.forEach(function(channel) { this.systemSpeak(channel, 'don\'t think you can hide slacker @' + slackName); }.bind(this)); }.bind(this)); }; IrcBot.prototype.setSlackRes = function(slackRes) { this.slackRes = slackRes; return this; }; IrcBot.prototype.setNameMap = function(nameMap) { this.nameMap = nameMap; if (this.config.isUsersTracking) { this._trackUsers(); } return this; }; IrcBot.prototype.addListener = function(type, listener) { this.client.addListener(type, listener); }; IrcBot.prototype.speak = function(channel, message) { if (!this.config.isSilent) { this.client.say(channel, message); } }; IrcBot.prototype.systemSpeak = function(channel, message) { if (!this.config.isSystemSilent) { this.speak(channel, message); } }; IrcBot.prototype.mapPronouns = function(message) { var map = { 'you': 'i', 'you\'re': 'i\'m' }; return message.split(' ').map(function(word) { return map[word.toLowerCase()] ? map[word.toLowerCase()] : word; }).join(' '); }; module.exports = IrcBot;
import {Draw, Anim, Preload, Sound, Elements, Components} from 'evolve-js'; import Core from './Core'; import Constants from './Constants'; import Helpers from './Helpers'; import Managers from './Managers'; import Engine from './Engine'; import release from '../release'; const status = { initialized: true, version: release.version, build: release.build, }; console.log('Genesi JS initialized', status); const genesi = { Core, Draw, Anim, Preload, Sound, Elements, Components, Constants, Helpers, Managers, Engine, status, }; export default genesi; export { Core, Draw, Anim, Preload, Sound, Elements, Components, Constants, Helpers, Managers, Engine, };
(function($) { /** * The Dutch language package * Translated by @jvanderheide */ FormValidation.I18n = $.extend(true, FormValidation.I18n, { 'nl_NL': { base64: { 'default': 'Voer een geldige Base64 geëncodeerde tekst in' }, between: { 'default': 'Voer een waarde in van %s tot en met %s', notInclusive: 'Voer een waarde die tussen %s en %s ligt' }, bic: { 'default': 'Voer een geldige BIC-code in' }, callback: { 'default': 'Voer een geldige waarde in' }, choice: { 'default': 'Voer een geldige waarde in', less: 'Kies minimaal %s optie(s)', more: 'Kies maximaal %s opties', between: 'Kies tussen de %s - %s opties' }, color: { 'default': 'Voer een geldige kleurcode in' }, creditCard: { 'default': 'Voer een geldig creditcardnummer in' }, cusip: { 'default': 'Voer een geldig CUSIP-nummer in' }, cvv: { 'default': 'Voer een geldig CVV-nummer in' }, date: { 'default': 'Voer een geldige datum in', min: 'Voer een datum in die na %s ligt', max: 'Voer een datum in die vóór %s ligt', range: 'Voer een datum in die tussen %s en %s ligt' }, different: { 'default': 'Voer een andere waarde in' }, digits: { 'default': 'Voer enkel cijfers in' }, ean: { 'default': 'Voer een geldige EAN-code in' }, ein: { 'default': 'Voer een geldige EIN-code in' }, emailAddress: { 'default': 'Voer een geldig e-mailadres in' }, file: { 'default': 'Kies een geldig bestand' }, greaterThan: { 'default': 'Voer een waarde in die gelijk is aan of groter is dan %s', notInclusive: 'Voer een waarde in die is groter dan %s' }, grid: { 'default': 'Voer een geldig GRId-nummer in' }, hex: { 'default': 'Voer een geldig hexadecimaal nummer in' }, iban: { 'default': 'Voer een geldig IBAN nummer in', countryNotSupported: 'De land code %s wordt niet ondersteund', country: 'Voer een geldig IBAN nummer in uit %s', countries: { AD: 'Andorra', AE: 'Verenigde Arabische Emiraten', AL: 'Albania', AO: 'Angola', AT: 'Oostenrijk', AZ: 'Azerbeidzjan', BA: 'Bosnië en Herzegovina', BE: 'België', BF: 'Burkina Faso', BG: 'Bulgarije"', BH: 'Bahrein', BI: 'Burundi', BJ: 'Benin', BR: 'Brazilië', CH: 'Zwitserland', CI: 'Ivoorkust', CM: 'Kameroen', CR: 'Costa Rica', CV: 'Cape Verde', CY: 'Cyprus', CZ: 'Tsjechische Republiek', DE: 'Duitsland', DK: 'Denemarken', DO: 'Dominicaanse Republiek', DZ: 'Algerije', EE: 'Estland', ES: 'Spanje', FI: 'Finland', FO: 'Faeröer', FR: 'Frankrijk', GB: 'Verenigd Koninkrijk', GE: 'Georgia', GI: 'Gibraltar', GL: 'Groenland', GR: 'Griekenland', GT: 'Guatemala', HR: 'Kroatië', HU: 'Hongarije', IE: 'Ierland', IL: 'Israël', IR: 'Iran', IS: 'IJsland', IT: 'Italië', JO: 'Jordan', KW: 'Koeweit', KZ: 'Kazachstan', LB: 'Libanon', LI: 'Liechtenstein', LT: 'Litouwen', LU: 'Luxemburg', LV: 'Letland', MC: 'Monaco', MD: 'Moldavië', ME: 'Montenegro', MG: 'Madagascar', MK: 'Macedonië', ML: 'Mali', MR: 'Mauretanië', MT: 'Malta', MU: 'Mauritius', MZ: 'Mozambique', NL: 'Nederland', NO: 'Noorwegen', PK: 'Pakistan', PL: 'Polen', PS: 'Palestijnse', PT: 'Portugal', QA: 'Qatar', RO: 'Roemenië', RS: 'Servië', SA: 'Saudi-Arabië', SE: 'Zweden', SI: 'Slovenië', SK: 'Slowakije', SM: 'San Marino', SN: 'Senegal', TN: 'Tunesië', TR: 'Turkije', VG: 'Britse Maagdeneilanden' } }, id: { 'default': 'Voer een geldig identificatie nummer in', countryNotSupported: 'De land code %s wordt niet ondersteund', country: 'Voer een geldig identificatie nummer in uit %s', countries: { BA: 'Bosnië en Herzegovina', BG: 'Bulgarije', BR: 'Brazilië', CH: 'Zwitserland', CL: 'Chili', CN: 'China', CZ: 'Tsjechische Republiek', DK: 'Denemarken', EE: 'Estland', ES: 'Spanje', FI: 'Finland', HR: 'Kroatië', IE: 'Ierland', IS: 'IJsland', LT: 'Litouwen', LV: 'Letland', ME: 'Montenegro', MK: 'Macedonië', NL: 'Nederland', RO: 'Roemenië', RS: 'Servië', SE: 'Zweden', SI: 'Slovenië', SK: 'Slowakije', SM: 'San Marino', TH: 'Thailand', ZA: 'Zuid-Afrika' } }, identical: { 'default': 'Voer dezelfde waarde in' }, imei: { 'default': 'Voer een geldig IMEI-nummer in' }, imo: { 'default': 'Voer een geldig IMO-nummer in' }, integer: { 'default': 'Voer een geldig getal in' }, ip: { 'default': 'Voer een geldig IP adres in', ipv4: 'Voer een geldig IPv4 adres in', ipv6: 'Voer een geldig IPv6 adres in' }, isbn: { 'default': 'Voer een geldig ISBN-nummer in' }, isin: { 'default': 'Voer een geldig ISIN-nummer in' }, ismn: { 'default': 'Voer een geldig ISMN-nummer in' }, issn: { 'default': 'Voer een geldig ISSN-nummer in' }, lessThan: { 'default': 'Voer een waarde in gelijk aan of kleiner dan %s', notInclusive: 'Voer een waarde in kleiner dan %s' }, mac: { 'default': 'Voer een geldig MAC adres in' }, meid: { 'default': 'Voer een geldig MEID-nummer in' }, notEmpty: { 'default': 'Voer een waarde in' }, numeric: { 'default': 'Voer een geldig kommagetal in' }, phone: { 'default': 'Voer een geldig telefoonnummer in', countryNotSupported: 'De land code %s wordt niet ondersteund', country: 'Voer een geldig telefoonnummer in uit %s', countries: { AE: 'Verenigde Arabische Emiraten', BR: 'Brazilië', CN: 'China', CZ: 'Tsjechische Republiek', DE: 'Duitsland', DK: 'Denemarken', ES: 'Spanje', FR: 'Frankrijk', GB: 'Verenigd Koninkrijk', MA: 'Marokko', PK: 'Pakistan', RO: 'Roemenië', RU: 'Rusland', SK: 'Slowakije', TH: 'Thailand', US: 'VS', VE: 'Venezuela' } }, regexp: { 'default': 'Voer een waarde in die overeenkomt met het patroon' }, remote: { 'default': 'Voer een geldige waarde in' }, rtn: { 'default': 'Voer een geldig RTN-nummer in' }, sedol: { 'default': 'Voer een geldig SEDOL-nummer in' }, siren: { 'default': 'Voer een geldig SIREN-nummer in' }, siret: { 'default': 'Voer een geldig SIRET-nummer in' }, step: { 'default': 'Voer een meervoud van %s in' }, stringCase: { 'default': 'Voer enkel kleine letters in', upper: 'Voer enkel hoofdletters in' }, stringLength: { 'default': 'Voer een waarde met de juiste lengte in', less: 'Voer minder dan %s karakters in', more: 'Voer meer dan %s karakters in', between: 'Voer tussen tussen %s en %s karakters in' }, uri: { 'default': 'Voer een geldige link in' }, uuid: { 'default': 'Voer een geldige UUID in', version: 'Voer een geldige UUID (versie %s) in' }, vat: { 'default': 'Voer een geldig BTW-nummer in', countryNotSupported: 'De land code %s wordt niet ondersteund', country: 'Voer een geldig BTW-nummer in uit %s', countries: { AT: 'Oostenrijk', BE: 'België', BG: 'Bulgarije', BR: 'Brazilië', CH: 'Zwitserland', CY: 'Cyprus', CZ: 'Tsjechische Republiek', DE: 'Duitsland', DK: 'Denemarken', EE: 'Estland', ES: 'Spanje', FI: 'Finland', FR: 'Frankrijk', GB: 'Verenigd Koninkrijk', GR: 'Griekenland', EL: 'Griekenland', HU: 'Hongarije', HR: 'Kroatië', IE: 'Ierland', IS: 'IJsland', IT: 'Italië', LT: 'Litouwen', LU: 'Luxemburg', LV: 'Letland', MT: 'Malta', NL: 'Nederland', NO: 'Noorwegen', PL: 'Polen', PT: 'Portugal', RO: 'Roemenië', RU: 'Rusland', RS: 'Servië', SE: 'Zweden', SI: 'Slovenië', SK: 'Slowakije', VE: 'Venezuela', ZA: 'Zuid-Afrika' } }, vin: { 'default': 'Voer een geldig VIN-nummer in' }, zipCode: { 'default': 'Voer een geldige postcode in', countryNotSupported: 'De land code %s wordt niet ondersteund', country: 'Voer een geldige postcode in uit %s', countries: { AT: 'Oostenrijk', BR: 'Brazilië', CA: 'Canada', CH: 'Zwitserland', CZ: 'Tsjechische Republiek', DE: 'Duitsland', DK: 'Denemarken', FR: 'Frankrijk', GB: 'Verenigd Koninkrijk', IE: 'Ierland', IT: 'Italië', MA: 'Marokko', NL: 'Nederland', PT: 'Portugal', RO: 'Roemenië', RU: 'Rusland', SE: 'Zweden', SG: 'Singapore', SK: 'Slowakije', US: 'VS' } } } }); }(jQuery));
/** * @author joel * 25-11-15. */ /// <reference path="../typings/tsd.d.ts" /> /// <reference path="../typings/app.d.ts" /> 'use strict'; var _ = require('lodash'); var Promise = require('bluebird'); var IsPromise = require('is-promise'); var PromiseEnsurer = (function () { function PromiseEnsurer() { } PromiseEnsurer.isPromise = function (value) { return IsPromise(value); }; PromiseEnsurer.transformToPromise = function (value) { return new Promise(function (resolve, reject) { if (_.isUndefined(value)) { reject(undefined); } else if (_.isBoolean(value)) { value ? resolve(undefined) : reject(undefined); } else { resolve(value); } }); }; PromiseEnsurer.ensure = function (value) { return this.isPromise(value) ? value : this.transformToPromise(value); }; return PromiseEnsurer; })(); module.exports = PromiseEnsurer;
/// <reference path="jquery-3.1.0.min.js" /> /// <reference path="jquery.touchSwipe.min.js" /> // Redirect user to SSL version of site. if (location.protocol != "https:" && location.href.indexOf("localhost") == -1 && location.href.indexOf("192.") == -1) { location.href = location.href.replace("http:", "https:"); } var frmGetLatLng; var txtAddress; var btnGetLatLng; var btnClearQuery; var btnGetGps; var divLat; var spanLat; var divLng; var spanLng; var divTwc; var divTwcTop; var divTwcMiddle; var divTwcBottom; var divTwcLeft; var divTwcRight; var divTwcNavContainer; var divTwcNav; var iframeTwc; var btnFullScreen; var divTwcBottomLeft; var divTwcBottomMiddle; var divTwcBottomRight; var divRefresh; var spanLastRefresh; var chkAutoRefresh; var lblRefreshCountDown; var spanRefreshCountDown; var spanCity; var spanState; var spanStationId; var spanRadarId; var spanZoneId; var radScrollDefault; var frmScrollText; var radScrollText; var txtScrollText; var btnScrollText; var frmScrollRss; var radScrollRss; var txtScrollRss; var btnScrollRss; var chkScrollHazardText; //var _InFullScreen = false; var _AutoSelectQuery = false; var _TwcDataUrl = ""; var _IsPlaying = false; var _NoSleep = new NoSleep(); var _LastUpdate = null; var _AutoRefreshIntervalId = null; var _AutoRefreshIntervalMs = 500; //var _AutoRefreshTotalIntervalMs = 10000; // 10 sec. //var _AutoRefreshTotalIntervalMs = 300000; // 5 min. var _AutoRefreshTotalIntervalMs = 600000; // 10 min. var _AutoRefreshCountMs = 0; var _IsAudioPlaying = false; var _IsNarrationPlaying = false; var _FullScreenOverride = false; var _WeatherParameters = null; var _WindowHeight = 0; var _WindowWidth = 0; var _AllowKeyDown = true; var _canvasIds = [ "canvasProgress", "canvasCurrentWeather", "canvasLatestObservations", "canvasTravelForecast", "canvasRegionalForecast1", "canvasRegionalForecast2", "canvasRegionalObservations", "canvasLocalForecast", "canvasExtendedForecast1", "canvasExtendedForecast2", "canvasAlmanac", "canvasAlmanacTides", "canvasOutlook", "canvasMarineForecast", "canvasAirQuality", "canvasLocalRadar", "canvasHazards" ]; var FullScreenResize = function (AutoRefresh) { var iframeDoc = $(iframeTwc[0].contentWindow.document); var WindowWidth = $(window).width(); var WindowHeight = $(window).height(); var NewWidth; var NewHeight; var IFrameWidth; var IFrameHeight; var LeftWidth; var LeftHeight; var RightWidth; var RightHeight; var TopHeight; var TopWidth; var BottomHeight; var BottomWidth; var Offset; var inFullScreen = InFullScreen(); if (inFullScreen == true) { //if (WindowWidth > WindowHeight) //if (WindowWidth > 850) //if (WindowWidth > 0) //if (WindowWidth > 640) if ((WindowWidth / WindowHeight) >= 1.583333333333333) // = 640 (TWC Width) + 48 (Icon min width on left side) + 12 (left padding) + 48 (Right icons) + 12 (right padding) / 480 (TWC Height) { NewHeight = WindowHeight + "px"; NewWidth = ""; divTwcTop.hide(); divTwcBottom.hide(); divTwcLeft.show(); divTwcRight.show(); divTwcMiddle.attr("style", "width:100%; height:100%; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;"); //IFrameWidth = (WindowHeight * 1.33333333333333333333); //iframeTwc.attr("style", "width:" + IFrameWidth + "px; height:100%; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;"); //LeftWidth = ((((WindowHeight * 16) / 9) - (WindowHeight * 1.25)) / 2) + "px"; LeftWidth = ((WindowWidth - (WindowHeight * 1.33333333333333333333)) / 2); if (LeftWidth < 60) { LeftWidth = 60; } divTwcLeft.find("div>div>a>img").css("width", ""); //divTwcLeft.find(">div").css("padding-right", "12px").css("padding-left", ""); divTwcLeft.attr("style", "width:" + LeftWidth + "px; height:100%; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;"); divTwcLeft.css("visibility", "visible"); divTwcLeft.css("opacity", "1"); if (AutoRefresh === true) { divTwcLeft.css("opacity", "0"); divTwcLeft.css("visibility", "hidden"); } divTwcLeft.css("position", ""); //RightWidth = ((((WindowHeight * 16) / 9) - (WindowHeight * 1.25)) / 2) + "px"; RightWidth = ((WindowWidth - (WindowHeight * 1.33333333333333333333)) / 2); if (RightWidth < 60) { RightWidth = 60; } divTwcRight.find("div>div>a>img").css("width", ""); //divTwcRight.find(">div").css("padding-left", "12px").css("padding-right", ""); divTwcRight.attr("style", "width:" + RightWidth + "px; height:100%; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;"); divTwcRight.css("visibility", "visible"); divTwcRight.css("opacity", "1"); if (AutoRefresh === true) { divTwcRight.css("opacity", "0"); divTwcRight.css("visibility", "hidden"); } divTwcRight.css("position", ""); IFrameWidth = WindowWidth - LeftWidth - RightWidth; NewWidth = IFrameWidth + "px"; iframeTwc.attr("style", "width:" + IFrameWidth + "px; height:100%; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;"); //console.log(WindowWidth); } else { NewHeight = ""; NewWidth = WindowWidth + "px"; divTwcTop.show(); divTwcBottom.show(); //divTwcLeft.hide(); //divTwcRight.hide(); //Offset = 400; Offset = 0; //IFrameHeight = ((WindowWidth - Offset) * 0.75) + "px"; //iframeTwc.attr("style", "width:100%; height:" + IFrameHeight + "; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;"); //divTwcMiddle.attr("style", "width:100%; height:" + IFrameHeight + "; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;"); TopHeight = ((WindowHeight - ((WindowWidth - Offset) * 0.75)) / 2); if (TopHeight < 0) { TopHeight = 0; } divTwcTop.attr("style", "width:100%; height:" + TopHeight + "px; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;"); BottomHeight = ((WindowHeight - ((WindowWidth - Offset) * 0.75)) / 2); if (BottomHeight < 30) { //BottomHeight = 30; BottomHeight = 0; } divTwcBottom.attr("style", "width:100%; height:" + BottomHeight + "px; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;"); divTwcBottom.css("visibility", "visible"); divTwcBottom.css("opacity", "1"); if (AutoRefresh === true) { divTwcBottom.css("opacity", "0"); divTwcBottom.css("visibility", "hidden"); } IFrameHeight = WindowHeight - TopHeight - BottomHeight; NewHeight = IFrameHeight + "px"; iframeTwc.attr("style", "width:100%; height:" + IFrameHeight + "px; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;"); divTwcMiddle.attr("style", "width:100%; height:" + IFrameHeight + "px; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;"); divTwcBottomLeft.hide(); divTwcBottomMiddle.hide(); divTwcBottomRight.hide(); divTwcLeft.show(); divTwcRight.show(); LeftWidth = (WindowWidth / 13); if (LeftWidth < 25) { LeftWidth = 25; } divTwcLeft.find("div>div>a>img").css("width", "100%"); //divTwcLeft.find(">div").css("padding-right", "0px"); divTwcLeft.attr("style", "width:" + LeftWidth + "px; height:" + IFrameHeight + "px; border:none; margin:0; padding:0; overflow:hidden; z-index:1000000;"); divTwcLeft.css("visibility", "visible"); divTwcLeft.css("opacity", "1"); if (AutoRefresh === true) { divTwcLeft.css("opacity", "0"); divTwcLeft.css("visibility", "hidden"); } divTwcLeft.css("position", "absolute"); divTwcLeft.css("left", "12px"); RightWidth = (WindowWidth / 13); if (RightWidth < 25) { RightWidth = 25; } divTwcRight.find("div>div>a>img").css("width", "100%"); //divTwcRight.find(">div").css("padding-left", "0px"); divTwcRight.attr("style", "width:" + RightWidth + "px; height:" + IFrameHeight + "px; border:none; margin:0; padding:0; overflow:hidden; z-index:1000000;"); divTwcRight.css("visibility", "visible"); divTwcRight.css("opacity", "1"); if (AutoRefresh === true) { divTwcRight.css("opacity", "0"); divTwcRight.css("visibility", "hidden"); } divTwcRight.css("position", "absolute"); divTwcRight.css("right", "12px"); } } if (inFullScreen == false) { NewHeight = ""; NewWidth = ""; divTwcTop.hide(); divTwcBottom.hide(); divTwcLeft.hide(); divTwcRight.hide(); divTwc.attr("style", ""); divTwcMiddle.attr("style", ""); iframeTwc.attr("style", ""); divTwcBottomLeft.show(); divTwcBottomMiddle.show(); divTwcBottomRight.show(); $(window).off("resize", FullScreenResize); } //iframeDoc.find("#canvasProgress").css("width", NewWidth); //iframeDoc.find("#canvasProgress").css("height", NewHeight); $(_canvasIds).each(function () { var canvas = iframeDoc.find("#" + this.toString()); canvas.css("width", NewWidth); canvas.css("height", NewHeight); }); if (inFullScreen == true) { $("body").css("overflow", "hidden"); $(".ToggleFullScreen").val("Exit Full Screen"); if (!GetFullScreenElement()) { EnterFullScreen(); } } else { $("body").css("overflow", ""); $(".ToggleFullScreen").val("Full Screen"); } //divTwc.show(); ////divTwc.css("display", "block"); //if (divTwc.css("display") != "block") //{ // divTwc.css("display", "block"); //} divTwcNavContainer.show(); }; var _lockOrientation = screen.lockOrientation || screen.mozLockOrientation || screen.msLockOrientation; var _unlockOrientation = screen.unlockOrientation || screen.mozUnlockOrientation || screen.msUnlockOrientation || (screen.orientation && screen.orientation.unlock); var OnFullScreen = function () { if (InFullScreen() == true) { divTwc.attr("style", "position:fixed; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;"); FullScreenResize(); $(window).on("resize", FullScreenResize); //FullScreenResize(); if (_lockOrientation) try { _lockOrientation("landscape-primary"); } catch (ex) { console.log("Unable to lock screen orientation."); }; } else { divTwc.attr("style", ""); divTwcMiddle.attr("style", ""); iframeTwc.attr("style", ""); $(window).off("resize", FullScreenResize); FullScreenResize(); if (_unlockOrientation) try { _unlockOrientation(); } catch (ex) { console.log("Unable to unlock screen orientation."); }; } }; var InFullScreen = function() { //return true; //return (document.fullscreenEnabled || document.mozFullScreenEnabled || document.webkitFullscreenEnabled); //return (window.innerHeight == screen.height); //return (((document.fullScreenElement || document.mozFullScreenElement || document.webkitFullscreenElement) != null) || (window.innerHeight >= screen.height)); //return ((GetFullScreenElement() != null) || (window.innerHeight == screen.height)); return ((_FullScreenOverride == true) || (GetFullScreenElement() != null) || (window.innerHeight == screen.height) || (window.innerHeight == (screen.height - 1))); }; var GetFullScreenElement = function() { if (_FullScreenOverride == true) { return document.body; } return (document.fullScreenElement || document.mozFullScreenElement || document.webkitFullscreenElement || document.msFullscreenElement); } var btnFullScreen_click = function () { //_InFullScreen = !(_InFullScreen); if (InFullScreen() == false) { EnterFullScreen(); ////position:fixed; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%; border:none; margin:0; padding:0; overflow:hidden; z-index:999999; //divTwc.attr("style", "position:fixed; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;"); ////iframeTwc.attr("style", "width:100%; height:90%; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;"); ////divTwcMiddle.attr("style", "width:100%; height:100%; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;"); ////divTwcLeft.attr("style", "width:100%; height:100%; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;"); ////iframeTwc.attr("style", "width:100%; height:100%; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;"); //FullScreenResize(); //$(window).on("resize", FullScreenResize); //FullScreenResize(); } else { ExitFullscreen(); //divTwc.attr("style", ""); //divTwcMiddle.attr("style", ""); //iframeTwc.attr("style", ""); //$(window).off("resize", FullScreenResize); //FullScreenResize(); } if (_IsPlaying == true) { _NoSleep.enable(); } else { _NoSleep.disable(); } UpdateFullScreenNavigate(); return false; }; var EnterFullScreen = function () { var element = document.body; // Supports most browsers and their versions. var requestMethod; requestMethod = element.requestFullScreen || element.webkitRequestFullScreen || element.mozRequestFullScreen || element.msRequestFullscreen; if (requestMethod) { // Native full screen. //requestMethod.call(element); requestMethod.call(element, { navigationUI: "hide" }); // https://bugs.chromium.org/p/chromium/issues/detail?id=933436#c7 } else if (typeof window.ActiveXObject !== "undefined") { // Older IE. var wscript = new ActiveXObject("WScript.Shell"); if (wscript !== null) { wscript.SendKeys("{F11}"); } } else { // iOS doesn't support FullScreen API. window.scrollTo(0, 0); _FullScreenOverride = true; $(window).resize(); } UpdateFullScreenNavigate(); }; var ExitFullscreen = function () { // exit full-screen if (_FullScreenOverride == true) { _FullScreenOverride = false; $(window).resize(); } if (document.exitFullscreen) { // Chrome 71 broke this if the user pressed F11 to enter full screen mode. document.exitFullscreen(); } else if (document.webkitExitFullscreen) { document.webkitExitFullscreen(); } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if (document.msExitFullscreen) { document.msExitFullscreen(); } }; var btnNavigateMenu_click = function () { //var iFrameLocation = iframeTwc[0].contentWindow.location; //iFrameLocation.hash = ""; //iFrameLocation.hash = "aProgress"; iframeTwc[0].contentWindow.NavigateMenu(); UpdateFullScreenNavigate(); return false; }; var LoadTwcData = function (Url, AutoRefresh) { txtAddress.blur(); StopAutoRefreshTimer(); _LastUpdate = null; AssignLastUpdate(); console.log("Url: " + Url); _TwcDataUrl = Url; iframeTwc.off("load"); iframeTwc.on("load", function (e) { switch (iframeTwc.attr("src")) { case "about:blank": if (Url == "") { iframeTwc.off("load"); return; } iframeTwc.attr("src", "twc3.html?_=" + (new Date).getTime().toString()); break; default: iframeTwc.off("load"); FullScreenResize(AutoRefresh); if (radScrollText.is(":checked") == true) { AssignScrollText({ ScrollText: txtScrollText.val() }); } else if (radScrollRss.is(":checked") == true) { AssignScrollText({ ScrollRss: txtScrollRss.val() }); } if (chkScrollHazardText.is(":checked") == true) { ScrollHazardText(true); } AssignThemes({ Themes: $("input[type='radio'][name='radThemes']:checked").val() }); iframeTwc[0].contentWindow.AssignThemes({ Themes: $("input[type='radio'][name='radThemes']:checked").val() }); iframeTwc[0].contentWindow.AssignUnits({ Units: $("input[type='radio'][name='radUnits']:checked").val() }); iframeTwc[0].contentWindow.SetCallBack({ CallBack: TwcCallBack }); iframeTwc[0].contentWindow.GetLatLng(Url); if (_IsPlaying == true) { iframeTwc[0].contentWindow.NavigatePlayToggle(); } if (_IsAudioPlaying == true) { iframeTwc[0].contentWindow.AudioPlayToggle(); } if (_IsNarrationPlaying == true) { iframeTwc[0].contentWindow.NarrationPlayToggle(); } $(iframeTwc[0].contentWindow.document).on("mousemove", document_mousemove); $(iframeTwc[0].contentWindow.document).on("mousedown", document_mousemove); $(iframeTwc[0].contentWindow.document).on("keydown", document_keydown); var SwipeCallBack = function (event, direction, distance, duration, fingerCount, fingerData) { console.log("You swiped " + direction); switch (direction) { case "left": btnNavigateNext_click(); break; case "right": btnNavigatePrevious_click(); break; } }; $(iframeTwc[0].contentWindow.document).swipe({ //Generic swipe handler for all directions swipeRight: SwipeCallBack, swipeLeft: SwipeCallBack, ////Default is 75px, set to 0 for demo so any distance triggers swipe //threshold: 0 }); break; } }); iframeTwc.attr("src", "about:blank"); }; var Themes = { ThemeA: 1, // Classic ThemeB: 2, // Sea Foam ThemeC: 3, // Comsic ThemeD: 4, // Dark }; var _Themes = Themes.ThemeA; var AssignThemes = function (e) { var forecolor; var backcolor; var butncolor; var brdrcolor; var invert; var themecolor; switch (e.Themes) { case "THEMEA": _Themes = Themes.ThemeA; break; case "THEMEB": _Themes = Themes.ThemeB; break; case "THEMEC": _Themes = Themes.ThemeC; break; case "THEMED": _Themes = Themes.ThemeD; break; } switch (_Themes) { case Themes.ThemeD: forecolor = "rgb(255, 255, 255)"; backcolor = "rgb(0, 0, 0)"; butncolor = "rgb(96, 96, 96)"; brdrcolor = "rgb(255, 255, 255)"; invert = "100"; themecolor = "#000000"; break; default: forecolor = "rgb(0, 0, 0)"; backcolor = "rgb(255, 255, 255)"; butncolor = "rgb(224, 224, 224)"; brdrcolor = "rgb(0, 0, 0)"; invert = "0"; themecolor = "#ffffff"; break; } $("button, input").css("background-color", butncolor); $("input, button, .autocomplete-suggestions").css("border", "solid 1px " + brdrcolor); $("body, input, button, .autocomplete-suggestion").css("color", forecolor); $("body, input[type=text], .autocomplete-suggestions").css("background-color", backcolor); $("#imgGetGps").css("filter", "invert(" + invert + "%)"); $("meta[name=theme-color]").attr("content", themecolor); }; var AssignLastUpdate = function () { var LastUpdate = "(None)"; if (_LastUpdate) { switch ($("input[type='radio'][name='radUnits']:checked").val()) { case "ENGLISH": LastUpdate = _LastUpdate.toLocaleString('en-US', { weekday: 'short', month: 'short', day: 'numeric', year: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric', timeZoneName: 'short' }); break; case "METRIC": LastUpdate = _LastUpdate.toLocaleString('en-GB', { weekday: 'short', month: 'short', day: 'numeric', year: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric', timeZoneName: 'short' }); break; } } spanLastRefresh.html(LastUpdate); if (_LastUpdate) { if (chkAutoRefresh.is(":checked") == true) { StartAutoRefreshTimer(); } } }; var TwcCallBack = function (e) { switch (e.Status) { case "LOADED": console.log("Twc Loaded"); _LastUpdate = e.LastUpdate; AssignLastUpdate(); break; case "WEATHERPARAMETERS": console.log("Weather Parameters"); _WeatherParameters = e.WeatherParameters; PopulateWeatherParameters(); break; case "ISPLAYING": console.log("Play Toggled"); _IsPlaying = e.Value; localStorage.setItem("TwcPlay", _IsPlaying); if (_IsPlaying == true) { _NoSleep.enable(); $("img[src='images/nav/ic_play_arrow_white_24dp_1x.png']").attr("title", "Pause"); $("img[src='images/nav/ic_play_arrow_white_24dp_1x.png']").attr("src", "images/nav/ic_pause_white_24dp_1x.png"); $("img[src='images/nav/ic_play_arrow_white_24dp_2x.png']").attr("title", "Pause"); $("img[src='images/nav/ic_play_arrow_white_24dp_2x.png']").attr("src", "images/nav/ic_pause_white_24dp_2x.png"); } else { _NoSleep.disable(); $("img[src='images/nav/ic_pause_white_24dp_1x.png']").attr("title", "Play"); $("img[src='images/nav/ic_pause_white_24dp_1x.png']").attr("src", "images/nav/ic_play_arrow_white_24dp_1x.png"); $("img[src='images/nav/ic_pause_white_24dp_2x.png']").attr("title", "Play"); $("img[src='images/nav/ic_pause_white_24dp_2x.png']").attr("src", "images/nav/ic_play_arrow_white_24dp_2x.png"); } break; case "ISAUDIOPLAYING": console.log("Audio Play Toggled"); _IsAudioPlaying = e.Value; localStorage.setItem("TwcAudioPlay", _IsAudioPlaying); if (_IsAudioPlaying == true) { $("img[src='images/nav/ic_volume_off_white_24dp_1x.png']").attr("title", "Mute"); $("img[src='images/nav/ic_volume_off_white_24dp_1x.png']").attr("src", "images/nav/ic_volume_up_white_24dp_1x.png"); $("img[src='images/nav/ic_volume_off_white_24dp_2x.png']").attr("title", "Mute"); $("img[src='images/nav/ic_volume_off_white_24dp_2x.png']").attr("src", "images/nav/ic_volume_up_white_24dp_2x.png"); } else { $("img[src='images/nav/ic_volume_up_white_24dp_1x.png']").attr("title", "Unmute"); $("img[src='images/nav/ic_volume_up_white_24dp_1x.png']").attr("src", "images/nav/ic_volume_off_white_24dp_1x.png"); $("img[src='images/nav/ic_volume_up_white_24dp_2x.png']").attr("title", "Unmute"); $("img[src='images/nav/ic_volume_up_white_24dp_2x.png']").attr("src", "images/nav/ic_volume_off_white_24dp_2x.png"); } break; case "ISNARRATIONPLAYING": console.log("Narration Play Toggled"); _IsNarrationPlaying = e.Value; localStorage.setItem("TwcNarrationPlay", _IsNarrationPlaying); if (_IsNarrationPlaying == true) { $("img[src='images/nav/ic_no_hearing_white_24dp_1x.png']").attr("title", "Turn off Narration"); $("img[src='images/nav/ic_no_hearing_white_24dp_1x.png']").attr("src", "images/nav/ic_hearing_white_24dp_1x.png"); $("img[src='images/nav/ic_no_hearing_white_24dp_2x.png']").attr("title", "Turn off Narration"); $("img[src='images/nav/ic_no_hearing_white_24dp_2x.png']").attr("src", "images/nav/ic_hearing_white_24dp_2x.png"); } else { $("img[src='images/nav/ic_hearing_white_24dp_1x.png']").attr("title", "Turn on Narration"); $("img[src='images/nav/ic_hearing_white_24dp_1x.png']").attr("src", "images/nav/ic_no_hearing_white_24dp_1x.png"); $("img[src='images/nav/ic_hearing_white_24dp_2x.png']").attr("title", "Turn on Narration"); $("img[src='images/nav/ic_hearing_white_24dp_2x.png']").attr("src", "images/nav/ic_no_hearing_white_24dp_2x.png"); } break; } }; var btnNavigateRefresh_click = function () { LoadTwcData(_TwcDataUrl); UpdateFullScreenNavigate(); return false; }; var btnNavigateNext_click = function () { iframeTwc[0].contentWindow.NavigateNext(); UpdateFullScreenNavigate(); return false; }; var btnNavigatePrevious_click = function () { iframeTwc[0].contentWindow.NavigatePrevious(); UpdateFullScreenNavigate(); return false; }; var window_resize = function () { //var iFrameLocation = iframeTwc[0].contentWindow.location; //var Hash = iFrameLocation.hash; var $window = $(window); if ($window.height() == _WindowHeight || $window.width() == _WindowWidth) { return; } _WindowHeight = $window.height(); _WindowWidth = $window.width(); try { ////iFrameLocation.hash = ""; ////iFrameLocation.hash = Hash; //iframeTwc[0].contentWindow.history.replaceState("", document.title, iFrameLocation.pathname); //iframeTwc[0].contentWindow.history.replaceState("", document.title, iFrameLocation.pathname + Hash); iframeTwc[0].contentWindow.NavigateReset(); } catch (ex) { } UpdateFullScreenNavigate(); }; var _NavigateFadeIntervalId = null; var UpdateFullScreenNavigate = function () { $(document.activeElement).blur(); //console.log("window_mousemove: inFullScreen = True"); //console.log(e); //if (divTwcLeft.css("visibility") != "") //{ // divTwcLeft.css("visibility", ""); // divTwcLeft.css("opacity", "0.0"); // divTwcLeft.animate({ opacity: 1.0 }, 1000); // //divTwcLeft.fadeIn(); //} //$("body").css("cursor", ""); $("body").removeClass("HideCursor"); $(iframeTwc[0].contentWindow.document).find("body").removeClass("HideCursor"); divTwcLeft.fadeIn2(); divTwcRight.fadeIn2(); divTwcBottom.fadeIn2(); //divTwcRight.fadeIn(); if (_NavigateFadeIntervalId) { window.clearTimeout(_NavigateFadeIntervalId); _NavigateFadeIntervalId = null; } _NavigateFadeIntervalId = window.setTimeout(function () { //console.log("window_mousemove: TimeOut"); var inFullScreen = InFullScreen(); //alert(inFullScreen) if (inFullScreen == true) { //$("body").css("cursor", "none !important"); $("body").addClass("HideCursor"); //$(iframeTwc[0].contentWindow).css("cursor", "none !important"); $(iframeTwc[0].contentWindow.document).find("body").addClass("HideCursor"); //divTwcLeft.css("visibility", ""); //divTwcLeft.animate({ opacity: 0.0 }, 1000, function () //{ // divTwcLeft.css("visibility", "hidden"); //}); divTwcLeft.fadeOut2(); divTwcRight.fadeOut2(); divTwcBottom.fadeOut2(); } //divTwcRight.fadeOut(); }, 2000); }; var document_mousemove = function (e) { var inFullScreen = InFullScreen(); //alert("document_mousemove") //console.log(e.originalEvent.buttons); if (inFullScreen == true) { if ((e.originalEvent.movementX == 0 && e.originalEvent.movementY == 0 && e.originalEvent.buttons == 0)) { return; } UpdateFullScreenNavigate(); } }; var document_keydown = function (e) { //if (_AllowKeyDown == false) //{ // return; //} //_AllowKeyDown = false; //window.setTimeout(function () //{ // _AllowKeyDown = true; //}, 500); var inFullScreen = InFullScreen(); var code = (e.keyCode || e.which); if (inFullScreen == true || document.activeElement == document.body) { switch (code) { case 32: // Space btnNavigatePlay_click(); return false; break; case 39: // Right Arrow case 34: // Page Down btnNavigateNext_click(); return false; break; case 37: // Left Arrow case 33: // Page Up btnNavigatePrevious_click(); return false; break; case 36: // Home btnNavigateMenu_click(); return false; break; case 48: // Restart btnNavigateRefresh_click(); return false; break; case 77: // M btnAudioPlay_click(); return false; break; case 78: // N btnNarrationPlay_click(); return false; break; case 70: // F btnFullScreen_click(); return false; break; } } }; $.fn.fadeIn2 = function () { var _self = this; var opacity = 0.0; var IntervalId = null; if (_self.css("opacity") != "0") { return; } //_self.css("visibility", ""); _self.css("visibility", "visible"); _self.css("opacity", "0.0"); IntervalId = window.setInterval(function () { opacity += 0.1; opacity = Math.round2(opacity, 1); _self.css("opacity", opacity.toString()); if (opacity == 1.0) { //_self.css("visibility", ""); _self.css("visibility", "visible"); window.clearInterval(IntervalId); } }, 50); return _self; }; $.fn.fadeOut2 = function () { var _self = this; var opacity = 1.0; var IntervalId = null; if (_self.css("opacity") != "1") { return; } //_self.css("visibility", ""); _self.css("visibility", "visible"); _self.css("opacity", "1.0"); IntervalId = window.setInterval(function () { opacity -= 0.2; opacity = Math.round2(opacity, 1); _self.css("opacity", opacity.toString()); if (opacity == 0) { _self.css("visibility", "hidden"); window.clearInterval(IntervalId); } }, 50); return _self; }; Math.round2 = function (value, decimals) { return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals); } var btnNavigatePlay_click = function () { iframeTwc[0].contentWindow.NavigatePlayToggle(); UpdateFullScreenNavigate(); //if (iframeTwc[0].contentWindow.IsPlaying() == true) //{ // _NoSleep.enable(); // $("img[src='images/nav/ic_play_arrow_white_24dp_1x.png']").attr("title", "Pause"); // $("img[src='images/nav/ic_play_arrow_white_24dp_1x.png']").attr("src", "images/nav/ic_pause_white_24dp_1x.png"); // $("img[src='images/nav/ic_play_arrow_white_24dp_2x.png']").attr("title", "Pause"); // $("img[src='images/nav/ic_play_arrow_white_24dp_2x.png']").attr("src", "images/nav/ic_pause_white_24dp_2x.png"); //} //else //{ // _NoSleep.disable(); // $("img[src='images/nav/ic_pause_white_24dp_1x.png']").attr("title", "Play"); // $("img[src='images/nav/ic_pause_white_24dp_1x.png']").attr("src", "images/nav/ic_play_arrow_white_24dp_1x.png"); // $("img[src='images/nav/ic_pause_white_24dp_2x.png']").attr("title", "Play"); // $("img[src='images/nav/ic_pause_white_24dp_2x.png']").attr("src", "images/nav/ic_play_arrow_white_24dp_2x.png"); //} return false; }; var btnAudioPlay_click = function () { iframeTwc[0].contentWindow.AudioPlayToggle(); UpdateFullScreenNavigate(); return false; }; var btnNarrationPlay_click = function () { iframeTwc[0].contentWindow.NarrationPlayToggle(); UpdateFullScreenNavigate(); return false; }; $(function () { _WindowHeight = $(window).height(); _WindowWidth = $(window).width(); frmGetLatLng = $("#frmGetLatLng"); txtAddress = $("#txtAddress"); btnGetLatLng = $("#btnGetLatLng"); btnClearQuery = $("#btnClearQuery"); btnGetGps = $("#btnGetGps"); divLat = $("#divLat"); spanLat = $("#spanLat"); divLng = $("#divLng"); spanLng = $("#spanLng"); iframeTwc = $("#iframeTwc"); btnFullScreen = $("#btnFullScreen"); divTwc = $("#divTwc"); divTwcTop = $("#divTwcTop"); divTwcMiddle = $("#divTwcMiddle"); divTwcBottom = $("#divTwcBottom"); divTwcLeft = $("#divTwcLeft"); divTwcRight = $("#divTwcRight"); divTwcNav = $("#divTwcNav"); divTwcNavContainer = $("#divTwcNavContainer"); divTwcBottomLeft = $("#divTwcBottomLeft"); divTwcBottomMiddle = $("#divTwcBottomMiddle"); divTwcBottomRight = $("#divTwcBottomRight"); radScrollDefault = $("#radScrollDefault"); radScrollDefault.on("change", radScroll_change); frmScrollText = $("#frmScrollText"); radScrollText = $("#radScrollText"); txtScrollText = $("#txtScrollText"); btnScrollText = $("#btnScrollText"); frmScrollText.on("submit", frmScrollText_submit); txtScrollText.on("focus", function () { txtScrollText.select(); }); radScrollText.on("change", radScroll_change); frmScrollRss = $("#frmScrollRss"); radScrollRss = $("#radScrollRss"); txtScrollRss = $("#txtScrollRss"); btnScrollRss = $("#btnScrollRss"); frmScrollRss.on("submit", frmScrollRss_submit); txtScrollRss.on("focus", function () { txtScrollRss.select(); }); radScrollRss.on("change", radScroll_change); txtAddress.on("focus", function () { txtAddress.select(); }); txtAddress.focus(); $(".NavigateMenu").on("click", btnNavigateMenu_click); $(".NavigateRefresh").on("click", btnNavigateRefresh_click); $(".NavigateNext").on("click", btnNavigateNext_click); $(".NavigatePrevious").on("click", btnNavigatePrevious_click); $(".NavigatePlay").on("click", btnNavigatePlay_click); $(".ToggleVolume").on("click", btnAudioPlay_click); $(".ToggleNarration").on("click", btnNarrationPlay_click); $(btnGetGps).on("click", btnGetGps_click); //$(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange', OnFullScreen); $(window).on("resize", OnFullScreen); $(window).on("resize", window_resize); $(document).on("mousemove", document_mousemove); $(document).on("mousedown", document_mousemove); divTwc.on("mousedown", document_mousemove); $(document).on("keydown", document_keydown); document.addEventListener("touchmove", function (e) { if (_FullScreenOverride == true) e.preventDefault() }); //$(document).on("keypress", document_keydown); $(".ToggleFullScreen").on("click", btnFullScreen_click); FullScreenResize(); //var AutoSelectQuery = false; var categories = [ 'Land Features', 'Bay', 'Channel', 'Cove', 'Dam', 'Delta', 'Gulf', 'Lagoon', 'Lake', 'Ocean', 'Reef', 'Reservoir', 'Sea', 'Sound', 'Strait', 'Waterfall', 'Wharf', // Water Features 'Amusement Park', 'Historical Monument', 'Landmark', 'Tourist Attraction', 'Zoo', // POI/Arts and Entertainment 'College', // POI/Education 'Beach', 'Campground', 'Golf Course', 'Harbor', 'Nature Reserve', 'Other Parks and Outdoors', 'Park', 'Racetrack', 'Scenic Overlook', 'Ski Resort', 'Sports Center', 'Sports Field', 'Wildlife Reserve', // POI/Parks and Outdoors 'Airport', 'Ferry', 'Marina', 'Pier', 'Port', 'Resort', // POI/Travel 'Postal', 'Populated Place' ], cats = categories.join(','), overrides = { '08736, Manasquan, New Jersey, USA': { x: -74.037, y: 40.1128 }, '32899, Orlando, Florida, USA': { x: -80.6774, y: 28.6143 }, '97003, Beaverton, Oregon, USA': { x: -122.8752489, y: 45.5050916 }, '99734, Prudhoe Bay, Alaska, USA': { x: -148.3372, y: 70.2552 }, 'Guam, Oceania': { x: 144.74, y: 13.46 }, 'Andover, Maine, United States': { x: -70.7525, y: 44.634167 }, 'Bear Creek, Pennsylvania, United States': { x: -75.772809, y: 41.204074 }, 'Bear Creek Village, Pennsylvania, United States': { x: -75.772809, y: 41.204074 }, 'New York City, New York, United States': { x: -74.0059, y: 40.7142 }, 'Pinnacles National Monument, San Benito County,California, United States': { x: -121.147278, y: 36.47075 }, 'Pinnacles National Park, CA-146, Paicines, California': { x: -121.147278, y: 36.47075 }, 'Welcome, Maryland, United States': { x: -77.081212, y: 38.4692469 }, 'Tampa, Florida, United States (City)': { x: -82.5329, y: 27.9756 }, 'San Francisco, California, United States': { x: -122.3758, y: 37.6188 }, //'Dayton, Ohio, United States (City)': { x: -84.05, y: 39.85 }, }, roundToPlaces = function (num, decimals) { var n = Math.pow(10, decimals); return Math.round((n * num).toFixed(decimals)) / n; }, doRedirectToGeometry = function (geom) { var location = window.location, query = '?lat=' + roundToPlaces(geom.y, 4) + '&lon=' + roundToPlaces(geom.x, 4), origin, domain; var Url = ""; if (location.pathname.match(/MapClick.php$/)) { if (location.origin) { origin = location.origin; } else { origin = location.protocol + "//" + location.hostname + (location.port ? ':' + location.port : ''); } //window.location = origin + location.pathname + query; Url = origin + location.pathname + query; } else { if (location.hostname.match(/dev\.nids\.noaa\.gov$/)) { domain = 'forecast.dev.nids.noaa.gov'; } else if (location.hostname.match(/preview.*\.weather\.gov$/)) { domain = 'preview-forecast.weather.gov'; } else { domain = 'forecast.weather.gov'; } //window.location = location.protocol + '//' + domain + '/MapClick.php' + query; //Url = location.protocol + '//' + domain + '/MapClick.php' + query; Url = 'https://' + domain + '/MapClick.php' + query; } Url = "cors/?u=" + encodeURIComponent(Url); //GetLatLng(Url); //// First clear the iframe //iframeTwc.on("load", function (e) //{ // //console.log("loaded..."); // switch (iframeTwc.attr("src")) // { // case "about:blank": // iframeTwc.attr("src", "twc3.html?_=" + (new Date).getTime().toString()); // //iframeTwc.attr("src", "twc3.html?a"); // break; // //case "twc3.html": // default: // iframeTwc.off("load"); // iframeTwc[0].contentWindow.GetLatLng(Url); // break; // } //}); //iframeTwc.attr("src", "about:blank"); LoadTwcData(Url); // Save the query localStorage.setItem("TwcQuery", txtAddress.val()); }; var PreviousSeggestionValue = null; var PreviousSeggestion = null; var OnSelect = function (suggestion) { var request; // Do not auto get the same city twice. if (PreviousSeggestionValue == suggestion.value) { return; } PreviousSeggestionValue = suggestion.value; PreviousSeggestion = suggestion; if (overrides[suggestion.value]) { doRedirectToGeometry(overrides[suggestion.value]); } else { request = $.ajax({ url: location.protocol + '//geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/find', data: { text: suggestion.value, magicKey: suggestion.data, f: 'json' }, jsonp: 'callback', dataType: 'jsonp' }); request.done(function (data) { var loc = data.locations[0]; if (loc) { doRedirectToGeometry(loc.feature.geometry); } else { alert('An unexpected error occurred. Please try a different search string.'); } }); } }; $("#frmGetLatLng #txtAddress").devbridgeAutocomplete({ serviceUrl: location.protocol + '//geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/suggest', deferRequestBy: 300, paramName: 'text', params: { f: 'json', countryCode: 'USA', //'USA,PRI,VIR,GUM,ASM', category: cats, maxSuggestions: 10 }, dataType: 'jsonp', transformResult: function (response) { if (_AutoSelectQuery == true) { _AutoSelectQuery = false; window.setTimeout(function () { $(ac.suggestionsContainer.children[0]).click(); }, 1); } return { suggestions: $.map(response.suggestions, function (i) { return { value: i.text, data: i.magicKey }; }) }; }, minChars: 3, showNoSuggestionNotice: true, noSuggestionNotice: 'No results found. Please try a different search string.', onSelect: OnSelect, //width: 400 width: 493 }); var ac = $("#frmGetLatLng #txtAddress").devbridgeAutocomplete(); frmGetLatLng.submit(function () { if (ac.suggestions[0]) { $(ac.suggestionsContainer.children[0]).click(); return false; //PreviousSeggestion = ac.suggestions[0]; } if (PreviousSeggestion) { PreviousSeggestionValue = null; OnSelect(PreviousSeggestion); } return false; }); // Auto load the previous query var TwcQuery = localStorage.getItem("TwcQuery"); var TwcQueryStr = getParameterByName("location"); if (TwcQueryStr) { console.log(TwcQueryStr); TwcQuery = TwcQueryStr; } if (TwcQuery) { _AutoSelectQuery = true; txtAddress.val(TwcQuery); txtAddress.blur(); txtAddress.focus(); } var TwcPlay = localStorage.getItem("TwcPlay"); if (!TwcPlay || TwcPlay == "true") { _IsPlaying = true; } var TwcAudioPlay = localStorage.getItem("TwcAudioPlay"); if (!TwcAudioPlay || TwcAudioPlay == "true") { _IsAudioPlaying = true; } var TwcNarrationPlay = localStorage.getItem("TwcNarrationPlay"); if (TwcNarrationPlay == "true") { _IsNarrationPlaying = true; } radScrollDefault.prop("checked", ""); radScrollText.prop("checked", ""); radScrollRss.prop("checked", ""); var TwcScrollText = localStorage.getItem("TwcScrollText"); if (TwcScrollText) { txtScrollText.val(TwcScrollText); } var TwcScrollRss = localStorage.getItem("TwcScrollRss"); if (TwcScrollRss) { txtScrollRss.val(TwcScrollRss); } var TwcScrollChecked = localStorage.getItem("TwcScrollChecked"); if (TwcScrollChecked) { $("#" + TwcScrollChecked).prop("checked", "checked"); } else { radScrollDefault.prop("checked", "checked"); } radScroll_change(); btnClearQuery.on("click", function () { spanCity.text(""); spanState.text(""); spanStationId.text(""); spanRadarId.text(""); spanZoneId.text(""); radScrollDefault.prop("checked", "checked"); radScrollText.prop("checked", ""); txtScrollText.val(""); radScrollRss.prop("checked", ""); txtScrollRss.val(""); radScroll_change(); localStorage.removeItem("TwcScrollText"); localStorage.removeItem("TwcScrollTextChecked"); chkScrollHazardText.prop("checked", ""); localStorage.removeItem("TwcScrollHazardText"); chkAutoRefresh.prop("checked", "checked"); localStorage.removeItem("TwcAutoRefresh"); $("#radEnglish").prop("checked", "checked"); localStorage.removeItem("TwcUnits"); $("#radThemeA").prop("checked", "checked"); AssignThemes({ Themes: "THEMEA" }); localStorage.removeItem("TwcThemes"); TwcCallBack({ Status: "ISNARRATIONPLAYING", Value: false }); localStorage.removeItem("TwcNarrationPlay"); _IsNarrationPlaying = false; TwcCallBack({ Status: "ISAUDIOPLAYING", Value: false }); localStorage.removeItem("TwcAudioPlay"); _IsAudioPlaying = true; TwcCallBack({ Status: "ISPLAYING", Value: false }); localStorage.removeItem("TwcPlay"); _IsPlaying = true; localStorage.removeItem("TwcQuery"); PreviousSeggestionValue = null; PreviousSeggestion = null; LoadTwcData(""); }); var TwcUnits = localStorage.getItem("TwcUnits"); if (!TwcUnits || TwcUnits == "ENGLISH") { $("#radEnglish").prop("checked", "checked"); } else if (TwcUnits == "METRIC") { $("#radMetric").prop("checked", "checked"); } var TwcThemes = localStorage.getItem("TwcThemes"); if (!TwcThemes || TwcThemes == "THEMEA") { $("#radThemeA").prop("checked", "checked"); } else if (TwcThemes == "THEMEB") { $("#radThemeB").prop("checked", "checked"); } else if (TwcThemes == "THEMEC") { $("#radThemeC").prop("checked", "checked"); } else if (TwcThemes == "THEMED") { $("#radThemeD").prop("checked", "checked"); } AssignThemes({ Themes: TwcThemes }); $("input[type='radio'][name='radUnits']").on("change", function () { var Units = $(this).val(); localStorage.setItem("TwcUnits", Units); AssignLastUpdate(); iframeTwc[0].contentWindow.AssignUnits({ Units: Units }); }); $("input[type='radio'][name='radThemes']").on("change", function () { var Themes = $(this).val(); localStorage.setItem("TwcThemes", Themes); AssignThemes({ Themes: Themes }); iframeTwc[0].contentWindow.AssignThemes({ Themes: Themes }); }); divRefresh = $("#divRefresh"); spanLastRefresh = $("#spanLastRefresh"); chkAutoRefresh = $("#chkAutoRefresh"); lblRefreshCountDown = $("#lblRefreshCountDown"); spanRefreshCountDown = $("#spanRefreshCountDown"); chkAutoRefresh.on("change", function () { var Checked = $(this).is(":checked"); if (_LastUpdate) { if (Checked == true) { StartAutoRefreshTimer(); } else { StopAutoRefreshTimer(); } } localStorage.setItem("TwcAutoRefresh", Checked); }); var TwcAutoRefresh = localStorage.getItem("TwcAutoRefresh"); if (!TwcAutoRefresh || TwcAutoRefresh == "true") { chkAutoRefresh.prop("checked", "checked"); } else { chkAutoRefresh.prop("checked", ""); } spanCity = $("#spanCity"); spanState = $("#spanState"); spanStationId = $("#spanStationId"); spanRadarId = $("#spanRadarId"); spanZoneId = $("#spanZoneId"); chkScrollHazardText = $("#chkScrollHazardText"); chkScrollHazardText.on("change", function () { var Checked = $(this).is(":checked"); ScrollHazardText(Checked); localStorage.setItem("TwcScrollHazardText", Checked); }); var TwcScrollHazardText = localStorage.getItem("TwcScrollHazardText"); if (TwcScrollHazardText && TwcScrollHazardText == "true") { chkScrollHazardText.prop("checked", "checked"); } else { chkScrollHazardText.prop("checked", ""); } }); var ScrollHazardText = function (enable) { if (iframeTwc[0].contentWindow.ScrollHazardText) { iframeTwc[0].contentWindow.ScrollHazardText(enable); } }; var StartAutoRefreshTimer = function () { //// Esnure that any previous timer has already stopped. //StopAutoRefreshTimer(); if (_AutoRefreshIntervalId) { // Timer is already running. return; } // Reset the time elapsed. _AutoRefreshCountMs = 0; var AutoRefreshTimer = function () { // Increment the total time elapsed. _AutoRefreshCountMs += _AutoRefreshIntervalMs; // Display the count down. var RemainingMs = (_AutoRefreshTotalIntervalMs - _AutoRefreshCountMs); if (RemainingMs < 0) { RemainingMs = 0; } var dt = new Date(RemainingMs); spanRefreshCountDown.html((dt.getMinutes() < 10 ? "0" + dt.getMinutes() : dt.getMinutes()) + ":" + (dt.getSeconds() < 10 ? "0" + dt.getSeconds() : dt.getSeconds())); if (_AutoRefreshCountMs >= _AutoRefreshTotalIntervalMs) { // Time has elapsed. LoadTwcData(_TwcDataUrl, true); } }; _AutoRefreshIntervalId = window.setInterval(AutoRefreshTimer, _AutoRefreshIntervalMs); AutoRefreshTimer(); }; var StopAutoRefreshTimer = function () { if (_AutoRefreshIntervalId) { window.clearInterval(_AutoRefreshIntervalId); spanRefreshCountDown.html("--:--"); _AutoRefreshIntervalId = null; } }; var btnGetGps_click = function () { if (!navigator.geolocation) { return; } var CurrentPosition = function (Position) { var Latitude = Position.coords.latitude; var Longitude = Position.coords.longitude; //Latitude = 40.7754622; Longitude = -73.2411506; console.log("Latitude: " + Latitude + "; Longitude: " + Longitude); //http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/reverseGeocode?location=-72.971293%2C+40.850043&f=pjson request = $.ajax({ url: location.protocol + '//geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/reverseGeocode', data: { location: Longitude + "," + Latitude, distance: 1000, // Find location upto 1 KM. f: 'json' }, jsonp: 'callback', dataType: 'jsonp' }); request.done(function (data) { console.log(data); var ZipCode = data.address.Postal; var City = data.address.City; var State = getStateTwoDigitCode(data.address.Region); var Country = data.address.CountryCode; var TwcQuery = ZipCode + ", " + City + ", " + State + ", " + Country; //var Url = "http://forecast.weather.gov/MapClick.php?lat=" + Latitude + "&lon=" + Longitude; txtAddress.val(TwcQuery); txtAddress.blur(); txtAddress.focus(); // Save the query localStorage.setItem("TwcQuery", TwcQuery); //LoadTwcData(Url); }); }; navigator.geolocation.getCurrentPosition(CurrentPosition); }; var PopulateWeatherParameters = function () { spanCity.text(_WeatherParameters.City + ", "); spanState.text(_WeatherParameters.State); spanStationId.text(_WeatherParameters.StationId); spanRadarId.text(_WeatherParameters.RadarId); spanZoneId.text(_WeatherParameters.ZoneId); }; var frmScrollText_submit = function (e) { radScroll_change(); return false; }; var frmScrollRss_submit = function (e) { radScroll_change(); return false; }; var radScroll_change = function (e) { txtScrollText.blur(); txtScrollText.addClass("Disabled"); btnScrollText.addClass("Disabled"); txtScrollRss.blur(); txtScrollRss.addClass("Disabled"); btnScrollRss.addClass("Disabled"); var ScrollCheckedId = $("input[name='radScroll']:checked").attr("id"); localStorage.setItem("TwcScrollChecked", ScrollCheckedId); switch (ScrollCheckedId) { case "radScrollDefault": AssignScrollText(null); break; case "radScrollText": txtScrollText.removeClass("Disabled"); btnScrollText.removeClass("Disabled"); var ScrollText = txtScrollText.val(); localStorage.setItem("TwcScrollText", ScrollText); AssignScrollText({ ScrollText: ScrollText }); break; case "radScrollRss": txtScrollRss.removeClass("Disabled"); btnScrollRss.removeClass("Disabled"); var ScrollRss = txtScrollRss.val(); localStorage.setItem("TwcScrollRss", ScrollRss); AssignScrollText({ ScrollRss: ScrollRss }); break; } }; var AssignScrollText = function (e) { if (iframeTwc[0].contentWindow.AssignScrollText) { iframeTwc[0].contentWindow.AssignScrollText(e); } }; var getParameterByName = function (name, url) { if (!url) url = window.location.href; url = decodeURIComponent(url); name = name.replace(/[\[\]]/g, "\\$&"); var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"), results = regex.exec(url); if (!results) return null; if (!results[2]) return ''; return decodeURIComponent(results[2].replace(/\+/g, " ")); };
/** * Forward renderer */ var ForwardRenderStage = PostProcessRenderStage.extend({ init: function() { this._super(); this.debugActive = false; this.debugger = null; }, onPostRender: function(context, scene, camera) { this._super(context, scene, camera); if (this.debugActive) { if (!this.debugger) this.initDebugger(context, scene); var gl = context.gl; gl.disable(gl.DEPTH_TEST); gl.disable(gl.CULL_FACE); context.modelview.push(); for (var i=0; i<this.debugger.quads.length; i++) { this.debugger.sampler.texture = this.debugger.quads[i].texture; this.material.bind({}, [this.debugger.sampler]); this.debugger.quads[i].quad.render(this.material.shader); this.material.unbind([this.debugger.sampler]); } this.debugger.sampler.texture = this.debugger.vsyncTextures[0]; this.material.bind({}, [this.debugger.sampler]); this.debugger.vsyncQuad.render(this.material.shader); this.material.unbind([this.debugger.sampler]); this.debugger.vsyncTextures.reverse(); context.modelview.pop(); } }, debug: function(val) { this.debugActive = !(val === false); }, initDebugger: function(context, scene) { var texRed = new Texture(context); texRed.name = "Red"; texRed.mipmapped = false; texRed.clearImage(context, [0xFF, 0x00, 0x00, 0xFF]); var texCyan = new Texture(context); texCyan.name = "Red"; texCyan.mipmapped = false; texCyan.clearImage(context, [0x00, 0xFF, 0xFF, 0xFF]); this.debugger = { quads: [], sampler: new Sampler('tex0', null), vsyncQuad: createQuad(0.85, 0.85, 0.1, 0.1), vsyncTextures: [ texRed, texCyan ] }; function createQuad(x, y, width, height) { var vertices = [x,y,0, x,y+height,0, x+width,y+height,0, x+width,y,0]; var quad = new TrianglesRenderBuffer(context, [0, 1, 2, 0, 2, 3]); quad.add('position', vertices, 3); quad.add("uv0", [0,0, 0,1, 1,1, 1,0], 2); return quad; } // Draw shadowmaps var size = 0.5; var x = -1; var y = 1 - size; for (var i=0; i<scene.lights.length; i++) { if (!scene.lights[i].enabled) continue; if (!scene.lights[i].shadowCasting) continue; if (!scene.lights[i].shadow) continue; if (scene.lights[i] instanceof DirectionalLight) { this.debugger.quads.push({ quad: createQuad(x, y, size, size), texture: scene.lights[i].shadow.texture }); x+=size; } } // Draw OIT buffers var size = 2/4; var x = -1; var y = -1; if (this.generator.oitStage.enabled) { this.debugger.quads.push({ quad: createQuad(x, y, size, size), texture: this.generator.oitStage.transparencyTarget.texture }); this.debugger.quads.push({ quad: createQuad(x+=size, y, size, size), texture: this.generator.oitStage.transparencyWeight.texture }); } // Draw depth stage, if enabled if (this.generator.depthStage.enabled) { this.debugger.quads.push({ quad: createQuad(x+=size, y, size, size), texture: this.generator.depthStage.target.texture }); } } });
"use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var SearchMailboxesResult_1 = require("../../MailboxSearch/SearchMailboxesResult"); var XmlElementNames_1 = require("../XmlElementNames"); var ServiceResponse_1 = require("./ServiceResponse"); /** * Represents the SearchMailboxes response. * * @sealed */ var SearchMailboxesResponse = (function (_super) { __extends(SearchMailboxesResponse, _super); /** * @internal Initializes a new instance of the **SearchMailboxesResponse** class. */ function SearchMailboxesResponse() { _super.call(this); this.searchResult = null; } Object.defineProperty(SearchMailboxesResponse.prototype, "SearchResult", { /** * Search mailboxes result */ get: function () { return this.searchResult; }, /**@internal set*/ set: function (value) { this.searchResult = value; }, enumerable: true, configurable: true }); /** * @internal Reads response elements from Xml JsObject. * * @param {any} jsObject The response object. * @param {ExchangeService} service The service. */ SearchMailboxesResponse.prototype.ReadElementsFromXmlJsObject = function (jsObject, service) { //super.ReadElementsFromXmlJsObject(jsObject, service); if (jsObject[XmlElementNames_1.XmlElementNames.SearchMailboxesResult]) { this.searchResult = SearchMailboxesResult_1.SearchMailboxesResult.LoadFromXmlJsObject(jsObject[XmlElementNames_1.XmlElementNames.SearchMailboxesResult], service); } }; return SearchMailboxesResponse; }(ServiceResponse_1.ServiceResponse)); exports.SearchMailboxesResponse = SearchMailboxesResponse;
var classstd_1_1allocator = [ [ "allocator", "d7/d75/classstd_1_1allocator.html#af58fb50c569cbd3244176fcbaedd8130", null ], [ "~allocator", "d7/d75/classstd_1_1allocator.html#a2391d38030fc1dca45118d2369ace201", null ], [ "allocate", "d7/d75/classstd_1_1allocator.html#aa134fbfdd3f8043f97cef77ce1956a40", null ], [ "allocate_aligned", "d7/d75/classstd_1_1allocator.html#acf631da5e35403653507f2de025c7966", null ], [ "deallocate", "d7/d75/classstd_1_1allocator.html#a023ddc78c271be016433e2e59a98df1c", null ], [ "get_name", "d7/d75/classstd_1_1allocator.html#acb0194676fc6dcf5df82e2b0c866b038", null ] ];
import React from 'react' import PropTypes from 'prop-types' import Control from '../control' import Fields from './fields' import _ from 'lodash' class Field extends React.Component { static propTypes = { action: PropTypes.string, columns: PropTypes.array, data: PropTypes.object, endpoint: PropTypes.string, errors: PropTypes.object, fields: PropTypes.array, include: PropTypes.bool, instructions: PropTypes.string, label: PropTypes.string, name: PropTypes.string, options: PropTypes.array, required: PropTypes.bool, tabIndex: PropTypes.number, type: PropTypes.oneOfType([ PropTypes.string, PropTypes.func ]).isRequired, scroll: PropTypes.bool, show: PropTypes.bool, onBusy: PropTypes.func, onReady: PropTypes.func, onScrollTo: PropTypes.func, onUpdateData: PropTypes.func } static defaultProps = { columns: [], data: {}, errors: {}, fields: [], include: true, options: [], required: false, scroll: true, show: true, onBusy: () => {}, onReady: () => {}, onUpdateData: () => {} } control = null _handleBusy = this._handleBusy.bind(this) _handleReady = this._handleReady.bind(this) _handleUpdateData = this._handleUpdateData.bind(this) render() { const { include, instructions, label, show, type } = this.props const error = this._getError() if(!include || !show) return null return ( <div className={ this._getClass() } key="control" ref={ node => this.control = node }> { label && <label>{ label }</label> } { instructions && <div className="instructions">{ instructions }</div> } { type === 'fields' ? <Fields { ...this._getFields() } /> : <Control { ...this._getControl() } /> } { error && <div className="error-message">{ error }</div> } </div> ) } componentDidUpdate(prevProps) { const { scroll, data, name } = this.props if(!_.isEqual(_.get(data, name), _.get(prevProps.data, name)) && scroll) { setTimeout(this._handleScrollTo.bind(this), 150) } } _getClass() { const { required } = this.props const error = this._getError() const classes = ['field'] if(required) classes.push('required') if(error) classes.push('error') return classes.join(' ') } _getError() { const { errors, name } = this.props return (errors && errors[name]) ? errors[name][0] : null } _getFields() { const { fields, form, onBusy, onReady, onUpdateData } = this.props return { fields, form, onBusy, onReady, onUpdateData } } _getControl() { const { data, name } = this.props const defaultValue = _.get(data, name) return { ...this.props, defaultValue, onBusy: this._handleBusy, onChange: this._handleUpdateData, onReady: this._handleReady } } _handleBusy() { this.props.onBusy(this.props.name) } _handleReady() { this.props.onReady(this.props.name) } _handleScrollTo() { const bottom = this.control.offsetTop + this.control.offsetHeight this.props.onScrollTo(bottom) } _handleUpdateData(value) { this.props.onUpdateData(this.props.name, value) } } export default Field
export default class End extends Phaser.State { constructor() { super(); } preload() { } create() { } update() { } }
'use strict'; var meta = $('.e2-player-meta-song').text().split(' · '); /* global Connector */ Connector.playerSelector = '.e2-player'; Connector.playButtonSelector = '.e2-player-control-play'; Connector.isPlaying = function() { return !$('.e2-player-control-play').is(':visible'); }; Connector.getArtist = function() { return meta[0]; }; Connector.getTrack = function() { return meta[1]; }; $(document).ready(function(){ // Needed because DOM is not changed during first song setTimeout(function() { $(Connector.playerSelector).append('<div class="webscrobbler-connector-loaded" style="display:none;"></div>'); }, 1000); });
/* * Copyright (c) 2012-2015 S-Core Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Constructor function * TextEditorPart implementation of EditorPart * This should be an ancestor of all text based editors. * * @constructor * @see EditorPart * @since: 2015.06.11 * @author: hw.shim * * file.__elemId removed */ // @formatter:off define([ 'dojo/topic', 'external/lodash/lodash.min', 'webida-lib/util/genetic', 'webida-lib/util/logger/logger-client', 'plugins/editors/plugin', 'plugins/editors/EditorPreference', 'plugins/workbench/plugin', 'plugins/workbench/ui/EditorModelManager', 'plugins/workbench/ui/EditorPart', 'plugins/workbench/ui/Part', 'plugins/workbench/ui/PartContainer', 'plugins/workbench/ui/PartModel', 'plugins/workbench/ui/partModelProvider', 'plugins/workbench/ui/PartRegistry', './configloader', './Document', './DocumentCommand', './preferences/preference-config', './TextEditorContextMenu', './TextEditorViewer', 'dojo/domReady!' ], function( topic, _, genetic, Logger, editors, EditorPreference, workbench, EditorModelManager, EditorPart, Part, PartContainer, PartModel, partModelProvider, PartRegistry, configloader, Document, DocumentCommand, preferenceConfig, TextEditorContextMenu, TextEditorViewer ) { 'use strict'; // @formatter:on /** * @typedef {Object} DataSource * @typedef {Object} Document */ //TODO : this.viewer -> this.getViewer() //See File.prototype.isModified = function () { var logger = new Logger(); //logger.off(); var preferenceIds = ['texteditor', 'texteditor.lines', 'texteditor.key-map', 'texteditor.show-hide', 'content-assist']; //To support synchronizeWidgetModel //TODO : refactor var recentViewers = new Map(); var partRegistry = workbench.getCurrentPage().getPartRegistry(); partRegistry.on(PartRegistry.PART_UNREGISTERED, function(part) { if (partModelProvider.isModelUsed(part.getModel()) === false) { recentViewers['delete'](part.getDataSource()); } }); function TextEditorPart(container) { logger.info('new TextEditorPart(' + container + ')'); EditorPart.apply(this, arguments); var that = this; var dataSource = container.getDataSource(); //TODO remove all dependency to file this.file = dataSource.getPersistence(); this.fileOpenedHandle = null; this.fileSavedHandle = null; this.preferences = null; this.foldingStatus = null; this.on(Part.CONTENT_READY, function(part) { console.log('Part.CONTENT_READY!!'); var viewer = part.getViewer(); var ds = part.getDataSource(); var recentViewer = recentViewers.get(ds); if (recentViewer) { viewer.synchronizeWidgetModel(recentViewer); } recentViewers.set(ds, viewer); }); } genetic.inherits(TextEditorPart, EditorPart, { initialize: function() { logger.info('initialize()'); this.initializeViewer(); this.initializeListeners(); this.initializePreferences(); }, initializeViewer: function() { logger.info('initializeViewer()'); var that = this; var viewer = this.getViewer(); var parent = this.getParentElement(); viewer.clearHistory(); viewer.markClean(); viewer.setSize(parent.offsetWidth, parent.offsetHeight); viewer.setMatchBrackets(true); var setStatusBarText = function() { var workbench = require('plugins/workbench/plugin'); var file = that.file; var viewer = that.getViewer(); var cursor = viewer.getCursor(); workbench.__editor = viewer; //TODO : refactor workbench.setContext([file.path], { cursor: (cursor.row + 1) + ':' + (cursor.col + 1) }); }; viewer.addCursorListener(setStatusBarText); viewer.addFocusListener(setStatusBarText); viewer.addCursorListener(function(viewer) { TextEditorPart.pushCursorLocation(viewer.file, viewer.getCursor()); }); viewer.addExtraKeys({ 'Ctrl-Alt-Left': function() { TextEditorPart.moveBack(); }, 'Ctrl-Alt-Right': function() { TextEditorPart.moveForth(); } }); }, /** * To initialize listeners you want * override this */ initializeListeners: function() { logger.info('initializeListeners()'); var that = this; //TODO : remove listener this.on(EditorPart.AFTER_SAVE, function() { that.foldingStatus = that.getViewer().getFoldings(); }); }, initializePreferences: function() { logger.info('initializePreferences()'); var viewer = this.getViewer(); var file = this.file; //preferences this.preferences = new EditorPreference(preferenceIds, viewer); this.preferences.setFields(this.getPreferences()); //editorconfig this.preferences.getField('texteditor', 'webida.editor.text-editor:editorconfig', function(value) { if (value === true) { configloader.editorconfig(viewer, file); } }); }, /** * To use the Preferences you want, override this method * and return Preferences you want use * * @returns preferenceConfig for TextEditor */ getPreferences: function() { return preferenceConfig; }, /** * To use the Context you want, override this method * and return Class you want use * * @returns TextEditorViewer */ getViewerClass: function() { return TextEditorViewer; }, /** * TODO : move to CodeEditorPart */ getFoldingStatus: function() { return this.foldingStatus; }, /** * @param {HTMLElement} parent * @return {Viewer} */ createViewer: function(parentNode) { logger.info('%c createViewer(' + parentNode.tagName + ')', 'color:green'); //TODO : remove this.setParentElement(parentNode); var that = this; //Viewer var ViewerClass = this.getViewerClass(); var viewer = new (ViewerClass)(parentNode, this.file); this.setViewer(viewer); this.initialize(); return viewer; }, /** * @return {Document} */ createModel: function() { logger.info('%c createModel()', 'color:green'); this.setModelManager(new EditorModelManager(this.getDataSource())); var model = this.getModelManager().getSynchronized(Document); //this.getModelManager().SynchroWith(SvgModel); this.setModel(model); return model; }, onDestroy: function() { logger.info('onDestroy()'); EditorPart.prototype.onDestroy.apply(this); if (this.viewer) { this.viewer.destroyWidget(); this.viewer = null; } else { logger.info('this.viewer not found'); logger.trace(); } //unset preferences if (this.preferences) { this.preferences.unsetFields(); } //unsubscribe topic if (this.fileOpenedHandle !== null) { logger.info('this.fileOpenedHandle.remove()'); this.fileOpenedHandle.remove(); } if (this.fileSavedHandle !== null) { this.fileSavedHandle.remove(); } }, focus: function() { logger.info('focus()'); this.getViewer().focus(); }, /** * @return {DocumentCommand} */ getCommand: function(request) { return new DocumentCommand(this.getModel(), request); }, getContextMenuClass: function() { return TextEditorContextMenu; }, getContextMenuItems: function(allItems) { logger.info('getContextMenuItems(' + allItems + ')'); var contextMenu = new (this.getContextMenuClass())(allItems, this); return contextMenu.getPromiseForAvailableItems(); }, save: function(callback) { logger.info('save(' + typeof callback + ')'); var that = this; this._beforeSave(); //TODO Refactor : find more neat way without setTimeout setTimeout(function() { EditorPart.prototype.save.call(that, callback); }); }, _beforeSave: function() { logger.info('_beforeSave'); var viewer = this.getViewer(); var doc = this.getModel(); var text = doc.getContents(); if ( typeof text === 'undefined') { return; } //logger.info('viewer.trimTrailingWhitespaces = ', // viewer.trimTrailingWhitespaces); //logger.info('viewer.insertFinalNewLine = ', // viewer.insertFinalNewLine); //logger.info('viewer.retabIndentations = ', // viewer.retabIndentations); if (viewer.trimTrailingWhitespaces && text.match(/( |\t)+$/m)) { text = text.replace(/( |\t)+$/mg, ''); } if (viewer.insertFinalNewLine && text.match(/.$/)) { text = text + '\n'; } if (viewer.retabIndentations) { var getSpaces = function(n) { var spaces = ['', ' ', ' ', ' ', ' ']; if (spaces[n] === undefined) { return (spaces[n] = ( n ? ' ' + getSpaces(n - 1) : '')); } else { return spaces[n]; } }; var unit = viewer.options.indentUnit, re = /^(( )*)\t/m, m; while (( m = text.match(re))) { text = text.replace(re, '$1' + getSpaces(unit - (m[0].length - 1) % unit)); } } if (text !== doc.getContents()) { var cursor = viewer.getCursor(); var scrollInfo = viewer.getScrollInfo(); viewer.refresh(text); //TODO Refactor : use execCommand(); viewer.setCursor(cursor); viewer.scrollToScrollInfo(scrollInfo); } } }); //Static functions var cursorStacks = { back: [], forth: [] }; TextEditorPart.moveTo = function(location) { topic.publish('editor/open', location.filepath, { show: true }, function(part) { var viewer = part.getViewer(); if (location.start && location.end) { viewer.setSelection(location.start, location.end); } else { viewer.setCursor(location.cursor); } viewer.addDeferredAction(function(viewer) { viewer.editor.focus(); }); }); }; TextEditorPart.moveBack = function() { if (cursorStacks.back.length > 1) { var popped = cursorStacks.back.pop(); if (popped) { cursorStacks.forth.push(popped); } TextEditorPart.moveTo(cursorStacks.back[cursorStacks.back.length - 1]); } }; TextEditorPart.moveForth = function() { var popped = cursorStacks.forth.pop(); if (popped) { cursorStacks.back.push(popped); TextEditorPart.moveTo(popped); } }; TextEditorPart.pushCursorLocation = function(file, cursor, forced) { logger.info('pushCursorLocation(file, ' + cursor + ', forced)'); var filepath = ( typeof file === 'string') ? file : file.getPath(); var thisLocation = { filepath: filepath, cursor: cursor, timestamp: new Date().getTime(), forced: forced }; function compareLocations(cursor1, cursor2, colspan, rowspan, timespan) { if (cursor1.filepath === cursor2.filepath) { // @formatter:off if (((!colspan || (Math.abs(cursor1.cursor.col - cursor2.cursor.col) < colspan)) && (!rowspan || (Math.abs(cursor1.cursor.row - cursor2.cursor.row) < rowspan))) || (!timespan || (Math.abs(cursor1.timestamp - cursor2.timestamp) < timespan))) { return true; } // @formatter:on return false; } else { return false; } } function similarLocations(cursor1, cursor2) { return compareLocations(cursor1, cursor2, 5, 5, 3000); } function identicalLocations(cursor1, cursor2) { return compareLocations(cursor1, cursor2, 1, 1, false); } if (cursorStacks.back.length > 0) { var latest = cursorStacks.back.pop(); // @formatter:off if (((forced || latest.forced) && !identicalLocations(thisLocation, latest)) || (!similarLocations(thisLocation, latest))) { cursorStacks.back.push(latest); cursorStacks.forth = []; } // @formatter:on } cursorStacks.back.push(thisLocation); return thisLocation; }; return TextEditorPart; });
var jsdom = require('jsdom').jsdom; var exposedProperties = ['window', 'navigator', 'document']; global.document = jsdom(''); global.window = document.defaultView; Object.keys(document.defaultView).forEach((property) => { if (typeof global[property] === 'undefined') { exposedProperties.push(property); global[property] = document.defaultView[property]; } }); global.navigator = { userAgent: 'node.js' }; var documentRef = document;
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var batteryEmpty = exports.batteryEmpty = { "viewBox": "0 0 2304 1792", "children": [{ "name": "path", "attribs": { "d": "M2176 576q53 0 90.5 37.5t37.5 90.5v384q0 53-37.5 90.5t-90.5 37.5v160q0 66-47 113t-113 47h-1856q-66 0-113-47t-47-113v-960q0-66 47-113t113-47h1856q66 0 113 47t47 113v160zM2176 1088v-384h-128v-288q0-14-9-23t-23-9h-1856q-14 0-23 9t-9 23v960q0 14 9 23t23 9h1856q14 0 23-9t9-23v-288h128z" } }] };
// Array.includes is not available in IE or Edge if (!Array.prototype.includes) { Array.prototype.includes = function(searchElement /*, fromIndex*/ ) { 'use strict'; var O = Object(this); var len = parseInt(O.length) || 0; if (len === 0) { return false; } var n = parseInt(arguments[1]) || 0; var k; if (n >= 0) { k = n; } else { k = len + n; if (k < 0) {k = 0;} } var currentElement; while (k < len) { currentElement = O[k]; if (searchElement === currentElement || (searchElement !== searchElement && currentElement !== currentElement)) { // NaN !== NaN return true; } k++; } return false; }; }
'use strict'; const sequelizeErrors = require('../../errors'); const QueryTypes = require('../../query-types'); const { QueryInterface } = require('../abstract/query-interface'); const { cloneDeep } = require('../../utils'); /** * The interface that Sequelize uses to talk with SQLite database */ class SQLiteQueryInterface extends QueryInterface { /** * A wrapper that fixes SQLite's inability to remove columns from existing tables. * It will create a backup of the table, drop the table afterwards and create a * new table with the same name but without the obsolete column. * * @override */ async removeColumn(tableName, attributeName, options) { options = options || {}; const fields = await this.describeTable(tableName, options); delete fields[attributeName]; const sql = this.queryGenerator.removeColumnQuery(tableName, fields); const subQueries = sql.split(';').filter(q => q !== ''); for (const subQuery of subQueries) await this.sequelize.query(`${subQuery};`, { raw: true, ...options }); } /** * A wrapper that fixes SQLite's inability to change columns from existing tables. * It will create a backup of the table, drop the table afterwards and create a * new table with the same name but with a modified version of the respective column. * * @override */ async changeColumn(tableName, attributeName, dataTypeOrOptions, options) { options = options || {}; const fields = await this.describeTable(tableName, options); fields[attributeName] = this.normalizeAttribute(dataTypeOrOptions); const sql = this.queryGenerator.removeColumnQuery(tableName, fields); const subQueries = sql.split(';').filter(q => q !== ''); for (const subQuery of subQueries) await this.sequelize.query(`${subQuery};`, { raw: true, ...options }); } /** * A wrapper that fixes SQLite's inability to rename columns from existing tables. * It will create a backup of the table, drop the table afterwards and create a * new table with the same name but with a renamed version of the respective column. * * @override */ async renameColumn(tableName, attrNameBefore, attrNameAfter, options) { options = options || {}; const fields = await this.assertTableHasColumn(tableName, attrNameBefore, options); fields[attrNameAfter] = { ...fields[attrNameBefore] }; delete fields[attrNameBefore]; const sql = this.queryGenerator.renameColumnQuery(tableName, attrNameBefore, attrNameAfter, fields); const subQueries = sql.split(';').filter(q => q !== ''); for (const subQuery of subQueries) await this.sequelize.query(`${subQuery};`, { raw: true, ...options }); } /** * @override */ async removeConstraint(tableName, constraintName, options) { let createTableSql; const constraints = await this.showConstraint(tableName, constraintName); // sqlite can't show only one constraint, so we find here the one to remove const constraint = constraints.find(constaint => constaint.constraintName === constraintName); if (!constraint) { throw new sequelizeErrors.UnknownConstraintError({ message: `Constraint ${constraintName} on table ${tableName} does not exist`, constraint: constraintName, table: tableName }); } createTableSql = constraint.sql; constraint.constraintName = this.queryGenerator.quoteIdentifier(constraint.constraintName); let constraintSnippet = `, CONSTRAINT ${constraint.constraintName} ${constraint.constraintType} ${constraint.constraintCondition}`; if (constraint.constraintType === 'FOREIGN KEY') { const referenceTableName = this.queryGenerator.quoteTable(constraint.referenceTableName); constraint.referenceTableKeys = constraint.referenceTableKeys.map(columnName => this.queryGenerator.quoteIdentifier(columnName)); const referenceTableKeys = constraint.referenceTableKeys.join(', '); constraintSnippet += ` REFERENCES ${referenceTableName} (${referenceTableKeys})`; constraintSnippet += ` ON UPDATE ${constraint.updateAction}`; constraintSnippet += ` ON DELETE ${constraint.deleteAction}`; } createTableSql = createTableSql.replace(constraintSnippet, ''); createTableSql += ';'; const fields = await this.describeTable(tableName, options); const sql = this.queryGenerator._alterConstraintQuery(tableName, fields, createTableSql); const subQueries = sql.split(';').filter(q => q !== ''); for (const subQuery of subQueries) await this.sequelize.query(`${subQuery};`, { raw: true, ...options }); } /** * @override */ async addConstraint(tableName, options) { if (!options.fields) { throw new Error('Fields must be specified through options.fields'); } if (!options.type) { throw new Error('Constraint type must be specified through options.type'); } options = cloneDeep(options); const constraintSnippet = this.queryGenerator.getConstraintSnippet(tableName, options); const describeCreateTableSql = this.queryGenerator.describeCreateTableQuery(tableName); const constraints = await this.sequelize.query(describeCreateTableSql, { ...options, type: QueryTypes.SELECT, raw: true }); let sql = constraints[0].sql; const index = sql.length - 1; //Replace ending ')' with constraint snippet - Simulates String.replaceAt //http://stackoverflow.com/questions/1431094 const createTableSql = `${sql.substr(0, index)}, ${constraintSnippet})${sql.substr(index + 1)};`; const fields = await this.describeTable(tableName, options); sql = this.queryGenerator._alterConstraintQuery(tableName, fields, createTableSql); const subQueries = sql.split(';').filter(q => q !== ''); for (const subQuery of subQueries) await this.sequelize.query(`${subQuery};`, { raw: true, ...options }); } /** * @override */ async getForeignKeyReferencesForTable(tableName, options) { const database = this.sequelize.config.database; const query = this.queryGenerator.getForeignKeysQuery(tableName, database); const result = await this.sequelize.query(query, options); return result.map(row => ({ tableName, columnName: row.from, referencedTableName: row.table, referencedColumnName: row.to, tableCatalog: database, referencedTableCatalog: database })); } /** * @override */ async dropAllTables(options) { options = options || {}; const skip = options.skip || []; const tableNames = await this.showAllTables(options); await this.sequelize.query('PRAGMA foreign_keys = OFF', options); await this._dropAllTables(tableNames, skip, options); await this.sequelize.query('PRAGMA foreign_keys = ON', options); } } exports.SQLiteQueryInterface = SQLiteQueryInterface;
export { default } from "@getflights/ember-field-components/helpers/route-exists";
'use strict'; module.exports = { db: 'mongodb://localhost/choreminder-dev', assets: { lib: { css: [ 'public/lib/bootstrap/dist/css/bootstrap.min.css', 'public/lib/bootstrap/dist/css/bootstrap-theme.min.css', 'public/lib/ng-sortable/dist/ng-sortable.css', 'public/lib/ng-sortable/dist/ng-sortable.style.css' ], js: [ 'public/lib/angular/angular.min.js', 'public/lib/angular-resource/angular-resource.js', 'public/lib/angular-cookies/angular-cookies.js', 'public/lib/angular-animate/angular-animate.js', 'public/lib/angular-touch/angular-touch.js', 'public/lib/angular-sanitize/angular-sanitize.js', 'public/lib/angular-ui-router/release/angular-ui-router.min.js', 'public/lib/angular-ui-utils/ui-utils.min.js', 'public/lib/angular-bootstrap/ui-bootstrap-tpls.min.js', 'public/lib/ng-sortable/dist/ng-sortable.js' ] }, css: 'public/dist/application.min.css', js: 'public/dist/application.min.js' }, app: { title: 'ChoreMinder' }, facebook: { clientID: process.env.FACEBOOK_ID || 'APP_ID', clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET', callbackURL: '/auth/facebook/callback' }, twitter: { clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY', clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET', callbackURL: '/auth/twitter/callback' }, google: { clientID: process.env.GOOGLE_ID || 'APP_ID', clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET', callbackURL: '/auth/google/callback' }, linkedin: { clientID: process.env.LINKEDIN_ID || 'APP_ID', clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET', callbackURL: '/auth/linkedin/callback' }, github: { clientID: process.env.GITHUB_ID || 'APP_ID', clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET', callbackURL: '/auth/github/callback' }, mailer: { from: process.env.MAILER_FROM || 'MAILER_FROM', options: { service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER', auth: { user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID', pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD' } } } };
version https://git-lfs.github.com/spec/v1 oid sha256:27f38ba2dada0d9f7367caca39e865462a9c84337c41916d19e3bbb9e4307f0f size 2595
var script = new Script(); function Product () { this.showProductResult = function (){ var that = this; $("#excelDataTable").find("tbody").remove(); var data = { ProductCount: $('#ProductCount').val(), ProductCountry: $('#ProductCountry').val() }; $.ajax({ method: "POST", url: "/product/result", data: data, complete: function(data){ if(data.status !== 500){ data = data.responseJSON; data = JSON.parse(data); console.log(data); script.buildHtmlTable(data); } }, error: function (data){ alert("ERROR " + data); } }); } this.showAllProductCount = function (){ var that = this; $.ajax({ method: "GET", url: "/product/count", complete: function(data){ if(data.status !== 500){ data = data.responseJSON; data = JSON.parse(data); var template = "{{#.}}" + "<option>{{кількість одиниць виробу}}</option>" + "{{/.}}"; var rendered = Mustache.render(template, data); $('#ProductCount').append(rendered); } } }); } this.showAllProductCountry = function (){ var that = this; $.ajax({ method: "GET", url: "/product/country", complete: function(data){ if(data.status !== 500){ data = data.responseJSON; data = JSON.parse(data); var template = "{{#.}}" + "<option>{{країна виробника}}</option>" + "{{/.}}"; var rendered = Mustache.render(template, data); $('#ProductCountry').append(rendered); } } }); } }
var fs = require('fs'); var protobuf = require('protobufjs'); var protoStr = fs.readFileSync(__dirname + '/remotecontrolmessages.proto', 'utf8'); var builder = protobuf.loadProto(protoStr); var ns = 'pb.remote'; function build(type) { return builder.build(ns+'.'+type); } var proto = { MsgType: build('MsgType'), EngineState: build('EngineState'), RepeatMode: build('RepeatMode'), ShuffleMode: build('ShuffleMode'), ReasonDisconnect: build('ReasonDisconnect'), DownloadItem: build('DownloadItem'), Message: build('Message') }; var Message = proto.Message; function getConstName(value, obj) { for (var name in obj) { if (obj[name] === value) { return name; } } return ''; } proto.getMsgTypeName = function (typeIndex) { return getConstName(typeIndex, proto.MsgType); }; proto.getEngineStateName = function (stateIndex) { return getConstName(stateIndex, proto.EngineState); }; proto.getRepeatModeName = function (repeatModeIndex) { return getConstName(repeatModeIndex, proto.RepeatMode); }; proto.getShuffleModeName = function (shuffleModeIndex) { return getConstName(shuffleModeIndex, proto.ShuffleMode); }; proto.getReasonDisconnectName = function (reasonIndex) { return getConstName(reasonIndex, proto.ReasonDisconnect); }; proto.getDownloadItemName = function (downloadItemIndex) { return getConstName(downloadItemIndex, proto.DownloadItem); }; module.exports = proto;
// vi: sts=2 sw=2 et const Lang = imports.lang; const Signals = imports.signals; const St = imports.gi.St; const Gio = imports.gi.Gio; const Gtk = imports.gi.Gtk; const GdkPixbuf = imports.gi.GdkPixbuf; const Main = imports.ui.main; const MessageTray = imports.ui.messageTray; const Util = imports.misc.util; const Gettext = imports.gettext.domain('gnome-shell-screenshot'); const _ = Gettext.gettext; const ExtensionUtils = imports.misc.extensionUtils; const Local = ExtensionUtils.getCurrentExtension(); const Path = Local.imports.path; const {dump} = Local.imports.dump; const Clipboard = Local.imports.clipboard; const Thumbnail = Local.imports.thumbnail; const NotificationIcon = 'camera-photo-symbolic'; const NotificationSourceName = 'Screenshot Tool'; const ICON_SIZE = 64; const getSource = () => { let source = new MessageTray.Source( NotificationSourceName, NotificationIcon ); Main.messageTray.add(source); return source; } const Notification = new Lang.Class({ Name: "ScreenshotTool.Notification", Extends: MessageTray.Notification, _init: function (source, image, file, newFilename) { let {width, height} = image.get_pixbuf(); this.parent( source, _("New Screenshot"), _("Size:") + " " + width + "x" + height, { gicon: Thumbnail.getIcon(file.get_path()) } ); this.connect("activated", this.onActivated.bind(this)); // makes banner expand on hover this.setForFeedback(true); this._file = file; this._image = image; this._newFilename = newFilename; }, createBanner: function() { let b = this.parent(); b.addAction(_("Copy"), this.onCopy.bind(this)); b.addAction(_("Save"), this.onSave.bind(this)); b._iconBin.child.icon_size = ICON_SIZE; return b; }, onActivated: function () { let context = global.create_app_launch_context(0, -1); Gio.AppInfo.launch_default_for_uri(this._file.get_uri(), context); }, onCopy: function () { Clipboard.setImage(this._image); }, onSave: function () { Util.spawn([ "gjs", Local.path + "/saveDlg.js", this._file.get_path(), Path.expand("$PICTURES"), this._newFilename, Local.dir.get_path(), ]); } }); Signals.addSignalMethods(Notification.prototype); const ErrorNotification = new Lang.Class({ Name: "ScreenshotTool.ErrorNotification", Extends: MessageTray.Notification, _init: function (source, message) { this.parent( source, _("Error"), message, { secondaryGIcon: new Gio.ThemedIcon({name: 'dialog-error'}) } ); } }); Signals.addSignalMethods(ErrorNotification.prototype); const notifyScreenshot = (image, file, newFilename) => { let source = getSource(); let notification = new Notification(source, image, file, newFilename); source.notify(notification); } const notifyError = (message) => { let source = getSource(); let notification = new ErrorNotification(source, message); source.notify(notification); }
const test = require('tape') const nlp = require('./_lib') test('topics:', function(t) { let list = [ ['Tony Hawk lives in Toronto. Tony Hawk is cool.', 'tony hawk'], ['I live Toronto. I think Toronto is cool.', 'toronto'], ['The EACD united in 1972. EACD must follow regulations.', 'eacd'], // ['The Elkjsdflkjsdf sells hamburgers. I think the Elkjsdflkjsdf eats turky.', 'elkjsdflkjsdf'], ["Toronto's citizens love toronto!", 'toronto'], ] list.forEach(function(a) { const arr = nlp(a[0]) .topics() .out('freq') t.equal(arr[0].reduced, a[1], a[0]) }) t.end() }) test('topics-false-positives:', function(t) { const arr = [ 'somone ate her lunch', 'everybody is dancing all night', "a man and a woman ate her son's breakfast", 'my brother walks to school', `She's coming by`, `if she doesn't like something about us she can keep us off`, ` She's it! She could be a soap opera.`, `she's a little dare-devil!`, ] arr.forEach(function(str, i) { const doc = nlp(str).topics() t.equal(doc.length, 0, 'topics #' + i + ' -> ' + doc.out()) }) t.end() }) test('topics-basic', function(t) { let doc = nlp('i went to Gloop University in Paris, France, with John H. Smith') let arr = doc.topics().out('array') t.deepEqual(arr, ['Gloop University', 'Paris, France,', 'John H. Smith'], 'found all three topics') t.end() }) test('misc entities', function(t) { let doc = nlp('The Children are right to laugh at you, Ralph') let m = doc.people() t.equal(m.length, 1, 'one person') m = doc.places() t.equal(m.length, 0, 'no places') m = doc.organizations() t.equal(m.length, 0, 'no organizations') m = doc.entities() t.equal(m.length, 1, 'one entity') t.end() }) test('topics concat:', function(t) { const things = nlp('spencer and danny are in Paris France and germany for Google Inc and IBM') .topics() .json({ normal: true, trim: true }) .map(o => o.normal) const want = ['spencer', 'danny', 'paris france', 'germany', 'google inc', 'ibm'] t.equal(things.join(', '), want.join(', '), 'found right things') t.end() })
gulp.task('default',['assets']);
// -------------------------------------------------------------------------- \\ // File: SearchTextView.js \\ // Module: ControlViews \\ // Requires: TextView.js \\ // Author: Neil Jenkins \\ // License: © 2010-2015 FastMail Pty Ltd. MIT Licensed. \\ // -------------------------------------------------------------------------- \\ "use strict"; ( function (NS) { var SearchTextView = NS.Class({ Extends: NS.TextView, type: 'v-SearchText', placeholder: 'Search', target: null, method: null, draw: function (layer, Element, el) { var children = SearchTextView.parent.draw.call(this, layer, Element, el); children.push( el('i.icon.v-icon-search'), new NS.ButtonView({ type: NS.bind(this, 'value', function (value) { return value ? 'v-SearchText-reset v-Button--iconOnly' : 'u-hidden'; }), icon: 'v-icon-clear', positioning: 'absolute', label: NS.loc('Clear Search'), target: this, method: 'reset' }) ); return children; }, reset: function () { this.set('value', '') .blur(); this.fire('search:reset'); }, activate: function () { if (!this.get('isDisabled')) { var target = this.get('target') || this, action; if (action = this.get('action')) { target.fire(action, {originView: this}); } else if (action = this.get('method')) { target[action](this); } this.fire('search:activate'); } }.observes('value') }); NS.SearchTextView = SearchTextView; }(O) );
System.register(['angular2/core', 'angular2/router', './hero.service'], function(exports_1) { var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var core_1, router_1, hero_service_1; var HeroDetailComponent; return { setters:[ function (core_1_1) { core_1 = core_1_1; }, function (router_1_1) { router_1 = router_1_1; }, function (hero_service_1_1) { hero_service_1 = hero_service_1_1; }], execute: function() { HeroDetailComponent = (function () { function HeroDetailComponent(_heroService, _routeParams) { this._heroService = _heroService; this._routeParams = _routeParams; } HeroDetailComponent.prototype.ngOnInit = function () { var _this = this; var id = +this._routeParams.get('id'); this._heroService .getHero(id) .then(function (h) { return _this.hero = h; }); }; HeroDetailComponent.prototype.goBack = function () { window.history.back(); }; HeroDetailComponent = __decorate([ core_1.Component({ selector: 'my-hero-detail', templateUrl: "app/hero-detail.component.html", inputs: ['hero'], styleUrls: ['app/hero-detail.component.css'] }), __metadata('design:paramtypes', [hero_service_1.HeroService, router_1.RouteParams]) ], HeroDetailComponent); return HeroDetailComponent; })(); exports_1("HeroDetailComponent", HeroDetailComponent); } } }); //# sourceMappingURL=hero-detail.component.js.map
'use strict'; /*eslint no-unused-vars: 0 no-undefined:0 */ var tester = require('./_lib/tester'); exports.examples = tester([ { rules: { contains: null }, value: null, error: true }, { rules: { contains: [ 123, 234, 345 ] }, value: 333, verr: { rule: 'contains', params: [ 123, 234, 345 ] } }, { rules: { contains: [ 123, 234, 345 ] }, value: 123, expect: true }, { rules: { contains: [ 123, 234, 345 ] }, value: '123', verr: { rule: 'contains', params: [ 123, 234, 345 ] } } ]);
 jQuery(window).load(function() { "use strict"; // Page Preloader jQuery('#preloader').delay(350).fadeOut(function(){ jQuery('body').delay(350).css({'overflow':'visible'}); }); }); jQuery(document).ready(function() { "use strict"; // Toggle Left Menu jQuery('.leftpanel .nav-parent > a').on('click', function() { var parent = jQuery(this).parent(); var sub = parent.find('> ul'); // Dropdown works only when leftpanel is not collapsed if(!jQuery('body').hasClass('leftpanel-collapsed')) { if(sub.is(':visible')) { sub.slideUp(200, function(){ parent.removeClass('nav-active'); jQuery('.mainpanel').css({height: ''}); adjustmainpanelheight(); }); } else { closeVisibleSubMenu(); parent.addClass('nav-active'); sub.slideDown(200, function(){ adjustmainpanelheight(); }); } } return false; }); function closeVisibleSubMenu() { jQuery('.leftpanel .nav-parent').each(function() { var t = jQuery(this); if(t.hasClass('nav-active')) { t.find('> ul').slideUp(200, function(){ t.removeClass('nav-active'); }); } }); } function adjustmainpanelheight() { // Adjust mainpanel height var docHeight = jQuery(document).height(); if(docHeight > jQuery('.mainpanel').height()) jQuery('.mainpanel').height(docHeight); } adjustmainpanelheight(); // Tooltip jQuery('.tooltips').tooltip({ container: 'body'}); // Popover jQuery('.popovers').popover(); // Close Button in Panels jQuery('.panel .panel-close').click(function(){ jQuery(this).closest('.panel').fadeOut(200); return false; }); // Form Toggles jQuery('.toggle').toggle({on: true}); jQuery('.toggle-chat1').toggle({on: false}); var scColor1 = '#428BCA'; if (jQuery.cookie('change-skin') && jQuery.cookie('change-skin') == 'bluenav') { scColor1 = '#fff'; } // Sparkline jQuery('#sidebar-chart').sparkline([4,3,3,1,4,3,2,2,3,10,9,6], { type: 'bar', height:'30px', barColor: scColor1 }); jQuery('#sidebar-chart2').sparkline([1,3,4,5,4,10,8,5,7,6,9,3], { type: 'bar', height:'30px', barColor: '#D9534F' }); jQuery('#sidebar-chart3').sparkline([5,9,3,8,4,10,8,5,7,6,9,3], { type: 'bar', height:'30px', barColor: '#1CAF9A' }); jQuery('#sidebar-chart4').sparkline([4,3,3,1,4,3,2,2,3,10,9,6], { type: 'bar', height:'30px', barColor: scColor1 }); jQuery('#sidebar-chart5').sparkline([1,3,4,5,4,10,8,5,7,6,9,3], { type: 'bar', height:'30px', barColor: '#F0AD4E' }); // Minimize Button in Panels jQuery('.minimize').click(function(){ var t = jQuery(this); var p = t.closest('.panel'); if(!jQuery(this).hasClass('maximize')) { p.find('.panel-body, .panel-footer').slideUp(200); t.addClass('maximize'); t.html('&plus;'); } else { p.find('.panel-body, .panel-footer').slideDown(200); t.removeClass('maximize'); t.html('&minus;'); } return false; }); // Add class everytime a mouse pointer hover over it jQuery('.nav-bracket > li').hover(function(){ jQuery(this).addClass('nav-hover'); }, function(){ jQuery(this).removeClass('nav-hover'); }); // Menu Toggle jQuery('.menutoggle').click(function(){ var body = jQuery('body'); var bodypos = body.css('position'); if(bodypos != 'relative') { if(!body.hasClass('leftpanel-collapsed')) { body.addClass('leftpanel-collapsed'); jQuery('.nav-bracket ul').attr('style',''); jQuery(this).addClass('menu-collapsed'); } else { body.removeClass('leftpanel-collapsed chat-view'); jQuery('.nav-bracket li.active ul').css({display: 'block'}); jQuery(this).removeClass('menu-collapsed'); } } else { if(body.hasClass('leftpanel-show')) body.removeClass('leftpanel-show'); else body.addClass('leftpanel-show'); adjustmainpanelheight(); } }); // Chat View jQuery('#chatview').click(function(){ var body = jQuery('body'); var bodypos = body.css('position'); if(bodypos != 'relative') { if(!body.hasClass('chat-view')) { body.addClass('leftpanel-collapsed chat-view'); jQuery('.nav-bracket ul').attr('style',''); } else { body.removeClass('chat-view'); if(!jQuery('.menutoggle').hasClass('menu-collapsed')) { jQuery('body').removeClass('leftpanel-collapsed'); jQuery('.nav-bracket li.active ul').css({display: 'block'}); } else { } } } else { if(!body.hasClass('chat-relative-view')) { body.addClass('chat-relative-view'); body.css({left: ''}); } else { body.removeClass('chat-relative-view'); } } }); reposition_topnav(); reposition_searchform(); jQuery(window).resize(function(){ if(jQuery('body').css('position') == 'relative') { jQuery('body').removeClass('leftpanel-collapsed chat-view'); } else { jQuery('body').removeClass('chat-relative-view'); jQuery('body').css({left: '', marginRight: ''}); } reposition_searchform(); reposition_topnav(); }); /* This function will reposition search form to the left panel when viewed * in screens smaller than 767px and will return to top when viewed higher * than 767px */ function reposition_searchform() { if(jQuery('.searchform').css('position') == 'relative') { jQuery('.searchform').insertBefore('.leftpanelinner .userlogged'); } else { jQuery('.searchform').insertBefore('.header-right'); } } /* This function allows top navigation menu to move to left navigation menu * when viewed in screens lower than 1024px and will move it back when viewed * higher than 1024px */ function reposition_topnav() { if(jQuery('.nav-horizontal').length > 0) { // top navigation move to left nav // .nav-horizontal will set position to relative when viewed in screen below 1024 if(jQuery('.nav-horizontal').css('position') == 'relative') { if(jQuery('.leftpanel .nav-bracket').length == 2) { jQuery('.nav-horizontal').insertAfter('.nav-bracket:eq(1)'); } else { // only add to bottom if .nav-horizontal is not yet in the left panel if(jQuery('.leftpanel .nav-horizontal').length == 0) jQuery('.nav-horizontal').appendTo('.leftpanelinner'); } jQuery('.nav-horizontal').css({display: 'block'}) .addClass('nav-pills nav-stacked nav-bracket'); jQuery('.nav-horizontal .children').removeClass('dropdown-menu'); jQuery('.nav-horizontal > li').each(function() { jQuery(this).removeClass('open'); jQuery(this).find('a').removeAttr('class'); jQuery(this).find('a').removeAttr('data-toggle'); }); if(jQuery('.nav-horizontal li:last-child').has('form')) { jQuery('.nav-horizontal li:last-child form').addClass('searchform').appendTo('.topnav'); jQuery('.nav-horizontal li:last-child').hide(); } } else { // move nav only when .nav-horizontal is currently from leftpanel // that is viewed from screen size above 1024 if(jQuery('.leftpanel .nav-horizontal').length > 0) { jQuery('.nav-horizontal').removeClass('nav-pills nav-stacked nav-bracket') .appendTo('.topnav'); jQuery('.nav-horizontal .children').addClass('dropdown-menu').removeAttr('style'); jQuery('.nav-horizontal li:last-child').show(); jQuery('.searchform').removeClass('searchform').appendTo('.nav-horizontal li:last-child .dropdown-menu'); jQuery('.nav-horizontal > li > a').each(function() { jQuery(this).parent().removeClass('nav-active'); if(jQuery(this).parent().find('.dropdown-menu').length > 0) { jQuery(this).attr('class','dropdown-toggle'); jQuery(this).attr('data-toggle','dropdown'); } }); } } } } // Sticky Header if(jQuery.cookie('sticky-header')) jQuery('body').addClass('stickyheader'); // Sticky Left Panel if(jQuery.cookie('sticky-leftpanel')) { jQuery('body').addClass('stickyheader'); jQuery('.leftpanel').addClass('sticky-leftpanel'); } // Left Panel Collapsed if(jQuery.cookie('leftpanel-collapsed')) { jQuery('body').addClass('leftpanel-collapsed'); jQuery('.menutoggle').addClass('menu-collapsed'); } // Changing Skin var c = jQuery.cookie('change-skin'); var cssSkin = 'css/style.'+c+'.css'; if (jQuery('body').css('direction') == 'rtl') { cssSkin = '../css/style.'+c+'.css'; jQuery('html').addClass('rtl'); } if(c) { jQuery('head').append('<link id="skinswitch" rel="stylesheet" href="'+cssSkin+'" />'); } // Changing Font var fnt = jQuery.cookie('change-font'); if(fnt) { jQuery('head').append('<link id="fontswitch" rel="stylesheet" href="css/font.'+fnt+'.css" />'); } // Check if leftpanel is collapsed if(jQuery('body').hasClass('leftpanel-collapsed')) jQuery('.nav-bracket .children').css({display: ''}); // Handles form inside of dropdown jQuery('.dropdown-menu').find('form').click(function (e) { e.stopPropagation(); }); // This is not actually changing color of btn-primary // This is like you are changing it to use btn-orange instead of btn-primary // This is for demo purposes only var c = jQuery.cookie('change-skin'); if (c && c == 'greyjoy') { $('.btn-primary').removeClass('btn-primary').addClass('btn-orange'); $('.rdio-primary').addClass('rdio-default').removeClass('rdio-primary'); $('.text-primary').removeClass('text-primary').addClass('text-orange'); } }); //// Analytics Code //(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ //(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), //m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) //})(window,document,'script','//www.google-analytics.com/analytics.js','ga'); //ga('create', 'UA-40361841-2', 'auto'); //ga('send', 'pageview');
(function(chai, expect, sinon) { describe(__filename, function() { var resolve1Spy, resolveSpy; before(function() { require("../setup.config.js"); }); before(function(done) { var ajaxStub = sinon.stub($, "ajax"); ajaxStub.returns(Promise.resolve()); // routeMatchedSpy = sinon.spy(); // routeNotMatchedSpy = sinon.spy(); // routeBeforeChangeSpy = sinon.spy(); // viewDestroyedSpy = sinon.spy(); // viewChangeSpy = sinon.spy(); // routeChangedSpy = sinon.spy(); resolveSpy = sinon.spy(); resolve1Spy = sinon.spy(); resolve2Spy = sinon.spy(); var routes = {}; routes["home"] = { url: "#/", templateUrl: "templates/index.html" }; routes["resolveFunc"] = { url: "#/resolving-func", resolve: function() { resolveSpy(); }, templateUrl: "templates/index.html" }; routes["resolveArrayOfFunc"] = { url: "#/resolving-array-funcs", resolve: [ function() { return resolveSpy(); }, function() { return resolve1Spy(); } ], templateUrl: "templates/index.html" }; routes["resolveArrayOfFuncAndValues"] = { url: "#/resolving-array-funcs-values", resolve: [ function() { return resolveSpy(); }, function() { return resolve1Spy(); }, "Some values" ], templateUrl: "templates/index.html" }; $.router .setData(routes) .setDefault("home") .run(".my-view", "home"); // $.router.onRouteMatched(routeMatchedSpy); // $.router.onRouteNotMatched(routeNotMatchedSpy); // $.router.onRouteBeforeChange(routeBeforeChangeSpy); // $.router.onViewDestroyed(viewDestroyedSpy); // $.router.onViewChange(viewChangeSpy); // $.router.onRouteChanged(routeChangedSpy); setTimeout(function() { done(); }, 20); }); after(function() { $.ajax.restore(); }); afterEach(function() { // routeMatchedSpy.resetHistory(); // routeNotMatchedSpy.resetHistory(); // routeBeforeChangeSpy.resetHistory(); // viewDestroyedSpy.resetHistory(); // viewChangeSpy.resetHistory(); // routeChangedSpy.resetHistory(); resolveSpy.resetHistory(); resolve1Spy.resetHistory(); resolve2Spy.resetHistory(); JSDOM.reconfigure({ url: URL }); }); it("should be function resolved", function(done) { var routeName = "resolveFunc"; $.router.go(routeName); setTimeout(function() { sinon.assert.calledOnce(resolveSpy); done(); }, 10); }); it("should be resolved function with in array", function(done) { var routeName = "resolveArrayOfFunc"; $.router.go(routeName); setTimeout(function() { sinon.assert.calledOnce(resolveSpy); sinon.assert.calledOnce(resolve1Spy); done(); }, 10); }); it("should be resolved function and non function with in array", function(done) { var routeName = "resolveArrayOfFuncAndValues"; $.router.go(routeName); setTimeout(function() { sinon.assert.calledOnce(resolveSpy); sinon.assert.calledOnce(resolve1Spy); done(); }, 10); }); }); })(require("chai"), require("chai").expect, require("sinon"));
function addPercentMetric(metricName, metricDescription, metricPercent) { function genPercentMarkup(metricName, metricDescription) { var metricMarkupTemplate = ['<tr class="metrics element container" data-metric="', '"><td class="metrics element info"> <div class="metrics element title">', '</div> <div class="metrics element description">', '</div></td><td class="metrics element progress"><div class="metrics element base"><div class="metrics element fill ', ' "></div></div></td><td class="metrics element number ', '"><div class="metrics element percent ', '"></div></td></tr>' ]; var metString = metricMarkupTemplate[0] + metricName + metricMarkupTemplate[1] + metricName + metricMarkupTemplate[2] + metricDescription + metricMarkupTemplate[3] + metricName + metricMarkupTemplate[4] + metricName + metricMarkupTemplate[5] + metricName + metricMarkupTemplate[6]; return metString; }; function setPercent(metricName, metricPercent) { $(".metrics.element.percent." + metricName).text(metricPercent.toString() + "%"); metricPercent = (metricPercent > 100) ? 100 : metricPercent; $(".metrics.element.fill." + metricName).animate({ "width": metricPercent.toString() + "%" }, 250); } var generatedMetric = genPercentMarkup(metricName, metricDescription); $(".metrics.table").append(generatedMetric); setPercent(metricName, metricPercent); } function addGraphMetric(metricName, metricDescription, metricArray) { function genGraphMarkup(metricName, metricDescription) { var metricMarkupTemplate = ['<tr class="metrics element container" data-metric="', '"><td class="metrics element info"><div class="metrics element title">', '</div> <div class="metrics element description">', '</div></td><td class="metrics element graph"><canvas class="metrics element ctx ', '"></canvas></td></tr>']; var metString = metricMarkupTemplate[0] + metricName + metricMarkupTemplate[1] + metricName + metricMarkupTemplate[2] + metricDescription + metricMarkupTemplate[3] + metricName + metricMarkupTemplate[4]; return metString; } function setGraph(metricName, metricArray) { var chartData = { labels : [], datasets : []}; metricArrayNum = []; for (var i = 0; i < metricArray.length; i++) { metricArrayNum = parseFloat(metricArray[i]); chartData['labels'].push(""); } graphData = { fillColor: 'rgba(31, 162, 222, 0.2)', label: "My First dataset", pointColor: 'rgba(31, 162, 222, 0.2)', pointHighlightFill: "#fff", pointHighlightStroke: 'rgba(31, 162, 222, 0.2)', pointStrokeColor: "#fff", strokeColor: "rgba(220,220,220,1)", data : metricArray } chartData['datasets'].push(graphData); respChart($(".ctx." + metricName), chartData); } var generatedMetric = genGraphMarkup(metricName, metricDescription); $(".metrics.table").append(generatedMetric); setGraph(metricName, metricArray); } function addPhotoMetric(metricName, metricDescription, metricPhotos) { function genPhotoMarkup(metricName, metricDescription) { var metricMarkupTemplate = ['<tr class="metrics element container" data-metric="', '"><td class="metrics element info"><div class="metrics element title">', '</div> <div class="metrics element description">', '</div></td><td class="metrics element photos"><div class="metrics element pics ', '"></div></td></tr>' ]; var metString = metricMarkupTemplate[0] + metricName + metricMarkupTemplate[1] + metricName + metricMarkupTemplate[2] + metricDescription + metricMarkupTemplate[3] + metricName + metricMarkupTemplate[4]; return metString; } function setImages(metricName, metricPhotos) { var imageMarkupTemplate = ['<a class="element fancybox" rel="group" href="data:image/png;base64,', '"><img class = "metrics element image" src="data:image/png;base64,', '" alt="image" /></a>' ]; var temporaryImageString = ""; for (var i = 0; i < metricPhotos.length; i++) { temporaryImageString = imageMarkupTemplate[0] + metricPhotos[i] + imageMarkupTemplate[1] + metricPhotos[i] + imageMarkupTemplate[2]; $(".metrics.element.pics." + metricName).append(temporaryImageString); } $(".metrics.element.pics." + metricName).animate({ "opacity": "1" }, 250); $(".fancybox").fancybox(); } var generatedMetric = genPhotoMarkup(metricName, metricDescription); $(".metrics.table").append(generatedMetric); setImages(metricName, metricPhotos); } function addRawMetric(metricName, metricDescription, metricData) { function genRawMarkup(metricName, metricDescription, metricData) { var metricMarkupTemplate = ['<tr class="metrics element container" data-metric="', '"><td class="metrics element info"> <div class="metrics element title">', '</div> <div class="metrics element description">', '</div></td><td class="metrics element text"><div class="metrics element raw ', '">', '</div></td></tr>' ]; var metString = metricMarkupTemplate[0] + metricName + metricMarkupTemplate[1] + metricName + metricMarkupTemplate[2] + metricDescription + metricMarkupTemplate[3] + metricName + metricMarkupTemplate[4] + metricData + metricMarkupTemplate[5]; return metString; } var generatedMetric = genRawMarkup(metricName, metricDescription, metricData); $(".metrics.table").append(generatedMetric); }
"use strict"; module.exports = exports = rebuild; exports.usage = 'Runs "clean" and "build" at once'; function rebuild(gyp, argv, callback) { gyp.todo.unshift({ name: 'clean', args: [] }, { name: 'build', args: ['rebuild'] }); process.nextTick(callback); } //# sourceMappingURL=rebuild-compiled.js.map
/** * @author weism * copyright 2015 Qcplay All Rights Reserved. */ /** * 颜色渐变动画 * @class qc.TweenAlpha */ var TweenColor = defineBehaviour('qc.TweenColor', qc.Tween, function() { var self = this; /** * @property {qc.Color} from - 起始的颜色值 */ self.from = Color.black; /** * @property {qc.Color} to - 最终的颜色值 */ self.to = Color.white; // 默认情况下不可用 self.enable = false; },{ from : qc.Serializer.COLOR, to : qc.Serializer.COLOR }); // 菜单上的显示 TweenColor.__menu = 'Tween/TweenColor'; /** * 处理对应的变化逻辑 * @param factor {number} - 形变的因子 * @param isFinished {boolean} - 是否已经结束 */ TweenColor.prototype.onUpdate = function(factor, isFinished) { var self = this; var _from = self.from.rgb, _to = self.to.rgb; var currColor = [ Phaser.Math.clamp(Math.round(_from[0] + factor * (_to[0] - _from[0])), 0, 255), Phaser.Math.clamp(Math.round(_from[1] + factor * (_to[1] - _from[1])), 0, 255), Phaser.Math.clamp(Math.round(_from[2] + factor * (_to[2] - _from[2])), 0, 255), Phaser.Math.clamp(self.from.alpha + factor * (self.to.alpha - self.from.alpha), 0, 1) ]; var color = new Color(currColor); self.gameObject.colorTint = color; }; /** * 将开始状态设成当前状态 */ TweenColor.prototype.setStartToCurrValue = function() { this.gameObject.colorTint = new Color(this.from.toString()); }; /** * 将结束状态设成当前状态 */ TweenColor.prototype.setEndToCurrValue = function() { this.gameObject.colorTint = new Color(this.to.toString()); }; /** * 将当前状态设为开始状态 */ TweenColor.prototype.setCurrToStartValue = function() { this.from = new Color(this.gameObject.colorTint.toString()); }; /** * 将当前状态设置为结束状态 */ TweenColor.prototype.setCurrToEndValue = function() { this.to = new Color(this.gameObject.colorTint.toString()); }; /** * 开始变色 * @param node {qc.Node} - 需要变色的节点 * @param duration {number} - 变色的时间 * @param color {qc.Color} - 最终颜色 * @returns {qc.TweenColor} */ TweenColor.begin = function(node, duration, color) { var tween = qc.Tween.begin('qc.TweenColor', node, duration); tween.from = new Color(node.colorTint.toString()); tween.to = color; if (duration <= 0) { tween.sample(1, true); tween.enable = false; } return tween; };
import React, { Component } from 'react'; import { Link } from 'react-router'; import Pagination from "../../components/Pagination"; import DeviceProfileStore from "../../stores/DeviceProfileStore"; import SessionStore from "../../stores/SessionStore"; class DeviceProfileRow extends Component { render() { return( <tr> <td><Link to={`organizations/${this.props.organizationID}/device-profiles/${this.props.deviceProfile.deviceProfileID}`}>{this.props.deviceProfile.name}</Link></td> </tr> ); } } class ListDeviceProfiles extends Component { constructor() { super(); this.state = { pageSize: 20, deviceProfiles: [], isAdmin: false, pageNumber: 1, pages: 1, }; this.updatePage = this.updatePage.bind(this); } componentDidMount() { this.updatePage(this.props); SessionStore.on("change", () => { this.setState({ isAdmin: SessionStore.isAdmin() || SessionStore.isOrganizationAdmin(this.props.params.organizationID), }); }); } updatePage(props) { this.setState({ isAdmin: SessionStore.isAdmin() || SessionStore.isOrganizationAdmin(this.props.params.organizationID), }); const page = (props.location.query.page === undefined) ? 1 : props.location.query.page; DeviceProfileStore.getAllForOrganizationID(props.params.organizationID, this.state.pageSize, (page-1) * this.state.pageSize, (totalCount, deviceProfiles) => { this.setState({ deviceProfiles: deviceProfiles, pageNumber: page, pages: Math.ceil(totalCount / this.state.pageSize), }); window.scrollTo(0, 0); }); } render() { const DeviceProfileRows = this.state.deviceProfiles.map((deviceProfile, i) => <DeviceProfileRow key={deviceProfile.deviceProfileID} deviceProfile={deviceProfile} organizationID={this.props.params.organizationID} />); return( <div className="panel panel-default"> <div className={`panel-heading clearfix ${this.state.isAdmin ? '' : 'hidden'}`}> <div className="btn-group pull-right"> <Link to={`organizations/${this.props.params.organizationID}/device-profiles/create`}><button type="button" className="btn btn-default btn-sm">Create device-profile</button></Link> </div> </div> <div className="panel-body"> <table className="table table-hover"> <thead> <tr> <th>Name</th> </tr> </thead> <tbody> {DeviceProfileRows} </tbody> </table> </div> <Pagination pages={this.state.pages} currentPage={this.state.pageNumber} pathname={`organizations/${this.props.params.organizationID}/device-profiles`} /> </div> ); } } export default ListDeviceProfiles;
var rangeUtil = { focusNode: function(node) { var range = document.createRange(); range.selectNode(node.childNodes[0]); range.collapse(); var selection = document.getSelection(); selection.removeAllRanges(); selection.addRange(range); }, selectNode: function(node) { var range = document.createRange(); range.selectNode(node.childNodes[0]); var selection = document.getSelection(); selection.removeAllRanges(); selection.addRange(range); }, getRange: function() { var selection = window.getSelection(); var sRange = selection.getRangeAt(0); return sRange; }, getRangeNode: function() { var sRange = rangeUtil.getRange(); var blogContainer = sRange.commonAncestorContainer; if (blogContainer.nodeType == 3) { //文本节点 blogContainer = blogContainer.parentNode; } return blogContainer; } }; module.exports = rangeUtil;
angular.module('davico.simone.webpage.nav', []) .service('navigationItems', function(){ var navigationItems = []; this.register = function(item){ navigationItems.push('/'+item); } this.items = function(){ return navigationItems; } this.indexOf = function(item) { return navigationItems.indexOf(item); } }) /* * Toggles an 'active' class if element has id matching with $location.end */ .directive('navItem', function(navigationItems){ return { restrict: 'A', link: function(scope, elem, attrs) { navigationItems.register(attrs.id); scope.$on('$locationChangeStart', function(event,next,current){ elem.removeClass('active'); if(next.endsWith(attrs.id)) { elem.toggleClass('active'); } }) } } })
"use strict"; /* eslint-disable node/no-unpublished-require */ const fs = require("fs"); const gulp = require("gulp"); const gutil = require("gulp-util"); const del = require("del"); const NwBuilder = require("nw-builder"); const archiver = require("archiver"); const runSequence = require("run-sequence"); /* eslint-enable node/no-unpublished-require */ const platforms = { win: ["win32", "win64"], osx: ["osx32", "osx64"], linux: ["linux32", "linux64"] }; const platformsArray = (() => { return Object.keys(platforms).reduce((prev, current) => { return prev.concat(current); }, []); })(); let currentTarget; switch (process.platform) { case "win32": currentTarget = "win"; break; case "darwin": currentTarget = "osx"; break; case "linux": currentTarget = "linux"; break; default: currentTarget = ""; break; } if (currentTarget) { switch (process.arch) { case "x64": currentTarget += "64"; break; case "ia32": currentTarget += "32"; break; default: currentTarget = ""; break; } } function readFile(file, encoding) { return new Promise((resolve, reject) => { encoding = encoding || "utf8"; fs.readFile(file, encoding, (err, data) => { if (err) { reject(err); return; } resolve(data); }); }); } function writeFile(file, data, encoding) { return new Promise((resolve, reject) => { encoding = encoding || "utf8"; fs.writeFile(file, data, encoding, err => { if (err) { reject(err); return; } resolve(); }); }); } function readJSON(file, encoding) { return readFile(file, encoding).then(data => JSON.parse(data)); } function writeJSON(file, data, encoding) { return writeFile(file, JSON.stringify(data, null, " ") + "\n", encoding); } function cleanList(target) { const list = []; const parent = "build/jikkyo"; if (target === "all") { list.push(parent); } else { list.push(`${parent}/${target}`); list.push(`${parent}/*-${target}.zip`); } return list; } function nw(targets) { const nwb = new NwBuilder({ files: "src/**/*", version: "0.12.3", platforms: targets, buildDir: "build", cacheDir: "cache", macCredits: "Credits.html", macIcns: "src/images/jikkyo.icns", winIco: "src/images/jikkyo.ico", zip: false, flavor: "normal" }); nwb.on("log", msg => { if (!/^Zipping/.test(msg)) gutil.log("nw-builder", msg); }); return nwb.build(); } function copyList(target) { const files = ["README.md", "LICENSE"]; if (target.includes("win")) { files.push("attachment/jikkyo_ct.cmd"); } else if (target.includes("osx")) { files.push("attachment/jikkyo_ct.command"); } else if (target.includes("linux")) { files.push("attachment/jikkyo_ct.sh"); } return files; } function pack(targets) { return readJSON("package.json").then(json => { const version = json.version; return Promise.all(targets.map(target => { return new Promise((resolve, reject) => { const dir = `build/jikkyo/${target}`; const name = `jikkyo-v${version}-${target}`; const out = `build/jikkyo/${name}.zip`; const archive = archiver("zip"); const output = fs.createWriteStream(out); output.on("close", resolve); archive.on("error", reject); archive.pipe(output); archive.directory(dir, name) .finalize(); }); })); }); } function release(target) { return new Promise((resolve, reject) => { runSequence(`clean:${target}`, `nw:${target}`, `copy:${target}`, `package:${target}`, err => { if (err) { reject(err); return; } resolve(); }); }); } gulp.task("sync", () => { return Promise.all([ readJSON("package.json"), readJSON("src/package.json") ]).then(jsons => { const pkg = jsons[0]; const srcPkg = jsons[1]; srcPkg.name = pkg.name; srcPkg.version = pkg.version; srcPkg.description = pkg.description; srcPkg.repository = pkg.repository; srcPkg.homepage = pkg.homepage; return writeJSON("src/package.json", srcPkg); }); }); gulp.task("clean:all", () => del(cleanList("all"))); gulp.task("nw:all", () => nw(platformsArray)); gulp.task("copy:all", Object.keys(platforms).map(platform => `copy:${platform}`)); gulp.task("package:all", Object.keys(platforms).map(platform => `package:${platform}`)); gulp.task("release:all", () => release("all")); Object.keys(platforms).forEach(platform => { gulp.task(`clean:${platform}`, platforms[platform].map(target => `clean:${target}`)); gulp.task(`nw:${platform}`, () => nw(platforms[platform])); gulp.task(`copy:${platform}`, platforms[platform].map(target => `copy:${target}`)); gulp.task(`package:${platform}`, platforms[platform].map(target => `package:${target}`)); gulp.task(`release:${platform}`, () => release(platform)); platforms[platform].forEach(target => { gulp.task(`clean:${target}`, () => del(cleanList(target))); gulp.task(`nw:${target}`, () => nw([target])); gulp.task(`copy:${target}`, () => { return gulp.src(copyList(target)).pipe(gulp.dest(`build/jikkyo/${target}`)); }); gulp.task(`package:${target}`, () => pack([target])); gulp.task(`release:${target}`, () => release(target)); }); }); gulp.task("clean", ["clean:all"]); if (currentTarget) { gulp.task("nw", [`nw:${currentTarget}`]); gulp.task("copy", [`copy:${currentTarget}`]); gulp.task("package", [`package:${currentTarget}`]); gulp.task("release", [`release:${currentTarget}`]); } gulp.task("default", ["nw"]);
var diff = require('../utils').diff; var debug = require('../utils/debug'); var registerComponent = require('../core/component').registerComponent; var THREE = require('../lib/three'); var degToRad = THREE.Math.degToRad; var warn = debug('components:light:warn'); /** * Light component. */ module.exports.Component = registerComponent('light', { schema: { angle: {default: 60, if: {type: ['spot']}}, color: {type: 'color'}, groundColor: {type: 'color', if: {type: ['hemisphere']}}, decay: {default: 1, if: {type: ['point', 'spot']}}, distance: {default: 0.0, min: 0, if: {type: ['point', 'spot']}}, intensity: {default: 1.0, min: 0, if: {type: ['ambient', 'directional', 'hemisphere', 'point', 'spot']}}, penumbra: {default: 0, min: 0, max: 1, if: {type: ['spot']}}, type: {default: 'directional', oneOf: ['ambient', 'directional', 'hemisphere', 'point', 'spot']}, target: {type: 'selector', if: {type: ['spot', 'directional']}} }, /** * Notifies scene a light has been added to remove default lighting. */ init: function () { var el = this.el; this.light = null; this.defaultTarget = null; this.system.registerLight(el); }, /** * (Re)create or update light. */ update: function (oldData) { var data = this.data; var diffData = diff(data, oldData); var light = this.light; var self = this; // Existing light. if (light && !('type' in diffData)) { // Light type has not changed. Update light. Object.keys(diffData).forEach(function (key) { var value = data[key]; switch (key) { case 'color': { light.color.set(value); break; } case 'groundcolor': { light.groundColor.set(value); break; } case 'angle': { light.angle = degToRad(value); break; } case 'target': { // Reset target if selector is null. if (value === null) { if (data.type === 'spot' || data.type === 'directional') { light.target = self.defaultTarget; } } else { // Target specified, set target to entity's `object3D` when it is loaded. if (value.hasLoaded) { self.onSetTarget(value); } else { value.addEventListener('loaded', self.onSetTarget.bind(self, value)); } } break; } default: { light[key] = value; } } }); return; } // No light yet or light type has changed. Create and add light. this.setLight(this.data); }, setLight: function (data) { var el = this.el; var newLight = this.getLight(data); if (newLight) { if (this.light) { el.removeObject3D('light'); } this.light = newLight; this.light.el = el; el.setObject3D('light', this.light); // HACK solution for issue #1624 if (data.type === 'spot' || data.type === 'directional' || data.type === 'hemisphere') { el.getObject3D('light').translateY(-1); } // set and position default lighttarget as a child to enable spotlight orientation if (data.type === 'spot') { el.setObject3D('light-target', this.defaultTarget); el.getObject3D('light-target').position.set(0, 0, -1); } } }, /** * Creates a new three.js light object given data object defining the light. * * @param {object} data */ getLight: function (data) { var angle = data.angle; var color = new THREE.Color(data.color).getHex(); var decay = data.decay; var distance = data.distance; var groundColor = new THREE.Color(data.groundColor).getHex(); var intensity = data.intensity; var type = data.type; var target = data.target; var light = null; switch (type.toLowerCase()) { case 'ambient': { return new THREE.AmbientLight(color, intensity); } case 'directional': { light = new THREE.DirectionalLight(color, intensity); this.defaultTarget = light.target; if (target) { if (target.hasLoaded) { this.onSetTarget(target); } else { target.addEventListener('loaded', this.onSetTarget.bind(this, target)); } } return light; } case 'hemisphere': { return new THREE.HemisphereLight(color, groundColor, intensity); } case 'point': { return new THREE.PointLight(color, intensity, distance, decay); } case 'spot': { light = new THREE.SpotLight(color, intensity, distance, degToRad(angle), data.penumbra, decay); this.defaultTarget = light.target; if (target) { if (target.hasLoaded) { this.onSetTarget(target); } else { target.addEventListener('loaded', this.onSetTarget.bind(this, target)); } } return light; } default: { warn('%s is not a valid light type. ' + 'Choose from ambient, directional, hemisphere, point, spot.', type); } } }, onSetTarget: function (targetEl) { this.light.target = targetEl.object3D; }, /** * Remove light on remove (callback). */ remove: function () { this.el.removeObject3D('light'); } });
module.exports = function(config) { config.set({ basePath: '', frameworks: ['jasmine'], /* Important to have here all files related to the project. Double check your dependencies in Angular module and HTML. */ files: [ 'https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js', 'https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular-mocks.js', 'https://cdnjs.cloudflare.com/ajax/libs/angular-translate/2.11.1/angular-translate.min.js', 'https://cdnjs.cloudflare.com/ajax/libs/angular-translate-loader-static-files/2.11.1/angular-translate-loader-static-files.min.js', 'https://d5wfroyti11sa.cloudfront.net/prod/client/ts-6.0.0-alpha.8.min.js', 'https://cdn.jsdelivr.net/lodash/4.14.0/lodash.min.js', 'javascripts/*.js', 'tests/*.spec.js' ], exclude: [], preprocessors: {}, reporters: ['progress'], port: 9876, colors: true, // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], singleRun: false, concurrency: Infinity }) };
(function() { 'use strict'; let EE = require('./ee'); let ES6 = require('./es6'); let log = require('ee-log'); let iterations = 100; let start; let ee = 0; let es6 = 0; for (let k = 0; k < 1000; k++) { start = process.hrtime(); for (let i = 0; i < iterations; i++) { new ES6({ name: "fabian" , age: 15 , isAlive: true }).describe(); } es6 += process.hrtime(start)[1]; log.success('ES6: '+(process.hrtime(start)[1])); start = process.hrtime(); for (let i = 0; i < iterations; i++) { new EE({ name: "fabian" , age: 15 , isAlive: true }).describe(); } ee += process.hrtime(start)[1]; log.success('EE: '+(process.hrtime(start)[1])); } log.warn('EE: '+(ee/1000/1000)); log.warn('ES6: '+(es6/1000/1000)); })();
import React from 'react' import {Row, Col, Tabs, Carousel} from 'antd' const TabPane = Tabs.TabPane import PCNewsBlock from './PC_news_block' import PCNewsImageBlock from './PC_news_image_block' export default class PCNewsContainer extends React.Component { render() { const settings = { dots: true, infinite: true, speed: 500, slidesToShow: 1, autoplay: true, } return( <div> <Row> <Col span={2}></Col> <Col span={20} className="container"> <div className="leftContainer"> <div className="carousel"> <Carousel {...settings}> <div> <img src="../../../../static/images/carousel_1.jpg"/> </div> <div> <img src="../../../../static/images/carousel_2.jpg"/> </div> <div> <img src="../../../../static/images/carousel_3.jpg"/> </div> <div> <img src="../../../../static/images/carousel_4.jpg"/> </div> </Carousel> </div> <PCNewsImageBlock count={6} type='guoji' width="400px" cartTitle="国际头条" width="400px" imageWidth='112px' /> <PCNewsImageBlock count={6} type='yule' width="400px" cartTitle="娱乐头条" width="400px" imageWidth='112px' /> </div> <Tabs className="tabs_news"> <TabPane tab='新闻' key="1"> <PCNewsBlock count={22} type="top" width="100%" bordered="false"></PCNewsBlock> </TabPane> <TabPane tab='国际' key="2"> <PCNewsBlock count={22} type="top" width="100%" bordered="false"></PCNewsBlock> </TabPane> </Tabs> </Col> <Col span={2}></Col> </Row> </div> ) } }
/** * naive SDK * Kevin Lee 31 March 2017 * Major Start on 26 July 2017 * * "Too Simple, Sometimes Naive ... UI gonna be" * A react-NAtIVE component for simple User Interface development * * Install (Vector Icon): * npm install react-native-vector-icons --save * * Edit android/app/build.gradle: // begin react-native-vector-icons project.ext.vectoricons = [ iconFontNames: [ 'MaterialIcons.ttf', 'Ionicons.ttf' ] ] apply from: "../../node_modules/react-native-vector-icons/fonts.gradle" // end react-native-vector-icons * Install (Administrator) (International Setting): * npm install intl * * Readings: * https://unbug.gitbooks.io/react-native-training/content/23_states_&_props.html * * Install DatePicker Component * npm install react-native-datepicker * * Install SideMenu Component * npm install react-native-side-menu * * Install Camera Component * npm install react-native-camera * react-native link react-native-camera * Edit node_modules/react-native-camera/android/build.gradle android { compileSdkVersion 23 buildToolsVersion "23.0.1" defaultConfig { minSdkVersion 16 targetSdkVersion 23 versionCode 1 versionName "1.0" } * ( Compile with react-native SDK version ) * Edit AndroidManifest.xml (android/app/main/): <uses-permission android:name="android.permission.CAMERA" /> <uses-feature android:name="android.hardware.camera" /> *** Supplement modules *** * Install react-native-mail npm install react-native-mail copy RNMail.m to nodes_modules/RNMail copy RNMailModule.jave to android/main/java/com/chirag/RNMail * Install react-navigation npm install react-nagivation **/ module.exports = { // Base Style & HTML get BaseStyle() { return require('./basestyle').default }, get Text() { return require('./text').default }, // Device and Screen Layout get Device() { return require('./device').default }, get Screen() { return require('./screen').default }, get Block() { return require('./block').default }, get Content() { return require('./block').default }, get Bar() { return require('./bar').default }, get Modal() { return require('./modal').default }, get DataBar() { return require('./databar').default }, get DataBlock() { return require('./datablock').default }, // Icon get Icon() { return require('./icon').default }, get IconList() { return require('./iconlist').default }, // Button family get Button() { return require('./button').default }, get ButtonList() { return require('./buttonlist').default }, get ButtonPanel() { return require('./buttonpanel').default }, get Roll() { return require('./roll').default }, get RollButton() { return require('./roll').default }, get CheckBox() { return require('./checkbox').default }, get RadioBox() { return require('./radiobox').default }, // Input UI element get Input() { return require('./input').default }, get NumberInput() { return require('./numberinput').default }, get DateSelect() { return require('./dateselect').default }, get ItemSelect() { return require('./itemselect').default }, get ImageSlider() { return require('./imageslider').default }, // Non-visual get MOM() { return require('./mom').default }, get Lang() { return require('./lang').default }, // Borrowed get SideMenu() { return require('./sidemenu').default }, // get Camera() { // return require('react-native-camera').default // }, }
var path = require('path'); var cheerio = require('cheerio'); var URI = require('URIjs'); var _ = require('lodash'); var Source = require('webpack/lib/Source'); /** * @class * @extends Source * @param {Module} sourceModule * @param {Chunk} sourceChunk * @param {Compilation} compilation */ function IndexHtmlSource(sourceModule, sourceChunk, compilation) { this.sourceModule = sourceModule; this.sourceChunk = sourceChunk; this.compilation = compilation; } module.exports = IndexHtmlSource; IndexHtmlSource.prototype = Object.create(Source.prototype); IndexHtmlSource.prototype.constructor = IndexHtmlSource; IndexHtmlSource.prototype.source = function() { var html = this._getHtmlFromModule(); var $ = cheerio.load(html); coalesceLinks($); this._resolveScripts($); return $.html(); }; /** * Extracts the HTML code from the module source */ IndexHtmlSource.prototype._getHtmlFromModule = function() { var compilation = this.compilation; var sourceChunk = this.sourceChunk; function moduleWasExtracted(module) { return module.loaders && module.loaders.some(function(loader) { return loader.match(/extract-text-webpack-plugin/); }) } function getExtractTextLoaderOptions(module) { for (var i = 0; i < module.loaders.length; i++) { var loader = module.loaders[i]; var match = loader.match(/extract-text-webpack-plugin[\\/]loader\.js\?({.*})/); if (match) { return JSON.parse(match[1]); } } } function getExtractedFilename(module) { var options = getExtractTextLoaderOptions(module); var loaderId = options && options.id; var extractTextPlugin = _.find(compilation.compiler.options.plugins, function (p) { return (p.constructor.name === 'ExtractTextPlugin') && ((typeof(p.id) === "undefined" && typeof(loaderId) === "undefined") || (p.id === loaderId)); }); var filenamePattern = extractTextPlugin.filename .replace(/\[(?:\w+:)?(contenthash)(?::[a-z]+\d*)?(?::(\d+))?]|([^\[\]]+)/ig, function(match, contentHash, maxLength, literalPart) { if (contentHash) { if (maxLength) { return '[a-f0-9]{1,' + maxLength + '}'; } else { return '[a-f0-9]+'; } } else { return regexpQuote(literalPart); } }); filenamePattern = new RegExp(filenamePattern); return _.find(sourceChunk.files, function(filename) { return filename.match(filenamePattern); }); } function __webpack_require__(moduleId) { var sourceModule; if (typeof moduleId === "number") { sourceModule = _.find(compilation.modules, function (m) { return m.id === moduleId; }); } else { sourceModule = moduleId; } if (!sourceModule) { return undefined; } if (_.endsWith(sourceModule.context, path.normalize('webpack-dev-server/client')) || _.endsWith(sourceModule.context, path.normalize('webpack/hot'))) { return undefined; } else if (moduleWasExtracted(sourceModule)) { return getExtractedFilename(sourceModule); } else { var module = {}; var source = sourceModule.source(null, {}); eval(source.source()); return module.exports; } } // This is where the "real" __webpack_require__ would store the public path, // it is used by url-loader to construct the link __webpack_require__.p = compilation.options.output.publicPath || ''; return __webpack_require__(this.sourceModule); }; /** * Resolve <script> tags that refer to entry points by replacing them with the final names of the bundles. * @param $ */ IndexHtmlSource.prototype._resolveScripts = function($) { var compilation = this.compilation; var sourceContext = this.sourceModule.context; $('script').each(function () { var scriptSrc = $(this).attr('src'); if (scriptSrc) { var scriptSrcUri = new URI(scriptSrc); if (!scriptSrcUri.is('absolute')) { var entry = path.resolve(sourceContext, scriptSrc); var moduleForEntry = _.find(compilation.modules, function (module) { return module.resource && path.normalize(module.resource) === entry }); if (moduleForEntry) { var chunkForEntry = moduleForEntry.chunks[0]; var chunkJsFile = _.find(chunkForEntry.files, function (file) { return new URI(file).filename().match(/\.js$/) }); if (chunkJsFile) { $(this).attr('src', chunkJsFile); } } } } }); }; function regexpQuote(s) { return s.toString().replace(/[-\\^$*+?.()|[\]{}]/g, "\\$&"); } /** * Coalesce all links with the same rel and href into one * @param $ */ function coalesceLinks($) { $('link').each(function () { var rel = $(this).attr('rel'); var href = $(this).attr('href'); $(this).nextAll("link[rel='" + rel + "'][href='" + href + "']").remove(); }); }
var express = require('express'); var router = express.Router(); var Examples = require('../models/Example'); var data; //出来通用数据 router.use(function(req, res, next) { data = { examples: [] }; Examples.find().then(function(examples) { data.examples = examples; next(); }); }); router.get('/', function(req, res, next) { data.examples = req.query.examples || ''; data.count = 0; data.page = Number(req.query.page || 1); data.limit = 8; data.pages = 0; data.category = req.query.category || 'all'; var where = {}; if (data.example) { where.example = data.example; } var rule; if (data.category == 'query') { rule = { '$or': [{ tag: eval('/' + req.query.search + '/i') }, { des: eval('/' + req.query.search + '/i') }] } } else if (data.category == 'all') { rule = {} } else { rule = { tag: eval('/' + req.query.category + '/i') } } Examples.where(where).count(rule).then(function(count) { data.count = count; //计算总页数 data.pages = Math.ceil(data.count / data.limit); //取值不能超过pages data.page = Math.min(data.page, data.pages); //取值不能小于1 data.page = Math.max(data.page, 1); var skip = (data.page - 1) * data.limit; Examples.where(where).find(rule).sort({ "link": 1 }).limit(data.limit).skip(skip).then(function(examples) { res.render('index', { category: data.category, examples: examples, count: data.count, pages: data.pages, limit: data.limit, page: data.page }); }); }); }); //详情页 router.get('/details', function(req, res, next) { var link = parseInt(req.query.id, 10); Examples.count().then(function(count) { Examples.findOne({ "link": link }).then(function(example) { Examples.update({ "link": link }, { $set: { "see": example.see + 1 } }).then(function(newExample) { Examples.findOne({ "link": link - 1 }).then(function(pre) { Examples.findOne({ "link": link + 1 }).then(function(next) { res.render('details', { example: example, pre: pre, next: next }); }); }); }); }); }); }); router.post('/praise', function(req, res, next) { var link = parseInt(req.body.id, 10); Examples.update({ "link": link }, { $inc: { love: 1 } }).then(function(example) { res.end('{"isOk":true}'); }); }); module.exports = router;
define(function () { return function (states) { if ( typeof states.initialize !== 'function' ) { throw new Error('Must have an initialize method'); } function FiniteStateMachine (options) { var state = states.initialize.call(this, options); if ( ! state ) { throw new Error('initialize did not set an initial state'); } this.send = function (event) { state = states[state].call(this, event) || state; }; this.currentState = function () { return state; }; } return FiniteStateMachine; }; });
export const REQUEST_POKEMONS = 'REQUEST_POKEMONS'; export const RECEIVE_POKEMONS = 'RECEIVE_POKEMONS'; export const REQUEST_POKEMON = 'REQUEST_POKEMON'; export const RECEIVE_POKEMON = 'RECEIVE_POKEMON'; export const SET_SEARCH_TERM = 'SET_SEARCH_TERM';
const win = typeof window == 'object' let THREE = win && window.THREE let { Camera, ClampToEdgeWrapping, DataTexture, FloatType, Mesh, NearestFilter, PlaneBufferGeometry, RGBAFormat, Scene, ShaderMaterial, WebGLRenderTarget } = (THREE || {}) /** * GPUComputationRenderer, based on SimulationRenderer by zz85 * * The GPUComputationRenderer uses the concept of variables. These variables are RGBA float textures that hold 4 floats * for each compute element (texel) * * Each variable has a fragment shader that defines the computation made to obtain the variable in question. * You can use as many variables you need, and make dependencies so you can use textures of other variables in the shader * (the sampler uniforms are added automatically) Most of the variables will need themselves as dependency. * * The renderer has actually two render targets per variable, to make ping-pong. Textures from the current frame are used * as inputs to render the textures of the next frame. * * The render targets of the variables can be used as input textures for your visualization shaders. * * Variable names should be valid identifiers and should not collide with THREE GLSL used identifiers. * a common approach could be to use 'texture' prefixing the variable name; i.e texturePosition, textureVelocity... * * The size of the computation (sizeX * sizeY) is defined as 'resolution' automatically in the shader. For example: * #DEFINE resolution vec2( 1024.0, 1024.0 ) * * ------------- * * Basic use: * * // Initialization... * * // Create computation renderer * var gpuCompute = new GPUComputationRenderer( 1024, 1024, renderer ); * * // Create initial state float textures * var pos0 = gpuCompute.createTexture(); * var vel0 = gpuCompute.createTexture(); * // and fill in here the texture data... * * // Add texture variables * var velVar = gpuCompute.addVariable( "textureVelocity", fragmentShaderVel, pos0 ); * var posVar = gpuCompute.addVariable( "texturePosition", fragmentShaderPos, vel0 ); * * // Add variable dependencies * gpuCompute.setVariableDependencies( velVar, [ velVar, posVar ] ); * gpuCompute.setVariableDependencies( posVar, [ velVar, posVar ] ); * * // Add custom uniforms * velVar.material.uniforms.time = { value: 0.0 }; * * // Check for completeness * var error = gpuCompute.init(); * if ( error !== null ) { * console.error( error ); * } * * * // In each frame... * * // Compute! * gpuCompute.compute(); * * // Update texture uniforms in your visualization materials with the gpu renderer output * myMaterial.uniforms.myTexture.value = gpuCompute.getCurrentRenderTarget( posVar ).texture; * * // Do your rendering * renderer.render( myScene, myCamera ); * * ------------- * * Also, you can use utility functions to create ShaderMaterial and perform computations (rendering between textures) * Note that the shaders can have multiple input textures. * * var myFilter1 = gpuCompute.createShaderMaterial( myFilterFragmentShader1, { theTexture: { value: null } } ); * var myFilter2 = gpuCompute.createShaderMaterial( myFilterFragmentShader2, { theTexture: { value: null } } ); * * var inputTexture = gpuCompute.createTexture(); * * // Fill in here inputTexture... * * myFilter1.uniforms.theTexture.value = inputTexture; * * var myRenderTarget = gpuCompute.createRenderTarget(); * myFilter2.uniforms.theTexture.value = myRenderTarget.texture; * * var outputRenderTarget = gpuCompute.createRenderTarget(); * * // Now use the output texture where you want: * myMaterial.uniforms.map.value = outputRenderTarget.texture; * * // And compute each frame, before rendering to screen: * gpuCompute.doRenderTarget( myFilter1, myRenderTarget ); * gpuCompute.doRenderTarget( myFilter2, outputRenderTarget ); * * * * @param {int} sizeX Computation problem size is always 2d: sizeX * sizeY elements. * @param {int} sizeY Computation problem size is always 2d: sizeX * sizeY elements. * @param {WebGLRenderer} renderer The renderer */ var GPUComputationRenderer = function ( sizeX, sizeY, renderer, userTHREE) { if (userTHREE) { ({ Camera, ClampToEdgeWrapping, DataTexture, FloatType, Mesh, NearestFilter, PlaneBufferGeometry, RGBAFormat, Scene, ShaderMaterial, WebGLRenderTarget} = userTHREE) } this.variables = []; this.currentTextureIndex = 0; var dataType = FloatType; var scene = new Scene(); var camera = new Camera(); camera.position.z = 1; var passThruUniforms = { passThruTexture: { value: null } }; var passThruShader = createShaderMaterial( getPassThroughFragmentShader(), passThruUniforms ); var mesh = new Mesh( new PlaneBufferGeometry( 2, 2 ), passThruShader ); scene.add( mesh ); this.setDataType = function ( type ) { dataType = type; return this; }; this.addVariable = function ( variableName, computeFragmentShader, initialValueTexture ) { var material = this.createShaderMaterial( computeFragmentShader ); var variable = { name: variableName, initialValueTexture: initialValueTexture, material: material, dependencies: null, renderTargets: [], wrapS: null, wrapT: null, minFilter: NearestFilter, magFilter: NearestFilter }; this.variables.push( variable ); return variable; }; this.setVariableDependencies = function ( variable, dependencies ) { variable.dependencies = dependencies; }; this.init = function () { if ( ! renderer.capabilities.isWebGL2 && ! renderer.extensions.get( "OES_texture_float" ) ) { return "No OES_texture_float support for float textures."; } if ( renderer.capabilities.maxVertexTextures === 0 ) { return "No support for vertex shader textures."; } for ( var i = 0; i < this.variables.length; i ++ ) { var variable = this.variables[ i ]; // Creates rendertargets and initialize them with input texture variable.renderTargets[ 0 ] = this.createRenderTarget( sizeX, sizeY, variable.wrapS, variable.wrapT, variable.minFilter, variable.magFilter ); variable.renderTargets[ 1 ] = this.createRenderTarget( sizeX, sizeY, variable.wrapS, variable.wrapT, variable.minFilter, variable.magFilter ); this.renderTexture( variable.initialValueTexture, variable.renderTargets[ 0 ] ); this.renderTexture( variable.initialValueTexture, variable.renderTargets[ 1 ] ); // Adds dependencies uniforms to the ShaderMaterial var material = variable.material; var uniforms = material.uniforms; if ( variable.dependencies !== null ) { for ( var d = 0; d < variable.dependencies.length; d ++ ) { var depVar = variable.dependencies[ d ]; if ( depVar.name !== variable.name ) { // Checks if variable exists var found = false; for ( var j = 0; j < this.variables.length; j ++ ) { if ( depVar.name === this.variables[ j ].name ) { found = true; break; } } if ( ! found ) { return "Variable dependency not found. Variable=" + variable.name + ", dependency=" + depVar.name; } } uniforms[ depVar.name ] = { value: null }; material.fragmentShader = "\nuniform sampler2D " + depVar.name + ";\n" + material.fragmentShader; } } } this.currentTextureIndex = 0; return null; }; this.compute = function () { var currentTextureIndex = this.currentTextureIndex; var nextTextureIndex = this.currentTextureIndex === 0 ? 1 : 0; for ( var i = 0, il = this.variables.length; i < il; i ++ ) { var variable = this.variables[ i ]; // Sets texture dependencies uniforms if ( variable.dependencies !== null ) { var uniforms = variable.material.uniforms; for ( var d = 0, dl = variable.dependencies.length; d < dl; d ++ ) { var depVar = variable.dependencies[ d ]; uniforms[ depVar.name ].value = depVar.renderTargets[ currentTextureIndex ].texture; } } // Performs the computation for this variable this.doRenderTarget( variable.material, variable.renderTargets[ nextTextureIndex ] ); } this.currentTextureIndex = nextTextureIndex; }; this.getCurrentRenderTarget = function ( variable ) { return variable.renderTargets[ this.currentTextureIndex ]; }; this.getAlternateRenderTarget = function ( variable ) { return variable.renderTargets[ this.currentTextureIndex === 0 ? 1 : 0 ]; }; function addResolutionDefine( materialShader ) { materialShader.defines.resolution = 'vec2( ' + sizeX.toFixed( 1 ) + ', ' + sizeY.toFixed( 1 ) + " )"; } this.addResolutionDefine = addResolutionDefine; // The following functions can be used to compute things manually function createShaderMaterial( computeFragmentShader, uniforms ) { uniforms = uniforms || {}; var material = new ShaderMaterial( { uniforms: uniforms, vertexShader: getPassThroughVertexShader(), fragmentShader: computeFragmentShader } ); addResolutionDefine( material ); return material; } this.createShaderMaterial = createShaderMaterial; this.createRenderTarget = function ( sizeXTexture, sizeYTexture, wrapS, wrapT, minFilter, magFilter ) { sizeXTexture = sizeXTexture || sizeX; sizeYTexture = sizeYTexture || sizeY; wrapS = wrapS || ClampToEdgeWrapping; wrapT = wrapT || ClampToEdgeWrapping; minFilter = minFilter || NearestFilter; magFilter = magFilter || NearestFilter; var renderTarget = new WebGLRenderTarget( sizeXTexture, sizeYTexture, { wrapS: wrapS, wrapT: wrapT, minFilter: minFilter, magFilter: magFilter, format: RGBAFormat, type: dataType, stencilBuffer: false, depthBuffer: false } ); return renderTarget; }; this.createTexture = function () { var data = new Float32Array( sizeX * sizeY * 4 ); return new DataTexture( data, sizeX, sizeY, RGBAFormat, FloatType ); }; this.renderTexture = function ( input, output ) { // Takes a texture, and render out in rendertarget // input = Texture // output = RenderTarget passThruUniforms.passThruTexture.value = input; this.doRenderTarget( passThruShader, output ); passThruUniforms.passThruTexture.value = null; }; this.doRenderTarget = function ( material, output ) { var currentRenderTarget = renderer.getRenderTarget(); mesh.material = material; renderer.setRenderTarget( output ); renderer.render( scene, camera ); mesh.material = passThruShader; renderer.setRenderTarget( currentRenderTarget ); }; // Shaders function getPassThroughVertexShader() { return "void main() {\n" + "\n" + " gl_Position = vec4( position, 1.0 );\n" + "\n" + "}\n"; } function getPassThroughFragmentShader() { return "uniform sampler2D passThruTexture;\n" + "\n" + "void main() {\n" + "\n" + " vec2 uv = gl_FragCoord.xy / resolution.xy;\n" + "\n" + " gl_FragColor = texture2D( passThruTexture, uv );\n" + "\n" + "}\n"; } }; export default GPUComputationRenderer;
'use strict'; (function (angular,buildfire) { angular.module('fixedTimerPluginContent', ['ngRoute', 'ui.bootstrap', 'ui.tinymce', 'timerModals', 'ui.sortable']) //injected ngRoute for routing .config(['$routeProvider', function ($routeProvider) { $routeProvider .when('/', { templateUrl: 'templates/home.html', controllerAs: 'ContentHome', controller: 'ContentHomeCtrl' }) .when('/item', { templateUrl: 'templates/timerItem.html', controllerAs: 'ContentItem', controller: 'ContentItemCtrl' }) .when('/item/:itemId', { templateUrl: 'templates/timerItem.html', controllerAs: 'ContentItem', controller: 'ContentItemCtrl' }) .otherwise('/'); }]) .run(['Location','Buildfire', function (Location,Buildfire) { // Handler to receive message from widget Buildfire.history.onPop(function(data, err){ if(data && data.label!='Item') Location.goToHome(); console.log('Buildfire.history.onPop called', data, err); }); }]) })(window.angular,window.buildfire);
function outerWidth(el, includeMargin){ var height = el.offsetWidth; if(includeMargin){ var style = getComputedStyle(el); height += parseInt(style.marginLeft) + parseInt(style.marginRight); } return height; } outerWidth(el, true);
/* jshint expr: true */ 'use strict' let chai = require ('chai') let assert = chai.assert let expect = chai.expect let BaeBaeModule = require('../../lib/baebae-module') describe('BaeBaeModule test suite', () => { let module = null describe('constructor tests', () => { it('should not throw an error', () => { assert.doesNotThrow(() => { module = new BaeBaeModule() }) }) it('should not be null', () => { expect(module).to.not.be.null }) }) describe('init tests', () => { let module = new BaeBaeModule() it('should not throw an error', () => { assert.doesNotThrow(() => { module.init() }) }) }) })
var _ = require('lodash'); var express = require('express'); var fs = require('fs'); var grappling = require('grappling-hook'); var path = require('path'); var utils = require('keystone-utils'); /** * Don't use process.cwd() as it breaks module encapsulation * Instead, let's use module.parent if it's present, or the module itself if there is no parent (probably testing keystone directly if that's the case) * This way, the consuming app/module can be an embedded node_module and path resolutions will still work * (process.cwd() breaks module encapsulation if the consuming app/module is itself a node_module) */ var moduleRoot = (function (_rootPath) { var parts = _rootPath.split(path.sep); parts.pop(); // get rid of /node_modules from the end of the path return parts.join(path.sep); })(module.parent ? module.parent.paths[0] : module.paths[0]); /** * Keystone Class */ var Keystone = function () { grappling.mixin(this).allowHooks('pre:static', 'pre:bodyparser', 'pre:session', 'pre:logger', 'pre:admin', 'pre:routes', 'pre:render', 'updates', 'signin', 'signout'); this.lists = {}; this.fieldTypes = {}; this.paths = {}; this._options = { 'name': 'Keystone', 'brand': 'Keystone', 'admin path': 'keystone', 'compress': true, 'headless': false, 'logger': ':method :url :status :response-time ms', 'auto update': false, 'model prefix': null, 'module root': moduleRoot, 'frame guard': 'sameorigin', }; this._redirects = {}; // expose express this.express = express; // init environment defaults this.set('env', process.env.NODE_ENV || 'development'); this.set('port', process.env.PORT || process.env.OPENSHIFT_NODEJS_PORT || '3000'); this.set('host', process.env.HOST || process.env.IP || process.env.OPENSHIFT_NODEJS_IP) || '0.0.0.0'; this.set('listen', process.env.LISTEN); this.set('ssl', process.env.SSL); this.set('ssl port', process.env.SSL_PORT || '3001'); this.set('ssl host', process.env.SSL_HOST || process.env.SSL_IP); this.set('ssl key', process.env.SSL_KEY); this.set('ssl cert', process.env.SSL_CERT); this.set('cookie secret', process.env.COOKIE_SECRET); this.set('cookie signin', (this.get('env') === 'development') ? true : false); this.set('embedly api key', process.env.EMBEDLY_API_KEY || process.env.EMBEDLY_APIKEY); this.set('mandrill api key', process.env.MANDRILL_API_KEY || process.env.MANDRILL_APIKEY); this.set('mandrill username', process.env.MANDRILL_USERNAME); this.set('google api key', process.env.GOOGLE_BROWSER_KEY); this.set('google server api key', process.env.GOOGLE_SERVER_KEY); this.set('ga property', process.env.GA_PROPERTY); this.set('ga domain', process.env.GA_DOMAIN); this.set('chartbeat property', process.env.CHARTBEAT_PROPERTY); this.set('chartbeat domain', process.env.CHARTBEAT_DOMAIN); this.set('allowed ip ranges', process.env.ALLOWED_IP_RANGES); if (process.env.S3_BUCKET && process.env.S3_KEY && process.env.S3_SECRET) { this.set('s3 config', { bucket: process.env.S3_BUCKET, key: process.env.S3_KEY, secret: process.env.S3_SECRET, region: process.env.S3_REGION }); } if (process.env.AZURE_STORAGE_ACCOUNT && process.env.AZURE_STORAGE_ACCESS_KEY) { this.set('azurefile config', { account: process.env.AZURE_STORAGE_ACCOUNT, key: process.env.AZURE_STORAGE_ACCESS_KEY }); } if (process.env.CLOUDINARY_URL) { // process.env.CLOUDINARY_URL is processed by the cloudinary package when this is set this.set('cloudinary config', true); } // init mongoose this.set('mongoose', require('mongoose')); this.mongoose.Promise = require('es6-promise').Promise; // Attach middleware packages, bound to this instance this.middleware = { api: require('./lib/middleware/api')(this), cors: require('./lib/middleware/cors')(this), }; }; _.extend(Keystone.prototype, require('./lib/core/options')); Keystone.prototype.prefixModel = function (key) { var modelPrefix = this.get('model prefix'); if (modelPrefix) { key = modelPrefix + '_' + key; } return require('mongoose/lib/utils').toCollectionName(key); }; /* Attach core functionality to Keystone.prototype */ Keystone.prototype.createItems = require('./lib/core/createItems'); Keystone.prototype.createRouter = require('./lib/core/createRouter'); Keystone.prototype.getOrphanedLists = require('./lib/core/getOrphanedLists'); Keystone.prototype.importer = require('./lib/core/importer'); Keystone.prototype.init = require('./lib/core/init'); Keystone.prototype.initDatabase = require('./lib/core/initDatabase'); Keystone.prototype.initExpressApp = require('./lib/core/initExpressApp'); Keystone.prototype.initExpressSession = require('./lib/core/initExpressSession'); Keystone.prototype.initNav = require('./lib/core/initNav'); Keystone.prototype.list = require('./lib/core/list'); Keystone.prototype.openDatabaseConnection = require('./lib/core/openDatabaseConnection'); Keystone.prototype.closeDatabaseConnection = require('./lib/core/closeDatabaseConnection'); Keystone.prototype.populateRelated = require('./lib/core/populateRelated'); Keystone.prototype.redirect = require('./lib/core/redirect'); Keystone.prototype.start = require('./lib/core/start'); Keystone.prototype.wrapHTMLError = require('./lib/core/wrapHTMLError'); /* Deprecation / Change warnings for 0.4 */ Keystone.prototype.routes = function () { throw new Error('keystone.routes(fn) has been removed, use keystone.set(\'routes\', fn)'); }; /** * The exports object is an instance of Keystone. */ var keystone = module.exports = new Keystone(); /* Note: until #1777 is complete, the order of execution here with the requires (specifically, they happen _after_ the module.exports above) is really important. As soon as the circular dependencies are sorted out to get their keystone instance from a closure or reference on {this} we can move these bindings into the Keystone constructor. */ // Expose modules and Classes keystone.Admin = { Server: require('./admin/server'), }; keystone.Email = require('./lib/email'); keystone.Field = require('./fields/types/Type'); keystone.Field.Types = require('./lib/fieldTypes'); keystone.Keystone = Keystone; keystone.List = require('./lib/list')(keystone); keystone.Storage = require('./lib/storage'); keystone.View = require('./lib/view'); keystone.content = require('./lib/content'); keystone.security = { csrf: require('./lib/security/csrf'), }; keystone.utils = utils; /** * returns all .js modules (recursively) in the path specified, relative * to the module root (where the keystone project is being consumed from). * * ####Example: * var models = keystone.import('models'); */ Keystone.prototype.import = function (dirname) { var initialPath = path.join(this.get('module root'), dirname); var doImport = function (fromPath) { var imported = {}; fs.readdirSync(fromPath).forEach(function (name) { var fsPath = path.join(fromPath, name); var info = fs.statSync(fsPath); // recur if (info.isDirectory()) { imported[name] = doImport(fsPath); } else { // only import files that we can `require` var ext = path.extname(name); var base = path.basename(name, ext); if (require.extensions[ext]) { imported[base] = require(fsPath); } } }); return imported; }; return doImport(initialPath); }; /** * Applies Application updates */ Keystone.prototype.applyUpdates = function (callback) { var self = this; self.callHook('pre:updates', function (err) { if (err) return callback(err); require('./lib/updates').apply(function (err) { if (err) return callback(err); self.callHook('post:updates', callback); }); }); }; /** * Logs a configuration error to the console */ Keystone.prototype.console = {}; Keystone.prototype.console.err = function (type, msg) { if (keystone.get('logger')) { var dashes = '\n------------------------------------------------\n'; console.log(dashes + 'KeystoneJS: ' + type + ':\n\n' + msg + dashes); } }; /** * Keystone version */ keystone.version = require('./package.json').version; // Expose Modules keystone.session = require('./lib/session');
/** * @file * @author Bryan Hazelbaker <bryan.hazelbaker@gmail.com> * @version 0.1 * * @copyright Copyright (c) 2013 Bryan Hazelbaker <bryan.hazelbaker@gmail.com> * Released under the MIT license. Read the entire license located in the * project root or at http://opensource.org/licenses/mit-license.php * * @brief Translate words into english. * * @details The skin parsers may need access to language specific words. * * @see https://github.com/delphian/astro-empires-javascript-library */ AstroEmpires.Language.english = function(word) { switch(word) { case 'credits': return 'credits'; break; } };
/** * only adapted XMLHttpRequest object. **/ let xhrObjectList = []; let proxyXhrOpen = () => { let handle = () => { let e = document.createEvent('Events'); e.initEvent('xhrRequestOpen'); let option = { url: arguments[1], method: arguments[0] }; e.opt = option; document.dispatchEvent(e); xhrObjectList.push(option); }; proxy('open', handle); }; // var proxyStateChange = function() { // var xhrObject = getXhrProto(); // window.xhrDone = false; // Object.defineProperty(xhrObject, 'onreadystatechange', { // get: function() { // return value; // }, // set: function(func) { // var that = this; // value = function(){ // func.apply(that); // console.log('new'); // if(that.readyState == 4){ // window.xhrDone = true; // console.log('xhrDone'); // } // } // // value.prototype = xhrObject.onreadystatechange; // } // }); // } let proxy = (funcName, injectFunc) => { if (!funcName || !injectFunc || typeof injectFunc !== 'function') { return false; } let xhrObject = getXhrProto(); if (xhrObject && xhrObject[funcName] && typeof xhrObject[funcName] === 'function') { let oldFunc = xhrObject[funcName]; xhrObject[funcName] = () => { injectFunc.apply(this, arguments); oldFunc.apply(this, arguments); }; } return true; }; let getXhrProto = () => { return window.XMLHttpRequest.prototype; }; let getXhrList = () => { return xhrObjectList; }; // let trigger = (eventName,dataMap) => { // let e = document.createEvent('Events'); // e.initEvent(eventName); // if (dataMap) { // for (let propName in dataMap) { // e[propName] = dataMap[propName]; // } // } // document.dispatchEvent(e); // }; // module.exports = { proxyXhrOpen, proxy, getXhrList };
describe('Hidden Moon Dōjō', function() { integration(function() { describe('Hidden Moon Dōjō\'s ability', function() { beforeEach(function() { this.setupTest({ phase: 'conflict', player1: { fate: 7, inPlay: ['fawning-diplomat'], dynastyDiscard: [ 'hidden-moon-dojo', 'mountaintop-statuary', 'favorable-ground', 'bayushi-liar', 'bayushi-manipulator', 'shosuro-miyako' ] }, player2: { inPlay: [] } }); }); it('should flip an adjacent card face up during a conflict', function() { this.bayushiLiar = this.player1.placeCardInProvince('bayushi-liar', 'province 1'); this.bayushiLiar.facedown = true; this.hiddenMoonDojo = this.player1.placeCardInProvince('hidden-moon-dojo', 'province 2'); this.favorableGround = this.player1.placeCardInProvince('favorable-ground', 'province 3'); this.bayushiManipulator = this.player1.placeCardInProvince('bayushi-manipulator', 'province 4'); this.bayushiManipulator.facedown = true; this.player1.clickCard(this.hiddenMoonDojo); expect(this.player1).toHavePrompt('Action Window'); this.noMoreActions(); this.initiateConflict({ attackers: ['fawning-diplomat'], defenders: [] }); this.player2.pass(); this.player1.clickCard(this.hiddenMoonDojo); expect(this.player1).toHavePrompt('Hidden Moon Dōjō'); expect(this.player1).toBeAbleToSelect(this.bayushiLiar); expect(this.player1).not.toBeAbleToSelect(this.favorableGround); expect(this.player1).not.toBeAbleToSelect(this.bayushiManipulator); this.player1.clickCard(this.bayushiLiar); expect(this.bayushiLiar.facedown).toBe(false); expect(this.player2).toHavePrompt('Conflict Action Window'); }); it('should trigger any abilities on being flipped', function() { this.mountaintopStatuary = this.player1.placeCardInProvince('mountaintop-statuary'); this.mountaintopStatuary.facedown = true; this.hiddenMoonDojo = this.player1.placeCardInProvince('hidden-moon-dojo', 'province 2'); this.noMoreActions(); this.initiateConflict({ attackers: ['fawning-diplomat'], defenders: [] }); this.player2.pass(); this.player1.clickCard(this.hiddenMoonDojo); expect(this.player1).toHavePrompt('Hidden Moon Dōjō'); this.player1.clickCard(this.mountaintopStatuary); expect(this.player1).toHavePrompt('Triggered Abilities'); expect(this.player1).toBeAbleToSelect(this.mountaintopStatuary); }); it('should let its controller play adjacent cards as if from hand', function() { this.bayushiLiar = this.player1.placeCardInProvince('bayushi-liar', 'province 1'); this.hiddenMoonDojo = this.player1.placeCardInProvince('hidden-moon-dojo', 'province 2'); this.bayushiManipulator = this.player1.placeCardInProvince('bayushi-manipulator', 'province 4'); this.player1.clickCard(this.bayushiLiar); expect(this.player1).toHavePrompt('Choose additional fate'); this.player1.clickPrompt('1'); expect(this.bayushiLiar.location).toBe('play area'); expect(this.bayushiLiar.fate).toBe(1); expect(this.player1.fate).toBe(5); }); it('should interact with Shosuro Miyako', function() { this.shosuroMiyako = this.player1.placeCardInProvince('shosuro-miyako'); this.hiddenMoonDojo = this.player1.placeCardInProvince('hidden-moon-dojo', 'province 2'); this.player1.clickCard(this.shosuroMiyako); this.player1.clickPrompt('0'); expect(this.player1).toHavePrompt('Triggered Abilities'); expect(this.player1).toBeAbleToSelect(this.shosuroMiyako); }); it('should let its controller play adjacent cards into the conflict', function() { this.bayushiLiar = this.player1.placeCardInProvince('bayushi-liar', 'province 1'); this.hiddenMoonDojo = this.player1.placeCardInProvince('hidden-moon-dojo', 'province 2'); this.bayushiManipulator = this.player1.placeCardInProvince('bayushi-manipulator', 'province 4'); this.noMoreActions(); this.initiateConflict({ type: 'political', attackers: ['fawning-diplomat'], defenders: [] }); this.player2.pass(); this.player1.clickCard(this.bayushiManipulator); expect(this.player1).toHavePrompt('Conflict Action Window'); this.player1.clickCard(this.bayushiLiar); expect(this.player1).toHavePrompt('Choose additional fate'); this.player1.clickPrompt('1'); expect(this.player1).toHavePrompt('Where do you wish to play this character?'); this.player1.clickPrompt('Conflict'); expect(this.bayushiLiar.location).toBe('play area'); expect(this.bayushiLiar.inConflict).toBe(true); expect(this.bayushiLiar.fate).toBe(1); expect(this.player1.fate).toBe(5); }); }); }); });
(function() { 'use strict'; angular .module('projectTask') .directive('datepickerValidationFix', datepickerValidationFix); function datepickerValidationFix() { return { restrict: 'A', require: 'mdDatepicker', link: function(scope, element, attrs, mdDatepickerCtrl) { mdDatepickerCtrl.$scope.$watch(function() { return mdDatepickerCtrl.minDate; }, function() { if (mdDatepickerCtrl.dateUtil.isValidDate(mdDatepickerCtrl.date)) { mdDatepickerCtrl.updateErrorState.call(mdDatepickerCtrl); } }); mdDatepickerCtrl.$scope.$watch(function() { return mdDatepickerCtrl.date; }, function() { mdDatepickerCtrl.updateErrorState.call(mdDatepickerCtrl); }); } }; } })();
"use strict"; // Definition of the application"s AngularJS module and routes // begins here. HTML5 history option is used to eliminate #hash // symbols in route URLs. var blogApp = angular.module("blogApp", ["ngRoute"]); blogApp.config([ "$routeProvider", "$locationProvider", function($routeProvider, $locationProvider) { $routeProvider .when("/home", { templateUrl: "templates/home.html", controller: "HomeController" }) .when("/", { redirectTo: "/home" }) .when("/create-blogger", { templateUrl: "templates/create-blogger.html", controller: "CreateBloggerController" }) .when("/create-post", { templateUrl: "templates/create-post.html", controller: "CreatePostController" }) .when("/read-post/:postid", { templateUrl: "templates/read-post.html", controller: "ReadPostController" }) .when("/list-bloggers", { templateUrl: "templates/list-bloggers.html", controller: "ListBloggersController" }) .when("/list-posts/:bloggerid", { templateUrl: "templates/list-posts.html", controller: "ListPostsController" }) .when("/update-blogger/:bloggerid", { templateUrl: "templates/update-blogger.html", controller: "UpdateBloggerController" }) .when("/update-post/:postid", { templateUrl: "templates/update-post.html", controller: "UpdatePostController" }) .when("/page-not-found", { templateUrl: "templates/page-not-found.html", controller: "PageNotFoundController" }) .otherwise({ redirectTo: "/home" }); // Use the HTML5 History API // https://scotch.io/tutorials/pretty-urls-in-angularjs-removing-the-hashtag $locationProvider.html5Mode(true); } ]);
//Better loop with magic attributes Handlebars.registerHelper ( 'loop', function ( context, fn, inverse) { var ret = ""; if ( context ) { if ( context instanceof Array && context.length < 1 ) { ret = inverse ( ret ); } else { var i = 0; for ( var attr in context ) { context [ attr ] [ '__key' ] = attr; context [ attr ] [ '__pos' ] = i++; ret = ret + fn ( context [ attr ] ); } } } else { ret = inverse ( ret ); } return ret; }); //"IF" style function Handlebars.registerHelper ( 'check', function( arg1, arg2, fn, inverse ) { if ( !arg2 ) { return Handlebars.helpers['if'].call(this, arg1, fn, inverse); } if ( arg1 == arg2 ) { return fn(this); } else { return inverse(this); } }); //"IF" style function Handlebars.registerHelper ( 'checknot', function(arg1, arg2, fn, inverse) { return Handlebars.helpers['check'].call(this, arg1, arg2, inverse, fn); }); //"IF" style function Handlebars.registerHelper ( 'indexOfZero', function( stack, needle, fn, inverse) { if ( stack && stack.indexOf ( needle ) === 0 ) { return fn(this); } else { return inverse(this); } }); //"IF" style function Handlebars.registerHelper ( 'haskey', function( arr, key, fn, inverse) { if ( arr && arr [ key ] ) { return fn(this); } else { return inverse(this); } }); //Quick "IF" Handlebars.registerHelper ( 'eq', function( arg1, arg2, ok, bad ) { if ( arg1 == arg2 ) { return new Handlebars.SafeString ( ok ); } return new Handlebars.SafeString ( bad ); } ); //Returns default if false Handlebars.registerHelper ( 'def', function ( val, def ) { if ( !val ) { return new Handlebars.SafeString ( def ); } return new Handlebars.SafeString ( val ); } ); //Truncates string Handlebars.registerHelper ( 'truncate', function ( str, len ) { var new_str = str.substr ( 0, len+1 ); while ( new_str.length ) { var ch = new_str.substr ( -1 ); new_str = new_str.substr ( 0, -1 ); if ( ch == ' ' ) { break; } } if ( new_str == '' ) { new_str = str.substr ( 0, len ); } return new Handlebars.SafeString ( new_str +'...' ); } ); //Use this with caution! Assign variable from template Handlebars.registerHelper ( 'assign', function () { var args = []; for ( var i=1,len=arguments.length; i<=len; i++) { if ( typeof ( arguments [ i ] ) === 'string' ) { args [ args.length ] = arguments [ i ]; } } Handlebars.registerHelper ( arguments [ 0 ], args.join ( '' ) ); return ''; } ); //Use this with caution! Unsets variable from template Handlebars.registerHelper ( 'unset', function ( variable ) { Handlebars.registerHelper ( variable, undefined ); return ''; } ); Handlebars.registerHelper ( 'br2nl', function( str ) { return new Handlebars.SafeString ( str.replace ( /<br\s?\/?>/g, "\n" ) ); }); Handlebars.registerHelper ( 'nl2br', function ( str ) { return new Handlebars.SafeString ( str.replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1<br />$2') ); } ); Handlebars.registerHelper ( 'dirname', function( str, assign ) { if ( str.indexOf ( '/' ) != 0 ) { str = '/' + str; } if ( typeof assign == 'string' ) { return Handlebars.helpers['assign'].call(this, assign, str.replace(/\\/g, '/').replace(/\/[^\/]*\/?$/, '') ); } else { return new Handlebars.SafeString ( str.replace(/\\/g, '/').replace(/\/[^\/]*\/?$/, '') ); } } ); //(name, num) or (num) Handlebars.registerHelper ( 'inc', function() { if ( arguments.length < 3 ) { return new Handlebars.SafeString ( parseInt ( arguments [ 0 ], 10 ) + 1 ); } else { var num = 0; if ( arguments [ 1 ] !== undefined ){ num = ( parseInt ( Number ( arguments [ 1 ] ), 10 ) + 1 ); } Handlebars.registerHelper ( arguments [ 0 ], num ); } } ); Handlebars.registerHelper ( 'join', function( arr, str ) { return new Handlebars.SafeString ( arr.join(str) ); } ); Handlebars.registerHelper ( 'ampify', function( str ) { if ( str && str != undefined ) { if ( !( typeof ( str ) == 'string' && isNaN( str ) ) ) { str = str.toString(); } return new Handlebars.SafeString ( str.replace ( /&/g, '&amp;' ) ); } return ''; } ); Handlebars.registerHelper ( 'entities_encode', function( str ) { if ( str && str != undefined ) { if ( !( typeof ( str ) == 'string' && isNaN( str ) ) ) { str = str.toString(); } return new Handlebars.SafeString ( str.replace ( /&/g, '&amp;' ).replace ( /</g, '&lt;' ).replace ( />/g, '&gt;' ) ); } return ''; } ); Handlebars.registerHelper ( 'entities_encode_unsafe', function( str ) { if ( str && str != undefined ) { if ( !( typeof ( str ) == 'string' && isNaN( str ) ) ) { str = str.toString(); } return str.replace ( /&/g, '&amp;' ); } return ''; } ); Handlebars.registerHelper ( 'entities_decode', function( str ) { if ( str && str != undefined ) { return new Handlebars.SafeString ( str.replace ( /&amp;/g, '&' ) ); } return ''; } ); Handlebars.registerHelper ( 'strip_tags', function( str ) { if ( str && str != undefined ) { var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi, commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi, allowed = ''; if ( str.replace ){ str = str.replace(commentsAndPhpTags, '').replace(tags, function ($0, $1) { return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : ''; }); } return new Handlebars.SafeString ( str ); } return ''; } ); Handlebars.registerHelper ( 'log', function( obj ) { console.log ( obj ); return ''; } ); Handlebars.registerHelper ( 'akey', function( ) { var name = arguments [ 0 ]; var arr = arguments [ 1 ]; for ( var i=2,len=arguments.length; i<len; i++) { if ( typeof ( arguments [ i ] ) == 'string' && arr != undefined ) { arr = arr [ arguments [ i ] ]; } } return Handlebars.registerHelper ( name, arr ); }); Handlebars.registerHelper ( 'getkey', function( ) { var name = arguments [ 0 ]; var arr = arguments [ 1 ]; for ( var i=2,len=arguments.length; i<len; i++) { if ( typeof ( arguments [ i ] ) == 'string' && arr != undefined ) { arr = arr [ arguments [ i ] ]; } } return arr; }); Handlebars.registerHelper ( 'substr', function( str, arg1, arg2 ) { return new Handlebars.SafeString ( str.substr(arg1, arg2) ); } ); Handlebars.registerHelper ( 'timestamp', function( str ) { return new Handlebars.SafeString ( new Date().getTime() ); }); Handlebars.registerHelper ( 'partial', function ( part ) { return new Handlebars.SafeString ( Handlebars.VM.invokePartial(Handlebars.partials [ part ], part, this, Handlebars.helpers, Handlebars.partials ) ); } );
angular.module('bookings.services', []) .factory('LoadingService', ['$ionicLoading', function($loading) { return { show: function(text) { text = text || '正在加载数据...' $loading.show({ template: '<ion-spinner icon="android" class="spinner"></ion-spinner>' + '<span>' + text + '</span>', hideOnStateChange : true }); }, hide: function() { $loading.hide(); } } }]) .factory('BookingsService', ['$http', '$q', 'LoadingService', 'bookingsConfig', function($http, $q, loading, config) { var sendRequest = function(action, params) { var defer = $q.defer(), url = config.BASE_URL + config.ACTION + action; params['d'] = +new Date(); $http.get(url, { params: params, timeout: 60* 1000 }).success(function(items) { defer.resolve(items); }).error(function() { loading.hide(); }); return defer.promise; }; return { // 获取指定医院的部门列表 getDepts: function(hostNo) { var params = { hosNo: hostNo }; return sendRequest(config.DEPT_ACTION_URL, params); }, // 获取指定医院下指定部门的医生列表 getDoctors: function(hostNo, deptNo, deptName) { var params = { hosNo: hostNo, deptNo: deptNo, deptName: deptName }; return sendRequest(config.DOCTER_ACTION_URL, params); }, // 获取医生的日程安排 getSchedulesForDoctor: function(hostNo, deptName, doctorName) { var params = { hosid: hostNo, docid: doctorName, deptid: deptName }; return sendRequest(config.DOCTER_SCHEDULE, params); }, // 获取用户预订记录 getRegHistory: function(cardNo, userName) { var params = { cardno: cardNo, type: 1, name: userName }; return sendRequest(config.USER_REG_LIST, params); }, // 校验一卡通卡号是否正确合法 validateCardNo: function(hostNo, cardNo) { var params = { hosNo: hostNo, hosCard: cardNo }; return sendRequest(config.VALID_CARD, params); }, // 预约医生 bookDoctor: function( params ){ return sendRequest(config.REG_URL, params); }, //取消预约 withDrawRegistration: function(hostNo, workflowId){ var params = { hosno: hostNo, workfloadid: workflowId }; return sendRequest(config.WITHDRAW_URL, params); } } } ]) .factory("storage", ["$window", function($window) { var storage = $window.localStorage; return { get: function(key) { var value = storage.getItem(key); try { value = JSON.parse(value); } catch (e) {} return value; }, set: function(key, value) { angular.isObject(value) && (value = JSON.stringify(value)); storage.setItem(key, value); }, remove: function( key ){ storage.removeItem(key); } } }]);
'use strict'; var cheerio = require('cheerio'); var sinon = require('sinon'); var expect = require('chai').expect; var BBPromise = require('bluebird'); var UserController = require('../../server/controllers/user_controller.js'); var OrganisationController = require('../../server/controllers/organisation_controller.js'); var mongoose = require('mongoose'); describe('routes: users', function () { describe('GET /users/{name}', function () { var response; var server = require('../../server/server.js').server; var $; before(function (done) { var user = { _id: '123456789', name: 'test', organisations: ['22222222222'], emailAddresses: [{address: 'email@test.com'}, {address: 'test@test.com'}] }; var organisationOne = { name: 'test-organisation-one', gitFolder: 'test folder' }; var organisationTwo = { name: 'test-organisation-two', gitFolder: 'test folder' }; sinon.stub(UserController, 'show').returns(new BBPromise(function (resolve) { resolve([user]); })); sinon.stub(OrganisationController, 'show').returns(new BBPromise(function (resolve) { resolve([organisationOne, organisationTwo]); })); server.inject({ method: 'GET', url: '/users/test' }, function (r) { response = r; $ = cheerio.load(response.result); done(); }); }); after(function (done) { UserController.show.restore(); OrganisationController.show.restore(); mongoose.disconnect(function () { delete mongoose.connection.db; done(); }); }); it('should return a 200 [ok] response', function () { expect(response.statusCode).to.equal(200); }); it('should display the users organisations', function () { expect(response.result).to.include('test-organisation-one'); expect(response.result).to.include('test-organisation-two'); }); it('should display the users email addresses', function () { expect(response.result).to.include('email@test.com'); expect(response.result).to.include('test@test.com'); }); }); describe('GET /users/new', function () { var response; var server = require('../../server/server.js').server; var $; before(function (done) { var organisationOne = { name: 'test-organisation-one', gitFolder: 'test folder' }; var organisationTwo = { name: 'test-organisation-two', gitFolder: 'test folder' }; sinon.stub(OrganisationController, 'index').returns(new BBPromise(function (resolve) { resolve([organisationOne, organisationTwo]); })); server.inject({ method: 'GET', url: '/users/new' }, function (r) { response = r; $ = cheerio.load(response.result); done(); }); }); after(function (done) { OrganisationController.index.restore(); mongoose.disconnect(function () { delete mongoose.connection.db; done(); }); }); it('should return a 200 [ok] response', function () { expect(response.statusCode).to.equal(200); }); it('should display a form', function () { expect($('form').length).to.equal(1); }); it('should submit the form to /users/create', function () { expect($('form').attr('action')).to.equal('/users/create'); }); it('should show dropdown for existing organisation in the form', function () { var organisations = $('form').find('select.dropdown option'); expect(organisations.length).to.equal(3); }); it('should show the existing organisations in the dropdown', function () { var organisations = $('form').find('select.dropdown option'); // the first drop down option is a '-' expect(organisations['1'].children[0].data).to.equal('test-organisation-one'); expect(organisations['2'].children[0].data).to.equal('test-organisation-two'); }); }); });
let DEFAULT_PATH_SEGMENT_SEPARATOR = '/'; /** * Class exposing some options that allow to control the formatting of path * when they are converted into String or parsed from String. */ export default class PathFormattingOptions { /** * */ constructor() { /** * Absolute path will be printed, as relative path, without the * first separator char at the start of the path. * * Does not affect parsing behavior. */ this.withoutRoot = false; /** * Path segment will be printed without pct-encoded characters. * * Does not affect parsing behavior. */ this.nonEncoded = false; /** * Character used to separate path segments. */ this.pathSegmentSeparator = DEFAULT_PATH_SEGMENT_SEPARATOR; } /** * Default formatting options. * * @return {PathFormattingOptions} default formatting options. */ static defaultOptions() { } }
// // Copyright (c) 2011 Mashery, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // 'Software'), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // // Module dependencies // var express = require('express'), util = require('util'), fs = require('fs'), OAuth = require('oauth').OAuth, query = require('querystring'), url = require('url'), http = require('http'), https = require('https'), crypto = require('crypto'), redis = require('redis'), RedisStore = require('connect-redis')(express); // Configuration try { var configJSON = fs.readFileSync(__dirname + "/config.json"); var config = JSON.parse(configJSON.toString()); } catch(e) { console.error("File config.json not found or is invalid. Try: `cp config.json.sample config.json`"); process.exit(1); } // // Redis connection // var defaultDB = '0'; var db; if (process.env.REDISTOGO_URL) { var rtg = require("url").parse(process.env.REDISTOGO_URL); db = require("redis").createClient(rtg.port, rtg.hostname); db.auth(rtg.auth.split(":")[1]); } else { db = redis.createClient(config.redis.port, config.redis.host); db.auth(config.redis.password); } db.on("error", function(err) { if (config.debug) { console.log("Error " + err); } }); // // Load API Configs // var apisConfig; fs.readFile('public/data/apiconfig.json', 'utf-8', function(err, data) { if (err) throw err; apisConfig = JSON.parse(data); if (config.debug) { console.log(util.inspect(apisConfig)); } }); var app = module.exports = express.createServer(); if (process.env.REDISTOGO_URL) { var rtg = require("url").parse(process.env.REDISTOGO_URL); config.redis.host = rtg.hostname; config.redis.port = rtg.port; config.redis.password = rtg.auth.split(":")[1]; } app.configure(function() { app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(express.logger()); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.cookieParser()); app.use(express.session({ secret: config.sessionSecret, store: new RedisStore({ 'host': config.redis.host, 'port': config.redis.port, 'pass': config.redis.password, 'maxAge': 1209600000 }) })); app.use(app.router); app.use(express.static(__dirname + '/public')); }); app.configure('development', function() { app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); }); app.configure('production', function() { app.use(express.errorHandler()); }); // // Middleware // function oauth(req, res, next) { console.log('OAuth process started'); var apiName = req.body.apiName, apiConfig = apisConfig[apiName]; if (apiConfig.oauth) { var apiKey = req.body.apiKey || req.body.key, apiSecret = req.body.apiSecret || req.body.secret, refererURL = url.parse(req.headers.referer), callbackURL = refererURL.protocol + '//' + refererURL.host + '/authSuccess/' + apiName, oa = new OAuth(apiConfig.oauth.requestURL, apiConfig.oauth.accessURL, apiKey, apiSecret, apiConfig.oauth.version, callbackURL, apiConfig.oauth.crypt); if (config.debug) { console.log('OAuth type: ' + apiConfig.oauth.type); console.log('Method security: ' + req.body.oauth); console.log('Session authed: ' + req.session[apiName]); console.log('apiKey: ' + apiKey); console.log('apiSecret: ' + apiSecret); }; // Check if the API even uses OAuth, then if the method requires oauth, then if the session is not authed if (apiConfig.oauth.type == 'three-legged' && req.body.oauth == 'authrequired' && (!req.session[apiName] || !req.session[apiName].authed) ) { if (config.debug) { console.log('req.session: ' + util.inspect(req.session)); console.log('headers: ' + util.inspect(req.headers)); console.log(util.inspect(oa)); // console.log(util.inspect(req)); console.log('sessionID: ' + util.inspect(req.sessionID)); // console.log(util.inspect(req.sessionStore)); }; oa.getOAuthRequestToken(function(err, oauthToken, oauthTokenSecret, results) { if (err) { res.send("Error getting OAuth request token : " + util.inspect(err), 500); } else { // Unique key using the sessionID and API name to store tokens and secrets var key = req.sessionID + ':' + apiName; db.set(key + ':apiKey', apiKey, redis.print); db.set(key + ':apiSecret', apiSecret, redis.print); db.set(key + ':requestToken', oauthToken, redis.print); db.set(key + ':requestTokenSecret', oauthTokenSecret, redis.print); // Set expiration to same as session db.expire(key + ':apiKey', 1209600000); db.expire(key + ':apiSecret', 1209600000); db.expire(key + ':requestToken', 1209600000); db.expire(key + ':requestTokenSecret', 1209600000); // res.header('Content-Type', 'application/json'); res.send({ 'signin': apiConfig.oauth.signinURL + oauthToken }); } }); } else if (apiConfig.oauth.type == 'two-legged' && req.body.oauth == 'authrequired') { // Two legged stuff... for now nothing. next(); } else { next(); } } else { next(); } } // // OAuth Success! // function oauthSuccess(req, res, next) { var oauthRequestToken, oauthRequestTokenSecret, apiKey, apiSecret, apiName = req.params.api, apiConfig = apisConfig[apiName], key = req.sessionID + ':' + apiName; // Unique key using the sessionID and API name to store tokens and secrets if (config.debug) { console.log('apiName: ' + apiName); console.log('key: ' + key); console.log(util.inspect(req.params)); }; db.mget([ key + ':requestToken', key + ':requestTokenSecret', key + ':apiKey', key + ':apiSecret' ], function(err, result) { if (err) { console.log(util.inspect(err)); } oauthRequestToken = result[0], oauthRequestTokenSecret = result[1], apiKey = result[2], apiSecret = result[3]; if (config.debug) { console.log(util.inspect(">>"+oauthRequestToken)); console.log(util.inspect(">>"+oauthRequestTokenSecret)); console.log(util.inspect(">>"+req.query.oauth_verifier)); }; var oa = new OAuth(apiConfig.oauth.requestURL, apiConfig.oauth.accessURL, apiKey, apiSecret, apiConfig.oauth.version, null, apiConfig.oauth.crypt); if (config.debug) { console.log(util.inspect(oa)); }; oa.getOAuthAccessToken(oauthRequestToken, oauthRequestTokenSecret, req.query.oauth_verifier, function(error, oauthAccessToken, oauthAccessTokenSecret, results) { if (error) { res.send("Error getting OAuth access token : " + util.inspect(error) + "["+oauthAccessToken+"]"+ "["+oauthAccessTokenSecret+"]"+ "["+util.inspect(results)+"]", 500); } else { if (config.debug) { console.log('results: ' + util.inspect(results)); }; db.mset([key + ':accessToken', oauthAccessToken, key + ':accessTokenSecret', oauthAccessTokenSecret ], function(err, results2) { req.session[apiName] = {}; req.session[apiName].authed = true; if (config.debug) { console.log('session[apiName].authed: ' + util.inspect(req.session)); }; next(); }); } }); }); } // // processRequest - handles API call // function processRequest(req, res, next) { if (config.debug) { console.log(util.inspect(req.body, null, 3)); }; var reqQuery = req.body, params = reqQuery.params || {}, methodURL = reqQuery.methodUri, httpMethod = reqQuery.httpMethod, apiKey = reqQuery.apiKey, apiSecret = reqQuery.apiSecret, apiName = reqQuery.apiName apiConfig = apisConfig[apiName], key = req.sessionID + ':' + apiName; // Replace placeholders in the methodURL with matching params for (var param in params) { if (params.hasOwnProperty(param)) { if (params[param] !== '') { // URL params are prepended with ":" var regx = new RegExp(':' + param); // If the param is actually a part of the URL, put it in the URL and remove the param if (!!regx.test(methodURL)) { methodURL = methodURL.replace(regx, params[param]); delete params[param] } } else { delete params[param]; // Delete blank params } } } var baseHostInfo = apiConfig.baseURL.split(':'); var baseHostUrl = baseHostInfo[0], baseHostPort = (baseHostInfo.length > 1) ? baseHostInfo[1] : ""; var paramString = query.stringify(params), privateReqURL = apiConfig.protocol + '://' + apiConfig.baseURL + apiConfig.privatePath + methodURL + ((paramString.length > 0) ? '?' + paramString : ""), options = { headers: {}, protocol: apiConfig.protocol + ':', host: baseHostUrl, port: baseHostPort, method: httpMethod, path: apiConfig.publicPath + methodURL// + ((paramString.length > 0) ? '?' + paramString : "") }; if (['POST','DELETE','PUT'].indexOf(httpMethod) !== -1) { var requestBody = query.stringify(params); } if (apiConfig.oauth) { console.log('Using OAuth'); // Three legged OAuth if (apiConfig.oauth.type == 'three-legged' && (reqQuery.oauth == 'authrequired' || (req.session[apiName] && req.session[apiName].authed))) { if (config.debug) { console.log('Three Legged OAuth'); }; db.mget([key + ':apiKey', key + ':apiSecret', key + ':accessToken', key + ':accessTokenSecret' ], function(err, results) { var apiKey = (typeof reqQuery.apiKey == "undefined" || reqQuery.apiKey == "undefined")?results[0]:reqQuery.apiKey, apiSecret = (typeof reqQuery.apiSecret == "undefined" || reqQuery.apiSecret == "undefined")?results[1]:reqQuery.apiSecret, accessToken = results[2], accessTokenSecret = results[3]; console.log(apiKey); console.log(apiSecret); console.log(accessToken); console.log(accessTokenSecret); var oa = new OAuth(apiConfig.oauth.requestURL || null, apiConfig.oauth.accessURL || null, apiKey || null, apiSecret || null, apiConfig.oauth.version || null, null, apiConfig.oauth.crypt); if (config.debug) { console.log('Access token: ' + accessToken); console.log('Access token secret: ' + accessTokenSecret); console.log('key: ' + key); }; oa.getProtectedResource(privateReqURL, httpMethod, accessToken, accessTokenSecret, function (error, data, response) { req.call = privateReqURL; // console.log(util.inspect(response)); if (error) { console.log('Got error: ' + util.inspect(error)); if (error.data == 'Server Error' || error.data == '') { req.result = 'Server Error'; } else { req.result = error.data; } res.statusCode = error.statusCode next(); } else { req.resultHeaders = response.headers; req.result = JSON.parse(data); next(); } }); } ); } else if (apiConfig.oauth.type == 'two-legged' && reqQuery.oauth == 'authrequired') { // Two-legged if (config.debug) { console.log('Two Legged OAuth'); }; var body, oa = new OAuth(null, null, apiKey || null, apiSecret || null, apiConfig.oauth.version || null, null, apiConfig.oauth.crypt); var resource = options.protocol + '://' + options.host + options.path, cb = function(error, data, response) { if (error) { if (error.data == 'Server Error' || error.data == '') { req.result = 'Server Error'; } else { console.log(util.inspect(error)); body = error.data; } res.statusCode = error.statusCode; } else { console.log(util.inspect(data)); var responseContentType = response.headers['content-type']; switch (true) { case /application\/javascript/.test(responseContentType): case /text\/javascript/.test(responseContentType): case /application\/json/.test(responseContentType): body = JSON.parse(data); break; case /application\/xml/.test(responseContentType): case /text\/xml/.test(responseContentType): default: } } // Set Headers and Call if (response) { req.resultHeaders = response.headers || 'None'; } else { req.resultHeaders = req.resultHeaders || 'None'; } req.call = url.parse(options.host + options.path); req.call = url.format(req.call); // Response body req.result = body; next(); }; switch (httpMethod) { case 'GET': console.log(resource); oa.get(resource, '', '',cb); break; case 'PUT': case 'POST': oa.post(resource, '', '', JSON.stringify(obj), null, cb); break; case 'DELETE': oa.delete(resource,'','',cb); break; } } else { // API uses OAuth, but this call doesn't require auth and the user isn't already authed, so just call it. unsecuredCall(); } } else { // API does not use authentication unsecuredCall(); } // Unsecured API Call helper function unsecuredCall() { console.log('Unsecured Call'); if (['POST','PUT','DELETE'].indexOf(httpMethod) === -1) { options.path += ((paramString.length > 0) ? '?' + paramString : ""); } // Add API Key to params, if any. if (apiKey != '' && apiKey != 'undefined' && apiKey != undefined) { if (options.path.indexOf('?') !== -1) { options.path += '&'; } else { options.path += '?'; } options.path += apiConfig.keyParam + '=' + apiKey; } // Perform signature routine, if any. if (apiConfig.signature) { if (apiConfig.signature.type == 'signed_md5') { // Add signature parameter var timeStamp = Math.round(new Date().getTime()/1000); var sig = crypto.createHash('md5').update('' + apiKey + apiSecret + timeStamp + '').digest(apiConfig.signature.digest); options.path += '&' + apiConfig.signature.sigParam + '=' + sig; } else if (apiConfig.signature.type == 'signed_sha256') { // sha256(key+secret+epoch) // Add signature parameter var timeStamp = Math.round(new Date().getTime()/1000); var sig = crypto.createHash('sha256').update('' + apiKey + apiSecret + timeStamp + '').digest(apiConfig.signature.digest); options.path += '&' + apiConfig.signature.sigParam + '=' + sig; } } // Setup headers, if any if (reqQuery.headerNames && reqQuery.headerNames.length > 0) { if (config.debug) { console.log('Setting headers'); }; var headers = {}; for (var x = 0, len = reqQuery.headerNames.length; x < len; x++) { if (config.debug) { console.log('Setting header: ' + reqQuery.headerNames[x] + ':' + reqQuery.headerValues[x]); }; if (reqQuery.headerNames[x] != '') { headers[reqQuery.headerNames[x]] = reqQuery.headerValues[x]; } } options.headers = headers; } if (!options.headers['Content-Length']) { if (requestBody) { options.headers['Content-Length'] = requestBody.length; } else { options.headers['Content-Length'] = 0; } } if (requestBody) { options.headers['Content-Type'] = 'application/x-www-form-urlencoded'; } if (config.debug) { console.log(util.inspect(options)); }; var doRequest; if (options.protocol === 'https' || options.protocol === 'https:') { console.log('Protocol: HTTPS'); options.protocol = 'https:' doRequest = https.request; } else { console.log('Protocol: HTTP'); doRequest = http.request; } // API Call. response is the response from the API, res is the response we will send back to the user. var apiCall = doRequest(options, function(response) { response.setEncoding('utf-8'); if (config.debug) { console.log('HEADERS: ' + JSON.stringify(response.headers)); console.log('STATUS CODE: ' + response.statusCode); }; res.statusCode = response.statusCode; var body = ''; response.on('data', function(data) { body += data; }) response.on('end', function() { delete options.agent; var responseContentType = response.headers['content-type']; switch (true) { case /application\/javascript/.test(responseContentType): case /application\/json/.test(responseContentType): console.log(util.inspect(body)); // body = JSON.parse(body); break; case /application\/xml/.test(responseContentType): case /text\/xml/.test(responseContentType): default: } // Set Headers and Call req.resultHeaders = response.headers; req.call = url.parse(options.host + options.path); req.call = url.format(req.call); // Response body req.result = body; console.log(util.inspect(body)); next(); }) }).on('error', function(e) { if (config.debug) { console.log('HEADERS: ' + JSON.stringify(res.headers)); console.log("Got error: " + e.message); console.log("Error: " + util.inspect(e)); }; }); if (requestBody) { apiCall.end(requestBody, 'utf-8'); } else { apiCall.end(); } } } // Dynamic Helpers // Passes variables to the view app.dynamicHelpers({ session: function(req, res) { // If api wasn't passed in as a parameter, check the path to see if it's there if (!req.params.api) { pathName = req.url.replace('/',''); // Is it a valid API - if there's a config file we can assume so fs.stat('public/data/' + pathName + '.json', function (error, stats) { if (stats) { req.params.api = pathName; } }); } // If the cookie says we're authed for this particular API, set the session to authed as well if (req.params.api && req.session[req.params.api] && req.session[req.params.api]['authed']) { req.session['authed'] = true; } return req.session; }, apiInfo: function(req, res) { if (req.params.api) { return apisConfig[req.params.api]; } else { return apisConfig; } }, apiName: function(req, res) { if (req.params.api) { return req.params.api; } }, apiDefinition: function(req, res) { if (req.params.api) { var data = fs.readFileSync('public/data/' + req.params.api + '.json'); return JSON.parse(data); } } }) // // Routes // app.get('/', function(req, res) { res.render('listAPIs', { title: config.title }); }); // Process the API request app.post('/processReq', oauth, processRequest, function(req, res) { var result = { headers: req.resultHeaders, response: req.result, call: req.call }; res.send(result); }); // Just auth app.all('/auth', oauth); // OAuth callback page, closes the window immediately after storing access token/secret app.get('/authSuccess/:api', oauthSuccess, function(req, res) { res.render('authSuccess', { title: 'OAuth Successful' }); }); app.post('/upload', function(req, res) { console.log(req.body.user); res.redirect('back'); }); // API shortname, all lowercase app.get('/:api([^\.]+)', function(req, res) { res.render('api'); }); // Only listen on $ node app.js if (!module.parent) { var port = process.env.PORT || config.port; app.listen(port); console.log("Express server listening on port %d", app.address().port); }
const errors = { espree: ["class-property.js"], }; run_spec(__dirname, ["babel", "flow", "typescript"], { errors, }); run_spec(__dirname, ["babel", "flow", "typescript"], { trailingComma: "all", errors, }); run_spec(__dirname, ["babel", "flow", "typescript"], { arrowParens: "always", errors, });
if(!process.env['TEST_VERSIONS'] || process.env['TEST_VERSIONS'] != 'generated_project') { process.exit(); } var fs = require('fs'); var ejs = require('ejs'); var options = { name: "Test1", author: "JB", nameSlug: "test-1", nameCamel: "Test1", projectType: "fe", has_jquery: true, has_jquery_vendor_config: false, } var file = fs.readFileSync('../generators/app/templates/package.json', 'utf8'); var generatedFile = ejs.render(file, options); fs.writeFileSync('generated_project/package.json', generatedFile);
/******************************* Build Task *******************************/ var gulp = require('gulp'), // node dependencies console = require('better-console'), fs = require('fs'), // gulp dependencies autoprefixer = require('gulp-autoprefixer'), chmod = require('gulp-chmod'), clone = require('gulp-clone'), flatten = require('gulp-flatten'), gulpif = require('gulp-if'), less = require('gulp-less'), plumber = require('gulp-plumber'), print = require('gulp-print'), rename = require('gulp-rename'), replace = require('gulp-replace'), runSequence = require('run-sequence'), // config config = require('../config/user'), tasks = require('../config/tasks'), install = require('../config/project/install'), // shorthand globs = config.globs, assets = config.paths.assets, output = config.paths.output, source = config.paths.source, banner = tasks.banner, comments = tasks.regExp.comments, log = tasks.log, settings = tasks.settings ; // add internal tasks (concat release) require('../collections/internal')(gulp); module.exports = function(callback) { var tasksCompleted = 0, maybeCallback = function() { tasksCompleted++; if(tasksCompleted === 1) { callback(); } }, stream, uncompressedStream ; console.info('Building CSS'); if( !install.isSetup() ) { console.error('Cannot build files. Run "gulp install" to set-up Semantic'); return; } // unified css stream stream = gulp.src(source.definitions + '/**/' + globs.components + '.less') .pipe(plumber(settings.plumber.less)) .pipe(less(settings.less)) .pipe(autoprefixer(settings.prefix)) .pipe(replace(comments.variables.in, comments.variables.out)) .pipe(replace(comments.license.in, comments.license.out)) .pipe(replace(comments.large.in, comments.large.out)) .pipe(replace(comments.small.in, comments.small.out)) .pipe(replace(comments.tiny.in, comments.tiny.out)) .pipe(flatten()) ; // two concurrent streams from same source to concat release uncompressedStream = stream.pipe(clone()); // uncompressed component css uncompressedStream .pipe(plumber()) .pipe(replace(assets.source, assets.uncompressed)) .pipe(gulpif(config.hasPermission, chmod(config.permission))) .pipe(gulp.dest(output.uncompressed)) .pipe(print(log.created)) .on('end', function() { runSequence('package uncompressed css', maybeCallback); }) ; };
import {Object} from 'j0'; export default Object.freeze;
/* jshint expr:true */ 'use strict'; /*! * node-bb10 * Copyright(c) 2013 Endare bvba <info@endare.com> * MIT Licensed * * * This file runs all the tests of the library * * @author Sam Verschueren <sam.verschueren@gmail.com> * @since 20 Mar. 2015 */ var chai = require('chai'), sinon = require('sinon'), sinonChai = require('sinon-chai'), https = require('https'); var should = chai.should(); chai.use(sinonChai); // library var bb10 = require('../index'), PushMessage = bb10.PushMessage, PushInitiator = bb10.PushInitiator, constants = require('../lib/Constants'); describe('node-bb10', function() { describe('Constants', function() { it('Should have a boundary that is equal to \'PMasdfglkjhqwert\'', function() { constants.BOUNDARY.should.be.equal('PMasdfglkjhqwert'); }); it('Should have \'\\r\\n\' as new line separator', function() { constants.NEW_LINE.should.be.equal('\r\n'); }); it('Should have the correct eval URL', function() { constants.EVAL_URL.should.be.equal('pushapi.eval.blackberry.com'); }); it('Should have the correct production URL', function() { constants.PRODUCTION_URL.should.be.equal('pushapi.na.blackberry.com'); }); }); describe('PushMessage', function() { describe('#constructor', function() { it('Should throw an error if no ID is provided', function() { PushMessage.bind(PushMessage).should.throw(Error); }); it('Should throw an error if an empty ID is provided', function() { PushMessage.bind(PushMessage, '').should.throw(Error); }); it('Should set the ID of it is provided', function() { var message = new PushMessage('test-id'); message.id.should.be.equal('test-id'); }); it('Should trim the whitespace of the ID', function() { var message = new PushMessage(' test-id '); message.id.should.be.equal('test-id'); }); it('Should set a blank message if no message is provided', function() { var message = new PushMessage('test-id'); message.message.should.be.equal(''); }); it('Should set the message if one is provided', function() { var message = new PushMessage('test-id', 'Hello World'); message.message.should.be.equal('Hello World'); }); it('Should set the delivery method to \'notspecified\'', function() { var message = new PushMessage('test-id', 'Hello World'); message.deliveryMethod.should.be.equal('notspecified'); }); it('Should have an empty list of recipients', function() { var message = new PushMessage('test-id', 'Hello World'); message.recipients.should.have.length(0); }); }); describe('#setMessage', function() { var message; beforeEach(function() { // Be sure to create a new message every time message = new PushMessage('test-id'); }); it('Should set the message correctly', function() { message.setMessage('hello message'); message.message.should.be.equal('hello message'); }); it('Should set a blank message if undefined is passed in as parameter', function() { message.setMessage(undefined); message.message.should.be.equal(''); }); }); describe('#setDeliveryMethod', function() { var message; beforeEach(function() { // Be sure to create a new message every time message = new PushMessage('test-id'); }); it('Should throw an error if the delivery method does not exist', function() { message.setDeliveryMethod.bind(message, 'unknownmethod').should.throw(Error); }); it('Should not throw an error if the delivery method is \'confirmed\'', function() { message.setDeliveryMethod.bind(message, 'confirmed').should.not.throw(Error); }); it('Should not throw an error if the delivery method is \'preferconfirmed\'', function() { message.setDeliveryMethod.bind(message, 'preferconfirmed').should.not.throw(Error); }); it('Should not throw an error if the delivery method is \'unconfirmed\'', function() { message.setDeliveryMethod.bind(message, 'preferconfirmed').should.not.throw(Error); }); it('Should not throw an error if the delivery method is \'unconfirmed\'', function() { message.setDeliveryMethod.bind(message, 'notspecified').should.not.throw(Error); }); it('Should set the delivery method to \'unconfirmed\'', function() { message.setDeliveryMethod('unconfirmed'); message.deliveryMethod.should.be.equal('unconfirmed'); }); }); describe('#addRecipient', function() { var message; beforeEach(function() { // Be sure to create a new message every time message = new PushMessage('test-id'); }); it('Should add one recipient to the list', function() { message.addRecipient('FFFFFFFF'); message.recipients.should.have.length(1); }); it('Should add the recipient \'FFFFFFFF\' to the list', function() { message.addRecipient('FFFFFFFF'); message.recipients[0].should.be.equal('FFFFFFFF'); }); it('Should add two recipients to the list if it is called twice with different tokens', function() { message.addRecipient('FFFFFFFF'); message.addRecipient('AAAAAAAA'); message.recipients.should.have.length(2); }); it('Should only have one recipient if it is called twice with the same token', function() { message.addRecipient('FFFFFFFF'); message.addRecipient('FFFFFFFF'); message.recipients.should.have.length(1); }); }); describe('#addAllRecipients', function() { var message; beforeEach(function() { // Be sure to create a new message every time message = new PushMessage('test-id'); }); it('Should throw an error if the argument provided is not an array', function() { message.addAllRecipients.bind(message, 'FFFFFFFF').should.throw(Error); }); it('Should add two recipients to the recipients list', function() { message.addAllRecipients(['AAAAAAAA', 'FFFFFFFF']); message.recipients.should.have.length(2); }); it('Should only add unique recipients', function() { message.addAllRecipients(['AAAAAAAA', 'FFFFFFFF', 'AAAAAAAA']); message.recipients.should.have.length(2); }); it('Should just append the recipients if it called twice', function() { message.addAllRecipients(['AAAAAAAA', 'FFFFFFFF']); message.addAllRecipients(['BBBBBBBB', 'CCCCCCCC']); message.recipients.should.have.length(4); }); }); describe('#clearRecipients', function() { var message; beforeEach(function() { // Be sure to create a new message every time message = new PushMessage('test-id'); message.addAllRecipients(['AAAAAAAA', 'FFFFFFFF']); }); it('Should clear the list of recipients', function() { message.clearRecipients(); message.recipients.should.have.length(0); }); }); describe('#toPAPMessage', function() { var message; beforeEach(function() { // Be sure to create a new message every time message = new PushMessage('test-id', 'Message content'); message.addRecipient('AAAAAAAA'); }); it('Should throw an error if no recipients are added to the message', function() { message.clearRecipients(); message.toPAPMessage.bind(message).should.throw(Error); }); it('Should convert to the correct PAP message with only one recipient', function() { var result = message.toPAPMessage({ "source-reference": "applicationID", "deliver-before-timestamp": "2015-05-21T12:00:00Z" }); var pap = [ '--PMasdfglkjhqwert', 'Content-Type: application/xml; charset=UTF-8', '', '<?xml version="1.0"?>', '<!DOCTYPE pap PUBLIC "-//WAPFORUM//DTD PAP 2.1//EN" "http://www.openmobilealliance.org/tech/DTD/pap_2.1.dtd">', '<pap>', ' <push-message push-id="test-id" source-reference="applicationID" deliver-before-timestamp="2015-05-21T12:00:00Z">', ' <address address-value="AAAAAAAA" />', ' <quality-of-service delivery-method="notspecified" />', ' </push-message>', '</pap>', '--PMasdfglkjhqwert', 'Content-Encoding: binary', 'Content-Type: text/html', 'Push-Message-ID: test-id', '', 'Message content', '', '--PMasdfglkjhqwert--', constants.NEW_LINE ]; result.should.be.equal(pap.join(constants.NEW_LINE)); }); it('Should convert to the correct PAP message with two recipients', function() { message.addAllRecipients(['AAAAAAAA', 'FFFFFFFF']); var result = message.toPAPMessage({ "source-reference": "applicationID", "deliver-before-timestamp": "2015-05-21T12:00:00Z" }); var pap = [ '--PMasdfglkjhqwert', 'Content-Type: application/xml; charset=UTF-8', '', '<?xml version="1.0"?>', '<!DOCTYPE pap PUBLIC "-//WAPFORUM//DTD PAP 2.1//EN" "http://www.openmobilealliance.org/tech/DTD/pap_2.1.dtd">', '<pap>', ' <push-message push-id="test-id" source-reference="applicationID" deliver-before-timestamp="2015-05-21T12:00:00Z">', ' <address address-value="AAAAAAAA" />', ' <address address-value="FFFFFFFF" />', ' <quality-of-service delivery-method="notspecified" />', ' </push-message>', '</pap>', '--PMasdfglkjhqwert', 'Content-Encoding: binary', 'Content-Type: text/html', 'Push-Message-ID: test-id', '', 'Message content', '', '--PMasdfglkjhqwert--', constants.NEW_LINE ]; result.should.be.equal(pap.join(constants.NEW_LINE)); }); it('Should convert to the correct PAP message when setting a different message', function() { message.setMessage('This is another message'); var result = message.toPAPMessage({ "source-reference": "applicationID", "deliver-before-timestamp": "2015-05-21T12:00:00Z" }); var pap = [ '--PMasdfglkjhqwert', 'Content-Type: application/xml; charset=UTF-8', '', '<?xml version="1.0"?>', '<!DOCTYPE pap PUBLIC "-//WAPFORUM//DTD PAP 2.1//EN" "http://www.openmobilealliance.org/tech/DTD/pap_2.1.dtd">', '<pap>', ' <push-message push-id="test-id" source-reference="applicationID" deliver-before-timestamp="2015-05-21T12:00:00Z">', ' <address address-value="AAAAAAAA" />', ' <quality-of-service delivery-method="notspecified" />', ' </push-message>', '</pap>', '--PMasdfglkjhqwert', 'Content-Encoding: binary', 'Content-Type: text/html', 'Push-Message-ID: test-id', '', 'This is another message', '', '--PMasdfglkjhqwert--', constants.NEW_LINE ]; result.should.be.equal(pap.join(constants.NEW_LINE)); }); it('Should convert to the correct PAP message with another delivery method', function() { message.setDeliveryMethod('unconfirmed'); var result = message.toPAPMessage({ "source-reference": "applicationID", "deliver-before-timestamp": "2015-05-21T12:00:00Z" }); var pap = [ '--PMasdfglkjhqwert', 'Content-Type: application/xml; charset=UTF-8', '', '<?xml version="1.0"?>', '<!DOCTYPE pap PUBLIC "-//WAPFORUM//DTD PAP 2.1//EN" "http://www.openmobilealliance.org/tech/DTD/pap_2.1.dtd">', '<pap>', ' <push-message push-id="test-id" source-reference="applicationID" deliver-before-timestamp="2015-05-21T12:00:00Z">', ' <address address-value="AAAAAAAA" />', ' <quality-of-service delivery-method="unconfirmed" />', ' </push-message>', '</pap>', '--PMasdfglkjhqwert', 'Content-Encoding: binary', 'Content-Type: text/html', 'Push-Message-ID: test-id', '', 'Message content', '', '--PMasdfglkjhqwert--', constants.NEW_LINE ]; result.should.be.equal(pap.join(constants.NEW_LINE)); }); it('Should convert to the correct PAP message with another ID, recipient and message', function() { message = new PushMessage('my-message-id', 'Hello World'); message.addRecipient('BBBBBBBB'); var result = message.toPAPMessage({ "source-reference": "source-refID", "deliver-before-timestamp": "2015-05-21T16:00:00Z" }); var pap = [ '--PMasdfglkjhqwert', 'Content-Type: application/xml; charset=UTF-8', '', '<?xml version="1.0"?>', '<!DOCTYPE pap PUBLIC "-//WAPFORUM//DTD PAP 2.1//EN" "http://www.openmobilealliance.org/tech/DTD/pap_2.1.dtd">', '<pap>', ' <push-message push-id="my-message-id" source-reference="source-refID" deliver-before-timestamp="2015-05-21T16:00:00Z">', ' <address address-value="BBBBBBBB" />', ' <quality-of-service delivery-method="notspecified" />', ' </push-message>', '</pap>', '--PMasdfglkjhqwert', 'Content-Encoding: binary', 'Content-Type: text/html', 'Push-Message-ID: my-message-id', '', 'Hello World', '', '--PMasdfglkjhqwert--', constants.NEW_LINE ]; result.should.be.equal(pap.join(constants.NEW_LINE)); }); }); }); describe('PushInitiator', function() { describe('#constructor', function() { it('Should set the evaluation to false if is not provided', function() { var initiator = new PushInitiator('appID', 'pwd', 'cpid'); initiator.isEvaluation.should.be.equal(false); }); it('Should set the evaluation to true if is explicitly set to true', function() { var initiator = new PushInitiator('appID', 'pwd', 'cpid', true); initiator.isEvaluation.should.be.equal(true); }); }); }); });
version https://git-lfs.github.com/spec/v1 oid sha256:aa442f1bc126171f12d93e8a97d2bf92fbb38d7773e392c265d41c11ccf7a4eb size 65862
'use strict'; (function () { var utils = require('./utils'); var VALID_CHILD_NODES = [ 'arg', 'flag', 'kwarg', 'command' ]; function RequireAll () { var children = utils.argsToArray(arguments); if (!children.length) { throw new Error('No child nodes supplied to RequireAll node'); } if (children.length < 2) { throw new Error('Only one child node supplied to RequireAll node. Use Require node'); } utils.validateChildren(children, VALID_CHILD_NODES); return { _type: 'require-all', children: children }; } module.exports = RequireAll; })();
// ==UserScript== // @name Agar.io Expose // @version 6.0 // @namespace xzfc // @updateURL https://raw.githubusercontent.com/xzfc/agar-expose/master/expose.user.js // @match http://agar.io/* // @match http://ogar.mivabe.nl/?ip=* // @run-at document-start // @grant GM_xmlhttpRequest // @grant unsafeWindow // ==/UserScript== window.stop() document.documentElement.innerHTML = null GM_xmlhttpRequest({method: "GET", url: "http://72.k.vu/out.html", onload: e => { document.open() document.write(e.responseText) document.close() }})
import 'core-js/fn/array/find'; import RcModule from '../../lib/RcModule'; import getRegionSettingsReducer, { getCountryCodeReducer, getAreaCodeReducer, } from './getRegionSettingsReducer'; import moduleStatuses from '../../enums/moduleStatuses'; import regionSettingsMessages from '../RegionSettings/regionSettingsMessages'; import actionTypes from './actionTypes'; import validateAreaCode from '../../lib/validateAreaCode'; import proxify from '../../lib/proxy/proxify'; export default class RegionSettings extends RcModule { constructor({ storage, extensionInfo, dialingPlan, alert, tabManager, ...options, }) { super({ ...options, actionTypes, }); this._storage = storage; this._alert = alert; this._dialingPlan = dialingPlan; this._extensionInfo = extensionInfo; this._tabManager = tabManager; this._countryCodeKey = 'regionSettingsCountryCode'; this._areaCodeKey = 'regionSettingsAreaCode'; this._reducer = getRegionSettingsReducer(this.actionTypes); this._storage.registerReducer({ key: this._countryCodeKey, reducer: getCountryCodeReducer(this.actionTypes), }); this._storage.registerReducer({ key: this._areaCodeKey, reducer: getAreaCodeReducer(this.actionTypes), }); } initialize() { let plans; this.store.subscribe(async () => { if ( this._storage.ready && this._dialingPlan.ready && this._extensionInfo.ready && this.status === moduleStatuses.pending ) { this.store.dispatch({ type: this.actionTypes.init, }); if (!this._tabManager || this._tabManager.active) { await this.checkRegionSettings(); } plans = this._dialingPlan.plans; this.store.dispatch({ type: this.actionTypes.initSuccess, }); } else if ( !this._storage.ready && this.ready ) { this.store.dispatch({ type: this.actionTypes.resetSuccess, }); } else if ( this.ready && plans !== this._dialingPlan.plans ) { plans = this._dialingPlan.plans; if (!this._tabManager || this._tabManager.active) { await this.checkRegionSettings(); } } }); } get status() { return this.state.status; } get ready() { return this.state.status === moduleStatuses.ready; } get availableCountries() { return this._dialingPlan.plans; } @proxify async checkRegionSettings() { let countryCode = this._storage.getItem(this._countryCodeKey); if (countryCode && !this._dialingPlan.plans.find(plan => ( plan.isoCode === countryCode ))) { countryCode = null; this._alert.warning({ message: regionSettingsMessages.dialingPlansChanged, ttl: 0 }); } if (!countryCode) { countryCode = this._dialingPlan.plans.find(plan => ( plan.isoCode === this._extensionInfo.country.isoCode )).isoCode; this.store.dispatch({ type: this.actionTypes.setData, countryCode, areaCode: '', }); } } @proxify async setData({ areaCode, countryCode, }) { if (!validateAreaCode(areaCode)) { this._alert.danger({ message: regionSettingsMessages.areaCodeInvalid, }); return; } this.store.dispatch({ type: this.actionTypes.setData, countryCode, areaCode: areaCode && areaCode.trim(), }); this._alert.info({ message: regionSettingsMessages.saveSuccess, }); } setCountryCode(countryCode) { this.setData({ countryCode, }); } setAreaCode(areaCode) { this.setData({ areaCode, }); } get countryCode() { return this._storage.getItem(this._countryCodeKey) || 'US'; } get areaCode() { return this._storage.getItem(this._areaCodeKey) || ''; } }
describe('Shameless Gossip', function() { integration(function() { describe('Shameless Gossip\'s ability', function() { beforeEach(function() { this.setupTest({ phase: 'conflict', player1: { inPlay: ['shameless-gossip', 'alibi-artist', 'bayushi-liar'] }, player2: { inPlay: ['doji-whisperer', 'doji-hotaru'] } }); this.shamelessGossip = this.player1.findCardByName('shameless-gossip'); this.shamelessGossip.dishonor(); this.alibiArtist = this.player1.findCardByName('alibi-artist'); this.alibiArtist.dishonor(); this.bayushiLiar = this.player1.findCardByName('bayushi-liar'); this.dojiWhisperer = this.player2.findCardByName('doji-whisperer'); this.dojiWhisperer.dishonor(); this.dojiHotaru = this.player2.findCardByName('doji-hotaru'); this.dojiHotaru.honor(); }); it('should not be triggerable if not participating', function() { expect(this.player1).toHavePrompt('Action Window'); this.player1.clickCard(this.shamelessGossip); expect(this.player1).toHavePrompt('Action Window'); this.noMoreActions(); this.initiateConflict({ attackers: [this.alibiArtist], defenders: [this.dojiWhisperer], type: 'political' }); this.player2.pass(); expect(this.player1).toHavePrompt('Conflict Action Window'); this.player1.clickCard(this.shamelessGossip); expect(this.player1).toHavePrompt('Conflict Action Window'); }); it('should prompt to choose any character with a personal honor token', function() { this.noMoreActions(); this.initiateConflict({ attackers: [this.shamelessGossip], defenders: [] }); this.player2.pass(); this.player1.clickCard(this.shamelessGossip); expect(this.player1).toHavePrompt('Choose a Character to move a status token from'); expect(this.player1).toBeAbleToSelect(this.shamelessGossip); expect(this.player1).toBeAbleToSelect(this.alibiArtist); expect(this.player1).not.toBeAbleToSelect(this.bayushiLiar); expect(this.player1).toBeAbleToSelect(this.dojiWhisperer); expect(this.player1).toBeAbleToSelect(this.dojiHotaru); }); it('should prompt to choose a second character controlled by the same player (without the same honor status) (controller)', function() { this.noMoreActions(); this.initiateConflict({ attackers: [this.shamelessGossip], defenders: [] }); this.player2.pass(); this.player1.clickCard(this.shamelessGossip); this.player1.clickCard(this.alibiArtist); expect(this.player1).toHavePrompt('Choose a Character to move the status token to'); expect(this.player1).not.toBeAbleToSelect(this.shamelessGossip); expect(this.player1).not.toBeAbleToSelect(this.alibiArtist); expect(this.player1).toBeAbleToSelect(this.bayushiLiar); expect(this.player1).not.toBeAbleToSelect(this.dojiWhisperer); expect(this.player1).not.toBeAbleToSelect(this.dojiHotaru); }); it('should prompt to choose a second character controlled by the same player (without the same honor status) (opponent)', function() { this.noMoreActions(); this.initiateConflict({ attackers: [this.shamelessGossip], defenders: [] }); this.player2.pass(); this.player1.clickCard(this.shamelessGossip); this.player1.clickCard(this.dojiHotaru); expect(this.player1).toHavePrompt('Choose a Character to move the status token to'); expect(this.player1).not.toBeAbleToSelect(this.shamelessGossip); expect(this.player1).not.toBeAbleToSelect(this.alibiArtist); expect(this.player1).not.toBeAbleToSelect(this.bayushiLiar); expect(this.player1).toBeAbleToSelect(this.dojiWhisperer); expect(this.player1).not.toBeAbleToSelect(this.dojiHotaru); }); it('should move the status token from the first character to the second', function() { this.noMoreActions(); this.initiateConflict({ attackers: [this.shamelessGossip], defenders: [] }); this.player2.pass(); this.player1.clickCard(this.shamelessGossip); this.player1.clickCard(this.dojiHotaru); this.player1.clickCard(this.dojiWhisperer); expect(this.dojiWhisperer.isHonored).toBe(false); expect(this.dojiWhisperer.isDishonored).toBe(false); expect(this.dojiHotaru.isHonored).toBe(false); expect(this.dojiHotaru.isDishonored).toBe(false); expect(this.getChatLogs(3)).toContain('player1 uses Shameless Gossip to move Doji Hotaru\'s Honored Token to Doji Whisperer'); }); }); }); });
const assert = require("chai").assert; const obj = require("../arithmetic") //Addition describe("Arithmetic operations:-", function(){ describe("Addition", function(){ it("addition(10, 5) equals 15", function(){ let result = obj.addition(10, 5) assert.equal(result, 15) }) it("addition(10, 5) is greater than 10", function(){ let result = obj.addition(10, 5) assert.isAbove(result, 10) }) it("addition(10, 5) returns a number", function(){ let result = obj.addition(10, 5) assert.typeOf(result, "number") }) }) //Subtraction describe("Subtraction", function(){ it("subtraction(10, 5) equals 5", function(){ let result = obj.subtraction(10, 5) assert.equal(result, 5) }) it("subtraction(10, 5) is less than 8", function(){ let result = obj.subtraction(10, 5) assert.isBelow(result, 8) }) it("subtraction(10, 5) returns a number", function(){ let result = obj.subtraction(10, 5) assert.typeOf(result, "number") }) }) //Multiplication describe("Multiplication", function(){ it("multiplication(10, 5) equals 50", function(){ let result = obj.multiplication(10, 5) assert.equal(result, 50) }) it("multiplication(10, 5) is less than 51", function(){ let result = obj.multiplication(10, 5) assert.isBelow(result, 51) }) it("multiplication(10, 5) returns a number", function(){ let result = obj.multiplication(10, 5) assert.typeOf(result, "number") }) }) //Divison describe("Division", function(){ it("isDivisorNotZero(10, 5) returns true", function(){ let result = obj.isDivisorNotZero(10, 5) assert.equal(result, true) }) it("divison(10, 5) equals 2", function(){ let result = obj.division(10, 5) assert.equal(result, 2) }) }) })
$(function(){ // $('.ui.sticky').sticky(); $("#input-query").on("keyup", function(event) { var query = $.trim($("#input-query").val()); console.log(query); $("#btn-query").attr("data-action-id", query); }); $("#input-query").on("keypress", function(event){ if(event.keyCode == 13){ //sendQuery(); $("#btn-query").trigger("click"); event.preventDefault(); } }); $("#btn-query").on("click", function() { sendQuery(); }); $("#result").on("click", ".btn-select-query", function(){ var $this = $(this); var query = $this.val(); $("#input-query").val(query); sendQuery(); }); }); function sendQuery(){ var query = $.trim($("#input-query").val()); if(query == ""){ var $query = $("#input-query"); $query.val(""); return false; } var data = { user_key: "WEB_USER", type: "text", content: query }; $.ajax({ url:"kakao/message", method: "POST", data: JSON.stringify(data), headers: { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-cache" }, }).done(function(res){ console.log(res); var $query = $("#input-query"); $query.val(""); var $result = $("#result"); var $message = $("<div class='message ui piled yellow segment'></div>"); if(res.message.photo){ $message.append("<image src='"+res.message.photo.url+"'/>"); } $message.append("<pre style='color: black'>"+res.message.text+"</pre>"); if(res.keyboard){ var keyboardType = res.keyboard.type; switch (keyboardType) { case "text": break; case "buttons": var buttons = res.keyboard.buttons; var $buttons = $("<div class=''></div>"); $.each(buttons, function(i, item){ // console.log(i, item); $buttons.append("<button class='ui mini blue button btn-select-query' value='"+item+"'>"+item+"</button>"); }); $message.append($buttons); break; } } console.log($message); $result.prepend($message); }); }
// ClientDS (Client Data Storage) works with Local/Session Storage, Cached Data, etc. // Note that __SERVER__ side will crash when accessing Local/Session Storage => do a check for __CLIENT__ // Usage: ClientDS.Local.setItem('myKey', 'value') let isClient = false if (typeof __CLIENT__ === 'undefined') { isClient = true // e.g. run from Storybook } else { isClient = __CLIENT__ } export default class ClientDS { static Session = { setItem: (key, val) => { if (isClient) { sessionStorage.setItem(key, val) } }, setJson: (key, val) => { if (val) { ClientDS.Session.setItem(key, JSON.stringify(val)) } else { ClientDS.Session.setItem(key, JSON.stringify({})) } }, getItem: (key) => { if (isClient) { return sessionStorage.getItem(key) } return null }, getJson: (key) => { const item = ClientDS.Session.getItem(key) if (item) { try { return JSON.parse(item) } catch (ex) { return null } } }, removeItem: (key) => { if (isClient) { sessionStorage.removeItem(key) } } } static Local = { setItem: (key, val) => { if (isClient) { localStorage.setItem(key, val) } }, setJson: (key, val) => { if (val) { ClientDS.Local.setItem(key, JSON.stringify(val)) } else { ClientDS.Local.setItem(key, JSON.stringify({})) } }, getItem: (key) => { if (isClient) { return localStorage.getItem(key) } return null }, getJson: (key) => { const item = ClientDS.Local.getItem(key) if (item) { try { return JSON.parse(item) } catch (ex) { return null } } }, removeItem: (key) => { if (isClient) { localStorage.removeItem(key) } } } static getLoginSession () { const ss = ClientDS.Session.getJson('sessionData') if (!ss) { return null } return ss } static setLoginSession (ss) { ClientDS.Session.setJson('sessionData', ss) } }
export default class User { constructor($http, $q) { 'ngInject'; this.Q = $q; this.HTTP = $http; this.init(); } init(){ this.HTTP.get("orbital.json").then( (res)=>{ this.modules = res.data; }).catch( (error)=>{ console.log(error); }); } }
import { inject, bindable, bindingMode } from 'aurelia-framework'; @inject(Element) export class LlStepFieldCustomElement { @bindable field = {}; @bindable calculations; @bindable({defaultBindingMode: bindingMode.twoWay}) outputTo; constructor(element) { this.element = element; this.field.properties = []; } outputToChanged() { if (Object.keys(this.outputTo).length === 0 && this.field) { this.outputTo.label = this.field.label; this.outputTo.description = this.field.description; this.outputTo.properties = this.field.properties; } } addProperty() { if (!this.field.properties) { this.field.properties = []; } if (this.field.properties.length < 4) { this.field.properties.push({}); } } removeProperty(index) { this.field.properties.splice(index, 1); } }
'use strict'; const assert = require('assert'); let http = require('http'); let https = require('https'); const os = require('os'); const fs = require('fs'); const express = require('../support/express'); const request = require('../support/client'); const app = express(); const key = fs.readFileSync(`${__dirname}/fixtures/key.pem`); const cert = fs.readFileSync(`${__dirname}/fixtures/cert.pem`); const cacert = fs.readFileSync(`${__dirname}/fixtures/ca.cert.pem`); const httpSockPath = [os.tmpdir(), 'superagent-http.sock'].join('/'); const httpsSockPath = [os.tmpdir(), 'superagent-https.sock'].join('/'); let httpServer; let httpsServer; if (process.env.HTTP2_TEST) { http = https = require('http2'); } app.get('/', (req, res) => { res.send('root ok!'); }); app.get('/request/path', (req, res) => { res.send('request path ok!'); }); describe('[unix-sockets] http', () => { if (process.platform === 'win32') { return; } before(done => { if (fs.existsSync(httpSockPath) === true) { // try unlink if sock file exists fs.unlinkSync(httpSockPath); } httpServer = http.createServer(app); httpServer.listen(httpSockPath, done); }); const base = `http+unix://${httpSockPath.replace(/\//g, '%2F')}`; describe('request', () => { it('path: / (root)', done => { request.get(`${base}/`).end((err, res) => { assert(res.ok); assert.strictEqual('root ok!', res.text); done(); }); }); it('path: /request/path', done => { request.get(`${base}/request/path`).end((err, res) => { assert(res.ok); assert.strictEqual('request path ok!', res.text); done(); }); }); }); after(() => { if (typeof httpServer.close === 'function') { httpServer.close(); } else httpServer.destroy(); }); }); describe('[unix-sockets] https', () => { if (process.platform === 'win32') { return; } before(done => { if (fs.existsSync(httpsSockPath) === true) { // try unlink if sock file exists fs.unlinkSync(httpsSockPath); } if (process.env.HTTP2_TEST) { httpsServer = https.createSecureServer({ key, cert }, app); } else { httpsServer = https.createServer({ key, cert }, app); } httpsServer.listen(httpsSockPath, done); }); const base = `https+unix://${httpsSockPath.replace(/\//g, '%2F')}`; describe('request', () => { it('path: / (root)', done => { request .get(`${base}/`) .ca(cacert) .end((err, res) => { assert.ifError(err); assert(res.ok); assert.strictEqual('root ok!', res.text); done(); }); }); it('path: /request/path', done => { request .get(`${base}/request/path`) .ca(cacert) .end((err, res) => { assert.ifError(err); assert(res.ok); assert.strictEqual('request path ok!', res.text); done(); }); }); }); after(done => { httpsServer.close(done); }); });
(function(){ angular.module('ui.grid') .factory('Grid', ['$q', '$compile', '$parse', 'gridUtil', 'uiGridConstants', 'GridOptions', 'GridColumn', 'GridRow', 'GridApi', 'rowSorter', 'rowSearcher', 'GridRenderContainer', '$timeout','ScrollEvent', function($q, $compile, $parse, gridUtil, uiGridConstants, GridOptions, GridColumn, GridRow, GridApi, rowSorter, rowSearcher, GridRenderContainer, $timeout, ScrollEvent) { /** * @ngdoc object * @name ui.grid.core.api:PublicApi * @description Public Api for the core grid features * */ /** * @ngdoc function * @name ui.grid.class:Grid * @description Grid is the main viewModel. Any properties or methods needed to maintain state are defined in * this prototype. One instance of Grid is created per Grid directive instance. * @param {object} options Object map of options to pass into the grid. An 'id' property is expected. */ var Grid = function Grid(options) { var self = this; // Get the id out of the options, then remove it if (options !== undefined && typeof(options.id) !== 'undefined' && options.id) { if (!/^[_a-zA-Z0-9-]+$/.test(options.id)) { throw new Error("Grid id '" + options.id + '" is invalid. It must follow CSS selector syntax rules.'); } } else { throw new Error('No ID provided. An ID must be given when creating a grid.'); } self.id = options.id; delete options.id; // Get default options self.options = GridOptions.initialize( options ); /** * @ngdoc object * @name appScope * @propertyOf ui.grid.class:Grid * @description reference to the application scope (the parent scope of the ui-grid element). Assigned in ui-grid controller * <br/> * use gridOptions.appScopeProvider to override the default assignment of $scope.$parent with any reference */ self.appScope = self.options.appScopeProvider; self.headerHeight = self.options.headerRowHeight; /** * @ngdoc object * @name footerHeight * @propertyOf ui.grid.class:Grid * @description returns the total footer height gridFooter + columnFooter */ self.footerHeight = self.calcFooterHeight(); /** * @ngdoc object * @name columnFooterHeight * @propertyOf ui.grid.class:Grid * @description returns the total column footer height */ self.columnFooterHeight = self.calcColumnFooterHeight(); self.rtl = false; self.gridHeight = 0; self.gridWidth = 0; self.columnBuilders = []; self.rowBuilders = []; self.rowsProcessors = []; self.columnsProcessors = []; self.styleComputations = []; self.viewportAdjusters = []; self.rowHeaderColumns = []; self.dataChangeCallbacks = {}; self.verticalScrollSyncCallBackFns = {}; self.horizontalScrollSyncCallBackFns = {}; // self.visibleRowCache = []; // Set of 'render' containers for self grid, which can render sets of rows self.renderContainers = {}; // Create a self.renderContainers.body = new GridRenderContainer('body', self); self.cellValueGetterCache = {}; // Cached function to use with custom row templates self.getRowTemplateFn = null; //representation of the rows on the grid. //these are wrapped references to the actual data rows (options.data) self.rows = []; //represents the columns on the grid self.columns = []; /** * @ngdoc boolean * @name isScrollingVertically * @propertyOf ui.grid.class:Grid * @description set to true when Grid is scrolling vertically. Set to false via debounced method */ self.isScrollingVertically = false; /** * @ngdoc boolean * @name isScrollingHorizontally * @propertyOf ui.grid.class:Grid * @description set to true when Grid is scrolling horizontally. Set to false via debounced method */ self.isScrollingHorizontally = false; /** * @ngdoc property * @name scrollDirection * @propertyOf ui.grid.class:Grid * @description set one of the uiGridConstants.scrollDirection values (UP, DOWN, LEFT, RIGHT, NONE), which tells * us which direction we are scrolling. Set to NONE via debounced method */ self.scrollDirection = uiGridConstants.scrollDirection.NONE; //if true, grid will not respond to any scroll events self.disableScrolling = false; function vertical (scrollEvent) { self.isScrollingVertically = false; self.api.core.raise.scrollEnd(scrollEvent); self.scrollDirection = uiGridConstants.scrollDirection.NONE; } var debouncedVertical = gridUtil.debounce(vertical, self.options.scrollDebounce); var debouncedVerticalMinDelay = gridUtil.debounce(vertical, 0); function horizontal (scrollEvent) { self.isScrollingHorizontally = false; self.api.core.raise.scrollEnd(scrollEvent); self.scrollDirection = uiGridConstants.scrollDirection.NONE; } var debouncedHorizontal = gridUtil.debounce(horizontal, self.options.scrollDebounce); var debouncedHorizontalMinDelay = gridUtil.debounce(horizontal, 0); /** * @ngdoc function * @name flagScrollingVertically * @methodOf ui.grid.class:Grid * @description sets isScrollingVertically to true and sets it to false in a debounced function */ self.flagScrollingVertically = function(scrollEvent) { if (!self.isScrollingVertically && !self.isScrollingHorizontally) { self.api.core.raise.scrollBegin(scrollEvent); } self.isScrollingVertically = true; if (self.options.scrollDebounce === 0 || !scrollEvent.withDelay) { debouncedVerticalMinDelay(scrollEvent); } else { debouncedVertical(scrollEvent); } }; /** * @ngdoc function * @name flagScrollingHorizontally * @methodOf ui.grid.class:Grid * @description sets isScrollingHorizontally to true and sets it to false in a debounced function */ self.flagScrollingHorizontally = function(scrollEvent) { if (!self.isScrollingVertically && !self.isScrollingHorizontally) { self.api.core.raise.scrollBegin(scrollEvent); } self.isScrollingHorizontally = true; if (self.options.scrollDebounce === 0 || !scrollEvent.withDelay) { debouncedHorizontalMinDelay(scrollEvent); } else { debouncedHorizontal(scrollEvent); } }; self.scrollbarHeight = 0; self.scrollbarWidth = 0; if (self.options.enableHorizontalScrollbar === uiGridConstants.scrollbars.ALWAYS) { self.scrollbarHeight = gridUtil.getScrollbarWidth(); } if (self.options.enableVerticalScrollbar === uiGridConstants.scrollbars.ALWAYS) { self.scrollbarWidth = gridUtil.getScrollbarWidth(); } self.api = new GridApi(self); /** * @ngdoc function * @name refresh * @methodOf ui.grid.core.api:PublicApi * @description Refresh the rendered grid on screen. * The refresh method re-runs both the columnProcessors and the * rowProcessors, as well as calling refreshCanvas to update all * the grid sizing. In general you should prefer to use queueGridRefresh * instead, which is basically a debounced version of refresh. * * If you only want to resize the grid, not regenerate all the rows * and columns, you should consider directly calling refreshCanvas instead. * */ self.api.registerMethod( 'core', 'refresh', this.refresh ); /** * @ngdoc function * @name queueGridRefresh * @methodOf ui.grid.core.api:PublicApi * @description Request a refresh of the rendered grid on screen, if multiple * calls to queueGridRefresh are made within a digest cycle only one will execute. * The refresh method re-runs both the columnProcessors and the * rowProcessors, as well as calling refreshCanvas to update all * the grid sizing. In general you should prefer to use queueGridRefresh * instead, which is basically a debounced version of refresh. * */ self.api.registerMethod( 'core', 'queueGridRefresh', this.queueGridRefresh ); /** * @ngdoc function * @name refreshRows * @methodOf ui.grid.core.api:PublicApi * @description Runs only the rowProcessors, columns remain as they were. * It then calls redrawInPlace and refreshCanvas, which adjust the grid sizing. * @returns {promise} promise that is resolved when render completes? * */ self.api.registerMethod( 'core', 'refreshRows', this.refreshRows ); /** * @ngdoc function * @name queueRefresh * @methodOf ui.grid.core.api:PublicApi * @description Requests execution of refreshCanvas, if multiple requests are made * during a digest cycle only one will run. RefreshCanvas updates the grid sizing. * @returns {promise} promise that is resolved when render completes? * */ self.api.registerMethod( 'core', 'queueRefresh', this.queueRefresh ); /** * @ngdoc function * @name handleWindowResize * @methodOf ui.grid.core.api:PublicApi * @description Trigger a grid resize, normally this would be picked * up by a watch on window size, but in some circumstances it is necessary * to call this manually * @returns {promise} promise that is resolved when render completes? * */ self.api.registerMethod( 'core', 'handleWindowResize', this.handleWindowResize ); /** * @ngdoc function * @name addRowHeaderColumn * @methodOf ui.grid.core.api:PublicApi * @description adds a row header column to the grid * @param {object} column def * */ self.api.registerMethod( 'core', 'addRowHeaderColumn', this.addRowHeaderColumn ); /** * @ngdoc function * @name scrollToIfNecessary * @methodOf ui.grid.core.api:PublicApi * @description Scrolls the grid to make a certain row and column combo visible, * in the case that it is not completely visible on the screen already. * @param {GridRow} gridRow row to make visible * @param {GridCol} gridCol column to make visible * @returns {promise} a promise that is resolved when scrolling is complete * */ self.api.registerMethod( 'core', 'scrollToIfNecessary', function(gridRow, gridCol) { return self.scrollToIfNecessary(gridRow, gridCol);} ); /** * @ngdoc function * @name scrollTo * @methodOf ui.grid.core.api:PublicApi * @description Scroll the grid such that the specified * row and column is in view * @param {object} rowEntity gridOptions.data[] array instance to make visible * @param {object} colDef to make visible * @returns {promise} a promise that is resolved after any scrolling is finished */ self.api.registerMethod( 'core', 'scrollTo', function (rowEntity, colDef) { return self.scrollTo(rowEntity, colDef);} ); /** * @ngdoc function * @name registerRowsProcessor * @methodOf ui.grid.core.api:PublicApi * @description * Register a "rows processor" function. When the rows are updated, * the grid calls each registered "rows processor", which has a chance * to alter the set of rows (sorting, etc) as long as the count is not * modified. * * @param {function(renderedRowsToProcess, columns )} processorFunction rows processor function, which * is run in the context of the grid (i.e. this for the function will be the grid), and must * return the updated rows list, which is passed to the next processor in the chain * @param {number} priority the priority of this processor. In general we try to do them in 100s to leave room * for other people to inject rows processors at intermediate priorities. Lower priority rowsProcessors run earlier. * * At present allRowsVisible is running at 50, sort manipulations running at 60-65, filter is running at 100, * sort is at 200, grouping and treeview at 400-410, selectable rows at 500, pagination at 900 (pagination will generally want to be last) */ self.api.registerMethod( 'core', 'registerRowsProcessor', this.registerRowsProcessor ); /** * @ngdoc function * @name registerColumnsProcessor * @methodOf ui.grid.core.api:PublicApi * @description * Register a "columns processor" function. When the columns are updated, * the grid calls each registered "columns processor", which has a chance * to alter the set of columns as long as the count is not * modified. * * @param {function(renderedColumnsToProcess, rows )} processorFunction columns processor function, which * is run in the context of the grid (i.e. this for the function will be the grid), and must * return the updated columns list, which is passed to the next processor in the chain * @param {number} priority the priority of this processor. In general we try to do them in 100s to leave room * for other people to inject columns processors at intermediate priorities. Lower priority columnsProcessors run earlier. * * At present allRowsVisible is running at 50, filter is running at 100, sort is at 200, grouping at 400, selectable rows at 500, pagination at 900 (pagination will generally want to be last) */ self.api.registerMethod( 'core', 'registerColumnsProcessor', this.registerColumnsProcessor ); /** * @ngdoc function * @name sortHandleNulls * @methodOf ui.grid.core.api:PublicApi * @description A null handling method that can be used when building custom sort * functions * @example * <pre> * mySortFn = function(a, b) { * var nulls = $scope.gridApi.core.sortHandleNulls(a, b); * if ( nulls !== null ){ * return nulls; * } else { * // your code for sorting here * }; * </pre> * @param {object} a sort value a * @param {object} b sort value b * @returns {number} null if there were no nulls/undefineds, otherwise returns * a sort value that should be passed back from the sort function * */ self.api.registerMethod( 'core', 'sortHandleNulls', rowSorter.handleNulls ); /** * @ngdoc function * @name sortChanged * @methodOf ui.grid.core.api:PublicApi * @description The sort criteria on one or more columns has * changed. Provides as parameters the grid and the output of * getColumnSorting, which is an array of gridColumns * that have sorting on them, sorted in priority order. * * @param {$scope} scope The scope of the controller. This is used to deregister this event when the scope is destroyed. * @param {Function} callBack Will be called when the event is emited. The function passes back an array of columns with * sorts on them, in priority order. * * @example * <pre> * gridApi.core.on.sortChanged( $scope, function(sortColumns){ * // do something * }); * </pre> */ self.api.registerEvent( 'core', 'sortChanged' ); /** * @ngdoc function * @name columnVisibilityChanged * @methodOf ui.grid.core.api:PublicApi * @description The visibility of a column has changed, * the column itself is passed out as a parameter of the event. * * @param {$scope} scope The scope of the controller. This is used to deregister this event when the scope is destroyed. * @param {Function} callBack Will be called when the event is emited. The function passes back the GridCol that has changed. * * @example * <pre> * gridApi.core.on.columnVisibilityChanged( $scope, function (column) { * // do something * } ); * </pre> */ self.api.registerEvent( 'core', 'columnVisibilityChanged' ); /** * @ngdoc method * @name notifyDataChange * @methodOf ui.grid.core.api:PublicApi * @description Notify the grid that a data or config change has occurred, * where that change isn't something the grid was otherwise noticing. This * might be particularly relevant where you've changed values within the data * and you'd like cell classes to be re-evaluated, or changed config within * the columnDef and you'd like headerCellClasses to be re-evaluated. * @param {string} type one of the * uiGridConstants.dataChange values (ALL, ROW, EDIT, COLUMN), which tells * us which refreshes to fire. * */ self.api.registerMethod( 'core', 'notifyDataChange', this.notifyDataChange ); /** * @ngdoc method * @name clearAllFilters * @methodOf ui.grid.core.api:PublicApi * @description Clears all filters and optionally refreshes the visible rows. * @param {object} refreshRows Defaults to true. * @param {object} clearConditions Defaults to false. * @param {object} clearFlags Defaults to false. * @returns {promise} If `refreshRows` is true, returns a promise of the rows refreshing. */ self.api.registerMethod('core', 'clearAllFilters', this.clearAllFilters); self.registerDataChangeCallback( self.columnRefreshCallback, [uiGridConstants.dataChange.COLUMN]); self.registerDataChangeCallback( self.processRowsCallback, [uiGridConstants.dataChange.EDIT]); self.registerDataChangeCallback( self.updateFooterHeightCallback, [uiGridConstants.dataChange.OPTIONS]); self.registerStyleComputation({ priority: 10, func: self.getFooterStyles }); }; Grid.prototype.calcFooterHeight = function () { if (!this.hasFooter()) { return 0; } var height = 0; if (this.options.showGridFooter) { height += this.options.gridFooterHeight; } height += this.calcColumnFooterHeight(); return height; }; Grid.prototype.calcColumnFooterHeight = function () { var height = 0; if (this.options.showColumnFooter) { height += this.options.columnFooterHeight; } return height; }; Grid.prototype.getFooterStyles = function () { var style = '.grid' + this.id + ' .ui-grid-footer-aggregates-row { height: ' + this.options.columnFooterHeight + 'px; }'; style += ' .grid' + this.id + ' .ui-grid-footer-info { height: ' + this.options.gridFooterHeight + 'px; }'; return style; }; Grid.prototype.hasFooter = function () { return this.options.showGridFooter || this.options.showColumnFooter; }; /** * @ngdoc function * @name isRTL * @methodOf ui.grid.class:Grid * @description Returns true if grid is RightToLeft */ Grid.prototype.isRTL = function () { return this.rtl; }; /** * @ngdoc function * @name registerColumnBuilder * @methodOf ui.grid.class:Grid * @description When the build creates columns from column definitions, the columnbuilders will be called to add * additional properties to the column. * @param {function(colDef, col, gridOptions)} columnBuilder function to be called */ Grid.prototype.registerColumnBuilder = function registerColumnBuilder(columnBuilder) { this.columnBuilders.push(columnBuilder); }; /** * @ngdoc function * @name buildColumnDefsFromData * @methodOf ui.grid.class:Grid * @description Populates columnDefs from the provided data * @param {function(colDef, col, gridOptions)} rowBuilder function to be called */ Grid.prototype.buildColumnDefsFromData = function (dataRows){ this.options.columnDefs = gridUtil.getColumnsFromData(dataRows, this.options.excludeProperties); }; /** * @ngdoc function * @name registerRowBuilder * @methodOf ui.grid.class:Grid * @description When the build creates rows from gridOptions.data, the rowBuilders will be called to add * additional properties to the row. * @param {function(row, gridOptions)} rowBuilder function to be called */ Grid.prototype.registerRowBuilder = function registerRowBuilder(rowBuilder) { this.rowBuilders.push(rowBuilder); }; /** * @ngdoc function * @name registerDataChangeCallback * @methodOf ui.grid.class:Grid * @description When a data change occurs, the data change callbacks of the specified type * will be called. The rules are: * * - when the data watch fires, that is considered a ROW change (the data watch only notices * added or removed rows) * - when the api is called to inform us of a change, the declared type of that change is used * - when a cell edit completes, the EDIT callbacks are triggered * - when the columnDef watch fires, the COLUMN callbacks are triggered * - when the options watch fires, the OPTIONS callbacks are triggered * * For a given event: * - ALL calls ROW, EDIT, COLUMN, OPTIONS and ALL callbacks * - ROW calls ROW and ALL callbacks * - EDIT calls EDIT and ALL callbacks * - COLUMN calls COLUMN and ALL callbacks * - OPTIONS calls OPTIONS and ALL callbacks * * @param {function(grid)} callback function to be called * @param {array} types the types of data change you want to be informed of. Values from * the uiGridConstants.dataChange values ( ALL, EDIT, ROW, COLUMN, OPTIONS ). Optional and defaults to * ALL * @returns {function} deregister function - a function that can be called to deregister this callback */ Grid.prototype.registerDataChangeCallback = function registerDataChangeCallback(callback, types, _this) { var uid = gridUtil.nextUid(); if ( !types ){ types = [uiGridConstants.dataChange.ALL]; } if ( !Array.isArray(types)){ gridUtil.logError("Expected types to be an array or null in registerDataChangeCallback, value passed was: " + types ); } this.dataChangeCallbacks[uid] = { callback: callback, types: types, _this:_this }; var self = this; var deregisterFunction = function() { delete self.dataChangeCallbacks[uid]; }; return deregisterFunction; }; /** * @ngdoc function * @name callDataChangeCallbacks * @methodOf ui.grid.class:Grid * @description Calls the callbacks based on the type of data change that * has occurred. Always calls the ALL callbacks, calls the ROW, EDIT, COLUMN and OPTIONS callbacks if the * event type is matching, or if the type is ALL. * @param {number} type the type of event that occurred - one of the * uiGridConstants.dataChange values (ALL, ROW, EDIT, COLUMN, OPTIONS) */ Grid.prototype.callDataChangeCallbacks = function callDataChangeCallbacks(type, options) { angular.forEach( this.dataChangeCallbacks, function( callback, uid ){ if ( callback.types.indexOf( uiGridConstants.dataChange.ALL ) !== -1 || callback.types.indexOf( type ) !== -1 || type === uiGridConstants.dataChange.ALL ) { if (callback._this) { callback.callback.apply(callback._this,this); } else { callback.callback( this ); } } }, this); }; /** * @ngdoc function * @name notifyDataChange * @methodOf ui.grid.class:Grid * @description Notifies us that a data change has occurred, used in the public * api for users to tell us when they've changed data or some other event that * our watches cannot pick up * @param {string} type the type of event that occurred - one of the * uiGridConstants.dataChange values (ALL, ROW, EDIT, COLUMN) */ Grid.prototype.notifyDataChange = function notifyDataChange(type) { var constants = uiGridConstants.dataChange; if ( type === constants.ALL || type === constants.COLUMN || type === constants.EDIT || type === constants.ROW || type === constants.OPTIONS ){ this.callDataChangeCallbacks( type ); } else { gridUtil.logError("Notified of a data change, but the type was not recognised, so no action taken, type was: " + type); } }; /** * @ngdoc function * @name columnRefreshCallback * @methodOf ui.grid.class:Grid * @description refreshes the grid when a column refresh * is notified, which triggers handling of the visible flag. * This is called on uiGridConstants.dataChange.COLUMN, and is * registered as a dataChangeCallback in grid.js * @param {string} name column name */ Grid.prototype.columnRefreshCallback = function columnRefreshCallback( grid ){ grid.buildColumns(); grid.queueGridRefresh(); }; /** * @ngdoc function * @name processRowsCallback * @methodOf ui.grid.class:Grid * @description calls the row processors, specifically * intended to reset the sorting when an edit is called, * registered as a dataChangeCallback on uiGridConstants.dataChange.EDIT * @param {string} name column name */ Grid.prototype.processRowsCallback = function processRowsCallback( grid ){ grid.queueGridRefresh(); }; /** * @ngdoc function * @name updateFooterHeightCallback * @methodOf ui.grid.class:Grid * @description recalculates the footer height, * registered as a dataChangeCallback on uiGridConstants.dataChange.OPTIONS * @param {string} name column name */ Grid.prototype.updateFooterHeightCallback = function updateFooterHeightCallback( grid ){ grid.footerHeight = grid.calcFooterHeight(); grid.columnFooterHeight = grid.calcColumnFooterHeight(); }; /** * @ngdoc function * @name getColumn * @methodOf ui.grid.class:Grid * @description returns a grid column for the column name * @param {string} name column name */ Grid.prototype.getColumn = function getColumn(name) { var columns = this.columns.filter(function (column) { return column.colDef.name === name; }); return columns.length > 0 ? columns[0] : null; }; /** * @ngdoc function * @name getColDef * @methodOf ui.grid.class:Grid * @description returns a grid colDef for the column name * @param {string} name column.field */ Grid.prototype.getColDef = function getColDef(name) { var colDefs = this.options.columnDefs.filter(function (colDef) { return colDef.name === name; }); return colDefs.length > 0 ? colDefs[0] : null; }; /** * @ngdoc function * @name assignTypes * @methodOf ui.grid.class:Grid * @description uses the first row of data to assign colDef.type for any types not defined. */ /** * @ngdoc property * @name type * @propertyOf ui.grid.class:GridOptions.columnDef * @description the type of the column, used in sorting. If not provided then the * grid will guess the type. Add this only if the grid guessing is not to your * satisfaction. One of: * - 'string' * - 'boolean' * - 'number' * - 'date' * - 'object' * - 'numberStr' * Note that if you choose date, your dates should be in a javascript date type * */ Grid.prototype.assignTypes = function(){ var self = this; self.options.columnDefs.forEach(function (colDef, index) { //Assign colDef type if not specified if (!colDef.type) { var col = new GridColumn(colDef, index, self); var firstRow = self.rows.length > 0 ? self.rows[0] : null; if (firstRow) { colDef.type = gridUtil.guessType(self.getCellValue(firstRow, col)); } else { colDef.type = 'string'; } } }); }; /** * @ngdoc function * @name isRowHeaderColumn * @methodOf ui.grid.class:Grid * @description returns true if the column is a row Header * @param {object} column column */ Grid.prototype.isRowHeaderColumn = function isRowHeaderColumn(column) { return this.rowHeaderColumns.indexOf(column) !== -1; }; /** * @ngdoc function * @name addRowHeaderColumn * @methodOf ui.grid.class:Grid * @description adds a row header column to the grid * @param {object} column def */ Grid.prototype.addRowHeaderColumn = function addRowHeaderColumn(colDef) { var self = this; var rowHeaderCol = new GridColumn(colDef, gridUtil.nextUid(), self); rowHeaderCol.isRowHeader = true; if (self.isRTL()) { self.createRightContainer(); rowHeaderCol.renderContainer = 'right'; } else { self.createLeftContainer(); rowHeaderCol.renderContainer = 'left'; } // relies on the default column builder being first in array, as it is instantiated // as part of grid creation self.columnBuilders[0](colDef,rowHeaderCol,self.options) .then(function(){ rowHeaderCol.enableFiltering = false; rowHeaderCol.enableSorting = false; rowHeaderCol.enableHiding = false; self.rowHeaderColumns.push(rowHeaderCol); self.buildColumns() .then( function() { self.preCompileCellTemplates(); self.queueGridRefresh(); }); }); }; /** * @ngdoc function * @name getOnlyDataColumns * @methodOf ui.grid.class:Grid * @description returns all columns except for rowHeader columns */ Grid.prototype.getOnlyDataColumns = function getOnlyDataColumns() { var self = this; var cols = []; self.columns.forEach(function (col) { if (self.rowHeaderColumns.indexOf(col) === -1) { cols.push(col); } }); return cols; }; /** * @ngdoc function * @name buildColumns * @methodOf ui.grid.class:Grid * @description creates GridColumn objects from the columnDefinition. Calls each registered * columnBuilder to further process the column * @param {object} options An object contains options to use when building columns * * * **orderByColumnDefs**: defaults to **false**. When true, `buildColumns` will reorder existing columns according to the order within the column definitions. * * @returns {Promise} a promise to load any needed column resources */ Grid.prototype.buildColumns = function buildColumns(opts) { var options = { orderByColumnDefs: false }; angular.extend(options, opts); // gridUtil.logDebug('buildColumns'); var self = this; var builderPromises = []; var headerOffset = self.rowHeaderColumns.length; var i; // Remove any columns for which a columnDef cannot be found // Deliberately don't use forEach, as it doesn't like splice being called in the middle // Also don't cache columns.length, as it will change during this operation for (i = 0; i < self.columns.length; i++){ if (!self.getColDef(self.columns[i].name)) { self.columns.splice(i, 1); i--; } } //add row header columns to the grid columns array _after_ columns without columnDefs have been removed self.rowHeaderColumns.forEach(function (rowHeaderColumn) { self.columns.unshift(rowHeaderColumn); }); // look at each column def, and update column properties to match. If the column def // doesn't have a column, then splice in a new gridCol self.options.columnDefs.forEach(function (colDef, index) { self.preprocessColDef(colDef); var col = self.getColumn(colDef.name); if (!col) { col = new GridColumn(colDef, gridUtil.nextUid(), self); self.columns.splice(index + headerOffset, 0, col); } else { // tell updateColumnDef that the column was pre-existing col.updateColumnDef(colDef, false); } self.columnBuilders.forEach(function (builder) { builderPromises.push(builder.call(self, colDef, col, self.options)); }); }); /*** Reorder columns if necessary ***/ if (!!options.orderByColumnDefs) { // Create a shallow copy of the columns as a cache var columnCache = self.columns.slice(0); // We need to allow for the "row headers" when mapping from the column defs array to the columns array // If we have a row header in columns[0] and don't account for it we'll overwrite it with the column in columnDefs[0] // Go through all the column defs, use the shorter of columns length and colDefs.length because if a user has given two columns the same name then // columns will be shorter than columnDefs. In this situation we'll avoid an error, but the user will still get an unexpected result var len = Math.min(self.options.columnDefs.length, self.columns.length); for (i = 0; i < len; i++) { // If the column at this index has a different name than the column at the same index in the column defs... if (self.columns[i + headerOffset].name !== self.options.columnDefs[i].name) { // Replace the one in the cache with the appropriate column columnCache[i + headerOffset] = self.getColumn(self.options.columnDefs[i].name); } else { // Otherwise just copy over the one from the initial columns columnCache[i + headerOffset] = self.columns[i + headerOffset]; } } // Empty out the columns array, non-destructively self.columns.length = 0; // And splice in the updated, ordered columns from the cache Array.prototype.splice.apply(self.columns, [0, 0].concat(columnCache)); } return $q.all(builderPromises).then(function(){ if (self.rows.length > 0){ self.assignTypes(); } }); }; /** * @ngdoc function * @name preCompileCellTemplates * @methodOf ui.grid.class:Grid * @description precompiles all cell templates */ Grid.prototype.preCompileCellTemplates = function() { var self = this; var preCompileTemplate = function( col ) { var html = col.cellTemplate.replace(uiGridConstants.MODEL_COL_FIELD, self.getQualifiedColField(col)); html = html.replace(uiGridConstants.COL_FIELD, 'grid.getCellValue(row, col)'); var compiledElementFn = $compile(html); col.compiledElementFn = compiledElementFn; if (col.compiledElementFnDefer) { col.compiledElementFnDefer.resolve(col.compiledElementFn); } }; this.columns.forEach(function (col) { if ( col.cellTemplate ){ preCompileTemplate( col ); } else if ( col.cellTemplatePromise ){ col.cellTemplatePromise.then( function() { preCompileTemplate( col ); }); } }); }; /** * @ngdoc function * @name getGridQualifiedColField * @methodOf ui.grid.class:Grid * @description Returns the $parse-able accessor for a column within its $scope * @param {GridColumn} col col object */ Grid.prototype.getQualifiedColField = function (col) { return 'row.entity.' + gridUtil.preEval(col.field); }; /** * @ngdoc function * @name createLeftContainer * @methodOf ui.grid.class:Grid * @description creates the left render container if it doesn't already exist */ Grid.prototype.createLeftContainer = function() { if (!this.hasLeftContainer()) { this.renderContainers.left = new GridRenderContainer('left', this, { disableColumnOffset: true }); } }; /** * @ngdoc function * @name createRightContainer * @methodOf ui.grid.class:Grid * @description creates the right render container if it doesn't already exist */ Grid.prototype.createRightContainer = function() { if (!this.hasRightContainer()) { this.renderContainers.right = new GridRenderContainer('right', this, { disableColumnOffset: true }); } }; /** * @ngdoc function * @name hasLeftContainer * @methodOf ui.grid.class:Grid * @description returns true if leftContainer exists */ Grid.prototype.hasLeftContainer = function() { return this.renderContainers.left !== undefined; }; /** * @ngdoc function * @name hasRightContainer * @methodOf ui.grid.class:Grid * @description returns true if rightContainer exists */ Grid.prototype.hasRightContainer = function() { return this.renderContainers.right !== undefined; }; /** * undocumented function * @name preprocessColDef * @methodOf ui.grid.class:Grid * @description defaults the name property from field to maintain backwards compatibility with 2.x * validates that name or field is present */ Grid.prototype.preprocessColDef = function preprocessColDef(colDef) { var self = this; if (!colDef.field && !colDef.name) { throw new Error('colDef.name or colDef.field property is required'); } //maintain backwards compatibility with 2.x //field was required in 2.x. now name is required if (colDef.name === undefined && colDef.field !== undefined) { // See if the column name already exists: var newName = colDef.field, counter = 2; while (self.getColumn(newName)) { newName = colDef.field + counter.toString(); counter++; } colDef.name = newName; } }; // Return a list of items that exist in the `n` array but not the `o` array. Uses optional property accessors passed as third & fourth parameters Grid.prototype.newInN = function newInN(o, n, oAccessor, nAccessor) { var self = this; var t = []; for (var i = 0; i < n.length; i++) { var nV = nAccessor ? n[i][nAccessor] : n[i]; var found = false; for (var j = 0; j < o.length; j++) { var oV = oAccessor ? o[j][oAccessor] : o[j]; if (self.options.rowEquality(nV, oV)) { found = true; break; } } if (!found) { t.push(nV); } } return t; }; /** * @ngdoc function * @name getRow * @methodOf ui.grid.class:Grid * @description returns the GridRow that contains the rowEntity * @param {object} rowEntity the gridOptions.data array element instance * @param {array} rows [optional] the rows to look in - if not provided then * looks in grid.rows */ Grid.prototype.getRow = function getRow(rowEntity, lookInRows) { var self = this; lookInRows = typeof(lookInRows) === 'undefined' ? self.rows : lookInRows; var rows = lookInRows.filter(function (row) { return self.options.rowEquality(row.entity, rowEntity); }); return rows.length > 0 ? rows[0] : null; }; /** * @ngdoc function * @name modifyRows * @methodOf ui.grid.class:Grid * @description creates or removes GridRow objects from the newRawData array. Calls each registered * rowBuilder to further process the row * * This method aims to achieve three things: * 1. the resulting rows array is in the same order as the newRawData, we'll call * rowsProcessors immediately after to sort the data anyway * 2. if we have row hashing available, we try to use the rowHash to find the row * 3. no memory leaks - rows that are no longer in newRawData need to be garbage collected * * The basic logic flow makes use of the newRawData, oldRows and oldHash, and creates * the newRows and newHash * * ``` * newRawData.forEach newEntity * if (hashing enabled) * check oldHash for newEntity * else * look for old row directly in oldRows * if !oldRowFound // must be a new row * create newRow * append to the newRows and add to newHash * run the processors * * Rows are identified using the hashKey if configured. If not configured, then rows * are identified using the gridOptions.rowEquality function */ Grid.prototype.modifyRows = function modifyRows(newRawData) { var self = this; var oldRows = self.rows.slice(0); var oldRowHash = self.rowHashMap || self.createRowHashMap(); self.rowHashMap = self.createRowHashMap(); self.rows.length = 0; newRawData.forEach( function( newEntity, i ) { var newRow; if ( self.options.enableRowHashing ){ // if hashing is enabled, then this row will be in the hash if we already know about it newRow = oldRowHash.get( newEntity ); } else { // otherwise, manually search the oldRows to see if we can find this row newRow = self.getRow(newEntity, oldRows); } // if we didn't find the row, it must be new, so create it if ( !newRow ){ newRow = self.processRowBuilders(new GridRow(newEntity, i, self)); } self.rows.push( newRow ); self.rowHashMap.put( newEntity, newRow ); }); self.assignTypes(); var p1 = $q.when(self.processRowsProcessors(self.rows)) .then(function (renderableRows) { return self.setVisibleRows(renderableRows); }); var p2 = $q.when(self.processColumnsProcessors(self.columns)) .then(function (renderableColumns) { return self.setVisibleColumns(renderableColumns); }); return $q.all([p1, p2]); }; /** * Private Undocumented Method * @name addRows * @methodOf ui.grid.class:Grid * @description adds the newRawData array of rows to the grid and calls all registered * rowBuilders. this keyword will reference the grid */ Grid.prototype.addRows = function addRows(newRawData) { var self = this; var existingRowCount = self.rows.length; for (var i = 0; i < newRawData.length; i++) { var newRow = self.processRowBuilders(new GridRow(newRawData[i], i + existingRowCount, self)); if (self.options.enableRowHashing) { var found = self.rowHashMap.get(newRow.entity); if (found) { found.row = newRow; } } self.rows.push(newRow); } }; /** * @ngdoc function * @name processRowBuilders * @methodOf ui.grid.class:Grid * @description processes all RowBuilders for the gridRow * @param {GridRow} gridRow reference to gridRow * @returns {GridRow} the gridRow with all additional behavior added */ Grid.prototype.processRowBuilders = function processRowBuilders(gridRow) { var self = this; self.rowBuilders.forEach(function (builder) { builder.call(self, gridRow, self.options); }); return gridRow; }; /** * @ngdoc function * @name registerStyleComputation * @methodOf ui.grid.class:Grid * @description registered a styleComputation function * * If the function returns a value it will be appended into the grid's `<style>` block * @param {function($scope)} styleComputation function */ Grid.prototype.registerStyleComputation = function registerStyleComputation(styleComputationInfo) { this.styleComputations.push(styleComputationInfo); }; // NOTE (c0bra): We already have rowBuilders. I think these do exactly the same thing... // Grid.prototype.registerRowFilter = function(filter) { // // TODO(c0bra): validate filter? // this.rowFilters.push(filter); // }; // Grid.prototype.removeRowFilter = function(filter) { // var idx = this.rowFilters.indexOf(filter); // if (typeof(idx) !== 'undefined' && idx !== undefined) { // this.rowFilters.slice(idx, 1); // } // }; // Grid.prototype.processRowFilters = function(rows) { // var self = this; // self.rowFilters.forEach(function (filter) { // filter.call(self, rows); // }); // }; /** * @ngdoc function * @name registerRowsProcessor * @methodOf ui.grid.class:Grid * @description * * Register a "rows processor" function. When the rows are updated, * the grid calls each registered "rows processor", which has a chance * to alter the set of rows (sorting, etc) as long as the count is not * modified. * * @param {function(renderedRowsToProcess, columns )} processorFunction rows processor function, which * is run in the context of the grid (i.e. this for the function will be the grid), and must * return the updated rows list, which is passed to the next processor in the chain * @param {number} priority the priority of this processor. In general we try to do them in 100s to leave room * for other people to inject rows processors at intermediate priorities. Lower priority rowsProcessors run earlier. * * At present all rows visible is running at 50, filter is running at 100, sort is at 200, grouping at 400, selectable rows at 500, pagination at 900 (pagination will generally want to be last) * */ Grid.prototype.registerRowsProcessor = function registerRowsProcessor(processor, priority) { if (!angular.isFunction(processor)) { throw 'Attempt to register non-function rows processor: ' + processor; } this.rowsProcessors.push({processor: processor, priority: priority}); this.rowsProcessors.sort(function sortByPriority( a, b ){ return a.priority - b.priority; }); }; /** * @ngdoc function * @name removeRowsProcessor * @methodOf ui.grid.class:Grid * @param {function(renderableRows)} rows processor function * @description Remove a registered rows processor */ Grid.prototype.removeRowsProcessor = function removeRowsProcessor(processor) { var idx = -1; this.rowsProcessors.forEach(function(rowsProcessor, index){ if ( rowsProcessor.processor === processor ){ idx = index; } }); if ( idx !== -1 ) { this.rowsProcessors.splice(idx, 1); } }; /** * Private Undocumented Method * @name processRowsProcessors * @methodOf ui.grid.class:Grid * @param {Array[GridRow]} The array of "renderable" rows * @param {Array[GridColumn]} The array of columns * @description Run all the registered rows processors on the array of renderable rows */ Grid.prototype.processRowsProcessors = function processRowsProcessors(renderableRows) { var self = this; // Create a shallow copy of the rows so that we can safely sort them without altering the original grid.rows sort order var myRenderableRows = renderableRows.slice(0); // Return myRenderableRows with no processing if we have no rows processors if (self.rowsProcessors.length === 0) { return $q.when(myRenderableRows); } // Counter for iterating through rows processors var i = 0; // Promise for when we're done with all the processors var finished = $q.defer(); // This function will call the processor in self.rowsProcessors at index 'i', and then // when done will call the next processor in the list, using the output from the processor // at i as the argument for 'renderedRowsToProcess' on the next iteration. // // If we're at the end of the list of processors, we resolve our 'finished' callback with // the result. function startProcessor(i, renderedRowsToProcess) { // Get the processor at 'i' var processor = self.rowsProcessors[i].processor; // Call the processor, passing in the rows to process and the current columns // (note: it's wrapped in $q.when() in case the processor does not return a promise) return $q.when( processor.call(self, renderedRowsToProcess, self.columns) ) .then(function handleProcessedRows(processedRows) { // Check for errors if (!processedRows) { throw "Processor at index " + i + " did not return a set of renderable rows"; } if (!angular.isArray(processedRows)) { throw "Processor at index " + i + " did not return an array"; } // Processor is done, increment the counter i++; // If we're not done with the processors, call the next one if (i <= self.rowsProcessors.length - 1) { return startProcessor(i, processedRows); } // We're done! Resolve the 'finished' promise else { finished.resolve(processedRows); } }); } // Start on the first processor startProcessor(0, myRenderableRows); return finished.promise; }; Grid.prototype.setVisibleRows = function setVisibleRows(rows) { var self = this; // Reset all the render container row caches for (var i in self.renderContainers) { var container = self.renderContainers[i]; container.canvasHeightShouldUpdate = true; if ( typeof(container.visibleRowCache) === 'undefined' ){ container.visibleRowCache = []; } else { container.visibleRowCache.length = 0; } } // rows.forEach(function (row) { for (var ri = 0; ri < rows.length; ri++) { var row = rows[ri]; var targetContainer = (typeof(row.renderContainer) !== 'undefined' && row.renderContainer) ? row.renderContainer : 'body'; // If the row is visible if (row.visible) { self.renderContainers[targetContainer].visibleRowCache.push(row); } } self.api.core.raise.rowsRendered(this.api); }; /** * @ngdoc function * @name registerColumnsProcessor * @methodOf ui.grid.class:Grid * @param {function(renderedColumnsToProcess, rows)} columnProcessor column processor function, which * is run in the context of the grid (i.e. this for the function will be the grid), and * which must return an updated renderedColumnsToProcess which can be passed to the next processor * in the chain * @param {number} priority the priority of this processor. In general we try to do them in 100s to leave room * for other people to inject columns processors at intermediate priorities. Lower priority columnsProcessors run earlier. * * At present all rows visible is running at 50, filter is running at 100, sort is at 200, grouping at 400, selectable rows at 500, pagination at 900 (pagination will generally want to be last) * @description Register a "columns processor" function. When the columns are updated, the grid calls each registered "columns processor", which has a chance to alter the set of columns, as long as the count is not modified. */ Grid.prototype.registerColumnsProcessor = function registerColumnsProcessor(processor, priority) { if (!angular.isFunction(processor)) { throw 'Attempt to register non-function rows processor: ' + processor; } this.columnsProcessors.push({processor: processor, priority: priority}); this.columnsProcessors.sort(function sortByPriority( a, b ){ return a.priority - b.priority; }); }; Grid.prototype.removeColumnsProcessor = function removeColumnsProcessor(processor) { var idx = this.columnsProcessors.indexOf(processor); if (typeof(idx) !== 'undefined' && idx !== undefined) { this.columnsProcessors.splice(idx, 1); } }; Grid.prototype.processColumnsProcessors = function processColumnsProcessors(renderableColumns) { var self = this; // Create a shallow copy of the rows so that we can safely sort them without altering the original grid.rows sort order var myRenderableColumns = renderableColumns.slice(0); // Return myRenderableRows with no processing if we have no rows processors if (self.columnsProcessors.length === 0) { return $q.when(myRenderableColumns); } // Counter for iterating through rows processors var i = 0; // Promise for when we're done with all the processors var finished = $q.defer(); // This function will call the processor in self.rowsProcessors at index 'i', and then // when done will call the next processor in the list, using the output from the processor // at i as the argument for 'renderedRowsToProcess' on the next iteration. // // If we're at the end of the list of processors, we resolve our 'finished' callback with // the result. function startProcessor(i, renderedColumnsToProcess) { // Get the processor at 'i' var processor = self.columnsProcessors[i].processor; // Call the processor, passing in the rows to process and the current columns // (note: it's wrapped in $q.when() in case the processor does not return a promise) return $q.when( processor.call(self, renderedColumnsToProcess, self.rows) ) .then(function handleProcessedRows(processedColumns) { // Check for errors if (!processedColumns) { throw "Processor at index " + i + " did not return a set of renderable rows"; } if (!angular.isArray(processedColumns)) { throw "Processor at index " + i + " did not return an array"; } // Processor is done, increment the counter i++; // If we're not done with the processors, call the next one if (i <= self.columnsProcessors.length - 1) { return startProcessor(i, myRenderableColumns); } // We're done! Resolve the 'finished' promise else { finished.resolve(myRenderableColumns); } }); } // Start on the first processor startProcessor(0, myRenderableColumns); return finished.promise; }; Grid.prototype.setVisibleColumns = function setVisibleColumns(columns) { // gridUtil.logDebug('setVisibleColumns'); var self = this; // Reset all the render container row caches for (var i in self.renderContainers) { var container = self.renderContainers[i]; container.visibleColumnCache.length = 0; } for (var ci = 0; ci < columns.length; ci++) { var column = columns[ci]; // If the column is visible if (column.visible) { // If the column has a container specified if (typeof(column.renderContainer) !== 'undefined' && column.renderContainer) { self.renderContainers[column.renderContainer].visibleColumnCache.push(column); } // If not, put it into the body container else { self.renderContainers.body.visibleColumnCache.push(column); } } } }; /** * @ngdoc function * @name handleWindowResize * @methodOf ui.grid.class:Grid * @description Triggered when the browser window resizes; automatically resizes the grid */ Grid.prototype.handleWindowResize = function handleWindowResize($event) { var self = this; self.gridWidth = gridUtil.elementWidth(self.element); self.gridHeight = gridUtil.elementHeight(self.element); self.queueRefresh(); }; /** * @ngdoc function * @name queueRefresh * @methodOf ui.grid.class:Grid * @description queues a grid refreshCanvas, a way of debouncing all the refreshes we might otherwise issue */ Grid.prototype.queueRefresh = function queueRefresh() { var self = this; if (self.refreshCanceller) { $timeout.cancel(self.refreshCanceller); } self.refreshCanceller = $timeout(function () { self.refreshCanvas(true); }); self.refreshCanceller.then(function () { self.refreshCanceller = null; }); return self.refreshCanceller; }; /** * @ngdoc function * @name queueGridRefresh * @methodOf ui.grid.class:Grid * @description queues a grid refresh, a way of debouncing all the refreshes we might otherwise issue */ Grid.prototype.queueGridRefresh = function queueGridRefresh() { var self = this; if (self.gridRefreshCanceller) { $timeout.cancel(self.gridRefreshCanceller); } self.gridRefreshCanceller = $timeout(function () { self.refresh(true); }); self.gridRefreshCanceller.then(function () { self.gridRefreshCanceller = null; }); return self.gridRefreshCanceller; }; /** * @ngdoc function * @name updateCanvasHeight * @methodOf ui.grid.class:Grid * @description flags all render containers to update their canvas height */ Grid.prototype.updateCanvasHeight = function updateCanvasHeight() { var self = this; for (var containerId in self.renderContainers) { if (self.renderContainers.hasOwnProperty(containerId)) { var container = self.renderContainers[containerId]; container.canvasHeightShouldUpdate = true; } } }; /** * @ngdoc function * @name buildStyles * @methodOf ui.grid.class:Grid * @description calls each styleComputation function */ // TODO: this used to take $scope, but couldn't see that it was used Grid.prototype.buildStyles = function buildStyles() { // gridUtil.logDebug('buildStyles'); var self = this; self.customStyles = ''; self.styleComputations .sort(function(a, b) { if (a.priority === null) { return 1; } if (b.priority === null) { return -1; } if (a.priority === null && b.priority === null) { return 0; } return a.priority - b.priority; }) .forEach(function (compInfo) { // this used to provide $scope as a second parameter, but I couldn't find any // style builders that used it, so removed it as part of moving to grid from controller var ret = compInfo.func.call(self); if (angular.isString(ret)) { self.customStyles += '\n' + ret; } }); }; Grid.prototype.minColumnsToRender = function minColumnsToRender() { var self = this; var viewport = this.getViewportWidth(); var min = 0; var totalWidth = 0; self.columns.forEach(function(col, i) { if (totalWidth < viewport) { totalWidth += col.drawnWidth; min++; } else { var currWidth = 0; for (var j = i; j >= i - min; j--) { currWidth += self.columns[j].drawnWidth; } if (currWidth < viewport) { min++; } } }); return min; }; Grid.prototype.getBodyHeight = function getBodyHeight() { // Start with the viewportHeight var bodyHeight = this.getViewportHeight(); // Add the horizontal scrollbar height if there is one //if (typeof(this.horizontalScrollbarHeight) !== 'undefined' && this.horizontalScrollbarHeight !== undefined && this.horizontalScrollbarHeight > 0) { // bodyHeight = bodyHeight + this.horizontalScrollbarHeight; //} return bodyHeight; }; // NOTE: viewport drawable height is the height of the grid minus the header row height (including any border) // TODO(c0bra): account for footer height Grid.prototype.getViewportHeight = function getViewportHeight() { var self = this; var viewPortHeight = this.gridHeight - this.headerHeight - this.footerHeight; // Account for native horizontal scrollbar, if present //if (typeof(this.horizontalScrollbarHeight) !== 'undefined' && this.horizontalScrollbarHeight !== undefined && this.horizontalScrollbarHeight > 0) { // viewPortHeight = viewPortHeight - this.horizontalScrollbarHeight; //} var adjustment = self.getViewportAdjustment(); viewPortHeight = viewPortHeight + adjustment.height; //gridUtil.logDebug('viewPortHeight', viewPortHeight); return viewPortHeight; }; Grid.prototype.getViewportWidth = function getViewportWidth() { var self = this; var viewPortWidth = this.gridWidth; //if (typeof(this.verticalScrollbarWidth) !== 'undefined' && this.verticalScrollbarWidth !== undefined && this.verticalScrollbarWidth > 0) { // viewPortWidth = viewPortWidth - this.verticalScrollbarWidth; //} var adjustment = self.getViewportAdjustment(); viewPortWidth = viewPortWidth + adjustment.width; //gridUtil.logDebug('getviewPortWidth', viewPortWidth); return viewPortWidth; }; Grid.prototype.getHeaderViewportWidth = function getHeaderViewportWidth() { var viewPortWidth = this.getViewportWidth(); //if (typeof(this.verticalScrollbarWidth) !== 'undefined' && this.verticalScrollbarWidth !== undefined && this.verticalScrollbarWidth > 0) { // viewPortWidth = viewPortWidth + this.verticalScrollbarWidth; //} return viewPortWidth; }; Grid.prototype.addVerticalScrollSync = function (containerId, callBackFn) { this.verticalScrollSyncCallBackFns[containerId] = callBackFn; }; Grid.prototype.addHorizontalScrollSync = function (containerId, callBackFn) { this.horizontalScrollSyncCallBackFns[containerId] = callBackFn; }; /** * Scroll needed containers by calling their ScrollSyncs * @param sourceContainerId the containerId that has already set it's top/left. * can be empty string which means all containers need to set top/left * @param scrollEvent */ Grid.prototype.scrollContainers = function (sourceContainerId, scrollEvent) { if (scrollEvent.y) { //default for no container Id (ex. mousewheel means that all containers must set scrollTop/Left) var verts = ['body','left', 'right']; this.flagScrollingVertically(scrollEvent); if (sourceContainerId === 'body') { verts = ['left', 'right']; } else if (sourceContainerId === 'left') { verts = ['body', 'right']; } else if (sourceContainerId === 'right') { verts = ['body', 'left']; } for (var i = 0; i < verts.length; i++) { var id = verts[i]; if (this.verticalScrollSyncCallBackFns[id]) { this.verticalScrollSyncCallBackFns[id](scrollEvent); } } } if (scrollEvent.x) { //default for no container Id (ex. mousewheel means that all containers must set scrollTop/Left) var horizs = ['body','bodyheader', 'bodyfooter']; this.flagScrollingHorizontally(scrollEvent); if (sourceContainerId === 'body') { horizs = ['bodyheader', 'bodyfooter']; } for (var j = 0; j < horizs.length; j++) { var idh = horizs[j]; if (this.horizontalScrollSyncCallBackFns[idh]) { this.horizontalScrollSyncCallBackFns[idh](scrollEvent); } } } }; Grid.prototype.registerViewportAdjuster = function registerViewportAdjuster(func) { this.viewportAdjusters.push(func); }; Grid.prototype.removeViewportAdjuster = function registerViewportAdjuster(func) { var idx = this.viewportAdjusters.indexOf(func); if (typeof(idx) !== 'undefined' && idx !== undefined) { this.viewportAdjusters.splice(idx, 1); } }; Grid.prototype.getViewportAdjustment = function getViewportAdjustment() { var self = this; var adjustment = { height: 0, width: 0 }; self.viewportAdjusters.forEach(function (func) { adjustment = func.call(this, adjustment); }); return adjustment; }; Grid.prototype.getVisibleRowCount = function getVisibleRowCount() { // var count = 0; // this.rows.forEach(function (row) { // if (row.visible) { // count++; // } // }); // return this.visibleRowCache.length; return this.renderContainers.body.visibleRowCache.length; }; Grid.prototype.getVisibleRows = function getVisibleRows() { return this.renderContainers.body.visibleRowCache; }; Grid.prototype.getVisibleColumnCount = function getVisibleColumnCount() { // var count = 0; // this.rows.forEach(function (row) { // if (row.visible) { // count++; // } // }); // return this.visibleRowCache.length; return this.renderContainers.body.visibleColumnCache.length; }; Grid.prototype.searchRows = function searchRows(renderableRows) { return rowSearcher.search(this, renderableRows, this.columns); }; Grid.prototype.sortByColumn = function sortByColumn(renderableRows) { return rowSorter.sort(this, renderableRows, this.columns); }; /** * @ngdoc function * @name getCellValue * @methodOf ui.grid.class:Grid * @description Gets the value of a cell for a particular row and column * @param {GridRow} row Row to access * @param {GridColumn} col Column to access */ Grid.prototype.getCellValue = function getCellValue(row, col){ if ( typeof(row.entity[ '$$' + col.uid ]) !== 'undefined' ) { return row.entity[ '$$' + col.uid].rendered; } else if (this.options.flatEntityAccess && typeof(col.field) !== 'undefined' ){ return row.entity[col.field]; } else { if (!col.cellValueGetterCache) { col.cellValueGetterCache = $parse(row.getEntityQualifiedColField(col)); } return col.cellValueGetterCache(row); } }; /** * @ngdoc function * @name getCellDisplayValue * @methodOf ui.grid.class:Grid * @description Gets the displayed value of a cell after applying any the `cellFilter` * @param {GridRow} row Row to access * @param {GridColumn} col Column to access */ Grid.prototype.getCellDisplayValue = function getCellDisplayValue(row, col) { if ( !col.cellDisplayGetterCache ) { var custom_filter = col.cellFilter ? " | " + col.cellFilter : ""; if (typeof(row.entity['$$' + col.uid]) !== 'undefined') { col.cellDisplayGetterCache = $parse(row.entity['$$' + col.uid].rendered + custom_filter); } else if (this.options.flatEntityAccess && typeof(col.field) !== 'undefined') { col.cellDisplayGetterCache = $parse(row.entity[col.field] + custom_filter); } else { col.cellDisplayGetterCache = $parse(row.getEntityQualifiedColField(col) + custom_filter); } } return col.cellDisplayGetterCache(row); }; Grid.prototype.getNextColumnSortPriority = function getNextColumnSortPriority() { var self = this, p = 0; self.columns.forEach(function (col) { if (col.sort && col.sort.priority && col.sort.priority > p) { p = col.sort.priority; } }); return p + 1; }; /** * @ngdoc function * @name resetColumnSorting * @methodOf ui.grid.class:Grid * @description Return the columns that the grid is currently being sorted by * @param {GridColumn} [excludedColumn] Optional GridColumn to exclude from having its sorting reset */ Grid.prototype.resetColumnSorting = function resetColumnSorting(excludeCol) { var self = this; self.columns.forEach(function (col) { if (col !== excludeCol && !col.suppressRemoveSort) { col.sort = {}; } }); }; /** * @ngdoc function * @name getColumnSorting * @methodOf ui.grid.class:Grid * @description Return the columns that the grid is currently being sorted by * @returns {Array[GridColumn]} An array of GridColumn objects */ Grid.prototype.getColumnSorting = function getColumnSorting() { var self = this; var sortedCols = [], myCols; // Iterate through all the columns, sorted by priority // Make local copy of column list, because sorting is in-place and we do not want to // change the original sequence of columns myCols = self.columns.slice(0); myCols.sort(rowSorter.prioritySort).forEach(function (col) { if (col.sort && typeof(col.sort.direction) !== 'undefined' && col.sort.direction && (col.sort.direction === uiGridConstants.ASC || col.sort.direction === uiGridConstants.DESC)) { sortedCols.push(col); } }); return sortedCols; }; /** * @ngdoc function * @name sortColumn * @methodOf ui.grid.class:Grid * @description Set the sorting on a given column, optionally resetting any existing sorting on the Grid. * Emits the sortChanged event whenever the sort criteria are changed. * @param {GridColumn} column Column to set the sorting on * @param {uiGridConstants.ASC|uiGridConstants.DESC} [direction] Direction to sort by, either descending or ascending. * If not provided, the column will iterate through the sort directions * specified in the {@link ui.grid.class:GridOptions.columnDef#sortDirectionCycle sortDirectionCycle} attribute. * @param {boolean} [add] Add this column to the sorting. If not provided or set to `false`, the Grid will reset any existing sorting and sort * by this column only * @returns {Promise} A resolved promise that supplies the column. */ Grid.prototype.sortColumn = function sortColumn(column, directionOrAdd, add) { var self = this, direction = null; if (typeof(column) === 'undefined' || !column) { throw new Error('No column parameter provided'); } // Second argument can either be a direction or whether to add this column to the existing sort. // If it's a boolean, it's an add, otherwise, it's a direction if (typeof(directionOrAdd) === 'boolean') { add = directionOrAdd; } else { direction = directionOrAdd; } if (!add) { self.resetColumnSorting(column); column.sort.priority = 0; // Get the actual priority since there may be columns which have suppressRemoveSort set column.sort.priority = self.getNextColumnSortPriority(); } else if (!column.sort.priority){ column.sort.priority = self.getNextColumnSortPriority(); } if (!direction) { // Find the current position in the cycle (or -1). var i = column.sortDirectionCycle.indexOf(column.sort.direction ? column.sort.direction : null); // Proceed to the next position in the cycle (or start at the beginning). i = (i+1) % column.sortDirectionCycle.length; // If suppressRemoveSort is set, and the next position in the cycle would // remove the sort, skip it. if (column.colDef && column.suppressRemoveSort && !column.sortDirectionCycle[i]) { i = (i+1) % column.sortDirectionCycle.length; } if (column.sortDirectionCycle[i]) { column.sort.direction = column.sortDirectionCycle[i]; } else { column.sort = {}; } } else { column.sort.direction = direction; } self.api.core.raise.sortChanged( self, self.getColumnSorting() ); return $q.when(column); }; /** * communicate to outside world that we are done with initial rendering */ Grid.prototype.renderingComplete = function(){ if (angular.isFunction(this.options.onRegisterApi)) { this.options.onRegisterApi(this.api); } this.api.core.raise.renderingComplete( this.api ); }; Grid.prototype.createRowHashMap = function createRowHashMap() { var self = this; var hashMap = new RowHashMap(); hashMap.grid = self; return hashMap; }; /** * @ngdoc function * @name refresh * @methodOf ui.grid.class:Grid * @description Refresh the rendered grid on screen. * @param {boolean} [rowsAltered] Optional flag for refreshing when the number of rows has changed. */ Grid.prototype.refresh = function refresh(rowsAltered) { var self = this; var p1 = self.processRowsProcessors(self.rows).then(function (renderableRows) { self.setVisibleRows(renderableRows); }); var p2 = self.processColumnsProcessors(self.columns).then(function (renderableColumns) { self.setVisibleColumns(renderableColumns); }); return $q.all([p1, p2]).then(function () { self.redrawInPlace(rowsAltered); self.refreshCanvas(true); }); }; /** * @ngdoc function * @name refreshRows * @methodOf ui.grid.class:Grid * @description Refresh the rendered rows on screen? Note: not functional at present * @returns {promise} promise that is resolved when render completes? * */ Grid.prototype.refreshRows = function refreshRows() { var self = this; return self.processRowsProcessors(self.rows) .then(function (renderableRows) { self.setVisibleRows(renderableRows); self.redrawInPlace(); self.refreshCanvas( true ); }); }; /** * @ngdoc function * @name refreshCanvas * @methodOf ui.grid.class:Grid * @description Builds all styles and recalculates much of the grid sizing * @param {object} buildStyles optional parameter. Use TBD * @returns {promise} promise that is resolved when the canvas * has been refreshed * */ Grid.prototype.refreshCanvas = function(buildStyles) { var self = this; if (buildStyles) { self.buildStyles(); } var p = $q.defer(); // Get all the header heights var containerHeadersToRecalc = []; for (var containerId in self.renderContainers) { if (self.renderContainers.hasOwnProperty(containerId)) { var container = self.renderContainers[containerId]; // Skip containers that have no canvasWidth set yet if (container.canvasWidth === null || isNaN(container.canvasWidth)) { continue; } if (container.header || container.headerCanvas) { container.explicitHeaderHeight = container.explicitHeaderHeight || null; container.explicitHeaderCanvasHeight = container.explicitHeaderCanvasHeight || null; containerHeadersToRecalc.push(container); } } } /* * * Here we loop through the headers, measuring each element as well as any header "canvas" it has within it. * * If any header is less than the largest header height, it will be resized to that so that we don't have headers * with different heights, which looks like a rendering problem * * We'll do the same thing with the header canvases, and give the header CELLS an explicit height if their canvas * is smaller than the largest canvas height. That was header cells without extra controls like filtering don't * appear shorter than other cells. * */ if (containerHeadersToRecalc.length > 0) { // Build the styles without the explicit header heights if (buildStyles) { self.buildStyles(); } // Putting in a timeout as it's not calculating after the grid element is rendered and filled out $timeout(function() { // var oldHeaderHeight = self.grid.headerHeight; // self.grid.headerHeight = gridUtil.outerElementHeight(self.header); var rebuildStyles = false; // Get all the header heights var maxHeaderHeight = 0; var maxHeaderCanvasHeight = 0; var i, container; var getHeight = function(oldVal, newVal){ if ( oldVal !== newVal){ rebuildStyles = true; } return newVal; }; for (i = 0; i < containerHeadersToRecalc.length; i++) { container = containerHeadersToRecalc[i]; // Skip containers that have no canvasWidth set yet if (container.canvasWidth === null || isNaN(container.canvasWidth)) { continue; } if (container.header) { var headerHeight = container.headerHeight = getHeight(container.headerHeight, parseInt(gridUtil.outerElementHeight(container.header), 10)); // Get the "inner" header height, that is the height minus the top and bottom borders, if present. We'll use it to make sure all the headers have a consistent height var topBorder = gridUtil.getBorderSize(container.header, 'top'); var bottomBorder = gridUtil.getBorderSize(container.header, 'bottom'); var innerHeaderHeight = parseInt(headerHeight - topBorder - bottomBorder, 10); innerHeaderHeight = innerHeaderHeight < 0 ? 0 : innerHeaderHeight; container.innerHeaderHeight = innerHeaderHeight; // If the header doesn't have an explicit height set, save the largest header height for use later // Explicit header heights are based off of the max we are calculating here. We never want to base the max on something we're setting explicitly if (!container.explicitHeaderHeight && innerHeaderHeight > maxHeaderHeight) { maxHeaderHeight = innerHeaderHeight; } } if (container.headerCanvas) { var headerCanvasHeight = container.headerCanvasHeight = getHeight(container.headerCanvasHeight, parseInt(gridUtil.outerElementHeight(container.headerCanvas), 10)); // If the header doesn't have an explicit canvas height, save the largest header canvas height for use later // Explicit header heights are based off of the max we are calculating here. We never want to base the max on something we're setting explicitly if (!container.explicitHeaderCanvasHeight && headerCanvasHeight > maxHeaderCanvasHeight) { maxHeaderCanvasHeight = headerCanvasHeight; } } } // Go through all the headers for (i = 0; i < containerHeadersToRecalc.length; i++) { container = containerHeadersToRecalc[i]; /* If: 1. We have a max header height 2. This container has a header height defined 3. And either this container has an explicit header height set, OR its header height is less than the max then: Give this container's header an explicit height so it will line up with the tallest header */ if ( maxHeaderHeight > 0 && typeof(container.headerHeight) !== 'undefined' && container.headerHeight !== null && (container.explicitHeaderHeight || container.headerHeight < maxHeaderHeight) ) { container.explicitHeaderHeight = getHeight(container.explicitHeaderHeight, maxHeaderHeight); } // Do the same as above except for the header canvas if ( maxHeaderCanvasHeight > 0 && typeof(container.headerCanvasHeight) !== 'undefined' && container.headerCanvasHeight !== null && (container.explicitHeaderCanvasHeight || container.headerCanvasHeight < maxHeaderCanvasHeight) ) { container.explicitHeaderCanvasHeight = getHeight(container.explicitHeaderCanvasHeight, maxHeaderCanvasHeight); } } // Rebuild styles if the header height has changed // The header height is used in body/viewport calculations and those are then used in other styles so we need it to be available if (buildStyles && rebuildStyles) { self.buildStyles(); } p.resolve(); }); } else { // Timeout still needs to be here to trigger digest after styles have been rebuilt $timeout(function() { p.resolve(); }); } return p.promise; }; /** * @ngdoc function * @name redrawCanvas * @methodOf ui.grid.class:Grid * @description Redraw the rows and columns based on our current scroll position * @param {boolean} [rowsAdded] Optional to indicate rows are added and the scroll percentage must be recalculated * */ Grid.prototype.redrawInPlace = function redrawInPlace(rowsAdded) { // gridUtil.logDebug('redrawInPlace'); var self = this; for (var i in self.renderContainers) { var container = self.renderContainers[i]; // gridUtil.logDebug('redrawing container', i); if (rowsAdded) { container.adjustRows(container.prevScrollTop, null); container.adjustColumns(container.prevScrollLeft, null); } else { container.adjustRows(null, container.prevScrolltopPercentage); container.adjustColumns(null, container.prevScrollleftPercentage); } } }; /** * @ngdoc function * @name hasLeftContainerColumns * @methodOf ui.grid.class:Grid * @description returns true if leftContainer has columns */ Grid.prototype.hasLeftContainerColumns = function () { return this.hasLeftContainer() && this.renderContainers.left.renderedColumns.length > 0; }; /** * @ngdoc function * @name hasRightContainerColumns * @methodOf ui.grid.class:Grid * @description returns true if rightContainer has columns */ Grid.prototype.hasRightContainerColumns = function () { return this.hasRightContainer() && this.renderContainers.right.renderedColumns.length > 0; }; /** * @ngdoc method * @methodOf ui.grid.class:Grid * @name scrollToIfNecessary * @description Scrolls the grid to make a certain row and column combo visible, * in the case that it is not completely visible on the screen already. * @param {GridRow} gridRow row to make visible * @param {GridCol} gridCol column to make visible * @returns {promise} a promise that is resolved when scrolling is complete */ Grid.prototype.scrollToIfNecessary = function (gridRow, gridCol) { var self = this; var scrollEvent = new ScrollEvent(self, 'uiGrid.scrollToIfNecessary'); // Alias the visible row and column caches var visRowCache = self.renderContainers.body.visibleRowCache; var visColCache = self.renderContainers.body.visibleColumnCache; /*-- Get the top, left, right, and bottom "scrolled" edges of the grid --*/ // The top boundary is the current Y scroll position PLUS the header height, because the header can obscure rows when the grid is scrolled downwards var topBound = self.renderContainers.body.prevScrollTop + self.headerHeight; // Don't the let top boundary be less than 0 topBound = (topBound < 0) ? 0 : topBound; // The left boundary is the current X scroll position var leftBound = self.renderContainers.body.prevScrollLeft; // The bottom boundary is the current Y scroll position, plus the height of the grid, but minus the header height. // Basically this is the viewport height added on to the scroll position var bottomBound = self.renderContainers.body.prevScrollTop + self.gridHeight - self.renderContainers.body.headerHeight - self.footerHeight - self.scrollbarWidth; // If there's a horizontal scrollbar, remove its height from the bottom boundary, otherwise we'll be letting it obscure rows //if (self.horizontalScrollbarHeight) { // bottomBound = bottomBound - self.horizontalScrollbarHeight; //} // The right position is the current X scroll position minus the grid width var rightBound = self.renderContainers.body.prevScrollLeft + Math.ceil(self.gridWidth); // If there's a vertical scrollbar, subtract it from the right boundary or we'll allow it to obscure cells //if (self.verticalScrollbarWidth) { // rightBound = rightBound - self.verticalScrollbarWidth; //} // We were given a row to scroll to if (gridRow !== null) { // This is the index of the row we want to scroll to, within the list of rows that can be visible var seekRowIndex = visRowCache.indexOf(gridRow); // Total vertical scroll length of the grid var scrollLength = (self.renderContainers.body.getCanvasHeight() - self.renderContainers.body.getViewportHeight()); // Add the height of the native horizontal scrollbar to the scroll length, if it's there. Otherwise it will mask over the final row //if (self.horizontalScrollbarHeight && self.horizontalScrollbarHeight > 0) { // scrollLength = scrollLength + self.horizontalScrollbarHeight; //} // This is the minimum amount of pixels we need to scroll vertical in order to see this row. var pixelsToSeeRow = ((seekRowIndex + 1) * self.options.rowHeight); // Don't let the pixels required to see the row be less than zero pixelsToSeeRow = (pixelsToSeeRow < 0) ? 0 : pixelsToSeeRow; var scrollPixels, percentage; // If the scroll position we need to see the row is LESS than the top boundary, i.e. obscured above the top of the self... if (pixelsToSeeRow < topBound) { // Get the different between the top boundary and the required scroll position and subtract it from the current scroll position\ // to get the full position we need scrollPixels = self.renderContainers.body.prevScrollTop - (topBound - pixelsToSeeRow); // Turn the scroll position into a percentage and make it an argument for a scroll event percentage = scrollPixels / scrollLength; scrollEvent.y = { percentage: percentage }; } // Otherwise if the scroll position we need to see the row is MORE than the bottom boundary, i.e. obscured below the bottom of the self... else if (pixelsToSeeRow > bottomBound) { // Get the different between the bottom boundary and the required scroll position and add it to the current scroll position // to get the full position we need scrollPixels = pixelsToSeeRow - bottomBound + self.renderContainers.body.prevScrollTop; // Turn the scroll position into a percentage and make it an argument for a scroll event percentage = scrollPixels / scrollLength; scrollEvent.y = { percentage: percentage }; } } // We were given a column to scroll to if (gridCol !== null) { // This is the index of the row we want to scroll to, within the list of rows that can be visible var seekColumnIndex = visColCache.indexOf(gridCol); // Total vertical scroll length of the grid var horizScrollLength = (self.renderContainers.body.getCanvasWidth() - self.renderContainers.body.getViewportWidth()); // Add the height of the native horizontal scrollbar to the scroll length, if it's there. Otherwise it will mask over the final row // if (self.verticalScrollbarWidth && self.verticalScrollbarWidth > 0) { // horizScrollLength = horizScrollLength + self.verticalScrollbarWidth; // } // This is the minimum amount of pixels we need to scroll vertical in order to see this column var columnLeftEdge = 0; for (var i = 0; i < seekColumnIndex; i++) { var col = visColCache[i]; columnLeftEdge += col.drawnWidth; } columnLeftEdge = (columnLeftEdge < 0) ? 0 : columnLeftEdge; var pinnedLeftWidth = self.renderContainers.left ? self.renderContainers.left.getViewportWidth() : 0; var columnRightEdge = columnLeftEdge + gridCol.drawnWidth + pinnedLeftWidth; // Don't let the pixels required to see the column be less than zero columnRightEdge = (columnRightEdge < 0) ? 0 : columnRightEdge; var horizScrollPixels, horizPercentage; // If the scroll position we need to see the row is LESS than the top boundary, i.e. obscured above the top of the self... if (columnLeftEdge < leftBound) { // Get the different between the top boundary and the required scroll position and subtract it from the current scroll position\ // to get the full position we need horizScrollPixels = self.renderContainers.body.prevScrollLeft - (leftBound - columnLeftEdge); // Turn the scroll position into a percentage and make it an argument for a scroll event horizPercentage = horizScrollPixels / horizScrollLength; horizPercentage = (horizPercentage > 1) ? 1 : horizPercentage; scrollEvent.x = { percentage: horizPercentage }; } // Otherwise if the scroll position we need to see the row is MORE than the bottom boundary, i.e. obscured below the bottom of the self... else if (columnRightEdge > rightBound) { // Get the different between the bottom boundary and the required scroll position and add it to the current scroll position // to get the full position we need horizScrollPixels = columnRightEdge - rightBound + self.renderContainers.body.prevScrollLeft; // Turn the scroll position into a percentage and make it an argument for a scroll event horizPercentage = horizScrollPixels / horizScrollLength; horizPercentage = (horizPercentage > 1) ? 1 : horizPercentage; scrollEvent.x = { percentage: horizPercentage }; } } var deferred = $q.defer(); // If we need to scroll on either the x or y axes, fire a scroll event if (scrollEvent.y || scrollEvent.x) { scrollEvent.withDelay = false; self.scrollContainers('',scrollEvent); var dereg = self.api.core.on.scrollEnd(null,function() { deferred.resolve(scrollEvent); dereg(); }); } else { deferred.resolve(); } return deferred.promise; }; /** * @ngdoc method * @methodOf ui.grid.class:Grid * @name scrollTo * @description Scroll the grid such that the specified * row and column is in view * @param {object} rowEntity gridOptions.data[] array instance to make visible * @param {object} colDef to make visible * @returns {promise} a promise that is resolved after any scrolling is finished */ Grid.prototype.scrollTo = function (rowEntity, colDef) { var gridRow = null, gridCol = null; if (rowEntity !== null && typeof(rowEntity) !== 'undefined' ) { gridRow = this.getRow(rowEntity); } if (colDef !== null && typeof(colDef) !== 'undefined' ) { gridCol = this.getColumn(colDef.name ? colDef.name : colDef.field); } return this.scrollToIfNecessary(gridRow, gridCol); }; /** * @ngdoc function * @name clearAllFilters * @methodOf ui.grid.class:Grid * @description Clears all filters and optionally refreshes the visible rows. * @param {object} refreshRows Defaults to true. * @param {object} clearConditions Defaults to false. * @param {object} clearFlags Defaults to false. * @returns {promise} If `refreshRows` is true, returns a promise of the rows refreshing. */ Grid.prototype.clearAllFilters = function clearAllFilters(refreshRows, clearConditions, clearFlags) { // Default `refreshRows` to true because it will be the most commonly desired behaviour. if (refreshRows === undefined) { refreshRows = true; } if (clearConditions === undefined) { clearConditions = false; } if (clearFlags === undefined) { clearFlags = false; } this.columns.forEach(function(column) { column.filters.forEach(function(filter) { filter.term = undefined; if (clearConditions) { filter.condition = undefined; } if (clearFlags) { filter.flags = undefined; } }); }); if (refreshRows) { return this.refreshRows(); } }; // Blatantly stolen from Angular as it isn't exposed (yet? 2.0?) function RowHashMap() {} RowHashMap.prototype = { /** * Store key value pair * @param key key to store can be any type * @param value value to store can be any type */ put: function(key, value) { this[this.grid.options.rowIdentity(key)] = value; }, /** * @param key * @returns {Object} the value for the key */ get: function(key) { return this[this.grid.options.rowIdentity(key)]; }, /** * Remove the key/value pair * @param key */ remove: function(key) { var value = this[key = this.grid.options.rowIdentity(key)]; delete this[key]; return value; } }; return Grid; }]); })();
import regionSettingsMessages from 'ringcentral-integration/modules/RegionSettings/regionSettingsMessages'; export default { region: "Región", [regionSettingsMessages.saveSuccess]: "La configuración se guardó correctamente.", [regionSettingsMessages.dialingPlansChanged]: "Su cuenta ya no se admite para su cuenta.\n Verifique su nueva {regionSettingsLink}.", regionSettings: "configuración de región", [regionSettingsMessages.areaCodeInvalid]: "Ingrese un código de área válido." }; // @key: @#@"region"@#@ @source: @#@"Region"@#@ // @key: @#@"[regionSettingsMessages.saveSuccess]"@#@ @source: @#@"Settings saved successfully."@#@ // @key: @#@"[regionSettingsMessages.dialingPlansChanged]"@#@ @source: @#@"The previous region is no longer supported for your account.\n Please verify your new {regionSettingsLink}."@#@ // @key: @#@"regionSettings"@#@ @source: @#@"region settings"@#@ // @key: @#@"[regionSettingsMessages.areaCodeInvalid]"@#@ @source: @#@"Please enter a valid area code."@#@
var hasOwn = {}.hasOwnProperty; var toString = {}.toString; var utils = module.exports = { isObject: function(o) { return toString.call(o) === '[object Object]'; }, protoExtend: function(sub) { var Super = this; var Constructor = hasOwn.call(sub, 'constructor') ? sub.constructor : function() { Super.apply(this, arguments); }; Constructor.prototype = Object.create(Super.prototype); for (var i in sub) { if (hasOwn.call(sub, i)) { Constructor.prototype[i] = sub[i]; } } for (i in Super) { if (hasOwn.call(Super, i)) { Constructor[i] = Super[i]; } } return Constructor; }, /** * convert fs.ReadStream to Buffer * * @param {fs.ReadStream} stream * @returns {Promise} */ streamToBuffer: function (stream) { return new Promise(function (resolve, reject) { var buffers = []; stream.on('error', reject); stream.on('data', function (data) { return buffers.push(data); }); stream.on('end', function () { return resolve(Buffer.concat(buffers)); }); }) } };