code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
/************************************************************************ * This file is part of EspoCRM. * * EspoCRM - Open Source CRM application. * Copyright (C) 2014-2022 Yurii Kuznietsov, Taras Machyshyn, Oleksii Avramenko * Website: https://www.espocrm.com * * EspoCRM is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * EspoCRM is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with EspoCRM. If not, see http://www.gnu.org/licenses/. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU General Public License version 3. * * In accordance with Section 7(b) of the GNU General Public License version 3, * these Appropriate Legal Notices must retain the display of the "EspoCRM" word. ************************************************************************/ define('views/admin/entity-manager/fields/icon-class', 'views/fields/base', function (Dep) { return Dep.extend({ editTemplate: 'admin/entity-manager/fields/icon-class/edit', setup: function () { Dep.prototype.setup.call(this); this.events['click [data-action="selectIcon"]'] = function () { this.selectIcon(); }; }, selectIcon: function () { this.createView('dialog', 'views/admin/entity-manager/modals/select-icon', {}, function (view) { view.render(); this.listenToOnce(view, 'select', function (value) { if (value === '') { value = null; } this.model.set(this.name, value); view.close(); }, this); }); }, fetch: function () { var data = {}; data[this.name] = this.model.get(this.name); return data; }, }); });
espocrm/espocrm
client/src/views/admin/entity-manager/fields/icon-class.js
JavaScript
gpl-3.0
2,409
var tap = require('tap') var Nightmare = require('nightmare') var guerrilla = require('../../') var isEmail = require('isemail') tap.test('.getScrambledAddress', function (t) { new Nightmare() .use(guerrilla.getScrambledAddress('dogs', function (email) { t.ok(isEmail(email), 'Gets scrambled email address') })) .run(function (err, nightmare) { if (err) throw err t.end() }) })
LegitTalon/nightmare-guerrilla
tests/spec/getScrambledAddress.js
JavaScript
gpl-3.0
415
// UI functions var getConversation = function (index, options) { options = options ? options : { "from": 0, "howMany": -1 }; try { external.Conversation(index, options.from, options.howMany); } catch (e) { error(e); return; }; }; var appendConversation = function (ol, username, date, index) { var li = document.createElement("li"); li.innerHTML = '<span style="float:left">' +username + "</span><span class='date small'>" + date + "<span>"; li.onclick = function () { window.otherUsername = username; getConversation(index); document.getElementById("textarea").value = ''; document.getElementById("send").disabled = true; this.className += " selected"; }; li.className = "clickable convli"; ol.appendChild(li); }; var appendMessage = function (ol, message, other, date, received) { var li = document.createElement("li"); var text = "<span class='username'>" + (received ? other : window.username) + "</span><span class='date small'>" + date + " </span></div>" + "<br /> " + message; li.className = "message" + (received ? "Left" : "Right"); li.innerHTML = text; ol.appendChild(li); }; function normalizedDate(stringDate) { var date = new Date(parseInt(stringDate.replace(/Date\(([0-9]+)\)/g, "$1").replace(/\//g, ""), 10)); return date.getDay() + "/" + date.getMonth() + "/" + date.getYear() + " - " + date.getHours() + ":" + date.getMinutes(); }; function showNewConversationForm() { var body = document.getElementById("body"), newBody = document.getElementById("newBody"); if (newBody.innerHTML == '') { newBody.innerHTML = '<div><h1 style="float:left; display:inline">New Conversation</h1><span title="Go Back" style="float:right; font-size: 25pt" class="clickable" onclick="showNewConversationForm()">X</span></div><br /><br /><br />' + '<div style="width: 80px">To:</div><input type="text" id="otherone" /><br />' + '<div style="width: 80px">Message:</div><div style="width:59%;float:left"><textarea id="newtextarea" onkeyup="document.getElementById(\'newsend\').disabled = false"></textarea></div>' + '<button disabled id="newsend" class="send" onclick="try { external.Send(document.getElementById(\'otherone\').value, document.getElementById(\'newtextarea\').value); } catch(e) { error(e); return; }; getConversation(0); showNewConversationForm(); location.href = \'#lastMessage\';">Send</button>'; newBody.style.width = '100%'; body.style.display = 'none'; return; } newBody.innerHTML = ''; body.style.display = 'block'; } // Functions called from C# function setUsername(username) { window.username = username; }; function clearConversations() { if (document.getElementById("conversations")) { document.getElementById("conversations").innerHTML = ""; } }; function clearConversation() { if (document.getElementById("conversation")) { document.getElementById("conversation").innerHTML = ""; } }; function error(error) { alert(error.message); } function updateConversations(conversations) { conversations = eval(conversations); for (var c in conversations) { var username = conversations[c].OtherName; var date = normalizedDate(conversations[c].LastDate); appendConversation(document.getElementById("conversations"), username, date, c); } }; function updateMessages(conversation) { var messages = eval(conversation); for (m in messages) { var msg = messages[m]; appendMessage(document.getElementById("conversation"), msg.Text.replace(/(?:\r\n|\r|\n)/g, '<br />'), msg.Conversation.OtherName, normalizedDate(msg.Date), msg.Received); } document.getElementById("conversation").innerHTML += '<div id="lastMessage"></div>'; document.getElementById("form").style.display = 'block'; location.href = "#lastMessage"; };
nerdzeu/nm.net
ClassLibrary1/Resources/js.js
JavaScript
gpl-3.0
3,959
'use strict'; angular.module('civicMakersClientApp') .factory('ProjectApi', function ($q, firebase, $firebaseArray) { function getAllProjects() { var deferred = $q.defer(); var ref = firebase.getRefTo('projects'); var projects = $firebaseArray(ref); projects.$loaded().then(function (results) { deferred.resolve(results); }); return deferred.promise; } function getFirstNProjects(n) { var deferred = $q.defer(); getAllProjects().then(function(projects) { deferred.resolve(projects.slice(0, n)); }); return deferred.promise; } function getProjectsNum() { var deferred = $q.defer(); getAllProjects().then(function(projects) { deferred.resolve(projects.length); }); return deferred.promise; } function queryProject(id) { var deferred = $q.defer(); var ref = firebase.getRefTo('projects/' + id); ref.once('value', function(snapshot) { deferred.resolve(snapshot.val()); }); return deferred.promise; } function saveProject (projectData) { var deferred = $q.defer(); var projectRef = firebase.getRef() .child('projects') .push(projectData, function (error){ if (error) { deferred.resolve(error); } else { deferred.resolve(projectRef.name()); } }); return deferred.promise; } function updateProjectData(projectId, data, nestedUrl) { var projectsBaseUrl = firebase.baseUrl + '/projects'; if (nestedUrl !== undefined) { firebase.updateData(projectsBaseUrl + '/' + projectId, nestedUrl, data); } else { firebase.updateData(projectsBaseUrl, projectId, data); } } return { getAllProjects: getAllProjects, queryProject: queryProject, getFirstNProjects: getFirstNProjects, getProjectsNum: getProjectsNum, saveProject: saveProject, updateProjectData: updateProjectData }; });
civicmakers/client
client/app/factories/ProjectApi/ProjectApi.service.js
JavaScript
gpl-3.0
2,036
/* * Copyright (C) 2016-2022 phantombot.github.io/PhantomBot * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ $.lang.register('bettingsystem.open.usage', 'Usage: !bet open ["title"] ["option1, option2, etc."] [minimum bet] [maximum bet] [close timer mins] - The quotes are needed for the title and options.'); $.lang.register('bettingsystem.open.error', 'You must chose a winning option on the previous bet before you can open a new one. Use !bet close [option]'); $.lang.register('bettingsystem.open.error.opened', 'A bet is already opened.'); $.lang.register('bettingsystem.open.success', 'A bet is now opened! "$1". Bet options: "$2". Bet with: !bet [amount] [option]'); $.lang.register('bettingsystem.close.error.usage', 'The bet is now closed! Waiting on winning result. Use !bet close [winning option]'); $.lang.register('bettingsystem.close.usage', 'Usage: !bet close [winning option]'); $.lang.register('bettingsystem.close.success', 'Bet is now closed! Winning option is $1! Calculating results and giving points to the winners!'); $.lang.register('bettingsystem.close.semi.success', 'The bet is now closed! Waiting on a winning option.'); $.lang.register('bettingsystem.close.success.winners', 'A total of $1 players won this bet! There was a total of $2 was won for the people who placed a bet on $3!'); $.lang.register('bettingsystem.save.format', 'Title: "$1", Options: "$2", Total Points: $3, Total Entries: $4, Points Won: $5.'); $.lang.register('bettingsystem.results', 'Current bet: Title: "$1", Options: "$2", Total Points: $3, Total Entries: $4'); $.lang.register('bettingsystem.global.usage', 'Usage: !bet [open / close / save / saveformat / lookup / results / togglemessages / gain]'); $.lang.register('bettingsystem.bet.usage', 'Usage: !bet [amount] [option]'); $.lang.register('bettingsystem.bet.error.neg', 'You cannot bet negative $1!'); $.lang.register('bettingsystem.bet.error.min', 'The minimum bet you can place is $1.'); $.lang.register('bettingsystem.bet.error.max', 'The maximum bet you can place is $1.'); $.lang.register('bettingsystem.bet.error.points', 'You don\'t have enough $1 to bet that much.'); $.lang.register('bettingsystem.bet.betplaced', 'You already placed a bet of $1 on $2.'); $.lang.register('bettingsystem.bet.null', 'That is not a valid bet option.'); $.lang.register('bettingsystem.toggle.save', 'Betting results will $1 be saved after closing a bet.'); $.lang.register('bettingsystem.warning.messages', 'Warning messages will $1 be diplayed in chat.'); $.lang.register('bettingsystem.saveformat.usage', 'Usage: !bet saveformat [date format] - Default is yy.M.dd'); $.lang.register('bettingsystem.saveformat.set', 'Save format has been changed to $1.'); $.lang.register('bettingsystem.gain.usage', 'Usage: !bet gain [percent]'); $.lang.register('bettingsystem.gain.set', 'Gain percent has been set to $1%'); $.lang.register('bettingsystem.lookup.usage', 'Usage: !bet lookup [$1] - use _# after the date if you made multiple bets that day.'); $.lang.register('bettingsystem.lookup.show', 'Bet from [$1] $2'); $.lang.register('bettingsystem.lookup.null', 'No bets were made on that day.'); $.lang.register('bettingsystem.now', 'now'); $.lang.register('bettingsystem.not', 'not');
PhantomBot/PhantomBot
javascript-source/lang/english/systems/systems-bettingSystem.js
JavaScript
gpl-3.0
3,837
/* eslint-disable import/no-extraneous-dependencies */ const proxy = require('http-proxy-middleware'); module.exports = (app) => { app.use(proxy('/api/socket', { target: `ws://${process.env.REACT_APP_URL_NAME}`, ws: true })); app.use(proxy('/api', { target: `http://${process.env.REACT_APP_URL_NAME}` })); };
tananaev/traccar-web
modern/src/setupProxy.js
JavaScript
gpl-3.0
315
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'docprops', 'ru', { bgColor: 'Цвет фона', bgFixed: 'Фон прикреплён (не проматывается)', bgImage: 'Ссылка на фоновое изображение', charset: 'Кодировка набора символов', charsetASCII: 'ASCII', charsetCE: 'Центрально-европейская', charsetCR: 'Кириллица', charsetCT: 'Китайская традиционная (Big5)', charsetGR: 'Греческая', charsetJP: 'Японская', charsetKR: 'Корейская', charsetOther: 'Другая кодировка набора символов', charsetTR: 'Турецкая', charsetUN: 'Юникод (UTF-8)', charsetWE: 'Западно-европейская', chooseColor: 'Выберите', design: 'Дизайн', docTitle: 'Заголовок страницы', docType: 'Заголовок типа документа', docTypeOther: 'Другой заголовок типа документа', label: 'Свойства документа', margin: 'Отступы страницы', marginBottom: 'Нижний', marginLeft: 'Левый', marginRight: 'Правый', marginTop: 'Верхний', meta: 'Метаданные', metaAuthor: 'Автор', metaCopyright: 'Авторские права', metaDescription: 'Описание документа', metaKeywords: 'Ключевые слова документа (через запятую)', other: 'Другой ...', previewHtml: '<p>Это <strong>пример</strong> текста, написанного с помощью <a href="javascript:void(0)">CKEditor</a>.</p>', title: 'Свойства документа', txtColor: 'Цвет текста', xhtmlDec: 'Включить объявления XHTML' });
tsmaryka/hitc
public/javascripts/ckeditor/plugins/docprops/lang/ru.js
JavaScript
gpl-3.0
1,959
/** * Main scripts */ console.log("app running...");
iraquitan/political-advisor
web/myapp/static/myapp/js/main.js
JavaScript
gpl-3.0
55
import { fixLoop, onTransitionEnd, onTransitionStart } from './swiper'; import { updateActiveIndex } from './swiper-index'; import { isHorizontal, maxTranslate, minTranslate } from './swiper-utils'; import { updateProgress } from './swiper-progress'; /*========================= Controller ===========================*/ export const SWIPER_CONTROLLER = { LinearSpline: function (_s, _platform, x, y) { this.x = x; this.y = y; this.lastIndex = x.length - 1; // Given an x value (x2), return the expected y2 value: // (x1,y1) is the known point before given value, // (x3,y3) is the known point after given value. var i1, i3; this.interpolate = function (x2) { if (!x2) return 0; // Get the indexes of x1 and x3 (the array indexes before and after given x2): i3 = binarySearch(this.x, x2); i1 = i3 - 1; // We have our indexes i1 & i3, so we can calculate already: // y2 := ((x2−x1) × (y3−y1)) ÷ (x3−x1) + y1 return ((x2 - this.x[i1]) * (this.y[i3] - this.y[i1])) / (this.x[i3] - this.x[i1]) + this.y[i1]; }; var binarySearch = (function () { var maxIndex, minIndex, guess; return function (array, val) { minIndex = -1; maxIndex = array.length; while (maxIndex - minIndex > 1) if (array[guess = maxIndex + minIndex >> 1] <= val) { minIndex = guess; } else { maxIndex = guess; } return maxIndex; }; })(); }, // xxx: for now i will just save one spline function to to getInterpolateFunction: function (s, plt, c) { if (!s._spline) s._spline = s.loop ? new SWIPER_CONTROLLER.LinearSpline(s, plt, s._slidesGrid, c._slidesGrid) : new SWIPER_CONTROLLER.LinearSpline(s, plt, s._snapGrid, c._snapGrid); }, setTranslate: function (s, plt, translate, byController, setWrapperTranslate) { var controlled = s.control; var multiplier, controlledTranslate; function setControlledTranslate(c) { // this will create an Interpolate function based on the snapGrids // x is the Grid of the scrolled scroller and y will be the controlled scroller // it makes sense to create this only once and recall it for the interpolation // the function does a lot of value caching for performance translate = c._rtl && isHorizontal(c) ? -s._translate : s._translate; if (s.controlBy === 'slide') { SWIPER_CONTROLLER.getInterpolateFunction(s, plt, c); // i am not sure why the values have to be multiplicated this way, tried to invert the snapGrid // but it did not work out controlledTranslate = -s._spline.interpolate(-translate); } if (!controlledTranslate || s.controlBy === 'container') { multiplier = (maxTranslate(c) - minTranslate(c)) / (maxTranslate(s) - minTranslate(s)); controlledTranslate = (translate - minTranslate(s)) * multiplier + minTranslate(c); } if (s.controlInverse) { controlledTranslate = maxTranslate(c) - controlledTranslate; } updateProgress(c, controlledTranslate); setWrapperTranslate(c, plt, controlledTranslate, false, s); updateActiveIndex(c); } if (Array.isArray(controlled)) { for (var i = 0; i < controlled.length; i++) { if (controlled[i] !== byController) { setControlledTranslate(controlled[i]); } } } else if (byController !== controlled) { setControlledTranslate(controlled); } }, setTransition: function (s, plt, duration, byController, setWrapperTransition) { var controlled = s.control; var i; function setControlledTransition(c) { setWrapperTransition(c, plt, duration, s); if (duration !== 0) { onTransitionStart(c); plt.transitionEnd(c._wrapper, () => { if (!controlled) return; if (c.loop && s.controlBy === 'slide') { fixLoop(c, plt); } onTransitionEnd(c, plt); }); } } if (Array.isArray(controlled)) { for (i = 0; i < controlled.length; i++) { if (controlled[i] !== byController) { setControlledTransition(controlled[i]); } } } else if (byController !== controlled) { setControlledTransition(controlled); } } }; //# sourceMappingURL=swiper-controller.js.map
ricardo7227/DAW
Cliente/Codigo fuente/my-app-apk/node_modules/ionic-angular/es2015/components/slides/swiper/swiper-controller.js
JavaScript
gpl-3.0
5,084
/** * @license Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'devtools', 'it', { title: 'Informazioni elemento', dialogName: 'Nome finestra di dialogo', tabName: 'Nome Tab', elementId: 'ID Elemento', elementType: 'Tipo elemento' });
tsmaryka/hitc
public/javascripts/ckeditor/plugins/devtools/lang/it.js
JavaScript
gpl-3.0
369
"use strict"; function getTrulyRandomWords(numWords) { var array = new Uint32Array(numWords); window.crypto.getRandomValues(array); var bytes = new sha256.Bytes.fromWordArray(array); if (bytes.words.length != numWords) throw new Error("Assertion failed"); //sanity: data is not constant! var i; var ok = false; for (i = 1; i < bytes.words.length; i++) { if (bytes.words[i-1] != bytes.words[i]) { ok = true; break; } } if (!ok) throw new Error("Non-random data!"); //erase original for (i = 0; i < array.length; i++) array[i] = 0; return bytes; } //Random data from window.crypto.getRandomValues(). function BrowserRandByteSource() { this.chunk = new Uint8Array(32); this.i = 32; } BrowserRandByteSource.prototype._refill = function() { //zero out chunk so that we can prove it was filled again var j; for (j = 0; j < this.chunk.length; j++) this.chunk[i] = 0; window.crypto.getRandomValues(this.chunk); //sanity: data is not constant! var i; var ok = false; for (i = 1; i < this.chunk.length; i++) { if (this.chunk[i-1] != this.chunk[i]) { ok = true; break; } } if (!ok) throw new Error("Non-random data!"); this.i = 0; }; BrowserRandByteSource.prototype.nextByte = function() { //Need more bytes? if (this.i >= this.chunk.length) this._refill(); return this.chunk[this.i++]; }; function ConstByteSource(hexStr) { this.bytes = []; this.idx = 0; var i, s; for (i = 0; i + 1 < hexStr.length; i += 2) { s = hexStr.substring(i, i+2); this.bytes.push(parseInt(s, 16)); } } ConstByteSource.prototype.nextByte = function() { if (this.idx >= this.bytes.length) this.idx = 0; return this.bytes[this.idx++]; }; //Read 5 bits at a time from any object having a nextByte() function. function FiveBitReader(byteSource) { this.byteSource = byteSource; this.bits = 0; this.nBitsAvailable = 0; } FiveBitReader.prototype.next5Bits = function() { //ensure we have at least 5 bits if (this.nBitsAvailable < 5) { var byte = this.byteSource.nextByte(); this.bits |= byte << (4 - this.nBitsAvailable); this.nBitsAvailable += 8; } //Take the high 5 bits var result = this.bits >> 7; //shift remaining bits left this.bits = (this.bits << 5) & 0xFFF; this.nBitsAvailable -= 5; return result; }; //Return a random number between 0 and 25 (inclusive). //To avoid modulo bias sometimes multiple calls to next5Bits() are necessary. function rand26(fiveBitReader) { //We must TAKE CARE to avoid modulo bias! //https://zuttobenkyou.wordpress.com/2012/10/18/generating-random-numbers-without-modulo-bias/ var i, x; for (i = 0; i < 1000; i++) { x = fiveBitReader.next5Bits(); if (x <= 25) return x; } throw new Error("Unsuitable random source!"); } //Convert an integer to an string of 0/1, padding with leading zeros. function byte2base2(b, padlen) { padlen = padlen || 8; var s = b.toString(2); while (s.length < padlen) { s = '0' + s; } return s; } function selftest() { // // Test secureShuffle // //rng that returns descending integers var rng = { i: 1000, rand_u16: function() { return this.i--; } }; //Above rng will reverse the list var list = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split(''); secureShuffle(list, rng); assertEq(list.join(''), 'ZYXWVUTSRQPONMLKJIHGFEDCBA'); //rng that returns fixed sequence rng = { seq: [3,1,4,5,2], i: 0, rand_u16: function() { var n = this.seq[this.i % this.seq.length]; this.i++; return n; } }; var list = 'ABCDE'.split(''); secureShuffle(list, rng); assertEq(list.join(''), 'BEACD'); // // arrayToGrid var ar = [0,1,2,3,4,5,6,7,8,9]; var grid = arrayToGrid(ar, 3, 2); assertEq(grid.length, 2); assertEq(grid[0].join(','), '0,1,2'); assertEq(grid[1].join(','), '3,4,5'); // // formatSeed var fmt = formatSeed('abcdefghijklmnopqrstuvwxyz123456').split('\n'); assertEq(fmt[0], 'abcd-efgh-ijkl-mnop'); assertEq(fmt[1], 'qrst-uvwx-yz12-3456'); shared_selftest(); sha256.selftest(); /* //Test ConstByteSource var cbs = new ConstByteSource('1234'); assert(cbs.nextByte() == 0x12); assert(cbs.nextByte() == 0x34); assert(cbs.nextByte() == 0x12); //Test byte2base2 assert(byte2base2(0) == '00000000'); assert(byte2base2(1) == '00000001'); assert(byte2base2(0xA5) == '10100101'); //Test FiveBitReader var fbr = new FiveBitReader(new ConstByteSource('5A')); var i; var list = []; for (i = 0; i < 9; i++) list.push(byte2base2(fbr.next5Bits(), 5)); var s = list.join(' '); assert(s == '01011 01001 01101 00101 10100 10110 10010 11010 01011'); //the following test vector was generated with a simple python program fbr = new FiveBitReader(new ConstByteSource('09e3291f04af2a5c2ecbc4537bd563')); list = []; for (i = 0; i < 24; i++) list.push(byte2base2(fbr.next5Bits(), 5)); s = list.join(','); var expect = '00001,00111,10001,10010,10010,00111,11000,00100,10101,11100,10101,00101,11000,01011,10110,01011,11000,10001,01001,10111,10111,10101,01011,00011'; assert(s == expect); // //Test rand26 // //A 5bit reader that returns a fixed number sequence fbr = { seq: [0,1,2,25,26,27,28,29,30,31,7], idx: 0, next5Bits: function() { return this.seq[this.idx++]; } }; assertEq(rand26(fbr), 0); assertEq(rand26(fbr), 1); assertEq(rand26(fbr), 2); assertEq(rand26(fbr), 25); //skipped 26-31 due to modulo bias assertEq(rand26(fbr), 7); */ console.log('selftest PASSED'); } function grid2HTML(grid, topIndexChars, sideIndexChars) { var lines = []; //top header var x, y; var line = ['<span class="topLeft">&nbsp;&nbsp;</span>']; for (x = 0; x < CARD_CHAR_W; x++) { line.push('<span class="topHdr">' + topIndexChars[x] + '</span>'); } //lines.push(line.join('')); lines.push(line.join('')); //rows var tmp, c; for (y = 0; y < CARD_CHAR_H; y++) { c = sideIndexChars[y]; if (c.length == 1) c = '&nbsp;' + c; tmp = '<span class="sideHdr">' + c + '</span>'; line = [tmp]; for (x = 0; x < grid[y].length; x++) line.push('<span id="c'+ x + '_' + y +'" class="cell">' + grid[y][x] + '</span>'); //line = [tmp].concat(grid[y]); lines.push(line.join('')); } return lines.join('<br/>'); } function logCounts(counts) { var lines = []; var alb = ALPHABET_26_LOWER; var i, s; var line = '' for (i = 0; i < counts.length; i++) { line += alb[i] + ' '; } console.log(line); var idealCount = CARD_CHAR_W * CARD_CHAR_H / alb.length; line = '' for (i = 0; i < counts.length; i++) { s = '' + counts[i]; if (counts[i] < 10) line += counts[i] + ' '; else line += counts[i] + ' '; } console.log(line); } var gScribbler = null; function Scribbler(canvasId, doneCallback, requiredNumSamples) { this.canvElm = document.getElementById(canvasId); this.ctx = this.canvElm.getContext("2d"); this.lastX = -1; this.lastY = -1; this.hue = 1.0; this.ctx.lineWidth = 4; this.noise = []; this.doneCallback = doneCallback; this.done = false; this.requiredNumSamples = requiredNumSamples; this.canvElm.addEventListener("mousemove", this.on_mousemove.bind(this)); this.canvElm.addEventListener("touchmove", this.on_mousemove.bind(this)); //for mobile devices } Scribbler.prototype.on_mousemove = function(e) { if (this.done || !e.clientX) return; //console.log(e.clientX + "," + e.clientY); var rect = this.canvElm.getBoundingClientRect(); var x = e.clientX - rect.left; var y = e.clientY - rect.top; if (this.lastX == -1) { this.lastX = x - 1; this.lastY = y - 1; } var ctx = this.ctx; this.hue += 0.05; if (this.hue > 1.0) this.hue = 0.0; this.ctx.strokeStyle = HSVtoRGB(this.hue, 1.0, 1.0); ctx.beginPath(); ctx.moveTo(this.lastX, this.lastY); ctx.lineTo(x, y); ctx.stroke(); ctx.closePath(); this.lastX = x; this.lastY = y; //use milliseconds and position as random data this.noise.push(performance.now() & 0xFFFFFFFF); //force primitive integer this.noise.push(x); this.noise.push(y); //update progress bar var elm = document.getElementById('progress'); var nSamples = this.noise.length / 3; var percent = Math.floor(nSamples / this.requiredNumSamples * 100.0); elm.firstChild.nodeValue = percent + '%'; //done? if (percent >= 100) { this.done = true; elm.firstChild.nodeValue = '100% - Thank you.'; //wait a second then submit var result = this.noise; var callback = this.doneCallback; setTimeout(function() { callback(result); }, 1000); } }; //http://stackoverflow.com/questions/17242144/javascript-convert-hsb-hsv-color-to-rgb-accurately function HSVtoRGB(h, s, v) { var r, g, b, i, f, p, q, t; i = Math.floor(h * 6); f = h * 6 - i; p = v * (1 - s); q = v * (1 - f * s); t = v * (1 - (1 - f) * s); switch (i % 6) { case 0: r = v, g = t, b = p; break; case 1: r = q, g = v, b = p; break; case 2: r = p, g = v, b = t; break; case 3: r = p, g = q, b = v; break; case 4: r = t, g = p, b = v; break; case 5: r = v, g = p, b = q; break; } r = Math.round(r * 255.0); g = Math.round(g * 255.0); b = Math.round(b * 255.0); return "#" + ((r << 16) | (g << 8) | b).toString(16); } function digestScribbleNoise(integers) { //sanity if (integers.length < 100) { throw new Error('Scribble noise too short'); } //sanity var i; for (i = 0; i < integers.length; i++) { if (typeof(integers[i]) != 'number') throw new Error('Scribble noise at index ' + i + ' is not a number!'); } //feed each integer to sha256 as a 32bit integer var input = sha256.Bytes.fromWordArray(integers); var hash = sha256.sha256(input); input.erase(); return hash; } function onScribbleDone(integers) { var noise1 = digestScribbleNoise(integers); //erase integers var i; for (i = 0; i < integers.length; i++) integers[i] = 0; beginStep2(noise1); } function createAZSeed(noise1, noise2) { //Mix noise from user and noise from OS var mixed = sha256.hmac(noise2, noise1); //Use mixed noise to generate 30 characters, A-Z. This is roughly // 128bits of entropy var rng = new UnbiasedRNG(new AES128_DRBG(mixed)); mixed.erase(); var seed = ''; var i; for (i = 0; i < 30; i++) seed += rng.rand_A_Z(); //Append 2 character checksum var chk = sha256.digestString(seed); var b0 = chk.getByte(0); var b1 = chk.getByte(1); seed += String.fromCharCode(0x41 + (b0 % 26)); //0x41 is 'A' seed += String.fromCharCode(0x41 + (b1 % 26)); chk.erase(); return seed; } //Convert a 1D array to a 2D array (array[h][w]) function arrayToGrid(ar, w, h) { var grid = new Array(h); var y; for (y = 0; y < h; y++) { grid[y] = ar.slice(y * w, y * w + w); } return grid; } function gridToStr(grid) { var lines = new Array(grid.length); var i, j; for (i = 0; i < grid.length; i++) { lines[i] = grid[i].join(''); } return lines.join('\n'); } function formatSeed(seed) { assertEq(seed.length, 32); //2 lines of 4 groups of 4 characters separated by dashes. var s = ''; var i, j; i = 0; while (i < seed.length) { if (i == seed.length / 2) s += '\n'; else if (i > 0) s += '-'; s += seed.substring(i, i + 4); i += 4; } return s; } function beginStep2(noise1) { toggleBlock('step1', false); var noise2 = getTrulyRandomWords(8); var seed = createAZSeed(noise1, noise2); noise1.erase(); noise2.erase(); var nPerCard = CARD_CHAR_W * CARD_CHAR_H; var chars = randCharsFromSeed(seed, nPerCard * 2); assertEq(chars.length, nPerCard * 2); var grid1 = arrayToGrid(chars, CARD_CHAR_W, CARD_CHAR_H); var grid2 = arrayToGrid(chars.slice(nPerCard), CARD_CHAR_W, CARD_CHAR_H); //charStats(chars); //console.log(gridToStr(grid1)); //console.log(''); //console.log(gridToStr(grid2)); var html1 = grid2HTML(grid1, CARD_TOP_INDEX_CHARS, CARD_SIDE_INDEX_CHARS.slice(0, CARD_CHAR_H)); var html2 = grid2HTML(grid2, CARD_TOP_INDEX_CHARS, CARD_SIDE_INDEX_CHARS.slice(CARD_CHAR_H)); document.getElementById('card1').innerHTML = html1; document.getElementById('card2').innerHTML = html2; var seedParts = formatSeed(seed).split('\n'); console.log(formatSeed(seed)); setElmText('seedPart1', seedParts[0]); setElmText('seedPart2', seedParts[1]); toggleBlock('step2', true); } function charStats(chars) { var letter, index; var alb = ALPHABET_26_LOWER; var counts = new Array(alb.length); var i; for (i = 0; i < counts.length; i++) counts[i] = 0; for (i = 0; i < chars.length; i++) { letter = chars[i]; index = alb.indexOf(letter); if (index == -1) throw new Error("letter not in alphabet"); counts[index]++; } logCounts(counts); } //Randomly reorder the given array without bias function secureShuffle(list, rng) { var count = list.length; //Don't attempt huge lists because we are using 16bit random integers if (count > 0x7fff) throw new Error('list too large'); //Create one random integer for every element. I avoid duplicates to // ensure a stable sort var ints = new Array(count); var i, j, k; for (i = 0; i < count; i++) { //the following rarely loops more than once j = 0; while (true) { //Rand 16bit integer. k = rng.rand_u16(); //Unique? if (ints.indexOf(k) == -1) { ints[i] = k; break; } j++; if (j > 1000 && j > count) throw new Error("Unable to produce unique integer"); } } //Attach random ints to each element for (i = 0; i < count; i++) { list[i] = [list[i], ints[i]]; ints[i] = 0; //erase } //Sort list.sort(function(a, b) { return a[1] - b[1]; }); //Detach random ints and erase for (i = 0; i < count; i++) { j = list[i]; list[i] = j[0]; j[0] = 0; j[1] = 0; } } function randCharsFromSeed(seed, count) { //Prepare a CSPRNG from the ASCII seed. //Initialize with HMAC in case of any sha256 weakness if (seed.length != 32) throw new Error("Wrong seed length"); var input = sha256.Bytes.fromStringUTF8(seed); var initHash = sha256.hmac(input, input); input.erase(); var rng = new UnbiasedRNG(new AES128_DRBG(initHash)); initHash.erase(); //I wish to have a roughly equal distribution of the letters A-Z. //For example, 'a' should occur roughly the same number of times as 'b'. // So instead of pulling letters out of a bag at random I'll start with // an equal distribution and then shuffle them randomly. var alphabet = ALPHABET_26_LOWER.split(""); //split converts string to array of chars //Repeat the alphabet nWhole times. Avoid appending // a truncated alphabet to avoid bias var chars = []; var nWhole = Math.floor(count / alphabet.length); var i; for (i = 0; i < nWhole; i++) chars = chars.concat(alphabet); //For the remainder, shuffle the alphabet and take a slice of it secureShuffle(alphabet, rng); chars = chars.concat(alphabet.slice(0, count - chars.length)); //Now we are ready to shuffle everything secureShuffle(chars, rng); console.log("Num bytes used " + rng.nBytesUsed); return chars; } function toggleBlock(elementOrId, force) { var elm = null; if (typeof(elementOrId) == 'string') elm = document.getElementById(elementOrId); var mode; if (force === true) mode = 'block'; else if (force === false) mode = 'none'; else { var isHidden = elm.style.display != 'block'; mode = isHidden ? 'block' : 'none'; } elm.style.display = mode; } function onLoad() { selftest(); gScribbler = new Scribbler('scribbleCanv', onScribbleDone, 50); /* //var randSrc = new BrowserRandByteSource(); //var grid = randAZGrid(CARD_CHAR_W, CARD_CHAR_H, randSrc); var grid = generateWellDispersedGrid(); //var card1 = randCard1(grid).join('<br/>'); var html = grid2HTML(grid); //document.getElementById('card1').innerHTML = card1; document.getElementById('card1').innerHTML = html; */ /* var card3 = randCard3(grid); document.getElementById('card3').innerHTML = card3; var card4 = randCard4(grid); document.getElementById('card4').innerHTML = card4; */ }
cruxic/calcpass
www/create.js
JavaScript
gpl-3.0
16,021
// ON STARTUP $(document).ready(function () { }); // ON WINDOW RESIZED $(window).resize(function() { psb_ResizeDaftarDiv(); psb_ResizeStatusDiv(); }); psb_ResizeDaftarDiv = function() { var docHeight = $(document).height(); var psbDaftarHeight = docHeight - 240 - 100; $("#psb_divDaftar").height(psbDaftarHeight); } psb_ResizeStatusDiv = function() { var docHeight = $(document).height(); var psbStatusHeight = docHeight - 240 - 90; $("#psb_divStatus").height(psbStatusHeight); } psb_InputPsbClicked = function() { $.ajax({ url : 'psb/psb.input.php', type: 'get', success : function(html) { $('#psb_content').html(html); } }) } psb_DaftarPsbClicked = function() { setTimeout(psb_ResizeDaftarDiv, 100); $.ajax({ url : 'psb/psb.daftar.php', type: 'get', success : function(html) { $('#psb_content').html(html); } }) } psb_StatusPsbClicked = function() { setTimeout(psb_ResizeStatusDiv, 100); $.ajax({ url : 'psb/psb.status.php', type: 'get', success : function(html) { $('#psb_content').html(html); } }) }
dedefajriansyah/jibas
anjungan/psb/psb.js
JavaScript
gpl-3.0
1,285
/************************************************************************ * This file is part of EspoCRM. * * EspoCRM - Open Source CRM application. * Copyright (C) 2014-2022 Yurii Kuznietsov, Taras Machyshyn, Oleksii Avramenko * Website: https://www.espocrm.com * * EspoCRM is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * EspoCRM is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with EspoCRM. If not, see http://www.gnu.org/licenses/. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU General Public License version 3. * * In accordance with Section 7(b) of the GNU General Public License version 3, * these Appropriate Legal Notices must retain the display of the "EspoCRM" word. ************************************************************************/ define('views/collapsed-modal', 'view', function (Dep) { return Dep.extend({ templateContent: ` <div class="title-container"> <a href="javascript:" data-action="expand" class="title">{{title}}</a> </div> <div class="close-container"> <a href="javascript:" data-action="close"><span class="fas fa-times"></span></a> </div> `, events: { 'click [data-action="expand"]': function () { this.expand(); }, 'click [data-action="close"]': function () { this.close(); }, }, data: function () { return { title: this.title, }; }, setup: function () { this.title = this.options.title || 'no-title'; }, expand: function () { this.trigger('expand'); }, close: function () { this.trigger('close'); }, }); });
espocrm/espocrm
client/src/views/collapsed-modal.js
JavaScript
gpl-3.0
2,397
define(["exports", "meta", "../../lit/index.js", "../es-global-bridge/es-global-bridge.js"], function (_exports, meta, _index, _esGlobalBridge) { "use strict"; Object.defineProperty(_exports, "__esModule", { value: true }); _exports.Hal9000 = void 0; meta = _interopRequireWildcard(meta); var _templateObject_2759c1609bf111ec9d3703fd9549253d, _templateObject2_2759c1609bf111ec9d3703fd9549253d; function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || babelHelpers.typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { babelHelpers.defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = babelHelpers.getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = babelHelpers.getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return babelHelpers.possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } /** * `hal-9000` * @element hal-9000 * `Robot assistant tag, hopefully not evil` * * @demo demo/index.html */ var Hal9000 = /*#__PURE__*/function (_LitElement) { babelHelpers.inherits(Hal9000, _LitElement); var _super = _createSuper(Hal9000); /** * Establish the element */ function Hal9000() { var _this; babelHelpers.classCallCheck(this, Hal9000); _this = _super.call(this); _this.commands = {}; _this.respondsTo = "(hal)"; _this.debug = false; _this.pitch = 0.9; _this.rate = 0.9; _this.language = navigator.language; // ensure singleton is set window.Hal9000 = window.Hal9000 || {}; window.Hal9000.instance = babelHelpers.assertThisInitialized(_this); var location = "".concat(new URL("./lib/annyang/annyang.min.js", meta.url).href); window.addEventListener("es-bridge-annyang-loaded", _this._annyangLoaded.bind(babelHelpers.assertThisInitialized(_this))); window.ESGlobalBridge.requestAvailability().load("annyang", location); // check for speech synthesis API if (typeof window.speechSynthesis !== "undefined") { _this.synth = window.speechSynthesis; _this.voices = _this.synth.getVoices(); for (var i = 0; i < _this.voices.length; i++) { if (_this.voices[i].default) { _this.defaultVoice = _this.voices[i].name; } } } return _this; } /** * Notice new voice commands added */ babelHelpers.createClass(Hal9000, [{ key: "render", value: // render function function render() { return (0, _index.html)(_templateObject_2759c1609bf111ec9d3703fd9549253d || (_templateObject_2759c1609bf111ec9d3703fd9549253d = babelHelpers.taggedTemplateLiteral([" <slot></slot>"]))); } // properties available to the custom element for data binding }, { key: "_commandsChanged", value: function _commandsChanged(newValue) { this.addCommands(newValue); } /** * Just rout add commands call to the right place */ }, { key: "addCommands", value: function addCommands(commands) { if (this.annyang) { this.annyang.addCommands(commands); } } /** * And the word was good. */ }, { key: "speak", value: function speak(text) { this.__text = text; if (this.synth) { this.utter = new SpeechSynthesisUtterance(this.__text); this.utter.pitch = this.pitch; this.utter.rate = this.rate; this.utter.lang = this.language; this.utter.voice = this.defaultVoice; // THOU SPEAKITH this.synth.speak(this.utter); } else { console.warn("I have no voice..."); } } /** * Annyang library has been loaded globally so we can use it */ }, { key: "_annyangLoaded", value: function _annyangLoaded() { this.annyang = window.annyang; // Add our commands to annyang if (this.annyang) { this.annyang.addCommands(this.commands); this.annyang.debug(this.debug); // Start listening. You can call this here, or attach this call to an event, button, etc. if (this.auto) { this.annyang.start({ autoRestart: true, continuous: true }); } else if (this.enabled) { this.annyang.start(); } // alert alert we are ready var evt = new CustomEvent("hal-9000-online", { bubbles: true, cancelable: false, detail: true }); this.dispatchEvent(evt); } } /** * Change the key name that is responded to */ }, { key: "_respondsToChanged", value: function _respondsToChanged(newValue, oldValue) { // remove all as our voice changed if (this.annyang) { this.annyang.removeCommands(); } var commands = {}; for (var i in this.commands) { if (i.replace(oldValue, newValue) !== i) { commands[i.replace(oldValue, newValue)] = this.commands[i]; } else { commands[i] = this.commands[i]; } } if (commands.length > 0) { this.commands = _objectSpread({}, commands); } } /** * Notice auto state changed so we start listening */ }, { key: "_autoChanged", value: function _autoChanged(newValue) { this.enabled = newValue; } /** * React to enabled state changing */ }, { key: "_enabledChanged", value: function _enabledChanged(newValue) { if (this.annyang) { if (newValue) { if (this.auto) { this.annyang.start({ autoRestart: true, continuous: true }); } else { this.annyang.start(); } } else { this.annyang.abort(); } } } /** * debug mode changed */ }, { key: "_debugChanged", value: function _debugChanged(newValue, oldValue) { if (this.annyang) { this.annyang.debug(newValue); } } /** * LitElement properties changed */ }, { key: "updated", value: function updated(changedProperties) { var _this2 = this; changedProperties.forEach(function (oldValue, propName) { if (propName == "commands") { _this2._commandsChanged(_this2[propName], oldValue); } if (propName == "respondsTo") { _this2._respondsToChanged(_this2[propName], oldValue); } if (propName == "debug") { _this2._debugChanged(_this2[propName], oldValue); } if (propName == "auto") { _this2._autoChanged(_this2[propName], oldValue); } if (propName == "enabled") { _this2._enabledChanged(_this2[propName], oldValue); } }); } /** * life cycle, element is removed from the DOM */ }, { key: "disconnectedCallback", value: function disconnectedCallback() { window.removeEventListener("es-bridge-annyang-loaded", this._annyangLoaded.bind(this)); babelHelpers.get(babelHelpers.getPrototypeOf(Hal9000.prototype), "disconnectedCallback", this).call(this); } }], [{ key: "styles", get: //styles function function get() { return [(0, _index.css)(_templateObject2_2759c1609bf111ec9d3703fd9549253d || (_templateObject2_2759c1609bf111ec9d3703fd9549253d = babelHelpers.taggedTemplateLiteral(["\n :host {\n display: block;\n }\n "])))]; } }, { key: "properties", get: function get() { return _objectSpread(_objectSpread({}, babelHelpers.get(babelHelpers.getPrototypeOf(Hal9000), "properties", this)), {}, { /** * Commands to listen for and take action on */ commands: { name: "commands", type: Object }, /** * The name that HAL 9000 should respond to. */ respondsTo: { name: "respondsTo", type: String, attribute: "responds-to" }, /** * Debug mode for annyang */ debug: { name: "debug", type: Boolean }, /** * Start automatically */ auto: { name: "auto", type: Boolean, reflect: true }, /** * Status of listening */ enabled: { name: "enabled", type: Boolean, reflect: true }, /** * Pitch of speech */ pitch: { name: "pitch", type: Number, reflect: true }, /** * Rate of speech */ rate: { name: "rate", type: Number, reflect: true }, /** * Language of the speaker */ language: { name: "language", type: String, reflect: true } }); } /** * Store the tag name to make it easier to obtain directly. * @notice function name must be here for tooling to operate correctly */ }, { key: "tag", get: function get() { return "hal-9000"; } }]); return Hal9000; }(_index.LitElement); // haxHooks() { // return { // haleditModeChanged: "haxeditModeChanged", // halActiveElementChanged: "halActiveElementChanged", // }; // } // halActiveElementChanged(element, value) { // if (value) { // this._haxstate = value; // } // } // haxeditModeChanged(value) { // this._haxstate = value; // } // ensure we can generate a singleton _exports.Hal9000 = Hal9000; window.customElements.define(Hal9000.tag, Hal9000); window.Hal9000 = window.Hal9000 || {}; window.Hal9000.requestAvailability = function () { if (!window.Hal9000.instance) { window.Hal9000.instance = new Hal9000(); } }; });
elmsln/elmsln
core/dslmcode/cores/haxcms-1/build/es5-amd/node_modules/@lrnwebcomponents/hal-9000/hal-9000.js
JavaScript
gpl-3.0
12,767
var searchData= [ ['gaintoggler',['GainToggler',['../d2/dc4/class_gain_toggler.html',1,'']]], ['gammaroot',['GammaRoot',['../d0/dc6/struct_gamma_root.html',1,'']]], ['ge4hen3processor',['Ge4Hen3Processor',['../d5/df2/class_ge4_hen3_processor.html',1,'']]], ['gecalibprocessor',['GeCalibProcessor',['../d0/d8c/class_ge_calib_processor.html',1,'']]], ['generalexception',['GeneralException',['../d1/d01/class_general_exception.html',1,'']]], ['generalwarning',['GeneralWarning',['../dc/d41/class_general_warning.html',1,'']]], ['generror',['GenError',['../d6/dfc/class_gen_error.html',1,'']]], ['geprocessor',['GeProcessor',['../d2/d54/class_ge_processor.html',1,'']]], ['gettraces',['GetTraces',['../dd/d57/class_get_traces.html',1,'']]], ['globals',['Globals',['../d3/daf/class_globals.html',1,'']]], ['goodtoggler',['GoodToggler',['../d2/dee/class_good_toggler.html',1,'']]], ['gslfitter',['GslFitter',['../dc/d06/class_gsl_fitter.html',1,'']]] ];
pixie16/paassdoc
search/classes_6.js
JavaScript
gpl-3.0
973
import Model from "../libs/Model"; import DAO from "./DAO"; export default class Content extends Model { constructor(obj = null) { super(obj, ['id', 'content', 'created_at', 'updated_at', 'title', 'name', 'doctor_id']); } static newInstance(...args) { return new Content(...args); } static buildHtmlForm(inputId, inputName, textareaId, textareaName, inputValue = "", textareaValue = "") { if (inputName == null) inputName = inputId; if (textareaName == null) textareaName = textareaId; let html = $('<div></div>'); let div1 = $('<div class="form-group"></div>'); let div2 = $('<div class="form-group"></div>'); let labelInput = $('<label></label>'); labelInput.html("Titre :"); labelInput.addClass('label-control'); let input = $('<input />'); input.attr('id', inputId); input.attr('type', 'text'); input.attr('name', inputName); input.val(inputValue); input.addClass('form-control'); let labelTextaera = $('<label></label>'); labelTextaera.html("Texte :"); labelTextaera.addClass("label-control"); let textarea = $('<textarea></textarea>'); textarea.attr('id', textareaId); textarea.attr('name', textareaName); textarea.addClass('form-control'); textarea.html(textareaValue); div1.append(labelInput); div1.append(input); div2.append(labelTextaera); div2.append(textarea); html.append(div1); html.append(div2); return html; } static async get(id, params = "") { return DAO.get(this, id, params); } static async create(data, params = "") { return DAO.create(this, data, params); } async update(params = "") { return DAO.update(this, params); } async delete(params = "") { return DAO.delete(this, params); } static remove(id, params = "") { return DAO.deleteFromId(this, id, params); } }
RobinMarechal/Kine
resources/assets/js/scripts/models/Content.js
JavaScript
gpl-3.0
2,091
export const siteItemStyle = { padding: '10px', backgroundColor: '#fcfcfc', boxShadow: '1px 1px 3px #ababab', transitionDuration: '250ms', transitionProperty: 'box-shadow', ':hover': { backgroundColor: '#fafafa', boxShadow: '1px 1px 3px #cdcdcd', }, font: 'caption', display: 'flex', flexDirection: 'row', }; export const btnStyle = { backgroundColor: '#fbfbfb', border: '1px solid #b1b1b1', boxShadow: '0 0 0 0 transparent', font: 'caption', height: '24px', outline: '0 !important', padding: '0 8px 0', transitionDuration: '250ms', transitionProperty: 'box-shadow, border', ':hover': { backgroundColor: '#ebebeb', border: '1px solid #b1b1b1', }, ':active': { backgroundColor: '#d4d4d4', border: '1px solid #858585', }, ':focus': { borderColor: '#fff', boxShadow: '0 0 0 2px rgba(97, 181, 255, 0.75)', }, }; export const textInputStyle = { backgroundColor: '#fff', border: '1px solid #b1b1b1', boxShadow: '0 0 0 0 rgba(97, 181, 255, 0)', font: 'caption', padding: '0 6px 0', transitionDuration: '250ms', transitionProperty: 'box-shadow', height: '24px', ':hover': { border: '1px solid #858585', }, ':focus': { borderColor: '#0996f8', boxShadow: '0 0 0 2px rgba(97, 181, 255, 0.75)', }, }; export const selectStyle = { backgroundColor: '#fbfbfb', border: '1px solid #b1b1b1', boxShadow: '0 0 0 0 transparent', font: 'caption', height: '24px', outline: '0', padding: '0 8px 0', MozAppearance: 'none', MozPaddingEnd: '24px', flexGrow: '1', transitionDuration: '250ms', transitionProperty: 'box-shadow, border', backgroundImage: 'url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiIgdmlld0JveD0iMCAwIDE2IDE2Ij4KICA8cGF0aCBkPSJNOCwxMkwzLDcsNCw2bDQsNCw0LTQsMSwxWiIgZmlsbD0iIzZBNkE2QSIgLz4KPC9zdmc+Cg==)', backgroundPosition: 'calc(100% - 4px) center', backgroundRepeat: 'no-repeat', textOverflow: 'ellipsis', ':hover': { backgroundColor: '#ebebeb', border: '1px solid #b1b1b1', }, ':focus': { borderColor: '#fff', boxShadow: '0 0 0 2px rgba(97, 181, 255, 0.75)', }, }; export const panelStyle = { color: '#222426', cursor: 'default', font: 'caption', padding: '0px', }; export const panelFormStyle = { display: 'flex', flexDirection: 'column', padding: '16px', }; export const panelFormItemStyle = { alignItems: 'center', display: 'flex', flexDirection: 'row', marginBottom: '12px', }; export const panelLastFormItemStyle = { marginBottom: '0', }; export const labelStyle = { flexShrink: '0', flexBasis: '80px', marginRight: '6px', textAlign: 'right', }; export const inputStyle = { flexGrow: '1', }; export const separatorStyle = { backgroundColor: 'rgba(0, 0, 0, 0.1)', width: '1px', zIndex: 99, }; export const tabHeaderStyle = { color: '#1a1a1a', display: 'flex', flexDirection: 'row', height: '41px', marginBottom: '-1px', padding: '0', }; export const tabButtonStyle = { base: { flex: '1 1 auto', margin: '0 -1px', padding: '12px', textAlign: 'center', ':hover': { backgroundColor: 'rgba(0, 0, 0, 0.06)', }, }, selected: { boxShadow: '0 -1px 0 #0670cc inset, 0 -4px 0 #0996f8 inset', color: '#0996f8', ':hover': { color: '#0670cc', }, }, }; export const popupFooterStyle = { backgroundColor: 'rgba(0, 0, 0, 0.06)', borderTop: '1px solid rgba(0, 0, 0, 0.15)', color: '#1a1a1a', display: 'flex', flexDirection: 'row', height: '41px', marginTop: '-1px', padding: 0, }; export const popupFooterButtonStyle = { font: 'caption', cursor: 'default', flex: '1 1 auto', margin: '0 -1px', padding: '12px', textAlign: 'center', ':hover': { backgroundColor: 'rgba(0, 0, 0, 0.06)', }, };
greizgh/Phashword
src/components/style.js
JavaScript
gpl-3.0
3,871
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'print', 'fi', { toolbar: 'Tulosta' });
tsmaryka/hitc
public/javascripts/ckeditor/plugins/print/lang/fi.js
JavaScript
gpl-3.0
215
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ 'use strict' exports.byteLength = byteLength exports.toByteArray = toByteArray exports.fromByteArray = fromByteArray var lookup = [] var revLookup = [] var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' for (var i = 0, len = code.length; i < len; ++i) { lookup[i] = code[i] revLookup[code.charCodeAt(i)] = i } revLookup['-'.charCodeAt(0)] = 62 revLookup['_'.charCodeAt(0)] = 63 function placeHoldersCount (b64) { var len = b64.length if (len % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4') } // the number of equal signs (place holders) // if there are two placeholders, than the two characters before it // represent one byte // if there is only one, then the three characters before it represent 2 bytes // this is just a cheap hack to not do indexOf twice return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 } function byteLength (b64) { // base64 is 4/3 + up to two characters of the original data return b64.length * 3 / 4 - placeHoldersCount(b64) } function toByteArray (b64) { var i, j, l, tmp, placeHolders, arr var len = b64.length placeHolders = placeHoldersCount(b64) arr = new Arr(len * 3 / 4 - placeHolders) // if there are placeholders, only get up to the last complete 4 chars l = placeHolders > 0 ? len - 4 : len var L = 0 for (i = 0, j = 0; i < l; i += 4, j += 3) { tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] arr[L++] = (tmp >> 16) & 0xFF arr[L++] = (tmp >> 8) & 0xFF arr[L++] = tmp & 0xFF } if (placeHolders === 2) { tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) arr[L++] = tmp & 0xFF } else if (placeHolders === 1) { tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) arr[L++] = (tmp >> 8) & 0xFF arr[L++] = tmp & 0xFF } return arr } function tripletToBase64 (num) { return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] } function encodeChunk (uint8, start, end) { var tmp var output = [] for (var i = start; i < end; i += 3) { tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) output.push(tripletToBase64(tmp)) } return output.join('') } function fromByteArray (uint8) { var tmp var len = uint8.length var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes var output = '' var parts = [] var maxChunkLength = 16383 // must be multiple of 3 // go through the array every three bytes, we'll deal with trailing stuff later for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) } // pad the end with zeros, but make sure to not forget the extra bytes if (extraBytes === 1) { tmp = uint8[len - 1] output += lookup[tmp >> 2] output += lookup[(tmp << 4) & 0x3F] output += '==' } else if (extraBytes === 2) { tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) output += lookup[tmp >> 10] output += lookup[(tmp >> 4) & 0x3F] output += lookup[(tmp << 2) & 0x3F] output += '=' } parts.push(output) return parts.join('') } },{}],2:[function(require,module,exports){ },{}],3:[function(require,module,exports){ (function (global){ 'use strict'; var buffer = require('buffer'); var Buffer = buffer.Buffer; var SlowBuffer = buffer.SlowBuffer; var MAX_LEN = buffer.kMaxLength || 2147483647; exports.alloc = function alloc(size, fill, encoding) { if (typeof Buffer.alloc === 'function') { return Buffer.alloc(size, fill, encoding); } if (typeof encoding === 'number') { throw new TypeError('encoding must not be number'); } if (typeof size !== 'number') { throw new TypeError('size must be a number'); } if (size > MAX_LEN) { throw new RangeError('size is too large'); } var enc = encoding; var _fill = fill; if (_fill === undefined) { enc = undefined; _fill = 0; } var buf = new Buffer(size); if (typeof _fill === 'string') { var fillBuf = new Buffer(_fill, enc); var flen = fillBuf.length; var i = -1; while (++i < size) { buf[i] = fillBuf[i % flen]; } } else { buf.fill(_fill); } return buf; } exports.allocUnsafe = function allocUnsafe(size) { if (typeof Buffer.allocUnsafe === 'function') { return Buffer.allocUnsafe(size); } if (typeof size !== 'number') { throw new TypeError('size must be a number'); } if (size > MAX_LEN) { throw new RangeError('size is too large'); } return new Buffer(size); } exports.from = function from(value, encodingOrOffset, length) { if (typeof Buffer.from === 'function' && (!global.Uint8Array || Uint8Array.from !== Buffer.from)) { return Buffer.from(value, encodingOrOffset, length); } if (typeof value === 'number') { throw new TypeError('"value" argument must not be a number'); } if (typeof value === 'string') { return new Buffer(value, encodingOrOffset); } if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { var offset = encodingOrOffset; if (arguments.length === 1) { return new Buffer(value); } if (typeof offset === 'undefined') { offset = 0; } var len = length; if (typeof len === 'undefined') { len = value.byteLength - offset; } if (offset >= value.byteLength) { throw new RangeError('\'offset\' is out of bounds'); } if (len > value.byteLength - offset) { throw new RangeError('\'length\' is out of bounds'); } return new Buffer(value.slice(offset, offset + len)); } if (Buffer.isBuffer(value)) { var out = new Buffer(value.length); value.copy(out, 0, 0, value.length); return out; } if (value) { if (Array.isArray(value) || (typeof ArrayBuffer !== 'undefined' && value.buffer instanceof ArrayBuffer) || 'length' in value) { return new Buffer(value); } if (value.type === 'Buffer' && Array.isArray(value.data)) { return new Buffer(value.data); } } throw new TypeError('First argument must be a string, Buffer, ' + 'ArrayBuffer, Array, or array-like object.'); } exports.allocUnsafeSlow = function allocUnsafeSlow(size) { if (typeof Buffer.allocUnsafeSlow === 'function') { return Buffer.allocUnsafeSlow(size); } if (typeof size !== 'number') { throw new TypeError('size must be a number'); } if (size >= MAX_LEN) { throw new RangeError('size is too large'); } return new SlowBuffer(size); } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"buffer":4}],4:[function(require,module,exports){ (function (global){ /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org> * @license MIT */ /* eslint-disable no-proto */ 'use strict' var base64 = require('base64-js') var ieee754 = require('ieee754') var isArray = require('isarray') exports.Buffer = Buffer exports.SlowBuffer = SlowBuffer exports.INSPECT_MAX_BYTES = 50 /** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) * === false Use Object implementation (most compatible, even IE6) * * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, * Opera 11.6+, iOS 4.2+. * * Due to various browser bugs, sometimes the Object implementation will be used even * when the browser supports typed arrays. * * Note: * * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. * * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. * * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of * incorrect length in some situations. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they * get the Object implementation, which is slower but behaves correctly. */ Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined ? global.TYPED_ARRAY_SUPPORT : typedArraySupport() /* * Export kMaxLength after typed array support is determined. */ exports.kMaxLength = kMaxLength() function typedArraySupport () { try { var arr = new Uint8Array(1) arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} return arr.foo() === 42 && // typed array instances can be augmented typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` } catch (e) { return false } } function kMaxLength () { return Buffer.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff } function createBuffer (that, length) { if (kMaxLength() < length) { throw new RangeError('Invalid typed array length') } if (Buffer.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = new Uint8Array(length) that.__proto__ = Buffer.prototype } else { // Fallback: Return an object instance of the Buffer class if (that === null) { that = new Buffer(length) } that.length = length } return that } /** * The Buffer constructor returns instances of `Uint8Array` that have their * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of * `Uint8Array`, so the returned instances will have all the node `Buffer` methods * and the `Uint8Array` methods. Square bracket notation works as expected -- it * returns a single octet. * * The `Uint8Array` prototype remains unmodified. */ function Buffer (arg, encodingOrOffset, length) { if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { return new Buffer(arg, encodingOrOffset, length) } // Common case. if (typeof arg === 'number') { if (typeof encodingOrOffset === 'string') { throw new Error( 'If encoding is specified then the first argument must be a string' ) } return allocUnsafe(this, arg) } return from(this, arg, encodingOrOffset, length) } Buffer.poolSize = 8192 // not used by this implementation // TODO: Legacy, not needed anymore. Remove in next major version. Buffer._augment = function (arr) { arr.__proto__ = Buffer.prototype return arr } function from (that, value, encodingOrOffset, length) { if (typeof value === 'number') { throw new TypeError('"value" argument must not be a number') } if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { return fromArrayBuffer(that, value, encodingOrOffset, length) } if (typeof value === 'string') { return fromString(that, value, encodingOrOffset) } return fromObject(that, value) } /** * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError * if value is a number. * Buffer.from(str[, encoding]) * Buffer.from(array) * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ Buffer.from = function (value, encodingOrOffset, length) { return from(null, value, encodingOrOffset, length) } if (Buffer.TYPED_ARRAY_SUPPORT) { Buffer.prototype.__proto__ = Uint8Array.prototype Buffer.__proto__ = Uint8Array if (typeof Symbol !== 'undefined' && Symbol.species && Buffer[Symbol.species] === Buffer) { // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 Object.defineProperty(Buffer, Symbol.species, { value: null, configurable: true }) } } function assertSize (size) { if (typeof size !== 'number') { throw new TypeError('"size" argument must be a number') } else if (size < 0) { throw new RangeError('"size" argument must not be negative') } } function alloc (that, size, fill, encoding) { assertSize(size) if (size <= 0) { return createBuffer(that, size) } if (fill !== undefined) { // Only pay attention to encoding if it's a string. This // prevents accidentally sending in a number that would // be interpretted as a start offset. return typeof encoding === 'string' ? createBuffer(that, size).fill(fill, encoding) : createBuffer(that, size).fill(fill) } return createBuffer(that, size) } /** * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ Buffer.alloc = function (size, fill, encoding) { return alloc(null, size, fill, encoding) } function allocUnsafe (that, size) { assertSize(size) that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) if (!Buffer.TYPED_ARRAY_SUPPORT) { for (var i = 0; i < size; ++i) { that[i] = 0 } } return that } /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ Buffer.allocUnsafe = function (size) { return allocUnsafe(null, size) } /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ Buffer.allocUnsafeSlow = function (size) { return allocUnsafe(null, size) } function fromString (that, string, encoding) { if (typeof encoding !== 'string' || encoding === '') { encoding = 'utf8' } if (!Buffer.isEncoding(encoding)) { throw new TypeError('"encoding" must be a valid string encoding') } var length = byteLength(string, encoding) | 0 that = createBuffer(that, length) var actual = that.write(string, encoding) if (actual !== length) { // Writing a hex string, for example, that contains invalid characters will // cause everything after the first invalid character to be ignored. (e.g. // 'abxxcd' will be treated as 'ab') that = that.slice(0, actual) } return that } function fromArrayLike (that, array) { var length = array.length < 0 ? 0 : checked(array.length) | 0 that = createBuffer(that, length) for (var i = 0; i < length; i += 1) { that[i] = array[i] & 255 } return that } function fromArrayBuffer (that, array, byteOffset, length) { array.byteLength // this throws if `array` is not a valid ArrayBuffer if (byteOffset < 0 || array.byteLength < byteOffset) { throw new RangeError('\'offset\' is out of bounds') } if (array.byteLength < byteOffset + (length || 0)) { throw new RangeError('\'length\' is out of bounds') } if (byteOffset === undefined && length === undefined) { array = new Uint8Array(array) } else if (length === undefined) { array = new Uint8Array(array, byteOffset) } else { array = new Uint8Array(array, byteOffset, length) } if (Buffer.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = array that.__proto__ = Buffer.prototype } else { // Fallback: Return an object instance of the Buffer class that = fromArrayLike(that, array) } return that } function fromObject (that, obj) { if (Buffer.isBuffer(obj)) { var len = checked(obj.length) | 0 that = createBuffer(that, len) if (that.length === 0) { return that } obj.copy(that, 0, 0, len) return that } if (obj) { if ((typeof ArrayBuffer !== 'undefined' && obj.buffer instanceof ArrayBuffer) || 'length' in obj) { if (typeof obj.length !== 'number' || isnan(obj.length)) { return createBuffer(that, 0) } return fromArrayLike(that, obj) } if (obj.type === 'Buffer' && isArray(obj.data)) { return fromArrayLike(that, obj.data) } } throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') } function checked (length) { // Note: cannot use `length < kMaxLength()` here because that fails when // length is NaN (which is otherwise coerced to zero.) if (length >= kMaxLength()) { throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + kMaxLength().toString(16) + ' bytes') } return length | 0 } function SlowBuffer (length) { if (+length != length) { // eslint-disable-line eqeqeq length = 0 } return Buffer.alloc(+length) } Buffer.isBuffer = function isBuffer (b) { return !!(b != null && b._isBuffer) } Buffer.compare = function compare (a, b) { if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { throw new TypeError('Arguments must be Buffers') } if (a === b) return 0 var x = a.length var y = b.length for (var i = 0, len = Math.min(x, y); i < len; ++i) { if (a[i] !== b[i]) { x = a[i] y = b[i] break } } if (x < y) return -1 if (y < x) return 1 return 0 } Buffer.isEncoding = function isEncoding (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'latin1': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return true default: return false } } Buffer.concat = function concat (list, length) { if (!isArray(list)) { throw new TypeError('"list" argument must be an Array of Buffers') } if (list.length === 0) { return Buffer.alloc(0) } var i if (length === undefined) { length = 0 for (i = 0; i < list.length; ++i) { length += list[i].length } } var buffer = Buffer.allocUnsafe(length) var pos = 0 for (i = 0; i < list.length; ++i) { var buf = list[i] if (!Buffer.isBuffer(buf)) { throw new TypeError('"list" argument must be an Array of Buffers') } buf.copy(buffer, pos) pos += buf.length } return buffer } function byteLength (string, encoding) { if (Buffer.isBuffer(string)) { return string.length } if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { return string.byteLength } if (typeof string !== 'string') { string = '' + string } var len = string.length if (len === 0) return 0 // Use a for loop to avoid recursion var loweredCase = false for (;;) { switch (encoding) { case 'ascii': case 'latin1': case 'binary': return len case 'utf8': case 'utf-8': case undefined: return utf8ToBytes(string).length case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return len * 2 case 'hex': return len >>> 1 case 'base64': return base64ToBytes(string).length default: if (loweredCase) return utf8ToBytes(string).length // assume utf8 encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.byteLength = byteLength function slowToString (encoding, start, end) { var loweredCase = false // No need to verify that "this.length <= MAX_UINT32" since it's a read-only // property of a typed array. // This behaves neither like String nor Uint8Array in that we set start/end // to their upper/lower bounds if the value passed is out of range. // undefined is handled specially as per ECMA-262 6th Edition, // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. if (start === undefined || start < 0) { start = 0 } // Return early if start > this.length. Done here to prevent potential uint32 // coercion fail below. if (start > this.length) { return '' } if (end === undefined || end > this.length) { end = this.length } if (end <= 0) { return '' } // Force coersion to uint32. This will also coerce falsey/NaN values to 0. end >>>= 0 start >>>= 0 if (end <= start) { return '' } if (!encoding) encoding = 'utf8' while (true) { switch (encoding) { case 'hex': return hexSlice(this, start, end) case 'utf8': case 'utf-8': return utf8Slice(this, start, end) case 'ascii': return asciiSlice(this, start, end) case 'latin1': case 'binary': return latin1Slice(this, start, end) case 'base64': return base64Slice(this, start, end) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return utf16leSlice(this, start, end) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = (encoding + '').toLowerCase() loweredCase = true } } } // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect // Buffer instances. Buffer.prototype._isBuffer = true function swap (b, n, m) { var i = b[n] b[n] = b[m] b[m] = i } Buffer.prototype.swap16 = function swap16 () { var len = this.length if (len % 2 !== 0) { throw new RangeError('Buffer size must be a multiple of 16-bits') } for (var i = 0; i < len; i += 2) { swap(this, i, i + 1) } return this } Buffer.prototype.swap32 = function swap32 () { var len = this.length if (len % 4 !== 0) { throw new RangeError('Buffer size must be a multiple of 32-bits') } for (var i = 0; i < len; i += 4) { swap(this, i, i + 3) swap(this, i + 1, i + 2) } return this } Buffer.prototype.swap64 = function swap64 () { var len = this.length if (len % 8 !== 0) { throw new RangeError('Buffer size must be a multiple of 64-bits') } for (var i = 0; i < len; i += 8) { swap(this, i, i + 7) swap(this, i + 1, i + 6) swap(this, i + 2, i + 5) swap(this, i + 3, i + 4) } return this } Buffer.prototype.toString = function toString () { var length = this.length | 0 if (length === 0) return '' if (arguments.length === 0) return utf8Slice(this, 0, length) return slowToString.apply(this, arguments) } Buffer.prototype.equals = function equals (b) { if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return true return Buffer.compare(this, b) === 0 } Buffer.prototype.inspect = function inspect () { var str = '' var max = exports.INSPECT_MAX_BYTES if (this.length > 0) { str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') if (this.length > max) str += ' ... ' } return '<Buffer ' + str + '>' } Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { if (!Buffer.isBuffer(target)) { throw new TypeError('Argument must be a Buffer') } if (start === undefined) { start = 0 } if (end === undefined) { end = target ? target.length : 0 } if (thisStart === undefined) { thisStart = 0 } if (thisEnd === undefined) { thisEnd = this.length } if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { throw new RangeError('out of range index') } if (thisStart >= thisEnd && start >= end) { return 0 } if (thisStart >= thisEnd) { return -1 } if (start >= end) { return 1 } start >>>= 0 end >>>= 0 thisStart >>>= 0 thisEnd >>>= 0 if (this === target) return 0 var x = thisEnd - thisStart var y = end - start var len = Math.min(x, y) var thisCopy = this.slice(thisStart, thisEnd) var targetCopy = target.slice(start, end) for (var i = 0; i < len; ++i) { if (thisCopy[i] !== targetCopy[i]) { x = thisCopy[i] y = targetCopy[i] break } } if (x < y) return -1 if (y < x) return 1 return 0 } // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, // OR the last index of `val` in `buffer` at offset <= `byteOffset`. // // Arguments: // - buffer - a Buffer to search // - val - a string, Buffer, or number // - byteOffset - an index into `buffer`; will be clamped to an int32 // - encoding - an optional encoding, relevant is val is a string // - dir - true for indexOf, false for lastIndexOf function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { // Empty buffer means no match if (buffer.length === 0) return -1 // Normalize byteOffset if (typeof byteOffset === 'string') { encoding = byteOffset byteOffset = 0 } else if (byteOffset > 0x7fffffff) { byteOffset = 0x7fffffff } else if (byteOffset < -0x80000000) { byteOffset = -0x80000000 } byteOffset = +byteOffset // Coerce to Number. if (isNaN(byteOffset)) { // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer byteOffset = dir ? 0 : (buffer.length - 1) } // Normalize byteOffset: negative offsets start from the end of the buffer if (byteOffset < 0) byteOffset = buffer.length + byteOffset if (byteOffset >= buffer.length) { if (dir) return -1 else byteOffset = buffer.length - 1 } else if (byteOffset < 0) { if (dir) byteOffset = 0 else return -1 } // Normalize val if (typeof val === 'string') { val = Buffer.from(val, encoding) } // Finally, search either indexOf (if dir is true) or lastIndexOf if (Buffer.isBuffer(val)) { // Special case: looking for empty string/buffer always fails if (val.length === 0) { return -1 } return arrayIndexOf(buffer, val, byteOffset, encoding, dir) } else if (typeof val === 'number') { val = val & 0xFF // Search for a byte value [0-255] if (Buffer.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === 'function') { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) } else { return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) } } return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) } throw new TypeError('val must be string, number or Buffer') } function arrayIndexOf (arr, val, byteOffset, encoding, dir) { var indexSize = 1 var arrLength = arr.length var valLength = val.length if (encoding !== undefined) { encoding = String(encoding).toLowerCase() if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') { if (arr.length < 2 || val.length < 2) { return -1 } indexSize = 2 arrLength /= 2 valLength /= 2 byteOffset /= 2 } } function read (buf, i) { if (indexSize === 1) { return buf[i] } else { return buf.readUInt16BE(i * indexSize) } } var i if (dir) { var foundIndex = -1 for (i = byteOffset; i < arrLength; i++) { if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { if (foundIndex === -1) foundIndex = i if (i - foundIndex + 1 === valLength) return foundIndex * indexSize } else { if (foundIndex !== -1) i -= i - foundIndex foundIndex = -1 } } } else { if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength for (i = byteOffset; i >= 0; i--) { var found = true for (var j = 0; j < valLength; j++) { if (read(arr, i + j) !== read(val, j)) { found = false break } } if (found) return i } } return -1 } Buffer.prototype.includes = function includes (val, byteOffset, encoding) { return this.indexOf(val, byteOffset, encoding) !== -1 } Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, true) } Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, false) } function hexWrite (buf, string, offset, length) { offset = Number(offset) || 0 var remaining = buf.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } // must be an even number of digits var strLen = string.length if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') if (length > strLen / 2) { length = strLen / 2 } for (var i = 0; i < length; ++i) { var parsed = parseInt(string.substr(i * 2, 2), 16) if (isNaN(parsed)) return i buf[offset + i] = parsed } return i } function utf8Write (buf, string, offset, length) { return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) } function asciiWrite (buf, string, offset, length) { return blitBuffer(asciiToBytes(string), buf, offset, length) } function latin1Write (buf, string, offset, length) { return asciiWrite(buf, string, offset, length) } function base64Write (buf, string, offset, length) { return blitBuffer(base64ToBytes(string), buf, offset, length) } function ucs2Write (buf, string, offset, length) { return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } Buffer.prototype.write = function write (string, offset, length, encoding) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8' length = this.length offset = 0 // Buffer#write(string, encoding) } else if (length === undefined && typeof offset === 'string') { encoding = offset length = this.length offset = 0 // Buffer#write(string, offset[, length][, encoding]) } else if (isFinite(offset)) { offset = offset | 0 if (isFinite(length)) { length = length | 0 if (encoding === undefined) encoding = 'utf8' } else { encoding = length length = undefined } // legacy write(string, encoding, offset, length) - remove in v0.13 } else { throw new Error( 'Buffer.write(string, encoding, offset[, length]) is no longer supported' ) } var remaining = this.length - offset if (length === undefined || length > remaining) length = remaining if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { throw new RangeError('Attempt to write outside buffer bounds') } if (!encoding) encoding = 'utf8' var loweredCase = false for (;;) { switch (encoding) { case 'hex': return hexWrite(this, string, offset, length) case 'utf8': case 'utf-8': return utf8Write(this, string, offset, length) case 'ascii': return asciiWrite(this, string, offset, length) case 'latin1': case 'binary': return latin1Write(this, string, offset, length) case 'base64': // Warning: maxLength not taken into account in base64Write return base64Write(this, string, offset, length) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return ucs2Write(this, string, offset, length) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.prototype.toJSON = function toJSON () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) } } function base64Slice (buf, start, end) { if (start === 0 && end === buf.length) { return base64.fromByteArray(buf) } else { return base64.fromByteArray(buf.slice(start, end)) } } function utf8Slice (buf, start, end) { end = Math.min(buf.length, end) var res = [] var i = start while (i < end) { var firstByte = buf[i] var codePoint = null var bytesPerSequence = (firstByte > 0xEF) ? 4 : (firstByte > 0xDF) ? 3 : (firstByte > 0xBF) ? 2 : 1 if (i + bytesPerSequence <= end) { var secondByte, thirdByte, fourthByte, tempCodePoint switch (bytesPerSequence) { case 1: if (firstByte < 0x80) { codePoint = firstByte } break case 2: secondByte = buf[i + 1] if ((secondByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) if (tempCodePoint > 0x7F) { codePoint = tempCodePoint } } break case 3: secondByte = buf[i + 1] thirdByte = buf[i + 2] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { codePoint = tempCodePoint } } break case 4: secondByte = buf[i + 1] thirdByte = buf[i + 2] fourthByte = buf[i + 3] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { codePoint = tempCodePoint } } } } if (codePoint === null) { // we did not generate a valid codePoint so insert a // replacement char (U+FFFD) and advance only 1 byte codePoint = 0xFFFD bytesPerSequence = 1 } else if (codePoint > 0xFFFF) { // encode to utf16 (surrogate pair dance) codePoint -= 0x10000 res.push(codePoint >>> 10 & 0x3FF | 0xD800) codePoint = 0xDC00 | codePoint & 0x3FF } res.push(codePoint) i += bytesPerSequence } return decodeCodePointsArray(res) } // Based on http://stackoverflow.com/a/22747272/680742, the browser with // the lowest limit is Chrome, with 0x10000 args. // We go 1 magnitude less, for safety var MAX_ARGUMENTS_LENGTH = 0x1000 function decodeCodePointsArray (codePoints) { var len = codePoints.length if (len <= MAX_ARGUMENTS_LENGTH) { return String.fromCharCode.apply(String, codePoints) // avoid extra slice() } // Decode in chunks to avoid "call stack size exceeded". var res = '' var i = 0 while (i < len) { res += String.fromCharCode.apply( String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) ) } return res } function asciiSlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i] & 0x7F) } return ret } function latin1Slice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i]) } return ret } function hexSlice (buf, start, end) { var len = buf.length if (!start || start < 0) start = 0 if (!end || end < 0 || end > len) end = len var out = '' for (var i = start; i < end; ++i) { out += toHex(buf[i]) } return out } function utf16leSlice (buf, start, end) { var bytes = buf.slice(start, end) var res = '' for (var i = 0; i < bytes.length; i += 2) { res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) } return res } Buffer.prototype.slice = function slice (start, end) { var len = this.length start = ~~start end = end === undefined ? len : ~~end if (start < 0) { start += len if (start < 0) start = 0 } else if (start > len) { start = len } if (end < 0) { end += len if (end < 0) end = 0 } else if (end > len) { end = len } if (end < start) end = start var newBuf if (Buffer.TYPED_ARRAY_SUPPORT) { newBuf = this.subarray(start, end) newBuf.__proto__ = Buffer.prototype } else { var sliceLen = end - start newBuf = new Buffer(sliceLen, undefined) for (var i = 0; i < sliceLen; ++i) { newBuf[i] = this[i + start] } } return newBuf } /* * Need to make sure that buffer isn't trying to write out of bounds. */ function checkOffset (offset, ext, length) { if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } return val } Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) { checkOffset(offset, byteLength, this.length) } var val = this[offset + --byteLength] var mul = 1 while (byteLength > 0 && (mul *= 0x100)) { val += this[offset + --byteLength] * mul } return val } Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length) return this[offset] } Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) return this[offset] | (this[offset + 1] << 8) } Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) return (this[offset] << 8) | this[offset + 1] } Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ((this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16)) + (this[offset + 3] * 0x1000000) } Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] * 0x1000000) + ((this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3]) } Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var i = byteLength var mul = 1 var val = this[offset + --i] while (i > 0 && (mul *= 0x100)) { val += this[offset + --i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length) if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) } Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset] | (this[offset + 1] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset + 1] | (this[offset] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16) | (this[offset + 3] << 24) } Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] << 24) | (this[offset + 1] << 16) | (this[offset + 2] << 8) | (this[offset + 3]) } Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, true, 23, 4) } Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, false, 23, 4) } Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, true, 52, 8) } Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, false, 52, 8) } function checkInt (buf, value, offset, ext, max, min) { if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') if (offset + ext > buf.length) throw new RangeError('Index out of range') } Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1 checkInt(this, value, offset, byteLength, maxBytes, 0) } var mul = 1 var i = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1 checkInt(this, value, offset, byteLength, maxBytes, 0) } var i = byteLength - 1 var mul = 1 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) this[offset] = (value & 0xff) return offset + 1 } function objectWriteUInt16 (buf, value, offset, littleEndian) { if (value < 0) value = 0xffff + value + 1 for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> (littleEndian ? i : 1 - i) * 8 } } Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) } else { objectWriteUInt16(this, value, offset, true) } return offset + 2 } Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) } else { objectWriteUInt16(this, value, offset, false) } return offset + 2 } function objectWriteUInt32 (buf, value, offset, littleEndian) { if (value < 0) value = 0xffffffff + value + 1 for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff } } Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset + 3] = (value >>> 24) this[offset + 2] = (value >>> 16) this[offset + 1] = (value >>> 8) this[offset] = (value & 0xff) } else { objectWriteUInt32(this, value, offset, true) } return offset + 4 } Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) } else { objectWriteUInt32(this, value, offset, false) } return offset + 4 } Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = 0 var mul = 1 var sub = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { sub = 1 } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = byteLength - 1 var mul = 1 var sub = 0 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { sub = 1 } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) if (value < 0) value = 0xff + value + 1 this[offset] = (value & 0xff) return offset + 1 } Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) } else { objectWriteUInt16(this, value, offset, true) } return offset + 2 } Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) } else { objectWriteUInt16(this, value, offset, false) } return offset + 2 } Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) this[offset + 2] = (value >>> 16) this[offset + 3] = (value >>> 24) } else { objectWriteUInt32(this, value, offset, true) } return offset + 4 } Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (value < 0) value = 0xffffffff + value + 1 if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) } else { objectWriteUInt32(this, value, offset, false) } return offset + 4 } function checkIEEE754 (buf, value, offset, ext, max, min) { if (offset + ext > buf.length) throw new RangeError('Index out of range') if (offset < 0) throw new RangeError('Index out of range') } function writeFloat (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) } ieee754.write(buf, value, offset, littleEndian, 23, 4) return offset + 4 } Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert) } Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert) } function writeDouble (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) } ieee754.write(buf, value, offset, littleEndian, 52, 8) return offset + 8 } Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) } Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) } // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy = function copy (target, targetStart, start, end) { if (!start) start = 0 if (!end && end !== 0) end = this.length if (targetStart >= target.length) targetStart = target.length if (!targetStart) targetStart = 0 if (end > 0 && end < start) end = start // Copy 0 bytes; we're done if (end === start) return 0 if (target.length === 0 || this.length === 0) return 0 // Fatal error conditions if (targetStart < 0) { throw new RangeError('targetStart out of bounds') } if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') if (end < 0) throw new RangeError('sourceEnd out of bounds') // Are we oob? if (end > this.length) end = this.length if (target.length - targetStart < end - start) { end = target.length - targetStart + start } var len = end - start var i if (this === target && start < targetStart && targetStart < end) { // descending copy from end for (i = len - 1; i >= 0; --i) { target[i + targetStart] = this[i + start] } } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { // ascending copy from start for (i = 0; i < len; ++i) { target[i + targetStart] = this[i + start] } } else { Uint8Array.prototype.set.call( target, this.subarray(start, start + len), targetStart ) } return len } // Usage: // buffer.fill(number[, offset[, end]]) // buffer.fill(buffer[, offset[, end]]) // buffer.fill(string[, offset[, end]][, encoding]) Buffer.prototype.fill = function fill (val, start, end, encoding) { // Handle string cases: if (typeof val === 'string') { if (typeof start === 'string') { encoding = start start = 0 end = this.length } else if (typeof end === 'string') { encoding = end end = this.length } if (val.length === 1) { var code = val.charCodeAt(0) if (code < 256) { val = code } } if (encoding !== undefined && typeof encoding !== 'string') { throw new TypeError('encoding must be a string') } if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding) } } else if (typeof val === 'number') { val = val & 255 } // Invalid ranges are not set to a default, so can range check early. if (start < 0 || this.length < start || this.length < end) { throw new RangeError('Out of range index') } if (end <= start) { return this } start = start >>> 0 end = end === undefined ? this.length : end >>> 0 if (!val) val = 0 var i if (typeof val === 'number') { for (i = start; i < end; ++i) { this[i] = val } } else { var bytes = Buffer.isBuffer(val) ? val : utf8ToBytes(new Buffer(val, encoding).toString()) var len = bytes.length for (i = 0; i < end - start; ++i) { this[i + start] = bytes[i % len] } } return this } // HELPER FUNCTIONS // ================ var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g function base64clean (str) { // Node strips out invalid characters like \n and \t from the string, base64-js does not str = stringtrim(str).replace(INVALID_BASE64_RE, '') // Node converts strings with length < 2 to '' if (str.length < 2) return '' // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not while (str.length % 4 !== 0) { str = str + '=' } return str } function stringtrim (str) { if (str.trim) return str.trim() return str.replace(/^\s+|\s+$/g, '') } function toHex (n) { if (n < 16) return '0' + n.toString(16) return n.toString(16) } function utf8ToBytes (string, units) { units = units || Infinity var codePoint var length = string.length var leadSurrogate = null var bytes = [] for (var i = 0; i < length; ++i) { codePoint = string.charCodeAt(i) // is surrogate component if (codePoint > 0xD7FF && codePoint < 0xE000) { // last char was a lead if (!leadSurrogate) { // no lead yet if (codePoint > 0xDBFF) { // unexpected trail if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } else if (i + 1 === length) { // unpaired lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } // valid lead leadSurrogate = codePoint continue } // 2 leads in a row if (codePoint < 0xDC00) { if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) leadSurrogate = codePoint continue } // valid surrogate pair codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 } else if (leadSurrogate) { // valid bmp char, but last char was a lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) } leadSurrogate = null // encode utf8 if (codePoint < 0x80) { if ((units -= 1) < 0) break bytes.push(codePoint) } else if (codePoint < 0x800) { if ((units -= 2) < 0) break bytes.push( codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x10000) { if ((units -= 3) < 0) break bytes.push( codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x110000) { if ((units -= 4) < 0) break bytes.push( codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else { throw new Error('Invalid code point') } } return bytes } function asciiToBytes (str) { var byteArray = [] for (var i = 0; i < str.length; ++i) { // Node's code seems to be doing this and not & 0x7F.. byteArray.push(str.charCodeAt(i) & 0xFF) } return byteArray } function utf16leToBytes (str, units) { var c, hi, lo var byteArray = [] for (var i = 0; i < str.length; ++i) { if ((units -= 2) < 0) break c = str.charCodeAt(i) hi = c >> 8 lo = c % 256 byteArray.push(lo) byteArray.push(hi) } return byteArray } function base64ToBytes (str) { return base64.toByteArray(base64clean(str)) } function blitBuffer (src, dst, offset, length) { for (var i = 0; i < length; ++i) { if ((i + offset >= dst.length) || (i >= src.length)) break dst[i + offset] = src[i] } return i } function isnan (val) { return val !== val // eslint-disable-line no-self-compare } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"base64-js":1,"ieee754":8,"isarray":11}],5:[function(require,module,exports){ module.exports = { "100": "Continue", "101": "Switching Protocols", "102": "Processing", "200": "OK", "201": "Created", "202": "Accepted", "203": "Non-Authoritative Information", "204": "No Content", "205": "Reset Content", "206": "Partial Content", "207": "Multi-Status", "208": "Already Reported", "226": "IM Used", "300": "Multiple Choices", "301": "Moved Permanently", "302": "Found", "303": "See Other", "304": "Not Modified", "305": "Use Proxy", "307": "Temporary Redirect", "308": "Permanent Redirect", "400": "Bad Request", "401": "Unauthorized", "402": "Payment Required", "403": "Forbidden", "404": "Not Found", "405": "Method Not Allowed", "406": "Not Acceptable", "407": "Proxy Authentication Required", "408": "Request Timeout", "409": "Conflict", "410": "Gone", "411": "Length Required", "412": "Precondition Failed", "413": "Payload Too Large", "414": "URI Too Long", "415": "Unsupported Media Type", "416": "Range Not Satisfiable", "417": "Expectation Failed", "418": "I'm a teapot", "421": "Misdirected Request", "422": "Unprocessable Entity", "423": "Locked", "424": "Failed Dependency", "425": "Unordered Collection", "426": "Upgrade Required", "428": "Precondition Required", "429": "Too Many Requests", "431": "Request Header Fields Too Large", "451": "Unavailable For Legal Reasons", "500": "Internal Server Error", "501": "Not Implemented", "502": "Bad Gateway", "503": "Service Unavailable", "504": "Gateway Timeout", "505": "HTTP Version Not Supported", "506": "Variant Also Negotiates", "507": "Insufficient Storage", "508": "Loop Detected", "509": "Bandwidth Limit Exceeded", "510": "Not Extended", "511": "Network Authentication Required" } },{}],6:[function(require,module,exports){ (function (Buffer){ // Copyright Joyent, Inc. and other Node contributors. // // 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. // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(arg) { if (Array.isArray) { return Array.isArray(arg); } return objectToString(arg) === '[object Array]'; } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = Buffer.isBuffer; function objectToString(o) { return Object.prototype.toString.call(o); } }).call(this,{"isBuffer":require("../../is-buffer/index.js")}) },{"../../is-buffer/index.js":10}],7:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. function EventEmitter() { this._events = this._events || {}; this._maxListeners = this._maxListeners || undefined; } module.exports = EventEmitter; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. EventEmitter.defaultMaxListeners = 10; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function(n) { if (!isNumber(n) || n < 0 || isNaN(n)) throw TypeError('n must be a positive number'); this._maxListeners = n; return this; }; EventEmitter.prototype.emit = function(type) { var er, handler, len, args, i, listeners; if (!this._events) this._events = {}; // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._events.error || (isObject(this._events.error) && !this._events.error.length)) { er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } else { // At least give some kind of context to the user var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); err.context = er; throw err; } } } handler = this._events[type]; if (isUndefined(handler)) return false; if (isFunction(handler)) { switch (arguments.length) { // fast cases case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: args = Array.prototype.slice.call(arguments, 1); handler.apply(this, args); } } else if (isObject(handler)) { args = Array.prototype.slice.call(arguments, 1); listeners = handler.slice(); len = listeners.length; for (i = 0; i < len; i++) listeners[i].apply(this, args); } return true; }; EventEmitter.prototype.addListener = function(type, listener) { var m; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events) this._events = {}; // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (this._events.newListener) this.emit('newListener', type, isFunction(listener.listener) ? listener.listener : listener); if (!this._events[type]) // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; else if (isObject(this._events[type])) // If we've already got an array, just append. this._events[type].push(listener); else // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; // Check for listener leak if (isObject(this._events[type]) && !this._events[type].warned) { if (!isUndefined(this._maxListeners)) { m = this._maxListeners; } else { m = EventEmitter.defaultMaxListeners; } if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); if (typeof console.trace === 'function') { // not supported in IE 10 console.trace(); } } } return this; }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function(type, listener) { if (!isFunction(listener)) throw TypeError('listener must be a function'); var fired = false; function g() { this.removeListener(type, g); if (!fired) { fired = true; listener.apply(this, arguments); } } g.listener = listener; this.on(type, g); return this; }; // emits a 'removeListener' event iff the listener was removed EventEmitter.prototype.removeListener = function(type, listener) { var list, position, length, i; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) return this; list = this._events[type]; length = list.length; position = -1; if (list === listener || (isFunction(list.listener) && list.listener === listener)) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); } else if (isObject(list)) { for (i = length; i-- > 0;) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position < 0) return this; if (list.length === 1) { list.length = 0; delete this._events[type]; } else { list.splice(position, 1); } if (this._events.removeListener) this.emit('removeListener', type, listener); } return this; }; EventEmitter.prototype.removeAllListeners = function(type) { var key, listeners; if (!this._events) return this; // not listening for removeListener, no need to emit if (!this._events.removeListener) { if (arguments.length === 0) this._events = {}; else if (this._events[type]) delete this._events[type]; return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { for (key in this._events) { if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = {}; return this; } listeners = this._events[type]; if (isFunction(listeners)) { this.removeListener(type, listeners); } else if (listeners) { // LIFO order while (listeners.length) this.removeListener(type, listeners[listeners.length - 1]); } delete this._events[type]; return this; }; EventEmitter.prototype.listeners = function(type) { var ret; if (!this._events || !this._events[type]) ret = []; else if (isFunction(this._events[type])) ret = [this._events[type]]; else ret = this._events[type].slice(); return ret; }; EventEmitter.prototype.listenerCount = function(type) { if (this._events) { var evlistener = this._events[type]; if (isFunction(evlistener)) return 1; else if (evlistener) return evlistener.length; } return 0; }; EventEmitter.listenerCount = function(emitter, type) { return emitter.listenerCount(type); }; function isFunction(arg) { return typeof arg === 'function'; } function isNumber(arg) { return typeof arg === 'number'; } function isObject(arg) { return typeof arg === 'object' && arg !== null; } function isUndefined(arg) { return arg === void 0; } },{}],8:[function(require,module,exports){ exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m var eLen = nBytes * 8 - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var nBits = -7 var i = isLE ? (nBytes - 1) : 0 var d = isLE ? -1 : 1 var s = buffer[offset + i] i += d e = s & ((1 << (-nBits)) - 1) s >>= (-nBits) nBits += eLen for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} m = e & ((1 << (-nBits)) - 1) e >>= (-nBits) nBits += mLen for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} if (e === 0) { e = 1 - eBias } else if (e === eMax) { return m ? NaN : ((s ? -1 : 1) * Infinity) } else { m = m + Math.pow(2, mLen) e = e - eBias } return (s ? -1 : 1) * m * Math.pow(2, e - mLen) } exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { var e, m, c var eLen = nBytes * 8 - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) var i = isLE ? 0 : (nBytes - 1) var d = isLE ? 1 : -1 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 value = Math.abs(value) if (isNaN(value) || value === Infinity) { m = isNaN(value) ? 1 : 0 e = eMax } else { e = Math.floor(Math.log(value) / Math.LN2) if (value * (c = Math.pow(2, -e)) < 1) { e-- c *= 2 } if (e + eBias >= 1) { value += rt / c } else { value += rt * Math.pow(2, 1 - eBias) } if (value * c >= 2) { e++ c /= 2 } if (e + eBias >= eMax) { m = 0 e = eMax } else if (e + eBias >= 1) { m = (value * c - 1) * Math.pow(2, mLen) e = e + eBias } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) e = 0 } } for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} e = (e << mLen) | m eLen += mLen for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} buffer[offset + i - d] |= s * 128 } },{}],9:[function(require,module,exports){ if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } },{}],10:[function(require,module,exports){ /*! * Determine if an object is a Buffer * * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org> * @license MIT */ // The _isBuffer check is for Safari 5-7 support, because it's missing // Object.prototype.constructor. Remove this eventually module.exports = function (obj) { return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) } function isBuffer (obj) { return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) } // For Node v0.10 support. Remove this eventually. function isSlowBuffer (obj) { return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) } },{}],11:[function(require,module,exports){ var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; },{}],12:[function(require,module,exports){ (function (process){ 'use strict'; if (!process.version || process.version.indexOf('v0.') === 0 || process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { module.exports = nextTick; } else { module.exports = process.nextTick; } function nextTick(fn, arg1, arg2, arg3) { if (typeof fn !== 'function') { throw new TypeError('"callback" argument must be a function'); } var len = arguments.length; var args, i; switch (len) { case 0: case 1: return process.nextTick(fn); case 2: return process.nextTick(function afterTickOne() { fn.call(null, arg1); }); case 3: return process.nextTick(function afterTickTwo() { fn.call(null, arg1, arg2); }); case 4: return process.nextTick(function afterTickThree() { fn.call(null, arg1, arg2, arg3); }); default: args = new Array(len - 1); i = 0; while (i < args.length) { args[i++] = arguments[i]; } return process.nextTick(function afterTick() { fn.apply(null, args); }); } } }).call(this,require('_process')) },{"_process":13}],13:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],14:[function(require,module,exports){ (function (global){ /*! https://mths.be/punycode v1.4.1 by @mathias */ ;(function(root) { /** Detect free variables */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; var freeModule = typeof module == 'object' && module && !module.nodeType && module; var freeGlobal = typeof global == 'object' && global; if ( freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal || freeGlobal.self === freeGlobal ) { root = freeGlobal; } /** * The `punycode` object. * @name punycode * @type Object */ var punycode, /** Highest positive signed 32-bit float value */ maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 /** Bootstring parameters */ base = 36, tMin = 1, tMax = 26, skew = 38, damp = 700, initialBias = 72, initialN = 128, // 0x80 delimiter = '-', // '\x2D' /** Regular expressions */ regexPunycode = /^xn--/, regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators /** Error messages */ errors = { 'overflow': 'Overflow: input needs wider integers to process', 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', 'invalid-input': 'Invalid input' }, /** Convenience shortcuts */ baseMinusTMin = base - tMin, floor = Math.floor, stringFromCharCode = String.fromCharCode, /** Temporary variable */ key; /*--------------------------------------------------------------------------*/ /** * A generic error utility function. * @private * @param {String} type The error type. * @returns {Error} Throws a `RangeError` with the applicable error message. */ function error(type) { throw new RangeError(errors[type]); } /** * A generic `Array#map` utility function. * @private * @param {Array} array The array to iterate over. * @param {Function} callback The function that gets called for every array * item. * @returns {Array} A new array of values returned by the callback function. */ function map(array, fn) { var length = array.length; var result = []; while (length--) { result[length] = fn(array[length]); } return result; } /** * A simple `Array#map`-like wrapper to work with domain name strings or email * addresses. * @private * @param {String} domain The domain name or email address. * @param {Function} callback The function that gets called for every * character. * @returns {Array} A new string of characters returned by the callback * function. */ function mapDomain(string, fn) { var parts = string.split('@'); var result = ''; if (parts.length > 1) { // In email addresses, only the domain name should be punycoded. Leave // the local part (i.e. everything up to `@`) intact. result = parts[0] + '@'; string = parts[1]; } // Avoid `split(regex)` for IE8 compatibility. See #17. string = string.replace(regexSeparators, '\x2E'); var labels = string.split('.'); var encoded = map(labels, fn).join('.'); return result + encoded; } /** * Creates an array containing the numeric code points of each Unicode * character in the string. While JavaScript uses UCS-2 internally, * this function will convert a pair of surrogate halves (each of which * UCS-2 exposes as separate characters) into a single code point, * matching UTF-16. * @see `punycode.ucs2.encode` * @see <https://mathiasbynens.be/notes/javascript-encoding> * @memberOf punycode.ucs2 * @name decode * @param {String} string The Unicode input string (UCS-2). * @returns {Array} The new array of code points. */ function ucs2decode(string) { var output = [], counter = 0, length = string.length, value, extra; while (counter < length) { value = string.charCodeAt(counter++); if (value >= 0xD800 && value <= 0xDBFF && counter < length) { // high surrogate, and there is a next character extra = string.charCodeAt(counter++); if ((extra & 0xFC00) == 0xDC00) { // low surrogate output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); } else { // unmatched surrogate; only append this code unit, in case the next // code unit is the high surrogate of a surrogate pair output.push(value); counter--; } } else { output.push(value); } } return output; } /** * Creates a string based on an array of numeric code points. * @see `punycode.ucs2.decode` * @memberOf punycode.ucs2 * @name encode * @param {Array} codePoints The array of numeric code points. * @returns {String} The new Unicode string (UCS-2). */ function ucs2encode(array) { return map(array, function(value) { var output = ''; if (value > 0xFFFF) { value -= 0x10000; output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); value = 0xDC00 | value & 0x3FF; } output += stringFromCharCode(value); return output; }).join(''); } /** * Converts a basic code point into a digit/integer. * @see `digitToBasic()` * @private * @param {Number} codePoint The basic numeric code point value. * @returns {Number} The numeric value of a basic code point (for use in * representing integers) in the range `0` to `base - 1`, or `base` if * the code point does not represent a value. */ function basicToDigit(codePoint) { if (codePoint - 48 < 10) { return codePoint - 22; } if (codePoint - 65 < 26) { return codePoint - 65; } if (codePoint - 97 < 26) { return codePoint - 97; } return base; } /** * Converts a digit/integer into a basic code point. * @see `basicToDigit()` * @private * @param {Number} digit The numeric value of a basic code point. * @returns {Number} The basic code point whose value (when used for * representing integers) is `digit`, which needs to be in the range * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is * used; else, the lowercase form is used. The behavior is undefined * if `flag` is non-zero and `digit` has no uppercase form. */ function digitToBasic(digit, flag) { // 0..25 map to ASCII a..z or A..Z // 26..35 map to ASCII 0..9 return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); } /** * Bias adaptation function as per section 3.4 of RFC 3492. * https://tools.ietf.org/html/rfc3492#section-3.4 * @private */ function adapt(delta, numPoints, firstTime) { var k = 0; delta = firstTime ? floor(delta / damp) : delta >> 1; delta += floor(delta / numPoints); for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { delta = floor(delta / baseMinusTMin); } return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); } /** * Converts a Punycode string of ASCII-only symbols to a string of Unicode * symbols. * @memberOf punycode * @param {String} input The Punycode string of ASCII-only symbols. * @returns {String} The resulting string of Unicode symbols. */ function decode(input) { // Don't use UCS-2 var output = [], inputLength = input.length, out, i = 0, n = initialN, bias = initialBias, basic, j, index, oldi, w, k, digit, t, /** Cached calculation results */ baseMinusT; // Handle the basic code points: let `basic` be the number of input code // points before the last delimiter, or `0` if there is none, then copy // the first basic code points to the output. basic = input.lastIndexOf(delimiter); if (basic < 0) { basic = 0; } for (j = 0; j < basic; ++j) { // if it's not a basic code point if (input.charCodeAt(j) >= 0x80) { error('not-basic'); } output.push(input.charCodeAt(j)); } // Main decoding loop: start just after the last delimiter if any basic code // points were copied; start at the beginning otherwise. for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { // `index` is the index of the next character to be consumed. // Decode a generalized variable-length integer into `delta`, // which gets added to `i`. The overflow checking is easier // if we increase `i` as we go, then subtract off its starting // value at the end to obtain `delta`. for (oldi = i, w = 1, k = base; /* no condition */; k += base) { if (index >= inputLength) { error('invalid-input'); } digit = basicToDigit(input.charCodeAt(index++)); if (digit >= base || digit > floor((maxInt - i) / w)) { error('overflow'); } i += digit * w; t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); if (digit < t) { break; } baseMinusT = base - t; if (w > floor(maxInt / baseMinusT)) { error('overflow'); } w *= baseMinusT; } out = output.length + 1; bias = adapt(i - oldi, out, oldi == 0); // `i` was supposed to wrap around from `out` to `0`, // incrementing `n` each time, so we'll fix that now: if (floor(i / out) > maxInt - n) { error('overflow'); } n += floor(i / out); i %= out; // Insert `n` at position `i` of the output output.splice(i++, 0, n); } return ucs2encode(output); } /** * Converts a string of Unicode symbols (e.g. a domain name label) to a * Punycode string of ASCII-only symbols. * @memberOf punycode * @param {String} input The string of Unicode symbols. * @returns {String} The resulting Punycode string of ASCII-only symbols. */ function encode(input) { var n, delta, handledCPCount, basicLength, bias, j, m, q, k, t, currentValue, output = [], /** `inputLength` will hold the number of code points in `input`. */ inputLength, /** Cached calculation results */ handledCPCountPlusOne, baseMinusT, qMinusT; // Convert the input in UCS-2 to Unicode input = ucs2decode(input); // Cache the length inputLength = input.length; // Initialize the state n = initialN; delta = 0; bias = initialBias; // Handle the basic code points for (j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue < 0x80) { output.push(stringFromCharCode(currentValue)); } } handledCPCount = basicLength = output.length; // `handledCPCount` is the number of code points that have been handled; // `basicLength` is the number of basic code points. // Finish the basic string - if it is not empty - with a delimiter if (basicLength) { output.push(delimiter); } // Main encoding loop: while (handledCPCount < inputLength) { // All non-basic code points < n have been handled already. Find the next // larger one: for (m = maxInt, j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue >= n && currentValue < m) { m = currentValue; } } // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>, // but guard against overflow handledCPCountPlusOne = handledCPCount + 1; if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { error('overflow'); } delta += (m - n) * handledCPCountPlusOne; n = m; for (j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue < n && ++delta > maxInt) { error('overflow'); } if (currentValue == n) { // Represent delta as a generalized variable-length integer for (q = delta, k = base; /* no condition */; k += base) { t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); if (q < t) { break; } qMinusT = q - t; baseMinusT = base - t; output.push( stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) ); q = floor(qMinusT / baseMinusT); } output.push(stringFromCharCode(digitToBasic(q, 0))); bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); delta = 0; ++handledCPCount; } } ++delta; ++n; } return output.join(''); } /** * Converts a Punycode string representing a domain name or an email address * to Unicode. Only the Punycoded parts of the input will be converted, i.e. * it doesn't matter if you call it on a string that has already been * converted to Unicode. * @memberOf punycode * @param {String} input The Punycoded domain name or email address to * convert to Unicode. * @returns {String} The Unicode representation of the given Punycode * string. */ function toUnicode(input) { return mapDomain(input, function(string) { return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; }); } /** * Converts a Unicode string representing a domain name or an email address to * Punycode. Only the non-ASCII parts of the domain name will be converted, * i.e. it doesn't matter if you call it with a domain that's already in * ASCII. * @memberOf punycode * @param {String} input The domain name or email address to convert, as a * Unicode string. * @returns {String} The Punycode representation of the given domain name or * email address. */ function toASCII(input) { return mapDomain(input, function(string) { return regexNonASCII.test(string) ? 'xn--' + encode(string) : string; }); } /*--------------------------------------------------------------------------*/ /** Define the public API */ punycode = { /** * A string representing the current Punycode.js version number. * @memberOf punycode * @type String */ 'version': '1.4.1', /** * An object of methods to convert from JavaScript's internal character * representation (UCS-2) to Unicode code points, and back. * @see <https://mathiasbynens.be/notes/javascript-encoding> * @memberOf punycode * @type Object */ 'ucs2': { 'decode': ucs2decode, 'encode': ucs2encode }, 'decode': decode, 'encode': encode, 'toASCII': toASCII, 'toUnicode': toUnicode }; /** Expose `punycode` */ // Some AMD build optimizers, like r.js, check for specific condition patterns // like the following: if ( typeof define == 'function' && typeof define.amd == 'object' && define.amd ) { define('punycode', function() { return punycode; }); } else if (freeExports && freeModule) { if (module.exports == freeExports) { // in Node.js, io.js, or RingoJS v0.8.0+ freeModule.exports = punycode; } else { // in Narwhal or RingoJS v0.7.0- for (key in punycode) { punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); } } } else { // in Rhino or a web browser root.punycode = punycode; } }(this)); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],15:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // 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. 'use strict'; // If obj.hasOwnProperty has been overridden, then calling // obj.hasOwnProperty(prop) will break. // See: https://github.com/joyent/node/issues/1707 function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } module.exports = function(qs, sep, eq, options) { sep = sep || '&'; eq = eq || '='; var obj = {}; if (typeof qs !== 'string' || qs.length === 0) { return obj; } var regexp = /\+/g; qs = qs.split(sep); var maxKeys = 1000; if (options && typeof options.maxKeys === 'number') { maxKeys = options.maxKeys; } var len = qs.length; // maxKeys <= 0 means that we should not limit keys count if (maxKeys > 0 && len > maxKeys) { len = maxKeys; } for (var i = 0; i < len; ++i) { var x = qs[i].replace(regexp, '%20'), idx = x.indexOf(eq), kstr, vstr, k, v; if (idx >= 0) { kstr = x.substr(0, idx); vstr = x.substr(idx + 1); } else { kstr = x; vstr = ''; } k = decodeURIComponent(kstr); v = decodeURIComponent(vstr); if (!hasOwnProperty(obj, k)) { obj[k] = v; } else if (isArray(obj[k])) { obj[k].push(v); } else { obj[k] = [obj[k], v]; } } return obj; }; var isArray = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; },{}],16:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // 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. 'use strict'; var stringifyPrimitive = function(v) { switch (typeof v) { case 'string': return v; case 'boolean': return v ? 'true' : 'false'; case 'number': return isFinite(v) ? v : ''; default: return ''; } }; module.exports = function(obj, sep, eq, name) { sep = sep || '&'; eq = eq || '='; if (obj === null) { obj = undefined; } if (typeof obj === 'object') { return map(objectKeys(obj), function(k) { var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; if (isArray(obj[k])) { return map(obj[k], function(v) { return ks + encodeURIComponent(stringifyPrimitive(v)); }).join(sep); } else { return ks + encodeURIComponent(stringifyPrimitive(obj[k])); } }).join(sep); } if (!name) return ''; return encodeURIComponent(stringifyPrimitive(name)) + eq + encodeURIComponent(stringifyPrimitive(obj)); }; var isArray = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; function map (xs, f) { if (xs.map) return xs.map(f); var res = []; for (var i = 0; i < xs.length; i++) { res.push(f(xs[i], i)); } return res; } var objectKeys = Object.keys || function (obj) { var res = []; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); } return res; }; },{}],17:[function(require,module,exports){ 'use strict'; exports.decode = exports.parse = require('./decode'); exports.encode = exports.stringify = require('./encode'); },{"./decode":15,"./encode":16}],18:[function(require,module,exports){ // a duplex stream is just a stream that is both readable and writable. // Since JS doesn't have multiple prototypal inheritance, this class // prototypally inherits from Readable, and then parasitically from // Writable. 'use strict'; /*<replacement>*/ var objectKeys = Object.keys || function (obj) { var keys = []; for (var key in obj) { keys.push(key); }return keys; }; /*</replacement>*/ module.exports = Duplex; /*<replacement>*/ var processNextTick = require('process-nextick-args'); /*</replacement>*/ /*<replacement>*/ var util = require('core-util-is'); util.inherits = require('inherits'); /*</replacement>*/ var Readable = require('./_stream_readable'); var Writable = require('./_stream_writable'); util.inherits(Duplex, Readable); var keys = objectKeys(Writable.prototype); for (var v = 0; v < keys.length; v++) { var method = keys[v]; if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; } function Duplex(options) { if (!(this instanceof Duplex)) return new Duplex(options); Readable.call(this, options); Writable.call(this, options); if (options && options.readable === false) this.readable = false; if (options && options.writable === false) this.writable = false; this.allowHalfOpen = true; if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; this.once('end', onend); } // the no-half-open enforcer function onend() { // if we allow half-open state, or if the writable side ended, // then we're ok. if (this.allowHalfOpen || this._writableState.ended) return; // no more data can be written. // But allow more writes to happen in this tick. processNextTick(onEndNT, this); } function onEndNT(self) { self.end(); } function forEach(xs, f) { for (var i = 0, l = xs.length; i < l; i++) { f(xs[i], i); } } },{"./_stream_readable":20,"./_stream_writable":22,"core-util-is":6,"inherits":9,"process-nextick-args":12}],19:[function(require,module,exports){ // a passthrough stream. // basically just the most minimal sort of Transform stream. // Every written chunk gets output as-is. 'use strict'; module.exports = PassThrough; var Transform = require('./_stream_transform'); /*<replacement>*/ var util = require('core-util-is'); util.inherits = require('inherits'); /*</replacement>*/ util.inherits(PassThrough, Transform); function PassThrough(options) { if (!(this instanceof PassThrough)) return new PassThrough(options); Transform.call(this, options); } PassThrough.prototype._transform = function (chunk, encoding, cb) { cb(null, chunk); }; },{"./_stream_transform":21,"core-util-is":6,"inherits":9}],20:[function(require,module,exports){ (function (process){ 'use strict'; module.exports = Readable; /*<replacement>*/ var processNextTick = require('process-nextick-args'); /*</replacement>*/ /*<replacement>*/ var isArray = require('isarray'); /*</replacement>*/ /*<replacement>*/ var Duplex; /*</replacement>*/ Readable.ReadableState = ReadableState; /*<replacement>*/ var EE = require('events').EventEmitter; var EElistenerCount = function (emitter, type) { return emitter.listeners(type).length; }; /*</replacement>*/ /*<replacement>*/ var Stream; (function () { try { Stream = require('st' + 'ream'); } catch (_) {} finally { if (!Stream) Stream = require('events').EventEmitter; } })(); /*</replacement>*/ var Buffer = require('buffer').Buffer; /*<replacement>*/ var bufferShim = require('buffer-shims'); /*</replacement>*/ /*<replacement>*/ var util = require('core-util-is'); util.inherits = require('inherits'); /*</replacement>*/ /*<replacement>*/ var debugUtil = require('util'); var debug = void 0; if (debugUtil && debugUtil.debuglog) { debug = debugUtil.debuglog('stream'); } else { debug = function () {}; } /*</replacement>*/ var BufferList = require('./internal/streams/BufferList'); var StringDecoder; util.inherits(Readable, Stream); function prependListener(emitter, event, fn) { // Sadly this is not cacheable as some libraries bundle their own // event emitter implementation with them. if (typeof emitter.prependListener === 'function') { return emitter.prependListener(event, fn); } else { // This is a hack to make sure that our error handler is attached before any // userland ones. NEVER DO THIS. This is here only because this code needs // to continue to work with older versions of Node.js that do not include // the prependListener() method. The goal is to eventually remove this hack. if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; } } function ReadableState(options, stream) { Duplex = Duplex || require('./_stream_duplex'); options = options || {}; // object stream flag. Used to make read(n) ignore n and to // make all the buffer merging and length checks go away this.objectMode = !!options.objectMode; if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer // Note: 0 is a valid value, means "don't call _read preemptively ever" var hwm = options.highWaterMark; var defaultHwm = this.objectMode ? 16 : 16 * 1024; this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; // cast to ints. this.highWaterMark = ~ ~this.highWaterMark; // A linked list is used to store data chunks instead of an array because the // linked list can remove elements from the beginning faster than // array.shift() this.buffer = new BufferList(); this.length = 0; this.pipes = null; this.pipesCount = 0; this.flowing = null; this.ended = false; this.endEmitted = false; this.reading = false; // a flag to be able to tell if the onwrite cb is called immediately, // or on a later tick. We set this to true at first, because any // actions that shouldn't happen until "later" should generally also // not happen before the first write call. this.sync = true; // whenever we return null, then we set a flag to say // that we're awaiting a 'readable' event emission. this.needReadable = false; this.emittedReadable = false; this.readableListening = false; this.resumeScheduled = false; // Crypto is kind of old and crusty. Historically, its default string // encoding is 'binary' so we have to make this configurable. // Everything else in the universe uses 'utf8', though. this.defaultEncoding = options.defaultEncoding || 'utf8'; // when piping, we only care about 'readable' events that happen // after read()ing all the bytes and not getting any pushback. this.ranOut = false; // the number of writers that are awaiting a drain event in .pipe()s this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled this.readingMore = false; this.decoder = null; this.encoding = null; if (options.encoding) { if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; this.decoder = new StringDecoder(options.encoding); this.encoding = options.encoding; } } function Readable(options) { Duplex = Duplex || require('./_stream_duplex'); if (!(this instanceof Readable)) return new Readable(options); this._readableState = new ReadableState(options, this); // legacy this.readable = true; if (options && typeof options.read === 'function') this._read = options.read; Stream.call(this); } // Manually shove something into the read() buffer. // This returns true if the highWaterMark has not been hit yet, // similar to how Writable.write() returns true if you should // write() some more. Readable.prototype.push = function (chunk, encoding) { var state = this._readableState; if (!state.objectMode && typeof chunk === 'string') { encoding = encoding || state.defaultEncoding; if (encoding !== state.encoding) { chunk = bufferShim.from(chunk, encoding); encoding = ''; } } return readableAddChunk(this, state, chunk, encoding, false); }; // Unshift should *always* be something directly out of read() Readable.prototype.unshift = function (chunk) { var state = this._readableState; return readableAddChunk(this, state, chunk, '', true); }; Readable.prototype.isPaused = function () { return this._readableState.flowing === false; }; function readableAddChunk(stream, state, chunk, encoding, addToFront) { var er = chunkInvalid(state, chunk); if (er) { stream.emit('error', er); } else if (chunk === null) { state.reading = false; onEofChunk(stream, state); } else if (state.objectMode || chunk && chunk.length > 0) { if (state.ended && !addToFront) { var e = new Error('stream.push() after EOF'); stream.emit('error', e); } else if (state.endEmitted && addToFront) { var _e = new Error('stream.unshift() after end event'); stream.emit('error', _e); } else { var skipAdd; if (state.decoder && !addToFront && !encoding) { chunk = state.decoder.write(chunk); skipAdd = !state.objectMode && chunk.length === 0; } if (!addToFront) state.reading = false; // Don't add to the buffer if we've decoded to an empty string chunk and // we're not in object mode if (!skipAdd) { // if we want the data now, just emit it. if (state.flowing && state.length === 0 && !state.sync) { stream.emit('data', chunk); stream.read(0); } else { // update the buffer info. state.length += state.objectMode ? 1 : chunk.length; if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); if (state.needReadable) emitReadable(stream); } } maybeReadMore(stream, state); } } else if (!addToFront) { state.reading = false; } return needMoreData(state); } // if it's past the high water mark, we can push in some more. // Also, if we have no data yet, we can stand some // more bytes. This is to work around cases where hwm=0, // such as the repl. Also, if the push() triggered a // readable event, and the user called read(largeNumber) such that // needReadable was set, then we ought to push more, so that another // 'readable' event will be triggered. function needMoreData(state) { return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); } // backwards compatibility. Readable.prototype.setEncoding = function (enc) { if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; this._readableState.decoder = new StringDecoder(enc); this._readableState.encoding = enc; return this; }; // Don't raise the hwm > 8MB var MAX_HWM = 0x800000; function computeNewHighWaterMark(n) { if (n >= MAX_HWM) { n = MAX_HWM; } else { // Get the next highest power of 2 to prevent increasing hwm excessively in // tiny amounts n--; n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16; n++; } return n; } // This function is designed to be inlinable, so please take care when making // changes to the function body. function howMuchToRead(n, state) { if (n <= 0 || state.length === 0 && state.ended) return 0; if (state.objectMode) return 1; if (n !== n) { // Only flow one buffer at a time if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; } // If we're asking for more than the current hwm, then raise the hwm. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); if (n <= state.length) return n; // Don't have enough if (!state.ended) { state.needReadable = true; return 0; } return state.length; } // you can override either this method, or the async _read(n) below. Readable.prototype.read = function (n) { debug('read', n); n = parseInt(n, 10); var state = this._readableState; var nOrig = n; if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we // already have a bunch of data in the buffer, then just trigger // the 'readable' event and move on. if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { debug('read: emitReadable', state.length, state.ended); if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); return null; } n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. if (n === 0 && state.ended) { if (state.length === 0) endReadable(this); return null; } // All the actual chunk generation logic needs to be // *below* the call to _read. The reason is that in certain // synthetic stream cases, such as passthrough streams, _read // may be a completely synchronous operation which may change // the state of the read buffer, providing enough data when // before there was *not* enough. // // So, the steps are: // 1. Figure out what the state of things will be after we do // a read from the buffer. // // 2. If that resulting state will trigger a _read, then call _read. // Note that this may be asynchronous, or synchronous. Yes, it is // deeply ugly to write APIs this way, but that still doesn't mean // that the Readable class should behave improperly, as streams are // designed to be sync/async agnostic. // Take note if the _read call is sync or async (ie, if the read call // has returned yet), so that we know whether or not it's safe to emit // 'readable' etc. // // 3. Actually pull the requested chunks out of the buffer and return. // if we need a readable event, then we need to do some reading. var doRead = state.needReadable; debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some if (state.length === 0 || state.length - n < state.highWaterMark) { doRead = true; debug('length less than watermark', doRead); } // however, if we've ended, then there's no point, and if we're already // reading, then it's unnecessary. if (state.ended || state.reading) { doRead = false; debug('reading or ended', doRead); } else if (doRead) { debug('do read'); state.reading = true; state.sync = true; // if the length is currently zero, then we *need* a readable event. if (state.length === 0) state.needReadable = true; // call internal read method this._read(state.highWaterMark); state.sync = false; // If _read pushed data synchronously, then `reading` will be false, // and we need to re-evaluate how much data we can return to the user. if (!state.reading) n = howMuchToRead(nOrig, state); } var ret; if (n > 0) ret = fromList(n, state);else ret = null; if (ret === null) { state.needReadable = true; n = 0; } else { state.length -= n; } if (state.length === 0) { // If we have nothing in the buffer, then we want to know // as soon as we *do* get something into the buffer. if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. if (nOrig !== n && state.ended) endReadable(this); } if (ret !== null) this.emit('data', ret); return ret; }; function chunkInvalid(state, chunk) { var er = null; if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { er = new TypeError('Invalid non-string/buffer chunk'); } return er; } function onEofChunk(stream, state) { if (state.ended) return; if (state.decoder) { var chunk = state.decoder.end(); if (chunk && chunk.length) { state.buffer.push(chunk); state.length += state.objectMode ? 1 : chunk.length; } } state.ended = true; // emit 'readable' now to make sure it gets picked up. emitReadable(stream); } // Don't emit readable right away in sync mode, because this can trigger // another read() call => stack overflow. This way, it might trigger // a nextTick recursion warning, but that's not so bad. function emitReadable(stream) { var state = stream._readableState; state.needReadable = false; if (!state.emittedReadable) { debug('emitReadable', state.flowing); state.emittedReadable = true; if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream); } } function emitReadable_(stream) { debug('emit readable'); stream.emit('readable'); flow(stream); } // at this point, the user has presumably seen the 'readable' event, // and called read() to consume some data. that may have triggered // in turn another _read(n) call, in which case reading = true if // it's in progress. // However, if we're not ended, or reading, and the length < hwm, // then go ahead and try to read some more preemptively. function maybeReadMore(stream, state) { if (!state.readingMore) { state.readingMore = true; processNextTick(maybeReadMore_, stream, state); } } function maybeReadMore_(stream, state) { var len = state.length; while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { debug('maybeReadMore read 0'); stream.read(0); if (len === state.length) // didn't get any data, stop spinning. break;else len = state.length; } state.readingMore = false; } // abstract method. to be overridden in specific implementation classes. // call cb(er, data) where data is <= n in length. // for virtual (non-string, non-buffer) streams, "length" is somewhat // arbitrary, and perhaps not very meaningful. Readable.prototype._read = function (n) { this.emit('error', new Error('_read() is not implemented')); }; Readable.prototype.pipe = function (dest, pipeOpts) { var src = this; var state = this._readableState; switch (state.pipesCount) { case 0: state.pipes = dest; break; case 1: state.pipes = [state.pipes, dest]; break; default: state.pipes.push(dest); break; } state.pipesCount += 1; debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; var endFn = doEnd ? onend : cleanup; if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn); dest.on('unpipe', onunpipe); function onunpipe(readable) { debug('onunpipe'); if (readable === src) { cleanup(); } } function onend() { debug('onend'); dest.end(); } // when the dest drains, it reduces the awaitDrain counter // on the source. This would be more elegant with a .once() // handler in flow(), but adding and removing repeatedly is // too slow. var ondrain = pipeOnDrain(src); dest.on('drain', ondrain); var cleanedUp = false; function cleanup() { debug('cleanup'); // cleanup event handlers once the pipe is broken dest.removeListener('close', onclose); dest.removeListener('finish', onfinish); dest.removeListener('drain', ondrain); dest.removeListener('error', onerror); dest.removeListener('unpipe', onunpipe); src.removeListener('end', onend); src.removeListener('end', cleanup); src.removeListener('data', ondata); cleanedUp = true; // if the reader is waiting for a drain event from this // specific writer, then it would cause it to never start // flowing again. // So, if this is awaiting a drain, then we just call it now. // If we don't know, then assume that we are waiting for one. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); } // If the user pushes more data while we're writing to dest then we'll end up // in ondata again. However, we only want to increase awaitDrain once because // dest will only emit one 'drain' event for the multiple writes. // => Introduce a guard on increasing awaitDrain. var increasedAwaitDrain = false; src.on('data', ondata); function ondata(chunk) { debug('ondata'); increasedAwaitDrain = false; var ret = dest.write(chunk); if (false === ret && !increasedAwaitDrain) { // If the user unpiped during `dest.write()`, it is possible // to get stuck in a permanently paused state if that write // also returned false. // => Check whether `dest` is still a piping destination. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { debug('false write response, pause', src._readableState.awaitDrain); src._readableState.awaitDrain++; increasedAwaitDrain = true; } src.pause(); } } // if the dest has an error, then stop piping into it. // however, don't suppress the throwing behavior for this. function onerror(er) { debug('onerror', er); unpipe(); dest.removeListener('error', onerror); if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); } // Make sure our error handler is attached before userland ones. prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. function onclose() { dest.removeListener('finish', onfinish); unpipe(); } dest.once('close', onclose); function onfinish() { debug('onfinish'); dest.removeListener('close', onclose); unpipe(); } dest.once('finish', onfinish); function unpipe() { debug('unpipe'); src.unpipe(dest); } // tell the dest that it's being piped to dest.emit('pipe', src); // start the flow if it hasn't been started already. if (!state.flowing) { debug('pipe resume'); src.resume(); } return dest; }; function pipeOnDrain(src) { return function () { var state = src._readableState; debug('pipeOnDrain', state.awaitDrain); if (state.awaitDrain) state.awaitDrain--; if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { state.flowing = true; flow(src); } }; } Readable.prototype.unpipe = function (dest) { var state = this._readableState; // if we're not piping anywhere, then do nothing. if (state.pipesCount === 0) return this; // just one destination. most common case. if (state.pipesCount === 1) { // passed in one, but it's not the right one. if (dest && dest !== state.pipes) return this; if (!dest) dest = state.pipes; // got a match. state.pipes = null; state.pipesCount = 0; state.flowing = false; if (dest) dest.emit('unpipe', this); return this; } // slow case. multiple pipe destinations. if (!dest) { // remove all. var dests = state.pipes; var len = state.pipesCount; state.pipes = null; state.pipesCount = 0; state.flowing = false; for (var i = 0; i < len; i++) { dests[i].emit('unpipe', this); }return this; } // try to find the right one. var index = indexOf(state.pipes, dest); if (index === -1) return this; state.pipes.splice(index, 1); state.pipesCount -= 1; if (state.pipesCount === 1) state.pipes = state.pipes[0]; dest.emit('unpipe', this); return this; }; // set up data events if they are asked for // Ensure readable listeners eventually get something Readable.prototype.on = function (ev, fn) { var res = Stream.prototype.on.call(this, ev, fn); if (ev === 'data') { // Start flowing on next tick if stream isn't explicitly paused if (this._readableState.flowing !== false) this.resume(); } else if (ev === 'readable') { var state = this._readableState; if (!state.endEmitted && !state.readableListening) { state.readableListening = state.needReadable = true; state.emittedReadable = false; if (!state.reading) { processNextTick(nReadingNextTick, this); } else if (state.length) { emitReadable(this, state); } } } return res; }; Readable.prototype.addListener = Readable.prototype.on; function nReadingNextTick(self) { debug('readable nexttick read 0'); self.read(0); } // pause() and resume() are remnants of the legacy readable stream API // If the user uses them, then switch into old mode. Readable.prototype.resume = function () { var state = this._readableState; if (!state.flowing) { debug('resume'); state.flowing = true; resume(this, state); } return this; }; function resume(stream, state) { if (!state.resumeScheduled) { state.resumeScheduled = true; processNextTick(resume_, stream, state); } } function resume_(stream, state) { if (!state.reading) { debug('resume read 0'); stream.read(0); } state.resumeScheduled = false; state.awaitDrain = 0; stream.emit('resume'); flow(stream); if (state.flowing && !state.reading) stream.read(0); } Readable.prototype.pause = function () { debug('call pause flowing=%j', this._readableState.flowing); if (false !== this._readableState.flowing) { debug('pause'); this._readableState.flowing = false; this.emit('pause'); } return this; }; function flow(stream) { var state = stream._readableState; debug('flow', state.flowing); while (state.flowing && stream.read() !== null) {} } // wrap an old-style stream as the async data source. // This is *not* part of the readable stream interface. // It is an ugly unfortunate mess of history. Readable.prototype.wrap = function (stream) { var state = this._readableState; var paused = false; var self = this; stream.on('end', function () { debug('wrapped end'); if (state.decoder && !state.ended) { var chunk = state.decoder.end(); if (chunk && chunk.length) self.push(chunk); } self.push(null); }); stream.on('data', function (chunk) { debug('wrapped data'); if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; var ret = self.push(chunk); if (!ret) { paused = true; stream.pause(); } }); // proxy all the other methods. // important when wrapping filters and duplexes. for (var i in stream) { if (this[i] === undefined && typeof stream[i] === 'function') { this[i] = function (method) { return function () { return stream[method].apply(stream, arguments); }; }(i); } } // proxy certain important events. var events = ['error', 'close', 'destroy', 'pause', 'resume']; forEach(events, function (ev) { stream.on(ev, self.emit.bind(self, ev)); }); // when we try to consume some more bytes, simply unpause the // underlying stream. self._read = function (n) { debug('wrapped _read', n); if (paused) { paused = false; stream.resume(); } }; return self; }; // exposed for testing purposes only. Readable._fromList = fromList; // Pluck off n bytes from an array of buffers. // Length is the combined lengths of all the buffers in the list. // This function is designed to be inlinable, so please take care when making // changes to the function body. function fromList(n, state) { // nothing buffered if (state.length === 0) return null; var ret; if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { // read it all, truncate the list if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); state.buffer.clear(); } else { // read part of list ret = fromListPartial(n, state.buffer, state.decoder); } return ret; } // Extracts only enough buffered data to satisfy the amount requested. // This function is designed to be inlinable, so please take care when making // changes to the function body. function fromListPartial(n, list, hasStrings) { var ret; if (n < list.head.data.length) { // slice is the same for buffers and strings ret = list.head.data.slice(0, n); list.head.data = list.head.data.slice(n); } else if (n === list.head.data.length) { // first chunk is a perfect match ret = list.shift(); } else { // result spans more than one buffer ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); } return ret; } // Copies a specified amount of characters from the list of buffered data // chunks. // This function is designed to be inlinable, so please take care when making // changes to the function body. function copyFromBufferString(n, list) { var p = list.head; var c = 1; var ret = p.data; n -= ret.length; while (p = p.next) { var str = p.data; var nb = n > str.length ? str.length : n; if (nb === str.length) ret += str;else ret += str.slice(0, n); n -= nb; if (n === 0) { if (nb === str.length) { ++c; if (p.next) list.head = p.next;else list.head = list.tail = null; } else { list.head = p; p.data = str.slice(nb); } break; } ++c; } list.length -= c; return ret; } // Copies a specified amount of bytes from the list of buffered data chunks. // This function is designed to be inlinable, so please take care when making // changes to the function body. function copyFromBuffer(n, list) { var ret = bufferShim.allocUnsafe(n); var p = list.head; var c = 1; p.data.copy(ret); n -= p.data.length; while (p = p.next) { var buf = p.data; var nb = n > buf.length ? buf.length : n; buf.copy(ret, ret.length - n, 0, nb); n -= nb; if (n === 0) { if (nb === buf.length) { ++c; if (p.next) list.head = p.next;else list.head = list.tail = null; } else { list.head = p; p.data = buf.slice(nb); } break; } ++c; } list.length -= c; return ret; } function endReadable(stream) { var state = stream._readableState; // If we get here before consuming all the bytes, then that is a // bug in node. Should never happen. if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); if (!state.endEmitted) { state.ended = true; processNextTick(endReadableNT, state, stream); } } function endReadableNT(state, stream) { // Check that we didn't get one last unshift. if (!state.endEmitted && state.length === 0) { state.endEmitted = true; stream.readable = false; stream.emit('end'); } } function forEach(xs, f) { for (var i = 0, l = xs.length; i < l; i++) { f(xs[i], i); } } function indexOf(xs, x) { for (var i = 0, l = xs.length; i < l; i++) { if (xs[i] === x) return i; } return -1; } }).call(this,require('_process')) },{"./_stream_duplex":18,"./internal/streams/BufferList":23,"_process":13,"buffer":4,"buffer-shims":3,"core-util-is":6,"events":7,"inherits":9,"isarray":11,"process-nextick-args":12,"string_decoder/":29,"util":2}],21:[function(require,module,exports){ // a transform stream is a readable/writable stream where you do // something with the data. Sometimes it's called a "filter", // but that's not a great name for it, since that implies a thing where // some bits pass through, and others are simply ignored. (That would // be a valid example of a transform, of course.) // // While the output is causally related to the input, it's not a // necessarily symmetric or synchronous transformation. For example, // a zlib stream might take multiple plain-text writes(), and then // emit a single compressed chunk some time in the future. // // Here's how this works: // // The Transform stream has all the aspects of the readable and writable // stream classes. When you write(chunk), that calls _write(chunk,cb) // internally, and returns false if there's a lot of pending writes // buffered up. When you call read(), that calls _read(n) until // there's enough pending readable data buffered up. // // In a transform stream, the written data is placed in a buffer. When // _read(n) is called, it transforms the queued up data, calling the // buffered _write cb's as it consumes chunks. If consuming a single // written chunk would result in multiple output chunks, then the first // outputted bit calls the readcb, and subsequent chunks just go into // the read buffer, and will cause it to emit 'readable' if necessary. // // This way, back-pressure is actually determined by the reading side, // since _read has to be called to start processing a new chunk. However, // a pathological inflate type of transform can cause excessive buffering // here. For example, imagine a stream where every byte of input is // interpreted as an integer from 0-255, and then results in that many // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in // 1kb of data being output. In this case, you could write a very small // amount of input, and end up with a very large amount of output. In // such a pathological inflating mechanism, there'd be no way to tell // the system to stop doing the transform. A single 4MB write could // cause the system to run out of memory. // // However, even in such a pathological case, only a single written chunk // would be consumed, and then the rest would wait (un-transformed) until // the results of the previous transformed chunk were consumed. 'use strict'; module.exports = Transform; var Duplex = require('./_stream_duplex'); /*<replacement>*/ var util = require('core-util-is'); util.inherits = require('inherits'); /*</replacement>*/ util.inherits(Transform, Duplex); function TransformState(stream) { this.afterTransform = function (er, data) { return afterTransform(stream, er, data); }; this.needTransform = false; this.transforming = false; this.writecb = null; this.writechunk = null; this.writeencoding = null; } function afterTransform(stream, er, data) { var ts = stream._transformState; ts.transforming = false; var cb = ts.writecb; if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); ts.writechunk = null; ts.writecb = null; if (data !== null && data !== undefined) stream.push(data); cb(er); var rs = stream._readableState; rs.reading = false; if (rs.needReadable || rs.length < rs.highWaterMark) { stream._read(rs.highWaterMark); } } function Transform(options) { if (!(this instanceof Transform)) return new Transform(options); Duplex.call(this, options); this._transformState = new TransformState(this); var stream = this; // start out asking for a readable event once data is transformed. this._readableState.needReadable = true; // we have implemented the _read method, and done the other things // that Readable wants before the first _read call, so unset the // sync guard flag. this._readableState.sync = false; if (options) { if (typeof options.transform === 'function') this._transform = options.transform; if (typeof options.flush === 'function') this._flush = options.flush; } // When the writable side finishes, then flush out anything remaining. this.once('prefinish', function () { if (typeof this._flush === 'function') this._flush(function (er, data) { done(stream, er, data); });else done(stream); }); } Transform.prototype.push = function (chunk, encoding) { this._transformState.needTransform = false; return Duplex.prototype.push.call(this, chunk, encoding); }; // This is the part where you do stuff! // override this function in implementation classes. // 'chunk' is an input chunk. // // Call `push(newChunk)` to pass along transformed output // to the readable side. You may call 'push' zero or more times. // // Call `cb(err)` when you are done with this chunk. If you pass // an error, then that'll put the hurt on the whole operation. If you // never call cb(), then you'll never get another chunk. Transform.prototype._transform = function (chunk, encoding, cb) { throw new Error('_transform() is not implemented'); }; Transform.prototype._write = function (chunk, encoding, cb) { var ts = this._transformState; ts.writecb = cb; ts.writechunk = chunk; ts.writeencoding = encoding; if (!ts.transforming) { var rs = this._readableState; if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); } }; // Doesn't matter what the args are here. // _transform does all the work. // That we got here means that the readable side wants more data. Transform.prototype._read = function (n) { var ts = this._transformState; if (ts.writechunk !== null && ts.writecb && !ts.transforming) { ts.transforming = true; this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); } else { // mark that we need a transform, so that any data that comes in // will get processed, now that we've asked for it. ts.needTransform = true; } }; function done(stream, er, data) { if (er) return stream.emit('error', er); if (data !== null && data !== undefined) stream.push(data); // if there's nothing in the write buffer, then that means // that nothing more will ever be provided var ws = stream._writableState; var ts = stream._transformState; if (ws.length) throw new Error('Calling transform done when ws.length != 0'); if (ts.transforming) throw new Error('Calling transform done when still transforming'); return stream.push(null); } },{"./_stream_duplex":18,"core-util-is":6,"inherits":9}],22:[function(require,module,exports){ (function (process){ // A bit simpler than readable streams. // Implement an async ._write(chunk, encoding, cb), and it'll handle all // the drain event emission and buffering. 'use strict'; module.exports = Writable; /*<replacement>*/ var processNextTick = require('process-nextick-args'); /*</replacement>*/ /*<replacement>*/ var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick; /*</replacement>*/ /*<replacement>*/ var Duplex; /*</replacement>*/ Writable.WritableState = WritableState; /*<replacement>*/ var util = require('core-util-is'); util.inherits = require('inherits'); /*</replacement>*/ /*<replacement>*/ var internalUtil = { deprecate: require('util-deprecate') }; /*</replacement>*/ /*<replacement>*/ var Stream; (function () { try { Stream = require('st' + 'ream'); } catch (_) {} finally { if (!Stream) Stream = require('events').EventEmitter; } })(); /*</replacement>*/ var Buffer = require('buffer').Buffer; /*<replacement>*/ var bufferShim = require('buffer-shims'); /*</replacement>*/ util.inherits(Writable, Stream); function nop() {} function WriteReq(chunk, encoding, cb) { this.chunk = chunk; this.encoding = encoding; this.callback = cb; this.next = null; } function WritableState(options, stream) { Duplex = Duplex || require('./_stream_duplex'); options = options || {}; // object stream flag to indicate whether or not this stream // contains buffers or objects. this.objectMode = !!options.objectMode; if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false // Note: 0 is a valid value, means that we always return false if // the entire buffer is not flushed immediately on write() var hwm = options.highWaterMark; var defaultHwm = this.objectMode ? 16 : 16 * 1024; this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; // cast to ints. this.highWaterMark = ~ ~this.highWaterMark; // drain event flag. this.needDrain = false; // at the start of calling end() this.ending = false; // when end() has been called, and returned this.ended = false; // when 'finish' is emitted this.finished = false; // should we decode strings into buffers before passing to _write? // this is here so that some node-core streams can optimize string // handling at a lower level. var noDecode = options.decodeStrings === false; this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string // encoding is 'binary' so we have to make this configurable. // Everything else in the universe uses 'utf8', though. this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement // of how much we're waiting to get pushed to some underlying // socket or file. this.length = 0; // a flag to see when we're in the middle of a write. this.writing = false; // when true all writes will be buffered until .uncork() call this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, // or on a later tick. We set this to true at first, because any // actions that shouldn't happen until "later" should generally also // not happen before the first write call. this.sync = true; // a flag to know if we're processing previously buffered items, which // may call the _write() callback in the same tick, so that we don't // end up in an overlapped onwrite situation. this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) this.onwrite = function (er) { onwrite(stream, er); }; // the callback that the user supplies to write(chunk,encoding,cb) this.writecb = null; // the amount that is being written when _write is called. this.writelen = 0; this.bufferedRequest = null; this.lastBufferedRequest = null; // number of pending user-supplied write callbacks // this must be 0 before 'finish' can be emitted this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs // This is relevant for synchronous Transform streams this.prefinished = false; // True if the error was already emitted and should not be thrown again this.errorEmitted = false; // count buffered requests this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always // one allocated and free to use, and we maintain at most two this.corkedRequestsFree = new CorkedRequest(this); } WritableState.prototype.getBuffer = function getBuffer() { var current = this.bufferedRequest; var out = []; while (current) { out.push(current); current = current.next; } return out; }; (function () { try { Object.defineProperty(WritableState.prototype, 'buffer', { get: internalUtil.deprecate(function () { return this.getBuffer(); }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') }); } catch (_) {} })(); // Test _writableState for inheritance to account for Duplex streams, // whose prototype chain only points to Readable. var realHasInstance; if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { realHasInstance = Function.prototype[Symbol.hasInstance]; Object.defineProperty(Writable, Symbol.hasInstance, { value: function (object) { if (realHasInstance.call(this, object)) return true; return object && object._writableState instanceof WritableState; } }); } else { realHasInstance = function (object) { return object instanceof this; }; } function Writable(options) { Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too. // `realHasInstance` is necessary because using plain `instanceof` // would return false, as no `_writableState` property is attached. // Trying to use the custom `instanceof` for Writable here will also break the // Node.js LazyTransform implementation, which has a non-trivial getter for // `_writableState` that would lead to infinite recursion. if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { return new Writable(options); } this._writableState = new WritableState(options, this); // legacy. this.writable = true; if (options) { if (typeof options.write === 'function') this._write = options.write; if (typeof options.writev === 'function') this._writev = options.writev; } Stream.call(this); } // Otherwise people can pipe Writable streams, which is just wrong. Writable.prototype.pipe = function () { this.emit('error', new Error('Cannot pipe, not readable')); }; function writeAfterEnd(stream, cb) { var er = new Error('write after end'); // TODO: defer error events consistently everywhere, not just the cb stream.emit('error', er); processNextTick(cb, er); } // If we get something that is not a buffer, string, null, or undefined, // and we're not in objectMode, then that's an error. // Otherwise stream chunks are all considered to be of length=1, and the // watermarks determine how many objects to keep in the buffer, rather than // how many bytes or characters. function validChunk(stream, state, chunk, cb) { var valid = true; var er = false; // Always throw error if a null is written // if we are not in object mode then throw // if it is not a buffer, string, or undefined. if (chunk === null) { er = new TypeError('May not write null values to stream'); } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { er = new TypeError('Invalid non-string/buffer chunk'); } if (er) { stream.emit('error', er); processNextTick(cb, er); valid = false; } return valid; } Writable.prototype.write = function (chunk, encoding, cb) { var state = this._writableState; var ret = false; if (typeof encoding === 'function') { cb = encoding; encoding = null; } if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; if (typeof cb !== 'function') cb = nop; if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { state.pendingcb++; ret = writeOrBuffer(this, state, chunk, encoding, cb); } return ret; }; Writable.prototype.cork = function () { var state = this._writableState; state.corked++; }; Writable.prototype.uncork = function () { var state = this._writableState; if (state.corked) { state.corked--; if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); } }; Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { // node::ParseEncoding() requires lower case. if (typeof encoding === 'string') encoding = encoding.toLowerCase(); if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); this._writableState.defaultEncoding = encoding; return this; }; function decodeChunk(state, chunk, encoding) { if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { chunk = bufferShim.from(chunk, encoding); } return chunk; } // if we're already writing something, then just put this // in the queue, and wait our turn. Otherwise, call _write // If we return false, then we need a drain event, so set that flag. function writeOrBuffer(stream, state, chunk, encoding, cb) { chunk = decodeChunk(state, chunk, encoding); if (Buffer.isBuffer(chunk)) encoding = 'buffer'; var len = state.objectMode ? 1 : chunk.length; state.length += len; var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. if (!ret) state.needDrain = true; if (state.writing || state.corked) { var last = state.lastBufferedRequest; state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); if (last) { last.next = state.lastBufferedRequest; } else { state.bufferedRequest = state.lastBufferedRequest; } state.bufferedRequestCount += 1; } else { doWrite(stream, state, false, len, chunk, encoding, cb); } return ret; } function doWrite(stream, state, writev, len, chunk, encoding, cb) { state.writelen = len; state.writecb = cb; state.writing = true; state.sync = true; if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); state.sync = false; } function onwriteError(stream, state, sync, er, cb) { --state.pendingcb; if (sync) processNextTick(cb, er);else cb(er); stream._writableState.errorEmitted = true; stream.emit('error', er); } function onwriteStateUpdate(state) { state.writing = false; state.writecb = null; state.length -= state.writelen; state.writelen = 0; } function onwrite(stream, er) { var state = stream._writableState; var sync = state.sync; var cb = state.writecb; onwriteStateUpdate(state); if (er) onwriteError(stream, state, sync, er, cb);else { // Check if we're actually ready to finish, but don't emit yet var finished = needFinish(state); if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { clearBuffer(stream, state); } if (sync) { /*<replacement>*/ asyncWrite(afterWrite, stream, state, finished, cb); /*</replacement>*/ } else { afterWrite(stream, state, finished, cb); } } } function afterWrite(stream, state, finished, cb) { if (!finished) onwriteDrain(stream, state); state.pendingcb--; cb(); finishMaybe(stream, state); } // Must force callback to be called on nextTick, so that we don't // emit 'drain' before the write() consumer gets the 'false' return // value, and has a chance to attach a 'drain' listener. function onwriteDrain(stream, state) { if (state.length === 0 && state.needDrain) { state.needDrain = false; stream.emit('drain'); } } // if there's something in the buffer waiting, then process it function clearBuffer(stream, state) { state.bufferProcessing = true; var entry = state.bufferedRequest; if (stream._writev && entry && entry.next) { // Fast case, write everything using _writev() var l = state.bufferedRequestCount; var buffer = new Array(l); var holder = state.corkedRequestsFree; holder.entry = entry; var count = 0; while (entry) { buffer[count] = entry; entry = entry.next; count += 1; } doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time // as the hot path ends with doWrite state.pendingcb++; state.lastBufferedRequest = null; if (holder.next) { state.corkedRequestsFree = holder.next; holder.next = null; } else { state.corkedRequestsFree = new CorkedRequest(state); } } else { // Slow case, write chunks one-by-one while (entry) { var chunk = entry.chunk; var encoding = entry.encoding; var cb = entry.callback; var len = state.objectMode ? 1 : chunk.length; doWrite(stream, state, false, len, chunk, encoding, cb); entry = entry.next; // if we didn't call the onwrite immediately, then // it means that we need to wait until it does. // also, that means that the chunk and cb are currently // being processed, so move the buffer counter past them. if (state.writing) { break; } } if (entry === null) state.lastBufferedRequest = null; } state.bufferedRequestCount = 0; state.bufferedRequest = entry; state.bufferProcessing = false; } Writable.prototype._write = function (chunk, encoding, cb) { cb(new Error('_write() is not implemented')); }; Writable.prototype._writev = null; Writable.prototype.end = function (chunk, encoding, cb) { var state = this._writableState; if (typeof chunk === 'function') { cb = chunk; chunk = null; encoding = null; } else if (typeof encoding === 'function') { cb = encoding; encoding = null; } if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks if (state.corked) { state.corked = 1; this.uncork(); } // ignore unnecessary end() calls. if (!state.ending && !state.finished) endWritable(this, state, cb); }; function needFinish(state) { return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; } function prefinish(stream, state) { if (!state.prefinished) { state.prefinished = true; stream.emit('prefinish'); } } function finishMaybe(stream, state) { var need = needFinish(state); if (need) { if (state.pendingcb === 0) { prefinish(stream, state); state.finished = true; stream.emit('finish'); } else { prefinish(stream, state); } } return need; } function endWritable(stream, state, cb) { state.ending = true; finishMaybe(stream, state); if (cb) { if (state.finished) processNextTick(cb);else stream.once('finish', cb); } state.ended = true; stream.writable = false; } // It seems a linked list but it is not // there will be only 2 of these for each stream function CorkedRequest(state) { var _this = this; this.next = null; this.entry = null; this.finish = function (err) { var entry = _this.entry; _this.entry = null; while (entry) { var cb = entry.callback; state.pendingcb--; cb(err); entry = entry.next; } if (state.corkedRequestsFree) { state.corkedRequestsFree.next = _this; } else { state.corkedRequestsFree = _this; } }; } }).call(this,require('_process')) },{"./_stream_duplex":18,"_process":13,"buffer":4,"buffer-shims":3,"core-util-is":6,"events":7,"inherits":9,"process-nextick-args":12,"util-deprecate":33}],23:[function(require,module,exports){ 'use strict'; var Buffer = require('buffer').Buffer; /*<replacement>*/ var bufferShim = require('buffer-shims'); /*</replacement>*/ module.exports = BufferList; function BufferList() { this.head = null; this.tail = null; this.length = 0; } BufferList.prototype.push = function (v) { var entry = { data: v, next: null }; if (this.length > 0) this.tail.next = entry;else this.head = entry; this.tail = entry; ++this.length; }; BufferList.prototype.unshift = function (v) { var entry = { data: v, next: this.head }; if (this.length === 0) this.tail = entry; this.head = entry; ++this.length; }; BufferList.prototype.shift = function () { if (this.length === 0) return; var ret = this.head.data; if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; --this.length; return ret; }; BufferList.prototype.clear = function () { this.head = this.tail = null; this.length = 0; }; BufferList.prototype.join = function (s) { if (this.length === 0) return ''; var p = this.head; var ret = '' + p.data; while (p = p.next) { ret += s + p.data; }return ret; }; BufferList.prototype.concat = function (n) { if (this.length === 0) return bufferShim.alloc(0); if (this.length === 1) return this.head.data; var ret = bufferShim.allocUnsafe(n >>> 0); var p = this.head; var i = 0; while (p) { p.data.copy(ret, i); i += p.data.length; p = p.next; } return ret; }; },{"buffer":4,"buffer-shims":3}],24:[function(require,module,exports){ (function (process){ var Stream = (function (){ try { return require('st' + 'ream'); // hack to fix a circular dependency issue when used with browserify } catch(_){} }()); exports = module.exports = require('./lib/_stream_readable.js'); exports.Stream = Stream || exports; exports.Readable = exports; exports.Writable = require('./lib/_stream_writable.js'); exports.Duplex = require('./lib/_stream_duplex.js'); exports.Transform = require('./lib/_stream_transform.js'); exports.PassThrough = require('./lib/_stream_passthrough.js'); if (!process.browser && process.env.READABLE_STREAM === 'disable' && Stream) { module.exports = Stream; } }).call(this,require('_process')) },{"./lib/_stream_duplex.js":18,"./lib/_stream_passthrough.js":19,"./lib/_stream_readable.js":20,"./lib/_stream_transform.js":21,"./lib/_stream_writable.js":22,"_process":13}],25:[function(require,module,exports){ (function (global){ var ClientRequest = require('./lib/request') var extend = require('xtend') var statusCodes = require('builtin-status-codes') var url = require('url') var http = exports http.request = function (opts, cb) { if (typeof opts === 'string') opts = url.parse(opts) else opts = extend(opts) // Normally, the page is loaded from http or https, so not specifying a protocol // will result in a (valid) protocol-relative url. However, this won't work if // the protocol is something else, like 'file:' var defaultProtocol = global.location.protocol.search(/^https?:$/) === -1 ? 'http:' : '' var protocol = opts.protocol || defaultProtocol var host = opts.hostname || opts.host var port = opts.port var path = opts.path || '/' // Necessary for IPv6 addresses if (host && host.indexOf(':') !== -1) host = '[' + host + ']' // This may be a relative url. The browser should always be able to interpret it correctly. opts.url = (host ? (protocol + '//' + host) : '') + (port ? ':' + port : '') + path opts.method = (opts.method || 'GET').toUpperCase() opts.headers = opts.headers || {} // Also valid opts.auth, opts.mode var req = new ClientRequest(opts) if (cb) req.on('response', cb) return req } http.get = function get (opts, cb) { var req = http.request(opts, cb) req.end() return req } http.Agent = function () {} http.Agent.defaultMaxSockets = 4 http.STATUS_CODES = statusCodes http.METHODS = [ 'CHECKOUT', 'CONNECT', 'COPY', 'DELETE', 'GET', 'HEAD', 'LOCK', 'M-SEARCH', 'MERGE', 'MKACTIVITY', 'MKCOL', 'MOVE', 'NOTIFY', 'OPTIONS', 'PATCH', 'POST', 'PROPFIND', 'PROPPATCH', 'PURGE', 'PUT', 'REPORT', 'SEARCH', 'SUBSCRIBE', 'TRACE', 'UNLOCK', 'UNSUBSCRIBE' ] }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./lib/request":27,"builtin-status-codes":5,"url":31,"xtend":34}],26:[function(require,module,exports){ (function (global){ exports.fetch = isFunction(global.fetch) && isFunction(global.ReadableStream) exports.blobConstructor = false try { new Blob([new ArrayBuffer(1)]) exports.blobConstructor = true } catch (e) {} // The xhr request to example.com may violate some restrictive CSP configurations, // so if we're running in a browser that supports `fetch`, avoid calling getXHR() // and assume support for certain features below. var xhr function getXHR () { // Cache the xhr value if (xhr !== undefined) return xhr if (global.XMLHttpRequest) { xhr = new global.XMLHttpRequest() // If XDomainRequest is available (ie only, where xhr might not work // cross domain), use the page location. Otherwise use example.com // Note: this doesn't actually make an http request. try { xhr.open('GET', global.XDomainRequest ? '/' : 'https://example.com') } catch(e) { xhr = null } } else { // Service workers don't have XHR xhr = null } return xhr } function checkTypeSupport (type) { var xhr = getXHR() if (!xhr) return false try { xhr.responseType = type return xhr.responseType === type } catch (e) {} return false } // For some strange reason, Safari 7.0 reports typeof global.ArrayBuffer === 'object'. // Safari 7.1 appears to have fixed this bug. var haveArrayBuffer = typeof global.ArrayBuffer !== 'undefined' var haveSlice = haveArrayBuffer && isFunction(global.ArrayBuffer.prototype.slice) // If fetch is supported, then arraybuffer will be supported too. Skip calling // checkTypeSupport(), since that calls getXHR(). exports.arraybuffer = exports.fetch || (haveArrayBuffer && checkTypeSupport('arraybuffer')) // These next two tests unavoidably show warnings in Chrome. Since fetch will always // be used if it's available, just return false for these to avoid the warnings. exports.msstream = !exports.fetch && haveSlice && checkTypeSupport('ms-stream') exports.mozchunkedarraybuffer = !exports.fetch && haveArrayBuffer && checkTypeSupport('moz-chunked-arraybuffer') // If fetch is supported, then overrideMimeType will be supported too. Skip calling // getXHR(). exports.overrideMimeType = exports.fetch || (getXHR() ? isFunction(getXHR().overrideMimeType) : false) exports.vbArray = isFunction(global.VBArray) function isFunction (value) { return typeof value === 'function' } xhr = null // Help gc }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],27:[function(require,module,exports){ (function (process,global,Buffer){ var capability = require('./capability') var inherits = require('inherits') var response = require('./response') var stream = require('readable-stream') var toArrayBuffer = require('to-arraybuffer') var IncomingMessage = response.IncomingMessage var rStates = response.readyStates function decideMode (preferBinary, useFetch) { if (capability.fetch && useFetch) { return 'fetch' } else if (capability.mozchunkedarraybuffer) { return 'moz-chunked-arraybuffer' } else if (capability.msstream) { return 'ms-stream' } else if (capability.arraybuffer && preferBinary) { return 'arraybuffer' } else if (capability.vbArray && preferBinary) { return 'text:vbarray' } else { return 'text' } } var ClientRequest = module.exports = function (opts) { var self = this stream.Writable.call(self) self._opts = opts self._body = [] self._headers = {} if (opts.auth) self.setHeader('Authorization', 'Basic ' + new Buffer(opts.auth).toString('base64')) Object.keys(opts.headers).forEach(function (name) { self.setHeader(name, opts.headers[name]) }) var preferBinary var useFetch = true if (opts.mode === 'disable-fetch' || 'timeout' in opts) { // If the use of XHR should be preferred and includes preserving the 'content-type' header. // Force XHR to be used since the Fetch API does not yet support timeouts. useFetch = false preferBinary = true } else if (opts.mode === 'prefer-streaming') { // If streaming is a high priority but binary compatibility and // the accuracy of the 'content-type' header aren't preferBinary = false } else if (opts.mode === 'allow-wrong-content-type') { // If streaming is more important than preserving the 'content-type' header preferBinary = !capability.overrideMimeType } else if (!opts.mode || opts.mode === 'default' || opts.mode === 'prefer-fast') { // Use binary if text streaming may corrupt data or the content-type header, or for speed preferBinary = true } else { throw new Error('Invalid value for opts.mode') } self._mode = decideMode(preferBinary, useFetch) self.on('finish', function () { self._onFinish() }) } inherits(ClientRequest, stream.Writable) ClientRequest.prototype.setHeader = function (name, value) { var self = this var lowerName = name.toLowerCase() // This check is not necessary, but it prevents warnings from browsers about setting unsafe // headers. To be honest I'm not entirely sure hiding these warnings is a good thing, but // http-browserify did it, so I will too. if (unsafeHeaders.indexOf(lowerName) !== -1) return self._headers[lowerName] = { name: name, value: value } } ClientRequest.prototype.getHeader = function (name) { var self = this return self._headers[name.toLowerCase()].value } ClientRequest.prototype.removeHeader = function (name) { var self = this delete self._headers[name.toLowerCase()] } ClientRequest.prototype._onFinish = function () { var self = this if (self._destroyed) return var opts = self._opts var headersObj = self._headers var body if (opts.method === 'POST' || opts.method === 'PUT' || opts.method === 'PATCH' || opts.method === 'MERGE') { if (capability.blobConstructor) { body = new global.Blob(self._body.map(function (buffer) { return toArrayBuffer(buffer) }), { type: (headersObj['content-type'] || {}).value || '' }) } else { // get utf8 string body = Buffer.concat(self._body).toString() } } if (self._mode === 'fetch') { var headers = Object.keys(headersObj).map(function (name) { return [headersObj[name].name, headersObj[name].value] }) global.fetch(self._opts.url, { method: self._opts.method, headers: headers, body: body, mode: 'cors', credentials: opts.withCredentials ? 'include' : 'same-origin' }).then(function (response) { self._fetchResponse = response self._connect() }, function (reason) { self.emit('error', reason) }) } else { var xhr = self._xhr = new global.XMLHttpRequest() try { xhr.open(self._opts.method, self._opts.url, true) } catch (err) { process.nextTick(function () { self.emit('error', err) }) return } // Can't set responseType on really old browsers if ('responseType' in xhr) xhr.responseType = self._mode.split(':')[0] if ('withCredentials' in xhr) xhr.withCredentials = !!opts.withCredentials if (self._mode === 'text' && 'overrideMimeType' in xhr) xhr.overrideMimeType('text/plain; charset=x-user-defined') if ('timeout' in opts) { xhr.timeout = opts.timeout xhr.ontimeout = function () { self.emit('timeout') } } Object.keys(headersObj).forEach(function (name) { xhr.setRequestHeader(headersObj[name].name, headersObj[name].value) }) self._response = null xhr.onreadystatechange = function () { switch (xhr.readyState) { case rStates.LOADING: case rStates.DONE: self._onXHRProgress() break } } // Necessary for streaming in Firefox, since xhr.response is ONLY defined // in onprogress, not in onreadystatechange with xhr.readyState = 3 if (self._mode === 'moz-chunked-arraybuffer') { xhr.onprogress = function () { self._onXHRProgress() } } xhr.onerror = function () { if (self._destroyed) return self.emit('error', new Error('XHR error')) } try { xhr.send(body) } catch (err) { process.nextTick(function () { self.emit('error', err) }) return } } } /** * Checks if xhr.status is readable and non-zero, indicating no error. * Even though the spec says it should be available in readyState 3, * accessing it throws an exception in IE8 */ function statusValid (xhr) { try { var status = xhr.status return (status !== null && status !== 0) } catch (e) { return false } } ClientRequest.prototype._onXHRProgress = function () { var self = this if (!statusValid(self._xhr) || self._destroyed) return if (!self._response) self._connect() self._response._onXHRProgress() } ClientRequest.prototype._connect = function () { var self = this if (self._destroyed) return self._response = new IncomingMessage(self._xhr, self._fetchResponse, self._mode) self._response.on('error', function(err) { self.emit('error', err) }) self.emit('response', self._response) } ClientRequest.prototype._write = function (chunk, encoding, cb) { var self = this self._body.push(chunk) cb() } ClientRequest.prototype.abort = ClientRequest.prototype.destroy = function () { var self = this self._destroyed = true if (self._response) self._response._destroyed = true if (self._xhr) self._xhr.abort() // Currently, there isn't a way to truly abort a fetch. // If you like bikeshedding, see https://github.com/whatwg/fetch/issues/27 } ClientRequest.prototype.end = function (data, encoding, cb) { var self = this if (typeof data === 'function') { cb = data data = undefined } stream.Writable.prototype.end.call(self, data, encoding, cb) } ClientRequest.prototype.flushHeaders = function () {} ClientRequest.prototype.setTimeout = function () {} ClientRequest.prototype.setNoDelay = function () {} ClientRequest.prototype.setSocketKeepAlive = function () {} // Taken from http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method var unsafeHeaders = [ 'accept-charset', 'accept-encoding', 'access-control-request-headers', 'access-control-request-method', 'connection', 'content-length', 'cookie', 'cookie2', 'date', 'dnt', 'expect', 'host', 'keep-alive', 'origin', 'referer', 'te', 'trailer', 'transfer-encoding', 'upgrade', 'user-agent', 'via' ] }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) },{"./capability":26,"./response":28,"_process":13,"buffer":4,"inherits":9,"readable-stream":24,"to-arraybuffer":30}],28:[function(require,module,exports){ (function (process,global,Buffer){ var capability = require('./capability') var inherits = require('inherits') var stream = require('readable-stream') var rStates = exports.readyStates = { UNSENT: 0, OPENED: 1, HEADERS_RECEIVED: 2, LOADING: 3, DONE: 4 } var IncomingMessage = exports.IncomingMessage = function (xhr, response, mode) { var self = this stream.Readable.call(self) self._mode = mode self.headers = {} self.rawHeaders = [] self.trailers = {} self.rawTrailers = [] // Fake the 'close' event, but only once 'end' fires self.on('end', function () { // The nextTick is necessary to prevent the 'request' module from causing an infinite loop process.nextTick(function () { self.emit('close') }) }) if (mode === 'fetch') { self._fetchResponse = response self.url = response.url self.statusCode = response.status self.statusMessage = response.statusText response.headers.forEach(function(header, key){ self.headers[key.toLowerCase()] = header self.rawHeaders.push(key, header) }) // TODO: this doesn't respect backpressure. Once WritableStream is available, this can be fixed var reader = response.body.getReader() function read () { reader.read().then(function (result) { if (self._destroyed) return if (result.done) { self.push(null) return } self.push(new Buffer(result.value)) read() }).catch(function(err) { self.emit('error', err) }) } read() } else { self._xhr = xhr self._pos = 0 self.url = xhr.responseURL self.statusCode = xhr.status self.statusMessage = xhr.statusText var headers = xhr.getAllResponseHeaders().split(/\r?\n/) headers.forEach(function (header) { var matches = header.match(/^([^:]+):\s*(.*)/) if (matches) { var key = matches[1].toLowerCase() if (key === 'set-cookie') { if (self.headers[key] === undefined) { self.headers[key] = [] } self.headers[key].push(matches[2]) } else if (self.headers[key] !== undefined) { self.headers[key] += ', ' + matches[2] } else { self.headers[key] = matches[2] } self.rawHeaders.push(matches[1], matches[2]) } }) self._charset = 'x-user-defined' if (!capability.overrideMimeType) { var mimeType = self.rawHeaders['mime-type'] if (mimeType) { var charsetMatch = mimeType.match(/;\s*charset=([^;])(;|$)/) if (charsetMatch) { self._charset = charsetMatch[1].toLowerCase() } } if (!self._charset) self._charset = 'utf-8' // best guess } } } inherits(IncomingMessage, stream.Readable) IncomingMessage.prototype._read = function () {} IncomingMessage.prototype._onXHRProgress = function () { var self = this var xhr = self._xhr var response = null switch (self._mode) { case 'text:vbarray': // For IE9 if (xhr.readyState !== rStates.DONE) break try { // This fails in IE8 response = new global.VBArray(xhr.responseBody).toArray() } catch (e) {} if (response !== null) { self.push(new Buffer(response)) break } // Falls through in IE8 case 'text': try { // This will fail when readyState = 3 in IE9. Switch mode and wait for readyState = 4 response = xhr.responseText } catch (e) { self._mode = 'text:vbarray' break } if (response.length > self._pos) { var newData = response.substr(self._pos) if (self._charset === 'x-user-defined') { var buffer = new Buffer(newData.length) for (var i = 0; i < newData.length; i++) buffer[i] = newData.charCodeAt(i) & 0xff self.push(buffer) } else { self.push(newData, self._charset) } self._pos = response.length } break case 'arraybuffer': if (xhr.readyState !== rStates.DONE || !xhr.response) break response = xhr.response self.push(new Buffer(new Uint8Array(response))) break case 'moz-chunked-arraybuffer': // take whole response = xhr.response if (xhr.readyState !== rStates.LOADING || !response) break self.push(new Buffer(new Uint8Array(response))) break case 'ms-stream': response = xhr.response if (xhr.readyState !== rStates.LOADING) break var reader = new global.MSStreamReader() reader.onprogress = function () { if (reader.result.byteLength > self._pos) { self.push(new Buffer(new Uint8Array(reader.result.slice(self._pos)))) self._pos = reader.result.byteLength } } reader.onload = function () { self.push(null) } // reader.onerror = ??? // TODO: this reader.readAsArrayBuffer(response) break } // The ms-stream case handles end separately in reader.onload() if (self._xhr.readyState === rStates.DONE && self._mode !== 'ms-stream') { self.push(null) } } }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) },{"./capability":26,"_process":13,"buffer":4,"inherits":9,"readable-stream":24}],29:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // 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. var Buffer = require('buffer').Buffer; var isBufferEncoding = Buffer.isEncoding || function(encoding) { switch (encoding && encoding.toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; default: return false; } } function assertEncoding(encoding) { if (encoding && !isBufferEncoding(encoding)) { throw new Error('Unknown encoding: ' + encoding); } } // StringDecoder provides an interface for efficiently splitting a series of // buffers into a series of JS strings without breaking apart multi-byte // characters. CESU-8 is handled as part of the UTF-8 encoding. // // @TODO Handling all encodings inside a single object makes it very difficult // to reason about this code, so it should be split up in the future. // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code // points as used by CESU-8. var StringDecoder = exports.StringDecoder = function(encoding) { this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); assertEncoding(encoding); switch (this.encoding) { case 'utf8': // CESU-8 represents each of Surrogate Pair by 3-bytes this.surrogateSize = 3; break; case 'ucs2': case 'utf16le': // UTF-16 represents each of Surrogate Pair by 2-bytes this.surrogateSize = 2; this.detectIncompleteChar = utf16DetectIncompleteChar; break; case 'base64': // Base-64 stores 3 bytes in 4 chars, and pads the remainder. this.surrogateSize = 3; this.detectIncompleteChar = base64DetectIncompleteChar; break; default: this.write = passThroughWrite; return; } // Enough space to store all bytes of a single character. UTF-8 needs 4 // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). this.charBuffer = new Buffer(6); // Number of bytes received for the current incomplete multi-byte character. this.charReceived = 0; // Number of bytes expected for the current incomplete multi-byte character. this.charLength = 0; }; // write decodes the given buffer and returns it as JS string that is // guaranteed to not contain any partial multi-byte characters. Any partial // character found at the end of the buffer is buffered up, and will be // returned when calling write again with the remaining bytes. // // Note: Converting a Buffer containing an orphan surrogate to a String // currently works, but converting a String to a Buffer (via `new Buffer`, or // Buffer#write) will replace incomplete surrogates with the unicode // replacement character. See https://codereview.chromium.org/121173009/ . StringDecoder.prototype.write = function(buffer) { var charStr = ''; // if our last write ended with an incomplete multibyte character while (this.charLength) { // determine how many remaining bytes this buffer has to offer for this char var available = (buffer.length >= this.charLength - this.charReceived) ? this.charLength - this.charReceived : buffer.length; // add the new bytes to the char buffer buffer.copy(this.charBuffer, this.charReceived, 0, available); this.charReceived += available; if (this.charReceived < this.charLength) { // still not enough chars in this buffer? wait for more ... return ''; } // remove bytes belonging to the current character from the buffer buffer = buffer.slice(available, buffer.length); // get the character that was split charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character var charCode = charStr.charCodeAt(charStr.length - 1); if (charCode >= 0xD800 && charCode <= 0xDBFF) { this.charLength += this.surrogateSize; charStr = ''; continue; } this.charReceived = this.charLength = 0; // if there are no more bytes in this buffer, just emit our char if (buffer.length === 0) { return charStr; } break; } // determine and set charLength / charReceived this.detectIncompleteChar(buffer); var end = buffer.length; if (this.charLength) { // buffer the incomplete character bytes we got buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); end -= this.charReceived; } charStr += buffer.toString(this.encoding, 0, end); var end = charStr.length - 1; var charCode = charStr.charCodeAt(end); // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character if (charCode >= 0xD800 && charCode <= 0xDBFF) { var size = this.surrogateSize; this.charLength += size; this.charReceived += size; this.charBuffer.copy(this.charBuffer, size, 0, size); buffer.copy(this.charBuffer, 0, 0, size); return charStr.substring(0, end); } // or just emit the charStr return charStr; }; // detectIncompleteChar determines if there is an incomplete UTF-8 character at // the end of the given buffer. If so, it sets this.charLength to the byte // length that character, and sets this.charReceived to the number of bytes // that are available for this character. StringDecoder.prototype.detectIncompleteChar = function(buffer) { // determine how many bytes we have to check at the end of this buffer var i = (buffer.length >= 3) ? 3 : buffer.length; // Figure out if one of the last i bytes of our buffer announces an // incomplete char. for (; i > 0; i--) { var c = buffer[buffer.length - i]; // See http://en.wikipedia.org/wiki/UTF-8#Description // 110XXXXX if (i == 1 && c >> 5 == 0x06) { this.charLength = 2; break; } // 1110XXXX if (i <= 2 && c >> 4 == 0x0E) { this.charLength = 3; break; } // 11110XXX if (i <= 3 && c >> 3 == 0x1E) { this.charLength = 4; break; } } this.charReceived = i; }; StringDecoder.prototype.end = function(buffer) { var res = ''; if (buffer && buffer.length) res = this.write(buffer); if (this.charReceived) { var cr = this.charReceived; var buf = this.charBuffer; var enc = this.encoding; res += buf.slice(0, cr).toString(enc); } return res; }; function passThroughWrite(buffer) { return buffer.toString(this.encoding); } function utf16DetectIncompleteChar(buffer) { this.charReceived = buffer.length % 2; this.charLength = this.charReceived ? 2 : 0; } function base64DetectIncompleteChar(buffer) { this.charReceived = buffer.length % 3; this.charLength = this.charReceived ? 3 : 0; } },{"buffer":4}],30:[function(require,module,exports){ var Buffer = require('buffer').Buffer module.exports = function (buf) { // If the buffer is backed by a Uint8Array, a faster version will work if (buf instanceof Uint8Array) { // If the buffer isn't a subarray, return the underlying ArrayBuffer if (buf.byteOffset === 0 && buf.byteLength === buf.buffer.byteLength) { return buf.buffer } else if (typeof buf.buffer.slice === 'function') { // Otherwise we need to get a proper copy return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength) } } if (Buffer.isBuffer(buf)) { // This is the slow version that will work with any Buffer // implementation (even in old browsers) var arrayCopy = new Uint8Array(buf.length) var len = buf.length for (var i = 0; i < len; i++) { arrayCopy[i] = buf[i] } return arrayCopy.buffer } else { throw new Error('Argument must be a Buffer') } } },{"buffer":4}],31:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // 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. 'use strict'; var punycode = require('punycode'); var util = require('./util'); exports.parse = urlParse; exports.resolve = urlResolve; exports.resolveObject = urlResolveObject; exports.format = urlFormat; exports.Url = Url; function Url() { this.protocol = null; this.slashes = null; this.auth = null; this.host = null; this.port = null; this.hostname = null; this.hash = null; this.search = null; this.query = null; this.pathname = null; this.path = null; this.href = null; } // Reference: RFC 3986, RFC 1808, RFC 2396 // define these here so at least they only have to be // compiled once on the first module load. var protocolPattern = /^([a-z0-9.+-]+:)/i, portPattern = /:[0-9]*$/, // Special case for a simple path URL simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, // RFC 2396: characters reserved for delimiting URLs. // We actually just auto-escape these. delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], // RFC 2396: characters not allowed for various reasons. unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), // Allowed by RFCs, but cause of XSS attacks. Always escape these. autoEscape = ['\''].concat(unwise), // Characters that are never ever allowed in a hostname. // Note that any invalid chars are also handled, but these // are the ones that are *expected* to be seen, so we fast-path // them. nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), hostEndingChars = ['/', '?', '#'], hostnameMaxLen = 255, hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, // protocols that can allow "unsafe" and "unwise" chars. unsafeProtocol = { 'javascript': true, 'javascript:': true }, // protocols that never have a hostname. hostlessProtocol = { 'javascript': true, 'javascript:': true }, // protocols that always contain a // bit. slashedProtocol = { 'http': true, 'https': true, 'ftp': true, 'gopher': true, 'file': true, 'http:': true, 'https:': true, 'ftp:': true, 'gopher:': true, 'file:': true }, querystring = require('querystring'); function urlParse(url, parseQueryString, slashesDenoteHost) { if (url && util.isObject(url) && url instanceof Url) return url; var u = new Url; u.parse(url, parseQueryString, slashesDenoteHost); return u; } Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { if (!util.isString(url)) { throw new TypeError("Parameter 'url' must be a string, not " + typeof url); } // Copy chrome, IE, opera backslash-handling behavior. // Back slashes before the query string get converted to forward slashes // See: https://code.google.com/p/chromium/issues/detail?id=25916 var queryIndex = url.indexOf('?'), splitter = (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', uSplit = url.split(splitter), slashRegex = /\\/g; uSplit[0] = uSplit[0].replace(slashRegex, '/'); url = uSplit.join(splitter); var rest = url; // trim before proceeding. // This is to support parse stuff like " http://foo.com \n" rest = rest.trim(); if (!slashesDenoteHost && url.split('#').length === 1) { // Try fast path regexp var simplePath = simplePathPattern.exec(rest); if (simplePath) { this.path = rest; this.href = rest; this.pathname = simplePath[1]; if (simplePath[2]) { this.search = simplePath[2]; if (parseQueryString) { this.query = querystring.parse(this.search.substr(1)); } else { this.query = this.search.substr(1); } } else if (parseQueryString) { this.search = ''; this.query = {}; } return this; } } var proto = protocolPattern.exec(rest); if (proto) { proto = proto[0]; var lowerProto = proto.toLowerCase(); this.protocol = lowerProto; rest = rest.substr(proto.length); } // figure out if it's got a host // user@server is *always* interpreted as a hostname, and url // resolution will treat //foo/bar as host=foo,path=bar because that's // how the browser resolves relative URLs. if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { var slashes = rest.substr(0, 2) === '//'; if (slashes && !(proto && hostlessProtocol[proto])) { rest = rest.substr(2); this.slashes = true; } } if (!hostlessProtocol[proto] && (slashes || (proto && !slashedProtocol[proto]))) { // there's a hostname. // the first instance of /, ?, ;, or # ends the host. // // If there is an @ in the hostname, then non-host chars *are* allowed // to the left of the last @ sign, unless some host-ending character // comes *before* the @-sign. // URLs are obnoxious. // // ex: // http://a@b@c/ => user:a@b host:c // http://a@b?@c => user:a host:c path:/?@c // v0.12 TODO(isaacs): This is not quite how Chrome does things. // Review our test case against browsers more comprehensively. // find the first instance of any hostEndingChars var hostEnd = -1; for (var i = 0; i < hostEndingChars.length; i++) { var hec = rest.indexOf(hostEndingChars[i]); if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) hostEnd = hec; } // at this point, either we have an explicit point where the // auth portion cannot go past, or the last @ char is the decider. var auth, atSign; if (hostEnd === -1) { // atSign can be anywhere. atSign = rest.lastIndexOf('@'); } else { // atSign must be in auth portion. // http://a@b/c@d => host:b auth:a path:/c@d atSign = rest.lastIndexOf('@', hostEnd); } // Now we have a portion which is definitely the auth. // Pull that off. if (atSign !== -1) { auth = rest.slice(0, atSign); rest = rest.slice(atSign + 1); this.auth = decodeURIComponent(auth); } // the host is the remaining to the left of the first non-host char hostEnd = -1; for (var i = 0; i < nonHostChars.length; i++) { var hec = rest.indexOf(nonHostChars[i]); if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) hostEnd = hec; } // if we still have not hit it, then the entire thing is a host. if (hostEnd === -1) hostEnd = rest.length; this.host = rest.slice(0, hostEnd); rest = rest.slice(hostEnd); // pull out port. this.parseHost(); // we've indicated that there is a hostname, // so even if it's empty, it has to be present. this.hostname = this.hostname || ''; // if hostname begins with [ and ends with ] // assume that it's an IPv6 address. var ipv6Hostname = this.hostname[0] === '[' && this.hostname[this.hostname.length - 1] === ']'; // validate a little. if (!ipv6Hostname) { var hostparts = this.hostname.split(/\./); for (var i = 0, l = hostparts.length; i < l; i++) { var part = hostparts[i]; if (!part) continue; if (!part.match(hostnamePartPattern)) { var newpart = ''; for (var j = 0, k = part.length; j < k; j++) { if (part.charCodeAt(j) > 127) { // we replace non-ASCII char with a temporary placeholder // we need this to make sure size of hostname is not // broken by replacing non-ASCII by nothing newpart += 'x'; } else { newpart += part[j]; } } // we test again with ASCII char only if (!newpart.match(hostnamePartPattern)) { var validParts = hostparts.slice(0, i); var notHost = hostparts.slice(i + 1); var bit = part.match(hostnamePartStart); if (bit) { validParts.push(bit[1]); notHost.unshift(bit[2]); } if (notHost.length) { rest = '/' + notHost.join('.') + rest; } this.hostname = validParts.join('.'); break; } } } } if (this.hostname.length > hostnameMaxLen) { this.hostname = ''; } else { // hostnames are always lower case. this.hostname = this.hostname.toLowerCase(); } if (!ipv6Hostname) { // IDNA Support: Returns a punycoded representation of "domain". // It only converts parts of the domain name that // have non-ASCII characters, i.e. it doesn't matter if // you call it with a domain that already is ASCII-only. this.hostname = punycode.toASCII(this.hostname); } var p = this.port ? ':' + this.port : ''; var h = this.hostname || ''; this.host = h + p; this.href += this.host; // strip [ and ] from the hostname // the host field still retains them, though if (ipv6Hostname) { this.hostname = this.hostname.substr(1, this.hostname.length - 2); if (rest[0] !== '/') { rest = '/' + rest; } } } // now rest is set to the post-host stuff. // chop off any delim chars. if (!unsafeProtocol[lowerProto]) { // First, make 100% sure that any "autoEscape" chars get // escaped, even if encodeURIComponent doesn't think they // need to be. for (var i = 0, l = autoEscape.length; i < l; i++) { var ae = autoEscape[i]; if (rest.indexOf(ae) === -1) continue; var esc = encodeURIComponent(ae); if (esc === ae) { esc = escape(ae); } rest = rest.split(ae).join(esc); } } // chop off from the tail first. var hash = rest.indexOf('#'); if (hash !== -1) { // got a fragment string. this.hash = rest.substr(hash); rest = rest.slice(0, hash); } var qm = rest.indexOf('?'); if (qm !== -1) { this.search = rest.substr(qm); this.query = rest.substr(qm + 1); if (parseQueryString) { this.query = querystring.parse(this.query); } rest = rest.slice(0, qm); } else if (parseQueryString) { // no query string, but parseQueryString still requested this.search = ''; this.query = {}; } if (rest) this.pathname = rest; if (slashedProtocol[lowerProto] && this.hostname && !this.pathname) { this.pathname = '/'; } //to support http.request if (this.pathname || this.search) { var p = this.pathname || ''; var s = this.search || ''; this.path = p + s; } // finally, reconstruct the href based on what has been validated. this.href = this.format(); return this; }; // format a parsed object into a url string function urlFormat(obj) { // ensure it's an object, and not a string url. // If it's an obj, this is a no-op. // this way, you can call url_format() on strings // to clean up potentially wonky urls. if (util.isString(obj)) obj = urlParse(obj); if (!(obj instanceof Url)) return Url.prototype.format.call(obj); return obj.format(); } Url.prototype.format = function() { var auth = this.auth || ''; if (auth) { auth = encodeURIComponent(auth); auth = auth.replace(/%3A/i, ':'); auth += '@'; } var protocol = this.protocol || '', pathname = this.pathname || '', hash = this.hash || '', host = false, query = ''; if (this.host) { host = auth + this.host; } else if (this.hostname) { host = auth + (this.hostname.indexOf(':') === -1 ? this.hostname : '[' + this.hostname + ']'); if (this.port) { host += ':' + this.port; } } if (this.query && util.isObject(this.query) && Object.keys(this.query).length) { query = querystring.stringify(this.query); } var search = this.search || (query && ('?' + query)) || ''; if (protocol && protocol.substr(-1) !== ':') protocol += ':'; // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. // unless they had them to begin with. if (this.slashes || (!protocol || slashedProtocol[protocol]) && host !== false) { host = '//' + (host || ''); if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; } else if (!host) { host = ''; } if (hash && hash.charAt(0) !== '#') hash = '#' + hash; if (search && search.charAt(0) !== '?') search = '?' + search; pathname = pathname.replace(/[?#]/g, function(match) { return encodeURIComponent(match); }); search = search.replace('#', '%23'); return protocol + host + pathname + search + hash; }; function urlResolve(source, relative) { return urlParse(source, false, true).resolve(relative); } Url.prototype.resolve = function(relative) { return this.resolveObject(urlParse(relative, false, true)).format(); }; function urlResolveObject(source, relative) { if (!source) return relative; return urlParse(source, false, true).resolveObject(relative); } Url.prototype.resolveObject = function(relative) { if (util.isString(relative)) { var rel = new Url(); rel.parse(relative, false, true); relative = rel; } var result = new Url(); var tkeys = Object.keys(this); for (var tk = 0; tk < tkeys.length; tk++) { var tkey = tkeys[tk]; result[tkey] = this[tkey]; } // hash is always overridden, no matter what. // even href="" will remove it. result.hash = relative.hash; // if the relative url is empty, then there's nothing left to do here. if (relative.href === '') { result.href = result.format(); return result; } // hrefs like //foo/bar always cut to the protocol. if (relative.slashes && !relative.protocol) { // take everything except the protocol from relative var rkeys = Object.keys(relative); for (var rk = 0; rk < rkeys.length; rk++) { var rkey = rkeys[rk]; if (rkey !== 'protocol') result[rkey] = relative[rkey]; } //urlParse appends trailing / to urls like http://www.example.com if (slashedProtocol[result.protocol] && result.hostname && !result.pathname) { result.path = result.pathname = '/'; } result.href = result.format(); return result; } if (relative.protocol && relative.protocol !== result.protocol) { // if it's a known url protocol, then changing // the protocol does weird things // first, if it's not file:, then we MUST have a host, // and if there was a path // to begin with, then we MUST have a path. // if it is file:, then the host is dropped, // because that's known to be hostless. // anything else is assumed to be absolute. if (!slashedProtocol[relative.protocol]) { var keys = Object.keys(relative); for (var v = 0; v < keys.length; v++) { var k = keys[v]; result[k] = relative[k]; } result.href = result.format(); return result; } result.protocol = relative.protocol; if (!relative.host && !hostlessProtocol[relative.protocol]) { var relPath = (relative.pathname || '').split('/'); while (relPath.length && !(relative.host = relPath.shift())); if (!relative.host) relative.host = ''; if (!relative.hostname) relative.hostname = ''; if (relPath[0] !== '') relPath.unshift(''); if (relPath.length < 2) relPath.unshift(''); result.pathname = relPath.join('/'); } else { result.pathname = relative.pathname; } result.search = relative.search; result.query = relative.query; result.host = relative.host || ''; result.auth = relative.auth; result.hostname = relative.hostname || relative.host; result.port = relative.port; // to support http.request if (result.pathname || result.search) { var p = result.pathname || ''; var s = result.search || ''; result.path = p + s; } result.slashes = result.slashes || relative.slashes; result.href = result.format(); return result; } var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), isRelAbs = ( relative.host || relative.pathname && relative.pathname.charAt(0) === '/' ), mustEndAbs = (isRelAbs || isSourceAbs || (result.host && relative.pathname)), removeAllDots = mustEndAbs, srcPath = result.pathname && result.pathname.split('/') || [], relPath = relative.pathname && relative.pathname.split('/') || [], psychotic = result.protocol && !slashedProtocol[result.protocol]; // if the url is a non-slashed url, then relative // links like ../.. should be able // to crawl up to the hostname, as well. This is strange. // result.protocol has already been set by now. // Later on, put the first path part into the host field. if (psychotic) { result.hostname = ''; result.port = null; if (result.host) { if (srcPath[0] === '') srcPath[0] = result.host; else srcPath.unshift(result.host); } result.host = ''; if (relative.protocol) { relative.hostname = null; relative.port = null; if (relative.host) { if (relPath[0] === '') relPath[0] = relative.host; else relPath.unshift(relative.host); } relative.host = null; } mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); } if (isRelAbs) { // it's absolute. result.host = (relative.host || relative.host === '') ? relative.host : result.host; result.hostname = (relative.hostname || relative.hostname === '') ? relative.hostname : result.hostname; result.search = relative.search; result.query = relative.query; srcPath = relPath; // fall through to the dot-handling below. } else if (relPath.length) { // it's relative // throw away the existing file, and take the new path instead. if (!srcPath) srcPath = []; srcPath.pop(); srcPath = srcPath.concat(relPath); result.search = relative.search; result.query = relative.query; } else if (!util.isNullOrUndefined(relative.search)) { // just pull out the search. // like href='?foo'. // Put this after the other two cases because it simplifies the booleans if (psychotic) { result.hostname = result.host = srcPath.shift(); //occationaly the auth can get stuck only in host //this especially happens in cases like //url.resolveObject('mailto:local1@domain1', 'local2@domain2') var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; if (authInHost) { result.auth = authInHost.shift(); result.host = result.hostname = authInHost.shift(); } } result.search = relative.search; result.query = relative.query; //to support http.request if (!util.isNull(result.pathname) || !util.isNull(result.search)) { result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); } result.href = result.format(); return result; } if (!srcPath.length) { // no path at all. easy. // we've already handled the other stuff above. result.pathname = null; //to support http.request if (result.search) { result.path = '/' + result.search; } else { result.path = null; } result.href = result.format(); return result; } // if a url ENDs in . or .., then it must get a trailing slash. // however, if it ends in anything else non-slashy, // then it must NOT get a trailing slash. var last = srcPath.slice(-1)[0]; var hasTrailingSlash = ( (result.host || relative.host || srcPath.length > 1) && (last === '.' || last === '..') || last === ''); // strip single dots, resolve double dots to parent dir // if the path tries to go above the root, `up` ends up > 0 var up = 0; for (var i = srcPath.length; i >= 0; i--) { last = srcPath[i]; if (last === '.') { srcPath.splice(i, 1); } else if (last === '..') { srcPath.splice(i, 1); up++; } else if (up) { srcPath.splice(i, 1); up--; } } // if the path is allowed to go above the root, restore leading ..s if (!mustEndAbs && !removeAllDots) { for (; up--; up) { srcPath.unshift('..'); } } if (mustEndAbs && srcPath[0] !== '' && (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { srcPath.unshift(''); } if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { srcPath.push(''); } var isAbsolute = srcPath[0] === '' || (srcPath[0] && srcPath[0].charAt(0) === '/'); // put the host back if (psychotic) { result.hostname = result.host = isAbsolute ? '' : srcPath.length ? srcPath.shift() : ''; //occationaly the auth can get stuck only in host //this especially happens in cases like //url.resolveObject('mailto:local1@domain1', 'local2@domain2') var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; if (authInHost) { result.auth = authInHost.shift(); result.host = result.hostname = authInHost.shift(); } } mustEndAbs = mustEndAbs || (result.host && srcPath.length); if (mustEndAbs && !isAbsolute) { srcPath.unshift(''); } if (!srcPath.length) { result.pathname = null; result.path = null; } else { result.pathname = srcPath.join('/'); } //to support request.http if (!util.isNull(result.pathname) || !util.isNull(result.search)) { result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); } result.auth = relative.auth || result.auth; result.slashes = result.slashes || relative.slashes; result.href = result.format(); return result; }; Url.prototype.parseHost = function() { var host = this.host; var port = portPattern.exec(host); if (port) { port = port[0]; if (port !== ':') { this.port = port.substr(1); } host = host.substr(0, host.length - port.length); } if (host) this.hostname = host; }; },{"./util":32,"punycode":14,"querystring":17}],32:[function(require,module,exports){ 'use strict'; module.exports = { isString: function(arg) { return typeof(arg) === 'string'; }, isObject: function(arg) { return typeof(arg) === 'object' && arg !== null; }, isNull: function(arg) { return arg === null; }, isNullOrUndefined: function(arg) { return arg == null; } }; },{}],33:[function(require,module,exports){ (function (global){ /** * Module exports. */ module.exports = deprecate; /** * Mark that a method should not be used. * Returns a modified function which warns once by default. * * If `localStorage.noDeprecation = true` is set, then it is a no-op. * * If `localStorage.throwDeprecation = true` is set, then deprecated functions * will throw an Error when invoked. * * If `localStorage.traceDeprecation = true` is set, then deprecated functions * will invoke `console.trace()` instead of `console.error()`. * * @param {Function} fn - the function to deprecate * @param {String} msg - the string to print to the console when `fn` is invoked * @returns {Function} a new "deprecated" version of `fn` * @api public */ function deprecate (fn, msg) { if (config('noDeprecation')) { return fn; } var warned = false; function deprecated() { if (!warned) { if (config('throwDeprecation')) { throw new Error(msg); } else if (config('traceDeprecation')) { console.trace(msg); } else { console.warn(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; } /** * Checks `localStorage` for boolean values for the given `name`. * * @param {String} name * @returns {Boolean} * @api private */ function config (name) { // accessing global.localStorage can trigger a DOMException in sandboxed iframes try { if (!global.localStorage) return false; } catch (_) { return false; } var val = global.localStorage[name]; if (null == val) return false; return String(val).toLowerCase() === 'true'; } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],34:[function(require,module,exports){ module.exports = extend var hasOwnProperty = Object.prototype.hasOwnProperty; function extend() { var target = {} for (var i = 0; i < arguments.length; i++) { var source = arguments[i] for (var key in source) { if (hasOwnProperty.call(source, key)) { target[key] = source[key] } } } return target } },{}],35:[function(require,module,exports){ let http = require('http'), hostname = 'localhost', port = 7777; http.createServer((req, res) => { console.log('NEW REQUEST'); let data = ''; res.writeHead(200, { 'Content-Type' : 'text/javascript', 'Access-Control-Allow-Origin' : '*' }); req.setEncoding('utf8'); req.on('data', buf => { data = data.concat(buf); }); req.on('error', () => { res.end('{}'); }); req.on('end', () => { data = JSON.parse(data); res.end(JSON.stringify(data)); }); }).listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); }); },{"http":25}]},{},[35]);
webenot/loftBlog-js
lesson8/server.out.js
JavaScript
gpl-3.0
209,651
/** * Created by nuintun on 2016/9/26. */ 'use strict'; module.exports = { '/news/company/:id': [ { action: 'company' } ], '/news/trade/:id': [ { action: 'trade' } ], '/news/help/:id': [ { action: 'help' } ], '/news/policy/:id': [ { action: 'policy' } ] };
GXTLW/gxt-front
routers/news/detail.js
JavaScript
gpl-3.0
333
// generated from ldml/main/*.xml, xpath: ldml/numbers ({ 'decimal':",", 'group':".", 'percentFormat':"#,##0 %" })
NESCent/plhdb
WebRoot/js/dojo/cldr/nls/de/number.js
JavaScript
gpl-3.0
139
const fs = require('fs'); var Milight = require('node-milight-promise').MilightController; var commands = require('node-milight-promise').commands2; // set up the milight object var light = new Milight({ ip: "255.255.255.255", delayBetweenCommands: 80, commandRepeat: 2 }); module.exports = { changeState: function (state, brightness, zone) { if(state) { light.sendCommands(commands.rgbw.on(zone), commands.rgbw.whiteMode(zone), commands.rgbw.brightness(brightness)); } else { light.sendCommands(commands.rgbw.off(zone)); } light.close(); }, changeBrightness: function (brightness, zone) { light.sendCommands(commands.rgbw.on(zone), commands.rgbw.brightness(brightness)); } };
wassupben/MiLight-Web-Interface
controller/lights.js
JavaScript
gpl-3.0
755
/** * @requires OpenLayers/Symbolizer.js */ /** * Class: OpenLayers.Symbolizer.Line * A symbolizer used to render line features. */ OpenLayers.Symbolizer.Line = OpenLayers.Class(OpenLayers.Symbolizer, { /** * APIProperty: strokeColor * {String} Color for line stroke. This is a RGB hex value (e.g. "#ff0000" * for red). */ strokeColor: null, /** * APIProperty: strokeOpacity * {Number} Stroke opacity (0-1). */ strokeOpacity: null, /** * APIProperty: strokeWidth * {Number} Pixel stroke width. */ strokeWidth: null, /** * APIProperty: strokeLinecap * {String} Stroke cap type ("butt", "round", or "square"). */ strokeLinecap: null, /** * Property: strokeDashstyle * {String} Stroke dash style according to the SLD spec. Note that the * OpenLayers values for strokeDashstyle ("dot", "dash", "dashdot", * "longdash", "longdashdot", or "solid") will not work in SLD, but * most SLD patterns will render correctly in OpenLayers. */ strokeDashstyle: "solid", /** * Constructor: OpenLayers.Symbolizer.Line * Create a symbolizer for rendering lines. * * Parameters: * config - {Object} An object containing properties to be set on the * symbolizer. Any documented symbolizer property can be set at * construction. * * Returns: * A new line symbolizer. */ initialize: function(config) { OpenLayers.Symbolizer.prototype.initialize.apply(this, arguments); }, CLASS_NAME: "OpenLayers.Symbolizer.Line" });
guolivar/totus-niwa
web/js/libs/openlayers/lib/OpenLayers/Symbolizer/Line.js
JavaScript
gpl-3.0
1,675
'use strict'; /** * nconf is used globally for config, client instantiates the necessary config files * import config throughout the application to share the global nconf */ var fs = require('fs-extra'); var config = require('nconf'); var defaults = require('./default'); var util = require('../lib/util'); var path = require('path'); var _ = require('lodash'); function _monitor(filePath) { fs.unwatchFile(filePath); fs.watchFile(filePath, function() { _reload(); }); } function _reload() { config.remove('user-client'); config.remove('default-client'); config.remove('global'); _init(); } function _init() { config.env().argv().defaults({}); var userSettingsPath; if (util.isMac()) { userSettingsPath = path.join(util.getHomeDirectory(), '.mavensmate-config.json'); } else if (util.isWindows()) { userSettingsPath = path.join(util.getWindowsAppDataPath(), 'MavensMate', 'mavensmate-config.json'); } else if (util.isLinux()) { userSettingsPath = path.join(util.getHomeDirectory(), '.config', '.mavensmate-config.json'); } var defaultSettings = {}; _.each(defaults, function(settingValue, settingKey) { defaultSettings[settingKey] = settingValue.default; }); // if user setting dont exist, copy default to user settings on disk if (!fs.existsSync(userSettingsPath)) { fs.outputJsonSync(userSettingsPath, defaultSettings, {spaces: 2}); } // ensure valid JSON configuration try { util.getFileBody(userSettingsPath, true); } catch(e) { logger.error('could not parse user JSON configuration, reverting to default'); fs.outputJsonSync(userSettingsPath, defaultSettings, { spaces: 2 }); } config.file('user', userSettingsPath); _monitor(userSettingsPath); config .add('global', { type: 'literal', store: defaultSettings}); // normalize mm_api_version to string with a single decimal var mmApiVersion = config.get('mm_api_version'); if (!util.endsWith(mmApiVersion,'.0')) { mmApiVersion = mmApiVersion+'.0'; config.set('mm_api_version', mmApiVersion); } if (config.get('mm_http_proxy')) { process.env.http_proxy = config.get('mm_http_proxy'); } if (config.get('mm_https_proxy')) { process.env.https_proxy = config.get('mm_https_proxy'); } } _init(); module.exports = config;
joeferraro/MavensMate
app/config/index.js
JavaScript
gpl-3.0
2,335
import { moduleFor, test } from 'ember-qunit'; moduleFor('controller:admin/cidade', 'Unit | Controller | admin/cidade', { // Specify the other units that are required for this test. // needs: ['controller:foo'] }); // Replace this with your real tests. test('it exists', function(assert) { let controller = this.subject(); assert.ok(controller); });
cuiateam/ajudame-web
tests/unit/controllers/admin/cidade-test.js
JavaScript
gpl-3.0
360
$(function() { if($(".has-error").length) { $('html,body').animate( { scrollTop: $(".has-error").offset().top-70 },'slow'); } $(".enabled").click(function() { $(this).parents(".element-container").removeClass("has-error"); }); $(".custom").click(function() { $(this).parents(".element-container").removeClass("has-error"); var id = $(this).data("for"), input = $("#" + id); if (input.length === 0) { return; } if ($(this).is(":checked")) { input.prop("readonly", false); input.val(input.data("custom")); } else { input.data("custom", input.val()); input.prop("readonly", true); input.val(input.data("default")); } }); //bind like this for popovers! $("form[name=frmAdmin]")[0].onsubmit = function() { var msgErrorMissingFC = _("Please enter a Feature Code or uncheck Customize"), fcs = [], error = null; $(".code").each(function(i, v) { var input = $(v); fcs.push(input.val()); if (!input.prop("readonly") && input.val().trim() === "") { error = { "item": input, "message": msgErrorMissingFC }; return false; } }); if (error !== null) { return warnInvalid(error.item, error.message); } else { return true; } }; });
FreePBX/featurecodeadmin
assets/js/featurecodeadmin.js
JavaScript
gpl-3.0
1,215
'use strict'; define([ 'jquery', 'underscore', 'Backbone', 'tpl!templates/userView', ], function($, _, Backbone, userViewTemplate){ var UserView = Backbone.View.extend({ className : 'user', tagName : 'tr', initialize: function(){ _.bindAll(this, 'render', 'changeVisibility'); this.model.on('change:visible', this.changeVisibility); this.render(); }, render: function(){ var model = this.model; var $el = this.$el; var variables = model.toJSON(); $.extend(variables, { createDate : new Date(variables.createDate), orderBy : this.model.collection.orderBy }); $el.html(userViewTemplate(variables)); }, changeVisibility : function(){ this.$el.toggle(this.model.get('visible')); } }); return UserView; });
anycook/anycook-backend-page
app/scripts/views/UserView.js
JavaScript
gpl-3.0
952
'use strict'; module.exports = function(Chart) { var helpers = Chart.helpers; var noop = helpers.noop; Chart.defaults.global.legend = { display: true, position: 'top', fullWidth: true, // marks that this box should take the full width of the canvas (pushing down other boxes) reverse: false, // a callback that will handle onClick: function(e, legendItem) { var index = legendItem.datasetIndex; var ci = this.chart; var meta = ci.getDatasetMeta(index); // See controller.isDatasetVisible comment meta.hidden = meta.hidden === null? !ci.data.datasets[index].hidden : null; // We hid a dataset ... rerender the chart ci.update(); }, onHover: null, labels: { boxWidth: 40, padding: 10, // Generates labels shown in the legend // Valid properties to return: // text : text to display // fillStyle : fill of coloured box // strokeStyle: stroke of coloured box // hidden : if this legend item refers to a hidden item // lineCap : cap style for line // lineDash // lineDashOffset : // lineJoin : // lineWidth : generateLabels: function(chart) { var data = chart.data; return helpers.isArray(data.datasets) ? data.datasets.map(function(dataset, i) { return { text: dataset.label, fillStyle: (!helpers.isArray(dataset.backgroundColor) ? dataset.backgroundColor : dataset.backgroundColor[0]), hidden: !chart.isDatasetVisible(i), lineCap: dataset.borderCapStyle, lineDash: dataset.borderDash, lineDashOffset: dataset.borderDashOffset, lineJoin: dataset.borderJoinStyle, lineWidth: dataset.borderWidth, strokeStyle: dataset.borderColor, pointStyle: dataset.pointStyle, // Below is extra data used for toggling the datasets datasetIndex: i }; }, this) : []; } } }; /** * Helper function to get the box width based on the usePointStyle option * @param labelopts {Object} the label options on the legend * @param fontSize {Number} the label font size * @return {Number} width of the color box area */ function getBoxWidth(labelOpts, fontSize) { return labelOpts.usePointStyle ? fontSize * Math.SQRT2 : labelOpts.boxWidth; } Chart.Legend = Chart.Element.extend({ initialize: function(config) { helpers.extend(this, config); // Contains hit boxes for each dataset (in dataset order) this.legendHitBoxes = []; // Are we in doughnut mode which has a different data type this.doughnutMode = false; }, // These methods are ordered by lifecyle. Utilities then follow. // Any function defined here is inherited by all legend types. // Any function can be extended by the legend type beforeUpdate: noop, update: function(maxWidth, maxHeight, margins) { var me = this; // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;) me.beforeUpdate(); // Absorb the master measurements me.maxWidth = maxWidth; me.maxHeight = maxHeight; me.margins = margins; // Dimensions me.beforeSetDimensions(); me.setDimensions(); me.afterSetDimensions(); // Labels me.beforeBuildLabels(); me.buildLabels(); me.afterBuildLabels(); // Fit me.beforeFit(); me.fit(); me.afterFit(); // me.afterUpdate(); return me.minSize; }, afterUpdate: noop, // beforeSetDimensions: noop, setDimensions: function() { var me = this; // Set the unconstrained dimension before label rotation if (me.isHorizontal()) { // Reset position before calculating rotation me.width = me.maxWidth; me.left = 0; me.right = me.width; } else { me.height = me.maxHeight; // Reset position before calculating rotation me.top = 0; me.bottom = me.height; } // Reset padding me.paddingLeft = 0; me.paddingTop = 0; me.paddingRight = 0; me.paddingBottom = 0; // Reset minSize me.minSize = { width: 0, height: 0 }; }, afterSetDimensions: noop, // beforeBuildLabels: noop, buildLabels: function() { var me = this; me.legendItems = me.options.labels.generateLabels.call(me, me.chart); if (me.options.reverse) { me.legendItems.reverse(); } }, afterBuildLabels: noop, // beforeFit: noop, fit: function() { var me = this; var opts = me.options; var labelOpts = opts.labels; var display = opts.display; var ctx = me.ctx; var globalDefault = Chart.defaults.global, itemOrDefault = helpers.getValueOrDefault, fontSize = itemOrDefault(labelOpts.fontSize, globalDefault.defaultFontSize), fontStyle = itemOrDefault(labelOpts.fontStyle, globalDefault.defaultFontStyle), fontFamily = itemOrDefault(labelOpts.fontFamily, globalDefault.defaultFontFamily), labelFont = helpers.fontString(fontSize, fontStyle, fontFamily); // Reset hit boxes var hitboxes = me.legendHitBoxes = []; var minSize = me.minSize; var isHorizontal = me.isHorizontal(); if (isHorizontal) { minSize.width = me.maxWidth; // fill all the width minSize.height = display ? 10 : 0; } else { minSize.width = display ? 10 : 0; minSize.height = me.maxHeight; // fill all the height } // Increase sizes here if (display) { ctx.font = labelFont; if (isHorizontal) { // Labels // Width of each line of legend boxes. Labels wrap onto multiple lines when there are too many to fit on one var lineWidths = me.lineWidths = [0]; var totalHeight = me.legendItems.length ? fontSize + (labelOpts.padding) : 0; ctx.textAlign = 'left'; ctx.textBaseline = 'top'; helpers.each(me.legendItems, function(legendItem, i) { var boxWidth = getBoxWidth(labelOpts, fontSize); var width = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width; if (lineWidths[lineWidths.length - 1] + width + labelOpts.padding >= me.width) { totalHeight += fontSize + (labelOpts.padding); lineWidths[lineWidths.length] = me.left; } // Store the hitbox width and height here. Final position will be updated in `draw` hitboxes[i] = { left: 0, top: 0, width: width, height: fontSize }; lineWidths[lineWidths.length - 1] += width + labelOpts.padding; }); minSize.height += totalHeight; } else { var vPadding = labelOpts.padding; var columnWidths = me.columnWidths = []; var totalWidth = labelOpts.padding; var currentColWidth = 0; var currentColHeight = 0; var itemHeight = fontSize + vPadding; helpers.each(me.legendItems, function(legendItem, i) { var boxWidth = getBoxWidth(labelOpts, fontSize); var itemWidth = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width; // If too tall, go to new column if (currentColHeight + itemHeight > minSize.height) { totalWidth += currentColWidth + labelOpts.padding; columnWidths.push(currentColWidth); // previous column width currentColWidth = 0; currentColHeight = 0; } // Get max width currentColWidth = Math.max(currentColWidth, itemWidth); currentColHeight += itemHeight; // Store the hitbox width and height here. Final position will be updated in `draw` hitboxes[i] = { left: 0, top: 0, width: itemWidth, height: fontSize }; }); totalWidth += currentColWidth; columnWidths.push(currentColWidth); minSize.width += totalWidth; } } me.width = minSize.width; me.height = minSize.height; }, afterFit: noop, // Shared Methods isHorizontal: function() { return this.options.position === 'top' || this.options.position === 'bottom'; }, // Actualy draw the legend on the canvas draw: function() { var me = this; var opts = me.options; var labelOpts = opts.labels; var globalDefault = Chart.defaults.global, lineDefault = globalDefault.elements.line, legendWidth = me.width, lineWidths = me.lineWidths; if (opts.display) { var ctx = me.ctx, cursor, itemOrDefault = helpers.getValueOrDefault, fontColor = itemOrDefault(labelOpts.fontColor, globalDefault.defaultFontColor), fontSize = itemOrDefault(labelOpts.fontSize, globalDefault.defaultFontSize), fontStyle = itemOrDefault(labelOpts.fontStyle, globalDefault.defaultFontStyle), fontFamily = itemOrDefault(labelOpts.fontFamily, globalDefault.defaultFontFamily), labelFont = helpers.fontString(fontSize, fontStyle, fontFamily); // Canvas setup ctx.textAlign = 'left'; ctx.textBaseline = 'top'; ctx.lineWidth = 0.5; ctx.strokeStyle = fontColor; // for strikethrough effect ctx.fillStyle = fontColor; // render in correct colour ctx.font = labelFont; var boxWidth = getBoxWidth(labelOpts, fontSize), hitboxes = me.legendHitBoxes; // current position var drawLegendBox = function(x, y, legendItem) { if (isNaN(boxWidth) || boxWidth <= 0) { return; } // Set the ctx for the box ctx.save(); ctx.fillStyle = itemOrDefault(legendItem.fillStyle, globalDefault.defaultColor); ctx.lineCap = itemOrDefault(legendItem.lineCap, lineDefault.borderCapStyle); ctx.lineDashOffset = itemOrDefault(legendItem.lineDashOffset, lineDefault.borderDashOffset); ctx.lineJoin = itemOrDefault(legendItem.lineJoin, lineDefault.borderJoinStyle); ctx.lineWidth = itemOrDefault(legendItem.lineWidth, lineDefault.borderWidth); ctx.strokeStyle = itemOrDefault(legendItem.strokeStyle, globalDefault.defaultColor); var isLineWidthZero = (itemOrDefault(legendItem.lineWidth, lineDefault.borderWidth) === 0); if (ctx.setLineDash) { // IE 9 and 10 do not support line dash ctx.setLineDash(itemOrDefault(legendItem.lineDash, lineDefault.borderDash)); } if (opts.labels && opts.labels.usePointStyle) { // Recalulate x and y for drawPoint() because its expecting // x and y to be center of figure (instead of top left) var radius = fontSize * Math.SQRT2 / 2; var offSet = radius / Math.SQRT2; var centerX = x + offSet; var centerY = y + offSet; // Draw pointStyle as legend symbol Chart.canvasHelpers.drawPoint(ctx, legendItem.pointStyle, radius, centerX, centerY); } else { // Draw box as legend symbol if (!isLineWidthZero) { ctx.strokeRect(x, y, boxWidth, fontSize); } ctx.fillRect(x, y, boxWidth, fontSize); } ctx.restore(); }; var fillText = function(x, y, legendItem, textWidth) { ctx.fillText(legendItem.text, boxWidth + (fontSize / 2) + x, y); if (legendItem.hidden) { // Strikethrough the text if hidden ctx.beginPath(); ctx.lineWidth = 2; ctx.moveTo(boxWidth + (fontSize / 2) + x, y + (fontSize / 2)); ctx.lineTo(boxWidth + (fontSize / 2) + x + textWidth, y + (fontSize / 2)); ctx.stroke(); } }; // Horizontal var isHorizontal = me.isHorizontal(); if (isHorizontal) { cursor = { x: me.left + ((legendWidth - lineWidths[0]) / 2), y: me.top + labelOpts.padding, line: 0 }; } else { cursor = { x: me.left + labelOpts.padding, y: me.top + labelOpts.padding, line: 0 }; } var itemHeight = fontSize + labelOpts.padding; helpers.each(me.legendItems, function(legendItem, i) { var textWidth = ctx.measureText(legendItem.text).width, width = boxWidth + (fontSize / 2) + textWidth, x = cursor.x, y = cursor.y; if (isHorizontal) { if (x + width >= legendWidth) { y = cursor.y += itemHeight; cursor.line++; x = cursor.x = me.left + ((legendWidth - lineWidths[cursor.line]) / 2); } } else if (y + itemHeight > me.bottom) { x = cursor.x = x + me.columnWidths[cursor.line] + labelOpts.padding; y = cursor.y = me.top; cursor.line++; } drawLegendBox(x, y, legendItem); hitboxes[i].left = x; hitboxes[i].top = y; // Fill the actual label fillText(x, y, legendItem, textWidth); if (isHorizontal) { cursor.x += width + (labelOpts.padding); } else { cursor.y += itemHeight; } }); } }, /** * Handle an event * @private * @param e {Event} the event to handle * @return {Boolean} true if a change occured */ handleEvent: function(e) { var me = this; var opts = me.options; var type = e.type === 'mouseup' ? 'click' : e.type; var changed = false; if (type === 'mousemove') { if (!opts.onHover) { return; } } else if (type === 'click') { if (!opts.onClick) { return; } } else { return; } var position = helpers.getRelativePosition(e, me.chart.chart), x = position.x, y = position.y; if (x >= me.left && x <= me.right && y >= me.top && y <= me.bottom) { // See if we are touching one of the dataset boxes var lh = me.legendHitBoxes; for (var i = 0; i < lh.length; ++i) { var hitBox = lh[i]; if (x >= hitBox.left && x <= hitBox.left + hitBox.width && y >= hitBox.top && y <= hitBox.top + hitBox.height) { // Touching an element if (type === 'click') { opts.onClick.call(me, e, me.legendItems[i]); changed = true; break; } else if (type === 'mousemove') { opts.onHover.call(me, e, me.legendItems[i]); changed = true; break; } } } } return changed; } }); // Register the legend plugin Chart.plugins.register({ beforeInit: function(chartInstance) { var opts = chartInstance.options; var legendOpts = opts.legend; if (legendOpts) { chartInstance.legend = new Chart.Legend({ ctx: chartInstance.chart.ctx, options: legendOpts, chart: chartInstance }); Chart.layoutService.addBox(chartInstance, chartInstance.legend); } } }); };
Brasmid/servicedesk-metal
core/chart.js/src/core/core.legend.js
JavaScript
gpl-3.0
13,996
(function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['../ApiClient'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. module.exports = factory(require('../ApiClient')); } else { // Browser globals (root is window) if (!root.NetRobotsApi) { root.NetRobotsApi = {}; } root.NetRobotsApi.ScanCommand = factory(root.NetRobotsApi.ApiClient); } }(this, function(ApiClient) { 'use strict'; /** * The ScanCommand model module. * @module model/ScanCommand * @version 2.0.0 */ /** * Constructs a new <code>ScanCommand</code>. * @alias module:model/ScanCommand * @class * @param direction * @param semiaperture */ var exports = function(direction, semiaperture) { this['direction'] = direction; this['semiaperture'] = semiaperture; }; /** * Constructs a <code>ScanCommand</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/ScanCommand} obj Optional instance to populate. * @return {module:model/ScanCommand} The populated <code>ScanCommand</code> instance. */ exports.constructFromObject = function(data, obj) { if (data) { obj = obj || new exports(); if (data.hasOwnProperty('direction')) { obj['direction'] = ApiClient.convertToType(data['direction'], 'Number'); } if (data.hasOwnProperty('semiaperture')) { obj['semiaperture'] = ApiClient.convertToType(data['semiaperture'], 'Number'); } } return obj; } /** * Direction expressed in degrees. 0 degree is EAST, 90 degree is NORTH, 180 degree is WEST, 270 degree is SOUTH * @member {Number} direction */ exports.prototype['direction'] = undefined; /** * The aperture angle, in degree, divided by 2. * @member {Number} semiaperture */ exports.prototype['semiaperture'] = undefined; return exports; }));
massimo-zaniboni/netrobots
robot_examples/javascript/rest_api/src/model/ScanCommand.js
JavaScript
gpl-3.0
2,266
reminder.factory("ReminderSchedule", ["$resource", "Config", function($resource, Config){ var ScheduleModel = $resource( Config.host + "projects/:project_id/reminder_schedules/:id", null, { update: { method: 'PUT' }, create: { method: 'POST'} }); // custom method for Schedule resource ScheduleModel.prototype.toParams = function(){ var _self = this; if(_self.hasConditions()) _self.conditions[0].operator = "=" return { reminder_schedule: { project_id: _self.project_id, reminder_group_id: _self.reminder_group_id, reminder_channels_attributes: _self.reminder_channels.map(function(reminder_channel){ return {id: reminder_channel.id, channel_id: reminder_channel.channel_id} }), call_flow_id: _self.call_flow_id, client_start_date: _self.client_start_date.strftime(Config.dateFormat), time_from: _self.time_from, time_to: _self.time_to, conditions: _self.conditions, retries: _self.retries_in_hours ? 1 : 0, retries_in_hours: _self.retries_in_hours, schedule_type: _self.schedule_type } } } ScheduleModel.prototype.findGroupIn = function(groups){ var _self = this; return groups.findElement(_self.group_id, function(groupId, group) { return group.id == groupId; }); } ScheduleModel.prototype.findCallFlowIn = function(callFlows){ var _self = this; return callFlows.findElement(_self.call_flow_id, function(callFlowId, callFlow) { return callFlow.id == callFlowId; }); } ScheduleModel.prototype.channelsAsText = function(channels){ var results = this.reminder_channels.map(function(reminderChannel){ var channel = channels.findElement(reminderChannel, function(reminderChannel, channel){ return reminderChannel.channel_id == channel.id; }) return channel.name }); return results.join(", ") }; ScheduleModel.prototype.hasConditions = function(){ return this.conditions.length > 0 } return ScheduleModel; }])
channainfo/reminder
app/assets/javascripts/reminder/services/reminder_schedule.js
JavaScript
gpl-3.0
2,088
/** * This file is part of the MailWizz EMA application. * * @package MailWizz EMA * @subpackage Payment Gateway Paypal * @author Serban George Cristian <cristian.serban@mailwizz.com> * @link http://www.mailwizz.com/ * @copyright 2013-2016 MailWizz EMA (http://www.mailwizz.com) * @license http://www.mailwizz.com/license/ * @since 1.0 */ jQuery(document).ready(function($){ var ajaxData = {}; if ($('meta[name=csrf-token-name]').length && $('meta[name=csrf-token-value]').length) { var csrfTokenName = $('meta[name=csrf-token-name]').attr('content'); var csrfTokenValue = $('meta[name=csrf-token-value]').attr('content'); ajaxData[csrfTokenName] = csrfTokenValue; } $('#paypal-hidden-form').on('submit', function(){ var $this = $(this); if ($this.data('submit')) { return true; } if ($this.data('ajaxRunning')) { return false; } $this.data('ajaxRunning', true); $.post($this.data('order'), $this.serialize(), function(json){ $this.data('ajaxRunning', false); if (json.status == 'error') { notify.remove().addError(json.message).show(); } else { $this.data('submit', true).submit(); } }, 'json'); return false; }); });
fwahyudi17/ofiskita
image/mailwizz/apps/common/extensions/payment-gateway-paypal/assets/customer/js/payment-form.js
JavaScript
gpl-3.0
1,333
/// <reference path="../typings/angularjs/angular.d.ts" /> // Install the angularjs.TypeScript.DefinitelyTyped NuGet package var App; (function (App) { "use strict"; // Create the module and define its dependencies. angular.module("app", []); })(App || (App = {}));
chan4lk/SharePoint-RestAPI
SupplierSystem/Scripts/app/app.module.js
JavaScript
gpl-3.0
279
'use strict'; var unit = { GCD: function GCD(a, b) { if (a == b && a == 0) { return 'NaN'; } else if (a / Math.floor(a) != 1 || b / Math.floor(b) != 1) { return 'undefined'; } else if (a / Math.floor(a) == 1 && b / Math.floor(b) == 1 && a != 0 && b != 0) { a = Math.abs(a); b = Math.abs(b); while (a && b) { a >= b ? a %= b : b %= a; }return a || b; } }, factor: function factor(n) { if (n / Math.floor(n) == 1 && n > 1) { var j = 0; var i = 2; var a = new Array(); do { if (n % i == 0) { a[j] = i; j++; n = n / i; } else { i++; } } while (i < n); a[j] = i; var res = {}; a.forEach(function (e) { res[e] = 1 + ~ ~res[e]; }); return a; } else { return 'Null'; } }, sort: function sort(array) { var count = array.length - 1; for (var i = 0; i < count; i++) { for (var j = 0; j < count - i; j++) { if (array[j] > array[j + 1]) { var max = array[j]; array[j] = array[j + 1]; array[j + 1] = max; } } }return array; } }; module.exports = unit; //unit.GCD(0.6,0.8); //unit.factor(12); //unit.sort();
AiJD/labs
JS/lab20-21/build/js/script.js
JavaScript
gpl-3.0
1,578
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ // Note that these are webpack requires, not CommonJS node requiring requires const React = require('react') const ImmutableComponent = require('../../../../js/components/immutableComponent') const {l10nErrorText} = require('../../../common/lib/httpUtil') const aboutActions = require('../../../../js/about/aboutActions') const getSetting = require('../../../../js/settings').getSetting const settings = require('../../../../js/constants/settings') const ModalOverlay = require('../../../../js/components/modalOverlay') const coinbaseCountries = require('../../../../js/constants/coinbaseCountries') const moment = require('moment') moment.locale(navigator.language) // Components const Button = require('../../../../js/components/button') const {FormTextbox, RecoveryKeyTextbox} = require('../textbox') const {FormDropdown, SettingDropdown} = require('../dropdown') class PaymentsTab extends ImmutableComponent { constructor () { super() this.state = { FirstRecoveryKey: '', SecondRecoveryKey: '' } this.printKeys = this.printKeys.bind(this) this.saveKeys = this.saveKeys.bind(this) this.createWallet = this.createWallet.bind(this) this.recoverWallet = this.recoverWallet.bind(this) this.handleFirstRecoveryKeyChange = this.handleFirstRecoveryKeyChange.bind(this) this.handleSecondRecoveryKeyChange = this.handleSecondRecoveryKeyChange.bind(this) } createWallet () { if (!this.props.ledgerData.get('created')) { aboutActions.createWallet() } } handleFirstRecoveryKeyChange (e) { this.setState({FirstRecoveryKey: e.target.value}) } handleSecondRecoveryKeyChange (e) { this.setState({SecondRecoveryKey: e.target.value}) } recoverWallet () { aboutActions.ledgerRecoverWallet(this.state.FirstRecoveryKey, this.state.SecondRecoveryKey) } recoverWalletFromFile () { aboutActions.ledgerRecoverWalletFromFile() } copyToClipboard (text) { aboutActions.setClipboard(text) } generateKeyFile (backupAction) { aboutActions.ledgerGenerateKeyFile(backupAction) } clearRecoveryStatus () { aboutActions.clearRecoveryStatus() this.props.hideAdvancedOverlays() } printKeys () { this.generateKeyFile('print') } saveKeys () { this.generateKeyFile('save') } get enabled () { return getSetting(settings.PAYMENTS_ENABLED, this.props.settings) } get fundsAmount () { if (!this.props.ledgerData.get('created')) { return null } return <div className='balance'> { !(this.props.ledgerData.get('balance') === undefined || this.props.ledgerData.get('balance') === null) ? <FormTextbox data-test-id='fundsAmount' readOnly value={this.btcToCurrencyString(this.props.ledgerData.get('balance'))} /> : <span><span data-test-id='accountBalanceLoading' data-l10n-id='accountBalanceLoading' /></span> } <a href='https://brave.com/Payments_FAQ.html' target='_blank'> <span className='fa fa-question-circle fundsFAQ' /> </a> </div> } get walletButton () { const buttonText = this.props.ledgerData.get('created') ? 'addFundsTitle' : (this.props.ledgerData.get('creating') ? 'creatingWallet' : 'createWallet') const onButtonClick = this.props.ledgerData.get('created') ? this.props.showOverlay.bind(this, 'addFunds') : (this.props.ledgerData.get('creating') ? () => {} : this.createWallet) return <Button data-test-id={buttonText} l10nId={buttonText} className='primaryButton addFunds' onClick={onButtonClick.bind(this)} disabled={this.props.ledgerData.get('creating')} /> } get paymentHistoryButton () { const walletCreated = this.props.ledgerData.get('created') && !this.props.ledgerData.get('creating') const walletTransactions = this.props.ledgerData.get('transactions') const walletHasTransactions = walletTransactions && walletTransactions.size let buttonText if ((!walletCreated) || (!this.nextReconcileDate)) { return null } else if (!walletHasTransactions) { buttonText = 'noPaymentHistory' } else { buttonText = 'viewPaymentHistory' } const l10nDataArgs = { reconcileDate: this.nextReconcileDate } const onButtonClick = this.props.showOverlay.bind(this, 'paymentHistory') return <Button className='paymentHistoryButton' l10nId={buttonText} l10nArgs={l10nDataArgs} onClick={onButtonClick.bind(this)} disabled={this.props.ledgerData.get('creating')} /> } get walletStatus () { const ledgerData = this.props.ledgerData let status = {} if (ledgerData.get('error')) { status.id = 'statusOnError' } else if (ledgerData.get('created')) { const transactions = ledgerData.get('transactions') const pendingFunds = Number(ledgerData.get('unconfirmed') || 0) if (pendingFunds + Number(ledgerData.get('balance') || 0) < 0.9 * Number(ledgerData.get('btc') || 0)) { status.id = 'insufficientFundsStatus' } else if (pendingFunds > 0) { status.id = 'pendingFundsStatus' status.args = {funds: this.btcToCurrencyString(pendingFunds)} } else if (transactions && transactions.size > 0) { status.id = 'defaultWalletStatus' } else { status.id = 'createdWalletStatus' } } else if (ledgerData.get('creating')) { status.id = 'creatingWalletStatus' } else { status.id = 'createWalletStatus' } return status } get tableContent () { const {LedgerTable} = require('../../../../js/about/preferences') // TODO: This should be sortable. #2497 return <LedgerTable ledgerData={this.props.ledgerData} settings={this.props.settings} onChangeSetting={this.props.onChangeSetting} siteSettings={this.props.siteSettings} /> } get overlayTitle () { if (coinbaseCountries.indexOf(this.props.ledgerData.get('countryCode')) > -1) { return 'addFunds' } else { return 'addFundsAlternate' } } get overlayContent () { const {BitcoinDashboard} = require('../../../../js/about/preferences') return <BitcoinDashboard ledgerData={this.props.ledgerData} settings={this.props.settings} bitcoinOverlayVisible={this.props.bitcoinOverlayVisible} qrcodeOverlayVisible={this.props.qrcodeOverlayVisible} showOverlay={this.props.showOverlay.bind(this, 'bitcoin')} hideOverlay={this.props.hideOverlay.bind(this, 'bitcoin')} showQRcode={this.props.showOverlay.bind(this, 'qrcode')} hideQRcode={this.props.hideOverlay.bind(this, 'qrcode')} hideParentOverlay={this.props.hideOverlay.bind(this, 'addFunds')} /> } get paymentHistoryContent () { const {PaymentHistory} = require('../../../../js/about/preferences') return <PaymentHistory ledgerData={this.props.ledgerData} /> } get paymentHistoryFooter () { let ledgerData = this.props.ledgerData if (!ledgerData.get('reconcileStamp')) { return null } const timestamp = ledgerData.get('reconcileStamp') const now = new Date().getTime() let l10nDataId = 'paymentHistoryFooterText' if (timestamp <= now) { l10nDataId = (timestamp <= (now - (24 * 60 * 60 * 1000))) ? 'paymentHistoryOverdueFooterText' : 'paymentHistoryDueFooterText' } const nextReconcileDateRelative = formattedTimeFromNow(timestamp) const l10nDataArgs = { reconcileDate: nextReconcileDateRelative } return <div className='paymentHistoryFooter'> <div className='nextPaymentSubmission'> <span data-l10n-id={l10nDataId} data-l10n-args={JSON.stringify(l10nDataArgs)} /> </div> <Button l10nId='paymentHistoryOKText' className='okButton primaryButton' onClick={this.props.hideOverlay.bind(this, 'paymentHistory')} /> </div> } get advancedSettingsContent () { const minDuration = this.props.ledgerData.getIn(['synopsisOptions', 'minDuration']) const minPublisherVisits = this.props.ledgerData.getIn(['synopsisOptions', 'minPublisherVisits']) const {SettingsList, SettingItem, SettingCheckbox, changeSetting} = require('../../../../js/about/preferences') return <div className='board'> <div className='panel advancedSettings'> <div className='settingsPanelDivider'> <div className='minimumPageTimeSetting' data-l10n-id='minimumPageTimeSetting' /> <SettingsList> <SettingItem> <SettingDropdown data-test-id='durationSelector' defaultValue={minDuration || 8000} onChange={changeSetting.bind(null, this.props.onChangeSetting, settings.MINIMUM_VISIT_TIME)}>> <option value='5000'>5 seconds</option> <option value='8000'>8 seconds</option> <option value='60000'>1 minute</option> </SettingDropdown> </SettingItem> </SettingsList> <div className='minimumVisitsSetting' data-l10n-id='minimumVisitsSetting' /> <SettingsList> <SettingItem> <SettingDropdown data-test-id='visitSelector' defaultValue={minPublisherVisits || 1} onChange={changeSetting.bind(null, this.props.onChangeSetting, settings.MINIMUM_VISITS)}>>> <option value='1'>1 visits</option> <option value='5'>5 visits</option> <option value='10'>10 visits</option> </SettingDropdown> </SettingItem> </SettingsList> </div> <div className='settingsPanelDivider'> {this.enabled ? <SettingsList> <SettingCheckbox dataL10nId='minimumPercentage' prefKey={settings.MINIMUM_PERCENTAGE} settings={this.props.settings} onChangeSetting={this.props.onChangeSetting} /> <SettingCheckbox dataL10nId='notifications' prefKey={settings.PAYMENTS_NOTIFICATIONS} settings={this.props.settings} onChangeSetting={this.props.onChangeSetting} /> </SettingsList> : null} </div> </div> </div> } get advancedSettingsFooter () { return <div className='panel advancedSettingsFooter'> <Button l10nId='backupLedger' className='primaryButton' onClick={this.props.showOverlay.bind(this, 'ledgerBackup')} /> <Button l10nId='recoverLedger' className='primaryButton' onClick={this.props.showOverlay.bind(this, 'ledgerRecovery')} /> <Button l10nId='done' className='whiteButton inlineButton' onClick={this.props.hideOverlay.bind(this, 'advancedSettings')} /> </div> } get ledgerBackupContent () { const paymentId = this.props.ledgerData.get('paymentId') const passphrase = this.props.ledgerData.get('passphrase') return <div className='board'> <div className='panel ledgerBackupContent'> <span data-l10n-id='ledgerBackupContent' /> <div className='copyKeyContainer'> <div className='copyContainer'> <Button l10nId='copy' className='copyButton whiteButton' onClick={this.copyToClipboard.bind(this, paymentId)} /> </div> <div className='keyContainer'> <h3 data-l10n-id='firstKey' /> <span>{paymentId}</span> </div> </div> <div className='copyKeyContainer'> <div className='copyContainer'> <Button l10nId='copy' className='copyButton whiteButton' onClick={this.copyToClipboard.bind(this, passphrase)} /> </div> <div className='keyContainer'> <h3 data-l10n-id='secondKey' /> <span>{passphrase}</span> </div> </div> </div> </div> } get ledgerBackupFooter () { return <div className='panel advancedSettingsFooter'> <Button l10nId='printKeys' className='primaryButton' onClick={this.printKeys} /> <Button l10nId='saveRecoveryFile' className='primaryButton' onClick={this.saveKeys} /> <Button l10nId='done' className='whiteButton inlineButton' onClick={this.props.hideOverlay.bind(this, 'ledgerBackup')} /> </div> } get ledgerRecoveryContent () { const {SettingsList, SettingItem} = require('../../../../js/about/preferences') const l10nDataArgs = { balance: this.btcToCurrencyString(this.props.ledgerData.get('balance')) } const recoverySucceeded = this.props.ledgerData.get('recoverySucceeded') const recoveryError = this.props.ledgerData.getIn(['error', 'error']) const isNetworkError = typeof recoveryError === 'object' return <div className='board'> { recoverySucceeded === true ? <div className='recoveryOverlay'> <h1 data-l10n-id='ledgerRecoverySucceeded' /> <p className='spaceAround' data-l10n-id='balanceRecovered' data-l10n-args={JSON.stringify(l10nDataArgs)} /> <Button l10nId='ok' className='whiteButton inlineButton' onClick={this.clearRecoveryStatus.bind(this)} /> </div> : null } { (recoverySucceeded === false && recoveryError && isNetworkError) ? <div className='recoveryOverlay'> <h1 data-l10n-id='ledgerRecoveryNetworkFailedTitle' className='recoveryError' /> <p data-l10n-id='ledgerRecoveryNetworkFailedMessage' className='spaceAround' /> <Button l10nId='ok' className='whiteButton inlineButton' onClick={this.clearRecoveryStatus.bind(this)} /> </div> : null } { (recoverySucceeded === false && recoveryError && !isNetworkError) ? <div className='recoveryOverlay'> <h1 data-l10n-id='ledgerRecoveryFailedTitle' /> <p data-l10n-id='ledgerRecoveryFailedMessage' className='spaceAround' /> <Button l10nId='ok' className='whiteButton inlineButton' onClick={this.clearRecoveryStatus.bind(this)} /> </div> : null } <div className='panel recoveryContent'> <h4 data-l10n-id='ledgerRecoverySubtitle' /> <div className='ledgerRecoveryContent' data-l10n-id='ledgerRecoveryContent' /> <SettingsList> <SettingItem> <h3 data-l10n-id='firstRecoveryKey' /> <RecoveryKeyTextbox id='firstRecoveryKey' onChange={this.handleFirstRecoveryKeyChange} /> <h3 data-l10n-id='secondRecoveryKey' /> <RecoveryKeyTextbox id='secondRecoveryKey' onChange={this.handleSecondRecoveryKeyChange} /> </SettingItem> </SettingsList> </div> </div> } get ledgerRecoveryFooter () { return <div className='panel advancedSettingsFooter'> <div className='recoveryFooterButtons'> <Button l10nId='recover' className='primaryButton' onClick={this.recoverWallet} /> <Button l10nId='recoverFromFile' className='primaryButton' onClick={this.recoverWalletFromFile} /> <Button l10nId='cancel' className='whiteButton' onClick={this.props.hideOverlay.bind(this, 'ledgerRecovery')} /> </div> </div> } get nextReconcileDate () { const ledgerData = this.props.ledgerData if ((ledgerData.get('error')) || (!ledgerData.get('reconcileStamp'))) { return null } const timestamp = ledgerData.get('reconcileStamp') return formattedTimeFromNow(timestamp) } get nextReconcileMessage () { const ledgerData = this.props.ledgerData const nextReconcileDateRelative = this.nextReconcileDate if (!nextReconcileDateRelative) { return null } const timestamp = ledgerData.get('reconcileStamp') const now = new Date().getTime() let l10nDataId = 'statusNextReconcileDate' if (timestamp <= now) { l10nDataId = (timestamp <= (now - (24 * 60 * 60 * 1000))) ? 'paymentHistoryOverdueFooterText' : 'statusNextReconcileToday' } const l10nDataArgs = { reconcileDate: nextReconcileDateRelative } return <div className='nextReconcileDate' data-l10n-args={JSON.stringify(l10nDataArgs)} data-l10n-id={l10nDataId} /> } get ledgerDataErrorText () { const ledgerError = this.props.ledgerData.get('error') if (!ledgerError) { return null } // 'error' here is a chromium webRequest error as returned by request.js const errorCode = ledgerError.get('error').get('errorCode') return l10nErrorText(errorCode) } btcToCurrencyString (btc) { const balance = Number(btc || 0) const currency = this.props.ledgerData.get('currency') || 'USD' if (balance === 0) { return `0 ${currency}` } if (this.props.ledgerData.get('btc') && typeof this.props.ledgerData.get('amount') === 'number') { const btcValue = this.props.ledgerData.get('btc') / this.props.ledgerData.get('amount') const fiatValue = (balance / btcValue).toFixed(2) let roundedValue = Math.floor(fiatValue) const diff = fiatValue - roundedValue if (diff > 0.74) roundedValue += 0.75 else if (diff > 0.49) roundedValue += 0.50 else if (diff > 0.24) roundedValue += 0.25 return `${roundedValue.toFixed(2)} ${currency}` } return `${balance} BTC` } get disabledContent () { return <div className='disabledContent'> <div className='paymentsMessage'> <h3 data-l10n-id='paymentsWelcomeTitle' /> <div data-l10n-id='paymentsWelcomeText1' /> <div className='boldText' data-l10n-id='paymentsWelcomeText2' /> <div data-l10n-id='paymentsWelcomeText3' /> <div data-l10n-id='paymentsWelcomeText4' /> <div data-l10n-id='paymentsWelcomeText5' /> <div> <span data-l10n-id='paymentsWelcomeText6' />&nbsp; <a href='https://brave.com/Payments_FAQ.html' target='_blank' data-l10n-id='paymentsWelcomeLink' />&nbsp; <span data-l10n-id='paymentsWelcomeText7' /> </div> </div> <div className='paymentsSidebar'> <h2 data-l10n-id='paymentsSidebarText1' /> <div data-l10n-id='paymentsSidebarText2' /> <a href='https://www.privateinternetaccess.com/' target='_blank'><div className='paymentsSidebarPIA' /></a> <div data-l10n-id='paymentsSidebarText3' /> <a href='https://www.bitgo.com/' target='_blank'><div className='paymentsSidebarBitgo' /></a> <div data-l10n-id='paymentsSidebarText4' /> <a href='https://www.coinbase.com/' target='_blank'><div className='paymentsSidebarCoinbase' /></a> </div> </div> } get enabledContent () { const {SettingsList, SettingItem, changeSetting} = require('../../../../js/about/preferences') // TODO: report when funds are too low // TODO: support non-USD currency return <div> <div className='walletBar'> <table> <thead> <tr> <th data-l10n-id='monthlyBudget' /> <th data-l10n-id='accountBalance' /> <th data-l10n-id='status' /> </tr> </thead> <tbody> <tr> <td> <SettingsList> <SettingItem> <FormDropdown data-test-id='fundsSelectBox' value={getSetting(settings.PAYMENTS_CONTRIBUTION_AMOUNT, this.props.settings)} onChange={changeSetting.bind(null, this.props.onChangeSetting, settings.PAYMENTS_CONTRIBUTION_AMOUNT)}> { [5, 10, 15, 20].map((amount) => <option value={amount}>{amount} {this.props.ledgerData.get('currency') || 'USD'}</option> ) } </FormDropdown> </SettingItem> <SettingItem> {this.paymentHistoryButton} </SettingItem> </SettingsList> </td> <td> { this.props.ledgerData.get('error') && this.props.ledgerData.get('error').get('caller') === 'getWalletProperties' ? <div> <div data-l10n-id='accountBalanceConnectionError' /> <div className='accountBalanceError' data-l10n-id={this.ledgerDataErrorText} /> </div> : <div> <SettingsList> <SettingItem> {this.fundsAmount} {this.walletButton} </SettingItem> </SettingsList> </div> } </td> <td> <div className='walletStatus' data-l10n-id={this.walletStatus.id} data-l10n-args={this.walletStatus.args ? JSON.stringify(this.walletStatus.args) : null} /> {this.nextReconcileMessage} </td> </tr> </tbody> </table> </div> {this.tableContent} </div> } render () { const {SettingCheckbox} = require('../../../../js/about/preferences') return <div className='paymentsContainer'> { this.enabled && this.props.addFundsOverlayVisible ? <ModalOverlay title={this.overlayTitle} content={this.overlayContent} onHide={this.props.hideOverlay.bind(this, 'addFunds')} /> : null } { this.enabled && this.props.paymentHistoryOverlayVisible ? <ModalOverlay title={'paymentHistoryTitle'} customTitleClasses={'paymentHistory'} content={this.paymentHistoryContent} footer={this.paymentHistoryFooter} onHide={this.props.hideOverlay.bind(this, 'paymentHistory')} /> : null } { this.enabled && this.props.advancedSettingsOverlayVisible ? <ModalOverlay title={'advancedSettingsTitle'} content={this.advancedSettingsContent} footer={this.advancedSettingsFooter} onHide={this.props.hideOverlay.bind(this, 'advancedSettings')} /> : null } { this.enabled && this.props.ledgerBackupOverlayVisible ? <ModalOverlay title={'ledgerBackupTitle'} content={this.ledgerBackupContent} footer={this.ledgerBackupFooter} onHide={this.props.hideOverlay.bind(this, 'ledgerBackup')} /> : null } { this.enabled && this.props.ledgerRecoveryOverlayVisible ? <ModalOverlay title={'ledgerRecoveryTitle'} content={this.ledgerRecoveryContent} footer={this.ledgerRecoveryFooter} onHide={this.props.hideOverlay.bind(this, 'ledgerRecovery')} /> : null } <div className='advancedSettingsWrapper'> { this.props.ledgerData.get('created') && this.enabled ? <Button l10nId='advancedSettings' className='advancedSettings whiteButton' onClick={this.props.showOverlay.bind(this, 'advancedSettings')} /> : null } </div> <div className='titleBar'> <div className='sectionTitleWrapper pull-left'> <span className='sectionTitle'>Brave Payments</span> <span className='sectionSubTitle'>beta</span> </div> <div className='paymentsSwitches'> <div className='enablePaymentsSwitch'> <span data-l10n-id='off' /> <SettingCheckbox dataL10nId='on' prefKey={settings.PAYMENTS_ENABLED} settings={this.props.settings} onChangeSetting={this.props.onChangeSetting} /> </div> { this.props.ledgerData.get('created') && this.enabled ? <div className='autoSuggestSwitch'> <SettingCheckbox dataL10nId='autoSuggestSites' prefKey={settings.AUTO_SUGGEST_SITES} settings={this.props.settings} onChangeSetting={this.props.onChangeSetting} /> <a className='moreInfoBtn fa fa-question-circle' href='https://brave.com/Payments_FAQ.html' target='_blank' data-l10n-id='paymentsFAQLink' /> </div> : null } </div> </div> { this.enabled ? this.enabledContent : this.disabledContent } </div> } } function formattedTimeFromNow (timestamp) { return moment(new Date(timestamp)).fromNow() } module.exports = PaymentsTab
darkdh/browser-laptop
app/renderer/components/preferences/paymentsTab.js
JavaScript
mpl-2.0
24,496
export default 'svg mock';
SphinxKnight/kuma
kuma/javascript/src/__mocks__/mockSvg.js
JavaScript
mpl-2.0
27
var spawn = require('child_process').spawn; var Promise = require('es6-promises'); function _task(args) { args = args || []; return new Promise(function(resolve, reject) { var tw = spawn('task', args); var stdout = ''; var stderr = ''; tw.stdout.on('data', function(data) { stdout += data.toString(); }); tw.stderr.on('data', function(data) { stderr += data.toString(); }); tw.on('close', function(code) { var data = { code: code, stdout: stdout, stderr: stderr, }; if (code === 0) { resolve(data); } else { reject(data); } }); tw.on('error', function(err) { reject(err); }); }); } function addTask(opts) { if (!('description' in opts)) { throw new Error('No description given for task.'); } var args = ['add']; for (var key in opts) { if (!opts.hasOwnProperty(key)) { continue; } args.push(key + ':' + opts[key]); } return _task(args) .then(function(data) { var match = data.stdout.match(/Created task (\d+)\./); if (match) { var id = match[1]; return new Task(id); } else { throw new Error('Unknown output "' + data.stdout + '".'); } }); } function Task(id) { this.id = id; } module.exports = { addTask: addTask, };
mythmon/bug-task
lib/taskwarrior.js
JavaScript
mpl-2.0
1,343
var Stream = require('stream').Stream, _u = require('underscore'); /** * A hacked querystream formatter which formats the output * as a json literal. Not production quality. */ function ArrayFormatter() { Stream.call(this); this.writable = true; this._done = false; this.meta = {}; } ArrayFormatter.prototype.__proto__ = Stream.prototype; ArrayFormatter.prototype.write = function (doc) { if (!this._hasWritten) { this._hasWritten = true; // open an object literal / array string along with the doc this.emit('data', '{ "results": [' + JSON.stringify(doc)); } else { this.emit('data', ',' + JSON.stringify(doc)); } return true; } ArrayFormatter.prototype.end = ArrayFormatter.prototype.destroy = function () { if (this._done) return; this._done = true; var str = ']'; if (this.total) str += ',"total":' + this.total; if (this.totalFiltered) str += ',"totalFiltered":' + this.totalFiltered; str += "}"; // close the object literal / array this.emit('data', str); // done this.emit('end'); } module.exports.ArrayFormatter = ArrayFormatter; function StreamTransformer(transformers) { Stream.call(this); this.writable = true; this._done = false; this.transformers = transformers || []; } StreamTransformer.prototype.__proto__ = Stream.prototype; StreamTransformer.prototype.write = function (doc) { var result = doc; this.transformers.some(function (v, k) { result = v.call(null, result) return result == null; }); if (result != null) this.emit('data', result); return true; } StreamTransformer.prototype.end = StreamTransformer.prototype.destroy = function () { if (this._done) return; this._done = true; // done this.emit('end'); } module.exports.StreamTransformer = StreamTransformer; function BufferedJSONStream(meta, single) { Stream.call(this); this.response = _u.extend({payload:[], status:0}, meta); this.writable = true; this._done = false; this._single = single; } BufferedJSONStream.prototype.__proto__ = Stream.prototype; BufferedJSONStream.prototype.asCallback = function (tostream) { return function (err, obj) { if (err) { this.response.error = err; this.status = 1; } else this.response.payload = obj; this.pipe(tostream); tostream.contentType('json'); this.end(); }.bind(this); } BufferedJSONStream.prototype.write = function (doc) { this.response.payload.push(doc); return true; } BufferedJSONStream.prototype.format = function (data) { return JSON.stringify(this.response); } BufferedJSONStream.prototype.end = BufferedJSONStream.prototype.destroy = function () { if (this._done) return; this._done = true; var payload = this.response.payload; if (payload) { var isArray = Array.isArray(payload) if (this._single == true || this._single == 'true' ) { if (isArray) { this.response.payload = payload.length ? payload[0] : null; } } } //emit the response this.emit('data', this.format(this.response)); // done this.emit('end'); } module.exports.BufferedJSONStream = BufferedJSONStream; module.exports.run = function (meta, tostream) { if (!tostream) { tostream = meta; meta = {}; } return new BufferedJSONStream(meta).asCallback(tostream); } function CallbackStream(callback) { Stream.call(this); this.writable = true; this._done = false this._callback = callback; process.nextTick(this._call.bind(this)); } CallbackStream.prototype.__proto__ = Stream.prototype; CallbackStream.prototype._call = function(){ if (this._callback) this._callback(this.asCallback()); } CallbackStream.prototype.write = function (doc) { this.emit('data', doc); return true; } CallbackStream.prototype.stream = function () { return this; } CallbackStream.prototype.asCallback = function () { return function (err, obj) { if (err) { this.emit('error', err); } else { if (Array.isArray(obj)) obj.forEach(this.write, this); else this.write(obj); } this.end(); }.bind(this); } CallbackStream.prototype.end = CallbackStream.prototype.destroy = function () { if (this._done) return; this._done = true; // done this.emit('end'); } module.exports.CallbackStream = CallbackStream;
adamlofting/menuplanner
node_modules/mers/lib/streams.js
JavaScript
mpl-2.0
4,622
const child_process = require('child_process'); const fs = require('fs'); const path = require('path'); child_process.execSync('npm run build'); const prefix = path.join('..', 'dist'); const json_string = fs.readFileSync(path.join(prefix, 'manifest.json')); const manifest = JSON.parse(json_string); const ios_filename = manifest['ios.js']; fs.writeFileSync( 'send-ios/assets/ios.js', fs.readFileSync(`${prefix}${ios_filename}`) ); const vendor_filename = manifest['vendor.js']; fs.writeFileSync( 'send-ios/assets/vendor.js', fs.readFileSync(`${prefix}${vendor_filename}`) );
mozilla/send
ios/generate-bundle.js
JavaScript
mpl-2.0
588
#!/usr/bin/env node // papi_keys_tojson.js // // TARGET PostgreSQL tags and source Moray tag definitions// // to json input var fs = require('fs'); var outstream = fs.createWriteStream("imgapi_keys.json", {flags : 'w' }); // Output filenames var f_db_RTT = "_s.json"; var f_db_LCT = "_r.json"; var f_db_HCT = "_m.json"; var db_RTT = "imgapi_images_s"; var db_LCT = "imgapi_images_r"; var db_HCT = "imgapi_images_m"; var pk_HCT = "_etag"; // The Primary Key of main table var keys_RTT = [ "error", "generate_passwords" ]; var keys_LCT = [ "activated", "cpu_type", "datacenter", "disabled", "disk_driver", "image_size", "nic_driver", "os", "public", "state", "type", "v" ]; var keys_HCT = [ // UIDs "uuid", "origin", "acl", "owner", // Timestamps "published_at", "expires_at", // Strings "name", "description", "version", "homepage", "urn", "billing_tags", // JSONB "tags", "users", "requirements", "files" ]; var keys_ALL = keys_RTT.concat(keys_LCT, keys_HCT); // ORIGIN PostgresQL DUMP TABLES // // MORAY STANDARD KEYS // These are the standard keys/columns in a Moray dump var keys_Moray = [ "_id", "_key", "_etag", "_mtime" ]; // MORAY CUSTOMIZED KEYS // These are all the custom keys added in code to the Moray dump // Any of these keys that match keys in HCT, LCT, RTT sets above // should be ignored as duplicates. // This duplicate matching is not yet automated. var keys_Moray_Custom = [ "_txn_snap", "_vnode", "uuid", "name", "version", "owner", "origin", "state", "urn", "tags", "bililng_tags", "acl", "activated", "disabled", "public", "os", "type", "expires_at" ]; // MORAY KEYS TO IGNORE // MUST APPEAR ON THE ABOVE LIST // These are all the custom keys added in code to the Moray dump // that should not appear (nor their values) in the output HCT. var keys_Moray_Custom_Ignore = [ "_txn_snap", "_vnode", // These are never populated as at 27 Aug 2014 "uuid", "name", "version", "owner", "origin", "state", "urn", "tags", "bililng_tags", "acl", "activated", "disabled", "public", "os", "type", "expires_at" ]; // JSON KEYS TO IGNORE // These are keys that are duplicates with mismatched names or deprecated // and not to be used in populating RTT/LCT/HCT var keys_Ignore = [ ]; var keys_LCT_top = [ "_r_id" ]; var keys_RTT_top = [ "_s_id", "_m_id", "_r_id", "tag", "value" ]; var keys_HCT_top = [ "_m_id", "_r_id" ]; var table_RTT = keys_RTT_top; var table_LCT = keys_LCT_top.concat(keys_LCT); function undupe(arr) { var i, len=arr.length, out=[], obj={}; for (i=0;i<len;i++) { obj[arr[i]]=0; } for (i in obj) { out.push(i); } return out; } // REMOVE keys_Moray_Custom_Ignore from keys_Moray_Custom function subtract(arr1, arr2) { var i; var j; var len1 = arr1.length; var len2 = arr2.length; var out=[]; var matched = false; for (i = 0; i < len1; i++) { matched = false; for (j = 0; j < len2; j++) { if (arr1[i] === arr2[j]) { matched = true; } } if (!matched) { out.push(arr1[i]); } } return out; } var keys_Moray_Custom_final = subtract(keys_Moray_Custom, keys_Moray_Custom_Ignore); var table_HCT_ = keys_HCT_top.concat(keys_Moray, keys_Moray_Custom_final, keys_HCT); var table_HCT = undupe(table_HCT_); var keys = { 'target' : { 'rtt' : keys_RTT, 'lct' : keys_LCT, 'hct' : keys_HCT, 'all' : keys_ALL }, 'source' : { 'moray' : keys_Moray, 'custom' : keys_Moray_Custom, 'custom-ignore' : keys_Moray_Custom_Ignore, 'ignore' : keys_Ignore }, 'tables' : { 'rtt' : table_RTT, 'lct' : table_LCT, 'hct' : table_HCT }, 'files' : { 'rtt' : f_db_RTT, 'lct' : f_db_LCT, 'hct' : f_db_HCT }, 'names' : { 'rtt' : db_RTT, 'lct' : db_LCT, 'hct' : db_HCT }, 'pk' : { 'hct' : pk_HCT } }; outstream.open(); var imgapi_json = JSON.stringify(keys); outstream.write(imgapi_json); //exports.keys = keys;
joyent/moray-etl-jsonb
lib/imgapi_keys_tojson.js
JavaScript
mpl-2.0
4,924
/* Copyright (c) 2016, Nebil Kawas García This source code is subject to the terms of the Mozilla Public License. You can obtain a copy of the MPL at <https://www.mozilla.org/MPL/2.0/>. snippet03.js -- Enter, update, exit */ // Definamos un nuevo _dataset_: los dígitos de pi. // var dataset = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]; // Definamos el ancho y la altura del elemento SVG. // var WIDTH = 800; // var HEIGHT = 500; // Definamos un nuevo contenedor, añadiendo una etiqueta <svg>. // Es importante inicializar ambas dimensiones: ancho y altura. // var container = d3.select('body') // .append('svg') // Añade elemento SVG, // .attr('width', WIDTH) // le ajusta su ancho, // .attr('height', HEIGHT); // y también su altura. // ============== // El ciclo de D3 // ============== // Este es uno de los conceptos esenciales que subyacen a D3. // El ciclo cuenta con tres fases: 'enter', 'update', 'exit'. // 'enter' // ======= // container.selectAll('rect') // Los elementos del documento -- DOM. // .data(dataset) // Los elementos de los datos. // .enter() // (¡El momento de la verdad!) // .append('rect') // Añade un <rect> por cada dato entrante. // .attr('width', 20) // .attr('height', 20) // // .attr('height', function(datum) { return datum * 30; }) // .attr('x', 10) // // .attr('x', function(datum, index) { return index * 50; }) // .attr('y', 10) // .attr('fill', 'maroon'); // Añadamos tres números al arreglo. // dataset.push(8); // dataset.push(9); // dataset.push(7); // console.log(dataset); // Con estas nuevas incorporaciones, apliquemos (casi) los mismos métodos. // La diferencia es que los elementos entrantes tendrán un color distinto. // container.selectAll('rect') // .data(dataset) // .enter() // .append('rect') // .attr('width', 20) // .attr('height', function(datum) { return datum * 30; }) // .attr('x', function(datum, index) { return index * 50; }) // .attr('y', 10) // .attr('fill', 'olive'); // 'exit' // ====== // Ahora, eliminemos dos datos. // dataset.pop(); // dataset.pop(); // console.log(dataset); // container.selectAll('rect') // Los elementos del documento -- DOM. // .data(dataset) // Los elementos de los datos. // .exit() // Toma el conjunto de salida. // .remove(); // Finalmente, borra sus elementos. // 'update' // ======== // La fase de 'update' no tiene un método asociado. // Al tener la misma cantidad de rectángulos como de datos, // sólo basta con aplicar los mismos atributos a cada ítem. // container.selectAll('rect') // .data(dataset) // .attr('width', 20) // .attr('height', function(datum) { return datum * 30; }) // .attr('x', function(datum, index) { return index * 50; }) // .attr('y', 10) // .attr('fill', 'navy');
nebil/d3js-demo
snippet03.js
JavaScript
mpl-2.0
3,069
(function() { "use strict"; var app = angular.module('RbsChangeApp'); function rbsCommercePaymentConnectorDeferred($http) { return { restrict: 'AE', scope: false, templateUrl: 'Theme/Rbs/Base/Rbs_Payment/Deferred/connector.twig', link: function(scope) { scope.loadingConnector = true; var postData = { connectorId: scope.selectedConnector.id, transactionId: scope.payment.transaction.id }; $http.post('Action/Rbs/Payment/GetDeferredConnectorData', postData) .success(function(data) { scope.connectorData = data; scope.loadingConnector = false; }) .error(function(data, status, headers) { console.log('GetDeferredConnectorInformation error', data, status, headers); }); scope.confirmOrder = function() { $http.post('Action/Rbs/Payment/DeferredConnectorReturnSuccess', postData) .success(function(data) { window.location = data['redirectURL']; }) .error(function(data, status, headers) { console.log('GetDeferredConnectorInformation error', data, status, headers); }); } } } } rbsCommercePaymentConnectorDeferred.$inject = ['$http']; app.directive('rbsCommercePaymentConnectorDeferred', rbsCommercePaymentConnectorDeferred); })();
jamiepg1/module-payment
Assets/Theme/connector.js
JavaScript
mpl-2.0
1,272
/* ** Copyright (c) 2012 The Khronos Group Inc. ** ** Permission is hereby granted, free of charge, to any person obtaining a ** copy of this software and/or associated documentation files (the ** "Materials"), to deal in the Materials without restriction, including ** without limitation the rights to use, copy, modify, merge, publish, ** distribute, sublicense, and/or sell copies of the Materials, and to ** permit persons to whom the Materials are 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 Materials. ** ** THE MATERIALS ARE 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 ** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. */ var WebGLTestUtils = (function() { "use strict"; /** * Wrapped logging function. * @param {string} msg The message to log. */ var log = function(msg) { bufferedLogToConsole(msg); }; /** * Wrapped logging function. * @param {string} msg The message to log. */ var error = function(msg) { // For the time being, diverting this to window.console.log rather // than window.console.error. If anyone cares enough they can // generalize the mechanism in js-test-pre.js. log(msg); }; /** * Turn off all logging. */ var loggingOff = function() { log = function() {}; error = function() {}; }; /** * Converts a WebGL enum to a string. * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {number} value The enum value. * @return {string} The enum as a string. */ var glEnumToString = function(gl, value) { // Optimization for the most common enum: if (value === gl.NO_ERROR) { return "NO_ERROR"; } for (var p in gl) { if (gl[p] == value) { if (p == 'drawingBufferWidth' || p == 'drawingBufferHeight') { continue; } return p; } } return "0x" + Number(value).toString(16); }; var lastError = ""; /** * Returns the last compiler/linker error. * @return {string} The last compiler/linker error. */ var getLastError = function() { return lastError; }; /** * Whether a haystack ends with a needle. * @param {string} haystack String to search * @param {string} needle String to search for. * @param {boolean} True if haystack ends with needle. */ var endsWith = function(haystack, needle) { return haystack.substr(haystack.length - needle.length) === needle; }; /** * Whether a haystack starts with a needle. * @param {string} haystack String to search * @param {string} needle String to search for. * @param {boolean} True if haystack starts with needle. */ var startsWith = function(haystack, needle) { return haystack.substr(0, needle.length) === needle; }; /** * A vertex shader for a single texture. * @type {string} */ var simpleTextureVertexShader = [ 'attribute vec4 vPosition;', 'attribute vec2 texCoord0;', 'varying vec2 texCoord;', 'void main() {', ' gl_Position = vPosition;', ' texCoord = texCoord0;', '}'].join('\n'); /** * A fragment shader for a single texture. * @type {string} */ var simpleTextureFragmentShader = [ 'precision mediump float;', 'uniform sampler2D tex;', 'varying vec2 texCoord;', 'void main() {', ' gl_FragData[0] = texture2D(tex, texCoord);', '}'].join('\n'); /** * A fragment shader for a single cube map texture. * @type {string} */ var simpleCubeMapTextureFragmentShader = [ 'precision mediump float;', 'uniform samplerCube tex;', 'uniform int face;', 'varying vec2 texCoord;', 'void main() {', // Transform [0, 1] -> [-1, 1] ' vec2 texC2 = (texCoord * 2.) - 1.;', // Transform 2d tex coord. to each face of TEXTURE_CUBE_MAP coord. ' vec3 texCube = vec3(0., 0., 0.);', ' if (face == 34069) {', // TEXTURE_CUBE_MAP_POSITIVE_X ' texCube = vec3(1., -texC2.y, -texC2.x);', ' } else if (face == 34070) {', // TEXTURE_CUBE_MAP_NEGATIVE_X ' texCube = vec3(-1., -texC2.y, texC2.x);', ' } else if (face == 34071) {', // TEXTURE_CUBE_MAP_POSITIVE_Y ' texCube = vec3(texC2.x, 1., texC2.y);', ' } else if (face == 34072) {', // TEXTURE_CUBE_MAP_NEGATIVE_Y ' texCube = vec3(texC2.x, -1., -texC2.y);', ' } else if (face == 34073) {', // TEXTURE_CUBE_MAP_POSITIVE_Z ' texCube = vec3(texC2.x, -texC2.y, 1.);', ' } else if (face == 34074) {', // TEXTURE_CUBE_MAP_NEGATIVE_Z ' texCube = vec3(-texC2.x, -texC2.y, -1.);', ' }', ' gl_FragData[0] = textureCube(tex, texCube);', '}'].join('\n'); /** * A vertex shader for a single texture. * @type {string} */ var noTexCoordTextureVertexShader = [ 'attribute vec4 vPosition;', 'varying vec2 texCoord;', 'void main() {', ' gl_Position = vPosition;', ' texCoord = vPosition.xy * 0.5 + 0.5;', '}'].join('\n'); /** * A vertex shader for a uniform color. * @type {string} */ var simpleVertexShader = [ 'attribute vec4 vPosition;', 'void main() {', ' gl_Position = vPosition;', '}'].join('\n'); /** * A fragment shader for a uniform color. * @type {string} */ var simpleColorFragmentShader = [ 'precision mediump float;', 'uniform vec4 u_color;', 'void main() {', ' gl_FragData[0] = u_color;', '}'].join('\n'); /** * A vertex shader for vertex colors. * @type {string} */ var simpleVertexColorVertexShader = [ 'attribute vec4 vPosition;', 'attribute vec4 a_color;', 'varying vec4 v_color;', 'void main() {', ' gl_Position = vPosition;', ' v_color = a_color;', '}'].join('\n'); /** * A fragment shader for vertex colors. * @type {string} */ var simpleVertexColorFragmentShader = [ 'precision mediump float;', 'varying vec4 v_color;', 'void main() {', ' gl_FragData[0] = v_color;', '}'].join('\n'); /** * Creates a program, attaches shaders, binds attrib locations, links the * program and calls useProgram. * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {!Array.<!WebGLShader|string>} shaders The shaders to * attach, or the source, or the id of a script to get * the source from. * @param {!Array.<string>} opt_attribs The attribs names. * @param {!Array.<number>} opt_locations The locations for the attribs. * @param {boolean} opt_logShaders Whether to log shader source. */ var setupProgram = function( gl, shaders, opt_attribs, opt_locations, opt_logShaders) { var realShaders = []; var program = gl.createProgram(); var shaderCount = 0; for (var ii = 0; ii < shaders.length; ++ii) { var shader = shaders[ii]; var shaderType = undefined; if (typeof shader == 'string') { var element = document.getElementById(shader); if (element) { if (element.type != "x-shader/x-vertex" && element.type != "x-shader/x-fragment") shaderType = ii ? gl.FRAGMENT_SHADER : gl.VERTEX_SHADER; shader = loadShaderFromScript(gl, shader, shaderType, undefined, opt_logShaders); } else if (endsWith(shader, ".vert")) { shader = loadShaderFromFile(gl, shader, gl.VERTEX_SHADER, undefined, opt_logShaders); } else if (endsWith(shader, ".frag")) { shader = loadShaderFromFile(gl, shader, gl.FRAGMENT_SHADER, undefined, opt_logShaders); } else { shader = loadShader(gl, shader, ii ? gl.FRAGMENT_SHADER : gl.VERTEX_SHADER, undefined, opt_logShaders); } } else if (opt_logShaders) { throw 'Shader source logging requested but no shader source provided'; } if (shader) { ++shaderCount; gl.attachShader(program, shader); } } if (shaderCount != 2) { error("Error in compiling shader"); return null; } if (opt_attribs) { for (var ii = 0; ii < opt_attribs.length; ++ii) { gl.bindAttribLocation( program, opt_locations ? opt_locations[ii] : ii, opt_attribs[ii]); } } gl.linkProgram(program); // Check the link status var linked = gl.getProgramParameter(program, gl.LINK_STATUS); if (!linked) { // something went wrong with the link lastError = gl.getProgramInfoLog (program); error("Error in program linking:" + lastError); gl.deleteProgram(program); return null; } gl.useProgram(program); return program; }; /** * Creates a program, attaches shader, sets up trasnform feedback varyings, * binds attrib locations, links the program and calls useProgram. * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {!Array.<!WebGLShader|string>} shaders The shaders to * attach, or the source, or the id of a script to get * the source from. * @param {!Array.<string>} varyings The transform feedback varying names. * @param {number} bufferMode The mode used to capture the varying variables. * @param {!Array.<string>} opt_attribs The attribs names. * @param {!Array.<number>} opt_locations The locations for the attribs. * @param {boolean} opt_logShaders Whether to log shader source. */ var setupTransformFeedbackProgram = function( gl, shaders, varyings, bufferMode, opt_attribs, opt_locations, opt_logShaders) { var realShaders = []; var program = gl.createProgram(); var shaderCount = 0; for (var ii = 0; ii < shaders.length; ++ii) { var shader = shaders[ii]; var shaderType = undefined; if (typeof shader == 'string') { var element = document.getElementById(shader); if (element) { if (element.type != "x-shader/x-vertex" && element.type != "x-shader/x-fragment") shaderType = ii ? gl.FRAGMENT_SHADER : gl.VERTEX_SHADER; shader = loadShaderFromScript(gl, shader, shaderType, undefined, opt_logShaders); } else if (endsWith(shader, ".vert")) { shader = loadShaderFromFile(gl, shader, gl.VERTEX_SHADER, undefined, opt_logShaders); } else if (endsWith(shader, ".frag")) { shader = loadShaderFromFile(gl, shader, gl.FRAGMENT_SHADER, undefined, opt_logShaders); } else { shader = loadShader(gl, shader, ii ? gl.FRAGMENT_SHADER : gl.VERTEX_SHADER, undefined, opt_logShaders); } } else if (opt_logShaders) { throw 'Shader source logging requested but no shader source provided'; } if (shader) { ++shaderCount; gl.attachShader(program, shader); } } if (shaderCount != 2) { error("Error in compiling shader"); return null; } if (opt_attribs) { for (var ii = 0; ii < opt_attribs.length; ++ii) { gl.bindAttribLocation( program, opt_locations ? opt_locations[ii] : ii, opt_attribs[ii]); } } gl.transformFeedbackVaryings(program, varyings, bufferMode); gl.linkProgram(program); // Check the link status var linked = gl.getProgramParameter(program, gl.LINK_STATUS); if (!linked) { // something went wrong with the link lastError = gl.getProgramInfoLog (program); error("Error in program linking:" + lastError); gl.deleteProgram(program); return null; } gl.useProgram(program); return program; }; /** * Creates a simple texture program. * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. * @return {WebGLProgram} */ var setupNoTexCoordTextureProgram = function(gl) { return setupProgram(gl, [noTexCoordTextureVertexShader, simpleTextureFragmentShader], ['vPosition'], [0]); }; /** * Creates a simple texture program. * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {number} opt_positionLocation The attrib location for position. * @param {number} opt_texcoordLocation The attrib location for texture coords. * @return {WebGLProgram} */ var setupSimpleTextureProgram = function( gl, opt_positionLocation, opt_texcoordLocation) { opt_positionLocation = opt_positionLocation || 0; opt_texcoordLocation = opt_texcoordLocation || 1; return setupProgram(gl, [simpleTextureVertexShader, simpleTextureFragmentShader], ['vPosition', 'texCoord0'], [opt_positionLocation, opt_texcoordLocation]); }; /** * Creates a simple cube map texture program. * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {number} opt_positionLocation The attrib location for position. * @param {number} opt_texcoordLocation The attrib location for texture coords. * @return {WebGLProgram} */ var setupSimpleCubeMapTextureProgram = function( gl, opt_positionLocation, opt_texcoordLocation) { opt_positionLocation = opt_positionLocation || 0; opt_texcoordLocation = opt_texcoordLocation || 1; return setupProgram(gl, [simpleTextureVertexShader, simpleCubeMapTextureFragmentShader], ['vPosition', 'texCoord0'], [opt_positionLocation, opt_texcoordLocation]); }; /** * Creates a simple vertex color program. * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {number} opt_positionLocation The attrib location for position. * @param {number} opt_vertexColorLocation The attrib location * for vertex colors. * @return {WebGLProgram} */ var setupSimpleVertexColorProgram = function( gl, opt_positionLocation, opt_vertexColorLocation) { opt_positionLocation = opt_positionLocation || 0; opt_vertexColorLocation = opt_vertexColorLocation || 1; return setupProgram(gl, [simpleVertexColorVertexShader, simpleVertexColorFragmentShader], ['vPosition', 'a_color'], [opt_positionLocation, opt_vertexColorLocation]); }; /** * Creates a simple color program. * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {number} opt_positionLocation The attrib location for position. * @return {WebGLProgram} */ var setupSimpleColorProgram = function(gl, opt_positionLocation) { opt_positionLocation = opt_positionLocation || 0; return setupProgram(gl, [simpleVertexShader, simpleColorFragmentShader], ['vPosition'], [opt_positionLocation]); }; /** * Creates buffers for a textured unit quad and attaches them to vertex attribs. * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {number} opt_positionLocation The attrib location for position. * @param {number} opt_texcoordLocation The attrib location for texture coords. * @return {!Array.<WebGLBuffer>} The buffer objects that were * created. */ var setupUnitQuad = function(gl, opt_positionLocation, opt_texcoordLocation) { return setupUnitQuadWithTexCoords(gl, [ 0.0, 0.0 ], [ 1.0, 1.0 ], opt_positionLocation, opt_texcoordLocation); }; /** * Creates buffers for a textured unit quad with specified lower left * and upper right texture coordinates, and attaches them to vertex * attribs. * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {!Array.<number>} lowerLeftTexCoords The texture coordinates for the lower left corner. * @param {!Array.<number>} upperRightTexCoords The texture coordinates for the upper right corner. * @param {number} opt_positionLocation The attrib location for position. * @param {number} opt_texcoordLocation The attrib location for texture coords. * @return {!Array.<WebGLBuffer>} The buffer objects that were * created. */ var setupUnitQuadWithTexCoords = function( gl, lowerLeftTexCoords, upperRightTexCoords, opt_positionLocation, opt_texcoordLocation) { return setupQuad(gl, { positionLocation: opt_positionLocation || 0, texcoordLocation: opt_texcoordLocation || 1, lowerLeftTexCoords: lowerLeftTexCoords, upperRightTexCoords: upperRightTexCoords }); }; /** * Makes a quad with various options. * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {!Object} options * * scale: scale to multiple unit quad values by. default 1.0. * positionLocation: attribute location for position. * texcoordLocation: attribute location for texcoords. * If this does not exist no texture coords are created. * lowerLeftTexCoords: an array of 2 values for the * lowerLeftTexCoords. * upperRightTexCoords: an array of 2 values for the * upperRightTexCoords. */ var setupQuad = function(gl, options) { var positionLocation = options.positionLocation || 0; var scale = options.scale || 1; var objects = []; var vertexObject = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vertexObject); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ 1.0 * scale , 1.0 * scale, -1.0 * scale , 1.0 * scale, -1.0 * scale , -1.0 * scale, 1.0 * scale , 1.0 * scale, -1.0 * scale , -1.0 * scale, 1.0 * scale , -1.0 * scale]), gl.STATIC_DRAW); gl.enableVertexAttribArray(positionLocation); gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0); objects.push(vertexObject); if (options.texcoordLocation !== undefined) { var llx = options.lowerLeftTexCoords[0]; var lly = options.lowerLeftTexCoords[1]; var urx = options.upperRightTexCoords[0]; var ury = options.upperRightTexCoords[1]; vertexObject = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vertexObject); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ urx, ury, llx, ury, llx, lly, urx, ury, llx, lly, urx, lly]), gl.STATIC_DRAW); gl.enableVertexAttribArray(options.texcoordLocation); gl.vertexAttribPointer(options.texcoordLocation, 2, gl.FLOAT, false, 0, 0); objects.push(vertexObject); } return objects; }; /** * Creates a program and buffers for rendering a textured quad. * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {number} opt_positionLocation The attrib location for * position. Default = 0. * @param {number} opt_texcoordLocation The attrib location for * texture coords. Default = 1. * @return {!WebGLProgram} */ var setupTexturedQuad = function( gl, opt_positionLocation, opt_texcoordLocation) { var program = setupSimpleTextureProgram( gl, opt_positionLocation, opt_texcoordLocation); setupUnitQuad(gl, opt_positionLocation, opt_texcoordLocation); return program; }; /** * Creates a program and buffers for rendering a color quad. * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {number} opt_positionLocation The attrib location for position. * @return {!WebGLProgram} */ var setupColorQuad = function(gl, opt_positionLocation) { opt_positionLocation = opt_positionLocation || 0; var program = setupSimpleColorProgram(gl); setupUnitQuad(gl, opt_positionLocation); return program; }; /** * Creates a program and buffers for rendering a textured quad with * specified lower left and upper right texture coordinates. * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {!Array.<number>} lowerLeftTexCoords The texture coordinates for the lower left corner. * @param {!Array.<number>} upperRightTexCoords The texture coordinates for the upper right corner. * @param {number} opt_positionLocation The attrib location for position. * @param {number} opt_texcoordLocation The attrib location for texture coords. * @return {!WebGLProgram} */ var setupTexturedQuadWithTexCoords = function( gl, lowerLeftTexCoords, upperRightTexCoords, opt_positionLocation, opt_texcoordLocation) { var program = setupSimpleTextureProgram( gl, opt_positionLocation, opt_texcoordLocation); setupUnitQuadWithTexCoords(gl, lowerLeftTexCoords, upperRightTexCoords, opt_positionLocation, opt_texcoordLocation); return program; }; /** * Creates a program and buffers for rendering a textured quad with * a cube map texture. * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {number} opt_positionLocation The attrib location for * position. Default = 0. * @param {number} opt_texcoordLocation The attrib location for * texture coords. Default = 1. * @return {!WebGLProgram} */ var setupTexturedQuadWithCubeMap = function( gl, opt_positionLocation, opt_texcoordLocation) { var program = setupSimpleCubeMapTextureProgram( gl, opt_positionLocation, opt_texcoordLocation); setupUnitQuad(gl, opt_positionLocation, opt_texcoordLocation); return program; }; /** * Creates a unit quad with only positions of a given resolution. * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {number} gridRes The resolution of the mesh grid, * expressed in the number of quads across and down. * @param {number} opt_positionLocation The attrib location for position. */ var setupIndexedQuad = function ( gl, gridRes, opt_positionLocation, opt_flipOddTriangles) { return setupIndexedQuadWithOptions(gl, { gridRes: gridRes, positionLocation: opt_positionLocation, flipOddTriangles: opt_flipOddTriangles }); }; /** * Creates a quad with various options. * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {!Object} options The options. See below. * @return {!Array.<WebGLBuffer>} The created buffers. * [positions, <colors>, indices] * * Options: * gridRes: number of quads across and down grid. * positionLocation: attrib location for position * flipOddTriangles: reverse order of vertices of every other * triangle * positionOffset: offset added to each vertex * positionMult: multipier for each vertex * colorLocation: attrib location for vertex colors. If * undefined no vertex colors will be created. */ var setupIndexedQuadWithOptions = function (gl, options) { var positionLocation = options.positionLocation || 0; var objects = []; var gridRes = options.gridRes || 1; var positionOffset = options.positionOffset || 0; var positionMult = options.positionMult || 1; var vertsAcross = gridRes + 1; var numVerts = vertsAcross * vertsAcross; var positions = new Float32Array(numVerts * 3); var indices = new Uint16Array(6 * gridRes * gridRes); var poffset = 0; for (var yy = 0; yy <= gridRes; ++yy) { for (var xx = 0; xx <= gridRes; ++xx) { positions[poffset + 0] = (-1 + 2 * xx / gridRes) * positionMult + positionOffset; positions[poffset + 1] = (-1 + 2 * yy / gridRes) * positionMult + positionOffset; positions[poffset + 2] = 0; poffset += 3; } } var buf = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buf); gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW); gl.enableVertexAttribArray(positionLocation); gl.vertexAttribPointer(positionLocation, 3, gl.FLOAT, false, 0, 0); objects.push(buf); if (options.colorLocation !== undefined) { var colors = new Float32Array(numVerts * 4); for (var yy = 0; yy <= gridRes; ++yy) { for (var xx = 0; xx <= gridRes; ++xx) { if (options.color !== undefined) { colors[poffset + 0] = options.color[0]; colors[poffset + 1] = options.color[1]; colors[poffset + 2] = options.color[2]; colors[poffset + 3] = options.color[3]; } else { colors[poffset + 0] = xx / gridRes; colors[poffset + 1] = yy / gridRes; colors[poffset + 2] = (xx / gridRes) * (yy / gridRes); colors[poffset + 3] = (yy % 2) * 0.5 + 0.5; } poffset += 4; } } buf = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buf); gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW); gl.enableVertexAttribArray(options.colorLocation); gl.vertexAttribPointer(options.colorLocation, 4, gl.FLOAT, false, 0, 0); objects.push(buf); } var tbase = 0; for (var yy = 0; yy < gridRes; ++yy) { var index = yy * vertsAcross; for (var xx = 0; xx < gridRes; ++xx) { indices[tbase + 0] = index + 0; indices[tbase + 1] = index + 1; indices[tbase + 2] = index + vertsAcross; indices[tbase + 3] = index + vertsAcross; indices[tbase + 4] = index + 1; indices[tbase + 5] = index + vertsAcross + 1; if (options.flipOddTriangles) { indices[tbase + 4] = index + vertsAcross + 1; indices[tbase + 5] = index + 1; } index += 1; tbase += 6; } } buf = gl.createBuffer(); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buf); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW); objects.push(buf); return objects; }; /** * Returns the constructor for a typed array that corresponds to the given * WebGL type. * @param {!WebGLRenderingContext} gl A WebGLRenderingContext. * @param {number} type The WebGL type (eg, gl.UNSIGNED_BYTE) * @return {!Constructor} The typed array constructor that * corresponds to the given type. */ var glTypeToTypedArrayType = function(gl, type) { switch (type) { case gl.BYTE: return window.Int8Array; case gl.UNSIGNED_BYTE: return window.Uint8Array; case gl.SHORT: return window.Int16Array; case gl.UNSIGNED_SHORT: case gl.UNSIGNED_SHORT_5_6_5: case gl.UNSIGNED_SHORT_4_4_4_4: case gl.UNSIGNED_SHORT_5_5_5_1: return window.Uint16Array; case gl.INT: return window.Int32Array; case gl.UNSIGNED_INT: return window.Uint32Array; default: throw 'unknown gl type ' + glEnumToString(gl, type); } }; /** * Returns the number of bytes per component for a given WebGL type. * @param {!WebGLRenderingContext} gl A WebGLRenderingContext. * @param {GLenum} type The WebGL type (eg, gl.UNSIGNED_BYTE) * @return {number} The number of bytes per component. */ var getBytesPerComponent = function(gl, type) { switch (type) { case gl.BYTE: case gl.UNSIGNED_BYTE: return 1; case gl.SHORT: case gl.UNSIGNED_SHORT: case gl.UNSIGNED_SHORT_5_6_5: case gl.UNSIGNED_SHORT_4_4_4_4: case gl.UNSIGNED_SHORT_5_5_5_1: return 2; case gl.INT: case gl.UNSIGNED_INT: return 4; default: throw 'unknown gl type ' + glEnumToString(gl, type); } }; /** * Returns the number of typed array elements per pixel for a given WebGL * format/type combination. The corresponding typed array type can be determined * by calling glTypeToTypedArrayType. * @param {!WebGLRenderingContext} gl A WebGLRenderingContext. * @param {GLenum} format The WebGL format (eg, gl.RGBA) * @param {GLenum} type The WebGL type (eg, gl.UNSIGNED_BYTE) * @return {number} The number of typed array elements per pixel. */ var getTypedArrayElementsPerPixel = function(gl, format, type) { switch (type) { case gl.UNSIGNED_SHORT_5_6_5: case gl.UNSIGNED_SHORT_4_4_4_4: case gl.UNSIGNED_SHORT_5_5_5_1: return 1; case gl.UNSIGNED_BYTE: break; default: throw 'not a gl type for color information ' + glEnumToString(gl, type); } switch (format) { case gl.RGBA: return 4; case gl.RGB: return 3; case gl.LUMINANCE_ALPHA: return 2; case gl.LUMINANCE: case gl.ALPHA: return 1; default: throw 'unknown gl format ' + glEnumToString(gl, format); } }; /** * Fills the given texture with a solid color. * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {!WebGLTexture} tex The texture to fill. * @param {number} width The width of the texture to create. * @param {number} height The height of the texture to create. * @param {!Array.<number>} color The color to fill with. * where each element is in the range 0 to 255. * @param {number} opt_level The level of the texture to fill. Default = 0. * @param {number} opt_format The format for the texture. * @param {number} opt_internalFormat The internal format for the texture. */ var fillTexture = function(gl, tex, width, height, color, opt_level, opt_format, opt_type, opt_internalFormat) { opt_level = opt_level || 0; opt_format = opt_format || gl.RGBA; opt_type = opt_type || gl.UNSIGNED_BYTE; opt_internalFormat = opt_internalFormat || opt_format; var pack = gl.getParameter(gl.UNPACK_ALIGNMENT); var numComponents = color.length; var bytesPerComponent = getBytesPerComponent(gl, opt_type); var rowSize = numComponents * width * bytesPerComponent; var paddedRowSize = Math.floor((rowSize + pack - 1) / pack) * pack; var size = rowSize + (height - 1) * paddedRowSize; size = Math.floor((size + bytesPerComponent - 1) / bytesPerComponent) * bytesPerComponent; var buf = new (glTypeToTypedArrayType(gl, opt_type))(size); for (var yy = 0; yy < height; ++yy) { var off = yy * paddedRowSize; for (var xx = 0; xx < width; ++xx) { for (var jj = 0; jj < numComponents; ++jj) { buf[off++] = color[jj]; } } } gl.bindTexture(gl.TEXTURE_2D, tex); gl.texImage2D( gl.TEXTURE_2D, opt_level, opt_internalFormat, width, height, 0, opt_format, opt_type, buf); }; /** * Creates a texture and fills it with a solid color. * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {number} width The width of the texture to create. * @param {number} height The height of the texture to create. * @param {!Array.<number>} color The color to fill with. A 4 element array * where each element is in the range 0 to 255. * @return {!WebGLTexture} */ var createColoredTexture = function(gl, width, height, color) { var tex = gl.createTexture(); fillTexture(gl, tex, width, height, color); return tex; }; var ubyteToFloat = function(c) { return c / 255; }; var ubyteColorToFloatColor = function(color) { var floatColor = []; for (var ii = 0; ii < color.length; ++ii) { floatColor[ii] = ubyteToFloat(color[ii]); } return floatColor; }; /** * Sets the "u_color" uniform of the current program to color. * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {!Array.<number>} color 4 element array of 0-1 color * components. */ var setFloatDrawColor = function(gl, color) { var program = gl.getParameter(gl.CURRENT_PROGRAM); var colorLocation = gl.getUniformLocation(program, "u_color"); gl.uniform4fv(colorLocation, color); }; /** * Sets the "u_color" uniform of the current program to color. * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {!Array.<number>} color 4 element array of 0-255 color * components. */ var setUByteDrawColor = function(gl, color) { setFloatDrawColor(gl, ubyteColorToFloatColor(color)); }; /** * Draws a previously setup quad in the given color. * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {!Array.<number>} color The color to draw with. A 4 * element array where each element is in the range 0 to * 1. */ var drawFloatColorQuad = function(gl, color) { var program = gl.getParameter(gl.CURRENT_PROGRAM); var colorLocation = gl.getUniformLocation(program, "u_color"); gl.uniform4fv(colorLocation, color); gl.drawArrays(gl.TRIANGLES, 0, 6); }; /** * Draws a previously setup quad in the given color. * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {!Array.<number>} color The color to draw with. A 4 * element array where each element is in the range 0 to * 255. */ var drawUByteColorQuad = function(gl, color) { drawFloatColorQuad(gl, ubyteColorToFloatColor(color)); }; /** * Draws a previously setupUnitQuad. * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. */ var drawUnitQuad = function(gl) { gl.drawArrays(gl.TRIANGLES, 0, 6); }; /** * Clears then Draws a previously setupUnitQuad. * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {!Array.<number>} opt_color The color to fill clear with before * drawing. A 4 element array where each element is in the range 0 to * 255. Default [255, 255, 255, 255] */ var clearAndDrawUnitQuad = function(gl, opt_color) { opt_color = opt_color || [255, 255, 255, 255]; gl.clearColor( opt_color[0] / 255, opt_color[1] / 255, opt_color[2] / 255, opt_color[3] / 255); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); drawUnitQuad(gl); }; /** * Draws a quad previously setup with setupIndexedQuad. * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {number} gridRes Resolution of grid. */ var drawIndexedQuad = function(gl, gridRes) { gl.drawElements(gl.TRIANGLES, gridRes * gridRes * 6, gl.UNSIGNED_SHORT, 0); }; /** * Draws a previously setupIndexedQuad * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {number} gridRes Resolution of grid. * @param {!Array.<number>} opt_color The color to fill clear with before * drawing. A 4 element array where each element is in the range 0 to * 255. Default [255, 255, 255, 255] */ var clearAndDrawIndexedQuad = function(gl, gridRes, opt_color) { opt_color = opt_color || [255, 255, 255, 255]; gl.clearColor( opt_color[0] / 255, opt_color[1] / 255, opt_color[2] / 255, opt_color[3] / 255); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); drawIndexedQuad(gl, gridRes); }; /** * Clips a range to min, max * (Eg. clipToRange(-5,7,0,20) would return {value:0,extent:2} * @param {number} value start of range * @param {number} extent extent of range * @param {number} min min. * @param {number} max max. * @return {!{value:number,extent:number}} The clipped value. */ var clipToRange = function(value, extent, min, max) { if (value < min) { extent -= min - value; value = min; } var end = value + extent; if (end > max) { extent -= end - max; } if (extent < 0) { value = max; extent = 0; } return {value:value, extent: extent}; }; /** * Determines if the passed context is an instance of a WebGLRenderingContext * or later variant (like WebGL2RenderingContext) * @param {CanvasRenderingContext} ctx The context to check. */ var isWebGLContext = function(ctx) { if (ctx instanceof WebGLRenderingContext) return true; if ('WebGL2RenderingContext' in window && ctx instanceof WebGL2RenderingContext) return true; return false; }; /** * Creates a check rect is used by checkCanvasRects. * @param {number} x left corner of region to check. * @param {number} y bottom corner of region to check in case of checking from * a GL context or top corner in case of checking from a 2D context. * @param {number} width width of region to check. * @param {number} height width of region to check. * @param {!Array.<number>} color The color expected. A 4 element array where * each element is in the range 0 to 255. * @param {string} opt_msg Message to associate with success. Eg * ("should be red"). * @param {number} opt_errorRange Optional. Acceptable error in * color checking. 0 by default. */ var makeCheckRect = function(x, y, width, height, color, msg, errorRange) { var rect = { 'x': x, 'y': y, 'width': width, 'height': height, 'color': color, 'msg': msg, 'errorRange': errorRange, 'checkRect': function (buf, l, b, w) { for (var px = (x - l) ; px < (x + width - l) ; ++px) { for (var py = (y - b) ; py < (y + height - b) ; ++py) { var offset = (py * w + px) * 4; for (var j = 0; j < color.length; ++j) { if (Math.abs(buf[offset + j] - color[j]) > errorRange) { testFailed(msg); var was = buf[offset + 0].toString(); for (j = 1; j < color.length; ++j) { was += "," + buf[offset + j]; } debug('at (' + px + ', ' + py + ') expected: ' + color + ' was ' + was); return; } } } } testPassed(msg); } } return rect; }; /** * Checks that a portions of a canvas or the currently attached framebuffer is 1 color. * @param {!WebGLRenderingContext|CanvasRenderingContext2D} gl The * WebGLRenderingContext or 2D context to use. * @param {!Array.<checkRect>} array of rects to check for matching color. */ var checkCanvasRects = function(gl, rects) { if (rects.length > 0) { var left = rects[0].x; var right = rects[0].x + rects[1].width; var bottom = rects[0].y; var top = rects[0].y + rects[0].height; for (var i = 1; i < rects.length; ++i) { left = Math.min(left, rects[i].x); right = Math.max(right, rects[i].x + rects[i].width); bottom = Math.min(bottom, rects[i].y); top = Math.max(top, rects[i].y + rects[i].height); } var width = right - left; var height = top - bottom; var buf = new Uint8Array(width * height * 4); gl.readPixels(left, bottom, width, height, gl.RGBA, gl.UNSIGNED_BYTE, buf); for (var i = 0; i < rects.length; ++i) { rects[i].checkRect(buf, left, bottom, width); } } }; /** * Checks that a portion of a canvas or the currently attached framebuffer is 1 color. * @param {!WebGLRenderingContext|CanvasRenderingContext2D} gl The * WebGLRenderingContext or 2D context to use. * @param {number} x left corner of region to check. * @param {number} y bottom corner of region to check in case of checking from * a GL context or top corner in case of checking from a 2D context. * @param {number} width width of region to check. * @param {number} height width of region to check. * @param {!Array.<number>} color The color expected. A 4 element array where * each element is in the range 0 to 255. * @param {number} opt_errorRange Optional. Acceptable error in * color checking. 0 by default. * @param {!function()} sameFn Function to call if all pixels * are the same as color. * @param {!function()} differentFn Function to call if a pixel * is different than color * @param {!function()} logFn Function to call for logging. * @param {Uint8Array} opt_readBackBuf typically passed to reuse existing * buffer while reading back pixels. */ var checkCanvasRectColor = function(gl, x, y, width, height, color, opt_errorRange, sameFn, differentFn, logFn, opt_readBackBuf) { if (isWebGLContext(gl) && !gl.getParameter(gl.FRAMEBUFFER_BINDING)) { // We're reading the backbuffer so clip. var xr = clipToRange(x, width, 0, gl.canvas.width); var yr = clipToRange(y, height, 0, gl.canvas.height); if (!xr.extent || !yr.extent) { logFn("checking rect: effective width or height is zero"); sameFn(); return; } x = xr.value; y = yr.value; width = xr.extent; height = yr.extent; } var errorRange = opt_errorRange || 0; if (!errorRange.length) { errorRange = [errorRange, errorRange, errorRange, errorRange] } var buf; if (isWebGLContext(gl)) { buf = opt_readBackBuf ? opt_readBackBuf : new Uint8Array(width * height * 4); gl.readPixels(x, y, width, height, gl.RGBA, gl.UNSIGNED_BYTE, buf); } else { buf = gl.getImageData(x, y, width, height).data; } for (var i = 0; i < width * height; ++i) { var offset = i * 4; for (var j = 0; j < color.length; ++j) { if (Math.abs(buf[offset + j] - color[j]) > errorRange[j]) { var was = buf[offset + 0].toString(); for (j = 1; j < color.length; ++j) { was += "," + buf[offset + j]; } differentFn('at (' + (x + (i % width)) + ', ' + (y + Math.floor(i / width)) + ') expected: ' + color + ' was ' + was); return; } } } sameFn(); }; /** * Checks that a portion of a canvas or the currently attached framebuffer is 1 color. * @param {!WebGLRenderingContext|CanvasRenderingContext2D} gl The * WebGLRenderingContext or 2D context to use. * @param {number} x left corner of region to check. * @param {number} y bottom corner of region to check in case of checking from * a GL context or top corner in case of checking from a 2D context. * @param {number} width width of region to check. * @param {number} height width of region to check. * @param {!Array.<number>} color The color expected. A 4 element array where * each element is in the range 0 to 255. * @param {string} opt_msg Message to associate with success or failure. Eg * ("should be red"). * @param {number} opt_errorRange Optional. Acceptable error in * color checking. 0 by default. */ var checkCanvasRect = function(gl, x, y, width, height, color, opt_msg, opt_errorRange) { checkCanvasRectColor( gl, x, y, width, height, color, opt_errorRange, function() { var msg = opt_msg; if (msg === undefined) msg = "should be " + color.toString(); testPassed(msg); }, function(differentMsg) { var msg = opt_msg; if (msg === undefined) msg = "should be " + color.toString(); testFailed(msg + "\n" + differentMsg); }, debug); }; /** * Checks that an entire canvas or the currently attached framebuffer is 1 color. * @param {!WebGLRenderingContext|CanvasRenderingContext2D} gl The * WebGLRenderingContext or 2D context to use. * @param {!Array.<number>} color The color expected. A 4 element array where * each element is in the range 0 to 255. * @param {string} msg Message to associate with success. Eg ("should be red"). * @param {number} errorRange Optional. Acceptable error in * color checking. 0 by default. */ var checkCanvas = function(gl, color, msg, errorRange) { checkCanvasRect(gl, 0, 0, gl.canvas.width, gl.canvas.height, color, msg, errorRange); }; /** * Checks a rectangular area both inside the area and outside * the area. * @param {!WebGLRenderingContext|CanvasRenderingContext2D} gl The * WebGLRenderingContext or 2D context to use. * @param {number} x left corner of region to check. * @param {number} y bottom corner of region to check in case of checking from * a GL context or top corner in case of checking from a 2D context. * @param {number} width width of region to check. * @param {number} height width of region to check. * @param {!Array.<number>} innerColor The color expected inside * the area. A 4 element array where each element is in the * range 0 to 255. * @param {!Array.<number>} outerColor The color expected * outside. A 4 element array where each element is in the * range 0 to 255. * @param {!number} opt_edgeSize: The number of pixels to skip * around the edges of the area. Defaut 0. * @param {!{width:number, height:number}} opt_outerDimensions * The outer dimensions. Default the size of gl.canvas. */ var checkAreaInAndOut = function(gl, x, y, width, height, innerColor, outerColor, opt_edgeSize, opt_outerDimensions) { var outerDimensions = opt_outerDimensions || { width: gl.canvas.width, height: gl.canvas.height }; var edgeSize = opt_edgeSize || 0; checkCanvasRect(gl, x + edgeSize, y + edgeSize, width - edgeSize * 2, height - edgeSize * 2, innerColor); checkCanvasRect(gl, 0, 0, x - edgeSize, outerDimensions.height, outerColor); checkCanvasRect(gl, x + width + edgeSize, 0, outerDimensions.width - x - width - edgeSize, outerDimensions.height, outerColor); checkCanvasRect(gl, 0, 0, outerDimensions.width, y - edgeSize, outerColor); checkCanvasRect(gl, 0, y + height + edgeSize, outerDimensions.width, outerDimensions.height - y - height - edgeSize, outerColor); }; /** * Checks that an entire buffer matches the floating point values provided. * (WebGL 2.0 only) * @param {!WebGL2RenderingContext} gl The WebGL2RenderingContext to use. * @param {number} target The buffer target to bind to. * @param {!Array.<number>} expected The values expected. * @param {string} opt_msg Optional. Message to associate with success. Eg ("should be red"). * @param {number} opt_errorRange Optional. Acceptable error in value checking. 0.001 by default. */ var checkFloatBuffer = function(gl, target, expected, opt_msg, opt_errorRange) { if (opt_msg === undefined) opt_msg = "buffer should match expected values"; if (opt_errorRange === undefined) opt_errorRange = 0.001; var floatArray = new Float32Array(expected.length); gl.getBufferSubData(target, 0, floatArray); for (var i = 0; i < expected.length; i++) { if (Math.abs(floatArray[i] - expected[i]) > opt_errorRange) { testFailed(opt_msg); debug('at [' + i + '] expected: ' + expected[i] + ' was ' + floatArray[i]); return; } } testPassed(opt_msg); }; /** * Loads a texture, calls callback when finished. * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {string} url URL of image to load * @param {function(!Image): void} callback Function that gets called after * image has loaded * @return {!WebGLTexture} The created texture. */ var loadTexture = function(gl, url, callback) { var texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); var image = new Image(); image.onload = function() { gl.bindTexture(gl.TEXTURE_2D, texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image); callback(image); }; image.src = url; return texture; }; /** * Checks whether the bound texture has expected dimensions. One corner pixel * of the texture will be changed as a side effect. * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {!WebGLTexture} texture The texture to check. * @param {number} width Expected width. * @param {number} height Expected height. * @param {GLenum} opt_format The texture's format. Defaults to RGBA. * @param {GLenum} opt_type The texture's type. Defaults to UNSIGNED_BYTE. */ var checkTextureSize = function(gl, width, height, opt_format, opt_type) { opt_format = opt_format || gl.RGBA; opt_type = opt_type || gl.UNSIGNED_BYTE; var numElements = getTypedArrayElementsPerPixel(gl, opt_format, opt_type); var buf = new (glTypeToTypedArrayType(gl, opt_type))(numElements); var errors = 0; gl.texSubImage2D(gl.TEXTURE_2D, 0, width - 1, height - 1, 1, 1, opt_format, opt_type, buf); if (gl.getError() != gl.NO_ERROR) { testFailed("Texture was smaller than the expected size " + width + "x" + height); ++errors; } gl.texSubImage2D(gl.TEXTURE_2D, 0, width - 1, height, 1, 1, opt_format, opt_type, buf); if (gl.getError() == gl.NO_ERROR) { testFailed("Texture was taller than " + height); ++errors; } gl.texSubImage2D(gl.TEXTURE_2D, 0, width, height - 1, 1, 1, opt_format, opt_type, buf); if (gl.getError() == gl.NO_ERROR) { testFailed("Texture was wider than " + width); ++errors; } if (errors == 0) { testPassed("Texture had the expected size " + width + "x" + height); } }; /** * Makes a shallow copy of an object. * @param {!Object} src Object to copy * @return {!Object} The copy of src. */ var shallowCopyObject = function(src) { var dst = {}; for (var attr in src) { if (src.hasOwnProperty(attr)) { dst[attr] = src[attr]; } } return dst; }; /** * Checks if an attribute exists on an object case insensitive. * @param {!Object} obj Object to check * @param {string} attr Name of attribute to look for. * @return {string?} The name of the attribute if it exists, * undefined if not. */ var hasAttributeCaseInsensitive = function(obj, attr) { var lower = attr.toLowerCase(); for (var key in obj) { if (obj.hasOwnProperty(key) && key.toLowerCase() == lower) { return key; } } }; /** * Returns a map of URL querystring options * @return {Object?} Object containing all the values in the URL querystring */ var getUrlOptions = (function() { var _urlOptionsParsed = false; var _urlOptions = {}; return function() { if (!_urlOptionsParsed) { var s = window.location.href; var q = s.indexOf("?"); var e = s.indexOf("#"); if (e < 0) { e = s.length; } var query = s.substring(q + 1, e); var pairs = query.split("&"); for (var ii = 0; ii < pairs.length; ++ii) { var keyValue = pairs[ii].split("="); var key = keyValue[0]; var value = decodeURIComponent(keyValue[1]); _urlOptions[key] = value; } _urlOptionsParsed = true; } return _urlOptions; } })(); var default3DContextVersion = 1; /** * Set the default context version for create3DContext. * Initially the default version is 1. * @param {number} Default version of WebGL contexts. */ var setDefault3DContextVersion = function(version) { default3DContextVersion = version; }; /** * Get the default contex version for create3DContext. * First it looks at the URI option |webglVersion|. If it does not exist, * then look at the global default3DContextVersion variable. */ var getDefault3DContextVersion = function() { return parseInt(getUrlOptions().webglVersion, 10) || default3DContextVersion; }; /** * Creates a webgl context. * @param {!Canvas|string} opt_canvas The canvas tag to get * context from. If one is not passed in one will be * created. If it's a string it's assumed to be the id of a * canvas. * @param {Object} opt_attributes Context attributes. * @param {!number} opt_version Version of WebGL context to create. * The default version can be set by calling setDefault3DContextVersion. * @return {!WebGLRenderingContext} The created context. */ var create3DContext = function(opt_canvas, opt_attributes, opt_version) { if (window.initTestingHarness) { window.initTestingHarness(); } var attributes = shallowCopyObject(opt_attributes || {}); if (!hasAttributeCaseInsensitive(attributes, "antialias")) { attributes.antialias = false; } if (!opt_version) { opt_version = parseInt(getUrlOptions().webglVersion, 10) || default3DContextVersion; } opt_canvas = opt_canvas || document.createElement("canvas"); if (typeof opt_canvas == 'string') { opt_canvas = document.getElementById(opt_canvas); } var context = null; var names; switch (opt_version) { case 2: names = ["webgl2", "experimental-webgl2"]; break; default: names = ["webgl", "experimental-webgl"]; break; } for (var i = 0; i < names.length; ++i) { try { context = opt_canvas.getContext(names[i], attributes); } catch (e) { } if (context) { break; } } if (!context) { testFailed("Unable to fetch WebGL rendering context for Canvas"); } return context; }; /** * Defines the exception type for a GL error. * @constructor * @param {string} message The error message. * @param {number} error GL error code */ function GLErrorException (message, error) { this.message = message; this.name = "GLErrorException"; this.error = error; }; /** * Wraps a WebGL function with a function that throws an exception if there is * an error. * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {string} fname Name of function to wrap. * @return {function()} The wrapped function. */ var createGLErrorWrapper = function(context, fname) { return function() { var rv = context[fname].apply(context, arguments); var err = context.getError(); if (err != context.NO_ERROR) { var msg = "GL error " + glEnumToString(context, err) + " in " + fname; throw new GLErrorException(msg, err); } return rv; }; }; /** * Creates a WebGL context where all functions are wrapped to throw an exception * if there is an error. * @param {!Canvas} canvas The HTML canvas to get a context from. * @param {Object} opt_attributes Context attributes. * @param {!number} opt_version Version of WebGL context to create * @return {!Object} The wrapped context. */ function create3DContextWithWrapperThatThrowsOnGLError(canvas, opt_attributes, opt_version) { var context = create3DContext(canvas, opt_attributes, opt_version); var wrap = {}; for (var i in context) { try { if (typeof context[i] == 'function') { wrap[i] = createGLErrorWrapper(context, i); } else { wrap[i] = context[i]; } } catch (e) { error("createContextWrapperThatThrowsOnGLError: Error accessing " + i); } } wrap.getError = function() { return context.getError(); }; return wrap; }; /** * Tests that an evaluated expression generates a specific GL error. * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {number|Array.<number>} glErrors The expected gl error or an array of expected errors. * @param {string} evalStr The string to evaluate. */ var shouldGenerateGLError = function(gl, glErrors, evalStr, opt_msg) { var exception; try { eval(evalStr); } catch (e) { exception = e; } if (exception) { testFailed(evalStr + " threw exception " + exception); } else { if (!opt_msg) { opt_msg = "after evaluating: " + evalStr; } glErrorShouldBe(gl, glErrors, opt_msg); } }; /** * Tests that an evaluated expression does not generate a GL error. * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {string} evalStr The string to evaluate. */ var failIfGLError = function(gl, evalStr) { var exception; try { eval(evalStr); } catch (e) { exception = e; } if (exception) { testFailed(evalStr + " threw exception " + exception); } else { glErrorShouldBeImpl(gl, gl.NO_ERROR, false, "after evaluating: " + evalStr); } }; /** * Tests that the first error GL returns is the specified error. * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {number|Array.<number>} glErrors The expected gl error or an array of expected errors. * @param {string} opt_msg Optional additional message. */ var glErrorShouldBe = function(gl, glErrors, opt_msg) { glErrorShouldBeImpl(gl, glErrors, true, opt_msg); }; /** * Tests that the first error GL returns is the specified error. Allows suppression of successes. * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {number|Array.<number>} glErrors The expected gl error or an array of expected errors. * @param {boolean} reportSuccesses Whether to report successes as passes, or to silently pass. * @param {string} opt_msg Optional additional message. */ var glErrorShouldBeImpl = function(gl, glErrors, reportSuccesses, opt_msg) { if (!glErrors.length) { glErrors = [glErrors]; } opt_msg = opt_msg || ""; var err = gl.getError(); var ndx = glErrors.indexOf(err); var errStrs = []; for (var ii = 0; ii < glErrors.length; ++ii) { errStrs.push(glEnumToString(gl, glErrors[ii])); } var expected = errStrs.join(" or "); if (ndx < 0) { var msg = "getError expected" + ((glErrors.length > 1) ? " one of: " : ": "); testFailed(msg + expected + ". Was " + glEnumToString(gl, err) + " : " + opt_msg); } else if (reportSuccesses) { var msg = "getError was " + ((glErrors.length > 1) ? "one of: " : "expected value: "); testPassed(msg + expected + " : " + opt_msg); } }; /** * Links a WebGL program, throws if there are errors. * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {!WebGLProgram} program The WebGLProgram to link. * @param {function(string): void} opt_errorCallback callback for errors. */ var linkProgram = function(gl, program, opt_errorCallback) { var errFn = opt_errorCallback || testFailed; // Link the program gl.linkProgram(program); // Check the link status var linked = gl.getProgramParameter(program, gl.LINK_STATUS); if (!linked) { // something went wrong with the link var error = gl.getProgramInfoLog (program); errFn("Error in program linking:" + error); gl.deleteProgram(program); } }; /** * Loads text from an external file. This function is asynchronous. * @param {string} url The url of the external file. * @param {!function(bool, string): void} callback that is sent a bool for * success and the string. */ var loadTextFileAsync = function(url, callback) { log ("loading: " + url); var error = 'loadTextFileAsync failed to load url "' + url + '"'; var request; if (window.XMLHttpRequest) { request = new XMLHttpRequest(); if (request.overrideMimeType) { request.overrideMimeType('text/plain'); } } else { throw 'XMLHttpRequest is disabled'; } try { request.open('GET', url, true); request.onreadystatechange = function() { if (request.readyState == 4) { var text = ''; // HTTP reports success with a 200 status. The file protocol reports // success with zero. HTTP does not use zero as a status code (they // start at 100). // https://developer.mozilla.org/En/Using_XMLHttpRequest var success = request.status == 200 || request.status == 0; if (success) { text = request.responseText; log("completed load request: " + url); } else { log("loading " + url + " resulted in unexpected status: " + request.status + " " + request.statusText); } callback(success, text); } }; request.onerror = function(errorEvent) { log("error occurred loading " + url); callback(false, ''); }; request.send(null); } catch (err) { log("failed to load: " + url + " with exception " + err.message); callback(false, ''); } }; /** * Recursively loads a file as a list. Each line is parsed for a relative * path. If the file ends in .txt the contents of that file is inserted in * the list. * * @param {string} url The url of the external file. * @param {!function(bool, Array<string>): void} callback that is sent a bool * for success and the array of strings. */ var getFileListAsync = function(url, callback) { var files = []; var getFileListImpl = function(url, callback) { var files = []; if (url.substr(url.length - 4) == '.txt') { loadTextFileAsync(url, function() { return function(success, text) { if (!success) { callback(false, ''); return; } var lines = text.split('\n'); var prefix = ''; var lastSlash = url.lastIndexOf('/'); if (lastSlash >= 0) { prefix = url.substr(0, lastSlash + 1); } var fail = false; var count = 1; var index = 0; for (var ii = 0; ii < lines.length; ++ii) { var str = lines[ii].replace(/^\s\s*/, '').replace(/\s\s*$/, ''); if (str.length > 4 && str[0] != '#' && str[0] != ";" && str.substr(0, 2) != "//") { var names = str.split(/ +/); var new_url = prefix + str; if (names.length == 1) { new_url = prefix + str; ++count; getFileListImpl(new_url, function(index) { return function(success, new_files) { log("got files: " + new_files.length); if (success) { files[index] = new_files; } finish(success); }; }(index++)); } else { var s = ""; var p = ""; for (var jj = 0; jj < names.length; ++jj) { s += p + prefix + names[jj]; p = " "; } files[index++] = s; } } } finish(true); function finish(success) { if (!success) { fail = true; } --count; log("count: " + count); if (!count) { callback(!fail, files); } } } }()); } else { files.push(url); callback(true, files); } }; getFileListImpl(url, function(success, files) { // flatten var flat = []; flatten(files); function flatten(files) { for (var ii = 0; ii < files.length; ++ii) { var value = files[ii]; if (typeof(value) == "string") { flat.push(value); } else { flatten(value); } } } callback(success, flat); }); }; /** * Gets a file from a file/URL. * @param {string} file the URL of the file to get. * @return {string} The contents of the file. */ var readFile = function(file) { var xhr = new XMLHttpRequest(); xhr.open("GET", file, false); xhr.send(); return xhr.responseText.replace(/\r/g, ""); }; var readFileList = function(url) { var files = []; if (url.substr(url.length - 4) == '.txt') { var lines = readFile(url).split('\n'); var prefix = ''; var lastSlash = url.lastIndexOf('/'); if (lastSlash >= 0) { prefix = url.substr(0, lastSlash + 1); } for (var ii = 0; ii < lines.length; ++ii) { var str = lines[ii].replace(/^\s\s*/, '').replace(/\s\s*$/, ''); if (str.length > 4 && str[0] != '#' && str[0] != ";" && str.substr(0, 2) != "//") { var names = str.split(/ +/); if (names.length == 1) { var new_url = prefix + str; files = files.concat(readFileList(new_url)); } else { var s = ""; var p = ""; for (var jj = 0; jj < names.length; ++jj) { s += p + prefix + names[jj]; p = " "; } files.push(s); } } } } else { files.push(url); } return files; }; /** * Loads a shader. * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {string} shaderSource The shader source. * @param {number} shaderType The type of shader. * @param {function(string): void} opt_errorCallback callback for errors. * @param {boolean} opt_logShaders Whether to log shader source. * @param {string} opt_shaderLabel Label that identifies the shader source in * the log. * @param {string} opt_url URL from where the shader source was loaded from. * If opt_logShaders is set, then a link to the source file will also be * added. * @param {boolean} Skip compilation status check. Default = false. * @return {!WebGLShader} The created shader. */ var loadShader = function( gl, shaderSource, shaderType, opt_errorCallback, opt_logShaders, opt_shaderLabel, opt_url, opt_skipCompileStatus) { var errFn = opt_errorCallback || error; // Create the shader object var shader = gl.createShader(shaderType); if (shader == null) { errFn("*** Error: unable to create shader '"+shaderSource+"'"); return null; } // Load the shader source gl.shaderSource(shader, shaderSource); var err = gl.getError(); if (err != gl.NO_ERROR) { errFn("*** Error loading shader '" + shader + "':" + glEnumToString(gl, err)); return null; } // Compile the shader gl.compileShader(shader); if (opt_logShaders) { var label = shaderType == gl.VERTEX_SHADER ? 'vertex shader' : 'fragment_shader'; if (opt_shaderLabel) { label = opt_shaderLabel + ' ' + label; } addShaderSources( gl, document.getElementById('console'), label, shader, shaderSource, opt_url); } // Check the compile status if (!opt_skipCompileStatus) { var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS); if (!compiled) { // Something went wrong during compilation; get the error lastError = gl.getShaderInfoLog(shader); errFn("*** Error compiling " + glEnumToString(gl, shaderType) + " '" + shader + "':" + lastError); gl.deleteShader(shader); return null; } } return shader; } /** * Loads a shader from a URL. * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {file} file The URL of the shader source. * @param {number} type The type of shader. * @param {function(string): void} opt_errorCallback callback for errors. * @param {boolean} opt_logShaders Whether to log shader source. * @param {boolean} Skip compilation status check. Default = false. * @return {!WebGLShader} The created shader. */ var loadShaderFromFile = function( gl, file, type, opt_errorCallback, opt_logShaders, opt_skipCompileStatus) { var shaderSource = readFile(file); return loadShader(gl, shaderSource, type, opt_errorCallback, opt_logShaders, undefined, file, opt_skipCompileStatus); }; var loadShaderFromFileAsync = function( gl, file, type, opt_errorCallback, opt_logShaders, opt_skipCompileStatus, callback) { loadTextFileAsync(file, function(gl, type, opt_errorCallback, opt_logShaders, file, opt_skipCompileStatus){ return function(success, shaderSource) { if (success) { var shader = loadShader(gl, shaderSource, type, opt_errorCallback, opt_logShaders, undefined, file, opt_skipCompileStatus); callback(true, shader); } else { callback(false, null); } } }(gl, type, opt_errorCallback, opt_logShaders, file, opt_skipCompileStatus)); }; /** * Gets the content of script. * @param {string} scriptId The id of the script tag. * @return {string} The content of the script. */ var getScript = function(scriptId) { var shaderScript = document.getElementById(scriptId); if (!shaderScript) { throw("*** Error: unknown script element " + scriptId); } return shaderScript.text; }; /** * Loads a shader from a script tag. * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {string} scriptId The id of the script tag. * @param {number} opt_shaderType The type of shader. If not passed in it will * be derived from the type of the script tag. * @param {function(string): void} opt_errorCallback callback for errors. * @param {boolean} opt_logShaders Whether to log shader source. * @param {boolean} Skip compilation status check. Default = false. * @return {!WebGLShader} The created shader. */ var loadShaderFromScript = function( gl, scriptId, opt_shaderType, opt_errorCallback, opt_logShaders, opt_skipCompileStatus) { var shaderSource = ""; var shaderScript = document.getElementById(scriptId); if (!shaderScript) { throw("*** Error: unknown script element " + scriptId); } shaderSource = shaderScript.text; if (!opt_shaderType) { if (shaderScript.type == "x-shader/x-vertex") { opt_shaderType = gl.VERTEX_SHADER; } else if (shaderScript.type == "x-shader/x-fragment") { opt_shaderType = gl.FRAGMENT_SHADER; } else { throw("*** Error: unknown shader type"); return null; } } return loadShader(gl, shaderSource, opt_shaderType, opt_errorCallback, opt_logShaders, undefined, undefined, opt_skipCompileStatus); }; var loadStandardProgram = function(gl) { var program = gl.createProgram(); gl.attachShader(program, loadStandardVertexShader(gl)); gl.attachShader(program, loadStandardFragmentShader(gl)); gl.bindAttribLocation(program, 0, "a_vertex"); gl.bindAttribLocation(program, 1, "a_normal"); linkProgram(gl, program); return program; }; var loadStandardProgramAsync = function(gl, callback) { loadStandardVertexShaderAsync(gl, function(gl) { return function(success, vs) { if (success) { loadStandardFragmentShaderAsync(gl, function(vs) { return function(success, fs) { if (success) { var program = gl.createProgram(); gl.attachShader(program, vs); gl.attachShader(program, fs); gl.bindAttribLocation(program, 0, "a_vertex"); gl.bindAttribLocation(program, 1, "a_normal"); linkProgram(gl, program); callback(true, program); } else { callback(false, null); } }; }(vs)); } else { callback(false, null); } }; }(gl)); }; /** * Loads shaders from files, creates a program, attaches the shaders and links. * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {string} vertexShaderPath The URL of the vertex shader. * @param {string} fragmentShaderPath The URL of the fragment shader. * @param {function(string): void} opt_errorCallback callback for errors. * @return {!WebGLProgram} The created program. */ var loadProgramFromFile = function( gl, vertexShaderPath, fragmentShaderPath, opt_errorCallback) { var program = gl.createProgram(); var vs = loadShaderFromFile( gl, vertexShaderPath, gl.VERTEX_SHADER, opt_errorCallback); var fs = loadShaderFromFile( gl, fragmentShaderPath, gl.FRAGMENT_SHADER, opt_errorCallback); if (vs && fs) { gl.attachShader(program, vs); gl.attachShader(program, fs); linkProgram(gl, program, opt_errorCallback); } if (vs) { gl.deleteShader(vs); } if (fs) { gl.deleteShader(fs); } return program; }; /** * Loads shaders from script tags, creates a program, attaches the shaders and * links. * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {string} vertexScriptId The id of the script tag that contains the * vertex shader. * @param {string} fragmentScriptId The id of the script tag that contains the * fragment shader. * @param {function(string): void} opt_errorCallback callback for errors. * @return {!WebGLProgram} The created program. */ var loadProgramFromScript = function loadProgramFromScript( gl, vertexScriptId, fragmentScriptId, opt_errorCallback) { var program = gl.createProgram(); gl.attachShader( program, loadShaderFromScript( gl, vertexScriptId, gl.VERTEX_SHADER, opt_errorCallback)); gl.attachShader( program, loadShaderFromScript( gl, fragmentScriptId, gl.FRAGMENT_SHADER, opt_errorCallback)); linkProgram(gl, program, opt_errorCallback); return program; }; /** * Loads shaders from source, creates a program, attaches the shaders and * links. * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {!WebGLShader} vertexShader The vertex shader. * @param {!WebGLShader} fragmentShader The fragment shader. * @param {function(string): void} opt_errorCallback callback for errors. * @return {!WebGLProgram} The created program. */ var createProgram = function(gl, vertexShader, fragmentShader, opt_errorCallback) { var program = gl.createProgram(); gl.attachShader(program, vertexShader); gl.attachShader(program, fragmentShader); linkProgram(gl, program, opt_errorCallback); return program; }; /** * Loads shaders from source, creates a program, attaches the shaders and * links. * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {string} vertexShader The vertex shader source. * @param {string} fragmentShader The fragment shader source. * @param {function(string): void} opt_errorCallback callback for errors. * @param {boolean} opt_logShaders Whether to log shader source. * @return {!WebGLProgram} The created program. */ var loadProgram = function( gl, vertexShader, fragmentShader, opt_errorCallback, opt_logShaders) { var program; var vs = loadShader( gl, vertexShader, gl.VERTEX_SHADER, opt_errorCallback, opt_logShaders); var fs = loadShader( gl, fragmentShader, gl.FRAGMENT_SHADER, opt_errorCallback, opt_logShaders); if (vs && fs) { program = createProgram(gl, vs, fs, opt_errorCallback) } if (vs) { gl.deleteShader(vs); } if (fs) { gl.deleteShader(fs); } return program; }; /** * Loads shaders from source, creates a program, attaches the shaders and * links but expects error. * * GLSL 1.0.17 10.27 effectively says that compileShader can * always succeed as long as linkProgram fails so we can't * rely on compileShader failing. This function expects * one of the shader to fail OR linking to fail. * * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {string} vertexShaderScriptId The vertex shader. * @param {string} fragmentShaderScriptId The fragment shader. * @return {WebGLProgram} The created program. */ var loadProgramFromScriptExpectError = function( gl, vertexShaderScriptId, fragmentShaderScriptId) { var vertexShader = loadShaderFromScript(gl, vertexShaderScriptId); if (!vertexShader) { return null; } var fragmentShader = loadShaderFromScript(gl, fragmentShaderScriptId); if (!fragmentShader) { return null; } var linkSuccess = true; var program = gl.createProgram(); gl.attachShader(program, vertexShader); gl.attachShader(program, fragmentShader); linkSuccess = true; linkProgram(gl, program, function() { linkSuccess = false; }); return linkSuccess ? program : null; }; var getActiveMap = function(gl, program, typeInfo) { var numVariables = gl.getProgramParameter(program, gl[typeInfo.param]); var variables = {}; for (var ii = 0; ii < numVariables; ++ii) { var info = gl[typeInfo.activeFn](program, ii); variables[info.name] = { name: info.name, size: info.size, type: info.type, location: gl[typeInfo.locFn](program, info.name) }; } return variables; }; /** * Returns a map of attrib names to info about those * attribs. * * eg: * { "attrib1Name": * { * name: "attrib1Name", * size: 1, * type: gl.FLOAT_MAT2, * location: 0 * }, * "attrib2Name[0]": * { * name: "attrib2Name[0]", * size: 4, * type: gl.FLOAT, * location: 1 * }, * } * * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {WebGLProgram} The program to query for attribs. * @return the map. */ var getAttribMap = function(gl, program) { return getActiveMap(gl, program, { param: "ACTIVE_ATTRIBUTES", activeFn: "getActiveAttrib", locFn: "getAttribLocation" }); }; /** * Returns a map of uniform names to info about those uniforms. * * eg: * { "uniform1Name": * { * name: "uniform1Name", * size: 1, * type: gl.FLOAT_MAT2, * location: WebGLUniformLocation * }, * "uniform2Name[0]": * { * name: "uniform2Name[0]", * size: 4, * type: gl.FLOAT, * location: WebGLUniformLocation * }, * } * * @param {!WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {WebGLProgram} The program to query for uniforms. * @return the map. */ var getUniformMap = function(gl, program) { return getActiveMap(gl, program, { param: "ACTIVE_UNIFORMS", activeFn: "getActiveUniform", locFn: "getUniformLocation" }); }; var basePath; var getResourcePath = function() { if (!basePath) { var expectedBase = "js/webgl-test-utils.js"; var scripts = document.getElementsByTagName('script'); for (var script, i = 0; script = scripts[i]; i++) { var src = script.src; var l = src.length; if (src.substr(l - expectedBase.length) == expectedBase) { basePath = src.substr(0, l - expectedBase.length); } } } return basePath + "resources/"; }; var loadStandardVertexShader = function(gl) { return loadShaderFromFile( gl, getResourcePath() + "vertexShader.vert", gl.VERTEX_SHADER); }; var loadStandardVertexShaderAsync = function(gl, callback) { loadShaderFromFileAsync(gl, getResourcePath() + "vertexShader.vert", gl.VERTEX_SHADER, undefined, undefined, undefined, callback); }; var loadStandardFragmentShader = function(gl) { return loadShaderFromFile( gl, getResourcePath() + "fragmentShader.frag", gl.FRAGMENT_SHADER); }; var loadStandardFragmentShaderAsync = function(gl, callback) { loadShaderFromFileAsync(gl, getResourcePath() + "fragmentShader.frag", gl.FRAGMENT_SHADER, undefined, undefined, undefined, callback); }; var loadUniformBlockProgram = function(gl) { var program = gl.createProgram(); gl.attachShader(program, loadUniformBlockVertexShader(gl)); gl.attachShader(program, loadUniformBlockFragmentShader(gl)); gl.bindAttribLocation(program, 0, "a_vertex"); gl.bindAttribLocation(program, 1, "a_normal"); linkProgram(gl, program); return program; }; var loadUniformBlockVertexShader = function(gl) { return loadShaderFromFile( gl, getResourcePath() + "uniformBlockShader.vert", gl.VERTEX_SHADER); }; var loadUniformBlockFragmentShader = function(gl) { return loadShaderFromFile( gl, getResourcePath() + "uniformBlockShader.frag", gl.FRAGMENT_SHADER); }; /** * Loads an image asynchronously. * @param {string} url URL of image to load. * @param {!function(!Element): void} callback Function to call * with loaded image. */ var loadImageAsync = function(url, callback) { var img = document.createElement('img'); img.onload = function() { callback(img); }; img.src = url; }; /** * Loads an array of images. * @param {!Array.<string>} urls URLs of images to load. * @param {!function(!{string, img}): void} callback Callback * that gets passed map of urls to img tags. */ var loadImagesAsync = function(urls, callback) { var count = 1; var images = { }; function countDown() { --count; if (count == 0) { log("loadImagesAsync: all images loaded"); callback(images); } } function imageLoaded(url) { return function(img) { images[url] = img; log("loadImagesAsync: loaded " + url); countDown(); } } for (var ii = 0; ii < urls.length; ++ii) { ++count; loadImageAsync(urls[ii], imageLoaded(urls[ii])); } countDown(); }; /** * Returns a map of key=value values from url. * @return {!Object.<string, number>} map of keys to values. */ var getUrlArguments = function() { var args = {}; try { var s = window.location.href; var q = s.indexOf("?"); var e = s.indexOf("#"); if (e < 0) { e = s.length; } var query = s.substring(q + 1, e); var pairs = query.split("&"); for (var ii = 0; ii < pairs.length; ++ii) { var keyValue = pairs[ii].split("="); var key = keyValue[0]; var value = decodeURIComponent(keyValue[1]); args[key] = value; } } catch (e) { throw "could not parse url"; } return args; }; /** * Makes an image from a src. * @param {string} src Image source URL. * @param {function()} onload Callback to call when the image has finised loading. * @param {function()} onerror Callback to call when an error occurs. * @return {!Image} The created image. */ var makeImage = function(src, onload, onerror) { var img = document.createElement('img'); if (onload) { img.onload = onload; } if (onerror) { img.onerror = onerror; } else { img.onerror = function() { log("WARNING: creating image failed; src: " + this.src); }; } if (src) { img.src = src; } return img; } /** * Makes an image element from a canvas. * @param {!HTMLCanvas} canvas Canvas to make image from. * @param {function()} onload Callback to call when the image has finised loading. * @param {string} imageFormat Image format to be passed to toDataUrl(). * @return {!Image} The created image. */ var makeImageFromCanvas = function(canvas, onload, imageFormat) { return makeImage(canvas.toDataURL(imageFormat), onload); }; /** * Makes a video element from a src. * @param {string} src Video source URL. * @param {function()} onerror Callback to call when an error occurs. * @return {!Video} The created video. */ var makeVideo = function(src, onerror) { var vid = document.createElement('video'); if (onerror) { vid.onerror = onerror; } else { vid.onerror = function() { log("WARNING: creating video failed; src: " + this.src); }; } if (src) { vid.src = src; } return vid; } /** * Inserts an image with a caption into 'element'. * @param {!HTMLElement} element Element to append image to. * @param {string} caption caption to associate with image. * @param {!Image} img image to insert. */ var insertImage = function(element, caption, img) { var div = document.createElement("div"); var label = document.createElement("div"); label.appendChild(document.createTextNode(caption)); div.appendChild(label); div.appendChild(img); element.appendChild(div); }; /** * Inserts a 'label' that when clicked expands to the pre formatted text * supplied by 'source'. * @param {!HTMLElement} element element to append label to. * @param {string} label label for anchor. * @param {string} source preformatted text to expand to. * @param {string} opt_url URL of source. If provided a link to the source file * will also be added. */ var addShaderSource = function(element, label, source, opt_url) { var div = document.createElement("div"); var s = document.createElement("pre"); s.className = "shader-source"; s.style.display = "none"; var ol = document.createElement("ol"); //s.appendChild(document.createTextNode(source)); var lines = source.split("\n"); for (var ii = 0; ii < lines.length; ++ii) { var line = lines[ii]; var li = document.createElement("li"); li.appendChild(document.createTextNode(line)); ol.appendChild(li); } s.appendChild(ol); var l = document.createElement("a"); l.href = "show-shader-source"; l.appendChild(document.createTextNode(label)); l.addEventListener('click', function(event) { if (event.preventDefault) { event.preventDefault(); } s.style.display = (s.style.display == 'none') ? 'block' : 'none'; return false; }, false); div.appendChild(l); if (opt_url) { var u = document.createElement("a"); u.href = opt_url; div.appendChild(document.createTextNode(" ")); u.appendChild(document.createTextNode("(" + opt_url + ")")); div.appendChild(u); } div.appendChild(s); element.appendChild(div); }; /** * Inserts labels that when clicked expand to show the original source of the * shader and also translated source of the shader, if that is available. * @param {WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {!HTMLElement} element element to append label to. * @param {string} label label for anchor. * @param {WebGLShader} shader Shader to show the sources for. * @param {string} shaderSource Original shader source. * @param {string} opt_url URL of source. If provided a link to the source file * will also be added. */ var addShaderSources = function( gl, element, label, shader, shaderSource, opt_url) { addShaderSource(element, label, shaderSource, opt_url); var debugShaders = gl.getExtension('WEBGL_debug_shaders'); if (debugShaders && shader) { var translatedSource = debugShaders.getTranslatedShaderSource(shader); if (translatedSource != '') { addShaderSource(element, label + ' translated for driver', translatedSource); } } }; /** * Sends shader information to the server to be dumped into text files * when tests are run from within the test-runner harness. * @param {WebGLRenderingContext} gl The WebGLRenderingContext to use. * @param {string} url URL of current. * @param {string} passMsg Test description. * @param {object} vInfo Object containing vertex shader information. * @param {object} fInfo Object containing fragment shader information. */ var dumpShadersInfo = function(gl, url, passMsg, vInfo, fInfo) { var shaderInfo = {}; shaderInfo.url = url; shaderInfo.testDescription = passMsg; shaderInfo.vLabel = vInfo.label; shaderInfo.vShouldCompile = vInfo.shaderSuccess; shaderInfo.vSource = vInfo.source; shaderInfo.fLabel = fInfo.label; shaderInfo.fShouldCompile = fInfo.shaderSuccess; shaderInfo.fSource = fInfo.source; shaderInfo.vTranslatedSource = null; shaderInfo.fTranslatedSource = null; var debugShaders = gl.getExtension('WEBGL_debug_shaders'); if (debugShaders) { if (vInfo.shader) shaderInfo.vTranslatedSource = debugShaders.getTranslatedShaderSource(vInfo.shader); if (fInfo.shader) shaderInfo.fTranslatedSource = debugShaders.getTranslatedShaderSource(fInfo.shader); } var dumpShaderInfoRequest = new XMLHttpRequest(); dumpShaderInfoRequest.open('POST', "/dumpShaderInfo", true); dumpShaderInfoRequest.setRequestHeader("Content-Type", "text/plain"); dumpShaderInfoRequest.send(JSON.stringify(shaderInfo)); }; // Add your prefix here. var browserPrefixes = [ "", "MOZ_", "OP_", "WEBKIT_" ]; /** * Given an extension name like WEBGL_compressed_texture_s3tc * returns the name of the supported version extension, like * WEBKIT_WEBGL_compressed_teture_s3tc * @param {string} name Name of extension to look for. * @return {string} name of extension found or undefined if not * found. */ var getSupportedExtensionWithKnownPrefixes = function(gl, name) { var supported = gl.getSupportedExtensions(); for (var ii = 0; ii < browserPrefixes.length; ++ii) { var prefixedName = browserPrefixes[ii] + name; if (supported.indexOf(prefixedName) >= 0) { return prefixedName; } } }; /** * Given an extension name like WEBGL_compressed_texture_s3tc * returns the supported version extension, like * WEBKIT_WEBGL_compressed_teture_s3tc * @param {string} name Name of extension to look for. * @return {WebGLExtension} The extension or undefined if not * found. */ var getExtensionWithKnownPrefixes = function(gl, name) { for (var ii = 0; ii < browserPrefixes.length; ++ii) { var prefixedName = browserPrefixes[ii] + name; var ext = gl.getExtension(prefixedName); if (ext) { return ext; } } }; /** * Returns possible prefixed versions of an extension's name. * @param {string} name Name of extension. May already include a prefix. * @return {Array.<string>} Variations of the extension name with known * browser prefixes. */ var getExtensionPrefixedNames = function(name) { var unprefix = function(name) { for (var ii = 0; ii < browserPrefixes.length; ++ii) { if (browserPrefixes[ii].length > 0 && name.substring(0, browserPrefixes[ii].length).toLowerCase() === browserPrefixes[ii].toLowerCase()) { return name.substring(browserPrefixes[ii].length); } } return name; } var unprefixed = unprefix(name); var variations = []; for (var ii = 0; ii < browserPrefixes.length; ++ii) { variations.push(browserPrefixes[ii] + unprefixed); } return variations; }; var replaceRE = /\$\((\w+)\)/g; /** * Replaces strings with property values. * Given a string like "hello $(first) $(last)" and an object * like {first:"John", last:"Smith"} will return * "hello John Smith". * @param {string} str String to do replacements in. * @param {...} 1 or more objects containing properties. */ var replaceParams = function(str) { var args = arguments; return str.replace(replaceRE, function(str, p1, offset, s) { for (var ii = 1; ii < args.length; ++ii) { if (args[ii][p1] !== undefined) { return args[ii][p1]; } } throw "unknown string param '" + p1 + "'"; }); }; var upperCaseFirstLetter = function(str) { return str.substring(0, 1).toUpperCase() + str.substring(1); }; /** * Gets a prefixed property. For example, * * var fn = getPrefixedProperty( * window, * "requestAnimationFrame"); * * Will return either: * "window.requestAnimationFrame", * "window.oRequestAnimationFrame", * "window.msRequestAnimationFrame", * "window.mozRequestAnimationFrame", * "window.webKitRequestAnimationFrame", * undefined * * the non-prefixed function is tried first. */ var propertyPrefixes = ["", "moz", "ms", "o", "webkit"]; var getPrefixedProperty = function(obj, propertyName) { for (var ii = 0; ii < propertyPrefixes.length; ++ii) { var prefix = propertyPrefixes[ii]; var name = prefix + propertyName; log(name); var property = obj[name]; if (property) { return property; } if (ii == 0) { propertyName = upperCaseFirstLetter(propertyName); } } return undefined; }; var _requestAnimFrame; /** * Provides requestAnimationFrame in a cross browser way. */ var requestAnimFrame = function(callback) { if (!_requestAnimFrame) { _requestAnimFrame = getPrefixedProperty(window, "requestAnimationFrame") || function(callback, element) { return window.setTimeout(callback, 1000 / 70); }; } _requestAnimFrame.call(window, callback); }; var _cancelAnimFrame; /** * Provides cancelAnimationFrame in a cross browser way. */ var cancelAnimFrame = function(request) { if (!_cancelAnimFrame) { _cancelAnimFrame = getPrefixedProperty(window, "cancelAnimationFrame") || window.clearTimeout; } _cancelAnimFrame.call(window, request); }; /** * Provides requestFullScreen in a cross browser way. */ var requestFullScreen = function(element) { var fn = getPrefixedProperty(element, "requestFullScreen"); if (fn) { fn.call(element); } }; /** * Provides cancelFullScreen in a cross browser way. */ var cancelFullScreen = function() { var fn = getPrefixedProperty(document, "cancelFullScreen"); if (fn) { fn.call(document); } }; var fullScreenStateName; (function() { var fullScreenStateNames = [ "isFullScreen", "fullScreen" ]; for (var ii = 0; ii < fullScreenStateNames.length; ++ii) { var propertyName = fullScreenStateNames[ii]; for (var jj = 0; jj < propertyPrefixes.length; ++jj) { var prefix = propertyPrefixes[jj]; if (prefix.length) { propertyName = upperCaseFirstLetter(propertyName); fullScreenStateName = prefix + propertyName; if (document[fullScreenStateName] !== undefined) { return; } } } fullScreenStateName = undefined; } }()); /** * @return {boolean} True if fullscreen mode is active. */ var getFullScreenState = function() { log("fullscreenstatename:" + fullScreenStateName); log(document[fullScreenStateName]); return document[fullScreenStateName]; }; /** * @param {!HTMLElement} element The element to go fullscreen. * @param {!function(boolean)} callback A function that will be called * when entering/exiting fullscreen. It is passed true if * entering fullscreen, false if exiting. */ var onFullScreenChange = function(element, callback) { propertyPrefixes.forEach(function(prefix) { var eventName = prefix + "fullscreenchange"; log("addevent: " + eventName); document.addEventListener(eventName, function(event) { log("event: " + eventName); callback(getFullScreenState()); }); }); }; /** * @param {!string} buttonId The id of the button that will toggle fullscreen * mode. * @param {!string} fullscreenId The id of the element to go fullscreen. * @param {!function(boolean)} callback A function that will be called * when entering/exiting fullscreen. It is passed true if * entering fullscreen, false if exiting. * @return {boolean} True if fullscreen mode is supported. */ var setupFullscreen = function(buttonId, fullscreenId, callback) { if (!fullScreenStateName) { return false; } var fullscreenElement = document.getElementById(fullscreenId); onFullScreenChange(fullscreenElement, callback); var toggleFullScreen = function(event) { if (getFullScreenState()) { cancelFullScreen(fullscreenElement); } else { requestFullScreen(fullscreenElement); } event.preventDefault(); return false; }; var buttonElement = document.getElementById(buttonId); buttonElement.addEventListener('click', toggleFullScreen); return true; }; /** * Waits for the browser to composite the web page. * @param {function()} callback A function to call after compositing has taken * place. */ var waitForComposite = function(callback) { var frames = 5; var countDown = function() { if (frames == 0) { // TODO(kbr): unify with js-test-pre.js and enable these with // verbose logging. // log("waitForComposite: callback"); callback(); } else { // log("waitForComposite: countdown(" + frames + ")"); --frames; requestAnimFrame.call(window, countDown); } }; countDown(); }; /** * Runs an array of functions, yielding to the browser between each step. * If you want to know when all the steps are finished add a last step. * @param {!Array.<function(): void>} steps Array of functions. */ var runSteps = function(steps) { if (!steps.length) { return; } // copy steps so they can't be modifed. var stepsToRun = steps.slice(); var currentStep = 0; var runNextStep = function() { stepsToRun[currentStep++](); if (currentStep < stepsToRun.length) { setTimeout(runNextStep, 1); } }; runNextStep(); }; /** * Starts playing a video and waits for it to be consumable. * @param {!HTMLVideoElement} video An HTML5 Video element. * @param {!function(!HTMLVideoElement): void} callback Function to call when * video is ready. */ var startPlayingAndWaitForVideo = function(video, callback) { var gotPlaying = false; var gotTimeUpdate = false; var maybeCallCallback = function() { if (gotPlaying && gotTimeUpdate && callback) { callback(video); callback = undefined; video.removeEventListener('playing', playingListener, true); video.removeEventListener('timeupdate', timeupdateListener, true); } }; var playingListener = function() { gotPlaying = true; maybeCallCallback(); }; var timeupdateListener = function() { // Checking to make sure the current time has advanced beyond // the start time seems to be a reliable heuristic that the // video element has data that can be consumed. if (video.currentTime > 0.0) { gotTimeUpdate = true; maybeCallCallback(); } }; video.addEventListener('playing', playingListener, true); video.addEventListener('timeupdate', timeupdateListener, true); video.loop = true; video.play(); }; var getHost = function(url) { url = url.replace("\\", "/"); var pos = url.indexOf("://"); if (pos >= 0) { url = url.substr(pos + 3); } var parts = url.split('/'); return parts[0]; } // This function returns the last 2 words of the domain of a URL // This is probably not the correct check but it will do for now. var getBaseDomain = function(host) { var parts = host.split(":"); var hostname = parts[0]; var port = parts[1] || "80"; parts = hostname.split("."); if(parts.length < 2) return hostname + ":" + port; var tld = parts[parts.length-1]; var domain = parts[parts.length-2]; return domain + "." + tld + ":" + port; } var runningOnLocalhost = function() { return window.location.hostname.indexOf("localhost") != -1 || window.location.hostname.indexOf("127.0.0.1") != -1; } var getLocalCrossOrigin = function() { var domain; if (window.location.host.indexOf("localhost") != -1) { domain = "127.0.0.1"; } else { domain = "localhost"; } var port = window.location.port || "80"; return window.location.protocol + "//" + domain + ":" + port } var getRelativePath = function(path) { var relparts = window.location.pathname.split("/"); relparts.pop(); // Pop off filename var pathparts = path.split("/"); var i; for (i = 0; i < pathparts.length; ++i) { switch (pathparts[i]) { case "": break; case ".": break; case "..": relparts.pop(); break; default: relparts.push(pathparts[i]); break; } } return relparts.join("/"); } var setupImageForCrossOriginTest = function(img, imgUrl, localUrl, callback) { window.addEventListener("load", function() { if (typeof(img) == "string") img = document.querySelector(img); if (!img) img = new Image(); img.addEventListener("load", callback, false); img.addEventListener("error", callback, false); if (runningOnLocalhost()) img.src = getLocalCrossOrigin() + getRelativePath(localUrl); else img.src = getUrlOptions().imgUrl || imgUrl; }, false); } /** * Convert sRGB color to linear color. * @param {!Array.<number>} color The color to be converted. * The array has 4 elements, for example [R, G, B, A]. * where each element is in the range 0 to 255. * @return {!Array.<number>} color The color to be converted. * The array has 4 elements, for example [R, G, B, A]. * where each element is in the range 0 to 255. */ var sRGBToLinear = function(color) { return [sRGBChannelToLinear(color[0]), sRGBChannelToLinear(color[1]), sRGBChannelToLinear(color[2]), color[3]] } /** * Convert linear color to sRGB color. * @param {!Array.<number>} color The color to be converted. * The array has 4 elements, for example [R, G, B, A]. * where each element is in the range 0 to 255. * @return {!Array.<number>} color The color to be converted. * The array has 4 elements, for example [R, G, B, A]. * where each element is in the range 0 to 255. */ var linearToSRGB = function(color) { return [linearChannelToSRGB(color[0]), linearChannelToSRGB(color[1]), linearChannelToSRGB(color[2]), color[3]] } function sRGBChannelToLinear(value) { value = value / 255; if (value <= 0.04045) value = value / 12.92; else value = Math.pow((value + 0.055) / 1.055, 2.4); return Math.trunc(value * 255 + 0.5); } function linearChannelToSRGB(value) { value = value / 255; if (value <= 0.0) { value = 0.0; } else if (value < 0.0031308) { value = value * 12.92; } else if (value < 1) { value = Math.pow(value, 0.41666) * 1.055 - 0.055; } else { value = 1.0; } return Math.trunc(value * 255 + 0.5); } var API = { addShaderSource: addShaderSource, addShaderSources: addShaderSources, cancelAnimFrame: cancelAnimFrame, create3DContext: create3DContext, GLErrorException: GLErrorException, create3DContextWithWrapperThatThrowsOnGLError: create3DContextWithWrapperThatThrowsOnGLError, checkAreaInAndOut: checkAreaInAndOut, checkCanvas: checkCanvas, checkCanvasRect: checkCanvasRect, checkCanvasRectColor: checkCanvasRectColor, checkCanvasRects: checkCanvasRects, checkFloatBuffer: checkFloatBuffer, checkTextureSize: checkTextureSize, clipToRange: clipToRange, createColoredTexture: createColoredTexture, createProgram: createProgram, clearAndDrawUnitQuad: clearAndDrawUnitQuad, clearAndDrawIndexedQuad: clearAndDrawIndexedQuad, drawUnitQuad: drawUnitQuad, drawIndexedQuad: drawIndexedQuad, drawUByteColorQuad: drawUByteColorQuad, drawFloatColorQuad: drawFloatColorQuad, dumpShadersInfo: dumpShadersInfo, endsWith: endsWith, failIfGLError: failIfGLError, fillTexture: fillTexture, getBytesPerComponent: getBytesPerComponent, getDefault3DContextVersion: getDefault3DContextVersion, getExtensionPrefixedNames: getExtensionPrefixedNames, getExtensionWithKnownPrefixes: getExtensionWithKnownPrefixes, getFileListAsync: getFileListAsync, getLastError: getLastError, getPrefixedProperty: getPrefixedProperty, getScript: getScript, getSupportedExtensionWithKnownPrefixes: getSupportedExtensionWithKnownPrefixes, getTypedArrayElementsPerPixel: getTypedArrayElementsPerPixel, getUrlArguments: getUrlArguments, getUrlOptions: getUrlOptions, getAttribMap: getAttribMap, getUniformMap: getUniformMap, glEnumToString: glEnumToString, glErrorShouldBe: glErrorShouldBe, glTypeToTypedArrayType: glTypeToTypedArrayType, hasAttributeCaseInsensitive: hasAttributeCaseInsensitive, insertImage: insertImage, loadImageAsync: loadImageAsync, loadImagesAsync: loadImagesAsync, loadProgram: loadProgram, loadProgramFromFile: loadProgramFromFile, loadProgramFromScript: loadProgramFromScript, loadProgramFromScriptExpectError: loadProgramFromScriptExpectError, loadShader: loadShader, loadShaderFromFile: loadShaderFromFile, loadShaderFromScript: loadShaderFromScript, loadStandardProgram: loadStandardProgram, loadStandardProgramAsync: loadStandardProgramAsync, loadStandardVertexShader: loadStandardVertexShader, loadStandardVertexShaderAsync: loadStandardVertexShaderAsync, loadStandardFragmentShader: loadStandardFragmentShader, loadStandardFragmentShaderAsync: loadStandardFragmentShaderAsync, loadUniformBlockProgram: loadUniformBlockProgram, loadUniformBlockVertexShader: loadUniformBlockVertexShader, loadUniformBlockFragmentShader: loadUniformBlockFragmentShader, loadTextFileAsync: loadTextFileAsync, loadTexture: loadTexture, log: log, loggingOff: loggingOff, makeCheckRect: makeCheckRect, makeImage: makeImage, makeImageFromCanvas: makeImageFromCanvas, makeVideo: makeVideo, error: error, shallowCopyObject: shallowCopyObject, setDefault3DContextVersion: setDefault3DContextVersion, setupColorQuad: setupColorQuad, setupProgram: setupProgram, setupTransformFeedbackProgram: setupTransformFeedbackProgram, setupQuad: setupQuad, setupIndexedQuad: setupIndexedQuad, setupIndexedQuadWithOptions: setupIndexedQuadWithOptions, setupSimpleColorProgram: setupSimpleColorProgram, setupSimpleTextureProgram: setupSimpleTextureProgram, setupSimpleCubeMapTextureProgram: setupSimpleCubeMapTextureProgram, setupSimpleVertexColorProgram: setupSimpleVertexColorProgram, setupNoTexCoordTextureProgram: setupNoTexCoordTextureProgram, setupTexturedQuad: setupTexturedQuad, setupTexturedQuadWithTexCoords: setupTexturedQuadWithTexCoords, setupTexturedQuadWithCubeMap: setupTexturedQuadWithCubeMap, setupUnitQuad: setupUnitQuad, setupUnitQuadWithTexCoords: setupUnitQuadWithTexCoords, setFloatDrawColor: setFloatDrawColor, setUByteDrawColor: setUByteDrawColor, startPlayingAndWaitForVideo: startPlayingAndWaitForVideo, startsWith: startsWith, shouldGenerateGLError: shouldGenerateGLError, readFile: readFile, readFileList: readFileList, replaceParams: replaceParams, requestAnimFrame: requestAnimFrame, runSteps: runSteps, waitForComposite: waitForComposite, // fullscreen api setupFullscreen: setupFullscreen, // sRGB converter api sRGBToLinear: sRGBToLinear, linearToSRGB: linearToSRGB, getHost: getHost, getBaseDomain: getBaseDomain, runningOnLocalhost: runningOnLocalhost, getLocalCrossOrigin: getLocalCrossOrigin, getRelativePath: getRelativePath, setupImageForCrossOriginTest: setupImageForCrossOriginTest, none: false }; Object.defineProperties(API, { noTexCoordTextureVertexShader: { value: noTexCoordTextureVertexShader, writable: false }, simpleTextureVertexShader: { value: simpleTextureVertexShader, writable: false }, simpleColorFragmentShader: { value: simpleColorFragmentShader, writable: false }, simpleVertexShader: { value: simpleVertexShader, writable: false }, simpleTextureFragmentShader: { value: simpleTextureFragmentShader, writable: false }, simpleCubeMapTextureFragmentShader: { value: simpleCubeMapTextureFragmentShader, writable: false }, simpleVertexColorFragmentShader: { value: simpleVertexColorFragmentShader, writable: false }, simpleVertexColorVertexShader: { value: simpleVertexColorVertexShader, writable: false } }); return API; }());
Yukarumya/Yukarum-Redfoxes
dom/canvas/test/webgl-conf/checkout/js/webgl-test-utils.js
JavaScript
mpl-2.0
104,349
var config = (function() { var title={ 'default' : '', 'wikidown':' [[Wikidown]](wikidown:home) ', 'jsh':' [[專為中學生寫的 JavaScript 程式書]](jsh:home) ', main:' [[Main]](main:home) ', }; var templateBySa='<%=wd%>\n\n----\n\n\<center style="font-size:small;color:#888888"><a href="https://creativecommons.org/licenses/by-sa/4.0/"><img src="web/img/by-sa.png" width="100"/></a><br/><a href="https://www.npmjs.com/package/wikidown">Powered by Wikidown!</a></center>\n'; var template={ 'default':templateBySa, 'wikidown':templateBySa }; var sideBook = "Book#home#active;Directory#directory;Content#content;Appendix#appendix;Reference#reference;"; var sideMooc = "Course#home#active;Textbook#textbook;Lecture#lecture;Video#video;Information#information#active;Assignment#assignment;Announcement#announcement;Overview#overview;Discussion#discussion;Reference#reference;"; var side={ 'default':'', wikidown:'', main:'' } return { title: title, side: side, template: template, } })(); if (typeof module !== 'undefined') module.exports = config;
ccckmit/fdbserver
web/config.js
JavaScript
mpl-2.0
1,171
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* * Copyright (c) 2014, Joyent, Inc. */ /* * Moray cache. */ var assert = require('assert-plus'); /* * Moray cache client constructor */ function Moray(options) { assert.object(options, 'moray-cache options'); assert.object(options.client, 'moray-cache options.client'); this.options = options; this.client = options.client; } /* * For a Moray cache just return right away since the moray connection is being * setup by the moray client separately */ Moray.prototype.connect = function (cb) { return cb(null); }; /* * Returns client.connected */ Moray.prototype.connected = function () { return this.client && this.client.connected; }; /* * Gets a list of VMs that live on a server */ Moray.prototype.getVmsForServer = function (server, callback) { return this.client.getVmsForServer(server, callback); }; /* * Sets a list of VMs that live on a server */ Moray.prototype.setVmsForServer = function (server, hash, callback) { return this.client.setVmsForServer(server, hash, callback); }; /* * Gets the status stamp for a VM. The stamp format has the following form: * * $zone_state:$last_modified * */ Moray.prototype.getState = function (uuid, callback) { return this.client.getState(uuid, callback); }; /* * Sets the state stamp for a VM. On a moray cache this is not needed because * we already persisted the VM state with either updateStateOnMoray or * updateVmOnMoray. In order to not break the interface we just call cb(); */ Moray.prototype.setState = function (uuid, hb, server, callback) { return callback(null); }; /* * Deletes the state stamp for a VM. Called after markAsDestroyed. On a moray * cache this is not needed because we already persisted the VM state as * destroyed with markAsDestroyed. In order to not break the interface we just * call cb(); */ Moray.prototype.delState = function (uuid, callback) { return callback(null); }; module.exports = Moray;
arekinath/sdc-vmapi
lib/cache/moray.js
JavaScript
mpl-2.0
2,186
var app = { planGroup: null, // Application Constructor initialize: function() { this.bindEvents(); }, bindEvents: function() { document.addEventListener('deviceready', this.onDeviceReady, false); }, onDeviceReady: function() { app.planGroup = document.getElementById('plan-group'); app.planGroup.loop = true; app.planGroup.addEventListener('touchstart', app.nextPlan); }, nextPlan: function() { app.planGroup.nextCard(); } } window.onload = function() { app.initialize(); }
zalun/school-plan-app
stage2/js/index.js
JavaScript
mpl-2.0
566
var userAgent = (window.navigator && navigator.userAgent) || "" function detect (pattern) { return pattern.test(userAgent) } function displayBanner (banner, browsers, categories) { if (detect(/Mobi/i)) return if ($.type(browsers) === 'string') browsers = [ browsers ] if ($.type(categories) === 'string') categories = [ categories ] var display = false for (var i = 0; i < browsers.length; i++) { var browser = browsers[i] switch (browser) { case 'chrome': display = detect(/Chrome/) break } if (display) break } if (display) { categories.forEach(category => { $('head').append(`<style> .category-${category} .download-banner-${banner} { display: block } </style>`) }) } }
LeoMcA/discourse-mozilla-theme
src/common/head_tag/2_display_banner.js
JavaScript
mpl-2.0
751
/** * Marching gulpfiles.js * */ 'use strict'; var path = require('path'), fs = require('graceful-fs'), argv = require('yargs').argv, requirejs = require('requirejs'), mergeStream = require('merge-stream'), gulp = require('gulp'), $ = require('gulp-load-plugins')(); var staticMap = JSON.parse(fs.readFileSync('./gulpfile.map', 'utf8')); /* A parameter to control optimization. */ var optimized = typeof argv.debug === 'undefined', whichWar = typeof argv.war === 'undefined' ? 0 : argv.war; var paths = { source: { stc: argv.SRC_DOCROOT || staticMap[whichWar].SRC_DOCROOT, war: argv.SRC_WARROOT || staticMap[whichWar].SRC_WARROOT }, dest: { stc: argv.DIST_DOCROOT || staticMap[whichWar].DIST_DOCROOT, war: argv.DIST_WARROOT || staticMap[whichWar].DIST_WARROOT }, bowerLib : 'node_modules', styles: 'css', scripts: 'js', lib: 'lib', images: 'images', fonts: 'fonts' }; var sourcesPaths = { styles: { base: [path.join(paths.source.stc, paths.styles, '**', '*.css')], sass : path.join(paths.source.stc, paths.styles, '**', '*.{sass,scss}') }, scripts: { base: path.join(paths.source.stc, paths.scripts, '**', '*.{js,map}') }, images: { base: path.join(paths.source.stc, paths.images, '**', '*.{png,gif,jpg,ico}') }, fonts: { base: path.join(paths.source.stc, paths.fonts, '**', '*.{eot,svg,ttf,woff,woff2,otf}') }, war: path.join(paths.source.war, '**', '*'), other: { base: path.join(paths.source.stc, '**', '*.{html,pdf,txt}') } }, targetPaths = { styles: path.join(paths.dest.stc, paths.styles), scripts: path.join(paths.dest.stc, paths.scripts), images: path.join(paths.dest.stc, paths.images), fonts: path.join(paths.dest.stc, paths.fonts), other: path.join(paths.dest.stc) }; function processCSS(glob) { return gulp.src(glob, { base: path.join(paths.source.stc, paths.styles) }).pipe($.cleanCss({ advanced: false, aggressiveMerging: false, keepSpecialComments: 0, mediaMerging: optimized, processImport: optimized }, function(error, minified) { if(error.errors.length > 0) { console.log('< minified: ' + minified + ' >'); console.log(error); } })).pipe(gulp.dest(targetPaths.styles)).pipe($.size({ title: '-> CSS', showFiles: true })); } function processSASS(glob) { var insert = require('gulp-insert'); return gulp.src(glob, { base: path.join(paths.source.stc, paths.styles) }).pipe(insert.prepend('$build-version: ' + argv.buildVersion + ';')).pipe($.sass({ outputStyle: optimized ? 'compressed' : 'expanded', precision: 8 })).pipe(gulp.dest(targetPaths.styles)).pipe($.size({ title: '-> SASS', showFiles: true })); } gulp.task('update-lib', function() { var mainStream = mergeStream(), packageMap = JSON.parse(fs.readFileSync('./package.map', 'utf8')), property = null, filesSrc = '', basePath = ''; function flushPipes(stream, pipes, dir) { if(pipes.indexOf(whichWar) > -1) { var fileName = property.dest[property.dest.length - 1]; if (fileName && fileName.indexOf('.') > -1) { var names = fileName ? fileName.split('.') : ['', '']; property.dest.pop(); stream = stream.pipe($.rename(function(path) { path.extname = '.' + names.pop(); path.basename = names.join(''); })); } stream.pipe(gulp.dest(path.join(staticMap[whichWar].SRC_DOCROOT, dir, property.dest.join('/')), { relativeSymlinks: true, useJunctions: false })); } return stream; } for(var i in packageMap) { property = packageMap[i]; filesSrc = path.join(paths.bowerLib, property.src.join('/')); basePath = path.join(paths.bowerLib, property.src.filter(function(item, index) { if (property.src.length - 1 > index && item.indexOf('.') > -1) { return true; } return item.indexOf('*') === -1 && item.indexOf('.') === -1; }).join('/')); switch(property.type) { case 'font': mainStream.add(flushPipes(gulp.src(filesSrc, { base: basePath }), property.pipes, paths.fonts).pipe($.size({ title: '-> ' + i }))); break; case 'style': mainStream.add(flushPipes(gulp.src(filesSrc, { base: basePath }), property.pipes, paths.styles).pipe($.size({ title: '-> ' + i }))); break; case 'script': mainStream.add(flushPipes(gulp.src(filesSrc, { base: basePath }), property.pipes, paths.scripts).pipe($.size({ title: '-> ' + i }))); break; case 'image': mainStream.add(flushPipes(gulp.src(filesSrc, { base: basePath }), property.pipes, paths.images).pipe($.size({ title: '-> ' + i }))); break; } } return mainStream; }); gulp.task('css', function() { return processCSS(sourcesPaths.styles.base); }); gulp.task('sass', function() { return processSASS(sourcesPaths.styles.sass); }); gulp.task('styles', function() { return gulp.series('sass', 'css'); }); gulp.task('scripts', function() { return optimized ? requirejs.optimize({ allowSourceOverwrites: true, appDir: paths.source.stc + '/' + paths.scripts, baseUrl: paths.lib, dir: paths.dest.stc + '/' + paths.scripts, mainConfigFile : paths.source.stc + '/' + paths.scripts + '/config.js', keepBuildDir: true, throwWhen: { optimize : true }, preserveLicenseComments: false }, function(buildResponse) { /* To get the optimized file contents. */ /* var contents = fs.readFileSync(config.out, 'utf8'); */ console.log('-> All scripts are optimized.'); }) : gulp.src(sourcesPaths.scripts.base).pipe($.jshint({ /* Visit http://www.jshint.com/docs/options/ to lookup detail */ /* Enforcing */ bitwise: false, camelcase: false, curly: true, eqeqeq: false, es3: false, forin: false, freeze: false, immed: true, indent: 4, latedef: true, laxbreak: true, lookup: false, newcap: true, noarg: false, noempty: true, nonbsp: true, nonew: true, plusplus: false, undef: true, unused: false, strict: false, maxparams: 5, maxdepth: 5, maxstatements : 10, maxcomplexity : 5, maxlen: 200, /* Environments */ browser : true, devel: true, jquery : true, node : false }))/* .pipe($.jshint.reporter(require('jshint-stylish'))) */.pipe(gulp.dest(targetPaths.scripts)).pipe($.size({ title: '-> Scripts unoptimized' })); }); gulp.task('images', function() { return gulp.src(sourcesPaths.images.base).pipe(gulp.dest(targetPaths.images)).pipe($.size({ title : '-> Images' })); }); gulp.task('fonts', function() { return gulp.src(sourcesPaths.fonts.base).pipe(gulp.dest(targetPaths.fonts)).pipe($.size({ title : '-> Fonts' })); }); gulp.task('war', function() { return gulp.src(sourcesPaths.war).pipe(gulp.dest(paths.dest.war)).pipe($.size({ title : '-> War' })); }); gulp.task('other', function() { return gulp.src(sourcesPaths.other.base).pipe(gulp.dest(targetPaths.other)).pipe($.size({ title : '-> Other' })); }); gulp.task('clean', function() { return gulp.src([path.join(paths.dest.stc, '*'), path.join(paths.dest.war, '*')], { read : false }).pipe($.clean({ force : true })); }); gulp.task('watch', function(next) { $.watch(sourcesPaths.styles.base, function(vinyl) { processCSS(vinyl.path); }); $.watch(sourcesPaths.styles.sass, function(vinyl) { var pattern = new RegExp('(^_)(.*)'); if(pattern.test(vinyl.stem)) { gulp.src([sourcesPaths.styles.sass, '!' + path.join(paths.source.stc, paths.styles, '**', '_*.{sass,scss}')]).pipe((function() { var through = require('through2'); var stream = through.obj(function(record, encoding, callback) { if (record.isBuffer()) { var content = record.contents.toString('utf8'), pathRe = path.relative(path.dirname(record.path), path.dirname(vinyl.path)), patternIm = new RegExp('\(^|\\s+)@import\\s+(\'|")' + pathRe + (pathRe ? '(\\\\|\/)' : '') + vinyl.stem.replace(pattern, '$1?$2') + '(\\' + vinyl.extname + ')?' + '(\'|");'); if(patternIm.test(content)) { // make sure the file goes through the next gulp plugin this.push(record); processSASS(record.path); } return callback(); } if (record.isStream()) { console.log(record.path + ' is stream.'); } // tell the stream engine that we are done with this file callback(); }); // returning the file stream return stream; })()); } else { processSASS(vinyl.path); } }); if(optimized) { gulp.watch(sourcesPaths.scripts.base, ['scripts']); } else { $.watch(sourcesPaths.scripts.base, function(vinyl) { gulp.src(vinyl.path, { base: path.join(paths.source.stc, paths.scripts) }).pipe(gulp.dest(targetPaths.scripts)).pipe($.size({ title : '-> Script', showFiles: true })); }); } $.watch(sourcesPaths.images.base, function(vinyl) { gulp.src(vinyl.path, { base: path.join(paths.source.stc, paths.images) }).pipe(gulp.dest(targetPaths.images)).pipe($.size({ title : '-> Image', showFiles: true })); }); $.watch(sourcesPaths.fonts.base, function(vinyl) { gulp.src(vinyl.path, { base: path.join(paths.source.stc, paths.fonts) }).pipe(gulp.dest(targetPaths.fonts)).pipe($.size({ title : '-> Font', showFiles: true })); }); $.watch(path.join(paths.source.war, '**', '*.{jsp,tag,MF,jar,xml}'), function(vinyl) { gulp.src(vinyl.path, { base: paths.source.war }).pipe(gulp.dest(paths.dest.war)).pipe($.size({ title : '-> Fragment', showFiles: true })); }); $.watch(sourcesPaths.other.base, function(vinyl) { gulp.src(vinyl.path, { base: paths.source.stc }).pipe(gulp.dest(targetPaths.other)).pipe($.size({ title : '-> Other', showFiles: true })); }); gulp.watch(['./package.json', './package.map'], ['update-lib']); }); // DEFAULT GULP TASK gulp.task('default', function() { gulp.series('clean', 'images', 'fonts', 'styles', 'scripts'); });
GrayYoung/grayyoung.github.io
gulpfile.js
JavaScript
mpl-2.0
10,133
openerp.e3z_web_menu_fold = function (instance) { instance.web.WebClient = instance.web.WebClient.extend({ events: { 'click .oe_toggle_secondary_menu': 'fold_menu' }, fold_menu: function () { $('span.oe_menu_fold').toggle() $('span.oe_menu_unfold').toggle() $('.oe_logo').toggleClass("hidden_element") $('.oe_secondary_menus_container').toggleClass("hidden_element") $('.oe_leftbar').toggleClass("oe_leftbar_folded") $('.oe_footer').toggle() } }) }
noemis-fr/old-custom
e3z_web_menu_fold/static/src/js/menu_fold.js
JavaScript
agpl-3.0
573
(function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; I18n.scoped('gradebook2', function(I18n) { return this.CurveGradesDialog = (function() { function CurveGradesDialog(assignment, gradebook) { var locals; this.assignment = assignment; this.gradebook = gradebook; this.curve = __bind(this.curve, this); locals = { assignment: this.assignment, action: "" + this.gradebook.options.context_url + "/gradebook/update_submission", middleScore: parseInt((this.assignment.points_possible || 0) * 0.6), showOutOf: this.assignment.points_possible >= 0 }; this.$dialog = $(Template('CurveGradesDialog', locals)); this.$dialog.formSubmit({ disableWhileLoading: true, processData: __bind(function(data) { var cnt, curves, idx, pre; cnt = 0; curves = this.curve(); for (idx in curves) { pre = "submissions[submission_" + idx + "]"; data[pre + "[assignment_id]"] = data.assignment_id; data[pre + "[user_id]"] = idx; data[pre + "[grade]"] = curves[idx]; cnt++; } if (cnt === 0) { this.$dialog.errorBox(I18n.t("errors.none_to_update", "None to Update")); return false; } return data; }, this), success: __bind(function(data) { var datum, submissions; this.$dialog.dialog('close'); submissions = (function() { var _i, _len, _results; _results = []; for (_i = 0, _len = data.length; _i < _len; _i++) { datum = data[_i]; _results.push(datum.submission); } return _results; })(); $.publish('submissions_updated', [submissions]); return alert(I18n.t("alerts.scores_updated", { one: "1 Student score updated", other: "%{count} Student scores updated" }, { count: data.length })); }, this) }).dialog({ width: 350, modal: true, resizable: false, open: this.curve, close: __bind(function() { return this.$dialog.remove(); }, this) }).fixDialogButtons(); this.$dialog.find("#middle_score").bind("blur change keyup focus", this.curve); this.$dialog.find("#assign_blanks").change(this.curve); } CurveGradesDialog.prototype.curve = function() { var breakPercents, breakScores, breaks, cnt, color, currentBreak, data, finalScore, finalScores, final_users_for_score, idx, interval, jdx, maxCount, middleScore, pct, score, scoreCount, scores, skipCount, student, tally, user, users, users_for_score, width, _ref; idx = 0; scores = {}; data = this.$dialog.getFormData(); users_for_score = []; scoreCount = 0; middleScore = parseInt($("#middle_score").val(), 10); middleScore = middleScore / this.assignment.points_possible; if (isNaN(middleScore)) { return; } _ref = this.gradebook.students; for (idx in _ref) { student = _ref[idx]; score = student["assignment_" + this.assignment.id].score; if (score > this.assignment.points_possible) { score = this.assignment.points_possible; } if (score < 0) { score = 0; } users_for_score[parseInt(score, 10)] = users_for_score[parseInt(score, 10)] || []; users_for_score[parseInt(score, 10)].push([idx, score || 0]); scoreCount++; } breaks = [0.006, 0.012, 0.028, 0.040, 0.068, 0.106, 0.159, 0.227, 0.309, 0.401, 0.500, 0.599, 0.691, 0.773, 0.841, 0.894, 0.933, 0.960, 0.977, 0.988, 1.000]; interval = (1.0 - middleScore) / Math.floor(breaks.length / 2); breakScores = []; breakPercents = []; idx = 0; while (idx < breaks.length) { breakPercents.push(1.0 - (interval * idx)); breakScores.push(Math.round((1.0 - (interval * idx)) * this.assignment.points_possible)); idx++; } tally = 0; finalScores = {}; currentBreak = 0; $("#results_list").empty(); $("#results_values").empty(); final_users_for_score = []; idx = users_for_score.length - 1; while (idx >= 0) { users = users_for_score[idx] || []; score = Math.round(breakScores[currentBreak]); for (jdx in users) { user = users[jdx]; finalScores[user[0]] = score; if (user[1] === 0) { finalScores[user[0]] = 0; } finalScore = finalScores[user[0]]; final_users_for_score[finalScore] = final_users_for_score[finalScore] || []; final_users_for_score[finalScore].push(user[0]); } tally += users.length; while (tally > (breaks[currentBreak] * scoreCount)) { currentBreak++; } idx--; } maxCount = 0; idx = final_users_for_score.length - 1; while (idx >= 0) { cnt = (final_users_for_score[idx] || []).length; if (cnt > maxCount) { maxCount = cnt; } idx--; } width = 15; skipCount = 0; idx = final_users_for_score.length - 1; while (idx >= 0) { users = final_users_for_score[idx]; pct = 0; cnt = 0; if (users || skipCount > (this.assignment.points_possible / 10)) { if (users) { pct = users.length / maxCount; cnt = users.length; } color = (idx === 0 ? "#ee8" : "#cdf"); $("#results_list").prepend("<td style='padding: 1px;'><div title='" + cnt + " student" + (cnt === 1 ? "" : "s") + " will get " + idx + " points' style='border: 1px solid #888; background-color: " + color + "; width: " + width + "px; height: " + (100 * pct) + "px; margin-top: " + (100 * (1 - pct)) + "px;'>&nbsp;</div></td>"); $("#results_values").prepend("<td style='text-align: center;'>" + idx + "</td>"); skipCount = 0; } else { skipCount++; } idx--; } $("#results_list").prepend("<td><div style='height: 100px; position: relative; width: 30px; font-size: 0.8em;'><img src='/images/number_of_students.png' alt='# of students'/><div style='position: absolute; top: 0; right: 3px;'>" + maxCount + "</div><div style='position: absolute; bottom: 0; right: 3px;'>0</div></div></td>"); $("#results_values").prepend("<td>&nbsp;</td>"); return finalScores; }; return CurveGradesDialog; })(); }); }).call(this);
faraazkhan/canvas
public/javascripts/compiled/gradebook2/CurveGradesDialog.js
JavaScript
agpl-3.0
7,017
window.mingle_node_name = 'Romain Gary'; window.mingle_node_url = 'http://mingle.thedod.iriscouch.com'; document.title = (document.title + ' - ' + window.mingle_node_name); document.write('You are connected via the <a target="_blank" href="'+window.mingle_node_url+'">'+window.mingle_node_name+'</a> server');
judywawira/Mingle
customize/example/_attachments/branding.js
JavaScript
agpl-3.0
310
(function(angular, $, _) { angular.module('mailingpresets').config(function($routeProvider) { $routeProvider.when('/mailingpresets', { controller: 'MailingpresetsSettingsCtrl', templateUrl: '~/mailingpresets/MailingpresetsSettingsCtrl.html', // If you need to look up data when opening the page, list it out // under "resolve". resolve: { mailingpresets: function(crmApi) { return crmApi('Mailingpreset', 'get', { 'option.limit': 0 }); }, mailinggroups: function (crmApi) { return crmApi('Group', 'get', {group_type: 2, is_active: 1}) }, ajaxendpoint: function (crmApi) { return crmApi('Mailingpreset', 'setting', {return: 'endpoint'}) }, exturl: function (crmApi) { return crmApi('Mailingpreset', 'setting', {return: 'exturl'}) } } }); } ); // The controller uses *injection*. This default injects a few things: // $scope -- This is the set of variables shared between JS and HTML. // crmApi, crmStatus, crmUiHelp -- These are services provided by civicrm-core. // myContact -- The current contact, defined above in config(). angular.module('mailingpresets').controller('MailingpresetsSettingsCtrl', function($scope, crmApi, crmStatus, crmUiHelp, crmFromAddresses, mailingpresets, mailinggroups, ajaxendpoint, exturl) { // The ts() and hs() functions help load strings for this module. var ts = $scope.ts = CRM.ts('mailingpresets'); var hs = $scope.hs = crmUiHelp({file: 'CRM/Mailingpreset/Presets'}); // See: templates/CRM/Mailingpresets/Presets.hlp // Variables used in the HTML $scope.crmFromAddresses = crmFromAddresses; $scope.crmMessageTemplates = CRM.crmMailing.mesTemplate; $scope.mailinggroups = mailinggroups.values; $scope.ajaxendpoint = ajaxendpoint.result; $scope.exturl = exturl.result; $scope.mailingpresets = []; if (mailingpresets.values.length > 0) { $scope.mailingpresets = mailingpresets.values; } // Handler for 'new' button at the bottom of the form. $scope.newpreset = function newpreset() { $scope.mailingpresets.push({ 'id': null, 'name': ts('Monthly newsletter'), 'subject': ts('Monthly newsletter'), 'from_id': '', 'group_id': '', 'template_id': '', }); }; // Handler for 'save' button next to each config. $scope.save = function save(preset) { return crmStatus( // Status messages. For defaults, just use "{}" {start: ts('Saving...'), success: ts('Saved')}, // The save action. Note that crmApi() returns a promise. crmApi('Mailingpreset', 'create', preset).then(function(data) { preset.id = data.id; }) ); }; // Handler for 'delete' button next to each config. $scope.remove = function remove(preset) { // Remove the preset from our array var index = $scope.mailingpresets.indexOf(preset); $scope.mailingpresets.splice(index, 1); if (preset.id) { return crmStatus( // Status messages. For defaults, just use "{}" {start: ts('Deleting...'), success: ts('Deleted')}, // The save action. Note that crmApi() returns a promise. crmApi('Mailingpreset', 'delete', preset) ); } }; }); })(angular, CRM.$, CRM._);
coopsymbiotic/coop.symbiotic.mailingpresets
ang/mailingpresets/MailingpresetsSettingsCtrl.js
JavaScript
agpl-3.0
3,484
var searchData= [ ['searchform',['SearchForm',['../classmain_1_1forms_1_1SearchForm.html',1,'main::forms']]], ['signupform',['SignUpForm',['../classmain_1_1forms_1_1SignUpForm.html',1,'main::forms']]], ['station',['Station',['../classmain_1_1models_1_1Station.html',1,'main::models']]] ];
DjangoChained/TchouTchouGo
docs/search/classes_5.js
JavaScript
agpl-3.0
295
var safeEval = require('notevil') module.exports.parse = function(literal){ literal = literal.replace(/\{\{([\w\W]*?)\}\}/g, function(_, exp){ return '{$: ' + JSON.stringify(fixIndent(exp)) + '}' }) return safeEval('j = {' + literal + '}') } module.exports.stringify = function(object){ return getObjectContent(object).trim() } module.exports.eval = xval function xval(object, context){ if (Array.isArray(object)){ return object.map(function(x){ return xval(x, context) }) } else if (object instanceof Object) { if (object.$){ return safeEval(object.$, context) } else { var res = {} Object.keys(object).forEach(function(key){ res[key] = xval(object[key], context) }) return res } } else { return object } } function getObjectContent(object){ var result = Object.keys(object).map(function(key){ return escapeKey(key) + ': ' + getLiteral(object[key]) }) return smartWrap(result) } var numberMatch = /^[0-9]/ function isNumeric(key){ return typeof key === 'string' && !!numberMatch.exec(key) } function escapeKey(key){ if (~key.indexOf(' ') || ~key.indexOf('"') || ~key.indexOf('-') || isNumeric(key)){ return JSON.stringify(String(key)) } else { return key } } function getArrayContent(array){ var result = array.map(function(obj){ return getLiteral(obj) }) return smartWrap(result) } function smartWrap(array){ if (array.join(', ').length>50){ return '\n' + array.join(',\n') + '\n' } else { return ' ' + array.join(', ') + ' ' } } function indent(text){ return text.replace(/\n(.)/g, '\n $1') } function getLiteral(value){ if (!value || typeof value !== 'object'){ return JSON.stringify(value) } else if (Array.isArray(value)){ return '[' + indent(getArrayContent(value)) + ']' } else if (value && '$' in value){ return '{{' + value['$'] + '}}' } else { return '{' + indent(getObjectContent(value)) + '}' } } var matchStartSpace = /^(\s+)/ var matchNewLineWrapper = /^\s*\n|\n\s*$/g function fixIndent(text){ if (text && ~text.indexOf('\n')){ text = text.replace(matchNewLineWrapper, '') var match = matchStartSpace.exec(text) var indent = match && match[1].length if (indent){ text = '\n' + text.replace(/(^|\n)(\s+)/g, function(_, start, spaces){ return start + spaces.slice(indent-2) }) + '\n' } } return text }
mmckegg/loop-drop-app
lib/jsmn.js
JavaScript
agpl-3.0
2,443
// Generated by CoffeeScript 1.6.1 (function() { var __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; define(["jquery", "underscore", "gettext", "xblock/runtime.v1", "js/views/xblock", "js/views/modals/edit_xblock"], function($, _, gettext, XBlock, XBlockView, EditXBlockModal) { var ModuleEdit; return ModuleEdit = (function(_super) { __extends(ModuleEdit, _super); function ModuleEdit() { return ModuleEdit.__super__.constructor.apply(this, arguments); } ModuleEdit.prototype.tagName = 'li'; ModuleEdit.prototype.className = 'component'; ModuleEdit.prototype.editorMode = 'editor-mode'; ModuleEdit.prototype.events = { "click .edit-button": 'clickEditButton', "click .delete-button": 'onDelete' }; ModuleEdit.prototype.initialize = function() { this.onDelete = this.options.onDelete; return this.render(); }; ModuleEdit.prototype.loadDisplay = function() { var xblockElement; xblockElement = this.$el.find('.xblock-student_view'); if (xblockElement.length > 0) { return XBlock.initializeBlock(xblockElement); } }; ModuleEdit.prototype.createItem = function(parent, payload, callback) { var _this = this; if (callback == null) { callback = function() {}; } payload.parent_locator = parent; return $.postJSON(this.model.urlRoot + '/', payload, function(data) { _this.model.set({ id: data.locator }); _this.$el.data('locator', data.locator); _this.$el.data('courseKey', data.courseKey); return _this.render(); }).success(callback); }; ModuleEdit.prototype.loadView = function(viewName, target, callback) { var _this = this; if (this.model.id) { return $.ajax({ url: "" + (decodeURIComponent(this.model.url())) + "/" + viewName, type: 'GET', cache: false, headers: { Accept: 'application/json' }, success: function(fragment) { return _this.renderXBlockFragment(fragment, target).done(callback); } }); } }; ModuleEdit.prototype.render = function() { var _this = this; return this.loadView('student_view', this.$el, function() { _this.loadDisplay(); return _this.delegateEvents(); }); }; ModuleEdit.prototype.clickEditButton = function(event) { var modal; event.preventDefault(); modal = new EditXBlockModal(); return modal.edit(this.$el, self.model, { refresh: _.bind(this.render, this) }); }; return ModuleEdit; })(XBlockView); }); }).call(this);
edxzw/edx-platform
cms/static/coffee/src/views/module_edit.js
JavaScript
agpl-3.0
3,132
/* * File: app/model/Rule.js * * This file was generated by Sencha Architect version 3.2.0. * http://www.sencha.com/products/architect/ * * This file requires use of the Ext JS 5.1.x library, under independent license. * License of Sencha Architect does not include license for Ext JS 5.1.x. For more * details see http://www.sencha.com/license or contact license@sencha.com. * * This file will be auto-generated each and everytime you save your project. * * Do NOT hand edit this file. */ Ext.define('GFManager.model.Rule', { extend: 'Ext.data.Model', requires: [ 'Ext.data.field.String', 'Ext.data.proxy.Rest', 'Ext.data.reader.Json', 'Ext.data.writer.Json' ], fields: [ { type: 'string', defaultValue: '', name: 'id', unique: true }, { type: 'string', defaultValue: '', name: 'name', unique: true }, { type: 'string', defaultValue: '', name: 'description' } ], proxy: { type: 'rest', url: '/api/v1/manager/missions/rules', reader: { type: 'json', rootProperty: 'data' }, writer: { type: 'json', writeAllFields: true, encode: true, rootProperty: 'data' } } });
atglab/gframework
Gframwork/public/ManagerBeta/app/model/Rule.js
JavaScript
agpl-3.0
1,439
import Component from '@ember/component'; import { inject as service } from '@ember/service'; import { on } from '@ember/object/evented'; import { task } from 'ember-concurrency'; import { t } from 'ember-intl'; import ENV from 'irene/config/environment'; import triggerAnalytics from 'irene/utils/trigger-analytics'; export default Component.extend({ intl: service(), ajax: service(), notify: service('notifications'), tagName: ['tr'], isDeletingInvitation: false, isResendingInvitation: false, showDeleteInvitationConfirmBox: false, showResendInvitationConfirmBox: false, tInvitationReSent: t('invitationReSent'), tInvitationDeleted: t('invitationDeleted'), tPleaseTryAgain: t('pleaseTryAgain'), /* Open resend-invitation confirmation */ openResendInvitationConfirmBox: task(function * () { yield this.set('showResendInvitationConfirmBox', true); }), /* Resend invitation */ confirmResend: task(function * () { this.set('isResendingInvitation', true); const invite = this.get('invitation'); yield invite.resend(); }).evented(), confirmResendSucceeded: on('confirmResend:succeeded', function() { this.get('notify').success(this.get('tInvitationReSent')); triggerAnalytics('feature', ENV.csb.inviteResend); this.set('showResendInvitationConfirmBox', false); this.set('isResendingInvitation', false); }), confirmResendErrored: on('confirmResend:errored', function(_, error) { let errMsg = this.get('tPleaseTryAgain'); if (error.errors && error.errors.length) { errMsg = error.errors[0].detail || errMsg; } else if(error.message) { errMsg = error.message; } this.get("notify").error(errMsg); this.set('showResendInvitationConfirmBox', false); this.set('isResendingInvitation', false); }), /* Open delete-invitation confirmation */ openDeleteInvitationConfirmBox: task(function * () { yield this.set('showDeleteInvitationConfirmBox', true); }), /* Delete invitation */ confirmDelete: task(function * () { this.set('isDeletingInvitation', true); const invite = this.get('invitation'); invite.deleteRecord(); yield invite.save(); }).evented(), confirmDeleteSucceeded: on('confirmDelete:succeeded', function() { this.get('notify').success(this.get('tInvitationDeleted')); triggerAnalytics('feature', ENV.csb.inviteDelete); this.set('showDeleteInvitationConfirmBox', false); this.set('isDeletingInvitation', false); }), confirmDeleteErrored: on('confirmDelete:errored', function(_, error) { let errMsg = this.get('tPleaseTryAgain'); if (error.errors && error.errors.length) { errMsg = error.errors[0].detail || errMsg; } else if(error.message) { errMsg = error.message; } this.get("notify").error(errMsg); this.set('isDeletingInvitation', false); }), actions: { confirmResendProxy() { this.get('confirmResend').perform(); }, confirmDeleteProxy() { this.get('confirmDelete').perform(); }, } });
appknox/irene
app/components/organization-invitation-overview.js
JavaScript
agpl-3.0
3,049
/* Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'maximize', 'ko', { maximize: '최대화', minimize: '최소화' } );
astrobin/astrobin
astrobin/static/astrobin/ckeditor/plugins/maximize/lang/ko.js
JavaScript
agpl-3.0
261
var class_menu___compat = [ [ "addMenuItem", "class_menu___compat.html#a499a08e7f1ff2b26fce99182d1043b49", null ], [ "addSeparator", "class_menu___compat.html#a1ee8d0796f48a84eba1f0692fb604654", null ], [ "defaultTemplate", "class_menu___compat.html#add8c5a33f231d9979e5f8bbded576d9e", null ], [ "getDefaultHref", "class_menu___compat.html#a43337484332528d943e8cc4ea4092f6e", null ], [ "init", "class_menu___compat.html#a4be4055f3361d4800e16bc2e2e38cda6", null ], [ "isCurrent", "class_menu___compat.html#ac061233320116be798fd33b2b16a2c98", null ], [ "setController", "class_menu___compat.html#aa4f9c9e545ef3a90856d30de93fe5e09", null ], [ "$current_menu_class", "class_menu___compat.html#a076886e4bce70198c63035ac97d0826e", null ], [ "$inactive_menu_class", "class_menu___compat.html#ab69638a8fabcb73402bd8946d20aec8d", null ], [ "$items", "class_menu___compat.html#a737abdef83dabb219182c1e88887c6c3", null ], [ "$last_item", "class_menu___compat.html#a635299a245fc12580c6de6b4e336a796", null ] ];
atk4/atk4-web
dox/html/class_menu___compat.js
JavaScript
agpl-3.0
1,042
'use strict'; var chai = require('chai'); var spies = require('chai-spies'); var openVeoApi = require('@openveo/api'); var BrowserPilot = process.requireManage('app/server/BrowserPilot.js'); var BROWSERS_MESSAGES = process.requireManage('app/server/browsersMessages.js'); var AdvancedEvent = openVeoApi.emitters.AdvancedEvent; var assert = chai.assert; chai.should(); chai.use(spies); // BrowserPilot.js describe('BrowserPilot', function() { var emitter; var namespace; var pilot; // Prepare tests beforeEach(function() { emitter = new openVeoApi.emitters.AdvancedEmitter(); namespace = new openVeoApi.socket.SocketNamespace(); pilot = new BrowserPilot(emitter, namespace); }); // MESSAGES property describe('MESSAGES', function() { it('should not be editable', function() { assert.throws(function() { pilot.MESSAGES = null; }); }); it('should expose the list of dispatched browsers\' messages', function() { assert.strictEqual(pilot.MESSAGES, BROWSERS_MESSAGES); }); }); // constructor describe('constructor', function() { it('should handle CONNECTED messages', function() { var expectedSocket = {id: '42'}; pilot.on(BROWSERS_MESSAGES.CONNECTED, function(id) { assert.strictEqual(id, expectedSocket.id, 'Wrong id'); assert.equal(pilot.clients[0].id, expectedSocket.id, 'Wrong client id'); assert.strictEqual(pilot.clients[0].socket, expectedSocket, 'Wrong socket'); }); emitter.emitEvent(new AdvancedEvent(BROWSERS_MESSAGES.CONNECTED, expectedSocket)); }); it('should handle DISCONNECTED messages', function() { var expectedSocket = {id: '42'}; pilot.on(BROWSERS_MESSAGES.DISCONNECTED, function(id) { assert.strictEqual(id, expectedSocket.id, 'Wrong id'); assert.equal(pilot.clients.length, 0, 'Unexpected client'); }); emitter.emitEvent(new AdvancedEvent(BROWSERS_MESSAGES.CONNECTED, expectedSocket)); emitter.emitEvent(new AdvancedEvent(BROWSERS_MESSAGES.DISCONNECTED, expectedSocket)); }); it('should handle ERROR messages', function() { var expectedSocket = {id: '42'}; var expectedError = new Error(); pilot.on(BROWSERS_MESSAGES.ERROR, function(error, id) { assert.strictEqual(error, expectedError, 'Wrong error'); assert.strictEqual(id, expectedSocket.id, 'Wrong id'); }); emitter.emitEvent(new AdvancedEvent(BROWSERS_MESSAGES.CONNECTED, expectedSocket)); emitter.emitEvent(new AdvancedEvent(BROWSERS_MESSAGES.ERROR, expectedError, expectedSocket)); }); it('should emit all other events', function() { emitter.emitEvent(new AdvancedEvent(BROWSERS_MESSAGES.UPDATE_NAME)); var events = [ BROWSERS_MESSAGES.UPDATE_NAME, BROWSERS_MESSAGES.REMOVE, BROWSERS_MESSAGES.REMOVE_HISTORIC, BROWSERS_MESSAGES.ADD_SCHEDULE, BROWSERS_MESSAGES.REMOVE_SCHEDULE, BROWSERS_MESSAGES.REMOVE_HISTORY, BROWSERS_MESSAGES.GET_DEVICES, BROWSERS_MESSAGES.GET_DEVICE_SETTINGS, BROWSERS_MESSAGES.UPDATE_DEVICE_STATE, BROWSERS_MESSAGES.START_DEVICE_SESSION, BROWSERS_MESSAGES.STOP_DEVICE_SESSION, BROWSERS_MESSAGES.INDEX_DEVICE_SESSION, BROWSERS_MESSAGES.GET_GROUPS, BROWSERS_MESSAGES.CREATE_GROUP, BROWSERS_MESSAGES.ADD_DEVICE_TO_GROUP, BROWSERS_MESSAGES.REMOVE_DEVICE_FROM_GROUP ]; events.forEach(function(event) { var expectedData = {}; pilot.on(event, function(data) { assert.strictEqual(data, expectedData); }); emitter.emitEvent(new AdvancedEvent(event, expectedData)); }); }); }); // get method describe('get', function() { it('should be able to get the BrowserPilot singleton', function() { assert.instanceOf(BrowserPilot.get(emitter, namespace), BrowserPilot); }); }); // connectDevice method describe('connectDevice', function() { it('should be able to inform all browsers about a new connected device', function() { var expectedDevice = {id: '42'}; namespace.emit = function(message, device) { assert.equal(message, 'device.connected', 'Wrong message'); assert.strictEqual(device, expectedDevice, 'Wrong device'); }; pilot.connectDevice(expectedDevice); }); }); // remove method describe('remove', function() { it('should be able to inform all browsers that a manageable has been removed', function() { var expectedManageable = {id: '42', type: 'type'}; namespace.emit = function(message, manageable) { assert.equal(message, 'removed', 'Wrong message'); assert.strictEqual(manageable.id, expectedManageable.id, 'Wrong id'); assert.strictEqual(manageable.type, expectedManageable.type, 'Wrong type'); }; pilot.remove(expectedManageable); }); }); // update method describe('update', function() { it('should be able to inform all browsers that a manageable has been updated', function() { var expectedManageable = {id: '42', type: 'type'}; var expectedProperty = 'property'; var expectedValue = 'value'; namespace.emit = function(message, data) { assert.equal(message, 'updated', 'Wrong message'); assert.strictEqual(data.id, expectedManageable.id, 'Wrong id'); assert.strictEqual(data.type, expectedManageable.type, 'Wrong type'); assert.strictEqual(data.key, expectedProperty, 'Wrong property'); assert.strictEqual(data.value, expectedValue, 'Wrong value'); }; pilot.update(expectedManageable, expectedProperty, expectedValue); }); }); // addSchedule method describe('addSchedule', function() { it('should be able to inform all browsers that a schedule has been added to a manageable', function() { var expectedManageable = {id: '42', type: 'type'}; var expectedSchedule = {}; namespace.emit = function(message, data) { assert.equal(message, 'newSchedule', 'Wrong message'); assert.strictEqual(data.id, expectedManageable.id, 'Wrong id'); assert.strictEqual(data.type, expectedManageable.type, 'Wrong type'); assert.strictEqual(data.schedule, expectedSchedule, 'Wrong schedule'); }; pilot.addSchedule(expectedManageable, expectedSchedule); }); }); // removeSchedule method describe('removeSchedule', function() { it('should be able to inform all browsers that a schedule has been removed from a manageable', function() { var expectedManageable = {id: '42', type: 'type'}; var expectedScheduleId = '43'; namespace.emit = function(message, data) { assert.equal(message, 'removedSchedule', 'Wrong message'); assert.strictEqual(data.id, expectedManageable.id, 'Wrong id'); assert.strictEqual(data.type, expectedManageable.type, 'Wrong type'); assert.strictEqual(data.scheduleId, expectedScheduleId, 'Wrong schedule id'); }; pilot.removeSchedule(expectedManageable, expectedScheduleId); }); }); // addHistoric method describe('addHistoric', function() { it('should be able to inform all browsers that an historic has been added to a manageable', function() { var expectedManageable = {id: '42', type: 'type'}; var expectedHistoric = {}; namespace.emit = function(message, data) { assert.equal(message, 'newHistoric', 'Wrong message'); assert.strictEqual(data.id, expectedManageable.id, 'Wrong id'); assert.strictEqual(data.type, expectedManageable.type, 'Wrong type'); assert.strictEqual(data.historic, expectedHistoric, 'Wrong historic'); }; pilot.addHistoric(expectedManageable, expectedHistoric); }); }); // removeHistoric method describe('removeHistoric', function() { it('should be able to inform all browsers that an historic has been removed from a manageable', function() { var expectedManageable = {id: '42', type: 'type'}; var expectedHistoricId = '43'; namespace.emit = function(message, data) { assert.equal(message, 'removedHistoric', 'Wrong message'); assert.strictEqual(data.id, expectedManageable.id, 'Wrong id'); assert.strictEqual(data.type, expectedManageable.type, 'Wrong type'); assert.strictEqual(data.historicId, expectedHistoricId, 'Wrong historic id'); }; pilot.removeHistoric(expectedManageable, expectedHistoricId); }); }); // removeHistory method describe('removeHistory', function() { it('should be able to inform all browsers that an historic has been removed from a manageable', function() { var expectedManageable = {id: '42', type: 'type'}; namespace.emit = function(message, data) { assert.equal(message, 'removedHistory', 'Wrong message'); assert.strictEqual(data.id, expectedManageable.id, 'Wrong id'); assert.strictEqual(data.type, expectedManageable.type, 'Wrong type'); }; pilot.removeHistory(expectedManageable); }); }); // updateDeviceState method describe('updateDeviceState', function() { it('should be able to inform all browsers that a device state has changed', function() { var expectedId = '42'; var expectedState = 'state'; namespace.emit = function(message, data) { assert.equal(message, 'device.updatedState', 'Wrong message'); assert.strictEqual(data.id, expectedId, 'Wrong id'); assert.strictEqual(data.state, expectedState, 'Wrong state'); }; pilot.updateDeviceState(expectedId, expectedState); }); }); // createGroup method describe('createGroup', function() { it('should be able to inform all browsers that a group has been created', function() { var expectedGroup = {}; namespace.emit = function(message, data) { assert.equal(message, 'group.created', 'Wrong message'); assert.strictEqual(data.group, expectedGroup, 'Wrong group'); }; pilot.createGroup(expectedGroup); }); }); // addDeviceToGroup method describe('addDeviceToGroup', function() { it('should be able to inform all browsers that a device has been added to a group', function() { var expectedDeviceId = '42'; var expectedGroupId = '43'; namespace.emit = function(message, data) { assert.equal(message, 'group.newDevice', 'Wrong message'); assert.strictEqual(data.deviceId, expectedDeviceId, 'Wrong device id'); assert.strictEqual(data.groupId, expectedGroupId, 'Wrong group id'); }; pilot.addDeviceToGroup(expectedDeviceId, expectedGroupId); }); }); // removeDeviceFromGroup method describe('removeDeviceFromGroup', function() { it('should be able to inform all browsers that a device has been removed from a group', function() { var expectedDeviceId = '42'; namespace.emit = function(message, data) { assert.equal(message, 'group.removedDevice', 'Wrong message'); assert.strictEqual(data.id, expectedDeviceId, 'Wrong device id'); }; pilot.removeDeviceFromGroup(expectedDeviceId); }); }); });
veo-labs/openveo-manage
tests/server/pilot/BrowserPilot.js
JavaScript
agpl-3.0
11,250
/* * Trainer Bartos * Victoria Road | Pet-Walking Road (100000202) * Pet Trainer */ var status; function start() { status = -1; action(1, 0, 0); } function action(mode, type, selection) { if (mode === -1) { cm.dispose(); return; } if (status === 0 && mode === 0) { cm.dispose(); return; } else if (status >= 1 && mode === 0) { cm.sendNext("Hmmm ... too busy to do it right now? If you feel like doing it, though, come back and find me."); cm.dispose(); return; } if (mode === 1) { status++; } else { status--; } if (status === 0) { cm.sendSimple("Do you have any business with me?\r\n#L0##bPlease tell me about this place.#l\r\n#L1#I'm here through a word from Mar the Fairy...#k#l"); } else if (status === 1) { if (selection === 0) { if (cm.haveItem(4031035)) { cm.sendNext("Get that letter, jump over obstacles with your pet, and take that letter to my brother Trainer Frod. Give him the letter and something good is going to happen to your pet."); cm.dispose(); return; } else { cm.sendYesNo("This is the road where you can go take a walk with your pet. You can just walk around with it, or you can train your pet to go through the obstacles here. If you aren't too close with your pet yet, that may present a problem and he will not follow your command as much... So, what do you think? Wanna train your pet?"); } } else { cm.sendOk("Hey, are you sure you've met #bMar the Fairy#k? Don't lie to me if you've never met her before because it's obvious. That wasn't even a good lie!!"); cm.dispose(); return; } } else if (status === 2) { cm.gainItem(4031035, 1); cm.sendNext("Ok, here's the letter. He wouldn't know I sent you if you just went there straight, so go through the obstacles with your pet, go to the very top, and then talk to Trainer Frod to give him the letter. It won't be hard if you pay attention to your pet while going through obstacles. Good luck!"); cm.dispose(); return; } }
NoetherEmmy/intransigentms-scripts
npc/1012006.js
JavaScript
agpl-3.0
2,234
/* Copyright 2012, Nabil SEFRIOUI This file is part of Skyproc. Skyproc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. Skyproc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Skyproc. If not, see <http://www.gnu.org/licenses/>. */ Ext.define('Sp.ui.PriceCombo', { extend: 'Ext.form.field.ComboBox', alias: 'widget.pricecombo', initComponent: function() { Ext.applyIf(this, { }); Ext.apply(this, { store: this.createStore(), valueField: 'uuid', hideTrigger: true, typeAhead: true, forceSelection: !this.allowPhantom, listConfig: { loadingText: TR("Searching"), emptyText: TR("No matching members found"), }, }); Ext.applyIf(this.listeners, { focus: { fn: function(me){ if (me.getRawValue().trim().length == 0){ me.clearValue(); } }, scope: this, }, }); this.callParent(arguments); }, createStore: function(){ var cfg = {}; var model; if (this.locationRec){ model = 'LocationMembership'; Ext.apply(cfg, { sorters: [ { property: 'person__last_name', direction: 'ASC' }, { property: 'person__first_name', direction: 'ASC' } ], proxy: { extraParams: { query_field: 'person__last_name', }, }, }); } else { model = 'Person_P'; Ext.apply(cfg, { sorters: [ { property: 'last_name', direction: 'ASC' }, { property: 'first_name', direction: 'ASC' } ], proxy: { extraParams: { query_field: 'last_name', }, }, }); } Ext.apply(cfg, { pageSize: this.pageSize, remoteSort: true, remoteFilter: true, }); return Data.createStore(model, cfg); }, setValue: function(value){ if (Ext.isObject(value)){ if (value.hasOwnProperty('first_name') && value.hasOwnProperty('last_name')){ if (this.locationRec){ var r = Data.create('LocationMembership', { person: value, }); } else { var r = Data.create('Person_P', value); } this.getStore().add(r); this.select(r); return this; } else if (value.hasOwnProperty('name')){ this.setRawValue(value.name); return this; } } else if (Ext.isString(value)){ return this; } else { return this.callParent(arguments); } }, getValue: function(){ var value = this.callParent(), new_value; if (Sp.utils.isUuid(value)){ var r = this.getStore().getById(value); var model = Data.getSpModelName(r); var new_value = {}; if (model == 'LocationMembership'){ new_value = { uuid: r.data.person.uuid, type: 'person', first_name: r.data.person.first_name, last_name: r.data.person.last_name, }; } else { new_value = { uuid: r.data.uuid, type: 'person', first_name: r.data.first_name, last_name: r.data.last_name, }; } } else if (Ext.isString(value) && value.length > 0){ new_value = { uuid: Ext.data.IdGenerator.get('uuid').generate(), type: 'phantom', name: value, }; } return (new_value ? new_value : value); }, });
skygeek/skyproc
wapp/js/ui/PriceCombo.js
JavaScript
agpl-3.0
4,997
'use strict'; var deepMerge = require('./deepMerge') var path = require('path') var bunyan = require('bunyan') var uuidGen = require('node-uuid') var measured = require('measured') function scheduleStatsLogging(ctx) { if (process.env.DISABLE_METRICS === '1') return var lastRun setInterval(function() { var values = { stats: ctx.stats } if (lastRun) { var thisRun = Date.now() values.jitter = thisRun - lastRun - 1000 lastRun = thisRun } else { lastRun = Date.now() } if (process && process.memoryUsage) values.memory = process.memoryUsage() // TODO we need other ways of delivering // metrics ctx.debug(values, 'metrics') }, 1000) } function Context(bunyan, parent) { this.prefix = [ ] this.limited_prefixes = {} if (parent === undefined) { this.stats = measured.createCollection() this.buildBunyan(bunyan) scheduleStatsLogging(this) } else { this.logger = bunyan this.stats = parent.stats this.extend(parent) } if (this.logger === undefined) throw new Error("problem creating logging context") } deepMerge({ buildBunyan: function(name) { var stdout_level = 'info' if (process.env.STDOUT_LOG_LEVEL !== undefined) stdout_level = process.env.STDOUT_LOG_LEVEL var file_level = 'debug' if (process.env.FILE_LOG_LEVEL !== undefined) file_level = process.env.FILE_LOG_LEVEL var list = [ { level: stdout_level, stream: process.stdout } ] if (file_level !== 'none') list.push({ level: file_level, path: path.resolve(__filename, '../../../logs/'+name+'.json') }) if (process.env.DOCKER_IP !== undefined && process.env.GELF_ENABLED == '1') { var gelfStream = require('gelf-stream'), stream = gelfStream.forBunyan(process.env.DOCKER_IP, 12201) list.push({ level: 'debug', type: 'raw', stream: stream }) } var logger = bunyan.createLogger({ name: name, serializers: bunyan.stdSerializers, streams: list}) if (file_level !== 'none') { var fileStreamState = logger.streams.filter(function(s) { return s.type === 'file' })[0].stream._writableState this.measure('logfile_buffer', 'gauge', function() { return fileStreamState.length }) } this.logger = logger }, child: function() { return new Context(this.logger.child.apply(this.logger, arguments), this) }, measure: function(set_or_name, type, fn) { var self = this function define(name, type, fn) { if (self[name] !== undefined) throw new Error(name +' is already defined in stats') // fn may be undefined, that's ok try { self[name] = self.stats[type].call(self.stats, name, fn) } catch(e) { console.log(name, type, fn) console.log(e) throw e } } if (typeof set_or_name === 'string') { define(set_or_name, type, fn) } else { for(var n in set_or_name) { define(n, set_or_name[n]) } } }, extend: function(parent) { this.prefix = parent.prefix.slice() Object.keys(parent.limited_prefixes).forEach(function(k) { this.limited_prefixes[k] = parent.limited_prefixes[k].slice() }, this) }, old_log: function() { var args = Array.prototype.slice.call(arguments), name = args.splice(0, 1)[0], other = this.limited_prefixes[name] || '' this.logger.info([ name ].concat(this.prefix, other, args).join(' ')) }, old_debug: function() { var args = Array.prototype.slice.call(arguments), name = args.splice(0, 1)[0], other = this.limited_prefixes[name] || '' this.logger.debug([ name ].concat(this.prefix, other, args).join(' ')) }, old_log_with: function(fn, parts, scope) { var ctx = new Context(this.logger, this) if (scope === undefined) { ctx.prefix = ctx.prefix.concat(parts) } else { if (ctx.limited_prefixes[scope] === undefined) ctx.limited_prefixes[scope] = [] ctx.limited_prefixes[scope] = ctx.limited_prefixes[scope].concat(parts) } return fn(ctx) }, }, Context.prototype); [ 'fatal', 'error', 'warn', 'info', 'debug', 'trace' ].forEach(function(name) { Context.prototype[name] = function() { return this.logger[name].apply(this.logger, arguments) } }) module.exports = { trace: function(fn_name, fn) { // TODO add `measured` stats to this return function(ctx) { var args = Array.prototype.slice.call(arguments), now = Date.now() args.splice(0, 1) ctx.trace({ args: args, trace_fn: fn_name }, 'start fn') function traceEnd(out) { ctx.trace({ trace_fn: fn_name, duration: Date.now() - now, promise: true, result: out }, 'end fn') } var result = fn.apply(this, arguments) if (typeof result.tap == 'function') { return result.tap(traceEnd) } else { traceEnd(result) return result } } }, create: function(name) { return new Context(name) }, }
curzonj/spacebox-nodejs-common
src/logging.js
JavaScript
agpl-3.0
5,757
(function () { 'use strict'; angular .module('friends') .controller('FriendsSearchController', FriendsSearchController); FriendsSearchController.$inject = ['FriendsService']; function FriendsSearchController(FriendsService) { var vm = this; vm.search = search; function search(){ FriendsService.search({friendName: vm.friendname}).then(function(users){ vm.users = users; }); }; } }());
trendzetter/VegetableGardenPlanner
modules/friends/client/controllers/search-friends.client.controller.js
JavaScript
agpl-3.0
451
/** * Created by filip on 11/28/14. */ 'use strict'; var Sort = { tsort: function (edges) { var nodes = {}, // hash: stringified id of the node => { id: id, afters: list of ids } sorted = [], // sorted list of IDs ( returned value ) visited = {}; // hash: id of already visited node => true var errors = []; var Node = function (id) { this.id = id; this.afters = []; }; // 1. build data structures edges.forEach(function (v) { var from = v.start_node, to = v.end_node; if (!nodes[from]) { nodes[from] = new Node(from); } if (!nodes[to]) { nodes[to] = new Node(to); } nodes[from].afters.push(to); }); // 2. topological sort Object.keys(nodes).forEach(function visit(idstr, ancestors) { var node = nodes[idstr], id = node.id; // if already exists, do nothing if (visited[idstr]) { return; } if (!Array.isArray(ancestors)) { ancestors = []; } ancestors.push(id); visited[idstr] = true; node.afters.forEach(function (afterID) { if (ancestors.indexOf(afterID) >= 0) { // if already in ancestors, a closed chain exists. // throw new Error('closed chain : ' + afterID + ' is in ' + id); errors.push('Closed chain : ' + afterID + ' is in ' + id); return false; } // has to map array not to keep reference of ancestors visit(afterID.toString(), ancestors.map(function (v) { return v; })); // recursive call }); sorted.unshift(id); }); return {sorted: sorted, errors: errors}; } }; module.exports = Sort;
rabix/registry
server/pipeline/top-sort.js
JavaScript
agpl-3.0
1,887
/* global fetch */ import 'isomorphic-fetch'; import withQuery from 'with-query'; const base = 'https://pathfinder.futuretense.io'; const paths = async (sourceAccount, destAsset, destAmount) => { const type = destAsset.asset_type; const params = { /* eslint-disable camelcase */ source_account: sourceAccount, destination_amount: destAmount.toString(), destination_asset_type: type, /* eslint-enable camelcase */ }; if (type !== 'native') { /* eslint-disable camelcase */ params.destination_asset_code = destAsset.asset_code; params.destination_asset_issuer = destAsset.asset.asset_issuer; /* eslint-enable camelcase */ } const response = await fetch(withQuery(`${base}/paths`, params)); if (!response.ok) { throw response; } const data = await response.json(); // eslint-disable-next-line no-underscore-dangle return data._embedded; }; export default { paths };
johansten/stargazer
app/pages/send/pathfinder.js
JavaScript
agpl-3.0
904
/* * This file is part of CoCalc: Copyright © 2020 Sagemath, Inc. * License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details */ /* * CoCalc, by SageMath, Inc., (c) 2016, 2017 -- License: AGPLv3 */ /* * Webpack configuration file Run dev server with source maps: npm run webpack-watch Then visit (say) https://dev0.sagemath.com/ or for smc-in-smc project, info.py URL, e.g. https://cocalc.com/14eed217-2d3c-4975-a381-b69edcb40e0e/port/56754/ This is far from ready to use yet, e.g., we need to properly serve primus websockets, etc.: webpack-dev-server --port=9000 -d Resources for learning webpack: - https://github.com/petehunt/webpack-howto - http://webpack.github.io/docs/tutorials/getting-started/ --- *# Information for developers This webpack config file might look scary, but it only consists of a few moving parts. 1. There is the "main" SMC application, which is split into "css", "lib" and "smc": 1. css: a collection of all static styles from various locations. It might be possible to use the text extraction plugin to make this a .css file, but that didn't work out. Some css is inserted, but it doesn't work and no styles are applied. In the end, it doesn't matter to load it one way or the other. Furthermore, as .js is even better, because the initial page load is instant and doesn't require to get the compiled css styles. 2. lib: this is a compilation of the essential js files in webapp-lib (via webapp-lib.js) 3. smc: the core smc library. besides this, there are also chunks ([number]-hash.js) that are loaded later on demand (read up on `require.ensure`). For example, such a chunkfile contains latex completions, the data for the wizard, etc. 2. There are static html files for the policies. The policy files originate in webapp-lib/policies, where at least one file is generated by update_react_static. That script runs part of the smc application in node.js to render to html. Then, that html output is included into the html page and compiled. It's not possible to automate this fully, because during the processing of these templates, the "css" chunk from point 1.1 above is injected, too. In the future, also other elements from the website (e.g. <Footer/>) will be rendered as separate static html template elements and included there. 3. There are auxiliary files for the "video chat" functionality. That might be redone differently, but for now rendering to html only works via the html webpack plugin in such a way, that it rewrites paths and post processes the files correctly to work. The remaining configuration deals with setting up variables (misc_node contains the centralized information about where the page is getting rendered to, because also the hub.coffee needs to know about certain file locations) Development vs. Production: There are two variables DEVMODE and PRODMODE. * Prodmode: * additional compression is enabled (do *not* add the -p switch to webpack, that's done here explicitly!) * all output filenames, except for the essential .html files, do have hashes and a rather flat hierarchy. * Devmode: * Apply as little additional plugins as possible (compiles faster). * File names have no hashes, or hashes are deterministically based on the content. This means, when running webpack-watch, you do not end up with a growing pile of thousands of files in the output directory. MathJax: It lives in its own isolated world. This means, don't mess with the MathJax.js ... It needs to know from where it is loaded (the path in the URL), to retrieve many additional files on demand. That's also the main reason why it is slow, because for each file a new SSL connection has to be setup! (unless, http/2 or spdy do https pipelining). How do we help MathJax a little bit by caching it, when the file names aren't hashed? The trick is to add the MathJax version number to the path, such that it is unique and will definitely trigger a reload after an update of MathJax. The MathjaxVersionedSymlink below (in combination with misc_node.MATHJAX_LIB) does extract the MathJax version number, computes the path, and symlinks to its location. Why in misc_node? The problem is, that also the jupyter server (in its isolated iframe), needs to know about the MathJax URL. That way, the hub can send down the URL to the jupyter server (there is no webapp client in between). */ "use strict"; // So we can require coffeescript code. require("coffeescript/register"); // So we can require Typescript code. require("ts-node").register(); let cleanWebpackPlugin, entries, hashname, MATHJAX_URL, output_fn, publicPath; const plugins = []; const _ = require("lodash"); const webpack = require("webpack"); const path = require("path"); const fs = require("fs"); const glob = require("glob"); const child_process = require("child_process"); const misc = require("smc-util/misc"); const misc_node = require("smc-util-node/misc_node"); const async = require("async"); const program = require("commander"); const SMC_VERSION = require("smc-util/smc-version").version; const theme = require("smc-util/theme"); const RES_VERSIONS = require("webapp-lib/resources/versions").versions; const git_head = child_process.execSync("git rev-parse HEAD"); const GIT_REV = git_head.toString().trim(); const TITLE = theme.SITE_NAME; const DESCRIPTION = theme.APP_TAGLINE; const SMC_REPO = "https://github.com/sagemathinc/cocalc"; const SMC_LICENSE = "AGPLv3"; const { WEBAPP_LIB } = misc_node; const INPUT = path.resolve(__dirname, WEBAPP_LIB); const OUTPUT = path.resolve(__dirname, misc_node.OUTPUT_DIR); const DEVEL = "development"; const NODE_ENV = process.env.NODE_ENV || DEVEL; const { NODE_DEBUG } = process.env; const PRODMODE = NODE_ENV !== DEVEL; const COMP_ENV = (process.env.CC_COMP_ENV || PRODMODE) && fs.existsSync("webapp-lib/compute-components.json"); const COMMERCIAL = !!COMP_ENV; // assume to be in the commercial setup, if we show the compute environment let { CDN_BASE_URL } = process.env; // CDN_BASE_URL must have a trailing slash const DEVMODE = !PRODMODE; const MINIFY = !!process.env.WP_MINIFY; const DEBUG = process.argv.includes("--debug"); const { MEASURE } = process.env; const SOURCE_MAP = !!process.env.SOURCE_MAP; const date = new Date(); const BUILD_DATE = date.toISOString(); const BUILD_TS = date.getTime(); const { GOOGLE_ANALYTICS } = misc_node; const CC_NOCLEAN = !!process.env.CC_NOCLEAN; // If True, do not run typescript compiler at all. Fast, // but obviously less safe. This is designed for use, e.g., // when trying to do a quick production build in an emergency, // when we already know the typescript all works. const TS_TRANSPILE_ONLY = !!process.env.TS_TRANSPILE_ONLY; // When building the static page or if the user explicitly sets // an env variable, we do not want to use the forking typescript // module instead. const DISABLE_TS_LOADER_OPTIMIZATIONS = !!process.env.DISABLE_TS_LOADER_OPTIMIZATIONS || PRODMODE || TS_TRANSPILE_ONLY; // create a file base_url to set a base url const { BASE_URL } = misc_node; // check and sanitiziation (e.g. an exising but empty env variable is ignored) // CDN_BASE_URL must have a trailing slash if (CDN_BASE_URL == null || CDN_BASE_URL.length === 0) { CDN_BASE_URL = null; } else { if (CDN_BASE_URL.slice(-1) !== "/") { throw new Error( `CDN_BASE_URL must be an URL-string ending in a '/' -- but it is ${CDN_BASE_URL}` ); } } // output build environment variables of webpack console.log(`SMC_VERSION = ${SMC_VERSION}`); console.log(`SMC_GIT_REV = ${GIT_REV}`); console.log(`NODE_ENV = ${NODE_ENV}`); console.log(`NODE_DEBUG = ${NODE_DEBUG}`); console.log(`COMP_ENV = ${COMP_ENV}`); console.log(`BASE_URL = ${BASE_URL}`); console.log(`CDN_BASE_URL = ${CDN_BASE_URL}`); console.log(`DEBUG = ${DEBUG}`); console.log(`MINIFY = ${MINIFY}`); console.log(`MEASURE = ${MEASURE}`); console.log(`INPUT = ${INPUT}`); console.log(`OUTPUT = ${OUTPUT}`); console.log(`GOOGLE_ANALYTICS = ${GOOGLE_ANALYTICS}`); console.log(`CC_NOCLEAN = ${CC_NOCLEAN}`); console.log(`TS_TRANSPILE_ONLY= ${TS_TRANSPILE_ONLY}`); console.log( `DISABLE_TS_LOADER_OPTIMIZATIONS = ${DISABLE_TS_LOADER_OPTIMIZATIONS}` ); // mathjax version → symlink with version info from package.json/version if (CDN_BASE_URL != null) { // the CDN url does not have the /static/... prefix! MATHJAX_URL = CDN_BASE_URL + path.join(misc_node.MATHJAX_SUBDIR, "MathJax.js"); } else { ({ MATHJAX_URL } = misc_node); // from where the files are served } const { MATHJAX_ROOT } = misc_node; // where the symlink originates const { MATHJAX_LIB } = misc_node; // where the symlink points to console.log(`MATHJAX_URL = ${MATHJAX_URL}`); console.log(`MATHJAX_ROOT = ${MATHJAX_ROOT}`); console.log(`MATHJAX_LIB = ${MATHJAX_LIB}`); // fallback case: if COMP_ENV is false (default) we still need empty json files to satisfy the webpack dependencies if (!COMP_ENV) { for (let fn of [ "webapp-lib/compute-components.json", "webapp-lib/compute-inventory.json", ]) { if (fs.existsSync(fn)) { continue; } fs.writeFileSync(fn, "{}"); } } // adds a banner to each compiled and minified source .js file // webpack2: https://webpack.js.org/guides/migrating/#bannerplugin-breaking-change const banner = new webpack.BannerPlugin({ banner: `\ This file is part of ${TITLE}. It was compiled ${BUILD_DATE} at revision ${GIT_REV} and version ${SMC_VERSION}. See ${SMC_REPO} for its ${SMC_LICENSE} code.\ `, entryOnly: true, }); // webpack plugin to do the linking after it's "done" class MathjaxVersionedSymlink { apply(compiler) { // make absolute path to the mathjax lib (lives in node_module of smc-webapp) const symto = path.resolve(__dirname, `${MATHJAX_LIB}`); console.log(`mathjax symlink: pointing to ${symto}`); const mksymlink = (dir, cb) => fs.access(dir, function (err) { if (err) { fs.symlink(symto, dir, cb); } }); const done = (compilation) => async.concat([MATHJAX_ROOT, misc_node.MATHJAX_NOVERS], mksymlink); const plugin = { name: "MathjaxVersionedSymlink" }; compiler.hooks.done.tap(plugin, done); } } const mathjaxVersionedSymlink = new MathjaxVersionedSymlink(); if (!CC_NOCLEAN) { // cleanup like "make distclean" // otherwise, compiles create an evergrowing pile of files const CleanWebpackPlugin = require("clean-webpack-plugin"); cleanWebpackPlugin = new CleanWebpackPlugin([OUTPUT], { verbose: true, dry: false, }); } // assets.json file const AssetsPlugin = require("assets-webpack-plugin"); const assetsPlugin = new AssetsPlugin({ path: OUTPUT, filename: "assets.json", fullPath: false, prettyPrint: true, metadata: { git_ref: GIT_REV, version: SMC_VERSION, built: BUILD_DATE, timestamp: BUILD_TS, }, }); // https://www.npmjs.com/package/html-webpack-plugin const HtmlWebpackPlugin = require("html-webpack-plugin"); // we need our own chunk sorter, because just by dependency doesn't work // this way, we can be 100% sure function smcChunkSorter(a, b) { const order = ["css", "fill", "vendor", "smc"]; if (order.indexOf(a.names[0]) < order.indexOf(b.names[0])) { return -1; } else { return 1; } } // https://github.com/kangax/html-minifier#options-quick-reference const htmlMinifyOpts = { empty: true, removeComments: true, minifyJS: true, minifyCSS: true, collapseWhitespace: true, conservativeCollapse: true, }; // when base_url_html is set, it is hardcoded into the index page // it mimics the logic of the hub, where all trailing slashes are removed // i.e. the production page has a base url of '' and smc-in-smc has '/.../...' let base_url_html = BASE_URL; // do *not* modify BASE_URL, it's needed with a '/' down below while (base_url_html && base_url_html[base_url_html.length - 1] === "/") { base_url_html = base_url_html.slice(0, base_url_html.length - 1); } // this is the main app.html file, which should be served without any caching // config: https://github.com/jantimon/html-webpack-plugin#configuration const pug2app = new HtmlWebpackPlugin({ filename: "app.html", chunksSortMode: smcChunkSorter, hash: PRODMODE, template: path.join(INPUT, "app.pug"), minify: htmlMinifyOpts, inject: false, templateParameters: function (compilation, assets, options) { return { files: assets, htmlWebpackPlugin: { options: { ...options, ...{ date: BUILD_DATE, title: TITLE, description: DESCRIPTION, BASE_URL: base_url_html, RES_VERSIONS, theme, COMP_ENV, components: {}, // no data needed, empty is fine inventory: {}, // no data needed, empty is fine git_rev: GIT_REV, mathjax: MATHJAX_URL, GOOGLE_ANALYTICS, COMMERCIAL, }, }, }, }; }, }); // global css loader configuration const cssConfig = JSON.stringify({ sourceMap: false, }); // this is like C's #ifdef for the source code. It is particularly useful in the // source code of CoCalc's webapp, such that it knows about itself's version and where // mathjax is. The version&date is shown in the hover-title in the footer (year). const setNODE_ENV = new webpack.DefinePlugin({ "process.env": { NODE_ENV: JSON.stringify(NODE_ENV), }, MATHJAX_URL: JSON.stringify(MATHJAX_URL), SMC_VERSION: JSON.stringify(SMC_VERSION), SMC_GIT_REV: JSON.stringify(GIT_REV), BUILD_DATE: JSON.stringify(BUILD_DATE), BUILD_TS: JSON.stringify(BUILD_TS), DEBUG: JSON.stringify(DEBUG), }); // Writes a JSON file containing the main webpack-assets and their filenames. const { StatsWriterPlugin } = require("webpack-stats-plugin"); const statsWriterPlugin = new StatsWriterPlugin({ filename: "webpack-stats.json", }); // https://webpack.js.org/guides/migrating/#uglifyjsplugin-minimize-loaders const loaderOptions = new webpack.LoaderOptionsPlugin({ minimize: true, options: { "html-minify-loader": { empty: true, // KEEP empty attributes cdata: true, // KEEP CDATA from scripts comments: false, removeComments: true, minifyJS: true, minifyCSS: true, collapseWhitespace: true, conservativeCollapse: true, }, }, // absolutely necessary, also see above in module.loaders/.html //sassLoader: // includePaths: [path.resolve(__dirname, 'src', 'scss')] //context: '/' }); if (cleanWebpackPlugin != null) { plugins.push(cleanWebpackPlugin); } plugins.push(...[setNODE_ENV, banner, loaderOptions]); // ATTN don't alter or add names here, without changing the sorting function above! entries = { css: "webapp-css.js", fill: "@babel/polyfill", smc: "webapp-cocalc.js", // code splitting: we take all of our vendor code and put it in a separate bundle (vendor.min.js) // this way it will have better caching/cache hits since it changes infrequently vendor: [ // local packages "./webapp-lib/primus/primus-engine.min.js", // npm packages are added to vendor code separately in splitChunks config below ], "pdf.worker": "./smc-webapp/node_modules/pdfjs-dist/build/pdf.worker.entry", }; plugins.push(...[pug2app, mathjaxVersionedSymlink]); if (!DISABLE_TS_LOADER_OPTIMIZATIONS) { console.log("Enabling ForkTsCheckerWebpackPlugin..."); if (process.env.TSC_WATCHDIRECTORY == null || process.env.TSC_WATCHFILE) { console.log( "To workaround performance issues with the default typescript watch, we set TSC_WATCH* env vars:" ); // See https://github.com/TypeStrong/fork-ts-checker-webpack-plugin/issues/236 // This one seems to work well; others miss changes: process.env.TSC_WATCHFILE = "UseFsEventsOnParentDirectory"; // Using "RecursiveDirectoryUsingFsWatchFile" for the directory is very inefficient on CoCalc. process.env.TSC_WATCHDIRECTORY = "RecursiveDirectoryUsingDynamicPriorityPolling"; } const ForkTsCheckerWebpackPlugin = require("fork-ts-checker-webpack-plugin"); plugins.push( new ForkTsCheckerWebpackPlugin({ // async false makes it much easy to see the error messages and // be aware of when compilation is done, // but is slower because it has to wait before showing them. // We still benefit from parallel computing though. // We could change this to async if there were some // better way to display that output is pending and that it appeared... // NOTE: it is very important to do // TSC_WATCHFILE=UseFsEventsWithFallbackDynamicPolling // in package.json's watch. See // https://blog.johnnyreilly.com/2019/05/typescript-and-high-cpu-usage-watch.html async: true, }) ); } if (DEVMODE) { console.log(`\ ****************************************************** * You have to visit: * * https://cocalc.com/[project_id]/port/[...]/app * ******************************************************`); } if (PRODMODE) { // configuration for the number of chunks and their minimum size plugins.push(new webpack.optimize.LimitChunkCountPlugin({ maxChunks: 5 })); } plugins.push(...[assetsPlugin, statsWriterPlugin]); const UglifyJsPlugin = require("uglifyjs-webpack-plugin"); const minimizer = new UglifyJsPlugin({ uglifyOptions: { output: { comments: new RegExp(`This file is part of ${TITLE}`, "g"), }, }, }); // to keep the banner inserted above // tuning generated filenames and the configs for the aux files loader. // FIXME this setting isn't picked up properly if (PRODMODE) { hashname = "[sha256:hash:base62:33].cacheme.[ext]"; // don't use base64, it's not recommended for some reason. } else { hashname = "[path][name].nocache.[ext]"; } const pngconfig = { name: hashname, limit: 16000, mimetype: "image/png" }; const svgconfig = { name: hashname, limit: 16000, mimetype: "image/svg+xml" }; const icoconfig = { name: hashname, mimetype: "image/x-icon" }; const woffconfig = { name: hashname, mimetype: "application/font-woff" }; // publicPath: either locally, or a CDN, see https://github.com/webpack/docs/wiki/configuration#outputpublicpath // In order to use the CDN, copy all files from the `OUTPUT` directory over there. // Caching: files ending in .html (like index.html or those in /policies/) and those matching '*.nocache.*' shouldn't be cached // all others have a hash and can be cached long-term (especially when they match '*.cacheme.*') if (CDN_BASE_URL != null) { publicPath = CDN_BASE_URL; } else { publicPath = path.join(BASE_URL, misc_node.OUTPUT_DIR) + "/"; } if (MEASURE) { const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer"); const bundleAnalyzerPlugin = new BundleAnalyzerPlugin({ analyzerMode: "static", }); plugins.push(...[bundleAnalyzerPlugin]); } module.exports = { cache: true, // https://webpack.js.org/configuration/devtool/#devtool // **do** use cheap-module-eval-source-map; it produces too large files, but who cares since we are not // using this in production. DO NOT use 'source-map', which is VERY slow. devtool: SOURCE_MAP ? "#cheap-module-eval-source-map" : undefined, mode: PRODMODE ? "production" : "development", optimization: { minimizer: [minimizer], // this doesn't play nice with a loading indicator on the app page. probably best to not use it. //splitChunks: { // cacheGroups: { // commons: { // test: /[\\/]node_modules[\\/]/, // name: "vendor", // chunks: "all", // }, // }, //}, }, entry: entries, output: { path: OUTPUT, publicPath, filename: PRODMODE ? "[name]-[hash].cacheme.js" : "[name].nocache.js", chunkFilename: PRODMODE ? "[id]-[hash].cacheme.js" : "[id].nocache.js", hashFunction: "sha256", }, module: { rules: [ { test: /\.coffee$/, loader: "coffee-loader" }, { test: /\.cjsx$/, loader: ["coffee-loader", "cjsx-loader"] }, { test: [/node_modules\/prom-client\/.*\.js$/], loader: "babel-loader" }, { test: [/latex-editor\/.*\.jsx?$/], loader: "babel-loader" }, // Note: see https://github.com/TypeStrong/ts-loader/issues/552 // for discussion of issues with ts-loader + webpack. { test: /\.tsx?$/, use: { loader: "ts-loader", options: TS_TRANSPILE_ONLY || DISABLE_TS_LOADER_OPTIMIZATIONS ? { transpileOnly: TS_TRANSPILE_ONLY } // run as normal or not at all : { // do not run typescript checker in same process... transpileOnly: !TS_TRANSPILE_ONLY, experimentalWatchApi: true, }, }, }, { test: /\.less$/, use: [ "style-loader", { loader: "css-loader", options: { importLoaders: 2, }, }, "postcss-loader", `less-loader?${cssConfig}`, ], }, { test: /\.scss$/i, use: [ "style-loader", { loader: "css-loader", options: { importLoaders: 2, }, }, "postcss-loader", `sass-loader?${cssConfig}`, ], }, { test: /\.sass$/i, use: [ "style-loader", { loader: "css-loader", options: { importLoaders: 2, }, }, "postcss-loader", `sass-loader?${cssConfig}&indentedSyntax`, ], }, { test: /\.png$/, use: [{ loader: "file-loader", options: pngconfig }], }, { test: /\.ico$/, use: [{ loader: "file-loader", options: icoconfig }], }, { test: /\.svg(\?[a-z0-9\.-=]+)?$/, use: [{ loader: "url-loader", options: svgconfig }], }, { test: /\.(jpg|jpeg|gif)$/, use: [{ loader: "file-loader", options: { name: hashname } }], }, { test: /\.html$/, include: [path.resolve(__dirname, "smc-webapp")], use: [ { loader: "raw-loader" }, { loader: "html-minify-loader", options: { conservativeCollapse: true }, }, ], }, { test: /\.hbs$/, loader: "handlebars-loader" }, { test: /\.woff(2)?(\?[a-z0-9\.-=]+)?$/, use: [{ loader: "url-loader", options: woffconfig }], }, { test: /\.ttf(\?[a-z0-9\.-=]+)?$/, use: [ { loader: "url-loader", options: { limit: 10000, mimetype: "application/octet-stream" }, }, ], }, { test: /\.eot(\?[a-z0-9\.-=]+)?$/, use: [{ loader: "file-loader", options: { name: hashname } }], }, // --- { test: /\.css$/i, use: [ "style-loader", { loader: "css-loader", options: { importLoaders: 1, }, }, "postcss-loader", ], }, { test: /\.pug$/, loader: "pug-loader" }, ], }, resolve: { // So we can require('file') instead of require('file.coffee') extensions: [ ".js", ".jsx", ".ts", ".tsx", ".json", ".coffee", ".cjsx", ".scss", ".sass", ], modules: [ path.resolve(__dirname), path.resolve(__dirname, WEBAPP_LIB), path.resolve(__dirname, "smc-util"), path.resolve(__dirname, "smc-util/node_modules"), path.resolve(__dirname, "smc-webapp"), path.resolve(__dirname, "smc-webapp/node_modules"), path.resolve(__dirname, "node_modules"), ], }, plugins, };
sagemathinc/smc
src/webpack.config.js
JavaScript
agpl-3.0
24,056
var nodeList = document.getElementsByClassName('draggable'); for(var i=0;i<nodeList.length;i++) { var obj = nodeList[i]; obj.addEventListener('touchmove', function(event) { var touch = event.targetTouches[0]; var ancho = this.offsetWidth; var alto = this.offsetHeight; event.target.style.left = touch.pageX-(ancho/2) + 'px'; event.target.style.top = touch.pageY-(alto/2) + 'px'; event.preventDefault(); }, false); }; document.querySelector('#b01a').onclick = function () { var audio = confirm('¿Quieres comenzar con la narración?'); if (audio == true) { document.getElementById('sonido_1').play(); var activar = document.getElementById('b01a'); activar.style.visibility ='hidden'; document.querySelector('#b02a').style.visibility ='visible'; } else { alert('Cancelado') } }; document.querySelector('#b02a').onclick = function () { document.getElementById('sonido_1').pause(); document.querySelector('#b02a').style.visibility ='hidden'; document.querySelector('#b01a').style.visibility ='visible'; };
movilla/movilla.github.io
resistencia/js/app.js
JavaScript
agpl-3.0
1,220
/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2010 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Daniel Wagner (d_wagner) ************************************************************************ */ /** * Modified qx.core.Init for server-side applications where no browser events * are available. */ qx.Class.define("simulator.Init", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { /** * Returns the instantiated qooxdoo application. * * @return {qx.core.Object} The application instance. */ getApplication : function() { return this.__application || null; }, /** * Runs when the application is loaded. Automatically creates an instance * of the class defined by the setting <code>qx.application</code>. * * @return {void} */ ready : function() { if (this.__application) { return; } qx.log.Logger.debug(this, "Load runtime: " + (new Date - qx.Bootstrap.LOADSTART) + "ms"); var app = qx.core.Environment.get("qx.application"); var clazz = qx.Class.getByName(app); if (clazz) { this.__application = new clazz; var start = new Date; this.__application.main(); qx.log.Logger.debug(this, "Main runtime: " + (new Date - start) + "ms"); var start = new Date; this.__application.finalize(); qx.log.Logger.debug(this, "Finalize runtime: " + (new Date - start) + "ms"); } else { qx.log.Logger.warn("Missing application class: " + app); } } } });
Seldaiendil/meyeOS
devtools/qooxdoo-1.5-sdk/component/simulator/source/class/simulator/Init.js
JavaScript
agpl-3.0
2,094
/* * Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U * * This file is part of fiware-iotagent-lib * * fiware-iotagent-lib is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * fiware-iotagent-lib is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public * License along with fiware-iotagent-lib. * If not, seehttp://www.gnu.org/licenses/. * * For those usages not covered by the GNU Affero General Public License * please contact with::[contacto@tid.es] * * Modified by: Daniel Calvo - ATOS Research & Innovation */ /* eslint-disable no-unused-vars */ const config = require('./testConfig'); const lwm2mClient = require('lwm2m-node-lib').client; const iotAgent = require('../../../lib/iotAgentLwm2m'); const ngsiTestUtils = require('../ngsiUtils'); const mongoUtils = require('../mongoDBUtils'); const async = require('async'); const apply = async.apply; const utils = require('../../utils'); const request = utils.request; const should = require('should'); const clientConfig = { host: 'localhost', port: '60001', endpointName: 'TestClient', url: '/robot', ipProtocol: 'udp4' }; const ngsiClient = ngsiTestUtils.createNgsi( config.ngsi.contextBroker.host, config.ngsi.contextBroker.port, 'smartgondor', '/gardens' ); let deviceInformation; describe('Command attributes test', function () { beforeEach(function (done) { lwm2mClient.init(config); async.series( [ apply(mongoUtils.cleanDbs, config.ngsi.contextBroker.host), apply(iotAgent.start, config), apply(lwm2mClient.registry.create, '/5000/0') ], done ); }); describe('When a command value is changed in Orion for a statically configured type', function () { beforeEach(function (done) { lwm2mClient.register( clientConfig.host, clientConfig.port, clientConfig.url, clientConfig.endpointName, function (error, result) { deviceInformation = result; async.series( [ async.apply(lwm2mClient.registry.create, '/9090/0'), async.apply(lwm2mClient.registry.setResource, '/9090/0', '0', '[]') ], done ); } ); }); afterEach(function (done) { async.series( [ apply(lwm2mClient.unregister, deviceInformation), iotAgent.stop, apply(mongoUtils.cleanDbs, config.ngsi.contextBroker.host), lwm2mClient.registry.reset ], done ); }); it('should send the execution command to the LWM2M client', function (done) { let handleExecuted = false; const attributes = [ { name: 'position', type: 'Array', value: '[15,6234,312]' } ]; function handleExecute(objectType, objectId, resourceId, args, callback) { objectType.should.equal('9090'); objectId.should.equal('0'); resourceId.should.equal('0'); handleExecuted = true; callback(); } lwm2mClient.setHandler(deviceInformation.serverInfo, 'execute', handleExecute); ngsiClient.update('TestClient:Robot', 'Robot', attributes, function (error, response, body) { should.not.exist(error); handleExecuted.should.equal(true); done(); }); }); it('should return a 200 OK statusCode', function (done) { const attributes = [ { name: 'position', type: 'Array', value: '[15,6234,312]' } ]; function handleExecute(objectType, objectId, resourceId, args, callback) { callback(); } lwm2mClient.setHandler(deviceInformation.serverInfo, 'execute', handleExecute); ngsiClient.update('TestClient:Robot', 'Robot', attributes, function (error, response, body) { should.not.exist(error); response.statusCode.should.equal(204); done(); }); }); }); describe('When a command value is changed in Orion for a preprovisioned device', function () { const options = { url: 'http://localhost:' + config.ngsi.server.port + '/iot/devices', method: 'POST', json: utils.readExampleFile('./test/provisionExamples/provisionDeviceWithCommands.json'), headers: { 'fiware-service': 'smartgondor', 'fiware-servicepath': '/gardens' } }; beforeEach(function (done) { request(options, function (error, response, body) { lwm2mClient.register(clientConfig.host, clientConfig.port, clientConfig.url, 'TestRobotPre', function ( error, result ) { deviceInformation = result; async.series( [ async.apply(lwm2mClient.registry.create, '/6789/0'), async.apply(lwm2mClient.registry.setResource, '/6789/0', '17', '[]') ], done ); }); }); }); afterEach(function (done) { async.series( [ apply(lwm2mClient.unregister, deviceInformation), iotAgent.stop, apply(mongoUtils.cleanDbs, config.ngsi.contextBroker.host), lwm2mClient.registry.reset ], done ); }); it('should send the execution command to the LWM2M client', function (done) { let handleExecuted = false; const attributes = [ { name: 'position', type: 'Array', value: '[15,6234,312]' } ]; function handleExecute(objectType, objectId, resourceId, args, callback) { objectType.should.equal('6789'); objectId.should.equal('0'); resourceId.should.equal('17'); handleExecuted = true; callback(); } lwm2mClient.setHandler(deviceInformation.serverInfo, 'execute', handleExecute); ngsiClient.update('RobotPre:TestRobotPre', 'RobotPre', attributes, function (error, response, body) { should.not.exist(error); handleExecuted.should.equal(true); done(); }); }); it('should return a 200 OK statusCode'); }); describe('When a command value is changed in Orion for a device registering in a configuration', function () { it('should send the execution command to the LWM2M client'); it('should return a 200 OK statusCode'); }); });
telefonicaid/lightweightm2m-iotagent
test/unit/ngsiv2/commands-test.js
JavaScript
agpl-3.0
7,891
/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Tino Butz (tbtz) ************************************************************************ */ /* ************************************************************************ #asset(qx/mobile/js/iscroll.js) #ignore(iScroll) ************************************************************************ */ /** * EXPERIMENTAL - NOT READY FOR PRODUCTION * * Mixin for the {@link Scroll} container. Used when the variant * <code>qx.mobile.nativescroll</code> is set to "off". Uses the iScroll script to simulate * the CSS position:fixed style. Position fixed is not available in iOS and * Android < 2.2. */ qx.Mixin.define("qx.ui.mobile.container.MIScroll", { /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ construct : function() { this.__initScroll(); this.__registerEventListeners(); }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { __scroll : null, /** * Mixin method. Creates the scroll element. * * @return {Element} The scroll element */ _createScrollElement : function() { var scroll = qx.bom.Element.create("div"); return scroll; }, /** * Mixin method. Returns the scroll content element.. * * @return {Element} The scroll content element */ _getScrollContentElement : function() { return this.getContainerElement().childNodes[0]; }, /** * Loads and inits the iScroll instance. * * @lint ignoreUndefined(iScroll) */ __initScroll : function() { if (!window.iScroll) { var resource = "qx/mobile/js/iscroll"; if (qx.core.Environment.get("qx.debug")) { resource += "-debug"; } resource += ".js"; var path = qx.util.ResourceManager.getInstance().toUri(resource); if (qx.core.Environment.get("qx.debug")) { path += "?" + new Date().getTime(); } var loader = new qx.io.ScriptLoader(); loader.load(path, this.__onScrollLoaded, this); } else { this._setScroll(this.__createScrollInstance()); } }, /** * Creates the iScroll instance. * * @return {iScroll} The iScroll instance * @lint ignoreUndefined(iScroll) */ __createScrollInstance : function() { var scroll = new iScroll(this.getContainerElement(), { hideScrollbar:true, fadeScrollbar:true, hScrollbar : false, scrollbarClass:"scrollbar", onBeforeScrollStart : function(e) { // QOOXDOO ENHANCEMENT: Do not prevent default for form elements var target = e.target; while (target.nodeType != 1) { target = target.parentNode; } if (target.tagName != 'SELECT' && target.tagName != 'INPUT' && target.tagName != 'TEXTAREA') { e.preventDefault(); } } }); return scroll; }, /** * Registers all needed event listener. */ __registerEventListeners : function() { qx.event.Registration.addListener(window, "orientationchange", this._refresh, this); qx.event.Registration.addListener(window, "resize", this._refresh, this); this.addListener("domupdated", this._refresh, this); }, /** * Unregisters all needed event listener. */ __unregisterEventListeners : function() { qx.event.Registration.removeListener(window, "orientationchange", this._refresh, this); qx.event.Registration.removeListener(window, "resize", this._refresh, this); this.removeListener("domupdated", this._refresh, this); }, /** * Load callback. Called when the iScroll script is loaded. * * @param status {String} the status of the script loading. See * {@link qx.io.ScriptLoader#load} for more information. */ __onScrollLoaded : function(status) { if (status == "success") { this._setScroll(this.__createScrollInstance()); } else { if (qx.core.Environment.get("qx.debug")) { this.error("Could not load iScroll"); } } }, /** * Setter for the scroll instance. * * @param scroll {iScroll} iScroll instance. */ _setScroll : function(scroll) { this.__scroll = scroll; }, /** * Calls the refresh function of iScroll. Needed to recalculate the * scrolling container. */ _refresh : function() { if (this.__scroll) { this.__scroll.refresh(); } } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function() { this.__unregisterEventListeners(); // Cleanup iScroll if (this.__scroll) { this.__scroll.destroy(); } this.__scroll; } });
Seldaiendil/meyeOS
devtools/qooxdoo-1.5-sdk/framework/source/class/qx/ui/mobile/container/MIScroll.js
JavaScript
agpl-3.0
5,642
/***************************/ //@Author: Adrian "yEnS" Mato Gondelle & Ivan Guardado Castro //@website: www.yensdesign.com //@email: yensamg@gmail.com //@license: Feel free to use it, but keep this credits please! /***************************/ $(document).ready(function(){ $(".menu > li").click(function(e){ switch(e.target.id){ case "comments": //change status & style menu $("#comments").addClass("active"); $("#overview").removeClass("active"); $("#experience").removeClass("active"); $("#appearances").removeClass("active"); //display selected division, hide others $("div.comments").fadeIn(); $("div.overview").css("display", "none"); $("div.experience").css("display", "none"); $("div.appearances").css("display", "none"); break; case "overview": //change status & style menu $("#comments").removeClass("active"); $("#overview").addClass("active"); $("#experience").removeClass("active"); $("#appearances").removeClass("active"); //display selected division, hide others $("div.comments").css("display", "none"); $("div.overview").fadeIn(); $("div.experience").css("display", "none"); $("div.appearances").css("display", "none"); break; case "experience": //change status & style menu $("#comments").removeClass("active"); $("#overview").removeClass("active"); $("#experience").addClass("active"); $("#appearances").removeClass("active"); //display selected division, hide others $("div.comments").css("display", "none"); $("div.overview").css("display", "none"); $("div.experience").fadeIn(); $("div.appearances").css("display", "none"); break; case "appearances": //change status & style menu $("#comments").removeClass("active"); $("#overview").removeClass("active"); $("#experience").removeClass("active"); $("#appearances").addClass("active"); //display selected division, hide others $("div.comments").css("display", "none"); $("div.overview").css("display", "none"); $("div.experience").css("display", "none"); $("div.appearances").fadeIn(); break; } //alert(e.target.id); return false; }); });
Hutspace/odekro
mzalendo/odekro/static/js/tabs.js
JavaScript
agpl-3.0
2,271
/** * Main object for integrating Typhos' BetterPonymotes with Discord * (c) 2015-2016 ByzantineFailure * * Many much thanks to BetterDiscord, from which a lot of ideas * are cribbed. * https://github.com/Jiiks/BetterDiscordApp * * Runs all our compiled code in Discord's Electron environment **/ module.exports = BPM; var path = require('path'), fs = require('fs'), bpmDir = getBpmDir(), self; function getBpmDir() { switch(process.platform) { case 'win32': return path.join(process.env.APPDATA, 'discord', 'bpm'); case 'darwin': return path.join(process.env.HOME, 'Library', 'Preferences', 'discord', 'bpm'); case 'linux': return path.resolve(process.execPath,'..', 'bpm'); default: return path.join('var', 'local', 'bpm'); } } function BPM(mainWindow) { self = this; self.mainWindow = mainWindow; } BPM.prototype.init = function() { var scripts = getScripts(); self.mainWindow.webContents.on('dom-ready', function() { scripts.forEach(function(script) { self.mainWindow.webContents.executeJavaScript(script); }); }); }; function readAddonFile(filename) { return fs.readFileSync(path.join(bpmDir, filename), 'utf-8'); } function getCustomScripts() { return fs.readdirSync(path.join(bpmDir, 'custom')) .filter(function(filename) { return filename.endsWith('.js'); }) .map(function(filename) { return readCustomFile(filename); }); } function readCustomFile(filename) { return fs.readFileSync(path.join(bpmDir, 'custom', filename), 'utf-8'); } function getScripts() { return [ readAddonFile('bpm.js') ] .concat(getCustomScripts()); }
ILikePizza555/BPM-for-Discord
discord/integration/bpm.js
JavaScript
agpl-3.0
1,746
OC.L10N.register( "bookmarks", { "Bookmarks" : "বুকমার্ক", "Bookm." : "বুকএম.", "No file provided for import" : "ইম্পোর্টের জন্য প্রদান করা কোন ফাইল", "Unsupported file type for import" : "ইমপোর্টের জন্য অসমর্থিত ফাইল টাইপ", "Error" : "ভুল", "Filter by tag" : "ট্যাগ দ্বারা ফিল্টার করুন", "Warning" : "সতর্কীকরণ", "Tags" : "ট্যাগ্স", "Are you sure you want to remove this tag from every entry?" : "আপনি আপনার প্রতি এন্ট্রি থেকে এই ট্যাগটি মুছে ফেলার ব্যাপারে নিশ্চিত?", "Import error" : "ইম্পোর্ট ত্রুটি", "Import completed successfully." : "ইম্পোর্ট সফলভাবে সম্পন্ন হয়েছে।", "Uploading..." : "আপলোডইং ...", "Add a bookmark" : "বুকমার্ক অ্যাড করুন ", "The title of the page" : "পৃষ্ঠার শিরোনাম", "The address of the page" : "পৃষ্ঠার ঠিকানা", "Description of the page" : "পৃষ্ঠার বিবরণ", "Save" : "সেভ", "Delete" : "মুছে ফেলা", "Edit" : "এডিট", "Cancel" : "বাতিল করা", "Drag this to your browser bookmarks and click it, when you want to bookmark a webpage quickly:" : "আপনার ব্রাউজারের বুকমার্কে এটি ড্র্যাগ করে নিয়ে যান এবং এটা ক্লিক করুন, যখন আপনি দ্রুত একটি ওয়েব পেজ বুকমার্ক করতে চান:", "Add to ownCloud" : "OwnCloud এ যোগ করুন", "Address" : "ঠিকানা", "Add" : "যোগ করা", "You have no bookmarks" : "আপনার কোন বুকমার্ক নেই", "Bookmarklet" : "বুকমার্কলেট", "Export & Import" : "এক্সপোর্ট ও ইম্পোর্ট", "Export" : "এক্সপোর্ট", "Import" : "ইম্পোর্ট" }, "nplurals=2; plural=(n != 1);");
tflidd/bookmarks
l10n/bn_IN.js
JavaScript
agpl-3.0
2,472
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), clean: [ 'demo/*.html', 'demo/css/*.css' ], webfont: { icons: { src: 'icons/*.{svg,eps}', dest: 'fonts', destCss: 'less/etalab', options: { stylesheet: 'less', relativeFontPath: '../../fonts', // font: 'etalab-icons', hashes: false } } }, jasmine: { etalab: { src: 'js/*.js', options: { specs: 'specs/**/*.specs.js', helpers: 'specs/helpers/*.js', template: 'runner.tmpl', vendor: [ 'bower/jquery/jquery.js', 'bower/jquery.cookie/jquery.cookie.js', 'bower/bootstrap/dist/js/bootstrap.js', 'bower/typeahead.js/dist/typeahead.js', 'bower/jquery.dotdotdot/src/js/jquery.dotdotdot.js', 'bower/swig/index.js' ], templateOptions: { metas: [ {name: 'domain', content: 'fake.fr'} ], links: [ {rel: 'home', href: 'http://www.fake.fr'}, {rel: 'wiki', href: 'http://wiki.fake.fr'}, {rel: 'wiki-api', href: 'http://wiki.fake.fr/api.php'}, {rel: 'questions', href: 'http://questions.fake.fr'} ] } } } }, jshint: { all: ['Gruntfile.js', 'js/*.js'], options: { jshintrc: '.jshintrc', } }, less: { options: { paths: ['bower/bootstrap/less'], yuicompress: true }, demo: { files: { 'demo/css/etalab.css': ['less/etalab.less'], 'demo/css/etalab-home.css': ['less/etalab-home.less'], 'demo/css/etalab-search.css': ['less/etalab-search.less'], 'demo/css/etalab-dataset.css': ['less/etalab-dataset.less'], 'demo/css/etalab-topic.css': ['less/etalab-topic.less'], } } }, watch: { less: { files: ['less/**/*.less'], tasks: ['less'] }, font: { files: ['icons/*.{svg,eps}'], tasks: ['webfont'] }, js: { files: 'js/*.js', tasks: ['test'] }, templates: { files: [ 'templates/*.swig', 'data/*.{json,yaml}' ], tasks: ['assemble'] }, livereload: { options: { livereload: true }, files: ['demo/**/*', 'js/*.js'] } }, connect: { options: { hostname: '*', port: 9000, open: true, livereload: true, base: ['.', 'demo', 'bower/bootstrap', 'bower/bootstrap/dist'] }, server: {} }, assemble: { options: { engine: 'swig', data: 'data/*' }, demo: { expand: true, cwd: 'templates', src: [ 'index.swig', // 'index-logged.swig', 'dataset.swig', // 'dataset-logged.swig', 'search.swig', // 'search-logged.swig', 'widgets.swig', // 'wdigets-logged.swig', 'topic.swig', 'error.swig', 'message.swig', 'form.swig', // 'topic.swig', ], dest: 'demo' } } }); // Load Grunt tasks declared in the package.json file require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks); grunt.loadNpmTasks('assemble'); grunt.registerTask('default', ['test']); grunt.registerTask('test', ['jasmine', 'jshint']); grunt.registerTask('dist', ['default', 'webfont']); grunt.registerTask('demo', ['clean', 'default', 'less', 'assemble', 'connect:server', 'watch']); };
etalab/etalab-assets
Gruntfile.js
JavaScript
agpl-3.0
4,816
/** Copyright (c) 2010-2013, Erik Hetzner This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * Flatten a nested array; e.g., [[1], [2,3]] -> [1,2,3] */ function flatten(a) { var retval = new Array(); for (var i in a) { var entry = a[i]; if (entry instanceof Array) { retval = retval.concat(flatten(entry)); } else { retval.push(entry); } } return retval; } var FW = { _scrapers : new Array() }; FW._Base = function () { this.callHook = function (hookName, item, doc, url) { if (typeof this['hooks'] === 'object') { var hook = this['hooks'][hookName]; if (typeof hook === 'function') { hook(item, doc, url); } } }; this.evaluateThing = function(val, doc, url) { var valtype = typeof val; if (valtype === 'object') { if (val instanceof Array) { /* map over each array val */ /* this.evaluate gets out of scope */ var parentEval = this.evaluateThing; var retval = val.map ( function(i) { return parentEval (i, doc, url); } ); return flatten(retval); } else { return val.evaluate(doc, url); } } else if (valtype === 'function') { return val(doc, url); } else { return val; } }; /* * makeItems is the function that does the work of making an item. * doc: the doc tree for the item * url: the url for the item * attachments ... * eachItem: a function to be called for each item made, with the arguments (doc, url, ...) * ret: the function to call when you are done, with no args */ this.makeItems = function (doc, url, attachments, eachItem, ret) { ret(); } }; FW.Scraper = function (init) { FW._scrapers.push(new FW._Scraper(init)); }; FW._Scraper = function (init) { for (x in init) { this[x] = init[x]; } this._singleFieldNames = [ "abstractNote", "applicationNumber", "archive", "archiveLocation", "artworkMedium", "artworkSize", "assignee", "audioFileType", "audioRecordingType", "billNumber", "blogTitle", "bookTitle", "callNumber", "caseName", "code", "codeNumber", "codePages", "codeVolume", "committee", "company", "conferenceName", "country", "court", "date", "dateDecided", "dateEnacted", "dictionaryTitle", "distributor", "docketNumber", "documentNumber", "DOI", "edition", "encyclopediaTitle", "episodeNumber", "extra", "filingDate", "firstPage", "forumTitle", "genre", "history", "institution", "interviewMedium", "ISBN", "ISSN", "issue", "issueDate", "issuingAuthority", "journalAbbreviation", "label", "language", "legalStatus", "legislativeBody", "letterType", "libraryCatalog", "manuscriptType", "mapType", "medium", "meetingName", "nameOfAct", "network", "number", "numberOfVolumes", "numPages", "pages", "patentNumber", "place", "postType", "presentationType", "priorityNumbers", "proceedingsTitle", "programTitle", "programmingLanguage", "publicLawNumber", "publicationTitle", "publisher", "references", "reportNumber", "reportType", "reporter", "reporterVolume", "rights", "runningTime", "scale", "section", "series", "seriesNumber", "seriesText", "seriesTitle", "session", "shortTitle", "studio", "subject", "system", "thesisType", "title", "type", "university", "url", "version", "videoRecordingType", "volume", "websiteTitle", "websiteType" ]; this._makeAttachments = function(doc, url, config, item) { if (config instanceof Array) { config.forEach(function (child) { this._makeAttachments(doc, url, child, item); }, this); } else if (typeof config === 'object') { /* plural or singual */ var urlsFilter = config["urls"] || config["url"]; var typesFilter = config["mimeTypes"] || config["mimeType"] || config["types"] || config["type"]; var titlesFilter = config["titles"] || config["title"]; var snapshotsFilter = config["snapshots"] || config["snapshot"]; var attachUrls = this.evaluateThing(urlsFilter, doc, url); var attachTitles = this.evaluateThing(titlesFilter, doc, url); var attachTypes = this.evaluateThing(typesFilter, doc, url); var attachSnapshots = this.evaluateThing(snapshotsFilter, doc, url); if (!(attachUrls instanceof Array)) { attachUrls = [attachUrls]; } for (var k in attachUrls) { var attachUrl = attachUrls[k]; var attachType; var attachTitle; var attachSnapshot; if (attachTypes instanceof Array) { attachType = attachTypes[k]; } else { attachType = attachTypes; } if (attachTitles instanceof Array) { attachTitle = attachTitles[k]; } else { attachTitle = attachTitles; } if (attachSnapshots instanceof Array) { attachSnapshot = attachSnapshots[k]; } else { attachSnapshot = attachSnapshots; } item["attachments"].push({ url : attachUrl, title : attachTitle, mimeType : attachType, snapshot : attachSnapshot }); } } }; this.makeItems = function (doc, url, ignore, eachItem, ret) { var item = new Zotero.Item(this.itemType); item.url = url; for (var i in this._singleFieldNames) { var field = this._singleFieldNames[i]; if (this[field]) { var fieldVal = this.evaluateThing(this[field], doc, url); if (fieldVal instanceof Array) { item[field] = fieldVal[0]; } else { item[field] = fieldVal; } } } var multiFields = ["creators", "tags"]; for (var j in multiFields) { var key = multiFields[j]; var val = this.evaluateThing(this[key], doc, url); if (val) { for (var k in val) { item[key].push(val[k]); } } } this._makeAttachments(doc, url, this["attachments"], item); eachItem(item, this, doc, url); ret(); }; }; FW._Scraper.prototype = new FW._Base; FW.MultiScraper = function (init) { FW._scrapers.push(new FW._MultiScraper(init)); }; FW._MultiScraper = function (init) { for (x in init) { this[x] = init[x]; } this._mkSelectItems = function(titles, urls) { var items = new Object; for (var i in titles) { items[urls[i]] = titles[i]; } return items; }; this._selectItems = function(titles, urls, callback) { var items = new Array(); Zotero.selectItems(this._mkSelectItems(titles, urls), function (chosen) { for (var j in chosen) { items.push(j); } callback(items); }); }; this._mkAttachments = function(doc, url, urls) { var attachmentsArray = this.evaluateThing(this['attachments'], doc, url); var attachmentsDict = new Object(); if (attachmentsArray) { for (var i in urls) { attachmentsDict[urls[i]] = attachmentsArray[i]; } } return attachmentsDict; }; /* This logic is very similar to that used by _makeAttachments in * a normal scraper, but abstracting it out would not achieve much * and would complicate it. */ this._makeChoices = function(config, doc, url, choiceTitles, choiceUrls) { if (config instanceof Array) { config.forEach(function (child) { this._makeTitlesUrls(child, doc, url, choiceTitles, choiceUrls); }, this); } else if (typeof config === 'object') { /* plural or singual */ var urlsFilter = config["urls"] || config["url"]; var titlesFilter = config["titles"] || config["title"]; var urls = this.evaluateThing(urlsFilter, doc, url); var titles = this.evaluateThing(titlesFilter, doc, url); var titlesIsArray = (titles instanceof Array); if (!(urls instanceof Array)) { urls = [urls]; } for (var k in urls) { var myUrl = urls[k]; var myTitle; if (titlesIsArray) { myTitle = titles[k]; } else { myTitle = titles; } choiceUrls.push(myUrl); choiceTitles.push(myTitle); } } }; this.makeItems = function(doc, url, ignore, eachItem, ret) { if (this.beforeFilter) { var newurl = this.beforeFilter(doc, url); if (newurl != url) { this.makeItems(doc, newurl, ignore, eachItem, ret); return; } } var titles = []; var urls = []; this._makeChoices(this["choices"], doc, url, titles, urls); var attachments = this._mkAttachments(doc, url, urls); var parentItemTrans = this.itemTrans; this._selectItems(titles, urls, function (itemsToUse) { if(!itemsToUse) { ret(); } else { var cb = function (doc1) { var url1 = doc1.documentURI; var itemTrans = parentItemTrans; if (itemTrans === undefined) { itemTrans = FW.getScraper(doc1, url1); } if (itemTrans === undefined) { /* nothing to do */ } else { itemTrans.makeItems(doc1, url1, attachments[url1], eachItem, function() {}); } }; Zotero.Utilities.processDocuments(itemsToUse, cb, ret); } }); }; }; FW._MultiScraper.prototype = new FW._Base; FW.WebDelegateTranslator = function (init) { return new FW._WebDelegateTranslator(init); }; FW._WebDelegateTranslator = function (init) { for (x in init) { this[x] = init[x]; } this.makeItems = function(doc, url, attachments, eachItem, ret) { // need for scoping var parentThis = this; var translator = Zotero.loadTranslator("web"); translator.setHandler("itemDone", function(obj, item) { eachItem(item, parentThis, doc, url); }); translator.setDocument(doc); if (this.translatorId) { translator.setTranslator(this.translatorId); translator.translate(); } else { translator.setHandler("translators", function(obj, translators) { if (translators.length) { translator.setTranslator(translators[0]); translator.translate(); } }); translator.getTranslators(); } ret(); }; }; FW._WebDelegateTranslator.prototype = new FW._Base; FW._StringMagic = function () { this._filters = new Array(); this.addFilter = function(filter) { this._filters.push(filter); return this; }; this.split = function(re) { return this.addFilter(function(s) { return s.split(re).filter(function(e) { return (e != ""); }); }); }; this.replace = function(s1, s2, flags) { return this.addFilter(function(s) { if (s.match(s1)) { return s.replace(s1, s2, flags); } else { return s; } }); }; this.prepend = function(prefix) { return this.replace(/^/, prefix); }; this.append = function(postfix) { return this.replace(/$/, postfix); }; this.remove = function(toStrip, flags) { return this.replace(toStrip, '', flags); }; this.trim = function() { return this.addFilter(function(s) { return Zotero.Utilities.trim(s); }); }; this.trimInternal = function() { return this.addFilter(function(s) { return Zotero.Utilities.trimInternal(s); }); }; this.match = function(re, group) { if (!group) group = 0; return this.addFilter(function(s) { var m = s.match(re); if (m === undefined || m === null) { return undefined; } else { return m[group]; } }); }; this.cleanAuthor = function(type, useComma) { return this.addFilter(function(s) { return Zotero.Utilities.cleanAuthor(s, type, useComma); }); }; this.key = function(field) { return this.addFilter(function(n) { return n[field]; }); }; this.capitalizeTitle = function() { return this.addFilter(function(s) { return Zotero.Utilities.capitalizeTitle(s); }); }; this.unescapeHTML = function() { return this.addFilter(function(s) { return Zotero.Utilities.unescapeHTML(s); }); }; this.unescape = function() { return this.addFilter(function(s) { return unescape(s); }); }; this._applyFilters = function(a, doc1) { for (i in this._filters) { a = flatten(a); /* remove undefined or null array entries */ a = a.filter(function(x) { return ((x !== undefined) && (x !== null)); }); for (var j = 0 ; j < a.length ; j++) { try { if ((a[j] === undefined) || (a[j] === null)) { continue; } else { a[j] = this._filters[i](a[j], doc1); } } catch (x) { a[j] = undefined; Zotero.debug("Caught exception " + x + "on filter: " + this._filters[i]); } } /* remove undefined or null array entries */ /* need this twice because they could have become undefined or null along the way */ a = a.filter(function(x) { return ((x !== undefined) && (x !== null)); }); } return flatten(a); }; }; FW.PageText = function () { return new FW._PageText(); }; FW._PageText = function() { this._filters = new Array(); this.evaluate = function (doc) { var a = [doc.documentElement.innerHTML]; a = this._applyFilters(a, doc); if (a.length == 0) { return false; } else { return a; } }; }; FW._PageText.prototype = new FW._StringMagic(); FW.Url = function () { return new FW._Url(); }; FW._Url = function () { this._filters = new Array(); this.evaluate = function (doc, url) { var a = [url]; a = this._applyFilters(a, doc); if (a.length == 0) { return false; } else { return a; } }; }; FW._Url.prototype = new FW._StringMagic(); FW.Xpath = function (xpathExpr) { return new FW._Xpath(xpathExpr); }; FW._Xpath = function (_xpath) { this._xpath = _xpath; this._filters = new Array(); this.text = function() { var filter = function(n) { if (typeof n === 'object' && n.textContent) { return n.textContent; } else { return n; } }; this.addFilter(filter); return this; }; this.sub = function(xpath) { var filter = function(n, doc) { var result = doc.evaluate(xpath, n, null, XPathResult.ANY_TYPE, null); if (result) { return result.iterateNext(); } else { return undefined; } }; this.addFilter(filter); return this; }; this.evaluate = function (doc) { var res = doc.evaluate(this._xpath, doc, null, XPathResult.ANY_TYPE, null); var resultType = res.resultType; var a = new Array(); if (resultType == XPathResult.STRING_TYPE) { a.push(res.stringValue); } else if (resultType == XPathResult.BOOLEAN_TYPE) { a.push(res.booleanValue); } else if (resultType == XPathResult.NUMBER_TYPE) { a.push(res.numberValue); } else if (resultType == XPathResult.ORDERED_NODE_ITERATOR_TYPE || resultType == XPathResult.UNORDERED_NODE_ITERATOR_TYPE) { var x; while ((x = res.iterateNext())) { a.push(x); } } a = this._applyFilters(a, doc); if (a.length == 0) { return false; } else { return a; } }; }; FW._Xpath.prototype = new FW._StringMagic(); FW.detectWeb = function (doc, url) { for (var i in FW._scrapers) { var scraper = FW._scrapers[i]; var itemType = scraper.evaluateThing(scraper['itemType'], doc, url); var v = scraper.evaluateThing(scraper['detect'], doc, url); if (v.length > 0 && v[0]) { return itemType; } } return undefined; }; FW.getScraper = function (doc, url) { var itemType = FW.detectWeb(doc, url); return FW._scrapers.filter(function(s) { return (s.evaluateThing(s['itemType'], doc, url) == itemType) && (s.evaluateThing(s['detect'], doc, url)); })[0]; }; FW.doWeb = function (doc, url) { var scraper = FW.getScraper(doc, url); scraper.makeItems(doc, url, [], function(item, scraper, doc, url) { scraper.callHook('scraperDone', item, doc, url); if (!item['title']) { item['title'] = ""; } item.complete(); }, function() { Zotero.done(); }); Zotero.wait(); };
simonster/zotero-transfw
framework.js
JavaScript
agpl-3.0
19,124
import React from 'react'; import PropTypes from 'prop-types'; import Statistic from 'interface/statistics/Statistic'; import STATISTIC_CATEGORY from './STATISTIC_CATEGORY'; export { default as STATISTIC_ORDER } from './STATISTIC_ORDER'; /** * @deprecated Use `interface/statistics/*` instead (add a component to display dual spell values and use that instead). */ const DualStatisticBox = ({ icon, values, footer, alignIcon, ...others }) => ( <Statistic {...others}> <div className="pad"> <small>{footer}</small> <div className="flex" style={{ marginTop: 15 }}> <div className="flex-sub" style={{ display: 'flex', alignItems: alignIcon, minWidth: 30 }} > {icon} </div> <div className="flex-main flex horizontal"> {values.map((val, i) => ( <div key={`${i}${val}`} className="panel-cell value"> {val} </div> ))} </div> </div> </div> </Statistic> ); DualStatisticBox.propTypes = { icon: PropTypes.node.isRequired, values: PropTypes.node.isRequired, alignIcon: PropTypes.string, footer: PropTypes.node, }; DualStatisticBox.defaultProps = { alignIcon: 'center', category: STATISTIC_CATEGORY.GENERAL, }; export default DualStatisticBox;
ronaldpereira/WoWAnalyzer
src/interface/others/DualStatisticBox.js
JavaScript
agpl-3.0
1,322
/* This file is a part of libertysoil.org website Copyright (C) 2015 Loki Education (Social Enterprise) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* eslint-env node, mocha */ import { readFile } from 'fs'; import bb from 'bluebird'; import faker from 'faker'; import { sortBy } from 'lodash'; import expect from '../../../test-helpers/expect'; import { login } from '../../../test-helpers/api'; import { createUser } from '../../../test-helpers/factories/user'; import { createPost, createPosts } from '../../../test-helpers/factories/post'; import { createHashtag, createHashtags } from '../../../test-helpers/factories/hashtag'; import { createSchool, createSchools } from '../../../test-helpers/factories/school'; import { createGeotag, createGeotags } from '../../../test-helpers/factories/geotag'; import { bookshelf, knex } from '../../../test-helpers/db'; const readFileAsync = bb.promisify(readFile); describe('other controllers', () => { let user, session; before(async () => { user = await createUser(); session = await login(user.get('username'), user.get('password')); }); after(async () => { await user.destroy(); }); describe('GET /api/v1/locale/:lang_code', () => { let locale; before(async () => { const text = await readFileAsync('res/locale/en.json'); locale = JSON.parse(text); }); it('responds with localization in JSON format', async () => { await expect( { url: `/api/v1/locale/en`, method: `GET`, }, 'body to satisfy', locale ); }); }); describe('GET /api/v1/quotes', () => { const Quote = bookshelf.model('Quote'); const quotes = []; before(async () => { for (let i = 0; i < 2; ++i) { quotes.push(await new Quote({ first_name: faker.name.firstName(), last_name: faker.name.firstName(), text: faker.lorem.paragraph(), }).save(null, { require: true })); } }); after(async () => { await knex('quotes').whereIn('id', quotes.map(quote => quote.id)).del(); }); it('responds with quotes', async () => { await expect( { url: `/api/v1/quotes`, method: `GET`, }, 'body to satisfy', sortBy(quotes.map(quote => quote.attributes), 'last_name') ); }); }); describe('GET /api/v1/user/tags', () => { let post, hashtag, school, geotag; before(async () => { post = await createPost({ user_id: user.id }); hashtag = await createHashtag(); school = await createSchool(); geotag = await createGeotag(); await post.hashtags().attach(hashtag.id); await post.schools().attach(school.id); await post.geotags().attach(geotag.id); }); after(async () => { await Promise.all([ post.destroy(), hashtag.destroy(), school.destroy(), geotag.destroy(), ]); }); it("responds with current user's tags", async () => { await expect( { session, url: `/api/v1/user/tags`, method: 'GET', }, 'body to satisfy', { hashtags: [{ id: hashtag.id }], schools: [{ id: school.id }], geotags: [{ id: geotag.id }], } ); }); }); describe('GET /api/v1/recent-tags', () => { let posts, hashtagIds, schoolIds, geotagIds; before(async () => { posts = await createPosts( Array.apply(null, Array(5)) .map((_, i) => ({ created_at: new Date(Date.UTC(2017, 11, i)) })) ); hashtagIds = (await createHashtags(6)).map(t => t.id); schoolIds = (await createSchools(6)).map(t => t.id); geotagIds = (await createGeotags(6)).map(t => t.id); for (const [i, post] of posts.entries()) { await post.hashtags().attach(hashtagIds[i]); await post.schools().attach(schoolIds[i]); await post.geotags().attach(geotagIds[i]); } }); after(async () => { await knex('hashtags').whereIn('id', hashtagIds).del(); await knex('schools').whereIn('id', schoolIds).del(); await knex('geotags').whereIn('id', geotagIds).del(); await knex('posts').whereIn('id', posts.map(post => post.id)).del(); }); it('responds with 5 recently used tags of all types', async () => { await expect( { method: 'GET', url: `/api/v1/recent-tags` }, 'body to satisfy', { hashtags: { entries: hashtagIds.slice(0, 5).reverse().map(id => ({ id })), post_count: 0, // only counts posts created withing last 24 hours }, schools: { entries: schoolIds.slice(0, 5).reverse().map(id => ({ id })), post_count: 0, }, geotags: { entries: geotagIds.slice(0, 5).reverse().map(id => ({ id })), post_count: 0, } } ); }); }); });
Lokiedu/libertysoil-site
test/integration/api/misc.js
JavaScript
agpl-3.0
5,614
/* Copyright 2008 Clipperz Srl This file is part of Clipperz Community Edition. Clipperz Community Edition is a web-based password manager and a digital vault for confidential data. For further information about its features and functionalities please refer to http://www.clipperz.com * Clipperz Community Edition is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * Clipperz Community Edition is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License along with Clipperz Community Edition. If not, see <http://www.gnu.org/licenses/>. */ if (typeof(Clipperz) == 'undefined') { Clipperz = {}; } if (typeof(Clipperz.PM) == 'undefined') { Clipperz.PM = {}; } if (typeof(Clipperz.PM.DataModel) == 'undefined') { Clipperz.PM.DataModel = {}; } //############################################################################# Clipperz.PM.DataModel.RecordVersion = function(aRecord, args) { args = args || {}; this._record = aRecord; this._reference = args.reference || Clipperz.PM.Crypto.randomKey(); this._version = args.version || Clipperz.PM.Crypto.encryptingFunctions.currentVersion; this._key = args.key || Clipperz.PM.Crypto.randomKey();; this._previousVersion = args.previousVersion || null; this._previousVersionKey = args.previousVersionKey || null; this.setIsBrandNew(args.reference == null); if (this.isBrandNew()) { this._fields = {}; this.setShouldLoadData(false); this.setShouldDecryptData(false); this.setShouldProcessData(false); } else { if (typeof(args.fields) != 'undefined') { this.processFieldData(args.fields); this.setShouldLoadData(false); this.setShouldDecryptData(false); this.setShouldProcessData(false); } else { if (typeof(args.data) != 'undefined') { this.setShouldLoadData(false); } else { this.setShouldLoadData(true); } this.setShouldDecryptData(true); this.setShouldProcessData(true); } } this._serverData = args.data; this._decryptedData = null; return this; } Clipperz.PM.DataModel.RecordVersion.prototype = MochiKit.Base.update(null, { 'toString': function() { return "RecordVersion"; }, //------------------------------------------------------------------------- 'record': function() { return this._record; }, //------------------------------------------------------------------------- 'reference': function() { return this._reference; }, 'setReference': function(aValue) { this._reference = aValue; }, //------------------------------------------------------------------------- 'key': function() { //MochiKit.Logging.logDebug(">>> RecordVersion.key"); //MochiKit.Logging.logDebug("--- RecordVersion.key - " + this._key); return this._key; }, 'setKey': function(aValue) { this._key = aValue; }, //------------------------------------------------------------------------- 'serverData': function() { return this._serverData; }, 'setServerData': function(aValue) { this._serverData = aValue; this.setShouldLoadData(false); return aValue; }, //------------------------------------------------------------------------- 'decryptedData': function() { //MochiKit.Logging.logDebug(">>> RecordVersion.decryptedData: " + (this._decryptedData ? MochiKit.Base.serializeJSON(aValue) : "null")); return this._decryptedData; }, 'setDecryptedData': function(aValue) { //MochiKit.Logging.logDebug(">>> RecordVersion.setDecryptedData: " + MochiKit.Base.serializeJSON(aValue)); this._decryptedData = aValue; this.setShouldDecryptData(false); return aValue; }, //------------------------------------------------------------------------- 'version': function() { return this._version; }, //------------------------------------------------------------------------- 'isBrandNew': function() { return this._isBrandNew; }, 'setIsBrandNew': function(aValue) { this._isBrandNew = aValue; }, //------------------------------------------------------------------------- 'fields': function() { return this._fields; }, 'addField': function(aField) { this.fields()[aField.key()] = aField; }, 'addNewField': function() { var newRecordField; newRecordField = new Clipperz.PM.DataModel.RecordField({recordVersion:this}); this.addField(newRecordField); return newRecordField; }, 'fieldWithName': function(aValue) { var result; var fieldValues; var i,c; result = null; fieldValues = MochiKit.Base.values(this.fields()); c = fieldValues.length; for (i=0; (i<c) && (result == null); i++) { var currentField; currentField = fieldValues[i]; if (currentField.label() == aValue) { result = currentField; } } return result; }, //------------------------------------------------------------------------- 'shouldLoadData': function() { return this._shouldLoadData; }, 'setShouldLoadData': function(aValue) { this._shouldLoadData = aValue; }, //------------------------------------------------------------------------- 'shouldDecryptData': function() { return this._shouldDecryptData; }, 'setShouldDecryptData': function(aValue) { this._shouldDecryptData = aValue; }, //------------------------------------------------------------------------- 'shouldProcessData': function() { return this._shouldProcessData; }, 'setShouldProcessData': function(aValue) { this._shouldProcessData = aValue; }, //------------------------------------------------------------------------- 'deferredData': function() { var deferredResult; //MochiKit.Logging.logDebug(">>> RecordVersion.deferredData - this: " + this); deferredResult = new MochiKit.Async.Deferred(); deferredResult.addCallback(MochiKit.Base.method(this, 'loadData')); deferredResult.addCallback(MochiKit.Base.method(this, 'decryptData')); deferredResult.addCallback(MochiKit.Base.method(this, 'processData')); deferredResult.callback(); //MochiKit.Logging.logDebug("<<< RecordVersion.deferredData"); return deferredResult; }, //------------------------------------------------------------------------- 'loadData': function() { var result; //MochiKit.Logging.logDebug(">>> RecordVersion.loadData - this: " + this); if (this.shouldLoadData()) { var deferredResult; alert("ERROR: this should have not happened yet!"); //MochiKit.Logging.logDebug("--- RecordVersion.loadData - 1"); deferredResult = new MochiKit.Async.Deferred(); //MochiKit.Logging.logDebug("--- RecordVersion.loadData - 2"); deferredResult.addCallback(MochiKit.Base.method(this, 'notify'), 'loadingRecordVersionData'); //MochiKit.Logging.logDebug("--- RecordVersion.loadData - 3"); deferredResult.addCallback(MochiKit.Base.method(this.user().connection(), 'message'), 'getRecordVersionDetail', {reference: this.reference()}); //MochiKit.Logging.logDebug("--- RecordVersion.loadData - 4"); deferredResult.addCallback(MochiKit.Base.method(this, 'setServerData')); //MochiKit.Logging.logDebug("--- RecordVersion.loadData - 5"); deferredResult.callback(); //MochiKit.Logging.logDebug("--- RecordVersion.loadData - 6"); result = deferredResult; //MochiKit.Logging.logDebug("--- RecordVersion.loadData - 7"); } else { //MochiKit.Logging.logDebug("--- RecordVersion.loadData - 8"); result = MochiKit.Async.succeed(this.serverData()); //MochiKit.Logging.logDebug("--- RecordVersion.loadData - 9"); } //MochiKit.Logging.logDebug("<<< RecordVersion.loadData"); return result; }, //------------------------------------------------------------------------- 'decryptData': function(anEncryptedData) { var result; //MochiKit.Logging.logDebug(">>> RecordVersion.decryptData - this: " + this + " (" + anEncryptedData + ")"); if (this.shouldDecryptData()) { var deferredResult; //MochiKit.Logging.logDebug("--- RecordVersion.decryptData - 1"); deferredResult = new MochiKit.Async.Deferred(); //MochiKit.Logging.logDebug("--- RecordVersion.decryptData - 2"); //deferredResult.addBoth(function(res) {MochiKit.Logging.logDebug("RecordVersion.decryptData 1: " + res); return res;}); deferredResult.addCallback(MochiKit.Base.method(this, 'notify'), 'decryptingRecordVersionData'); //MochiKit.Logging.logDebug("--- RecordVersion.decryptData - 3"); //deferredResult.addBoth(function(res) {MochiKit.Logging.logDebug("RecordVersion.decryptData 2: " + res); return res;}); deferredResult.addCallback(Clipperz.PM.Crypto.deferredDecrypt, this.key(), anEncryptedData, this.version()); //MochiKit.Logging.logDebug("--- RecordVersion.decryptData - 4"); //deferredResult.addBoth(function(res) {MochiKit.Logging.logDebug("RecordVersion.decryptData 3: " + res); return res;}); //MochiKit.Logging.logDebug("--- RecordVersion.decryptData - 5"); //deferredResult.addBoth(function(res) {MochiKit.Logging.logDebug("RecordVersion.decryptData 4: " + res); return res;}); deferredResult.addCallback(MochiKit.Base.method(this, 'setDecryptedData')); //MochiKit.Logging.logDebug("--- RecordVersion.decryptData - 6"); //deferredResult.addBoth(function(res) {MochiKit.Logging.logDebug("RecordVersion.decryptData 5: " + res); return res;}); deferredResult.callback(); //MochiKit.Logging.logDebug("--- RecordVersion.decryptData - 7"); result = deferredResult; //MochiKit.Logging.logDebug("--- RecordVersion.decryptData - 8"); } else { //MochiKit.Logging.logDebug("--- RecordVersion.decryptData - 9"); result = MochiKit.Async.succeed(this.decryptedData()); //MochiKit.Logging.logDebug("--- RecordVersion.decryptData - 10"); } //MochiKit.Logging.logDebug("<<< RecordVersion.decryptData"); return result; }, //------------------------------------------------------------------------- 'processFieldData': function(someValues) { this._fields = {}; if (someValues.constructor == Array) { var i, c; c = someValues.length; for (i=0; i<c; i++) { var newRecordField; var currentFieldValues; currentFieldValues = someValues[i]; currentFieldValues['recordVersion'] = this; newRecordField = new Clipperz.PM.DataModel.RecordField(currentFieldValues); this._fields[newRecordField.key()] = newRecordField; } } else { var fieldKey; for (fieldKey in someValues) { var newRecordField; var currentFieldValues; currentFieldValues = someValues[fieldKey]; currentFieldValues['key'] = fieldKey; currentFieldValues['recordVersion'] = this; newRecordField = new Clipperz.PM.DataModel.RecordField(currentFieldValues); this._fields[fieldKey] = newRecordField; } } }, 'processData': function(someValues) { if (this.shouldProcessData()) { this.processFieldData(someValues.fields); this.setShouldProcessData(false); } this.notify('recordVersionDataReady'); return this; }, //------------------------------------------------------------------------- 'notify': function(aValue) { Clipperz.NotificationCenter.notify(this, aValue); }, //------------------------------------------------------------------------- 'removeField': function(aField) { delete this.fields()[aField.key()]; }, //------------------------------------------------------------------------- 'previousVersion': function() { return this._previousVersion; }, 'setPreviousVersion': function(aValue) { this._previousVersion = aValue; }, //------------------------------------------------------------------------- 'previousVersionKey': function() { return this._previousVersionKey; }, 'setPreviousVersionKey': function(aValue) { this._previousVersionKey = aValue; }, //------------------------------------------------------------------------- 'serializedData': function() { var result; var fieldKey; //MochiKit.Logging.logDebug(">>> RecordVersion.serializedData"); result = { fields: {} }; //MochiKit.Logging.logDebug("--- RecordVersion.serializedData - 1"); for (fieldKey in this.fields()) { //MochiKit.Logging.logDebug("--- RecordVersion.serializedData - 2"); result.fields[fieldKey] = this.fields()[fieldKey].serializeData(); //MochiKit.Logging.logDebug("--- RecordVersion.serializedData - 3"); } //MochiKit.Logging.logDebug("--- RecordVersion.serializedData - 4"); //MochiKit.Logging.logDebug("<<< RecordVersion.serializedData: " + MochiKit.Base.serializeJSON(result)); return result; }, 'currentDataSnapshot': function() { var result; result = this.serializedData(); result['version'] = this.version(); result['reference'] = this.reference(); result['previousVersionKey'] = this.previousVersionKey(); return result; }, //------------------------------------------------------------------------- 'encryptedData': function() { var deferredResult; var result; //MochiKit.Logging.logDebug(">>> RecordVersion.encryptedData - " + this); result = {}; deferredResult = new MochiKit.Async.Deferred(); //MochiKit.Logging.logDebug("--- RecordVersion.encryptedData - 1"); //deferredResult.addBoth(function(res) {MochiKit.Logging.logDebug("RecordVersion.encryptedData - 1: " + res); return res;}); deferredResult.addCallback(function(aResult, aRecordVersion) { aResult['reference'] = aRecordVersion.reference(); aResult['recordReference'] = aRecordVersion.record().reference(); // TODO - this seems to be completely useless return aResult; }, result, this); //MochiKit.Logging.logDebug("--- RecordVersion.encryptedData - 2"); //deferredResult.addBoth(function(res) {MochiKit.Logging.logDebug("RecordVersion.encryptedData - 2: " + res); return res;}); deferredResult.addCallback(Clipperz.PM.Crypto.deferredEncryptWithCurrentVersion, this.key(), this.serializedData()); //deferredResult.addBoth(function(res) {MochiKit.Logging.logDebug("RecordVersion.encryptedData - 3: " + res); return res;}); deferredResult.addCallback(function(aResult, res) { aResult['data'] = res; return aResult; }, result); //MochiKit.Logging.logDebug("--- RecordVersion.encryptedData - 3"); //deferredResult.addBoth(function(res) {MochiKit.Logging.logDebug("RecordVersion.encryptedData - 4: " + res); return res;}); deferredResult.addCallback(function(aResult) { aResult['version'] = Clipperz.PM.Crypto.encryptingFunctions.currentVersion; return aResult; }, result); //MochiKit.Logging.logDebug("--- RecordVersion.encryptedData - 4"); if (this.previousVersion() != null) { //MochiKit.Logging.logDebug("--- RecordVersion.encryptedData - 5"); //deferredResult.addBoth(function(res) {MochiKit.Logging.logDebug("RecordVersion.encryptedData - 5: " + res); return res;}); deferredResult.addCallback(function(aResult, aRecordVersion) { aResult['previousVersion'] = aRecordVersion.previousVersion(); return aResult; }, result, this); //MochiKit.Logging.logDebug("--- RecordVersion.encryptedData - 6"); //deferredResult.addBoth(function(res) {MochiKit.Logging.logDebug("RecordVersion.encryptedData - 6: " + res); return res;}); deferredResult.addCallback(Clipperz.PM.Crypto.deferredEncryptWithCurrentVersion, this.key(), this.previousVersionKey()); //deferredResult.addBoth(function(res) {MochiKit.Logging.logDebug("RecordVersion.encryptedData - 7: " + res); return res;}); deferredResult.addCallback(function(aResult, res) { aResult['previousVersionKey'] = res; return aResult; }, result); //deferredResult.addBoth(function(res) {MochiKit.Logging.logDebug("RecordVersion.encryptedData - 8: " + res); return res;}); //MochiKit.Logging.logDebug("--- RecordVersion.encryptedData - 7"); } else { //MochiKit.Logging.logDebug("--- RecordVersion.encryptedData - 8"); //deferredResult.addBoth(function(res) {MochiKit.Logging.logDebug("RecordVersion.encryptedData - 9: " + res); return res;}); deferredResult.addCallback(function(aResult) { aResult['previousVersionKey'] = Clipperz.PM.Crypto.nullValue; return aResult; }, result); //MochiKit.Logging.logDebug("--- RecordVersion.encryptedData - 9"); //deferredResult.addBoth(function(res) {MochiKit.Logging.logDebug("RecordVersion.encryptedData - 10: " + res); return res;}); }; //deferredResult.addBoth(function(res) {MochiKit.Logging.logDebug("RecordVersion.encryptedData - 11: " + res); return res;}); deferredResult.callback(); //MochiKit.Logging.logDebug("<<< RecordVersion.encryptedData"); return deferredResult; }, //------------------------------------------------------------------------- 'createNewVersion': function() { this.setPreviousVersion(this.reference()); this.setPreviousVersionKey(this.key()); this.setReference(Clipperz.PM.Crypto.randomKey()); this.setKey(Clipperz.PM.Crypto.randomKey()); }, //------------------------------------------------------------------------- /* 'shouldLoadData': function() { return ((this.data() == null) && (this.isBrandNew() === false)); }, 'loadData': function() { //MochiKit.Logging.logDebug(">>> Record.loadData (" + this.label() + ")"); // if (this.shouldLoadData()) { // this.user().connection().message( 'getRecordDetail', // {recordReference: this.reference()}, // { callback:MochiKit.Base.bind(this.loadDataCallback, this), // errorHandler:Clipperz.PM.defaultErrorHandler }); // } else { // this.notify('loadDataDone'); // } }, 'loadDataCallback': function() { MochiKit.Logging.logDebug("RecordVersion.loadDataCallback: " + MochiKit.Base.serializeJSON(arguments)); }, */ //------------------------------------------------------------------------- __syntaxFix__: "syntax fix" });
fmdhs/cz
js/src/Clipperz/PM/DataModel/RecordVersion.js
JavaScript
agpl-3.0
17,877
'use strict'; angular.module('myApp.eating', ['ngRoute']) .config(['$routeProvider', function ($routeProvider) { $routeProvider.when('/eating', { templateUrl: 'views/eating/eating.html', controller: 'EatingCtrl' }); }]) .controller('EatingCtrl', function ($scope, $http) { $scope.storageuser = JSON.parse(localStorage.getItem("fs_web_userdata")); $scope.diets = {}; $http.get(urlapi + 'diets') .then(function (data) { console.log('data success'); console.log(data); // for browser console $scope.diets = data.data; // for UI localStorage.setItem('fs_web_diets', JSON.stringify($scope.diets)); }, function (data, status) { console.log('data error'); console.log(status); console.log(data); }); $scope.user={}; $http.get(urlapi + 'users/' + $scope.storageuser._id) .then(function(data) { console.log('data success'); console.log(data); // for browser console $scope.user = data.data; // for UI if ($scope.user._id == $scope.storageuser._id) { localStorage.setItem("fs_web_userdata", JSON.stringify($scope.user)); $scope.storageuser = JSON.parse(localStorage.getItem("fs_web_userdata")); } }, function(data, status) { console.log('data error'); console.log(status); console.log(data); }); });
grup3ea/webAngular1
app/views/eating/eating.js
JavaScript
agpl-3.0
1,661
import { FETCH_TODOS_REQUEST, FETCH_TODOS_SUCCESS, FETCH_TODOS_FAILURE, ADD_TODO_REQUEST, ADD_TODO_SUCCESS, ADD_TODO_FAILURE, COMPLETE_TODO, SET_VISIBILITY_FILTER, VisibilityFilters } from '../actions/todoActions'; const { SHOW_ALL } = VisibilityFilters; import createReducer from '../utils/create-reducer'; const initialState = { visibilityFilter: 'SHOW_ALL', todos: [], isLoading: false } const actionHandlers = { ['SET_VISIBILITY_FILTER']: (state, action) => ({ visibilityFilter: action.filter }), ['FETCH_TODOS_SUCCESS']: (state, action) => ( { todos: [].concat(action.todos.data) } ), ['ADD_TODO_REQUEST']: (state, action) => (state), ['ADD_TODO_SUCCESS']: (state, action) => ( [...state, { text: action.text, completed: false }] ), ['ADD_TODO_FAILURE']: (state, action) => (state), ['COMPLETE_TODO']: (state, action) => ( [...state.slice(0, action.index), Object.assign({}, state[action.index], { completed: true }), ...state.slice(action.index + 1) ]) } export default createReducer(initialState, actionHandlers);
HeapCity/heap_city
client/js/reducers/todoReducers.js
JavaScript
agpl-3.0
1,097
function langToggle() { document.querySelector("body").classList.add("is-lang-active"); function toggleLangClass(e){ e.preventDefault(); document.querySelector(".lang-wrapper").classList.toggle("is-lang-open"); } function langToggleClickOut(e) { var targetElements, targetTriggers, i; if (!e.target.closest(".lang-wrapper")) { targetElements = document.querySelector(".lang-wrapper").classList.remove("is-lang-open"); } } document.querySelector(".lang-trigger").addEventListener("click", toggleLangClass); document.querySelector("body").addEventListener("click", langToggleClickOut); } langToggle();
decidim/decidim.org
source/javascripts/lang-toggle.js
JavaScript
agpl-3.0
661
/* #-- # Copyright (C) 2007-2009 Johan Sørensen <johan@johansorensen.com> # Copyright (C) 2009 Marius Mathiesen <marius.mathiesen@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. #-- */ $(document).ready(function() { // Project Sluggorizin' $("form #project_title").keyup(function(event) { var slug = $("form #project_slug"); if (slug.text() != "") return; var lintName = function(val) { var linted = val.replace(/\W+/g, ' ').replace(/\ +/g, '-'); linted = linted.toLowerCase().replace(/\-+$/g, ''); return linted; } slug.val( lintName(this.value) ); }); // Line highlighting/selection $("#codeblob").highlightSelectedLines(); // no-op links $("a.link_noop").click(function(event) { event.preventDefault(); }); // Comment previewing $("input#comment_preview_button").click(function(event){ var formElement = $(this).parents("form"); var url = formElement.attr("action"); url += "/preview" $.post(url, formElement.serialize(), function(data, responseText){ if (responseText === "success") { $("#comment_preview").html(data); $("#comment_preview").fadeIn(); } }); event.preventDefault(); }); // Project previewing $("input#project_preview_button").click(function(event){ var formElement = $(this).parents("form"); var url = $(this).attr("gts:url"); $.post(url, formElement.serialize(), function(data, response) { if (response === "success") $("#project-preview").html(data).fadeIn(); }); event.preventDefault(); }); // Markdown help toggling $(".markdown-help-toggler").click(function(event){ $(".markdown_help").toggle(); event.preventDefault(); }); $("a#advanced-search-toggler").click(function(event) { $("#search_help").slideToggle(); event.preventDefault(); }); // Merge request status color picking $("#merge_request_statuses input.color_pickable").SevenColorPicker(); // Toggle details of commit events $("a.commit_event_toggler").click(function(event){ var callbackUrl = $(this).attr("gts:url"); var eventId = $(this).attr("gts:id"); $("#commits_in_event_" + eventId).toggle(); if ($("#commits_in_event_" + eventId).is(":visible")) { $("#commits_in_event_" + eventId).load(callbackUrl); } event.preventDefault(); }); // frontpage for non-loggedin users // Unobtrusively hooking the regular/OpenID login box stuff, so that it works // in a semi-sensible way with javascript disabled. $("#big_header_login_box_to_openid, #big_header_login_box_to_regular").click(function(e){ $("#big_header_login_box_openid").toggle("fast"); $("#big_header_login_box_regular").toggle("fast"); e.preventDefault(); }); // replace the search form input["submit"] with something fancier $("#main_menu_search_form").each(function(){ var headerSearchForm = this; var labelText = "Search..."; var searchInput = $(this).find("input[type=text]"); searchInput.val(labelText); searchInput.click(function(event){ if (searchInput.val() == labelText) { searchInput.val(""); searchInput.removeClass("unfocused"); } }); searchInput.blur(function(event){ if (searchInput.val() == "") { searchInput.val(labelText); searchInput.addClass("unfocused"); } }); // hide the 'native' submit button and replace it with our // own awesome submit button var nativeSubmitButton = $(this).find("input[type=submit]"); nativeSubmitButton.hide(); var awesomeSubmitButton = $(document.createElement("a")); awesomeSubmitButton.attr({ 'id':'main_menu_search_form_graphic_submit', 'href': '#' }); awesomeSubmitButton.click(function(event){ headerSearchForm.submit(); event.preventDefault(); }); nativeSubmitButton.after(awesomeSubmitButton); }); // Commment editing $(".comment .edit_link a").live("click", function(){ var commentContainer = $(this).parents(".comment"); var formUrl = $(this).attr("gts:url"); var spinner = $(this).parent().next(".link-spinner").show(); var commentId = commentContainer.attr("gts:comment-id"); var commentLink = commentContainer.siblings("[name=comment_" + commentId + "]"); jQuery.ajax({url:formUrl, success:function(data) { spinner.hide(); commentContainer.append(data); commentContainer.find("form").submit(function(){ var url = $(this).attr("action"); var data = $(this).serialize(); jQuery.post(url, data, function(payload) { commentLink.remove(); commentContainer.replaceWith(payload); }); return false; }) }, error: function(){ spinner.hide(); commentContainer.append( "<p>We're sorry, but you're not allowed to edit the comment. " + "Only the creator of a comment may edit it, and then only for " + "a short period of time after it's been created</p>" ); }}); }); $(".comment .comment_form .cancel").live("click", function(){ var theForm = $(this).parents(".comment_form"); theForm.remove(); }); // Relative times based on clients browser time jQuery.extend(jQuery.timeago.settings.strings, { seconds: "a minute", minute: "a minute", minutes: "%d minutes", hour: "an hour", hours: "%d hours", day: "a day", days: "%d days", month: "a month", months: "%d months", year: "a year", years: "%d years" }); jQuery('abbr.timeago').timeago(); // Rails generates some quite obtrusive markup when // :method => whatever is used in link_to etc. jQuery("a[data-request-method]").replaceRailsGeneratedForm(); // watchable/favorite list filtering $("#watchable-list").each(function() { $this = $(this); $this.find(".filters a.all").addClass("current") $this.find(".filters a").css({'outline':'none'}); var makeCurrent = function(newCurrent) { $this.find(".filters a").removeClass("current"); $(newCurrent).addClass("current"); }; var swapAndMakeCurrent = function(klass, current) { $this.find(".favorite." + klass).show(); $this.find(".favorite:not(." + klass + ")").hide(); makeCurrent(current); } $this.find(".filters a.all").click(function() { $this.find(".favorite").show(); makeCurrent(this); return false; }); $this.find(".filters a.repositories").click(function() { swapAndMakeCurrent("repository", this); return false; }); $this.find(".filters a.merge-requests").click(function() { swapAndMakeCurrent("merge_request"); return false; }); $this.find(".filters a.mine").click(function() { swapAndMakeCurrent("mine"); return false; }); $this.find(".filters a.foreign").click(function() { swapAndMakeCurrent("foreign"); return false; }); }); // Favorite toggling and deletion on the /favorites page $("#favorite-listing tr:odd").addClass("odd"); $("#favorite-listing td.notification .favorite.update a").click(function() { $this = $(this); if ("off" == $this.text()) { payload = "_method=put&favorite[notify_by_email]=1"; } else { payload = "_method=put&favorite[notify_by_email]=0"; } $.post($this.attr("href"), payload, function(data, respTxt){ if ("success" === respTxt) { if ("off" === $this.text()) { $this.text("on").removeClass("disabled").addClass("enabled"); } else { $this.text("off").removeClass("enabled").addClass("disabled") } } }); return false; }); $("#favorite-listing td.unwatch .favorite a.watch-link").click(function() { $this = $(this); payload = "_method=delete"; $.post($this.attr("href"), payload, function(data, respTxt){ if ("success" === respTxt) { $this.parents("tr").fadeOut("normal", function(){ $(this).remove(); $("#favorite-listing tr").removeClass("odd"); $("#favorite-listing tr:odd").addClass("odd"); }); } }); return false; }); }); if (!Gitorious) var Gitorious = {}; Gitorious.DownloadChecker = { checkURL: function(url, container) { var element = $("#" + container); //element.absolutize(); var sourceLink = element.prev(); // Position the box if (sourceLink) { element.css({ 'top': parseInt(element[0].style.top) - (element.height()+10) + "px", 'width': '175px', 'height': '70px', 'position': 'absolute' }); } element.html('<p class="spin"><img src="/images/spinner.gif" /></p>'); element.show(); // load the status element.load(url, function(responseText, textStatus, XMLHttpRequest){ if (textStatus == "success") { $(this).html(responseText); } }); return false; } }; // Gitorious.Wordwrapper = { // wrap: function(elements) { // elements.each(function(e) { // //e.addClassName("softwrapped"); // e.removeClassName("unwrapped"); // }); // }, // unwrap: function(elements) { // elements.each(function(e) { // //e.removeClassName("softwrapped"); // e.addClassName("unwrapped"); // }); // }, // toggle: function(elements) { // if (/unwrapped/.test(elements.first().className)) { // Gitorious.Wordwrapper.wrap(elements); // } else { // Gitorious.Wordwrapper.unwrap(elements); // } // } // } // A class used for selecting ranges of objects function CommitRangeSelector(commitListUrl, targetBranchesUrl, statusElement) { this.commitListUrl = commitListUrl this.targetBranchesUrl = targetBranchesUrl; this.statusElement = statusElement; this.endsAt = null; this.sourceBranchName = null; this.targetBranchName = null; this.REASONABLY_SANE_RANGE_SIZE = 50; this.endSelected = function(el) { this.endsAt = $(el); this.update(); }; this.onSourceBranchChange = function(event) { if (sourceBranch = $('#merge_request_source_branch')) { this.sourceBranchSelected(sourceBranch); } }; this.onTargetRepositoryChange = function(event) { $("#spinner").fadeIn(); $.post(this.targetBranchesUrl, $("#new_merge_request").serialize(), function(data, responseText) { if (responseText === "success") { $("#target_branch_selection").html(data); $("#spinner").fadeOut(); } }); this._updateCommitList(); }; this.onTargetBranchChange = function(event) { if (targetBranch = $('#merge_request_target_branch').val()) { this.targetBranchSelected(targetBranch); } }; this.targetBranchSelected = function(branchName) { if (branchName != this.targetBranchName) { this.targetBranchName = branchName; this._updateCommitList(); } }; this.sourceBranchSelected = function(branchName) { if (branchName != this.sourceBranchName) { this.sourceBranchName = branchName; this._updateCommitList(); } }; this.update = function() { if (this.endsAt) { $(".commit_row").each(function(){ $(this).removeClass("selected") }); var selectedTr = this.endsAt.parent().parent(); selectedTr.addClass('selected'); var selectedTrCount = 1; selectedTr.nextAll().each(function() { $(this).addClass('selected'); selectedTrCount++; }); if (selectedTrCount > this.REASONABLY_SANE_RANGE_SIZE) { $("#large_selection_warning").slideDown(); } else { $("#large_selection_warning").slideUp(); } // update the status field with the selected range var to = selectedTr.find(".sha-abbrev a").html(); var from = $(".commit_row:last .sha-abbrev a").html(); $("." + this.statusElement).each(function() { $(this).html(from + ".." + to); }); } }; this._updateCommitList = function() { $("#commit_table").replaceWith('<p class="hint">Loading commits&hellip; ' + '<img src="/images/spinner.gif"/></p>'); $.post(this.commitListUrl, $("#new_merge_request").serialize(), function(data, responseText) { if (responseText === "success") $("#commit_selection").html(data); }); } } function toggle_wiki_preview(target_url) { var wiki_preview = $('#page_preview'); var wiki_edit = $('#page_content'); var wiki_form = wiki_edit[0].form; var toggler = $('#wiki_preview_toggler'); if (toggler.val() == "Hide preview") { toggler.val("Show preview"); } else { toggler.val("Hide preview"); wiki_preview.html(""); $.post(target_url, $(wiki_form).serialize(), function(data, textStatus){ if (textStatus == "success") { wiki_preview.html(data); } }); } jQuery.each([wiki_preview, wiki_edit], function(){ $(this).toggle() }); } // function load_commit_status() // { // var merge_request_uri = document.location.pathname; // ['merged','unmerged'].each(function(s) // { // var i1 = new Image(); // i1.src = "/images/merge_requests/" + s + ".png"; // }); // $$('tr.commit_row').each(function(commit_row) // { // id = commit_row.getAttribute('data-merge-request-commit-id'); // new Ajax.Request(merge_request_uri + "/commit_status?commit_id=" + id, {method:'get', onSuccess: function(transport){ // commit_row.removeClassName("unknown-status"); // if (transport.responseText == 'false'){ // commit_row.addClassName("unmerged"); // } // else{ // commit_row.addClassName("merged"); // } // }}); // }); // }
Gitorious-backup/base_uri-fixes
public/javascripts/application.js
JavaScript
agpl-3.0
15,421
//Pointer function $(Obj){return document.getElementById(Obj)} //Ajax function loadDoc(file) { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("main").innerHTML=this.responseText; } }; xhttp.open("GET", file, true); xhttp.send(); } window.onpopstate = function(event){ loadDoc(location.hash.substr(1)+'.html') }; if(location.reload){ if(!location.hash)location.hash='#inicio' loadDoc(location.hash.substr(1)+'.html') }
webkoom/pwasystem
js.js
JavaScript
agpl-3.0
533
(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','https://www.google-analytics.com/analytics.js','ga'); ga('create', ga_id, 'auto'); if (location.hostname == 'localhost') { console.log('debug mode - Google analytics') ga('set', 'sendHitTask', null); } else { ga('send', 'pageview'); }
Maronato/SpottedBot
main/static/main/js/GA.js
JavaScript
agpl-3.0
525
// @flow export const maxCheck = (num: number, max: number) => { if (num >= max) return max return num } export const temp = 0
mimccio/komi-app
src/lib/helpers/numberHelpers.js
JavaScript
agpl-3.0
132
import test from 'ava'; import * as integer from '../../../../src/index.js'; test('translate', (t) => { t.throws(integer.translate.bind(null, 16, 16, '!00b0C0def'), { message: /invalid/, }); t.throws(integer.translate.bind(null, 37, 36, '!'), { message: /not implemented/, }); t.throws(integer.translate.bind(null, 36, 37, 'z'), { message: /not implemented/, }); t.is(integer.translate(2, 2, '0'), '0'); t.is(integer.translate(2, 2, '1'), '1'); t.is(integer.translate(2, 2, '10'), '10'); t.is(integer.translate(2, 2, '11'), '11'); t.is(integer.translate(2, 2, '1001010111'), '1001010111'); t.is(integer.translate(16, 16, '0'), '0'); t.is(integer.translate(16, 16, 'a'), 'a'); t.is(integer.translate(16, 16, 'A0'), 'a0'); t.is(integer.translate(16, 16, 'a1'), 'a1'); t.is(integer.translate(16, 16, 'a00b0C0def'), 'a00b0c0def'); t.is(integer.translate(2, 16, '11'), '3'); t.is(integer.translate(16, 2, '3'), '11'); t.is(integer.translate(2, 16, '10001'), '11'); t.is(integer.translate(16, 2, '11'), '10001'); t.is(integer.translate(2, 10, '11'), '3'); t.is(integer.translate(10, 2, '3'), '11'); t.is(integer.translate(10, 16, '256'), '100'); t.is(integer.translate(16, 10, '100'), '256'); t.is(integer.translate(10, 16, '255'), 'ff'); t.is(integer.translate(16, 10, 'ff'), '255'); t.is(integer.translate(16, 10, 'fedcba9876543210'), '18364758544493064720'); t.is( integer.translate(36, 10, '1234567890azertyuiopqsdfghjklmwxcvbn'), '3126485650002806599616785647451052281250564436264094355', ); }); test('convert bug', (t) => { const src = '2a9a63896d946d67f7a9d370d6c60d971a0659e5d96548e799e92b79f784e24f'; const parsed = integer.parse(16, 10000000, src); t.deepEqual(src, integer.stringify(10000000, 16, parsed, 0, parsed.length)); });
aureooms/js-integer-big-endian
test/src/core/convert/translate.js
JavaScript
agpl-3.0
1,793
/* Copyright Härnösands kommun(C) 2014 This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. All rights reserved. This program and the accompanying materials are made available under the terms of the GNU Affero General Public License which accompanies this distribution, and is available at http://www.gnu.org/licenses/agpl-3.0.html */ /** * A controller to handle tooldetails for measure line tool. */ Ext.define('AdmClient.controller.toolDetails.MeasureLine', { extend : 'AdmClient.controller.MapConfiguration', requires : [ 'AdmClient.view.mapconfiguration.tools.details.*', 'AdmClient.view.MapConfiguration'], refs : [{ ref : 'toolsGrid', selector : '#toolsGrid' }], toolId: 'MeasureLine', config: {id: 'MeasureLine', type: 'MeasureLine'}, init : function() { this.control({ '#toolsGrid checkcolumn' : { checkchange : this.toolSelected } }); }, toolSelected : function(chkBox, rowIndex, checked, eOpts) { var store = this.getToolsGrid().getSelectionModel().store; if (store.data.items[rowIndex].data.id === this.toolId) { this.getToolsGrid().getSelectionModel().store.checkTool(rowIndex, checked, this.config); } } });
Sundsvallskommun/OpenEMap-Admin-WebUserInterface
src/main/javascript/controller/toolDetails/MeasureLine.js
JavaScript
agpl-3.0
1,805
import Ember from 'ember'; import RegexValidator from 'ember-simple-validate/lib/validators/regex'; import Validator from 'ember-simple-validate/lib/validator'; import { module, test } from 'qunit'; var get = Ember.get; var set = Ember.set; var subject; module('Validators/Regex', { beforeEach: function() { subject = RegexValidator.create(); } }); test('it is an instance of a validator', function(assert) { assert.ok(subject instanceof Validator); }); test('it allows empty values (unless paired with required)', function(assert) { assert.ok(subject.call('')); assert.ok(subject.call(null)); assert.ok(subject.call(undefined)); }); test('it validates simple values', function(assert) { subject.set('options.pattern', /ab+a/); var result = subject.call('abbba'); assert.equal(result, true); result = subject.call('abbcba'); assert.equal(result, false); }); test('it formats error messages', function(assert) { var pattern = 'abc'; var value = 'foo'; subject.set('options.pattern', pattern); subject.call(value); assert.equal(subject.get('errors').length, 1); var errorMessage = subject.get('errors')[0]; var expected = new RegExp('"' + value + '".*/' + pattern + '/'); assert.ok(expected.test(errorMessage)); });
ChinookBook/ember-simple-validate
tests/unit/lib/validators/regex-test.js
JavaScript
agpl-3.0
1,269
function show_alert(e) { e.preventDefault(); if(confirm("Do you really want to replace '<%= $filename %>'?")) document.forms[0].submit(); else return false; } function show_msgdeletealert() { if(confirm("Do you really want to delete this message?")) document.forms[0].submit(); else document.forms[0].cancel(); return false; }
iwelch/sylspace
static/js/confirm.js
JavaScript
agpl-3.0
371
'use strict'; /** * This file process should arguments the terminal */ function process(){ var command = 'read'; console.log('Fake reading terminal arguments'); return command; } exports.process = process;
telefonicaid/PopBox
lib/cli.js
JavaScript
agpl-3.0
218
import React from 'react'; import Modal from 'react-modal'; export const ModalWrapper = ({ isOpen, handleClose, children }) => ( <Modal isOpen={isOpen} onRequestClose={handleClose} style={{ content: { bottom: 'none' } }} > {children} </Modal> ); export default ModalWrapper;
rabblerouser/core
frontend/src/admin/common/Modal.js
JavaScript
agpl-3.0
299
/********************************************************************** Freeciv-web - the web version of Freeciv. http://play.freeciv.org/ Copyright (C) 2009-2015 The Freeciv-web project This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ***********************************************************************/ var touch_start_x; var touch_start_y; var map_select_setting_enabled = true; var map_select_check = false; var map_select_check_started = 0; var map_select_active = false; var map_select_x; var map_select_y; var mouse_touch_started_on_unit = false; /**************************************************************************** Init 2D mapctrl ****************************************************************************/ function mapctrl_init_2d() { // Register keyboard and mouse listener using JQuery. $("#canvas").mouseup(mapview_mouse_click); $("#canvas").mousedown(mapview_mouse_down); $(window).mousemove(mouse_moved_cb); if (is_touch_device()) { $('#canvas').bind('touchstart', mapview_touch_start); $('#canvas').bind('touchend', mapview_touch_end); $('#canvas').bind('touchmove', mapview_touch_move); } } /**************************************************************************** Triggered when the mouse button is clicked UP on the mapview canvas. ****************************************************************************/ function mapview_mouse_click(e) { var rightclick = false; var middleclick = false; if (!e) e = window.event; if (e.which) { rightclick = (e.which == 3); middleclick = (e.which == 2); } else if (e.button) { rightclick = (e.button == 2); middleclick = (e.button == 1 || e.button == 4); } if (rightclick) { /* right click to recenter. */ if (!map_select_active || !map_select_setting_enabled) { context_menu_active = true; recenter_button_pressed(mouse_x, mouse_y); } else { context_menu_active = false; map_select_units(mouse_x, mouse_y); } map_select_active = false; map_select_check = false; } else if (!rightclick && !middleclick) { /* Left mouse button*/ action_button_pressed(mouse_x, mouse_y, SELECT_POPUP); } } /**************************************************************************** Triggered when the mouse button is clicked DOWN on the mapview canvas. ****************************************************************************/ function mapview_mouse_down(e) { var rightclick = false; var middleclick = false; if (!e) e = window.event; if (e.which) { rightclick = (e.which == 3); middleclick = (e.which == 2); } else if (e.button) { rightclick = (e.button == 2); middleclick = (e.button == 1 || e.button == 4); } if (!rightclick && !middleclick) { /* Left mouse button is down */ if (goto_active) return; setTimeout("check_mouse_drag_unit(" + mouse_x + "," + mouse_y + ");", 200); } else if (middleclick || e['altKey']) { popit(); return false; } else if (rightclick && !map_select_active && is_right_mouse_selection_supported()) { map_select_check = true; map_select_x = mouse_x; map_select_y = mouse_y; map_select_check_started = new Date().getTime(); /* The context menu blocks the right click mouse up event on some * browsers. */ context_menu_active = false; } } /**************************************************************************** This function is triggered when beginning a touch event on a touch device, eg. finger down on screen. ****************************************************************************/ function mapview_touch_start(e) { e.preventDefault(); touch_start_x = e.originalEvent.touches[0].pageX - $('#canvas').position().left; touch_start_y = e.originalEvent.touches[0].pageY - $('#canvas').position().top; var ptile = canvas_pos_to_tile(touch_start_x, touch_start_y); if (ptile == null) return; var sunit = find_visible_unit(ptile); if (sunit != null && client.conn.playing != null && sunit['owner'] == client.conn.playing.playerno) { mouse_touch_started_on_unit = true; } else { mouse_touch_started_on_unit = false; } } /**************************************************************************** This function is triggered when ending a touch event on a touch device, eg finger up from screen. ****************************************************************************/ function mapview_touch_end(e) { action_button_pressed(touch_start_x, touch_start_y, SELECT_POPUP); } /**************************************************************************** This function is triggered on a touch move event on a touch device. ****************************************************************************/ function mapview_touch_move(e) { mouse_x = e.originalEvent.touches[0].pageX - $('#canvas').position().left; mouse_y = e.originalEvent.touches[0].pageY - $('#canvas').position().top; var diff_x = (touch_start_x - mouse_x) * 2; var diff_y = (touch_start_y - mouse_y) * 2; touch_start_x = mouse_x; touch_start_y = mouse_y; if (!goto_active) { check_mouse_drag_unit(mouse_x, mouse_y); mapview['gui_x0'] += diff_x; mapview['gui_y0'] += diff_y; } if (client.conn.playing == null) return; /* Request preview goto path */ goto_preview_active = true; if (goto_active && current_focus.length > 0) { var ptile = canvas_pos_to_tile(mouse_x, mouse_y); if (ptile != null) { for (var i = 0; i < current_focus.length; i++) { if (i >= 20) return; // max 20 units goto a time. if (goto_request_map[current_focus[i]['id'] + "," + ptile['x'] + "," + ptile['y']] == null) { request_goto_path(current_focus[i]['id'], ptile['x'], ptile['y']); } } } } } /**************************************************************************** This function is triggered when the mouse is clicked on the city canvas. ****************************************************************************/ function city_mapview_mouse_click(e) { var rightclick; if (!e) e = window.event; if (e.which) { rightclick = (e.which == 3); } else if (e.button) { rightclick = (e.button == 2); } if (!rightclick) { city_action_button_pressed(mouse_x, mouse_y); } } /**************************************************************************** This function checks if there is a visible unit on the given canvas position, and selects that visible unit, and activates goto for touch devices. ****************************************************************************/ function check_mouse_drag_unit(canvas_x, canvas_y) { var ptile = canvas_pos_to_tile(canvas_x, canvas_y); if (ptile == null || !mouse_touch_started_on_unit) return; var sunit = find_visible_unit(ptile); if (sunit != null) { if (client.conn.playing != null && sunit['owner'] == client.conn.playing.playerno) { set_unit_focus(sunit); if (is_touch_device()) activate_goto(); } } var ptile_units = tile_units(ptile); if (ptile_units.length > 1) { update_active_units_dialog(); } } /************************************************************************** Do some appropriate action when the "main" mouse button (usually left-click) is pressed. For more sophisticated user control use (or write) a different xxx_button_pressed function. **************************************************************************/ function action_button_pressed(canvas_x, canvas_y, qtype) { var ptile = canvas_pos_to_tile(canvas_x, canvas_y); if (can_client_change_view() && ptile != null) { /* FIXME: Some actions here will need to check can_client_issue_orders. * But all we can check is the lowest common requirement. */ do_map_click(ptile, qtype, true); } } /************************************************************************** Do some appropriate action when the "main" mouse button (usually left-click) is pressed. For more sophisticated user control use (or write) a different xxx_button_pressed function. **************************************************************************/ function city_action_button_pressed(canvas_x, canvas_y) { var ptile = canvas_pos_to_tile(canvas_x, canvas_y); if (can_client_change_view() && ptile != null) { /* FIXME: Some actions here will need to check can_client_issue_orders. * But all we can check is the lowest common requirement. */ do_city_map_click(ptile); } } /************************************************************************** This will select and set focus to all the units which are in the selected rectangle on the map when the mouse is selected using the right mouse button. [canvas_x, canvas_y, map_select_x, map_select_y]. **************************************************************************/ function map_select_units(canvas_x, canvas_y) { var selected_tiles = {}; var selected_units = []; if (client_is_observer()) return; var start_x = (map_select_x < canvas_x) ? map_select_x : canvas_x; var start_y = (map_select_y < canvas_y) ? map_select_y : canvas_y; var end_x = (map_select_x < canvas_x) ? canvas_x : map_select_x; var end_y = (map_select_y < canvas_y) ? canvas_y : map_select_y; for (var x = start_x; x < end_x; x += 15) { for (var y = start_y; y < end_y; y += 15) { var ptile = canvas_pos_to_tile(x, y); if (ptile != null) { selected_tiles[ptile['tile']] = ptile; } } } for (var tile_id in selected_tiles) { var ptile = selected_tiles[tile_id]; var cunits = tile_units(ptile); if (cunits == null) continue; for (var i = 0; i < cunits.length; i++) { var aunit = cunits[i]; if (aunit['owner'] == client.conn.playing.playerno) { selected_units.push(aunit); } } } current_focus = selected_units; update_active_units_dialog(); } /************************************************************************** Recenter the map on the canvas location, on user request. Usually this is done with a right-click. **************************************************************************/ function recenter_button_pressed(canvas_x, canvas_y) { var map_scroll_border = 8; var big_map_size = 24; var ptile = canvas_pos_to_tile(canvas_x, canvas_y); var orig_tile = ptile; /* Prevent the user from scrolling outside the map. */ if (ptile != null && ptile['y'] > (map['ysize'] - map_scroll_border) && map['xsize'] > big_map_size && map['ysize'] > big_map_size) { ptile = map_pos_to_tile(ptile['x'], map['ysize'] - map_scroll_border); } if (ptile != null && ptile['y'] < map_scroll_border && map['xsize'] > big_map_size && map['ysize'] > big_map_size) { ptile = map_pos_to_tile(ptile['x'], map_scroll_border); } if (can_client_change_view() && ptile != null && orig_tile != null) { var sunit = find_visible_unit(orig_tile); if (!client_is_observer() && sunit != null && sunit['owner'] == client.conn.playing.playerno) { /* the user right-clicked on own unit, show context menu instead of recenter. */ if (current_focus.length <= 1) set_unit_focus(sunit); $("#canvas").contextMenu(true); $("#canvas").contextmenu(); } else { $("#canvas").contextMenu(false); /* FIXME: Some actions here will need to check can_client_issue_orders. * But all we can check is the lowest common requirement. */ enable_mapview_slide(ptile); center_tile_mapcanvas(ptile); } } } /************************************************************************** ... **************************************************************************/ function handle_info_text_message(packet) { var message = decodeURIComponent(packet['message']); var regxp = /\n/gi; message = message.replace(regxp, "<br>\n"); show_dialog_message("Tile Information", message); } /************************************************************************** This function shows the dialog containing active units on the current tile. **************************************************************************/ function update_active_units_dialog() { var unit_info_html = ""; var ptile = null; var punits = []; var width = 0; if (client_is_observer() || !unitpanel_active) return; if (current_focus.length == 1) { ptile = index_to_tile(current_focus[0]['tile']); punits.push(current_focus[0]); var tmpunits = tile_units(ptile); for (var i = 0; i < tmpunits.length; i++) { var kunit = tmpunits[i]; if (kunit['id'] == current_focus[0]['id']) continue; punits.push(kunit); } } else if (current_focus.length > 1) { punits = current_focus; } for (var i = 0; i < punits.length; i++) { var punit = punits[i]; var sprite = get_unit_image_sprite(punit); var active = (current_focus.length > 1 || current_focus[0]['id'] == punit['id']); unit_info_html += "<div id='unit_info_div' class='" + (active ? "current_focus_unit" : "") + "'><div id='unit_info_image' onclick='set_unit_focus_and_redraw(units[" + punit['id'] + "])' " + " style='background: transparent url(" + sprite['image-src'] + ");background-position:-" + sprite['tileset-x'] + "px -" + sprite['tileset-y'] + "px; width: " + sprite['width'] + "px;height: " + sprite['height'] + "px;'" + "'></div></div>"; width = sprite['width']; } if (current_focus.length == 1) { /* show info about the active focus unit. */ var aunit = current_focus[0]; var ptype = unit_type(aunit); unit_info_html += "<div id='active_unit_info' title='" + ptype['helptext'] + "'>"; if (client.conn.playing != null && current_focus[0]['owner'] != client.conn.playing.playerno) { unit_info_html += "<b>" + nations[players[current_focus[0]['owner']]['nation']]['adjective'] + "</b> "; } unit_info_html += "<b>" + ptype['name'] + "</b>: "; if (get_unit_homecity_name(aunit) != null) { unit_info_html += " " + get_unit_homecity_name(aunit) + " "; } if (current_focus[0]['owner'] == client.conn.playing.playerno) { unit_info_html += "<span>" + get_unit_moves_left(aunit) + "</span> "; } unit_info_html += "<br><span title='Attack strength'>A:" + ptype['attack_strength'] + "</span> <span title='Defense strength'>D:" + ptype['defense_strength'] + "</span> <span title='Firepower'>F:" + ptype['firepower'] + "</span> <span title='Health points'>H:" + ptype['hp'] + "</span>"; if (aunit['veteran'] > 0) { unit_info_html += " <span>Veteran: " + aunit['veteran'] + "</span>"; } if (ptype['transport_capacity'] > 0) { unit_info_html += " <span>Transport: " + ptype['transport_capacity'] + "</span>"; } unit_info_html += "</div>"; } else if (current_focus.length >= 1 && client.conn.playing != null && current_focus[0]['owner'] != client.conn.playing.playerno) { unit_info_html += "<div id='active_unit_info'>" + current_focus.length + " foreign units (" + nations[players[current_focus[0]['owner']]['nation']]['adjective'] +")</div> "; } else if (current_focus.length > 1) { unit_info_html += "<div id='active_unit_info'>" + current_focus.length + " units selected.</div> "; } $("#game_unit_info").html(unit_info_html); if (current_focus.length > 0) { /* reposition and resize unit dialog. */ var newwidth = 32 + punits.length * (width + 10); if (newwidth < 140) newwidth = 140; var newheight = 75 + normal_tile_height; $("#game_unit_panel").parent().show(); $("#game_unit_panel").parent().width(newwidth); $("#game_unit_panel").parent().height(newheight); $("#game_unit_panel").parent().css("left", ($( window ).width() - newwidth) + "px"); $("#game_unit_panel").parent().css("top", ($( window ).height() - newheight - 30) + "px"); $("#game_unit_panel").parent().css("background", "rgba(50,50,40,0.5)"); } else { $("#game_unit_panel").parent().hide(); } $("#active_unit_info").tooltip(); }
andreasrosdal/freeciv-web
freeciv-web/src/main/webapp/javascript/2dcanvas/mapctrl.js
JavaScript
agpl-3.0
16,757
"use strict"; var express = require("express"), config = require("config"), helpers = require("./src/helpers"); module.exports = function () { var app = express(); app.use( express.compress() ); // configure logging if ("development" == app.get("env")) { app.use(express.logger("dev")); } else if ("production" == app.get("env")) { app.use(express.logger("default")); } // Configure some settings app.set("json spaces", 2); // in production as well as in dev // Intercept the static content app.use("/", express.static(__dirname + "/static", { maxAge: 5 * 60 * 60 * 1000 })); // Set up the default response app.use(function (req, res, next) { // By default don't cache anything (much easier when working with CloudFront) res.header( "Cache-Control", helpers.cacheControl(0) ); // Allow all domains to request data (see CORS for more details) res.header("Access-Control-Allow-Origin", "*"); next(); }); // Load the sub-apps app.use("/v1/country", require("./src/country")); app.use("/v1/books", require("./src/books")); app.use("/v1/ping", require("./src/ping")); app.get("/", function (req, res) { res.header( "Cache-Control", helpers.cacheControl(3600) ); res.redirect("/v1"); }); app.get("/v1", function (req, res) { var urlBase = config.api.protocol + "://" + config.api.hostport + "/v1/"; res.header( "Cache-Control", helpers.cacheControl(3600) ); res.jsonp({ books: urlBase + "books", ping: urlBase + "ping", }); }); // 404 everything that was not caught above app.all("*", function (req, res) { res.status(404); res.jsonp({ error: "404 - page not found" }); }); // Default error handling - TODO change to JSON app.use(function (error, req, res, next) { if (error.status != 403) { return next(); } res.status(403); res.jsonp({ error: "403 - forbidden"}); }); if ("development" == app.get("env")) { app.use(express.errorHandler()); } return app; };
OpenBookPrices/openbookprices-api
index.js
JavaScript
agpl-3.0
2,044
export class InOutViewController extends BaseViewController { constructor( options = {} ) { _.defaults( options, { type_array: null, job_api: null, job_item_api: null, old_type_status: {}, show_job_ui: false, show_job_item_ui: false, show_branch_ui: false, show_department_ui: false, show_good_quantity_ui: false, show_bad_quantity_ui: false, show_transfer_ui: false, show_node_ui: false, original_note: false, new_note: false } ); super( options ); } init( options ) { Global.setUINotready( true ); this.permission_id = 'punch'; this.viewId = 'InOut'; this.script_name = 'InOutView'; this.table_name_key = 'punch'; this.context_menu_name = $.i18n._( 'In/Out' ); this.api = TTAPI.APIPunch; //Tried to fix Cannot call method 'getJobItem' of null. Use ( Global.getProductEdition() >= 20 ) if ( ( Global.getProductEdition() >= 20 ) ) { this.job_api = TTAPI.APIJob; this.job_item_api = TTAPI.APIJobItem; } this.render(); this.buildContextMenu(); this.initPermission(); this.initData(); this.is_changed = true; } getCustomContextMenuModel() { var context_menu_model = { exclude: ['default'], include: [ContextMenuIconName.save, ContextMenuIconName.cancel] }; return context_menu_model; } addPermissionValidate( p_id ) { if ( !Global.isSet( p_id ) ) { p_id = this.permission_id; } if ( p_id === 'report' ) { return true; } if ( PermissionManager.validate( p_id, 'punch_in_out' ) ) { return true; } return false; } jobUIValidate() { if ( PermissionManager.validate( 'job', 'enabled' ) && PermissionManager.validate( 'punch', 'edit_job' ) ) { return true; } return false; } jobItemUIValidate() { if ( PermissionManager.validate( 'punch', 'edit_job_item' ) ) { return true; } return false; } branchUIValidate() { if ( PermissionManager.validate( 'punch', 'edit_branch' ) ) { return true; } return false; } departmentUIValidate() { if ( PermissionManager.validate( 'punch', 'edit_department' ) ) { return true; } return false; } goodQuantityUIValidate() { if ( PermissionManager.validate( 'punch', 'edit_quantity' ) ) { return true; } return false; } badQuantityUIValidate() { if ( PermissionManager.validate( 'punch', 'edit_quantity' ) && PermissionManager.validate( 'punch', 'edit_bad_quantity' ) ) { return true; } return false; } transferUIValidate() { if ( PermissionManager.validate( 'punch', 'edit_transfer' ) ) { return true; } return false; } noteUIValidate() { if ( PermissionManager.validate( 'punch', 'edit_note' ) ) { return true; } return false; } //Speical permission check for views, need override initPermission() { if ( this.jobUIValidate() ) { this.show_job_ui = true; } else { this.show_job_ui = false; } if ( this.jobItemUIValidate() ) { this.show_job_item_ui = true; } else { this.show_job_item_ui = false; } if ( this.branchUIValidate() ) { this.show_branch_ui = true; } else { this.show_branch_ui = false; } if ( this.departmentUIValidate() ) { this.show_department_ui = true; } else { this.show_department_ui = false; } if ( this.goodQuantityUIValidate() ) { this.show_good_quantity_ui = true; } else { this.show_good_quantity_ui = false; } if ( this.badQuantityUIValidate() ) { this.show_bad_quantity_ui = true; } else { this.show_bad_quantity_ui = false; } if ( this.transferUIValidate() ) { this.show_transfer_ui = true; } else { this.show_transfer_ui = false; } if ( this.noteUIValidate() ) { this.show_node_ui = true; } else { this.show_node_ui = false; } var result = false; // Error: Uncaught TypeError: (intermediate value).isBranchAndDepartmentAndJobAndJobItemEnabled is not a function on line 207 var company_api = TTAPI.APICompany; if ( company_api && _.isFunction( company_api.isBranchAndDepartmentAndJobAndJobItemEnabled ) ) { result = company_api.isBranchAndDepartmentAndJobAndJobItemEnabled( { async: false } ); } //tried to fix Unable to get property 'getResult' of undefined or null reference, added if(!result) if ( !result ) { this.show_branch_ui = false; this.show_department_ui = false; this.show_job_ui = false; this.show_job_item_ui = false; } else { result = result.getResult(); if ( !result.branch ) { this.show_branch_ui = false; } if ( !result.department ) { this.show_department_ui = false; } if ( !result.job ) { this.show_job_ui = false; } if ( !result.job_item ) { this.show_job_item_ui = false; } } if ( !this.show_job_ui && !this.show_job_item_ui ) { this.show_bad_quantity_ui = false; this.show_good_quantity_ui = false; } } render() { super.render(); } initOptions( callBack ) { var options = [ { option_name: 'type' }, { option_name: 'status' } ]; this.initDropDownOptions( options, function( result ) { if ( callBack ) { callBack( result ); // First to initialize drop down options, and then to initialize edit view UI. } } ); } getUserPunch( callBack ) { var $this = this; var station_id = Global.getStationID(); var api_station = TTAPI.APIStation; if ( station_id ) { api_station.getCurrentStation( station_id, '10', { onResult: function( result ) { doNext( result ); } } ); } else { api_station.getCurrentStation( '', '10', { onResult: function( result ) { doNext( result ); } } ); } function doNext( result ) { // Error: Uncaught TypeError: undefined is not a function in /interface/html5/#!m=TimeSheet&date=20150324&user_id=36135&sm=InOut line 285 if ( !$this.api || typeof $this.api['getUserPunch'] !== 'function' ) { return; } var res_data = result.getResult(); //setCookie( 'StationID', res_data ); Global.setStationID( res_data ); $this.api.getUserPunch( { onResult: function( result ) { var result_data = result.getResult(); //keep the inout view fields consistent for screenshots in unit test mode if ( Global.UNIT_TEST_MODE === true ) { result_data.punch_date = 'UNITTEST'; result_data.punch_time = 'UNITTEST'; } if ( !result.isValid() ) { TAlertManager.showErrorAlert( result ); $this.onCancelClick( true ); return; } if ( Global.isSet( result_data ) ) { callBack( result_data ); } else { $this.onCancelClick(); } } } ); } } onCancelClick( force_no_confirm ) { this.is_changed = true; super.onCancelClick( force_no_confirm ); } openEditView() { var $this = this; if ( this.edit_only_mode && this.api ) { this.initOptions( function( result ) { if ( !$this.edit_view ) { $this.initEditViewUI( 'InOut', 'InOutEditView.html' ); } $this.getUserPunch( function( result ) { // Waiting for the TTAPI.API returns data to set the current edit record. $this.current_edit_record = result; //keep fields consistent in unit test mode for consistent screenshots if ( Global.UNIT_TEST_MODE === true ) { $this.current_edit_record.punch_date = 'UNITTEST'; $this.current_edit_record.punch_time = 'UNITTEST'; } $this.initEditView(); } ); } ); } } onFormItemChange( target, doNotValidate ) { this.setIsChanged( target ); this.setMassEditingFieldsWhenFormChange( target ); var key = target.getField(); var c_value = target.getValue(); this.current_edit_record[key] = c_value; switch ( key ) { case 'transfer': this.onTransferChanged(); break; case 'job_id': if ( ( Global.getProductEdition() >= 20 ) ) { this.edit_view_ui_dic['job_quick_search'].setValue( target.getValue( true ) ? ( target.getValue( true ).manual_id ? target.getValue( true ).manual_id : '' ) : '' ); this.setJobItemValueWhenJobChanged( target.getValue( true ), 'job_item_id', { status_id: 10, job_id: this.current_edit_record.job_id } ); this.edit_view_ui_dic['job_quick_search'].setCheckBox( true ); } break; case 'job_item_id': if ( ( Global.getProductEdition() >= 20 ) ) { this.edit_view_ui_dic['job_item_quick_search'].setValue( target.getValue( true ) ? ( target.getValue( true ).manual_id ? target.getValue( true ).manual_id : '' ) : '' ); this.edit_view_ui_dic['job_item_quick_search'].setCheckBox( true ); } break; case 'job_quick_search': case 'job_item_quick_search': if ( ( Global.getProductEdition() >= 20 ) ) { this.onJobQuickSearch( key, c_value ); //Don't validate immediately as onJobQuickSearch is doing async API calls, and it would cause a guaranteed validation failure. doNotValidate = true; } break; } if ( !doNotValidate ) { this.validate(); } } onTransferChanged( initial_load ) { var is_transfer = false; if ( this.edit_view_ui_dic && this.edit_view_ui_dic['transfer'] && this.edit_view_ui_dic['transfer'].getValue() == true ) { is_transfer = true; } // type_id_widget is undefined in interface/html5/framework/jquery.min.js?v=9.0.1-20151022-091549 line 2 > eval line 390 var type_id_widget = this.edit_view_ui_dic['type_id']; var status_id_widget = this.edit_view_ui_dic['status_id']; if ( is_transfer && type_id_widget && status_id_widget ) { type_id_widget.setEnabled( false ); status_id_widget.setEnabled( false ); this.old_type_status.type_id = type_id_widget.getValue(); this.old_type_status.status_id = status_id_widget.getValue(); type_id_widget.setValue( 10 ); status_id_widget.setValue( 10 ); this.current_edit_record.type_id = 10; this.current_edit_record.status_id = 10; } else if ( type_id_widget && status_id_widget ) { type_id_widget.setEnabled( true ); status_id_widget.setEnabled( true ); if ( this.old_type_status.hasOwnProperty( 'type_id' ) ) { type_id_widget.setValue( this.old_type_status.type_id ); status_id_widget.setValue( this.old_type_status.status_id ); this.current_edit_record.type_id = this.old_type_status.type_id; this.current_edit_record.status_id = this.old_type_status.status_id; } } if ( is_transfer == true ) { if ( this.original_note == '' ) { this.original_note = this.current_edit_record.note; } else { this.original_note = this.edit_view_ui_dic.note.getValue(); } this.edit_view_ui_dic.note.setValue( this.new_note ? this.new_note : '' ); this.current_edit_record.note = this.new_note ? this.new_note : ''; } else if ( typeof initial_load == 'undefined' || initial_load === false ) { this.new_note = this.edit_view_ui_dic.note.getValue(); this.edit_view_ui_dic.note.setValue( this.original_note ? this.original_note : '' ); this.current_edit_record.note = this.original_note ? this.original_note : ''; } } //Make sure this.current_edit_record is updated before validate validate() { var $this = this; var record = {}; if ( this.is_mass_editing ) { for ( var key in this.edit_view_ui_dic ) { if ( !this.edit_view_ui_dic.hasOwnProperty( key ) ) { continue; } var widget = this.edit_view_ui_dic[key]; if ( Global.isSet( widget.isChecked ) ) { if ( widget.isChecked() && widget.getEnabled() ) { record[key] = widget.getValue(); } } } } else { record = this.current_edit_record; } record = this.uniformVariable( record ); this.api.setUserPunch( record, true, { onResult: function( result ) { $this.validateResult( result ); } } ); } // Overrides BaseViewController doSaveAPICall( record, ignoreWarning, callback ) { var current_api = this.getCurrentAPI(); if ( !callback ) { callback = { onResult: function( result ) { this.onSaveResult( result ); }.bind( this ) }; } current_api.setIsIdempotent( true ); //Force to idempotent API call to avoid duplicate network requests from causing errors displayed to the user. return current_api.setUserPunch( record, false, ignoreWarning, callback ); } onSaveResult( result ) { super.onSaveResult( result ); if ( LocalCacheData.current_open_primary_controller && LocalCacheData.current_open_primary_controller.viewId === 'TimeSheet' ) { LocalCacheData.current_open_primary_controller.search(); } } setErrorMenu() { var len = this.context_menu_array.length; for ( var i = 0; i < len; i++ ) { var context_btn = $( this.context_menu_array[i] ); var id = $( context_btn.find( '.ribbon-sub-menu-icon' ) ).attr( 'id' ); context_btn.removeClass( 'disable-image' ); switch ( id ) { case ContextMenuIconName.cancel: break; default: context_btn.addClass( 'disable-image' ); break; } } } getOtherFieldReferenceField() { return 'note'; } buildEditViewUI() { super.buildEditViewUI(); var $this = this; var tab_model = { 'tab_punch': { 'label': $.i18n._( 'Punch' ) }, 'tab_audit': true, }; this.setTabModel( tab_model ); //Tab 0 start var tab_punch = this.edit_view_tab.find( '#tab_punch' ); var tab_punch_column1 = tab_punch.find( '.first-column' ); this.edit_view_tabs[0] = []; this.edit_view_tabs[0].push( tab_punch_column1 ); var form_item_input; var widgetContainer; var label; // Employee form_item_input = Global.loadWidgetByName( FormItemType.TEXT ); form_item_input.TText( { field: 'user_id_readonly' } ); this.addEditFieldToColumn( $.i18n._( 'Employee' ), form_item_input, tab_punch_column1, '' ); // Time form_item_input = Global.loadWidgetByName( FormItemType.TIME_PICKER ); form_item_input.TTimePicker( { field: 'punch_time' } ); this.addEditFieldToColumn( $.i18n._( 'Time' ), form_item_input, tab_punch_column1 ); // Date // punch_date, punch_dates form_item_input = Global.loadWidgetByName( FormItemType.DATE_PICKER ); form_item_input.TDatePicker( { field: 'punch_date' } ); this.addEditFieldToColumn( $.i18n._( 'Date' ), form_item_input, tab_punch_column1 ); //Transfer form_item_input = Global.loadWidgetByName( FormItemType.CHECKBOX ); form_item_input.TCheckbox( { field: 'transfer' } ); this.addEditFieldToColumn( $.i18n._( 'Transfer' ), form_item_input, tab_punch_column1, '', null, true ); if ( !this.show_transfer_ui ) { this.detachElement( 'transfer' ); } // Punch form_item_input = Global.loadWidgetByName( FormItemType.COMBO_BOX ); form_item_input.TComboBox( { field: 'type_id' } ); form_item_input.setSourceData( $this.type_array ); this.addEditFieldToColumn( $.i18n._( 'Punch Type' ), form_item_input, tab_punch_column1 ); // In/Out form_item_input = Global.loadWidgetByName( FormItemType.COMBO_BOX ); form_item_input.TComboBox( { field: 'status_id' } ); form_item_input.setSourceData( $this.status_array ); this.addEditFieldToColumn( $.i18n._( 'In/Out' ), form_item_input, tab_punch_column1 ); // Branch form_item_input = Global.loadWidgetByName( FormItemType.AWESOME_BOX ); form_item_input.AComboBox( { api_class: TTAPI.APIBranch, allow_multiple_selection: false, layout_name: 'global_branch', show_search_inputs: true, set_empty: true, field: 'branch_id' } ); this.addEditFieldToColumn( $.i18n._( 'Branch' ), form_item_input, tab_punch_column1, '', null, true ); if ( !this.show_branch_ui ) { this.detachElement( 'branch_id' ); } // Department form_item_input = Global.loadWidgetByName( FormItemType.AWESOME_BOX ); form_item_input.AComboBox( { api_class: TTAPI.APIDepartment, allow_multiple_selection: false, layout_name: 'global_department', show_search_inputs: true, set_empty: true, field: 'department_id' } ); this.addEditFieldToColumn( $.i18n._( 'Department' ), form_item_input, tab_punch_column1, '', null, true ); if ( !this.show_department_ui ) { this.detachElement( 'department_id' ); } if ( ( Global.getProductEdition() >= 20 ) ) { //Job form_item_input = Global.loadWidgetByName( FormItemType.AWESOME_BOX ); form_item_input.AComboBox( { api_class: TTAPI.APIJob, allow_multiple_selection: false, layout_name: 'global_job', show_search_inputs: true, set_empty: true, setRealValueCallBack: ( function( val ) { if ( val ) { job_coder.setValue( val.manual_id ); } } ), field: 'job_id' } ); widgetContainer = $( '<div class=\'widget-h-box\'></div>' ); var job_coder = Global.loadWidgetByName( FormItemType.TEXT_INPUT ); job_coder.TTextInput( { field: 'job_quick_search', disable_keyup_event: true } ); job_coder.addClass( 'job-coder' ); widgetContainer.append( job_coder ); widgetContainer.append( form_item_input ); this.addEditFieldToColumn( $.i18n._( 'Job' ), [form_item_input, job_coder], tab_punch_column1, '', widgetContainer, true ); if ( !this.show_job_ui ) { this.detachElement( 'job_id' ); } // Task form_item_input = Global.loadWidgetByName( FormItemType.AWESOME_BOX ); form_item_input.AComboBox( { api_class: TTAPI.APIJobItem, allow_multiple_selection: false, layout_name: 'global_job_item', show_search_inputs: true, set_empty: true, setRealValueCallBack: ( function( val ) { if ( val ) { job_item_coder.setValue( val.manual_id ); } } ), field: 'job_item_id' } ); widgetContainer = $( '<div class=\'widget-h-box\'></div>' ); var job_item_coder = Global.loadWidgetByName( FormItemType.TEXT_INPUT ); job_item_coder.TTextInput( { field: 'job_item_quick_search', disable_keyup_event: true } ); job_item_coder.addClass( 'job-coder' ); widgetContainer.append( job_item_coder ); widgetContainer.append( form_item_input ); this.addEditFieldToColumn( $.i18n._( 'Task' ), [form_item_input, job_item_coder], tab_punch_column1, '', widgetContainer, true ); if ( !this.show_job_item_ui ) { this.detachElement( 'job_item_id' ); } } // Quantity if ( ( Global.getProductEdition() >= 20 ) ) { var good = Global.loadWidgetByName( FormItemType.TEXT_INPUT ); good.TTextInput( { field: 'quantity', width: 40 } ); good.addClass( 'quantity-input' ); var good_label = $( '<span class=\'widget-right-label\'>' + $.i18n._( 'Good' ) + ': </span>' ); var bad = Global.loadWidgetByName( FormItemType.TEXT_INPUT ); bad.TTextInput( { field: 'bad_quantity', width: 40 } ); bad.addClass( 'quantity-input' ); var bad_label = $( '<span class=\'widget-right-label\'>/ ' + $.i18n._( 'Bad' ) + ': </span>' ); widgetContainer = $( '<div class=\'widget-h-box\'></div>' ); widgetContainer.append( good_label ); widgetContainer.append( good ); widgetContainer.append( bad_label ); widgetContainer.append( bad ); this.addEditFieldToColumn( $.i18n._( 'Quantity' ), [good, bad], tab_punch_column1, '', widgetContainer, true ); if ( !this.show_bad_quantity_ui && !this.show_good_quantity_ui ) { this.detachElement( 'quantity' ); } else { if ( !this.show_bad_quantity_ui ) { bad_label.hide(); bad.hide(); } if ( !this.show_good_quantity_ui ) { good_label.hide(); good.hide(); } } } //Note form_item_input = Global.loadWidgetByName( FormItemType.TEXT_AREA ); form_item_input.TTextArea( { field: 'note', width: '100%' } ); this.addEditFieldToColumn( $.i18n._( 'Note' ), form_item_input, tab_punch_column1, '', null, true, true ); form_item_input.parent().width( '45%' ); if ( !this.show_node_ui ) { this.detachElement( 'note' ); } } setCurrentEditRecordData() { // reset old_types, should only be set when type change and transfer is true. fixed bug 1500 this.old_type_status = {}; //Set current edit record data to all widgets for ( var key in this.current_edit_record ) { if ( !this.current_edit_record.hasOwnProperty( key ) ) { continue; } var widget = this.edit_view_ui_dic[key]; if ( Global.isSet( widget ) ) { switch ( key ) { case 'user_id_readonly': widget.setValue( this.current_edit_record.first_name + ' ' + this.current_edit_record.last_name ); break; case 'job_id': if ( ( Global.getProductEdition() >= 20 ) ) { var args = {}; args.filter_data = { status_id: 10, user_id: this.current_edit_record.user_id }; widget.setDefaultArgs( args ); widget.setValue( this.current_edit_record[key] ); } break; case 'job_item_id': if ( ( Global.getProductEdition() >= 20 ) ) { var args = {}; args.filter_data = { status_id: 10, job_id: this.current_edit_record.job_id }; widget.setDefaultArgs( args ); widget.setValue( this.current_edit_record[key] ); } break; case 'job_quick_search': break; case 'job_item_quick_search': break; case 'transfer': // do this at last break; case 'punch_time': case 'punch_date': widget.setEnabled( false ); widget.setValue( this.current_edit_record[key] ); break; default: widget.setValue( this.current_edit_record[key] ); break; } } } //Error: Uncaught TypeError: Cannot read property 'setValue' of undefined in interface/html5/#!m=TimeSheet&date=20151019&user_id=25869&show_wage=0&sm=InOut line 926 //The API will return if transfer should be enabled/disabled by default. if ( this.show_transfer_ui && this.edit_view_ui_dic['transfer'] ) { this.edit_view_ui_dic['transfer'].setValue( this.current_edit_record['transfer'] ); } this.onTransferChanged( true ); this.collectUIDataToCurrentEditRecord(); this.setEditViewDataDone(); } setEditViewDataDone() { super.setEditViewDataDone(); this.confirm_on_exit = true; //confirm on leaving even if no changes have been made so users can't accidentally not save punches by logging out without clicking save for example } } InOutViewController.loadView = function() { Global.loadViewSource( 'InOut', 'InOutView.html', function( result ) { var args = {}; var template = _.template( result ); Global.contentContainer().html( template( args ) ); } ); };
aydancoskun/timetrex-community-edition
interface/html5/views/attendance/in_out/InOutViewController.js
JavaScript
agpl-3.0
22,183
if (!Array.prototype.map) { // eslint-disable-next-line no-extend-native Array.prototype.map = function(fun /*, thisp */) { if (this === void 0 || this === null) { throw TypeError(); } var t = Object(this); var len = t.length >>> 0; if (typeof fun !== "function") { throw TypeError(); } var res = []; res.length = len; var thisp = arguments[1], i; for (i = 0; i < len; i++) { if (i in t) { res[i] = fun.call(thisp, t[i], i, t); } } return res; }; }
ctrlo/GADS
src/polyfills/array.map.js
JavaScript
agpl-3.0
544
define([ 'lakaxita/utils/collections', 'lakaxita/news/models', ], function(Collections, NewsModels) { News = Collections.Collection.extend({ url: '/api/news/', model: NewsModels.News, }); return {News: News}; })
labkaxita/lakaxita
lakaxita/static/js/lakaxita/news/collections.js
JavaScript
agpl-3.0
266
{ "classAlias": "widget.tinymce", "className": "Ext.ux.form.TinyMceTextArea", "inherits": "Ext.form.field.TextArea", "autoName": "MyTinyMceEditor", "helpText": "A TinyMCE 4 WYSIWYG editor", "validParentTypes": [ "abstractcontainer" ], "validChildTypes": [ ], "toolbox": { "name": "TinyMCE WYSIWYG Editor", "category": "Forms", "groups": [ "Forms" ] }, "configs": [{ "name": "iceUserName", "type": "string", "hidden": false, "initialValue": "", "merge": false }, { name: "iceUserId", type: "number", hidden: false, initialValue: 0, merge: false }, { name: 'tinyMCEConfig', type: 'object', hidden: false, merge: false }, { name: 'noWysiwyg', type: 'boolean', hidden: false, initialValue: false, merge: false }, { name: 'plugin_advlist', type: 'boolean', hidden: false, initialValue: false, merge: false }, { name: 'plugin_anchor', type: 'boolean', hidden: false, initialValue: false, merge: false }, { name: 'plugin_autolink', type: 'boolean', hidden: false, initialValue: false, merge: false }, { name: 'plugin_autoresize', type: 'boolean', hidden: false, initialValue: false, merge: false }, { name: 'plugin_autosave', type: 'boolean', hidden: false, initialValue: false, merge: false }, { name: 'plugin_bbcode', type: 'boolean', hidden: false, initialValue: false, merge: false }, { name: 'plugin_bloom', type: 'boolean', hidden: false, initialValue: false, merge: false }, { name: 'plugin_charmap', type: 'boolean', hidden: false, initialValue: false, merge: false }, { name: 'plugin_code', type: 'boolean', hidden: false, initialValue: false, merge: false }, { name: 'plugin_compat3x', type: 'boolean', hidden: false, initialValue: false, merge: false }, { name: 'plugin_contextmenu', type: 'boolean', hidden: false, initialValue: false, merge: false }, { name: 'plugin_directionality', type: 'boolean', hidden: false, initialValue: false, merge: false }, { name: 'plugin_emoticons', type: 'boolean', hidden: false, initialValue: false, merge: false }, { name: 'plugin_fullpage', type: 'boolean', hidden: false, initialValue: false, merge: false }, { name: 'plugin_fullscreen', type: 'boolean', hidden: false, initialValue: true, merge: false }, { name: 'plugin_image', type: 'boolean', hidden: false, initialValue: false, merge: false }, { name: 'image_list', type: 'array', hidden: false, initialValue: null, merge: false }, { name: 'plugin_legacyoutput', type: 'boolean', hidden: false, initialValue: false, merge: false }, { name: 'plugin_link', type: 'boolean', hidden: false, initialValue: false, merge: false }, { name: 'plugin_lists', type: 'boolean', hidden: false, initialValue: false, merge: false }, { name: 'plugin_importcss', type: 'boolean', hidden: false, initialValue: false, merge: false }, { name: 'plugin_media', type: 'boolean', hidden: false, initialValue: false, merge: false }, { name: 'plugin_nonbreaking', type: 'boolean', hidden: false, initialValue: false, merge: false }, { name: 'plugin_noneditable', type: 'boolean', hidden: false, initialValue: false, merge: false }, { name: 'plugin_pagebreak', type: 'boolean', hidden: false, initialValue: false, merge: false }, { name: 'plugin_paste', type: 'boolean', hidden: false, initialValue: true, merge: false }, { name: 'plugin_preview', type: 'boolean', hidden: false, initialValue: false, merge: false }, { name: 'plugin_print', type: 'boolean', hidden: false, initialValue: false, merge: false }, { name: 'plugin_save', type: 'boolean', hidden: false, initialValue: false, merge: false }, { name: 'plugin_searchreplace', type: 'boolean', hidden: false, initialValue: false, merge: false }, { name: 'plugin_spellchecker', type: 'boolean', hidden: false, initialValue: false, merge: false }, { name: 'plugin_table', type: 'boolean', hidden: false, initialValue: false, merge: false }, { name: 'plugin_textcolor', type: 'boolean', hidden: false, initialValue: false, merge: false }, { name: 'plugin_visualblocks', type: 'boolean', hidden: false, initialValue: false, merge: false }, { name: 'plugin_visualchars', type: 'boolean', hidden: false, initialValue: false, merge: false }, { name: 'plugin_wordcount', type: 'boolean', hidden: false, initialValue: false, merge: false }, { name: 'plugin_ice', type: 'boolean', hidden: false, initialValue: false, merge: false }, { name: 'plugin_icesearchreplace', type: 'boolean', hidden: false, initialValue: false, merge: false }, { name: 'font_formats', type: 'string', hidden: false, initialValue: null, // initialValue: "Arial=arial,helvetica,sans-serif;Comic Sans MS=comic sans ms,sans-serif;", merge: false }, { name: 'statusbar', type: 'boolean', hidden: false, initialValue: 'true', merge: false }, { name: 'showFormattingToolbar', type: 'boolean', hidden: false, initialValue: true, merge: false }, { name: 'showEditorMenu', type: 'boolean', hidden: false, initialValue: false, merge: false }, { name: 'showCustomMenu', type: 'boolean', hidden: false, initialValue: false, merge: false }, { name: 'browserSpellCheck', type: 'boolean', hidden: false, initialValue: true, merge: false }, { name: 'languages', type: 'string', hidden: false, initialValue: true, merge: false }, { name: 'defaultLanguage', type: 'string', hidden: false, initialValue: true, merge: false }, { name: 'hideToolbarOnBlur', type: 'boolean', hidden: false, initialValue: null, merge: false }, { name: 'customEditorMenu', type: 'object', hidden: false, merge: false, initalValue: null /* initialValue: { edit: { title: 'Edit', items: 'undo redo|cut copy paste | selectall' }, insert: { title: 'Insert', items: '|' }, view: { title: 'View', items: 'visualaid' }, format: { title: 'Format', items: 'bold italic underline strikethrough superscript subscript | formats | removeformat' } } */ }, { name: 'formattingToolbar', type: 'string', initialValue: 'undo redo | bold italic underline strikethrough superscript subscript | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | removeformat', hidden: false, merge: false }] }
Kolbaskin/janusjs
static/admin/packages/TinyMCE/architect/TinyMceTextAreaDef.js
JavaScript
lgpl-2.1
8,656
/* * This file is part of Cockpit. * * Copyright (C) 2013 Red Hat, Inc. * * Cockpit is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * Cockpit is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Cockpit; If not, see <http://www.gnu.org/licenses/>. */ /* global jQuery */ /* global cockpit */ /* global _ */ /* global C_ */ var shell = shell || { }; (function($, cockpit, shell) { PageShutdownDialog.prototype = { _init: function() { this.id = "shutdown-dialog"; }, setup: function() { $("#shutdown-restart").click($.proxy(this, "restart")); $("#shutdown-poweroff").click($.proxy(this, "poweroff")); $("#shutdown-delay").html( this.delay_btn = shell.select_btn($.proxy(this, "update"), [ { choice: "1", title: _("1 Minute") }, { choice: "5", title: _("5 Minutes") }, { choice: "20", title: _("20 Minutes") }, { choice: "40", title: _("40 Minutes") }, { choice: "60", title: _("60 Minutes") }, { choice: "0", title: _("No Delay") }, { choice: "x", title: _("Specific Time") } ]). css("display", "inline")); $("#shutdown-time input").change($.proxy(this, "update")); }, enter: function() { this.address = shell.get_page_machine(); /* TODO: This needs to be migrated away from the old dbus */ this.cockpitd = shell.dbus(this.address); this.cockpitd_manager = this.cockpitd.get("/com/redhat/Cockpit/Manager", "com.redhat.Cockpit.Manager"); $(this.cockpitd_manager).on("notify.shutdown", $.proxy(this, "update")); $("#shutdown-message"). val(""). attr("placeholder", _("Message to logged in users")); shell.select_btn_select(this.delay_btn, "1"); this.update(); }, show: function() { }, leave: function() { $(this.cockpitd_manager).off(".shutdown"); this.cockpitd.release(); this.cockpitd = null; this.cockpitd_manager = null; }, update: function() { var disabled = false; if (this.cockpitd) { var host = shell.util.hostname_for_display(this.cockpitd_manager); $('#shutdown-dialog .modal-title').text(cockpit.format(_("Shutdown $0"), host)); } var delay = shell.select_btn_selected(this.delay_btn); $("#shutdown-time").toggle(delay == "x"); if (delay == "x") { var h = parseInt($("#shutdown-time input:nth-child(1)").val(), 10); var m = parseInt($("#shutdown-time input:nth-child(3)").val(), 10); var valid = (h >= 0 && h < 24) && (m >= 0 && m < 60); $("#shutdown-time").toggleClass("has-error", !valid); if (!valid) disabled = true; } $("#shutdown-dialog button.btn-primary").prop('disabled', disabled); }, shutdown: function(op) { var delay = shell.select_btn_selected(this.delay_btn); var message = $("#shutdown-message").val(); var when; if (delay == "x") when = ($("#shutdown-time input:nth-child(1)").val() + ":" + $("#shutdown-time input:nth-child(3)").val()); else when = "+" + delay; this.cockpitd_manager.call('Shutdown', op, when, message, function(error) { $('#shutdown-dialog').modal('hide'); if (error && error.name != 'Disconnected') shell.show_unexpected_error(error); }); }, restart: function() { this.shutdown('restart'); }, poweroff: function() { this.shutdown('shutdown'); } }; function PageShutdownDialog() { this._init(); } shell.dialogs.push(new PageShutdownDialog()); })(jQuery, cockpit, shell);
sub-mod/cockpit
pkg/shell/cockpit-shutdown.js
JavaScript
lgpl-2.1
4,677
var app = angular.module("web-stream-wall", [ "ui.bootstrap", "pascalprecht.translate", "LocalStorageModule", "firebase" ]) ;
tsaikd/web-stream-wall
app.js
JavaScript
lgpl-3.0
131
/** * @package Hibouk (O,O) * @subpackage application (ap_) * @author David Dauvergne * @licence GNU Lesser General Public Licence see LICENCE file or http://www.gnu.org/licenses/lgpl.html */ /** * Module ap_editionToolbar */ define('bdl/edition/ap_editionToolbar', function() { var _toInactivated = function(el,d) { if(d) el.setAttribute('inactivated','false'); else el.setAttribute('inactivated','true'); }; // enregistrement d'un status var _registerS = function(commandName,rangeState, selectorTags, selectorClass, computedStyle, element) { cp_editor.commands.registerState(commandName,rangeState,selectorTags,selectorClass,computedStyle, function(){element.setAttribute('inactivated','true');}, function(){element.setAttribute('inactivated','false');} ); }; // enregistrement de commandes var _registerE = function(commandName,value,element,fnc) { element.command = function (ev) { cp_editor.commands.exec(commandName,value); }; cp_editor.commands.registerExec(commandName,fnc); }; var editionToolbar = { init : function (LANG) { var rangeState = null; // buttons // undo/redo var btUndo = document.getElementById('edition_undo'); var btRedo = document.getElementById('edition_redo'); // bascule source/texte var btsource = document.getElementById('edition_txtcode'); // events btUndo.command = function (event) { cp_editor.undoRedo.undo(); }; btRedo.command = function (event) { cp_editor.undoRedo.redo(); }; btsource.command = function (event) { var mode = cp_editor.composer.toogleView(); btsource.setAttribute('mode',mode); }; // notifications cp_editor.notify.sub('document:undoredo',function(data){ _toInactivated(btUndo,data.undo); _toInactivated(btRedo,data.redo); }); cp_editor.notify.sub('document:undoSave',function(data){ btUndo.setAttribute('inactivated','false'); btRedo.setAttribute('inactivated','true'); }); cp_editor.notify.sub('composer:show',function(data){ btsource.setAttribute('mode',data.mode); btsource.setAttribute('inactivated','false'); // undo/redo _toInactivated(btUndo,data.undoState); _toInactivated(btRedo,data.redoState); return [data]; }); cp_editor.notify.sub('composer:empty',function(){ btsource.setAttribute('inactivated','true'); btsource.setAttribute('mode','edit'); // undo/redo btUndo.setAttribute('inactivated','true'); btRedo.setAttribute('inactivated','true'); }); cp_editor.notify.sub('document:rangeChange',function(data){ rangeState = data.selection; return [data]; }); // remove ------------------------------------------------------------------------ // gum ------------------------------------------------------------------------ var edition_remove = document.getElementById('edition_remove'); var edition_gum = document.getElementById('edition_gum'); cp_editor.notify.sub('document:treeChange',function(data){ if(data.nodes) { edition_remove.setAttribute('inactivated','false'); if(data.nodes[data.nodes.length-1]) if(data.nodes[data.nodes.length-1].parentNode.nodeName.toLowerCase()!='body') edition_gum.setAttribute('inactivated','false'); } else { edition_remove.setAttribute('inactivated','true'); edition_gum.setAttribute('inactivated','true'); _stateP(''); edition_blockselect.setAttribute('inactivated','true'); } return [data]; }); _registerE('remove',null,edition_remove,function(value,command,doc) { var n = cp_editor.dom('selectedNodes'); if(n.elems[0].nodeName.toLowerCase()!='body') { n.rm(); edition_remove.setAttribute('inactivated','true'); } }); _registerE('gum',null,edition_gum,function(value,command,doc) { var n = cp_editor.dom('selectedNodes'); if(n.elems[0].nodeName.toLowerCase()!='body' && n.elems[0].parentNode.nodeName.toLowerCase()!='body') { n.unwarp(); edition_gum.setAttribute('inactivated','true'); } }); // bold ------------------------------------------------------------------------ var edition_bold = document.getElementById('edition_bold'); _registerS('bold',true,'b',null,null,edition_bold); _registerS('bold',false,'b',null,null,edition_bold); _registerE('bold',null,edition_bold,function(value,command,doc) { if(command.rangeState){ var i = document.createElement("b"); cp_editor.dom().surroundSelection(i); } else { command.getTreeDom().filterTagName('b').each(function (el) { cp_editor.dom(el).unwarp(); edition_bold.setAttribute('inactivated','true'); }); } }); // italic ------------------------------------------------------------------------ var edition_italic = document.getElementById('edition_italic'); _registerS('italic',true,'i',null,null,edition_italic); _registerS('italic',false,'i',null,null,edition_italic); _registerE('italic',null,edition_italic,function(value,command,doc) { if(command.rangeState){ var i = document.createElement("i"); cp_editor.dom().surroundSelection(i); } else { command.getTreeDom().filterTagName('i').each(function (el) { cp_editor.dom(el).unwarp(); edition_italic.setAttribute('inactivated','true'); }); } }); // underline ------------------------------------------------------------------------ var edition_underline = document.getElementById('edition_underline'); _registerS('underline',true,'span',null,{key:'text-decoration',value:'underline'},edition_underline); _registerS('underline',false,'span',null,{key:'text-decoration',value:'underline'},edition_underline); _registerE('underline',null,edition_underline,function(value,command,doc) { if(command.rangeState){ var span = document.createElement("span"); span.style.textDecoration = 'underline'; //span.classList.add('_underline_'); cp_editor.dom().surroundSelection(span); } else { command.getTreeDom().filterComputedStyle({key:'text-decoration',value:'underline'}).each(function (el) { cp_editor.dom(el).unwarp(); edition_underline.setAttribute('inactivated','true'); }); } }); // superscript ------------------------------------------------------------------------ var edition_superscript = document.getElementById('edition_superscript'); _registerS('superscript',true,'sup',null,null,edition_superscript); _registerS('superscript',false,'sup',null,null,edition_superscript); _registerE('superscript',null,edition_superscript,function(value,command,doc) { if(command.rangeState){ var sup = document.createElement("sup"); cp_editor.dom().surroundSelection(sup); } else { command.getTreeDom().filterTagName('sup').each(function (el) { cp_editor.dom(el).unwarp(); edition_superscript.setAttribute('inactivated','true'); }); } }); // subscript ------------------------------------------------------------------------ var edition_subscript = document.getElementById('edition_subscript'); _registerS('subscript',true,'sub',null,null,edition_subscript); _registerS('subscript',false,'sub',null,null,edition_subscript); _registerE('subscript',null,edition_subscript,function(value,command,doc) { if(command.rangeState){ cp_editor.dom().surroundSelection(document.createElement("sub")); } else { command.getTreeDom().filterTagName('sub').each(function (el) { cp_editor.dom(el).unwarp(); edition_subscript.setAttribute('inactivated','true'); }); } }); // p align ------------------------------------------------------------------------ var blockList = 'div,p,h1,h2,h3,h4,h5,h6,blockquote'; var edition_right = document.getElementById('edition_right'); var edition_left = document.getElementById('edition_left'); var edition_center = document.getElementById('edition_center'); var edition_justify = document.getElementById('edition_justify'); var _stateP = function(nameEl){ ['right','left','center','justify'].forEach(function (name) { if(name==nameEl || nameEl=='') document.getElementById('edition_'+name).setAttribute('inactivated','true'); else document.getElementById('edition_'+name).setAttribute('inactivated','false'); }); }; cp_editor.commands.registerState('p_start',false,blockList,null,{key:'text-align',value:'start'}, function(){_stateP('');}, function(){_stateP('all');} ); cp_editor.commands.registerState('p_right',false,blockList,null,{key:'text-align',value:'right'}, function(){_stateP('');}, function(){_stateP('right');} ); edition_right.command = function (ev) { cp_editor.commands.exec('p_alignTexte','right'); }; cp_editor.commands.registerState('p_left',false,blockList,null,{key:'text-align',value:'left'}, function(){_stateP('');}, function(){_stateP('left');} ); edition_left.command = function (ev) { cp_editor.commands.exec('p_alignTexte','left'); }; cp_editor.commands.registerState('p_center',false,blockList,null,{key:'text-align',value:'center'}, function(){_stateP('');}, function(){_stateP('center');} ); edition_center.command = function (ev) { cp_editor.commands.exec('p_alignTexte','center'); }; cp_editor.commands.registerState('p_justify',false,blockList,null,{key:'text-align',value:'justify'}, function(){_stateP('');}, function(){_stateP('justify');} ); edition_justify.command = function (ev) { cp_editor.commands.exec('p_alignTexte','justify'); }; cp_editor.commands.registerExec('p_alignTexte',function(value,command,doc) { command.getTreeDom().filterTagName(blockList).each(function (el) { cp_editor.dom(el).css('text-align',value); }); }); var edition_blockselect = document.getElementById('edition_blockselect'); edition_blockselect.init({ bl_p : 'Paragraphe', bl_h1 : 'Titre 1', bl_h2 : 'Titre 2', bl_h3 : 'Titre 3', bl_h4 : 'Titre 4', bl_h5 : 'Titre 5', bl_h6 : 'Titre 6', bl_div : 'Division', bl_blockquote : 'Citation' },UITYPE.paths.bdl+'/edition/images/ap_'); edition_blockselect.setAttribute('status','bl_p'); edition_blockselect.addEventListener('change', function (ev) { cp_editor.commands.exec('toogle_block',ev.detail.status.substring(3)); }); cp_editor.commands.registerState('toogle_block',false,blockList,null,null, function(){edition_blockselect.setAttribute('inactivated','true');}, function(resultState){ var name = resultState.last().elems[0].nodeName.toLowerCase(); edition_blockselect.setAttribute('status','bl_'+name); edition_blockselect.setAttribute('inactivated','false'); } ); cp_editor.commands.registerExec('toogle_block',function(value,command,doc) { var last = command.getTreeDom().filterTagName(blockList).last(); var attr = last.attrToString(); last.toogleTag('<'+value+attr+'>','</'+value+'>'); }); // crossref ------------------------------------------------------------------------ var edition_crossref = document.getElementById('edition_crossref'); cp_editor.commands.registerState('crossref',true,'*',null,null, function(){edition_crossref.setAttribute('inactivated','false');}, function(){edition_crossref.setAttribute('inactivated','true');} ); cp_editor.notify.sub('document:treeChange',function(data){ if(data.nodes) edition_crossref.setAttribute('inactivated','false'); else edition_crossref.setAttribute('inactivated','true'); return [data]; }); _registerE('crossref',null,edition_crossref,function(value,command,doc) { var last = command.getTreeDom().filterTagName('a').filterClassName('crossref-type-page').last(); if(last.elems[0]==undefined){ // insertion var activeID = cp_editor.composer.getActiveID(); command.execCommand("InsertHTML", false, '<a class="crossref-type-page" id="__tmp_cross__">→</a>'); // on retrouve l'élément inséré var _activeElement = cp_editor.composer.getComposerElement(); var crossEl = _activeElement.contentWindow.document.body.querySelector('#__tmp_cross__'); var scrollT = _activeElement.contentWindow.document.documentElement.scrollTop; var scrollL = _activeElement.contentWindow.document.documentElement.scrollLeft; // recherche de la cible cp_editor.composer.setTarget(function(id,targetID){ // vérifier que le document existe toujours if(cp_editor.composer.isAdd(activeID)){ // on l'affiche cp_editor.composer.show(activeID); var c = "#"+id; if(activeID!=targetID) c = targetID+c; if(crossEl){ crossEl.setAttribute('href',c); crossEl.removeAttribute('id'); _activeElement.contentWindow.scrollTo( scrollL, scrollT ); cp_editor.composer.setEffect(crossEl); } } }); } else { // suppression cp_editor.dom(last.elems[0]).rm(); edition_crossref.setAttribute('inactivated','true'); } }); // link ------------------------------------------------------------------------ var edition_link = document.getElementById('edition_link'); _registerS('link',true,'a',null,null,edition_link); _registerS('link',false,'a',null,null,edition_link); _registerE('link',null,edition_link,function(value,command,doc) { if(command.rangeState){ //document.execCommand("CreateLink", false, "http://stackoverflow.com/"); document.body.insertComponent('beforeend', '<cp:dialog id="dialog_link" width="300px" height="150px" title="'+LANG.link+'" hide="no"><div style="margin-top:10px;height:30px;text-align:center;"><input type="text" id="dialog_link_input" value="http://"/></div></cp:dialog>'); var dialog_link = document.getElementById("dialog_link"); dialog_link.command = function (event) { var a = cp_editor.dom().surroundSelection(document.createElement("a")); a.attr({href:document.getElementById("dialog_link_input").value,target:"_blank"}); dialog_link.parentNode.removeChild( dialog_link ); }; } else { command.getTreeDom().filterTagName('a').each(function (el) { cp_editor.dom(el).unwarp(); edition_link.setAttribute('inactivated','true'); }); } }); // img ------------------------------------------------------------------------ var edition_img = document.getElementById('edition_img'); cp_editor.commands.registerState('img',false,'img',null,null, function(){edition_img.setAttribute('inactivated','false');}, function(){edition_img.setAttribute('inactivated','true');} ); cp_editor.notify.sub('document:treeChange',function(data){ if(data.nodes) edition_img.setAttribute('inactivated','false'); else edition_img.setAttribute('inactivated','true'); return [data]; }); _registerE('img',null,edition_img,function(value,command,doc) { $bundles('appli', 'bookImagesfiles', function( dialog ) { dialog.init(command,cp_editor,edition_img); }); }); // footnote ------------------------------------------------------------------------ var edition_footnote = document.getElementById('edition_footnote'); cp_editor.commands.registerState('footnote',true,'*',null,null, function(){edition_crossref.setAttribute('inactivated','false');}, function(){edition_crossref.setAttribute('inactivated','true');} ); cp_editor.notify.sub('document:treeChange',function(data){ if(data.nodes) edition_footnote.setAttribute('inactivated','false'); else edition_footnote.setAttribute('inactivated','true'); return [data]; }); _registerE('footnote',null,edition_footnote,function(value,command,doc) { var last = command.getTreeDom().filterTagName('a').filterClassName('footnote-mark').last(); if(last.elems[0]==undefined){ // insertion var activeID = cp_editor.composer.getActiveID(); var idMark = _id = 'f_'+new Date().getTime(); command.execCommand("InsertHTML", false, '<a class="footnote-mark" id="'+idMark+'"><sup>x</sup></a>'); // on retrouve l'élément inséré var _activeElement = cp_editor.composer.getComposerElement(); var crossEl = _activeElement.contentWindow.document.body.querySelector('#'+idMark); var scrollT = _activeElement.contentWindow.document.documentElement.scrollTop; var scrollL = _activeElement.contentWindow.document.documentElement.scrollLeft; // recherche de la cible cp_editor.composer.setTarget(function(id,targetID){ // vérifier que le document existe toujours if(cp_editor.composer.isAdd(activeID)){ // on l'affiche cp_editor.composer.show(activeID); var note = _activeElement.contentWindow.document.body.querySelector('#'+id); note.classList.add('footnote-foot'); var foot_number = note.querySelector('.footnote-number'); if(foot_number==undefined) note.insertAdjacentHTML('afterbegin','<a class="footnote-number" href="#'+idMark+'">x. </a>'); else foot_number.setAttribute('href','#'+idMark); crossEl.setAttribute('href','#'+id); // numérotation [].forEach.call(_activeElement.contentWindow.document.body.querySelectorAll('.footnote-mark'),function(el,i) { var _f = i+1; el.innerHTML = '<sup>'+_f+'</sup>'; var _id = el.getAttribute('href').substring(1); var _foot = _activeElement.contentWindow.document.getElementById(_id); var _foot_number = _foot.querySelector('.footnote-number'); if(_foot_number!=undefined) _foot_number.innerHTML = _f+'. '; }); _activeElement.contentWindow.scrollTo( scrollL, scrollT ); cp_editor.composer.setEffect(crossEl); } }); } else { // suppression cp_editor.dom(last.elems[0]).rm(); edition_crossref.setAttribute('inactivated','true'); } }); } }; return editionToolbar; });
8moustapha8/Hibouk
bundles/edition/ap_editionToolbar.js
JavaScript
lgpl-3.0
18,070