code
stringlengths
2
1.05M
import isNil from "lodash/isNil"; import isArray from "lodash/isArray"; import isFunction from "lodash/isFunction"; import isObject from "lodash/isObject"; import mergeWith from "lodash/mergeWith"; import Fakerator from "lib/fakerator"; module.exports = function() { let locale = require("lib/locales/sv-SE"); let fbLocale = require("lib/locales/default"); // Merge locale and fallback locale = mergeWith(locale, fbLocale, (objValue) => { // DON'T MERGE ARRAYS if (isArray(objValue) || isFunction(objValue)) return objValue; if (!isNil(objValue) && !isObject(objValue)) return objValue; }); return new Fakerator(locale); };
module.exports = { 'tokens': [ { 'type': 'category', 'name': 'Colors', 'tokens': [ { 'variable': '--app-accent-color', 'name': 'App Accent Color', 'type': 'color', 'themes': { 'plain': { 'value': 'black', 'variable': '--plain-black-color' }, 'funky': { 'value': 'orange', 'variable': '--funky-orange-color' } }, 'description': 'Accent color' }, { 'variable': '--app-call-to-action-color', 'name': 'App Call To Action Color', 'type': 'color', 'themes': { 'plain': { 'value': 'red', 'variable': '--plain-red-color' }, 'funky': { 'value': 'orange', 'variable': '--funky-orange-color' } }, 'description': 'Primary interaction color' } ] }, { 'type': 'category', 'name': 'Shadows', 'tokens': [ { 'variable': '--app-box-shadow', 'name': 'App Box Shadow', 'type': 'shadow', 'themes': { 'plain': { 'value': '0 0 8px 2px rgba(92,43,54,0.2)' }, 'funky': { 'value': '0 0 8px 2px rgba(0,0,0,0.2)' } } } ] }, { 'type': 'category', 'name': 'Borders', 'tokens': [ { 'variable': '--app-border-radius', 'name': 'App Border Radius', 'type': 'border-radius', 'themes': { 'plain': { 'value': '20rem' }, 'funky': { 'value': '3px' } } }, { 'variable': '--app-border-width', 'name': 'App Border Width', 'type': 'border-width', 'themes': { 'plain': { 'value': '2px' }, 'funky': { 'value': '7px' } } }, { 'variable': '--app-border-style', 'name': 'App Border Style', 'type': 'border-style', 'themes': { 'plain': { 'value': 'dashed' }, 'funky': { 'value': 'dotted' } } } ] }, { 'type': 'category', 'name': 'Opacity', 'tokens': [ { 'variable': '--app-opacity-30', 'name': 'Opacity 30%', 'type': 'opacity', 'themes': { 'plain': { 'value': '0.3' }, 'funky': { 'value': '0.3' } } }, { 'variable': '--app-opacity-60', 'name': 'Opacity 60%', 'type': 'opacity', 'themes': { 'plain': { 'value': '0.6' }, 'funky': { 'value': '0.6' } } }, { 'variable': '--app-opacity-90', 'name': 'Opacity 90%', 'type': 'opacity', 'themes': { 'plain': { 'value': '0.9' }, 'funky': { 'value': '0.9' } } } ] }, { 'type': 'category', 'name': 'Spaces', 'tokens': [ { 'variable': '--app-space-xs', 'name': 'App Space XS', 'type': 'size', 'themes': { 'plain': { 'value': '0.25rem' }, 'funky': { 'value': '0.25rem' } } }, { 'variable': '--app-space-s', 'name': 'App Space S', 'type': 'size', 'themes': { 'plain': { 'value': '0.5rem' }, 'funky': { 'value': '0.5rem' } } }, { 'variable': '--app-space-m', 'name': 'App Space M', 'type': 'size', 'themes': { 'plain': { 'value': '1rem' }, 'funky': { 'value': '1rem' } } }, { 'variable': '--app-space-l', 'name': 'App Space L', 'type': 'size', 'themes': { 'plain': { 'value': '1.5rem' }, 'funky': { 'value': '1.5rem' } } }, { 'variable': '--app-space-xl', 'name': 'App Space XL', 'type': 'size', 'themes': { 'plain': { 'value': '2rem' }, 'funky': { 'value': '2rem' } } }, { 'variable': '--app-space-xxl', 'name': 'App Space XXL', 'type': 'size', 'themes': { 'plain': { 'value': '4rem' }, 'funky': { 'value': '4rem' } } } ] } ] }
/* * Copyright (C) 2014 United States Government as represented by the Administrator of the * National Aeronautics and Space Administration. All Rights Reserved. */ /** * @exports BMNGRestLayer */ define([ '../error/ArgumentError', '../layer/Layer', '../util/Logger', '../util/PeriodicTimeSequence', '../layer/RestTiledImageLayer' ], function (ArgumentError, Layer, Logger, PeriodicTimeSequence, RestTiledImageLayer) { "use strict"; /** * Constructs a Blue Marble layer. * @alias BMNGRestLayer * @constructor * @augments Layer * @classdesc Represents the 12 month collection of Blue Marble Next Generation imagery for the year 2004. * By default the month of January is displayed, but this can be changed by setting this class' time * property to indicate the month to display. * @param {String} serverAddress The server address of the tile service. May be null, in which case the * current origin is used (see window.location). * @param {String} pathToData The path to the data directory relative to the specified server address. * May be null, in which case the server address is assumed to be the full path to the data directory. * @param {String} displayName The display name to assign this layer. Defaults to "Blue Marble" if null or * undefined. * @param {Date} initialTime A date value indicating the month to display. The nearest month to the specified * time is displayed. January is displayed if this argument is null or undefined, i.e., new Date("2004-01"); * See {@link RestTiledImageLayer} for a description of its contents. May be null, in which case default * values are used. */ var BMNGRestLayer = function (serverAddress, pathToData, displayName, initialTime) { Layer.call(this, displayName || "Blue Marble time series"); /** * A value indicating the month to display. The nearest month to the specified time is displayed. * @type {Date} * @default January 2004 (new Date("2004-01")); */ this.time = initialTime || new Date("2004-01"); this.pickEnabled = false; // Intentionally not documented. this.layers = {}; // holds the layers as they're created. // Intentionally not documented. this.layerNames = [ {month: "BlueMarble-200401", time: BMNGRestLayer.availableTimes[0]}, {month: "BlueMarble-200402", time: BMNGRestLayer.availableTimes[1]}, {month: "BlueMarble-200403", time: BMNGRestLayer.availableTimes[2]}, {month: "BlueMarble-200404", time: BMNGRestLayer.availableTimes[3]}, {month: "BlueMarble-200405", time: BMNGRestLayer.availableTimes[4]}, {month: "BlueMarble-200406", time: BMNGRestLayer.availableTimes[5]}, {month: "BlueMarble-200407", time: BMNGRestLayer.availableTimes[6]}, {month: "BlueMarble-200408", time: BMNGRestLayer.availableTimes[7]}, {month: "BlueMarble-200409", time: BMNGRestLayer.availableTimes[8]}, {month: "BlueMarble-200410", time: BMNGRestLayer.availableTimes[9]}, {month: "BlueMarble-200411", time: BMNGRestLayer.availableTimes[10]}, {month: "BlueMarble-200412", time: BMNGRestLayer.availableTimes[11]} ]; this.timeSequence = new PeriodicTimeSequence("2004-01-01/2004-12-01/P1M"); // By default if no server address and path are sent as parameters in the constructor, // the layer's data is retrieved from http://worldwindserver.net this.serverAddress = serverAddress || "http://worldwindserver.net/webworldwind/"; this.pathToData = pathToData || "/standalonedata/Earth/BlueMarble256/"; // Alternatively, the data can be retrieved from a local folder as follows. // - Download the file located in: // http://worldwindserver.net/webworldwind/WebWorldWindStandaloneData.zip // - Unzip it into the Web World Wind top-level directory so that the "standalonedata" directory is a peer // of examples, src, apps and worldwind.js. // - Uncomment the following lines or call BMNGRestLayer from the application with these parameters: //this.serverAddress = serverAddress || null; //this.pathToData = pathToData || "../standalonedata/Earth/BlueMarble256/"; }; BMNGRestLayer.prototype = Object.create(Layer.prototype); /** * Indicates the available times for this layer. * @type {Date[]} * @readonly */ BMNGRestLayer.availableTimes = [ new Date("2004-01"), new Date("2004-02"), new Date("2004-03"), new Date("2004-04"), new Date("2004-05"), new Date("2004-06"), new Date("2004-07"), new Date("2004-08"), new Date("2004-09"), new Date("2004-10"), new Date("2004-11"), new Date("2004-12") ]; /** * Initiates retrieval of this layer's level 0 images for all sub-layers. Use * [isPrePopulated]{@link TiledImageLayer#isPrePopulated} to determine when the images have been retrieved * and associated with the level 0 tiles. * Pre-populating is not required. It is used to eliminate the visual effect of loading tiles incrementally, * but only for level 0 tiles. An application might pre-populate a layer in order to delay displaying it * within a time series until all the level 0 images have been retrieved and added to memory. * @param {WorldWindow} wwd The world window for which to pre-populate this layer. * @throws {ArgumentError} If the specified world window is null or undefined. */ BMNGRestLayer.prototype.prePopulate = function (wwd) { if (!wwd) { throw new ArgumentError( Logger.logMessage(Logger.LEVEL_SEVERE, "BMNGRestLayer", "prePopulate", "missingWorldWindow")); } for (var i = 0; i < this.layerNames.length; i++) { var layerName = this.layerNames[i].month; if (!this.layers[layerName]) { this.createSubLayer(layerName); } this.layers[layerName].prePopulate(wwd); } }; /** * Indicates whether this layer's level 0 tile images for all sub-layers have been retrieved and associated * with the tiles. * Use [prePopulate]{@link TiledImageLayer#prePopulate} to initiate retrieval of level 0 images. * @param {WorldWindow} wwd The world window associated with this layer. * @returns {Boolean} true if all level 0 images have been retrieved, otherwise false. * @throws {ArgumentError} If the specified world window is null or undefined. */ BMNGRestLayer.prototype.isPrePopulated = function (wwd) { for (var i = 0; i < this.layerNames.length; i++) { var layer = this.layers[this.layerNames[i].month]; if (!layer || !layer.isPrePopulated(wwd)) { return false; } } return true; }; BMNGRestLayer.prototype.doRender = function (dc) { var layer = this.nearestLayer(this.time); layer.opacity = this.opacity; if (this.detailControl) { layer.detailControl = this.detailControl; } layer.doRender(dc); this.inCurrentFrame = layer.inCurrentFrame; }; // Intentionally not documented. BMNGRestLayer.prototype.nearestLayer = function (time) { var nearestName = this.nearestLayerName(time); if (!this.layers[nearestName]) { this.createSubLayer(nearestName); } return this.layers[nearestName]; }; BMNGRestLayer.prototype.createSubLayer = function (layerName) { var dataPath = this.pathToData + layerName; this.layers[layerName] = new RestTiledImageLayer(this.serverAddress, dataPath, this.displayName); }; // Intentionally not documented. BMNGRestLayer.prototype.nearestLayerName = function (time) { var milliseconds = time.getTime(); if (milliseconds <= this.layerNames[0].time.getTime()) { return this.layerNames[0].month; } if (milliseconds >= this.layerNames[11].time.getTime()) { return this.layerNames[11].month; } for (var i = 0; i < this.layerNames.length - 1; i++) { var leftTime = this.layerNames[i].time.getTime(), rightTime = this.layerNames[i + 1].time.getTime(); if (milliseconds >= leftTime && milliseconds <= rightTime) { var dLeft = milliseconds - leftTime, dRight = rightTime - milliseconds; return dLeft < dRight ? this.layerNames[i].month : this.layerNames[i + 1].month; } } }; return BMNGRestLayer; });
console.log('Hello!'); var thermostat = new Thermostat(); var updateTemperature = function() { $('#temperature_display').text(thermostat.temperature); $('#temperature_display').css('color', thermostat.colour); }; $(document).ready(function() { updateTemperature(); $('#increase-button').on('click', function() { thermostat.increaseTemp(); updateTemperature(); }); $('#decrease-button').on('click', function() { thermostat.decreaseTemp(); updateTemperature(); }); $('#reset-button').on('click', function() { thermostat.reset(); updateTemperature(); }); $('#power-saving-mode').on('change', function() { if (this.checked) { thermostat.powerSavingOn(); } else { thermostat.powerSavingOff(); } updateTemperature(); }); $('#weather-status-form').submit(function(event){ event.preventDefault(); captureCity = $('#weather-city').val(); console.log(captureCity); processForm(); updateTemperature(); }); }); function processForm() { $.ajax({ url: 'http://api.openweathermap.org/data/2.5/weather?q=' + captureCity, jsonp: 'callback', dataType: 'jsonp', cache: false, data: { q: $('#weather-city').val(), }, success: function (response) { $('#current-city').text(response.name); $('#weather-description').text(response.weather[0].description); $('#weather-temp').text((response.main.temp -273.15).toFixed(1)); $('#weather-wind').text(response.wind.speed); }, }); }
var Observer = require('../../../../src/observer') var config = require('../../../../src/config') var _ = require('../../../../src/util') describe('Observer', function () { it('create on non-observables', function () { // skip primitive value var ob = Observer.create(1) expect(ob).toBeUndefined() // avoid vue instance ob = Observer.create(new _.Vue()) expect(ob).toBeUndefined() // avoid frozen objects ob = Observer.create(Object.freeze({})) expect(ob).toBeUndefined() }) it('create on object', function () { // on object var obj = { a: {}, b: {} } var ob = Observer.create(obj) expect(ob instanceof Observer).toBe(true) expect(ob.value).toBe(obj) expect(obj.__ob__).toBe(ob) // should've walked children expect(obj.a.__ob__ instanceof Observer).toBe(true) expect(obj.b.__ob__ instanceof Observer).toBe(true) // should return existing ob on already observed objects var ob2 = Observer.create(obj) expect(ob2).toBe(ob) }) it('create on array', function () { // on object var arr = [{}, {}] var ob = Observer.create(arr) expect(ob instanceof Observer).toBe(true) expect(ob.value).toBe(arr) expect(arr.__ob__).toBe(ob) // should've walked children expect(arr[0].__ob__ instanceof Observer).toBe(true) expect(arr[1].__ob__ instanceof Observer).toBe(true) }) it('observing object prop change', function () { var obj = { a: { b: 2 } } Observer.create(obj) // mock a watcher! var watcher = { deps: [], addDep: function (dep) { this.deps.push(dep) dep.addSub(this) }, update: jasmine.createSpy() } // collect dep Observer.setTarget(watcher) obj.a.b Observer.setTarget(null) expect(watcher.deps.length).toBe(3) // obj.a + a.b + b obj.a.b = 3 expect(watcher.update.calls.count()).toBe(1) // swap object obj.a = { b: 4 } expect(watcher.update.calls.count()).toBe(2) watcher.deps = [] Observer.setTarget(watcher) obj.a.b Observer.setTarget(null) expect(watcher.deps.length).toBe(3) // set on the swapped object obj.a.b = 5 expect(watcher.update.calls.count()).toBe(3) }) it('observing $add/$set/$delete', function () { var obj = { a: 1 } var ob = Observer.create(obj) var dep = ob.dep spyOn(dep, 'notify') obj.$add('b', 2) expect(obj.b).toBe(2) expect(dep.notify.calls.count()).toBe(1) obj.$delete('a') expect(obj.hasOwnProperty('a')).toBe(false) expect(dep.notify.calls.count()).toBe(2) // should ignore adding an existing key obj.$add('b', 3) expect(obj.b).toBe(2) expect(dep.notify.calls.count()).toBe(2) // set existing key, should be a plain set and not // trigger own ob's notify obj.$set('b', 3) expect(obj.b).toBe(3) expect(dep.notify.calls.count()).toBe(2) // set non-existing key obj.$set('c', 1) expect(obj.c).toBe(1) expect(dep.notify.calls.count()).toBe(3) // should ignore deleting non-existing key obj.$delete('a') expect(dep.notify.calls.count()).toBe(3) // should work on non-observed objects var obj2 = { a: 1 } obj2.$delete('a') expect(obj2.hasOwnProperty('a')).toBe(false) }) it('observing array mutation', function () { var arr = [] var ob = Observer.create(arr) var dep = ob.dep spyOn(dep, 'notify') var objs = [{}, {}, {}] arr.push(objs[0]) arr.pop() arr.unshift(objs[1]) arr.shift() arr.splice(0, 0, objs[2]) arr.sort() arr.reverse() expect(dep.notify.calls.count()).toBe(7) // inserted elements should be observed objs.forEach(function (obj) { expect(obj.__ob__ instanceof Observer).toBe(true) }) }) it('array $set', function () { var arr = [1] var ob = Observer.create(arr) var dep = ob.dep spyOn(dep, 'notify') arr.$set(0, 2) expect(arr[0]).toBe(2) expect(dep.notify.calls.count()).toBe(1) // setting out of bound index arr.$set(2, 3) expect(arr[2]).toBe(3) expect(dep.notify.calls.count()).toBe(2) }) it('array $remove', function () { var arr = [{}, {}] var obj1 = arr[0] var obj2 = arr[1] var ob = Observer.create(arr) var dep = ob.dep spyOn(dep, 'notify') // remove by index arr.$remove(0) expect(arr.length).toBe(1) expect(arr[0]).toBe(obj2) expect(dep.notify.calls.count()).toBe(1) // remove by identity, not in array arr.$remove(obj1) expect(arr.length).toBe(1) expect(arr[0]).toBe(obj2) expect(dep.notify.calls.count()).toBe(1) // remove by identity, in array arr.$remove(obj2) expect(arr.length).toBe(0) expect(dep.notify.calls.count()).toBe(2) }) it('no proto', function () { config.proto = false // object var obj = {a: 1} var ob = Observer.create(obj) expect(obj.$add).toBeTruthy() expect(obj.$delete).toBeTruthy() var dep = ob.dep spyOn(dep, 'notify') obj.$add('b', 2) expect(dep.notify).toHaveBeenCalled() // array var arr = [1, 2, 3] var ob2 = Observer.create(arr) expect(arr.$set).toBeTruthy() expect(arr.$remove).toBeTruthy() expect(arr.push).not.toBe([].push) var dep2 = ob2.dep spyOn(dep2, 'notify') arr.push(1) expect(dep2.notify).toHaveBeenCalled() config.proto = true }) })
const { BrowserWindow } = require('electron'); const path = require('path'); class RecorderWindow { constructor() { let htmlPath = 'file://' + path.join(__dirname, '..') + '/pages/recorder_window.html' this.window = new BrowserWindow({ show: false, height: 400, width: 600, minHeight: 200, minWidth: 200, frame: false, hasShadow: false, alwaysOnTop: true, transparent: true, resizable: true }); this.window.loadURL(htmlPath); } disable() { this.window.setResizable(false); this.window.setIgnoreMouseEvents(true); } enable() { this.window.setResizable(true); this.window.setIgnoreMouseEvents(false); } } module.exports = RecorderWindow;
/* This file is part of Ext JS 4 Copyright (c) 2011 Sencha Inc Contact: http://www.sencha.com/contact Commercial Usage Licensees holding valid commercial licenses may use this file in accordance with the Commercial Software License Agreement provided with the Software or, alternatively, in accordance with the terms contained in a written agreement between you and Sencha. If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact. */ Ext.define('Sample.notdeadlock.A', { extend: 'Sample.notdeadlock.B' });
;(function(){ "use strict"; const module = window.load = { name: "xhr" }; const xhr = module.exports = (type, url, cb, opts) => { const xhr = new XMLHttpRequest(); if (opts) Object.keys(opts).map(key => xhr[key] = opts[key]); xhr.open(type, url); xhr.onreadystatechange = () => { if (xhr.readyState == 4) { cb(xhr); } } xhr.send(); return xhr; }; xhr.get = (url, cb, opts) => xhr("GET", url, cb, opts); xhr.post = (url, cb, opts) => xhr("POST", url, cb, opts); xhr.json = (url, cb, opts) => xhr("GET", url, res => cb(JSON.parse(res.responseText)), opts); })();
module.exports = /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ({ /***/ 0: /***/ (function(module, exports, __webpack_require__) { __webpack_require__(430); module.exports = __webpack_require__(430); /***/ }), /***/ 430: /***/ (function(module, exports) { (function( window, undefined ) { kendo.cultures["zh-SG"] = { name: "zh-SG", numberFormat: { pattern: ["-n"], decimals: 2, ",": ",", ".": ".", groupSize: [3], percent: { pattern: ["-n%","n%"], decimals: 2, ",": ",", ".": ".", groupSize: [3], symbol: "%" }, currency: { name: "Singapore Dollar", abbr: "SGD", pattern: ["($n)","$n"], decimals: 2, ",": ",", ".": ".", groupSize: [3], symbol: "$" } }, calendars: { standard: { days: { names: ["星期日","星期一","星期二","星期三","星期四","星期五","星期六"], namesAbbr: ["周日","周一","周二","周三","周四","周五","周六"], namesShort: ["日","一","二","三","四","五","六"] }, months: { names: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"], namesAbbr: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"] }, AM: ["上午","上午","上午"], PM: ["下午","下午","下午"], patterns: { d: "d/M/yyyy", D: "yyyy'年'M'月'd'日'", F: "yyyy'年'M'月'd'日' tt h:mm:ss", g: "d/M/yyyy tt h:mm", G: "d/M/yyyy tt h:mm:ss", m: "M'月'd'日'", M: "M'月'd'日'", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", t: "tt h:mm", T: "tt h:mm:ss", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", y: "yyyy'年'M'月'", Y: "yyyy'年'M'月'" }, "/": "/", ":": ":", firstDay: 0 } } } })(this); /***/ }) /******/ });
var subject = require('../../lib/helpers/injector'); var Promise = require('bluebird'); describe('injector', function() { it('returns a function returning a promise', function() { var fn = subject({}); expect(fn('name', [])).to.be.instanceOf(Promise); }); });
const merge = require('webpack-merge') const HtmlWebpackPlugin = require('html-webpack-plugin') const ExtractTextPlugin = require('extract-text-webpack-plugin') const base = require('./webpack.config.base') const pkg = require('../app/package.json') module.exports = merge(base, { entry: { renderer: ['./app/renderer.js'] }, module: { loaders: [ { test: /\.vue$/, loader: 'vue' }, { test: /\.css$/, loader: ExtractTextPlugin.extract('style', 'css', { publicPath: '../' }) }, { test: /\.less$/, loader: ExtractTextPlugin.extract('style', 'css!less', { publicPath: '../' }) }, // { test: /\.html$/, loader: 'vue-html' }, { test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, loader: 'url', query: { limit: 10000, name: 'img/[name].[hash:7].[ext]' } }, { test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, loader: 'url', query: { limit: 10000, name: 'font/[name].[hash:7].[ext]' } } ] }, resolve: { extensions: ['', '.js', '.json', '.css', '.less', '.sass', '.scss', '.vue'] }, target: 'electron-renderer', // devServer: { // // contentBase: './build', // historyApiFallback: true, // progress: true, // inline: true, // colors: true, // quiet: false, // noInfo: false, // // lazy: true, // hot: true, // port: 2080 // }, plugins: [ new ExtractTextPlugin('css/[name].css') ], vue: { loaders: { // html: 'raw', // js: 'babel', css: ExtractTextPlugin.extract('css', { publicPath: '../' }), less: ExtractTextPlugin.extract('css!less', { publicPath: '../' }) }, autoprefixer: false } }) if (process.env.NODE_ENV === 'production') { module.exports.plugins = (module.exports.plugins || []).concat([ // generate dist index.html with correct asset hash for caching. // you can customize output by editing /index.html // see https://github.com/ampedandwired/html-webpack-plugin new HtmlWebpackPlugin({ template: './app/index.ejs', filename: 'index.html', title: pkg.productName, chunks: ['renderer'], excludeChunks: ['main'], inject: true, minify: { removeComments: true, collapseWhitespace: true, removeAttributeQuotes: true // more options: https://github.com/kangax/html-minifier#options-quick-reference } }) ]) } else { module.exports.module.preLoaders.push( { test: /\.vue$/, loader: 'eslint', exclude: /node_modules/ } ) module.exports.plugins = (module.exports.plugins || []).concat([ new HtmlWebpackPlugin({ template: './app/index.ejs', filename: 'index.html', title: pkg.productName, chunks: ['renderer'], excludeChunks: ['main'], inject: true }) ]) }
var https = require('https'); var xml2js = require('xml2js'); var groups = {}; var host, port , auth, origin; groups.getUserGroups = function(req, res) { var options = { rejectUnauthorized: false, hostname: host, port: port, path: "/sap/opu/odata/UI2/PAGE_BUILDER_PERS/PageSets('%2FUI2%2FFiori2LaunchpadHome')/Pages?$expand=PageChipInstances/Chip/ChipBags/ChipProperties", method: 'GET', auth: auth, agent: false }; var parser = new xml2js.Parser(); https.get(options, function(response) { var bodyChunks = []; response.on('data', function(chunk) { bodyChunks.push(chunk); }).on('end', function() { var body = Buffer.concat(bodyChunks); var jsonResult = []; console.log(body.toString()); //convert the XML response to JSON using the xml2js parser.parseString(body, function (err, result) { var groups = result.feed.entry; var currentGroupProperties, currentGroupTiles; if(groups){ for(var i=0; i<groups.length; i++){ currentGroupProperties = groups[i].content[0]['m:properties'][0]; currentGroupTiles = groups[i].link[3]['m:inline'][0].feed[0].entry; var groupJson = { id : currentGroupProperties['d:id'][0], title : currentGroupProperties['d:id'][0]==='/UI2/Fiori2LaunchpadHome'? 'My Home' : currentGroupProperties['d:title'][0], tiles: [] }; //iterate on current group tiles and add them the json var tileProps, chip, curTile; if(currentGroupTiles){ for(var k=0; k<currentGroupTiles.length; k++){ chip = currentGroupTiles[k].link[1]['m:inline'][0]; if(chip !== ""){ //Need to remove tiles that were built from a catalog chip which is no longer exists, they should be removed...(not appear in FLP) tileProps = chip.entry[0].content[0]['m:properties'][0]; //currentGroupTiles[k].content[0]['m:properties'][0]; curTile = { title: tileProps['d:title'][0], configuration: parseConfiguration(tileProps['d:configuration'][0]), url: tileProps['d:url'][0], baseChipId: tileProps['d:baseChipId'][0],//identify the type of tile (e.g."X-SAP-UI2-CHIP:/UI2/DYNAMIC_APPLAUNCHER") id: tileProps['d:id'][0] }; curTile.isDoubleWidth = curTile.configuration.col > 1; curTile.isDoubleHeight = curTile.configuration.row > 1; curTile.icon = '/images/index/main/apps/NewsImage11.png'; curTile.refreshInterval = curTile.configuration['service_refresh_interval']; curTile.realIcon = matchTileIcon(curTile.configuration['display_icon_url']); curTile.navigationTargetUrl = curTile.configuration['navigation_target_url']; curTile.serviceURL = curTile.configuration['service_url']; //Try to build working app url curTile.navUrl = undefined; if(curTile.navigationTargetUrl){ if(curTile.navigationTargetUrl.indexOf('#')===-1){ //it doesn't contain semantic object + action curTile.navUrl = origin + curTile.navigationTargetUrl; }else{ curTile.navUrl = origin + '/sap/bc/ui5_ui5/ui2/ushell/shells/abap/FioriLaunchpad.html?' + curTile.navigationTargetUrl; } } curTile.dynamicData = 0; getDynamicData(curTile); curTile.description = curTile.configuration['display_subtitle_text']; curTile.displayInfoText = curTile.configuration['display_info_text']; curTile.displayNumberUnit = curTile.configuration['display_number_unit']; switch(curTile.baseChipId){ case "X-SAP-UI2-CHIP:/UI2/AR_SRVC_NEWS": curTile.type = 0; break; case "X-SAP-UI2-CHIP:/UI2/DYNAMIC_APPLAUNCHER": curTile.type = 1; break; default: //"X-SAP-UI2-CHIP:/UI2/STATIC_APPLAUNCHER": curTile.type = 2; } groupJson.tiles.push(curTile); } } } if(groupJson.tiles.length === 0){ groupJson.tiles.push(getEmptyTile()); } jsonResult.push(groupJson); } } //Needs to be after the parsing completes res.json({ //Set the response back status: 'OK', results:jsonResult }); }) }) }).on('error', function(e) { console.error(e); var jsonResult = jsonResult || []; //work-around for non working ABAP if(jsonResult.length === 0){ for(var i=0; i<6; i++){ var tile, tiles = []; for(var k=0 ; k<i; k++){ tile = { title: "TileTitle_" + k, description: "TileDescription_" + k, configuration: JSON.parse('{"row":"1","col":"1"}'), //Default value for regular tiles url: "TODO tileURL", baseChipId: "TODO", id: "Tile_" + k, isNews: (k%2)?true:false }; tile.isDoubleWidth = tile.configuration.row > 1, tile.isDoubleHeight = tile.configuration.col > 1, tiles.push(tile); } jsonResult.push({ id : "Group_" + i, title : "GroupTitle_" + i, tiles: tiles }); } } res.json({ //Set the response back status: 'OK', results:jsonResult }); }); var parseConfiguration = function(confString){ var res; if(!confString){ res = {"row":"1","col":"1"}; }else{ res = JSON.parse(confString); if(res.tileConfiguration){ res = JSON.parse(res.tileConfiguration); } } return res; }; var getEmptyTile = function(){ return { title: '', configuration: {"row":"1","col":"1"}, url: '', icon: '/images/index/main/apps/plusSign.png', type: -1 }; }; var getDynamicData = function(curTile){ if(curTile.serviceURL){ options.path = curTile.serviceURL; https.get(options, function(response) { var bodyChunks = []; response.on('data', function(chunk) { bodyChunks.push(chunk); }); response.on('end', function() { var body = Buffer.concat(bodyChunks); this.dynamicData = body.toString(); }); }.bind(curTile)) } }; var matchTileIcon = function(fontName){ switch(fontName){ case 'sap-icon://multi-select': return 'glyphicon glyphicon-list'; break; case 'sap-icon://action-settings': return 'glyphicon glyphicon-cog'; break; case 'sap-icon://appointment': return 'glyphicon glyphicon-calendar'; break; case 'sap-icon://travel-itinerary': return 'glyphicon glyphicon-plane'; break; case 'sap-icon://table-chart': return 'glyphicon glyphicon-th'; break; default: return 'glyphicon glyphicon-eye-close'; } } }; module.exports = function(opts) { if(opts) { if(opts.fiori) { var url = opts.fiori.split('//')[1].split(':'); host = url[0]; port = url[1]; origin = opts.fiori; } if(opts.fioriAuth) { auth = opts.fioriAuth; } } return groups; };
'use strict'; const fs = require('fs'); const path = require('path'); const Router = require('koa-router'); const apiRouter = require('./api'); const ask = require('../lib/ask'); const config = require('config'); const indexFilePath = path.resolve(__dirname, '..', 'views', 'index.html'); const router = new Router(); const apiAddress = config.port ? `//${config.path}:${config.port}/api` : `//${config.path}/api`; router.use('/api', apiRouter.routes(), apiRouter.allowedMethods()); router.get('/*', index); const appScripts = getStartScripts(); let indexFileContents = null; async function index (ctx) { if (indexFileContents === null) { let indexFile = await ask(fs, 'readFile', indexFilePath); indexFileContents = new Function ('state', `return \`${indexFile}\``)({ apiAddress, appScripts }); } ctx.body = indexFileContents; } function getStartScripts() { if (process.env.NODE_ENV === 'production') { return `<script type="text/javascript" src="/js/app.bundle.js"></script>`; } else { return `<script type="text/javascript" src="/js/simple-require.js"></script> <script type="text/javascript" src="/js/index.js"></script>`; } } module.exports = router;
var group__spi__interface__gr = [ [ "Status Error Codes", "group__spi__execution__status.html", "group__spi__execution__status" ], [ "SPI Events", "group__SPI__events.html", "group__SPI__events" ], [ "SPI Control Codes", "group__SPI__control.html", "group__SPI__control" ], [ "ARM_DRIVER_SPI", "group__spi__interface__gr.html#structARM__DRIVER__SPI", [ [ "GetVersion", "group__spi__interface__gr.html#a8834b281da48583845c044a81566c1b3", null ], [ "GetCapabilities", "group__spi__interface__gr.html#a065b5fc24d0204692f0f95a44351ac1e", null ], [ "Initialize", "group__spi__interface__gr.html#afac50d0b28860f7b569293e6b713f8a4", null ], [ "Uninitialize", "group__spi__interface__gr.html#adcf20681a1402869ecb5c6447fada17b", null ], [ "PowerControl", "group__spi__interface__gr.html#aba8f1c8019af95ffe19c32403e3240ef", null ], [ "Send", "group__spi__interface__gr.html#a44eedddf4428cf4b98883b6c27d31922", null ], [ "Receive", "group__spi__interface__gr.html#adb9224a35fe16c92eb0dd103638e4cf3", null ], [ "Transfer", "group__spi__interface__gr.html#ad88b63ed74c03ba06b0599ab06ad4cf7", null ], [ "GetDataCount", "group__spi__interface__gr.html#ad1d892ab3932f65cd7cdf2d0a91ae5da", null ], [ "Control", "group__spi__interface__gr.html#a6e0f47a92f626a971c5197fca6545505", null ], [ "GetStatus", "group__spi__interface__gr.html#a7305e7248420cdb4b02ceba87672178d", null ] ] ], [ "ARM_SPI_CAPABILITIES", "group__spi__interface__gr.html#structARM__SPI__CAPABILITIES", [ [ "simplex", "group__spi__interface__gr.html#af244e2c2facf6414e3886495ee6b40bc", null ], [ "ti_ssi", "group__spi__interface__gr.html#a8053c540e5d531b692224bdc2463f36a", null ], [ "microwire", "group__spi__interface__gr.html#a9b4e858eb1d414128994742bf121f94c", null ], [ "event_mode_fault", "group__spi__interface__gr.html#a309619714f0c4febaa497ebdb9b7e3ca", null ], [ "reserved", "group__spi__interface__gr.html#aa43c4c21b173ada1b6b7568956f0d650", null ] ] ], [ "ARM_SPI_STATUS", "group__spi__interface__gr.html#structARM__SPI__STATUS", [ [ "busy", "group__spi__interface__gr.html#a50c88f3c1d787773e2ac1b59533f034a", null ], [ "data_lost", "group__spi__interface__gr.html#a9675630df67587ecd171c7ef12b9d22a", null ], [ "mode_fault", "group__spi__interface__gr.html#aeaf54ec655b7a64b9e88578c5f39d4e3", null ], [ "reserved", "group__spi__interface__gr.html#aa43c4c21b173ada1b6b7568956f0d650", null ] ] ], [ "ARM_SPI_SignalEvent_t", "group__spi__interface__gr.html#gafde9205364241ee81290adc0481c6640", null ], [ "ARM_SPI_GetVersion", "group__spi__interface__gr.html#gad5db9209ef1d64a7915a7278d6a402c8", null ], [ "ARM_SPI_GetCapabilities", "group__spi__interface__gr.html#gaf4823a11ab5efcd47c79b13801513ddc", null ], [ "ARM_SPI_Initialize", "group__spi__interface__gr.html#ga1a3c11ed523a4355cd91069527945906", null ], [ "ARM_SPI_Uninitialize", "group__spi__interface__gr.html#ga0c480ee3eabb82fc746e89741ed2e03e", null ], [ "ARM_SPI_PowerControl", "group__spi__interface__gr.html#ga1a1e7e80ea32ae381b75213c32aa8067", null ], [ "ARM_SPI_Send", "group__spi__interface__gr.html#gab2a303d1071e926280d50682f4808479", null ], [ "ARM_SPI_Receive", "group__spi__interface__gr.html#ga726aff54e782ed9b47f7ba1280a3d8f6", null ], [ "ARM_SPI_Transfer", "group__spi__interface__gr.html#gaa24026b3822c10272e301f1505136ec2", null ], [ "ARM_SPI_GetDataCount", "group__spi__interface__gr.html#gaaaecaaf4ec1922f22e7f9de63af5ccdb", null ], [ "ARM_SPI_Control", "group__spi__interface__gr.html#gad18d229992598d6677bec250015e5d1a", null ], [ "ARM_SPI_GetStatus", "group__spi__interface__gr.html#ga60d33d8788a76c388cc36e066240b817", null ], [ "ARM_SPI_SignalEvent", "group__spi__interface__gr.html#ga505b2d787348d51351d38fee98ccba7e", null ] ];
import checkEmpty from '../helpers/checkEmpty'; const validateReview = { validateFields(req, res, next) { const { content } = req.body; if (checkEmpty(content)) { return res.status(400).json({ status: 'fail', message: 'Review content field cannot be empty' }); } next(); } }; export default validateReview;
const m = require('mithril'); const Component = require('../../core/Component'); class ProjectBanner extends Component { view(vnode) { return m('.project', { style: "background-image: url(" + vnode.attrs.bannerImage + ")", onclick: function() { m.route.set("/" + vnode.attrs.id) } }, [ m('.overlay', [ m('.text-container', [ m('span', [ m('h5', vnode.attrs.title), m('i.fa.fa-info-circle') ]), m('p', vnode.attrs.brief) ]), ]) ]) } } module.exports = ProjectBanner;
/** * Created by chenjianjun on 16/2/25. */ var env=require("../../config"); var type=env.Thinky.type; /* { "success": true, "message": null, "data": [ { "id": 227, "recordVideoId": 9, "createTime": "2016-01-21 17:31:09", "updateTime": "2016-01-21 17:31:09", "operater": 1, "isUsed": 1, "name": "做你的新娘", "description": "", "hitNum": 500, "remark": "", "videoUrl": "ftp://192.168.1.3/ftppub/CQ/uploadResource/video/20150923/48716448481998474070/1024X768.mp4\t", "coverUrlWeb": "http://img.jsbn.com/followvideo/20160121/14533686688047965_1200x800.jpg", "coverUrlWx": "http://img.jsbn.com/followvideo/20160121/14533686690550054_1200x800.jpg", "coverUrlApp": "http://img.jsbn.com/followvideo/20160121/14533686689416315_1200x800.jpg", "seasonId": 9, "position": "record_video_list", "weight": 9 } ], "code": 200, "count": 2 } * */ // 婚纱摄影--纪实MV模型 const RecordVideo = env.Thinky.createModel('recordVideo', { // 发布Id id: type.number(), // 纪实ID recordVideoId: type.number(), // 创建时间 createTime: type.string(), // 修改时间 updateTime: type.string(), // 操作员 operater: type.number(), // 是否有效 isUsed: type.number(), // 纪实MV名称 name: type.string(), // 纪实MV描述 description: type.string(), // 热度 hitNum: type.number(), // 视频备注 remark: type.string(), // 视频地址 videoUrl: type.string(), // 网站封面图片地址 coverUrlWeb: type.string(), // 微信封面图片地址 coverUrlWx: type.string(), // APP封面图片地址 coverUrlApp: type.string(), // 分季ID seasonId: type.number(), // 权重 weight: type.number() }) RecordVideo.ensureIndex('weight'); module.exports=RecordVideo;
export { default } from 'ember-fhir/models/parameters';
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), errorHandler = require('./errors'), Book = mongoose.model('Book'), _ = require('lodash'); // , // googleapi = require('node-google-api')('AIzaSyAffzxPYpgZ14gieEE04_u4U-5Y26UQ8_0'); // exports.gbooks = function(req, res) { // googleapi.build(function(api) { // for(var k in api){ // console.log(k); // } // }); // var favoriteslist = req.favoriteslist; // favoriteslist.googleapi.build(function(err, api){ // }) // googleapi.build(function(api) { // api.books.mylibrary.bookshelves.list({ // userId: '114705319517394488779', // source: 'gbs_lp_bookshelf_list' // }, function(result){ // if(result.error) { // console.log(result.error); // } else { // for(var i in result.items) { // console.log(result.items[i].summary); // } // } // }); // }); // }; /** * Create a Book */ exports.create = function(req, res) { var book = new Book(req.body); book.user = req.user; book.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(book); } }); }; /** * Show the current Book */ exports.read = function(req, res) { res.jsonp(req.book); }; /** * Update a Book */ exports.update = function(req, res) { var book = req.book ; book = _.extend(book , req.body); book.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(book); } }); }; /** * Delete an Book */ exports.delete = function(req, res) { var book = req.book ; book.remove(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(book); } }); }; /** * List of Books */ exports.list = function(req, res) { Book.find().sort('-created').populate('user', 'displayName').exec(function(err, books) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(books); } }); }; /** * Book middleware */ exports.bookByID = function(req, res, next, id) { Book.findById(id).populate('user', 'displayName').exec(function(err, book) { if (err) return next(err); if (! book) return next(new Error('Failed to load Book ' + id)); req.book = book ; next(); }); }; /** * Book authorization middleware */ exports.hasAuthorization = function(req, res, next) { if (req.book.user.id !== req.user.id) { return res.status(403).send('User is not authorized'); } next(); };
import { Mongo } from 'meteor/mongo' export const Saved = new Mongo.Collection('saved'); if (Meteor.isClient) { Meteor.subscribe('saved') } if (Meteor.isServer) { Meteor.publish('saved', function savedPublication() { return Saved.find() }) }
'use babel'; import moment from 'moment'; import openUrl from 'opn'; const addError = ({ project, branch, build, endDate, commit }) => { const relativeTime = moment(endDate).fromNow(); atom.notifications.addError(`Build #${build.id} has failed`, { buttons: [ { onDidClick() { openUrl(`https://app.codeship.com/projects/${project.id}/builds/${build.id}`); this.model.dismiss(); }, text: 'View Details', }, { text: 'Dismiss', onDidClick() { this.model.dismiss(); }, }, ], description: `**branch:** ${branch}<br />**commit:** ${commit.message}`, detail: `The build for ${project.name} failed ${relativeTime}, view details to find out why.`, dismissable: true, icon: 'alert', }); }; const addStart = () => {}; const addSuccess = () => {}; export { addError, addStart, addSuccess };
var userData = [ {'fName':'Justin', 'lName' : 'Gil', 'age': 70, 'gender': 'M', 'phone': '949-111-1111', 'profilePic': '../pix/justin.jpeg', 'city' : 'San Diego', 'add' : '55 Serenity' , 'Bio': 'I like soccer and long walks on the beach.', 'userIndex' : 1, 'username': 'justin', 'password': 'lol', 'state' : 'CA', 'zip' : '92092'}, {'fName':'Momin', 'lName' : 'Khan', 'age': 60, 'gender': 'M', 'phone': '949-111-1312', 'profilePic': '../pix/momin.jpeg', 'city' : 'Carlsbad', 'add' : '23 Rollings' , 'Bio': 'I like soccer and long walks on the beach.', 'userIndex' : 2, 'username': 'momin', 'password': 'lol', 'state' : 'CA', 'zip' : '92312'}, {'fName':'Scott', 'lName' : 'Chen', 'age': 50, 'gender': 'M', 'phone': '949-111-1113', 'profilePic': '../pix/scott.jpeg', 'city' : 'Oceanside', 'add' : '35 Jasmin' , 'Bio': 'I like soccer and long walks on the beach.', 'userIndex' : 3, 'username': 'scott', 'password': 'lol', 'state' : 'CA', 'zip' : '42092'}, {'fName':'Charles', 'lName' : 'Chen', 'age': 72, 'gender': 'M', 'phone': '949-111-1114', 'profilePic': '../pix/charles.jpeg', 'city' : 'Coronado', 'add' : '388 Rose', 'Bio': 'I like soccer and long walks on the beach.', 'userIndex' : 4, 'username': 'charles', 'password': 'lol', 'state' : 'CA', 'zip' : '52092'} ] localStorage.setItem('userDataLocalStorage', JSON.stringify(userData)); $(function () { var invalidAccountWarning = document.getElementById("invalid_account_warning"); invalidAccountWarning.style.display = "none"; }); $("#login").click(function() { var invalidAccountWarning = document.getElementById("invalid_account_warning"); invalidAccountWarning.style.display = "none"; var username = document.getElementById("inputted_username").value; var password = document.getElementById("inputted_password").value; var loggedInUserIndex = 0; for (var i = 0; i < userData.length; i++) { var currData = userData[i]; if(username == currData.username && password == currData.password) loggedInUserIndex = currData.userIndex; } if(loggedInUserIndex != 0) { localStorage.setItem('loggedInUserIndex', loggedInUserIndex); console.log(loggedInUserIndex); window.location.href = 'home.html'; } else { invalidAccountWarning.style.display = "block"; } });
import FormComponent from '../../form-component'; export class TextArea extends FormComponent { constructor(context, options) { super( context, context.querySelector('.text-area__input'), context.querySelector('.text-area__error'), 'Text Area', options ); super.init(); this.initEvents(); } initEvents() { this.field.addEventListener('focus', () => { this.setIsFilledIn(true); }); this.field.addEventListener('blur', () => this.setIsFilledIn()); this.field.addEventListener('input', () => { // Don't just call setIsFilledIn() for the case where you've removed // the text field value but are still focusing the text field this.setIsFilledIn( this.field.value || this.field === document.activeElement ); }); } } export const selector = '[class^="text-area--"]';
/** * @aside guide tabs * @aside video tabs-toolbars * @aside example tabs * @aside example tabs-bottom * * Tab Panels are a great way to allow the user to switch between several pages that are all full screen. Each * Component in the Tab Panel gets its own Tab, which shows the Component when tapped on. Tabs can be positioned at * the top or the bottom of the Tab Panel, and can optionally accept title and icon configurations. * * Here's how we can set up a simple Tab Panel with tabs at the bottom. Use the controls at the top left of the example * to toggle between code mode and live preview mode (you can also edit the code and see your changes in the live * preview): * * @example miniphone preview * Ext.create('Ext.TabPanel', { * fullscreen: true, * tabBarPosition: 'bottom', * * defaults: { * styleHtmlContent: true * }, * * items: [ * { * title: 'Home', * iconCls: 'home', * html: 'Home Screen' * }, * { * title: 'Contact', * iconCls: 'user', * html: 'Contact Screen' * } * ] * }); * One tab was created for each of the {@link Ext.Panel panels} defined in the items array. Each tab automatically uses * the title and icon defined on the item configuration, and switches to that item when tapped on. We can also position * the tab bar at the top, which makes our Tab Panel look like this: * * @example miniphone preview * Ext.create('Ext.TabPanel', { * fullscreen: true, * * defaults: { * styleHtmlContent: true * }, * * items: [ * { * title: 'Home', * html: 'Home Screen' * }, * { * title: 'Contact', * html: 'Contact Screen' * } * ] * }); * */ Ext.define('Ext.tab.Panel', { extend: 'Ext.Container', xtype: 'tabpanel', alternateClassName: 'Ext.TabPanel', requires: ['Ext.tab.Bar'], config: { /** * @cfg {String} ui * Sets the UI of this component. * Available values are: `light` and `dark`. * @accessor */ ui: 'dark', /** * @cfg {Object} tabBar * An Ext.tab.Bar configuration. * @accessor */ tabBar: true, /** * @cfg {String} tabBarPosition * The docked position for the {@link #tabBar} instance. * Possible values are 'top' and 'bottom'. * @accessor */ tabBarPosition: 'top', /** * @cfg layout * @inheritdoc */ layout: { type: 'card', animation: { type: 'slide', direction: 'left' } }, /** * @cfg cls * @inheritdoc */ cls: Ext.baseCSSPrefix + 'tabpanel' /** * @cfg {Boolean/String/Object} scrollable * @accessor * @hide */ /** * @cfg {Boolean/String/Object} scroll * @hide */ }, initialize: function() { this.callParent(); this.on({ order: 'before', activetabchange: 'doTabChange', delegate: '> tabbar', scope: this }); this.on({ disabledchange: 'onItemDisabledChange', delegate: '> component', scope: this }); }, platformConfig: [{ theme: ['Blackberry'], tabBarPosition: 'bottom' }], /** * Tab panels should not be scrollable. Instead, you should add scrollable to any item that * you want to scroll. * @private */ applyScrollable: function() { return false; }, /** * Updates the Ui for this component and the {@link #tabBar}. */ updateUi: function(newUi, oldUi) { this.callParent(arguments); if (this.initialized) { this.getTabBar().setUi(newUi); } }, /** * @private */ doSetActiveItem: function(newActiveItem, oldActiveItem) { if (newActiveItem) { var items = this.getInnerItems(), oldIndex = items.indexOf(oldActiveItem), newIndex = items.indexOf(newActiveItem), reverse = oldIndex > newIndex, animation = this.getLayout().getAnimation(), tabBar = this.getTabBar(), oldTab = tabBar.parseActiveTab(oldIndex), newTab = tabBar.parseActiveTab(newIndex); if (animation && animation.setReverse) { animation.setReverse(reverse); } this.callParent(arguments); if (newIndex != -1) { this.forcedChange = true; tabBar.setActiveTab(newIndex); this.forcedChange = false; if (oldTab) { oldTab.setActive(false); } if (newTab) { newTab.setActive(true); } } } }, /** * Updates this container with the new active item. * @param {Object} tabBar * @param {Object} newTab * @return {Boolean} */ doTabChange: function(tabBar, newTab) { var oldActiveItem = this.getActiveItem(), newActiveItem; this.setActiveItem(tabBar.indexOf(newTab)); newActiveItem = this.getActiveItem(); return this.forcedChange || oldActiveItem !== newActiveItem; }, /** * Creates a new {@link Ext.tab.Bar} instance using {@link Ext#factory}. * @param {Object} config * @return {Object} * @private */ applyTabBar: function(config) { if (config === true) { config = {}; } if (config) { Ext.applyIf(config, { ui: this.getUi(), docked: this.getTabBarPosition() }); } return Ext.factory(config, Ext.tab.Bar, this.getTabBar()); }, /** * Adds the new {@link Ext.tab.Bar} instance into this container. * @private */ updateTabBar: function(newTabBar) { if (newTabBar) { this.add(newTabBar); this.setTabBarPosition(newTabBar.getDocked()); } }, /** * Updates the docked position of the {@link #tabBar}. * @private */ updateTabBarPosition: function(position) { var tabBar = this.getTabBar(); if (tabBar) { tabBar.setDocked(position); } }, onItemAdd: function(card) { var me = this; if (!card.isInnerItem()) { return me.callParent(arguments); } var tabBar = me.getTabBar(), initialConfig = card.getInitialConfig(), tabConfig = initialConfig.tab || {}, tabTitle = (card.getTitle) ? card.getTitle() : initialConfig.title, tabIconCls = (card.getIconCls) ? card.getIconCls() : initialConfig.iconCls, tabHidden = (card.getHidden) ? card.getHidden() : initialConfig.hidden, tabDisabled = (card.getDisabled) ? card.getDisabled() : initialConfig.disabled, tabBadgeText = (card.getBadgeText) ? card.getBadgeText() : initialConfig.badgeText, innerItems = me.getInnerItems(), index = innerItems.indexOf(card), tabs = tabBar.getItems(), activeTab = tabBar.getActiveTab(), currentTabInstance = (tabs.length >= innerItems.length) && tabs.getAt(index), tabInstance; if (tabTitle && !tabConfig.title) { tabConfig.title = tabTitle; } if (tabIconCls && !tabConfig.iconCls) { tabConfig.iconCls = tabIconCls; } if (tabHidden && !tabConfig.hidden) { tabConfig.hidden = tabHidden; } if (tabDisabled && !tabConfig.disabled) { tabConfig.disabled = tabDisabled; } if (tabBadgeText && !tabConfig.badgeText) { tabConfig.badgeText = tabBadgeText; } //<debug warn> if (!currentTabInstance && !tabConfig.title && !tabConfig.iconCls) { if (!tabConfig.title && !tabConfig.iconCls) { Ext.Logger.error('Adding a card to a tab container without specifying any tab configuration'); } } //</debug> tabInstance = Ext.factory(tabConfig, Ext.tab.Tab, currentTabInstance); if (!currentTabInstance) { tabBar.insert(index, tabInstance); } card.tab = tabInstance; me.callParent(arguments); if (!activeTab && activeTab !== 0) { tabBar.setActiveTab(tabBar.getActiveItem()); } }, /** * If an item gets enabled/disabled and it has an tab, we should also enable/disable that tab * @private */ onItemDisabledChange: function(item, newDisabled) { if (item && item.tab) { item.tab.setDisabled(newDisabled); } }, // @private onItemRemove: function(item, index) { this.getTabBar().remove(item.tab, this.getAutoDestroy()); this.callParent(arguments); } }, function() { //<deprecated product=touch since=2.0> /** * @cfg {Boolean} tabBarDock * @inheritdoc Ext.tab.Panel#tabBarPosition * @deprecated 2.0.0 Please use {@link #tabBarPosition} instead. */ Ext.deprecateProperty(this, 'tabBarDock', 'tabBarPosition'); //</deprecated> });
window.PerfHelpers = window.PerfHelpers || {}; ;(function(PerfHelpers) { var timers = {}; PerfHelpers = window.performance || {}; PerfHelpers.now = PerfHelpers.now || function () {}; if ((!console) || (!console.time)) { console.time = function() {}; console.timeEnd = function() {}; } var consoleTime = console.time.bind(window.console); var consoleTimeEnd = console.timeEnd.bind(window.console); console.time = function(key) { var phTimeKey = '[PHTime]' + key; timers[phTimeKey + '_start'] = PerfHelpers.now(); var _startDate = (new Date().toLocaleString()); timers[phTimeKey + '_startDate'] = _startDate; //console.log(phTimeKey + '[STARTED]: ' + _startDate); consoleTime(phTimeKey); }; console.timeEnd = function (key) { var phTimeKey = '[PHTime]' + key; var _startTime = timers[phTimeKey + '_start']; if (_startTime) { var _endDate = (new Date().toLocaleString()); var _endTime = PerfHelpers.now(); var _totalTime = _endTime - _startTime; delete timers[phTimeKey + '_start']; delete timers[phTimeKey + '_startDate']; //console.log(phTimeKey + '[ENDED]: ' + _endDate); consoleTimeEnd(phTimeKey); if ('ga' in window) { var alKey = 'ACT_' + key; var _roundedTime = Math.round(_totalTime); ga('send', 'timing', 'web-performance', alKey, _roundedTime, 'Total Time'); ga('send', { hitType: 'event', eventCategory: 'web-performance', eventAction: alKey, eventLabel: _endDate, eventValue: _roundedTime }); // console.debug('[GA][timing]:', 'send', 'event', 'web-performance', alKey, _endDate, _roundedTime); } return _totalTime; } else { return undefined; } }; })(window.PerfHelpers);
function preloadimages(n,o){function r(){++a>=e&&o(i)}var a=0,e=0,i=n instanceof Array?[]:{};for(var c in n)e++,i[c]=new Image,i[c].src=n[c],i[c].onload=r,i[c].onerror=r,i[c].onabort=r}
module.exports = function(locker) { /* locker.add(function(callback) { //Return content in format: callback({ name: "Vehicle Speed", type: "metric", content: { x: 0, y: 0, xtitle: "Time", ytitle: "Speed" }, tags: ["vehicle", "speed", "velocity", "car"] }); }); locker.add(function(callback) { //Return content in format: callback({ name: "Vehicle RPM", type: "metric", content: { x: 0, y: 0, xtitle: "Time", ytitle: "Revolutions Per Minute" }, tags: ["vehicle", "rpm", "revolutions", "car"] }); }); locker.add(function(callback) { callback({ name: "Image test", type: "image", content: { url: "http://24.media.tumblr.com/tumblr_mc6vgcDUEK1qmbg8bo1_500.jpg" }, tags: ["vehicle", "rpm", "revolutions", "car"] }); }); */ }
{ it("returns a key", () => { var nativeEvent = new KeyboardEvent("keypress", { key: "f" }); expect(getEventKey(nativeEvent)).toBe("f"); }); }
/** * A 32-bit unsigned bitfield that describes an entity's classification(s) * @typedef {number} EntityClass */ /** * Enumerate entity classes */ const ENTITY = { NULL: 0x00, // Base celestial classes ASTEROID: 0x01, // floating rock in space, orbits star COMET: 0x02, // an asteroid with a highly-eccentric orbit PLANET: 0x04, // a large celestial that orbits a star MOON: 0x08, // something that orbits a celestial that is not a star STAR: 0x10, // a luminous sphere of plasma, typically the center of a solar system BLACKHOLE: 0x20, // a object dense enough to maintain an event horizon // Celestial modifiers GAS: 0x40, // is a gas giant / gas world ICE: 0x80, // is an ice giant / ice world DESERT: 0x100, // is a desert world DWARF: 0x200, // is a "dwarf" in its category GIANT: 0x400, // is a "giant" in its category NEUTRON: 0x800, // is a composed of "neutronium" (ie neutron stars) // Empire Units VESSEL: 0x1000, // a vessel is any empire-made object, manned or unmanned SHIP: 0x2000, // a ship is a manned vessel equipped with engines DRONE: 0x4000, // a drone is an unmanned vessel equipped with engines STATION: 0x8000, // a station is a large habitable vessel with reduced maneuverability (if any) - can be orbital or ground-based MILITARY: 0x10000, // a military vessel belongs to an empire's military COLONY: 0x20000 // a colony is a ground-based civilian population }; /** * An Entity is any object representing something in the game world. This may include: planets, stars, starships, * cultures, empires, etc. */ class Entity { /** * Entity constructor method * @param {string} [name] * Defines the name of this entity * @param {Coord} [coords] * Defines the default coordinates of this entity * @param {EntityClass} [eClass] * Defines this entity's eClass */ constructor(name, coords, eClass) { /** The entity's non-unique name */ this.name = name || ""; /** The entity's class */ this.eClass = eClass || ENTITY.NULL; if(coords) { // Set this entity's location this.setPos(coords.xPos, coords.yPos, coords.system); } // Register this entity to LogicM LogicM.addEntity(this); } /** * * @param {number} [xPos=0] * The new x coordinate * @param {number} [yPos=0] * The new y coordinate * @param {string} [system] * The name of the star system */ setPos(xPos=0, yPos=0, system) { this.xPos = xPos; this.yPos = yPos; this.system = system || this.system; } } /** * A table describing an entity's display properties * * @typedef {Object} DisplayProperties * @property {number} radius - The entity's real radius, in km * @property {number} [minRadius=0] - The entity's minimum draw radius, in pixels * @property {string} [color=#ffffff] - The entity's draw color */ /** * A RenderEntity is an entity that structures render data. It can be drawn onto the screen. * @extends Entity */ class RenderEntity extends Entity { /** * RenderEntity constructor method * @param {string} name * Defines the name of this entity * @param {Coord} coords * Defines the default coordinates of this entity * @param {DisplayProperties} displayProps * Defines the default display properties * @param {EntityClass} [eClass] * Defines this entity's eClass */ constructor(name, coords, displayProps, eClass) { super(name, coords, eClass); /** Set to true if this entity can be rendered */ this.canRender = true; /** Entity's draw radius */ this.radius = displayProps.radius || 0; /** Entity's minimum radius */ this.minRadius = displayProps.minRadius || 0; /** Entity's draw color */ this.color = displayProps.color || 'white'; // Register this visible entity to the Logic Module if(LogicM.getViewingSystem() == coords.system) { RenderM.addRenderEntity(this); } } }
var _; //globals /* This section uses a functional extension known as Underscore.js - http://documentcloud.github.com/underscore/ "Underscore is a utility-belt library for JavaScript that provides a lot of the functional programming support that you would expect in Prototype.js (or Ruby), but without extending any of the built-in JavaScript objects. It's the tie to go along with jQuery's tux." */ describe("About Higher Order Functions", function () { it("should use filter to return array items that meet a criteria", function () { var numbers = [1,2,3]; var odd = _(numbers).filter(function (x) { return x % 2 !== 0 }); expect(odd).toEqual([1,3]); expect(odd.length).toBe(2); expect(numbers.length).toBe(3); }); it("should use 'map' to transform each element", function () { var numbers = [1, 2, 3]; var numbersPlus1 = _(numbers).map(function(x) { return x + 1 }); expect(numbersPlus1).toEqual([2,3,4]); expect(numbers).toEqual([1,2,3]); }); it("should use 'reduce' to update the same result on each iteration", function () { var numbers = [1, 2, 3]; var reduction = _(numbers).reduce( function(memo, x) { //note: memo is the result from last call, and x is the current number return memo + x; }, /* initial */ 0 ); expect(reduction).toBe(6); expect(numbers).toEqual([1,2,3]); }); it("should use 'forEach' for simple iteration", function () { var numbers = [1,2,3]; var msg = ""; var isEven = function (item) { msg += (item % 2) === 0; }; _(numbers).forEach(isEven); expect(msg).toEqual('falsetruefalse'); expect(numbers).toEqual([1,2,3]); }); it("should use 'all' to test whether all items pass condition", function () { var onlyEven = [2,4,6]; var mixedBag = [2,4,5,6]; var isEven = function(x) { return x % 2 === 0 }; expect(_(onlyEven).all(isEven)).toBe(true); expect(_(mixedBag).all(isEven)).toBe(false); }); it("should use 'any' to test if any items passes condition" , function () { var onlyEven = [2,4,6]; var mixedBag = [2,4,5,6]; var isEven = function(x) { return x % 2 === 0 }; expect(_(onlyEven).any(isEven)).toBe(true); expect(_(mixedBag).any(isEven)).toBe(true); }); it("should use range to generate an array", function() { expect(_.range(3)).toEqual([0, 1, 2]); expect(_.range(1, 4)).toEqual([1, 2, 3]); expect(_.range(0, -4, -1)).toEqual([0, -1, -2, -3]); }); it("should use flatten to make nested arrays easy to work with", function() { expect(_([ [1, 2], [3, 4] ]).flatten()).toEqual([1,2,3,4]); }); it("should use chain() ... .value() to use multiple higher order functions", function() { var result = _([ [0, 1], 2 ]).chain() .flatten() .map(function(x) { return x+1 } ) .reduce(function (sum, x) { return sum + x }) .value(); expect(result).toEqual(6); }); });
const autoAdjustOverflow = { adjustX: 1, adjustY: 1 } const targetOffset = [0, 0] export const placements = { left: { points: ['cr', 'cl'], overflow: autoAdjustOverflow, offset: [-3, 0], targetOffset }, right: { points: ['cl', 'cr'], overflow: autoAdjustOverflow, offset: [3, 0], targetOffset }, top: { points: ['bc', 'tc'], overflow: autoAdjustOverflow, offset: [0, -3], targetOffset }, bottom: { points: ['tc', 'bc'], overflow: autoAdjustOverflow, offset: [0, 3], targetOffset }, topLeft: { points: ['bl', 'tl'], overflow: autoAdjustOverflow, offset: [0, -3], targetOffset }, leftTop: { points: ['tr', 'tl'], overflow: autoAdjustOverflow, offset: [-3, 0], targetOffset }, topRight: { points: ['br', 'tr'], overflow: autoAdjustOverflow, offset: [0, -3], targetOffset }, rightTop: { points: ['tl', 'tr'], overflow: autoAdjustOverflow, offset: [3, 0], targetOffset }, bottomRight: { points: ['tr', 'br'], overflow: autoAdjustOverflow, offset: [0, 3], targetOffset }, rightBottom: { points: ['bl', 'br'], overflow: autoAdjustOverflow, offset: [3, 0], targetOffset }, bottomLeft: { points: ['tl', 'bl'], overflow: autoAdjustOverflow, offset: [0, 3], targetOffset }, leftBottom: { points: ['br', 'bl'], overflow: autoAdjustOverflow, offset: [-3, 0], targetOffset } } export default placements
'use strict'; function removeIndex(key, id, callback) { var client = this._; client.del(key + ':' + id + '@index', callback); } module.exports = removeIndex;
/* FTUI Plugin * Copyright (c) 2016 Mario Stephan <[email protected]> * Under MIT License (http://www.opensource.org/licenses/mit-license.php) */ /* global ftui:true, Modul_widget:true */ "use strict"; var Modul_medialist = function () { $('head').append('<link rel="stylesheet" href="' + ftui.config.dir + '/../css/ftui_medialist.css" type="text/css" />'); function changedCurrent(elem, pos) { elem.find('.media').each(function (index) { $(this).removeClass('current'); }); var idx = elem.hasClass('index1') ? pos - 1 : pos; var currentElem = elem.find('.media').eq(idx); if (currentElem.length > 0) { currentElem.addClass("current"); if (elem.hasClass("autoscroll")) { elem.scrollTop(currentElem.offset().top - elem.offset().top + elem.scrollTop()); } } } function init_attr(elem) { elem.initData('get', 'STATE'); elem.initData('set', 'play'); elem.initData('pos', 'Pos'); elem.initData('cmd', 'set'); elem.initData('color', ftui.getClassColor(elem) || ftui.getStyle('.' + me.widgetname, 'color') || '#222'); elem.initData('background-color', ftui.getStyle('.' + me.widgetname, 'background-color') || 'transparent'); elem.initData('text-color', ftui.getStyle('.' + me.widgetname, 'text-color') || '#ddd'); elem.initData('width', '90%'); elem.initData('height', '80%'); me.addReading(elem, 'get'); me.addReading(elem, 'pos'); } function init_ui(elem) { // prepare container element var width = elem.data('width'); var widthUnit = ($.isNumeric(width)) ? 'px' : ''; var height = elem.data('height'); var heightUnit = ($.isNumeric(height)) ? 'px' : ''; elem.html('') .addClass('media-list') .css({ width: width + widthUnit, maxWidth: width + widthUnit, height: height + heightUnit, color: elem.mappedColor('text-color'), backgroundColor: elem.mappedColor('background-color'), }); elem.on('click', '.media', function (index) { elem.data('value', elem.hasClass('index1') ? $(this).index() + 1 : $(this).index()); elem.transmitCommand(); }); } function update(dev, par) { // update medialist reading me.elements.filterDeviceReading('get', dev, par) .each(function (index) { var elem = $(this); var list = elem.getReading('get').val; var pos = elem.getReading('pos').val; if (ftui.isValid(list)) { elem.html(''); var text = ''; try { var collection = JSON.parse(list); for (var idx in collection) { var media = collection[idx]; text += '<div class="media">'; text += '<div class="media-image">'; text += '<img class="cover" src="' + media.Cover + '"/>'; text += '</div>'; text += '<div class="media-text">'; text += '<div class="title" data-track="' + media.Track + '">' + media.Title + '</div>'; text += '<div class="artist">' + media.Artist + '</div>'; text += '<div class="duration">' + ftui.durationFromSeconds(media.Time) + '</div>'; text += '</div></div>'; } } catch (e) { ftui.log(1, 'widget-' + me.widgetname + ': error:' + e); ftui.log(1, list); ftui.toast('<b>widget-' + me.widgetname + '</b><br>' + e, 'error'); } elem.append(text).fadeIn(); } if (pos) { changedCurrent(elem, pos); } }); //extra reading for current position me.elements.filterDeviceReading('pos', dev, par) .each(function (idx) { var elem = $(this); var pos = elem.getReading('pos').val; if (ftui.isValid(pos)){ changedCurrent(elem, pos); } }); } // public // inherit members from base class var me = $.extend(new Modul_widget(), { //override members widgetname: 'medialist', init_attr: init_attr, init_ui: init_ui, update: update, }); return me; };
version https://git-lfs.github.com/spec/v1 oid sha256:2d79d4ce9f72e0b9db16aee949410ecd30bfcfb5205af39053f05ac39083e151 size 22425
module.exports = function (grunt) { // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), requirejs: { compile: { options: { shim: { grape: { exports: 'Grape' } }, paths:{ grape:'../../../../dist/grape.min' }, baseUrl: "js", name: "../node_modules/almond/almond", include: ["pong"], out: "build/pong.min.js", optimize: 'uglify2', logLevel: 3, uglify2: { output: { beautify: true }, compress: { sequences: false }, warnings: true, mangle: false } } } } }); grunt.loadNpmTasks('grunt-contrib-requirejs'); grunt.registerTask('default', ['requirejs']); };
'unit tests'; module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: './src', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['mocha', 'chai', 'sinon', 'browserify'], browserify: { debug: true, transform: ['browserify-shim'], plugin: ['stringify'] }, // list of files / patterns to load in the browser files: [ '../test/**/*Test.js', {pattern: '**/*.js', included: false, load: false}, {pattern: '../test/**/*Test.js', included: false, load: false}, ], // list of files to exclude exclude: [ 'gulpfile.js' ], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { '../test/**/*Test.js': ['browserify'] }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['mocha'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: false, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['Chrome'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: true, // capture console.log client: { captureConsole: true } }); };
const FeedParser = require("feedparser"); const request = require("request"); const Promise = require("bluebird"); const flatten = require("lodash").flatten; const nodemailer = require("nodemailer"); const cfg = require("dotenv").config(); const readUrls = require("./urls.json"); const EMAIL_OPTIONS = { host: "smtp.gmail.com", port: 465, secure: true, auth: { user: cfg.EMAIL, pass: cfg.APP_PASS } }; const urls = Object.keys(readUrls).filter((url) => readUrls[url]); Promise.map(urls, (url) => { return new Promise((resolve, reject) => { const items = []; const req = request(url); const feeder = new FeedParser(); req.on("error", reject); req.on('response', function (res) { if (res.statusCode != 200) return reject(new Error("Something went wrong.")); res.pipe(feeder); }); feeder.on("error", reject); feeder.on("readable", function () { let item; while (item = this.read()) { items.push(item); } }); feeder.on("end", () => { return resolve(items.map((item) => { return { title: item.title, link: item.link }; })); }); }); }).then(flatten).then(email).catch(console.error); function email(items) { const transporter = nodemailer.createTransport(EMAIL_OPTIONS); const mail = { from: cfg.EMAIL, to: cfg.EMAIL, subject: "New Craigslist Finds", html: items.map((item) => `<a href=${item.link}>${item.title}</a>`).join("<br /><br />") }; transporter.sendMail(mail, (err, info) => { if (err) { return console.error(err); } console.log("Mail Sent: " + info.response); }); }
const {Scene, Sprite} = spritejs; const container = document.getElementById('stage'); const scene = new Scene({ container, width: 1200, height: 600, // contextType: '2d', }); const layer = scene.layer(); (async function () { const sprite = new Sprite({ anchor: 0.5, bgcolor: 'red', pos: [500, 300], size: [200, 200], borderRadius: 50, }); layer.append(sprite); await sprite.transition(2.0) .attr({ bgcolor: 'green', width: width => width + 100, }); await sprite.transition(1.0) .attr({ bgcolor: 'orange', height: height => height + 100, }); }());
import webpack from 'webpack'; import path from 'path'; export default { debug: true, devtool: 'cheap-module-eval-source-map', noInfo: false, entry: [ // 'eventsource-polyfill', // necessary for hot reloading with IE 'webpack-hot-middleware/client?reload=true', //note that it reloads the page if hot module reloading fails. './src/index' ], target: 'web', output: { path: __dirname + '/dist', // Note: Physical files are only output by the production build task `npm run build`. publicPath: '/', filename: 'bundle.js' }, devServer: { contentBase: './src' }, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin() ], module: { loaders: [ {test: /\.js$/, include: path.join(__dirname, 'src'), loaders: ['babel']}, {test: /(\.css)$/, loaders: ['style', 'css']}, {test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file"}, {test: /\.(woff|woff2)$/, loader: "url?prefix=font/&limit=5000"}, {test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/octet-stream"}, {test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=image/svg+xml"} ] } };
/* Copyright (c) 2004-2012, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ if(!dojo._hasResource["dojox.gfx.silverlight_attach"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code. dojo._hasResource["dojox.gfx.silverlight_attach"] = true; dojo.provide("dojox.gfx.silverlight_attach"); dojo.require("dojox.gfx.silverlight"); dojo.experimental("dojox.gfx.silverlight_attach"); (function(){ var g = dojox.gfx, sl = g.silverlight; sl.attachNode = function(node){ // summary: creates a shape from a Node // node: Node: an Silverlight node return null; // not implemented }; sl.attachSurface = function(node){ // summary: creates a surface from a Node // node: Node: an Silverlight node return null; // dojox.gfx.Surface }; })(); }
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './components/App'; import Greetings from './components/Greetings'; import SignupPage from './components/signup/SignupPage' export default ( <Route path="/" component={App}> <IndexRoute component={Greetings}/> //make all main routes components as class components <Route path="signup" component={SignupPage}/> </Route> )
(function() { 'use strict'; angular .module('tiny-leaflet-directive') .factory('tldMapService', tldMapService); tldMapService.$inject = ['tldHelpers']; function tldMapService(tldHelpers) { var maps = {}; return { setMap: setMap, getMap: getMap, unresolveMap: unresolveMap }; function setMap(leafletMap, mapId) { var defer = tldHelpers.getUnresolvedDefer(maps, mapId); defer.resolve(leafletMap); tldHelpers.setResolvedDefer(maps, mapId); } function getMap (mapId) { var defer = tldHelpers.getDefer(maps, mapId); return defer.promise; } function unresolveMap(mapId) { maps[mapId] = undefined; } } })();
/*eslint-disable react/prop-types*/ import React, { Component } from 'react' import ReactDOM from 'react-dom' import { createStore } from 'redux' import { Provider, connect, ReactReduxContext } from '../../src/index.js' import * as rtl from '@testing-library/react' import '@testing-library/jest-dom/extend-expect' const createExampleTextReducer = () => (state = 'example text') => state describe('React', () => { describe('Provider', () => { afterEach(() => rtl.cleanup()) const createChild = (storeKey = 'store') => { class Child extends Component { render() { return ( <ReactReduxContext.Consumer> {({ store }) => { let text = '' if (store) { text = store.getState().toString() } return ( <div data-testid="store"> {storeKey} - {text} </div> ) }} </ReactReduxContext.Consumer> ) } } return Child } const Child = createChild() it('should not enforce a single child', () => { const store = createStore(() => ({})) // Ignore propTypes warnings const propTypes = Provider.propTypes Provider.propTypes = {} const spy = jest.spyOn(console, 'error').mockImplementation(() => {}) expect(() => rtl.render( <Provider store={store}> <div /> </Provider> ) ).not.toThrow() expect(() => rtl.render(<Provider store={store} />)).not.toThrow( /children with exactly one child/ ) expect(() => rtl.render( <Provider store={store}> <div /> <div /> </Provider> ) ).not.toThrow(/a single React element child/) spy.mockRestore() Provider.propTypes = propTypes }) it('should add the store to context', () => { const store = createStore(createExampleTextReducer()) const spy = jest.spyOn(console, 'error').mockImplementation(() => {}) const tester = rtl.render( <Provider store={store}> <Child /> </Provider> ) expect(spy).toHaveBeenCalledTimes(0) spy.mockRestore() expect(tester.getByTestId('store')).toHaveTextContent( 'store - example text' ) }) it('accepts new store in props', () => { const store1 = createStore((state = 10) => state + 1) const store2 = createStore((state = 10) => state * 2) const store3 = createStore((state = 10) => state * state + 1) let externalSetState class ProviderContainer extends Component { constructor() { super() this.state = { store: store1 } externalSetState = this.setState.bind(this) } render() { return ( <Provider store={this.state.store}> <Child /> </Provider> ) } } const tester = rtl.render(<ProviderContainer />) expect(tester.getByTestId('store')).toHaveTextContent('store - 11') rtl.act(() => { externalSetState({ store: store2 }) }) expect(tester.getByTestId('store')).toHaveTextContent('store - 20') rtl.act(() => { store1.dispatch({ type: 'hi' }) }) expect(tester.getByTestId('store')).toHaveTextContent('store - 20') rtl.act(() => { store2.dispatch({ type: 'hi' }) }) expect(tester.getByTestId('store')).toHaveTextContent('store - 20') rtl.act(() => { externalSetState({ store: store3 }) }) expect(tester.getByTestId('store')).toHaveTextContent('store - 101') rtl.act(() => { store1.dispatch({ type: 'hi' }) }) expect(tester.getByTestId('store')).toHaveTextContent('store - 101') rtl.act(() => { store2.dispatch({ type: 'hi' }) }) expect(tester.getByTestId('store')).toHaveTextContent('store - 101') rtl.act(() => { store3.dispatch({ type: 'hi' }) }) expect(tester.getByTestId('store')).toHaveTextContent('store - 101') }) it('should handle subscriptions correctly when there is nested Providers', () => { const reducer = (state = 0, action) => action.type === 'INC' ? state + 1 : state const innerStore = createStore(reducer) const innerMapStateToProps = jest.fn((state) => ({ count: state })) @connect(innerMapStateToProps) class Inner extends Component { render() { return <div>{this.props.count}</div> } } const outerStore = createStore(reducer) @connect((state) => ({ count: state })) class Outer extends Component { render() { return ( <Provider store={innerStore}> <Inner /> </Provider> ) } } rtl.render( <Provider store={outerStore}> <Outer /> </Provider> ) expect(innerMapStateToProps).toHaveBeenCalledTimes(1) rtl.act(() => { innerStore.dispatch({ type: 'INC' }) }) expect(innerMapStateToProps).toHaveBeenCalledTimes(2) }) it('should pass state consistently to mapState', () => { function stringBuilder(prev = '', action) { return action.type === 'APPEND' ? prev + action.body : prev } const store = createStore(stringBuilder) rtl.act(() => { store.dispatch({ type: 'APPEND', body: 'a' }) }) let childMapStateInvokes = 0 @connect((state) => ({ state })) class Container extends Component { emitChange() { store.dispatch({ type: 'APPEND', body: 'b' }) } render() { return ( <div> <button onClick={this.emitChange.bind(this)}>change</button> <ChildContainer parentState={this.props.state} /> </div> ) } } const childCalls = [] @connect((state, parentProps) => { childMapStateInvokes++ childCalls.push([state, parentProps.parentState]) // The state from parent props should always be consistent with the current state return {} }) class ChildContainer extends Component { render() { return <div /> } } const tester = rtl.render( <Provider store={store}> <Container /> </Provider> ) expect(childMapStateInvokes).toBe(1) // The store state stays consistent when setState calls are batched rtl.act(() => { store.dispatch({ type: 'APPEND', body: 'c' }) }) expect(childMapStateInvokes).toBe(2) expect(childCalls).toEqual([ ['a', 'a'], ['ac', 'ac'], ]) // setState calls DOM handlers are batched const button = tester.getByText('change') rtl.fireEvent.click(button) expect(childMapStateInvokes).toBe(3) // Provider uses unstable_batchedUpdates() under the hood rtl.act(() => { store.dispatch({ type: 'APPEND', body: 'd' }) }) expect(childCalls).toEqual([ ['a', 'a'], ['ac', 'ac'], // then store update is processed ['acb', 'acb'], // then store update is processed ['acbd', 'acbd'], // then store update is processed ]) expect(childMapStateInvokes).toBe(4) }) it('works in <StrictMode> without warnings (React 16.3+)', () => { if (!React.StrictMode) { return } const spy = jest.spyOn(console, 'error').mockImplementation(() => {}) const store = createStore(() => ({})) rtl.render( <React.StrictMode> <Provider store={store}> <div /> </Provider> </React.StrictMode> ) expect(spy).not.toHaveBeenCalled() }) it.skip('should unsubscribe before unmounting', () => { const store = createStore(createExampleTextReducer()) const subscribe = store.subscribe // Keep track of unsubscribe by wrapping subscribe() const spy = jest.fn(() => ({})) store.subscribe = (listener) => { const unsubscribe = subscribe(listener) return () => { spy() return unsubscribe() } } const div = document.createElement('div') ReactDOM.render( <Provider store={store}> <div /> </Provider>, div ) expect(spy).toHaveBeenCalledTimes(0) ReactDOM.unmountComponentAtNode(div) expect(spy).toHaveBeenCalledTimes(1) }) it('should handle store and children change in a the same render', () => { const reducerA = (state = { nestedA: { value: 'expectedA' } }) => state const reducerB = (state = { nestedB: { value: 'expectedB' } }) => state const storeA = createStore(reducerA) const storeB = createStore(reducerB) @connect((state) => ({ value: state.nestedA.value })) class ComponentA extends Component { render() { return <div data-testid="value">{this.props.value}</div> } } @connect((state) => ({ value: state.nestedB.value })) class ComponentB extends Component { render() { return <div data-testid="value">{this.props.value}</div> } } const { getByTestId, rerender } = rtl.render( <Provider store={storeA}> <ComponentA /> </Provider> ) expect(getByTestId('value')).toHaveTextContent('expectedA') rerender( <Provider store={storeB}> <ComponentB /> </Provider> ) expect(getByTestId('value')).toHaveTextContent('expectedB') }) }) })
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import styles from '../../build/styles'; export default class Subtitle extends Component { static propTypes = { children: PropTypes.any, className: PropTypes.string, size: PropTypes.oneOf([ 'is1', 'is2', 'is3', 'is4', 'is5', 'is6', ]), }; static defaultProps = { className: '', }; createClassName() { return [ styles.subtitle, styles[this.props.size], this.props.className, ].join(' ').trim(); } render() { return ( <p {...this.props} className={this.createClassName()}> {this.props.children} </p> ); } }
define(function(require, exports, module) { var Notify = require('common/bootstrap-notify'); exports.run = function() { var $form = $("#user-roles-form"), isTeacher = $form.find('input[value=ROLE_TEACHER]').prop('checked'), currentUser = $form.data('currentuser'), editUser = $form.data('edituser'); if (currentUser == editUser) { $form.find('input[value=ROLE_SUPER_ADMIN]').attr('disabled', 'disabled'); }; $form.find('input[value=ROLE_USER]').on('change', function(){ if ($(this).prop('checked') === false) { $(this).prop('checked', true); var user_name = $('#change-user-roles-btn').data('user') ; Notify.info('用户必须拥有'+user_name+'角色'); } }); $form.on('submit', function() { var roles = []; var $modal = $('#modal'); $form.find('input[name="roles[]"]:checked').each(function(){ roles.push($(this).val()); }); if ($.inArray('ROLE_USER', roles) < 0) { var user_name = $('#change-user-roles-btn').data('user') ; Notify.danger('用户必须拥有'+user_name+'角色'); return false; } if (isTeacher && $.inArray('ROLE_TEACHER', roles) < 0) { if (!confirm('取消该用户的教师角色,同时将收回该用户所有教授的课程的教师权限。您真的要这么做吗?')) { return false; } } $form.find('input[value=ROLE_SUPER_ADMIN]').removeAttr('disabled'); $('#change-user-roles-btn').button('submiting').addClass('disabled'); $.post($form.attr('action'), $form.serialize(), function(html) { $modal.modal('hide'); Notify.success('用户组保存成功'); var $tr = $(html); $('#' + $tr.attr('id')).replaceWith($tr); }).error(function(){ Notify.danger('操作失败'); }); return false; }); }; });
/** * Test async injectors */ import { memoryHistory } from 'react-router'; import { put } from 'redux-saga/effects'; import { fromJS } from 'immutable'; import configureStore from 'store'; import { injectAsyncReducer, injectAsyncSagas, getAsyncInjectors, } from '../asyncInjectors'; // Fixtures const initialState = fromJS({ reduced: 'soon' }); const reducer = (state = initialState, action) => { switch (action.type) { case 'TEST': return state.set('reduced', action.payload); default: return state; } }; function* testSaga() { yield put({ type: 'TEST', payload: 'yup' }); } const sagas = [ testSaga, ]; describe('asyncInjectors', () => { let store; describe('getAsyncInjectors', () => { beforeAll(() => { store = configureStore({}, memoryHistory); }); it('given a store, should return all async injectors', () => { const { injectReducer, injectSagas } = getAsyncInjectors(store); injectReducer('test', reducer); injectSagas(sagas); const actual = store.getState().get('test'); const expected = initialState.merge({ reduced: 'yup' }); expect(actual.toJS()).toEqual(expected.toJS()); }); it('should throw if passed invalid store shape', () => { let result = false; Reflect.deleteProperty(store, 'dispatch'); try { getAsyncInjectors(store); } catch (err) { result = err.name === 'Invariant Violation'; } expect(result).toEqual(true); }); }); describe('helpers', () => { beforeAll(() => { store = configureStore({}, memoryHistory); }); describe('injectAsyncReducer', () => { it('given a store, it should provide a function to inject a reducer', () => { const injectReducer = injectAsyncReducer(store); injectReducer('test', reducer); const actual = store.getState().get('test'); const expected = initialState; expect(actual.toJS()).toEqual(expected.toJS()); }); it('should not assign reducer if already existing', () => { const injectReducer = injectAsyncReducer(store); injectReducer('test', reducer); injectReducer('test', () => {}); expect(store.asyncReducers.test.toString()).toEqual(reducer.toString()); }); it('should throw if passed invalid name', () => { let result = false; const injectReducer = injectAsyncReducer(store); try { injectReducer('', reducer); } catch (err) { result = err.name === 'Invariant Violation'; } try { injectReducer(999, reducer); } catch (err) { result = err.name === 'Invariant Violation'; } expect(result).toEqual(true); }); it('should throw if passed invalid reducer', () => { let result = false; const injectReducer = injectAsyncReducer(store); try { injectReducer('bad', 'nope'); } catch (err) { result = err.name === 'Invariant Violation'; } try { injectReducer('coolio', 12345); } catch (err) { result = err.name === 'Invariant Violation'; } expect(result).toEqual(true); }); }); describe('injectAsyncSagas', () => { it('given a store, it should provide a function to inject a saga', () => { const injectSagas = injectAsyncSagas(store); injectSagas(sagas); const actual = store.getState().get('test'); const expected = initialState.merge({ reduced: 'yup' }); expect(actual.toJS()).toEqual(expected.toJS()); }); it('should throw if passed invalid saga', () => { let result = false; const injectSagas = injectAsyncSagas(store); try { injectSagas({ testSaga }); } catch (err) { result = err.name === 'Invariant Violation'; } try { injectSagas(testSaga); } catch (err) { result = err.name === 'Invariant Violation'; } expect(result).toEqual(true); }); }); }); });
module.exports = function (grunt) { "use strict"; grunt.initConfig({ pkg: grunt.file.readJSON("package.json"), // grunt-contrib-clean clean: { instrument: "<%= instrument.options.basePath %>" }, // grunt-contrib-jshint jshint: { files: [ "<%= instrument.files %>", "<%= mochaTest.test.src %>", "bin/**.js", "gruntfile.js", "node_tests/**/*.js" ], options: grunt.file.readJSON(".jshintrc") }, // grunt-mocha-test mochaTest: { test: { options: { reporter: "spec" }, src: "node_tests/**/*.test.js" } }, // grunt-contrib-watch watch: { files: ["<%= jshint.files %>"], tasks: ["beautify", "test"] }, // grunt-istanbul instrument: { files: "node_libs/**/*.js", options: { basePath: "coverage/instrument/" } }, storeCoverage: { options: { dir: "coverage/reports/<%= pkg.version %>" } }, makeReport: { src: "<%= storeCoverage.options.dir %>/*.json", options: { type: "lcov", dir: "<%= storeCoverage.options.dir %>", print: "detail" } }, // grunt-jsbeautifier jsbeautifier: { files: ["<%= jshint.files %>"], options: { js: grunt.file.readJSON(".jsbeautifyrc") } } }); grunt.loadNpmTasks("grunt-contrib-clean"); grunt.loadNpmTasks("grunt-contrib-jshint"); grunt.loadNpmTasks("grunt-contrib-watch"); grunt.loadNpmTasks("grunt-istanbul"); grunt.loadNpmTasks("grunt-jsbeautifier"); grunt.loadNpmTasks("grunt-mocha-test"); grunt.registerTask("register_globals", function (task) { var moduleRoot; if ("coverage" === task) { moduleRoot = __dirname + "/" + grunt.template.process("<%= instrument.options.basePath %>"); } else if ("test" === task) { moduleRoot = __dirname; } global.MODULE_ROOT = moduleRoot; global.MODULE_ROOT_TESTS = __dirname + "/node_tests"; }); grunt.registerTask("beautify", ["jsbeautifier"]); grunt.registerTask("cover", ["register_globals:coverage", "clean:instrument", "instrument", "lint", "mochaTest", "storeCoverage", "makeReport"]); grunt.registerTask("lint", ["jshint"]); grunt.registerTask("test", ["register_globals:test", "clean:instrument", "lint", "mochaTest"]); grunt.registerTask("default", ["jsbeautifier", "test"]); };
const EventEmitter = require('events'); /** * Ends the session. Uses session protocol command. * * @example * this.demoTest = function (browser) { * browser.end(); * }; * * @method end * @syntax .end([callback]) * @param {function} [callback] Optional callback function to be called when the command finishes. * @see session * @api protocol.sessions */ class End extends EventEmitter { command(callback) { const client = this.client; if (this.api.sessionId) { this.api.session('delete', result => { client.session.clearSession(); client.setApiProperty('sessionId', null); this.complete(callback, result); }); } else { setImmediate(() => { this.complete(callback, null); }); } return this.client.api; } complete(callback, result) { if (typeof callback === 'function') { callback.call(this.api, result); } this.emit('complete'); } } module.exports = End;
import Botkit from 'botkit'; import os from 'os'; import Wit from 'botkit-middleware-witai'; import moment from 'moment-timezone'; import models from '../../app/models'; import storageCreator from '../lib/storage'; import setupReceiveMiddleware from '../middleware/receiveMiddleware'; import notWitController from './notWit'; import miscController from './misc'; import sessionsController from './sessions'; import pingsController from './pings'; import slashController from './slash'; import dashboardController from './dashboard'; import { seedAndUpdateUsers } from '../../app/scripts'; require('dotenv').config(); var env = process.env.NODE_ENV || 'development'; if (env == 'development') { process.env.SLACK_ID = process.env.DEV_SLACK_ID; process.env.SLACK_SECRET = process.env.DEV_SLACK_SECRET; } // actions import { firstInstallInitiateConversation, loginInitiateConversation } from '../actions'; // Wit Brain if (process.env.WIT_TOKEN) { var wit = Wit({ token: process.env.WIT_TOKEN, minimum_confidence: 0.55 }); } else { console.log('Error: Specify WIT_TOKEN in environment'); process.exit(1); } export { wit }; /** * *** CONFIG **** */ var config = {}; const storage = storageCreator(config); var controller = Botkit.slackbot({ interactive_replies: true, storage }); export { controller }; /** * User has joined slack channel ==> make connection * then onboard! */ controller.on('team_join', function (bot, message) { console.log("\n\n\n ~~ joined the team ~~ \n\n\n"); const SlackUserId = message.user.id; console.log(message.user.id); bot.api.users.info({ user: SlackUserId }, (err, response) => { if (!err) { const { user, user: { id, team_id, name, tz } } = response; const email = user.profile && user.profile.email ? user.profile.email : ''; models.User.find({ where: { SlackUserId }, }) .then((user) => { if (!user) { models.User.create({ TeamId: team_id, email, tz, SlackUserId, SlackName: name }); } else { user.update({ TeamId: team_id, SlackName: name }) } }); } }); }); /** * User has updated data ==> update our DB! */ controller.on('user_change', function (bot, message) { console.log("\n\n\n ~~ user updated profile ~~ \n\n\n"); if (message && message.user) { const { user, user: { name, id, team_id, tz } } = message; const SlackUserId = id; const email = user.profile && user.profile.email ? user.profile.email : ''; models.User.find({ where: { SlackUserId }, }) .then((user) => { if (!user) { models.User.create({ TeamId: team_id, email, tz, SlackUserId, SlackName: name }); } else { user.update({ TeamId: team_id, SlackName: name }) } }); } }); // simple way to keep track of bots export var bots = {}; if (!process.env.SLACK_ID || !process.env.SLACK_SECRET || !process.env.HTTP_PORT) { console.log('Error: Specify SLACK_ID SLACK_SECRET and HTTP_PORT in environment'); process.exit(1); } // Custom Toki Config export function customConfigBot(controller) { // beef up the bot setupReceiveMiddleware(controller); notWitController(controller); dashboardController(controller); pingsController(controller); sessionsController(controller); slashController(controller); miscController(controller); } // try to avoid repeat RTM's export function trackBot(bot) { bots[bot.config.token] = bot; } /** * *** TURN ON THE BOT **** * VIA SIGNUP OR LOGIN */ export function connectOnInstall(team_config) { console.log(`\n\n\n\n CONNECTING ON INSTALL \n\n\n\n`); let bot = controller.spawn(team_config); controller.trigger('create_bot', [bot, team_config]); } export function connectOnLogin(identity) { // bot already exists, get bot token for this users team var SlackUserId = identity.user_id; var TeamId = identity.team_id; models.Team.find({ where: { TeamId } }) .then((team) => { const { token } = team; if (token) { var bot = controller.spawn({ token }); controller.trigger('login_bot', [bot, identity]); } }) } controller.on('rtm_open',function(bot) { console.log(`\n\n\n\n** The RTM api just connected! for bot token: ${bot.config.token}\n\n\n`); }); // upon install controller.on('create_bot', (bot,team) => { const { id, url, name, bot: { token, user_id, createdBy, accessToken, scopes } } = team; // this is what is used to save team data const teamConfig = { TeamId: id, createdBy, url, name, token, scopes, accessToken } if (bots[bot.config.token]) { // already online! do nothing. console.log("already online! restarting bot due to re-install"); // restart the bot bots[bot.config.token].closeRTM(); } bot.startRTM((err) => { if (!err) { console.log("\n\n RTM on with team install and listening \n\n"); trackBot(bot); controller.saveTeam(teamConfig, (err, id) => { if (err) { console.log("Error saving team") } else { console.log("Team " + team.name + " saved"); console.log(`\n\n installing users... \n\n`); bot.api.users.list({}, (err, response) => { if (!err) { const { members } = response; seedAndUpdateUsers(members); } firstInstallInitiateConversation(bot, team); }); } }); } else { console.log("RTM failed") } }); }); // subsequent logins controller.on('login_bot', (bot,identity) => { if (bots[bot.config.token]) { // already online! do nothing. console.log("already online! do nothing."); loginInitiateConversation(bot, identity); } else { bot.startRTM((err) => { if (!err) { console.log("RTM on and listening"); trackBot(bot); loginInitiateConversation(bot, identity); } else { console.log("RTM failed") console.log(err); } }); } });
/** Create by Huy: [email protected] ~ [email protected] 07/31/2015 */ define(["durandal/app", "knockout", "bootstrap", "viewmodels/component-4"], function (app, ko, bootstrap, Component4) { return function () { var me = this; var dashboardViewModel = this; dashboardViewModel.compoment4 = ko.observable(); dashboardViewModel.activate = function () { me.compoment4(new Component4(0)) } } });
/* ************************************************************************ Copyright (c) 2013 UBINITY SAS Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ************************************************************************* */ var ChromeapiPlugupCardTerminalFactory = Class.extend(CardTerminalFactory, { /** @lends ChromeapiPlugupCardTerminalFactory.prototype */ /** * @class Implementation of the {@link CardTerminalFactory} using the Chrome API for Plug-up Dongle * @constructs * @augments CardTerminalFactory */ initialize: function(pid, usagePage, ledgerTransport, vid) { this.pid = pid; this.vid = vid; this.usagePage = usagePage; this.ledgerTransport = ledgerTransport; }, list_async: function(pid, usagePage) { if (typeof chromeDevice == "undefined") { throw "Content script is not available"; } return chromeDevice.enumerateDongles_async(this.pid, this.usagePage, this.vid) .then(function(result) { return result.deviceList; }); }, waitInserted: function() { throw "Not implemented" }, getCardTerminal: function(device) { return new ChromeapiPlugupCardTerminal(device, undefined, this.ledgerTransport); } });
'use strict'; /** * Created by Alex Levshin on 26/11/16. */ var RootFolder = process.env.ROOT_FOLDER; if (!global.rootRequire) { global.rootRequire = function (name) { return require(RootFolder + '/' + name); }; } var restify = require('restify'); var _ = require('lodash'); var fs = require('fs'); var expect = require('chai').expect; var ApiPrefix = '/api/v1'; var Promise = require('promise'); var config = rootRequire('config'); var util = require('util'); var WorktyRepositoryCodePath = RootFolder + '/workties-repository'; var SubVersion = config.restapi.getLatestVersion().sub; // YYYY.M.D // Init the test client using supervisor account (all acl permissions) var adminClient = restify.createJsonClient({ version: SubVersion, url: config.restapi.getConnectionString(), headers: { 'Authorization': config.supervisor.getAuthorizationBasic() // supervisor }, rejectUnauthorized: false }); describe('Workflow Rest API', function () { var WorkflowsPerPage = 3; var Workflows = []; var WorktiesPerPage = 2; var Workties = []; var WorktiesInstances = []; var WORKTIES_FILENAMES = ['unsorted/nodejs/unit-tests/without-delay.zip']; console.log('Run Workflow API tests for version ' + ApiPrefix + '/' + SubVersion); function _createPromises(callback, count) { var promises = []; for (var idx = 0; idx < count; idx++) { promises.push(callback(idx)); } return promises; } function _createWorkty(idx) { return new Promise(function (resolve, reject) { try { var compressedCode = fs.readFileSync(WorktyRepositoryCodePath + '/' + WORKTIES_FILENAMES[0]); adminClient.post(ApiPrefix + '/workties', { name: 'myworkty' + idx, desc: 'worktydesc' + idx, compressedCode: compressedCode, template: true }, function (err, req, res, data) { var workty = data; adminClient.post(ApiPrefix + '/workties/' + data._id + '/properties', { property: { name: 'PropertyName', value: 'PropertyValue' } }, function (err, req, res, data) { workty.propertiesIds = [data]; resolve({res: res, data: workty}); }); }); } catch (ex) { reject(ex); } }); } function _createWorkflow(idx) { return new Promise(function (resolve, reject) { try { adminClient.post(ApiPrefix + '/workflows', { name: 'myworkflow' + idx, desc: 'workflowdesc' + idx }, function (err, req, res, data) { resolve({res: res, data: data}); }); } catch (ex) { reject(ex); } }); } function _createWorktyInstance(idx) { return new Promise(function (resolve, reject) { try { adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances', { name: 'worktyinstance' + idx, desc: 'worktyinstance' + idx, worktyId: Workties[idx]._id, embed: 'properties' }, function (err, req, res, data) { resolve({res: res, data: data}); }); } catch (ex) { reject(ex); } }); } // Delete workflows and workties function _deleteWorkty(idx) { return new Promise(function (resolve, reject) { try { adminClient.del(ApiPrefix + '/workties/' + Workties[idx]._id, function (err, req, res, data) { resolve({res: res}); }); } catch (ex) { reject(ex); } }); } function _deleteWorkflow(idx) { return new Promise(function (resolve, reject) { try { adminClient.del(ApiPrefix + '/workflows/' + Workflows[idx]._id, function (err, req, res, data) { resolve({res: res}); }); } catch (ex) { reject(ex); } }); } // Run once before the first test case before(function (done) { Promise.all(_createPromises(_createWorkty, WorktiesPerPage)).then(function (results) { // Create workties for (var idx = 0; idx < results.length; idx++) { var res = results[idx].res; var data = results[idx].data; expect(res.statusCode).to.equals(201); expect(data).to.not.be.empty; Workties.push(data); } return Promise.all(_createPromises(_createWorkflow, WorkflowsPerPage)); }).then(function (results) { // Create workflows for (var idx = 0; idx < results.length; idx++) { var res = results[idx].res; var data = results[idx].data; expect(res.statusCode).to.equals(201); expect(data).to.not.be.empty; Workflows.push(data); } return Promise.all(_createPromises(_createWorktyInstance, WorktiesPerPage)); }).then(function (results) { // Create workties instances for (var idx = 0; idx < results.length; idx++) { var res = results[idx].res; var data = results[idx].data; expect(res.statusCode).to.equals(201); expect(data).to.not.be.empty; WorktiesInstances.push(data); } }).done(function (err) { expect(err).to.be.undefined; done(); }); }); // Run once after the last test case after(function (done) { Promise.all(_createPromises(_deleteWorkty, WorktiesPerPage)).then(function (results) { // Delete workties for (var idx = 0; idx < results.length; idx++) { var res = results[idx].res; expect(res.statusCode).to.equals(204); } return Promise.all(_createPromises(_deleteWorkflow, WorkflowsPerPage)); }).then(function (results) { // Delete workflows for (var idx = 0; idx < results.length; idx++) { var res = results[idx].res; expect(res.statusCode).to.equals(204); } }).done(function (err) { expect(err).to.be.undefined; done(); }); }); describe('.getAll()', function () { it('should get a 200 response', function (done) { adminClient.get(ApiPrefix + '/workflows', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.have.length.above(1); done(); }); }); it('should get 3', function (done) { adminClient.get(ApiPrefix + '/workflows?page_num=1&per_page=3', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.have.length(3); done(); }); }); it('should get 2', function (done) { adminClient.get(ApiPrefix + '/workflows?per_page=2', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.have.length(2); done(); }); }); it('should get records-count', function (done) { adminClient.get(ApiPrefix + '/workflows?per_page=3&count=true', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.have.length(3); expect(res.headers).to.contain.keys('records-count'); expect(res.headers['records-count']).equals('3'); done(); }); }); it('should get sorted', function (done) { adminClient.get(ApiPrefix + '/workflows?per_page=3&sort=_id', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.have.length(3); expect(data).to.satisfy(function (workflows) { var currentValue = null; _.each(workflows, function (workflow) { if (!currentValue) { currentValue = workflow._id; } else { if (workflow._id <= currentValue) expect(true).to.be.false(); currentValue = workflow._id; } }); return true; }); done(); }); }); it('should get fields', function (done) { adminClient.get(ApiPrefix + '/workflows?per_page=3&fields=_id,name,desc', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.have.length(3); expect(data).to.satisfy(function (workflows) { _.each(workflows, function (workflow) { expect(workflow).to.have.keys(['_id', 'name', 'desc']); }); return true; }); done(); }); }); it('should get embed fields', function (done) { adminClient.get(ApiPrefix + '/workflows?per_page=3&embed=worktiesInstances,account', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.have.length(3); expect(data).to.satisfy(function (workflows) { _.each(workflows, function (workflow) { expect(workflow).to.contain.keys('accountId', 'worktiesInstancesIds'); expect(workflow.accountId).to.contain.keys('_id'); if (workflow.worktiesInstancesIds.length > 0) { expect(workflow.worktiesInstancesIds[0]).to.contain.keys('_id'); } }); return true; }); done(); }); }); }); describe('.getById()', function () { it('should get a 200 response', function (done) { adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; done(); }); }); it('should get a 500 response not found', function (done) { adminClient.get(ApiPrefix + '/workflows/' + 'N', function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(500); expect(data).to.not.be.empty; expect(data).to.have.keys('error'); expect(data.error).to.have.keys(['code', 'error_link', 'message', 'inputParameters']); expect(data.error.code).to.equals(1); expect(data.error.error_link).to.not.be.empty; expect(data.error.message).to.not.be.empty; done(); }); }); it('should get records-count', function (done) { adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '?count=true', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; expect(res.headers).to.contain.keys('records-count'); expect(res.headers['records-count']).equals('1'); done(); }); }); it('should get fields', function (done) { adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '?fields=_id,name,desc', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; expect(data).to.have.keys(['_id', 'name', 'desc']); done(); }); }); it('should get embed fields', function (done) { adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '?embed=worktiesInstances,account', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; expect(data).to.contain.keys('accountId', 'worktiesInstancesIds'); expect(data.accountId).to.contain.keys('_id'); if (data.worktiesInstancesIds.length > 0) { expect(data.worktiesInstancesIds[0]).to.contain.keys('_id'); } done(); }); }); }); describe('.add()', function () { it('should get a 409 response', function (done) { adminClient.post(ApiPrefix + '/workflows', function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(409); var error = JSON.parse(err.message).error; expect(error.message).to.equals("Validation Error"); expect(error.errors).to.have.length(1); expect(error.errors[0].message).to.equals("Path `name` is required."); done(); }); }); it('should get a 201 response', function (done) { // Create workflow adminClient.post(ApiPrefix + '/workflows', { name: 'mytestworkflow', desc: 'testworkflow' }, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(201); expect(res.headers).to.contain.keys('location'); expect(data).to.not.be.null; var workflowId = data._id; expect(res.headers.location).to.have.string('/' + workflowId); expect(data.name).to.be.equal('mytestworkflow'); expect(data.desc).to.be.equal('testworkflow'); // Delete workflow adminClient.del(res.headers.location, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(204); done(); }); }); }); }); describe('.update()', function () { it('should get a 400 response', function (done) { adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id, function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(400); var error = JSON.parse(err.message).error; expect(error.errors).is.empty; done(); }); }); it('should get a 409 response', function (done) { adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id, {name: ''}, function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(409); var error = JSON.parse(err.message).error; expect(error.errors).to.have.length(1); expect(error.errors[0].message).to.equals("Path `name` is required."); done(); }); }); it('should get a 200 response', function (done) { adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id, { name: 'mytestworkflow', desc: 'testworkflow' }, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.null; var workflowId = data._id; expect(workflowId).to.equals(Workflows[0]._id); expect(data.name).to.be.equal('mytestworkflow'); expect(data.desc).to.be.equal('testworkflow'); done(); }); }); }); describe('.del()', function () { it('should get a 500 response not found', function (done) { // Delete workflow adminClient.del(ApiPrefix + '/workflows/' + Workflows[0]._id + 'N', function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(500); done(); }); }); it('should get a 204 response', function (done) { // Create workflow adminClient.post(ApiPrefix + '/workflows', { name: 'mytestworkflow', desc: 'testworkflow' }, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(201); expect(res.headers).to.contain.keys('location'); expect(data).to.not.be.null; var workflowId = data._id; expect(res.headers.location).to.have.string('/' + workflowId); // Delete workflow adminClient.del(ApiPrefix + '/workflows/' + workflowId, function (err, req, res, data) { expect(err).to.be.null; expect(data).is.empty; expect(res.statusCode).to.equals(204); done(); }); }); }); }); describe('.run()', function () { it('should get a 200 response', function (done) { adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id + '/running', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; done(); }); }); it('should get a 500 response not found', function (done) { adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id + 'N' + '/running', function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(500); expect(data).to.not.be.empty; expect(data).to.have.keys('error'); expect(data.error).to.have.keys(['code', 'error_link', 'message', 'inputParameters']); expect(data.error.code).to.be.equals(1); expect(data.error.error_link).to.not.be.empty; expect(data.error.message).to.not.be.empty; done(); }); }); describe('multiple workflows', function () { var WorkflowExtraPerPage = 2; var WorkflowExtraIds = []; function _deleteExtraWorkflow(idx) { return new Promise(function (resolve, reject) { try { adminClient.del(ApiPrefix + '/workflows/' + WorkflowExtraIds[idx], function (err, req, res, data) { resolve({res: res}); }); } catch (ex) { reject(ex); } }); } // Run once before the first test case before(function (done) { Promise.all(_createPromises(_createWorkflow, WorkflowExtraPerPage)).then(function (results) { // Create workflows for (var idx = 0; idx < results.length; idx++) { var res = results[idx].res; var data = results[idx].data; expect(res.statusCode).to.equals(201); expect(data).to.not.be.empty; WorkflowExtraIds.push(data._id); } }).done(function (err) { expect(err).to.be.undefined; done(); }); }); // Run once after the last test case after(function (done) { Promise.all(_createPromises(_deleteExtraWorkflow, WorkflowExtraPerPage)).then(function (results) { // Delete workflows for (var idx = 0; idx < results.length; idx++) { var res = results[idx].res; expect(res.statusCode).to.equals(204); } }).done(function (err) { expect(err).to.be.undefined; done(); }); }); }); }); describe('.stop()', function () { it('should get a 200 response', function (done) { // Run workflow adminClient.del(ApiPrefix + '/workflows/' + Workflows[0]._id + '/running', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); done(); }); }); it('should get a 500 response not found', function (done) { adminClient.del(ApiPrefix + '/workflows/' + Workflows[0]._id + 'N' + '/running', function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(500); expect(data).to.not.be.empty; expect(data).to.have.keys('error'); expect(data.error).to.have.keys(['code', 'error_link', 'message', 'inputParameters']); expect(data.error.code).to.be.equals(1); expect(data.error.error_link).to.not.be.empty; expect(data.error.message).to.not.be.empty; done(); }); }); it('should get a 200 response after two stops', function (done) { // Run workflow adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id + '/running', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; // Stop workflow twice adminClient.del(ApiPrefix + '/workflows/' + Workflows[0]._id + '/running', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); adminClient.del(ApiPrefix + '/workflows/' + Workflows[0]._id + '/running', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); done(); }); }); }); }); }); describe('.resume()', function () { it('should get a 200 response', function (done) { // Resume workflow adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id + '/running', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; done(); }); }); it('should get a 500 response not found', function (done) { adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id + 'N' + '/running', function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(500); expect(data).to.not.be.empty; expect(data).to.have.keys('error'); expect(data.error).to.have.keys(['code', 'error_link', 'message', 'inputParameters']); expect(data.error.code).to.be.equals(1); expect(data.error.error_link).to.not.be.empty; expect(data.error.message).to.not.be.empty; done(); }); }); }); describe('Workties instances', function () { describe('.getAllWorktiesInstances()', function () { it('should get a 200 response', function (done) { adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.have.length.above(0); expect(data[0].workflowId).to.equals(Workflows[0]._id); done(); }); }); it('should get 2', function (done) { adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?per_page=2', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.have.length(2); done(); }); }); it('should get records-count', function (done) { adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?per_page=2&count=true', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.have.length(2); expect(res.headers).to.contain.keys('records-count'); expect(res.headers['records-count']).equals('2'); done(); }); }); it('should get fields', function (done) { adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?per_page=2&fields=_id,desc,created', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.have.length(2); expect(data).to.satisfy(function (workflowInstances) { _.each(workflowInstances, function (workflowInstance) { expect(workflowInstance).to.have.keys(['_id', 'desc', 'created']); }); return true; }); done(); }); }); it('should get embed fields', function (done) { adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?per_page=2&embed=workflow,state', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.have.length(2); expect(data).to.satisfy(function (workflowInstances) { _.each(workflowInstances, function (workflowInstance) { expect(workflowInstance).to.contain.keys('stateId', 'workflowId'); expect(workflowInstance.workflowId).to.contain.keys('_id'); if (workflowInstance.stateId.length > 0) { expect(workflowInstance.stateId[0]).to.contain.keys('_id'); } }); return true; }); done(); }); }); }); describe('.getWorktyInstanceById()', function () { it('should get a 200 response', function (done) { adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances/' + WorktiesInstances[0]._id, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; done(); }); }); it('should get a 500 response not found', function (done) { adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances/' + WorktiesInstances[0]._id + 'N', function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(500); expect(data).to.not.be.empty; expect(data).to.have.keys('error'); expect(data.error).to.have.keys(['code', 'error_link', 'message', 'inputParameters']); expect(data.error.code).to.equals(1); expect(data.error.error_link).to.not.be.empty; expect(data.error.message).to.not.be.empty; done(); }); }); it('should get records-count', function (done) { adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances/' + WorktiesInstances[0]._id + '?count=true', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; expect(res.headers).to.contain.keys('records-count'); expect(res.headers['records-count']).equals('1'); done(); }); }); it('should get fields', function (done) { adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances/' + WorktiesInstances[0]._id + '?fields=_id,desc', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; expect(data).to.have.keys(['_id', 'desc']); done(); }); }); it('should get embed fields', function (done) { adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances/' + WorktiesInstances[0]._id + '?embed=workflow,state', function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; expect(data).to.contain.keys('stateId', 'workflowId'); expect(data.stateId).to.contain.keys('_id'); expect(data.workflowId).to.contain.keys('_id'); expect(data.workflowId._id).to.equals(Workflows[0]._id); done(); }); }); }); describe('.addWorktyInstance()', function () { it('should get a 201 response', function (done) { // Create workty instance adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances', { desc: 'descworktyinstance4', worktyId: Workties[0]._id }, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(201); expect(res.headers).to.contain.keys('location'); expect(data).to.not.be.null; expect(data.worktyId).to.be.equal(Workties[0]._id); expect(data.desc).to.be.equal('descworktyinstance4'); // Delete workty instance adminClient.del(res.headers.location, function (err, req, res, data) { expect(err).to.be.null; expect(data).is.empty; expect(res.statusCode).to.equals(204); done(); }); }); }); it('should get a 500 response with code 12 position type is unknown', function (done) { adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?position_type=unknown', { desc: 'testworkty', worktyId: Workties[0]._id }, function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(500); expect(data).to.have.keys('error'); expect(data.error).to.have.keys(['code', 'error_link', 'message', 'inputParameters']); expect(data.error.code).to.equals(12); expect(data.error.error_link).to.not.be.empty; expect(data.error.message).to.not.be.empty; done(); }); }); it('should get a 201 response for position type is last', function (done) { adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?position_type=last', { desc: 'testworkty', worktyId: Workties[0]._id }, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(201); expect(res.headers).to.contain.keys('location'); expect(data).to.not.be.null; var worktyInstanceId = data._id; expect(res.headers.location).to.have.string('worktiesInstances/' + worktyInstanceId); expect(data.desc).to.be.equal('testworkty'); var headerLocation = res.headers.location; // Get workflow to check workty instance added in last position adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; expect(data.worktiesInstancesIds).to.satisfy(function (worktiesInstancesIds) { if (worktiesInstancesIds.length !== 3) { return false; } return worktyInstanceId === worktiesInstancesIds[worktiesInstancesIds.length - 1]; }); // Delete workty instance adminClient.del(headerLocation, function (err, req, res, data) { expect(err).to.be.null; expect(data).is.empty; expect(res.statusCode).to.equals(204); done(); }); }); }); }); it('should get a 201 response for position type is first', function (done) { adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?position_type=first', { desc: 'testworkty', worktyId: Workties[0]._id }, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(201); expect(res.headers).to.contain.keys('location'); expect(data).to.not.be.null; var worktyInstanceId = data._id; expect(res.headers.location).to.have.string('worktiesInstances/' + worktyInstanceId); expect(data.desc).to.be.equal('testworkty'); var headerLocation = res.headers.location; // Get workflow to check workty instance added in first position adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; expect(data.worktiesInstancesIds).to.satisfy(function (worktiesInstancesIds) { if (worktiesInstancesIds.length !== 3) { return false; } return worktyInstanceId === worktiesInstancesIds[0]; }); // Delete workty instance adminClient.del(headerLocation, function (err, req, res, data) { expect(err).to.be.null; expect(data).is.empty; expect(res.statusCode).to.equals(204); done(); }); }); }); }); it('should get a 201 response for position index is 0 among 4 values', function (done) { adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?position_index=0', { desc: 'testworkty', worktyId: Workties[0]._id }, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(201); expect(res.headers).to.contain.keys('location'); expect(data).to.not.be.null; var worktyInstanceId = data._id; expect(res.headers.location).to.have.string('worktiesInstances/' + worktyInstanceId); expect(data.desc).to.be.equal('testworkty'); var headerLocation = res.headers.location; // Get workflow to check workty instance added by index 1 adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; expect(data.worktiesInstancesIds).to.satisfy(function (worktiesInstancesIds) { if (worktiesInstancesIds.length !== 3) { return false; } return _.indexOf(worktiesInstancesIds, worktyInstanceId) === 0; }); // Delete workty instance adminClient.del(headerLocation, function (err, req, res, data) { expect(err).to.be.null; expect(data).is.empty; expect(res.statusCode).to.equals(204); done(); }); }); }); }); it('should get a 500 response with code 10 for position index is -1', function (done) { adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?position_index=-1', { desc: 'testworkty', worktyId: Workties[0]._id }, function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(500); expect(data).to.have.keys('error'); expect(data.error).to.have.keys(['code', 'error_link', 'message', 'inputParameters']); expect(data.error.code).to.equals(10); expect(data.error.error_link).to.not.be.empty; expect(data.error.message).to.not.be.empty; done(); }); }); it('should get a 500 response with code 11 for missing position id', function (done) { adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?position_id=N', { desc: 'testworkty', worktyId: Workties[0]._id }, function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(500); expect(data).to.have.keys('error'); expect(data.error).to.have.keys(['code', 'error_link', 'message', 'inputParameters']); expect(data.error.code).to.equals(11); expect(data.error.error_link).to.not.be.empty; expect(data.error.message).to.not.be.empty; done(); }); }); it('should get a 201 response for position id', function (done) { // Insert workty by index 0 adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?position_index=0', { desc: 'testworkty', worktyId: Workties[0]._id }, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(201); expect(res.headers).to.contain.keys('location'); expect(data).to.not.be.null; var worktyInstanceId = data._id; expect(res.headers.location).to.have.string('worktiesInstances/' + worktyInstanceId); expect(data.desc).to.be.equal('testworkty'); var headerLocationFirst = res.headers.location; // Get workflow to check workty instance added by index 1 adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; expect(data.worktiesInstancesIds).to.satisfy(function (worktiesInstancesIds) { if (worktiesInstancesIds.length !== 3) { return false; } return _.indexOf(worktiesInstancesIds, worktyInstanceId) === 0; }); // Insert workty instance before worktyInstanceId adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?position_id=' + worktyInstanceId, { desc: 'testworkty', worktyId: Workties[0]._id }, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(201); expect(res.headers).to.contain.keys('location'); expect(data).to.not.be.null; worktyInstanceId = data._id; expect(res.headers.location).to.have.string('worktiesInstances/' + worktyInstanceId); expect(data.desc).to.be.equal('testworkty'); var headerLocation = res.headers.location; // Get workflow to check workty instance added by index 1 adminClient.get(ApiPrefix + '/workflows/' + Workflows[0]._id, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.empty; expect(data.worktiesInstancesIds).to.satisfy(function (worktiesInstancesIds) { if (worktiesInstancesIds.length !== 4) { return false; } return _.indexOf(worktiesInstancesIds, worktyInstanceId) === 0; }); // Delete first workty instance adminClient.del(headerLocationFirst, function (err, req, res, data) { expect(err).to.be.null; expect(data).is.empty; expect(res.statusCode).to.equals(204); // Delete second workty instance adminClient.del(headerLocation, function (err, req, res, data) { expect(err).to.be.null; expect(data).is.empty; expect(res.statusCode).to.equals(204); done(); }); }); }); }); }); }); }); it('should get a 500 response with code 1 for missing worktyId', function (done) { adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances?position_index=-1', {desc: 'testworkty'}, function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(409); expect(data).to.have.keys('error'); expect(data.error).to.have.keys(['code', 'error_link', 'message', 'errors', 'inputParameters']); expect(data.error.code).is.empty; expect(data.error.error_link).to.not.be.empty; expect(data.error.message).to.not.be.empty; done(); }); }); }); describe('.updateWorktyInstance()', function () { it('should get a 400 response', function (done) { adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances/' + WorktiesInstances[0]._id, function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(400); var error = JSON.parse(err.message).error; expect(error.errors).is.empty; done(); }); }); it('should get a 200 response', function (done) { adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances/' + WorktiesInstances[0]._id, {desc: 'updateddesc'}, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data).to.not.be.null; expect(data.desc).to.be.equal('updateddesc'); done(); }); }); }); describe('.delWorktyInstance()', function () { it('should get a 500 response not found', function (done) { // Delete workty instance adminClient.del(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances/' + WorktiesInstances[0]._id + 'N', function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(500); done(); }); }); it('should get a 204 response', function (done) { // Create workty instance adminClient.post(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances', { desc: 'testworkty', worktyId: Workties[0]._id }, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(201); expect(res.headers).to.contain.keys('location'); expect(data).to.not.be.null; var workflowId = data.workflowId; var worktyInstanceId = data._id; expect(res.headers.location).to.have.string('/' + workflowId); // Delete workty instance adminClient.del(ApiPrefix + '/workflows/' + workflowId + '/worktiesInstances/' + worktyInstanceId, function (err, req, res, data) { expect(err).to.be.null; expect(data).is.empty; expect(res.statusCode).to.equals(204); done(); }); }); }); }); describe('.updateWorktyInstanceProperty()', function () { it('should get a 400 response', function (done) { adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances/' + WorktiesInstances[0]._id + '/properties/' + WorktiesInstances[0].propertiesIds[0]._id, function (err, req, res, data) { expect(err).to.not.be.null; expect(res.statusCode).to.equals(400); var error = JSON.parse(err.message).error; expect(error.errors).is.empty; done(); }); }); it('should get a 200 response', function (done) { adminClient.put(ApiPrefix + '/workflows/' + Workflows[0]._id + '/worktiesInstances/' + WorktiesInstances[0]._id + '/properties/' + WorktiesInstances[0].propertiesIds[0]._id, { name: 'NewPropertyName', value: 'NewPropertyValue' }, function (err, req, res, data) { expect(err).to.be.null; expect(res.statusCode).to.equals(200); expect(data.name).to.be.equal('NewPropertyName'); expect(data.value).to.be.equal('NewPropertyValue'); done(); }); }); }); }); });
require.register("scripts/product", function(exports, require, module) { var req = require('scripts/req'); AddStyleTagToItemVM = function(user, styletag_repo) { // this is very similar to AddItemToCollectionVM - yet different. var self = this; self.styletags = styletag_repo.create_filter(); self.styletags.load_until_entry(100); self.target_item = ko.observable(null); self.selected_styletag = ko.observable(); self.show_select_styletag = ko.computed(function() { return self.target_item(); }); self.show_must_login = ko.observable(false); var request_add_styletag_to_item = function(item, styletag, success, error) { req.post("/api/styletag-item/create/", JSON.stringify({'item': item.id, 'styletag': styletag.name}), success, error); }; self.confirmed_must_login = function() { self.show_must_login(false); }; self.confirmed_add_styletag = function() { if (!self.selected_styletag()) { // user selected "Choose..." in the drop-down return; } if (!_.contains(self.target_item().styletags(), self.selected_styletag())) { var success = function() { self.target_item().styletags.push(self.selected_styletag().name); self.target_item(null); }; var error = function() { self.target_item(null); /* TODO: display something to user. */ }; request_add_styletag_to_item(self.target_item(), self.selected_styletag(), success, error); }; }; self.add_to_item = function(item) { if (!user()) { self.show_must_login(true); return; } console.log("lets go add styletag"); self.target_item(item); }; }; ProductVM = function(template_name, item_repo, add_to_collection_vm, favorites_vm, add_styletag_to_item_vm) { var self = this; self.template_name = template_name; self.product = ko.observable(null); self.add_to_collection_vm = add_to_collection_vm; self.favorites_vm = favorites_vm; self.add_styletag_to_item_vm = add_styletag_to_item_vm self.load = function(params) { item_repo.fetch(params.product_id, self.product); } }; exports.ProductVM = ProductVM; exports.AddStyleTagToItemVM = AddStyleTagToItemVM; });
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = undefined; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = require("react"); var _react2 = _interopRequireDefault(_react); var _propTypes = require("prop-types"); var _propTypes2 = _interopRequireDefault(_propTypes); var _textInput = require("./text-input"); var _textInput2 = _interopRequireDefault(_textInput); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } function validateEmail(email) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(email); } var EmailInput = function (_TextInput) { _inherits(EmailInput, _TextInput); function EmailInput(props) { _classCallCheck(this, EmailInput); return _possibleConstructorReturn(this, (EmailInput.__proto__ || Object.getPrototypeOf(EmailInput)).call(this, props)); } _createClass(EmailInput, [{ key: "onValid", value: function onValid(e) { if (!!this.props.onValid) { this.props.onValid(validateEmail(e.target.value), e); } } }]); return EmailInput; }(_textInput2.default); exports.default = EmailInput; EmailInput.propTypes = { type: _propTypes2.default.string.isRequired }; EmailInput.defaultProps = { type: "email" };
import React, { Component } from 'react'; import List from 'react-toolbox/lib/list/List'; import ListSubHeader from 'react-toolbox/lib/list/ListSubHeader'; import ListCheckbox from 'react-toolbox/lib/list/ListCheckbox'; import ListItem from 'react-toolbox/lib/list/ListItem'; import Dropdown from 'react-toolbox/lib/dropdown/Dropdown'; import ConnectedStoreHOC from '../utils/connect.store.hoc'; import * as Actions from '../utils/actions'; import { NEW_PHOTO_DURATIONS } from '../configs/constants'; const NEW_PHOTO_INTERVAL_OPTIONS = [ { value: NEW_PHOTO_DURATIONS.ALWAYS, label: 'Always' }, { value: NEW_PHOTO_DURATIONS.HOURLY, label: 'Hourly' }, { value: NEW_PHOTO_DURATIONS.DAILY, label: 'Daily' }, ]; const handleFetchFromServerChange = (value, ev) => Actions.setSetting({ fetchFromServer: value }); const handleNewPhotoIntervalChange = (value, ev) => Actions.setSetting({ newPhotoDuration: parseInt(value, 10) }); const NewPhotoIntervalDropdown = ({ refreshInterval, className }) => ( <Dropdown label="Duration" className={className} value={refreshInterval} source={NEW_PHOTO_INTERVAL_OPTIONS} onChange={handleNewPhotoIntervalChange} /> ); class SettingsContainer extends Component { componentDidMount() { // lazy initialize the state object setTimeout(() => Actions.refresh(false), 0); } render() { const { fetchFromServer, newPhotoDuration } = this.props; return ( <List selectable ripple> <ListSubHeader caption="Background Photos" /> <ListCheckbox caption="Load Fresh" legend="If disabled, it will cycle through a list of locally stored wallpapers only." checked={fetchFromServer} onChange={handleFetchFromServerChange} /> <ListItem itemContent={ <div> <p className="settings__inlineItem">Show new photo</p> <NewPhotoIntervalDropdown className="settings__inlineItem" refreshInterval={newPhotoDuration} /> </div> } ripple={false} selectable={false} /> </List>); } } export default ConnectedStoreHOC(SettingsContainer);
import { defaultAction, } from '../actions'; import { DEFAULT_ACTION, } from '../constants'; describe('Marginals actions', () => { describe('Default Action', () => { it('has a type of DEFAULT_ACTION', () => { const expected = { type: DEFAULT_ACTION, }; expect(defaultAction()).toEqual(expected); }); }); });
//A simple build file using the tests directory for requirejs { baseUrl: "../../../requirejs/tests/text", paths: { text: "../../../requirejs/../text/text" }, dir: "builds/text", optimize: "none", optimizeAllPluginResources: true, modules: [ { name: "widget" } ] }
/* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'stylescombo', 'no', { label: 'Stil', panelTitle: 'Stilformater', panelTitle1: 'Blokkstiler', panelTitle2: 'Inlinestiler', panelTitle3: 'Objektstiler' } );
"use strict"; var sqlite3 = require('sqlite3'); var authHelper = require('./server/helpers/auth'); var db = new sqlite3.Database('./data/users.db'); db.serialize(function() { db.run( 'CREATE TABLE "users" (' + '"id" INTEGER PRIMARY KEY AUTOINCREMENT,' + '"username" TEXT,' + '"password" TEXT' + ')' ); db.run("INSERT INTO users('username', 'password') VALUES (?, ?)", ["admin", authHelper.hashPassword("teste")]); }); db.close();
"use strict" var writeIEEE754 = require('../float_parser').writeIEEE754 , readIEEE754 = require('../float_parser').readIEEE754 , Long = require('../long').Long , Double = require('../double').Double , Timestamp = require('../timestamp').Timestamp , ObjectID = require('../objectid').ObjectID , Symbol = require('../symbol').Symbol , BSONRegExp = require('../regexp').BSONRegExp , Code = require('../code').Code , Decimal128 = require('../decimal128') , MinKey = require('../min_key').MinKey , MaxKey = require('../max_key').MaxKey , DBRef = require('../db_ref').DBRef , Binary = require('../binary').Binary; // To ensure that 0.4 of node works correctly var isDate = function isDate(d) { return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; } var calculateObjectSize = function calculateObjectSize(object, serializeFunctions, ignoreUndefined) { var totalLength = (4 + 1); if(Array.isArray(object)) { for(var i = 0; i < object.length; i++) { totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined) } } else { // If we have toBSON defined, override the current object if(object.toBSON) { object = object.toBSON(); } // Calculate size for(var key in object) { totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined) } } return totalLength; } /** * @ignore * @api private */ function calculateElement(name, value, serializeFunctions, isArray, ignoreUndefined) { // If we have toBSON defined, override the current object if(value && value.toBSON){ value = value.toBSON(); } switch(typeof value) { case 'string': return 1 + Buffer.byteLength(name, 'utf8') + 1 + 4 + Buffer.byteLength(value, 'utf8') + 1; case 'number': if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { // 32 bit return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (4 + 1); } else { return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (8 + 1); } } else { // 64 bit return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (8 + 1); } case 'undefined': if(isArray || !ignoreUndefined) return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (1); return 0; case 'boolean': return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (1 + 1); case 'object': if(value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (1); } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (12 + 1); } else if(value instanceof Date || isDate(value)) { return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (8 + 1); } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (1 + 4 + 1) + value.length; } else if(value instanceof Long || value instanceof Double || value instanceof Timestamp || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Double' || value['_bsontype'] == 'Timestamp') { return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (8 + 1); } else if(value instanceof Decimal128 || value['_bsontype'] == 'Decimal128') { return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (16 + 1); } else if(value instanceof Code || value['_bsontype'] == 'Code') { // Calculate size depending on the availability of a scope if(value.scope != null && Object.keys(value.scope).length > 0) { return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 4 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); } else { return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1; } } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { // Check what kind of subtype we have if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (value.position + 1 + 4 + 1 + 4); } else { return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (value.position + 1 + 4 + 1); } } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + Buffer.byteLength(value.value, 'utf8') + 4 + 1 + 1; } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { // Set up correct object for serialization var ordered_values = { '$ref': value.namespace , '$id' : value.oid }; // Add db reference if it exists if(null != value.db) { ordered_values['$db'] = value.db; } return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined); } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1 + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 } else if(value instanceof BSONRegExp || value['_bsontype'] == 'BSONRegExp') { return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + Buffer.byteLength(value.pattern, 'utf8') + 1 + Buffer.byteLength(value.options, 'utf8') + 1 } else { return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + calculateObjectSize(value, serializeFunctions, ignoreUndefined) + 1; } case 'function': // WTF for 0.4.X where typeof /someregexp/ === 'function' if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1 + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 } else { if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 4 + 4 + Buffer.byteLength(value.toString(), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); } else if(serializeFunctions) { return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 4 + Buffer.byteLength(value.toString(), 'utf8') + 1; } } } return 0; } var BSON = {}; // BSON MAX VALUES BSON.BSON_INT32_MAX = 0x7FFFFFFF; BSON.BSON_INT32_MIN = -0x80000000; // JS MAX PRECISE VALUES BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. module.exports = calculateObjectSize;
/** * DocumentController * * @description :: Server-side logic for managing documents * @help :: See http://links.sailsjs.org/docs/controllers */ var exec = require('child_process').exec; var path = require('path'); var fs = require('fs'); var UPLOADFOLDER = __dirname+'/../../.tmp/uploads'; module.exports = { /** * `OdfController.create()` */ upload: function (req, res) { req.file("documents").upload(function (err, files) { if (err) { sails.log.error(err); return res.serverError(err); } for (var i = 0; i < files.length; i++) { files[i].uploadedAs = path.basename(files[i].fd); }; // EmailService.send(from, subject, text, html); return res.json({ message: files.length + ' file(s) uploaded successfully!', files: files }); }); }, // filters source: http://listarchives.libreoffice.org/global/users/msg15151.html // org.openoffice.da.writer2xhtml.epub // org.openoffice.da.calc2xhtml11 // Text - txt - csv (StarCalc) // impress_svg_Export // math8 // EPS - Encapsulated PostScript // StarOffice XML (Base) Report Chart // org.openoffice.da.writer2xhtml.mathml.xsl // impress_svm_Export // MS Excel 95 (StarWriter) // impress_pdf_addstream_import // JPG - JPEG // placeware_Export // StarOffice XML (Math) // T602Document // impress_jpg_Export // writer_globaldocument_StarOffice_XML_Writer // draw_emf_Export // MS Word 2003 XML // WMF - MS Windows Metafile // GIF - Graphics Interchange // writer_pdf_import // calc8 // writer_globaldocument_StarOffice_XML_Writer_GlobalDocument // MS Word 97 Vorlage // impress_tif_Export // draw_xpm_Export // Calc MS Excel 2007 XML // Text (encoded) // MathML XML (Math) // MET - OS/2 Metafile // MS PowerPoint 97 AutoPlay // impress8 // StarOffice XML (Calc) // calc_HTML_WebQuery // RAS - Sun Rasterfile // MS Excel 5.0 (StarWriter) // impress_png_Export // DXF - AutoCAD Interchange // impress_pct_Export // impress_met_Export // SGF - StarOffice Writer SGF // draw_eps_Export // Calc MS Excel 2007 Binary // calc8_template // Calc MS Excel 2007 XML Template // impress_pbm_Export // draw_pdf_import // Calc Office Open XML // math_pdf_Export // Rich Text Format (StarCalc) // MS PowerPoint 97 Vorlage // StarOffice XML (Base) // DIF // Impress MS PowerPoint 2007 XML Template // MS Excel 2003 XML // impress_ras_Export // draw_PCD_Photo_CD_Base16 // draw_bmp_Export // WordPerfect Graphics // StarOffice XML (Writer) // PGM - Portable Graymap // Office Open XML Text Template // MS Excel 5.0/95 // draw_svg_Export // draw_PCD_Photo_CD_Base4 // TGA - Truevision TARGA // Quattro Pro 6.0 // writer_globaldocument_pdf_Export // calc_pdf_addstream_import // writerglobal8_HTML // draw_svm_Export // HTML // EMF - MS Windows Metafile // PPM - Portable Pixelmap // Lotus // impress_ppm_Export // draw_jpg_Export // Text // TIF - Tag Image File // Impress Office Open XML AutoPlay // StarOffice XML (Base) Report // PNG - Portable Network Graphic // draw8 // Rich Text Format // writer_web_StarOffice_XML_Writer_Web_Template // org.openoffice.da.writer2xhtml // MS_Works // Office Open XML Text // SVG - Scalable Vector Graphics // org.openoffice.da.writer2xhtml11 // draw_tif_Export // impress_gif_Export // StarOffice XML (Draw) // StarOffice XML (Impress) // Text (encoded) (StarWriter/Web) // writer_web_pdf_Export // MediaWiki_Web // impress_pdf_Export // draw_pdf_addstream_import // draw_png_Export // HTML (StarCalc) // HTML (StarWriter) // impress_StarOffice_XML_Impress_Template // draw_pct_Export // calc_StarOffice_XML_Calc_Template // MS Excel 95 Vorlage/Template // writerglobal8_writer // MS Excel 95 // draw_met_Export // dBase // MS Excel 97 // MS Excel 4.0 // draw_pbm_Export // impress_StarOffice_XML_Draw // Impress Office Open XML // writerweb8_writer // chart8 // MediaWiki // MS Excel 4.0 Vorlage/Template // impress_wmf_Export // draw_ras_Export // writer_StarOffice_XML_Writer_Template // BMP - MS Windows // impress8_template // LotusWordPro // impress_pgm_Export // SGV - StarDraw 2.0 // draw_PCD_Photo_CD_Base // draw_html_Export // writer8_template // Calc Office Open XML Template // writerglobal8 // draw_flash_Export // MS Word 2007 XML Template // impress8_draw // CGM - Computer Graphics Metafile // MS PowerPoint 97 // WordPerfect // impress_emf_Export // writer_pdf_Export // PSD - Adobe Photoshop // PBM - Portable Bitmap // draw_ppm_Export // writer_pdf_addstream_import // PCX - Zsoft Paintbrush // writer_web_HTML_help // MS Excel 4.0 (StarWriter) // Impress Office Open XML Template // org.openoffice.da.writer2xhtml.mathml // MathType 3.x // impress_xpm_Export // writer_web_StarOffice_XML_Writer // writerweb8_writer_template // MS Word 95 // impress_html_Export // MS Word 97 // draw_gif_Export // writer8 // MS Excel 5.0/95 Vorlage/Template // draw8_template // StarOffice XML (Chart) // XPM // draw_pdf_Export // calc_pdf_Export // impress_eps_Export // XBM - X-Consortium // Text (encoded) (StarWriter/GlobalDocument) // writer_MIZI_Hwp_97 // MS WinWord 6.0 // Lotus 1-2-3 1.0 (WIN) (StarWriter) // SYLK // MS Word 2007 XML // Text (StarWriter/Web) // impress_pdf_import // MS Excel 97 Vorlage/Template // Impress MS PowerPoint 2007 XML AutoPlay // Impress MS PowerPoint 2007 XML // draw_wmf_Export // Unifa Adressbuch // org.openoffice.da.calc2xhtml // impress_bmp_Export // Lotus 1-2-3 1.0 (DOS) (StarWriter) // MS Word 95 Vorlage // MS WinWord 5 // PCT - Mac Pict // SVM - StarView Metafile // draw_StarOffice_XML_Draw_Template // impress_flash_Export // draw_pgm_Export convert: function (req, res) { var stdout = ''; var stderr = ''; sails.log.info('convert'); if(!req.param('filename')) res.badRequest('filename is required'); var source = req.param('filename'); var inputDir = UPLOADFOLDER +'/'+source; var outputFileExtension = req.param('extension') ? req.param('extension') : 'pdf'; // example 'pdf'; var outputFilterName = req.param('filter') ? ':'+req.param('filter') : ''; //(optinal) example ':'+'MS Excel 95'; var outputDir = UPLOADFOLDER; if(req.param('dir')) { outputDir += '/'+req.param('dir'); } outputDir = path.normalize(outputDir); inputDir = path.normalize(inputDir); var target = outputDir+"/"+path.basename(source, '.odt')+"."+outputFileExtension; var command = 'soffice --headless --invisible --convert-to '+outputFileExtension+outputFilterName+' --outdir '+outputDir+' '+inputDir; sails.log.info(command); var child = exec(command, function (code, stdout, stderr) { if(code) { sails.log.error(code); } if(stderr) { sails.log.error(stderr); } if(stdout) { sails.log.info(stdout); } res.json({target:target, code: code, stdout: stdout, stderr: stderr}); // res.download(target); // not working over socket.io }); } };
'use strict'; var assert = require('assert'), mongoose = require('mongoose'), mobgoose = require('../')(mongoose); var Foo = mongoose.model('Foo', new mongoose.Schema({}), 'foo_collection_name'); it('accepts configuration without url', function() { return mobgoose({ host: 'localhost', database: 'test123' }) .then(function(connection) { var model = connection.model('Foo'); assert(model.db.name === 'test123'); }); }); it('supports a simple conection string', function() { return mobgoose('mongodb://localhost:27017/test') .then(function(connection) { var model = connection.model('Foo'); assert(model.db.name === 'test'); }); }); it('keeps the model collection name', function() { return mobgoose('mongodb://localhost:27017/test') .then(function(connection) { var model = connection.model('Foo'); assert(model.collection.name === 'foo_collection_name'); }); }); describe('different databases on the same server', function(done) { var connection1, connection2; before(function() { return mobgoose({ host: 'localhost', database: 'test1' }) .then(function(connection) { connection1 = connection; }); }); before(function() { return mobgoose({ host: 'localhost', database: 'test2' }) .then(function(connection) { connection2 = connection; }); }); it('use one actual connection', function() { assert(Object.keys(mobgoose.connections).length === 1); }); it('produce connections in the connected readyState', function() { assert(connection1.readyState === mongoose.STATES.connected); assert(connection2.readyState === mongoose.STATES.connected); }); it('register their own models', function() { assert(connection1.model('Foo') !== undefined); assert(connection1.model('Foo').modelName === Foo.modelName); assert(connection1.model('Foo').db.name === 'test1'); assert(connection2.model('Foo') !== undefined); assert(connection2.model('Foo').modelName === Foo.modelName); assert(connection2.model('Foo').db.name === 'test2'); }); }); describe('multiple hosts', function() { it('work with a bunch of databases', function() { return Promise.all(['localhost', '127.0.0.1'].map((host) => { return Promise.all(['foo', 'bar', 'baz'].map((database) => { return mobgoose({ host: host, database: database }); })); })) .then(function() { assert(Object.keys(mobgoose.connections).length == 2); }); }); });
"use strict"; const setupTask = require('utils').setupTask; const calcTasks = require("calcTasks"); module.exports = { run : function(creep){ if(!creep.task){ var room = creep.room; var creepsByTask = _(Game.creeps).filter( (c) => c.task && c.task.roomName == room.name).groupBy('task.type').value(); var upgradeList = calcTasks.calcUpgradeTasks(room,creepsByTask); var myIndex = _.findIndex(upgradeList, (t) => true); if(myIndex != -1){ var upgradeContainer = room.controller.pos.findInRange(FIND_STRUCTURES,1,{filter: (s) => s.structureType == STRUCTURE_CONTAINER})[0]; creep.task=upgradeList[myIndex]; if(upgradeContainer != undefined){ creep.task.containerId = upgradeContainer.id; } return OK; } } } }
// GET /api/v1/nowplaying/groovesalad { "stationId": "groovesalad", "time": 1425871720000, "artist": "Panorama", "title": "Selene", "album": "Panorama", "trackCorrected": false, "artistCorrected": false, "albumCorrected": false, "corrected": false, "duration": 335000, "durationEstimated": false }
/** * Using Rails-like standard naming convention for endpoints. * GET /api/bridges -> index * POST /api/bridges -> create * GET /api/bridges/:id -> show * PUT /api/bridges/:id -> upsert * PATCH /api/bridges/:id -> patch * DELETE /api/bridges/:id -> destroy */ 'use strict'; import jsonpatch from 'fast-json-patch'; import Bridge from './bridge.model'; function respondWithResult(res, statusCode) { statusCode = statusCode || 200; return function(entity) { if (entity) { return res.status(statusCode).json(entity); } return null; }; } function patchUpdates(patches) { return function(entity) { try { // eslint-disable-next-line prefer-reflect jsonpatch.apply(entity, patches, /*validate*/ true); } catch(err) { return Promise.reject(err); } return entity.save(); }; } function removeEntity(res) { return function(entity) { if (entity) { return entity.remove() .then(() => { res.status(204).end(); }); } }; } function handleEntityNotFound(res) { return function(entity) { if (!entity) { res.status(404).end(); return null; } return entity; }; } function handleError(res, statusCode) { statusCode = statusCode || 500; return function(err) { res.status(statusCode).send(err); }; } // Gets a list of Bridges export function index(req, res) { return Bridge.find().exec() .then(respondWithResult(res)) .catch(handleError(res)); } // Gets a single Bridge from the DB export function show(req, res) { return Bridge.findById(req.params.id).exec() .then(handleEntityNotFound(res)) .then(respondWithResult(res)) .catch(handleError(res)); } // Creates a new Bridge in the DB export function create(req, res) { return Bridge.create(req.body) .then(respondWithResult(res, 201)) .catch(handleError(res)); } // Upserts the given Bridge in the DB at the specified ID export function upsert(req, res) { if (req.body._id) { Reflect.deleteProperty(req.body, '_id'); } return Bridge.findOneAndUpdate({_id: req.params.id}, req.body, {new: true, upsert: true, setDefaultsOnInsert: true, runValidators: true}).exec() .then(respondWithResult(res)) .catch(handleError(res)); } // Updates an existing Bridge in the DB export function patch(req, res) { if (req.body._id) { Reflect.deleteProperty(req.body, '_id'); } return Bridge.findById(req.params.id).exec() .then(handleEntityNotFound(res)) .then(patchUpdates(req.body)) .then(respondWithResult(res)) .catch(handleError(res)); } // Deletes a Bridge from the DB export function destroy(req, res) { return Bridge.findById(req.params.id).exec() .then(handleEntityNotFound(res)) .then(removeEntity(res)) .catch(handleError(res)); }
/* jQuery UI Sortable plugin wrapper @param [ui-sortable] {object} Options to pass to $.fn.sortable() merged onto ui.config */ angular.module('ui.sortable', []) .value('uiSortableConfig',{}) .directive('uiSortable', [ 'uiSortableConfig', function(uiSortableConfig) { return { require: '?ngModel', link: function(scope, element, attrs, ngModel) { function combineCallbacks(first,second){ if( second && (typeof second === "function") ){ return function(e,ui){ first(e,ui); second(e,ui); }; } return first; } var opts = {}; var callbacks = { receive: null, remove:null, start:null, stop:null, update:null }; var apply = function(e, ui) { if (ui.item.sortable.resort || ui.item.sortable.relocate) { scope.$apply(); } }; angular.extend(opts, uiSortableConfig); if (ngModel) { ngModel.$render = function() { element.sortable( "refresh" ); }; callbacks.start = function(e, ui) { // Save position of dragged item ui.item.sortable = { index: ui.item.index() }; }; callbacks.update = function(e, ui) { // For some reason the reference to ngModel in stop() is wrong ui.item.sortable.resort = ngModel; }; callbacks.receive = function(e, ui) { ui.item.sortable.relocate = true; // added item to array into correct position and set up flag ngModel.$modelValue.splice(ui.item.index(), 0, ui.item.sortable.moved); }; callbacks.remove = function(e, ui) { // copy data into item if (ngModel.$modelValue.length === 1) { ui.item.sortable.moved = ngModel.$modelValue.splice(0, 1)[0]; } else { ui.item.sortable.moved = ngModel.$modelValue.splice(ui.item.sortable.index, 1)[0]; } }; callbacks.stop = function(e, ui) { // digest all prepared changes if (ui.item.sortable.resort && !ui.item.sortable.relocate) { // Fetch saved and current position of dropped element var end, start; start = ui.item.sortable.index; end = ui.item.index(); // Reorder array and apply change to scope ui.item.sortable.resort.$modelValue.splice(end, 0, ui.item.sortable.resort.$modelValue.splice(start, 1)[0]); } }; } scope.$watch(attrs.uiSortable, function(newVal, oldVal){ angular.forEach(newVal, function(value, key){ if( callbacks[key] ){ // wrap the callback value = combineCallbacks( callbacks[key], value ); if ( key === 'stop' ){ // call apply after stop value = combineCallbacks( value, apply ); } } element.sortable('option', key, value); }); }, true); angular.forEach(callbacks, function(value, key ){ opts[key] = combineCallbacks(value, opts[key]); }); // call apply after stop opts.stop = combineCallbacks( opts.stop, apply ); // Create sortable element.sortable(opts); } }; } ]);
load("build/jslint.js"); var src = readFile("dist/jquery.ImageColorPicker.js"); JSLINT(src, { evil: true, forin: true }); // All of the following are known issues that we think are 'ok' // (in contradiction with JSLint) more information here: // http://docs.jquery.com/JQuery_Core_Style_Guidelines var ok = { "Expected an identifier and instead saw 'undefined' (a reserved word).": true, "Use '===' to compare with 'null'.": true, "Use '!==' to compare with 'null'.": true, "Expected an assignment or function call and instead saw an expression.": true, "Expected a 'break' statement before 'case'.": true }; var e = JSLINT.errors, found = 0, w; for ( var i = 0; i < e.length; i++ ) { w = e[i]; if ( !ok[ w.reason ] ) { found++; print( "\n" + w.evidence + "\n" ); print( " Problem at line " + w.line + " character " + w.character + ": " + w.reason ); } } if ( found > 0 ) { print( "\n" + found + " Error(s) found." ); } else { print( "JSLint check passed." ); }
var fs = require('fs'); var os=require('os'); var express = require('express'), // wine = require('./routes/wines'); user = require('./services/user'); contact = require('./services/contact'); inbox = require('./services/inbox'); outbox = require('./services/outbox'); device = require('./services/device'); audio = require('./services/audio'); GLOBAL.GCMessage = require('./lib/GCMessage.js'); GLOBAL.Sound = require('./lib/Sound.js'); GLOBAL.PORT = 3000; GLOBAL.IP = "54.214.9.117"; GLOBAL.HOSTNAME = "vivu.uni.me"; //GLOBAL.IP = "127.0.0.1"; GLOBAL.__dirname = __dirname; var app = express(); app.configure(function () { app.use(express.logger('dev')); /* 'default', 'short', 'tiny', 'dev' */ app.use(express.bodyParser()); app.use(express.static(__dirname + '/public/html')); }); app.set('views', __dirname + '/views'); app.engine('html', require('ejs').renderFile); app.get('/$',function (req, res){ res.render('homepage.html'); }); app.get('/audio/flash',function (req, res){ try{ var filePath = __dirname + "/public/flash/dewplayer.swf"; var audioFile = fs.statSync(filePath); res.setHeader('Content-Type', 'application/x-shockwave-flash'); res.setHeader('Content-Length',audioFile.size); var readStream = fs.createReadStream(filePath); readStream.on('data', function(data) { res.write(data); }); readStream.on('end', function() { res.end(); }); } catch(e){ console.log("Error when process get /audio/:id, error: "+ e); res.send("Error from server"); } }); app.get('/cfs/audio/:id',function (req, res){ try{ var audioId = req.params.id; var ip = GLOBAL.IP; var host = ip+":8888"; var source = "http://"+host+"/public/audio/"+audioId+".mp3"; res.render('index1.html', { sourceurl:source, sourceid: audioId }); } catch(e){ console.log("Error when process get cfs/audio/:id, error: "+ e); res.send("Error from server"); } }); /* app.get('/cfs/audio/:id',function (req, res) { console.log("hostname:"+os.hostname()); try{ var audioId = req.params.id; var ip = GLOBAL.IP; var host = ip+":8888"; var source = "http://"+host+"/public/audio/"+audioId+".mp3"; //var source = "http://s91.stream.nixcdn.com/3ce626c71801e67a340ef3b7997001be/51828581/NhacCuaTui025/RingBackTone-SunnyHill_4g6z.mp3"; res.render(__dirname + '/public/template/index.jade', {sourceurl:source, sourceid: audioId}); } catch(e){ console.log("Error when process get cfs/audio/:id, error: "+ e); res.send("Error from server"); } }); */ /* app.get('/audio/:id',function (req, res) { try{ var audioId = req.params.id; var filePath = __dirname + "/public/audio/"+audioId+".mp3"; var audioFile = fs.statSync(filePath); res.setHeader('Content-Type', 'audio/mpeg'); res.setHeader('Content-Length',audioFile.size); var readStream = fs.createReadStream(filePath); readStream.on('data', function(data) { res.write(data); }); readStream.on('end', function() { res.end(); }); } catch(e){ console.log("Error when process get /audio/:id, error: "+ e); res.send("Error from server"); } }); */ /* app.get('/wines', wine.findAll); app.get('/wines/:id', wine.findById); app.post('/wines', wine.addWine); app.put('/wines', wine.updateWine); app.delete('/wines/:id', wine.deleteWine); */ //gcm service //app.get('/services/gcm', bllUsers); // user service app.get('/services/users', user.findAllUsers); //app.get('/services/users/:id', user.findUserByUserId); app.get('/services/users/:facebookid',user.findUserByFacebookID); app.post('/services/users/searchname', user.findUserByUserName); app.post('/services/users', user.addUser); app.put('/services/users/:id', user.updateUser); app.delete('/services/users/:id', user.deleteUserByUserId); app.delete('/services/users', user.deleteAllUsers); //contact service app.get('/services/contacts', contact.findAllContacts); app.get('/services/contacts/byuserid/:id', contact.getAllContactByUserId); app.post('/services/contacts', contact.addContact); app.delete('/services/contacts', contact.deleteAllContacts); /* app.post('/services/contacts', user.addUser); app.put('/services/contacts/:id', user.updateUser); app.delete('/services/contacts/:id', user.deleteUserByUserId); */ //inbox service app.post('/services/inboxs/delete', inbox.deleteInboxs); app.post('/services/inboxs', inbox.addInbox); app.get('/services/inboxs', inbox.findAllInboxs); app.get('/services/inboxs/byuserid/:id', inbox.findInboxByUserId); app.delete('/services/inboxs', inbox.deleteAllInboxs); app.put('/services/inboxs', inbox.updateInboxs); //app.put('/services/inbox', inbox.updateInbox); //outbox service app.post('/services/outboxs/delete', outbox.deleteOutboxs); app.post('/services/outboxs', outbox.addOutbox); app.get('/services/outboxs', outbox.findAllInboxs); app.get('/services/outboxs/byuserid/:id', outbox.findOutboxByUserId); app.delete('/services/outboxs', outbox.deleteAllOutboxs); //device service app.post('/services/devices', device.addDevice); app.get('/services/devices', device.getAllDevices); app.get('/services/devices/byuserid/:id', device.getAllDevicesByUserId); app.delete('/services/devices', device.deleteAllDevices); //audio service app.post('/upload', audio.uploadAudio); app.get('/upload/view', function(req, res){ res.send( '<form action="/upload" method="post" enctype="multipart/form-data">'+ '<input type="file" name="source">'+ '<input type="submit" value="Upload">'+ '</form>' ); }); /************************test******************************************/ app.get('/convert', function(req, res){ function removeSubstring(str,strrm){ var newstr = str.replace(strrm,""); return newstr; } GLOBAL.__staticDir = removeSubstring(GLOBAL.__dirname,"/vivuserver/trunk"); var audioDir = GLOBAL.__staticDir + "/staticserver/public/audio/"; var soundlib = new GLOBAL.Sound; soundlib.convertWavToMp3(audioDir + "24.wav",audioDir + "testout1.mp3"); res.send("Ok"); }); /************************end test******************************************/ app.listen(GLOBAL.PORT); console.log('Listening on port 3000...');
// Javascript helper functions for parsing and displaying UUIDs in the MongoDB shell. // This is a temporary solution until SERVER-3153 is implemented. // To create BinData values corresponding to the various driver encodings use: // var s = "{00112233-4455-6677-8899-aabbccddeeff}"; // var uuid = UUID(s); // new Standard encoding // var juuid = JUUID(s); // JavaLegacy encoding // var csuuid = CSUUID(s); // CSharpLegacy encoding // var pyuuid = PYUUID(s); // PythonLegacy encoding // To convert the various BinData values back to human readable UUIDs use: // uuid.toUUID() => 'UUID("00112233-4455-6677-8899-aabbccddeeff")' // juuid.ToJUUID() => 'JUUID("00112233-4455-6677-8899-aabbccddeeff")' // csuuid.ToCSUUID() => 'CSUUID("00112233-4455-6677-8899-aabbccddeeff")' // pyuuid.ToPYUUID() => 'PYUUID("00112233-4455-6677-8899-aabbccddeeff")' // With any of the UUID variants you can use toHexUUID to echo the raw BinData with subtype and hex string: // uuid.toHexUUID() => 'HexData(4, "00112233-4455-6677-8899-aabbccddeeff")' // juuid.toHexUUID() => 'HexData(3, "77665544-3322-1100-ffee-ddccbbaa9988")' // csuuid.toHexUUID() => 'HexData(3, "33221100-5544-7766-8899-aabbccddeeff")' // pyuuid.toHexUUID() => 'HexData(3, "00112233-4455-6677-8899-aabbccddeeff")' function HexToBase64(hex) { var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; var base64 = ""; var group; for (var i = 0; i < 30; i += 6) { group = parseInt(hex.substr(i, 6), 16); base64 += base64Digits[(group >> 18) & 0x3f]; base64 += base64Digits[(group >> 12) & 0x3f]; base64 += base64Digits[(group >> 6) & 0x3f]; base64 += base64Digits[group & 0x3f]; } group = parseInt(hex.substr(30, 2), 16); base64 += base64Digits[(group >> 2) & 0x3f]; base64 += base64Digits[(group << 4) & 0x3f]; base64 += "=="; return base64; } function Base64ToHex(base64) { var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; var hexDigits = "0123456789abcdef"; var hex = ""; for (var i = 0; i < 24; ) { var e1 = base64Digits.indexOf(base64[i++]); var e2 = base64Digits.indexOf(base64[i++]); var e3 = base64Digits.indexOf(base64[i++]); var e4 = base64Digits.indexOf(base64[i++]); var c1 = (e1 << 2) | (e2 >> 4); var c2 = ((e2 & 15) << 4) | (e3 >> 2); var c3 = ((e3 & 3) << 6) | e4; hex += hexDigits[c1 >> 4]; hex += hexDigits[c1 & 15]; if (e3 != 64) { hex += hexDigits[c2 >> 4]; hex += hexDigits[c2 & 15]; } if (e4 != 64) { hex += hexDigits[c3 >> 4]; hex += hexDigits[c3 & 15]; } } return hex; } function UUID(uuid) { var hex = uuid.replace(/[{}-]/g, ""); // remove extra characters var base64 = HexToBase64(hex); return new BinData(4, base64); // new subtype 4 } function JUUID(uuid) { var hex = uuid.replace(/[{}-]/g, ""); // remove extra characters var msb = hex.substr(0, 16); var lsb = hex.substr(16, 16); msb = msb.substr(14, 2) + msb.substr(12, 2) + msb.substr(10, 2) + msb.substr(8, 2) + msb.substr(6, 2) + msb.substr(4, 2) + msb.substr(2, 2) + msb.substr(0, 2); lsb = lsb.substr(14, 2) + lsb.substr(12, 2) + lsb.substr(10, 2) + lsb.substr(8, 2) + lsb.substr(6, 2) + lsb.substr(4, 2) + lsb.substr(2, 2) + lsb.substr(0, 2); hex = msb + lsb; var base64 = HexToBase64(hex); return new BinData(3, base64); } function CSUUID(uuid) { var hex = uuid.replace(/[{}-]/g, ""); // remove extra characters var a = hex.substr(6, 2) + hex.substr(4, 2) + hex.substr(2, 2) + hex.substr(0, 2); var b = hex.substr(10, 2) + hex.substr(8, 2); var c = hex.substr(14, 2) + hex.substr(12, 2); var d = hex.substr(16, 16); hex = a + b + c + d; var base64 = HexToBase64(hex); return new BinData(3, base64); } function PYUUID(uuid) { var hex = uuid.replace(/[{}-]/g, ""); // remove extra characters var base64 = HexToBase64(hex); return new BinData(3, base64); } BinData.prototype.toUUID = function () { var hex = Base64ToHex(this.base64()); // don't use BinData's hex function because it has bugs in older versions of the shell var uuid = hex.substr(0, 8) + '-' + hex.substr(8, 4) + '-' + hex.substr(12, 4) + '-' + hex.substr(16, 4) + '-' + hex.substr(20, 12); return 'UUID("' + uuid + '")'; } BinData.prototype.toJUUID = function () { var hex = Base64ToHex(this.base64()); // don't use BinData's hex function because it has bugs in older versions of the shell var msb = hex.substr(0, 16); var lsb = hex.substr(16, 16); msb = msb.substr(14, 2) + msb.substr(12, 2) + msb.substr(10, 2) + msb.substr(8, 2) + msb.substr(6, 2) + msb.substr(4, 2) + msb.substr(2, 2) + msb.substr(0, 2); lsb = lsb.substr(14, 2) + lsb.substr(12, 2) + lsb.substr(10, 2) + lsb.substr(8, 2) + lsb.substr(6, 2) + lsb.substr(4, 2) + lsb.substr(2, 2) + lsb.substr(0, 2); hex = msb + lsb; var uuid = hex.substr(0, 8) + '-' + hex.substr(8, 4) + '-' + hex.substr(12, 4) + '-' + hex.substr(16, 4) + '-' + hex.substr(20, 12); return 'JUUID("' + uuid + '")'; } BinData.prototype.toCSUUID = function () { var hex = Base64ToHex(this.base64()); // don't use BinData's hex function because it has bugs in older versions of the shell var a = hex.substr(6, 2) + hex.substr(4, 2) + hex.substr(2, 2) + hex.substr(0, 2); var b = hex.substr(10, 2) + hex.substr(8, 2); var c = hex.substr(14, 2) + hex.substr(12, 2); var d = hex.substr(16, 16); hex = a + b + c + d; var uuid = hex.substr(0, 8) + '-' + hex.substr(8, 4) + '-' + hex.substr(12, 4) + '-' + hex.substr(16, 4) + '-' + hex.substr(20, 12); return 'CSUUID("' + uuid + '")'; } BinData.prototype.toPYUUID = function () { var hex = Base64ToHex(this.base64()); // don't use BinData's hex function because it has bugs var uuid = hex.substr(0, 8) + '-' + hex.substr(8, 4) + '-' + hex.substr(12, 4) + '-' + hex.substr(16, 4) + '-' + hex.substr(20, 12); return 'PYUUID("' + uuid + '")'; } BinData.prototype.toHexUUID = function () { var hex = Base64ToHex(this.base64()); // don't use BinData's hex function because it has bugs var uuid = hex.substr(0, 8) + '-' + hex.substr(8, 4) + '-' + hex.substr(12, 4) + '-' + hex.substr(16, 4) + '-' + hex.substr(20, 12); return 'HexData(' + this.subtype() + ', "' + uuid + '")'; } function TestUUIDHelperFunctions() { var s = "{00112233-4455-6677-8899-aabbccddeeff}"; var uuid = UUID(s); var juuid = JUUID(s); var csuuid = CSUUID(s); var pyuuid = PYUUID(s); print(uuid.toUUID()); print(juuid.toJUUID()); print(csuuid.toCSUUID()); print(pyuuid.toPYUUID()); print(uuid.toHexUUID()); print(juuid.toHexUUID()); print(csuuid.toHexUUID()); print(pyuuid.toHexUUID()); }
var assert = require('assert'); var RequestBuilder = require('../lib/rest-builder'); describe('REST Request Builder', function () { describe('Request templating', function () { var server = null; before(function (done) { var express = require('express'); var app = express(); app.configure(function () { app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.set('view engine', 'ejs'); app.use(express.favicon()); // app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); }); app.all('*', function (req, res, next) { res.setHeader('Content-Type', 'application/json'); var payload = { method: req.method, url: req.url, headers: req.headers, query: req.query, body: req.body }; res.json(200, payload); }); server = app.listen(app.get('port'), function (err, data) { // console.log('Server listening on ', app.get('port')); done(err, data); }); }); after(function(done) { server && server.close(done); }); it('should substitute the variables', function (done) { var builder = new RequestBuilder('GET', 'http://localhost:3000/{p}').query({x: '{x}', y: 2}); builder.invoke({p: 1, x: 'X'}, function (err, body, response) { // console.log(response.headers); assert.equal(200, response.statusCode); if (typeof body === 'string') { body = JSON.parse(body); } // console.log(body); assert.equal(body.query.x, 'X'); assert.equal(body.query.y, 2); done(err, body); }); }); it('should support default variables', function (done) { var builder = new RequestBuilder('GET', 'http://localhost:3000/{p=100}').query({x: '{x=ME}', y: 2}); builder.invoke({p: 1}, function (err, body, response) { // console.log(response.headers); assert.equal(200, response.statusCode); if (typeof body === 'string') { body = JSON.parse(body); } // console.log(body); assert.equal(0, body.url.indexOf('/1')); assert.equal('ME', body.query.x); assert.equal(2, body.query.y); done(err, body); }); }); it('should support typed variables', function (done) { var builder = new RequestBuilder('POST', 'http://localhost:3000/{p=100}').query({x: '{x=100:number}', y: 2}) .body({a: '{a=1:number}', b: '{b=true:boolean}'}); builder.invoke({p: 1, a: 100, b: false}, function (err, body, response) { // console.log(response.headers); assert.equal(200, response.statusCode); if (typeof body === 'string') { body = JSON.parse(body); } // console.log(body); assert.equal(0, body.url.indexOf('/1')); assert.equal(100, body.query.x); assert.equal(2, body.query.y); assert.equal(100, body.body.a); assert.equal(false, body.body.b); done(err, body); }); }); it('should report missing required variables', function (done) { var builder = new RequestBuilder('POST', 'http://localhost:3000/{!p}').query({x: '{x=100:number}', y: 2}) .body({a: '{^a:number}', b: '{!b=true:boolean}'}); try { builder.invoke({a: 100, b: false}, function (err, body, response) { // console.log(response.headers); assert.equal(200, response.statusCode); if (typeof body === 'string') { body = JSON.parse(body); } // console.log(body); done(err, body); }); assert.fail(); } catch(err) { // This is expected done(null, null); } }); it('should support required variables', function (done) { var builder = new RequestBuilder('POST', 'http://localhost:3000/{!p}').query({x: '{x=100:number}', y: 2}) .body({a: '{^a:number}', b: '{!b=true:boolean}'}); builder.invoke({p: 1, a: 100, b: false}, function (err, body, response) { // console.log(response.headers); assert.equal(200, response.statusCode); if (typeof body === 'string') { body = JSON.parse(body); } // console.log(body); assert.equal(0, body.url.indexOf('/1')); assert.equal(100, body.query.x); assert.equal(2, body.query.y); assert.equal(100, body.body.a); assert.equal(false, body.body.b); done(err, body); }); }); it('should build an operation with the parameter names', function (done) { var builder = new RequestBuilder('POST', 'http://localhost:3000/{p}').query({x: '{x}', y: 2}); var fn = builder.operation(['p', 'x']); fn(1, 'X', function (err, body, response) { assert.equal(200, response.statusCode); if (typeof body === 'string') { body = JSON.parse(body); } // console.log(body); assert.equal(0, body.url.indexOf('/1')); assert.equal('X', body.query.x); assert.equal(2, body.query.y); // console.log(body); done(err, body); }); }); it('should build an operation with the parameter names as args', function (done) { var builder = new RequestBuilder('POST', 'http://localhost:3000/{p}').query({x: '{x}', y: 2}); var fn = builder.operation('p', 'x'); fn(1, 'X', function (err, body, response) { assert.equal(200, response.statusCode); if (typeof body === 'string') { body = JSON.parse(body); } // console.log(body); assert.equal(0, body.url.indexOf('/1')); assert.equal('X', body.query.x); assert.equal(2, body.query.y); // console.log(body); done(err, body); }); }); it('should build from a json doc', function (done) { var builder = new RequestBuilder(require('./request-template.json')); // console.log(builder.parse()); builder.invoke({p: 1, a: 100, b: false}, function (err, body, response) { // console.log(response.headers); assert.equal(200, response.statusCode); if (typeof body === 'string') { body = JSON.parse(body); } // console.log(body); assert.equal(0, body.url.indexOf('/1')); assert.equal(100, body.query.x); assert.equal(2, body.query.y); assert.equal(100, body.body.a); assert.equal(false, body.body.b); done(err, body); }); }); }); });
/** * Copyright 2015 aixigo AG * Released under the MIT license. * http://laxarjs.org/license */ require( [ 'laxar', 'laxar-application/var/flows/embed/dependencies', 'json!laxar-application/var/flows/embed/resources.json' ], function( ax, mainDependencies, mainResources ) { 'use strict'; window.laxar.fileListings = { application: mainResources, bower_components: mainResources, includes: mainResources }; ax.bootstrap( mainDependencies ); } );
import React from 'react'; import Tap from '../hahoo/Tap'; class BtnUpLevel extends React.Component { static propTypes = { onItemClick: React.PropTypes.func } state = {} render() { const { onItemClick, ...rest } = this.props; return (<Tap onTap={onItemClick} className="btn btn-default" {...rest} ><i className="fa fa-arrow-circle-up fa-fw" /> 上级</Tap>); } } export default BtnUpLevel;
"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.default = void 0; var _graphqlRelay = require("graphql-relay"); var _EnsayoType = _interopRequireDefault(require("./EnsayoType"));function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}var _default = (0, _graphqlRelay.connectionDefinitions)({ name: 'Ensayos', nodeType: _EnsayoType.default });exports.default = _default; //# sourceMappingURL=EnsayosConnection.js.map
/** * @author Phuluong * Feb 13, 2016 */ /** Exports **/ module.exports = new Config(); /** Imports **/ var fs = require("fs"); var util = require(__dir + '/core/app/util'); /** Modules **/ function Config() { var configContainer = {}; /** * Get config value by key * @param {String} key * @param {} defaultValue * @returns {} */ this.get = function (key, defaultValue) { var retval = defaultValue; if (configContainer[key] != null) { retval = configContainer[key]; } else { key = key.replaceAll(".", "/"); var path = __dir + "/config/" + key; var parentPath = path.substring(0, path.lastIndexOf("/")); try { var property = path.substring(path.lastIndexOf("/") + 1, path.length); if (fs.existsSync(path + ".js")) { retval = require(path); } else if (fs.existsSync(parentPath + ".js")) { if ((require(parentPath))[property] != null) { retval = (require(parentPath))[property]; } } else if (key.indexOf("package") == 0) { retval = (require(__dir + "/package.json"))[property]; } configContainer[key] = retval; } catch (exc) { } } if (retval == null) { } return retval; }; /** * Set config value * @param {String} key * @param {} value */ this.set = function (key, value) { configContainer[key] = value; }; }
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'addressbook-app', environment: environment, baseURL: '/', locationType: 'auto', emberPouch: { localDb: 'dentone-addressbook', remoteDb: 'https://wasilleptichandfurningio:[email protected]/addressbook/' }, EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, contentSecurityPolicy:{ 'default-src': "'none'", 'script-src': "'self' 'unsafe-inline'", 'style-src': "'self' 'unsafe-inline' https://fonts.googleapis.com", 'font-src': "'self' fonts.gstatic.com", 'connect-src': "'self' https://dentone.cloudant.com/", 'img-src': "'self' data:", 'media-src': "'self'" }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { } return ENV; };
/* global describe, before, it */ require('mocha') require('should') var async = require('async') var testUtils = require('./testUtils') var errorMessage = require('../errorMessages/errorMessages') var mongo_dcms_core = require('../index') describe('should get file Content by file id', function () { var filepath = './test/testAsset/testTextFile.txt' var savedFileId var document = { filePath: filepath, fileName: 'testTextFile.txt', contentType: 'binary/octet-stream', identityMetaData: { projectId: 10 } } before(function (done) { this.timeout(5000) async.series([ function (callback) { testUtils.clearDb(callback) }, function (callback) { mongo_dcms_core.connect(testUtils.dbUrl) mongo_dcms_core.uploadFile(document, {}, function (err, sucess) { if (err) { callback(err) } else { savedFileId = sucess.fileId callback(null) } }) } ], done) }) it('should get file Content by file id', function (done) { mongo_dcms_core.getFileContentByFileId(savedFileId, function (err, sucess) { if (err) { err.should.equal(null) done() } else { sucess.fileData.should.not.equal(null) sucess.contentType.should.equal('binary/octet-stream') sucess.fileName.should.equal('testTextFile.txt') sucess.fileMetaData.should.not.equal(null) sucess.fileMetaData.should.not.equal(undefined) done() } }) }) it('should return message file not found', function (done) { mongo_dcms_core.getFileContentByFileId('56f0dc0ca80f6cc01929cd1e', function (err, sucess) { if (err) { err.should.equal(errorMessage.fileNotFoundForSpecifiedFileId) done() } else { sucess.should.equal(null) done() } }) }) })
/** * Lawnchair! * --- * clientside json store * */ var Lawnchair = function () { // lawnchair requires json if (!JSON) throw 'JSON unavailable! Include http://www.json.org/json2.js to fix.' // options are optional; callback is not if (arguments.length <= 2 && arguments.length > 0) { var callback = (typeof arguments[0] === 'function') ? arguments[0] : arguments[1] , options = (typeof arguments[0] === 'function') ? {} : arguments[0] } else { throw 'Incorrect # of ctor args!' } if (typeof callback !== 'function') throw 'No callback was provided'; // default configuration this.record = options.record || 'record' // default for records this.name = options.name || 'records' // default name for underlying store // mixin first valid adapter var adapter // if the adapter is passed in we try to load that only if (options.adapter) { adapter = Lawnchair.adapters[Lawnchair.adapters.indexOf(options.adapter)] adapter = adapter.valid() ? adapter : undefined // otherwise find the first valid adapter for this env } else { for (var i = 0, l = Lawnchair.adapters.length; i < l; i++) { adapter = Lawnchair.adapters[i].valid() ? Lawnchair.adapters[i] : undefined if (adapter) break } } // we have failed if (!adapter) throw 'No valid adapter.' // yay! mixin the adapter for (var j in adapter) { this[j] = adapter[j] } // call init for each mixed in plugin for (var i = 0, l = Lawnchair.plugins.length; i < l; i++) Lawnchair.plugins[i].call(this) // init the adapter this.init(options, callback) } Lawnchair.adapters = [] /** * queues an adapter for mixin * === * - ensures an adapter conforms to a specific interface * */ Lawnchair.adapter = function (id, obj) { // add the adapter id to the adapter obj // ugly here for a cleaner dsl for implementing adapters obj['adapter'] = id // methods required to implement a lawnchair adapter var implementing = 'adapter valid init keys save batch get exists all remove nuke'.split(' ') // mix in the adapter for (var i in obj) if (implementing.indexOf(i) === -1) throw 'Invalid adapter! Nonstandard method: ' + i // if we made it this far the adapter interface is valid Lawnchair.adapters.push(obj) } Lawnchair.plugins = [] /** * generic shallow extension for plugins * === * - if an init method is found it registers it to be called when the lawnchair is inited * - yes we could use hasOwnProp but nobody here is an asshole */ Lawnchair.plugin = function (obj) { for (var i in obj) i === 'init' ? Lawnchair.plugins.push(obj[i]) : this.prototype[i] = obj[i] } /** * helpers * */ Lawnchair.prototype = { isArray: Array.isArray || function(o) { return Object.prototype.toString.call(o) === '[object Array]' }, // awesome shorthand callbacks as strings. this is shameless theft from dojo. lambda: function (callback) { return this.fn(this.record, callback) }, // first stab at named parameters for terse callbacks; dojo: first != best // ;D fn: function (name, callback) { return typeof callback == 'string' ? new Function(name, callback) : callback }, // returns a unique identifier (by way of Backbone.localStorage.js) // TODO investigate smaller UUIDs to cut on storage cost uuid: function () { var S4 = function () { return (((1+Math.random())*0x10000)|0).toString(16).substring(1); } return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4()); }, // a classic iterator each: function (callback) { var cb = this.lambda(callback) // iterate from chain if (this.__results) { for (var i = 0, l = this.__results.length; i < l; i++) cb.call(this, this.__results[i], i) } // otherwise iterate the entire collection else { this.all(function(r) { for (var i = 0, l = r.length; i < l; i++) cb.call(this, r[i], i) }) } return this } // -- }; Lawnchair.adapter('webkit-sqlite', (function () { // private methods var fail = function (e, i) { console.log('error in sqlite adaptor!', e, i) } , now = function () { return new Date() } // FIXME need to use better date fn // not entirely sure if this is needed... if (!Function.prototype.bind) { Function.prototype.bind = function( obj ) { var slice = [].slice , args = slice.call(arguments, 1) , self = this , nop = function () {} , bound = function () { return self.apply(this instanceof nop ? this : (obj || {}), args.concat(slice.call(arguments))) } nop.prototype = self.prototype bound.prototype = new nop() return bound } } // public methods return { valid: function() { return !!(window.openDatabase) }, init: function (options, callback) { var that = this , cb = that.fn(that.name, callback) , create = "CREATE TABLE IF NOT EXISTS " + this.name + " (id NVARCHAR(32) UNIQUE PRIMARY KEY, value TEXT, timestamp REAL)" , win = cb.bind(this) // open a connection and create the db if it doesn't exist this.db = openDatabase(this.name, '1.0.0', this.name, 65536) this.db.transaction(function (t) { t.executeSql(create, [], win, fail) }) }, keys: function (callback) { var cb = this.lambda(callback) , that = this , keys = "SELECT id FROM " + this.name + " ORDER BY timestamp DESC" this.db.transaction(function(t) { var win = function (xxx, results) { if (results.rows.length == 0 ) { cb.call(that, []) } else { var r = []; for (var i = 0, l = results.rows.length; i < l; i++) { r.push(results.rows.item(i).id); } cb.call(that, r) } } t.executeSql(keys, [], win, fail) }) return this }, // you think thats air you're breathing now? save: function (obj, callback) { var that = this , id = obj.key || that.uuid() , ins = "INSERT INTO " + this.name + " (value, timestamp, id) VALUES (?,?,?)" , up = "UPDATE " + this.name + " SET value=?, timestamp=? WHERE id=?" , win = function () { if (callback) { obj.key = id; that.lambda(callback).call(that, obj) }} , val = [now(), id] // existential that.exists(obj.key, function(exists) { // transactions are like condoms that.db.transaction(function(t) { // TODO move timestamp to a plugin var insert = function (obj) { val.unshift(JSON.stringify(obj)) t.executeSql(ins, val, win, fail) } // TODO move timestamp to a plugin var update = function (obj) { delete(obj.key) val.unshift(JSON.stringify(obj)) t.executeSql(up, val, win, fail) } // pretty exists ? update(obj) : insert(obj) }) }); return this }, // FIXME this should be a batch insert / just getting the test to pass... batch: function (objs, cb) { var results = [] , done = false , that = this var updateProgress = function(obj) { results.push(obj) done = results.length === objs.length } var checkProgress = setInterval(function() { if (done) { if (cb) that.lambda(cb).call(that, results) clearInterval(checkProgress) } }, 200) for (var i = 0, l = objs.length; i < l; i++) this.save(objs[i], updateProgress) return this }, get: function (keyOrArray, cb) { var that = this , sql = '' // batch selects support if (this.isArray(keyOrArray)) { sql = 'SELECT id, value FROM ' + this.name + " WHERE id IN ('" + keyOrArray.join("','") + "')" } else { sql = 'SELECT id, value FROM ' + this.name + " WHERE id = '" + keyOrArray + "'" } // FIXME // will always loop the results but cleans it up if not a batch return at the end.. // in other words, this could be faster var win = function (xxx, results) { var o = null , r = [] if (results.rows.length) { for (var i = 0, l = results.rows.length; i < l; i++) { o = JSON.parse(results.rows.item(i).value) o.key = results.rows.item(i).id r.push(o) } } if (!that.isArray(keyOrArray)) r = r.length ? r[0] : null if (cb) that.lambda(cb).call(that, r) } this.db.transaction(function(t){ t.executeSql(sql, [], win, fail) }) return this }, exists: function (key, cb) { var is = "SELECT * FROM " + this.name + " WHERE id = ?" , that = this , win = function(xxx, results) { if (cb) that.fn('exists', cb).call(that, (results.rows.length > 0)) } this.db.transaction(function(t){ t.executeSql(is, [key], win, fail) }) return this }, all: function (callback) { var that = this , all = "SELECT * FROM " + this.name , r = [] , cb = this.fn(this.name, callback) || undefined , win = function (xxx, results) { if (results.rows.length != 0) { for (var i = 0, l = results.rows.length; i < l; i++) { var obj = JSON.parse(results.rows.item(i).value) obj.key = results.rows.item(i).id r.push(obj) } } if (cb) cb.call(that, r) } this.db.transaction(function (t) { t.executeSql(all, [], win, fail) }) return this }, remove: function (keyOrObj, cb) { var that = this , key = typeof keyOrObj === 'string' ? keyOrObj : keyOrObj.key , del = "DELETE FROM " + this.name + " WHERE id = ?" , win = function () { if (cb) that.lambda(cb).call(that) } this.db.transaction( function (t) { t.executeSql(del, [key], win, fail); }); return this; }, nuke: function (cb) { var nuke = "DELETE FROM " + this.name , that = this , win = cb ? function() { that.lambda(cb).call(that) } : function(){} this.db.transaction(function (t) { t.executeSql(nuke, [], win, fail) }) return this } ////// }})())
(function(){function h(a){return function(){return this[a]}}var k=this;function n(a){return"string"==typeof a}function p(a,c){var b=a.split("."),d=k;!(b[0]in d)&&d.execScript&&d.execScript("var "+b[0]);for(var e;b.length&&(e=b.shift());)!b.length&&void 0!==c?d[e]=c:d=d[e]?d[e]:d[e]={}};var q="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function s(a){var c=Number(a);return 0==c&&/^[\s\xa0]*$/.test(a)?NaN:c};function t(a,c){this.b=a|0;this.a=c|0}var v={};function w(a){if(-128<=a&&128>a){var c=v[a];if(c)return c}c=new t(a|0,0>a?-1:0);-128<=a&&128>a&&(v[a]=c);return c}function x(a){return isNaN(a)||!isFinite(a)?y:a<=-z?A:a+1>=z?aa:0>a?B(x(-a)):new t(a%C|0,a/C|0)} function D(a,c){if(0==a.length)throw Error("number format error: empty string");var b=c||10;if(2>b||36<b)throw Error("radix out of range: "+b);if("-"==a.charAt(0))return B(D(a.substring(1),b));if(0<=a.indexOf("-"))throw Error('number format error: interior "-" character: '+a);for(var d=x(Math.pow(b,8)),e=y,f=0;f<a.length;f+=8){var g=Math.min(8,a.length-f),m=parseInt(a.substring(f,f+g),b);8>g?(g=x(Math.pow(b,g)),e=e.multiply(g).add(x(m))):(e=e.multiply(d),e=e.add(x(m)))}return e} var C=4294967296,z=C*C/2,y=w(0),E=w(1),F=w(-1),aa=new t(-1,2147483647),A=new t(0,-2147483648),G=w(16777216); t.prototype.toString=function(a){a=a||10;if(2>a||36<a)throw Error("radix out of range: "+a);if(H(this))return"0";if(0>this.a){if(I(this,A)){var c=x(a),b=J(this,c),c=L(b.multiply(c),this);return b.toString(a)+c.b.toString(a)}return"-"+B(this).toString(a)}for(var b=x(Math.pow(a,6)),c=this,d="";;){var e=J(c,b),f=L(c,e.multiply(b)).b.toString(a),c=e;if(H(c))return f+d;for(;6>f.length;)f="0"+f;d=""+f+d}};function M(a){return 0<=a.b?a.b:C+a.b}function H(a){return 0==a.a&&0==a.b} function I(a,c){return a.a==c.a&&a.b==c.b}function N(a,c){if(I(a,c))return 0;var b=0>a.a,d=0>c.a;return b&&!d?-1:!b&&d?1:0>L(a,c).a?-1:1}function B(a){return I(a,A)?A:(new t(~a.b,~a.a)).add(E)}t.prototype.add=function(a){var c=this.a>>>16,b=this.a&65535,d=this.b>>>16,e=a.a>>>16,f=a.a&65535,g=a.b>>>16,m;m=0+((this.b&65535)+(a.b&65535));a=0+(m>>>16);a+=d+g;d=0+(a>>>16);d+=b+f;b=0+(d>>>16);b=b+(c+e)&65535;return new t((a&65535)<<16|m&65535,b<<16|d&65535)};function L(a,c){return a.add(B(c))} t.prototype.multiply=function(a){if(H(this)||H(a))return y;if(I(this,A))return 1==(a.b&1)?A:y;if(I(a,A))return 1==(this.b&1)?A:y;if(0>this.a)return 0>a.a?B(this).multiply(B(a)):B(B(this).multiply(a));if(0>a.a)return B(this.multiply(B(a)));if(0>N(this,G)&&0>N(a,G))return x((this.a*C+M(this))*(a.a*C+M(a)));var c=this.a>>>16,b=this.a&65535,d=this.b>>>16,e=this.b&65535,f=a.a>>>16,g=a.a&65535,m=a.b>>>16;a=a.b&65535;var u,l,r,K;K=0+e*a;r=0+(K>>>16);r+=d*a;l=0+(r>>>16);r=(r&65535)+e*m;l+=r>>>16;r&=65535; l+=b*a;u=0+(l>>>16);l=(l&65535)+d*m;u+=l>>>16;l&=65535;l+=e*g;u+=l>>>16;l&=65535;u=u+(c*a+b*m+d*g+e*f)&65535;return new t(r<<16|K&65535,u<<16|l)}; function J(a,c){if(H(c))throw Error("division by zero");if(H(a))return y;if(I(a,A)){if(I(c,E)||I(c,F))return A;if(I(c,A))return E;var b;b=1;if(0==b)b=a;else{var d=a.a;b=32>b?new t(a.b>>>b|d<<32-b,d>>b):new t(d>>b-32,0<=d?0:-1)}b=J(b,c).shiftLeft(1);if(I(b,y))return 0>c.a?E:F;d=L(a,c.multiply(b));return b.add(J(d,c))}if(I(c,A))return y;if(0>a.a)return 0>c.a?J(B(a),B(c)):B(J(B(a),c));if(0>c.a)return B(J(a,B(c)));for(var e=y,d=a;0<=N(d,c);){b=Math.max(1,Math.floor((d.a*C+M(d))/(c.a*C+M(c))));for(var f= Math.ceil(Math.log(b)/Math.LN2),f=48>=f?1:Math.pow(2,f-48),g=x(b),m=g.multiply(c);0>m.a||0<N(m,d);)b-=f,g=x(b),m=g.multiply(c);H(g)&&(g=E);e=e.add(g);d=L(d,m)}return e}t.prototype.shiftLeft=function(a){a&=63;if(0==a)return this;var c=this.b;return 32>a?new t(c<<a,this.a<<a|c>>>32-a):new t(0,c<<a-32)};var O=Array.prototype,P=O.forEach?function(a,c,b){O.forEach.call(a,c,b)}:function(a,c,b){for(var d=a.length,e=n(a)?a.split(""):a,f=0;f<d;f++)f in e&&c.call(b,e[f],f,a)},Q=O.map?function(a,c,b){return O.map.call(a,c,b)}:function(a,c,b){for(var d=a.length,e=Array(d),f=n(a)?a.split(""):a,g=0;g<d;g++)g in f&&(e[g]=c.call(b,f[g],g,a));return e};function R(a,c,b){if(a.reduce)return a.reduce(c,b);var d=b;P(a,function(b,f){d=c.call(void 0,d,b,f,a)});return d} function S(a,c,b){return 2>=arguments.length?O.slice.call(a,c):O.slice.call(a,c,b)};function T(a){return U(1,arguments,function(a,b){return a.add(b)})}function V(a,c){var b=W(2,[a,c]).d;return X(b[0]/b[1])}function Y(a){return U(3,arguments,function(a,b){return L(a,b)})}function Z(a){return U(4,arguments,function(a,b){return a.multiply(b)})} function $(a){if("number"==typeof a)return a;var c=a.toString(),b=a.c;if(0!=b){var d;a=!1;"-"==c.charAt(0)&&(a=!0,c=c.replace(/^\-/,""));c.length<=b?(c=String(s(c)),d=c.indexOf("."),-1==d&&(d=c.length),b=Math.max(0,b-d),d=Array(b+1).join("0")+c,b="0"):(d=c.slice(-b),b=c.slice(0,-b));c=(a?"-":"")+b+"."+d}return s(c)}function U(a,c,b){c=W(a,c);b=R(S(c.d,1),b,c.d[0]);b.k(a,c.d.length,c.i);return b} function X(a){if(!n(a)&&"number"!=typeof a)throw Error('Invalid value: "'+a+'"');a=s(String(a));var c=String(a),b,d;if(d=c.match(/\.(\d+)$/)){b=D;var e=RegExp,f;f=".".replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g,"\\$1").replace(/\x08/g,"\\x08");e=e(f,"");c=c.replace(e,"");b=b(c);b.e(a,d[1].length)}else b=D(c),b.e(a);return b} function W(a,c){c=Q(c,function(a){return a instanceof t?a:X(a)});if(4==a){var b=R(c,function(a,b){return a+b.c},0);return{d:c,i:b}}var d=Math.max.apply(null,Q(c,function(a){return a.c}));if(0!=d){var e,f;c=Q(c,function(a){e=d-a.c;return 0!=e?(f=a.multiply(x(Math.pow(10,e))),f.j(a),f):a})}return{d:c,i:d}} (function(a,c){for(var b,d,e=1;e<arguments.length;e++){d=arguments[e];for(b in d)a[b]=d[b];for(var f=0;f<q.length;f++)b=q[f],Object.prototype.hasOwnProperty.call(d,b)&&(a[b]=d[b])}})(t.prototype,{f:void 0,c:0,h:null,g:0,k:function(a,c,b){this.h=a;this.g=c;this.c=b},n:h("h"),m:h("g"),e:function(a,c){a&&(this.f=a);this.c=c||0},j:function(a){this.e(a.f,a.c)},p:h("f"),o:h("c"),l:function(){return 0!=this.c}}); p("sao.calc",function(a){var c,b=[],d=[];P(arguments,function(a){n(a)&&/^\+|\-|\*|\/$/.test(a)?b[b.length]=a:d[d.length]=a});c=R(S(d,1),function(a,c){switch(b.shift()){case "+":return T(a,c);case "-":return Y(a,c);case "/":return V(a,c);case "*":return Z(a,c)}},d[0]);return $(c)});p("sao.add",T);p("sao.div",V);p("sao.sub",Y);p("sao.mul",Z);p("sao.finalize",$); p("sao.round",function(a,c){var b="number"==typeof a?X(a):a,d=b.toString().replace(/^\-/,""),e=c||0;if(b.l()&&!(b.c<=e)){var f=b.c,d=d.charAt(d.length-f+e),b=X(b.toString().slice(0,-(f-e)));b.e(void 0,e);4<s(d)?(e=x(1),e=0>b.a?B(e):e,e=b.add(e),e.j(b)):e=b;return $(e)}return $(b)});})()
/** * drcProcess * Created by dcorns on 1/2/15. */ 'use strict'; var RunApp = require('./runApp'); var Server = require('./server'); var parseInput = require('./parseInput'); var CommandList = require('./commandList'); var runApp = new RunApp(); var cmds = new CommandList(); cmds.add(['ls', 'pwd', 'service', 'ps']); var firstServer = new Server('firstServer'); firstServer.start(3000, function(err, cnn){ cnn.on('data', function(data){ parseInput(data, function(err, obj){ if(err) cnn.write(err); else { if(obj.cmd.substr(0, 6) === 'login:'){ cnn.loginID = obj.cmd.substr(6); cnn.write('Welcome ' + cnn.loginID + '\r\n'); cnn.write('Valid Commands: ' + cmds.listCommands() + '\r\n'); cnn.write('Use # to add parameters: example: ls#/\r\n'); cnn.write('Use - to add options: example: ls#/ -al or ls#-al\r\n'); console.log(cnn.loginID + ' connected'); } else { if(cmds.validate(obj.cmd) > -1){ runApp.run(obj.params, cnn, obj.cmd); } else{ cnn.write('Valid commands: ' + cmds.listCommands()); } } } }); }); });
"use strict"; const tester = require("./framework"); const repeatAsyncUntil = require("../source/regularly"); module.exports = tester.run([ tester.make("repeatAsyncUntil() should repeat calls to λ while predicate returns false", async () => { let executionsCount = 0; const λ = async () => ++executionsCount; const predicate = async () => executionsCount === 2; await repeatAsyncUntil(λ, predicate); return executionsCount === 2; }) ]);
import {ATTACHMENTS} from "../constants"; export default (...args) => { // Use one or the other const attachments = args.length ? args : ATTACHMENTS; return { props: { attach: { type: String, validator: value => value === "" || attachments.includes(value) } }, computed: { getAttach() { if(typeof this.attach === "string") { return this.attach ? `${this.attach} attached` : "attached"; } } } }; };
'use strict'; module.exports = Source; const inherits = require('util').inherits; const Stream = require('../stream'); const Chunk = require('../chunk'); const Compose = require('../through/compose'); const Break = require('../through/break'); const Filter = require('../through/filter'); const Map = require('../through/map'); const Take = require('../through/take'); const Each = require('../feed/each'); const Value = require('../feed/value'); module.exports = Source; inherits(Source, Stream); function Source(){ Stream.call(this); this.async = false; } Source.prototype.iterator = function iterator() { return new this.constructor.Iterator(this); }; Source.prototype.pipe = function pipe(feed) { return feed.feed([this]); }; Source.prototype.break = function breake(fn, async){ return this.pipe(new Break(fn, async)); }; Source.prototype.filter = function filter(fn, async){ return this.pipe(new Filter(fn, async)); }; Source.prototype.map = function map(fn, async){ return this.pipe(new Map(fn, async)); }; Source.prototype.take = function take(max){ return this.pipe(new Take(max)); }; Source.prototype.each = function each(fn){ return this.pipe(new Each(fn)); }; Source.prototype.value = function value(async){ return this.pipe(new Value(async)); };
// Idea and initial code from https://github.com/aomra015/ember-cli-chart import Ember from 'ember'; export default Ember.Component.extend({ tagName: 'canvas', attributeBindings: ['width', 'height'], onlyValues: false, chartData: {}, didInsertElement: function(){ var context = this.get('element').getContext('2d'); var type = Ember.String.classify(this.get('type')); var options = { responsive: true, showTooltips: true, pointDot: true, pointDotRadius: 3, pointHitDetectionRadius: 8, bezierCurve: false, barValueSpacing: 1, datasetStrokeWidth: 3 }; // animation is very sexy, but it hogs browser. Waiting for chart.js 2.0 // https://github.com/nnnick/Chart.js/issues/653 options.animation = false; if (this.get("onlyValues")) { options.showScale = false; } var data = {labels: [], datasets: []}; this.get("chartData.labels").forEach((l) => { data.labels.push(l); }); this.get("chartData.datasets").forEach((ds) => { var dataSet = this._chartColors(ds.label); dataSet.data = ds.data.map((v) => { return v; }); data.datasets.push(dataSet); }); var chart = new Chart(context)[type](data, options); this.set('chart', chart); }, willDestroyElement: function(){ this.get('chart').destroy(); }, updateChart: function() { //// redraw // this.willDestroyElement(); // this.didInsertElement(); var chart = this.get("chart"); while (chart.scale.xLabels.length && chart.scale.xLabels[0] !== this.get("chartData.labels")[0]) { chart.removeData(); } this.get("chartData.labels").forEach((label, i) => { if (i < chart.scale.xLabels.length) { this.get("chartData.datasets").forEach((ds, j) => { if (this.get("type") === "Line") { chart.datasets[j].points[i].value = ds.data[i]; } else { chart.datasets[j].bars[i].value = ds.data[i]; } }); } else { var values = []; this.get("chartData.datasets").forEach((ds) => { values.push(ds.data[i]); }); chart.addData(values, label); } }); chart.update(); }.observes("chartData", "chartData.[]"), _chartColors: function(label) { if (label === "count") { return { fillColor: "rgba(151,187,205,1)", strokeColor: "rgba(151,187,205,1)" }; } else { var base = { max: "203,46,255", up: "46,255,203", avg: "46,203,255", min: "46,98,255", sum: "98,56,255", }[label] || "151,187,205"; return { fillColor: "rgba(" + base + ",0.03)", strokeColor: "rgba(" + base + ",0.5)", pointColor: "rgba(" + base + ",0.5)", // pointStrokeColor: "red", //"rgba(" + base + ")", // pointHighlightFill: "green", //"rgba(" + base + ")", // pointHighlightStroke: "blue",// "rgba(" + base + ")", // pointStrokeColor: "#fff", // pointHighlightFill: "#fff", // pointHighlightStroke: "rgba(220,220,220,1)", }; } } });
/* * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved. * * 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. * */ /*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */ /*global define, $, CodeMirror, window */ /** * Editor is a 1-to-1 wrapper for a CodeMirror editor instance. It layers on Brackets-specific * functionality and provides APIs that cleanly pass through the bits of CodeMirror that the rest * of our codebase may want to interact with. An Editor is always backed by a Document, and stays * in sync with its content; because Editor keeps the Document alive, it's important to always * destroy() an Editor that's going away so it can release its Document ref. * * For now, there's a distinction between the "master" Editor for a Document - which secretly acts * as the Document's internal model of the text state - and the multitude of "slave" secondary Editors * which, via Document, sync their changes to and from that master. * * For now, direct access to the underlying CodeMirror object is still possible via _codeMirror -- * but this is considered deprecated and may go away. * * The Editor object dispatches the following events: * - keyEvent -- When any key event happens in the editor (whether it changes the text or not). * Event handlers are passed ({Editor}, {KeyboardEvent}). The 2nd arg is the raw DOM event. * Note: most listeners will only want to respond when event.type === "keypress". * - cursorActivity -- When the user moves the cursor or changes the selection, or an edit occurs. * Note: do not listen to this in order to be generally informed of edits--listen to the * "change" event on Document instead. * - scroll -- When the editor is scrolled, either by user action or programmatically. * - lostContent -- When the backing Document changes in such a way that this Editor is no longer * able to display accurate text. This occurs if the Document's file is deleted, or in certain * Document->editor syncing edge cases that we do not yet support (the latter cause will * eventually go away). * * The Editor also dispatches "change" events internally, but you should listen for those on * Documents, not Editors. * * These are jQuery events, so to listen for them you do something like this: * $(editorInstance).on("eventname", handler); */ define(function (require, exports, module) { "use strict"; var EditorManager = require("editor/EditorManager"), CodeHintManager = require("editor/CodeHintManager"), Commands = require("command/Commands"), CommandManager = require("command/CommandManager"), Menus = require("command/Menus"), PerfUtils = require("utils/PerfUtils"), PreferencesManager = require("preferences/PreferencesManager"), Strings = require("strings"), TextRange = require("document/TextRange").TextRange, ViewUtils = require("utils/ViewUtils"); var PREFERENCES_CLIENT_ID = "com.adobe.brackets.Editor", defaultPrefs = { useTabChar: false, tabSize: 4, indentUnit: 4 }; /** Editor preferences */ var _prefs = PreferencesManager.getPreferenceStorage(PREFERENCES_CLIENT_ID, defaultPrefs); /** @type {boolean} Global setting: When inserting new text, use tab characters? (instead of spaces) */ var _useTabChar = _prefs.getValue("useTabChar"); /** @type {boolean} Global setting: Tab size */ var _tabSize = _prefs.getValue("tabSize"); /** @type {boolean} Global setting: Indent unit (i.e. number of spaces when indenting) */ var _indentUnit = _prefs.getValue("indentUnit"); /** * @private * Handle Tab key press. * @param {!CodeMirror} instance CodeMirror instance. */ function _handleTabKey(instance) { // Tab key handling is done as follows: // 1. If the selection is before any text and the indentation is to the left of // the proper indentation then indent it to the proper place. Otherwise, // add another tab. In either case, move the insertion point to the // beginning of the text. // 2. If the selection is after the first non-space character, and is not an // insertion point, indent the entire line(s). // 3. If the selection is after the first non-space character, and is an // insertion point, insert a tab character or the appropriate number // of spaces to pad to the nearest tab boundary. var from = instance.getCursor(true), to = instance.getCursor(false), line = instance.getLine(from.line), indentAuto = false, insertTab = false; if (from.line === to.line) { if (line.search(/\S/) > to.ch || to.ch === 0) { indentAuto = true; } } if (indentAuto) { var currentLength = line.length; CodeMirror.commands.indentAuto(instance); // If the amount of whitespace didn't change, insert another tab if (instance.getLine(from.line).length === currentLength) { insertTab = true; to.ch = 0; } } else if (instance.somethingSelected()) { CodeMirror.commands.indentMore(instance); } else { insertTab = true; } if (insertTab) { if (instance.getOption("indentWithTabs")) { CodeMirror.commands.insertTab(instance); } else { var i, ins = "", numSpaces = _indentUnit; numSpaces -= to.ch % numSpaces; for (i = 0; i < numSpaces; i++) { ins += " "; } instance.replaceSelection(ins, "end"); } } } /** * @private * Handle left arrow, right arrow, backspace and delete keys when soft tabs are used. * @param {!CodeMirror} instance CodeMirror instance * @param {number} direction Direction of movement: 1 for forward, -1 for backward * @param {function} functionName name of the CodeMirror function to call * @return {boolean} true if key was handled */ function _handleSoftTabNavigation(instance, direction, functionName) { var handled = false; if (!instance.getOption("indentWithTabs")) { var cursor = instance.getCursor(), jump = cursor.ch % _indentUnit, line = instance.getLine(cursor.line); if (direction === 1) { jump = _indentUnit - jump; if (cursor.ch + jump > line.length) { // Jump would go beyond current line return false; } if (line.substr(cursor.ch, jump).search(/\S/) === -1) { instance[functionName](jump, "char"); handled = true; } } else { // Quick exit if we are at the beginning of the line if (cursor.ch === 0) { return false; } // If we are on the tab boundary, jump by the full amount, // but not beyond the start of the line. if (jump === 0) { jump = _indentUnit; } // Search backwards to the first non-space character var offset = line.substr(cursor.ch - jump, jump).search(/\s*$/g); if (offset !== -1) { // Adjust to jump to first non-space character jump -= offset; } if (jump > 0) { instance[functionName](-jump, "char"); handled = true; } } } return handled; } /** * Checks if the user just typed a closing brace/bracket/paren, and considers automatically * back-indenting it if so. */ function _checkElectricChars(jqEvent, editor, event) { var instance = editor._codeMirror; if (event.type === "keypress") { var keyStr = String.fromCharCode(event.which || event.keyCode); if (/[\]\{\}\)]/.test(keyStr)) { // If all text before the cursor is whitespace, auto-indent it var cursor = instance.getCursor(); var lineStr = instance.getLine(cursor.line); var nonWS = lineStr.search(/\S/); if (nonWS === -1 || nonWS >= cursor.ch) { // Need to do the auto-indent on a timeout to ensure // the keypress is handled before auto-indenting. // This is the same timeout value used by the // electricChars feature in CodeMirror. window.setTimeout(function () { instance.indentLine(cursor.line); }, 75); } } } } function _handleKeyEvents(jqEvent, editor, event) { _checkElectricChars(jqEvent, editor, event); // Pass the key event to the code hint manager. It may call preventDefault() on the event. CodeHintManager.handleKeyEvent(editor, event); } function _handleSelectAll() { var editor = EditorManager.getFocusedEditor(); if (editor) { editor._selectAllVisible(); } } /** * List of all current (non-destroy()ed) Editor instances. Needed when changing global preferences * that affect all editors, e.g. tabbing or color scheme settings. * @type {Array.<Editor>} */ var _instances = []; /** * @constructor * * Creates a new CodeMirror editor instance bound to the given Document. The Document need not have * a "master" Editor realized yet, even if makeMasterEditor is false; in that case, the first time * an edit occurs we will automatically ask EditorManager to create a "master" editor to render the * Document modifiable. * * ALWAYS call destroy() when you are done with an Editor - otherwise it will leak a Document ref. * * @param {!Document} document * @param {!boolean} makeMasterEditor If true, this Editor will set itself as the (secret) "master" * Editor for the Document. If false, this Editor will attach to the Document as a "slave"/ * secondary editor. * @param {!string} mode Syntax-highlighting language mode; "" means plain-text mode. * See {@link EditorUtils#getModeFromFileExtension()}. * @param {!jQueryObject} container Container to add the editor to. * @param {!Object<string, function(Editor)>} additionalKeys Mapping of keyboard shortcuts to * custom handler functions. Mapping is in CodeMirror format * @param {{startLine: number, endLine: number}=} range If specified, range of lines within the document * to display in this editor. Inclusive. */ function Editor(document, makeMasterEditor, mode, container, additionalKeys, range) { var self = this; _instances.push(this); // Attach to document: add ref & handlers this.document = document; document.addRef(); if (range) { // attach this first: want range updated before we process a change this._visibleRange = new TextRange(document, range.startLine, range.endLine); } // store this-bound version of listeners so we can remove them later this._handleDocumentChange = this._handleDocumentChange.bind(this); this._handleDocumentDeleted = this._handleDocumentDeleted.bind(this); $(document).on("change", this._handleDocumentChange); $(document).on("deleted", this._handleDocumentDeleted); // (if makeMasterEditor, we attach the Doc back to ourselves below once we're fully initialized) this._inlineWidgets = []; // Editor supplies some standard keyboard behavior extensions of its own var codeMirrorKeyMap = { "Tab": _handleTabKey, "Shift-Tab": "indentLess", "Left": function (instance) { if (!_handleSoftTabNavigation(instance, -1, "moveH")) { CodeMirror.commands.goCharLeft(instance); } }, "Right": function (instance) { if (!_handleSoftTabNavigation(instance, 1, "moveH")) { CodeMirror.commands.goCharRight(instance); } }, "Backspace": function (instance) { if (!_handleSoftTabNavigation(instance, -1, "deleteH")) { CodeMirror.commands.delCharLeft(instance); } }, "Delete": function (instance) { if (!_handleSoftTabNavigation(instance, 1, "deleteH")) { CodeMirror.commands.delCharRight(instance); } }, "Esc": function (instance) { self.removeAllInlineWidgets(); }, "'>'": function (cm) { cm.closeTag(cm, '>'); }, "'/'": function (cm) { cm.closeTag(cm, '/'); } }; EditorManager.mergeExtraKeys(self, codeMirrorKeyMap, additionalKeys); // We'd like null/"" to mean plain text mode. CodeMirror defaults to plaintext for any // unrecognized mode, but it complains on the console in that fallback case: so, convert // here so we're always explicit, avoiding console noise. if (!mode) { mode = "text/plain"; } // Create the CodeMirror instance // (note: CodeMirror doesn't actually require using 'new', but jslint complains without it) this._codeMirror = new CodeMirror(container, { electricChars: false, // we use our own impl of this to avoid CodeMirror bugs; see _checkElectricChars() indentWithTabs: _useTabChar, tabSize: _tabSize, indentUnit: _indentUnit, lineNumbers: true, matchBrackets: true, dragDrop: false, // work around issue #1123 extraKeys: codeMirrorKeyMap }); // Can't get CodeMirror's focused state without searching for // CodeMirror-focused. Instead, track focus via onFocus and onBlur // options and track state with this._focused this._focused = false; this._installEditorListeners(); $(this) .on("keyEvent", _handleKeyEvents) .on("change", this._handleEditorChange.bind(this)); // Set code-coloring mode BEFORE populating with text, to avoid a flash of uncolored text this._codeMirror.setOption("mode", mode); // Initially populate with text. This will send a spurious change event, so need to make // sure this is understood as a 'sync from document' case, not a genuine edit this._duringSync = true; this._resetText(document.getText()); this._duringSync = false; if (range) { // Hide all lines other than those we want to show. We do this rather than trimming the // text itself so that the editor still shows accurate line numbers. this._codeMirror.operation(function () { var i; for (i = 0; i < range.startLine; i++) { self._hideLine(i); } var lineCount = self.lineCount(); for (i = range.endLine + 1; i < lineCount; i++) { self._hideLine(i); } }); this.setCursorPos(range.startLine, 0); } // Now that we're fully initialized, we can point the document back at us if needed if (makeMasterEditor) { document._makeEditable(this); } // Add scrollTop property to this object for the scroll shadow code to use Object.defineProperty(this, "scrollTop", { get: function () { return this._codeMirror.getScrollInfo().y; } }); } /** * Removes this editor from the DOM and detaches from the Document. If this is the "master" * Editor that is secretly providing the Document's backing state, then the Document reverts to * a read-only string-backed mode. */ Editor.prototype.destroy = function () { // CodeMirror docs for getWrapperElement() say all you have to do is "Remove this from your // tree to delete an editor instance." $(this.getRootElement()).remove(); _instances.splice(_instances.indexOf(this), 1); // Disconnect from Document this.document.releaseRef(); $(this.document).off("change", this._handleDocumentChange); $(this.document).off("deleted", this._handleDocumentDeleted); if (this._visibleRange) { // TextRange also refs the Document this._visibleRange.dispose(); } // If we're the Document's master editor, disconnecting from it has special meaning if (this.document._masterEditor === this) { this.document._makeNonEditable(); } // Destroying us destroys any inline widgets we're hosting. Make sure their closeCallbacks // run, at least, since they may also need to release Document refs this._inlineWidgets.forEach(function (inlineWidget) { inlineWidget.onClosed(); }); }; /** * Handles Select All specially when we have a visible range in order to work around * bugs in CodeMirror when lines are hidden. */ Editor.prototype._selectAllVisible = function () { var startLine = this.getFirstVisibleLine(), endLine = this.getLastVisibleLine(); this.setSelection({line: startLine, ch: 0}, {line: endLine, ch: this.document.getLine(endLine).length}); }; /** * Ensures that the lines that are actually hidden in the inline editor correspond to * the desired visible range. */ Editor.prototype._updateHiddenLines = function () { if (this._visibleRange) { var cm = this._codeMirror, self = this; cm.operation(function () { // TODO: could make this more efficient by only iterating across the min-max line // range of the union of all changes var i; for (i = 0; i < cm.lineCount(); i++) { if (i < self._visibleRange.startLine || i > self._visibleRange.endLine) { self._hideLine(i); } else { // Double-check that the set of NON-hidden lines matches our range too console.assert(!cm.getLineHandle(i).hidden); } } }); } }; Editor.prototype._applyChanges = function (changeList) { // _visibleRange has already updated via its own Document listener. See if this change caused // it to lose sync. If so, our whole view is stale - signal our owner to close us. if (this._visibleRange) { if (this._visibleRange.startLine === null || this._visibleRange.endLine === null) { $(this).triggerHandler("lostContent"); return; } } // Apply text changes to CodeMirror editor var cm = this._codeMirror; cm.operation(function () { var change, newText; for (change = changeList; change; change = change.next) { newText = change.text.join('\n'); if (!change.from || !change.to) { if (change.from || change.to) { console.assert(false, "Change record received with only one end undefined--replacing entire text"); } cm.setValue(newText); } else { cm.replaceRange(newText, change.from, change.to); } } }); // The update above may have inserted new lines - must hide any that fall outside our range this._updateHiddenLines(); }; /** * Responds to changes in the CodeMirror editor's text, syncing the changes to the Document. * There are several cases where we want to ignore a CodeMirror change: * - if we're the master editor, editor changes can be ignored because Document is already listening * for our changes * - if we're a secondary editor, editor changes should be ignored if they were caused by us reacting * to a Document change */ Editor.prototype._handleEditorChange = function (event, editor, changeList) { // we're currently syncing from the Document, so don't echo back TO the Document if (this._duringSync) { return; } // Secondary editor: force creation of "master" editor backing the model, if doesn't exist yet this.document._ensureMasterEditor(); if (this.document._masterEditor !== this) { // Secondary editor: // we're not the ground truth; if we got here, this was a real editor change (not a // sync from the real ground truth), so we need to sync from us into the document // (which will directly push the change into the master editor). // FUTURE: Technically we should add a replaceRange() method to Document and go through // that instead of talking to its master editor directly. It's not clear yet exactly // what the right Document API would be, though. this._duringSync = true; this.document._masterEditor._applyChanges(changeList); this._duringSync = false; // Update which lines are hidden inside our editor, since we're not going to go through // _applyChanges() in our own editor. this._updateHiddenLines(); } // Else, Master editor: // we're the ground truth; nothing else to do, since Document listens directly to us // note: this change might have been a real edit made by the user, OR this might have // been a change synced from another editor CodeHintManager.handleChange(this); }; /** * Responds to changes in the Document's text, syncing the changes into our CodeMirror instance. * There are several cases where we want to ignore a Document change: * - if we're the master editor, Document changes should be ignored becuase we already have the right * text (either the change originated with us, or it has already been set into us by Document) * - if we're a secondary editor, Document changes should be ignored if they were caused by us sending * the document an editor change that originated with us */ Editor.prototype._handleDocumentChange = function (event, doc, changeList) { var change; // we're currently syncing to the Document, so don't echo back FROM the Document if (this._duringSync) { return; } if (this.document._masterEditor !== this) { // Secondary editor: // we're not the ground truth; and if we got here, this was a Document change that // didn't come from us (e.g. a sync from another editor, a direct programmatic change // to the document, or a sync from external disk changes)... so sync from the Document this._duringSync = true; this._applyChanges(changeList); this._duringSync = false; } // Else, Master editor: // we're the ground truth; nothing to do since Document change is just echoing our // editor changes }; /** * Responds to the Document's underlying file being deleted. The Document is now basically dead, * so we must close. */ Editor.prototype._handleDocumentDeleted = function (event) { // Pass the delete event along as the cause (needed in MultiRangeInlineEditor) $(this).triggerHandler("lostContent", [event]); }; /** * Install singleton event handlers on the CodeMirror instance, translating them into multi- * listener-capable jQuery events on the Editor instance. */ Editor.prototype._installEditorListeners = function () { var self = this; // FUTURE: if this list grows longer, consider making this a more generic mapping // NOTE: change is a "private" event--others shouldn't listen to it on Editor, only on // Document this._codeMirror.setOption("onChange", function (instance, changeList) { $(self).triggerHandler("change", [self, changeList]); }); this._codeMirror.setOption("onKeyEvent", function (instance, event) { $(self).triggerHandler("keyEvent", [self, event]); return event.defaultPrevented; // false tells CodeMirror we didn't eat the event }); this._codeMirror.setOption("onCursorActivity", function (instance) { $(self).triggerHandler("cursorActivity", [self]); }); this._codeMirror.setOption("onScroll", function (instance) { // If this editor is visible, close all dropdowns on scroll. // (We don't want to do this if we're just scrolling in a non-visible editor // in response to some document change event.) if (self.isFullyVisible()) { Menus.closeAll(); } $(self).triggerHandler("scroll", [self]); // notify all inline widgets of a position change self._fireWidgetOffsetTopChanged(self.getFirstVisibleLine() - 1); }); // Convert CodeMirror onFocus events to EditorManager activeEditorChanged this._codeMirror.setOption("onFocus", function () { self._focused = true; EditorManager._notifyActiveEditorChanged(self); }); this._codeMirror.setOption("onBlur", function () { self._focused = false; // EditorManager only cares about other Editors gaining focus, so we don't notify it of anything here }); }; /** * Sets the contents of the editor and clears the undo/redo history. Dispatches a change event. * Semi-private: only Document should call this. * @param {!string} text */ Editor.prototype._resetText = function (text) { var perfTimerName = PerfUtils.markStart("Edtitor._resetText()\t" + (!this.document || this.document.file.fullPath)); var cursorPos = this.getCursorPos(), scrollPos = this.getScrollPos(); // This *will* fire a change event, but we clear the undo immediately afterward this._codeMirror.setValue(text); // Make sure we can't undo back to the empty state before setValue() this._codeMirror.clearHistory(); // restore cursor and scroll positions this.setCursorPos(cursorPos); this.setScrollPos(scrollPos.x, scrollPos.y); PerfUtils.addMeasurement(perfTimerName); }; /** * Gets the current cursor position within the editor. If there is a selection, returns whichever * end of the range the cursor lies at. * @param {boolean} expandTabs If true, return the actual visual column number instead of the character offset in * the "ch" property. * @return !{line:number, ch:number} */ Editor.prototype.getCursorPos = function (expandTabs) { var cursor = this._codeMirror.getCursor(); if (expandTabs) { var line = this._codeMirror.getRange({line: cursor.line, ch: 0}, cursor), tabSize = Editor.getTabSize(), column = 0, i; for (i = 0; i < line.length; i++) { if (line[i] === '\t') { column += (tabSize - (column % tabSize)); } else { column++; } } cursor.ch = column; } return cursor; }; /** * Sets the cursor position within the editor. Removes any selection. * @param {number} line The 0 based line number. * @param {number=} ch The 0 based character position; treated as 0 if unspecified. */ Editor.prototype.setCursorPos = function (line, ch) { this._codeMirror.setCursor(line, ch); }; /** * Given a position, returns its index within the text (assuming \n newlines) * @param {!{line:number, ch:number}} * @return {number} */ Editor.prototype.indexFromPos = function (coords) { return this._codeMirror.indexFromPos(coords); }; /** * Returns true if pos is between start and end (inclusive at both ends) * @param {{line:number, ch:number}} pos * @param {{line:number, ch:number}} start * @param {{line:number, ch:number}} end * */ Editor.prototype.posWithinRange = function (pos, start, end) { var startIndex = this.indexFromPos(start), endIndex = this.indexFromPos(end), posIndex = this.indexFromPos(pos); return posIndex >= startIndex && posIndex <= endIndex; }; /** * @return {boolean} True if there's a text selection; false if there's just an insertion point */ Editor.prototype.hasSelection = function () { return this._codeMirror.somethingSelected(); }; /** * Gets the current selection. Start is inclusive, end is exclusive. If there is no selection, * returns the current cursor position as both the start and end of the range (i.e. a selection * of length zero). * @return {!{start:{line:number, ch:number}, end:{line:number, ch:number}}} */ Editor.prototype.getSelection = function () { var selStart = this._codeMirror.getCursor(true), selEnd = this._codeMirror.getCursor(false); return { start: selStart, end: selEnd }; }; /** * @return {!string} The currently selected text, or "" if no selection. Includes \n if the * selection spans multiple lines (does NOT reflect the Document's line-endings style). */ Editor.prototype.getSelectedText = function () { return this._codeMirror.getSelection(); }; /** * Sets the current selection. Start is inclusive, end is exclusive. Places the cursor at the * end of the selection range. * @param {!{line:number, ch:number}} start * @param {!{line:number, ch:number}} end */ Editor.prototype.setSelection = function (start, end) { this._codeMirror.setSelection(start, end); }; /** * Selects word that the given pos lies within or adjacent to. If pos isn't touching a word * (e.g. within a token like "//"), moves the cursor to pos without selecting a range. * Adapted from selectWordAt() in CodeMirror v2. * @param {!{line:number, ch:number}} */ Editor.prototype.selectWordAt = function (pos) { var line = this.document.getLine(pos.line), start = pos.ch, end = pos.ch; function isWordChar(ch) { return (/\w/).test(ch) || ch.toUpperCase() !== ch.toLowerCase(); } while (start > 0 && isWordChar(line.charAt(start - 1))) { --start; } while (end < line.length && isWordChar(line.charAt(end))) { ++end; } this.setSelection({line: pos.line, ch: start}, {line: pos.line, ch: end}); }; /** * Gets the total number of lines in the the document (includes lines not visible in the viewport) * @returns {!number} */ Editor.prototype.lineCount = function () { return this._codeMirror.lineCount(); }; /** * Gets the number of the first visible line in the editor. * @returns {number} The 0-based index of the first visible line. */ Editor.prototype.getFirstVisibleLine = function () { return (this._visibleRange ? this._visibleRange.startLine : 0); }; /** * Gets the number of the last visible line in the editor. * @returns {number} The 0-based index of the last visible line. */ Editor.prototype.getLastVisibleLine = function () { return (this._visibleRange ? this._visibleRange.endLine : this.lineCount() - 1); }; // FUTURE change to "hideLines()" API that hides a range of lines at once in a single operation, then fires offsetTopChanged afterwards. /* Hides the specified line number in the editor * @param {!number} */ Editor.prototype._hideLine = function (lineNumber) { var value = this._codeMirror.hideLine(lineNumber); // when this line is hidden, notify all following inline widgets of a position change this._fireWidgetOffsetTopChanged(lineNumber); return value; }; /** * Gets the total height of the document in pixels (not the viewport) * @param {!boolean} includePadding * @returns {!number} height in pixels */ Editor.prototype.totalHeight = function (includePadding) { return this._codeMirror.totalHeight(includePadding); }; /** * Gets the scroller element from the editor. * @returns {!HTMLDivElement} scroller */ Editor.prototype.getScrollerElement = function () { return this._codeMirror.getScrollerElement(); }; /** * Gets the root DOM node of the editor. * @returns {Object} The editor's root DOM node. */ Editor.prototype.getRootElement = function () { return this._codeMirror.getWrapperElement(); }; /** * Gets the lineSpace element within the editor (the container around the individual lines of code). * FUTURE: This is fairly CodeMirror-specific. Logic that depends on this may break if we switch * editors. * @returns {Object} The editor's lineSpace element. */ Editor.prototype._getLineSpaceElement = function () { return $(".CodeMirror-lines", this.getScrollerElement()).children().get(0); }; /** * Returns the current scroll position of the editor. * @returns {{x:number, y:number}} The x,y scroll position in pixels */ Editor.prototype.getScrollPos = function () { return this._codeMirror.getScrollInfo(); }; /** * Sets the current scroll position of the editor. * @param {number} x scrollLeft position in pixels * @param {number} y scrollTop position in pixels */ Editor.prototype.setScrollPos = function (x, y) { this._codeMirror.scrollTo(x, y); }; /** * Adds an inline widget below the given line. If any inline widget was already open for that * line, it is closed without warning. * @param {!{line:number, ch:number}} pos Position in text to anchor the inline. * @param {!InlineWidget} inlineWidget The widget to add. */ Editor.prototype.addInlineWidget = function (pos, inlineWidget) { var self = this; inlineWidget.id = this._codeMirror.addInlineWidget(pos, inlineWidget.htmlContent, inlineWidget.height, function (id) { self._removeInlineWidgetInternal(id); inlineWidget.onClosed(); }); this._inlineWidgets.push(inlineWidget); inlineWidget.onAdded(); // once this widget is added, notify all following inline widgets of a position change this._fireWidgetOffsetTopChanged(pos.line); }; /** * Removes all inline widgets */ Editor.prototype.removeAllInlineWidgets = function () { // copy the array because _removeInlineWidgetInternal will modifying the original var widgets = [].concat(this.getInlineWidgets()); widgets.forEach(function (widget) { this.removeInlineWidget(widget); }, this); }; /** * Removes the given inline widget. * @param {number} inlineWidget The widget to remove. */ Editor.prototype.removeInlineWidget = function (inlineWidget) { var lineNum = this._getInlineWidgetLineNumber(inlineWidget); // _removeInlineWidgetInternal will get called from the destroy callback in CodeMirror. this._codeMirror.removeInlineWidget(inlineWidget.id); // once this widget is removed, notify all following inline widgets of a position change this._fireWidgetOffsetTopChanged(lineNum); }; /** * Cleans up the given inline widget from our internal list of widgets. * @param {number} inlineId id returned by addInlineWidget(). */ Editor.prototype._removeInlineWidgetInternal = function (inlineId) { var i; var l = this._inlineWidgets.length; for (i = 0; i < l; i++) { if (this._inlineWidgets[i].id === inlineId) { this._inlineWidgets.splice(i, 1); break; } } }; /** * Returns a list of all inline widgets currently open in this editor. Each entry contains the * inline's id, and the data parameter that was passed to addInlineWidget(). * @return {!Array.<{id:number, data:Object}>} */ Editor.prototype.getInlineWidgets = function () { return this._inlineWidgets; }; /** * Sets the height of an inline widget in this editor. * @param {!InlineWidget} inlineWidget The widget whose height should be set. * @param {!number} height The height of the widget. * @param {boolean} ensureVisible Whether to scroll the entire widget into view. */ Editor.prototype.setInlineWidgetHeight = function (inlineWidget, height, ensureVisible) { var info = this._codeMirror.getInlineWidgetInfo(inlineWidget.id), oldHeight = (info && info.height) || 0; this._codeMirror.setInlineWidgetHeight(inlineWidget.id, height, ensureVisible); // update position for all following inline editors if (oldHeight !== height) { var lineNum = this._getInlineWidgetLineNumber(inlineWidget); this._fireWidgetOffsetTopChanged(lineNum); } }; /** * @private * Get the starting line number for an inline widget. * @param {!InlineWidget} inlineWidget * @return {number} The line number of the widget or -1 if not found. */ Editor.prototype._getInlineWidgetLineNumber = function (inlineWidget) { var info = this._codeMirror.getInlineWidgetInfo(inlineWidget.id); return (info && info.line) || -1; }; /** * @private * Fire "offsetTopChanged" events when inline editor positions change due to * height changes of other inline editors. * @param {!InlineWidget} inlineWidget */ Editor.prototype._fireWidgetOffsetTopChanged = function (lineNum) { var self = this, otherLineNum; this.getInlineWidgets().forEach(function (other) { otherLineNum = self._getInlineWidgetLineNumber(other); if (otherLineNum > lineNum) { $(other).triggerHandler("offsetTopChanged"); } }); }; /** Gives focus to the editor control */ Editor.prototype.focus = function () { this._codeMirror.focus(); }; /** Returns true if the editor has focus */ Editor.prototype.hasFocus = function () { return this._focused; }; /** * Re-renders the editor UI */ Editor.prototype.refresh = function () { this._codeMirror.refresh(); }; /** * Re-renders the editor, and all children inline editors. */ Editor.prototype.refreshAll = function () { this.refresh(); this.getInlineWidgets().forEach(function (multilineEditor, i, arr) { multilineEditor.sizeInlineWidgetToContents(true); multilineEditor._updateRelatedContainer(); multilineEditor.editors.forEach(function (editor, j, arr) { editor.refresh(); }); }); }; /** * Shows or hides the editor within its parent. Does not force its ancestors to * become visible. * @param {boolean} show true to show the editor, false to hide it */ Editor.prototype.setVisible = function (show) { $(this.getRootElement()).css("display", (show ? "" : "none")); this._codeMirror.refresh(); if (show) { this._inlineWidgets.forEach(function (inlineWidget) { inlineWidget.onParentShown(); }); } }; /** * Returns true if the editor is fully visible--i.e., is in the DOM, all ancestors are * visible, and has a non-zero width/height. */ Editor.prototype.isFullyVisible = function () { return $(this.getRootElement()).is(":visible"); }; /** * Gets the syntax-highlighting mode for the current selection or cursor position. (The mode may * vary within one file due to embedded languages, e.g. JS embedded in an HTML script block). * * Returns null if the mode at the start of the selection differs from the mode at the end - * an *approximation* of whether the mode is consistent across the whole range (a pattern like * A-B-A would return A as the mode, not null). * * @return {?(Object|String)} Object or Name of syntax-highlighting mode; see {@link EditorUtils#getModeFromFileExtension()}. */ Editor.prototype.getModeForSelection = function () { var sel = this.getSelection(); // Check for mixed mode info (meaning mode varies depending on position) // TODO (#921): this only works for certain mixed modes; some do not expose this info var startState = this._codeMirror.getTokenAt(sel.start).state; if (startState.mode) { var startMode = startState.mode; // If mixed mode, check that mode is the same at start & end of selection if (sel.start.line !== sel.end.line || sel.start.ch !== sel.end.ch) { var endState = this._codeMirror.getTokenAt(sel.end).state; var endMode = endState.mode; if (startMode !== endMode) { return null; } } return startMode; } else { // Mode does not vary: just use the editor-wide mode return this._codeMirror.getOption("mode"); } }; /** * Gets the syntax-highlighting mode for the document. * * @return {Object|String} Object or Name of syntax-highlighting mode; see {@link EditorUtils#getModeFromFileExtension()}. */ Editor.prototype.getModeForDocument = function () { return this._codeMirror.getOption("mode"); }; /** * Sets the syntax-highlighting mode for the document. * * @param {string} mode Name of syntax highlighting mode. */ Editor.prototype.setModeForDocument = function (mode) { this._codeMirror.setOption("mode", mode); }; /** * The Document we're bound to * @type {!Document} */ Editor.prototype.document = null; /** * If true, we're in the middle of syncing to/from the Document. Used to ignore spurious change * events caused by us (vs. change events caused by others, which we need to pay attention to). * @type {!boolean} */ Editor.prototype._duringSync = false; /** * @private * NOTE: this is actually "semi-private": EditorManager also accesses this field... as well as * a few other modules. However, we should try to gradually move most code away from talking to * CodeMirror directly. * @type {!CodeMirror} */ Editor.prototype._codeMirror = null; /** * @private * @type {!Array.<{id:number, data:Object}>} */ Editor.prototype._inlineWidgets = null; /** * @private * @type {?TextRange} */ Editor.prototype._visibleRange = null; // Global settings that affect all Editor instances (both currently open Editors as well as those created // in the future) /** * Sets whether to use tab characters (vs. spaces) when inserting new text. Affects all Editors. * @param {boolean} value */ Editor.setUseTabChar = function (value) { _useTabChar = value; _instances.forEach(function (editor) { editor._codeMirror.setOption("indentWithTabs", _useTabChar); }); _prefs.setValue("useTabChar", Boolean(_useTabChar)); }; /** @type {boolean} Gets whether all Editors use tab characters (vs. spaces) when inserting new text */ Editor.getUseTabChar = function (value) { return _useTabChar; }; /** * Sets tab character width. Affects all Editors. * @param {number} value */ Editor.setTabSize = function (value) { _tabSize = value; _instances.forEach(function (editor) { editor._codeMirror.setOption("tabSize", _tabSize); }); _prefs.setValue("tabSize", _tabSize); }; /** @type {number} Get indent unit */ Editor.getTabSize = function (value) { return _tabSize; }; /** * Sets indentation width. Affects all Editors. * @param {number} value */ Editor.setIndentUnit = function (value) { _indentUnit = value; _instances.forEach(function (editor) { editor._codeMirror.setOption("indentUnit", _indentUnit); }); _prefs.setValue("indentUnit", _indentUnit); }; /** @type {number} Get indentation width */ Editor.getIndentUnit = function (value) { return _indentUnit; }; // Global commands that affect the currently focused Editor instance, wherever it may be CommandManager.register(Strings.CMD_SELECT_ALL, Commands.EDIT_SELECT_ALL, _handleSelectAll); // Define public API exports.Editor = Editor; });
'use strict'; /** * Email.js service * * @description: A set of functions similar to controller's actions to avoid code duplication. */ const _ = require('lodash'); const sendmail = require('sendmail')({ silent: true }); module.exports = { send: (options, cb) => { return new Promise((resolve, reject) => { // Default values. options = _.isObject(options) ? options : {}; options.from = options.from || '"Administration Panel" <[email protected]>'; options.replyTo = options.replyTo || '"Administration Panel" <[email protected]>'; options.text = options.text || options.html; options.html = options.html || options.text; // Send the email. sendmail({ from: options.from, to: options.to, replyTo: options.replyTo, subject: options.subject, text: options.text, html: options.html }, function (err) { if (err) { reject([{ messages: [{ id: 'Auth.form.error.email.invalid' }] }]); } else { resolve(); } }); }); } };
DS.classes.Message = function(create){ var relations = []; //check check(create, { time: DS.classes.Time, data: Match.Optional(Object) }); //create _.extend(this, create); //add relations this.addRelation = function(relation, reversed){ check(relation, DS.classes.Relation); check(reversed, Boolean); relations.push({ 'relation': relation, 'reversed': reversed }); }; this.getRelations = function(){ return relations; } };
'use strict'; import React from 'react'; import {BootstrapTable, TableHeaderColumn} from 'react-bootstrap-table'; var products = []; function addProducts(quantity) { var startId = products.length; for (var i = 0; i < quantity; i++) { var id = startId + i; products.push({ id: id, name: "Item name " + id, price: 100 + i }); } } addProducts(5); var order = 'desc'; export default class SortTable extends React.Component{ handleBtnClick = e => { if(order === 'desc'){ this.refs.table.handleSort('asc', 'name'); order = 'asc'; } else { this.refs.table.handleSort('desc', 'name'); order = 'desc'; } } render(){ return ( <div> <p style={{color:'red'}}>You cam click header to sort or click following button to perform a sorting by expose API</p> <button onClick={this.handleBtnClick}>Sort Product Name</button> <BootstrapTable ref="table" data={products}> <TableHeaderColumn dataField="id" isKey={true} dataSort={true}>Product ID</TableHeaderColumn> <TableHeaderColumn dataField="name" dataSort={true}>Product Name</TableHeaderColumn> <TableHeaderColumn dataField="price">Product Price</TableHeaderColumn> </BootstrapTable> </div> ); } };
//////////////////////////////////////////////////////////////////////////////////// ////// Events //////////////////////////////////////////////////////////////////////////////////// 'use strict'; // DI var db, responseHandler; /** * * @param req the HTTP requests, contains header and body parameters * @param res the callback to which send HTTP response * @param next facilitate restify function chaining */ exports.findAll = function (req, res, next) { req.check('appid', '"appid": must be a valid identifier').notNull(); var errors = req.validationErrors(), appid; if (errors) { responseHandler(res).error(400, errors); return; } appid = req.params.appid; db.findAllEvents({'application_id': appid}, responseHandler(res, next)); }; /** * * @param req the HTTP requests, contains header and body parameters * @param res the callback to which send HTTP response * @param next facilitate restify function chaining */ exports.findById = function (req, res, next) { req.check('appid', '"appid": must be a valid identifier').notNull(); req.check('eventid', '"eventid": must be a valid identifier').notNull(); var errors = req.validationErrors(), appid, eventid; if (errors) { responseHandler(res).error(400, errors); return; } appid = req.params.appid; eventid = req.params.eventid; db.findEventById({'application_id': appid, 'event_id': eventid}, responseHandler(res, next)); }; /** * * @param req the HTTP requests, contains header and body parameters * @param res the callback to which send HTTP response * @param next facilitate restify function chaining */ exports.create = function (req, res, next) { req.check('appid', '"appid": must be a valid identifier').notNull(); req.check('type', '"type": must be a valid identifier').notNull(); req.check('user', '"user": must be a valid identifier').notNull(); req.check('issued', '"date": must be a valid date').isDate(); var errors = req.validationErrors(), appid, type, user, issued; if (errors) { responseHandler(res).error(400, errors); return; } appid = req.params.appid; type = req.params.type; user = req.params.user; issued = req.params.issued; // or "2013-02-26"; // TODO today or specified db.createEvent( {'application_id': appid, 'type': type, 'user': user, 'issued': issued}, responseHandler(res, next) ); };
'use strict'; const path = require('path'); const request = require('supertest'); const pedding = require('pedding'); const assert = require('assert'); const sleep = require('ko-sleep'); const mm = require('..'); const fixtures = path.join(__dirname, 'fixtures'); const baseDir = path.join(fixtures, 'app-event'); describe('test/app_event.test.js', () => { afterEach(mm.restore); describe('after ready', () => { let app; before(() => { app = mm.app({ baseDir, cache: false, }); return app.ready(); }); after(() => app.close()); it('should listen by eventByRequest', done => { done = pedding(3, done); app.once('eventByRequest', done); app.on('eventByRequest', done); request(app.callback()) .get('/event') .expect(200) .expect('done', done); }); }); describe('before ready', () => { let app; beforeEach(() => { app = mm.app({ baseDir, cache: false, }); }); afterEach(() => app.ready()); afterEach(() => app.close()); it('should listen after app ready', done => { done = pedding(2, done); app.once('appReady', done); app.on('appReady', done); }); it('should listen after app instantiate', done => { done = pedding(2, done); app.once('appInstantiated', done); app.on('appInstantiated', done); }); }); describe('throw before app init', () => { let app; beforeEach(() => { const baseDir = path.join(fixtures, 'app'); const customEgg = path.join(fixtures, 'error-framework'); app = mm.app({ baseDir, customEgg, cache: false, }); }); afterEach(() => app.close()); it('should listen using app.on', done => { app.on('error', err => { assert(err.message === 'start error'); done(); }); }); it('should listen using app.once', done => { app.once('error', err => { assert(err.message === 'start error'); done(); }); }); it('should throw error from ready', function* () { try { yield app.ready(); } catch (err) { assert(err.message === 'start error'); } }); it('should close when app init failed', function* () { app.once('error', () => {}); yield sleep(1000); // app._app is undefined yield app.close(); }); }); });
/*! * Kaiseki * Copyright(c) 2012 BJ Basañes / Shiki ([email protected]) * MIT Licensed * * See the README.md file for documentation. */ var request = require('request'); var _ = require('underscore'); var Kaiseki = function(options) { if (!_.isObject(options)) { // Original signature this.applicationId = arguments[0]; this.restAPIKey = arguments[1]; this.masterKey = null; this.sessionToken = arguments[2] || null; this.request = request; this.baseURL = 'https://api.parse.com'; } else { // New interface to allow masterKey and custom request function options = options || {}; this.applicationId = options.applicationId; this.restAPIKey = options.restAPIKey; this.masterKey = options.masterKey || null; this.sessionToken = options.sessionToken || null; this.request = options.request || request; this.baseURL = options.serverURL; } }; Kaiseki.prototype = { applicationId: null, restAPIKey: null, masterKey: null, // required for deleting files sessionToken: null, createUser: function(data, callback) { this._jsonRequest({ method: 'POST', url: '/1/users', params: data, callback: function(err, res, body, success) { if (!err && success) body = _.extend({}, data, body); callback(err, res, body, success); } }); }, getUser: function(objectId, params, callback) { this._jsonRequest({ url: '/1/users/' + objectId, params: _.isFunction(params) ? null : params, callback: _.isFunction(params) ? params : callback }); }, // Also used for validating a session token // https://parse.com/docs/rest#users-validating getCurrentUser: function(sessionToken, callback) { if (_.isFunction(sessionToken)) { callback = sessionToken; sessionToken = undefined; } this._jsonRequest({ url: '/1/users/me', sessionToken: sessionToken, callback: callback }); }, loginFacebookUser: function(facebookAuthData, callback) { this._socialLogin({facebook: facebookAuthData}, callback); }, loginTwitterUser: function(twitterAuthData, callback) { this._socialLogin({twitter: twitterAuthData}, callback); }, loginUser: function(username, password, callback) { this._jsonRequest({ url: '/1/login', params: { username: username, password: password }, callback: callback }); }, updateUser: function(objectId, data, callback) { this._jsonRequest({ method: 'PUT', url: '/1/users/' + objectId, params: data, callback: callback }); }, deleteUser: function(objectId, callback) { this._jsonRequest({ method: 'DELETE', url: '/1/users/' + objectId, callback: callback }); }, getUsers: function(params, callback) { this._jsonRequest({ url: '/1/users', params: _.isFunction(params) ? null : params, callback: _.isFunction(params) ? params : callback }); }, requestPasswordReset: function(email, callback) { this._jsonRequest({ method: 'POST', url: '/1/requestPasswordReset', params: {'email': email}, callback: callback }); }, createObjects: function(className, data, callback) { var requests = []; for (var i = 0; i < data.length; i++) { requests.push({ 'method': 'POST', 'path': '/1/classes/' + className, 'body': data[i] }); } this._jsonRequest({ method: 'POST', url: '/1/batch/', params: { requests: requests }, callback: function(err, res, body, success) { if (!err && success) body = _.extend({}, data, body); callback(err, res, body, success); } }); }, createObject: function(className, data, callback) { this._jsonRequest({ method: 'POST', url: '/1/classes/' + className, params: data, callback: function(err, res, body, success) { if (!err && success) body = _.extend({}, data, body); callback(err, res, body, success); } }); }, getObject: function(className, objectId, params, callback) { this._jsonRequest({ url: '/1/classes/' + className + '/' + objectId, params: _.isFunction(params) ? null : params, callback: _.isFunction(params) ? params : callback }); }, updateObjects: function(className, updates, callback) { var requests = [], update = null; for (var i = 0; i < updates.length; i++) { update = updates[i]; requests.push({ 'method': 'PUT', 'path': '/1/classes/' + className + '/' + update.objectId, 'body': update.data }); } this._jsonRequest({ method: 'POST', url: '/1/batch/', params: { requests: requests }, callback: callback }); }, updateObject: function(className, objectId, data, callback) { this._jsonRequest({ method: 'PUT', url: '/1/classes/' + className + '/' + objectId, params: data, callback: callback }); }, deleteObject: function(className, objectId, callback) { this._jsonRequest({ method: 'DELETE', url: '/1/classes/' + className + '/' + objectId, callback: callback }); }, getObjects: function(className, params, callback) { this._jsonRequest({ url: '/1/classes/' + className, params: _.isFunction(params) ? null : params, callback: _.isFunction(params) ? params : callback }); }, countObjects: function(className, params, callback) { var paramsMod = params; if (_.isFunction(params)) { paramsMod = {}; paramsMod['count'] = 1; paramsMod['limit'] = 0; } else { paramsMod['count'] = 1; paramsMod['limit'] = 0; } this._jsonRequest({ url: '/1/classes/' + className, params: paramsMod, callback: _.isFunction(params) ? params : callback }); }, createRole: function(data, callback) { this._jsonRequest({ method: 'POST', url: '/1/roles', params: data, callback: function(err, res, body, success) { if (!err && success) body = _.extend({}, data, body); callback(err, res, body, success); } }); }, getRole: function(objectId, params, callback) { this._jsonRequest({ url: '/1/roles/' + objectId, params: _.isFunction(params) ? null : params, callback: _.isFunction(params) ? params : callback }); }, updateRole: function(objectId, data, callback) { this._jsonRequest({ method: 'PUT', url: '/1/roles/' + objectId, params: data, callback: callback }); }, deleteRole: function(objectId, callback) { this._jsonRequest({ method: 'DELETE', url: '/1/roles/' + objectId, callback: callback }); }, getRoles: function(params, callback) { this._jsonRequest({ url: '/1/roles', params: _.isFunction(params) ? null : params, callback: _.isFunction(params) ? params : callback }); }, uploadFile: function(filePath, fileName, callback) { if (_.isFunction(fileName)) { callback = fileName; fileName = null; } var contentType = require('mime').lookup(filePath); if (!fileName) fileName = filePath.replace(/^.*[\\\/]/, ''); // http://stackoverflow.com/a/423385/246142 var buffer = require('fs').readFileSync(filePath); this.uploadFileBuffer(buffer, contentType, fileName, callback); }, uploadFileBuffer: function(buffer, contentType, fileName, callback) { this._jsonRequest({ method: 'POST', url: '/1/files/' + fileName, body: buffer, headers: { 'Content-type': contentType }, callback: callback }); }, deleteFile: function(name, callback) { this._jsonRequest({ method: 'DELETE', url: '/1/files/' + name, callback: callback }); }, sendPushNotification: function(data, callback) { this._jsonRequest({ method: 'POST', url: '/1/push', params: data, callback: function(err, res, body, success) { if (!err && success) body = _.extend({}, data, body); callback.apply(this, arguments); } }); }, sendAnalyticsEvent: function(eventName, dimensionsOrCallback, callback) { this._jsonRequest({ method: 'POST', url: '/1/events/' + eventName, params: _.isFunction(dimensionsOrCallback) ? {} : dimensionsOrCallback, callback: _.isFunction(dimensionsOrCallback) ? dimensionsOrCallback : callback }); }, stringifyParamValues: function(params) { if (!params || _.isEmpty(params)) return null; var values = _(params).map(function(value, key) { if (_.isObject(value) || _.isArray(value)) return JSON.stringify(value); else return value; }); var keys = _(params).keys(); var ret = {}; for (var i = 0; i < keys.length; i++) ret[keys[i]] = values[i]; return ret; }, _socialLogin: function(authData, callback) { this._jsonRequest({ method: 'POST', url: '/1/users', params: { authData: authData }, callback: callback }); }, _jsonRequest: function(opts) { var sessionToken = opts.sessionToken || this.sessionToken; opts = _.omit(opts, 'sessionToken'); opts = _.extend({ method: 'GET', url: null, params: null, body: null, headers: null, callback: null }, opts); var reqOpts = { method: opts.method, headers: { 'X-Parse-Application-Id': this.applicationId, 'X-Parse-REST-API-Key': this.restAPIKey } }; if (sessionToken) reqOpts.headers['X-Parse-Session-Token'] = sessionToken; if (this.masterKey) reqOpts.headers['X-Parse-Master-Key'] = this.masterKey; if (opts.headers) _.extend(reqOpts.headers, opts.headers); if (opts.params) { if (opts.method == 'GET') opts.params = this.stringifyParamValues(opts.params); var key = 'qs'; if (opts.method === 'POST' || opts.method === 'PUT') key = 'json'; reqOpts[key] = opts.params; } else if (opts.body) { reqOpts.body = opts.body; } this.request(this.baseURL + opts.url, reqOpts, function(err, res, body) { var isCountRequest = opts.params && !_.isUndefined(opts.params['count']) && !!opts.params.count; var success = !err && res && (res.statusCode === 200 || res.statusCode === 201); if (res && res.headers['content-type'] && res.headers['content-type'].toLowerCase().indexOf('application/json') >= 0) { if (body != null && !_.isObject(body) && !_.isArray(body)) // just in case it's been parsed already body = JSON.parse(body); if (body != null) { if (body.error) { success = false; } else if (body.results && _.isArray(body.results) && !isCountRequest) { // If this is a "count" request. Don't touch the body/result. body = body.results; } } } opts.callback(err, res, body, success); }); } }; module.exports = Kaiseki;
(function(app) { "use strict"; app.directive("ratingInput", [ "$rootScope", function($rootScope) { return { restrict: "A", link: function($scope, $element, $attrs) { $element.raty({ score: $attrs.cdRatingInput, half: true, halfShow: true, starHalf: "/Content/Images/star-half-big.png", starOff: "/Content/Images/star-off-big.png", starOn: "/Content/Images/star-on-big.png", hints: ["Poor", "Average", "Good", "Very Good", "Excellent"], target: "#Rating", targetKeep: true, noRatedMsg: "Not Rated yet!", scoreName: "Rating", click: function(score) { $rootScope.$broadcast("Broadcast::RatingAvailable", score); } }); } }; } ]); })(angular.module("books"));
{ "status": { "error": false, "code": 200, "type": "success", "message": "Success" }, "pagination": { "before_cursor": null, "after_cursor": null, "previous_link": null, "next_link": null }, "data": [ { "id": 1111, "name": "marketing" } ] }
var gulp = require('gulp'); var connect = require('gulp-connect'); var uglify = require('gulp-uglify'); var concat = require('gulp-concat'); var opn = require('opn'); var config = { rootDir: '.', servingPort: 8080, servingDir: './dist', paths: { src: { scripts: './src/**/*.js', styles: './src/**/*.css', images: '', index: './src/index.html', partials: ['./src/**/*.html', '!./index.html'], }, distDev: './dist.dev', distProd: './dist.prod' } } gulp.task('build', function() { }); gulp.task('serve', ['connect'], function() { return opn('http://localhost:' + config.servingPort); }); gulp.task('livereload', function() { console.log('reloading') gulp.src(config.filesToWatch) .pipe(connect.reload()); }); gulp.task('connect', function() { connect.server({ root: config.servingDir, port: config.servingPort, livereload: false, fallback: config.servingDir + '/index.html' }); }); gulp.task('watch', function() { gulp.watch([config.sourcePaths.css, config.sourcePaths.html, config.sourcePaths.js], ['livereload']); }); gulp.task('default', ['serve']); //default: clean-build-prod //serve dev
import React from 'react' import {Observable} from 'rx' import {TextField} from 'material-ui' import ThemeManager from 'material-ui/lib/styles/theme-manager'; import MyRawTheme from '../components/Theme.js'; import ThemeDecorator from 'material-ui/lib/styles/theme-decorator'; import {compose} from 'recompose' import {observeProps, createEventHandler} from 'rx-recompose' import {clickable} from '../style.css' import {View} from '../components' let Search = compose( // ASDFGHJKL: ThemeDecorator(ThemeManager.getMuiTheme(MyRawTheme)) , observeProps(props$ => { // Create search query observable let setQuery = createEventHandler() let query$ = setQuery.share() query$ // Only search for songs that are not only spaces 😂 .filter(x => x.trim() !== '') // Only every 300 ms .debounce(300) // Get the `doSearch` method from props .withLatestFrom(props$.pluck('doSearch'), (query, doSearch) => doSearch(query)) // Search for the query .subscribe(func => { func() }) return { // Pass down function to set the query setQuery: Observable.just(setQuery), // Pass down the current query value query: query$.startWith(''), // Pass down force-search function when pressing enter doSearch: props$.pluck('doSearch'), // Function to start playing song when clicked on playSong: props$.pluck('playSong'), // Searchresults to display searchResults: Observable.merge( // Results from the search props$.pluck('results$') // Get results observable .distinctUntilChanged() // Only when unique .flatMapLatest(x => x) // Morph into the results$ .startWith([]) // And set off with a empty array , query$ // When query is only spaces .filter(x => x.trim() === '') // Reset the results to empty array .map(() => []) ), } }) )(({query, setQuery, searchResults, playSong, doSearch}) => ( <View> <TextField hintText="Search for a song! :D" onChange={(e,value) => setQuery(e.target.value)} value={query} onEnterKeyDown={doSearch(query)} fullWidth={true} underlineStyle={{borderWidth: 2}} /> <View> { /* List all the results */ } { searchResults.map(result => <View key={result.nid} className={clickable} // On click, reset the query and play the song! onClick={() => { playSong(result)() setQuery('') }} // Same as setting the text, but more compact children={`${result.title} - ${result.artist}`} /> )} </View> </View> )) export default Search
(function(ns) { /** * JSON CORS utility * Wraps up all the cors stuff into a simple post or get. Falls back to jsonp */ var JSONCORS = function() { var self = this; var supportsCORS = ('withCredentials' in new XMLHttpRequest()) || (typeof XDomainRequest != 'undefined'); /********************************************************************************/ // Utils /********************************************************************************/ /** * Serializes a dictionary into a url query * @param m: the map to serialize * @return the url query (no preceeding ?) */ var serializeURLQuery = function(m) { var args = []; for (var k in m) { args.push(encodeURIComponent(k) + '=' + encodeURIComponent(m[k])) } return args.join('&'); }; /********************************************************************************/ // CORS /********************************************************************************/ /** * Performs a CORS request which wraps the response through our marshalled API * @param url: the url to visit * @param method: GET|POST the http method * @param payload: the payload to send (undefined for GET) * @param success: executed on success. Given response then http status then xhr * @param failure: executed on failure. Given http status then error then xhr * @return the XHR object */ self.requestCORS = function(url, method, payload, success, failure) { method = method.toUpperCase(); var xhr; if (typeof XDomainRequest != 'undefined') { xhr = new XDomainRequest(); xhr.open(method, url); } else { xhr = new XMLHttpRequest(); xhr.open(method, url, true); } xhr.onload = function() { var json; try { json = JSON.parse(xhr.responseText); } catch(e) { /* noop */ } var status = (json && json.http_status !== undefined) ? json.http_status : xhr.status; if (status >= 200 && status <= 299) { success(json, status, xhr); } else { failure(xhr.status, json ? json.error : undefined, xhr); } }; xhr.onerror = function() { failure(xhr.status, undefined, xhr); }; if (method === 'POST') { xhr.setRequestHeader("Content-type","application/json"); xhr.send(JSON.stringify(payload)); } else { xhr.send(); } return xhr; }; /********************************************************************************/ // JSONP /********************************************************************************/ /** * Performs a JSONP request which wraps the response through our marshalled API * @param url: the url to visit * @param method: GET|POST the http method * @param payload: the payload to send (undefined for GET) * @param success: executed on success. Given response then http status then xhr * @param failure: executed on failure. Given http status then error then xhr * @return the XHR object */ self.requestJSONP = function(url, method, payload, success, failure) { method = method.toUpperCase(); var jsonp = document.createElement('script'); jsonp.type = 'text/javascript'; // Success callback var id = '__jsonp_' + Math.ceil(Math.random() * 10000); var dxhr = { jsonp:true, id:id, response:undefined }; window[id] = function(r) { jsonp.parentElement.removeChild(jsonp); delete window[id]; dxhr.response = r; if (r === undefined || r === null) { success(undefined, 200, dxhr); } else { if (r.http_status >= 200 && r.http_status <= 299) { success(r, r.http_status, dxhr); } else { failure(r.http_status, r.error, dxhr); } } }; // Error callback jsonp.onerror = function() { jsonp.parentElement.removeChild(jsonp); dxhr.jsonp_transport_error = 'ScriptErrorFailure'; failure(0, undefined, dxhr); }; var urlQuery; if (method === 'POST') { urlQuery = '?' + serializeURLQuery(payload) + '&callback=' + id + '&_=' + new Date().getTime(); } else { urlQuery = '?' + 'callback=' + id + '&_=' + new Date().getTime(); } jsonp.src = url + urlQuery; document.head.appendChild(jsonp); return dxhr; }; /********************************************************************************/ // GET /********************************************************************************/ /** * Makes a get request * @param url=/: the url to post to * @param success=undefined: executed on http success with the response * @param failure=undefined: executed on http failure * @param complete=undefined: executed after http success or failure * Returns either the xhr request or a jsonp holding object */ self.get = function(options) { var method = supportsCORS ? 'requestCORS' : 'requestJSONP'; return self[method](options.url || window.location.href, 'GET', undefined, function(response, status, xhr) { if (options.success) { options.success(response, status, xhr); } if (options.complete) { options.complete(); } }, function(status, error, xhr) { if (options.failure) { options.failure(status, error, xhr); } if (options.complete) { options.complete(); } }); }; /********************************************************************************/ // POST /********************************************************************************/ /** * Makes a post request * @param url=/: the url to post to * @param payload={}: the payload to send * @param success=undefined: executed on http success with the response * @param failure=undefined: executed on http failure * @param complete=undefined: executed after http success or failure * Returns either the xhr request or a jsonp holding object */ self.post = function(options) { var method = supportsCORS ? 'requestCORS' : 'requestJSONP'; return self[method](options.url || window.location.href, 'POST', options.payload || {}, function(response, status, xhr) { if (options.success) { options.success(response, status, xhr); } if (options.complete) { options.complete(); } }, function(status, error, xhr) { if (options.failure) { options.failure(status, error, xhr); } if (options.complete) { options.complete(); } }); }; return self; }; ns.stacktodo = ns.stacktodo || {}; ns.stacktodo.core = ns.stacktodo.core || {}; ns.stacktodo.core.jsoncors = new JSONCORS(); })(window);
{ //using constants const a = 2; console.log( a ); // 2 a = 3; // TypeError! } { //an array constant const a = [1,2,3]; a.push( 4 ); console.log( a ); // [1,2,3,4] a = 42; // TypeError! } //we can change the object using its methods, we just cannot reassign it...
import {ProviderSpecification} from 'dxref-core/system/provider/provider-specification'; import { module, test } from 'qunit'; module('Unit | dxref-core | system | provider | provider-specification'); test('provider-specification', function(assert) { var myFunc = function() {}; var providerSpec = new ProviderSpecification(['VALUE$Date', 'A', 'B', 'C', myFunc]); assert.deepEqual(providerSpec.getDependencies(), ['A', 'B', 'C']); assert.strictEqual(providerSpec.getFunctionArg(), myFunc); assert.equal(providerSpec.getOutputType(), 'VALUE$Date'); }); /** Validation of non-provider-specification conformance is tested in the bootstrap-validators-test.js */
version https://git-lfs.github.com/spec/v1 oid sha256:c1d57d1ad50c4639ecd398deb6c1db998e272cc6faf1314dec77ca509ca49153 size 1303
team1 = {"name" : "Iron Patriot", "key": "MURICA", "puzzles" : [{"idPz": 0}, // Breakfast {"idPz": 1}, // Blueprints, all {"idPz": 2}, // Morning Rotation # 1 // {"idPz": 14}, // Morning Rotation # 1 Item! (to alieviate routing issues slightly) {"idPz": 3}, // Morning Rotation # 2 // {"idPz": 15}, // Morning Rotation # 2 Item! (to alieviate routing issues slightly) {"idPz": 4}, // Morning Rotation # 3 // {"idPz": 16}, // Morning Rotation # 3 Item! (to alieviate routing issues slightly) {"idPz": 5}, // Morning Rotation # 4 // {"idPz": 17}, // Morning Rotation # 4 Item! (to alieviate routing issues slightly) {"idPz": 6}, // All together now. {"idPz": 7}, // Lunch Time {"idPz": 8}, // Evening Rotation # 1 {"idPz": 9}, // Evening Rotation # 2 {"idPz": 10}, // Evening Rotation # 3 {"idPz": 11}, // Evening Rotation # 4 {"idPz": 12}, // All together now (Blueprints) {"idPz": 13}, // All together now (Final) ], "wordweb":[], "jarvisStream" : {}, "wordwebUnknown":[0], "currentPuzzle" : 0, "teamNum" : 1, "eveningBufferIndex" : 0 } team2 = {"name" : "War Machine", "key": "WARMACHINEROX", "puzzles" : [{"idPz": 0}, // Breakfast {"idPz": 1}, // Blueprints, all {"idPz": 3}, // Morning Rotation # 2 // {"idPz": 15}, // Morning Rotation # 2 Item! (to alieviate routing issues slightly) {"idPz": 4}, // Morning Rotation # 3 // {"idPz": 16}, // Morning Rotation # 3 Item! (to alieviate routing issues slightly) {"idPz": 5}, // Morning Rotation # 4 // {"idPz": 17}, // Morning Rotation # 4 Item! (to alieviate routing issues slightly) {"idPz": 2}, // Morning Rotation # 1 // {"idPz": 14}, // Morning Rotation # 1 Item! (to alieviate routing issues slightly) {"idPz": 6}, // All together now. {"idPz": 7}, // Lunch Time {"idPz": 9}, // Evening Rotation # 2 {"idPz": 10}, // Evening Rotation # 3 {"idPz": 11}, // Evening Rotation # 4 {"idPz": 8}, // Evening Rotation # 1 {"idPz": 12}, // All together now (Blueprints) {"idPz": 13}, // All together now (Final) ], "wordweb":[], "jarvisStream" : {}, "wordwebUnknown":[0], "currentPuzzle" : 0, "teamNum" : 2, "eveningBufferIndex" : 0 } team3 = {"name" : "Hulkbuster", "key": "IRONSMASH", "puzzles" : [{"idPz": 0}, // Breakfast {"idPz": 1}, // Blueprints, all {"idPz": 4}, // Morning Rotation # 3 // {"idPz": 16}, // Morning Rotation # 3 Item! (to alieviate routing issues slightly) {"idPz": 5}, // Morning Rotation # 4 // {"idPz": 17}, // Morning Rotation # 4 Item! (to alieviate routing issues slightly) {"idPz": 2}, // Morning Rotation # 1 // {"idPz": 14}, // Morning Rotation # 1 Item! (to alieviate routing issues slightly) {"idPz": 3}, // Morning Rotation # 2 // {"idPz": 15}, // Morning Rotation # 2 Item! (to alieviate routing issues slightly) {"idPz": 6}, // All together now. {"idPz": 7}, // Lunch Time {"idPz": 10}, // Evening Rotation # 3 {"idPz": 11}, // Evening Rotation # 4 {"idPz": 8}, // Evening Rotation # 1 {"idPz": 9}, // Evening Rotation # 2 {"idPz": 12}, // All together now (Blueprints) {"idPz": 13}, // All together now (Final) ], "wordweb":[], "jarvisStream" : {}, "wordwebUnknown":[0], "currentPuzzle" : 0, "teamNum" : 3, "eveningBufferIndex" : 0 } team4 = {"name" : "Mark I", "key": "OLDSKOOL", "puzzles" : [{"idPz": 0}, // Breakfast {"idPz": 1}, // Blueprints, all {"idPz": 5}, // Morning Rotation # 4 // {"idPz": 17}, // Morning Rotation # 4 Item! (to alieviate routing issues slightly) {"idPz": 2}, // Morning Rotation # 1 // {"idPz": 14}, // Morning Rotation # 1 Item! (to alieviate routing issues slightly) {"idPz": 3}, // Morning Rotation # 2 // {"idPz": 15}, // Morning Rotation # 2 Item! (to alieviate routing issues slightly) {"idPz": 4}, // Morning Rotation # 3 // {"idPz": 16}, // Morning Rotation # 3 Item! (to alieviate routing issues slightly) {"idPz": 6}, // All together now. {"idPz": 7}, // Lunch Time {"idPz": 11}, // Evening Rotation # 4 {"idPz": 8}, // Evening Rotation # 1 {"idPz": 9}, // Evening Rotation # 2 {"idPz": 10}, // Evening Rotation # 3 {"idPz": 12}, // All together now (Blueprints) {"idPz": 13}, // All together now (Final) ], "wordweb":[], "jarvisStream" : {}, "wordwebUnknown":[0], "currentPuzzle" : 0, "teamNum" : 4, "eveningBufferIndex" : 0 } allPuzzles = [{"name": "Breakfast", //0 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, // "showInput": false, "endCondition" : {"websocket": "breakfastOver"}, // "puzzIntro": {"name": "<a href='www.skeenan.com'>Something to help, take it with you.</a>", // ".mp3": null, // "action": null}, "hint": [{"name": "Welcome to breakfast, relax, eat some.", ".mp3": null, "trig": {'time': 10}, "action": null}] }, {"name": "Blueprints", //1 "desc": "Our first Puzzle!", "file": "./puzzles/puzzle1", "estTime": 40, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "isStatPuzzle": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "wrong": "Did you really think that was the right answer?", "menace": true, "insect": true, "pluto": true, "cable": true }, "puzzIntro": {"name": "Go pick up physics quizzes", ".mp3": null, "action": null}, "hint": [{"name": "This puzzle isn't about QR codes", // ".mp3": "./audio/puzzle1/hint1", "trig": {'time': 60*10}, "text": "I can't see what you're doing from here, but have you tried to stack them?", "action": null}, {"name": "Look for letters", // ".mp3": "./audio/puzzle1/hint1", "trig": {'time': 60*15}, "text": "I can't see what you're doing from here, but have you tried to stack them?", "action": null}, {"name": "You can use an anagram solver if you want", // ".mp3": "./audio/puzzle1/hint1", "trig": {'time': 60*20}, "text": "I can't see what you're doing from here, but have you tried to stack them?", "action": null}] }, {"name": "The Grid", //2 "desc": "Our second Puzzle!", "file": "./puzzles/puzzle2", "estTime": 60, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "isStatPuzzle": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "wolverine": true}, "puzzIntro": {"name": "We need you at the Admissions conference room", ".mp3": null, "action": null}, "hint": [{"name": "It's a Sudoku", // ".mp3": "./audio/puzzle2/hint1", "trig": {'time': 60*20}, "action": null}, {"name": "Oh look, semaphore!", // ".mp3": "./audio/puzzle2/hint1", "trig": {'time': 60*25}, "action": null}, {"name": "You should probably look at it from the side the flags are on", // ".mp3": "./audio/puzzle2/hint1", "trig": {'time': 60*30}, "action": null}] }, {"name": "The Arc", //3 "desc": "Our second Puzzle!", "file": "./puzzles/puzzle2", "estTime": 60, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "isStatPuzzle": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "Colston": true}, "puzzIntro": {"name": "Eat", ".mp3": null, "action": null}, "hint": [] }, {"name": "Lasers", //4 "desc": "Our second Puzzle!", "file": "./puzzles/puzzle2", "estTime": 60, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "isStatPuzzle": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "nefaria": true}, "puzzIntro": {"name": "Spalding sub-basement", ".mp3": null, "action": null}, "hint": [{"name": "If you give me power, I can give you information", // ".mp3": "./audio/puzzle2/hint1", "trig": {'time': 60*15}, "action": null}, {"name": "The dates are important", // ".mp3": "./audio/puzzle2/hint1", "trig": {'time': 60*15}, "action": null}, {"name": "Have you tried putting them in order?", // ".mp3": "./audio/puzzle2/hint1", "trig": {'time': 60*20}, "action": null}, {"name": "More information about the songs is better (feel free to use Google)", // ".mp3": "./audio/puzzle2/hint1", "trig": {'time': 60*25}, "action": null}] }, {"name": "Rebus", //5 "desc": "Our second Puzzle!", "file": "./puzzles/puzzle2", "estTime": 60, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "isStatPuzzle": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "Harold Hogan": true}, "puzzIntro": {"name": "Lloyd Deck", ".mp3": null, "action": null}, "hint": [{"name": "The number of the puzzle will prove of use", // ".mp3": "./audio/puzzle2/hint1", "trig": {'time':60*10}, "action": null}, {"name": "index puzzle answer by puzzle number", // ".mp3": "./audio/puzzle2/hint1", "trig": {'time':60*15}, "action": null}] }, {"name": "Squares", //6 - Last before lunch "desc": "Our second Puzzle!", "file": "./puzzles/puzzle2", "estTime": 60, "overlap": true, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "allSolveTogether": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "jhammer": true}, "puzzIntro": {"name": "Everyone meet at the BBB front patio", ".mp3": null, "action": null}, "hint": [] }, {"name": "Lunch", //7 - Lunch "desc": "Our second Puzzle!", "file": "./puzzles/puzzle2", "estTime": 60, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "showInput": false, "endCondition" : {"websocket": "lunchOver"}, // "responses": {"": "You could try to give me something, anything before you press enter you know.", // "answer": true}, // "puzzIntro": {"name": "Eat", // ".mp3": null, // "action": null}, "hint": [] }, {"name": "Teamwork", //8 "desc": "Our second Puzzle!", "file": "./puzzles/puzzle2", "estTime": 60, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "endCondition" : {"websocket": "nextAfternoonPuzzle"}, "isAfternoon" : true, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "stop hammer time!": true }, "puzzIntro": {"name": "We need you at CDC 257", ".mp3": null, "action": null}, "hint": [] }, {"name": "Laserz", //9 "desc": "Our second Puzzle!", "file": "./puzzles/puzzle2", "estTime": 60, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "endCondition" : {"websocket": "nextAfternoonPuzzle"}, "isAfternoon" : true, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "answer": true}, "puzzIntro": {"name": "Moore (070 - 2)", ".mp3": null, "action": null}, "hint": [] }, {"name": "The Game", //10 "desc": "Our second Puzzle!", "file": "./puzzles/puzzle2", "estTime": 60, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "endCondition" : {"websocket": "nextAfternoonPuzzle"}, "isAfternoon" : true, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "YAYYYYYYYYYyYYYyY": true}, "puzzIntro": {"name": "A projector room close to home", ".mp3": null, "action": null}, "hint": [] }, {"name": "The Web", //11 "desc": "Our second Puzzle!", "file": "./puzzles/puzzle2", "estTime": 60, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "endCondition" : {"websocket": "nextAfternoonPuzzle"}, "overlap": true, "isAfternoon" : true, "overlap": true, "isWordWeb": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "answer": true}, "puzzIntro": {"name": "", ".mp3": null, "action": null}, "hint": [] }, {"name": "Take two on Blueprints", //12 "desc": "Our second Puzzle!", "file": "./puzzles/puzzle2", "estTime": 60, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "allSolveTogether": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "answer": true}, // "puzzIntro": {"name": "Eat", // ".mp3": null, // "action": null}, "hint": [] }, {"name": "This is it", //13 "desc": "Our second Puzzle!", "file": "./puzzles/puzzle2", "estTime": 60, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "answer": false}, //Can't have a "correct answer" for the last puzzle, or else crash // "puzzIntro": {"name": "Eat", // ".mp3": null, // "action": null}, "hint": [] }, {"name": "The Mask", //14 "desc": "Our second Puzzle!", "file": "./puzzles/puzzle2", "estTime": 60, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "responses": {"": "You could try to give me something, anything before you press enter you know.", "answer": true}, // "puzzIntro": {"name": "Eat", // ".mp3": null, // "action": null}, "hint": [] }, {"name": "The Glove", //15 "desc": "Our second Puzzle!", "file": "./puzzles/puzzle2", "estTime": 60, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "responses": {"": "You could try to give me something, anything before you press enter you know.", "answer": true}, // "puzzIntro": {"name": "Eat", // ".mp3": null, // "action": null}, "hint": [] }, {"name": "The Core", //16 "desc": "Our second Puzzle!", "file": "./puzzles/puzzle2", "estTime": 60, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "responses": {"": "You could try to give me something, anything before you press enter you know.", "answer": true}, // "puzzIntro": {"name": "Eat", // ".mp3": null, // "action": null}, "hint": [] }, {"name": "The Repulsor", //17 "desc": "Our second Puzzle!", "file": "./puzzles/puzzle2", "estTime": 60, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "responses": {"": "You could try to give me something, anything before you press enter you know.", "answer": true}, // "puzzIntro": {"name": "Eat", // ".mp3": null, // "action": null}, "hint": [] } ] morningBuffers = [{"name": "First Square", //0 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "dues": true, "birth": true, "oracle": true, "yolk": true }, "puzzIntro": {"name": "<a href='squares/1987.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "Second Square", //1 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "unix": true, "choose": true, "him": true, "graft": true }, "puzzIntro": {"name": "<a href='squares/2631.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "Another Square", //2 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "seer": true, "kraft": true, "eunuchs": true }, "puzzIntro": {"name": "<a href='squares/3237.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "The fourth", //3 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "paced": true, "idle": true, "paws": true, "tea": true }, "puzzIntro": {"name": "<a href='squares/4126.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "Num Five.", //4 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "bode": true, "idyll": true, "grease": true, "laze": true }, "puzzIntro": {"name": "<a href='squares/5346.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "Square six start", //5 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "lies": true, "ax": true, "tax": true, "bask": true }, "puzzIntro": {"name": "<a href='squares/6987.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "Square 7 begin", //6 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "ail": true, "tacks": true, "yolk": true }, "puzzIntro": {"name": "<a href='squares/7123.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "Eight Squares In", //7 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "cedar": true, "chorale": true, "marquis": true }, "puzzIntro": {"name": "<a href='squares/8873.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "Nine lives, nine squares", //8 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "corral": true, "bruise": true, "sics": true, "pair": true }, "puzzIntro": {"name": "<a href='squares/9314.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "Ten Four", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "oohs": true, "six": true, "quire": true, "stayed": true }, "puzzIntro": {"name": "<a href='squares/10242.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "Square 11", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "want": true, "few": true, "avricle": true }, "puzzIntro": {"name": "<a href='squares/11235.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "A Dozen!", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "pride": true, "staid": true, "paste": true, "woe": true }, "puzzIntro": {"name": "<a href='squares/12198.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "Lucky 13", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "reads": true, "place": true, "whoa": true, "bowed": true }, "puzzIntro": {"name": "<a href='squares/13124.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "14 it is", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "profit": true, "yule": true, "basque": true, "plaice": true }, "puzzIntro": {"name": "<a href='squares/14092.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "You're at 15!", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "lichen": true, "you'll": true, "ale": true }, "puzzIntro": {"name": "<a href='squares/15098.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "Sweet 16", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "feeder": true, "cere": true, "sorted": true }, "puzzIntro": {"name": "<a href='squares/16981.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "Boring 17", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "pare": true, "none": true, "chews": true, "sordid": true }, "puzzIntro": {"name": "<a href='squares/17092.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "Old enough to go to War(machine)", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "nun": true, "cache": true, "ooze": true, "wave": true }, "puzzIntro": {"name": "<a href='squares/18923.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "19", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "coin": true, "maid": true, "pryed": true, "waive": true }, "puzzIntro": {"name": "<a href='squares/19238.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] }, {"name": "20", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "plait": true, "made": true, "reeds": true, "lynx": true }, "puzzIntro": {"name": "<a href='squares/20.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] }, {"name": "21", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "links": true, "prophet": true, "floes": true, "rain": true }, "puzzIntro": {"name": "<a href='squares/21.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] }, {"name": "22", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "root": true, "reign": true, "liken": true }, "puzzIntro": {"name": "<a href='squares/22.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] }, {"name": "23", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "phew": true, "crewel": true, "tapir": true }, "puzzIntro": {"name": "<a href='squares/23.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] }, {"name": "24", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "taper": true, "allowed": true }, "puzzIntro": {"name": "<a href='squares/24.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] }, {"name": "25", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "cents": true, "ewe": true }, "puzzIntro": {"name": "<a href='squares/25.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "26", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "jewel": true, "whore": true, "sense": true }, "puzzIntro": {"name": "<a href='squares/26.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "27", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "cyclet": true, "liar": true, "joule": true }, "puzzIntro": {"name": "<a href='squares/27.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "28", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "mood": true, "pause": true, "islet": true }, "puzzIntro": {"name": "<a href='squares/28.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "29", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "epoch": true, "phlox": true, "want": true }, "puzzIntro": {"name": "<a href='squares/29.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "30", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "mooed": true, "Greece": true, "word": true }, "puzzIntro": {"name": "<a href='squares/30.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "31", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "acts": true, "whirred": true, "palate": true }, "puzzIntro": {"name": "<a href='squares/31.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "32", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "maize": true, "pallette": true }, "puzzIntro": {"name": "<a href='squares/32.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "33", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "you": true, "sine": true, "marqaee": true }, "puzzIntro": {"name": "<a href='squares/33.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "34", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "brews": true, "massed": true, "hoar": true, "sign": true }, "puzzIntro": {"name": "<a href='squares/34.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "35", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "potpourri": true, "doe": true, "epic": true }, "puzzIntro": {"name": "<a href='squares/35.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "36", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "rabbit": true, "rose": true, "popery": true }, "puzzIntro": {"name": "<a href='squares/36.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "37", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "rabbet": true, "illicit": true }, "puzzIntro": {"name": "<a href='squares/37.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] } ] eveningBuffers = [{"name": "To Find", //0 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "showInput": false, "endCondition" : {"websocket": "breakfastOver"}, "puzzIntro": {"name": "<a href='www.skeenan.com'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] }] morningBufferIndex = 0 stats = {} adminSockets = {sockets: []}; teams = [team1, team2, team3, team4]; function initTeams() { for (var team in teams) { teams[team].aboutToStart = 0; teams[team].sockets = []; for (var aPuzzle in teams[team].puzzles) { aPuzzle = teams[team].puzzles[aPuzzle]; aPuzzle.puzzle = allPuzzles[aPuzzle.idPz]; aPuzzle.startTime = null; aPuzzle.elapsed = null; aPuzzle.hints = []; } startPuzzle(teams[team]) } } function reloadAllPuzzles(){ for (var team in teams) { for (var aPuzzle in teams[team].puzzles) { aPuzzle = teams[team].puzzles[aPuzzle]; aPuzzle.puzzle = allPuzzles[aPuzzle.idPz]; } } } function startPuzzle(team) { //Init Jarvis stream team.jarvisStream[team.currentPuzzle] = {"name": team.puzzles[team.currentPuzzle].puzzle.name, "desc": team.puzzles[team.currentPuzzle].puzzle.desc, "data": []} var nextIntro = team.puzzles[team.currentPuzzle].puzzle.puzzIntro if (team.puzzles[team.currentPuzzle].puzzIntro){ nextIntro = team.puzzles[team.currentPuzzle].puzzIntro } if (nextIntro){ newJarvisMessageOut(team, nextIntro) } if (team.puzzles[team.currentPuzzle].puzzle.name === "Squares"){ for (var i = morningBufferIndex; i < morningBuffers.length; i++) { newJarvisMessageOut(team, morningBuffers[i].puzzIntro) }; } if (team.puzzles[team.currentPuzzle].puzzle.name === "Lunch"){ morningBufferIndex = morningBuffers.length } startPuzzleTimer(team) } function resaveAllTeams(){ //Save all the teams } function logNewStat(team, statName, value, isIncrement){ // if (!stats[statName]){ // stats[statName] = {1: 0, 2: 0, 3: 0, 4: 0} // } // if (isIncrement){ // stats[statName][team.teamNum] += value // } else { // stats[statName][team.teamNum] = value // } // updateAllCompetitionData() } function logStatsOnTime(team){ if (team.puzzles[team.currentPuzzle].puzzle.isStatPuzzle){ logNewStat(team, team.puzzles[team.currentPuzzle].puzzle.name + " time", Math.floor(team.puzzles[team.currentPuzzle].elapsed/60), false) } } function startNextPuzzle(team){ logStatsOnTime(team) team.puzzles[team.currentPuzzle].puzzle.isActive = false if (team.currentPuzzle === -1) { team.currentPuzzle = team.lastPuzzleIndex } if (team.puzzles[team.currentPuzzle + 1].puzzle.overlap || !team.puzzles[team.currentPuzzle + 1].puzzle.isActive) { if (team.puzzles[team.currentPuzzle].puzzle.isWordWeb){ emitToAllTeams(team, "bootOffWeb", true) } team.currentPuzzle ++ team.puzzles[team.currentPuzzle].puzzle.isActive = true } else { team.lastPuzzleIndex = team.currentPuzzle team.currentPuzzle = -1 team.puzzles[-1] = {} team.puzzles[-1].puzzle = getNextBuffer(team) } startPuzzle(team) } function getNextBuffer(team){ if (morningBufferIndex < morningBuffers.length){ logNewStat(team, "Pieces Found", 1, true) output = morningBuffers[morningBufferIndex] morningBufferIndex ++ return output } else { // I'm just going to assume that we're in the afternoon // if (team.eveningBufferIndex < eveningBuffers.length){ // output = eveningBuffers[team.eveningBufferIndex] // team.eveningBufferIndex ++ // return output // } else { return {"name": "Error finding next puzzle. Let's say SEGFAULT", "responses": {"": "You could try to give me something, anything before you press enter you know.", "answer": true}} // } } } function startPuzzleTimer(team){ if (team.timer == null){ team.puzzles[team.currentPuzzle].elapsed = 0; team.timer = function(){ if (typeof this.puzzles[this.currentPuzzle].elapsed === 'undefined'){ return; } this.puzzles[this.currentPuzzle].elapsed ++; emitToAllTeams(this, 'tick', {'elapsed' : this.puzzles[this.currentPuzzle].elapsed}) checkPuzzTimerHints(this); } var myVar=setInterval(function(){team.timer()},1000); } team.puzzles[team.currentPuzzle].start } function checkPuzzTimerHints(team){ var outHint = null; var puzzHints = allPuzzles[team.currentPuzzle].hint; // var outHintIndex = 0; var isUpdated = false; for (var hint in puzzHints){ if (puzzHints[hint].trig.time != null && puzzHints[hint].trig.time == team.puzzles[team.currentPuzzle].elapsed) { outHint = puzzHints[hint]; isUpdated = true; // isUpdated = (isUpdated || (hint != oldHints[outHintIndex])); // outHintIndex ++; } } if (isUpdated){ newJarvisMessageOut(team, outHint) } } function sendAllPuzzleData(team){ //TODO: Send all relevant puzzle data, how do we make sure client only // renders the most recent hint? var puzzleOut = constructAllPuzzleData(team); emitToAllTeams(team, 'jarvisUpdate', puzzleOut) emitToAllTeams(adminSockets, 'jarvisUpdate', puzzleOut) } function constructAllPuzzleData(team){ out = {}; out.name = team.name out.currentPuzzle = team.currentPuzzle out.currentPuzzleName = team.puzzles[team.currentPuzzle].puzzle.name out.jarvisStream = team.jarvisStream out.teamNum = team.teamNum out.showInput = team.puzzles[team.currentPuzzle].puzzle.showInput out.stats = stats return out } function updateAllCompetitionData(){ try{ var puzzleOut = {} for (team in teams){ team = teams[team] puzzleOut = constructAllPuzzleData(team); emitToAllTeams(team, 'compUpdate', puzzleOut) } emitToAllTeams(adminSockets, 'jarvisUpdate', puzzleOut) } catch (err) { console.log(err) } } function newJarvisMessageOut(team, message){ team.jarvisStream[team.currentPuzzle].data.push(message); // TODO: Persist! sendAllPuzzleData(team); emitToAllTeams(team, 'jarvisMessage', message) } if (teams[0].sockets == null) { initTeams() } reloadAllPuzzles(); module.exports.teams = teams; module.exports.allPuzzles = allPuzzles; module.exports.reloadAllPuzzles = reloadAllPuzzles; module.exports.resaveAllTeams = resaveAllTeams; module.exports.startPuzzle = startPuzzle; module.exports.startNextPuzzle = startNextPuzzle; module.exports.sendAllPuzzleData = sendAllPuzzleData; module.exports.emitToAllTeams = emitToAllTeams; module.exports.constructAllPuzzleData = constructAllPuzzleData; module.exports.adminSockets = adminSockets; module.exports.newJarvisMessageOut = newJarvisMessageOut; module.exports.stats = stats; module.exports.logNewStat = logNewStat;
import Off from './Off'; import On from './On'; // ============================== // CONCRETE CONTEXT // ============================== export default class Computer { constructor() { this._currentState = null; this._states = { off: new Off(), on: new On() }; } power() { this._currentState.power(this); } getCurrentState() { return this._currentState; } setCurrentState(state) { this._currentState = state; } getStates() { return this._states; } }