text
stringlengths
2
6.14k
/* 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 }) ]) }
'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--"]';
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);
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 <mstephan@shared-files.de> * 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; } } })();
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: codocmm@gmail.com ~ nqhuy2k6@gmail.com 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); } });
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 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." ); }
/** * 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:6c01f93f266bb3cf6dfd579de0e8e51354ee3bf3@dentone.cloudant.com/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() } }) }) })
/** * 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)", }; } } });
'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" <no-reply@strapi.io>'; options.replyTo = options.replyTo || '"Administration Panel" <no-reply@strapi.io>'; 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(); }); }); });
(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
{ //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
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; } }
var dir_f4703b3db1bd5f8d2d3fca771c570947 = [ [ "led.c", "led_8c.html", "led_8c" ], [ "tick.c", "tick_8c.html", "tick_8c" ], [ "usart2.c", "usart2_8c.html", "usart2_8c" ] ];
import { h } from 'omi'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(h(h.f, null, h("circle", { cx: "7.2", cy: "14.4", r: "3.2" }), h("circle", { cx: "14.8", cy: "18", r: "2" }), h("circle", { cx: "15.2", cy: "8.8", r: "4.8" })), 'BubbleChart');
var Nightmare = require('nightmare') var NTU = require('./NightmareTestUtils') const NounPhraseTest = (nightmare, delay) => { return nightmare // Can I open the addedit form and make it go away by clicking cancel? .click('#add-np').wait(delay) .click('#np-addedit-form #cancel').wait(delay) .then( res => {return NTU.lookFor(nightmare, '#np-addedit-form', false)}) // If I open the addedit form, enter and a save a noun, // will the form then go away and can I see the insertNounPhraseCheck mark in the quiz? /*.then( res => { return nightmare .click('#add-np').wait(delay) .type('#base', 'carrot').wait(delay) .click('#save-np').wait(delay) }) .then( res => {return NTU.lookFor(nightmare, '#np-addedit-form', false)}) .then( res => {return NTU.lookFor(nightmare, '#insertNounPhraseCheck', true)}) // Can I open the addedit form via editing and make it go away by clicking cancel? .then( res => { return nightmare .click('#id1').wait(delay) .click('#cancel').wait(delay) }) .then( res => {return NTU.lookFor(nightmare, '#np-addedit-form', false)}) // If I open the addedit form via editing, change and a save a noun, // will the form then go away and can I see the updateNounPhraseCheck mark in the quiz? .then( res => { return nightmare .click('#id1').wait(delay) .type('#base', 'beaver').wait(delay) .click('#save-np').wait(delay) }) .then( res => {return NTU.lookFor(nightmare, '#np-addedit-form', false)}) .then( res => {return NTU.lookFor(nightmare, '#updateNounPhraseCheck', true)}) // If I open the addedit form via editing and delete the noun, // will the form then go away and can I see the deleteNounPhraseCheck mark in the quiz? .then( res => { return nightmare .click('#id1').wait(delay) .click('#delete-np').wait(delay) }) .then( res => {return NTU.lookFor(nightmare, '#np-addedit-form', false)}) .then( res => {return NTU.lookFor(nightmare, '#deleteNounPhraseCheck', true)}) //.then( res => {return NTU.lookFor(nightmare, '#quiz', false)}) .then( res => { return nightmare .click('#add-np').wait(delay) .type('#base', 'carrot').wait(delay) .click('#save-np').wait(delay) })*/ // Can I see the examples button? //.then( res => {return NTU.lookFor(nightmare, '#examples', true)}) // Does it go away after I click it? //.then( res => {return nightmare.click('#examples')}) //.then( res => {return NTU.lookFor(nightmare, '#examples', false)}) } module.exports = NounPhraseTest
import { UIPanel, UIRow, UIHorizontalRule } from './libs/ui.js'; import { AddObjectCommand } from './commands/AddObjectCommand.js'; import { RemoveObjectCommand } from './commands/RemoveObjectCommand.js'; import { MultiCmdsCommand } from './commands/MultiCmdsCommand.js'; import { SetMaterialValueCommand } from './commands/SetMaterialValueCommand.js'; function MenubarEdit( editor ) { var strings = editor.strings; var container = new UIPanel(); container.setClass( 'menu' ); var title = new UIPanel(); title.setClass( 'title' ); title.setTextContent( strings.getKey( 'menubar/edit' ) ); container.add( title ); var options = new UIPanel(); options.setClass( 'options' ); container.add( options ); // Undo var undo = new UIRow(); undo.setClass( 'option' ); undo.setTextContent( strings.getKey( 'menubar/edit/undo' ) ); undo.onClick( function () { editor.undo(); } ); options.add( undo ); // Redo var redo = new UIRow(); redo.setClass( 'option' ); redo.setTextContent( strings.getKey( 'menubar/edit/redo' ) ); redo.onClick( function () { editor.redo(); } ); options.add( redo ); // Clear History var option = new UIRow(); option.setClass( 'option' ); option.setTextContent( strings.getKey( 'menubar/edit/clear_history' ) ); option.onClick( function () { if ( confirm( 'The Undo/Redo History will be cleared. Are you sure?' ) ) { editor.history.clear(); } } ); options.add( option ); editor.signals.historyChanged.add( function () { var history = editor.history; undo.setClass( 'option' ); redo.setClass( 'option' ); if ( history.undos.length == 0 ) { undo.setClass( 'inactive' ); } if ( history.redos.length == 0 ) { redo.setClass( 'inactive' ); } } ); // --- options.add( new UIHorizontalRule() ); // Clone var option = new UIRow(); option.setClass( 'option' ); option.setTextContent( strings.getKey( 'menubar/edit/clone' ) ); option.onClick( function () { var object = editor.selected; if ( object.parent === null ) return; // avoid cloning the camera or scene object = object.clone(); editor.execute( new AddObjectCommand( editor, object ) ); } ); options.add( option ); // Delete var option = new UIRow(); option.setClass( 'option' ); option.setTextContent( strings.getKey( 'menubar/edit/delete' ) ); option.onClick( function () { var object = editor.selected; if ( object !== null && object.parent !== null ) { editor.execute( new RemoveObjectCommand( editor, object ) ); } } ); options.add( option ); // Minify shaders var option = new UIRow(); option.setClass( 'option' ); option.setTextContent( strings.getKey( 'menubar/edit/minify_shaders' ) ); option.onClick( function () { var root = editor.selected || editor.scene; var errors = []; var nMaterialsChanged = 0; var path = []; function getPath( object ) { path.length = 0; var parent = object.parent; if ( parent !== undefined ) getPath( parent ); path.push( object.name || object.uuid ); return path; } var cmds = []; root.traverse( function ( object ) { var material = object.material; if ( material !== undefined && material.isShaderMaterial ) { try { var shader = glslprep.minifyGlsl( [ material.vertexShader, material.fragmentShader ] ); cmds.push( new SetMaterialValueCommand( editor, object, 'vertexShader', shader[ 0 ] ) ); cmds.push( new SetMaterialValueCommand( editor, object, 'fragmentShader', shader[ 1 ] ) ); ++ nMaterialsChanged; } catch ( e ) { var path = getPath( object ).join( "/" ); if ( e instanceof glslprep.SyntaxError ) errors.push( path + ":" + e.line + ":" + e.column + ": " + e.message ); else { errors.push( path + ": Unexpected error (see console for details)." ); console.error( e.stack || e ); } } } } ); if ( nMaterialsChanged > 0 ) { editor.execute( new MultiCmdsCommand( editor, cmds ), 'Minify Shaders' ); } window.alert( nMaterialsChanged + " material(s) were changed.\n" + errors.join( "\n" ) ); } ); options.add( option ); options.add( new UIHorizontalRule() ); // Set textures to sRGB. See #15903 var option = new UIRow(); option.setClass( 'option' ); option.setTextContent( strings.getKey( 'menubar/edit/fixcolormaps' ) ); option.onClick( function () { editor.scene.traverse( fixColorMap ); } ); options.add( option ); var colorMaps = [ 'map', 'envMap', 'emissiveMap' ]; function fixColorMap( obj ) { var material = obj.material; if ( material !== undefined ) { if ( Array.isArray( material ) === true ) { for ( var i = 0; i < material.length; i ++ ) { fixMaterial( material[ i ] ); } } else { fixMaterial( material ); } editor.signals.sceneGraphChanged.dispatch(); } } function fixMaterial( material ) { var needsUpdate = material.needsUpdate; for ( var i = 0; i < colorMaps.length; i ++ ) { var map = material[ colorMaps[ i ] ]; if ( map ) { map.encoding = THREE.sRGBEncoding; needsUpdate = true; } } material.needsUpdate = needsUpdate; } return container; } export { MenubarEdit };
import React from 'react'; class Icon extends React.Component { constructor(props) { super(props); this.displayName = 'Icon'; this.icon = "fa " + this.props.icon + " " + this.props.size; } render() { return ( <i className={this.icon}></i> ); } } export default Icon;
import './init' import React from 'react' import ReactDom from 'react-dom' import Root from './root' import {APP_THEMES_LIGHT, APP_THEMES_DARK} from 'reducers/settings/constants' import LocalStorage from 'lib/localStorage' import {initializeStore} from './redux/store' import {initServiceWorker} from './swWindow' // render app const renderApp = (Component, appRoot, store) => { initServiceWorker(store) ReactDom.render( <Component store={store} />, appRoot, () => { // need to make this for feature tests - application ready for testing window.__isAppReady = true }) } const prepareStoreData = () => { let theme = LocalStorage.getItem('theme') if (!theme) { if (window.matchMedia('(prefers-color-scheme: dark)')?.matches) { theme = APP_THEMES_DARK } } return { settings: { theme: theme || APP_THEMES_LIGHT } } } // init store and start app const appRoot = document.getElementById('app-root') const store = initializeStore(prepareStoreData()) renderApp(Root, appRoot, store)
/** * @author Kai Salmen / www.kaisalmen.de */ 'use strict'; if ( KSX.test.projectionspace === undefined ) KSX.test.projectionspace = {}; KSX.test.projectionspace.VerifyPP = (function () { PPCheck.prototype = Object.create(KSX.core.ThreeJsApp.prototype, { constructor: { configurable: true, enumerable: true, value: PPCheck, writable: true } }); function PPCheck(elementToBindTo, loader) { KSX.core.ThreeJsApp.call(this); this.configure({ name: 'PPCheck', htmlCanvas: elementToBindTo, useScenePerspective: true, loader: loader }); this.controls = null; this.projectionSpace = new KSX.instancing.ProjectionSpace({ low: { index: 0, name: 'Low', x: 240, y: 100, defaultHeightFactor: 9, mesh: null }, medium: { index: 1, name: 'Medium', x: 720, y: 302, defaultHeightFactor: 18, mesh: null } }, 0); this.cameraDefaults = { posCamera: new THREE.Vector3( 300, 300, 300 ), far: 100000 }; } PPCheck.prototype.initPreGL = function() { var scope = this; var callbackOnSuccess = function () { scope.preloadDone = true; }; scope.projectionSpace.loadAsyncResources( callbackOnSuccess ); }; PPCheck.prototype.initGL = function () { this.projectionSpace.initGL(); this.projectionSpace.flipTexture( 'linkPixelProtest' ); this.scenePerspective.scene.add( this.projectionSpace.dimensions[this.projectionSpace.index].mesh ); this.scenePerspective.setCameraDefaults( this.cameraDefaults ); this.controls = new THREE.TrackballControls( this.scenePerspective.camera ); }; PPCheck.prototype.resizeDisplayGL = function () { this.controls.handleResize(); }; PPCheck.prototype.renderPre = function () { this.controls.update(); }; return PPCheck; })();
import test from 'ava' import Vue from 'vue' import {createRenderer} from 'vue-server-renderer' import ContentPlaceholder from '../src' test.cb('ssr', t => { const rows = [{height: '5px', boxes: [[0, '40px']]}] const renderer = createRenderer() const app = new Vue({ template: '<content-placeholder :rows="rows"></content-placeholder>', components: {ContentPlaceholder}, data: {rows} }) renderer.renderToString(app, (err, html) => { t.falsy(err) t.true(html.includes('data-server-rendered')) t.end() }) })
import { dealsService } from '../services'; const fetchDealsData = () => { return dealsService().getDeals() .then(res => { return res.data }) // Returning [] as a placeholder now so it does not error out when this service // fails. We should be handling this in our DISPATCH_REQUEST_FAILURE .catch(() => []); }; export default fetchDealsData;
import { createPlugin } from 'draft-extend'; // TODO(mime): can't we just use LINK? i forget why we're using ANCHOR separately..., something with images probably :-/ const ENTITY_TYPE = 'ANCHOR'; // TODO(mime): one day, maybe switch wholesale to draft-extend. for now, we have a weird hybrid // of draft-extend/draft-convert/draft-js-plugins export default createPlugin({ htmlToEntity: (nodeName, node, create) => { if (nodeName === 'a') { const mutable = node.firstElementChild?.nodeName === 'IMG' ? 'IMMUTABLE' : 'MUTABLE'; const { href, target } = node; return create(ENTITY_TYPE, mutable, { href, target }); } }, entityToHTML: (entity, originalText) => { if (entity.type === ENTITY_TYPE) { const { href } = entity.data; return `<a href="${href}" target="_blank" rel="noopener noreferrer">${originalText}</a>`; } return originalText; }, }); export const AnchorDecorator = (props) => { const { href } = props.contentState.getEntity(props.entityKey).getData(); return ( <a href={href} target="_blank" rel="noopener noreferrer"> {props.children} </a> ); }; export function anchorStrategy(contentBlock, callback, contentState) { contentBlock.findEntityRanges((character) => { const entityKey = character.getEntity(); return entityKey !== null && contentState.getEntity(entityKey).getType() === ENTITY_TYPE; }, callback); }
'use strict'; var assert = require('../../helpers/assert'); var commandOptions = require('../../factories/command-options'); var stub = require('../../helpers/stub').stub; var Promise = require('../../../lib/ext/promise'); var Task = require('../../../lib/models/task'); var TestCommand = require('../../../lib/commands/test'); describe('test command', function() { var tasks; var options; var buildRun; var testRun; beforeEach(function(){ tasks = { Build: Task.extend(), Test: Task.extend() }; options = commandOptions({ tasks: tasks, testing: true }); stub(tasks.Test.prototype, 'run', Promise.resolve()); stub(tasks.Build.prototype, 'run', Promise.resolve()); buildRun = tasks.Build.prototype.run; testRun = tasks.Test.prototype.run; }); it('builds and runs test', function() { return new TestCommand(options).validateAndRun([]).then(function() { assert.equal(buildRun.called, 1, 'expected build task to be called once'); assert.equal(testRun.called, 1, 'expected test task to be called once'); }); }); it('has the correct options', function() { return new TestCommand(options).validateAndRun([]).then(function() { var buildOptions = buildRun.calledWith[0][0]; var testOptions = testRun.calledWith[0][0]; assert.equal(buildOptions.environment, 'development', 'has correct env'); assert.ok(buildOptions.outputPath, 'has outputPath'); assert.equal(testOptions.configFile, './testem.json', 'has config file'); assert.equal(testOptions.port, 7357, 'has config file'); }); }); it('passes through custom configFile option', function() { return new TestCommand(options).validateAndRun(['--config-file=some-random/path.json']).then(function() { var testOptions = testRun.calledWith[0][0]; assert.equal(testOptions.configFile, 'some-random/path.json'); }); }); it('passes through custom port option', function() { return new TestCommand(options).validateAndRun(['--port=5678']).then(function() { var testOptions = testRun.calledWith[0][0]; assert.equal(testOptions.port, 5678); }); }); });
import Vector from '../prototype' import {componentOrder, allComponents} from './components' export const withInvertedCurryingSupport = f => { const curried = right => left => f(left, right) return (first, second) => { if (second === undefined) { // check for function to allow usage by the pipeline function if (Array.isArray(first) && first.length === 2 && !(first[0] instanceof Function) && !(first[0] instanceof Number)) { return f(first[0], first[1]) } // curried form uses the given single parameter as the right value for the operation f return curried(first) } return f(first, second) } } export const skipUndefinedArguments = (f, defaultValue) => (a, b) => a === undefined || b === undefined ? defaultValue : f(a, b) export const clone = v => { if (Array.isArray(v)) { const obj = Object.create(Vector.prototype) v.forEach((value, i) => { obj[allComponents[i]] = value }) return [...v] } const prototype = Object.getPrototypeOf(v) return Object.assign(Object.create(prototype === Object.prototype ? Vector.prototype : prototype), v) }
module.exports = function() { return { server: { src: ['<%= tmp %>/index.html'], ignorePath: /\.\.\// } } };
'use strict'; angular.module('mpApp') .factory( 'preloader', function($q, $rootScope) { // I manage the preloading of image objects. Accepts an array of image URLs. function Preloader(imageLocations) { // I am the image SRC values to preload. this.imageLocations = imageLocations; // As the images load, we'll need to keep track of the load/error // counts when announing the progress on the loading. this.imageCount = this.imageLocations.length; this.loadCount = 0; this.errorCount = 0; // I am the possible states that the preloader can be in. this.states = { PENDING: 1, LOADING: 2, RESOLVED: 3, REJECTED: 4 }; // I keep track of the current state of the preloader. this.state = this.states.PENDING; // When loading the images, a promise will be returned to indicate // when the loading has completed (and / or progressed). this.deferred = $q.defer(); this.promise = this.deferred.promise; } // --- // STATIC METHODS. // --- // I reload the given images [Array] and return a promise. The promise // will be resolved with the array of image locations. 111111 Preloader.preloadImages = function(imageLocations) { var preloader = new Preloader(imageLocations); return (preloader.load()); }; // --- // INSTANCE METHODS. // --- Preloader.prototype = { // Best practice for "instnceof" operator. constructor: Preloader, // --- // PUBLIC METHODS. // --- // I determine if the preloader has started loading images yet. isInitiated: function isInitiated() { return (this.state !== this.states.PENDING); }, // I determine if the preloader has failed to load all of the images. isRejected: function isRejected() { return (this.state === this.states.REJECTED); }, // I determine if the preloader has successfully loaded all of the images. isResolved: function isResolved() { return (this.state === this.states.RESOLVED); }, // I initiate the preload of the images. Returns a promise. 222 load: function load() { // If the images are already loading, return the existing promise. if (this.isInitiated()) { return (this.promise); } this.state = this.states.LOADING; for (var i = 0; i < this.imageCount; i++) { this.loadImageLocation(this.imageLocations[i]); } // Return the deferred promise for the load event. return (this.promise); }, // --- // PRIVATE METHODS. // --- // I handle the load-failure of the given image location. handleImageError: function handleImageError(imageLocation) { this.errorCount++; // If the preload action has already failed, ignore further action. if (this.isRejected()) { return; } this.state = this.states.REJECTED; this.deferred.reject(imageLocation); }, // I handle the load-success of the given image location. handleImageLoad: function handleImageLoad(imageLocation) { this.loadCount++; // If the preload action has already failed, ignore further action. if (this.isRejected()) { return; } // Notify the progress of the overall deferred. This is different // than Resolving the deferred - you can call notify many times // before the ultimate resolution (or rejection) of the deferred. this.deferred.notify({ percent: Math.ceil(this.loadCount / this.imageCount * 100), imageLocation: imageLocation }); // If all of the images have loaded, we can resolve the deferred // value that we returned to the calling context. if (this.loadCount === this.imageCount) { this.state = this.states.RESOLVED; this.deferred.resolve(this.imageLocations); } }, // I load the given image location and then wire the load / error // events back into the preloader instance. // -- // NOTE: The load/error events trigger a $digest. 333 loadImageLocation: function loadImageLocation(imageLocation) { var preloader = this; // When it comes to creating the image object, it is critical that // we bind the event handlers BEFORE we actually set the image // source. Failure to do so will prevent the events from proper // triggering in some browsers. var image = angular.element(new Image()) .bind('load', function(event) { // Since the load event is asynchronous, we have to // tell AngularJS that something changed. $rootScope.$apply( function() { preloader.handleImageLoad(event.target.src); // Clean up object reference to help with the // garbage collection in the closure. preloader = image = event = null; } ); }) .bind('error', function(event) { // Since the load event is asynchronous, we have to // tell AngularJS that something changed. $rootScope.$apply( function() { preloader.handleImageError(event.target.src); // Clean up object reference to help with the // garbage collection in the closure. preloader = image = event = null; } ); }) .attr('src', imageLocation); } }; // Return the factory instance. return (Preloader); } );
var gulp = require('gulp'); gulp.task('dist', ['setProduction', 'sass:dist', 'browserify:dist']);
'use strict'; import Chart from 'chart.js'; import Controller from './controller'; import Scale, {defaults} from './scale'; // Register the Controller and Scale Chart.controllers.smith = Controller; Chart.defaults.smith = { aspectRatio: 1, scale: { type: 'smith', }, tooltips: { callbacks: { title: () => null, label: (bodyItem, data) => { const dataset = data.datasets[bodyItem.datasetIndex]; const d = dataset.data[bodyItem.index]; return dataset.label + ': ' + d.real + ' + ' + d.imag + 'i'; } } } }; Chart.scaleService.registerScaleType('smith', Scale, defaults);
var packageInfo = require('./package.json'); var taskList = [{name:'default'},{name:'delete'},{name:'build'},{name:'copy'},{name:'minify'}]; var gulpTalk2me = require('gulp-talk2me'); var talk2me = new gulpTalk2me(packageInfo,taskList); var del = require('del'); var gulp = require('gulp'); var runSequence = require('run-sequence'); var sourcemaps = require('gulp-sourcemaps'); var rename = require('gulp-rename'); var ngAnnotate = require('gulp-ng-annotate'); var bytediff = require('gulp-bytediff'); var uglify = require('gulp-uglify'); var concat = require('gulp-concat'); var templateCache = require('gulp-angular-templatecache'); var series = require('stream-series'); var angularFilesort = require('gulp-angular-filesort'); console.log(talk2me.greeting); gulp.task('default',function(callback){ runSequence('build',callback); }); gulp.task('delete',function(callback){ del('dist/**/*', callback()); }); gulp.task('build',function(callback){ runSequence('delete',['copy','minify'],callback); }); gulp.task('copy',function(){ return series(genTemplateStream(),gulp.src(['src/**/*.js','!src/**/*.spec.js'])) .pipe(sourcemaps.init()) .pipe(angularFilesort()) .pipe(concat('bs-fa-boolean-directive.js', {newLine: ';\n'})) .pipe(ngAnnotate({ add: true })) .pipe(sourcemaps.write('./')) .pipe(gulp.dest('dist')); }); gulp.task('minify',function(){ return series(genTemplateStream(),gulp.src(['src/**/*.js','!src/**/*.spec.js'])) .pipe(sourcemaps.init()) .pipe(angularFilesort()) .pipe(concat('bs-fa-boolean-directive.js', {newLine: ';'})) .pipe(rename(function (path) { path.basename += ".min"; })) .pipe(ngAnnotate({ add: true })) .pipe(bytediff.start()) .pipe(uglify({mangle: true})) .pipe(bytediff.stop()) .pipe(sourcemaps.write('./')) .pipe(gulp.dest('dist')); }); function genTemplateStream () { return gulp.src(['src/**/*.view.html']) .pipe(templateCache({standalone:true,module:'bs-fa-boolean.template'})); }
var BasicMathLib = artifacts.require("./BasicMathLib.sol"); var Array256Lib = artifacts.require("./Array256Lib.sol"); var TokenLib = artifacts.require("./TokenLib.sol"); var CrowdsaleLib = artifacts.require("./CrowdsaleLib.sol"); var EvenDistroCrowdsaleLib = artifacts.require("./EvenDistroCrowdsaleLib.sol"); var CrowdsaleTestTokenEteenD = artifacts.require("./CrowdsaleTestTokenEteenD"); var EvenDistroTestEteenD = artifacts.require("./EvenDistroTestEteenD.sol"); var CrowdsaleTestTokenTenD = artifacts.require("./CrowdsaleTestTokenTenD"); var EvenDistroTestTenD = artifacts.require("./EvenDistroTestTenD.sol"); module.exports = function(deployer, network, accounts) { deployer.deploy(BasicMathLib,{overwrite: false}); deployer.deploy(Array256Lib, {overwrite: false}); deployer.link(BasicMathLib, TokenLib); deployer.deploy(TokenLib, {overwrite: false}); deployer.link(BasicMathLib,CrowdsaleLib); deployer.link(TokenLib,CrowdsaleLib); deployer.deploy(CrowdsaleLib, {overwrite: false}); deployer.link(BasicMathLib,EvenDistroCrowdsaleLib); deployer.link(TokenLib,EvenDistroCrowdsaleLib); deployer.link(CrowdsaleLib,EvenDistroCrowdsaleLib); deployer.deploy(EvenDistroCrowdsaleLib, {overwrite:false}); if(network === "development" || network === "coverage"){ deployer.link(TokenLib,CrowdsaleTestTokenEteenD); deployer.link(CrowdsaleLib,EvenDistroTestEteenD); deployer.link(EvenDistroCrowdsaleLib, EvenDistroTestEteenD); deployer.link(TokenLib,CrowdsaleTestTokenTenD); deployer.link(CrowdsaleLib,EvenDistroTestTenD); deployer.link(EvenDistroCrowdsaleLib, EvenDistroTestTenD); // startTime 3 days + 1 hour in the future var startTime = (Math.floor((new Date().valueOf()/1000))) + 262800; // first price step in 7 days var stepOne = startTime + 604800; // second price step in 14 days var stepTwo = stepOne + 604800; // endTime in 30 days var endTime = startTime + 2592000; deployer.deploy(CrowdsaleTestTokenEteenD, accounts[0], "Eighteen Decimals", "ETEEN", 18, 50000000000000000000000000, false, {from:accounts[5]}) .then(function() { var purchaseData =[startTime,600000000000000000000,100, stepOne,600000000000000000000,100, stepTwo,300000000000000000000,0]; return deployer.deploy(EvenDistroTestEteenD, accounts[5], purchaseData, endTime, 100, 10000000000000000000000, false, CrowdsaleTestTokenEteenD.address, {from:accounts[5]}) }) .then(function(){ return deployer.deploy(CrowdsaleTestTokenTenD, accounts[0], "Ten Decimals", "TEN", 10, 1000000000000000, false, {from:accounts[5]}) }) .then(function() { // start next sale in 7 days startTime = endTime + 604800; stepOne = startTime + 604800; stepTwo = stepOne + 604800; endTime = startTime + 2592000; purchaseData =[startTime,4000000000000,0, stepOne,8000000000000,20000000000000, stepTwo,16000000000000,0]; return deployer.deploy(EvenDistroTestTenD, accounts[0], purchaseData, endTime, 25, 0, true, CrowdsaleTestTokenTenD.address, {from:accounts[5]}) }); } };
// // Adapted from: // http://stackoverflow.com/questions/22330103/how-to-include-node-modules-in-a-separate-browserify-vendor-bundle // var gulp = require('gulp'); var browserify = require('browserify'); var source = require('vinyl-source-stream'); var bust = require('gulp-buster'); var streamify = require('gulp-streamify'); var htmlreplace = require('gulp-html-replace'); var fs = require('fs'); var packageJson = require('./package.json'); var dependencies = Object.keys(packageJson && packageJson.dependencies || {}); function handleErrors(error) { console.error(error.stack); // Emit 'end' as the stream wouldn't do it itself. // Without this, the gulp task won't end and the watch stops working. this.emit('end'); } gulp.task('libs', function () { return browserify({debug: true}) .require(dependencies) .bundle() .on('error', handleErrors) .pipe(source('libs.js')) .pipe(gulp.dest('./dist/')) .pipe(streamify(bust())) .pipe(gulp.dest('.')); }); gulp.task('scripts', function () { return browserify('./src/index.js', {debug: true}) .external(dependencies) .bundle() .on('error', handleErrors) .on('end', ()=>{console.log("ended")}) .pipe(source('scripts.js')) .pipe(gulp.dest('./dist/')) .pipe(streamify(bust())) .pipe(gulp.dest('.')); }); gulp.task('css', function () { return gulp.src('./styles/styles.css') .pipe(gulp.dest('./dist/')) .pipe(streamify(bust())) .pipe(gulp.dest('.')); }); gulp.task('icons', function () { return gulp.src('./icons/**/*') .pipe(gulp.dest('./dist/icons')); }); gulp.task('favicons', function () { return gulp.src('./favicons/**/*') .pipe(gulp.dest('./dist/')); }); gulp.task('html', function () { var busters = JSON.parse(fs.readFileSync('busters.json')); return gulp.src('index.html') .pipe(htmlreplace({ 'css': 'styles.css?v=' + busters['dist/styles.css'], 'js': [ 'libs.js?v=' + busters['dist/libs.js'], 'scripts.js?v=' + busters['dist/scripts.js'] ] })) .pipe(gulp.dest('./dist/')); }); gulp.task('watch', function(){ gulp.watch('package.json', ['libs']); gulp.watch('src/**', ['scripts']); gulp.watch('styles/styles.css', ['css']); gulp.watch('icons/**', ['icons']); gulp.watch('favicons/**', ['favicons']); gulp.watch(['busters.json', 'index.html'], ['html']); }); gulp.task('default', ['libs', 'scripts', 'css', 'icons', 'favicons', 'html', 'watch']);
BrowserPolicy.content.allowOriginForAll("*.googleapis.com"); BrowserPolicy.content.allowOriginForAll("*.gstatic.com"); BrowserPolicy.content.allowOriginForAll("*.bootstrapcdn.com"); BrowserPolicy.content.allowOriginForAll("*.geobytes.com"); BrowserPolicy.content.allowFontDataUrl();
'use strict' if (!process.addAsyncListener) require('async-listener') var noop = function () {} module.exports = function () { return new AsyncState() } function AsyncState () { var state = this process.addAsyncListener({ create: asyncFunctionInitialized, before: asyncCallbackBefore, error: noop, after: asyncCallbackAfter }) // Record the state currently set on on the async-state object and return a // snapshot of it. The returned object will later be passed as the `data` // arg in the functions below. function asyncFunctionInitialized () { var data = {} for (var key in state) { data[key] = state[key] } return data } // We just returned from the event-loop: We'll now restore the state // previously saved by `asyncFunctionInitialized`. function asyncCallbackBefore (context, data) { for (var key in data) { state[key] = data[key] } } // Clear the state so that it doesn't leak between isolated async stacks. function asyncCallbackAfter (context, data) { for (var key in state) { delete state[key] } } }
/** Problem 9. Extract e-mails Write a function for extracting all email addresses from given text. All sub-strings that match the format @… should be recognized as emails. Return the emails as array of strings. */ console.log('Problem 9. Extract e-mails'); var text='gosho@gmail.com bla bla bla pesho_peshev@yahoo.com bla bla gosho_geshev@outlook.com' function extractEmails(text) { var result=text.match(/[A-Z0-9._-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/gi); return result; } console.log('Text: '+text); console.log('E-mail: '+extractEmails(text)); console.log('#########################################');