code
stringlengths
2
1.05M
var MARKER_RESIZING = 'djs-resizing', MARKER_RESIZE_NOT_OK = 'resize-not-ok'; var LOW_PRIORITY = 500; import { attr as svgAttr, remove as svgRemove, classes as svgClasses } from 'tiny-svg'; /** * Provides previews for resizing shapes when resizing. * * @param {EventBus} eventBus * @param {Canvas} canvas * @param {PreviewSupport} previewSupport */ export default function ResizePreview(eventBus, canvas, previewSupport) { /** * Update resizer frame. * * @param {Object} context */ function updateFrame(context) { var shape = context.shape, bounds = context.newBounds, frame = context.frame; if (!frame) { frame = context.frame = previewSupport.addFrame(shape, canvas.getDefaultLayer()); canvas.addMarker(shape, MARKER_RESIZING); } if (bounds.width > 5) { svgAttr(frame, { x: bounds.x, width: bounds.width }); } if (bounds.height > 5) { svgAttr(frame, { y: bounds.y, height: bounds.height }); } if (context.canExecute) { svgClasses(frame).remove(MARKER_RESIZE_NOT_OK); } else { svgClasses(frame).add(MARKER_RESIZE_NOT_OK); } } /** * Remove resizer frame. * * @param {Object} context */ function removeFrame(context) { var shape = context.shape, frame = context.frame; if (frame) { svgRemove(context.frame); } canvas.removeMarker(shape, MARKER_RESIZING); } // add and update previews eventBus.on('resize.move', LOW_PRIORITY, function(event) { updateFrame(event.context); }); // remove previews eventBus.on('resize.cleanup', function(event) { removeFrame(event.context); }); } ResizePreview.$inject = [ 'eventBus', 'canvas', 'previewSupport' ];
angular.module('account.settings', ['config', 'account.settings.social', 'security.service', 'security.authorization', 'services.accountResource', 'services.utility','ui.bootstrap', 'directives.serverError']); angular.module('account.settings').controller('AccountSettingsCtrl', [ '$scope','$location', '$log', 'security', 'utility', 'accountResource', 'accountDetails', 'SOCIAL', '$rootScope', function($scope, $location, $log, security, utility, restResource, accountDetails, SOCIAL, $rootScope){ //local vars var account = accountDetails.account; var user = accountDetails.user; $scope.displayContShop = function() { var retVal = false; if ($rootScope.previous) { if ($rootScope.previous.indexOf('/product/')) { retVal = true; } } return retVal; }; $scope.contShop = function(){ return $location.path($rootScope.previous); }; var submitDetailForm = function(){ $scope.alerts.detail = []; restResource.setAccountDetails($scope.userDetail).then(function(data){ if(data.success){ $scope.alerts.detail.push({ type: 'success', msg: 'Account detail is updated.' }); }else{ angular.forEach(data.errors, function(err, index){ $scope.alerts.detail.push({ type: 'danger', msg: err }); }); } }, function(x){ $scope.alerts.detail.push({ type: 'danger', msg: 'Error updating account details: ' + x }); }); }; var submitIdentityForm = function(){ $scope.alerts.identity = []; restResource.setIdentity($scope.user).then(function(data){ if(data.success){ $scope.alerts.identity.push({ type: 'success', msg: 'User identity is updated.' }); }else{ //error due to server side validation $scope.errfor = data.errfor; angular.forEach(data.errfor, function(err, field){ $scope.identityForm[field].$setValidity('server', false); }); angular.forEach(data.errors, function(err, index){ $scope.alerts.identity.push({ type: 'danger', msg: err }); }); } }, function(x){ $scope.alerts.identity.push({ type: 'danger', msg: 'Error updating user identity: ' + x }); }); }; var submitPasswordForm = function(){ $scope.alerts.pass = []; restResource.setPassword($scope.pass).then(function(data){ $scope.pass = {}; $scope.passwordForm.$setPristine(); if(data.success){ $scope.alerts.pass.push({ type: 'success', msg: 'Password is updated.' }); }else{ //error due to server side validation angular.forEach(data.errors, function(err, index){ $scope.alerts.pass.push({ type: 'danger', msg: err }); }); } }, function(x){ $scope.alerts.pass.push({ type: 'danger', msg: 'Error updating password: ' + x }); }); }; var disconnect = function(provider){ var errorAlert = { type: 'warning', msg: 'Error occurred when disconnecting your '+ provider + ' account. Please try again later.' }; $scope.socialAlerts = []; security.socialDisconnect(provider).then(function(data){ if(data.success){ $scope.social[provider]['connected'] = false; $scope.socialAlerts.push({ type: 'info', msg: 'Successfully disconnected your '+ provider +' account.' }); }else{ $scope.socialAlerts.push(errorAlert); } }, function(x){ $scope.socialAlerts.push(errorAlert); }); }; //model def $scope.errfor = {}; //for identity server-side validation $scope.alerts = { detail: [], identity: [], pass: [] }; $scope.userDetail = { first: account.name.first, middle: account.name.middle, last: account.name.last, company:account.company, phone: account.phone, zip: account.zip }; $scope.user = { username: user.username, email: user.email }; $scope.pass = {}; $scope.social = null; if(!angular.equals({}, SOCIAL)){ $scope.social = SOCIAL; if(user.google && user.google.id){ $scope.social.google.connected = true; } if(user.facebook && user.facebook.id){ $scope.social.facebook.connected = true; } } $scope.socialAlerts = []; //initial behavior var search = $location.search(); if(search.provider){ if(search.success === 'true'){ $scope.socialAlerts.push({ type: 'info', msg: 'Successfully connected your '+ search.provider +' account.' }); }else{ $scope.socialAlerts.push({ type: 'warning', msg: 'Unable to connect your '+ search.provider + ' account. ' + search.reason }); } } // method def $scope.hasError = utility.hasError; $scope.showError = utility.showError; $scope.canSave = utility.canSave; $scope.closeAlert = function(key, ind){ $scope.alerts[key].splice(ind, 1); }; $scope.closeSocialAlert = function(ind){ $scope.socialAlerts.splice(ind, 1); }; $scope.submit = function(ngFormCtrl){ switch (ngFormCtrl.$name){ case 'detailForm': submitDetailForm(); break; case 'identityForm': submitIdentityForm(); break; case 'passwordForm': submitPasswordForm(); break; default: return; } }; $scope.disconnect = function(provider){ if($scope.social){ disconnect(provider); } }; } ]);
// hackerNewsScrapeServer.js // sets up a http server // and displays the info scraped from hacker news // to make it work type "node testScrapeServer.js" // go to http://localhost:8080/ // requires request, cheerio, express, mongoose, jade var request = require('request'); var cheerio = require('cheerio'); var express = require('express'); var jade = require('jade'); var app = express(); // creates server var metadataArray = [ ]; request('https://news.ycombinator.com', function(error, response, page){ if(!error && response.statusCode == 200){ var $ = cheerio.load(page); // puts the html in the parser $('span.comhead').each(function(i, element){ var a=$(this).prev(); // selects previous data var rank=a.parent().parent().text(); // gets rank by parsing text two elements higher var title=a.text(); // parses link title var url=a.attr('href'); // parses href attribute from "a" element var subtext = a.parent().parent().next().children('.subtext').children(); // gets the subtext from the children var points = $(subtext).eq(0).text(); var username = $(subtext).eq(1).text(); var comments = $(subtext).eq(2).text(); var metadata = { // creates a new object rank: parseInt(rank), title: title, url: url, points: parseInt(points), username: username, comments: parseInt(comments) }; metadataArray.push(metadata); // pushes metadata into an array }); } }); app.get('/', function(req, res){ res.send(JSON.stringify(metadataArray, null, 4)); // sends this to the server }); app.listen(8080); // listens to port 8080
// http://emberjs.com/guides/models/using-the-store/ EmberjsRails4.Store = DS.Store.extend({ // Override the default adapter with the `DS.ActiveModelAdapter` which // is built to work nicely with the ActiveModel::Serializers gem. adapter: '_ams' });
require('./app.less'); var appFunc = require('../utils/appFunc'), homeView = require('../home/home'), contactsView = require('../contacts/contacts'), settingView = require('../setting/setting'); module.exports = { init: function(){ this.i18next(''); homeView.init(); contactsView.init(); settingView.init(); }, i18next: function(content){ var that = this; var renderData = {}; var output = appFunc.renderTpl(content,renderData); $$('.views .i18n').each(function(){ var value; var i18nKey = $$(this).data('i18n'); var handle = i18nKey.split(']'); if(handle.length > 1 ){ var attr = handle[0].replace('[',''); value = that.i18nValue(handle[1]); $$(this).attr(attr,value); }else{ value = that.i18nValue(i18nKey); $$(this).html(value); } }); return output; }, i18nValue: function(key){ var keys = key.split('.'); var value = null; for (var idx = 0, size = keys.length; idx < size; idx++) { if (value !== null) { value = value[keys[idx]]; } else { value = i18n[keys[idx]]; } } return value; } };
$(function() { $(".infoblocks").slick({ // autoplay: true, arrows: false, dots: true, slidesToShow: 1, customPaging : function(slider, i) { var title = $(slider.$slides[i]).data('title'); return '<span></span> <strong>'+title+'</strong>'; }, }); });
export const ic_check_circle_outline_outline = {"viewBox":"0 0 24 24","children":[{"name":"path","attribs":{"d":"M0 0h24v24H0V0z","fill":"none"},"children":[]},{"name":"path","attribs":{"d":"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm4.59-12.42L10 14.17l-2.59-2.58L6 13l4 4 8-8z"},"children":[]}]};
import subDays from 'date-fns/subDays' import { dateId, formatDate } from '../../../utils/format-date.js' describe('the homepage', () => { let todaysId let todaysMonth let todaysDay let yesterdaysId let yesterdaysMonth let yesterdaysDay beforeEach(() => { todaysId = dateId(new Date()) todaysMonth = formatDate(todaysId, 'month') todaysDay = formatDate(todaysId, 'day') yesterdaysId = dateId(subDays(new Date(), 1)) yesterdaysMonth = formatDate(yesterdaysId, 'month') yesterdaysDay = formatDate(yesterdaysId, 'day') }) it('visits the home and redirects to todays artwork page', () => { cy.visit('/') cy.url().should('include', `/${todaysId}`) cy.get('h1') .contains(`Today, ${todaysMonth} ${todaysDay}`) .should('have.length', 1) cy.get('.timeline-nav-button--prev').click() cy.get('h1') .contains(`Yesterday, ${yesterdaysMonth} ${yesterdaysDay}`) .should('have.length', 1) }) }) // Test that share metadata changes. // Test that head metadata changes. // Setup mock data.
#!/usr/bin/env node 'use strict'; const cp = require( 'child_process' ) , path = require( 'path' ) , http = require( 'http' ) , test = require( 'tape' ); function launchServer() { let server = cp.fork( getRelativePath('../app/index'), [ getRelativePath( './smoke.json' ) ] ); process.on( 'exit', () => { server.kill(); }); return server; } let server = launchServer(); test( 'success route without token', (t) => { setTimeout( () => { const url = 'http://localhost:3000/pass/refs/heads/master/199ef929c24965a176126aed951110ec85dec3b6'; http.get( url, (result) => { result.on( 'data', (chunk) => { const response = JSON.parse(chunk.toString()); t.true( response.hasOwnProperty( 'state' ) ); t.equal( response.state, 'success' ); t.end(); server.kill(); }); }) .on( 'error', (err) => { server.kill(); }); }, 1000 ); }); function getRelativePath(filePath) { return path.join( __dirname, filePath ); }
'use strict'; angular.module('example').controller('ExampleController', ['$scope', 'Authentication', function($scope, Authentication) { $scope.authentication = Authentication; } ]);
export function getMeta() { return { name: 'root', component: 'Layout', className: 'mk-app-hot-modify-app', children: [{ name: 'left', component: 'Layout', className: 'mk-app-hot-modify-app-left', children: [{ name: 'search', component: 'Input.Search', placeholder: "请输入app name过滤", value: '{{data.search}}', onChange: '{{$searchChange}}' }, { name: 'apps', component: 'Tree', onSelect: '{{$appSelected}}', selectedKeys: '{{[data.selectApp.name]}}', _visible: '{{data.apps && data.apps.length > 0}}', children: [{ name: 'app', component: 'Tree.TreeNode', key: '{{data.apps[_rowIndex].name}}', title: '{{data.apps[_rowIndex].name}}', _power: 'for in data.apps' }] }] }, { name: 'content', component: 'Layout', className: 'mk-app-hot-modify-app-content', children: [{ name: 'card', component: 'Card', className: 'mk-app-hot-modify-app-content-main', title: { name: 'type', component: 'Radio.Group', value: '{{data.selectType}}', onChange: '{{$typeChange}}', children: [{ name: 'meta', component: 'Radio.Button', value: 'meta', children: '元数据(meta)' }, { name: 'state', component: 'Radio.Button', value: 'state', children: '当前状态(state)' }] }, extra: { name: 'extra', component: '::div', children: [{ name: 'format', component: 'Button', style: { marginRight: 6 }, type: 'softly', children: '格式化', onClick: '{{$formatJson}}' }, { name: 'reset', component: 'Button', _visible: "{{data.selectType == 'meta'}}", type: 'softly', children: '重置', onClick: '{{$reset}}' }] }, children: [{ name: 'json', component: 'CodeMirror', value: '{{data.currentJson}}', onChange: '{{$jsonChange}}', options: { mode: 'javascript', theme: 'material', lineNumbers: true, inputStyle: 'textarea' } }] }] }] } } export function getInitState() { return { data: { apps: [], selectApp: {}, search: '', other: {} } } }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.writeUpdateInfo = undefined; var _bluebirdLst; function _load_bluebirdLst() { return _bluebirdLst = require("bluebird-lst"); } /** @internal */ let writeUpdateInfo = exports.writeUpdateInfo = (() => { var _ref = (0, (_bluebirdLst || _load_bluebirdLst()).coroutine)(function* (event, _publishConfigs) { const packager = event.packager; const publishConfigs = yield (0, (_PublishManager || _load_PublishManager()).getPublishConfigsForUpdateInfo)(packager, _publishConfigs, event.arch); if (publishConfigs == null || publishConfigs.length === 0) { return; } const target = event.target; const outDir = target.outDir; const version = packager.appInfo.version; const sha2 = new (_lazyVal || _load_lazyVal()).Lazy(function () { return (0, (_builderUtil || _load_builderUtil()).hashFile)(event.file, "sha256", "hex"); }); const isMac = packager.platform === (_core || _load_core()).Platform.MAC; const releaseInfo = Object.assign({}, packager.config.releaseInfo); if (releaseInfo.releaseNotes == null) { const releaseNotesFile = yield packager.getResource(releaseInfo.releaseNotesFile, "release-notes.md"); const releaseNotes = releaseNotesFile == null ? null : yield (0, (_fsExtraP || _load_fsExtraP()).readFile)(releaseNotesFile, "utf-8"); // to avoid undefined in the file, check for null if (releaseNotes != null) { releaseInfo.releaseNotes = releaseNotes; } } delete releaseInfo.releaseNotesFile; const createdFiles = new Set(); const sharedInfo = yield createUpdateInfo(version, event, releaseInfo); for (let publishConfig of publishConfigs) { let info = sharedInfo; if (publishConfig.provider === "bintray") { continue; } if (publishConfig.provider === "github" && "releaseType" in publishConfig) { publishConfig = Object.assign({}, publishConfig); delete publishConfig.releaseType; } const channel = publishConfig.channel || "latest"; let dir = outDir; if (publishConfigs.length > 1 && publishConfig !== publishConfigs[0]) { dir = _path.join(outDir, publishConfig.provider); } // spaces is a new publish provider, no need to keep backward compatibility const isElectronUpdater1xCompatibility = publishConfig.provider !== "spaces"; if (isMac && isElectronUpdater1xCompatibility) { yield writeOldMacInfo(publishConfig, outDir, dir, channel, createdFiles, version, packager); } const updateInfoFile = _path.join(dir, `${channel}${isMac ? "-mac" : ""}.yml`); if (createdFiles.has(updateInfoFile)) { continue; } createdFiles.add(updateInfoFile); // noinspection JSDeprecatedSymbols if (isElectronUpdater1xCompatibility && packager.platform === (_core || _load_core()).Platform.WINDOWS && info.sha2 == null) { // backward compatibility info.sha2 = yield sha2.value; } if (event.safeArtifactName != null && publishConfig.provider === "github") { info = Object.assign({}, info, { githubArtifactName: event.safeArtifactName }); } yield (0, (_fsExtraP || _load_fsExtraP()).outputFile)(updateInfoFile, (0, (_jsYaml || _load_jsYaml()).safeDump)(info)); // artifact should be uploaded only to designated publish provider packager.info.dispatchArtifactCreated({ file: updateInfoFile, arch: null, packager, target: null, publishConfig }); } }); return function writeUpdateInfo(_x, _x2) { return _ref.apply(this, arguments); }; })(); let createUpdateInfo = (() => { var _ref2 = (0, (_bluebirdLst || _load_bluebirdLst()).coroutine)(function* (version, event, releaseInfo) { const info = Object.assign({ version, releaseDate: new Date().toISOString(), path: _path.basename(event.file), sha512: yield (0, (_builderUtil || _load_builderUtil()).hashFile)(event.file) }, releaseInfo); const packageFiles = event.packageFiles; if (packageFiles != null) { const keys = Object.keys(packageFiles); if (keys.length > 0) { info.packages = {}; for (const arch of keys) { const packageFileInfo = packageFiles[arch]; info.packages[arch] = Object.assign({}, packageFileInfo, { file: _path.basename(packageFileInfo.file) }); } } } return info; }); return function createUpdateInfo(_x3, _x4, _x5) { return _ref2.apply(this, arguments); }; })(); // backward compatibility - write json file let writeOldMacInfo = (() => { var _ref3 = (0, (_bluebirdLst || _load_bluebirdLst()).coroutine)(function* (publishConfig, outDir, dir, channel, createdFiles, version, packager) { const isGitHub = publishConfig.provider === "github"; const updateInfoFile = isGitHub && outDir === dir ? _path.join(dir, "github", `${channel}-mac.json`) : _path.join(dir, `${channel}-mac.json`); if (!createdFiles.has(updateInfoFile)) { createdFiles.add(updateInfoFile); yield (0, (_fsExtraP || _load_fsExtraP()).outputJson)(updateInfoFile, { version, releaseDate: new Date().toISOString(), url: (0, (_PublishManager || _load_PublishManager()).computeDownloadUrl)(publishConfig, packager.generateName2("zip", "mac", isGitHub), packager) }, { spaces: 2 }); packager.info.dispatchArtifactCreated({ file: updateInfoFile, arch: null, packager, target: null, publishConfig }); } }); return function writeOldMacInfo(_x6, _x7, _x8, _x9, _x10, _x11, _x12) { return _ref3.apply(this, arguments); }; })(); //# sourceMappingURL=updateUnfoBuilder.js.map var _builderUtil; function _load_builderUtil() { return _builderUtil = require("builder-util"); } var _fsExtraP; function _load_fsExtraP() { return _fsExtraP = require("fs-extra-p"); } var _jsYaml; function _load_jsYaml() { return _jsYaml = require("js-yaml"); } var _lazyVal; function _load_lazyVal() { return _lazyVal = require("lazy-val"); } var _path = _interopRequireWildcard(require("path")); var _core; function _load_core() { return _core = require("../core"); } var _PublishManager; function _load_PublishManager() { return _PublishManager = require("./PublishManager"); } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
export const handleErrors = (response) => { if (!response.ok) { throw Error(response.statusText); } return response; }; export const handleCatch = console.error;
// @flow import type { Action } from '../flowTypes' import type { UserCredentials, User } from './flowTypes' import types from './types' const signIn = (credentials: UserCredentials, resolve: Function, reject: Function): Action => { return { type: types.SIGN_IN, payload: { credentials, resolve, reject } } } const setUser = (user: User, token: string): Action => { return { type: types.SET_USER, payload: { user, token } } } export default { signIn, setUser }
/** * dateTimeRangePicker Widget * * This widget allows for the use of checkboxes and radio boxes alongside formBuilder * * Public Methods: * setRange() * serializeDate() * deserializeDate() * get() * set() * isDirty() * clearDirty() * clear() * validate() */ import $ from 'jquery'; import moment from 'moment'; const dict = {}; $.widget('formBuilder.dateTimeRangePicker', { _dateTimeRangePickerTemplate: '<div class="date-range-picker form">' + '<input type="text" name="from" data-type="dateTime" data-label="'+dict.from+'"/>' + '<input type="text" name="to" data-type="dateTime" data-label="'+dict.to+'"/>' + '<button type="button" class="previous-range">&lt;&lt;</button>' + '<div class="input-field-group range-select">' + '<select name="range" style="width: 138px;">' + '<option value="custom">'+dict.custom+'</option>' + '<option value="day">'+dict.day+'</option>' + '<option value="week">'+dict.week+'</option>' + '<option value="month">'+dict.month+'</option>' + '<option value="year">'+dict.year+'</option>' + '</select>' + '</div>' + '<button type="button" class="next-range">&gt;&gt;</button>' + '</div>', _create: function () { const self = this, e = self.element; const form = self.form = $('<div></div>').html(self._dateTimeRangePickerTemplate).find('.date-range-picker').formBuilder(); e.append(form); self.fromDate = form.find('input[name="from"]').on('keyup ondateselect', function () { $(self.range).val('custom'); }); // self.fromDate.inputField('setLabel', e.attr('data-from-label')); self.toDate = form.find('input[name="to"]').on('keyup ondateselect', function () { $(self.range).val('custom'); }); // self.toDate.inputField('setLabel', e.attr('data-to-label')); form.find('button.previous-range').button().on('click', function () { self._moveRange(-1, $(self.range).val()); }); form.find('button.next-range').button().on('click', function () { self._moveRange(1, $(self.range).val()); }); self.range = form.find('select[name="range"]').on('change', function () { self.setRange($(this).val()); }); }, _moveRange: function (number, unit) { const self = this, fromTypeInstance = self.fromDate.inputField('getType'), toTypeInstance = self.toDate.inputField('getType'); if (fromTypeInstance.dateWidgetInstance.isEmpty() || unit === 'custom') { return; } const fromDate = self.deserializeDate(fromTypeInstance.dateWidgetInstance.get()); const begin = fromDate.add(number, unit); const end = moment(begin).add(1,unit).subtract(1,'day'); fromTypeInstance.dateWidgetInstance.set(self.serializeDate(begin)); toTypeInstance.dateWidgetInstance.set(self.serializeDate(end)); // Force times to be correct in regards to DST if(fromTypeInstance.timeWidgetInstance.isEmpty()) { fromTypeInstance.timeWidgetInstance.set(moment().hours(0).minutes(0).utc().format('HH:mm')); } if(toTypeInstance.timeWidgetInstance.isEmpty()) { toTypeInstance.timeWidgetInstance.set(moment().hours(23).minutes(59).utc().format('HH:mm')); } }, setRange: function (range) { const self = this, fromTypeInstance = self.fromDate.inputField('getType'), toTypeInstance = self.toDate.inputField('getType'); let fromDate; if (range === 'custom') { return; } fromDate = fromTypeInstance.dateWidgetInstance.get(); if (!fromDate) { fromDate = moment(); } if (typeof fromDate === 'string') { fromDate = self.deserializeDate(fromDate); } const from = fromDate.startOf(range); const to = moment(from).endOf(range); fromTypeInstance.dateWidgetInstance.set(self.serializeDate(from)); toTypeInstance.dateWidgetInstance.set(self.serializeDate(to)); // Force times to be correct in regards to DST if(fromTypeInstance.timeWidgetInstance.isEmpty()) { fromTypeInstance.timeWidgetInstance.set(moment().hours(0).minutes(0).utc().format('HH:mm')); } if(toTypeInstance.timeWidgetInstance.isEmpty()) { toTypeInstance.timeWidgetInstance.set(moment().hours(23).minutes(59).utc().format('HH:mm')); } self.range.val(range); }, serializeDate: function (momentDate) { if (!momentDate) { return; } return momentDate.format('YYYY-MM-DD'); }, deserializeDate: function (stringDate) { if (!stringDate) { return; } return moment(stringDate, 'YYYY-MM-DD'); }, get: function () { const self = this; return self.form.formBuilder('get'); }, set: function (data) { const self = this; self.form.formBuilder('set', data); }, isDirty: function () { return this.form.formBuilder('isDirty'); }, clearDirty: function () { const self = this; self.form.formBuilder('clearDirty'); }, clear: function () { const self = this; self.set({ from: '', to: '', range: 'custom' }); }, validate: function () { const self = this, form = self.form; if (!form.formBuilder('validate')) { return false; } } });
"use strict"; /** * @class elFinder - file manager for web * * @author Dmitry (dio) Levashov **/ window.elFinder = function(node, opts) { this.time('load'); var self = this, /** * Node on which elfinder creating * * @type jQuery **/ node = $(node), /** * Store node contents. * * @see this.destroy * @type jQuery **/ prevContent = $('<div/>').append(node.contents()), /** * Store node inline styles * * @see this.destroy * @type String **/ prevStyle = node.attr('style'), /** * Instance ID. Required to get/set cookie * * @type String **/ id = node.attr('id') || '', /** * Events namespace * * @type String **/ namespace = 'elfinder-'+(id || Math.random().toString().substr(2, 7)), /** * Mousedown event * * @type String **/ mousedown = 'mousedown.'+namespace, /** * Keydown event * * @type String **/ keydown = 'keydown.'+namespace, /** * Keypress event * * @type String **/ keypress = 'keypress.'+namespace, /** * Is shortcuts/commands enabled * * @type Boolean **/ enabled = true, /** * Store enabled value before ajax requiest * * @type Boolean **/ prevEnabled = true, /** * List of build-in events which mapped into methods with same names * * @type Array **/ events = ['enable', 'disable', 'load', 'open', 'reload', 'select', 'add', 'remove', 'change', 'dblclick', 'getfile', 'lockfiles', 'unlockfiles', 'dragstart', 'dragstop'], /** * Rules to validate data from backend * * @type Object **/ rules = {}, /** * Current working directory hash * * @type String **/ cwd = '', /** * Current working directory options * * @type Object **/ cwdOptions = { path : '', url : '', tmbUrl : '', disabled : [], separator : '/', archives : [], extract : [], copyOverwrite : true, uploadMaxSize : 0, tmb : false // old API }, /** * Files/dirs cache * * @type Object **/ files = {}, /** * Selected files hashes * * @type Array **/ selected = [], /** * Events listeners * * @type Object **/ listeners = {}, /** * Shortcuts * * @type Object **/ shortcuts = {}, /** * Buffer for copied files * * @type Array **/ clipboard = [], /** * Copied/cuted files hashes * Prevent from remove its from cache. * Required for dispaly correct files names in error messages * * @type Array **/ remember = [], /** * Queue for 'open' requests * * @type Array **/ queue = [], /** * Net drivers names * * @type Array **/ netDrivers = [], /** * Commands prototype * * @type Object **/ base = new self.command(self), /** * elFinder node width * * @type String * @default "auto" **/ width = 'auto', /** * elFinder node height * * @type Number * @default 400 **/ height = 400, beeper = $(document.createElement('audio')).hide().appendTo('body')[0], syncInterval, open = function(data) { if (data.init) { // init - reset cache files = {}; } else { // remove only files from prev cwd for (var i in files) { if (files.hasOwnProperty(i) && files[i].mime != 'directory' && files[i].phash == cwd && $.inArray(i, remember) === -1) { delete files[i]; } } } cwd = data.cwd.hash; cache(data.files); if (!files[cwd]) { cache([data.cwd]); } self.lastDir(cwd); }, /** * Store info about files/dirs in "files" object. * * @param Array files * @return void **/ cache = function(data) { var l = data.length, f; while (l--) { f = data[l]; if (f.name && f.hash && f.mime) { if (!f.phash) { var name = 'volume_'+f.name, i18 = self.i18n(name); if (name != i18) { f.i18 = i18; } } files[f.hash] = f; } } }, /** * Exec shortcut * * @param jQuery.Event keydown/keypress event * @return void */ execShortcut = function(e) { var code = e.keyCode, ctrlKey = !!(e.ctrlKey || e.metaKey); if (enabled) { $.each(shortcuts, function(i, shortcut) { if (shortcut.type == e.type && shortcut.keyCode == code && shortcut.shiftKey == e.shiftKey && shortcut.ctrlKey == ctrlKey && shortcut.altKey == e.altKey) { e.preventDefault() e.stopPropagation(); shortcut.callback(e, self); self.debug('shortcut-exec', i+' : '+shortcut.description); } }); // prevent tab out of elfinder if (code == 9 && !$(e.target).is(':input')) { e.preventDefault(); } } }, date = new Date(), utc, i18n ; /** * Protocol version * * @type String **/ this.api = null; /** * elFinder use new api * * @type Boolean **/ this.newAPI = false; /** * elFinder use old api * * @type Boolean **/ this.oldAPI = false; /** * User os. Required to bind native shortcuts for open/rename * * @type String **/ this.OS = navigator.userAgent.indexOf('Mac') !== -1 ? 'mac' : navigator.userAgent.indexOf('Win') !== -1 ? 'win' : 'other'; /** * User browser UA. * jQuery.browser: version deprecated: 1.3, removed: 1.9 * * @type Object **/ this.UA = (function(){ var webkit = !document.uniqueID && !window.opera && !window.sidebar && window.localStorage && typeof window.orientation == "undefined"; return { // Browser IE <= IE 6 ltIE6:typeof window.addEventListener == "undefined" && typeof document.documentElement.style.maxHeight == "undefined", // Browser IE <= IE 7 ltIE7:typeof window.addEventListener == "undefined" && typeof document.querySelectorAll == "undefined", // Browser IE <= IE 8 ltIE8:typeof window.addEventListener == "undefined" && typeof document.getElementsByClassName == "undefined", IE:document.uniqueID, Firefox:window.sidebar, Opera:window.opera, Webkit:webkit, Chrome:webkit && window.chrome, Safari:webkit && !window.chrome, Mobile:typeof window.orientation != "undefined", Touch:typeof window.ontouchstart != "undefined" }; })(); /** * Configuration options * * @type Object **/ this.options = $.extend(true, {}, this._options, opts||{}); if (opts.ui) { this.options.ui = opts.ui; } if (opts.commands) { this.options.commands = opts.commands; } if (opts.uiOptions && opts.uiOptions.toolbar) { this.options.uiOptions.toolbar = opts.uiOptions.toolbar; } $.extend(this.options.contextmenu, opts.contextmenu); /** * Ajax request type * * @type String * @default "get" **/ this.requestType = /^(get|post)$/i.test(this.options.requestType) ? this.options.requestType.toLowerCase() : 'get', /** * Any data to send across every ajax request * * @type Object * @default {} **/ this.customData = $.isPlainObject(this.options.customData) ? this.options.customData : {}; /** * Any custom headers to send across every ajax request * * @type Object * @default {} */ this.customHeaders = $.isPlainObject(this.options.customHeaders) ? this.options.customHeaders : {}; /** * Any custom xhrFields to send across every ajax request * * @type Object * @default {} */ this.xhrFields = $.isPlainObject(this.options.xhrFields) ? this.options.xhrFields : {}; /** * ID. Required to create unique cookie name * * @type String **/ this.id = id; /** * URL to upload files * * @type String **/ this.uploadURL = opts.urlUpload || opts.url; /** * Events namespace * * @type String **/ this.namespace = namespace; /** * Interface language * * @type String * @default "en" **/ this.lang = this.i18[this.options.lang] && this.i18[this.options.lang].messages ? this.options.lang : 'en'; i18n = this.lang == 'en' ? this.i18['en'] : $.extend(true, {}, this.i18['en'], this.i18[this.lang]); /** * Interface direction * * @type String * @default "ltr" **/ this.direction = i18n.direction; /** * i18 messages * * @type Object **/ this.messages = i18n.messages; /** * Date/time format * * @type String * @default "m.d.Y" **/ this.dateFormat = this.options.dateFormat || i18n.dateFormat; /** * Date format like "Yesterday 10:20:12" * * @type String * @default "{day} {time}" **/ this.fancyFormat = this.options.fancyDateFormat || i18n.fancyDateFormat; /** * Today timestamp * * @type Number **/ this.today = (new Date(date.getFullYear(), date.getMonth(), date.getDate())).getTime()/1000; /** * Yesterday timestamp * * @type Number **/ this.yesterday = this.today - 86400; utc = this.options.UTCDate ? 'UTC' : ''; this.getHours = 'get'+utc+'Hours'; this.getMinutes = 'get'+utc+'Minutes'; this.getSeconds = 'get'+utc+'Seconds'; this.getDate = 'get'+utc+'Date'; this.getDay = 'get'+utc+'Day'; this.getMonth = 'get'+utc+'Month'; this.getFullYear = 'get'+utc+'FullYear'; /** * Css classes * * @type String **/ this.cssClass = 'ui-helper-reset ui-helper-clearfix ui-widget ui-widget-content ui-corner-all elfinder elfinder-'+(this.direction == 'rtl' ? 'rtl' : 'ltr')+' '+this.options.cssClass; /** * Method to store/fetch data * * @type Function **/ this.storage = (function() { try { return 'localStorage' in window && window['localStorage'] !== null ? self.localStorage : self.cookie; } catch (e) { return self.cookie; } })(); this.viewType = this.storage('view') || this.options.defaultView || 'icons'; this.sortType = this.storage('sortType') || this.options.sortType || 'name'; this.sortOrder = this.storage('sortOrder') || this.options.sortOrder || 'asc'; this.sortStickFolders = this.storage('sortStickFolders'); if (this.sortStickFolders === null) { this.sortStickFolders = !!this.options.sortStickFolders; } else { this.sortStickFolders = !!this.sortStickFolders } this.sortRules = $.extend(true, {}, this._sortRules, this.options.sortsRules); $.each(this.sortRules, function(name, method) { if (typeof method != 'function') { delete self.sortRules[name]; } }); this.compare = $.proxy(this.compare, this); /** * Delay in ms before open notification dialog * * @type Number * @default 500 **/ this.notifyDelay = this.options.notifyDelay > 0 ? parseInt(this.options.notifyDelay) : 500; /** * Base draggable options * * @type Object **/ this.draggable = { appendTo : 'body', addClasses : true, delay : 30, distance : 8, revert : true, refreshPositions : true, cursor : 'move', cursorAt : {left : 50, top : 47}, drag : function(e, ui) { if (! ui.helper.data('locked')) { ui.helper.toggleClass('elfinder-drag-helper-plus', e.shiftKey||e.ctrlKey||e.metaKey); } }, start : function(e, ui) { var targets = $.map(ui.helper.data('files')||[], function(h) { return h || null ;}), cnt, h; cnt = targets.length; while (cnt--) { h = targets[cnt]; if (files[h].locked) { ui.helper.addClass('elfinder-drag-helper-plus').data('locked', true); break; } } }, stop : function() { self.trigger('focus').trigger('dragstop'); }, helper : function(e, ui) { var element = this.id ? $(this) : $(this).parents('[id]:first'), helper = $('<div class="elfinder-drag-helper"><span class="elfinder-drag-helper-icon-plus"/></div>'), icon = function(mime) { return '<div class="elfinder-cwd-icon '+self.mime2class(mime)+' ui-corner-all"/>'; }, hashes, l; self.trigger('dragstart', {target : element[0], originalEvent : e}); hashes = element.is('.'+self.res('class', 'cwdfile')) ? self.selected() : [self.navId2Hash(element.attr('id'))]; helper.append(icon(files[hashes[0]].mime)).data('files', hashes).data('locked', false); if ((l = hashes.length) > 1) { helper.append(icon(files[hashes[l-1]].mime) + '<span class="elfinder-drag-num">'+l+'</span>'); } return helper; } }; /** * Base droppable options * * @type Object **/ this.droppable = { // greedy : true, tolerance : 'pointer', accept : '.elfinder-cwd-file-wrapper,.elfinder-navbar-dir,.elfinder-cwd-file', hoverClass : this.res('class', 'adroppable'), drop : function(e, ui) { var dst = $(this), targets = $.map(ui.helper.data('files')||[], function(h) { return h || null }), result = [], c = 'class', cnt, hash, i, h; if (dst.is('.'+self.res(c, 'cwd'))) { hash = cwd; } else if (dst.is('.'+self.res(c, 'cwdfile'))) { hash = dst.attr('id'); } else if (dst.is('.'+self.res(c, 'navdir'))) { hash = self.navId2Hash(dst.attr('id')); } cnt = targets.length; while (cnt--) { h = targets[cnt]; // ignore drop into itself or in own location h != hash && files[h].phash != hash && result.push(h); } if (result.length) { ui.helper.hide(); self.clipboard(result, !(e.ctrlKey||e.shiftKey||e.metaKey||ui.helper.data('locked'))); self.exec('paste', hash); self.trigger('drop', {files : targets}); } } }; /** * Return true if filemanager is active * * @return Boolean **/ this.enabled = function() { return node.is(':visible') && enabled; } /** * Return true if filemanager is visible * * @return Boolean **/ this.visible = function() { return node.is(':visible'); } /** * Return root dir hash for current working directory * * @return String */ this.root = function(hash) { var dir = files[hash || cwd], i; while (dir && dir.phash) { dir = files[dir.phash] } if (dir) { return dir.hash; } while (i in files && files.hasOwnProperty(i)) { dir = files[i] if (!dir.phash && !dir.mime == 'directory' && dir.read) { return dir.hash } } return ''; } /** * Return current working directory info * * @return Object */ this.cwd = function() { return files[cwd] || {}; } /** * Return required cwd option * * @param String option name * @return mixed */ this.option = function(name) { return cwdOptions[name]||''; } /** * Return file data from current dir or tree by it's hash * * @param String file hash * @return Object */ this.file = function(hash) { return files[hash]; }; /** * Return all cached files * * @return Array */ this.files = function() { return $.extend(true, {}, files); } /** * Return list of file parents hashes include file hash * * @param String file hash * @return Array */ this.parents = function(hash) { var parents = [], dir; while ((dir = this.file(hash))) { parents.unshift(dir.hash); hash = dir.phash; } return parents; } this.path2array = function(hash, i18) { var file, path = []; while (hash && (file = files[hash]) && file.hash) { path.unshift(i18 && file.i18 ? file.i18 : file.name); hash = file.phash; } return path; } /** * Return file path * * @param Object file * @return String */ this.path = function(hash, i18) { return files[hash] && files[hash].path ? files[hash].path : this.path2array(hash, i18).join(cwdOptions.separator); } /** * Return file url if set * * @param Object file * @return String */ this.url = function(hash) { var file = files[hash]; if (!file || !file.read) { return ''; } if (file.url == '1') { this.request({ data : {cmd : 'url', target : hash}, preventFail : true, options: {async: false} }) .done(function(data) { file.url = data.url || ''; }) .fail(function() { file.url = ''; }); } if (file.url) { return file.url; } if (cwdOptions.url) { return cwdOptions.url + $.map(this.path2array(hash), function(n) { return encodeURIComponent(n); }).slice(1).join('/') } var params = $.extend({}, this.customData, { cmd: 'file', target: file.hash }); if (this.oldAPI) { params.cmd = 'open'; params.current = file.phash; } return this.options.url + (this.options.url.indexOf('?') === -1 ? '?' : '&') + $.param(params, true); } /** * Return thumbnail url * * @param String file hash * @return String */ this.tmb = function(hash) { var file = files[hash], url = file && file.tmb && file.tmb != 1 ? cwdOptions['tmbUrl'] + file.tmb : ''; if (url && (this.UA.Opera || this.UA.IE)) { url += '?_=' + new Date().getTime(); } return url; } /** * Return selected files hashes * * @return Array **/ this.selected = function() { return selected.slice(0); } /** * Return selected files info * * @return Array */ this.selectedFiles = function() { return $.map(selected, function(hash) { return files[hash] ? $.extend({}, files[hash]) : null }); }; /** * Return true if file with required name existsin required folder * * @param String file name * @param String parent folder hash * @return Boolean */ this.fileByName = function(name, phash) { var hash; for (hash in files) { if (files.hasOwnProperty(hash) && files[hash].phash == phash && files[hash].name == name) { return files[hash]; } } }; /** * Valid data for required command based on rules * * @param String command name * @param Object cammand's data * @return Boolean */ this.validResponse = function(cmd, data) { return data.error || this.rules[this.rules[cmd] ? cmd : 'defaults'](data); } /** * Return bytes from ini formated size * * @param String ini formated size * @return Integer */ this.returnBytes = function(val) { if (val == '-1') val = 0; if (val) { // for ex. 1mb, 1KB val = val.replace(/b$/i, ''); var last = val.charAt(val.length - 1).toLowerCase(); val = val.replace(/[gmk]$/i, ''); if (last == 'g') { val = val * 1024 * 1024 * 1024; } else if (last == 'm') { val = val * 1024 * 1024; } else if (last == 'k') { val = val * 1024; } } return val; }; /** * Proccess ajax request. * Fired events : * @todo * @example * @todo * @return $.Deferred */ this.request = function(options) { var self = this, o = this.options, dfrd = $.Deferred(), // request data data = $.extend({}, o.customData, {mimes : o.onlyMimes}, options.data || options), // command name cmd = data.cmd, // call default fail callback (display error dialog) ? deffail = !(options.preventDefault || options.preventFail), // call default success callback ? defdone = !(options.preventDefault || options.preventDone), // options for notify dialog notify = $.extend({}, options.notify), // do not normalize data - return as is raw = !!options.raw, // sync files on request fail syncOnFail = options.syncOnFail, // open notify dialog timeout timeout, // request options options = $.extend({ url : o.url, async : true, type : this.requestType, dataType : 'json', cache : false, // timeout : 100, data : data, headers : this.customHeaders, xhrFields: this.xhrFields }, options.options || {}), /** * Default success handler. * Call default data handlers and fire event with command name. * * @param Object normalized response data * @return void **/ done = function(data) { data.warning && self.error(data.warning); cmd == 'open' && open($.extend(true, {}, data)); // fire some event to update cache/ui data.removed && data.removed.length && self.remove(data); data.added && data.added.length && self.add(data); data.changed && data.changed.length && self.change(data); // fire event with command name self.trigger(cmd, data); // force update content data.sync && self.sync(); }, /** * Request error handler. Reject dfrd with correct error message. * * @param jqxhr request object * @param String request status * @return void **/ error = function(xhr, status) { var error; switch (status) { case 'abort': error = xhr.quiet ? '' : ['errConnect', 'errAbort']; break; case 'timeout': error = ['errConnect', 'errTimeout']; break; case 'parsererror': error = ['errResponse', 'errDataNotJSON']; break; default: if (xhr.status == 403) { error = ['errConnect', 'errAccess']; } else if (xhr.status == 404) { error = ['errConnect', 'errNotFound']; } else { error = 'errConnect'; } } dfrd.reject(error, xhr, status); }, /** * Request success handler. Valid response data and reject/resolve dfrd. * * @param Object response data * @param String request status * @return void **/ success = function(response) { if (raw) { return dfrd.resolve(response); } if (!response) { return dfrd.reject(['errResponse', 'errDataEmpty'], xhr); } else if (!$.isPlainObject(response)) { return dfrd.reject(['errResponse', 'errDataNotJSON'], xhr); } else if (response.error) { return dfrd.reject(response.error, xhr); } else if (!self.validResponse(cmd, response)) { return dfrd.reject('errResponse', xhr); } response = self.normalize(response); if (!self.api) { self.api = response.api || 1; self.newAPI = self.api >= 2; self.oldAPI = !self.newAPI; } if (response.options) { cwdOptions = $.extend({}, cwdOptions, response.options); } if (response.netDrivers) { self.netDrivers = response.netDrivers; } if (cmd == 'open' && !!data.init) { self.uplMaxSize = self.returnBytes(response.uplMaxSize); self.uplMaxFile = !!response.uplMaxFile? parseInt(response.uplMaxFile) : 20; } dfrd.resolve(response); response.debug && self.debug('backend-debug', response.debug); }, xhr, _xhr ; defdone && dfrd.done(done); dfrd.fail(function(error) { if (error) { deffail ? self.error(error) : self.debug('error', self.i18n(error)); } }) if (!cmd) { return dfrd.reject('errCmdReq'); } if (syncOnFail) { dfrd.fail(function(error) { error && self.sync(); }); } if (notify.type && notify.cnt) { timeout = setTimeout(function() { self.notify(notify); dfrd.always(function() { notify.cnt = -(parseInt(notify.cnt)||0); self.notify(notify); }) }, self.notifyDelay) dfrd.always(function() { clearTimeout(timeout); }); } // quiet abort not completed "open" requests if (cmd == 'open') { while ((_xhr = queue.pop())) { if (_xhr.state() == 'pending') { _xhr.quiet = true; _xhr.abort(); } } } delete options.preventFail xhr = this.transport.send(options).fail(error).done(success); // this.transport.send(options) // add "open" xhr into queue if (cmd == 'open') { queue.unshift(xhr); dfrd.always(function() { var ndx = $.inArray(xhr, queue); ndx !== -1 && queue.splice(ndx, 1); }); } return dfrd; }; /** * Compare current files cache with new files and return diff * * @param Array new files * @return Object */ this.diff = function(incoming) { var raw = {}, added = [], removed = [], changed = [], isChanged = function(hash) { var l = changed.length; while (l--) { if (changed[l].hash == hash) { return true; } } }; $.each(incoming, function(i, f) { raw[f.hash] = f; }); // find removed $.each(files, function(hash, f) { !raw[hash] && removed.push(hash); }); // compare files $.each(raw, function(hash, file) { var origin = files[hash]; if (!origin) { added.push(file); } else { $.each(file, function(prop) { if (file[prop] != origin[prop]) { changed.push(file) return false; } }); } }); // parents of removed dirs mark as changed (required for tree correct work) $.each(removed, function(i, hash) { var file = files[hash], phash = file.phash; if (phash && file.mime == 'directory' && $.inArray(phash, removed) === -1 && raw[phash] && !isChanged(phash)) { changed.push(raw[phash]); } }); return { added : added, removed : removed, changed : changed }; } /** * Sync content * * @return jQuery.Deferred */ this.sync = function() { var self = this, dfrd = $.Deferred().done(function() { self.trigger('sync'); }), opts1 = { data : {cmd : 'open', init : 1, target : cwd, tree : this.ui.tree ? 1 : 0}, preventDefault : true }, opts2 = { data : {cmd : 'tree', target : (cwd == this.root())? cwd : this.file(cwd).phash}, preventDefault : true }; $.when( this.request(opts1), this.request(opts2) ) .fail(function(error) { dfrd.reject(error); error && self.request({ data : {cmd : 'open', target : self.lastDir(''), tree : 1, init : 1}, notify : {type : 'open', cnt : 1, hideCnt : true}, preventDefault : true }); }) .done(function(odata, pdata) { var diff = self.diff(odata.files.concat(pdata && pdata.tree ? pdata.tree : [])); diff.added.push(odata.cwd) diff.removed.length && self.remove(diff); diff.added.length && self.add(diff); diff.changed.length && self.change(diff); return dfrd.resolve(diff); }); return dfrd; } this.upload = function(files) { return this.transport.upload(files, this); } /** * Attach listener to events * To bind to multiply events at once, separate events names by space * * @param String event(s) name(s) * @param Object event handler * @return elFinder */ this.bind = function(event, callback) { var i; if (typeof(callback) == 'function') { event = ('' + event).toLowerCase().split(/\s+/); for (i = 0; i < event.length; i++) { if (listeners[event[i]] === void(0)) { listeners[event[i]] = []; } listeners[event[i]].push(callback); } } return this; }; /** * Remove event listener if exists * * @param String event name * @param Function callback * @return elFinder */ this.unbind = function(event, callback) { var l = listeners[('' + event).toLowerCase()] || [], i = l.indexOf(callback); i > -1 && l.splice(i, 1); //delete callback; // need this? callback = null return this; }; /** * Fire event - send notification to all event listeners * * @param String event type * @param Object data to send across event * @return elFinder */ this.trigger = function(event, data) { var event = event.toLowerCase(), handlers = listeners[event] || [], i, j; this.debug('event-'+event, data) if (handlers.length) { event = $.Event(event); for (i = 0; i < handlers.length; i++) { // to avoid data modifications. remember about "sharing" passing arguments in js :) event.data = $.extend(true, {}, data); try { if (handlers[i](event, this) === false || event.isDefaultPrevented()) { this.debug('event-stoped', event.type); break; } } catch (ex) { window.console && window.console.log && window.console.log(ex); } } } return this; } /** * Bind keybord shortcut to keydown event * * @example * elfinder.shortcut({ * pattern : 'ctrl+a', * description : 'Select all files', * callback : function(e) { ... }, * keypress : true|false (bind to keypress instead of keydown) * }) * * @param Object shortcut config * @return elFinder */ this.shortcut = function(s) { var patterns, pattern, code, i, parts; if (this.options.allowShortcuts && s.pattern && $.isFunction(s.callback)) { patterns = s.pattern.toUpperCase().split(/\s+/); for (i= 0; i < patterns.length; i++) { pattern = patterns[i] parts = pattern.split('+'); code = (code = parts.pop()).length == 1 ? code > 0 ? code : code.charCodeAt(0) : $.ui.keyCode[code]; if (code && !shortcuts[pattern]) { shortcuts[pattern] = { keyCode : code, altKey : $.inArray('ALT', parts) != -1, ctrlKey : $.inArray('CTRL', parts) != -1, shiftKey : $.inArray('SHIFT', parts) != -1, type : s.type || 'keydown', callback : s.callback, description : s.description, pattern : pattern }; } } } return this; } /** * Registered shortcuts * * @type Object **/ this.shortcuts = function() { var ret = []; $.each(shortcuts, function(i, s) { ret.push([s.pattern, self.i18n(s.description)]); }); return ret; }; /** * Get/set clipboard content. * Return new clipboard content. * * @example * this.clipboard([]) - clean clipboard * this.clipboard([{...}, {...}], true) - put 2 files in clipboard and mark it as cutted * * @param Array new files hashes * @param Boolean cut files? * @return Array */ this.clipboard = function(hashes, cut) { var map = function() { return $.map(clipboard, function(f) { return f.hash }); } if (hashes !== void(0)) { clipboard.length && this.trigger('unlockfiles', {files : map()}); remember = []; clipboard = $.map(hashes||[], function(hash) { var file = files[hash]; if (file) { remember.push(hash); return { hash : hash, phash : file.phash, name : file.name, mime : file.mime, read : file.read, locked : file.locked, cut : !!cut } } return null; }); this.trigger('changeclipboard', {clipboard : clipboard.slice(0, clipboard.length)}); cut && this.trigger('lockfiles', {files : map()}); } // return copy of clipboard instead of refrence return clipboard.slice(0, clipboard.length); } /** * Return true if command enabled * * @param String command name * @return Boolean */ this.isCommandEnabled = function(name) { return this._commands[name] ? $.inArray(name, cwdOptions.disabled) === -1 : false; } /** * Exec command and return result; * * @param String command name * @param String|Array usualy files hashes * @param String|Array command options * @return $.Deferred */ this.exec = function(cmd, files, opts) { return this._commands[cmd] && this.isCommandEnabled(cmd) ? this._commands[cmd].exec(files, opts) : $.Deferred().reject('No such command'); } /** * Create and return dialog. * * @param String|DOMElement dialog content * @param Object dialog options * @return jQuery */ this.dialog = function(content, options) { return $('<div/>').append(content).appendTo(node).elfinderdialog(options); } /** * Return UI widget or node * * @param String ui name * @return jQuery */ this.getUI = function(ui) { return this.ui[ui] || node; } this.command = function(name) { return name === void(0) ? this._commands : this._commands[name]; } /** * Resize elfinder node * * @param String|Number width * @param Number height * @return void */ this.resize = function(w, h) { node.css('width', w).height(h).trigger('resize'); this.trigger('resize', {width : node.width(), height : node.height()}); } /** * Restore elfinder node size * * @return elFinder */ this.restoreSize = function() { this.resize(width, height); } this.show = function() { node.show(); this.enable().trigger('show'); } this.hide = function() { this.disable().trigger('hide'); node.hide(); } /** * Destroy this elFinder instance * * @return void **/ this.destroy = function() { if (node && node[0].elfinder) { this.trigger('destroy').disable(); listeners = {}; shortcuts = {}; $(document).add(node).unbind('.'+this.namespace); self.trigger = function() { } node.children().remove(); node.append(prevContent.contents()).removeClass(this.cssClass).attr('style', prevStyle); node[0].elfinder = null; if (syncInterval) { clearInterval(syncInterval); } } } /************* init stuffs ****************/ // check jquery ui if (!($.fn.selectable && $.fn.draggable && $.fn.droppable)) { return alert(this.i18n('errJqui')); } // check node if (!node.length) { return alert(this.i18n('errNode')); } // check connector url if (!this.options.url) { return alert(this.i18n('errURL')); } $.extend($.ui.keyCode, { 'F1' : 112, 'F2' : 113, 'F3' : 114, 'F4' : 115, 'F5' : 116, 'F6' : 117, 'F7' : 118, 'F8' : 119, 'F9' : 120 }); this.dragUpload = false; this.xhrUpload = (typeof XMLHttpRequestUpload != 'undefined' || typeof XMLHttpRequestEventTarget != 'undefined') && typeof File != 'undefined' && typeof FormData != 'undefined'; // configure transport object this.transport = {} if (typeof(this.options.transport) == 'object') { this.transport = this.options.transport; if (typeof(this.transport.init) == 'function') { this.transport.init(this) } } if (typeof(this.transport.send) != 'function') { this.transport.send = function(opts) { return $.ajax(opts); } } if (this.transport.upload == 'iframe') { this.transport.upload = $.proxy(this.uploads.iframe, this); } else if (typeof(this.transport.upload) == 'function') { this.dragUpload = !!this.options.dragUploadAllow; } else if (this.xhrUpload && !!this.options.dragUploadAllow) { this.transport.upload = $.proxy(this.uploads.xhr, this); this.dragUpload = true; } else { this.transport.upload = $.proxy(this.uploads.iframe, this); } /** * Alias for this.trigger('error', {error : 'message'}) * * @param String error message * @return elFinder **/ this.error = function() { var arg = arguments[0]; return arguments.length == 1 && typeof(arg) == 'function' ? self.bind('error', arg) : self.trigger('error', {error : arg}); } // create bind/trigger aliases for build-in events $.each(['enable', 'disable', 'load', 'open', 'reload', 'select', 'add', 'remove', 'change', 'dblclick', 'getfile', 'lockfiles', 'unlockfiles', 'dragstart', 'dragstop', 'search', 'searchend', 'viewchange'], function(i, name) { self[name] = function() { var arg = arguments[0]; return arguments.length == 1 && typeof(arg) == 'function' ? self.bind(name, arg) : self.trigger(name, $.isPlainObject(arg) ? arg : {}); } }); // bind core event handlers this .enable(function() { if (!enabled && self.visible() && self.ui.overlay.is(':hidden')) { enabled = true; $('texarea:focus,input:focus,button').blur(); node.removeClass('elfinder-disabled'); } }) .disable(function() { prevEnabled = enabled; enabled = false; node.addClass('elfinder-disabled'); }) .open(function() { selected = []; }) .select(function(e) { selected = $.map(e.data.selected || e.data.value|| [], function(hash) { return files[hash] ? hash : null; }); }) .error(function(e) { var opts = { cssClass : 'elfinder-dialog-error', title : self.i18n(self.i18n('error')), resizable : false, destroyOnClose : true, buttons : {} }; opts.buttons[self.i18n(self.i18n('btnClose'))] = function() { $(this).elfinderdialog('close'); }; self.dialog('<span class="elfinder-dialog-icon elfinder-dialog-icon-error"/>'+self.i18n(e.data.error), opts); }) .bind('tree parents', function(e) { cache(e.data.tree || []); }) .bind('tmb', function(e) { $.each(e.data.images||[], function(hash, tmb) { if (files[hash]) { files[hash].tmb = tmb; } }) }) .add(function(e) { cache(e.data.added||[]); }) .change(function(e) { $.each(e.data.changed||[], function(i, file) { var hash = file.hash; if ((files[hash].width && !file.width) || (files[hash].height && !file.height)) { files[hash].width = undefined; files[hash].height = undefined; } files[hash] = files[hash] ? $.extend(files[hash], file) : file; }); }) .remove(function(e) { var removed = e.data.removed||[], l = removed.length, rm = function(hash) { var file = files[hash]; if (file) { if (file.mime == 'directory' && file.dirs) { $.each(files, function(h, f) { f.phash == hash && rm(h); }); } delete files[hash]; } }; while (l--) { rm(removed[l]); } }) .bind('search', function(e) { cache(e.data.files); }) .bind('rm', function(e) { var play = beeper.canPlayType && beeper.canPlayType('audio/wav; codecs="1"'); play && play != '' && play != 'no' && $(beeper).html('<source src="./sounds/rm.wav" type="audio/wav">')[0].play() }) ; // bind external event handlers $.each(this.options.handlers, function(event, callback) { self.bind(event, callback); }); /** * History object. Store visited folders * * @type Object **/ this.history = new this.history(this); // in getFileCallback set - change default actions on double click/enter/ctrl+enter if (typeof(this.options.getFileCallback) == 'function' && this.commands.getfile) { this.bind('dblclick', function(e) { e.preventDefault(); self.exec('getfile').fail(function() { self.exec('open'); }); }); this.shortcut({ pattern : 'enter', description : this.i18n('cmdgetfile'), callback : function() { self.exec('getfile').fail(function() { self.exec(self.OS == 'mac' ? 'rename' : 'open') }) } }) .shortcut({ pattern : 'ctrl+enter', description : this.i18n(this.OS == 'mac' ? 'cmdrename' : 'cmdopen'), callback : function() { self.exec(self.OS == 'mac' ? 'rename' : 'open') } }); } /** * Loaded commands * * @type Object **/ this._commands = {}; if (!$.isArray(this.options.commands)) { this.options.commands = []; } // check required commands $.each(['open', 'reload', 'back', 'forward', 'up', 'home', 'info', 'quicklook', 'getfile', 'help'], function(i, cmd) { $.inArray(cmd, self.options.commands) === -1 && self.options.commands.push(cmd); }); // load commands $.each(this.options.commands, function(i, name) { var cmd = self.commands[name]; if ($.isFunction(cmd) && !self._commands[name]) { cmd.prototype = base; self._commands[name] = new cmd(); self._commands[name].setup(name, self.options.commandsOptions[name]||{}); } }); // prepare node node.addClass(this.cssClass) .bind(mousedown, function() { !enabled && self.enable(); }); /** * UI nodes * * @type Object **/ this.ui = { // container for nav panel and current folder container workzone : $('<div/>').appendTo(node).elfinderworkzone(this), // container for folders tree / places navbar : $('<div/>').appendTo(node).elfindernavbar(this, this.options.uiOptions.navbar || {}), // contextmenu contextmenu : $('<div/>').appendTo(node).elfindercontextmenu(this), // overlay overlay : $('<div/>').appendTo(node).elfinderoverlay({ show : function() { self.disable(); }, hide : function() { prevEnabled && self.enable(); } }), // current folder container cwd : $('<div/>').appendTo(node).elfindercwd(this, this.options.uiOptions.cwd || {}), // notification dialog window notify : this.dialog('', { cssClass : 'elfinder-dialog-notify', position : {top : '12px', right : '12px'}, resizable : false, autoOpen : false, title : '&nbsp;', width : 280 }), statusbar : $('<div class="ui-widget-header ui-helper-clearfix ui-corner-bottom elfinder-statusbar"/>').hide().appendTo(node) } // load required ui $.each(this.options.ui || [], function(i, ui) { var name = 'elfinder'+ui, opts = self.options.uiOptions[ui] || {}; if (!self.ui[ui] && $.fn[name]) { self.ui[ui] = $('<'+(opts.tag || 'div')+'/>').appendTo(node)[name](self, opts); } }); // store instance in node node[0].elfinder = this; // make node resizable this.options.resizable && !this.UA.Touch && $.fn.resizable && node.resizable({ handles : 'se', minWidth : 300, minHeight : 200 }); if (this.options.width) { width = this.options.width; } if (this.options.height) { height = parseInt(this.options.height); } // update size self.resize(width, height); // attach events to document $(document) // disable elfinder on click outside elfinder .bind('click.'+this.namespace, function(e) { enabled && !$(e.target).closest(node).length && self.disable(); }) // exec shortcuts .bind(keydown+' '+keypress, execShortcut); // attach events to window self.options.useBrowserHistory && $(window) .on('popstate', function(ev) { var target = ev.originalEvent.state && ev.originalEvent.state.thash; target && !$.isEmptyObject(self.files()) && self.request({ data : {cmd : 'open', target : target, onhistory : 1}, notify : {type : 'open', cnt : 1, hideCnt : true}, syncOnFail : true }); }); // send initial request and start to pray >_< this.trigger('init') .request({ data : {cmd : 'open', target : self.startDir(), init : 1, tree : this.ui.tree ? 1 : 0}, preventDone : true, notify : {type : 'open', cnt : 1, hideCnt : true}, freeze : true }) .fail(function() { self.trigger('fail').disable().lastDir(''); listeners = {}; shortcuts = {}; $(document).add(node).unbind('.'+this.namespace); self.trigger = function() { }; }) .done(function(data) { self.load().debug('api', self.api); data = $.extend(true, {}, data); open(data); self.trigger('open', data); }); // update ui's size after init this.one('load', function() { node.trigger('resize'); if (self.options.sync > 1000) { syncInterval = setInterval(function() { self.sync(); }, self.options.sync) } }); // self.timeEnd('load'); } /** * Prototype * * @type Object */ elFinder.prototype = { res : function(type, id) { return this.resources[type] && this.resources[type][id]; }, /** * Internationalization object * * @type Object */ i18 : { en : { translator : '', language : 'English', direction : 'ltr', dateFormat : 'd.m.Y H:i', fancyDateFormat : '$1 H:i', messages : {} }, months : ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], monthsShort : ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], days : ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], daysShort : ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] }, /** * File mimetype to kind mapping * * @type Object */ kinds : { 'unknown' : 'Unknown', 'directory' : 'Folder', 'symlink' : 'Alias', 'symlink-broken' : 'AliasBroken', 'application/x-empty' : 'TextPlain', 'application/postscript' : 'Postscript', 'application/vnd.ms-office' : 'MsOffice', 'application/vnd.ms-word' : 'MsWord', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' : 'MsWord', 'application/vnd.ms-word.document.macroEnabled.12' : 'MsWord', 'application/vnd.openxmlformats-officedocument.wordprocessingml.template' : 'MsWord', 'application/vnd.ms-word.template.macroEnabled.12' : 'MsWord', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' : 'MsWord', 'application/vnd.ms-excel' : 'MsExcel', 'application/vnd.ms-excel.sheet.macroEnabled.12' : 'MsExcel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.template' : 'MsExcel', 'application/vnd.ms-excel.template.macroEnabled.12' : 'MsExcel', 'application/vnd.ms-excel.sheet.binary.macroEnabled.12' : 'MsExcel', 'application/vnd.ms-excel.addin.macroEnabled.12' : 'MsExcel', 'application/vnd.ms-powerpoint' : 'MsPP', 'application/vnd.openxmlformats-officedocument.presentationml.presentation' : 'MsPP', 'application/vnd.ms-powerpoint.presentation.macroEnabled.12' : 'MsPP', 'application/vnd.openxmlformats-officedocument.presentationml.slideshow' : 'MsPP', 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12' : 'MsPP', 'application/vnd.openxmlformats-officedocument.presentationml.template' : 'MsPP', 'application/vnd.ms-powerpoint.template.macroEnabled.12' : 'MsPP', 'application/vnd.ms-powerpoint.addin.macroEnabled.12' : 'MsPP', 'application/vnd.openxmlformats-officedocument.presentationml.slide' : 'MsPP', 'application/vnd.ms-powerpoint.slide.macroEnabled.12' : 'MsPP', 'application/pdf' : 'PDF', 'application/xml' : 'XML', 'application/vnd.oasis.opendocument.text' : 'OO', 'application/vnd.oasis.opendocument.text-template' : 'OO', 'application/vnd.oasis.opendocument.text-web' : 'OO', 'application/vnd.oasis.opendocument.text-master' : 'OO', 'application/vnd.oasis.opendocument.graphics' : 'OO', 'application/vnd.oasis.opendocument.graphics-template' : 'OO', 'application/vnd.oasis.opendocument.presentation' : 'OO', 'application/vnd.oasis.opendocument.presentation-template' : 'OO', 'application/vnd.oasis.opendocument.spreadsheet' : 'OO', 'application/vnd.oasis.opendocument.spreadsheet-template' : 'OO', 'application/vnd.oasis.opendocument.chart' : 'OO', 'application/vnd.oasis.opendocument.formula' : 'OO', 'application/vnd.oasis.opendocument.database' : 'OO', 'application/vnd.oasis.opendocument.image' : 'OO', 'application/vnd.openofficeorg.extension' : 'OO', 'application/x-shockwave-flash' : 'AppFlash', 'application/flash-video' : 'Flash video', 'application/x-bittorrent' : 'Torrent', 'application/javascript' : 'JS', 'application/rtf' : 'RTF', 'application/rtfd' : 'RTF', 'application/x-font-ttf' : 'TTF', 'application/x-font-otf' : 'OTF', 'application/x-rpm' : 'RPM', 'application/x-web-config' : 'TextPlain', 'application/xhtml+xml' : 'HTML', 'application/docbook+xml' : 'DOCBOOK', 'application/x-awk' : 'AWK', 'application/x-gzip' : 'GZIP', 'application/x-bzip2' : 'BZIP', 'application/zip' : 'ZIP', 'application/x-zip' : 'ZIP', 'application/x-rar' : 'RAR', 'application/x-tar' : 'TAR', 'application/x-7z-compressed' : '7z', 'application/x-jar' : 'JAR', 'text/plain' : 'TextPlain', 'text/x-php' : 'PHP', 'text/html' : 'HTML', 'text/javascript' : 'JS', 'text/css' : 'CSS', 'text/rtf' : 'RTF', 'text/rtfd' : 'RTF', 'text/x-c' : 'C', 'text/x-csrc' : 'C', 'text/x-chdr' : 'CHeader', 'text/x-c++' : 'CPP', 'text/x-c++src' : 'CPP', 'text/x-c++hdr' : 'CPPHeader', 'text/x-shellscript' : 'Shell', 'application/x-csh' : 'Shell', 'text/x-python' : 'Python', 'text/x-java' : 'Java', 'text/x-java-source' : 'Java', 'text/x-ruby' : 'Ruby', 'text/x-perl' : 'Perl', 'text/x-sql' : 'SQL', 'text/xml' : 'XML', 'text/x-comma-separated-values' : 'CSV', 'image/x-ms-bmp' : 'BMP', 'image/jpeg' : 'JPEG', 'image/gif' : 'GIF', 'image/png' : 'PNG', 'image/tiff' : 'TIFF', 'image/x-targa' : 'TGA', 'image/vnd.adobe.photoshop' : 'PSD', 'image/xbm' : 'XBITMAP', 'image/pxm' : 'PXM', 'audio/mpeg' : 'AudioMPEG', 'audio/midi' : 'AudioMIDI', 'audio/ogg' : 'AudioOGG', 'audio/mp4' : 'AudioMPEG4', 'audio/x-m4a' : 'AudioMPEG4', 'audio/wav' : 'AudioWAV', 'audio/x-mp3-playlist' : 'AudioPlaylist', 'video/x-dv' : 'VideoDV', 'video/mp4' : 'VideoMPEG4', 'video/mpeg' : 'VideoMPEG', 'video/x-msvideo' : 'VideoAVI', 'video/quicktime' : 'VideoMOV', 'video/x-ms-wmv' : 'VideoWM', 'video/x-flv' : 'VideoFlash', 'video/x-matroska' : 'VideoMKV', 'video/ogg' : 'VideoOGG' }, /** * Ajax request data validation rules * * @type Object */ rules : { defaults : function(data) { if (!data || (data.added && !$.isArray(data.added)) || (data.removed && !$.isArray(data.removed)) || (data.changed && !$.isArray(data.changed))) { return false; } return true; }, open : function(data) { return data && data.cwd && data.files && $.isPlainObject(data.cwd) && $.isArray(data.files); }, tree : function(data) { return data && data.tree && $.isArray(data.tree); }, parents : function(data) { return data && data.tree && $.isArray(data.tree); }, tmb : function(data) { return data && data.images && ($.isPlainObject(data.images) || $.isArray(data.images)); }, upload : function(data) { return data && ($.isPlainObject(data.added) || $.isArray(data.added));}, search : function(data) { return data && data.files && $.isArray(data.files)} }, /** * Commands costructors * * @type Object */ commands : {}, parseUploadData : function(text) { var data; if (!$.trim(text)) { return {error : ['errResponse', 'errDataEmpty']}; } try { data = $.parseJSON(text); } catch (e) { return {error : ['errResponse', 'errDataNotJSON']}; } if (!this.validResponse('upload', data)) { return {error : ['errResponse']}; } data = this.normalize(data); data.removed = $.merge((data.removed || []), $.map(data.added||[], function(f) { return f.hash; })); return data; }, iframeCnt : 0, uploads : { // check droped contents checkFile : function(data, fm) { if (!!data.checked || data.type == 'files') { return data.files; } else if (data.type == 'data') { var dfrd = $.Deferred(), files = [], paths = [], dirctorys = [], entries = [], processing = 0, readEntries = function(dirReader) { var toArray = function(list) { return Array.prototype.slice.call(list || []); }; var readFile = function(fileEntry, callback) { var dfrd = $.Deferred(); if (typeof fileEntry == 'undefined') { dfrd.reject('empty'); } else if (fileEntry.isFile) { fileEntry.file(function (file) { dfrd.resolve(file); }, function(e){ dfrd.reject(); }); } else { dfrd.reject('dirctory'); } return dfrd.promise(); }; dirReader.readEntries(function (results) { if (!results.length) { var len = entries.length - 1; var read = function(i) { readFile(entries[i]).done(function(file){ if (! (fm.OS == 'win' && file.name.match(/^(?:desktop\.ini|thumbs\.db)$/i)) && ! (fm.OS == 'mac' && file.name.match(/^\.ds_store$/i))) { paths.push(entries[i].fullPath); files.push(file); } }).fail(function(e){ if (e == 'dirctory') { // dirctory dirctorys.push(entries[i]); } else if (e == 'empty') { // dirctory is empty } else { // why fail? } }).always(function(){ processing--; if (i < len) { processing++; read(++i); } }); }; processing++; read(0); processing--; } else { entries = entries.concat(toArray(results)); readEntries(dirReader); } }); }, doScan = function(items, isEntry) { var dirReader, entry; entries = []; var length = items.length; for (var i = 0; i < length; i++) { if (! isEntry) { entry = !!items[i].getAsEntry? items[i].getAsEntry() : items[i].webkitGetAsEntry(); } else { entry = items[i]; } if (entry) { if (entry.isFile) { paths.push(''); files.push(data.files.items[i].getAsFile()); } else if (entry.isDirectory) { if (processing > 0) { dirctorys.push(entry); } else { processing = 0; dirReader = entry.createReader(); processing++; readEntries(dirReader); } } } } }; doScan(data.files.items); setTimeout(function wait() { if (processing > 0) { setTimeout(wait, 10); } else { if (dirctorys.length > 0) { doScan([dirctorys.shift()], true); setTimeout(wait, 10); } else { dfrd.resolve([files, paths]); } } }, 10); return dfrd.promise(); } else { var ret = []; var check = []; var str = data.files[0]; if (data.type == 'html') { var tmp = $("<html/>").append($.parseHTML(str)); $('img[src]', tmp).each(function(){ var url, purl, self = $(this), pa = self.closest('a'); if (pa && pa.attr('href') && pa.attr('href').match(/\.(?:jpe?g|gif|bmp|png)/i)) { purl = pa.attr('href'); } url = self.attr('src'); if (url) { if (purl) { $.inArray(purl, ret) == -1 && ret.push(purl); $.inArray(url, check) == -1 && check.push(url); } else { $.inArray(url, ret) == -1 && ret.push(url); } } }); $('a[href]', tmp).each(function(){ var loc, parseUrl = function(url) { var a = document.createElement('a'); a.href = url; return a; }; if ($(this).text()) { loc = parseUrl($(this).attr('href')); if (loc.href && ! loc.pathname.match(/(?:\.html?|\/[^\/.]*)$/i)) { if ($.inArray(loc.href, ret) == -1 && $.inArray(loc.href, check) == -1) ret.push(loc.href); } } }); } else { var regex, m, url; regex = /(http[^<>"{}|\\^\[\]`\s]+)/ig; while (m = regex.exec(str)) { url = m[1].replace(/&amp;/g, '&'); if ($.inArray(url, ret) == -1) ret.push(url); } } return ret; } }, // upload transport using iframe iframe : function(data, fm) { var self = fm ? fm : this, input = data.input? data.input : false, files = !input ? self.uploads.checkFile(data, self) : false, dfrd = $.Deferred() .fail(function(error) { error && self.error(error); }) .done(function(data) { data.warning && self.error(data.warning); data.removed && self.remove(data); data.added && self.add(data); data.changed && self.change(data); self.trigger('upload', data); data.sync && self.sync(); }), name = 'iframe-'+self.namespace+(++self.iframeCnt), form = $('<form action="'+self.uploadURL+'" method="post" enctype="multipart/form-data" encoding="multipart/form-data" target="'+name+'" style="display:none"><input type="hidden" name="cmd" value="upload" /></form>'), msie = this.UA.IE, // clear timeouts, close notification dialog, remove form/iframe onload = function() { abortto && clearTimeout(abortto); notifyto && clearTimeout(notifyto); notify && self.notify({type : 'upload', cnt : -cnt}); setTimeout(function() { msie && $('<iframe src="javascript:false;"/>').appendTo(form); form.remove(); iframe.remove(); }, 100); }, iframe = $('<iframe src="'+(msie ? 'javascript:false;' : 'about:blank')+'" name="'+name+'" style="position:absolute;left:-1000px;top:-1000px" />') .bind('load', function() { iframe.unbind('load') .bind('load', function() { var data = self.parseUploadData(iframe.contents().text()); onload(); data.error ? dfrd.reject(data.error) : dfrd.resolve(data); }); // notify dialog notifyto = setTimeout(function() { notify = true; self.notify({type : 'upload', cnt : cnt}); }, self.options.notifyDelay); // emulate abort on timeout if (self.options.iframeTimeout > 0) { abortto = setTimeout(function() { onload(); dfrd.reject([errors.connect, errors.timeout]); }, self.options.iframeTimeout); } form.submit(); }), cnt, notify, notifyto, abortto ; if (files && files.length) { $.each(files, function(i, val) { form.append('<input type="hidden" name="upload[]" value="'+val+'"/>'); }); cnt = 1; } else if (input && $(input).is(':file') && $(input).val()) { form.append(input); cnt = input.files ? input.files.length : 1; } else { return dfrd.reject(); } form.append('<input type="hidden" name="'+(self.newAPI ? 'target' : 'current')+'" value="'+self.cwd().hash+'"/>') .append('<input type="hidden" name="html" value="1"/>') .append($(input).attr('name', 'upload[]')); $.each(self.options.onlyMimes||[], function(i, mime) { form.append('<input type="hidden" name="mimes[]" value="'+mime+'"/>'); }); $.each(self.options.customData, function(key, val) { form.append('<input type="hidden" name="'+key+'" value="'+val+'"/>'); }); form.appendTo('body'); iframe.appendTo('body'); return dfrd; }, // upload transport using XMLHttpRequest xhr : function(data, fm) { var self = fm ? fm : this, xhr = new XMLHttpRequest(), notifyto = null, notifyto2 = null, dataChecked = data.checked, isDataType = (data.isDataType || data.type == 'data'), retry = 0, dfrd = $.Deferred() .fail(function(error) { error && self.error(error); }) .done(function(data) { xhr = null; files = null; data.warning && self.error(data.warning); data.removed && self.remove(data); data.added && self.add(data); data.changed && self.change(data); self.trigger('upload', data); data.sync && self.sync(); }) .always(function() { notifyto && clearTimeout(notifyto); dataChecked && !data.multiupload && checkNotify() && self.notify({type : 'upload', cnt : -cnt, progress : 0, size : 0}); notifyto2 && clearTimeout(notifyto2); chunkMerge && self.ui.notify.children('.elfinder-notify-chunkmerge').length && self.notify({type : 'chunkmerge', cnt : -1}); }), formData = new FormData(), files = data.input ? data.input.files : self.uploads.checkFile(data, self), cnt = data.checked? (isDataType? files[0].length : files.length) : files.length, loaded = 0, prev, filesize = 0, notify = false, checkNotify = function() { return notify = (notify || self.ui.notify.children('.elfinder-notify-upload').length); }, startNotify = function(size) { if (!size) size = filesize; return setTimeout(function() { notify = true; self.notify({type : 'upload', cnt : cnt, progress : loaded - prev, size : size}); prev = loaded; }, self.options.notifyDelay); }, target = (data.target || self.cwd().hash), chunkMerge = false; !chunkMerge && (prev = loaded); if (!isDataType && !cnt) { return dfrd.reject(['errUploadNoFiles']); } xhr.addEventListener('error', function() { dfrd.reject('errConnect'); }, false); xhr.addEventListener('abort', function() { dfrd.reject(['errConnect', 'errAbort']); }, false); xhr.addEventListener('load', function(e) { var status = xhr.status, res, curr = 0, error = ''; if (status != 200) { if (status > 500) { error = 'errResponse'; } else { error = 'errConnect'; } } else { if (xhr.readyState != 4) { error = ['errConnect', 'errTimeout']; // am i right? } if (!xhr.responseText) { error = ['errResponse', 'errDataEmpty']; } } if (error) { if (chunkMerge || retry++ > 3) { var file = isDataType? files[0][0] : files[0]; if (file._cid) { formData = new FormData(); files = [{_chunkfail: true}]; formData.append('chunk', file._chunk); formData.append('cid' , file._cid); isDataType = false; send(files); return; } return dfrd.reject(error); } else { filesize = 0; xhr.open('POST', self.uploadURL, true); xhr.send(formData); return; } } loaded = filesize; if (checkNotify() && (curr = loaded - prev)) { self.notify({type : 'upload', cnt : 0, progress : curr, size : 0}); } res = self.parseUploadData(xhr.responseText); // chunked upload commit if (res._chunkmerged) { formData = new FormData(); var _file = [{_chunkmerged: res._chunkmerged, _name: res._name}]; chunkMerge = true; notifyto2 = setTimeout(function() { self.notify({type : 'chunkmerge', cnt : 1}); }, self.options.notifyDelay); isDataType? send(_file, files[1]) : send(_file); return; } res._multiupload = data.multiupload? true : false; res.error ? dfrd.reject(res.error) : dfrd.resolve(res); }, false); xhr.upload.addEventListener('loadstart', function(e) { if (!chunkMerge && e.lengthComputable) { loaded = e.loaded; retry && (loaded = 0); filesize = e.total; if (!loaded) { loaded = parseInt(filesize * 0.05); } if (checkNotify()) { self.notify({type : 'upload', cnt : 0, progress : loaded - prev, size : data.multiupload? 0 : filesize}); prev = loaded; } } }, false); xhr.upload.addEventListener('progress', function(e) { var curr; if (e.lengthComputable && !chunkMerge) { loaded = e.loaded; // to avoid strange bug in safari (not in chrome) with drag&drop. // bug: macos finder opened in any folder, // reset safari cache (option+command+e), reload elfinder page, // drop file from finder // on first attempt request starts (progress callback called ones) but never ends. // any next drop - successfull. if (!data.checked && loaded > 0 && !notifyto) { notifyto = startNotify(); } if (!filesize) { retry && (loaded = 0); filesize = e.total; if (!loaded) { loaded = parseInt(filesize * 0.05); } } curr = loaded - prev; if (checkNotify() && (curr/e.total) >= 0.05) { self.notify({type : 'upload', cnt : 0, progress : curr, size : 0}); prev = loaded; } } }, false); var send = function(files, paths){ var size = 0, fcnt = 1, sfiles = [], c = 0, total = cnt, maxFileSize, totalSize = 0, chunked = []; var chunkID = +new Date(); var BYTES_PER_CHUNK = fm.uplMaxSize - 8190; // margin 8kb if (! dataChecked && (isDataType || data.type == 'files')) { maxFileSize = fm.option('uploadMaxSize')? fm.option('uploadMaxSize') : 0; for (var i=0; i < files.length; i++) { if (maxFileSize && files[i].size >= maxFileSize) { self.error(self.i18n('errUploadFile', files[i].name) + ' ' + self.i18n('errUploadFileSize')); cnt--; total--; continue; } if (fm.uplMaxSize && files[i].size >= fm.uplMaxSize) { var SIZE = files[i].size; var start = 0; var end = BYTES_PER_CHUNK; var chunks = -1; var blob = files[i]; var total = Math.floor(SIZE / BYTES_PER_CHUNK); totalSize += SIZE; chunked[chunkID] = 0; while(start < SIZE) { var chunk; if ('slice' in blob) { chunk = blob.slice(start, end); } else if ('mozSlice' in blob) { chunk = blob.mozSlice(start, end); } else if ('webkitSlice' in blob) { chunk = blob.webkitSlice(start, end); } else { chunk = null; break; } chunk._chunk = blob.name + '.' + ++chunks + '_' + total + '.part'; chunk._cid = chunkID; chunked[chunkID]++; if (size) { c++; } if (typeof sfiles[c] == 'undefined') { sfiles[c] = []; if (isDataType) { sfiles[c][0] = []; sfiles[c][1] = []; } } size = fm.uplMaxSize; fcnt = 1; if (isDataType) { sfiles[c][0].push(chunk); sfiles[c][1].push(paths[i]); } else { sfiles[c].push(chunk); } start = end; end = start + BYTES_PER_CHUNK; } if (chunk == null) { self.error(self.i18n('errUploadFile', files[i].name) + ' ' + self.i18n('errUploadFileSize')); cnt--; total--; } else { total += chunks; } continue; } if ((fm.uplMaxSize && size + files[i].size >= fm.uplMaxSize) || fcnt > fm.uplMaxFile) { size = 0; fcnt = 1; c++; } if (typeof sfiles[c] == 'undefined') { sfiles[c] = []; if (isDataType) { sfiles[c][0] = []; sfiles[c][1] = []; } } if (isDataType) { sfiles[c][0].push(files[i]); sfiles[c][1].push(paths[i]); } else { sfiles[c].push(files[i]); } size += files[i].size; totalSize += files[i].size; fcnt++; } if (sfiles.length == 0) { data.checked = true; return false; } if (sfiles.length > 1) { notifyto = startNotify(totalSize); var added = [], done = 0, last = sfiles.length, failChunk = [], multi = function(files, num){ var sfiles = []; while(files.length && sfiles.length < num) { sfiles.push(files.shift()); } if (sfiles.length) { for (var i=0; i < sfiles.length; i++) { var cid = isDataType? (sfiles[i][0][0]._cid || null) : (sfiles[i][0]._cid || null); if (!!failChunk[cid]) { last--; continue; } fm.exec('upload', { type: data.type, isDataType: isDataType, files: sfiles[i], checked: true, target: target, multiupload: true}) .fail(function(error) { if (cid) { failChunk[cid] = true; } error && self.error(error); }) .always(function(e) { if (e.added) added = $.merge(added, e.added); if (last <= ++done) { fm.trigger('multiupload', {added: added}); notifyto && clearTimeout(notifyto); if (checkNotify()) { self.notify({type : 'upload', cnt : -cnt, progress : 0, size : 0}); } } multi(files, 1); // Next one }); } } }; multi(sfiles, 3); // Max connection: 3 return true; } if (isDataType) { files = sfiles[0][0]; paths = sfiles[0][1]; } else { files = sfiles[0]; } } if (!dataChecked && (!fm.UA.Safari || !data.files)) { notifyto = startNotify(); } dataChecked = true; if (! files.length) { dfrd.reject(['errUploadNoFiles']); } xhr.open('POST', self.uploadURL, true); // set request headers if (fm.customHeaders) { $.each(fm.customHeaders, function(key) { xhr.setRequestHeader(key, this); }); } // set xhrFields if (fm.xhrFields) { $.each(fm.xhrFields, function(key) { if (key in xhr) { xhr[key] = this; } }); } formData.append('cmd', 'upload'); formData.append(self.newAPI ? 'target' : 'current', target); $.each(self.options.customData, function(key, val) { formData.append(key, val); }); $.each(self.options.onlyMimes, function(i, mime) { formData.append('mimes['+i+']', mime); }); $.each(files, function(i, file) { if (file._chunkmerged) { formData.append('chunk', file._chunkmerged); formData.append('upload[]', file._name); } else { if (file._chunkfail) { formData.append('upload[]', 'chunkfail'); formData.append('mimes', 'chunkfail'); } else { formData.append('upload[]', file); } if (file._chunk) { formData.append('chunk', file._chunk); formData.append('cid' , file._cid); } } }); if (isDataType) { $.each(paths, function(i, path) { formData.append('upload_path[]', path); }); } xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 0) { // ff bug while send zero sized file // for safari - send directory dfrd.reject(['errConnect', 'errAbort']); } }; xhr.send(formData); return true; }; if (! isDataType) { if (! send(files)) { dfrd.reject(); } } else { if (dataChecked) { send(files[0], files[1]); } else { notifyto2 = setTimeout(function() { self.notify({type : 'readdir', cnt : 1, hideCnt: true}); }, self.options.notifyDelay); files.done(function(result){ notifyto2 && clearTimeout(notifyto2); self.notify({type : 'readdir', cnt : -1}); cnt = result[0].length; if (cnt) { send(result[0], result[1]); } else { dfrd.reject(['errUploadNoFiles']); } }).fail(function(){ dfrd.reject(['errUploadNoFiles']); }); } } return dfrd; } }, /** * Bind callback to event(s) The callback is executed at most once per event. * To bind to multiply events at once, separate events names by space * * @param String event name * @param Function callback * @return elFinder */ one : function(event, callback) { var self = this, h = $.proxy(callback, function(event) { setTimeout(function() {self.unbind(event.type, h);}, 3); return callback.apply(this, arguments); }); return this.bind(event, h); }, /** * Set/get data into/from localStorage * * @param String key * @param String|void value * @return String */ localStorage : function(key, val) { var s = window.localStorage; key = 'elfinder-'+key+this.id; if (val === null) { return s.removeItem(key); } if (val !== void(0)) { try { s.setItem(key, val); } catch (e) { s.clear(); s.setItem(key, val); } } return s.getItem(key); }, /** * Get/set cookie * * @param String cookie name * @param String|void cookie value * @return String */ cookie : function(name, value) { var d, o, c, i; name = 'elfinder-'+name+this.id; if (value === void(0)) { if (document.cookie && document.cookie != '') { c = document.cookie.split(';'); name += '='; for (i=0; i<c.length; i++) { c[i] = $.trim(c[i]); if (c[i].substring(0, name.length) == name) { return decodeURIComponent(c[i].substring(name.length)); } } } return ''; } o = $.extend({}, this.options.cookie); if (value === null) { value = ''; o.expires = -1; } if (typeof(o.expires) == 'number') { d = new Date(); d.setTime(d.getTime()+(o.expires * 86400000)); o.expires = d; } document.cookie = name+'='+encodeURIComponent(value)+'; expires='+o.expires.toUTCString()+(o.path ? '; path='+o.path : '')+(o.domain ? '; domain='+o.domain : '')+(o.secure ? '; secure' : ''); return value; }, /** * Get start directory (by location.hash or last opened directory) * * @return String */ startDir : function() { var locHash = window.location.hash; if (locHash && locHash.match(/^#elf_/)) { return locHash.replace(/^#elf_/, ''); } else { return this.lastDir(); } }, /** * Get/set last opened directory * * @param String|undefined dir hash * @return String */ lastDir : function(hash) { return this.options.rememberLastDir ? this.storage('lastdir', hash) : ''; }, /** * Node for escape html entities in texts * * @type jQuery */ _node : $('<span/>'), /** * Replace not html-safe symbols to html entities * * @param String text to escape * @return String */ escape : function(name) { return this._node.text(name).html(); }, /** * Cleanup ajax data. * For old api convert data into new api format * * @param String command name * @param Object data from backend * @return Object */ normalize : function(data) { var filter = function(file) { if (file && file.hash && file.name && file.mime) { if (file.mime == 'application/x-empty') { file.mime = 'text/plain'; } return file; } return null; return file && file.hash && file.name && file.mime ? file : null; }; if (data.files) { data.files = $.map(data.files, filter); } if (data.tree) { data.tree = $.map(data.tree, filter); } if (data.added) { data.added = $.map(data.added, filter); } if (data.changed) { data.changed = $.map(data.changed, filter); } if (data.api) { data.init = true; } return data; }, /** * Update sort options * * @param {String} sort type * @param {String} sort order * @param {Boolean} show folder first */ setSort : function(type, order, stickFolders) { this.storage('sortType', (this.sortType = this.sortRules[type] ? type : 'name')); this.storage('sortOrder', (this.sortOrder = /asc|desc/.test(order) ? order : 'asc')); this.storage('sortStickFolders', (this.sortStickFolders = !!stickFolders) ? 1 : ''); this.trigger('sortchange'); }, _sortRules : { name : function(file1, file2) { return file1.name.toLowerCase().localeCompare(file2.name.toLowerCase()); }, size : function(file1, file2) { var size1 = parseInt(file1.size) || 0, size2 = parseInt(file2.size) || 0; return size1 == size2 ? 0 : size1 > size2 ? 1 : -1; return (parseInt(file1.size) || 0) > (parseInt(file2.size) || 0) ? 1 : -1; }, kind : function(file1, file2) { return file1.mime.localeCompare(file2.mime); }, date : function(file1, file2) { var date1 = file1.ts || file1.date, date2 = file2.ts || file2.date; return date1 == date2 ? 0 : date1 > date2 ? 1 : -1 } }, /** * Compare files based on elFinder.sort * * @param Object file * @param Object file * @return Number */ compare : function(file1, file2) { var self = this, type = self.sortType, asc = self.sortOrder == 'asc', stick = self.sortStickFolders, rules = self.sortRules, sort = rules[type], d1 = file1.mime == 'directory', d2 = file2.mime == 'directory', res; if (stick) { if (d1 && !d2) { return -1; } else if (!d1 && d2) { return 1; } } res = asc ? sort(file1, file2) : sort(file2, file1); return type != 'name' && res == 0 ? res = asc ? rules.name(file1, file2) : rules.name(file2, file1) : res; }, /** * Sort files based on config * * @param Array files * @return Array */ sortFiles : function(files) { return files.sort(this.compare); }, /** * Open notification dialog * and append/update message for required notification type. * * @param Object options * @example * this.notify({ * type : 'copy', * msg : 'Copy files', // not required for known types @see this.notifyType * cnt : 3, * hideCnt : false, // true for not show count * progress : 10 // progress bar percents (use cnt : 0 to update progress bar) * }) * @return elFinder */ notify : function(opts) { var type = opts.type, msg = this.messages['ntf'+type] ? this.i18n('ntf'+type) : this.i18n('ntfsmth'), ndialog = this.ui.notify, notify = ndialog.children('.elfinder-notify-'+type), ntpl = '<div class="elfinder-notify elfinder-notify-{type}"><span class="elfinder-dialog-icon elfinder-dialog-icon-{type}"/><span class="elfinder-notify-msg">{msg}</span> <span class="elfinder-notify-cnt"/><div class="elfinder-notify-progressbar"><div class="elfinder-notify-progress"/></div></div>', delta = opts.cnt, size = (typeof opts.size != 'undefined')? parseInt(opts.size) : null, progress = (typeof opts.progress != 'undefined' && opts.progress >= 0) ? opts.progress : null, cnt, total, prc; if (!type) { return this; } if (!notify.length) { notify = $(ntpl.replace(/\{type\}/g, type).replace(/\{msg\}/g, msg)) .appendTo(ndialog) .data('cnt', 0); if (progress != null) { notify.data({progress : 0, total : 0}); } } cnt = delta + parseInt(notify.data('cnt')); if (cnt > 0) { !opts.hideCnt && notify.children('.elfinder-notify-cnt').text('('+cnt+')'); ndialog.is(':hidden') && ndialog.elfinderdialog('open'); notify.data('cnt', cnt); if ((progress != null) && (total = notify.data('total')) >= 0 && (prc = notify.data('progress')) >= 0) { total += size != null? size : delta; prc += progress; (size == null && delta < 0) && (prc += delta * 100); notify.data({progress : prc, total : total}); if (size != null) { prc *= 100; total = Math.max(1, total); } progress = parseInt(prc/total); notify.find('.elfinder-notify-progress') .animate({ width : (progress < 100 ? progress : 100)+'%' }, 20); } } else { notify.remove(); !ndialog.children().length && ndialog.elfinderdialog('close'); } return this; }, /** * Open confirmation dialog * * @param Object options * @example * this.confirm({ * title : 'Remove files', * text : 'Here is question text', * accept : { // accept callback - required * label : 'Continue', * callback : function(applyToAll) { fm.log('Ok') } * }, * cancel : { // cancel callback - required * label : 'Cancel', * callback : function() { fm.log('Cancel')} * }, * reject : { // reject callback - optionally * label : 'No', * callback : function(applyToAll) { fm.log('No')} * }, * all : true // display checkbox "Apply to all" * }) * @return elFinder */ confirm : function(opts) { var complete = false, options = { cssClass : 'elfinder-dialog-confirm', modal : true, resizable : false, title : this.i18n(opts.title || 'confirmReq'), buttons : {}, close : function() { !complete && opts.cancel.callback(); $(this).elfinderdialog('destroy'); } }, apply = this.i18n('apllyAll'), label, checkbox; if (opts.reject) { options.buttons[this.i18n(opts.reject.label)] = function() { opts.reject.callback(!!(checkbox && checkbox.prop('checked'))) complete = true; $(this).elfinderdialog('close') }; } options.buttons[this.i18n(opts.accept.label)] = function() { opts.accept.callback(!!(checkbox && checkbox.prop('checked'))) complete = true; $(this).elfinderdialog('close') }; options.buttons[this.i18n(opts.cancel.label)] = function() { $(this).elfinderdialog('close') }; if (opts.all) { if (opts.reject) { options.width = 370; } options.create = function() { checkbox = $('<input type="checkbox" />'); $(this).next().children().before($('<label>'+apply+'</label>').prepend(checkbox)); } options.open = function() { var pane = $(this).next(), width = parseInt(pane.children(':first').outerWidth() + pane.children(':last').outerWidth()); if (width > parseInt(pane.width())) { $(this).closest('.elfinder-dialog').width(width+30); } } } return this.dialog('<span class="elfinder-dialog-icon elfinder-dialog-icon-confirm"/>' + this.i18n(opts.text), options); }, /** * Create unique file name in required dir * * @param String file name * @param String parent dir hash * @return String */ uniqueName : function(prefix, phash) { var i = 0, ext = '', p, name; prefix = this.i18n(prefix); phash = phash || this.cwd().hash; if ((p = prefix.indexOf('.txt')) != -1) { ext = '.txt'; prefix = prefix.substr(0, p); } name = prefix+ext; if (!this.fileByName(name, phash)) { return name; } while (i < 10000) { name = prefix + ' ' + (++i) + ext; if (!this.fileByName(name, phash)) { return name; } } return prefix + Math.random() + ext; }, /** * Return message translated onto current language * * @param String|Array message[s] * @return String **/ i18n : function() { var self = this, messages = this.messages, input = [], ignore = [], message = function(m) { var file; if (m.indexOf('#') === 0) { if ((file = self.file(m.substr(1)))) { return file.name; } } return m; }, i, j, m; for (i = 0; i< arguments.length; i++) { m = arguments[i]; if (typeof m == 'string') { input.push(message(m)); } else if ($.isArray(m)) { for (j = 0; j < m.length; j++) { if (typeof m[j] == 'string') { input.push(message(m[j])); } } } } for (i = 0; i < input.length; i++) { // dont translate placeholders if ($.inArray(i, ignore) !== -1) { continue; } m = input[i]; // translate message m = messages[m] || m; // replace placeholders in message m = m.replace(/\$(\d+)/g, function(match, placeholder) { placeholder = i + parseInt(placeholder); if (placeholder > 0 && input[placeholder]) { ignore.push(placeholder) } return input[placeholder] || ''; }); input[i] = m; } return $.map(input, function(m, i) { return $.inArray(i, ignore) === -1 ? m : null; }).join('<br>'); }, /** * Convert mimetype into css classes * * @param String file mimetype * @return String */ mime2class : function(mime) { var prefix = 'elfinder-cwd-icon-'; mime = mime.split('/'); return prefix+mime[0]+(mime[0] != 'image' && mime[1] ? ' '+prefix+mime[1].replace(/(\.|\+)/g, '-') : ''); }, /** * Return localized kind of file * * @param Object|String file or file mimetype * @return String */ mime2kind : function(f) { var mime = typeof(f) == 'object' ? f.mime : f, kind; if (f.alias) { kind = 'Alias'; } else if (this.kinds[mime]) { kind = this.kinds[mime]; } else { if (mime.indexOf('text') === 0) { kind = 'Text'; } else if (mime.indexOf('image') === 0) { kind = 'Image'; } else if (mime.indexOf('audio') === 0) { kind = 'Audio'; } else if (mime.indexOf('video') === 0) { kind = 'Video'; } else if (mime.indexOf('application') === 0) { kind = 'App'; } else { kind = mime; } } return this.messages['kind'+kind] ? this.i18n('kind'+kind) : mime; var mime = typeof(f) == 'object' ? f.mime : f, kind = this.kinds[mime]||'unknown'; if (f.alias) { kind = 'Alias'; } else if (kind == 'unknown') { if (mime.indexOf('text') === 0) { kind = 'Text'; } else if (mime.indexOf('image') === 0) { kind = 'Image'; } else if (mime.indexOf('audio') === 0) { kind = 'Audio'; } else if (mime.indexOf('video') === 0) { kind = 'Video'; } else if (mime.indexOf('application') === 0) { kind = 'Application'; } } return this.i18n(kind); }, /** * Return localized date * * @param Object file object * @return String */ formatDate : function(file, ts) { var self = this, ts = ts || file.ts, i18 = self.i18, date, format, output, d, dw, m, y, h, g, i, s; if (self.options.clientFormatDate && ts > 0) { date = new Date(ts*1000); h = date[self.getHours](); g = h > 12 ? h - 12 : h; i = date[self.getMinutes](); s = date[self.getSeconds](); d = date[self.getDate](); dw = date[self.getDay](); m = date[self.getMonth]() + 1; y = date[self.getFullYear](); format = ts >= this.yesterday ? this.fancyFormat : this.dateFormat; output = format.replace(/[a-z]/gi, function(val) { switch (val) { case 'd': return d > 9 ? d : '0'+d; case 'j': return d; case 'D': return self.i18n(i18.daysShort[dw]); case 'l': return self.i18n(i18.days[dw]); case 'm': return m > 9 ? m : '0'+m; case 'n': return m; case 'M': return self.i18n(i18.monthsShort[m-1]); case 'F': return self.i18n(i18.months[m-1]); case 'Y': return y; case 'y': return (''+y).substr(2); case 'H': return h > 9 ? h : '0'+h; case 'G': return h; case 'g': return g; case 'h': return g > 9 ? g : '0'+g; case 'a': return h > 12 ? 'pm' : 'am'; case 'A': return h > 12 ? 'PM' : 'AM'; case 'i': return i > 9 ? i : '0'+i; case 's': return s > 9 ? s : '0'+s; } return val; }); return ts >= this.yesterday ? output.replace('$1', this.i18n(ts >= this.today ? 'Today' : 'Yesterday')) : output; } else if (file.date) { return file.date.replace(/([a-z]+)\s/i, function(a1, a2) { return self.i18n(a2)+' '; }); } return self.i18n('dateUnknown'); }, /** * Return css class marks file permissions * * @param Object file * @return String */ perms2class : function(o) { var c = ''; if (!o.read && !o.write) { c = 'elfinder-na'; } else if (!o.read) { c = 'elfinder-wo'; } else if (!o.write) { c = 'elfinder-ro'; } return c; }, /** * Return localized string with file permissions * * @param Object file * @return String */ formatPermissions : function(f) { var p = []; f.read && p.push(this.i18n('read')); f.write && p.push(this.i18n('write')); return p.length ? p.join(' '+this.i18n('and')+' ') : this.i18n('noaccess'); }, /** * Return formated file size * * @param Number file size * @return String */ formatSize : function(s) { var n = 1, u = 'b'; if (s == 'unknown') { return this.i18n('unknown'); } if (s > 1073741824) { n = 1073741824; u = 'GB'; } else if (s > 1048576) { n = 1048576; u = 'MB'; } else if (s > 1024) { n = 1024; u = 'KB'; } s = s/n; return (s > 0 ? n >= 1048576 ? s.toFixed(2) : Math.round(s) : 0) +' '+u; }, navHash2Id : function(hash) { return 'nav-'+hash; }, navId2Hash : function(id) { return typeof(id) == 'string' ? id.substr(4) : false; }, log : function(m) { window.console && window.console.log && window.console.log(m); return this; }, debug : function(type, m) { var d = this.options.debug; if (d == 'all' || d === true || ($.isArray(d) && $.inArray(type, d) != -1)) { window.console && window.console.log && window.console.log('elfinder debug: ['+type+'] ['+this.id+']', m); } return this; }, time : function(l) { window.console && window.console.time && window.console.time(l); }, timeEnd : function(l) { window.console && window.console.timeEnd && window.console.timeEnd(l); } }
// @flow import React, {Component} from 'react' import css from '../styles/common.css' type Props = { buttonAction: Function, hiddenItemsN: number, amount: number, title: string, search: Function, searchValue: string, } export class SectionHeader extends Component { props: Props render() { return( <div className={css.sectionHeaderContainer}> <div className={css.sectionHeaderLayout}> <h3> <span>{this.props.amount} {this.props.title}</span> {this.props.hiddenItemsN > 0 && <span> ({this.props.hiddenItemsN} hidden)</span> } </h3> <div className={css.sectionHeaderActions}> <div className={css.searchInputGroup}><input type="text" value={this.props.searchValue} placeholder="Search" onChange={this.props.search} className={css.searchInput} /></div> <button className={css.btnAdd} onClick={this.props.buttonAction}><span>+</span></button> </div> </div> </div> ) } }
"use strict"; /** * @typedef {function(promise:angular.$q.Promise, options:{expectSuccess:boolean=, expectFailure:boolean=, expectUnfinished:boolean=, flushHttp:(number|boolean)=}):*} */ var PromiseHelper; /** * Returns a helper function used to invoke promises and check the results. * @param {$rootScope.Scope} $rootScope * @param {$httpBackend=} $httpBackend * @returns {PromiseHelper} */ function promiseHelper($rootScope, $httpBackend) { return function runPromise(promise, options) { var result = {}; promise.then(function(promiseResolvedWith) { result = { promise_resolved_with: promiseResolvedWith === undefined ? "(undefined)" : promiseResolvedWith, actual_result: promiseResolvedWith }; }).catch(function(promiseFailedWith) { result = { promise_failed_with: promiseFailedWith === undefined ? "(undefined)" : promiseFailedWith, actual_result: promiseFailedWith }; }); if (options.flushHttp && $httpBackend) { if (typeof options.flushHttp === 'number') { $httpBackend.flush(options.flushHttp); } else { $httpBackend.flush(); } } $rootScope.$apply(); if (options.expectSuccess) { expect(result.promise_failed_with).toBeUndefined(); expect(result.promise_resolved_with).toBeDefined(); } else if (options.expectFailure) { expect(result.promise_resolved_with).toBeUndefined(); expect(result.promise_failed_with).toBeDefined(); } else if (options.expectUnfinished) { expect(result.promise_resolved_with).toBeUndefined(); expect(result.promise_failed_with).toBeUndefined(); } return result.actual_result; } }
function bottles(number) { if (number === 0) { return 'No more bottles'; } if (number === 1) { return '1 bottle'; } return number + ' bottles'; } function action(currentVerse) { if (currentVerse === 0) { return 'Go to the store and buy some more, '; } let sbj = currentVerse === 1 ? 'it' : 'one'; return 'Take ' + sbj + ' down and pass it around, '; } function nextBottle(currentVerse) { return bottles(nextVerse(currentVerse)).toLowerCase() + ' of beer on the wall.\n'; } function nextVerse(currentVerse) { return currentVerse === 0 ? 99 : currentVerse - 1; } class BeerSong { static verse(number) { let line1 = bottles(number) + ' of beer on the wall, '; let line2 = bottles(number).toLowerCase() + ' of beer.\n'; let line3 = action(number); let line4 = nextBottle(number); return [line1, line2, line3, line4].join(''); } static sing(first = 99, last = 0) { let verses = []; for (let i = first; i >= last; i--) { verses.push(this.verse(i)); } return verses.join('\n'); } } export default BeerSong;
"use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var XmlElementNames_1 = require("../Core/XmlElementNames"); var XmlNamespace_1 = require("../Enumerations/XmlNamespace"); var ComplexProperty_1 = require("./ComplexProperty"); var StandardUser_1 = require("../Enumerations/StandardUser"); var ExtensionMethods_1 = require("../ExtensionMethods"); var UserId = (function (_super) { __extends(UserId, _super); function UserId(primarySmtpAddressOrStandardUser) { _super.call(this); if (typeof primarySmtpAddressOrStandardUser !== 'undefined') { if (typeof primarySmtpAddressOrStandardUser === 'string') { this.primarySmtpAddress = primarySmtpAddressOrStandardUser; } else { this.standardUser = primarySmtpAddressOrStandardUser; } } } Object.defineProperty(UserId.prototype, "SID", { get: function () { return this.sID; }, set: function (value) { var _this = this; this.SetFieldValue({ getValue: function () { return _this.sID; }, setValue: function (data) { return _this.sID = data; } }, value); }, enumerable: true, configurable: true }); Object.defineProperty(UserId.prototype, "PrimarySmtpAddress", { get: function () { return this.primarySmtpAddress; }, set: function (value) { var _this = this; this.SetFieldValue({ getValue: function () { return _this.primarySmtpAddress; }, setValue: function (data) { return _this.primarySmtpAddress = data; } }, value); }, enumerable: true, configurable: true }); Object.defineProperty(UserId.prototype, "DisplayName", { get: function () { return this.displayName; }, set: function (value) { var _this = this; this.SetFieldValue({ getValue: function () { return _this.displayName; }, setValue: function (data) { return _this.displayName = data; } }, value); }, enumerable: true, configurable: true }); Object.defineProperty(UserId.prototype, "StandardUser", { get: function () { return this.standardUser; }, set: function (value) { var _this = this; this.SetFieldValue({ getValue: function () { return _this.standardUser; }, setValue: function (data) { return _this.standardUser = data; } }, value); }, enumerable: true, configurable: true }); UserId.prototype.InternalToJson = function (service) { throw new Error("UserId.ts - InternalToJson : Not implemented."); }; UserId.prototype.IsValid = function () { return typeof this.StandardUser === 'number' || !ExtensionMethods_1.StringHelper.IsNullOrEmpty(this.PrimarySmtpAddress) || !ExtensionMethods_1.StringHelper.IsNullOrEmpty(this.SID); }; UserId.prototype.LoadFromJson = function (jsonProperty /*JsonObject*/, service) { throw new Error("UserId.ts - LoadFromJson : Not implemented."); }; UserId.prototype.LoadFromXmlJsObject = function (jsonProperty, service) { for (var key in jsonProperty) { switch (key) { case XmlElementNames_1.XmlElementNames.SID: this.sID = jsonProperty[key]; break; case XmlElementNames_1.XmlElementNames.PrimarySmtpAddress: this.primarySmtpAddress = jsonProperty[key]; break; case XmlElementNames_1.XmlElementNames.DisplayName: this.displayName = jsonProperty[key]; break; case XmlElementNames_1.XmlElementNames.DistinguishedUser: //debugger;//check for enum value consistency this.standardUser = StandardUser_1.StandardUser[jsonProperty[key]]; break; default: break; } } }; UserId.prototype.WriteElementsToXml = function (writer) { writer.WriteElementValue(XmlNamespace_1.XmlNamespace.Types, XmlElementNames_1.XmlElementNames.SID, this.SID); writer.WriteElementValue(XmlNamespace_1.XmlNamespace.Types, XmlElementNames_1.XmlElementNames.PrimarySmtpAddress, this.PrimarySmtpAddress); writer.WriteElementValue(XmlNamespace_1.XmlNamespace.Types, XmlElementNames_1.XmlElementNames.DisplayName, this.DisplayName); writer.WriteElementValue(XmlNamespace_1.XmlNamespace.Types, XmlElementNames_1.XmlElementNames.DistinguishedUser, this.StandardUser); }; return UserId; }(ComplexProperty_1.ComplexProperty)); exports.UserId = UserId;
import { get } from '../../lib/api'; import Schemas from '../../lib/schemas'; import * as constants from '../../constants/groups'; /** * Fetch one group */ export default (slug) => { return dispatch => { dispatch(request(slug)); return get(`/groups/${slug}`, { schema: Schemas.GROUP }) .then(json => dispatch(success(slug, json))) .catch(error => dispatch(failure(slug, error))); }; }; function request(slug) { return { type: constants.GROUP_REQUEST, slug }; } export function success(slug, json) { return { type: constants.GROUP_SUCCESS, slug, groups: json.groups }; } function failure(slug, error) { return { type: constants.GROUP_FAILURE, slug, error }; }
var Zeta = require('../../../../'), conf = require('../../conf.js'), m = Zeta.module('l2e', ['l2e']); m.load(); conf.v = m.config('v'); conf.ns.v1 = m.config.of('ns').val('v1'); conf.ns.v2 = m.config.of('ns').val('v2'); conf.ns.ns.v1 = m.config.of('ns').of('ns').val('v1'); conf.ns.ns.v2 = m.config.of('ns').of('ns').val('v2'); //this changes would not take effects m.config('v', 2); m.config.of('ns').val('v1', 2).val('v2', 4); m.config.of('ns').of('ns').val('v1', 2).val('v2', 4); m.l2e = true; m.factory('l2e.f', function() { return 1; }) .provider('l2e.p', function() {}) .handler('l2e.h', function($scope) { $scope.res.end(404); }) .get('/l2e', 'l2e.h') .setInit(function() { this.il2e = true; });
const watcher = new ScrollWatcher(); const enter = ['enter', 'fully-enter']; const exit = ['exit', 'partial-exit']; const all = enter.concat(exit); let firstChild; [].forEach.call(document.getElementsByClassName('move'), (each) => { watcher .watch(each) .on('enter', function (evt) { firstChild = evt.target.firstElementChild; firstChild.lastElementChild.textContent = 'entered'; evt.target.classList.remove(...all); evt.target.classList.add('enter'); setCssClass(evt.target, 'enter'); }) .on('exit', function (evt) { evt.target.classList.remove(...all); evt.target.classList.add('exit'); setCssClass(evt.target, 'exit'); }) .on('enter:full', function (evt) { firstChild = evt.target.firstElementChild; firstChild.lastElementChild.textContent = 'fully entered'; evt.target.classList.remove(...all); evt.target.classList.add('fully-enter'); setCssClass(evt.target, 'fully-enter'); }) .on('exit:partial', function (evt) { firstChild = evt.target.firstElementChild; firstChild.lastElementChild.textContent = 'partial exited'; evt.target.classList.remove(...all); evt.target.classList.add('partial-exit'); setCssClass(evt.target, 'partial-exit'); }); }); function setCssClass(target, klass) { switch (target) { case $('rect1'): $('actual-class1').value = klass; break; case $('rect2'): $('actual-class2').value = klass; break; case $('rect3'): $('actual-class3').value = klass; break; case $('rect4'): $('actual-class4').value = klass; break; case $('rect5'): $('actual-class5').value = klass; break; case $('rect6'): $('actual-class6').value = klass; break; default: } } function $(id) { return document.getElementById(id); }
var revive = require('./revive'); function parse(json, reviver){ return revive(JSON.parse(json, reviver)); } module.exports = parse;
(function () { 'use strict'; var factory = { create: function (length, element) { for (var i = 0; i < length; i++) { this.append(element[i]); } } }; /** * 代码区域编程语言名称展示 */ var language = { init: function () { var figure = document.querySelectorAll('figure'), length = figure.length; factory.create.bind(this)(length, figure); }, append: function (element) { var lang = element.className.replace(/(highlight)|\s/g, ''), label = document.createElement('label'); label.innerText = lang; label.style.cssText = 'position: absolute;' + 'top: 0;' + 'left: 50%;'+ 'margin-left: -' + lang.length / 4 + 'em;' + 'color: #2B2B2B;' + 'text-transform: uppercase;' + 'font-family: Courier, "Courier New", monospace;' + 'line-height: 38px;'; element.appendChild(label); } }; /** * 图片区域描述文字展示 & 大图预览 */ var preview = { init: function () { var img = document.querySelectorAll('img'), length = img.length; factory.create.bind(this)(length, img); }, append: function (element) { var alt = element.alt; var src = element.src; element.addEventListener('click', function () { var div = document.createElement('div'); div.style.cssText = 'position: fixed;' + 'top: 0;' + 'left: 0;' + 'width: 100%;' + 'height: 100%;' + 'background: rgba(0, 0, 0, 0.8);' + 'cursor: zoom-out;' + 'display: flex;' + 'align-items: center;' + 'transition: opacity .4s;' + 'animation: fadeIn .4s;'; var fixDocumentHandler = function (e) { e.preventDefault(); }; div.addEventListener('click', function () { div.style.opacity = '0'; setTimeout(function () { document.body.removeChild(div); document.body.removeEventListener('mousewheel', fixDocumentHandler, false); document.body.removeEventListener('touchmove', fixDocumentHandler, false); }, 400); }, false); document.body.addEventListener('mousewheel', fixDocumentHandler, false); document.body.addEventListener('touchmove', fixDocumentHandler, false); document.body.appendChild(div); var img = document.createElement('img'); img.src = src; img.style.cssText = 'max-width: 90%;' + 'max-height: 94%;' + 'margin: auto;' + 'display: block;'; div.appendChild(img); }, false); var label = document.createElement('label'); label.innerText = alt; label.style.cssText = 'margin-top: 8px;' + 'color: #808080;' + 'font-size: 14px;' + 'display: flex;' + 'justify-content: center;'; element.parentNode.appendChild(label); } }; language.init(); preview.init(); })();
let path = require('path'); let packageJson = require('./package.json'); let vendors = Object.keys(packageJson.dependencies); let polyfills = ['es6-shim','whatwg-fetch','tslib']; polyfills.forEach(polyKey => { let indx = vendors.indexOf(polyKey); if(indx > -1){ vendors.splice(indx,1); } }); module.exports = { entry: { polyfills, app:['./src/find-me/main/main.ts'] }, output: { path: path.resolve(__dirname, './public'), filename: '[name]-bundle.js' }, devServer: { inline: true, contentBase: './', port: 9000, proxy: { "/cards": { target: "http://localhost:3000", pathRewrite: {"^/cards/" : "/cards/"} } ,"/socket.io":{ target: "http://localhost:3000", pathRewrite: {"^/socket.io/" : "/socket.io/"} } } }, module: { loaders: [ { test: /\.ts$/, enforce: 'pre', loader: 'tslint-loader', options: { configFile:'tslint.json' } } ,{ test: modulePath => modulePath.endsWith('.ts') && !modulePath.endsWith('.d.ts'), loader: 'ts-loader' } ,{ test: /\.html$/,loader:'ferrugemjs-loader'} ,{ test: /\.css$/, use: [ 'style-loader', 'css-loader' ] } ,{ test: /\.scss$/, use: [ 'style-loader', 'css-loader', 'sass-loader'] } ,{ test: /\.(d\.ts|eot|woff|woff2|ttf|svg|png|jpg|less)$/, loader: 'url-loader?limit=30000&name=[name]-[hash].[ext]' } ] }, resolve: { extensions: [".js",".ts",".html"] ,alias:{ "apps":path.resolve(__dirname, './src/find-me') ,"ui":path.resolve(__dirname, './src/ui') ,"root_app":path.resolve(__dirname, './src/find-me') ,"ferrugemjs":"ferrugemjs/dist/core" ,"ferrugemjs-router":"ferrugemjs-router/dist/router" ,"bootstrap":"bootstrap/dist" ,"bootstrap-datepicker":"bootstrap-datepicker/dist" ,"selectize":"selectize/dist" } } }
describe('Rectangle TEST', function() { describe('Rectangle.prototype.getWidth', function() { // Positive it('should return 0.5', function() { var rectangle = new Rectangle(1, 1, 0.5, 1); expect(rectangle.getWidth()).toEqual(0.5); }); // Negative it('should return 0', function() { var rectangle = new Rectangle(1, 1, -0.5, 1); expect(rectangle.getWidth()).toEqual(0); }); it('should return 0', function() { var rectangle = new Rectangle(1, 1, '', 1); expect(rectangle.getWidth()).toEqual(0); }); }); });
const config = { id: 'WatchUs.Info' }; export default config;
export Wizard from './Wizard'; export WizardStep from './WizardStep';
'use strict'; angular.module('mysmarthouseWebApp') .controller('SettingsCtrl', function($scope, Restangular) { $scope.devices = []; Restangular.all('sensors') .getList() .then(function(sensors) { sensors.forEach(function(item) { item.deviceType = 'sensor'; $scope.devices.push(item); }); }) .then(function() { return Restangular.all('controllers'). getList(); }) .then(function(controllers) { controllers.forEach(function(item) { item.deviceType = 'controller'; $scope.devices.push(item); }); }) .then(function() { var socket = io(); socket.on('sensor:data', function(data) { console.log(123); var sensor = _.findWhere($scope.devices, { _id: data._id }); sensor.lastValue = data.value; $scope.$apply(); }); socket.on('sensor:status', function(data){ var sensor = _.findWhere($scope.devices, { _id: data._id }); sensor.connected = data.isConnected; $scope.$apply(); }) }); //$scope.devices = [ // {deviceType: 'sensor', name: 'Humidity Sensor', connected: true, type: 'value', boardId: 2, pin: 6, lastValue: 10}, // {deviceType: 'sensor', name: 'Baro Sensor', connected: true, type: 'value',boardId: 2, pin: 6, lastValue: 1550}, // {deviceType: 'controller', name: 'Lamp 1', connected: true, type: 'relay',boardId: 2, pin: 6, lastValue: 10}, // {deviceType: 'sensor', name: 'Electricity Sensor', connected: false, type: 'electricity', boardId: 2, pin: 6,lastValue: 10}, // {deviceType: 'controller', name: 'White Bra', connected: true, type: 'relay',boardId: 2, pin: 6, lastValue: 10}, //] });
import React, { Component } from 'react'; import urls from '../../GestionsComponents/configs/serverConfigurations' import { Chart, Bar, Line } from 'react-chartjs-2'; import { Dropdown, DropdownMenu, DropdownItem, Progress } from 'reactstrap'; const month_days = { 1 : 31, 2 : 28, 3 : 31, 4 : 30, 5 : 31, 6 : 30, 7 : 31, 8 : 31, 9 : 30, 10 : 31, 11 : 30, 12 : 31, 13 : 29 } const brandPrimary = '#20a8d8'; const brandSuccess = '#4dbd74'; const brandInfo = '#63c2de'; const brandDanger = '#f86c6b'; // Main Chart // convert Hex to RGBA function convertHex(hex,opacity) { hex = hex.replace('#',''); var r = parseInt(hex.substring(0,2), 16); var g = parseInt(hex.substring(2,4), 16); var b = parseInt(hex.substring(4,6), 16); var result = 'rgba('+r+','+g+','+b+','+opacity/100+')'; return result; } const plugin = { afterDatasetsDraw: function(chart, easing) { // To only draw at the end of animation, check for easing === 1 var ctx = chart.chart.ctx; chart.data.datasets.forEach(function (dataset, i) { var meta = chart.getDatasetMeta(i); if (!meta.hidden) { meta.data.forEach(function(element, index) { // Draw the text in black, with the specified font ctx.fillStyle = 'rgb(0, 0, 0)'; var fontSize = 12; var fontStyle = 'normal'; var fontFamily = 'Helvetica Neue'; ctx.font = Chart.helpers.fontString(fontSize, fontStyle, fontFamily); // Just naively convert to string for now var dataString = dataset.data[index].toString(); // Make sure alignment settings are correct ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; var padding = 5; var position = element.tooltipPosition(); ctx.fillText(dataString, position.x, position.y - (fontSize / 2) - padding); }); } }); } } const mainChartOpts = { maintainAspectRatio: false, tooltips: { mode: 'nearest', intersect : false } } export default class Report extends Component { constructor(props) { super(props); this.state = { distancePerDay :[], timeUsagePerDay :[], stopTimePerDay :[], tripsNumPerDay :[], avgDistance :0, avgTimeUsage :0, totalTimeUsage :0, totalDistance :0, dataReady : false, dateFrom : null, dateTo : null, charts : [] }; } componentDidMount(){ this.getScooterReport(); } getScooterReport(){ const queryMethod = 'GET'; let search = this.props.location.search.replace(/\?/g,'').split('&'); let id = search[0].split('=')[1]; let dateOrigin = new Date('2017-04'); let dateFromOrigin = dateOrigin.toISOString(); let dateFrom = new Date(search[1].split('=')[1]); let dateTo =new Date(search[2].split('=')[1]); let urlTrips = 'http://vps92599.ovh.net:8082/api/reports/trips'+this.props.location.search; let urlStops = 'http://vps92599.ovh.net:8082/api/reports/stops'+this.props.location.search; let urlSummary = 'http://vps92599.ovh.net:8082/api/reports/summary?deviceId='+id+'&from='+dateFromOrigin+'&to='+dateTo.toISOString(); let urlTripsAll = 'http://vps92599.ovh.net:8082/api/reports/trips?deviceId='+id+'&from='+dateFromOrigin+'&to='+dateTo.toISOString(); let urlStopsAll = 'http://vps92599.ovh.net:8082/api/reports/stops?deviceId='+id+'&from='+dateFromOrigin+'&to='+dateTo.toISOString(); let urls = [urlSummary,urlTrips,urlStops,urlTripsAll,urlStopsAll]; var promises = urls.map(url => fetch(url,{ credentials: 'include' }).then(y => y.json())); Promise.all(promises).then(results => { let result_period = this.analyseTripsAndStops(results[1],results[2],dateFrom); let career_distance = (results[0][0]['distance']/1000).toFixed(1); let career_time = this.getCareerTotalUsageTime(results[3],results[4]); let charts = this.generateChart([result_period[0],result_period[1],result_period[2],result_period[3]],result_period[6]); this.setState({ distancePerDay :result_period[0], timeUsagePerDay :result_period[1], stopTimePerDay :result_period[2], tripsNumPerDay :result_period[3], avgDistance :result_period[4], avgTimeUsage :result_period[5], totalTimeUsage :career_time, totalDistance :career_distance, dataReady : true, dateFrom : dateFrom, dateTo : dateTo, charts : charts }) }).catch(err=>{ console.log(err); this.setState({ dataReady : false }); }); } getCareerTotalUsageTime(trips,stops){ let tripsTotal = 0; let stopsTotal = 0; trips.map((instance,index)=>{ let date1 = new Date(instance['startTime']); let date2 = new Date(instance['endTime']); let dayIndex = date1.getDate(); let dayEndIndex = date2.getDate(); if (dayIndex===dayEndIndex) { tripsTotal = tripsTotal+(instance['duration']/1000); } //total km per day from trips }) stops.map((instance,index)=>{ let date1 = new Date(instance['startTime']); let date2 = new Date(instance['endTime']); let dayIndex = date1.getDate(); let dayEndIndex = date2.getDate(); if (dayIndex===dayEndIndex) { //total km per day from trips stopsTotal = stopsTotal+(instance['duration']/1000); } }) return ((tripsTotal+stopsTotal)/60).toFixed(1); } analyseTripsAndStops(trips,stops,date){ //data from trips let year = date.getFullYear(); let month = year%4!==0?date.getMonth()+1:13; let monthString = date.toUTCString().split(' ')[2]; let dayNum = month_days[month]; let dayStartInPeriod = date.getDate(); let daysInPeriod = dayNum-dayStartInPeriod+1; let dayList = []; let distancePerDay = [];//from trips /km let timeUsagePerDay = [];//from tripTimePerDay + stopTimePerDay /seconds let stopTimePerDay = [];//from stops /seconds let tripsNumPerDay = [];//from trips /int let tripTimePerDay = [];//from trips /seconds for (var i = 0; i < daysInPeriod; i++) { dayList[i] = dayStartInPeriod+i+'-'+monthString; distancePerDay[i] = 0; timeUsagePerDay[i] = 0; tripsNumPerDay[i] = 0; tripTimePerDay[i] = 0; stopTimePerDay[i] = 0; } trips.map((instance,index)=>{ let date1 = new Date(instance['startTime']); let date2 = new Date(instance['endTime']); let dayIndex = date1.getDate()-dayStartInPeriod; let dayEndIndex = date2.getDate()-dayStartInPeriod; if (dayIndex===dayEndIndex) { distancePerDay[dayIndex] = distancePerDay[dayIndex]+(instance['distance']/1000); tripsNumPerDay[dayIndex] = tripsNumPerDay[dayIndex] + 1; tripTimePerDay[dayIndex] = tripTimePerDay[dayIndex]+(instance['duration']/1000); } //total km per day from trips }) stops.map((instance,index)=>{ let date1 = new Date(instance['startTime']); let date2 = new Date(instance['endTime']); let dayIndex = date1.getDate()-dayStartInPeriod; let dayEndIndex = date2.getDate()-dayStartInPeriod; if (dayIndex===dayEndIndex) { //total km per day from trips stopTimePerDay[dayIndex] = stopTimePerDay[dayIndex]+(instance['duration']/1000); } }) //calculate total timeUsagePerDay.map((instance,index)=>{ timeUsagePerDay[index] = stopTimePerDay[index] + tripTimePerDay[index] // /hours }) let totalTimeUsage = (timeUsagePerDay.reduce((a,b) => (a+b))/60); let totalDistance = distancePerDay.reduce((a,b) => (a+b)); //format to hours and kms with 2 point timeUsagePerDay.map((instance,index)=>{ timeUsagePerDay[index] = (timeUsagePerDay[index]/60).toFixed(1); // /hours }) tripTimePerDay.map((instance,index)=>{ tripTimePerDay[index] = (tripTimePerDay[index]/60).toFixed(1); // /hours }) distancePerDay.map((instance,index)=>{ distancePerDay[index] = distancePerDay[index].toFixed(1); // /kms }) stopTimePerDay.map((instance,index)=>{ stopTimePerDay[index] = (stopTimePerDay[index]/60).toFixed(1); // /hours }) let avgDistance = (totalDistance/daysInPeriod).toFixed(1); let avgTimeUsage = (totalTimeUsage/daysInPeriod).toFixed(1); return [distancePerDay,timeUsagePerDay,stopTimePerDay,tripsNumPerDay,avgDistance,avgTimeUsage,dayList] } generateChart(reportData,label){ let distancePerDay = { labels: label, datasets: [ { label: 'Distance journalière', backgroundColor: convertHex(brandPrimary,10), borderColor: brandPrimary, pointHoverBackgroundColor: '#fff', borderWidth: 2, data: reportData[0] } ] } let timeUsagePerDay= { labels: label, datasets: [ { label: 'Temps de déplacement', backgroundColor: convertHex(brandInfo,10), borderColor: brandInfo, pointHoverBackgroundColor: '#fff', borderWidth: 2, data: reportData[1] } ] } let stopTimePerDay= { labels: label, datasets: [ { label: 'Temps d’arrêt chez le client ', backgroundColor: convertHex(brandDanger,10), borderColor: brandDanger, pointHoverBackgroundColor: '#fff', borderWidth: 2, data: reportData[2] } ] } let tripsNumPerDay= { labels: label, datasets: [ { label: 'Nombre de départ journalier', backgroundColor: convertHex(brandSuccess,10), borderColor: brandSuccess, pointHoverBackgroundColor: '#fff', borderWidth: 2, data: reportData[3] } ] } return [distancePerDay,timeUsagePerDay,stopTimePerDay,tripsNumPerDay] } formatterDate(date){ return new Date(date).toISOString().split('T')[0]; } render(){ console.log(this.props.location.search); let dateStart = this.state.dataReady?this.state.dateFrom.toLocaleDateString():''; let dateEnd = this.state.dataReady?this.state.dateTo.toLocaleDateString():''; let scooter_id = this.state.dataReady?(this.props.location.search.split('nom_scooter=')[1]):''; let header = "Rapport d’activité sur la période du " + dateStart + " Au " +dateEnd+" pour le scooter "+scooter_id ; return ( <div className="animated fadeIn m-4"> <div className="row" id="printArea"> <button type="button" id="printButton" onClick={()=>{ document.getElementById("printButton").hidden=true; window.print(); document.getElementById("printButton").hidden=false; }}>Print</button> <h1 className="text-info text-center col-12">{header}</h1> <div className="col-sm-4 col-lg-3 offset-md-3"> <div className="card card-inverse card-primary"> <div className="card-block pb-0"> <h4 className="mb-0">{this.state.dataReady?this.state.totalDistance+' KM':null}</h4> <p>Distance totale Parcourue</p> </div> </div> </div> <div className="col-sm-4 col-lg-3"> <div className="card card-inverse card-info"> <div className="card-block pb-0"> <h4 className="mb-0">{this.state.dataReady?this.state.totalTimeUsage+' Min':null}</h4> <p>Temps de parcours total</p> </div> </div> </div> <div className="col-sm-4 col-lg-3 offset-md-3"> <div className="card card-inverse card-warning"> <div className="card-block pb-0"> <h4 className="mb-0">{this.state.dataReady?this.state.avgDistance+' KM':null}</h4> <p>Distance moyenne sur la période</p> </div> </div> </div> <div className="col-sm-4 col-lg-3"> <div className="card card-inverse card-danger"> <div className="card-block pb-0"> <h4 className="mb-0">{this.state.dataReady?this.state.avgTimeUsage+' Min':null}</h4> <p>Temps moyen sur la période</p> </div> </div> </div> <h4 className="text-info text-center col-12">CRUIS RENT vous donne le détail de votre activité de livraison par service lors de la semaine d’évaluation</h4> <div className="col-sm-4 col-lg-5 offset-md-1"> <div className="card"> <div className="card-block"> <div className="row"> <div className="col"> <h4 className="card-title mb-0">Distance journalière (km)</h4> <span className="small text-muted">{this.state.dataReady?this.state.dateFrom.toLocaleDateString():null}</span> <span className="small text-muted">{this.state.dataReady?'-':null}</span> <span className="small text-muted">{this.state.dataReady?this.state.dateTo.toLocaleDateString():null}</span> </div> </div> <div className="chart-wrapper" style={{height: 200 + 'px', marginTop : 20 + 'px'}}> {this.state.dataReady?<Bar data={this.state.charts[0]} options={mainChartOpts} plugins={[plugin]} height={300}/>:null} </div> </div> <div className="card-footer "> <div className="row"> <div className="col-lg-12 col-sm-12"> <div className="card-title mb-0 text-center text-muted">Ce graphique fait la synthèse de distance parcouru par jour du scooter</div> </div> </div> </div> </div> </div> <div className="col-sm-4 col-lg-5"> <div className="card"> <div className="card-block"> <div className="row"> <div className="col"> <h4 className="card-title mb-0">Temps de déplacement (en min)</h4> <span className="small text-muted">{this.state.dataReady?this.state.dateFrom.toLocaleDateString():null}</span> <span className="small text-muted">{this.state.dataReady?'-':null}</span> <span className="small text-muted">{this.state.dataReady?this.state.dateTo.toLocaleDateString():null}</span> </div> </div> <div className="chart-wrapper" style={{height: 200 + 'px', marginTop : 20 + 'px'}}> {this.state.dataReady?<Bar data={this.state.charts[1]} options={mainChartOpts} plugins={[plugin]} height={300}/>:null} </div> </div> <div className="card-footer "> <div className="row"> <div className="col-lg-12 col-sm-12"> <div className="card-title mb-0 text-center text-muted">Ce graphique fait la synthèse des temps d’utilisation du scooter par jour </div> </div> </div> </div> </div> </div> <div className="col-sm-6 col-lg-5 offset-md-1"> <div className="card"> <div className="card-block"> <div className="row"> <div className="col"> <h4 className="card-title mb-0">Temps d’arrêt chez le client (en min)</h4> <span className="small text-muted">{this.state.dataReady?this.state.dateFrom.toLocaleDateString():null}</span> <span className="small text-muted">{this.state.dataReady?'-':null}</span> <span className="small text-muted">{this.state.dataReady?this.state.dateTo.toLocaleDateString():null}</span> </div> </div> <div className="chart-wrapper" style={{height: 200 + 'px', marginTop : 20 + 'px'}}> {this.state.dataReady?<Bar data={this.state.charts[2]} options={mainChartOpts} plugins={[plugin]} height={300}/>:null} </div> </div> <div className="card-footer "> <div className="row"> <div className="col-lg-12 col-sm-12"> <div className="card-title mb-0 text-center text-muted">Ce graphique fait la somme des temps d’arrêt lorsque le scooter est hors restaurant</div> </div> </div> </div> </div> </div> <div className="col-sm-6 col-lg-5"> <div className="card"> <div className="card-block"> <div className="row"> <div className="col"> <h4 className="card-title mb-0">Nombre de départ journalier</h4> <span className="small text-muted">{this.state.dataReady?this.state.dateFrom.toLocaleDateString():null}</span> <span className="small text-muted">{this.state.dataReady?'-':null}</span> <span className="small text-muted">{this.state.dataReady?this.state.dateTo.toLocaleDateString():null}</span> </div> </div> <div className="chart-wrapper" style={{height: 200 + 'px', marginTop : 20 + 'px'}}> {this.state.dataReady?<Line data={this.state.charts[3]} options={mainChartOpts} plugins={[plugin]} height={300}/>:null} </div> </div> <div className="card-footer "> <div className="row"> <div className="col-lg-12 col-sm-12"> <div className="card-title mb-0 text-center text-muted">Ce graphique fait la somme des départs en livraison</div> </div> </div> </div> </div> </div> <div className="col-lg-12 text-center"><strong>CRUIS RENT</strong> 82 Avenue Denfert Rochereau – Tel : 0954 55 4000 – <a href="http://www.cruisrent.com">www.cruisrent.com</a> RCS Paris 812 634 160 00012 – SASU au capital de 30 000 € - TVA Intracommunautaire : FR37 812634160</div> </div> </div> ) } }
define(function(require) { 'use strict'; var Promise = require('intern/dojo/Promise'); function WorkerProxy() { this.counter = 0; this.deferreds = {}; this.worker = new Worker('../../test/helper/worker.js'); this.worker.addEventListener('message', this._handleMessage.bind(this), false); } WorkerProxy.prototype = { _handleMessage: function(event) { var id = event.data.id; var dfd = this.deferreds[id]; if (!dfd) { return; } if (event.data.error) { var _error = new Error(event.data.error.split('\n')[0]); _error.stack = event.data.error; dfd.reject(_error); } else { dfd.resolve(event.data.result); } delete this.deferreds[id]; }, _wrapTest: function(promise, deferred, callback) { promise.then( deferred.callback(callback), deferred.reject.bind(deferred) ); }, terminate: function() { this.worker && this.worker.terminate(); this.worker = null; }, run: function(modules, callback) { var id = this.counter++; this.worker.postMessage({ id: id, modules: (typeof modules === 'string' ? [modules] : modules) || [], callback: String(callback), }); var dfd = new Promise.Deferred(); this.deferreds[id] = dfd; dfd.promise.test = this._wrapTest.bind(this, dfd.promise); return dfd.promise; }, }; if (typeof window === undefined || !window.Worker) { return null; } return WorkerProxy; });
/** * @flow */ import React, { Children, } from 'react'; import { StyleSheet, View, } from 'react-native'; import PureComponent from '../utils/PureComponent'; import StaticContainer from 'react-static-container'; import invariant from 'invariant'; import _ from 'lodash'; import Actions from '../ExNavigationActions'; import ExNavigatorContext from '../ExNavigatorContext'; import ExNavigationBar from '../ExNavigationBar'; import ExNavigationSlidingTabItem from './ExNavigationSlidingTabItem'; import { ExNavigationTabContext } from '../tab/ExNavigationTab'; import { TabViewAnimated, TabViewPagerPan, TabBarTop, TabBar } from 'react-native-tab-view'; import { createNavigatorComponent } from '../ExNavigationComponents'; import type ExNavigationContext from '../ExNavigationContext'; // TODO: Fill this in type SlidingTabItem = { id: string, element: React.Element<any>, children: Array<React.Element<any>>, }; type Props = { barBackgroundColor?: string, children: Array<React.Element<any>>, indicatorStyle?: any, initialTab: string, lazy?: bool, navigation: any, navigationState: any, onRegisterNavigatorContext: () => any, onChangeTab: (key: string) => any, onUnregisterNavigatorContext: (navigatorUID: string) => void, position: "top" | "bottom", pressColor?: string, renderBefore: () => ?React.Element<any>, renderHeader?: (props: any) => ?React.Element<any>, renderFooter?: (props: any) => ?React.Element<any>, renderLabel?: (routeParams: any) => ?React.Element<any>, style?: any, swipeEnabled?: boolean, tabBarStyle?: any, tabStyle?: any, }; type State = { id: string, navigatorUID: string, tabItems: Array<SlidingTabItem>, parentNavigatorUID: string, }; class ExNavigationSlidingTab extends PureComponent<any, Props, State> { props: Props; state: State; static route = { __isNavigator: true, }; static navigationBarStyles = { borderBottomWidth: 0, elevation: 0, }; static defaultProps = { barBackgroundColor: ExNavigationBar.DEFAULT_BACKGROUND_COLOR, indicatorStyle: {}, position: 'top', pressColor: 'rgba(0,0,0,0.2)', tabStyle: {}, renderBefore: () => null, }; static contextTypes = { parentNavigatorUID: React.PropTypes.string, }; static childContextTypes = { parentNavigatorUID: React.PropTypes.string, navigator: React.PropTypes.instanceOf(ExNavigationTabContext), }; constructor(props, context) { super(props, context); this.state = { tabItems: [], id: props.id, navigatorUID: props.navigatorUID, parentNavigatorUID: context.parentNavigatorUID, }; } getChildContext() { return { navigator: this._getNavigatorContext(), parentNavigatorUID: this.state.navigatorUID, }; } componentWillMount() { let tabItems = this._parseTabItems(this.props); this._registerNavigatorContext(); let routes = tabItems.map(({ id, title }) => ({ title, key: id })); let routeKeys = routes.map(r => r.key); this.props.navigation.dispatch(Actions.setCurrentNavigator( this.state.navigatorUID, this.state.parentNavigatorUID, 'slidingTab', {}, routes, this.props.initialTab ? routeKeys.indexOf(this.props.initialTab) : 0, )); } componentWillUnmount() { this.props.navigation.dispatch(Actions.removeNavigator(this.state.navigatorUID)); this.props.onUnregisterNavigatorContext(this.state.navigatorUID); } componentWillReceiveProps(nextProps) { // TODO: Should make it possible to dynamically add children after initial render? // if (nextProps.children && nextProps.children !== this.props.children) { // this._parseTabItems(nextProps); // } } componentDidUpdate(prevProps) { if (prevProps.navigation.dispatch !== this.props.navigation.dispatch) { this._registerNavigatorContext(); } // When we're changing tabs, let's make sure we set the current navigator to be the controlled navigator, // if it exists. if (prevProps.navigationState !== this.props.navigationState) { const navigationState = this.props.navigationState; const currentTabKey = navigationState.routes[navigationState.index].key; const navigatorUIDForTabKey = this._getNavigatorContext().getNavigatorUIDForTabKey(currentTabKey); if (navigatorUIDForTabKey) { this.props.navigation.dispatch( Actions.setCurrentNavigator(navigatorUIDForTabKey) ); } } } render() { if (!this.props.children || !this.state.tabItems) { return null; } const navigationState: ?Object = this._getNavigationState(); if (!navigationState) { return null; } if (this.state.tabItems.length !== navigationState.routes.length) { return null; } return ( <TabViewAnimated lazy={this.props.lazy} style={[styles.container, this.props.style]} navigationState={navigationState} renderScene={this._renderScene} renderPager={this._renderPager} renderHeader={this.props.renderHeader || (this.props.position !== 'bottom' ? this._renderTabBar : undefined)} renderFooter={this.props.renderFooter || (this.props.position === 'bottom' ? this._renderTabBar : undefined)} onRequestChangeTab={this._setActiveTab} /> ); } _renderPager = (props) => { return ( <TabViewPagerPan {...props} swipeEnabled={this.props.swipeEnabled} /> ); } _renderScene = ({ route }) => { let tabItem = this.state.tabItems.find(i => i.id === route.key); if (tabItem) { return tabItem.element; } else { return null; } }; _renderTabBar = (props) => { const TabBarComponent = this.props.position === 'top' ? TabBarTop : TabBar; const tabBarProps = { pressColor: this.props.pressColor, indicatorStyle: this.props.indicatorStyle, tabStyle: this.props.tabStyle, renderLabel: this.props.renderLabel, style: [{backgroundColor: this.props.barBackgroundColor}, this.props.tabBarStyle], }; return ( <View> {this.props.renderBefore()} <TabBarComponent {...props} {...tabBarProps} /> </View> ); } _updateRenderedTabKeys(props, currentRenderedTabKeys) { const navState = this._getNavigationState(props); const currentTabItems = navState.routes.map(c => c.key); const selectedChild = navState.routes[navState.index]; return [ ..._.uniq(_.without([...currentRenderedTabKeys, ...currentTabItems], selectedChild.key)), selectedChild.key, ]; } _parseTabItems(props) { const tabItems = Children.map(props.children, (child, index) => { invariant( child.type === ExNavigationSlidingTabItem, 'All children of SlidingTabNavigation must be SlidingTabNavigationItems.', ); const tabItemProps = child.props; let tabItem = { ..._.omit(tabItemProps, ['children']), }; invariant( !tabItem.renderLabel, 'renderLabel should be passed to SlidingTabNavigation instead of SlidingTabNavigationItem.', ); if (Children.count(tabItemProps.children) > 0) { tabItem.element = Children.only(tabItemProps.children); } return tabItem; }); this.setState({ tabItems, }); return tabItems; } _setActiveTab = (i) => { let tabItem = this.state.tabItems[i]; let key = tabItem.id; this._getNavigatorContext().jumpToTab(key); if (typeof this.props.onChangeTab === 'function') { this.props.onChangeTab(key); } } _getNavigationState(props: ?Props): Object { if (!props) { props = this.props; } const { navigationState } = props; return navigationState; } _registerNavigatorContext() { this.props.onRegisterNavigatorContext( this.state.navigatorUID, new ExNavigationTabContext( this.state.navigatorUID, this.state.parentNavigatorUID, this.state.id, this.props.navigation, ) ); } _getNavigatorContext(): ExNavigationTabContext { const navigatorContext: any = this.props.navigation.getNavigatorByUID(this.state.navigatorUID); return (navigatorContext: ExNavigationTabContext); } } export default createNavigatorComponent(ExNavigationSlidingTab); const styles = StyleSheet.create({ container: { flex: 1, }, });
import { PULLING_TREND_GIF, PULLED_TREND_GIF, SEARCH_RESULT, SEARCHING_GIF_TAGS, RESET_TRENDGIF } from '../actions/giphy'; const DEFAULT_STATE = { loading: false, trendGifs: [], searchLoading: false, searchResult:[], offSet: 0 }; export default function giphyReducer(state = DEFAULT_STATE, action){ switch(action.type){ case SEARCHING_GIF_TAGS: return { ...state, searchLoading: true } case SEARCH_RESULT: return { ...state, searchResult: action.searchResult, searchLoading: false } case PULLING_TREND_GIF: return { ...state, loading: true } case PULLED_TREND_GIF: return { ...state, loading: false, trendGifs: [...state.trendGifs, ...action.gifs], offSet: action.offSet} case RESET_TRENDGIF: return DEFAULT_STATE; default: return state; } }
//Crime Change Highcharts Script// $(function () { $('#crimechange').highcharts({ chart: { type: 'column' }, title: { text: 'Change in Violent Crime Since 2010', style: { color: '#FF6F40', font: 'bold 36px "Trebuchet MS", Verdana, sans-serif' } }, xAxis: { categories: ['Detroit', 'Memphis', 'Baltimore', 'Milwaukee', 'Nashville', 'Indianapolis', 'Washington, DC', 'Philadelphia', 'Houston', 'Oklahoma City'] }, credits: { enabled: false }, series: [{ name: 'Change in the number of violent crimes per 100,000 since 2010', color: 'rgba(56,66,79,1)', data: [-255, 142, -95, 230, 92, 26, -63, -55, -79, 4] }, ] }); }); //Script for Top 20 Hicharts// $(function () { $('#crimechart').highcharts({ chart: { type: 'column' }, title: { text: 'Top Ten Most Violent Cities', style: { color: '#FF6F40', font: 'bold 36px "Trebuchet MS", Verdana, sans-serif' } }, xAxis: { categories: [ 'Detroit', 'Memphis', 'Baltimore', 'Milwaukee', 'Nashville', 'Indianapolis', 'Washington, DC', 'Philadelphia', 'Houston', 'Oklahoma City' ] }, yAxis: [{ min: 0, title: { text: 'Violent Crime Rate' } }, { title: { text: '' }, opposite: true }], legend: { shadow: false }, tooltip: { shared: true }, plotOptions: { column: { grouping: false, shadow: false, borderWidth: 0 } }, series: [{ name: '2010', color: 'rgba(56,66,79,.6)', data: [2378, 1608, 1500, 1065, 1124, 1160, 1241, 1215, 1071, 915], pointPadding: 0.0, pointPlacement: -0.0 }, { name: '2012', color: 'rgba(56,66,79,1)', data: [2123, 1750, 1405, 1295, 1216, 1186, 1178, 1160, 993, 919], pointPadding: 0.2, pointPlacement: -0.0 } ] }); }); //Scripts for Baltimore Detroit Comparison $(function () { $('#Detroit').highcharts({ chart: { type: 'line' }, title: { text: 'Violent Crimes per 100,000', text: 'Top Ten Most Violent Cities', style: { color: '#FF6F40', font: 'bold 36px "Trebuchet MS", Verdana, sans-serif' } }, subtitle: { text: 'Source: Bureau of Justice Statistics' }, xAxis: { categories: ['2002', '2003', '2004', '2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012'], labels: { style: { color: '#C2CBCE' } } }, yAxis: { labels:{enabled: false}, title: { text: '', labels: { style: { color: '#C2CBCE' } } } }, plotOptions: { line: { dataLabels: { enabled: false }, enableMouseTracking: true } }, series: [{ name: 'Detroit', data: [2073,2018,1740,2358,2419,2287,1985, 1992,2378,2137,2123], color: '#FF6F40', }, { name: 'Baltimore', data: [2055, 1735,1839,1755,1697,1631,1589,1513,1500,1418,1405], color: '#38424F', }] }); });
export default function (target, value) { function unshift ({state, input, resolveArg}) { if (!resolveArg.isTag(target, 'state')) { throw new Error('Cerebral operator.unshift: You have to use the STATE TAG as first argument') } state.unshift(resolveArg.path(target), resolveArg.value(value)) } unshift.displayName = `operator.unshift(${String(target)}, ${String(value)})` return unshift }
/** * User Schema */ var mongoose = require('mongoose'); var Schema = mongoose.Schema; var userSchema = new Schema({ _id:String, email:String, last_name:String, first_name:String, token:String }); module.exports = mongoose.model('users', userSchema);
// hey webpack const { resolve } = require('path') module.exports = env => { return { context: resolve('src'), entry: './js/ClientApp.js', output: { path: resolve('dist'), filename: './bundle.js', publicPath: 'http://localhost:8080/dist/' }, resolve: { extensions: ['.js'] }, devServer: { historyApiFallback: true }, stats: { colors: true, reasons: true, chunks: true }, devtool: env.prod ? 'source-map' : 'eval', module: { loaders: [ {enforce: 'pre', test: /\.js$/, loaders: ['eslint-loader'], exclude: /node_modules/}, {test: /\.js$/, loaders: ['babel-loader'], exclude: /node_modules/} ] } } }
/* ************************************************************************ Copyright: 2013 Hericus Software, LLC License: The MIT License (MIT) Authors: Steven M. Cherry ************************************************************************ */ /* ************************************************************************ #asset(PACKAGE/icon/64x64/shadow/server_to_client.png) ************************************************************************ */ /** This class defines a dialog that presents a list box * to the user. You can set the window title, icon, and label to customize * the presentation of the window. */ qx.Class.define("PACKAGE.dialog.LRTaskDialog", { extend : PACKAGE.dialog.OKDialog, /** You may pass in window title, icon, and label values. */ construct : function ( lrTask, callback, errorCallback, callbackThis ) { this.lrTask = lrTask; this.icon = "PACKAGE/icon/64x64/shadow/server_to_client.png"; this.label = "The Server is working on your request..."; // Call the parent constructor: this.base( arguments, this.lrTask.getTaskName()); this.ok_btn.setLabel( "Close" ); this.callback = callback; this.callbackThis = callbackThis; this.errorCallback = errorCallback; // Setup our timer to continually call this.runLongPoll; this.timer = qx.util.TimerManager.getInstance(); this.timerID = this.timer.start( this.runLongPoll, 1000, this, null, 1000 ); this.debug("timer started"); this.ok_btn.addListener("execute", function() { this.timer.stop( this.timerID ); }, this ); }, members : { /** This method is used to allow child classes to override the size * of this dialog box. */ doSetSpace : function () { this.setWidth(400); this.setHeight(200); }, /** This method is used to allow child classes to add objects to our * main layout. */ doFormLayout : function ( layout ) { var a1 = new qx.ui.basic.Atom(this.label, this.icon ); layout.add(a1); this.pb = new qx.ui.indicator.ProgressBar(this.lrTask.getTaskStart(), this.lrTask.getTaskFinish() ); this.pb_label = new qx.ui.basic.Label( this.lrTask.getTaskMsg() ); layout.add( this.pb ); layout.add( this.pb_label ); }, /** This method allows you to set the focus of whichever field you * want when this window becomes active. This will be called every * time this window becomes the active window, which will only happen * once for a modal window. */ setFocusFirst : function () { }, /** This loop will poll the server and update the progress bar with information * about our long running task on the server. When it is complete, we'll call * the original call-back with the final response document. */ runLongPoll : function(userData, timerId) { this.debug("runLongPoll"); // We have to send the requests directly rather than going through Api.SendRequest, because // we will handle the LRTask objects comming back during the interim of the long running // task. If we used Api.SendRequest, it would end up opening another instance of us for // each LRTask object that it received. var req = new qx.bom.request.Xhr; req.onreadystatechange = qx.lang.Function.bind( function() { if(req.readyState != 4){ return; // not ready yet } this.debug("readystatechange"); if(!req.responseXML){ this.debug("no response xml"); PACKAGE.Statics.doAlert("Server is not responding, please try again"); this.timer.stop( timerId ); // stop our timer to prevent further calls to this method this.okPressed = false; this.close(); if(this.errorCallback){ this.errorCallback.call( this.errorThis, req ); } return; } var response = req.responseXML.documentElement; if(PACKAGE.Api.returnHasErrors( response, true, this.errorCallback, this.callbackThis ) ){ this.debug("response has errors"); this.timer.stop( timerId ); // stop our timer to prevent further calls to this method this.okPressed = false; this.close(); if(this.errorCallback){ this.errorCallback.call( this.callbackThis, req ); } return; } if(response.nodeName === "GetOneLRTask"){ this.debug("node name is GetOneLRTask"); // This is still our long running task. Update our progress bar with new information var objectList = PACKAGE.sqldo.LRTask.readElementChildren( response ); if(objectList.length !== 0){ this.lrTask = objectList[0]; this.pb.setMaximum( this.lrTask.getTaskFinish() ); this.pb.setValue( this.lrTask.getTaskCurrent() ); this.pb_label.setValue( this.lrTask.getTaskMsg() ); } } else { // The long running task has completed, and now we have the correct response. Call // the original callback and fire the apiCallSucceeded event this.debug("node name is not GetOneLRTask: " + response.nodeName ); this.timer.stop( timerId ); // stop our timer to prevent further calls to this method this.ok_btn.press(); this.ok_btn.execute(); if(this.callback){ this.callback.call( this.callbackThis, response ); } if(this.callbackThis){ this.callbackThis.fireEvent( "apiCallSucceeded" ); } } }, this ); // Now Send the request var requestDoc = qx.xml.Document.create( null, "GetOneLRTask" ); var requestRoot = requestDoc.documentElement; this.lrTask.createXMLElement( requestRoot ); req.open( "POST", "/logic/utils/GetOneLRTask", true); req.send( PACKAGE.Statics.xmlDocToString( requestDoc ) ); this.debug("sending GetOneLRTask api"); } }, destruct : function() { //this._disposeObjects( "listBox" ); } });
var fs = require('fs'); var url='https://mobile.bet365.com/#type=InPlay;key=;ip=1;lng=1'; var page = require('webpage').create(); //page.settings.userAgent ="Mozilla/5.0 (Linux; Android 4.2.2; en-us; SAMSUNG GT-I9195 Build/JDQ39) AppleWebKit/535.19 (KHTML, like Gecko) Version/1.0 Chrome/18.0.1025.308 Mobile Safari/535.19"; page.settings.webSecurityEnabled=false; page.settings.userAgent ="Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.23 Mobile Safari/537.36"; page.viewportSize = {width: 360, height: 640}; page.open(url, function() { page.injectJs("jquery.js"); setInterval(function(){ eval( fs.read('in.js') ); fs.write('in.js', '', 'w'); },1000); });
define(['text!./user-info.html', 'app', 'authentication', 'services/navigation'], function(template, app) { 'use strict'; app.directive("userInfo", ['navigation', 'authentication', '$location', '$window', function (navigation, authentication, $location, $window) { return { restrict: 'E', template: template, replace: true, transclude: false, scope: {}, link: function ($scope) { navigation.securize(); authentication.getUser().then(function(u){ $scope.user = u; }); $scope.actionPassword = function () { var redirect_uri = $window.encodeURIComponent($location.protocol()+'://'+$location.host()+':'+$location.port()+'/'); $window.location.href = 'https://accounts.cbd.int/password?redirect_uri='+redirect_uri; }; //============================================================ // // //============================================================ $scope.actionProfile = function () { var redirect_uri = $window.encodeURIComponent($location.protocol()+'://'+$location.host()+':'+$location.port()+'/'); $window.location.href = 'https://accounts.cbd.int/profile?redirect_uri='+redirect_uri; }; } }; }]); });
var testName = 'new'; var test = require('tape'); var path = require('path'); var config = require('../configure'); var parsers = require('../parsers'); var configDir = path.join(__dirname, 'fixtures/config/' + testName); // custom parsers var ini = require('ini'); var yaml = require('js-yaml'); var json5 = require('json5'); test('new', function(t) { var data; t.plan(8); // -- default instance data = config({ directories: configDir }); t.deepEqual(data, { fields: { field_1: '1 from js', field_2: '2 from json', field_3: '3 from json' } }, 'expect to get js and json files combined'); data = config({ directories: configDir, parsers: {ini: ini.parse, json: null}}); t.deepEqual(data, { fields: { field_0: '0 from ini', field_1: '1 from js', field_2: '2 from js' } }, 'expect to get ini and js files combined'); // -- first level, no `js` config = config.new({parsers: {js: null}}); data = config({ directories: configDir }); t.deepEqual(data, { fields: { field_2: '2 from json', field_3: '3 from json' } }, 'expect to get just json file'); data = config({ directories: configDir, parsers: {ini: ini.parse}}); t.deepEqual(data, { fields: { field_0: '0 from ini', field_1: '1 from ini', field_2: '2 from json', field_3: '3 from json' } }, 'expect to get ini and json files combined'); // -- second level, with `json5` and `yaml` config = config.new({parsers: { json5: json5.parse, yaml : function(str) { return yaml.safeLoad(str); } }}); data = config({ directories: configDir }); t.deepEqual(data, { fields: { field_2: '2 from json', field_3: '3 from json5', field_4: '4 from yaml', field_5: '5 from yaml' } }, 'expect to get json, json5 and yaml files combined'); data = config({ directories: configDir, parsers: {ini: ini.parse}}); t.deepEqual(data, { fields: { field_0: '0 from ini', field_1: '1 from ini', field_2: '2 from json', field_3: '3 from json5', field_4: '4 from yaml', field_5: '5 from yaml' } }, 'expect to get ini, json, json5 and yaml files combined'); // -- three levels deep, with `ini` and `yml` config = config.new({parsers: { ini: ini.parse, yml: config.parsers.yaml }}); data = config({ directories: configDir }); t.deepEqual(data, { fields: { field_0: '0 from ini', field_1: '1 from ini', field_2: '2 from json', field_3: '3 from json5', field_4: '4 from yaml', field_5: '5 from yml', field_6: '6 from yml' } }, 'expect to get ini, json, json5, yaml and yml files combined'); data = config({ directories: configDir, parsers: {js: parsers.js}}); t.deepEqual(data, { fields: { field_0: '0 from ini', field_1: '1 from js', field_2: '2 from json', field_3: '3 from json5', field_4: '4 from yaml', field_5: '5 from yml', field_6: '6 from yml' } }, 'expect to get ini, js, json, json5, yaml and yml files combined'); });
var heinzelDatatypes = require('../index'), dataTypes = require('../lib/datatypes'), dataTypeProvider = require('../lib/datatypesProvider'); require('mocha-as-promised')(); describe('Datatypes', function() { describe('#map', function() { it('should map postgres integer to heinzel integer', function () { var mapper = heinzelDatatypes.createMapper(dataTypeProvider.pg, dataTypeProvider.heinzel); return mapper(dataTypes.pg.Integer).should.become('int'); }); it('should map postgres double prescision to heinzel double', function() { var mapper = heinzelDatatypes.createMapper(dataTypeProvider.pg, dataTypeProvider.heinzel); return mapper(dataTypes.pg['double precision']).should.become('double'); }); it('should fail if mapping file doesn\'t exist', function () { var mapper = heinzelDatatypes.createMapper('nonExistingMappingSource', dataTypeProvider.heinzel); return mapper(dataTypes.pg.Integer).should.be.rejected; }); }); });
/** * (c)2015 Create at: 2015-05-29 * @author Scm <ejbscm@hotmail.com> * @docauthor Scm <ejbscm@hotmail.com> * @filepath form.js * * eui.js may be freely distributed under the MIT license. * * @namespace Form * @desc 序列化表单提交参数及赋值等相关封装. */ (function($){ /** * 将用作提交的表单元素的值编译成拥有`name`和`value`对象组成的数组。 * 不能使用的表单元素,buttons,未选中的radio buttons/checkboxs 将会被跳过。 结果不包含file inputs的数据。 * * serializeArray() ⇒ array * * @function * @name #serializeArray * @memberof Form * @returns {Array} * @example * $('form').serializeArray() * //=> [{ name: 'size', value: 'micro' }, * // { name: 'name', value: 'Eui' }] */ $.fn.serializeArray = function() { var name, type, result = [], add = function(value) { if (value.forEach) return value.forEach(add) result.push({ name: name, value: value }) } if (this[0]) $.each(this[0].elements, function(_, field){ type = field.type, name = field.name if (name && field.nodeName.toLowerCase() != 'fieldset' && !field.disabled && type != 'submit' && type != 'reset' && type != 'button' && type != 'file' && ((type != 'radio' && type != 'checkbox') || field.checked)) add($(field).val()) }) return result } /** * 在Ajax post请求中将用作提交的表单元素的值编译成 URL编码的 字符串。 * * serialize() ⇒ string * * @function * @name #serialize * @memberof Form * @return {String} 编码后的字符串,用`&`连接 */ $.fn.serialize = function(){ var result = [] this.serializeArray().forEach(function(elm){ result.push(encodeURIComponent(elm.name) + '=' + encodeURIComponent(elm.value)) }) return result.join('&') } /** * 表单批量赋值,根据`name`属性匹配. * * 备注:如果是`span`标签,那么是通过`initname`属性识别. * * @function * @name #setValues * @memberof Form * @param {Object} data 表单的初始数据 */ $.fn.setValues = function(data){ var form = this; for(var name in data){ var val = data[name]; if (!_checkField(name, val)){ form.find('input[name="'+name+'"]').val(val); form.find('textarea[name="'+name+'"]').val(val); form.find('select[name="'+name+'"]').val(val); $('span[initname="'+name + '"]',form).text(val); } } // check the checkbox and radio fields function _checkField(name, val){ var cc = form.find('input[name="'+name+'"][type=radio], input[name="'+name+'"][type=checkbox]'); if (cc.length){ cc.prop('checked', false); cc.each(function(){ var f = $(this); if (f.val() == String(val) || $.inArray(f.val(), $.isArray(val)?val:[val]) >= 0){ f.prop('checked', true); } }); return true; } return false; } } /** * 为 “submit” 事件绑定一个处理函数,或者触发元素上的 “submit” 事件。 * 当没有给定function参数时,触发当前表单“submit”事件, 并且执行默认的提交表单行为,除非调用了 `preventDefault()`。 * * 当给定function参数时,在当前元素上它简单得为其在“submit”事件绑定一个处理函数。 * * submit() ⇒ self * submit(function(e){ ... }) ⇒ self * * @function * @name #submit * @memberof Form * @param {Function} callback 成功回调函数. * @returns {$} */ $.fn.submit = function(callback) { if (0 in arguments) this.bind('submit', callback) else if (this.length) { var event = $.Event('submit') this.eq(0).trigger(event) if (!event.isDefaultPrevented()) this.get(0).submit() } return this } })(Eui);
import { test, moduleForModel } from "ember-qunit"; import { stubRequest } from 'ember-cli-fake-server'; import Ember from "ember"; const {extend} = Ember.$; function getMetadata(store, type) { return extend({}, store._metadataFor(type)); } moduleForModel('moose', 'Metadata', { needs: ['serializer:application', 'adapter:application'] }); test('loads meta data from top-level non-reserved keys for collection resources', function(assert){ stubRequest('get', '/mooses', (request) => { request.ok({ page: 1, total_pages: 2, _embedded: { mooses: [{ id: 'moose-9000', _links: { self: { href: "http://example.com/mooses/moose-9000" } } }] } }); }); const store = this.store(); return store.findAll('moose').then(function(mooses){ assert.deepEqual(getMetadata(store, 'moose'), {page: 1, total_pages: 2}); }); }); test('loads meta data from top-level non-reserved keys for collection resources returned from store.query', function(assert){ stubRequest('get', '/mooses', (request) => { request.ok({ page: 1, total_pages: 2, _embedded: { mooses: [{ id: 'moose-9000', _links: { self: { href: "http://example.com/mooses/moose-9000" } } }] } }); }); const store = this.store(); return store.query('moose', {}).then(function(mooses){ assert.deepEqual(getMetadata(store, 'moose'), {page: 1, total_pages: 2}); }); }); test('loads meta data from explicit `meta` key for collections', function(assert){ stubRequest('get', '/mooses', (request) => { request.ok({ meta: { page: 1, total_pages: 2, }, _embedded: { mooses: [{ id: 'moose-9000', _links: { self: { href: "http://example.com/mooses/moose-9000" } } }] } }); }); const store = this.store(); return store.findAll('moose').then(function(mooses){ assert.deepEqual(getMetadata(store, 'moose'), {page: 1, total_pages: 2}); }); }); test('includes links in meta data for collections', function(assert){ stubRequest('get', '/mooses', (request) => { request.ok({ _links: { self: { href: '/mooses' } }, some_meta_val: 42, _embedded: { mooses: [{ id: 'moose-9000', _links: { self: { href: "http://example.com/mooses/moose-9000" } } }] } }); }); const store = this.store(); return store.findAll('moose').then(function(mooses){ assert.deepEqual(getMetadata(store, 'moose'), {links: {self: '/mooses'}, some_meta_val: 42}); }); }); test('loads meta data from explicit `meta` key for single resources', function(assert){ stubRequest('get', '/mooses/moose-9000', (request) => { request.ok({ meta: { page: 1, total_pages: 2, }, _links: { self: { href: '/mooses/1' } }, id: 'moose-9000' }); }); const store = this.store(); return Ember.run(function(){ store.findRecord('moose', 'moose-9000').then(function(mooses){ assert.deepEqual(getMetadata(store, 'moose'), {page: 1, total_pages: 2}); }); }); });
import {combineReducers, createStore} from 'redux'; import React from 'react'; import ReactDOM from 'react-dom'; const todo = (state, action) => { switch (action.type) { case 'ADD_TODO': return { id: action.id, text: action.text, completed: false }; case 'TOGGLE_TODO': if (state.id !== action.id) { return state; } return { ...state, completed: !state.completed }; default: return state; } }; const todos = (state = [], action) => { switch (action.type) { case 'ADD_TODO': return [ ...state, todo(undefined, action) ]; case 'TOGGLE_TODO': return state.map(t => todo(t, action) ); default: return state; } }; const visibilityFilter = ( state = 'SHOW_ALL', action ) => { switch (action.type) { case 'SET_VISIBILITY_FILTER': return action.filter; default: return state; } }; const todoApp = combineReducers({ todos, visibilityFilter }); const store = createStore(todoApp); let nextTodoId = 0; class TodoApp extends React.Component { render() { return ( <div> <input ref={node => { this.input = node; }} /> <button onClick={() => { store.dispatch({ type: 'ADD_TODO', text: this.input.value, id: nextTodoId }); nextTodoId += 1; this.input.value = ''; }}> Add TODO </button> <ul> {this.props.todos.map(todo => <li key={todo.id}>{todo.text}</li> )} </ul> </div> ); } } const render = () => { ReactDOM.render( <TodoApp todos={store.getState().todos} />, document.getElementById('app') ); }; store.subscribe(render); render();
var fs = require('fs'), glob = require('glob'), icons = require('paradigm-icons-partial-handlebars'), path = require('path') module.exports = function(options) { var assets = (options.assets || false), cwd = options.cwd, Handlebars = options.Handlebars, helpersPath = options.helpersPath, partialsPath = options.partialsPath // Load helpers var helpers = glob.sync(helpersPath + '/**/*.js', {cwd: cwd}) helpers.forEach( function(helper) { require(path.join(cwd, helper))(Handlebars) }) // Load partials var partials = glob.sync(partialsPath + '/**/*.hbs') partials.forEach( function(partial) { var matches = partial.split('.hbs') if (!matches) { return } var name = matches[0].replace(partialsPath + '/', '') var template = fs.readFileSync(path.join(cwd, partial), 'utf8') Handlebars.registerPartial(name, template) }) var partialLoaders = glob.sync(partialsPath + '/**/*.js') partialLoaders.forEach( function(partialLoader) { require(path.join(cwd, partialLoader))(Handlebars) }) }
import Templates from "../Templates.js"; import AuthController from "../controllers/Auth.js"; import translations from "../nls/views/login.js"; var LoginView = { "template": Templates.getView( "login" ), data(){ return { "username": "", "password": "", translations }; }, "on": { login(){ var data = this.get(); AuthController .login( data.username, data.password ) .catch( () => { /* eslint "no-console": "off", "no-debugger": "off", "vars-on-top": "off", "no-unused-vars": "off", "complexity": "off" */ console.log( "handle errors in form" ); } ); return false; } } }; export default LoginView;
// index.js console.log('index.js: I get a arequire() function for my module'); var arequire = require('../../../lib/arequire.js')(require) // usualy do : require('nway/arequire')(require) console.log('index.js: For demo purpose, I export my application object'); var application = module.exports = { goFoo: function(callback) { console.log('index.js: goFoo(). Asynchronously require foo.js. This is an application split point.'); arequire('./foo.js', function(err, foo) { if(err) throw err; console.log('index.js: foo.js is imported. Execute it exported function foo().'); foo(); callback && callback(); }) } ,goBar: function(callback) { console.log('index.js: goBar(). Asynchronously require bar.js. This is an application split point.'); arequire('./bar.js', function(err, bar) { if(err) throw err; console.log('index.js: bar.js is imported. Execute it exported function bar().'); bar(); callback && callback(); }) } } console.log('index.js: Go in the FOO part of the application:'); application.goFoo(function() { console.log('index.js: Now go in the BAR part of the application:'); application.goBar(); });
var DOCUMENTER_CURRENT_VERSION = "previews/PR367";
import { execFile } from 'child_process'; import fs from 'fs'; import path from 'path'; import { initLog } from 'roc'; import flow from 'flow-bin'; import { default as flowconfig } from '../resources/flowconfig'; const log = initLog(); const HEAVY_EXCLAMATION_MARK_SYMBOL = '❗'; const expectedOutput = stdout => /Found \d+ error[s]?/.test(stdout); const numErrors = (stdout) => /Found (\d+) error[s]?/.exec(stdout)[1]; const removeErrorFooter = (stdout) => stdout.replace(/Found \d+ error[s]?/, ''); const errorString = (num) => ((num > 1) ? 'errors' : 'error'); const configFileExists = () => fs.existsSync(path.join(process.cwd(), '.flowconfig')); const createConfigFile = () => { const target = path.join(process.cwd(), '.flowconfig'); fs.writeFileSync(target, flowconfig); }; export default () => () => { if (!configFileExists()) { log.small.warn('No .flowconfig file found - creating.'); log.small.info('You should commit .flowconfig to your source code repsository.'); createConfigFile(); } else { log.small.info('Using .flowconfig file in root of project.'); } log.small.info('Starting Flow type check. This may take a short while, please be patient.\n'); return () => execFile(flow, ['check'], (err, stdout) => { if (err && expectedOutput(stdout)) { const num = numErrors(stdout); log.small.raw('warn', 'red', HEAVY_EXCLAMATION_MARK_SYMBOL)(`Flow found ${num} ${errorString(num)}:\n`); log.small.raw('error')(removeErrorFooter(stdout)); } else if (err) { log.small.raw('warn', 'red', HEAVY_EXCLAMATION_MARK_SYMBOL)( 'Flow terminated abnormally - you may have an error in your configuration.\n'); log.small.raw('error')(err); } else { log.small.success(stdout); } }); };
/************************************************************************************** ** Author: Guillaume ARM ************************************************************** ** main.js: Some Fjs tests ************************************************************ **************************************************************************************/ //import { __, inject, flip, apply, foldl, compose } from '.' // global scope injector const globalScopeInjector = lib => { lib.globalScopeInjector = undefined for (let f of Object.keys(lib)) global[f] = lib[f] } import * as F from '.' globalScopeInjector(F); // Test compose and foldl // This reads from right to left const rev = ([...xs]) => { return foldl ((acc,x) => [x, ...acc]) ('') (xs); } const toString = t => t.join("") console.log ( compose ([toString, rev]) ("Hello World") ) // Test appl, content:truey const f1 = (a,b,c,d) => a+b+c+d const f2 = apply(f1, 1, __, 3, __) console.log(f2(2,4)) let initWithHello = flip (inject) ({id: 1, data: [], content: "Hello World"}) console.log([{id: 1, content:true}].map(initWithHello))
const { adminBroadcast, broadcastAndEmit, emit, emitError } = require('../utils'); const { getActiveGenfors } = require('../models/meeting.accessors'); const { validatePin } = require('../managers/meeting'); const { addAnonymousUser } = require('../managers/user'); const { validatePasswordHash, publicUser } = require('../managers/user'); const { getUserByUsername } = require('../models/user.accessors'); const logger = require('../logging'); const { AUTH_REGISTER, AUTH_AUTHENTICATED } = require('../../common/actionTypes/auth'); const { ADD_USER } = require('../../common/actionTypes/users'); const register = async (socket, data) => { const { pin, passwordHash } = data; const user = await socket.request.user(); const username = user.onlinewebId; const genfors = await getActiveGenfors(); const { completedRegistration } = user; if (completedRegistration) { let validPasswordHash = false; try { validPasswordHash = await validatePasswordHash(user, passwordHash); } catch (err) { logger.debug('Failed to validate user', { username }); emitError(socket, new Error('Validering av personlig kode feilet')); return; } if (validPasswordHash) { emit(socket, AUTH_AUTHENTICATED, { authenticated: true }); } else { emitError(socket, new Error('Feil personlig kode')); } return; } if (!genfors.registrationOpen) { emitError(socket, new Error('Registreringen er ikke åpen.')); return; } if (!await validatePin(pin)) { logger.silly('User failed pin code', { username, pin }); emitError(socket, new Error('Feil pinkode')); return; } try { await addAnonymousUser(username, passwordHash); } catch (err) { logger.debug('Failed to register user', { username }); emitError(socket, new Error('Noe gikk galt under registreringen. Prøv igjen')); return; } logger.silly('Successfully registered', { username }); emit(socket, AUTH_AUTHENTICATED, { authenticated: true }); const registeredUser = await getUserByUsername(username, genfors.id); broadcastAndEmit(socket, ADD_USER, publicUser(registeredUser)); adminBroadcast(socket, ADD_USER, publicUser(registeredUser, true)); }; const listener = (socket) => { async function action(data) { switch (data.type) { case AUTH_REGISTER: { await register(socket, data); break; } default: break; } } socket.on('action', action); }; module.exports = { listener, register, };
(function() { var root = this, Backbone = root.Backbone, Handlebars = root.Handlebars, Thorax = root.Thorax, _ = root._, $ = root.$, _destroy = Thorax.View.prototype.destroy, _on = Thorax.View.prototype.on; _.extend(Thorax.Util, { _cloneEvents: function(source, target, key) { source[key] = _.clone(target[key]); //need to deep clone events array _.each(source[key], function(value, _key) { if (_.isArray(value)) { target[key][_key] = _.clone(value); } }); } }); [ [Backbone, 'Router'], [Backbone, 'Collection'], [Backbone, 'Model'], [Backbone, 'View'], [Thorax, 'View'], [Thorax, 'HelperView'] ].forEach(function(definition) { var obj = definition[0], key = definition[1]; var klass = Thorax.Util.extendConstructor(obj, key, function($super) { this.constructor._events.forEach(function(event) { this.on.apply(this, event); }, this); if (this.events) { _.each(Thorax.Util.getValue(this, 'events'), function(handler, eventName) { this.on(eventName, handler, this); }, this); } $super.apply(this, Array.prototype.slice.call(arguments, 1)); }); var _extend = klass.extend; _.extend(klass, { _events: [], extend: function() { var child = _extend.apply(this, arguments); Thorax.Util._cloneEvents(this, child, '_events'); return child; }, on: function(eventName, callback) { if (typeof eventName === 'object') { _.each(eventName, function(value, key) { this.on(key, value); }, this); } else { if (_.isArray(callback)) { callback.forEach(function(cb) { this._events.push([eventName, cb]); }, this); } else { this._events.push([eventName, callback]); } } return this; } }); }); _.extend(Thorax.View.prototype, { freeze: function(options) { options = _.defaults(options || {}, { dom: true, children: true }); this._eventArgumentsToUnbind && this._eventArgumentsToUnbind.forEach(function(args) { args[0].off(args[1], args[2], args[3]); }); this._eventArgumentsToUnbind = []; this.off(); if (options.dom) { this.undelegateEvents(); } this.trigger('freeze'); if (options.children) { _.each(this.children, function(child, id) { child.freeze(options); }, this); } }, destroy: function() { var response = _destroy.apply(this, arguments); this.freeze(); return response; }, on: function(eventName, handler, context) { if (typeof eventName === 'object') { //events in {name:handler} format if (arguments.length === 1) { _.each(eventName, function(value, key) { this.on(key, value, this); }, this); //events on other objects to auto dispose of when view frozen } else if (arguments.length > 1) { if (!this._eventArgumentsToUnbind) { this._eventArgumentsToUnbind = []; } var args = Array.prototype.slice.call(arguments); this._eventArgumentsToUnbind.push(args); args[0].on.apply(args[0], args.slice(1)); } } else { (_.isArray(handler) ? handler : [handler]).forEach(function(handler) { var params = eventParamsFromEventItem(eventName, handler, context || this); if (params.type === 'DOM') { //will call _addEvent during delegateEvents() if (!this._eventsToDelegate) { this._eventsToDelegate = []; } this._eventsToDelegate.push(params); } else { this._addEvent(params); } }, this); } return this; }, delegateEvents: function(events) { this.undelegateEvents(); if (events) { if (_.isFunction(events)) { events = events.call(this); } this._eventsToDelegate = []; this.on(events); } this._eventsToDelegate && this._eventsToDelegate.forEach(this._addEvent, this); }, //params may contain: //- name //- originalName //- selector //- type "view" || "DOM" //- handler _addEvent: function(params) { if (params.type === 'view') { params.name.split(/\s+/).forEach(function(name) { _on.call(this, name, params.handler, params.context || this); }, this); } else { var boundHandler = containHandlerToCurentView(bindEventHandler.call(this, params.handler), this.cid); if (params.selector) { //TODO: determine why collection views and some nested views //need defered event delegation var name = params.name + '.delegateEvents' + this.cid; if (typeof jQuery !== 'undefined' && $ === jQuery) { _.defer(_.bind(function() { this.$el.on(name, params.selector, boundHandler); }, this)); } else { this.$el.on(name, params.selector, boundHandler); } } else { this.$el.on(name, boundHandler); } } } }); var eventSplitter = /^(\S+)(?:\s+(.+))?/; var domEvents = [ 'mousedown', 'mouseup', 'mousemove', 'mouseover', 'mouseout', 'touchstart', 'touchend', 'touchmove', 'click', 'dblclick', 'keyup', 'keydown', 'keypress', 'submit', 'change', 'focus', 'blur' ]; var domEventRegexp = new RegExp('^(' + domEvents.join('|') + ')'); function containHandlerToCurentView(handler, cid) { return function(event) { var view = $(event.target).view({helper: false}); if (view && view.cid == cid) { handler(event); } } } function bindEventHandler(callback) { var method = typeof callback === 'function' ? callback : this[callback]; if (!method) { throw new Error('Event "' + callback + '" does not exist'); } return _.bind(method, this); } function eventParamsFromEventItem(name, handler, context) { var params = { originalName: name, handler: typeof handler === 'string' ? this[handler] : handler }; if (name.match(domEventRegexp)) { var match = eventSplitter.exec(name); params.name = match[1]; params.type = 'DOM'; params.selector = match[2]; } else { params.name = name; params.type = 'view'; } params.context = context; return params; } })();
'use strict'; /* eslint-disable func-names */ /* eslint-disable prefer-arrow-callback */ const assert = require('assert'); const supertest = require('supertest'); const Xible = require('..'); const CONFIG_PATH = '~/.xible/config.json'; const xible = new Xible({ configPath: CONFIG_PATH }); describe('/api/typedefs', function () { before(function () { this.timeout(10000); return xible.init(); }); after(function () { return xible.close(); }); describe('GET /', function () { it('should return list of typedefs', function () { return supertest(xible.expressApp) .get('/api/typedefs') .expect(200) .expect((res) => assert.equal(res.body.string.name, 'string')); }); }); describe('GET /:typedef', function () { it('string should return single typedef', function () { return supertest(xible.expressApp) .get('/api/typedefs/string') .expect(200) .expect((res) => assert.strictEqual(res.body.color, 'yellow')) .expect((res) => assert.strictEqual(res.body.name, 'string')) .expect((res) => assert.strictEqual(res.body.extends, 'object')); }); it('non existing should return 404', function () { return supertest(xible.expressApp) .get('/api/typedefs/does_hopefully_not_exist_for_real') .expect(404); }); }); });
var fs = require('fs'); var path = require('path'); var superagent = require('superagent'); var restify = require('restify'); var builder = require('botbuilder'); var server = restify.createServer(); var oxford = require('project-oxford'); var telegramDebug = require('./telegram-debug'); var jsonPrettify = require('json-pretty'); /** * START BOOTSTRAP */ var applicationPassword = null; var config = { environment: (process.env.NODE_ENV || 'development'), botCredentials: {}, luisCredentials: {}, visionApiCredentials: {} }; config.botCredentials.appId = process.env.MICROSOFT_APP_ID; config.botCredentials.appPassword = process.env.MICROSOFT_APP_PASSWORD; config.luisCredentials.id = process.env.MICROSOFT_LUIS_ID; config.luisCredentials.key = process.env.MICROSOFT_LUIS_KEY; config.visionApiCredentials.key = process.env.MICROSOFT_VISIONAPI_KEY; var model = `https://api.projectoxford.ai/luis/v1/application?id=${config.luisCredentials.id}&subscription-key=${config.luisCredentials.key}`; var recognizer = new builder.LuisRecognizer(model); var dialog = new builder.IntentDialog({ recognizers: [ recognizer ] }); /** * START CONTROLLER */ var connector = (config.environment === 'development') ? new builder.ConsoleConnector().listen() : new builder.ChatConnector(config.botCredentials); var bot = new builder.UniversalBot(connector); bot.mwReceive.push((message, next) => { if(message.text === 'RESET YOURSELF') { telegramDebug.notify('Bot conversation reset.'); var msg = new builder.Message() .text('You have exited the conversation. I\'m sorry I messed up ):') .address(savedAddress); bot.send(msg); setTimeout(() => { bot.receive( ( new builder .Message() .text('RESET CONVERSATION') .address(savedAddress) ).toMessage() ); }, 1000); } next(); }); bot.dialog('/', dialog); const pathToIntents = path.join(__dirname, '/intents'); const intentListing = fs.readdirSync(pathToIntents); intentListing.forEach(intent => { const currentIntent = require(path.join(pathToIntents, `/${intent}`)); console.info(`Registered intent ${currentIntent.label}`); dialog.matches(currentIntent.label, currentIntent.callbackProvider(builder, bot)); }); // builder.DialogAction.send('We\'ve just launched the Building Information Model Fund from Building and Construction Authority (BCA).')); // dialog.onDefault([ function(session, args, next) { console.log('|----------------------session-----------------------|'); console.log(session); console.log('|---------------------/session-----------------------|'); console.log('|------------------------args------------------------|'); console.log(args); console.log('|-----------------------/args------------------------|'); }, builder.DialogAction.send("It went through") ]); dialog.matches('Upload', function (session, results) { session.beginDialog('/uploadImage'); }); var visionClient = new oxford.Client(config.visionApiCredentials.key); bot.dialog('/uploadImage', [ (session) => { builder.Prompts.attachment(session, "Upload the document and I will keep track of the claim."); }, (session, results) => { results.response.forEach(function (attachment) { visionClient.vision.ocr({ url: attachment.contentUrl, language: 'en' }).then(function (response) { if ((typeof response !== 'undefined') && (typeof response.regions !== 'undefined') && (response.regions.length > 0) && (typeof response.regions[0].lines !== 'undefined')) { var ocrText = ''; response.regions.forEach(data => { data.lines.forEach(line => { ocrText +="\n"; line.words.forEach(word => { ocrText += word.text +" "; }); }); }); var currencyAmount = ocrText.match(/([a-zA-Z]{2,10}|\$)*(\s){0,3}((\d|O|o)+(\.|\,)\s*){1,5}(\d|O|o){2}/g); var others = ocrText; if (currencyAmount !== null) { //telegramDebug.notify(ocrText); session.endDialog("I have added your invoice of " + currencyAmount[currencyAmount.length - 1].split(/\s+/).pop().replace(/(\O|\o)/g,'0') + " ."); } else { session.send("I couldn't read your document, please send a clearer image."); } } else { session.send("I couldn't read your document. Please send it in JPG or PNG format again."); } }, function(err) { console.log(arguments); session.endDialog("I'm sorry, an unknown error has occured. Please send your question again."); }); }); } ]); if(config.environment === 'production') { server.get('/users', function(req, res, next) { const User = require('./users'); res.writeHead(200, { 'Content-Length': Buffer.byteLength(User.getUsers()), 'Content-Type': 'text/html' }); res.write(User.getUsers()); }); server.get('/user/tg', function(req, res, next) { const savedAddress = { "bot": { "id": "bizgrants_bot", "name": "grant_bot" }, "channelId": "telegram", "conversation": { "id": "51225644", "isGroup": false }, "id": "GR1MqlAMOy5", "serviceUrl": "https://telegram.botframework.com", "useAuth": true, "user": { "id": "51225644", "name": "zuiyoung" } }; var msg = new builder.Message() .text('Hi Mr. Tan, your grant application with ID \'SA7661L70XC\' (Market Readiness Assistance by Internal Expansion Singapore) is missing a receipt. ') .address(savedAddress); bot.send(msg); setTimeout(() => { var msgTrigger = new builder.Message() .text('I\'d like to upload a document.') .address(savedAddress); bot.receive(msgTrigger.toMessage()); }, 1300); res.send('done'); }); server.get('/user/fb', function(req, res, next) { const savedAddress = { "bot": { "id": "1286630571400655", "name": "grant_bot" }, "channelId": "facebook", "conversation": { "id": "1104052302964625-1286630571400655", "isGroup": false }, "id": "mid.1478833841639:485bc7c387", "serviceUrl": "https://facebook.botframework.com", "useAuth": true, "user": { "id": "1104052302964625", "name": "Joseph Goh" } }; var msg = new builder.Message() .text('Hi Mr. Tan, your grant application with ID \'SA7661L70XC\' (Market Readiness Assistance by Internal Expansion Singapore) is missing a receipt. ') .address(savedAddress); bot.send(msg); setTimeout(() => { var msgTrigger = new builder.Message() .text('I\'d like to upload a document.') .address(savedAddress); bot.receive(msgTrigger.toMessage()); }, 1300); res.send('done'); }); server.use(restify.bodyParser({ mapParams: true })); server.post('/api/messages', [function(req, res, next) { //telegramDebug.logJson(req.body.channelId); //telegramDebug.logJson(req.body.channelData.message.chat); var exampleData = { "channelData": { "message": { "chat": { "first_name": "Joseph Matthias", "id": 267230627, "last_name": "Goh", "type": "private", "username": "zephinzer" }, "date": 1478760927, "from": { "first_name": "Joseph Matthias", "id": 267230627, "last_name": "Goh", "username": "zephinzer" }, "message_id": 2738, "text": "am i eligible?" }, "update_id": 619114743 }, "channelId": "telegram", "conversation": { "id": "267230627", "isGroup": false }, "from": { "id": "267230627", "name": "zephinzer" }, "id": "8TThQHqc76I", "recipient": { "id": "bizgrants_bot", "name": "grant_bot" }, "serviceUrl": "https://telegram.botframework.com/", "text": "am i eligible?", "timestamp": "2016-11-10T06:55:27.0703571+00:00", "type": "message" }; next(); }, connector.listen()]); server.listen(process.env.port || process.env.PORT || 3978, function () { telegramDebug.notify('Bot started in production mode!'); console.log('%s listening to %s', server.name, server.url); }); } /** * ENDOF CONTROLLER */
import React from 'react'; import _ from 'lodash'; import Component from './component'; import Link from './link'; import Icon from './icon'; class IconLink extends Component { static get propTypes() { return Component.withPropTypes(Icon.propTypes, Link.propTypes); } render() { const linkProps = _.omit(this.props, 'name'); return <Link {...linkProps}> <Icon name={this.props.name}/> </Link> } } export default IconLink;
/*global define*/ define([ '../Core/defaultValue', '../Core/defined', '../Core/defineProperties', '../Core/DeveloperError', '../Core/Event', './createPropertyDescriptor' ], function( defaultValue, defined, defineProperties, DeveloperError, Event, createPropertyDescriptor) { 'use strict'; /** * Describes a two dimensional icon located at the position of the containing {@link Entity}. * <p> * <div align='center'> * <img src='images/Billboard.png' width='400' height='300' /><br /> * Example billboards * </div> * </p> * * @alias BillboardGraphics * @constructor * * @param {Object} [options] Object with the following properties: * @param {Property} [options.image] A Property specifying the Image, URI, or Canvas to use for the billboard. * @param {Property} [options.show=true] A boolean Property specifying the visibility of the billboard. * @param {Property} [options.scale=1.0] A numeric Property specifying the scale to apply to the image size. * @param {Property} [options.horizontalOrigin=HorizontalOrigin.CENTER] A Property specifying the {@link HorizontalOrigin}. * @param {Property} [options.verticalOrigin=VerticalOrigin.CENTER] A Property specifying the {@link VerticalOrigin}. * @param {Property} [options.eyeOffset=Cartesian3.ZERO] A {@link Cartesian3} Property specifying the eye offset. * @param {Property} [options.pixelOffset=Cartesian2.ZERO] A {@link Cartesian2} Property specifying the pixel offset. * @param {Property} [options.rotation=0] A numeric Property specifying the rotation about the alignedAxis. * @param {Property} [options.alignedAxis=Cartesian3.ZERO] A {@link Cartesian3} Property specifying the axis of rotation. * @param {Property} [options.width] A numeric Property specifying the width of the billboard in pixels, overriding the native size. * @param {Property} [options.height] A numeric Property specifying the height of the billboard in pixels, overriding the native size. * @param {Property} [options.color=Color.WHITE] A Property specifying the tint {@link Color} of the image. * @param {Property} [options.scaleByDistance] A {@link NearFarScalar} Property used to scale the point based on distance from the camera. * @param {Property} [options.translucencyByDistance] A {@link NearFarScalar} Property used to set translucency based on distance from the camera. * @param {Property} [options.pixelOffsetScaleByDistance] A {@link NearFarScalar} Property used to set pixelOffset based on distance from the camera. * @param {Property} [options.imageSubRegion] A Property specifying a {@link BoundingRectangle} that defines a sub-region of the image to use for the billboard, rather than the entire image. * @param {Property} [options.sizeInMeters] A boolean Property specifying whether this billboard's size should be measured in meters. * * @demo {@link http://cesiumjs.org/Cesium/Apps/Sandcastle/index.html?src=Billboards.html|Cesium Sandcastle Billboard Demo} */ function BillboardGraphics(options) { this._image = undefined; this._imageSubscription = undefined; this._imageSubRegion = undefined; this._imageSubRegionSubscription = undefined; this._width = undefined; this._widthSubscription = undefined; this._height = undefined; this._heightSubscription = undefined; this._scale = undefined; this._scaleSubscription = undefined; this._rotation = undefined; this._rotationSubscription = undefined; this._alignedAxis = undefined; this._alignedAxisSubscription = undefined; this._horizontalOrigin = undefined; this._horizontalOriginSubscription = undefined; this._verticalOrigin = undefined; this._verticalOriginSubscription = undefined; this._color = undefined; this._colorSubscription = undefined; this._eyeOffset = undefined; this._eyeOffsetSubscription = undefined; this._heightReference = undefined; this._heightReferenceSubscription = undefined; this._pixelOffset = undefined; this._pixelOffsetSubscription = undefined; this._show = undefined; this._showSubscription = undefined; this._scaleByDistance = undefined; this._scaleByDistanceSubscription = undefined; this._translucencyByDistance = undefined; this._translucencyByDistanceSubscription = undefined; this._pixelOffsetScaleByDistance = undefined; this._pixelOffsetScaleByDistanceSubscription = undefined; this._sizeInMeters = undefined; this._sizeInMetersSubscription = undefined; this._definitionChanged = new Event(); this.merge(defaultValue(options, defaultValue.EMPTY_OBJECT)); } defineProperties(BillboardGraphics.prototype, { /** * Gets the event that is raised whenever a property or sub-property is changed or modified. * @memberof BillboardGraphics.prototype * * @type {Event} * @readonly */ definitionChanged : { get : function() { return this._definitionChanged; } }, /** * Gets or sets the Property specifying the Image, URI, or Canvas to use for the billboard. * @memberof BillboardGraphics.prototype * @type {Property} */ image : createPropertyDescriptor('image'), /** * Gets or sets the Property specifying a {@link BoundingRectangle} that defines a * sub-region of the <code>image</code> to use for the billboard, rather than the entire image. * @memberof BillboardGraphics.prototype * @type {Property} */ imageSubRegion : createPropertyDescriptor('imageSubRegion'), /** * Gets or sets the numeric Property specifying the uniform scale to apply to the image. * A scale greater than <code>1.0</code> enlarges the billboard while a scale less than <code>1.0</code> shrinks it. * <p> * <div align='center'> * <img src='images/Billboard.setScale.png' width='400' height='300' /><br/> * From left to right in the above image, the scales are <code>0.5</code>, <code>1.0</code>, and <code>2.0</code>. * </div> * </p> * @memberof BillboardGraphics.prototype * @type {Property} * @default 1.0 */ scale : createPropertyDescriptor('scale'), /** * Gets or sets the numeric Property specifying the rotation of the image * counter clockwise from the <code>alignedAxis</code>. * @memberof BillboardGraphics.prototype * @type {Property} * @default 0 */ rotation : createPropertyDescriptor('rotation'), /** * Gets or sets the {@link Cartesian3} Property specifying the axis of rotation * in the fixed frame. When set to Cartesian3.ZERO the rotation is from the top of the screen. * @memberof BillboardGraphics.prototype * @type {Property} * @default Cartesian3.ZERO */ alignedAxis : createPropertyDescriptor('alignedAxis'), /** * Gets or sets the Property specifying the {@link HorizontalOrigin}. * @memberof BillboardGraphics.prototype * @type {Property} * @default HorizontalOrigin.CENTER */ horizontalOrigin : createPropertyDescriptor('horizontalOrigin'), /** * Gets or sets the Property specifying the {@link VerticalOrigin}. * @memberof BillboardGraphics.prototype * @type {Property} * @default VerticalOrigin.CENTER */ verticalOrigin : createPropertyDescriptor('verticalOrigin'), /** * Gets or sets the Property specifying the {@link Color} that is multiplied with the <code>image</code>. * This has two common use cases. First, the same white texture may be used by many different billboards, * each with a different color, to create colored billboards. Second, the color's alpha component can be * used to make the billboard translucent as shown below. An alpha of <code>0.0</code> makes the billboard * transparent, and <code>1.0</code> makes the billboard opaque. * <p> * <div align='center'> * <table border='0' cellpadding='5'><tr> * <td align='center'><code>default</code><br/><img src='images/Billboard.setColor.Alpha255.png' width='250' height='188' /></td> * <td align='center'><code>alpha : 0.5</code><br/><img src='images/Billboard.setColor.Alpha127.png' width='250' height='188' /></td> * </tr></table> * </div> * </p> * @memberof BillboardGraphics.prototype * @type {Property} * @default Color.WHITE */ color : createPropertyDescriptor('color'), /** * Gets or sets the {@link Cartesian3} Property specifying the billboard's offset in eye coordinates. * Eye coordinates is a left-handed coordinate system, where <code>x</code> points towards the viewer's * right, <code>y</code> points up, and <code>z</code> points into the screen. * <p> * An eye offset is commonly used to arrange multiple billboards or objects at the same position, e.g., to * arrange a billboard above its corresponding 3D model. * </p> * Below, the billboard is positioned at the center of the Earth but an eye offset makes it always * appear on top of the Earth regardless of the viewer's or Earth's orientation. * <p> * <div align='center'> * <table border='0' cellpadding='5'><tr> * <td align='center'><img src='images/Billboard.setEyeOffset.one.png' width='250' height='188' /></td> * <td align='center'><img src='images/Billboard.setEyeOffset.two.png' width='250' height='188' /></td> * </tr></table> * <code>b.eyeOffset = new Cartesian3(0.0, 8000000.0, 0.0);</code> * </div> * </p> * @memberof BillboardGraphics.prototype * @type {Property} * @default Cartesian3.ZERO */ eyeOffset : createPropertyDescriptor('eyeOffset'), /** * Gets or sets the Property specifying the {@link HeightReference}. * @memberof BillboardGraphics.prototype * @type {Property} * @default HeightReference.NONE */ heightReference : createPropertyDescriptor('heightReference'), /** * Gets or sets the {@link Cartesian2} Property specifying the billboard's pixel offset in screen space * from the origin of this billboard. This is commonly used to align multiple billboards and labels at * the same position, e.g., an image and text. The screen space origin is the top, left corner of the * canvas; <code>x</code> increases from left to right, and <code>y</code> increases from top to bottom. * <p> * <div align='center'> * <table border='0' cellpadding='5'><tr> * <td align='center'><code>default</code><br/><img src='images/Billboard.setPixelOffset.default.png' width='250' height='188' /></td> * <td align='center'><code>b.pixeloffset = new Cartesian2(50, 25);</code><br/><img src='images/Billboard.setPixelOffset.x50y-25.png' width='250' height='188' /></td> * </tr></table> * The billboard's origin is indicated by the yellow point. * </div> * </p> * @memberof BillboardGraphics.prototype * @type {Property} * @default Cartesian2.ZERO */ pixelOffset : createPropertyDescriptor('pixelOffset'), /** * Gets or sets the boolean Property specifying the visibility of the billboard. * @memberof BillboardGraphics.prototype * @type {Property} * @default true */ show : createPropertyDescriptor('show'), /** * Gets or sets the numeric Property specifying the billboard's width in pixels. * When undefined, the native width is used. * @memberof BillboardGraphics.prototype * @type {Property} */ width : createPropertyDescriptor('width'), /** * Gets or sets the numeric Property specifying the height of the billboard in pixels. * When undefined, the native height is used. * @memberof BillboardGraphics.prototype * @type {Property} */ height : createPropertyDescriptor('height'), /** * Gets or sets {@link NearFarScalar} Property specifying the scale of the billboard based on the distance from the camera. * A billboard's scale will interpolate between the {@link NearFarScalar#nearValue} and * {@link NearFarScalar#farValue} while the camera distance falls within the upper and lower bounds * of the specified {@link NearFarScalar#near} and {@link NearFarScalar#far}. * Outside of these ranges the billboard's scale remains clamped to the nearest bound. * @memberof BillboardGraphics.prototype * @type {Property} */ scaleByDistance : createPropertyDescriptor('scaleByDistance'), /** * Gets or sets {@link NearFarScalar} Property specifying the translucency of the billboard based on the distance from the camera. * A billboard's translucency will interpolate between the {@link NearFarScalar#nearValue} and * {@link NearFarScalar#farValue} while the camera distance falls within the upper and lower bounds * of the specified {@link NearFarScalar#near} and {@link NearFarScalar#far}. * Outside of these ranges the billboard's translucency remains clamped to the nearest bound. * @memberof BillboardGraphics.prototype * @type {Property} */ translucencyByDistance : createPropertyDescriptor('translucencyByDistance'), /** * Gets or sets {@link NearFarScalar} Property specifying the pixel offset of the billboard based on the distance from the camera. * A billboard's pixel offset will interpolate between the {@link NearFarScalar#nearValue} and * {@link NearFarScalar#farValue} while the camera distance falls within the upper and lower bounds * of the specified {@link NearFarScalar#near} and {@link NearFarScalar#far}. * Outside of these ranges the billboard's pixel offset remains clamped to the nearest bound. * @memberof BillboardGraphics.prototype * @type {Property} */ pixelOffsetScaleByDistance : createPropertyDescriptor('pixelOffsetScaleByDistance'), /** * Gets or sets the boolean Property specifying if this billboard's size will be measured in meters. * @memberof BillboardGraphics.prototype * @type {Property} * @default false */ sizeInMeters : createPropertyDescriptor('sizeInMeters') }); /** * Duplicates this instance. * * @param {BillboardGraphics} [result] The object onto which to store the result. * @returns {BillboardGraphics} The modified result parameter or a new instance if one was not provided. */ BillboardGraphics.prototype.clone = function(result) { if (!defined(result)) { return new BillboardGraphics(this); } result.color = this._color; result.eyeOffset = this._eyeOffset; result.heightReference = this._heightReference; result.horizontalOrigin = this._horizontalOrigin; result.image = this._image; result.imageSubRegion = this._imageSubRegion; result.pixelOffset = this._pixelOffset; result.scale = this._scale; result.rotation = this._rotation; result.alignedAxis = this._alignedAxis; result.show = this._show; result.verticalOrigin = this._verticalOrigin; result.width = this._width; result.height = this._height; result.scaleByDistance = this._scaleByDistance; result.translucencyByDistance = this._translucencyByDistance; result.pixelOffsetScaleByDistance = this._pixelOffsetScaleByDistance; result.sizeInMeters = this._sizeInMeters; return result; }; /** * Assigns each unassigned property on this object to the value * of the same property on the provided source object. * * @param {BillboardGraphics} source The object to be merged into this object. */ BillboardGraphics.prototype.merge = function(source) { //>>includeStart('debug', pragmas.debug); if (!defined(source)) { throw new DeveloperError('source is required.'); } //>>includeEnd('debug'); this.color = defaultValue(this._color, source.color); this.eyeOffset = defaultValue(this._eyeOffset, source.eyeOffset); this.heightReference = defaultValue(this._heightReference, source.heightReference); this.horizontalOrigin = defaultValue(this._horizontalOrigin, source.horizontalOrigin); this.image = defaultValue(this._image, source.image); this.imageSubRegion = defaultValue(this._imageSubRegion, source.imageSubRegion); this.pixelOffset = defaultValue(this._pixelOffset, source.pixelOffset); this.scale = defaultValue(this._scale, source.scale); this.rotation = defaultValue(this._rotation, source.rotation); this.alignedAxis = defaultValue(this._alignedAxis, source.alignedAxis); this.show = defaultValue(this._show, source.show); this.verticalOrigin = defaultValue(this._verticalOrigin, source.verticalOrigin); this.width = defaultValue(this._width, source.width); this.height = defaultValue(this._height, source.height); this.scaleByDistance = defaultValue(this._scaleByDistance, source.scaleByDistance); this.translucencyByDistance = defaultValue(this._translucencyByDistance, source.translucencyByDistance); this.pixelOffsetScaleByDistance = defaultValue(this._pixelOffsetScaleByDistance, source.pixelOffsetScaleByDistance); this.sizeInMeters = defaultValue(this._sizeInMeters, source.sizeInMeters); }; return BillboardGraphics; });
'use strict'; /** * Removes whitespace from the left end of a string. * * @param {String} subjectString The string to left trim. * @throws {TypeError} If `subjectString` is not string. * @return {String} The result string. * @example * * trimLeft(' Lorem ipsum dolor si amet.'); * // -> 'Lorem ipsum dolor si amet.' */ function trimLeft(subjectString) { if (typeof subjectString !== 'string') { throw new TypeError('Expected a string for first argument'); } return String.prototype.trimStart ? subjectString.trimStart() : subjectString.replace(/^\s+/, ''); } module.exports = trimLeft;
import semver from 'semver'; function getValidRange(version) { return semver.prerelease(version) // Remove pre-release versions by incrementing them. This works because a pre-release is less // than the corresponding non-pre-prelease version. ? semver.inc(version, 'patch') // Convert partial versions, such as 16 or 16.8, to their corresponding range notation, so that // they work with the rest of the semver functions. : semver.validRange(version); } export default function getAdapterForReactVersion(reactVersion) { const versionRange = getValidRange(reactVersion); if (semver.intersects(versionRange, '^16.4.0')) { return 'enzyme-adapter-react-16'; } if (semver.intersects(versionRange, '~16.3.0')) { return 'enzyme-adapter-react-16.3'; } if (semver.intersects(versionRange, '~16.2')) { return 'enzyme-adapter-react-16.2'; } if (semver.intersects(versionRange, '~16.0.0 || ~16.1')) { return 'enzyme-adapter-react-16.1'; } if (semver.intersects(versionRange, '^15.5.0')) { return 'enzyme-adapter-react-15'; } if (semver.intersects(versionRange, '15.0.0 - 15.4.x')) { return 'enzyme-adapter-react-15.4'; } if (semver.intersects(versionRange, '^0.14.0')) { return 'enzyme-adapter-react-14'; } if (semver.intersects(versionRange, '^0.13.0')) { return 'enzyme-adapter-react-13'; } throw new RangeError(`No Enzyme adapter could be found for React version “${reactVersion}”`); }
var vows = require('vows'), assert = require('assert'), deploy = require('deploy'); vows.describe('Configuration').addBatch({ 'Accepts no parameter': { topic: function () { return deploy.config; }, 'returns base configuration with no initial pargs ': function (topic) { var _fnValue = topic(); assert.deepEqual (_fnValue, {user: 'postgres', password: null, database: 'postgres'}); }, 'returns updated config when object as arg': function(topic) { var _fnValue = topic({host: 'localhost', password: 'password'}); assert.deepEqual (_fnValue, {user: 'postgres', password: 'password', database: 'postgres', host: 'localhost'}); }, 'accepts a string as a conf': function(topic) { var _fnValue = topic('some_invalid_conf_string'); assert.equal (_fnValue, 'some_invalid_conf_string'); } } }).export(module);
import exportLocale from './lib/exportLocale'; export default exportLocale;
/*global exit */ let path = require('path'); let globule = require('globule'); let merge = require('merge'); let http = require('http'); let shelljs = require('shelljs'); function joinPath() { return path.join.apply(path.join, arguments); } function filesMatchingPattern(files) { return globule.find(files, {nonull: true}); } function fileMatchesPattern(patterns, intendedPath) { return globule.isMatch(patterns, intendedPath); } function recursiveMerge(target, source) { return merge.recursive(target, source); } function checkIsAvailable(url, callback) { http.get(url, function (res) { callback(true); }).on('error', function (res) { callback(false); }); } function httpGet(url, callback) { return http.get(url, callback); } function runCmd(cmd, options) { let result = shelljs.exec(cmd, options || {silent: true}); if (result.code !== 0) { console.log("error doing.. " + cmd); console.log(result.output); if (result.stderr !== undefined) { console.log(result.stderr); } exit(); } } function cd(folder) { shelljs.cd(folder); } function sed(file, pattern, replace) { shelljs.sed('-i', pattern, replace, file); } function exit(code) { process.exit(code); } //TODO: Maybe desired to just `module.exports = this` ? module.exports = { joinPath: joinPath, filesMatchingPattern: filesMatchingPattern, fileMatchesPattern: fileMatchesPattern, recursiveMerge: recursiveMerge, checkIsAvailable: checkIsAvailable, httpGet: httpGet, runCmd: runCmd, cd: cd, sed: sed, exit: exit };
// ========================================================================== // Project: MySystem // Copyright: ©2011 Concord Consortium // ========================================================================== /*globals MySystem */ MySystem.savingController = SC.Object.create({ // this should be set saveFunction: null, saveTime: null, displayTime: null, saveTimer: null, autoSaveFrequency: 20000, // save every 20 seconds displayFrequency: 5000, // update disaply every 5 seconds // computes human-readable 'Saved: <when> text' saveStatusText: function() { var saveTime = this.get('saveTime'), seconds = 0, minutes = 0, hours = 0, timeNow = new Date().getTime(); if (!!!this.get('saveFunction')){ return 'Saving disabled.'; } if (!!!saveTime) { return 'Not saved yet.'; } if (!this.get('dataIsDirty')) { // if we aren't dirty, we are effectively saved: this.set('saveTime', new Date().getTime()); return 'Saved.'; } seconds = (timeNow - saveTime) / 1000.0; minutes = seconds / 60; hours = minutes / 60; seconds = Math.floor(seconds); minutes = Math.floor(minutes); hours = Math.floor(hours); if (seconds < 60) { return ('Saved seconds ago.'); } if (minutes === 1) { return ('Saved ' + minutes + ' minute ago.' ); } if (minutes < 60) { return ('Saved ' + minutes + ' minutes ago.'); } if (hours === 1) { return ('Saved ' + hours + ' hour ago.' ); } return ('Saved ' + hours + ' hours ago.'); }.property('saveTime', 'displayTime'), enableManualSave: function(){ return !!this.get('saveFunction') && !!this.get('dataIsDirty'); }.property('saveFunction', 'dataIsDirty'), processLearnerDiagram: function(submit) { MySystem.rubricController.score(submit); MySystem.GraphicPreview.makePreview(MySystem.store); }, // Called to attempt to save the diagram. Either by pressing 'save', navigating away, // or when the save button is pressed. // IMPORANT: dataSources must call: MySystem.savingController.set('dataIsDirty', YES); save: function() { var isSubmit = NO; if(this.get('saveFunction') && this.get('dataIsDirty')) { this.processLearnerDiagram(isSubmit); this.get('saveFunction')(isSubmit); } }, // submit the diagram which tells the saving code to make sure to lock the saved // state so it won't be overriden submit: function(){ var isSubmit = YES; this.processLearnerDiagram(true); if(this.get('saveFunction')) { this.get('saveFunction')(isSubmit); } }, // Called when save function returns. // @param successful {Boolean} true if the data was successfully saved saveSuccessful: function(successful) { if (successful){ this.set('dataIsDirty', NO); this.set('saveTime', new Date().getTime()); } }, // Called when our dispayTimer reaches <displayFrequency> seconds // this will have the side-effect of calling this.saveStatusText() // which is observes 'displayTime'. updateDisplayTime: function() { this.set('displayTime', new Date().getTime()); }, setupTimers: function() { var saveTimer = null, displayTimer = null; if (!!this.get('displayTimer')){ this.get('displayTimer').invalidate(); this.set('displayTimer', null); } if (!!this.get('saveTimer')){ this.get('saveTimer').invalidate(); this.set('saveTimer', null); } // This timer will attempt to display the last save time every <displayFrequency> seconds // unless the value for autoSaveFrequency is less than 1. if (this.get('displayFrequency') > 0) { this.set('displayTimer',SC.Timer.schedule({ target: this, action: 'updateDisplayTime', interval: this.get('displayFrequency'), repeats: YES })); } // This timer will attempt to save dataevery <autoSaveFrequency> seconds // unless the value for autoSaveFrequency is less than 1. if (this.get('autoSaveFrequency') > 0) { this.set('saveTimer', SC.Timer.schedule({ target: this, action: 'save', interval: this.get('autoSaveFrequency'), repeats: YES })); } }.observes('displayFrequency','autoSaveFrequency'), init: function() { sc_super(); this.setupTimers(); }, destroy: function() { // ensure that our timers are destroyed. this.get('saveTimer').invalidate(); this.set('saveTimer', null); this.get('displayTimer').invalidate(); this.set('displayTimer', null); sc_super(); } });
const path = require('path'); const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const configuration = require('./configuration.js'); module.exports = { entry: './src/main.js', output: { path: path.resolve(__dirname, './dist'), publicPath: process.env.PUBLIC_PATH || '/dist/', filename: 'main.sentinelle.js', }, mode: process.env.NODE_ENV, devServer: { host: '0.0.0.0', port: process.env.PORT || 5000, disableHostCheck: true, }, devtool: 'sourcemap', resolve: { alias: { vue$: 'vue/dist/vue.common.js', }, symlinks: false, }, module: { rules: [ { test: /\.vue$/, loader: 'vue-loader', options: { loaders: { js: { loader: 'babel-loader', }, }, }, }, { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader', }, }, { test: /\.(png|jpg|gif|svg)$/, use: { loader: 'file-loader', }, }, ], }, plugins: [ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: `"${process.env.NODE_ENV}"` }, __CONFIGURATION: JSON.stringify(configuration), }), new HtmlWebpackPlugin({ title: 'sentinelle', meta: { viewport: 'width=device-width, initial-scale=1', }, favicon: path.resolve(__dirname, './src/assets/favicon.png'), }), ], };
var __ = require('underscore'), Backbone = require('backbone'), $ = require('jquery'); Backbone.$ = $; var loadTemplate = require('../utils/loadTemplate'), countriesModel = require('../models/countriesMd'), Taggle = require('taggle'), MediumEditor = require('medium-editor'), messageModal = require('../utils/messageModal'), chosen = require('../utils/chosen.jquery.min.js'); module.exports = Backbone.View.extend({ events: { 'click #shippingFreeTrue': 'disableShippingPrice', 'click #shippingFreeFalse': 'enableShippingPrice', 'change .js-itemImageUpload': 'resizeImage', 'change #inputType': 'changeType', 'click .js-editItemDeleteImage': 'deleteImage', 'blur input': 'validateInput', 'blur textarea': 'validateInput', 'focus #inputExpirationDate': 'addDefaultTime', 'click .js-itemEditClearDate': 'clearDate' }, initialize: function(){ var self=this, hashArray = this.model.get('vendor_offer').listing.item.image_hashes, nowDate = new Date(), nowMonth = nowDate.getMonth()+ 1; function padTime(val){ "use strict"; if(val >= 10){ return val; } else { return "0" + val; } } this.defaultDate = nowDate.getFullYear() + "-" + padTime(nowMonth) + "-" + padTime(nowDate.getDate()) + "T" + padTime(nowDate.getHours()) + ":" + padTime(nowDate.getMinutes()); this.combinedImagesArray = []; __.each(hashArray, function(hash){ self.combinedImagesArray.push(self.model.get('serverUrl')+"get_image?hash="+hash); }); //add images urls to the combinedImagesArray for rendering this.model.set('combinedImagesArray', this.combinedImagesArray); this.inputKeyword; //add existing hashes to the list to be uploaded on save var anotherHashArray = __.clone(self.model.get("vendor_offer").listing.item.image_hashes); self.model.set("imageHashesToUpload", anotherHashArray); self.model.set('expTime', self.model.get('vendor_offer').listing.metadata.expiry.replace(" UTC", "")); this.render(); }, render: function(){ var self = this; loadTemplate('./js/templates/itemEdit.html', function(loadedTemplate) { self.$el.html(loadedTemplate(self.model.toJSON())); self.setFormValues(); // prevent the body from picking up drag actions //TODO: make these nice backbone events $(document.body).bind("dragover", function(e) { e.preventDefault(); return false; }); $(document.body).bind("drop", function(e){ e.preventDefault(); return false; }); var editor = new MediumEditor('#inputDescription', { placeholder: { text: '' }, toolbar: { imageDragging: false, sticky: true } }); }); return this; }, setFormValues: function(){ //TODO: Refactor to a generic enumeration pattern var typeValue = String(this.model.get('vendor_offer').listing.metadata.category) || "physical good", self = this; this.$el.find('input[name=nsfw]').val([String(this.model.get('vendor_offer').listing.item.nsfw)]); this.$el.find('input[name=free_shipping]').val([String(this.model.get('vendor_offer').listing.shipping.free)]); this.$el.find('#inputType').val(typeValue); //hide or unhide shipping based on product type if(typeValue === "physical good") { this.enableShipping(); } else { this.disableShipping(); } //hide or unhide shipping based on free shipping if(this.model.get('vendor_offer').listing.shipping.free == true){ this.disableShippingPrice(); } else { this.enableShippingPrice(); } //if item has a condition, set it if(this.model.get('vendor_offer').listing.item.condition){ this.$el.find('#inputCondition').val(String(this.model.get('vendor_offer').listing.item.condition)); } //add all countries to the Ships To select list var countries = new countriesModel(); var countryList = countries.get('countries'); var shipsTo = this.$el.find('#shipsTo'); __.each(countryList, function(countryFromList, i){ shipsTo.append('<option value="'+countryFromList.dataName+'">'+countryFromList.name+'</option>'); }); var shipsToValue = this.model.get('vendor_offer').listing.shipping.shipping_regions; //if shipsToValue is empty, set it to the user's country shipsToValue = shipsToValue.length > 0 ? shipsToValue : this.model.get('userCountry'); shipsTo.val(shipsToValue); var keywordTags = this.model.get('vendor_offer').listing.item.keywords; keywordTags = keywordTags ? keywordTags.filter(Boolean) : []; //activate tags plugin //hacky fix for now, because DOM is not complete when taggle is called, resulting in a container size of zero //TODO: find a fix for this, so taggle is initialized after reflow is complete window.setTimeout(function(){ self.inputKeyword = new Taggle('inputKeyword', { tags: keywordTags, preserveCase: true, submitKeys: [188, 9, 13, 32], saveOnBlur: true }); },1); //set chosen inputs $('.chosen').chosen({width: '100%'}); //focus main input this.$el.find('input[name=title]').focus(); $('#obContainer').animate({ scrollTop: "460px" }); }, disableShippingPrice: function(){ this.$el.find('.js-shippingPriceRow').addClass('visuallyHidden'); this.$el.find('#shippingPriceLocalLocal, #shippingPriceInternationalLocal') .prop({disabled: true, require: false}); //if prices are disabled, force free_shipping to be free this.$el.find('input[name=free_shipping]').val(["true"]); }, enableShippingPrice: function(){ this.$el.find('.js-shippingPriceRow').removeClass('visuallyHidden'); this.$el.find('#shippingPriceLocalLocal, #shippingPriceInternationalLocal') .prop({disabled: false, require: true}); }, disableShipping: function(){ this.$el.find('.js-shippingRow, .js-shippingRowFree').addClass('visuallyHidden'); this.$el.find('.js-shippingRow input') .prop({disabled: true, require: false}); }, enableShipping: function() { this.$el.find('.js-shippingRow, .js-shippingRowFree').removeClass('visuallyHidden'); this.$el.find('.js-shippingRow input') .prop({disabled: false, require: true}); //if chosen selector started hidden, it will be too narrow $('.js-shippingRow .chosen-container').css({width: '100%'}); }, changeType: function(e) { var newTyleValue = $(e.target).val(); if(newTyleValue === "physical good") { this.enableShipping(); //only show shipping prices if free shipping is not true if(this.$el.find('input[name=free_shipping]').val() == "false") { this.enableShippingPrice(); } } else { this.disableShipping(); this.disableShippingPrice(); } }, addDefaultTime: function(e){ "use strict"; var timeInput = this.$el.find('#inputExpirationDate'), currentValue = timeInput.val(); if(!currentValue){ timeInput.val(this.defaultDate); } this.$el.find('.js-itemEditClearDateWrapper').removeClass('hide'); }, clearDate: function(){ "use strict"; this.$el.find('#inputExpirationDate').val(''); }, resizeImage: function(){ "use strict"; var self = this, imageFiles = this.$el.find('.js-itemImageUpload')[0].files, maxH = 357, maxW = 357, imageList = [], imageCount = imageFiles.length; __.each(imageFiles, function(imageFile, i){ var newImage = document.createElement("img"), ctx; newImage.src = imageFile.path; newImage.onload = function() { var imgH = newImage.height, imgW = newImage.width, dataURI, canvas = document.createElement("canvas"); self.$el.find('.js-itemEditImageLoading').removeClass("fadeOut"); if (imgW < imgH){ //if image width is smaller than height, set width to max imgH *= maxW/imgW; imgW = maxW; }else{ imgW *= maxH/imgH; imgH = maxH; } canvas.width = imgW; canvas.height = imgH; ctx = canvas.getContext('2d'); ctx.drawImage(newImage, 0, 0, imgW, imgH); dataURI = canvas.toDataURL('image/jpeg', 0.75); dataURI = dataURI.replace(/^data:image\/(png|jpeg);base64,/, ""); imageList.push(dataURI); if(i+1 === imageCount) { self.uploadImage(imageList); } }; }); }, uploadImage: function(imageList){ var self = this, formData = new FormData(); __.each(imageList, function(dataURL){ "use strict"; formData.append('image', dataURL); }); $.ajax({ type: "POST", url: self.model.get('serverUrl') + "upload_image", contentType: false, processData: false, dataType: "json", data: formData, success: function(data) { var hashArray, imageArray; if (data.success === true){ imageArray = __.clone(self.model.get("combinedImagesArray")); hashArray = __.clone(self.model.get("imageHashesToUpload")); __.each(data.image_hashes, function (hash) { if(hash != "b472a266d0bd89c13706a4132ccfb16f7c3b9fcb" && hash.length === 40){ imageArray.push(self.model.get('serverUrl') + "get_image?hash=" + hash); hashArray.push(hash); } }); self.model.set("combinedImagesArray", imageArray); self.model.set("imageHashesToUpload", hashArray); self.$el.find('.js-itemEditImageLoading').addClass("fadeOut"); self.updateImages(); }else if (data.success === false){ messageModal.show(window.polyglot.t('errorMessages.saveError'), "<i>" + data.reason + "</i>"); } }, error: function(jqXHR, status, errorThrown){ console.log(jqXHR); console.log(status); console.log(errorThrown); } }); }, updateImages: function(){ var self = this, subImageDivs = this.$el.find('.js-editItemSubImage'), imageArray = this.model.get("combinedImagesArray"), uploadMsg = this.$el.find('.js-itemEditLoadPhotoMessage'); //remove extra subImage divs subImageDivs.slice(imageArray.length).remove(); if(imageArray.length > 0){ __.each(imageArray, function (imageURL, i) { if (i < subImageDivs.length){ $(subImageDivs[i]).css('background-image', 'url(' + imageURL + ')'); }else{ $('<div class="itemImg itemImg-small js-editItemSubImage" style="background-image: url(' + imageURL + ');" data-index="' + i + '"><div class="btn btn-corner btn-cornerTR btn-cornerTRSmall btn-flushTop btn-c1 fade btn-shadow1 js-editItemDeleteImage"><i class="ion-close-round icon-centered icon-small"></i></div></div>') .appendTo(self.$el.find('.js-editItemSubImagesWrapper')); } }); uploadMsg.addClass('hide'); } else { uploadMsg.removeClass('hide'); } }, deleteImage: function(e) { var imageUploadArray, imgIndex = $(e.target).closest('.itemImg').data('index'), imageArray = __.clone(this.model.get("combinedImagesArray")); imageArray.splice(imgIndex, 1); this.model.set("combinedImagesArray", imageArray); imageUploadArray = __.clone(this.model.get("imageHashesToUpload")); imageUploadArray.splice(imgIndex, 1); this.model.set("imageHashesToUpload", imageUploadArray); this.updateImages(); }, validateInput: function(e) { "use strict"; e.target.checkValidity(); $(e.target).closest('.flexRow').addClass('formChecked'); }, saveChanges: function(){ var self = this, formData, //deleteThisItem, cCode = this.model.get('userCurrencyCode'), submitForm = this.$el.find('#contractForm')[0], keywordsArray = this.inputKeyword.getTagValues(); /* deleteThisItem = function(newHash){ $.ajax({ type: "DELETE", url: self.model.get('serverUrl') + "contracts?id="+self.model.get('id'), success: function() { self.trigger('deleteOldDone', newHash); }, error: function(jqXHR, status, errorThrown){ console.log(jqXHR); console.log(status); console.log(errorThrown); } }); }; */ this.$el.find('#inputCurrencyCode').val(cCode); this.$el.find('#inputShippingCurrencyCode').val(cCode); this.$el.find('#inputShippingOrigin').val(this.model.get('userCountry')); //convert number field to string field this.$el.find('#inputPrice').val(this.$el.find('#priceLocal').val()); this.$el.find('#inputShippingDomestic').val(this.$el.find('#shippingPriceLocalLocal').val()); this.$el.find('#inputShippingInternational').val(this.$el.find('#shippingPriceInternationalLocal').val()); /* if(cCode === "BTC"){ this.$el.find('#inputPrice').val(this.$el.find('.js-priceBtc').val()); this.$el.find('#inputShippingDomestic').val(this.$el.find('#shippingPriceLocalBtc').val()); this.$el.find('#inputShippingInternational').val(this.$el.find('#shippingPriceInternationalBtc').val()); }else{ this.$el.find('#inputPrice').val(this.$el.find('.js-priceLocal').val()); this.$el.find('#inputShippingDomestic').val(this.$el.find('#shippingPriceLocalLocal').val()); this.$el.find('#inputShippingInternational').val(this.$el.find('#shippingPriceInternationalLocal').val()); } */ formData = new FormData(submitForm); //add old and new image hashes __.each(this.model.get('imageHashesToUpload'), function(imHash){ //make sure all hashes are valid if(imHash != "b472a266d0bd89c13706a4132ccfb16f7c3b9fcb" && imHash.length === 40){ formData.append('images', imHash); } }); if(keywordsArray.length > 0){ __.each(keywordsArray, function(keyword){ "use strict"; formData.append('keywords', keyword); }); } else { formData.append('keywords', ""); } //if this is an existing product, do not delete the images if (self.model.get('id')) { formData.append('delete_images', false); } //if this is an existing item, pass in the contract id if(self.model.get('vendor_offer').listing.contract_id){ formData.append('contract_id', self.model.get('vendor_offer').listing.contract_id); } //if condition is disabled, insert default value if($('#inputCondition:disabled').length > 0){ formData.append('condition', 'New'); } //add moderator list from profile __.each(this.model.get('moderators'), function(moderator){ formData.append('moderators', moderator.guid); }); //add formChecked class to form so invalid fields are styled as invalid this.$el.find('#contractForm').addClass('formChecked'); if(submitForm.checkValidity()){ $.ajax({ type: "POST", url: self.model.get('serverUrl') + "contracts", contentType: false, processData: false, data: formData, success: function (data) { //var returnedId = self.model.get('id'); data = JSON.parse(data); /* //if the itemEdit model has an id, it was cloned from an existing item //if the id returned is the same, an edit was made with no changes, don't delete it if (returnedId && data.success === true && returnedId != data.id){ deleteThisItem(data.id); }else if (data.success === false){ messageModal.show(window.polyglot.t('errorMessages.saveError'), "<i>" + data.reason + "</i>"); }else{ //item is new or unchanged */ //self.trigger('saveNewDone', data.id); //} if (data.success === true) { self.trigger('saveNewDone', data.id); } else { messageModal.show(window.polyglot.t('errorMessages.saveError'), "<i>" + data.reason + "</i>"); } }, error: function (jqXHR, status, errorThrown) { console.log(jqXHR); console.log(status); console.log(errorThrown); } }); }else{ var invalidInputList = ""; $(submitForm).find('input').each(function() { if($(this).is(":invalid")){ invalidInputList += "<br/>"+$(this).attr('id'); } }); messageModal.show(window.polyglot.t('errorMessages.saveError'), window.polyglot.t('errorMessages.missingError') + "<br><i>"+ invalidInputList+"</i>"); } }, close: function(){ __.each(this.subViews, function(subView) { if(subView.close){ subView.close(); }else{ subView.unbind(); subView.remove(); } }); this.unbind(); this.remove(); } });
/* global exports */ // An example configuration file. exports.config = { specs: ['e2e/**/*Spec.js'], baseUrl: 'http://localhost:8000', sauceUser: process.env.SAUCE_USERNAME, sauceKey: process.env.SAUCE_ACCESS_KEY, multiCapabilities: [{ browserName: 'chrome', 'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER }, { browserName: 'firefox', 'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER }, { browserName: 'internet explorer', 'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER // }, { // browserName: 'safari', // 'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER }] };
//********************** var mongoose = require('mongoose'); var Connection = function (uri) { var that = this; // console.log(); mongoose.connect('mongodb://heroku_7lzprs54:s7keb2oh4f3ao6ukrkgpt5f55a@ds017165.mlab.com:17165/heroku_7lzprs54', { // mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost/vgdl' , { useMongoClient: true }); var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error: ')); db.once('open', function (callback) { console.log('database connected'); }) // that.games = require('./game-schema.js'); // that.experiments = require('./experiment-schema.js'); Object.freeze(that); return that; } module.exports = Connection();
BlazeLayout.setRoot('body'); const i18nTagToT9n = (i18nTag) => { // t9n/i18n tags are same now, see: https://github.com/softwarerero/meteor-accounts-t9n/pull/129 // but we keep this conversion function here, to be aware that that they are different system. return i18nTag; }; Template.userFormsLayout.onRendered(() => { const i18nTag = navigator.language; if (i18nTag) { T9n.setLanguage(i18nTagToT9n(i18nTag)); } EscapeActions.executeAll(); }); Template.userFormsLayout.helpers({ languages() { return _.map(TAPi18n.getLanguages(), (lang, code) => { return { tag: code, name: lang.name === 'br' ? 'Brezhoneg' : lang.name, }; }).sort(function(a, b) { if (a.name === b.name) { return 0; } else { return a.name > b.name ? 1 : -1; } }); }, isCurrentLanguage() { const t9nTag = i18nTagToT9n(this.tag); const curLang = T9n.getLanguage() || 'en'; return t9nTag === curLang; }, }); Template.userFormsLayout.events({ 'change .js-userform-set-language'(evt) { const i18nTag = $(evt.currentTarget).val(); T9n.setLanguage(i18nTagToT9n(i18nTag)); evt.preventDefault(); }, }); Template.defaultLayout.events({ 'click .js-close-modal': () => { Modal.close(); }, });
var script = ('currentScript' in document) ? document.currentScript : document.getElementsByTagName('script')[document.getElementsByTagName('script').length - 1]; var rootDir = Array(document.location.href.replace(document.location.hash,'').split(/[/\\]/).filter(function(e, i){return script.src.split(/[/\\]/)[i] !== e;}).length).join('../'); // Bootstrap (function (window) { 'use strict'; var defaultConfig = function (window) { window.require = window.require || {}; window.require.baseUrl = rootDir + 'target/compiled'; window.require.sourceDir = rootDir + 'src/'; window.require.deps = (window.require.deps || []).concat(["common"]); window.require.packages = (window.require.packages || []).concat(["common","common"]); window.__bootstrap = function () { document.write('<script src="' + rootDir + '../node_modules/requirejs/require.js" defer="defer"></script>'); }; document.write('<script src="' + rootDir + 'target/compiled/app.nocache.js"></script>'); }; if (script.getAttribute("test")) { if (window.mochaPhantomJS) document.write('<script src="' + rootDir + '../include/polyfills.js"></script>'); document.write('<link rel="stylesheet" type="text/css" href="' + rootDir + '../node_modules/mocha/mocha.css" />'); document.write('<script src="' + rootDir + '../node_modules/mocha/mocha.js"></script>'); document.write('<script src="' + rootDir + '../node_modules/chai/chai.js"></script>'); document.write('<script src="' + rootDir + '../include/mochaRun.js"></script>'); window.__runTest = function () { if (window.mochaPhantomJS) { mochaPhantomJS.run(); } else { mocha.run(); } }; if (window.__setupTest) { window.require = window.require || {}; window.require.callback = function () { window.__setupTest(window.__runTest); }; } if (window.mochaPhantomJS && script.getAttribute("test").toLocaleUpperCase() == "UI") { document.write('<base href="' + rootDir + 'target/finalized/">'); document.write('<script src="app.nocache.js"></script>'); } else { defaultConfig(window); } } else { defaultConfig(window); } })(window);
module.exports = function override(config, env) { config.output = { ...config.output, globalObject: `(typeof self !== undefined ? self : this)` } config.module.rules.unshift({ test: /\.worker\.ts/, use: { loader: 'worker-loader' } }) return config }
var color_green="#27cebc"; var color_blue="#00acec"; var color_yellow="#FDD01C"; var color_red="#f35958"; var color_grey="#dce0e8"; var color_black="#1b1e24"; var color_purple="#6d5eac"; var color_primary="#6d5eac"; var color_success="#4eb2f5"; var color_danger="#f35958"; var color_warning="#f7cf5e"; var color_info="#3b4751"; $(document).ready(function () { calculateHeight(); $(".remove-widget").click(function () { $(this).parent().parent().parent().addClass('animated fadeOut'); $(this).parent().parent().parent().attr('id', 'id_a'); //$(this).parent().parent().parent().hide(); setTimeout(function () { $('#id_a').remove(); }, 400); return false; }); $(".create-folder").click(function () { $('.folder-input').show(); return false; }); $(".folder-name").keypress(function (e) { if (e.which == 13) { $('.folder-input').hide(); $('<li><a href="#"><div class="status-icon green"></div>' + $(this).val() + '</a> </li>').insertBefore(".folder-input"); $(this).val(''); } }); $("#menu-collapse").click(function () { if ($('.page-sidebar').hasClass('mini')) { $('.page-sidebar').removeClass('mini'); $('.page-content').removeClass('condensed-layout'); $('.footer-widget').show(); } else { $('.page-sidebar').addClass('mini'); $('.page-content').addClass('condensed-layout'); $('.footer-widget').hide(); calculateHeight(); } }); $(".inside").children('input').blur(function () { $(this).parent().children('.add-on').removeClass('input-focus'); }); $(".inside").children('input').focus(function () { $(this).parent().children('.add-on').addClass('input-focus'); }); $(".input-group.transparent").children('input').blur(function () { $(this).parent().children('.input-group-addon').removeClass('input-focus'); }); $(".input-group.transparent").children('input').focus(function () { $(this).parent().children('.input-group-addon').addClass('input-focus'); }); $(".bootstrap-tagsinput input").blur(function () { $(this).parent().removeClass('input-focus'); }); $(".bootstrap-tagsinput input").focus(function () { $(this).parent().addClass('input-focus'); }); $('#my-task-list').popover({ html: true, content: function () { return $('#notification-list').html(); } }); $('#user-options').click(function () { $('#my-task-list').popover('hide'); }); //*********************************** BEGIN CHAT POPUP***************************** // if($('body').hasClass('rtl')){ // $('.chat-menu-toggle').sidr({ // name: 'sidr', // side: 'left', // complete: function () {} // }); // } // else{ // $('.chat-menu-toggle').sidr({ // name: 'sidr', // side: 'right', // complete: function () {} // }); // } $(".simple-chat-popup").click(function () { $(this).addClass('hide'); $('#chat-message-count').addClass('hide'); }); setTimeout(function () { $('#chat-message-count').removeClass('hide'); $('#chat-message-count').addClass('animated bounceIn'); $('.simple-chat-popup').removeClass('hide'); $('.simple-chat-popup').addClass('animated fadeIn'); }, 5000); setTimeout(function () { $('.simple-chat-popup').addClass('hide'); $('.simple-chat-popup').removeClass('animated fadeIn'); $('.simple-chat-popup').addClass('animated fadeOut'); }, 8000); //*********************************** END CHAT POPUP***************************** //**********************************BEGIN MAIN MENU******************************** jQuery('.page-sidebar li > a').on('click', function (e) { if ($(this).next().hasClass('sub-menu') === false) { return; } var parent = $(this).parent().parent(); parent.children('li.open').children('a').children('.arrow').removeClass('open'); parent.children('li.open').children('a').children('.arrow').removeClass('active'); parent.children('li.open').children('.sub-menu').slideUp(200); parent.children('li').removeClass('open'); // parent.children('li').removeClass('active'); var sub = jQuery(this).next(); if (sub.is(":visible")) { jQuery('.arrow', jQuery(this)).removeClass("open"); jQuery(this).parent().removeClass("active"); sub.slideUp(200, function () { handleSidenarAndContentHeight(); }); } else { jQuery('.arrow', jQuery(this)).addClass("open"); jQuery(this).parent().addClass("open"); sub.slideDown(200, function () { handleSidenarAndContentHeight(); }); } e.preventDefault(); }); //Auto close open menus in Condensed menu if ($('.page-sidebar').hasClass('mini')) { var elem = jQuery('.page-sidebar ul'); elem.children('li.open').children('a').children('.arrow').removeClass('open'); elem.children('li.open').children('a').children('.arrow').removeClass('active'); elem.children('li.open').children('.sub-menu').slideUp(200); elem.children('li').removeClass('open'); } //**********************************END MAIN MENU******************************** //**** Element Background and height ******************************************** $('[data-height-adjust="true"]').each(function () { var h = $(this).attr('data-elem-height'); $(this).css("min-height", h); $(this).css('background-image', 'url(' + $(this).attr("data-background-image") + ')'); $(this).css('background-repeat', 'no-repeat'); if ($(this).attr('data-background-image')) { } }); function equalHeight(group) { tallest = 0; group.each(function () { thisHeight = $(this).height(); if (thisHeight > tallest) { tallest = thisHeight; } }); group.height(tallest); } $('[data-aspect-ratio="true"]').each(function () { $(this).height($(this).width()); }); $('[data-sync-height="true"]').each(function () { equalHeight($(this).children()); }); $(window).resize(function () { $('[data-aspect-ratio="true"]').each(function () { $(this).height($(this).width()); }); $('[data-sync-height="true"]').each(function () { equalHeight($(this).children()); }); }); $('#main-menu-wrapper').scrollbar(); // initMainMenu(); //***********************************BEGIN Fixed Menu***************************** function initMainMenu() { } initExtendedLayoutMenuScroll(); function initExtendedLayoutMenuScroll(){ } $('.tip').tooltip(); //***********************************BEGIN Horinzontal Menu***************************** $('.horizontal-menu .bar-inner > ul > li').on('click', function () { $(this).toggleClass('open').siblings().removeClass('open'); }); if($('body').hasClass('horizontal-menu')){ $('.content').on('click', function () { $('.horizontal-menu .bar-inner > ul > li').removeClass('open'); }); } //***********************************END Horinzontal Menu***************************** //***********************************BEGIN Lazyload images***************************** if ($.fn.lazyload) { $("img.lazy").lazyload({ effect: "fadeIn" }); } //***********************************BEGIN Grids***************************** $('.grid .tools a.remove').on('click', function () { var removable = jQuery(this).parents(".grid"); if (removable.next().hasClass('grid') || removable.prev().hasClass('grid')) { jQuery(this).parents(".grid").remove(); } else { jQuery(this).parents(".grid").parent().remove(); } }); $('.grid .tools a.reload').on('click', function () { var el = jQuery(this).parents(".grid"); blockUI(el); window.setTimeout(function () { unblockUI(el); }, 1000); }); $('.grid .tools .collapse, .grid .tools .expand').on('click', function () { var el = jQuery(this).parents(".grid").children(".grid-body"); if (jQuery(this).hasClass("collapse")) { jQuery(this).removeClass("collapse").addClass("expand"); el.slideUp(200); } else { jQuery(this).removeClass("expand").addClass("collapse"); el.slideDown(200); } }); $('.user-info .collapse').on('click', function () { jQuery(this).parents(".user-info ").stop().slideToggle(400, "swing"); }); //***********************************END Grids***************************** var handleSidenarAndContentHeight = function () { var content = $('.page-content'); var sidebar = $('.page-sidebar'); if (!content.attr("data-height")) { content.attr("data-height", content.height()); } if (sidebar.height() > content.height()) { content.css("min-height", sidebar.height() + 120); } else { content.css("min-height", content.attr("data-height")); } }; $('.panel-group').on('hidden.bs.collapse', function (e) { $(this).find('.panel-heading').not($(e.target)).addClass('collapsed'); }); $('.panel-group').on('shown.bs.collapse', function (e) { // $(e.target).prev('.accordion-heading').find('.accordion-toggle').removeClass('collapsed'); }); //***********************************BEGIN Layout Readjust ***************************** $(window).setBreakpoints({ distinct: true, breakpoints: [ 320, 480, 768, 1024] }); //Break point entry $(window).bind('enterBreakpoint320', function () { $('#main-menu-toggle-wrapper').show(); $('#portrait-chat-toggler').show(); $('#header_inbox_bar').hide(); $('#main-menu').removeClass('mini'); $('.page-content').removeClass('condensed'); rebuildSider(); }); $(window).bind('enterBreakpoint480', function () { $('#main-menu-toggle-wrapper').show(); $('.header-seperation').show(); $('#portrait-chat-toggler').show(); $('#header_inbox_bar').hide(); //Incase if condensed layout is applied $('#main-menu').removeClass('mini'); $('.page-content').removeClass('condensed'); rebuildSider(); }); $(window).bind('enterBreakpoint768', function () { $('#main-menu-toggle-wrapper').show(); $('#portrait-chat-toggler').show(); $('#header_inbox_bar').hide(); if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) { $('#main-menu').removeClass('mini'); $('.page-content').removeClass('condensed'); rebuildSider(); } }); $(window).bind('enterBreakpoint1024', function () { if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) { var elem = jQuery('.page-sidebar ul'); elem.children('li.open').children('a').children('.arrow').removeClass('open'); elem.children('li.open').children('a').children('.arrow').removeClass('active'); elem.children('li.open').children('.sub-menu').slideUp(200); elem.children('li').removeClass('open'); } $('.bar').show(); $('.bar').css('overflow','visible'); }); $(window).bind('exitBreakpoint320', function () { $('#main-menu-toggle-wrapper').hide(); $('#portrait-chat-toggler').hide(); $('#header_inbox_bar').show(); closeAndRestSider(); }); $(window).bind('exitBreakpoint480', function () { $('#main-menu-toggle-wrapper').hide(); $('#portrait-chat-toggler').hide(); $('#header_inbox_bar').show(); closeAndRestSider(); }); $(window).bind('exitBreakpoint768', function () { $('#main-menu-toggle-wrapper').hide(); $('#portrait-chat-toggler').hide(); $('#header_inbox_bar').show(); closeAndRestSider(); }); //***********************************END Layout Readjust ***************************** //***********************************BEGIN Function calls ***************************** function closeAndRestSider() { if ($('#main-menu').attr('data-inner-menu') == '1') { $('#main-menu').addClass("mini"); $('#main-menu').removeClass("left"); } else { $('#main-menu').removeClass("left"); } } $('#main-menu-toggle').on('touchstart click', function (e) { e.preventDefault(); toggleMainMenu(); }); $('#chat-menu-toggle, .chat-menu-toggle').on('touchstart click', function (e) { e.preventDefault(); toggleChat(); }); function rebuildSider() { } //***********************************END Function calls ***************************** //***********************************BEGIN Main Menu Toggle ***************************** $('#layout-condensed-toggle').click(function () { if ($('#main-menu').attr('data-inner-menu') == '1') { //Do nothing console.log("Menu is already condensed"); } else { if ($('#main-menu').hasClass('mini')) { $('body').removeClass('grey'); $('body').removeClass('condense-menu'); $('#main-menu').removeClass('mini'); $('.page-content').removeClass('condensed'); $('.scrollup').removeClass('to-edge'); $('.header-seperation').show(); //Bug fix - In high resolution screen it leaves a white margin $('.header-seperation').css('height', '61px'); $('.footer-widget').show(); } else { $('body').addClass('grey'); $('#main-menu').addClass('mini'); $('.page-content').addClass('condensed'); $('.scrollup').addClass('to-edge'); $('.header-seperation').hide(); $('.footer-widget').hide(); $('.main-menu-wrapper').scrollbar('destroy'); } } }); $('#horizontal-menu-toggle').click(function () { if($('body').hasClass('breakpoint-480') || $('body').hasClass('breakpoint-320') ){ $('.bar').slideToggle(200, "linear"); } }); //***********************************END Main Menu Toggle ***************************** //***********************************BEGIN Slimscroller ***************************** $('.scroller').each(function () { var h = $(this).attr('data-height'); $(this).scrollbar({ ignoreMobile:true }); if(h != null || h !=""){ if($(this).parent('.scroll-wrapper').length > 0) $(this).parent().css('max-height',h); else $(this).css('max-height',h); } }); //***********************************END Slimscroller ***************************** //***********************************BEGIN dropdow menu ***************************** $('.dropdown-toggle').click(function () { $("img").trigger("unveil"); }); //***********************************END dropdow menu ***************************** //***********************************BEGIN Global sparkline chart ***************************** if ($.fn.sparkline) { $('.sparklines').sparkline('html', { enableTagOptions: true }); } //***********************************END Global sparkline chart ***************************** //***********************************BEGIN Function calls ***************************** $('table th .checkall').on('click', function () { if ($(this).is(':checked')) { $(this).closest('table').find(':checkbox').attr('checked', true); $(this).closest('table').find('tr').addClass('row_selected'); //$(this).parent().parent().parent().toggleClass('row_selected'); } else { $(this).closest('table').find(':checkbox').attr('checked', false); $(this).closest('table').find('tr').removeClass('row_selected'); } }); //***********************************BEGIN Function calls ***************************** //***********************************BEGIN Function calls ***************************** $('.animate-number').each(function () { $(this).animateNumbers($(this).attr("data-value"), true, parseInt($(this).attr("data-animation-duration"), 10)); }); $('.animate-progress-bar').each(function () { $(this).css('width', $(this).attr("data-percentage")); }); //***********************************BEGIN Function calls ***************************** //***********************************BEGIN Tiles Controller Options ***************************** $('.widget-item > .controller .reload').click(function () { var el = $(this).parent().parent(); blockUI(el); window.setTimeout(function () { unblockUI(el); }, 1000); }); $('.widget-item > .controller .remove').click(function () { $(this).parent().parent().parent().addClass('animated fadeOut'); $(this).parent().parent().parent().attr('id', 'id_remove_temp_id'); setTimeout(function () { $('#id_remove_temp_id').remove(); }, 400); }); $('.tiles .controller .reload').click(function () { var el = $(this).parent().parent().parent(); blockUI(el); window.setTimeout(function () { unblockUI(el); }, 1000); }); $('.tiles .controller .remove').click(function () { $(this).parent().parent().parent().parent().addClass('animated fadeOut'); $(this).parent().parent().parent().parent().attr('id', 'id_remove_temp_id'); setTimeout(function () { $('#id_remove_temp_id').remove(); }, 400); }); if (!jQuery().sortable) { return; } $(".sortable").sortable({ connectWith: '.sortable', iframeFix: false, items: 'div.grid', opacity: 0.8, helper: 'original', revert: true, forceHelperSize: true, placeholder: 'sortable-box-placeholder round-all', forcePlaceholderSize: true, tolerance: 'pointer' }); //***********************************BEGIN Function calls ***************************** //***********************************BEGIN Function calls ***************************** $(window).resize(function () { calculateHeight(); }); $(window).scroll(function () { if ($(this).scrollTop() > 100) { $('.scrollup').fadeIn(); } else { $('.scrollup').fadeOut(); } }); //***********************************BEGIN Function calls ***************************** $('.scrollup').click(function () { $("html, body").animate({ scrollTop: 0 }, 700); return false; }); $("img").unveil(); }); $(window).resize(function () { }); function calculateHeight() { var contentHeight = parseInt($('.page-content').height(), 10); } function toggleMainMenu(){ var timer; if($('body').hasClass('open-menu-left')){ $('body').removeClass('open-menu-left'); timer= setTimeout(function(){ $('.page-sidebar').removeClass('visible'); }, 300); } else{ clearTimeout(timer); $('.page-sidebar').addClass('visible'); setTimeout(function(){ $('body').addClass('open-menu-left'); }, 50); } } function toggleChat(){ var timer; if($('body').hasClass('open-menu-right')){ $('body').removeClass('open-menu-right'); timer= setTimeout(function(){ $('.chat-window-wrapper').removeClass('visible'); }, 300); } else{ clearTimeout(timer); $('.chat-window-wrapper').addClass('visible'); $('body').addClass('open-menu-right'); } } $('body.open-menu-left .page-content').on('touchstart', function (e) { alert("asd"); }); //******************************* Bind Functions Jquery- LAYOUT OPTIONS API *************** (function ($) { //Show/Hide Main Menu $.fn.toggleMenu = function () { var windowWidth = window.innerWidth; if(windowWidth >768){ $(this).toggleClass('hide-sidebar'); } }; //Condense Main Menu $.fn.condensMenu = function () { var windowWidth = window.innerWidth; if(windowWidth >768){ if ($(this).hasClass('hide-sidebar')) $(this).toggleClass('hide-sidebar'); $(this).toggleClass('condense-menu'); $(this).find('#main-menu').toggleClass('mini'); } }; //Toggle Fixed Menu Options $.fn.toggleFixedMenu = function () { var windowWidth = window.innerWidth; if(windowWidth >768){ $(this).toggleClass('menu-non-fixed'); } }; $.fn.toggleHeader = function () { $(this).toggleClass('hide-top-content-header'); }; $.fn.toggleChat = function () { toggleChat(); }; $.fn.layoutReset = function () { $(this).removeClass('hide-sidebar'); $(this).removeClass('condense-menu'); $(this).removeClass('hide-top-content-header'); if(!$('body').hasClass('extended-layout')) $(this).find('#main-menu').removeClass('mini'); }; })(jQuery); function blockUI(el) { $(el).block({ message: '<div class="loading-animator"></div>', css: { border: 'none', padding: '2px', backgroundColor: 'none' }, overlayCSS: { backgroundColor: '#fff', opacity: 0.3, cursor: 'wait' } }); } // wrapper function to un-block element(finish loading) function unblockUI(el) { $(el).unblock(); }
import urlQuery from '../utils/url-query'; export default openFullscreen; export const type = 'OPEN_FULLSCREEN'; function openFullscreen() { return (dispatch, getState) => { const {base, id, environment} = getState(); if (id === '..' || !window.open) { return; } const href = urlQuery.format({ pathname: `${base}demo/${id}/index.html`, query: {environment} }); window.open(href, '_blank'); }; } openFullscreen.type = type;
var __reflect = (this && this.__reflect) || function (p, c, t) { p.__class__ = c, t ? t.push(c) : t = [c], p.__types__ = p.__types__ ? t.concat(p.__types__) : t; }; var __extends = this && this.__extends || function __extends(t, e) { function r() { this.constructor = t; } for (var i in e) e.hasOwnProperty(i) && (t[i] = e[i]); r.prototype = e.prototype, t.prototype = new r(); }; var Main = (function (_super) { __extends(Main, _super); function Main() { var _this = _super.call(this) || this; _this.addEventListener(egret.Event.ADDED_TO_STAGE, _this.onAddStage, _this); return _this; } Main.prototype.onAddStage = function (event) { this.init(); }; Main.prototype.init = function () { var txt = new egret.TextField(); this.addChild(txt); //添加到显示列表 txt.size = 60; //字体大小 txt.textColor = 0xff0000; //文本颜色 txt.text = "HelloWorld"; //文本内容 txt.x = 200; //x 坐标 txt.y = 200; //y 坐标 //创建一个Shape图形 var shape = new egret.Shape(); this.addChild(shape); //添加到容器中 shape.x = this.stage.stageWidth / 2; //需要在舞台添加后stage才能被引用 shape.y = this.stage.stageHeight / 2; shape.graphics.lineStyle(1, 0xff0000); shape.graphics.moveTo(0, 0); var R = 300; //半径 var n = 7; //边 for (var i = 1; i <= 360; i++) { var len = R * Math.sin(n * i); var tx = Math.cos(i) * len; var ty = Math.sin(i) * len; shape.graphics.lineTo(tx, ty); } }; return Main; }(egret.DisplayObjectContainer)); __reflect(Main.prototype, "Main"); //# sourceMappingURL=Main.js.map
// import 'react-native' import React from 'react' import View from '../index.js' import {shallow} from 'enzyme'; import { render, unmountComponentAtNode } from 'react-dom' import { cssLabels, rehydrate } from 'glamor' // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; test('renders correctly', () => { const tree = renderer.create( <View /> ).toJSON(); expect(tree).toMatchSnapshot(); }); // test('alignsVertical', () => { // // render(<View alignVertical='top' />, node, () => { // // expect(childStyle(node).justifyContent).toEqual('flex-start') // // }) // // cssLabels(true) // const Comp = shallow(<View alignVertical='top'/>) // // const className = Object.keys(Comp.prop('className'))[0] // console.log(Comp.props()); // // console.log(rehydrate([className])); // // console.log(Comp.prop('className')); // // expect(Comp.prop('style').justifyContent).toBe('flex-start') // expect(Comp.instance().props.style.justifyContent).toBe('flex-start') // cssLabels(false) // // expect(tree).toMatchSnapshot(); // }); // // // // it('applies the style to a given node', () => { // // render(<div {...style({ backgroundColor: 'red' })}/>, node, () => { // // expect(childStyle(node).backgroundColor).toEqual('rgb(255, 0, 0)') // // }) // // }) // // // function childStyle(node, p = null) { // return window.getComputedStyle(node.childNodes[0], p) // }
var baseUrl="",loadCss=function(a){var b=document.createElement("link");b.type="text/css";b.rel="stylesheet";b.href=baseUrl+a+".css";document.getElementsByTagName("head")[0].appendChild(b)}; require.config({baseUrl:baseUrl,map:{"*":{css:"assets/require-css/css"}},shim:{bootstrap:{deps:["jquery"]},bootbox:{deps:["jquery","bootstrap"]},bootstrapTable:{deps:["jquery","bootstrap","css!assets/bootstrap-tables/bootstrap-table.min.css"]},mcustomScrollbar:{deps:["jquery","css!assets/jquery-mcustom-scrollbar/jquery.mCustomScrollbar.min.css"]},validator:{deps:["jquery"]},MobileDetect:{deps:["jquery"]},datepicker:{deps:["jquery","bootstrap","css!assets/datepicker/css/datepicker.css"]},pickadate:{deps:["jquery", "css!assets/pickadate/themes/default.css"]},"pickadate-date":{deps:["jquery","pickadate","css!assets/pickadate/themes/default.date.css"]},"pickadate-time":{deps:["jquery","pickadate","css!assets/pickadate/themes/default.time.css"]},bootstrapTableFC:{deps:["jquery","bootstrapTable"]},mask:{deps:["jquery"]},select2:{deps:["jquery","css!assets/select2/css/select2.min.css","css!assets/select2/css/select2-bootstrap.css"]},notify:{deps:["jquery"]}},paths:{jquery:"assets/jquery/jquery.min",bootstrap:"assets/bootstrap/js/bootstrap.min", bootbox:"assets/bootbox/bootbox",datepicker:"assets/datepicker/js/bootstrap-datepicker",validator:"assets/bootstrap-validator/validator.min",mcustomScrollbar:"assets/jquery-mcustom-scrollbar/jquery.mCustomScrollbar.min",bootstrapTable:"assets/bootstrap-tables/bootstrap-table.min",bootstrapTableFC:"assets/bootstrap-tables/extensions/filter-control/bootstrap-table-filter-control.min",MobileDetect:"assets/mobile-detect/mobile-detect.min",mask:"assets/maskedinput/maskedinput",pickadate:"assets/pickadate/picker", "pickadate-date":"assets/pickadate/picker.date","pickadate-time":"assets/pickadate/picker.time",select2:"assets/select2/js/select2.min",notify:"/assets/notifyjs/notify.min"}}); requirejs(["jquery","MobileDetect","bootstrap","mcustomScrollbar","notify"],function(a,b){var c=new b(window.navigator.userAgent);a(document).ready(function(){a('nav.sidebar [data-toggle="tooltip"]').tooltip({container:"nav.sidebar"});c.mobile()||a(".sidebar-main").mCustomScrollbar({theme:"minimal",axis:"y"});a('[data-toggle="sidebar-toggle"]').click(function(){a(a(this).attr("href")).toggleClass("collapsed");a(".content-main, .footer-container").toggleClass("expanded")});a('[data-toggle="dropdown-sidebar"]').click(function(b){b.preventDefault(); a(this).parent().toggleClass("open")});a.notify.defaults({clickToHide:!0,autoHide:!0,autoHideDelay:5E3,arrowShow:!0,arrowSize:5,position:"...",elementPosition:"bottom left",globalPosition:"top right",style:"bootstrap",className:"error",showAnimation:"slideDown",showDuration:400,hideAnimation:"slideUp",hideDuration:200,gap:2})})});
var express = require('express'); var router = express.Router(); var mongoose = require('mongoose'); var User = mongoose.model('User'); // Create new user router.post('/', function(req, res, next) { user = new User(req.body); user.save(function (err) { if(err) { next(err); } res.status(200); res.send(); }); }); router.post('/:id', function (req, res, next) { user = User.findById(req.params.id, function (err, user) { if (err) { next(err); } user.username = req.body.username; user.password = req.body.password; user.roles = req.body.roles; user.save(function (err) { if (err) { next(err); } res.status(200); res.send(); }); }); }); module.exports = router;
// Generated by CoffeeScript 1.9.3 (function() { var ItemRegistry; module.exports = ItemRegistry = (function() { function ItemRegistry() { this.items = new WeakSet; } ItemRegistry.prototype.addItem = function(item) { if (this.hasItem(item)) { throw new Error("The workspace can only contain one instance of item " + item); } return this.items.add(item); }; ItemRegistry.prototype.removeItem = function(item) { return this.items["delete"](item); }; ItemRegistry.prototype.hasItem = function(item) { return this.items.has(item); }; return ItemRegistry; })(); }).call(this);
/* ======================================================================== * Bootstrap: carousel.js v3.4.0 * http://getbootstrap.com/javascript/#carousel * ======================================================================== * Copyright 2011-2018 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // CAROUSEL CLASS DEFINITION // ========================= var Carousel = function (element, options) { this.$element = $(element) this.$indicators = this.$element.find('.carousel-indicators') this.options = options this.paused = null this.sliding = null this.interval = null this.$active = null this.$items = null this.options.keyboard && this.$element.on('keydown.bs.carousel', $.proxy(this.keydown, this)) this.options.pause == 'hover' && !('ontouchstart' in document.documentElement) && this.$element .on('mouseenter.bs.carousel', $.proxy(this.pause, this)) .on('mouseleave.bs.carousel', $.proxy(this.cycle, this)) } Carousel.VERSION = '3.4.0' Carousel.TRANSITION_DURATION = 600 Carousel.DEFAULTS = { interval: 5000, pause: 'hover', wrap: true, keyboard: true } Carousel.prototype.keydown = function (e) { if (/input|textarea/i.test(e.target.tagName)) return switch (e.which) { case 37: this.prev(); break case 39: this.next(); break default: return } e.preventDefault() } Carousel.prototype.cycle = function (e) { e || (this.paused = false) this.interval && clearInterval(this.interval) this.options.interval && !this.paused && (this.interval = setInterval($.proxy(this.next, this), this.options.interval)) return this } Carousel.prototype.getItemIndex = function (item) { this.$items = item.parent().children('.item') return this.$items.index(item || this.$active) } Carousel.prototype.getItemForDirection = function (direction, active) { var activeIndex = this.getItemIndex(active) var willWrap = (direction == 'prev' && activeIndex === 0) || (direction == 'next' && activeIndex == (this.$items.length - 1)) if (willWrap && !this.options.wrap) return active var delta = direction == 'prev' ? -1 : 1 var itemIndex = (activeIndex + delta) % this.$items.length return this.$items.eq(itemIndex) } Carousel.prototype.to = function (pos) { var that = this var activeIndex = this.getItemIndex(this.$active = this.$element.find('.item.active')) if (pos > (this.$items.length - 1) || pos < 0) return if (this.sliding) return this.$element.one('slid.bs.carousel', function () { that.to(pos) }) // yes, "slid" if (activeIndex == pos) return this.pause().cycle() return this.slide(pos > activeIndex ? 'next' : 'prev', this.$items.eq(pos)) } Carousel.prototype.pause = function (e) { e || (this.paused = true) if (this.$element.find('.next, .prev').length && $.support.transition) { this.$element.trigger($.support.transition.end) this.cycle(true) } this.interval = clearInterval(this.interval) return this } Carousel.prototype.next = function () { if (this.sliding) return return this.slide('next') } Carousel.prototype.prev = function () { if (this.sliding) return return this.slide('prev') } Carousel.prototype.slide = function (type, next) { var $active = this.$element.find('.item.active') var $next = next || this.getItemForDirection(type, $active) var isCycling = this.interval var direction = type == 'next' ? 'left' : 'right' var that = this if ($next.hasClass('active')) return (this.sliding = false) var relatedTarget = $next[0] var slideEvent = $.Event('slide.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) this.$element.trigger(slideEvent) if (slideEvent.isDefaultPrevented()) return this.sliding = true isCycling && this.pause() if (this.$indicators.length) { this.$indicators.find('.active').removeClass('active') var $nextIndicator = $(this.$indicators.children()[this.getItemIndex($next)]) $nextIndicator && $nextIndicator.addClass('active') } var slidEvent = $.Event('slid.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) // yes, "slid" if ($.support.transition && this.$element.hasClass('slide')) { $next.addClass(type) if (typeof $next === 'object' && $next.length) { $next[0].offsetWidth // force reflow } $active.addClass(direction) $next.addClass(direction) $active .one('bsTransitionEnd', function () { $next.removeClass([type, direction].join(' ')).addClass('active') $active.removeClass(['active', direction].join(' ')) that.sliding = false setTimeout(function () { that.$element.trigger(slidEvent) }, 0) }) .emulateTransitionEnd(Carousel.TRANSITION_DURATION) } else { $active.removeClass('active') $next.addClass('active') this.sliding = false this.$element.trigger(slidEvent) } isCycling && this.cycle() return this } // CAROUSEL PLUGIN DEFINITION // ========================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.carousel') var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option) var action = typeof option == 'string' ? option : options.slide if (!data) $this.data('bs.carousel', (data = new Carousel(this, options))) if (typeof option == 'number') data.to(option) else if (action) data[action]() else if (options.interval) data.pause().cycle() }) } var old = $.fn.carousel $.fn.carousel = Plugin $.fn.carousel.Constructor = Carousel // CAROUSEL NO CONFLICT // ==================== $.fn.carousel.noConflict = function () { $.fn.carousel = old return this } // CAROUSEL DATA-API // ================= var clickHandler = function (e) { var $this = $(this) var href = $this.attr('href') if (href) { href = href.replace(/.*(?=#[^\s]+$)/, '') // strip for ie7 } var target = $this.attr('data-target') || href var $target = $(document).find(target) if (!$target.hasClass('carousel')) return var options = $.extend({}, $target.data(), $this.data()) var slideIndex = $this.attr('data-slide-to') if (slideIndex) options.interval = false Plugin.call($target, options) if (slideIndex) { $target.data('bs.carousel').to(slideIndex) } e.preventDefault() } $(document) .on('click.bs.carousel.data-api', '[data-slide]', clickHandler) .on('click.bs.carousel.data-api', '[data-slide-to]', clickHandler) $(window).on('load', function () { $('[data-ride="carousel"]').each(function () { var $carousel = $(this) Plugin.call($carousel, $carousel.data()) }) }) }(jQuery);
// MIT License: // // Copyright (c) 2016-2017, Alexander I. Chebykin // // 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. /** * CAI CP v.0.9 * * @module : Configuration subsystem * @author : Alexander I. Chebykin <alex.chebykin@gmail.com> * @copyright : Copyright (c) 2016-2017 Alexander I. Chebykin * @version : 0.9 * @build date : 2017-07-23 * @license : MIT * @link : https://github.com/CAI79/CAI-CP ******************************************************************/ (function () { 'use strict'; /** * Return GET parameter * * @param {string} key Key name * * returns {string} */ function $_GET(key) { var s = window.location.search; s = s.match(new RegExp(key + '=([^&=]+)')); return s ? s[1] : false; } /** * SetupSystem constructor * * @returns {undefined} */ function SetupSystem() { this.locale = 'en'; this.langs = []; this.tranlation = []; } /** * * @param {int} init_level Initialization level: 1 - configure language * 2 - do localization * 3 - load languages list * * @returns {undefined} */ SetupSystem.prototype.init = function (init_level) { var setup_instance = this, request = new XMLHttpRequest(), res_data; switch (init_level) { case 1: // Configure language if ($_GET('lang') !== '') { this.locale = $_GET('lang'); } else { request.open('GET', '../../../json/settings.json'); request.send(); request.onreadystatechange = function () { if (this.readyState === 4) { if (this.status === 200) { res_data = JSON.parse(this.responseText); setup_instance.locale = res_data.lang; } } }; } this.init(2); break; case 2: // Do localization request.open('GET', '../../../json/locale/' + this.locale + '.json'); request.send(); request.onreadystatechange = function () { if (this.readyState === 4) { if (this.status === 200) { res_data = JSON.parse(this.responseText); setup_instance.tranlation = res_data; document.getElementById('lbl_dim_on_create').textContent = res_data.dim_on_create; document.getElementById('lbl_default_language').textContent = res_data.default_language; document.getElementById('lbl_check_files_rights').textContent = res_data.check_files_rights; document.getElementById('lbl_check_hdd_temp_interval').textContent = res_data.check_hdd_temp_int; document.getElementById('lbl_check_users_online_interval').textContent = res_data.check_users_online_int; document.getElementById('lbl_max_hdd_temp').textContent = res_data.max_hdd_temp; document.getElementById('lbl_check_smart_interval').textContent = res_data.check_smart_int; document.getElementById('lbl_temp_secs').textContent = res_data.secs; document.getElementById('lbl_smart_secs').textContent = res_data.secs; document.getElementById('lbl_users_online_secs').textContent = res_data.secs; document.getElementById('fsl_general').textContent = res_data.general_settings; document.getElementById('fsl_monitoring').textContent = res_data.monitoring; document.getElementById('fsl_apps').textContent = res_data.applications; document.getElementById('lbl_enabled').textContent = res_data.enbld; document.getElementById('lbl_app_name').textContent = res_data.application; document.getElementById('lbl_app_ver').textContent = res_data.version; document.getElementById('lbl_app_author').textContent = res_data.author; document.getElementById('in_submit').value = res_data.save; document.getElementById("frm_submit").classList.remove('hidden'); } } }; this.init(3); break; case 3: // Load languages list request.open('GET', '../../../json/settings.json'); request.send(); request.onreadystatechange = function () { if (this.readyState === 4) { if (this.status === 200) { var select_lang = document.getElementById('default_language'); res_data = JSON.parse(this.responseText); document.getElementById('dim_on_create').checked = res_data.dim_on_create; document.getElementById('chk_files_rights').checked = res_data.check_files_rights; document.getElementById('chk_temp_interval').value = res_data.check_hdd_temp_interval; document.getElementById('chk_smart_interval').value = res_data.check_smart_interval; document.getElementById('chk_users_online_interval').value = res_data.check_users_online_interval; document.getElementById('max_hdd_temp').value = res_data.max_hdd_temp; setup_instance.langs = res_data.langs; for (var language in res_data.langs) { var opt_lang = document.createElement('option'); opt_lang.value = language; opt_lang.appendChild(document.createTextNode(res_data.langs[language])); if (res_data.lang === language) { opt_lang.selected = true; } else if (!$_GET('lang') && setup_instance.locale === language){ opt_lang.selected = true; } select_lang.appendChild(opt_lang); } } } }; this.init(4); break; case 4: // Load apps list request.open('GET', '../../../apps/?do=get_apps'); request.send(); request.onreadystatechange = function () { if (this.readyState === 4) { if (this.status === 200) { var apps_table = document.getElementById('tbl_apps'), apps_tr, apps_td, apps_name, apps_caption, apps_check, i = 0; res_data = JSON.parse(this.responseText); for (var app_info in res_data) { apps_tr = document.createElement('tr'); apps_td = document.createElement('td'); apps_caption = document.createElement('input'); apps_caption.type = 'hidden'; apps_caption.name = 'app_caption[' + i + ']'; apps_caption.value = res_data[app_info].caption; apps_td.appendChild(apps_caption); apps_name = document.createElement('input'); apps_name.type = 'hidden'; apps_name.name = 'app_name[' + i + ']'; apps_name.value = app_info; apps_td.appendChild(apps_name); apps_check = document.createElement('input'); apps_check.type = 'checkbox'; apps_check.name = 'app_enabled[' + i + ']'; apps_check.value = '1'; apps_check.checked = res_data[app_info].enabled; apps_td.appendChild(apps_check); apps_tr.appendChild(apps_td); apps_td = document.createElement('td'); apps_td.appendChild(document.createTextNode(res_data[app_info].caption)); apps_tr.appendChild(apps_td); apps_td = document.createElement('td'); apps_td.appendChild(document.createTextNode(res_data[app_info].version)); apps_tr.appendChild(apps_td); apps_td = document.createElement('td'); apps_td.appendChild(document.createTextNode(res_data[app_info].author)); apps_tr.appendChild(apps_td); apps_table.appendChild(apps_tr); i++; } } } }; } }; document.addEventListener('DOMContentLoaded', function () { 'use strict'; /** * Initialize setup object */ var setup = new SetupSystem(); setup.init(1); document.getElementById('frm_submit').onsubmit = function () { var xhr = new XMLHttpRequest(); xhr.onload = function () { if (xhr.responseText === 'true') { alert(setup.tranlation.settings_saved); window.top.location.reload(true); } else { alert(setup.tranlation.error); } }; if (this.method.toLowerCase() === 'post') { xhr.open (this.method, this.action, true); xhr.send (new FormData (this)); } else { var element, el_type, file, search = ''; for (var i = 0; i < this.elements.length; i++) { element = this.elements[i]; if (!element.hasAttribute('name')) { continue; } el_type = element.nodeName.toLowerCase() === 'input' ? element.getAttribute('type').toLowerCase() : 'text'; if (el_type === 'file') { for (file = 0; file < element.files.length; search += '&' + escape(element.name) + '=' + escape(element.files[file++].name)); } else if ((el_type !== 'radio' && el_type !== 'checkbox') || element.checked) { search += '&' + escape(element.name) + '=' + escape(element.value); } } xhr.open('get', this.action.replace(/(?:\?.*)?$/, search.replace(/^&/, '?')), true); xhr.send(null); } return false; }; }); }());
/*global chrome*/ chrome.app.runtime.onLaunched.addListener(function() { chrome.app.window.create('/index.html', { id: "git-browse-app-main", }); });
import webpack from 'webpack' import cssnano from 'cssnano' import HtmlWebpackPlugin from 'html-webpack-plugin' import ExtractTextPlugin from 'extract-text-webpack-plugin' import config from '../config' import _debug from 'debug' const debug = _debug('app:webpack:config') const paths = config.utils_paths const {__DEV__, __PROD__, __TEST__} = config.globals debug('Create configuration.') const webpackConfig = { name: 'client', target: 'web', devtool: config.compiler_devtool, resolve: { root: paths.client(), extensions: ['', '.js', '.jsx', '.json'] }, module: {} } // ------------------------------------ // Entry Points // ------------------------------------ const APP_ENTRY_PATHS = [ paths.client('main.js') ] webpackConfig.entry = { app: __DEV__ ? APP_ENTRY_PATHS.concat(`webpack-hot-middleware/client?path=${config.compiler_public_path}__webpack_hmr`) : APP_ENTRY_PATHS, vendor: config.compiler_vendor } // ------------------------------------ // Bundle Output // ------------------------------------ webpackConfig.output = { filename: `[name].[${config.compiler_hash_type}].js`, path: paths.dist(), publicPath: config.compiler_public_path } // ------------------------------------ // Plugins // ------------------------------------ webpackConfig.plugins = [ new webpack.DefinePlugin(config.globals), new HtmlWebpackPlugin({ template: paths.client('index.html'), hash: false, favicon: paths.client('static/favicon.ico'), filename: 'index.html', inject: 'body', minify: { collapseWhitespace: true } }) ] if (__DEV__) { debug('Enable plugins for live development (HMR, NoErrors).') webpackConfig.plugins.push( new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin() ) } else if (__PROD__) { debug('Enable plugins for production (OccurenceOrder, Dedupe & UglifyJS).') webpackConfig.plugins.push( new webpack.optimize.OccurrenceOrderPlugin(), new webpack.optimize.DedupePlugin(), new webpack.optimize.UglifyJsPlugin({ compress: { unused: true, dead_code: true, warnings: false } }) ) } // Don't split bundles during testing, since we only want import one bundle if (!__TEST__) { webpackConfig.plugins.push( new webpack.optimize.CommonsChunkPlugin({ names: ['vendor'] }) ) } // ------------------------------------ // Pre-Loaders // ------------------------------------ /* [ NOTE ] We no longer use eslint-loader due to it severely impacting build times for larger projects. `npm run lint` still exists to aid in deploy processes (such as with CI), and it's recommended that you use a linting plugin for your IDE in place of this loader. If you do wish to continue using the loader, you can uncomment the code below and run `npm i --save-dev eslint-loader`. This code will be removed in a future release. webpackConfig.module.preLoaders = [{ test: /\.(js|jsx)$/, loader: 'eslint', exclude: /node_modules/ }] webpackConfig.eslint = { configFile: paths.base('.eslintrc'), emitWarning: __DEV__ } */ // ------------------------------------ // Loaders // ------------------------------------ // JavaScript / JSON webpackConfig.module.loaders = [{ test: /\.(js|jsx)$/, exclude: /node_modules/, loader: 'babel', query: { cacheDirectory: true, plugins: ['transform-runtime'], presets: ['es2015', 'react', 'stage-0'] } }, { test: /\.json$/, loader: 'json' }] // ------------------------------------ // Style Loaders // ------------------------------------ // We use cssnano with the postcss loader, so we tell // css-loader not to duplicate minimization. const BASE_CSS_LOADER = 'css?sourceMap&-minimize' // Add any packge names here whose styles need to be treated as CSS modules. // These paths will be combined into a single regex. const PATHS_TO_TREAT_AS_CSS_MODULES = [ // 'react-toolbox', (example) ] // If config has CSS modules enabled, treat this project's styles as CSS modules. if (config.compiler_css_modules) { PATHS_TO_TREAT_AS_CSS_MODULES.push( paths.client().replace(/[\^\$\.\*\+\-\?\=\!\:\|\\\/\(\)\[\]\{\}\,]/g, '\\$&') // eslint-disable-line ) } const isUsingCSSModules = !!PATHS_TO_TREAT_AS_CSS_MODULES.length const cssModulesRegex = new RegExp(`(${PATHS_TO_TREAT_AS_CSS_MODULES.join('|')})`) // Loaders for styles that need to be treated as CSS modules. if (isUsingCSSModules) { const cssModulesLoader = [ BASE_CSS_LOADER, 'modules', 'importLoaders=1', 'localIdentName=[name]__[local]___[hash:base64:5]' ].join('&') webpackConfig.module.loaders.push({ test: /\.scss$/, include: cssModulesRegex, loaders: [ 'style', cssModulesLoader, 'postcss', 'sass?sourceMap' ] }) webpackConfig.module.loaders.push({ test: /\.css$/, include: cssModulesRegex, loaders: [ 'style', cssModulesLoader, 'postcss' ] }) } // Loaders for files that should not be treated as CSS modules. const excludeCSSModules = isUsingCSSModules ? cssModulesRegex : false webpackConfig.module.loaders.push({ test: /\.scss$/, exclude: excludeCSSModules, loaders: [ 'style', BASE_CSS_LOADER, 'postcss', 'sass?sourceMap' ] }) webpackConfig.module.loaders.push({ test: /\.css$/, exclude: excludeCSSModules, loaders: [ 'style', BASE_CSS_LOADER, 'postcss' ] }) // ------------------------------------ // Style Configuration // ------------------------------------ webpackConfig.sassLoader = { includePaths: paths.client('styles') } webpackConfig.postcss = [ cssnano({ autoprefixer: { add: true, remove: true, browsers: ['last 2 versions'] }, discardComments: { removeAll: true }, discardUnused: false, mergeIdents: false, reduceIdents: false, safe: true, sourcemap: true }) ] // File loaders /* eslint-disable */ webpackConfig.module.loaders.push( { test: /\.woff(\?.*)?$/, loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/font-woff' }, { test: /\.woff2(\?.*)?$/, loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/font-woff2' }, { test: /\.otf(\?.*)?$/, loader: 'file?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=font/opentype' }, { test: /\.ttf(\?.*)?$/, loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/octet-stream' }, { test: /\.eot(\?.*)?$/, loader: 'file?prefix=fonts/&name=[path][name].[ext]' }, { test: /\.svg(\?.*)?$/, loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=image/svg+xml' }, { test: /\.(png|jpg|gif)$/, loader: 'url?limit=8192' } ) /* eslint-enable */ // ------------------------------------ // Finalize Configuration // ------------------------------------ // when we don't know the public path (we know it only when HMR is enabled [in development]) we // need to use the extractTextPlugin to fix this issue: // http://stackoverflow.com/questions/34133808/webpack-ots-parsing-error-loading-fonts/34133809#34133809 if (!__DEV__) { debug('Apply ExtractTextPlugin to CSS loaders.') webpackConfig.module.loaders.filter((loader) => loader.loaders && loader.loaders.find((name) => /css/.test(name.split('?')[0])) ).forEach((loader) => { const [first, ...rest] = loader.loaders loader.loader = ExtractTextPlugin.extract(first, rest.join('!')) Reflect.deleteProperty(loader, 'loaders') }) webpackConfig.plugins.push( new ExtractTextPlugin('[name].[contenthash].css', { allChunks: true }) ) } export default webpackConfig
/** * Base64 Encoder * * @see `gherkin/formatter/json_formatter` * @param {string} input File data * @returns {string} Base64-encoded file */ function base64encode(input) { var swaps = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9","+","/"]; var input_binary = ""; var output = ""; var temp_binary; var index; for (index=0; index < input.length; index++) { temp_binary = input.charCodeAt(index).toString(2); while (temp_binary.length < 8) { temp_binary = "0"+temp_binary; } input_binary = input_binary + temp_binary; while (input_binary.length >= 6) { output = output + swaps[parseInt(input_binary.substring(0,6),2)]; input_binary = input_binary.substring(6); } } if (input_binary.length === 4) { temp_binary = input_binary + "00"; output = output + swaps[parseInt(temp_binary,2)]; output = output + "="; } if (input_binary.length === 2) { temp_binary = input_binary + "0000"; output = output + swaps[parseInt(temp_binary,2)]; output = output + "=="; } return output; }
module.exports = function(Quill) { const BlockEmbed = Quill.import("blots/block/embed") const ClipCache = require("../IframeClipCache.js") const cssClass = require("../../utils/cssClass.js") const DIMENSION_TIMER_INTERVAL = 5000 const CSS_SCOPE_CLASS_PREFIX = "css-scope__" class IframeBlot extends BlockEmbed { constructor(element, value) { super(element, value) /* NOTE: I'm creating custom variables even if they already exist on the blot, because I like consistent naming with the rest of my library */ /** * The html element */ this.element = element /** * ID of the clip-cache storage */ this.clipCacheId = ClipCache.generateId() // a tick to let Quill put the element into the DOM setTimeout(() => { // check compatibility if (!element.contentDocument || !element.contentWindow) { console.error("iframe javascript interface not supported") return } this.initialize() }, 0) } deleteAt(index, length) { if (this.delete) this.delete() super.deleteAt(index, length) } value() { // override this return super.value() } /////////////////////////// // Custom implementation // /////////////////////////// /** * Initialize all necessary things */ initialize() { /** * Parent text pad */ this.textPad = null /** * Document of the iframe content */ this.contentDocument = this.element.contentDocument /** * Window of the iframe content */ this.contentWindow = this.element.contentWindow /** * Body of the content document */ this.contentBody = this.contentDocument.body /** * Content div of the iframe */ this.contentDiv = null this.getParentTextPad() this.setupDomAndStyles() this.startDimensionTimer() } /** * Finds the parent text pad element */ getParentTextPad() { // find parent widet let el = this.element let padElement = null while (el.parentElement) { if (el.getAttribute("mycelium-text-pad") === "here") { padElement = el break } el = el.parentElement } if (!padElement) { console.error("Unable to find parent text pad!") return null } this.textPad = padElement.textPad } /** * Create content document */ setupDomAndStyles() { // set iframe attributes this.element.setAttribute("scrolling", "no") this.element.setAttribute("frameborder", "0") // set clip-cache id this.element.setAttribute("mycelium-clip-cache-id", this.clipCacheId) // create and register content div this.contentBody.innerHTML = `<div></div>` this.contentDiv = this.contentBody.children[0] // remove margin and margin overflow this.contentBody.style.margin = "0" this.contentDiv.style.padding = "1px" this.copyCssStyles() this.applyCssScopes() } /** * Applies all CSS styles to the iframe content * that are in the main document body */ copyCssStyles() { let links = this.element.ownerDocument.querySelectorAll( 'link[rel="stylesheet"]' ) for (let i = 0; i < links.length; i++) { let copy = this.contentDocument.createElement("link") copy.setAttribute("href", links[i].getAttribute("href")) copy.setAttribute("type", links[i].getAttribute("type")) copy.setAttribute("rel", links[i].getAttribute("rel")) this.contentDocument.body.appendChild(copy) } let styles = this.element.ownerDocument.querySelectorAll("style") for (let i = 0; i < styles.length; i++) { let copy = this.contentDocument.createElement("style") copy.innerHTML = styles[i].innerHTML this.contentDocument.body.appendChild(copy) } } /** * Adds css scopes to the content div element */ applyCssScopes() { let scopes = this.textPad.options.cssScope if (scopes === null) return if (typeof(scopes) === "string") scopes = [scopes] for (let i = 0; i < scopes.length; i++) { cssClass( this.contentDiv, CSS_SCOPE_CLASS_PREFIX + scopes[i], true ) } } /** * Starts the dimension timer */ startDimensionTimer() { // call the update once right after initialization setTimeout(() => { this.updateDimensions() }, 500) // random offset setTimeout(() => { // interval this.dimensionTimerId = setInterval(() => { this.updateDimensions() }, DIMENSION_TIMER_INTERVAL) }, Math.random() * DIMENSION_TIMER_INTERVAL) } /** * Updates iframe height */ updateDimensions() { this.element.style.height = this.contentDiv.offsetHeight + "px" } /** * Loads quill.js in the iframe * (not called by default, you have to call this yourself) */ loadQuill(callback) { let rootQuillScript = this.element.ownerDocument.querySelector( 'script[mycelium-quill-script]' ) if (!rootQuillScript) { console.error("Mycelium quill script not found!") return } quillLink = this.contentDocument.createElement("script") quillLink.onload = () => { // register blots require("../../initialization.js").setupQuill(this.contentWindow) // redirect undo and redo commands let history = this.contentWindow.Quill.import("modules/history") history.prototype.undo = () => { this.textPad.quill.history.undo() } history.prototype.redo = () => { this.textPad.quill.history.redo() } callback() } quillLink.src = rootQuillScript.src this.contentBody.appendChild(quillLink) } /** * Called, when the blot is being deleted */ destroy() { // remove timer clearInterval(this.dimensionTimerId) } } IframeBlot.tagName = "iframe" return IframeBlot }
module.exports = function(app){ // ===================================== // STUDIES PAGE ========= // ===================================== var fs = require('fs'); app.get('/etudes', function(req, res) { fs.readFile('./data/etudes.json', 'utf8', function (err, data) { if (err) { console.log(err); } var obj = JSON.parse(data); console.log(obj.pageTitle); res.render('etudes.ejs', {obj : obj}); // load the template.ejs file }); }); }
'use strict'; const validator = require('validator'); /** * Created by Adrian on 20-Mar-16. */ module.exports = (IFace) => { return class SanitizeDomain extends IFace { static code() { return "DOMAIN" }; static publicName() { return "Domain"; } /* Validates if the given domain is a valid domain name * OPTIONS: * - private=false -> if set to true, will pass if the domain is a local one * - underscore=true -> allow underscores? * */ validate(d, opt) { if(typeof d !== 'string' || !d) return false; d = d.trim().toLowerCase(); d = d.replace(/\s+/g,''); let v = validator.isFQDN(d, { require_tld: opt.private ? false : true, allow_underscores: (typeof opt.underscore === 'undefined' ? true : opt.underscore) }); if(!v) return false; return { value: d }; } } };
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import { describe, it } from 'mocha'; import { expectPassesRule, expectFailsRule } from './harness'; import { KnownFragmentNames, unknownFragmentMessage, } from '../rules/KnownFragmentNames'; function undefFrag(fragName, line, column) { return { message: unknownFragmentMessage(fragName), locations: [{ line, column }], }; } describe('Validate: Known fragment names', () => { it('known fragment names are valid', () => { expectPassesRule( KnownFragmentNames, ` { human(id: 4) { ...HumanFields1 ... on Human { ...HumanFields2 } ... { name } } } fragment HumanFields1 on Human { name ...HumanFields3 } fragment HumanFields2 on Human { name } fragment HumanFields3 on Human { name } `, ); }); it('unknown fragment names are invalid', () => { expectFailsRule( KnownFragmentNames, ` { human(id: 4) { ...UnknownFragment1 ... on Human { ...UnknownFragment2 } } } fragment HumanFields on Human { name ...UnknownFragment3 } `, [ undefFrag('UnknownFragment1', 4, 14), undefFrag('UnknownFragment2', 6, 16), undefFrag('UnknownFragment3', 12, 12), ], ); }); });
Rickshaw.namespace('Rickshaw.Graph.Renderer.LinePlot'); Rickshaw.Graph.Renderer.LinePlot = Rickshaw.Class.create( Rickshaw.Graph.Renderer, { name: 'lineplot', defaults: function($super) { return Rickshaw.extend( $super(), { unstack: true, fill: false, stroke: true, padding:{ top: 0.01, right: 0.01, bottom: 0.01, left: 0.01 }, dotSize: 3, strokeWidth: 2 } ); }, seriesPathFactory: function() { var graph = this.graph; return d3.line() .x( function(d) { return graph.x(d.x) } ) .y( function(d) { return graph.y(d.y) } ) .curve(this.graph.curve) .defined( function(d) { return d.y !== null } ); }, render: function(args) { args = args || {}; var graph = this.graph; var series = args.series || graph.series; var vis = args.vis || graph.vis; var dotSize = this.dotSize; vis.selectAll('*').remove(); var data = series .filter(function(s) { return !s.disabled }) .map(function(s) { return s.stack }); var nodes = vis.selectAll("path") .data(data) .enter().append("svg:path") .attr("d", this.seriesPathFactory()); var i = 0; series.forEach(function(series) { if (series.disabled) return; series.path = nodes._groups[0][i++]; this._styleSeries(series); }, this); series.forEach(function(series) { if (series.disabled) return; var nodes = vis.selectAll("x") .data(series.stack.filter( function(d) { return d.y !== null } )) .enter().append("svg:circle") .attr("cx", function(d) { return graph.x(d.x) }) .attr("cy", function(d) { return graph.y(d.y) }) .attr("r", function(d) { return ("r" in d) ? d.r : dotSize}); Array.prototype.forEach.call(nodes._groups[0], function(n) { if (!n) return; n.setAttribute('data-color', series.color); n.setAttribute('fill', 'white'); n.setAttribute('stroke', series.color); n.setAttribute('stroke-width', this.strokeWidth); }.bind(this)); }, this); } } );
'use strict'; var fs = require('fs'); var pluginFile = 'scatterplot.js'; var baseURL = 'http://slc05pvj.us.oracle.com:9704/mobile/'; var bimad = require('orabimad-server'); var HOSTNAME = 'localhost'; var LIVERELOAD_PORT = 35729; var lrSnippet = require('connect-livereload')({port: LIVERELOAD_PORT}); var dynamicServer = function(connect, dir) { return new bimad.server(pluginFile, dir).createMiddleware(); } var readFile = function(path, encoding) { encoding = (encoding === undefined)?null:encoding; return fs.readFileSync(path, {'encoding': encoding}); } var archive = function(zip, path) { var fileStat = fs.statSync(path); if (fileStat.isDirectory()) { // read file and archive recursively var files = fs.readdirSync(path); // pick up csv files for (var i=0, len=files.length; i<len; i++) { archive(zip, path+'/'+files[i]); } } else if (fileStat.isFile()) { // ignore some files if (path.search(/.DS_Store|.*~|.*.swp/) !== -1) { return; } var buf = readFile(path); zip.file(path, buf.toString('base64'), {base64: true}); } } var getPluginId = function() { var vm = require('vm'); var code = fs.readFileSync(pluginFile).toString('utf8'); vm.runInThisContext('var plugin='+code); return vm.runInThisContext('plugin.id'); } var reauth = function(securityService, pluginService) { var inquirer = require('inquirer'); var URL = require('url'); inquirer.prompt([{ type: 'input', name: 'server', message: 'Enter server url', default: URL.format(baseURL) },{ type: 'input', name: 'username', message: 'Enter Login name with Administrator priviledge' }, { type: 'password', name: 'password', message: 'Enter Login password with Administrator priviledge' }], function(answers) { var username = answers['username']; var password = answers['password']; var newURL = answers['server']; if (newURL !== baseURL) { baseURL = newURL; securityService.setURL(baseURL); pluginService.setURL(baseURL); } // login to get token securityService.login(username, password); }); } module.exports = function (grunt) { // load all grunt tasks require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks); grunt.initConfig({ watch: { options: { nospawn: true, livereload: LIVERELOAD_PORT }, watchFiles: { files: [pluginFile, 'data/*.csv', 'assets/*.js', 'assets/**/*.js', 'assets/*.css', 'assets/**/*.css'], tasks: ['reload'] } }, reload: { port: LIVERELOAD_PORT, livereload: true }, connect: { options: { port: 9000, hostname: HOSTNAME }, livereload: { options: { middleware: function (connect) { return [ lrSnippet, dynamicServer(connect, '.') ]; } } } }, open: { server: { path: 'http://<%= connect.options.hostname %>:<%= connect.options.port %>' } } }); grunt.registerTask('server', ['connect:livereload', 'open', 'watch']); /* grunt.registerTask('logout', 'Logout from the server', function(a,b) { var SecurityService = bimad.ws.SecurityService; var securityService = new SecurityService(baseURL); var session = securityService.loadSession(); if (session != null) { securityService.logout(session); } }); */ grunt.registerTask('archive', 'Archive Files for deploy', function() { // create zip var zip = new require('node-zip')(); var path = require('path'); archive(zip, pluginFile); // archive assets if exists if (fs.existsSync('assets')) { archive(zip, 'assets'); } // parse pluginFile and get id var pluginId = getPluginId(); var dum = zip.generate({base64: false, compression: 'DEFLATE'}); fs.writeFileSync(pluginId+'.xmp', zip.generate({base64: false, compression: 'DEFLATE'}), 'binary'); }); grunt.registerTask('_deploy', 'Deploy plugin code', function() { var done = this.async(); var PluginService = bimad.ws.PluginService; var SecurityService = bimad.ws.SecurityService; // read plugin file var Buffer = require('buffer').Buffer; var pluginId = getPluginId(); var data = new Buffer(fs.readFileSync(pluginId+'.xmp', {encoding: null})).toString('base64'); var pluginService = new PluginService(baseURL); pluginService.on('success', function() { console.log('SUCCESSFULLY UPLOADED'); done(); }); pluginService.on('error', function(err) { console.log('Deploy error occurred. '+err); // typically, invalid (expired) token. // ask user to enter username and password securityService.once('success', function(token) { pluginService.deploy(token, appPath, pluginId, data); }); reauth(securityService, pluginService); }); // check saved session var securityService = new SecurityService(baseURL); var session = securityService.loadSession(); // if there is not, re-authenticate var appPath = '/DUM_FORNOW'; if (session === undefined || session === null) { console.log('Session code is not found reauth before deploy.'); // typically, invalid (expired) token. // ask user to enter username and password securityService.once('success', function(token) { pluginService.deploy(token, appPath, pluginId, data); }); reauth(securityService, pluginService); } else { // console.log("Try deploying pliugin file with session="+session); pluginService.deploy(session, appPath, pluginId, data); } }); grunt.registerTask('undeploy', 'Undeploy plugin code', function() { var done = this.async(); var PluginService = bimad.ws.PluginService; var SecurityService = bimad.ws.SecurityService; var pluginId = getPluginId(); var pluginService = new PluginService(baseURL); pluginService.on('success', function(val) { if (val.toString() === 'true') { console.log('SUCCESSFULLY DELETED'); } else { console.log('PLUGIN WAS NOT FOUND'); } done(); }); pluginService.on('error', function(err) { console.log('Deploy error occurred. '+err); // typically, invalid (expired) token. // ask user to enter username and password securityService.once('success', function(token) { pluginService.undeploy(token, appPath, pluginId); }); reauth(securityService, pluginService); }); // check saved session var securityService = new SecurityService(baseURL); var session = securityService.loadSession(); // if there is not, re-authenticate var appPath = '/DUM_FORNOW'; if (session === undefined || session === null) { console.log('Session code is not found reauth before deploy.'); // typically, invalid (expired) token. // ask user to enter username and password securityService.once('success', function(token) { pluginService.undeploy(token, appPath, pluginId); }); reauth(securityService, pluginService); } else { // console.log("Try deploying pliugin file with session="+session); pluginService.undeploy(session, appPath, pluginId); } }); grunt.registerTask('deploy', ['archive', '_deploy']); };
export * from './reactive';
window.gameon = window.gameon || {}; window.gameon.wordutils = new (function () { "use strict"; var self = this; var word_frequencies = { 'E': 12.02, 'T': 9.10, 'A': 8.12, 'O': 7.68, 'I': 7.31, 'N': 6.95, 'S': 6.28, 'R': 6.02, 'H': 5.92, 'D': 4.32, 'L': 3.98, 'U': 2.88, 'C': 2.71, 'M': 2.61, 'F': 2.30, 'Y': 2.11, 'W': 2.09, 'G': 2.03, 'P': 1.82, 'B': 1.49, 'V': 1.11, 'K': 0.69, 'X': 0.17, 'Q': 0.11, 'J': 0.10, 'Z': 0.07 }; var scrabbleScoring = { 'A': 1, 'B': 3, 'C': 3, 'D': 2, 'E': 1, 'F': 4, 'G': 2, 'H': 4, 'I': 1, 'J': 8, 'K': 5, 'L': 1, 'M': 3, 'N': 1, 'O': 1, 'P': 3, 'Q': 10, 'R': 1, 'S': 1, 'T': 1, 'U': 1, 'V': 4, 'W': 4, 'X': 8, 'Y': 4, 'Z': 10 }; function cdf(hist) { var keys = Object.keys(hist); for (var i = 1; i < keys.length; i++) { hist[keys[i]] = hist[keys[i]] + hist[keys[i - 1]]; } return hist; } var word_cdf = cdf(word_frequencies); self.getRandomLetter = function () { var position = Math.random(); var keys = Object.keys(word_cdf); for (var i = 0; i < keys.length; i++) { if (position <= word_cdf[keys[i]] / 100) { return keys[i]; } } }; self.scoreWord = function (word) { var score = 0; for (var i = 0; i < word.length; i++) { score += scrabbleScoring[word[i].toUpperCase()]; } return score; }; self.scoreLetter = function (l) { return scrabbleScoring[l.toUpperCase()]; }; self.capitaliseFirstLetter = function (word) { return word.charAt(0).toUpperCase() + word.slice(1); } });
import React, { Component, PropTypes } from 'react' class ScrollWrapper extends Component { state = { offset: 0 } handleScroll(e) { console.log('-------------------------------------------'); console.log('-------------------------------------------'); console.log('scroll') var doc = document.documentElement var top = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0) console.log('-------------------------------------------'); console.dir(top) this.setState({ offset: top }) } componentDidMount() { console.log('-------------------------------------------'); console.log('mounting') window.addEventListener("scroll", this.handleScroll.bind(this)) } componentWillUnmount() { window.removeEventListener("scroll", this.handleScroll.bind(this)) } render() { return ( <div> <div style={{ marginTop: (this.state.offset + 'px') }}> { this.props.children } </div> </div> ) } } export default ScrollWrapper
var log = (message) => console.log(message); export {log};
/*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ // Provides control sap.ui.commons.ListBox. sap.ui.define(['jquery.sap.global', './library', 'sap/ui/core/Control', 'sap/ui/core/delegate/ItemNavigation', 'jquery.sap.strings'], function(jQuery, library, Control, ItemNavigation/* , jQuerySap */) { "use strict"; /** * Constructor for a new ListBox. * * @param {string} [sId] ID for the new control, generated automatically if no ID is given * @param {object} [mSettings] Initial settings for the new control * * @class * Provides a list of items from which users can choose an item. * For the design of the list box, features such as defining the list box height, fixing the number of visible items, * choosing one item to be the item that is marked by default when the list box is shown, * or a scroll bar for large list boxes are available. * @extends sap.ui.core.Control * * @author SAP SE * @version 1.38.4 * * @constructor * @public * @deprecated Since version 1.38. Instead, use the <code>sap.m.List</code> control. * @alias sap.ui.commons.ListBox * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel */ var ListBox = Control.extend("sap.ui.commons.ListBox", /** @lends sap.ui.commons.ListBox.prototype */ { metadata : { library : "sap.ui.commons", properties : { /** * Determines whether the ListBox is interactive or not. * Can be used to disable interaction with mouse or keyboard. */ editable : {type : "boolean", group : "Behavior", defaultValue : true}, /** * Determines whether the ListBox is enabled or not. * Can be used to disable interaction with mouse or keyboard. * Disabled controls have another color display depending on custom settings. */ enabled : {type : "boolean", group : "Behavior", defaultValue : true}, /** * Determines whether multiple selection is allowed. */ allowMultiSelect : {type : "boolean", group : "Behavior", defaultValue : false}, /** * Control width as common CSS-size (px or % as unit, for example). */ width : {type : "sap.ui.core.CSSSize", group : "Dimension", defaultValue : null}, /** * Control height as common CSS-size (px or % as unit, for example). * The setting overrides any definitions made for the setVisibleItems() method. */ height : {type : "sap.ui.core.CSSSize", group : "Dimension", defaultValue : null}, /** * Scroll bar position from the top. * Setting the scrollTop property and calling scrollToIndex are two operations * influencing the same "physical" property, so the last call "wins". */ scrollTop : {type : "int", group : "Behavior", defaultValue : -1}, /** * Determines whether the icons of the list items shall also be displayed. * Enabling icons requires some space to be reserved for them. * Displaying icons can also influence the width and height of a single item, * which affects the overall height of the ListBox when defined in number of items. * Note that the number of icons that can be displayed in the ListBox depends on the * size of the icons themselves and of the total ListBox height. */ displayIcons : {type : "boolean", group : "Behavior", defaultValue : false}, /** * Determines whether the text values from the additionalText property (see sap.ui.core.ListItems) shall be displayed. */ displaySecondaryValues : {type : "boolean", group : "Misc", defaultValue : false}, /** * Determines the text alignment in the primary ListBox column. */ valueTextAlign : {type : "sap.ui.core.TextAlign", group : "Appearance", defaultValue : sap.ui.core.TextAlign.Begin}, /** * Determines the text alignment in the secondary ListBox text column (if available). */ secondaryValueTextAlign : {type : "sap.ui.core.TextAlign", group : "Appearance", defaultValue : sap.ui.core.TextAlign.Begin}, /** * Determines the minimum width of the ListBox. If not set, there is no minimum width. */ minWidth : {type : "sap.ui.core.CSSSize", group : "Dimension", defaultValue : null}, /** * Determines the maximum width of the ListBox. If not set, there is no maximum width. */ maxWidth : {type : "sap.ui.core.CSSSize", group : "Dimension", defaultValue : null}, /** * The ListBox height in number of items that are initially displayed without scrolling. * This setting overwrites height settings in terms of CSS size that have been made. * When the items have different heights, the height of the first item is used for all * other item height calculations. * Note that if there are one or more separators between the visible ListBox items, * the displayed items might not relate 1:1 to the initially specified number of items. * When the value is retrieved, it equals the previously set value if it was set; * otherwise, it will be the number of items completely fitting into the ListBox without * scrolling in the case the control was already rendered. * Note that if the control was not rendered, the behavior will be undefined, * it may return -1 or any other number. */ visibleItems : {type : "int", group : "Dimension", defaultValue : null} }, defaultAggregation : "items", aggregations : { /** * Aggregation of items to be displayed. Must be either of type sap.ui.core.ListItem or sap.ui.core.SeparatorItem. */ items : {type : "sap.ui.core.Item", multiple : true, singularName : "item"} }, associations : { /** * Association to controls / ids which describe this control (see WAI-ARIA attribute aria-describedby). */ ariaDescribedBy : {type : "sap.ui.core.Control", multiple : true, singularName : "ariaDescribedBy"}, /** * Association to controls / ids which label this control (see WAI-ARIA attribute aria-labelledby). */ ariaLabelledBy : {type : "sap.ui.core.Control", multiple : true, singularName : "ariaLabelledBy"} }, events : { /** * Event is fired when selection is changed by user interaction. */ select : { parameters : { /** * ID of the ListBox which triggered the event. */ id : {type : "string"}, /** * The currently selected index of the ListBox. * In the case of multiple selection, this is exactly one of the selected indices - * the one whose selection has triggered the selection change. * To get all currently selected indices, use selectedIndices. */ selectedIndex : {type : "int"}, /** * The currently selected item of the ListBox. * In the case of multiple selection, this is exactly one of the selected items - * the one whose selection has triggered the selection change. */ selectedItem : {type : "sap.ui.core.Item"}, /** * Array containing the indices which are selected. */ selectedIndices : {type : "int[]"} } } } }}); /** * Initializes the ListBox control * @private */ ListBox.prototype.init = function () { this.allowTextSelection(false); if (!this._bHeightInItems) { // otherwise setVisibleItems was already called by the JSON constructor this._bHeightInItems = false; // decides whether the height is set as CSS size (height is in height property then) or in multiples of an item height (height is in this._iVisibleItems then) this._iVisibleItems = -1; // initially -1, this subsequently must be the number of items that are visible without scrolling; the value is either set directly if the height is given in items, or calculated in onAfterRendering } this._sTotalHeight = null; // if height is set in items, this contains the if (ListBox._fItemHeight === undefined) { ListBox._fItemHeight = -1; } if (ListBox._iBordersAndStuff === undefined) { ListBox._iBordersAndStuff = -1; } this._aSelectionMap = []; this._iLastDirectlySelectedIndex = -1; //FIXME Mapping from activeItems index to the id of it for item navigation purposes this._aActiveItems = null; }; /** * Re-initializes the ListBox, so all sizes are fine after a theme switch * @private */ ListBox.prototype.onThemeChanged = function () { this._sTotalHeight = null; if (!this._bHeightInItems) { this._iVisibleItems = -1; // re-calculation only required for ItemNavigation - shouldn't change when explicitly set } this._skipStoreScrollTop = true; // Skip remembering the scrolltop in next onBeforeRendering due to theme change if (this.getDomRef()) { this.invalidate(); } }; /** * Called before rendering. Required for storing the scroll position. * @private */ ListBox.prototype.onBeforeRendering = function () { if (this._skipStoreScrollTop) { delete this._skipStoreScrollTop; return; } this.getScrollTop(); // store current ScrollTop // TODO: store focus?? }; /** * Called after rendering. Required for calculating and setting the correct heights. * @private */ ListBox.prototype.onAfterRendering = function () { var oDomRef = this.getDomRef(); // calculate item height if (ListBox._fItemHeight <= 0) { // TODO: merge with width measurement which is currently in renderer // create dummy ListBox with dummy item var oStaticArea = sap.ui.getCore().getStaticAreaRef(); var div = document.createElement("div"); div.id = "sap-ui-commons-ListBox-sizeDummy"; div.innerHTML = '<div class="sapUiLbx sapUiLbxFlexWidth sapUiLbxStd"><ul><li class="sapUiLbxI"><span class="sapUiLbxITxt">&nbsp;</span></li></ul></div>'; if (sap.ui.Device.browser.safari) { oStaticArea.insertBefore(div, oStaticArea.firstChild); } else { oStaticArea.appendChild(div); } var oItemDomRef = div.firstChild.firstChild.firstChild; ListBox._fItemHeight = oItemDomRef.offsetHeight; // subpixel rendering strategy in IE >= 9 can lead to the total being larger than the sum of heights if (!!sap.ui.Device.browser.internet_explorer && (document.documentMode == 9 || document.documentMode == 10)) { // TODO: browser version check... not good... var cs = document.defaultView.getComputedStyle(oItemDomRef.firstChild, ""); var h = parseFloat(cs.getPropertyValue("height").split("px")[0]); if (!(typeof h === "number") || !(h > 0)) { // sometimes cs.getPropertyValue("height") seems to return "auto" h = jQuery(oItemDomRef.firstChild).height(); } var pt = parseFloat(cs.getPropertyValue("padding-top").split("px")[0]); var pb = parseFloat(cs.getPropertyValue("padding-bottom").split("px")[0]); var bt = parseFloat(cs.getPropertyValue("border-top-width").split("px")[0]); var bb = parseFloat(cs.getPropertyValue("border-bottom-width").split("px")[0]); ListBox._fItemHeight = h + pt + pb + bt + bb; } // remove the dummy oStaticArea.removeChild(div); } // calculate height of ListBox borders and padding if (ListBox._iBordersAndStuff == -1) { var $DomRef = jQuery(this.getDomRef()); var outerHeight = $DomRef.outerHeight(); var innerHeight = $DomRef.height(); ListBox._iBordersAndStuff = outerHeight - innerHeight; } // Height is set in number of visible items if (this._bHeightInItems) { if (this._sTotalHeight == null) { //...but the height needs to be calculated first this._calcTotalHeight(); // TODO: verify this._sTotalHeight is > 0 // now set height oDomRef.style.height = this._sTotalHeight; } // else height was already set in the renderer! } // find out how many items are visible because the ItemNavigation needs to know if (this._iVisibleItems == -1) { this._updatePageSize(); } // Collect items for ItemNavigation TODO: make it cleaner var oFocusRef = this.getFocusDomRef(), aRows = oFocusRef.childNodes, aDomRefs = [], aItems = this.getItems(); this._aActiveItems = []; var aActiveItems = this._aActiveItems; for (var i = 0; i < aRows.length; i++) { if (!(aItems[i] instanceof sap.ui.core.SeparatorItem)) { aActiveItems[aDomRefs.length] = i; aDomRefs.push(aRows[i]); } } // init ItemNavigation if (!this.oItemNavigation) { var bNotInTabChain = (!this.getEnabled() || !this.getEditable()); this.oItemNavigation = new ItemNavigation(null, null, bNotInTabChain); this.oItemNavigation.attachEvent(ItemNavigation.Events.AfterFocus, this._handleAfterFocus, this); this.addDelegate(this.oItemNavigation); } this.oItemNavigation.setRootDomRef(oFocusRef); this.oItemNavigation.setItemDomRefs(aDomRefs); this.oItemNavigation.setCycling(false); this.oItemNavigation.setSelectedIndex(this._getNavigationIndexForRealIndex(this.getSelectedIndex())); this.oItemNavigation.setPageSize(this._iVisibleItems); // Page down by number of visible items // Apply scrollTop // if scrolling to a certain item index is currently requested (but was not done because the control was not rendered before), do it now if (this.oScrollToIndexRequest) { this.scrollToIndex(this.oScrollToIndexRequest.iIndex, this.oScrollToIndexRequest.bLazy); // keep the oScrollToIndexRequest for the timeouted call } else { var scrollTop = this.getProperty("scrollTop"); if (scrollTop > -1) { oDomRef.scrollTop = scrollTop; } } // sometimes this did not work, so repeat it after a timeout (consciously done twice, yes) var that = this; window.setTimeout(function() { // needs to be delayed because in Firefox sometimes the scrolling seems to come too early // if scrolling to a certain item index is currently requested (but was not done because the control was not rendered before), do it now if (that.oScrollToIndexRequest) { that.scrollToIndex(that.oScrollToIndexRequest.iIndex, that.oScrollToIndexRequest.bLazy); that.oScrollToIndexRequest = null; } else { var scrollTop = that.getProperty("scrollTop"); if (scrollTop > -1) { oDomRef.scrollTop = scrollTop; } } }, 0); }; /** * For the given iIndex, this method calculates the index of the respective item within the ItemNavigation set. * (if there are separators, the ItemNavigation does not know them) * Prerequisite: the iIndex points to an element which is NOT a Separator or disabled (= it must be known to the ItemNavigation) * * @param {int} iIndex real index (with separators) * @return {int} iNavIndex itemnavigation index (without separators) * @private */ ListBox.prototype._getNavigationIndexForRealIndex = function(iIndex) { var aItems = this.getItems(); var iNavIndex = iIndex; for (var i = 0; i < iIndex; i++) { if (aItems[i] instanceof sap.ui.core.SeparatorItem) { iNavIndex--; } } return iNavIndex; }; /** * Calculates the number of visible items. * Must happen after rendering and whenever the height is changed without rerendering. * @private */ ListBox.prototype._updatePageSize = function() { var oDomRef = this.getDomRef(); if (oDomRef) { if (ListBox._fItemHeight > 0) { this._iVisibleItems = Math.floor(oDomRef.clientHeight / ListBox._fItemHeight); } // else shouldn't happen } // else: nothing to do, item navigation will be initialized after rendering }; /** * If the ListBox has a scroll bar because the number of items is larger than the number of visible items, * this method scrolls to the item with the given index. * If there are enough items, this item will then appear at the topmost visible position in the ListBox. * If bLazy is true, it only scrolls as far as required to make the item visible. * Setting the scrollTop property and calling scrollToIndex are two operations * influencing the same "physical" property, so the last call "wins". * * @param {int} iIndex The index to which the ListBox should scroll. * @param {boolean} bLazy * If set to true, the ListBox only scrolls if the item is not completely visible, and it scrolls for exactly the space to make it fully visible. If set to false, the item is scrolled to the top position (if possible). * @return {sap.ui.commons.ListBox} <code>this</code> to allow method chaining. * @public */ ListBox.prototype.scrollToIndex = function(iIndex, bLazy) { var oDomRef = this.getDomRef(); if (oDomRef) { // only if already rendered var oItem = this.$("list").children("li[data-sap-ui-lbx-index=" + iIndex + "]"); oItem = oItem.get(0); if (oItem) { var iScrollTop = oItem.offsetTop; if (!bLazy) { // scroll there without any conditions this.setScrollTop(iScrollTop); } else { // "lazy" means we should only scroll if required and as far as required var iCurrentScrollTop = oDomRef.scrollTop; var iViewPortHeight = jQuery(oDomRef).height(); if (iCurrentScrollTop >= iScrollTop) { // if we have to scroll up, the behavior is fine already this.setScrollTop(iScrollTop); } else if ((iScrollTop + ListBox._fItemHeight) > (iCurrentScrollTop + iViewPortHeight)) { // bottom Edge of item > bottom edge of viewport // the item is - at least partly - below the current viewport of the ListBox, so scroll down. But only as far as required this.setScrollTop(Math.ceil(iScrollTop + ListBox._fItemHeight - iViewPortHeight)); // round because of _fItemHeight } // else if the item is already fully visible, do nothing } } // store the actual position this.getScrollTop(); } else { // control not yet rendered, thus item height is unknown, so remember request for after rendering this.oScrollToIndexRequest = {iIndex:iIndex,bLazy:bLazy}; } return this; }; /** * Returns the number of visible items. * @return {int} Number of visible items. * @public */ ListBox.prototype.getVisibleItems = function() { return this._iVisibleItems; }; /** * Makes the ListBox render with a height that allows it to display exactly the given number of items. * * @param {int} iItemCount The number of items that should fit into the ListBox without scrolling. * @return {sap.ui.commons.ListBox} <code>this</code> to allow method chaining. * @public */ ListBox.prototype.setVisibleItems = function(iItemCount) { /* *For the calculation, the size of the first item is used; if no item is present, an invisible dummy item * is rendered and instantly removed again. * Therefore, this method will not work for items with different heights and if actual items have a different * size than generic empty dummy items. */ // TODO: prevent values less than 1, or make them go back to CSS heights this.setProperty("visibleItems", iItemCount, true); this._iVisibleItems = iItemCount; if (iItemCount < 0) { this._bHeightInItems = false; } else { this._bHeightInItems = true; } // the actual height to set must be calculated now or later this._sTotalHeight = null; // if already rendered, calculate and set the height var oDomRef = this.getDomRef(); if (oDomRef) { if (this._bHeightInItems) { var oFirstItem = oDomRef.firstChild ? oDomRef.firstChild.firstChild : null; if (oFirstItem || ((ListBox._fItemHeight > 0) && (ListBox._iBordersAndStuff > 0))) { oDomRef.style.height = this._calcTotalHeight(); } else { // already rendered, but no dummy item! this.invalidate(); } } else { oDomRef.style.height = this.getHeight(); this._updatePageSize(); if (this.oItemNavigation) { this.oItemNavigation.setPageSize(this._iVisibleItems); // Page down by number of visible items } } } //if (this._sTotalHeight == null) { // this is the "else" clause covering all cases where the height was not set above // called before rendering, so the calculation and setting of the actual CSS height to set must be done later //} return this; }; /** * Calculates the outer height of the ListBox from the known item height and number of items that should fit. * The result (a CSS size string) is returned as well as assigned to this._sTotalHeight. * Precondition: the control is rendered, this._iVisibleItems, sap.ui.commons.ListBox._iBordersAndStuff and * sap.ui.commons.ListBox._fItemHeight are initialized. * * @returns {string} the required outer height as CSS size * @private */ ListBox.prototype._calcTotalHeight = function() { // TODO: check preconditions var desiredHeight = this._iVisibleItems * ListBox._fItemHeight; this._sTotalHeight = (desiredHeight + ListBox._iBordersAndStuff) + "px"; return this._sTotalHeight; }; /** * Sets the height of this ListBox in CSS units. * * @param {sap.ui.core.CSSSize} sHeight New height for the ListBox. * @return {sap.ui.commons.ListBox} <code>this</code> to allow method chaining. * @public */ ListBox.prototype.setHeight = function(sHeight) { this.validateProperty("height", sHeight); if (this.getHeight() === sHeight) { return this; } this._bHeightInItems = false; this._iVisibleItems = -1; var oDomRef = this.getDomRef(); if (oDomRef) { oDomRef.style.height = sHeight; this._updatePageSize(); if (this.oItemNavigation) { this.oItemNavigation.setPageSize(this._iVisibleItems); // Page down by number of visible items } } return this.setProperty("height", sHeight, true); // no re-rendering }; /** * Sets the width of this ListBox in CSS units. * * @param {sap.ui.core.CSSSize} sWidth New width for the ListBox. * @return {sap.ui.commons.ListBox} <code>this</code> to allow method chaining. * @public */ ListBox.prototype.setWidth = function(sWidth) { var oDomRef = this.getDomRef(); if (oDomRef) { oDomRef.style.width = sWidth; } this.setProperty("width", sWidth, true); // no re-rendering return this; }; /** * Positions the ListBox contents so that they are scrolled-down by the given number of pixels. * * @param {int} iScrollTop Vertical scroll position in pixels. * @return {sap.ui.commons.ListBox} <code>this</code> to allow method chaining. * @public */ ListBox.prototype.setScrollTop = function (iScrollTop) { iScrollTop = Math.round(iScrollTop); var scrollDomRef = this.getDomRef(); this.oScrollToIndexRequest = null; // delete any pending scroll request if (scrollDomRef) { scrollDomRef.scrollTop = iScrollTop; } this.setProperty("scrollTop", iScrollTop, true); // no rerendering return this; }; /** * Returns how many pixels the ListBox contents are currently scrolled down. * * @return {int} Vertical scroll position. * @public */ ListBox.prototype.getScrollTop = function () { var scrollDomRef = this.getDomRef(); if (scrollDomRef) { var scrollTop = Math.round(scrollDomRef.scrollTop); this.setProperty("scrollTop", scrollTop, true); return scrollTop; } else { return this.getProperty("scrollTop"); } }; /* --- user interaction handling methods --- */ ListBox.prototype.onmousedown = function(oEvent) { if (!!sap.ui.Device.browser.webkit && oEvent.target && oEvent.target.id === this.getId()) { // ListBox scrollbar has been clicked; webkit completely removes the focus, which breaks autoclose popups var idToFocus = document.activeElement ? document.activeElement.id : this.getId(); var that = this; window.setTimeout(function(){ var scrollPos = that.getDomRef().scrollTop; // yes, this scrollPosition is the right one to use. The one before setTimeout works for the scrollbar grip, but not for the arrows jQuery.sap.focus(jQuery.sap.domById(idToFocus)); // re-set the focus that.getDomRef().scrollTop = scrollPos; // re-apply the scroll position (otherwise the focus() call would scroll the focused element into view) },0); } }; ListBox.prototype.onclick = function (oEvent) { this._handleUserActivation(oEvent); }; ListBox.prototype.onsapspace = function (oEvent) { this._handleUserActivation(oEvent); }; /* * Ensure the sapspace event with modifiers is also handled as well as the respective "enter" events */ ListBox.prototype.onsapspacemodifiers = ListBox.prototype.onsapspace; ListBox.prototype.onsapenter = ListBox.prototype.onsapspace; ListBox.prototype.onsapentermodifiers = ListBox.prototype.onsapspace; /** * Internal method invoked when the user activates an item. * Differentiates and dispatches according to modifier key and current selection. * @param {jQuery.Event} oEvent jQuery Event * @private */ ListBox.prototype._handleUserActivation = function (oEvent) { if (!this.getEnabled() || !this.getEditable()) { return; } var oSource = oEvent.target; if (oSource.id === "" || jQuery.sap.endsWith(oSource.id, "-txt")) { oSource = oSource.parentNode; if (oSource.id === "") { // could be the image inside the first cell oSource = oSource.parentNode; } } var attr = jQuery(oSource).attr("data-sap-ui-lbx-index"); if (typeof attr == "string" && attr.length > 0) { var iIndex = parseInt(attr, 10); // Get the selected index from the HTML var aItems = this.getItems(); var oItem = aItems[iIndex]; // oItem could be a separator, though! // It could be the case that the list of items changed during the click event handling. Ensure the item is still the one in if (aItems.length <= iIndex) { // TODO: very questionable! Why set the index to the last position? And why allow removing items during the processing? Remove! iIndex = aItems.length - 1; } if (iIndex >= 0 && iIndex < aItems.length) { // TODO: this should be known by now if (oItem.getEnabled() && !(oItem instanceof sap.ui.core.SeparatorItem)) { // Take care of selection and select event if (oEvent.ctrlKey || oEvent.metaKey) { // = CTRL this._handleUserActivationCtrl(iIndex, oItem); } else if (oEvent.shiftKey) { this.setSelectedIndices(this._getUserSelectionRange(iIndex)); this.fireSelect({ id:this.getId(), selectedIndex:iIndex, selectedIndices:this.getSelectedIndices(), /* NEW (do not use hungarian prefixes!) */ selectedItem:oItem, sId:this.getId(), aSelectedIndices:this.getSelectedIndices() /* OLD */ }); this._iLastDirectlySelectedIndex = iIndex; } else { this._handleUserActivationPlain(iIndex, oItem); } } } oEvent.preventDefault(); oEvent.stopPropagation(); } }; /** * Called when the user triggers an item without holding a modifier key. * Changes the selection in the expected way. * * @param {int} iIndex index that should be selected * @param {sap.ui.core.Item} oItem item that should be selected * @private */ ListBox.prototype._handleUserActivationPlain = function (iIndex, oItem) { this._iLastDirectlySelectedIndex = iIndex; this.oItemNavigation.setSelectedIndex(this._getNavigationIndexForRealIndex(iIndex)); if (this.getSelectedIndex() != iIndex || this.getSelectedIndices().length > 1) { this.setSelectedIndex(iIndex); // Replace selection this.fireSelect({ id:this.getId(), selectedIndex:iIndex, selectedIndices:this.getSelectedIndices(), /* NEW (do not use hungarian prefixes!) */ selectedItem:oItem, sId:this.getId(), aSelectedIndices:this.getSelectedIndices() /* OLD */ }); } }; /** * Called when the user triggers an item while pressing the Ctrl key. * Changes the selection in the expected way for the "Ctrl" case. * * @param {int} iIndex index that should be selected * @param {sap.ui.core.Item} oItem item that should be selected * @private */ ListBox.prototype._handleUserActivationCtrl = function (iIndex, oItem) { this._iLastDirectlySelectedIndex = iIndex; this.oItemNavigation.setSelectedIndex(this._getNavigationIndexForRealIndex(iIndex)); if (this.isIndexSelected(iIndex)) { this.removeSelectedIndex(iIndex); // Remove from multi-selection } else { this.addSelectedIndex(iIndex); // Add to multi-selection } this.fireSelect({ id:this.getId(), selectedIndex:iIndex, selectedIndices:this.getSelectedIndices(), /* NEW (do not use hungarian prefixes!) */ selectedItem:oItem, sId:this.getId(), aSelectedIndices:this.getSelectedIndices() /* OLD */ }); }; /** * Calculates the list of indices ranging from the previously selected item to the * given index. Used internally for calculating the new selection range when the user holds the "shift" key * while clicking in the ListBox. * * @param {int} iIndex index of selection end * @returns {int[]} Indices of user selection range * @private */ ListBox.prototype._getUserSelectionRange = function (iIndex) { if (this._iLastDirectlySelectedIndex == -1) { // TODO: Use focus and continue execution return []; } var aItems = this.getItems(); var aRange = []; var i; if (this._iLastDirectlySelectedIndex <= iIndex) { for (i = this._iLastDirectlySelectedIndex; i <= iIndex; i++) { if ((i > -1) && (aItems[i].getEnabled() && !(aItems[i] instanceof sap.ui.core.SeparatorItem))) { aRange.push(i); } } } else { for (i = iIndex; i <= this._iLastDirectlySelectedIndex; i++) { if ((i > -1) && (aItems[i].getEnabled() && !(aItems[i] instanceof sap.ui.core.SeparatorItem))) { aRange.push(i); } } } return aRange; }; /* --- Overwritten setters and getters affecting the selection --- */ /** * Zero-based index of selected item. Index value for no selection is -1. * When multiple selection is enabled and multiple items are selected, * the method returns the first selected item. * * @return {int} Selected index * @public */ ListBox.prototype.getSelectedIndex = function() { for (var i = 0; i < this._aSelectionMap.length; i++) { if (this._aSelectionMap[i]) { return i; } } return -1; }; /** * Sets the zero-based index of the currently selected item. *This method removes any previous selections. When the given index is invalid, the call is ignored. * * @param {int} iSelectedIndex Index to be selected. * @return {sap.ui.commons.ListBox} <code>this</code> to allow method chaining. * @public */ ListBox.prototype.setSelectedIndex = function(iSelectedIndex) { if ((iSelectedIndex < -1) || (iSelectedIndex > this._aSelectionMap.length - 1)) { return this; } // Invalid index // do not select a disabled or separator item var aItems = this.getItems(); if ((iSelectedIndex > -1) && (!aItems[iSelectedIndex].getEnabled() || (aItems[iSelectedIndex] instanceof sap.ui.core.SeparatorItem))) { return this; } for (var i = 0; i < this._aSelectionMap.length; i++) { this._aSelectionMap[i] = false; } this._aSelectionMap[iSelectedIndex] = true; // And inform the itemNavigation about this, too if (this.oItemNavigation) { this.oItemNavigation.setSelectedIndex(this._getNavigationIndexForRealIndex(iSelectedIndex)); } this.getRenderer().handleSelectionChanged(this); return this; }; /** * Adds the given index to current selection. * When multiple selection is disabled, this replaces the current selection. * When the given index is invalid, the call is ignored. * * @param {int} iSelectedIndex Index to add to selection.. * @return {sap.ui.commons.ListBox} <code>this</code> to allow method chaining. * @public */ ListBox.prototype.addSelectedIndex = function(iSelectedIndex) { if (!this.getAllowMultiSelect()) { // If multi-selection is not allowed, this call equals setSelectedIndex this.setSelectedIndex(iSelectedIndex); } // Multi-selectable case if ((iSelectedIndex < -1) || (iSelectedIndex > this._aSelectionMap.length - 1)) { return this; } // Invalid index // do not select a disabled or separator item var aItems = this.getItems(); if ((iSelectedIndex > -1) && (!aItems[iSelectedIndex].getEnabled() || (aItems[iSelectedIndex] instanceof sap.ui.core.SeparatorItem))) { return this; } if (this._aSelectionMap[iSelectedIndex]) { return this; } // Selection does not change // Was not selected before this._aSelectionMap[iSelectedIndex] = true; this.getRenderer().handleSelectionChanged(this); return this; }; /** * Removes the given index from this selection. When the index is invalid or not selected, the call is ignored. * * @param {int} iIndex Index that shall be removed from selection. * @return {sap.ui.commons.ListBox} <code>this</code> to allow method chaining. * @public */ ListBox.prototype.removeSelectedIndex = function(iIndex) { if ((iIndex < 0) || (iIndex > this._aSelectionMap.length - 1)) { return this; } // Invalid index if (!this._aSelectionMap[iIndex]) { return this; } // Selection does not change // Was selected before this._aSelectionMap[iIndex] = false; this.getRenderer().handleSelectionChanged(this); return this; }; /** * Removes complete selection. * * @return {sap.ui.commons.ListBox} <code>this</code> to allow method chaining. * @public */ ListBox.prototype.clearSelection = function() { for (var i = 0; i < this._aSelectionMap.length; i++) { if (this._aSelectionMap[i]) { this._aSelectionMap[i] = false; } } // More or less re-initialized this._iLastDirectlySelectedIndex = -1; // Reset the index also in ItemNavigation if (this.oItemNavigation) { this.oItemNavigation.setSelectedIndex( -1); } this.getRenderer().handleSelectionChanged(this); return this; }; /** * Zero-based indices of selected items, wrapped in an array. An empty array means "no selection". * * @return {int[]} Array of selected indices. * @public */ ListBox.prototype.getSelectedIndices = function() { var aResult = []; for (var i = 0; i < this._aSelectionMap.length; i++) { if (this._aSelectionMap[i]) { aResult.push(i); } } return aResult; }; /** * Zero-based indices of selected items, wrapped in an array. An empty array means "no selection". * When multiple selection is disabled and multiple items are given, * the selection is set to the index of the first valid index in the given array. * Any invalid indices are ignored. * The previous selection is in any case replaced. * * @param {int[]} aSelectedIndices Indices of the items to be selected. * @return {sap.ui.commons.ListBox} <code>this</code> to allow method chaining. * @public */ ListBox.prototype.setSelectedIndices = function(aSelectedIndices) { var indicesToSet = []; var aItems = this.getItems(); var i; for (i = 0; i < aSelectedIndices.length; i++) { if ((aSelectedIndices[i] > -1) && (aSelectedIndices[i] < this._aSelectionMap.length)) { if (aItems[aSelectedIndices[i]].getEnabled() && !(aItems[aSelectedIndices[i]] instanceof sap.ui.core.SeparatorItem)) { indicesToSet.push(aSelectedIndices[i]); } } } if (indicesToSet.length > 0) { // TODO: Disable event listening to items?? // With multi-selection disabled, use the first valid index only if (!this.getAllowMultiSelect()) { indicesToSet = [indicesToSet[0]]; } } for (i = 0; i < this._aSelectionMap.length; i++) { this._aSelectionMap[i] = false; } // O(n+m) for (i = 0; i < indicesToSet.length; i++) { this._aSelectionMap[indicesToSet[i]] = true; } this.getRenderer().handleSelectionChanged(this); return this; }; /** * Adds the given indices to selection. Any invalid indices are ignored. * * @param {int[]} aSelectedIndices Indices of the items that shall additionally be selected. * @return {sap.ui.commons.ListBox} <code>this</code> to allow method chaining. * @public */ ListBox.prototype.addSelectedIndices = function(aSelectedIndices) { var indicesToSet = []; var aItems = this.getItems(); var i; for (i = 0; i < aSelectedIndices.length; i++) { if ((aSelectedIndices[i] > -1) && (aSelectedIndices[i] < this._aSelectionMap.length)) { // do not select a disabled or separator item if (aItems[aSelectedIndices[i]].getEnabled() && !(aItems[aSelectedIndices[i]] instanceof sap.ui.core.SeparatorItem)) { indicesToSet.push(aSelectedIndices[i]); } } } if (indicesToSet.length > 0) { // TODO: Disable event listening to items?? // With multi-selection disabled, use the first valid index only if (!this.getAllowMultiSelect()) { indicesToSet = [indicesToSet[0]]; } // O(n+m) for (i = 0; i < indicesToSet.length; i++) { this._aSelectionMap[indicesToSet[i]] = true; } this.getRenderer().handleSelectionChanged(this); } return this; }; /** * Returns whether the given index is selected. * * @param {int} iIndex Index which is checked for selection state. * @return {boolean} Whether index is selected. * @public */ ListBox.prototype.isIndexSelected = function(iIndex) { if ((iIndex < -1) || (iIndex > this._aSelectionMap.length - 1)) { return false; // Invalid index -> not selected } return this._aSelectionMap[iIndex]; }; /** * Keys of the items to be selected, wrapped in an array. An empty array means no selection. * When multiple selection is disabled, and multiple keys are given, * the selection is set to the item with the first valid key in the given array. * Any invalid keys are ignored. * The previous selection is replaced in any case. * * @param {string[]} aSelectedKeys The keys of the items to be selected. * @return {sap.ui.commons.ListBox} <code>this</code> to allow method chaining. * @public */ ListBox.prototype.setSelectedKeys = function(aSelectedKeys) { var aItems = this.getItems(); var mKeyMap = {}; for (var i = 0; i < aSelectedKeys.length; i++) { // put the keys into a map to hopefully search faster below mKeyMap[aSelectedKeys[i]] = true; } var aIndices = []; for (var j = 0; j < aItems.length; j++) { if (mKeyMap[aItems[j].getKey()]) { aIndices.push(j); } } return this.setSelectedIndices(aIndices); }; /** * Returns the keys of the selected items in an array. * If a selected item does not have a key, the respective array entry will be undefined. * * @return {string[]} Array with selected keys. * @public */ ListBox.prototype.getSelectedKeys = function() { var aItems = this.getItems(); var aResult = []; for (var i = 0; i < this._aSelectionMap.length; i++) { if (this._aSelectionMap[i]) { aResult.push(aItems[i].getKey()); } } return aResult; }; /** * Returns selected item. When no item is selected, "null" is returned. * When multi-selection is enabled and multiple items are selected, only the first selected item is returned. * * @return {sap.ui.core.Item} Selected item * @public */ ListBox.prototype.getSelectedItem = function() { var iIndex = this.getSelectedIndex(); if ((iIndex < 0) || (iIndex >= this._aSelectionMap.length)) { return null; } return this.getItems()[iIndex]; }; /** * Returns an array containing the selected items. In the case of no selection, an empty array is returned. * * @return {sap.ui.core.Item[]} Selected items. * @public */ ListBox.prototype.getSelectedItems = function() { var aItems = this.getItems(); var aResult = []; for (var i = 0; i < this._aSelectionMap.length; i++) { if (this._aSelectionMap[i]) { aResult.push(aItems[i]); } } return aResult; }; ListBox.prototype.setAllowMultiSelect = function(bAllowMultiSelect) { this.setProperty("allowMultiSelect", bAllowMultiSelect); var oneWasSelected = false; var twoWereSelected = false; if (!bAllowMultiSelect && this._aSelectionMap) { for (var i = 0; i < this._aSelectionMap.length; i++) { if (this._aSelectionMap[i]) { if (!oneWasSelected) { oneWasSelected = true; } else { this._aSelectionMap[i] = false; twoWereSelected = true; } } } } if (twoWereSelected) { this.getRenderer().handleSelectionChanged(this); } return this; }; /** * Handles the event that gets fired by the {@link sap.ui.core.delegate.ItemNavigation} delegate. * * @param {sap.ui.base.Event} oControlEvent The event that gets fired by the {@link sap.ui.core.delegate.ItemNavigation} delegate. * @private */ ListBox.prototype._handleAfterFocus = function(oControlEvent) { var iIndex = oControlEvent.getParameter("index"); iIndex = ((iIndex !== undefined && iIndex >= 0) ? this._aActiveItems[iIndex] : 0); this.getRenderer().handleARIAActivedescendant(this, iIndex); }; /* --- "items" aggregation methods, overwritten to update _aSelectionMap and allow filteredItems --- */ /* * Implementation of API method setItems. * Semantically belonging to "items" aggregation but not part of generated method set. * @param bNoItemsChanged not in official API, only needed in DropdownBox TypeAhead */ /** * Allows setting the list items as array for this instance of ListBox. * * @param {sap.ui.core.ListItem[]} aItems The items to set for this ListBox. * @param {boolean} bDestroyItems Optional boolean parameter to indicate that the formerly set items should be destroyed, instead of just removed. * @return {sap.ui.commons.ListBox} <code>this</code> to allow method chaining. * @public */ ListBox.prototype.setItems = function(aItems, bDestroyItems, bNoItemsChanged) { this._bNoItemsChangeEvent = true; if (bDestroyItems) { this.destroyItems(); } else { this.removeAllItems(); } for (var i = 0, l = aItems.length; i < l; i++) { this.addItem(aItems[i]); } this._bNoItemsChangeEvent = undefined; if (!bNoItemsChanged) { this.fireEvent("itemsChanged", {event: "setItems", items: aItems}); //private event used in DropdownBox } return this; }; ListBox.prototype.addItem = function(oItem) { this._bNoItemInvalidateEvent = true; this.addAggregation("items", oItem); this._bNoItemInvalidateEvent = false; if ( !this._aSelectionMap ) { this._aSelectionMap = []; } this._aSelectionMap.push(false); if (!this._bNoItemsChangeEvent) { this.fireEvent("itemsChanged", {event: "addItem", item: oItem}); //private event used in DropdownBox } oItem.attachEvent("_change", this._handleItemChanged, this); return this; }; ListBox.prototype.insertItem = function(oItem, iIndex) { if ((iIndex < 0) || (iIndex > this._aSelectionMap.length)) { return this; } // Ignore invalid index TODO:: check behavior for iIndex=length // TODO: Negative indices might be used to count from end of array this._bNoItemInvalidateEvent = true; this.insertAggregation("items", oItem, iIndex); this._bNoItemInvalidateEvent = false; this._aSelectionMap.splice(iIndex, 0, false); this.invalidate(); if (!this._bNoItemsChangeEvent) { this.fireEvent("itemsChanged", {event: "insertItems", item: oItem, index: iIndex}); //private event used in DropdownBox } oItem.attachEvent("_change", this._handleItemChanged, this); return this; }; ListBox.prototype.removeItem = function(vElement) { var iIndex = vElement; if (typeof (vElement) == "string") { // ID of the element is given vElement = sap.ui.getCore().byId(vElement); } if (typeof (vElement) == "object") { // the element itself is given or has just been retrieved iIndex = this.indexOfItem(vElement); } if ((iIndex < 0) || (iIndex > this._aSelectionMap.length - 1)) { if (!this._bNoItemsChangeEvent) { this.fireEvent("itemsChanged", {event: "removeItem", item: vElement}); //private event used in DropdownBox } return undefined; } // Ignore invalid index this._bNoItemInvalidateEvent = true; var oRemoved = this.removeAggregation("items", iIndex); this._bNoItemInvalidateEvent = false; this._aSelectionMap.splice(iIndex, 1); this.invalidate(); if (!this._bNoItemsChangeEvent) { this.fireEvent("itemsChanged", {event: "removeItem", item: oRemoved}); //private event used in DropdownBox } oRemoved.detachEvent("_change", this._handleItemChanged, this); return oRemoved; }; ListBox.prototype.removeAllItems = function() { this._bNoItemInvalidateEvent = true; var oRemoved = this.removeAllAggregation("items"); this._bNoItemInvalidateEvent = false; this._aSelectionMap = []; this.invalidate(); if (!this._bNoItemsChangeEvent) { this.fireEvent("itemsChanged", {event: "removeAllItems"}); //private event used in DropdownBox } for ( var i = 0; i < oRemoved.length; i++) { oRemoved[i].detachEvent("_change", this._handleItemChanged, this); } return oRemoved; }; ListBox.prototype.destroyItems = function() { var aItems = this.getItems(); for ( var i = 0; i < aItems.length; i++) { aItems[i].detachEvent("_change", this._handleItemChanged, this); } this._bNoItemInvalidateEvent = true; var destroyed = this.destroyAggregation("items"); this._bNoItemInvalidateEvent = false; this._aSelectionMap = []; this.invalidate(); if (!this._bNoItemsChangeEvent) { this.fireEvent("itemsChanged", {event: "destroyItems"}); //private event used in DropdownBox } return destroyed; }; ListBox.prototype.updateItems = function(){ this._bNoItemsChangeEvent = true; // is cleared in _itemsChangedAfterUpdateafter all changes are done // only new and removed items will be updated here. // If items are "reused" they only change their properies this.updateAggregation("items"); this._bNoItemInvalidateEvent = true; // fire change event asynchrounusly to be sure all binding update is done if (!this._bItemsChangedAfterUpdate) { this._bItemsChangedAfterUpdate = jQuery.sap.delayedCall(0, this, "_itemsChangedAfterUpdate"); } }; ListBox.prototype._itemsChangedAfterUpdate = function(){ this._bNoItemsChangeEvent = undefined; this._bItemsChangedAfterUpdate = undefined; this._bNoItemInvalidateEvent = undefined; this.fireEvent("itemsChanged", {event: "updateItems"}); //private event used in DropdownBox }; /** * Does all the cleanup when the ListBox is to be destroyed. * Called from the element's destroy() method. * @private */ ListBox.prototype.exit = function (){ if (this.oItemNavigation) { this.removeDelegate(this.oItemNavigation); this.oItemNavigation.destroy(); delete this.oItemNavigation; } if (this._bItemsChangedAfterUpdate) { jQuery.sap.clearDelayedCall(this._bItemsChangedAfterUpdate); this._bItemsChangedAfterUpdate = undefined; this._bNoItemsChangeEvent = undefined; this._bNoItemInvalidateEvent = undefined; } // No super.exit() to call }; /* * Overrides getFocusDomRef of base element class. * @public */ ListBox.prototype.getFocusDomRef = function() { return this.getDomRef("list"); }; /* * Overwrites default implementation * the label must point to the UL element * @public */ ListBox.prototype.getIdForLabel = function () { return this.getId() + '-list'; }; /* * inform ComboBox if an item has changed */ ListBox.prototype._handleItemChanged = function(oEvent) { if (!this._bNoItemInvalidateEvent) { this.fireEvent("itemInvalidated", {item: oEvent.oSource}); //private event used in ComboBox } }; return ListBox; }, /* bExport= */ true);
(function(){ 'use strict'; angular.module('gantt.progress', ['gantt', 'gantt.progress.templates']).directive('ganttProgress', ['moment', '$compile', '$document', function(moment, $compile, $document) { return { restrict: 'E', require: '^gantt', scope: { enabled: '=?' }, link: function(scope, element, attrs, ganttCtrl) { var api = ganttCtrl.gantt.api; // Load options from global options attribute. if (scope.options && typeof(scope.options.progress) === 'object') { for (var option in scope.options.progress) { scope[option] = scope.options.progress[option]; } } if (scope.enabled === undefined) { scope.enabled = true; } api.directives.on.new(scope, function(directiveName, taskScope, taskElement) { if (directiveName === 'ganttTaskBackground') { var progressScope = taskScope.$new(); progressScope.pluginScope = scope; var ifElement = $document[0].createElement('div'); angular.element(ifElement).attr('data-ng-if', 'task.model.progress !== undefined && pluginScope.enabled'); var progressElement = $document[0].createElement('gantt-task-progress'); if (attrs.templateUrl !== undefined) { angular.element(progressElement).attr('data-template-url', attrs.templateUrl); } if (attrs.template !== undefined) { angular.element(progressElement).attr('data-template', attrs.template); } angular.element(ifElement).append(progressElement); taskElement.append($compile(ifElement)(progressScope)); } }); api.tasks.on.clean(scope, function(model) { if (model.est !== undefined && !moment.isMoment(model.est)) { model.est = moment(model.est); //Earliest Start Time } if (model.lct !== undefined && !moment.isMoment(model.lct)) { model.lct = moment(model.lct); //Latest Completion Time } }); } }; }]); }());
var request = require('request'); var baby = require('babyparse'); function getMonthFormatted(date) { var month = date.getMonth() + 1; return month < 10 ? '0' + month : '' + month; // ('' + month) for string result } function getYearFormatted(date) { var month = date.getFullYear(); return '' + month; // ('' + month) for string result } exports.iinetDateFormat = function(date) { return getYearFormatted(date) + getMonthFormatted(date) } exports.logon = function(username, password, callback) { return request.post({ headers: { 'content-type': 'application/x-www-form-urlencoded' }, url: 'https://toolbox3.iinet.net.au/login', body: "ReturnUrl=%2F&Username=" + encodeURIComponent(username) + "&Password=" + encodeURIComponent(password) + "&action%3AIndex=", }, function(error, response, body) { if (!error) { callback(null, { 'volumeUsageByMonthCSV': function(task, date, c2) { var myCookie = request.cookie(response.headers['set-cookie'][0]); var cookieJar = request.jar(); cookieJar.setCookie(myCookie, 'https://toolbox3.iinet.net.au/login'); request.post({ headers: { 'content-type': 'application/x-www-form-urlencoded' }, jar: cookieJar, url: 'https://toolbox3.iinet.net.au/broadband/volumeusage/' + task + '/dailycsv', body: "month=" + exports.iinetDateFormat(date) + "&downloadId=daily-csv" }, function(e, r, b) { if (e) c2(e) else c2(null, b); }); }, 'volumeUsageByMonth' : function(task,date,c2) { this.volumeUsageByMonthCSV(task,date, function(err,csv) { if(err) { c2(err) } else { c2(null,baby.parse(csv)) } }) } , 'logout': function(c2) { var myCookie = request.cookie(response.headers['set-cookie'][0]); var cookieJar = request.jar(); cookieJar.setCookie(myCookie, 'https://toolbox3.iinet.net.au/login'); request.get({ jar: cookieJar, url: 'https://toolbox3.iinet.net.au/logout', }, function(e, r, b) { c2(e) }); } } ) } else { callback(error) } } ); } //exports.ParseVolumeUsage = function(string) {}
/* This Source Code Form is subject to the terms of the MIT license * If a copy of the MIT license was not distributed with this file, you can * obtain one at https://raw.github.com/mozilla/butter/master/LICENSE */ (function() { define( [ "core/logger", "core/eventmanager", "core/track", "core/popcorn-wrapper", "util/uri", "util/mediatypes", "analytics" ], function( Logger, EventManager, Track, PopcornWrapper, URI, MediaTypes, analytics ) { var __guid = 0; var Media = function ( mediaOptions ) { mediaOptions = mediaOptions || {}; EventManager.extend( this ); var _tracks = [], _orderedTracks = [], _id = "Media" + __guid++, _logger = new Logger( _id ), _name = mediaOptions.name || _id, _url = mediaOptions.url, _ready = false, _target = mediaOptions.target, _registry, _currentTime = 0, _duration = mediaOptions.duration || -1, _popcornOptions = mediaOptions.popcornOptions, _mediaUpdateInterval, _clipData = {}, _this = this, _popcornWrapper; function mediaReady() { _this.duration = _popcornWrapper.duration; _ready = true; for( var i = 0, l = _tracks.length; i < l; i++ ) { _tracks[ i ].updateTrackEvents(); } // If the target element has a `data-butter-media-controls` property, // set the `controls` attribute on the corresponding media element. var targetElement = document.getElementById( _target ); if ( targetElement && targetElement.getAttribute( "data-butter-media-controls" ) ) { _popcornWrapper.popcorn.controls( true ); } _this.dispatch( "mediaready" ); } _popcornWrapper = new PopcornWrapper( _id, { popcornEvents: { muted: function(){ _this.dispatch( "mediamuted", _this ); }, unmuted: function(){ _this.dispatch( "mediaunmuted", _this ); }, volumechange: function(){ _this.dispatch( "mediavolumechange", _popcornWrapper.volume ); }, timeupdate: function(){ _currentTime = _popcornWrapper.currentTime; _this.dispatch( "mediatimeupdate", _this ); }, pause: function(){ clearInterval( _mediaUpdateInterval ); _this.dispatch( "mediapause" ); }, play: function(){ _mediaUpdateInterval = setInterval( function(){ _currentTime = _popcornWrapper.currentTime; }, 10 ); _this.dispatch( "mediaplay" ); }, ended: function(){ analytics.event( "Media Ended", { nonInteraction: true, label: "Editor" }); _this.dispatch( "mediaended" ); }, seeked: function(){ _this.dispatch( "mediaseeked" ); } }, prepare: mediaReady, timeout: function(){ _this.dispatch( "mediatimeout" ); }, fail: function(){ _this.dispatch( "mediafailed", "error" ); }, setup: { target: _target, url: _url }, makeVideoURLsUnique: mediaOptions.makeVideoURLsUnique }); this.popcornCallbacks = null; this.popcornScripts = null; this.maxPluginZIndex = 0; this.clear = function(){ for ( var i = _tracks.length - 1; i >= 0; i-- ) { _this.removeTrack( _tracks[ i ] ); } }; function ensureNewTrackIsTrack( track ) { if ( !( track instanceof Track ) ) { track = new Track( track ); } return track; } function setupNewTrack( track ) { track._media = _this; _tracks.push( track ); _this.chain( track, [ "tracktargetchanged", "tracknamechanged", "trackeventadded", "trackeventeditorclose", "trackeventremoved", "trackeventupdated", "trackeventselected", "trackeventdeselected" ]); track.setPopcornWrapper( _popcornWrapper ); } function addNewTrackTrackEvents( track ) { var trackEvents = track.trackEvents; if ( trackEvents.length > 0 ) { for ( var i=0, l=trackEvents.length; i<l; ++i ) { track.dispatch( "trackeventadded", trackEvents[ i ] ); } } } this.addTrack = function ( track, forceFirst ) { if ( forceFirst && _orderedTracks[ 0 ] ) { return _this.insertTrackBefore( _orderedTracks[ 0 ] ); } track = ensureNewTrackIsTrack( track ); if ( track._media ) { throw "Track already belongs to a Media object. Use `media.removeTrack` prior to this function."; } // Give new track last order since it's newest track.order = _tracks.length; setupNewTrack( track ); // Simply add the track onto the ordered tracks array _orderedTracks.push( track ); _this.dispatch( "trackadded", track ); _this.dispatch( "trackorderchanged", _orderedTracks ); addNewTrackTrackEvents( track ); return track; }; this.insertTrackBefore = function( otherTrack, newTrack ) { newTrack = ensureNewTrackIsTrack( newTrack ); if ( newTrack._media ) { throw "Track already belongs to a Media object. Use `media.removeTrack` prior to this function."; } var idx = _orderedTracks.indexOf( otherTrack ); if ( idx > -1 ) { // Give new track last order since it's newest newTrack.order = idx; // Insert new track _orderedTracks.splice( idx, 0, newTrack ); setupNewTrack( newTrack ); _this.dispatch( "trackadded", newTrack ); // Sort tracks after added one to update their order. _this.sortTracks( idx + 1 ); addNewTrackTrackEvents( newTrack ); return newTrack; } else { throw "inserTrackBefore must be passed a valid relative track."; } }; this.getTrackById = function( id ) { for ( var i = 0, l = _tracks.length; i < l; ++i ) { if ( _tracks[ i ].id === id ) { return _tracks[ i ]; } } }; this.getTrackByOrder = function( order ) { for ( var i = 0; i < _orderedTracks.length; i++ ) { if ( order === _orderedTracks[ i ].order ) { return _orderedTracks[ i ]; } } }; this.removeTrack = function ( track ) { var idx = _tracks.indexOf( track ), trackEvent, orderedIndex; if ( idx > -1 ) { _tracks.splice( idx, 1 ); orderedIndex = _orderedTracks.indexOf( track ); var events = track.trackEvents; for ( var i=0, l=events.length; i<l; ++i ) { trackEvent = events[ i ]; trackEvent.selected = false; trackEvent.unbind(); track.dispatch( "trackeventremoved", trackEvent ); } //for _this.unchain( track, [ "tracktargetchanged", "tracknamechanged", "trackeventadded", "trackeventeditorclose", "trackeventremoved", "trackeventupdated", "trackeventselected", "trackeventdeselected" ]); track.setPopcornWrapper( null ); track._media = null; _orderedTracks.splice( orderedIndex, 1 ); _this.dispatch( "trackremoved", track ); _this.sortTracks( orderedIndex ); return track; } //if }; //removeTrack this.findTrackWithTrackEventId = function( id ){ for( var i=0, l=_tracks.length; i<l; ++i ){ var te = _tracks[ i ].getTrackEventById( id ); if( te ){ return { track: _tracks[ i ], trackEvent: te }; } } //for }; //findTrackWithTrackEventId this.getManifest = function( name ) { return _registry[ name ]; }; //getManifest function setupContent(){ // In the case of URL being a string, check that it doesn't follow our format for // Null Video (EG #t=,200). Without the check it incorrectly will splice on the comma. if ( _url && _url.indexOf( "#t" ) !== 0 && _url.indexOf( "," ) > -1 ) { _url = _url.split( "," ); } if ( _url && _target ) { if ( !_popcornWrapper.popcorn ) { _popcornWrapper.prepare( _url, _target, _popcornOptions, _this.popcornCallbacks, _this.popcornScripts ); } else { // We don't need to actually destroy the popcorn instance, simply change it's source. _popcornWrapper.popcorn.media.src = _url; mediaReady(); } } } this.setupContent = setupContent; this.onReady = function( callback ){ function onReady( e ) { callback( e ); _this.unlisten( "mediaready", onReady ); } if ( _ready ) { callback(); } else { _this.listen( "mediaready", onReady ); } }; this.pause = function(){ _popcornWrapper.paused = true; }; //pause this.play = function(){ _popcornWrapper.paused = false; }; this.generatePopcornString = function( callbacks, scripts ){ var popcornOptions = _popcornOptions || {}; callbacks = callbacks || _this.popcornCallbacks; scripts = scripts || _this.popcornScripts; var collectedEvents = []; for ( var i = 0, l = _tracks.length; i < l; ++i ) { collectedEvents = collectedEvents.concat( _tracks[ i ].trackEvents ); } return _popcornWrapper.generatePopcornString( popcornOptions, _url, _target, null, callbacks, scripts, collectedEvents ); }; function compareTrackOrder( a, b ) { return a.order - b.order; } this.sortTracks = function( startIndex, endIndex ) { var i = startIndex || 0, l = endIndex || _orderedTracks.length; for ( ; i <= l; ++i ) { if ( _orderedTracks[ i ] ) { _orderedTracks[ i ].order = i; _orderedTracks[ i ].updateTrackEvents(); } } _orderedTracks.sort( compareTrackOrder ); _this.dispatch( "trackorderchanged", _orderedTracks ); }; this.getNextTrack = function( currentTrack ) { var trackIndex = _orderedTracks.indexOf( currentTrack ); if ( trackIndex > -1 && trackIndex < _orderedTracks.length - 1 ) { return _orderedTracks[ trackIndex + 1 ]; } return null; }; this.getPreviousTrack = function( currentTrack ) { var trackIndex = _orderedTracks.indexOf( currentTrack ); if ( trackIndex > -1 && trackIndex <= _orderedTracks.length - 1 ) { return _orderedTracks[ trackIndex - 1 ]; } return null; }; this.getLastTrack = function( currentTrack ) { var trackIndex = _orderedTracks.indexOf( currentTrack ); if ( trackIndex > 0 ) { return _orderedTracks[ trackIndex - 1 ]; } return null; }; this.findNextAvailableTrackFromTimes = function( start, end ) { for ( var i = 0, l = _orderedTracks.length; i < l; ++i ) { if ( !_orderedTracks[ i ].findOverlappingTrackEvent( start, end ) ) { return _orderedTracks[ i ]; } } return null; }; this.forceEmptyTrackSpaceAtTime = function( track, start, end, ignoreTrackEvent ) { var nextTrack; if ( track.findOverlappingTrackEvent( start, end, ignoreTrackEvent ) ) { nextTrack = _this.getNextTrack( track ); if ( nextTrack ) { if ( nextTrack.findOverlappingTrackEvent( start, end, ignoreTrackEvent ) ) { return _this.insertTrackBefore( nextTrack ); } else { return nextTrack; } } else { return this.addTrack(); } } return track; }; this.fixTrackEventBounds = function() { var i, j, tracks, tracksLength, trackEvents, trackEventsLength, trackEvent, trackEventOptions, start, end; tracks = _orderedTracks.slice(); // loop through all tracks for ( i = 0, tracksLength = tracks.length; i < tracksLength; i++ ) { trackEvents = tracks[ i ].trackEvents.slice(); // loop through all track events for ( j = 0, trackEventsLength = trackEvents.length; j < trackEventsLength; j++ ) { trackEvent = trackEvents[ j ]; trackEventOptions = trackEvent.popcornOptions; start = trackEventOptions.start; end = trackEventOptions.end; // check if track event is out of bounds if ( end > _duration ) { if ( start > _duration ) { // remove offending track event trackEvent.track.removeTrackEvent( trackEvent ); } else { trackEvent.update({ end: _duration }); } } } } }; this.hasTrackEvents = function() { for ( var i = 0, l = _tracks.length; i < l; ++i ) { if ( _tracks[ i ].trackEvents.length ) { return true; } } }; // Internally we decorate URLs with a unique butteruid, strip it when exporting function sanitizeUrl() { var sanitized; function sanitize( url ) { return URI.stripUnique( url ).toString(); } // Deal with url being single or array of multiple if ( Array.isArray( _url ) ) { sanitized = []; _url.forEach( function( url ) { sanitized.push( sanitize( url ) ); }); return sanitized; } else { return sanitize( _url ); } } Object.defineProperties( this, { ended: { enumerable: true, get: function(){ if( _popcornWrapper.popcorn ){ return _popcornWrapper.popcorn.ended(); } return false; } }, url: { enumerable: true, get: function() { return _url; }, set: function( val ) { if ( _url !== val ) { _url = val; _ready = false; setupContent(); } } }, target: { get: function() { return _target; }, set: function( val ) { if ( _target !== val ) { _target = val; setupContent(); _this.dispatch( "mediatargetchanged", _this ); } }, enumerable: true }, muted: { enumerable: true, get: function(){ return _popcornWrapper.muted; }, set: function( val ){ _popcornWrapper.muted = val; } }, ready: { enumerable: true, get: function(){ return _ready; } }, clipData: { get: function() { return _clipData; }, enumerable: true }, name: { get: function(){ return _name; }, enumerable: true }, id: { get: function(){ return _id; }, enumerable: true }, tracks: { get: function(){ return _tracks; }, enumerable: true }, orderedTracks: { get: function() { return _orderedTracks; }, enumerable: true }, currentTime: { get: function(){ return _currentTime; }, set: function( time ){ if( time !== undefined ){ _currentTime = time; if( _currentTime < 0 ){ _currentTime = 0; } if( _currentTime > _duration ){ _currentTime = _duration; } //if _popcornWrapper.currentTime = _currentTime; _this.dispatch( "mediatimeupdate", _this ); } //if }, enumerable: true }, duration: { get: function(){ return _duration; }, set: function( time ){ if( time ){ _duration = +time; _logger.log( "duration changed to " + _duration ); _this.fixTrackEventBounds(); _this.dispatch( "mediadurationchanged", _this ); } }, enumerable: true }, json: { get: function() { var exportJSONTracks = []; for ( var i = 0, l = _orderedTracks.length; i < l; ++i ) { exportJSONTracks.push( _orderedTracks[ i ].json ); } return { id: _id, name: _name, url: sanitizeUrl(), target: _target, duration: _duration, popcornOptions: _popcornOptions, controls: _popcornWrapper.popcorn ? _popcornWrapper.popcorn.controls() : false, tracks: exportJSONTracks, clipData: _clipData, currentTime: _currentTime }; }, set: function( importData ){ var newTrack, url, i, l, fallbacks = [], sources = []; function doImportTracks() { if ( importData.tracks ) { var importTracks = importData.tracks; if( Array.isArray( importTracks ) ) { for ( i = 0, l = importTracks.length; i < l; ++i ) { newTrack = new Track(); _this.addTrack( newTrack ); newTrack.json = importTracks[ i ]; } // Backwards comp for old base media. // Insert previous base media as a sequence event as the last track. if ( importData.url && _duration >= 0 ) { var firstSource; // If sources is a single array and of type null player, // don't bother making a sequence. if ( url.length > 1 || MediaTypes.checkUrl( url[ 0 ] ) !== "null" ) { // grab first source as main source. sources.push( URI.makeUnique( url.shift() ).toString() ); for ( i = 0; i < url.length; i++ ) { fallbacks.push( URI.makeUnique( url[ i ] ).toString() ); } firstSource = sources[ 0 ]; MediaTypes.getMetaData( firstSource, function( data ) { newTrack = new Track(); _this.addTrack( newTrack ); newTrack.addTrackEvent({ type: "sequencer", popcornOptions: { start: 0, end: _duration, source: sources, title: data.title, fallback: fallbacks, duration: _duration, target: "video-container" } }); _clipData[ firstSource ] = firstSource; }); } } } else if ( console ) { console.warn( "Ignoring imported track data. Must be in an Array." ); } } } if( importData.name ) { _name = importData.name; } if( importData.target ){ _this.target = importData.target; } url = importData.url; if ( !Array.isArray( url ) ) { url = [ url ]; } if ( importData.duration >= 0 ) { _duration = importData.duration; _this.url = "#t=," + _duration; doImportTracks(); } else { MediaTypes.getMetaData( url[ 0 ], function success( data ) { _duration = data.duration; _this.url = "#t=," + _duration; doImportTracks(); }); } if ( importData.clipData ) { var tempClipData = importData.clipData, source; // We have changed how we use the clip data by keying differently. // This is to prevent duplicate clips being added via the old way by keying them // our new way on import. for ( var key in tempClipData ) { if ( tempClipData.hasOwnProperty( key ) ) { source = tempClipData[ key ]; if ( !_clipData[ key ] ) { _clipData[ key ] = source; } } } } }, enumerable: true }, registry: { get: function(){ return _registry; }, set: function( val ){ _registry = val; }, enumerable: true }, popcorn: { enumerable: true, get: function(){ return _popcornWrapper; } }, paused: { enumerable: true, get: function(){ return _popcornWrapper.paused; }, set: function( val ){ _popcornWrapper.paused = val; } }, volume: { enumerable: true, get: function(){ return _popcornWrapper.volume; }, set: function( val ){ _popcornWrapper.volume = val; } }, popcornOptions: { enumerable: true, get: function(){ return _popcornOptions; }, set: function( val ){ _popcornOptions = val; _this.dispatch( "mediapopcornsettingschanged", _this ); setupContent(); } } }); }; //Media return Media; }); }());
function Shell(color, magnitude, type, special) { this.color = color; this.magnitude = magnitude; this.type = type; this.special = special; }
export class App { configureRouter(config, router) { config.title = 'Learning Aurelia'; config.map([ { route: ['', 'h1p1'], name: 'h1p1', nav: true, title: 'Header 1 & Page 1', viewPorts: { header: { moduleId: 'header-1' }, content: { moduleId: 'page-1' } } }, { route: 'h1p2', name: 'h1p2', nav: true, title: 'Header 1 & Page 2', navigationStrategy: ins => { ins.config.viewPorts = { header: { moduleId: 'header-1' }, content: { moduleId: 'page-2' } }; } }, { route: 'h2p2', name: 'h2p2', nav: true, title: 'Header 2 & Page 2', viewPorts: { header: { moduleId: 'header-2' }, content: { moduleId: 'page-2' } } }, ]); this.router = router; } }
/** * Created by esoragoto on 15-12-23. */ function ChangeLang(){ myform = document.getElementById('langform'); myform.submit(); }