commit
stringlengths
40
40
subject
stringlengths
1
1.49k
old_file
stringlengths
4
311
new_file
stringlengths
4
311
new_contents
stringlengths
1
29.8k
old_contents
stringlengths
0
9.9k
lang
stringclasses
3 values
proba
float64
0
1
036d3b4e1866b5f56e12a4019bca779b7d317969
change readme
src/js/components/navigation/KLSteps/index.js
src/js/components/navigation/KLSteps/index.js
/** * @file KLSteps 步骤条 * @author ziane(zianecui@gmail.com) */ const Component = require('../../../ui-base/component'); const template = require('./index.html'); const _ = require('../../../ui-base/_'); /** * @class KLSteps * @extend Component * @param {object} [options.data] = 绑定属性 * @param {object[]} [options.data.steps=null] <=> 数据源 * @param {number} [options.data.steps[].status] => 状态id,支持方法,传入当前 current 返回 true 则属于当前状态 * @param {string} [options.data.steps[].title] => 步骤标题 * @param {object[]} [options.data.steps[].description] => 步骤具体描述 * @param {number} [options.data.current=0] <=> 当前状态 * @param {string} [options.data.size] => 当前尺寸,sm */ const KLSteps = Component.extend({ name: 'kl-steps', template, config() { _.extend(this.data, { steps: [], current: 0, size: '', currentIndex: 0, }); this.supr(); }, init() { this.supr(); this.$watch('current', () => { this.juedgeFinishedItem(); }); }, juedgeFinishedItem() { const data = this.data; const current = data.current; const steps = data.steps; steps.forEach((item, index) => { if ((typeof item.status !== 'function' && item.status / 1 === current / 1) || (typeof item.status === 'function' && item.status(current))) { data.currentIndex = index; } }); }, }); module.exports = KLSteps;
/** * @file KLSteps 步骤条 * @author ziane(zianecui@gmail.com) */ const Component = require('../../../ui-base/component'); const template = require('./index.html'); const _ = require('../../../ui-base/_'); /** * @class KLSteps * @extend Component * @param {object} [options.data] = 绑定属性 * @param {object[]} [options.data.steps=null] <=> 数据源 * @param {number} [options.data.steps[].status] => 状态id * @param {string} [options.data.steps[].title] => 步骤标题 * @param {object[]} [options.data.steps[].description] => 步骤具体描述 * @param {number} [options.data.current=0] <=> 当前状态 * @param {string} [options.data.size] => 当前尺寸,sm */ const KLSteps = Component.extend({ name: 'kl-steps', template, config() { _.extend(this.data, { steps: [], current: 0, size: '', currentIndex: 0, }); this.supr(); }, init() { this.supr(); this.$watch('current', () => { this.juedgeFinishedItem(); }); }, juedgeFinishedItem() { const data = this.data; const current = data.current; const steps = data.steps; steps.forEach((item, index) => { if ((typeof item.status !== 'function' && item.status / 1 === current / 1) || (typeof item.status === 'function' && item.status(current))) { data.currentIndex = index; } }); }, }); module.exports = KLSteps;
JavaScript
0.000001
68db3627a88782e5127e83aaa4cc8f80c2626942
fix test configs
karma-espower-preprocessor/karma.conf.js
karma-espower-preprocessor/karma.conf.js
module.exports = function (config) { config.set({ basePath: '', frameworks: ['mocha', 'expect'], files: [ { pattern: 'node_modules/requirejs/require.js', included: false }, { pattern: 'test/fixture/amd.html', watched: true, served: true, included: false }, { pattern: 'build/power-assert.js', watched: true, served: true, included: true }, { pattern: 'test/tobe_instrumented/assertion.js', watched: true, served: true, included: true }, { pattern: 'test/tobe_instrumented/assertion.es6.js', watched: true, served: true, included: true }, { pattern: 'test/tobe_instrumented/customization.js', watched: true, served: true, included: true }, { pattern: 'test/not_tobe_instrumented/not_instrumented.js', watched: true, served: true, included: true }, { pattern: 'test/tobe_instrumented/modules.js', watched: true, served: true, included: true } ], preprocessors: { 'test/tobe_*/*.js': ['espower'] }, espowerPreprocessor: { options: { emitActualCode: false } }, reporters: ['dots'], port: 9876, colors: true, browsers: ['Chrome', 'Firefox'], singleRun: true }); };
module.exports = function (config) { config.set({ basePath: '', frameworks: ['mocha', 'expect'], files: [ { pattern: 'node_modules/requirejs/require.js', included: false }, { pattern: 'test/fixture/amd.html', watched: true, served: true, included: false }, { pattern: 'build/power-assert.js', watched: true, served: true, included: true }, { pattern: 'test/tobe_instrumented/assertion.js', watched: true, served: true, included: true }, { pattern: 'test/tobe_instrumented/assertion.es6.js', watched: true, served: true, included: true }, { pattern: 'test/tobe_instrumented/customization.js', watched: true, served: true, included: true }, { pattern: 'test/not_tobe_instrumented/not_instrumented.js', watched: true, served: true, included: true }, { pattern: 'test/tobe_instrumented/modules.js', watched: true, served: true, included: true } ], preprocessors: { 'test/*/*.js': ['espower'] }, espowerPreprocessor: { options: { emitActualCode: false } }, reporters: ['dots'], port: 9876, colors: true, browsers: ['Chrome', 'Firefox'], singleRun: true }); };
JavaScript
0
221d49f83ebbb23a9ddffe76cb90c74c1e347dc7
Use separate property to shutdown workers
worker-manager.js
worker-manager.js
var Worker = require('./worker') /** * Tracks worker state across runs. */ function WorkerManager () { this._pollHandle = null this.workers = {} this.isPolling = false this.shouldShutdown = false } WorkerManager.prototype.registerWorker = function registerWorker (workerData) { if (this.workers[workerData.id]) { this.unregisterWorker(this.workers[workerData.id]) } var worker = new Worker(workerData) worker.emit('status', worker.status) this.workers[workerData.id] = worker return worker } WorkerManager.prototype.unregisterWorker = function unregisterWorker (worker) { worker.emit('delete', worker) worker.removeAllListeners() delete this.workers[worker.id] return worker } WorkerManager.prototype.updateWorker = function updateWorker (workerData) { var workers = this.workers if (workers[workerData.id]) { var worker = workers[workerData.id] var prevStatus = worker.status Object.keys(workerData).forEach(function (k) { worker[k] = workerData[k] }) if (worker.status !== prevStatus) { worker.emit('status', worker.status) } } } WorkerManager.prototype.startPolling = function startPolling (client, pollingTimeout, callback) { if (this.isPolling || this.shouldShutdown) { return } var self = this this.isPolling = true client.getWorkers(function (err, updatedWorkers) { if (err) { self.isPolling = false return (callback ? callback(err) : null) } var activeWorkers = (updatedWorkers || []).reduce(function (o, worker) { o[worker.id] = worker return o }, {}) Object.keys(self.workers).forEach(function (workerId) { if (activeWorkers[workerId]) { // process updates self.updateWorker(activeWorkers[workerId]) } else { // process deletions self.unregisterWorker(self.workers[workerId]) } }) self._pollHandle = setTimeout(function () { self.isPolling = false self.startPolling(client, pollingTimeout, callback) }, pollingTimeout) }) } WorkerManager.prototype.stopPolling = function stopPolling () { if (this._pollHandle) { clearTimeout(this._pollHandle) this._pollHandle = null } this.shouldShutdown = true } // expose a single, shared instance of WorkerManager module.exports = new WorkerManager()
var Worker = require('./worker') /** * Tracks worker state across runs. */ function WorkerManager () { this._pollHandle = null this.workers = {} this.isPolling = false } WorkerManager.prototype.registerWorker = function registerWorker (workerData) { if (this.workers[workerData.id]) { this.unregisterWorker(this.workers[workerData.id]) } var worker = new Worker(workerData) worker.emit('status', worker.status) this.workers[workerData.id] = worker return worker } WorkerManager.prototype.unregisterWorker = function unregisterWorker (worker) { worker.emit('delete', worker) worker.removeAllListeners() delete this.workers[worker.id] return worker } WorkerManager.prototype.updateWorker = function updateWorker (workerData) { var workers = this.workers if (workers[workerData.id]) { var worker = workers[workerData.id] var prevStatus = worker.status Object.keys(workerData).forEach(function (k) { worker[k] = workerData[k] }) if (worker.status !== prevStatus) { worker.emit('status', worker.status) } } } WorkerManager.prototype.startPolling = function startPolling (client, pollingTimeout, callback) { if (this.isPolling) { return } var self = this this.isPolling = true client.getWorkers(function (err, updatedWorkers) { if (err) { self.isPolling = false return (callback ? callback(err) : null) } var activeWorkers = (updatedWorkers || []).reduce(function (o, worker) { o[worker.id] = worker return o }, {}) Object.keys(self.workers).forEach(function (workerId) { if (activeWorkers[workerId]) { // process updates self.updateWorker(activeWorkers[workerId]) } else { // process deletions self.unregisterWorker(self.workers[workerId]) } }) self._pollHandle = setTimeout(function () { self.isPolling = false self.startPolling(client, pollingTimeout, callback) }, pollingTimeout) }) } WorkerManager.prototype.stopPolling = function stopPolling () { if (this._pollHandle) { clearTimeout(this._pollHandle) this._pollHandle = null } this.isPolling = false } // expose a single, shared instance of WorkerManager module.exports = new WorkerManager()
JavaScript
0
e44447153bddf2cfacddac0af533944fd329b883
enable source map.
webpack.config.js
webpack.config.js
var path = require('path'); var env = process.env.NODE_ENV || 'dev'; module.exports = { entry: './src/main.js', output: { path: './dist', publicPath: '/dist', filename: 'bundle.js' }, devServer: { inline: true, port: 3000, historyApiFallback: true }, devtool: 'source-map', resolve: { root: path.resolve(__dirname), // create tasks to choose prod/dev env // need to create an issue alias: { config: 'config/config.' + env + '.js' } }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel' }, { test: /\.scss$/, loaders: ['style', 'css', 'sass'] } ] } };
var path = require('path'); var env = process.env.NODE_ENV || 'dev'; module.exports = { entry: './src/main.js', output: { path: './dist', publicPath: '/dist', filename: 'bundle.js' }, devServer: { inline: true, port: 3000, historyApiFallback: true }, resolve: { root: path.resolve(__dirname), // create tasks to choose prod/dev env // need to create an issue alias: { config: 'config/config.' + env + '.js' } }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel' }, { test: /\.scss$/, loaders: ['style', 'css', 'sass'] } ] } };
JavaScript
0
a35c3e8052efc885284e6ac19433ee2442cfb6e5
remove unused variables
routes/docker/exec.js
routes/docker/exec.js
var express = require('express'), handler = require('../common/handler'), docker = require('../../config').docker; let router = express.Router(); router .param('id', (req, res, next, id) => { req.exec = docker.getExec(id); next(); }) .get('/:id/json', (req, res) => { req.exec.inspect(handler.sendTo(res)); }) .post('/:id/start', (req, res) => { console.log('start'); req.exec.start(req.body, handler.sendTo(res, () => { res.status(201); })); }) .post('/:id/resize', (req, res) => { req.exec.start(req.body, handler.sendTo(res, () => { res.status(201); })); }); module.exports = router;
var express = require('express'), handler = require('../common/handler'), docker = require('../../config').docker; let router = express.Router(); router .param('id', (req, res, next, id) => { req.exec = docker.getExec(id); next(); }) .get('/:id/json', (req, res) => { req.exec.inspect(handler.sendTo(res)); }) .post('/:id/start', (req, res) => { console.log('start'); req.exec.start(req.body, handler.sendTo(res, data => { res.status(201); })); }) .post('/:id/resize', (req, res) => { req.exec.start(req.body, handler.sendTo(res, data => { res.status(201); })); }); module.exports = router;
JavaScript
0.000014
c4662893e120cae90c65206a4cac43056269bc8a
Fix the order of array key when sortObjectKeys = true is given
src/object-inspector/ObjectInspector.js
src/object-inspector/ObjectInspector.js
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import TreeView from '../tree-view/TreeView'; import ObjectRootLabel from './ObjectRootLabel'; import ObjectLabel from './ObjectLabel'; import ThemeProvider from '../styles/ThemeProvider'; const createIterator = (showNonenumerable, sortObjectKeys) => { const objectIterator = function*(data) { const shouldIterate = (typeof data === 'object' && data !== null) || typeof data === 'function'; if (!shouldIterate) return; const isArray = Array.isArray(data); // iterable objects (except arrays) if (!isArray && data[Symbol.iterator]) { let i = 0; for (let entry of data) { if (Array.isArray(entry) && entry.length === 2) { const [k, v] = entry; yield { name: k, data: v, }; } else { yield { name: i.toString(), data: entry, }; } i++; } } else { const keys = Object.getOwnPropertyNames(data); if (sortObjectKeys === true && !isArray) { // Array keys should not be sorted in alphabetical order keys.sort(); } else if (typeof sortObjectKeys === 'function') { keys.sort(sortObjectKeys); } for (let propertyName of keys) { if (data.propertyIsEnumerable(propertyName)) { const propertyValue = data[propertyName]; yield { name: propertyName || `""`, data: propertyValue, }; } else if (showNonenumerable) { // To work around the error (happens some time when propertyName === 'caller' || propertyName === 'arguments') // 'caller' and 'arguments' are restricted function properties and cannot be accessed in this context // http://stackoverflow.com/questions/31921189/caller-and-arguments-are-restricted-function-properties-and-cannot-be-access let propertyValue; try { propertyValue = data[propertyName]; } catch (e) { // console.warn(e) } if (propertyValue !== undefined) { yield { name: propertyName, data: propertyValue, isNonenumerable: true, }; } } } // [[Prototype]] of the object: `Object.getPrototypeOf(data)` // the property name is shown as "__proto__" if (showNonenumerable && data !== Object.prototype /* already added */) { yield { name: '__proto__', data: Object.getPrototypeOf(data), isNonenumerable: true, }; } } }; return objectIterator; }; const defaultNodeRenderer = ({ depth, name, data, isNonenumerable }) => depth === 0 ? <ObjectRootLabel name={name} data={data} /> : <ObjectLabel name={name} data={data} isNonenumerable={isNonenumerable} />; /** * Tree-view for objects */ class ObjectInspector extends Component { static defaultProps = { showNonenumerable: false, theme: 'chromeLight', }; static propTypes = { /** An integer specifying to which level the tree should be initially expanded. */ expandLevel: PropTypes.number, /** An array containing all the paths that should be expanded when the component is initialized, or a string of just one path */ expandPaths: PropTypes.oneOfType([PropTypes.string, PropTypes.array]), name: PropTypes.string, /** Not required prop because we also allow undefined value */ data: PropTypes.any, /** A known theme or theme object */ theme: PropTypes.oneOfType([PropTypes.string, PropTypes.object]), /** Show non-enumerable properties */ showNonenumerable: PropTypes.bool, /** Sort object keys with optional compare function. */ sortObjectKeys: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]), /** Provide a custom nodeRenderer */ nodeRenderer: PropTypes.func, }; render() { const { showNonenumerable, sortObjectKeys, nodeRenderer, ...rest } = this.props; const dataIterator = createIterator(showNonenumerable, sortObjectKeys); const renderer = nodeRenderer ? nodeRenderer : defaultNodeRenderer; return ( <ThemeProvider theme={this.props.theme}> <TreeView nodeRenderer={renderer} dataIterator={dataIterator} {...rest} /> </ThemeProvider> ); } } export default ObjectInspector;
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import TreeView from '../tree-view/TreeView'; import ObjectRootLabel from './ObjectRootLabel'; import ObjectLabel from './ObjectLabel'; import ThemeProvider from '../styles/ThemeProvider'; const createIterator = (showNonenumerable, sortObjectKeys) => { const objectIterator = function*(data) { const shouldIterate = (typeof data === 'object' && data !== null) || typeof data === 'function'; if (!shouldIterate) return; // iterable objects (except arrays) if (!Array.isArray(data) && data[Symbol.iterator]) { let i = 0; for (let entry of data) { if (Array.isArray(entry) && entry.length === 2) { const [k, v] = entry; yield { name: k, data: v, }; } else { yield { name: i.toString(), data: entry, }; } i++; } } else { const keys = Object.getOwnPropertyNames(data); if (sortObjectKeys === true) { keys.sort(); } else if (typeof sortObjectKeys === 'function') { keys.sort(sortObjectKeys); } for (let propertyName of keys) { if (data.propertyIsEnumerable(propertyName)) { const propertyValue = data[propertyName]; yield { name: propertyName || `""`, data: propertyValue, }; } else if (showNonenumerable) { // To work around the error (happens some time when propertyName === 'caller' || propertyName === 'arguments') // 'caller' and 'arguments' are restricted function properties and cannot be accessed in this context // http://stackoverflow.com/questions/31921189/caller-and-arguments-are-restricted-function-properties-and-cannot-be-access let propertyValue; try { propertyValue = data[propertyName]; } catch (e) { // console.warn(e) } if (propertyValue !== undefined) { yield { name: propertyName, data: propertyValue, isNonenumerable: true, }; } } } // [[Prototype]] of the object: `Object.getPrototypeOf(data)` // the property name is shown as "__proto__" if (showNonenumerable && data !== Object.prototype /* already added */) { yield { name: '__proto__', data: Object.getPrototypeOf(data), isNonenumerable: true, }; } } }; return objectIterator; }; const defaultNodeRenderer = ({ depth, name, data, isNonenumerable }) => depth === 0 ? <ObjectRootLabel name={name} data={data} /> : <ObjectLabel name={name} data={data} isNonenumerable={isNonenumerable} />; /** * Tree-view for objects */ class ObjectInspector extends Component { static defaultProps = { showNonenumerable: false, theme: 'chromeLight', }; static propTypes = { /** An integer specifying to which level the tree should be initially expanded. */ expandLevel: PropTypes.number, /** An array containing all the paths that should be expanded when the component is initialized, or a string of just one path */ expandPaths: PropTypes.oneOfType([PropTypes.string, PropTypes.array]), name: PropTypes.string, /** Not required prop because we also allow undefined value */ data: PropTypes.any, /** A known theme or theme object */ theme: PropTypes.oneOfType([PropTypes.string, PropTypes.object]), /** Show non-enumerable properties */ showNonenumerable: PropTypes.bool, /** Sort object keys with optional compare function. */ sortObjectKeys: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]), /** Provide a custom nodeRenderer */ nodeRenderer: PropTypes.func, }; render() { const { showNonenumerable, sortObjectKeys, nodeRenderer, ...rest } = this.props; const dataIterator = createIterator(showNonenumerable, sortObjectKeys); const renderer = nodeRenderer ? nodeRenderer : defaultNodeRenderer; return ( <ThemeProvider theme={this.props.theme}> <TreeView nodeRenderer={renderer} dataIterator={dataIterator} {...rest} /> </ThemeProvider> ); } } export default ObjectInspector;
JavaScript
0.999997
abfd69cba9797b46b82c40f64788ce6dbfa0408e
remove public path for prod
webpack.config.js
webpack.config.js
const webpack = require('webpack'); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin') const UglifyJsPlugin = require("uglifyjs-webpack-plugin"); const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin"); module.exports = { mode: "production", devtool: '#source-map', node: { fs: 'empty', net: 'empty', module: 'empty' }, entry: './src/frontend/App.js', output: { path: path.resolve(__dirname + '/dist/'), filename: 'assets/bundle.js' }, optimization: { minimizer: [ new UglifyJsPlugin({ cache: true, parallel: true, sourceMap: true // set to true if you want JS source maps }), new OptimizeCSSAssetsPlugin({}) ] }, module: { rules: [ { test: /\.jsx?$/, loader: 'babel-loader', exclude: /node_modules/, query: { presets:['react']} }, { test: /\.css$/, use: [ MiniCssExtractPlugin.loader, "css-loader?modules&importLoaders=1&localIdentName=[name]_[local]_[hash:base64:5]"], exclude: /node_modules/ }, { test: /\.scss$/, use: [ MiniCssExtractPlugin.loader, "css-loader", 'sass-loader'], exclude: /node_modules/ }, { test: /\.(png|jp(e*)g)$/, use: [{ loader: 'url-loader', options: { limit: 8000, // Convert images < 8kb to base64 strings name: 'assets/img/[hash]-[name].[ext]' } }] }, { test: /\.(eot|svg|ttf|woff|woff2)$/, use: [ { loader: 'file-loader', options: { name: 'assets/fonts/[name].[ext]' } } ] } ] }, plugins: [ new MiniCssExtractPlugin({ filename: "assets/[name].css", chunkFilename: "assets/[id].css" }), new HtmlWebpackPlugin({ template: './src/index.template.html', inject: 'body', filename: 'index.html' }) ], resolve: { modules: ['node_modules'], alias: { "Components": path.resolve("./src/frontend/Components"), "Containers": path.resolve("./src/frontend/Containers"), "css": path.resolve("./src/frontend/css"), "Assets": path.resolve("./src/backend/assets"), "Routes": path.resolve("./src/backend/routes") }, extensions: ['.js', '.jsx', '.json', '.css', '.scss'] }, target: 'web' };
const webpack = require('webpack'); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin') const UglifyJsPlugin = require("uglifyjs-webpack-plugin"); const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin"); module.exports = { mode: "production", devtool: '#source-map', node: { fs: 'empty', net: 'empty', module: 'empty' }, entry: './src/frontend/App.js', output: { path: path.resolve(__dirname + '/dist/'), publicPath: '/', filename: 'assets/bundle.js' }, optimization: { minimizer: [ new UglifyJsPlugin({ cache: true, parallel: true, sourceMap: true // set to true if you want JS source maps }), new OptimizeCSSAssetsPlugin({}) ] }, module: { rules: [ { test: /\.jsx?$/, loader: 'babel-loader', exclude: /node_modules/, query: { presets:['react']} }, { test: /\.css$/, use: [ MiniCssExtractPlugin.loader, "css-loader?modules&importLoaders=1&localIdentName=[name]_[local]_[hash:base64:5]"], exclude: /node_modules/ }, { test: /\.scss$/, use: [ MiniCssExtractPlugin.loader, "css-loader", 'sass-loader'], exclude: /node_modules/ }, { test: /\.(png|jp(e*)g)$/, use: [{ loader: 'url-loader', options: { limit: 8000, // Convert images < 8kb to base64 strings name: 'assets/img/[hash]-[name].[ext]' } }] }, { test: /\.(eot|svg|ttf|woff|woff2)$/, use: [ { loader: 'file-loader', options: { name: 'assets/fonts/[name].[ext]' } } ] } ] }, plugins: [ new MiniCssExtractPlugin({ filename: "assets/[name].css", chunkFilename: "assets/[id].css" }), new HtmlWebpackPlugin({ template: './src/index.template.html', inject: 'body', filename: 'index.html' }) ], resolve: { modules: ['node_modules'], alias: { "Components": path.resolve("./src/frontend/Components"), "Containers": path.resolve("./src/frontend/Containers"), "css": path.resolve("./src/frontend/css"), "Assets": path.resolve("./src/backend/assets"), "Routes": path.resolve("./src/backend/routes") }, extensions: ['.js', '.jsx', '.json', '.css', '.scss'] }, target: 'web' };
JavaScript
0
97c41cd9710edf4e5bd9b4afcc2ef945450d8581
remove appiumVersion
test/endtoend/wdio.remote.conf.js
test/endtoend/wdio.remote.conf.js
const base = require('./wdio.base.conf') const { CompanionService } = require('./utils') function createCapability (capability) { return { 'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER, build: process.env.TRAVIS_BUILD_NUMBER, extendedDebugging: true, ...capability } } exports.config = Object.assign(base.config, { capabilities: [ { browserName: 'firefox', version: '40.0', platform: 'Linux' }, { browserName: 'firefox', version: '61.0', platform: 'Windows 10' }, { browserName: 'internet explorer', version: '10.0', platform: 'Windows 8' }, { browserName: 'internet explorer', version: '11.0', platform: 'Windows 10' }, { browserName: 'chrome', version: '70.0', platform: 'Windows 10' }, { browserName: 'MicrosoftEdge', version: '14', platform: 'Windows 10' }, { browserName: 'MicrosoftEdge', version: '17', platform: 'Windows 10' }, // { browserName: 'safari', version: '11.0', platform: 'macOS 10.12' }, // { browserName: 'safari', version: '10.0', platformName: 'iOS', platformVersion: '10.0', deviceOrientation: 'portrait', deviceName: 'iPhone 6 Simulator', appiumVersion: '1.7.1' }, { browserName: 'chrome', platformName: 'Android', platformVersion: '6.0', deviceOrientation: 'portrait', deviceName: 'Android Emulator' } ].map(createCapability), // If you only want to run your tests until a specific amount of tests have failed use // bail (default is 0 - don't bail, run all tests). bail: 3, // Set a base URL in order to shorten url command calls. If your url parameter starts // with "/", then the base url gets prepended. baseUrl: 'http://localhost', // Test runner services // Services take over a specific job you don't want to take care of. They enhance // your test setup with almost no effort. Unlike plugins, they don't add new // commands. Instead, they hook themselves up into the test process. services: ['static-server', 'sauce', new CompanionService()], user: process.env.SAUCE_USERNAME, key: process.env.SAUCE_ACCESS_KEY })
const base = require('./wdio.base.conf') const { CompanionService } = require('./utils') function createCapability (capability) { return { 'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER, build: process.env.TRAVIS_BUILD_NUMBER, extendedDebugging: true, ...capability } } exports.config = Object.assign(base.config, { capabilities: [ { browserName: 'firefox', version: '40.0', platform: 'Linux' }, { browserName: 'firefox', version: '61.0', platform: 'Windows 10' }, { browserName: 'internet explorer', version: '10.0', platform: 'Windows 8' }, { browserName: 'internet explorer', version: '11.0', platform: 'Windows 10' }, { browserName: 'chrome', version: '70.0', platform: 'Windows 10' }, { browserName: 'MicrosoftEdge', version: '14', platform: 'Windows 10' }, { browserName: 'MicrosoftEdge', version: '17', platform: 'Windows 10' }, // { browserName: 'safari', version: '11.0', platform: 'macOS 10.12' }, // { browserName: 'safari', version: '10.0', platformName: 'iOS', platformVersion: '10.0', deviceOrientation: 'portrait', deviceName: 'iPhone 6 Simulator', appiumVersion: '1.7.1' }, { browserName: 'chrome', platformName: 'Android', platformVersion: '6.0', deviceOrientation: 'portrait', deviceName: 'Android Emulator', appiumVersion: '1.7.1' } ].map(createCapability), // If you only want to run your tests until a specific amount of tests have failed use // bail (default is 0 - don't bail, run all tests). bail: 3, // Set a base URL in order to shorten url command calls. If your url parameter starts // with "/", then the base url gets prepended. baseUrl: 'http://localhost', // Test runner services // Services take over a specific job you don't want to take care of. They enhance // your test setup with almost no effort. Unlike plugins, they don't add new // commands. Instead, they hook themselves up into the test process. services: ['static-server', 'sauce', new CompanionService()], user: process.env.SAUCE_USERNAME, key: process.env.SAUCE_ACCESS_KEY })
JavaScript
0.000003
7d474e8169f45a6622760a29450436be42489213
Fix null body issue
client/src/components/Issue.js
client/src/components/Issue.js
import React from 'react'; import Avatar from './Avatar'; import Assignee from './Assignee'; import Labels from './Labels'; import Moment from 'react-moment'; import PropTypes from 'prop-types'; const Issue = ({ issue: { user: { avatar_url }, html_url, title, assignee, created_at, updated_at, labels, body } }) => { return ( <div className="issue"> <h2> <a href={html_url}>{title}</a> </h2> <Avatar url={avatar_url} user_url={getUserUrlFromIssueUrl(html_url)} /> <div> <a href={getRepoUrlFromIssueUrl(html_url)}> {getRepoNameFromIssueUrl(html_url)} </a> {assignee && <Assignee user={assignee} />} <div className="times"> <div className="timeAgo"> Created:&nbsp; <Moment fromNow parse="YYYY-MM-DDTHH:mm:ssZ"> {created_at} </Moment> </div> <div className="timeAgo"> Updated:&nbsp; <Moment fromNow parse="YYYY-MM-DDTHH:mm:ssZ"> {updated_at} </Moment> </div> </div> </div> <Labels labels={labels} /> <p className="issue-body"> {body ? body.length < maxBodyLength ? body : body.substr(0, maxBodyLength) + '...' : ''} </p> </div> ); }; const maxBodyLength = 500; function getRepoUrlFromIssueUrl(html_url) { let pattern = /^https:\/\/github.com\/[^/]+\/[^/]+\//; let matches = html_url.match(pattern); let repoUrl = ''; if (matches && matches.length > 0) { repoUrl = matches[0]; } return repoUrl; } function getUserUrlFromIssueUrl(html_url) { let pattern = /^https:\/\/github.com\/[^/]+\//; let matches = html_url.match(pattern); let userUrl = ''; if (matches && matches.length > 0) { userUrl = matches[0]; } return userUrl; } function getRepoNameFromIssueUrl(html_url) { let pattern = /https:\/\/github.com\/([^/]+)\/([^/]+)\//; let matches = html_url.match(pattern); let repoName = ''; if (matches && matches.length > 2) { repoName = matches[1] + '/' + matches[2]; } return repoName; } Issue.propTypes = { issue: PropTypes.shape({ html_url: PropTypes.string.isRequired, user: PropTypes.shape({ avatar_url: PropTypes.string.isRequired }).isRequired, title: PropTypes.string.isRequired, assignee: PropTypes.shape({ html_url: PropTypes.string.isRequired, avatar_url: PropTypes.string.isRequired }), created_at: PropTypes.string.isRequired, updated_at: PropTypes.string.isRequired, labels: PropTypes.array.isRequired, body: PropTypes.string }).isRequired }; export default Issue;
import React from 'react'; import Avatar from './Avatar'; import Assignee from './Assignee'; import Labels from './Labels'; import Moment from 'react-moment'; import PropTypes from 'prop-types'; const Issue = ({ issue: { user: { avatar_url }, html_url, title, assignee, created_at, updated_at, labels, body } }) => { return ( <div className='issue'> <h2> <a href={html_url}>{title}</a> </h2> <Avatar url={avatar_url} user_url={getUserUrlFromIssueUrl(html_url)} /> <div> <a href={getRepoUrlFromIssueUrl(html_url)}> {getRepoNameFromIssueUrl(html_url)} </a> {assignee && <Assignee user={assignee} />} <div className='times'> <div className='timeAgo'> Created: <Moment fromNow parse='YYYY-MM-DDTHH:mm:ssZ'> {created_at} </Moment> </div> <div className='timeAgo'> Updated: <Moment fromNow parse='YYYY-MM-DDTHH:mm:ssZ'> {updated_at} </Moment> </div> </div> </div> <Labels labels={labels} /> <p className='issue-body'> {body.length < maxBodyLength ? body : body.substr(0, maxBodyLength) + '...'} </p> </div> ); }; const maxBodyLength = 500; function getRepoUrlFromIssueUrl(html_url) { let pattern = /^https:\/\/github.com\/[^/]+\/[^/]+\//; let matches = html_url.match(pattern); let repoUrl = ''; if (matches && matches.length > 0) { repoUrl = matches[0]; } return repoUrl; } function getUserUrlFromIssueUrl(html_url) { let pattern = /^https:\/\/github.com\/[^/]+\//; let matches = html_url.match(pattern); let userUrl = ''; if (matches && matches.length > 0) { userUrl = matches[0]; } return userUrl; } function getRepoNameFromIssueUrl(html_url) { let pattern = /https:\/\/github.com\/([^/]+)\/([^/]+)\//; let matches = html_url.match(pattern); let repoName = ''; if (matches && matches.length > 2) { repoName = matches[1] + '/' + matches[2]; } return repoName; } Issue.propTypes = { issue: PropTypes.shape({ html_url: PropTypes.string.isRequired, user: PropTypes.shape({ avatar_url: PropTypes.string.isRequired }).isRequired, title: PropTypes.string.isRequired, assignee: PropTypes.shape({ html_url: PropTypes.string.isRequired, avatar_url: PropTypes.string.isRequired }), created_at: PropTypes.string.isRequired, updated_at: PropTypes.string.isRequired, labels: PropTypes.array.isRequired, body: PropTypes.string.isRequired }).isRequired }; export default Issue;
JavaScript
0.000001
b4d77fa1968a8faa79dfeceaee13bd3fecf630aa
Update building config
webpack.config.js
webpack.config.js
const path = require('path'); module.exports = { entry: path.join(__dirname, 'src'), output: { library: 'RsuiteDatepicker', libraryTarget: 'umd', umdNamedDefine: true, path: path.join(__dirname, 'dist'), filename: 'rsuite-datepicker.js' }, module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel-loader' }, { test: /\.less$/, loader: 'style!css!less' } ] }, externals: { 'react': { root: 'React', commonjs2: 'react', commonjs: 'react', amd: 'react' }, 'react-dom': { root: 'ReactDOM', commonjs2: 'react-dom', commonjs: 'react-dom', amd: 'react-dom' } } };
const path = require('path'); module.exports = { entry: path.join(__dirname, 'src'), output: { library: 'RsuiteDatepicker', libraryTarget: 'umd', path: path.join(__dirname, 'dist'), filename: 'bundle.js' }, module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel-loader', query: { presets: ['es2015', 'react'] } }, { test: /\.less$/, loader: 'style!css!less' } ] }, devtool: 'source-map', externals: { 'react': 'React', 'react-dom': 'ReactDOM', 'moment': 'moment' } };
JavaScript
0.000001
13361865c78fa6be9828ab4c6bf53169f7bf52fc
made action verbs uppercase. #16
src/actionTypes.js
src/actionTypes.js
export const BLUR = 'redux-form/BLUR'; export const CHANGE = 'redux-form/CHANGE'; export const INITIALIZE = 'redux-form/INITIALIZE'; export const RESET = 'redux-form/RESET'; export const TOUCH = 'redux-form/TOUCH'; export const TOUCH_ALL = 'redux-form/TOUCH_ALL'; export const UNTOUCH = 'redux-form/UNTOUCH'; export const UNTOUCH_ALL = 'redux-form/UNTOUCH_ALL';
export const BLUR = 'redux-form/blur'; export const CHANGE = 'redux-form/change'; export const INITIALIZE = 'redux-form/initialize'; export const RESET = 'redux-form/reset'; export const TOUCH = 'redux-form/touch'; export const TOUCH_ALL = 'redux-form/touch-all'; export const UNTOUCH = 'redux-form/untouch'; export const UNTOUCH_ALL = 'redux-form/untouch-all';
JavaScript
0.999173
92f6d5545818b338a0642e79103e5e284662cb38
Add failing test
test/fixtures/hard/indentation.js
test/fixtures/hard/indentation.js
import styled, { keyframes, css } from 'styled-components' // None of the below should throw indentation errors const Comp = () => { const Button = styled.button` color: blue; ` return Button } const Comp2 = () => { const InnerComp = () => { const Button = styled.button` color: blue; ` return Button } return InnerComp() } const Button = styled.button`color: blue;` const animations = { spinnerCircle: keyframes` 0% { opacity: 0; } 100% { opacity: 1; } ` } const helper = condition => { if (condition) { return css` color: red; &:hover { color: blue; } ` } return null }
import styled, { keyframes } from 'styled-components' // None of the below should throw indentation errors const Comp = () => { const Button = styled.button` color: blue; ` return Button } const Comp2 = () => { const InnerComp = () => { const Button = styled.button` color: blue; ` return Button } return InnerComp() } const Button = styled.button`color: blue;` const animations = { spinnerCircle: keyframes` 0% { opacity: 0; } 100% { opacity: 1; } ` }
JavaScript
0.000138
6703cf195a87cb3758015379cf2302d6ebe32366
Make bin/rnws.js executable
bin/rnws.js
bin/rnws.js
#!/usr/bin/env node const path = require('path'); const fs = require('fs'); const program = require('commander'); const package = require('../package.json'); const fetch = require('../lib/fetch'); const Server = require('../lib/Server'); /** * Create a server instance using the provided options. * @param {Object} opts react-native-webpack-server options * @return {Server} react-native-webpack-server server */ function createServer(opts) { opts.webpackConfigPath = path.resolve(process.cwd(), opts.webpackConfigPath); if (fs.existsSync(opts.webpackConfigPath)) { opts.webpackConfig = require(path.resolve(process.cwd(), opts.webpackConfigPath)); } else { throw new Error('Must specify webpackConfigPath or create ./webpack.config.js'); } delete opts.webpackConfigPath; const server = new Server(opts); return server; } function commonOptions(program) { return program .option( '-H, --hostname [hostname]', 'Hostname on which the server will listen. [localhost]', 'localhost' ) .option( '-P, --port [port]', 'Port on which the server will listen. [8080]', 8080 ) .option( '-p, --packagerPort [port]', 'Port on which the react-native packager will listen. [8081]', 8081 ) .option( '-w, --webpackPort [port]', 'Port on which the webpack dev server will listen. [8082]', 8082 ) .option( '-c, --webpackConfigPath [path]', 'Path to the webpack configuration file. [webpack.config.js]', 'webpack.config.js' ) .option( '-e, --entry [name]', 'Webpack entry module. [index.ios]', 'index.ios' ); } program.version(package.version); commonOptions(program.command('start')) .description('Start the webpack server.') .option('-r, --hot', 'Enable hot module replacement. [false]', false) .action(function(options) { const opts = options.opts(); const server = createServer(opts); server.start(); }); commonOptions(program.command('bundle')) .description('Bundle the app for distribution.') .option( '-b, --bundlePath [path]', 'Path where the bundle should be written. [./iOS/main.jsbundle]', './iOS/main.jsbundle' ) .action(function(options) { const opts = options.opts(); const server = createServer(opts); const url = 'http://localhost:' + opts.port + '/index.ios.bundle'; const targetPath = path.resolve(opts.bundlePath); server.start(); fetch(url).then(function(content) { fs.writeFileSync(targetPath, content); server.stop(); // XXX: Hack something is keeping the process alive but we can still // safely kill here without leaving processes hanging around... process.exit(0); }).catch(function(err) { console.log('Error creating bundle...', err.stack); server.stop(); }); }); program.parse(process.argv);
#!/usr/bin/env node const path = require('path'); const fs = require('fs'); const program = require('commander'); const package = require('../package.json'); const fetch = require('../lib/fetch'); const Server = require('../lib/Server'); /** * Create a server instance using the provided options. * @param {Object} opts react-native-webpack-server options * @return {Server} react-native-webpack-server server */ function createServer(opts) { opts.webpackConfigPath = path.resolve(process.cwd(), opts.webpackConfigPath); if (fs.existsSync(opts.webpackConfigPath)) { opts.webpackConfig = require(path.resolve(process.cwd(), opts.webpackConfigPath)); } else { throw new Error('Must specify webpackConfigPath or create ./webpack.config.js'); } delete opts.webpackConfigPath; const server = new Server(opts); return server; } function commonOptions(program) { return program .option( '-H, --hostname [hostname]', 'Hostname on which the server will listen. [localhost]', 'localhost' ) .option( '-P, --port [port]', 'Port on which the server will listen. [8080]', 8080 ) .option( '-p, --packagerPort [port]', 'Port on which the react-native packager will listen. [8081]', 8081 ) .option( '-w, --webpackPort [port]', 'Port on which the webpack dev server will listen. [8082]', 8082 ) .option( '-c, --webpackConfigPath [path]', 'Path to the webpack configuration file. [webpack.config.js]', 'webpack.config.js' ) .option( '-e, --entry [name]', 'Webpack entry module. [index.ios]', 'index.ios' ); } program.version(package.version); commonOptions(program.command('start')) .description('Start the webpack server.') .option('-r, --hot', 'Enable hot module replacement. [false]', false) .action(function(options) { const opts = options.opts(); const server = createServer(opts); server.start(); }); commonOptions(program.command('bundle')) .description('Bundle the app for distribution.') .option( '-b, --bundlePath [path]', 'Path where the bundle should be written. [./iOS/main.jsbundle]', './iOS/main.jsbundle' ) .action(function(options) { const opts = options.opts(); const server = createServer(opts); const url = 'http://localhost:' + opts.port + '/index.ios.bundle'; const targetPath = path.resolve(opts.bundlePath); server.start(); fetch(url).then(function(content) { fs.writeFileSync(targetPath, content); server.stop(); // XXX: Hack something is keeping the process alive but we can still // safely kill here without leaving processes hanging around... process.exit(0); }).catch(function(err) { console.log('Error creating bundle...', err.stack); server.stop(); }); }); program.parse(process.argv);
JavaScript
0.000015
3135fb1373abcedb2f001d12a59509151cbad113
update babel-loder config
webpack.config.js
webpack.config.js
module.exports = webpackConfig => { webpackConfig.babel.plugins.push('antd'); webpackConfig.module.loaders.unshift( { test: /\.jsx?/, exclude: /node_modules/, loader: 'babel', query: { presets: [ 'es2015', 'react', 'stage-0' ] } } ); return webpackConfig; };
module.exports = webpackConfig => { webpackConfig.babel.plugins.push('antd'); webpackConfig.module.loaders.unshift( { test: /src(\\|\/).+\.jsx?$/, exclude: /node_modules/, loader: 'babel', query: { presets: [ 'es2015', 'react', 'stage-0' ] } } ); return webpackConfig; };
JavaScript
0
127a05ae0dffa44e70906e11d1b66be9bb8d6442
Fix test case mistakes
client/test/changeset_tests.js
client/test/changeset_tests.js
/** * Copyright 2010 PolicyPad * * 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. */ /** * These test deal with generating changesets based in user * insertions in the editor. */ module("Insertion Changeset Generation"); /** * Old: foobar * New: foobarbaz * * Expected: Z:6>3=6+3$baz */ test('simple single line append', function() { equals(generateChangeset('foobar', 'foobarbaz'), 'Z:6>3=6+3$baz'); }); /** * Old: fo * New: foo * * Expected: Z:2>1=2+1$o */ test('single character append', function() { equals(generateChangeset('fo', 'foo'), 'Z:2>1=2+1$o'); }); /** * Old: foobaz * New: foobarbaz * * Expected: Z:6>3=5+3=1$rba */ test('simple single line insert', function() { equals(generateChangeset('foobaz', 'foobarbaz'), 'Z:6>3=5+3=1$rba'); }); /** * Old: foo\n * New: foo\nbar * * Expected: Z:4>3|1=4+3$bar */ test('simple multi line append', function() { equals(generateChangeset('foo\n', 'foo\nbar'), 'Z:4>3|1=4+3$bar'); }); /** * Old: foo\nbar * New: foo\nbar\nbaz * * Expected: Z:7>4|1=4=3|1+1+3$\nbaz */ test('simple multi line append without original newline', function() { equals(generateChangeset('foo\nbar', 'foo\nbar\nbaz'), 'Z:7>4|1=4=3|1+1+3$\nbaz'); }); /** * Old: foo\nbaz * New: foo\nbar\nbaz * * Expected: Z:7>4|1=4+4$bar\n */ test('simple multi line insert', function() { equals(generateChangeset('foo\nbaz', 'foo\nbar\nbaz'), 'Z:7>4|1=4=2|1+2+2=1$r\nba'); }); /** * These tests deal with generating changesets based on deletions * from within the editor. */ module('Deletion Changeset Generation'); /** * Old: fooo * New: foo * * Expected: Z:4<1=3-1 */ test('simple single character delete', function() { equals(generateChangeset('fooo', 'foo'), 'Z:4<1=3-1'); }); /** * Old: foobarbaz * New: foobaz * * Expected: Z:9<3=5-3=1 */ test('simple single line characters delete', function() { equals(generateChangeset('foobarbaz', 'foobaz'), 'Z:9<3=5-3=1'); });
/** * Copyright 2010 PolicyPad * * 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. */ /** * These test deal with generating changesets based in user * insertions in the editor. */ module("Insertion Changeset Generation"); /** * Old: foobar * New: foobarbaz * * Expected: Z:6>3=6+3$baz */ test('simple single line append', function() { equals(generateChangeset('foobar', 'foobarbaz'), 'Z:6>3=6+3$baz'); }); /** * Old: fo * New: foo * * Expected: Z:2>1=2+1$o */ test('single character append', function() { equals(generateChangeset('fo', 'foo'), 'Z:2>1=2+1$o'); }); /** * Old: foobaz * New: foobarbaz * * Expected: Z:6>3=3+3$bar */ test('simple single line insert', function() { equals(generateChangeset('foobaz', 'foobarbaz'), 'Z:6>3=3+3$bar'); }); /** * Old: foo\n * New: foo\nbar * * Expected: Z:4>3|1=4+3$bar */ test('simple multi line append', function() { equals(generateChangeset('foo\n', 'foo\nbar'), 'Z:4>3|1=4+3$bar'); }); /** * Old: foo\nbar * New: foo\nbar\nbaz * * Expected: Z:7>4|1=4=3+4$\nbaz */ test('simple multi line append without original newline', function() { equals(generateChangeset('foo\nbar', 'foo\nbar\nbaz'), 'Z:7>4|1=4=3+4$\nbaz'); }); /** * Old: foo\nbaz * New: foo\nbar\nbaz * * Expected: Z:7>4|1=4+4$bar\n */ test('simple multi line insert', function() { equals(generateChangeset('foo\nbaz', 'foo\nbar\nbaz'), 'Z:7>4|1=4+4$bar\n'); }); /** * These tests deal with generating changesets based on deletions * from within the editor. */ module('Deletion Changeset Generation'); /** * Old: fooo * New: foo * * Expected: Z:4<1=3-1 */ test('simple single character delete', function() { equals(generateChangeset('fooo', 'foo'), 'Z:4<1=3-1'); }); /** * Old: foobarbaz * New: foobaz * * Expected: Z:6<3=3-3 */ test('simple single line characters delete', function() { equals(generateChangeset('foobarbaz', 'foobaz'), 'Z:6<3=3-3'); });
JavaScript
0.999995
932c97d216606859ac8b0049c3a615e23681ef21
Fix dz can use new components
packages/strapi-plugin-content-type-builder/utils/attributes.js
packages/strapi-plugin-content-type-builder/utils/attributes.js
'use strict'; const _ = require('lodash'); const toUID = (name, plugin) => { const modelUID = Object.keys(strapi.contentTypes).find(key => { const ct = strapi.contentTypes[key]; if (ct.modelName === name && ct.plugin === plugin) return true; }); return modelUID; }; const fromUID = uid => { const contentType = strapi.contentTypes[uid]; const { modelName, plugin } = contentType; return { modelName, plugin }; }; const hasComponent = model => { const compoKeys = Object.keys(model.attributes || {}).filter(key => { return model.attributes[key].type === 'component'; }); return compoKeys.length > 0; }; const isRelation = attribute => _.has(attribute, 'target') || _.has(attribute, 'model') || _.has(attribute, 'collection'); /** * Formats a component's attributes * @param {Object} attributes - the attributes map * @param {Object} context - function context * @param {Object} context.component - the associated component */ const formatAttributes = model => { return Object.keys(model.attributes).reduce((acc, key) => { acc[key] = formatAttribute(key, model.attributes[key], { model }); return acc; }, {}); }; /** * Fromats a component attribute * @param {string} key - the attribute key * @param {Object} attribute - the attribute * @param {Object} context - function context * @param {Object} context.component - the associated component */ const formatAttribute = (key, attribute, { model }) => { if (_.has(attribute, 'type')) return attribute; // format relations const relation = (model.associations || []).find( assoc => assoc.alias === key ); const { plugin } = attribute; let targetEntity = attribute.model || attribute.collection; if (plugin === 'upload' && targetEntity === 'file') { return { type: 'media', multiple: attribute.collection ? true : false, required: attribute.required ? true : false, }; } else { return { nature: relation.nature, target: targetEntity === '*' ? targetEntity : toUID(targetEntity, plugin), plugin: plugin || undefined, dominant: attribute.dominant ? true : false, targetAttribute: attribute.via || undefined, columnName: attribute.columnName || undefined, targetColumnName: _.get( strapi.getModel(targetEntity, plugin), ['attributes', attribute.via, 'columnName'], undefined ), unique: attribute.unique ? true : false, }; } }; // TODO: move to schema builder const replaceTemporaryUIDs = uidMap => schema => { return { ...schema, attributes: Object.keys(schema.attributes).reduce((acc, key) => { const attr = schema.attributes[key]; if (attr.type === 'component') { if (_.has(uidMap, attr.component)) { acc[key] = { ...attr, component: uidMap[attr.component], }; return acc; } if (!_.has(strapi.components, attr.component)) { throw new Error('component.notFound'); } } if ( attr.type === 'dynamiczone' && _.intersection(attr.components, Object.keys(uidMap)).length > 0 ) { acc[key] = { ...attr, components: attr.components.map(value => { if (_.has(uidMap, value)) return uidMap[value]; if (!_.has(strapi.components, value)) { throw new Error('component.notFound'); } return value; }), }; return acc; } acc[key] = attr; return acc; }, {}), }; }; module.exports = { fromUID, toUID, hasComponent, isRelation, replaceTemporaryUIDs, formatAttributes, formatAttribute, };
'use strict'; const _ = require('lodash'); const toUID = (name, plugin) => { const modelUID = Object.keys(strapi.contentTypes).find(key => { const ct = strapi.contentTypes[key]; if (ct.modelName === name && ct.plugin === plugin) return true; }); return modelUID; }; const fromUID = uid => { const contentType = strapi.contentTypes[uid]; const { modelName, plugin } = contentType; return { modelName, plugin }; }; const hasComponent = model => { const compoKeys = Object.keys(model.attributes || {}).filter(key => { return model.attributes[key].type === 'component'; }); return compoKeys.length > 0; }; const isRelation = attribute => _.has(attribute, 'target') || _.has(attribute, 'model') || _.has(attribute, 'collection'); /** * Formats a component's attributes * @param {Object} attributes - the attributes map * @param {Object} context - function context * @param {Object} context.component - the associated component */ const formatAttributes = model => { return Object.keys(model.attributes).reduce((acc, key) => { acc[key] = formatAttribute(key, model.attributes[key], { model }); return acc; }, {}); }; /** * Fromats a component attribute * @param {string} key - the attribute key * @param {Object} attribute - the attribute * @param {Object} context - function context * @param {Object} context.component - the associated component */ const formatAttribute = (key, attribute, { model }) => { if (_.has(attribute, 'type')) return attribute; // format relations const relation = (model.associations || []).find( assoc => assoc.alias === key ); const { plugin } = attribute; let targetEntity = attribute.model || attribute.collection; if (plugin === 'upload' && targetEntity === 'file') { return { type: 'media', multiple: attribute.collection ? true : false, required: attribute.required ? true : false, }; } else { return { nature: relation.nature, target: targetEntity === '*' ? targetEntity : toUID(targetEntity, plugin), plugin: plugin || undefined, dominant: attribute.dominant ? true : false, targetAttribute: attribute.via || undefined, columnName: attribute.columnName || undefined, targetColumnName: _.get( strapi.getModel(targetEntity, plugin), ['attributes', attribute.via, 'columnName'], undefined ), unique: attribute.unique ? true : false, }; } }; const replaceTemporaryUIDs = uidMap => schema => { return { ...schema, attributes: Object.keys(schema.attributes).reduce((acc, key) => { const attr = schema.attributes[key]; if (attr.type === 'component') { if (_.has(uidMap, attr.component)) { acc[key] = { ...attr, component: uidMap[attr.component], }; return acc; } if (!_.has(strapi.components, attr.component)) { throw new Error('component.notFound'); } } if ( attr.type === 'dynamiczone' && _.intersection(attr.components, Object.keys(uidMap)).length > 0 ) { acc[key] = { ...attr, components: attr.components.map(value => { if (_.has(uidMap, value)) return uidMap[value]; if (!_.has(strapi.components, attr.component)) { throw new Error('component.notFound'); } return value; }), }; return acc; } acc[key] = attr; return acc; }, {}), }; }; module.exports = { fromUID, toUID, hasComponent, isRelation, replaceTemporaryUIDs, formatAttributes, formatAttribute, };
JavaScript
0
e68462264402c61ab3802657a6dce054e40d9ec0
Add xls & ppt support
contentscript.js
contentscript.js
// Avoid recursive frame insertion... var extensionOrigin = 'chrome-extension://' + chrome.runtime.id; if (!location.ancestorOrigins.contains(extensionOrigin)) { // Supported File Types var fileTypes = ['.pdf', '.doc', '.xls', '.ppt']; var links = document.getElementsByTagName('a'); var pdfLinks = []; Object.keys(links).forEach(function (id) { var link = links[id]; fileTypes.some(function (ext) { if (link.href.indexOf(ext) > -1) { pdfLinks.push(link); return true; } }); }); pdfLinks.forEach(function (link) { var iframe = document.createElement('iframe'); // Must be declared at web_accessible_resources in manifest.json iframe.src = chrome.runtime.getURL('frame.html') + '?url=' + link.href; // Basic Style iframe.style.cssText = 'display:block;height:600px;width:664px;z-index:99999;border:none;margin-top:10px;margin-bottom:10px;'; // Insert after Link to include in Google doc viewer link.parentNode.insertBefore(iframe, link.nextSibling) }); }
// Avoid recursive frame insertion... var extensionOrigin = 'chrome-extension://' + chrome.runtime.id; if (!location.ancestorOrigins.contains(extensionOrigin)) { var links = document.getElementsByTagName('a'); var pdfLinks = []; Object.keys(links).forEach(function (id) { var link = links[id]; if (link.href.indexOf('.pdf') > -1 || link.href.indexOf('.doc') > -1) { pdfLinks.push(link); } }); pdfLinks.forEach(function (link) { var iframe = document.createElement('iframe'); // Must be declared at web_accessible_resources in manifest.json iframe.src = chrome.runtime.getURL('frame.html') + '?url=' + link.href; // Basic Style iframe.style.cssText = 'display:block;height:600px;width:664px;z-index:99999;border:none;margin-top:10px;margin-bottom:10px;'; // Insert after Link to include in Google doc viewer link.parentNode.insertBefore(iframe, link.nextSibling) }); }
JavaScript
0
c339e575c51ce62e409b33c05a7de4173d13126b
Fix toJSON call
model/base.js
model/base.js
// db.Base extensions. Currently purely about base methods needed for JSON snapshots 'use strict'; var memoize = require('memoizee/plain') , ensureDb = require('dbjs/valid-dbjs'); module.exports = memoize(function (db) { ensureDb(db).Base.prototype.__descriptorPrototype__.setProperties({ // Field (label: value) JSON serializer fieldToJSON: function (ignore) { var value = this.object.get(this.key), result; if (value.forEach && !this.nested && this.multiple) { result = []; value.forEach(function (value) { result.push(this.type.valueToJSON(value, this)); }, this); value = result; } else { value = this.type.valueToJSON(value, this); } return { label: this.dynamicLabelKey ? this.object.get(this.dynamicLabelKey) : this.label, value: value }; } }); db.Base.prototype.defineProperties({ // Whether value should be considered as empty isEmpty: { type: db.Function }, toJSON: { type: db.Function } }); return db.Base.defineProperties({ // Whether provided value should be considered empty isValueEmpty: { type: db.Function, value: function (value) { if (value == null) return true; if (typeof value.isEmpty !== 'function') return false; return value.isEmpty(); } }, // Returns JSON representation of provided value (in many cases it's same as value) valueToJSON: { type: db.Function, value: function (value, descriptor) { if (value == null) return value; if (this.database.isObjectType(this)) { if (typeof value.toJSON === 'function') return value.toJSON(descriptor); return value.toString(descriptor); } return (new this(value)).toString(descriptor); } } }); }, { normalizer: require('memoizee/normalizers/get-1')() });
// db.Base extensions. Currently purely about base methods needed for JSON snapshots 'use strict'; var memoize = require('memoizee/plain') , ensureDb = require('dbjs/valid-dbjs'); module.exports = memoize(function (db) { ensureDb(db).Base.prototype.__descriptorPrototype__.setProperties({ // Field (label: value) JSON serializer fieldToJSON: function (ignore) { var value = this.object.get(this.key), result; if (value.forEach && !this.nested && this.multiple) { result = []; value.forEach(function (value) { result.push(this.type.valueToJSON(value, this)); }, this); value = result; } else { value = this.type.valueToJSON(value, this); } return { label: this.dynamicLabelKey ? this.object.get(this.dynamicLabelKey) : this.label, value: value }; } }); db.Base.prototype.defineProperties({ // Whether value should be considered as empty isEmpty: { type: db.Function }, toJSON: { type: db.Function } }); return db.Base.defineProperties({ // Whether provided value should be considered empty isValueEmpty: { type: db.Function, value: function (value) { if (value == null) return true; if (typeof value.isEmpty !== 'function') return false; return value.isEmpty(); } }, // Returns JSON representation of provided value (in many cases it's same as value) valueToJSON: { type: db.Function, value: function (value, descriptor) { if (value == null) return value; if (this.database.isObjectType(this)) { if (typeof value.toJSON === 'function') return value.toJSON(this); return value.toString(descriptor); } return (new this(value)).toString(descriptor); } } }); }, { normalizer: require('memoizee/normalizers/get-1')() });
JavaScript
0.000648
f7ffc12c320883bb591e8e0a8099ed2e262c6365
Fix buffer size
bin/tcap.js
bin/tcap.js
#!/usr/bin/env node 'use strict'; var commander = require('commander'); var TChannelTracker = require('../tchannel-tracker.js'); var ansi = require('../ansi.js'); if (require.main === module) { main(); } function main(arg) { commander.version(require('../package.json').version) .option('-i --interface [interface', 'network interface name for capture (defaults to first with an address)', '') .option('-f --filter [filter]', 'packet filter in pcap-filter(7) syntax (default: all TCP packets on port 4040)') .option('-b --buffer-size [mb]', 'size in MiB to buffer between libpcap and app (default: 10)') .option('--no-color', 'disables colors (default: not attached to a tty)') .parse(process.argv); var color = commander.color && !!process.stdout.isTTY; ansi.no_color = !color; var bufferSizeMb = commander.bufferSize || 10; checkUid(); var tracker = new TChannelTracker({ interface: commander.interface, filter: commander.filter, bufferSize: bufferSizeMb * 1024 * 1024 }); tracker.listen(); } function checkUid() { if (process.getuid() !== 0) { console.log(ansi.red(ansi.bold("Warning: not running with root privs, which are usually required for raw packet capture."))); console.log(ansi.red("Trying to open anyway...")); } }
#!/usr/bin/env node 'use strict'; var commander = require('commander'); var TChannelTracker = require('../tchannel-tracker.js'); var ansi = require('../ansi.js'); if (require.main === module) { main(); } function main(arg) { commander.version(require('../package.json').version) .option('-i --interface [interface', 'network interface name for capture (defaults to first with an address)', '') .option('-f --filter [filter]', 'packet filter in pcap-filter(7) syntax (default: all TCP packets on port 4040)') .option('-b --buffer-size [mb]', 'size in MiB to buffer between libpcap and app (default: 10)') .option('--no-color', 'disables colors (default: not attached to a tty)') .parse(process.argv); var color = commander.color && !!process.stdout.isTTY; ansi.no_color = !color; var bufferSizeMb = commander.bufferSize || 10; checkUid(); var tracker = new TChannelTracker({ interface: commander.interface, filter: commander.filter, bufferSize: bufferSizeMb }); tracker.listen(); } function checkUid() { if (process.getuid() !== 0) { console.log(ansi.red(ansi.bold("Warning: not running with root privs, which are usually required for raw packet capture."))); console.log(ansi.red("Trying to open anyway...")); } }
JavaScript
0.000009
6a7dc4f4e3e1e0ac0bd3922f022ce08b12ffd535
Add Chapter 09, exercise 2
eloquent_js_exercises/chapter09/chapter09_ex02.js
eloquent_js_exercises/chapter09/chapter09_ex02.js
let text = "'I'm the cook,' he said, 'it's my job.'"; // Change this call. console.log(text.replace(/(\W|^)'|'(\W|$)/g, '$1"$2')); // → "I'm the cook," he said, "it's my job."
var text = "'I'm the cook,' he said, 'it's my job.'"; console.log( text.replace(/([a-z])'([a-z])/gi, "$1~~$2") .replace(/'/g, "\"") .replace(/~~/g, "'"));
JavaScript
0
4fc97327ea6f5d2750e55ee99e030690ba3f0023
Move Equalizer project to top of file
data/projects.js
data/projects.js
// When you add a new project, please add it to the top of the array! export default [ { name: 'Equalizer', description: 'Web audio player with equalizer', repository: 'https://github.com/Bloomca/equalizer', homepage: 'http://bloomca.github.io/equalizer/', screenshot: 'data/images/equalizer.png' }, { name: 'Bornycentre', description: 'An app to get your Bornycentre built with Cycle.js', repository: 'https://github.com/teawaterwire/bornycentre', homepage: 'http://bornycent.re/', screenshot: 'data/images/bornycentre.png' }, { name: 'TAMS Tools', description: 'A set of tools for teaching and learning computer science built with Cycle.js', repository: 'https://github.com/laszlokorte/tams-tools', homepage: 'https://thesis.laszlokorte.de/', screenshot: 'data/images/tams-tools.png' }, { name: 'Cycle Conway', description: 'Conway\'s Game of Life built with Cycle.js', repository: 'https://github.com/raquelxmoss/cycle-conway', homepage: 'http://raquelxmoss.github.io/cycle-conway', screenshot: 'data/images/cycle-conway.png' }, { name: 'Hangman', description: 'Hangman game built with Cycle.js', repository: 'https://github.com/class-ideas/cyclejs-hangman', homepage: 'http://class-ideas.github.io/cyclejs-hangman/', screenshot: 'data/images/hangman.png' }, { name: 'Concentration', description: 'A card game about memory and concentration', repository: 'https://github.com/class-ideas/cyclejs-concentration', homepage: 'http://class-ideas.github.io/cyclejs-concentration/', screenshot: 'data/images/concentration.png' }, { name: 'TodoMVC', description: 'TodoMVC example implemented in Cycle.js', repository: 'https://github.com/cyclejs/todomvc-cycle', homepage: 'http://cycle.js.org/todomvc-cycle/', screenshot: 'data/images/todomvc.png' }, { name: 'Cycle Music Sequencer', description: 'An easy way to make melodies in your browser, powered by Cycle.js and Tone.js', repository: 'https://github.com/widdershin/cycle-music-sequencer/', homepage: 'http://widdersh.in/cycle-music-sequencer/', screenshot: 'data/images/cycle-music-sequencer.png' }, { name: 'Tricycle', description: 'Try Cycle.js in your browser, no setup required', repository: 'https://github.com/widdershin/tricycle/', homepage: 'http://widdersh.in/tricycle', screenshot: 'data/images/tricycle.png' }, { name: 'Ghostwriter', description: 'Autocompleting rap/rhyme editor', repository: 'https://github.com/widdershin/ghostwriter', homepage: 'http://widdersh.in/ghostwriter', screenshot: 'data/images/ghostwriter.png' }, { name: 'Powerpeople', description: 'An app used internally at Powershop to help staff learn the names of their coworkers. Shown here with Pokemon as an example.', repository: 'https://github.com/Widdershin/powerpeople', homepage: 'https://github.com/Widdershin/powerpeople', screenshot: 'data/images/powerpeople.png' }, { name: 'RxMarbles', description: 'Interactive diagrams of Rx Observables', repository: 'https://github.com/staltz/rxmarbles', homepage: 'http://rxmarbles.com/', screenshot: 'data/images/rxmarbles.png' } ]; // When you add a new project, please add it to the top of the array!
// When you add a new project, please add it to the top of the array! export default [ { name: 'Bornycentre', description: 'An app to get your Bornycentre built with Cycle.js', repository: 'https://github.com/teawaterwire/bornycentre', homepage: 'http://bornycent.re/', screenshot: 'data/images/bornycentre.png' }, { name: 'TAMS Tools', description: 'A set of tools for teaching and learning computer science built with Cycle.js', repository: 'https://github.com/laszlokorte/tams-tools', homepage: 'https://thesis.laszlokorte.de/', screenshot: 'data/images/tams-tools.png' }, { name: 'Cycle Conway', description: 'Conway\'s Game of Life built with Cycle.js', repository: 'https://github.com/raquelxmoss/cycle-conway', homepage: 'http://raquelxmoss.github.io/cycle-conway', screenshot: 'data/images/cycle-conway.png' }, { name: 'Hangman', description: 'Hangman game built with Cycle.js', repository: 'https://github.com/class-ideas/cyclejs-hangman', homepage: 'http://class-ideas.github.io/cyclejs-hangman/', screenshot: 'data/images/hangman.png' }, { name: 'Concentration', description: 'A card game about memory and concentration', repository: 'https://github.com/class-ideas/cyclejs-concentration', homepage: 'http://class-ideas.github.io/cyclejs-concentration/', screenshot: 'data/images/concentration.png' }, { name: 'TodoMVC', description: 'TodoMVC example implemented in Cycle.js', repository: 'https://github.com/cyclejs/todomvc-cycle', homepage: 'http://cycle.js.org/todomvc-cycle/', screenshot: 'data/images/todomvc.png' }, { name: 'Cycle Music Sequencer', description: 'An easy way to make melodies in your browser, powered by Cycle.js and Tone.js', repository: 'https://github.com/widdershin/cycle-music-sequencer/', homepage: 'http://widdersh.in/cycle-music-sequencer/', screenshot: 'data/images/cycle-music-sequencer.png' }, { name: 'Tricycle', description: 'Try Cycle.js in your browser, no setup required', repository: 'https://github.com/widdershin/tricycle/', homepage: 'http://widdersh.in/tricycle', screenshot: 'data/images/tricycle.png' }, { name: 'Ghostwriter', description: 'Autocompleting rap/rhyme editor', repository: 'https://github.com/widdershin/ghostwriter', homepage: 'http://widdersh.in/ghostwriter', screenshot: 'data/images/ghostwriter.png' }, { name: 'Powerpeople', description: 'An app used internally at Powershop to help staff learn the names of their coworkers. Shown here with Pokemon as an example.', repository: 'https://github.com/Widdershin/powerpeople', homepage: 'https://github.com/Widdershin/powerpeople', screenshot: 'data/images/powerpeople.png' }, { name: 'RxMarbles', description: 'Interactive diagrams of Rx Observables', repository: 'https://github.com/staltz/rxmarbles', homepage: 'http://rxmarbles.com/', screenshot: 'data/images/rxmarbles.png' }, { name: 'Equalizer', description: 'Web audio player with equalizer', repository: 'https://github.com/Bloomca/equalizer', homepage: 'http://bloomca.github.io/equalizer/', screenshot: 'data/images/equalizer.png' } ];
JavaScript
0
96258a4d3e3b592d11de3a2edfceb874129be270
Add correlationId to message options
Response.js
Response.js
'use strict' class Response { constructor(messenger, msg) { this.messenger = messenger this.queue = msg.properties.replyTo this.corr = msg.properties.corr } send (msg) { if(this.queue){ this.messenger.publish( this.queue, msg, ) } } ok (payload) { this.send({status: 'ok', correlationId: this.corr, content: payload}) } error (payload) { this.send({status: 'ok', correlationId: this.corr, content: payload}) } } module.exports = Response
'use strict' class Response { constructor(messenger, msg) { this.messenger = messenger this.queue = msg.properties.replyTo this.corr = msg.properties.corr } send (msg) { if(this.queue){ this.messenger.publish( this.queue, msg, {correlationId: this.corr} ) } } ok (payload) { this.send({status: 'ok', content: payload}) } error (payload) { this.send({status: 'ok', content: payload}) } } module.exports = Response
JavaScript
0.000001
ba30c5cea4baa2ff57061c3146a7ee2f96e01528
Fix error page.
errors/browser/admin/views/errors-page.js
errors/browser/admin/views/errors-page.js
var ErrorsCollection = require('../collections/errors'); var ErrorView = require('./error'); module.exports = require('ridge/views/page').extend({ events: { 'click button[data-command="removeAll"]': 'removeAll', 'click button[data-command="removeFiltered"]': 'removeFiltered', 'click button[data-command="removePage"]': 'removePage' }, removeAll: function() { var _view = this; $.ajax({ method: 'DELETE', url: '/api/errors', success: function() { _view.fetch(null, _view.state.get('query')); } }); }, removeFiltered: function() { var _view = this; $.ajax({ method: 'DELETE', url: '/api/errors?' + _view.state.get('query'), success: function() { _view.fetch(null, _view.state.get('query')); } }); }, removePage: function() { var _view = this; _.invokeMap(this.modelViews, 'delete'); this.modelViews = []; this.fetch(null, this.state.get('query')); }, elements: { container: '.collection.container' }, subviews: { paginations: [ '.pagination', require('ridge/views/pagination'), { template: 'admin/pagination', multi: true } ], search: [ '.search', require('ridge/views/search') ] }, initialize: function(options) { this.collection = new ErrorsCollection(); this.listenTo(this.collection, 'reset', this.reset); this.listenTo(this.state, 'change:query', this.fetch); }, fetch: function(state, query) { this.collection.fetch({ reset: true, data: query }); }, attach: function() { this.collection.reset({ totalCount: this.state.get('totalCount'), errors: this.state.get('errors') }, { parse: true }); }, reset: function (models, options) { _.invokeMap(this.modelViews, 'remove'); this.modelViews = []; models.each(this.renderModel.bind(this)); }, renderModel: function(model) { this.modelViews.push(new ErrorView({ model: model, data: this.data, }).enter(this.elements.container)); }, });
var ErrorsCollection = require('../collections/errors'); var ErrorView = require('./error'); module.exports = require('ridge/views/page').extend({ events: { 'click button[data-command="removeAll"]': 'removeAll', 'click button[data-command="removeFiltered"]': 'removeFiltered', 'click button[data-command="removePage"]': 'removePage' }, removeAll: function() { var _view = this; $.ajax({ method: 'DELETE', url: '/api/errors', success: function() { _view.fetch(null, this.state.get('query')); } }); }, removeFiltered: function() { var _view = this; $.ajax({ method: 'DELETE', url: '/api/errors?' + this.state.get('query'), success: function() { _view.fetch(null, this.state.get('query')); } }); }, removePage: function() { var _view = this; _.invokeMap(this.modelViews, 'delete'); this.modelViews = []; this.fetch(null, this.state.get('query')); }, elements: { container: '.collection.container' }, subviews: { paginations: [ '.pagination', require('ridge/views/pagination'), { template: 'admin/pagination', multi: true } ], search: [ '.search', require('ridge/views/search') ] }, initialize: function(options) { this.collection = new ErrorsCollection(); this.listenTo(this.collection, 'reset', this.reset); this.listenTo(this.state, 'change:query', this.fetch); }, fetch: function(state, query) { this.collection.fetch({ reset: true, data: query }); }, attach: function() { this.collection.reset({ totalCount: this.state.get('totalCount'), errors: this.state.get('errors') }, { parse: true }); }, reset: function (models, options) { _.invokeMap(this.modelViews, 'remove'); this.modelViews = []; models.each(this.renderModel.bind(this)); }, renderModel: function(model) { this.modelViews.push(new ErrorView({ model: model, data: this.data, }).enter(this.elements.container)); }, });
JavaScript
0
b5d7847f3a817140f24f07c1165269f38e0e24c6
Update version string to 2.6.0-pre.4.dev
version.js
version.js
if (enyo && enyo.version) { enyo.version["enyo-cordova"] = "2.6.0-pre.4.dev"; }
if (enyo && enyo.version) { enyo.version["enyo-cordova"] = "2.6.0-pre.4"; }
JavaScript
0
a04cf25a556f0e10a1399a3c37570bc25e2f1d4f
Fix name of the SJ ssid
modules/SJ.js
modules/SJ.js
'use strict'; // Example response /* data({ "version":"1.6", "ip":"10.101.5.100", "mac":"00:05:69:4B:74:59", "online":"0", "timeleft":"0", "authenticated":"1", "userclass":"2", "expires":"Never", "timeused":"175", "data_download_used":"131427344", "data_upload_used":"745893", "data_total_used":"132173237", "data_download_limit":"0", "data_upload_limit":"0", "data_total_limit":"209715200", "bandwidth_download_limit":"0", "bandwidth_upload_limit":"0" }); */ var request = require( 'request' ); module.exports = { ssid: 'SJ', percentageLimit: 95, shouldRefresh: function( callback ){ var percentage, _this = this; request( 'http://www.ombord.info/api/jsonp/user/?callback=data&_' + Date.now(), function( error, response, data ){ if( error ){ // We should probably do something here // exports.log doesn't seem to work for some reason, it's not really needed anyway // module.parent.exports.log( 'Unable to load quota' ); return false; } // Make sure there is no newlines or spaces or anything data.trim(); // Strip the JSONP stuff, we really don't need it data = data.substr( 5 ); // Strip "data(" data = data.substr( 0, data.length - 2 ); // Strip the final ");" // Should be raw JSON now data = JSON.parse( data ); // Get the percentage used percentage = Math.round( data.data_total_used / data.data_total_limit * 100 ); if( percentage >= _this.percentageLimit ){ callback( true, percentage ); } else { callback( false, percentage ); } }); } };
'use strict'; // Example response /* data({ "version":"1.6", "ip":"10.101.5.100", "mac":"00:05:69:4B:74:59", "online":"0", "timeleft":"0", "authenticated":"1", "userclass":"2", "expires":"Never", "timeused":"175", "data_download_used":"131427344", "data_upload_used":"745893", "data_total_used":"132173237", "data_download_limit":"0", "data_upload_limit":"0", "data_total_limit":"209715200", "bandwidth_download_limit":"0", "bandwidth_upload_limit":"0" }); */ var request = require( 'request' ); module.exports = { name: 'SJ', percentageLimit: 95, shouldRefresh: function( callback ){ var percentage, _this = this; request( 'http://www.ombord.info/api/jsonp/user/?callback=data&_' + Date.now(), function( error, response, data ){ if( error ){ // We should probably do something here // exports.log doesn't seem to work for some reason, it's not really needed anyway // module.parent.exports.log( 'Unable to load quota' ); return false; } // Make sure there is no newlines or spaces or anything data.trim(); // Strip the JSONP stuff, we really don't need it data = data.substr( 5 ); // Strip "data(" data = data.substr( 0, data.length - 2 ); // Strip the final ");" // Should be raw JSON now data = JSON.parse( data ); // Get the percentage used percentage = Math.round( data.data_total_used / data.data_total_limit * 100 ); if( percentage >= _this.percentageLimit ){ callback( true, percentage ); } else { callback( false, percentage ); } }); } };
JavaScript
0.999988
554cf9a8bad27f0b5701ed236290f581587e1531
add isFeature function
meteor/imports/helpers.js
meteor/imports/helpers.js
/* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. Copyright (c) 2014 Mozilla Corporation */ import { _ } from 'meteor/underscore'; // helper functions getSetting=function (settingKey){ // prefer Meteor.settings.public.mozdef // then the subscribed collection if ( _.has(Meteor.settings.public.mozdef,settingKey) ){ return Meteor.settings.public.mozdef[settingKey]; }else{ if ( mozdefsettings.findOne({ key : settingKey }) ){ return mozdefsettings.findOne({ key : settingKey }).value; }else{ return ''; } } }; isFeature = function(featureName){ if ( features.findOne({'name':featureName}) ){ return features.findOne({'name':featureName}).enabled; }else{ return true; } };
/* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. Copyright (c) 2014 Mozilla Corporation */ import { _ } from 'meteor/underscore'; // helper functions getSetting=function (settingKey){ // prefer Meteor.settings.public.mozdef // then the subscribed collection if ( _.has(Meteor.settings.public.mozdef,settingKey) ){ return Meteor.settings.public.mozdef[settingKey]; }else{ if ( mozdefsettings.findOne({ key : settingKey }) ){ return mozdefsettings.findOne({ key : settingKey }).value; }else{ return ''; } } };
JavaScript
0.000124
04c10207973f28827d1914f233511f3f1cc3de2f
Fix bs modal closing when datepicker hide event is triggered
app/admin/formwidgets/datepicker/assets/js/datepicker.js
app/admin/formwidgets/datepicker/assets/js/datepicker.js
/* * Color Picker plugin * * Data attributes: * - data-control="datePicker" - enables the plugin on an element */ +function ($) { "use strict"; // FIELD DATEPICKER CLASS DEFINITION // ============================ var DatePicker = function (element, options) { this.options = options this.$el = $(element) this.picker = null this.$dataLocker = null this.bindPicker() } DatePicker.DEFAULTS = { autoclose: true, mode: 'date', format: 'dd-mm-yyyy', todayHighlight: true, templates: { leftArrow: '<i class="fa fa-long-arrow-left"></i>', rightArrow: '<i class="fa fa-long-arrow-right"></i>' }, language: 'en', } DatePicker.prototype.bindPicker = function () { this.$dataLocker = this.$el.parent('div').find('[data-datepicker-value]') if (this.options.mode === 'datetime') { this.$el.datetimepicker({ format: this.options.format, icons: { time: "fa fa-clock-o", date: "fa fa-calendar", up: "fa fa-arrow-up", down: "fa fa-arrow-down" } }); this.$el.on('change.datetimepicker', $.proxy(this.onSelectDateTimePicker, this)) } else { this.options.language = this.options.language.replace('_', '-').split('-').shift(); this.picker = this.$el.datepicker(this.options); this.parsePickerValue() this.$el.on('changeDate', $.proxy(this.onSelectDatePicker, this)) // Stops bootstrap modal from closing when datepicker hide event is triggered // https://github.com/uxsolutions/bootstrap-datepicker/issues/50#issuecomment-90855951 .on('hide', function(event) { event.preventDefault(); event.stopPropagation(); }) } } DatePicker.prototype.parsePickerValue = function () { var value = this.$el.val() if (value === '30-11--0001') this.$el.val('') } DatePicker.prototype.onSelectDatePicker = function(event) { var pickerDate = moment(event.date.toDateString()) var lockerValue = pickerDate.format('YYYY-MM-DD') this.$dataLocker.val(lockerValue) } DatePicker.prototype.onSelectDateTimePicker = function(event) { var lockerValue = event.date.format('YYYY-MM-DD HH:mm:ss') this.$dataLocker.val(lockerValue) this.$el.datetimepicker('hide') } // // FIELD DatePicker PLUGIN DEFINITION // ============================ var old = $.fn.datePicker $.fn.datePicker = function (option) { var args = Array.prototype.slice.call(arguments, 1), result this.each(function () { var $this = $(this) var data = $this.data('ti.datePicker') var options = $.extend({}, DatePicker.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data) $this.data('ti.datePicker', (data = new DatePicker(this, options))) if (typeof option == 'string') result = data[option].apply(data, args) if (typeof result != 'undefined') return false }) return result ? result : this } $.fn.datePicker.Constructor = DatePicker // FIELD DatePicker NO CONFLICT // ================= $.fn.datePicker.noConflict = function () { $.fn.datePicker = old return this } // FIELD DatePicker DATA-API // =============== $(document).render(function () { $('[data-control="datepicker"]').datePicker() }); }(window.jQuery);
/* * Color Picker plugin * * Data attributes: * - data-control="datePicker" - enables the plugin on an element */ +function ($) { "use strict"; // FIELD DATEPICKER CLASS DEFINITION // ============================ var DatePicker = function (element, options) { this.options = options this.$el = $(element) this.picker = null this.$dataLocker = null this.bindPicker() } DatePicker.DEFAULTS = { autoclose: true, mode: 'date', format: 'dd-mm-yyyy', todayHighlight: true, templates: { leftArrow: '<i class="fa fa-long-arrow-left"></i>', rightArrow: '<i class="fa fa-long-arrow-right"></i>' }, language: 'en', } DatePicker.prototype.bindPicker = function () { this.$dataLocker = this.$el.parent('div').find('[data-datepicker-value]') if (this.options.mode === 'datetime') { this.$el.datetimepicker({ format: this.options.format, icons: { time: "fa fa-clock-o", date: "fa fa-calendar", up: "fa fa-arrow-up", down: "fa fa-arrow-down" } }); this.$el.on('change.datetimepicker', $.proxy(this.onSelectDateTimePicker, this)) } else { this.options.language = this.options.language.replace('_', '-').split('-').shift(); this.picker = this.$el.datepicker(this.options); this.parsePickerValue() this.$el.on('changeDate', $.proxy(this.onSelectDatePicker, this)) } } DatePicker.prototype.parsePickerValue = function () { var value = this.$el.val() if (value === '30-11--0001') this.$el.val('') } DatePicker.prototype.onSelectDatePicker = function(event) { var pickerDate = moment(event.date.toDateString()) var lockerValue = pickerDate.format('YYYY-MM-DD') this.$dataLocker.val(lockerValue) } DatePicker.prototype.onSelectDateTimePicker = function(event) { var lockerValue = event.date.format('YYYY-MM-DD HH:mm:ss') this.$dataLocker.val(lockerValue) this.$el.datetimepicker('hide') } // // FIELD DatePicker PLUGIN DEFINITION // ============================ var old = $.fn.datePicker $.fn.datePicker = function (option) { var args = Array.prototype.slice.call(arguments, 1), result this.each(function () { var $this = $(this) var data = $this.data('ti.datePicker') var options = $.extend({}, DatePicker.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data) $this.data('ti.datePicker', (data = new DatePicker(this, options))) if (typeof option == 'string') result = data[option].apply(data, args) if (typeof result != 'undefined') return false }) return result ? result : this } $.fn.datePicker.Constructor = DatePicker // FIELD DatePicker NO CONFLICT // ================= $.fn.datePicker.noConflict = function () { $.fn.datePicker = old return this } // FIELD DatePicker DATA-API // =============== $(document).render(function () { $('[data-control="datepicker"]').datePicker() }); }(window.jQuery);
JavaScript
0
7bc80c5a84e277cef288fe2a5d35b1d1347fc10b
Improve comment of byte alignment computation.
examples/jsm/renderers/webgpu/WebGPUAttributes.js
examples/jsm/renderers/webgpu/WebGPUAttributes.js
class WebGPUAttributes { constructor( device ) { this.buffers = new WeakMap(); this.device = device; } get( attribute ) { return this.buffers.get( attribute ); } remove( attribute ) { const data = this.buffers.get( attribute ); if ( data ) { data.buffer.destroy(); this.buffers.delete( attribute ); } } update( attribute, isIndex = false, usage = null ) { let data = this.buffers.get( attribute ); if ( data === undefined ) { if ( usage === null ) { usage = ( isIndex === true ) ? GPUBufferUsage.INDEX : GPUBufferUsage.VERTEX; } data = this._createBuffer( attribute, usage ); this.buffers.set( attribute, data ); } else if ( usage && usage !== data.usage ) { data.buffer.destroy(); data = this._createBuffer( attribute, usage ); this.buffers.set( attribute, data ); } else if ( data.version < attribute.version ) { this._writeBuffer( data.buffer, attribute ); data.version = attribute.version; } } _createBuffer( attribute, usage ) { const array = attribute.array; const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441 const buffer = this.device.createBuffer( { size: size, usage: usage | GPUBufferUsage.COPY_DST, mappedAtCreation: true, } ); new array.constructor( buffer.getMappedRange() ).set( array ); buffer.unmap(); attribute.onUploadCallback(); return { version: attribute.version, buffer: buffer, usage: usage }; } _writeBuffer( buffer, attribute ) { const array = attribute.array; const updateRange = attribute.updateRange; if ( updateRange.count === - 1 ) { // Not using update ranges this.device.defaultQueue.writeBuffer( buffer, 0, array, 0 ); } else { this.device.defaultQueue.writeBuffer( buffer, 0, array, updateRange.offset * array.BYTES_PER_ELEMENT, updateRange.count * array.BYTES_PER_ELEMENT ); updateRange.count = - 1; // reset range } } } export default WebGPUAttributes;
class WebGPUAttributes { constructor( device ) { this.buffers = new WeakMap(); this.device = device; } get( attribute ) { return this.buffers.get( attribute ); } remove( attribute ) { const data = this.buffers.get( attribute ); if ( data ) { data.buffer.destroy(); this.buffers.delete( attribute ); } } update( attribute, isIndex = false, usage = null ) { let data = this.buffers.get( attribute ); if ( data === undefined ) { if ( usage === null ) { usage = ( isIndex === true ) ? GPUBufferUsage.INDEX : GPUBufferUsage.VERTEX; } data = this._createBuffer( attribute, usage ); this.buffers.set( attribute, data ); } else if ( usage && usage !== data.usage ) { data.buffer.destroy(); data = this._createBuffer( attribute, usage ); this.buffers.set( attribute, data ); } else if ( data.version < attribute.version ) { this._writeBuffer( data.buffer, attribute ); data.version = attribute.version; } } _createBuffer( attribute, usage ) { const array = attribute.array; const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment const buffer = this.device.createBuffer( { size: size, usage: usage | GPUBufferUsage.COPY_DST, mappedAtCreation: true, } ); new array.constructor( buffer.getMappedRange() ).set( array ); buffer.unmap(); attribute.onUploadCallback(); return { version: attribute.version, buffer: buffer, usage: usage }; } _writeBuffer( buffer, attribute ) { const array = attribute.array; const updateRange = attribute.updateRange; if ( updateRange.count === - 1 ) { // Not using update ranges this.device.defaultQueue.writeBuffer( buffer, 0, array, 0 ); } else { this.device.defaultQueue.writeBuffer( buffer, 0, array, updateRange.offset * array.BYTES_PER_ELEMENT, updateRange.count * array.BYTES_PER_ELEMENT ); updateRange.count = - 1; // reset range } } } export default WebGPUAttributes;
JavaScript
0
ecbbde5d78bccc0fb56b0cacbe0a0c4413a0f0c8
add functions to set slide-* CSS rules
app/assets/javascripts/app/controllers/FormController.js
app/assets/javascripts/app/controllers/FormController.js
function FormController($window, $filter, FormDataService, WordService, GenreService, BandNameService, ShareBandNameService) { var ctrl = this; ctrl.formData = FormDataService.formData; ctrl.genres = []; ctrl.bandWords = []; ctrl.bandName = ShareBandNameService; ctrl.slideDir; ctrl.getGenreNames = function() { GenreService.getGenres() .then(function(response) { ctrl.genres.push(response.data.genres); }); } ctrl.getBeginningWords = function() { WordService.getWords() .then(function(response) { var beginningWords = $filter('removeBeginningWordsFilter')(response.data.words, true); ctrl.beginningWords = $filter('editBeginningWordsFilter')(beginningWords, ['The', 'By', 'Of', 'That', 'This', 'In']); }); } ctrl.setBeginningWords = function() { if (ctrl.formData.beginsWith != undefined && ctrl.formData.beginsWith != '') { ctrl.bandWords.push(ctrl.formData.beginsWith); } } ctrl.getRandomInt = function(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } ctrl.setBandWords = function(numOfWords) { WordService.getWords() .then(function(response) { var words = $filter('removeBeginningWordsFilter')(response.data.words, false); var i = 0 while (i++ < numOfWords) { var randomWordIndex = ctrl.getRandomInt(0, words.length-1); ctrl.bandWords.push(words[randomWordIndex].string); } ctrl.bandName.name = ctrl.bandWords.join(' '); ctrl.saveBandName(); ctrl.bandWords = []; }); } ctrl.setBandGenre = function() { ctrl.bandName.genre_id = ctrl.formData.genre_id; } ctrl.saveBandName = function() { var data = { band_name: { name: ctrl.bandName.name, genre_id: parseInt(ctrl.bandName.genre_id) }, }; BandNameService.postBandName(data); } ctrl.getBandName = function(numOfWords) { ctrl.setBandGenre(); ctrl.setBeginningWords(); ctrl.setBandWords(numOfWords); $window.location.href = '/#/band-name'; } ctrl.slideViewLeft = () => { ctrl.slideDir = 'slide-left'; } ctrl.slideViewRight = () => { ctrl.slideDir = 'slide-right'; } ctrl.getGenreNames(); ctrl.getBeginningWords(); } angular .module('app') .controller('FormController', FormController);
function FormController($window, $filter, FormDataService, WordService, GenreService, BandNameService, ShareBandNameService) { var ctrl = this; ctrl.formData = FormDataService.formData; ctrl.genres = []; ctrl.bandWords = []; ctrl.bandName = ShareBandNameService; ctrl.getGenreNames = function() { GenreService.getGenres() .then(function(response) { ctrl.genres.push(response.data.genres); }); } ctrl.getBeginningWords = function() { WordService.getWords() .then(function(response) { var beginningWords = $filter('removeBeginningWordsFilter')(response.data.words, true); ctrl.beginningWords = $filter('editBeginningWordsFilter')(beginningWords, ['The', 'By', 'Of', 'That', 'This', 'In']); }); } ctrl.setBeginningWords = function() { if (ctrl.formData.beginsWith != undefined && ctrl.formData.beginsWith != '') { ctrl.bandWords.push(ctrl.formData.beginsWith); } } ctrl.getRandomInt = function(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } ctrl.setBandWords = function(numOfWords) { WordService.getWords() .then(function(response) { var words = $filter('removeBeginningWordsFilter')(response.data.words, false); var i = 0 while (i++ < numOfWords) { var randomWordIndex = ctrl.getRandomInt(0, words.length-1); ctrl.bandWords.push(words[randomWordIndex].string); } ctrl.bandName.name = ctrl.bandWords.join(' '); ctrl.saveBandName(); ctrl.bandWords = []; }); } ctrl.setBandGenre = function() { ctrl.bandName.genre_id = ctrl.formData.genre_id; } ctrl.saveBandName = function() { var data = { band_name: { name: ctrl.bandName.name, genre_id: parseInt(ctrl.bandName.genre_id) }, }; BandNameService.postBandName(data); } ctrl.getBandName = function(numOfWords) { ctrl.setBandGenre(); ctrl.setBeginningWords(); ctrl.setBandWords(numOfWords); $window.location.href = '/#/band-name'; } ctrl.getGenreNames(); ctrl.getBeginningWords(); } angular .module('app') .controller('FormController', FormController);
JavaScript
0
fbb8cdcd2d6957cea85f21431c59aedff3bdaf12
Return 204 status code for DELETE and PUT requests
controllers/api.js
controllers/api.js
'use strict'; /** * GET /api/challenges * List of challenges. */ exports.getChallenges = function get(req, res) { res.json({ challenges: [] }); }; /** * POST /api/challenges/ * Create a new challenge. */ exports.postChallenge = function post(req, res) { res.status(201).send("Created new challenge"); } /** * PUT /api/challenges/:challengeId * Updated a new challenge. */ exports.putChallenge = function put(req, res) { res.status(204).send("Update challenge"); } /** * DELETE /api/challenges/:challengeId * Delete a challenge. */ exports.deleteChallenge = function deleteChallenge(req, res) { res.status(204).send("Delete challenge"); } /** * GET /api/teams * List of teams. */ exports.getTeams = function get(req, res) { res.json({ teams: [] }); }; /** * POST /api/teams * Create a new team. */ exports.postTeam = function post(req, res) { res.status(201).send("Created new team"); } /** * POST /api/teams/:teamId * Update a team by id. */ exports.putTeam = function put(req, res) { res.status(204).send("Updated a team"); } /** * POST /api/teams/:teamId * Delete a team by id. */ exports.deleteTeam = function deleteTeam(req, res) { res.status(204).send("Deleted a team"); }
'use strict'; /** * GET /api/challenges * List of challenges. */ exports.getChallenges = function get(req, res) { res.json({ challenges: [] }); }; /** * POST /api/challenges/ * Create a new challenge. */ exports.postChallenge = function post(req, res) { res.status(201).send("Created new challenge"); } /** * PUT /api/challenges/:challengeId * Updated a new challenge. */ exports.putChallenge = function put(req, res) { res.status(201).send("Update challenge"); } /** * DELETE /api/challenges/:challengeId * Delete a challenge. */ exports.deleteChallenge = function deleteChallenge(req, res) { res.status(204).send("Delete challenge"); } /** * GET /api/teams * List of teams. */ exports.getTeams = function get(req, res) { res.json({ teams: [] }); }; /** * POST /api/teams * Create a new team. */ exports.postTeam = function post(req, res) { res.status(201).send("Created new team"); } /** * POST /api/teams/:teamId * Update a team by id. */ exports.putTeam = function put(req, res) { res.status(201).send("Updated a team"); } /** * POST /api/teams/:teamId * Delete a team by id. */ exports.deleteTeam = function deleteTeam(req, res) { res.status(204).send("Deleted a team"); }
JavaScript
0.000001
c35381b80da7dfdd6cb984226a7d61b85297b122
remove console.log
src/components/component-helpers.js
src/components/component-helpers.js
// @flow export function getSource({ data, isFullscreen }) { let { source = data.src } = data; if (typeof source === 'string') return source; return isFullscreen ? source.fullscreen : source.regular; } export function getThumbnail({ data }) { const { source } = data; if (typeof source === 'string') return source; return source.thumbnail; }
// @flow export function getSource({ data, isFullscreen }) { let { source = data.src } = data; console.log(source) if (typeof source === 'string') return source; return isFullscreen ? source.fullscreen : source.regular; } export function getThumbnail({ data }) { const { source } = data; if (typeof source === 'string') return source; return source.thumbnail; }
JavaScript
0.000006
f64a66dcc482776b3970ca6645f7e64abc410ffb
change end point name
src/client/services/server-api/index.js
src/client/services/server-api/index.js
const io = require('socket.io-client'); const qs = require('querystring'); const _ = require('lodash'); const socket = io.connect('/'); const defaultFetchOpts = { method: 'GET', headers: { 'Content-type': 'application/json', 'Accept': 'application/json' } }; const ServerAPI = { getGraphAndLayout(uri, version) { return fetch(`/api/get-graph-and-layout?${qs.stringify({uri, version})}`, defaultFetchOpts).then(res => res.json()); }, pcQuery(method, params){ return fetch(`/pc-client/${method}?${qs.stringify(params)}`, defaultFetchOpts); }, datasources(){ return fetch('/pc-client/datasources', defaultFetchOpts).then(res => res.json()); }, querySearch(query){ return fetch(`/pc-client/querySearch?${qs.stringify(query)}`, defaultFetchOpts).then(res => res.json()); }, geneQuery(query){ query.genes=_.concat(['padding'],query.genes.split(' ')); return fetch('/enrichment/validation', { method:'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' }, body:qs.stringify(query) }).then(res => res.json()); }, getGeneInformation(ids,type){ return fetch(`https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?retmode=json&db=${type}&id=${ids.join(',')}`, {method: 'GET'}).then(res => res.json()); }, getNeighborhood(ids,kind){ const source=ids.map(id=>`source=${id}`).join('&'); const patterns = '&pattern=controls-phosphorylation-of&pattern=in-complex-with&pattern=controls-expression-of&pattern=interacts-with'; return fetch(`http://www.pathwaycommons.org/pc2/graph?${source}&kind=${kind}&format=TXT${patterns}`,defaultFetchOpts).then(res => res.text()); }, // Send a diff in a node to the backend. The backend will deal with merging these diffs into // a layout submitNodeChange(uri, version, nodeId, bbox) { socket.emit('submitDiff', { uri: uri, version: version.toString(), diff: { nodeID: nodeId, bbox: bbox } }); }, submitLayoutChange(uri, version, layout) { socket.emit('submitLayout', { uri: uri, version: version, layout: layout }); }, initReceiveLayoutChange(callback) { socket.on('layoutChange', layoutJSON => { callback(layoutJSON); }); }, initReceiveNodeChange(callback) { socket.on('nodeChange', nodeDiff => { callback(nodeDiff); }); }, }; module.exports = ServerAPI;
const io = require('socket.io-client'); const qs = require('querystring'); const _ = require('lodash'); const socket = io.connect('/'); const defaultFetchOpts = { method: 'GET', headers: { 'Content-type': 'application/json', 'Accept': 'application/json' } }; const ServerAPI = { getGraphAndLayout(uri, version) { return fetch(`/api/get-graph-and-layout?${qs.stringify({uri, version})}`, defaultFetchOpts).then(res => res.json()); }, pcQuery(method, params){ return fetch(`/pc-client/${method}?${qs.stringify(params)}`, defaultFetchOpts); }, datasources(){ return fetch('/pc-client/datasources', defaultFetchOpts).then(res => res.json()); }, querySearch(query){ return fetch(`/pc-client/querySearch?${qs.stringify(query)}`, defaultFetchOpts).then(res => res.json()); }, geneQuery(query){ query.genes=_.concat(['padding'],query.genes.split(' ')); return fetch('/enrichment/gene-query', { method:'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' }, body:qs.stringify(query) }).then(res => res.json()); }, getGeneInformation(ids,type){ return fetch(`https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?retmode=json&db=${type}&id=${ids.join(',')}`, {method: 'GET'}).then(res => res.json()); }, getNeighborhood(ids,kind){ const source=ids.map(id=>`source=${id}`).join('&'); const patterns = '&pattern=controls-phosphorylation-of&pattern=in-complex-with&pattern=controls-expression-of&pattern=interacts-with'; return fetch(`http://www.pathwaycommons.org/pc2/graph?${source}&kind=${kind}&format=TXT${patterns}`,defaultFetchOpts).then(res => res.text()); }, // Send a diff in a node to the backend. The backend will deal with merging these diffs into // a layout submitNodeChange(uri, version, nodeId, bbox) { socket.emit('submitDiff', { uri: uri, version: version.toString(), diff: { nodeID: nodeId, bbox: bbox } }); }, submitLayoutChange(uri, version, layout) { socket.emit('submitLayout', { uri: uri, version: version, layout: layout }); }, initReceiveLayoutChange(callback) { socket.on('layoutChange', layoutJSON => { callback(layoutJSON); }); }, initReceiveNodeChange(callback) { socket.on('nodeChange', nodeDiff => { callback(nodeDiff); }); }, }; module.exports = ServerAPI;
JavaScript
0.000195
f07aacbefc4270196f49e8e7308e13d7fe8d6634
update array/uneek -- format and lint
src/array/uneek.js
src/array/uneek.js
// uniq <https://github.com/mikolalysenko/uniq> // Copyright (c) 2013 Mikola Lysenko (MIT) 'use strict' function unique (list, compare, sorted) { if (list.length === 0) return list if (compare) { if (!sorted) list.sort(compare) return unique_pred(list, compare) } if (!sorted) list.sort() return unique_eq(list) } function unique_pred (list, compare) { var ptr = 1 var len = list.length var a = list[0] var b = list[0] for (var i = 1; i < len; ++i) { b = a a = list[i] if (compare(a, b)) { if (i === ptr) { ptr++ continue } list[ptr++] = a } } list.length = ptr return list } function unique_eq (list) { var ptr = 1 var len = list.length var a = list[0] var b = list[0] for (var i = 1; i < len; ++i) { b = a a = list[i] if (a !== b) { if (i === ptr) { ptr++ continue } list[ptr++] = a } } list.length = ptr return list } module.exports = unique;
// uniq <https://github.com/mikolalysenko/uniq> // Copyright (c) 2013 Mikola Lysenko (MIT) "use strict" function unique (list, compare, sorted) { if(list.length === 0) return list if(compare) { if(!sorted) list.sort(compare) return unique_pred(list, compare) } if(!sorted) list.sort() return unique_eq(list) } function unique_pred (list, compare) { var ptr = 1 var len = list.length var a = list[0] var b = list[0] for(var i = 1; i < len; ++i) { b = a a = list[i] if(compare(a, b)) { if(i === ptr) { ptr++ continue } list[ptr++] = a } } list.length = ptr return list } function unique_eq (list) { var ptr = 1 var len = list.length var a = list[0] var b = list[0] for(var i = 1; i < len; ++i) { b = a a = list[i] if(a !== b) { if(i === ptr) { ptr++ continue } list[ptr++] = a } } list.length = ptr return list } module.exports = unique
JavaScript
0
ffb165d7974ed6d168148f4e86b38824bf2e6dcb
Put word in subject
words-short.js
words-short.js
(function() { "use strict"; var R = require('ramda'); var w = require('./get-word'); var mail = require('./sendmail'); // custom R functions var r = {}; // make function that tests if a word contains a character r.strContains = R.curry(function(ch, word) { return R.strIndexOf(ch, word) >= 0; }); // create random function r.random = function(n) { return Math.floor(Math.random() * n); }; // load the words array var words = w.getWords(); // make function to test if a word os a particular length var isLengthN = R.curry(function(n, w) { return w.length === n; }); var isLength3 = isLengthN(3); // test for j,k, q & x var hasValuableChar = R.anyPredicates([r.strContains('j'), r.strContains('k'), r.strContains('q'), r.strContains('x') ]); // want 3-letter words with a valuable character var pick = R.and(isLength3, hasValuableChar); // get short valuable words var w3valuable = R.filter(pick, words); // dump all // console.log(w3valuable); // console.log(w3valuable.length); // pick one at random var word = w3valuable[r.random(w3valuable.length)]; console.log(word); mail.send('peter@codeindeed.com', 'peter@peterorum.com', 'Word of the day: ' + word); }());
(function() { "use strict"; var R = require('ramda'); var w = require('./get-word'); var mail = require('./sendmail'); // custom R functions var r = {}; // make function that tests if a word contains a character r.strContains = R.curry(function(ch, word) { return R.strIndexOf(ch, word) >= 0; }); // create random function r.random = function(n) { return Math.floor(Math.random() * n); }; // load the words array var words = w.getWords(); // make function to test if a word os a particular length var isLengthN = R.curry(function(n, w) { return w.length === n; }); var isLength3 = isLengthN(3); // test for j,k, q & x var hasValuableChar = R.anyPredicates([r.strContains('j'), r.strContains('k'), r.strContains('q'), r.strContains('x') ]); // want 3-letter words with a valuable character var pick = R.and(isLength3, hasValuableChar); // get short valuable words var w3valuable = R.filter(pick, words); // dump all // console.log(w3valuable); // console.log(w3valuable.length); // pick one at random var word = w3valuable[r.random(w3valuable.length)]; console.log(word); mail.send('peter@codeindeed.com', 'peter@peterorum.com', 'Word of the day', word); }());
JavaScript
0.750936
af7d3b465af7c4c46177e2e3e038488b87b13699
improve wizard prop
src/components/props/wizard-prop.js
src/components/props/wizard-prop.js
import SchemaProp from './schema-prop.js' import findIndex from 'lodash-es/findIndex' import { getWidget } from '@/utils' import objectMixin from '../mixins/object-mixin' export default { name: 'wizard-prop', mixins: [objectMixin], methods: { getSteps (steps) { return Object.keys(steps).map(step => { return { label: steps[step].title, slot: step, } }) }, getPageProps (props) { return props.map(prop => { const removedProps = this.props.splice(findIndex(this.props, {name: prop}), 1) if (removedProps && removedProps.length > 0) { return removedProps[0] } }) }, extractPagesProps (steps) { return Object.keys(steps).map(step => { if (step.includes('ui:others')) { return this.props } else if (step.includes('ui')) { return this.getPageProps(steps[step].props) } else { return this.props.splice(findIndex(this.props, {name: step}), 1) } }) }, chooseStepsStrategy () { if (this.uiOptions && this.uiOptions['ui:steps']) { const steps = this.getSteps(this.uiOptions['ui:steps']) const pages = this.extractPagesProps(this.uiOptions['ui:steps']) return {steps, pages} } else { const steps = this.props.map(prop => { return { label: this.schema.properties[prop.name].title || prop.name, slot: prop.name, } }) const pages = this.props return {steps, pages} } }, }, render (h) { const {steps, pages} = this.chooseStepsStrategy() return h(getWidget(this.schema, this.uiOptions.widget || 'wizard', this.registry.widgets), { props: { id: this.idSchema.$id, steps, ...this.uiOptions, } }, pages.map((page, index) => { return h('div', { slot: steps[index].slot, }, page.map(prop => { return h(SchemaProp, { props: { name: prop.name, schema: prop.schema, uiSchema: prop.uiSchema, errorSchema: prop.errorSchema, idSchema: prop.idSchema, required: this.isRequired(prop.name), value: prop.value, registry: this.registry, onUpload: prop.onUpload, onPreview: prop.onPreview, }, on: { input: propVal => { this.$emit('input', Object.assign({}, this.value, {[prop.name]: propVal})) }, blur: propVal => { this.$emit('blur', Object.assign({}, this.value, {[prop.name]: propVal})) } } }) }) ) }) ) }, }
import SchemaProp from './schema-prop.js' import findIndex from 'lodash-es/findIndex' import { getWidget } from '@/utils' import objectMixin from '../mixins/object-mixin' export default { name: 'wizard-prop', mixins: [objectMixin], methods: { getSteps (steps) { return Object.keys(steps).map(step => { return { label: steps[step].title, slot: step, } }) }, extractPagesProps (steps) { return Object.keys(steps).map(step => { if (step.includes('ui:others')) { return this.props } else { const index = findIndex(this.props, {name: step}) return this.props.splice(index, 1) } }) } }, render (h) { let steps, pages if (this.uiOptions && this.uiOptions['ui:steps']) { steps = this.getSteps(this.uiOptions['ui:steps']) pages = this.extractPagesProps(this.uiOptions['ui:steps']) } else { steps = this.props.map(prop => { return { label: this.schema.properties[prop.name].title || prop.name, slot: prop.name, } }) pages = this.props } return h(getWidget(this.schema, this.uiOptions.widget || 'wizard', this.registry.widgets), { props: { id: this.idSchema.$id, steps, ...this.uiOptions, } }, pages.map((page, index) => { return h('div', { slot: steps[index].slot, }, page.map(prop => { return h(SchemaProp, { props: { name: prop.name, schema: prop.schema, uiSchema: prop.uiSchema, errorSchema: prop.errorSchema, idSchema: prop.idSchema, required: this.isRequired(prop.name), value: prop.value, registry: this.registry, onUpload: prop.onUpload, onPreview: prop.onPreview, }, on: { input: propVal => { this.$emit('input', Object.assign({}, this.value, {[prop.name]: propVal})) }, blur: propVal => { this.$emit('blur', Object.assign({}, this.value, {[prop.name]: propVal})) } } }) }) ) }) ) }, }
JavaScript
0.000001
fb4baf66624373964ff885f0d696d25d20a1df44
Update schedule.js
utils/scripts/schedule.js
utils/scripts/schedule.js
/** * schedule.js: Fetch your UoG schedule from WebAdvisor. * * Author: Nick Presta * Copyright: Copyright 2012 * License: MIT * Version: 0.0.1 * Maintainer: Nick Presta * Email: nick@nickpresta.ca */ var casper = require('casper').create(); var fs = require('fs'), input = fs.open('/dev/stdin', 'r'); if (!casper.cli.options.hasOwnProperty('semester')) { var date = new Date(); var month = date.getMonth(); var year = date.getYear().toString().substr(1); if (month <= 3) { // Winter semester - January to April casper.cli.options.semester = 'W' + year; } else if (month <= 7) { // Summer semseter - May to August casper.cli.options.semseter = 'S' + year; } else { // Fall semester - September to December casper.cli.options.semseter = 'F' + year; } } if (!casper.cli.options.hasOwnProperty('username') || !casper.cli.options.hasOwnProperty('password')) { casper.cli.options.username = input.readLine(); casper.cli.options.password = input.readLine(); if (!casper.cli.options.username || !casper.cli.options.password) { casper.echo("You must provide a username and password argument (--username, --password)."); casper.echo("You may also input the arguments on command line (username first line, password next."); casper.exit(); } } // Login casper.start('https://webadvisor.uoguelph.ca/WebAdvisor/WebAdvisor?TOKENIDX=1631421451&SS=LGRQ', function() { this.evaluate(function(username, password) { document.querySelector('input#USER_NAME').value = username; document.querySelector('input#CURR_PWD').value = password; document.querySelector('input[name="SUBMIT2"]').click(); }, { username: casper.cli.options.username, password: casper.cli.options.password }); }); // Click on "Students" casper.then(function() { this.click('h3 + ul li a.WBST_Bars'); }); // Click on "Class Schedule" casper.then(function() { this.click('a[href$="ST-WESTS13A"]'); }); // Set dropdown to "W12" and submit form casper.then(function() { this.fill('form[name="datatelform"]', { 'VAR4': casper.cli.options.semester }, true); }); // Grab schedule data casper.then(function() { var data = this.evaluate(function() { return window.delimitedMeetingInfo; }); this.echo(data); }); casper.run(function() { casper.exit(); });
/** * schedule.js: Fetch your UoG schedule from WebAdvisor. * * Author: Nick Presta * Copyright: Copyright 2012 * License: GPL * Version: 0.0.1 * Maintainer: Nick Presta * Email: nick@nickpresta.ca */ var casper = require('casper').create(); var fs = require('fs'), input = fs.open('/dev/stdin', 'r'); if (!casper.cli.options.hasOwnProperty('semester')) { var date = new Date(); var month = date.getMonth(); var year = date.getYear().toString().substr(1); if (month <= 3) { // Winter semester - January to April casper.cli.options.semester = 'W' + year; } else if (month <= 7) { // Summer semseter - May to August casper.cli.options.semseter = 'S' + year; } else { // Fall semester - September to December casper.cli.options.semseter = 'F' + year; } } if (!casper.cli.options.hasOwnProperty('username') || !casper.cli.options.hasOwnProperty('password')) { casper.cli.options.username = input.readLine(); casper.cli.options.password = input.readLine(); if (!casper.cli.options.username || !casper.cli.options.password) { casper.echo("You must provide a username and password argument (--username, --password)."); casper.echo("You may also input the arguments on command line (username first line, password next."); casper.exit(); } } // Login casper.start('https://webadvisor.uoguelph.ca/WebAdvisor/WebAdvisor?TOKENIDX=1631421451&SS=LGRQ', function() { this.evaluate(function(username, password) { document.querySelector('input#USER_NAME').value = username; document.querySelector('input#CURR_PWD').value = password; document.querySelector('input[name="SUBMIT2"]').click(); }, { username: casper.cli.options.username, password: casper.cli.options.password }); }); // Click on "Students" casper.then(function() { this.click('h3 + ul li a.WBST_Bars'); }); // Click on "Class Schedule" casper.then(function() { this.click('a[href$="ST-WESTS13A"]'); }); // Set dropdown to "W12" and submit form casper.then(function() { this.fill('form[name="datatelform"]', { 'VAR4': casper.cli.options.semester }, true); }); // Grab schedule data casper.then(function() { var data = this.evaluate(function() { return window.delimitedMeetingInfo; }); this.echo(data); }); casper.run(function() { casper.exit(); });
JavaScript
0.000002
744af911f4f28669a2f477145d93e63db951f0ec
Deploy Flow v0.85 to www
src/model/immutable/SampleDraftInlineStyle.js
src/model/immutable/SampleDraftInlineStyle.js
/** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @format * @flow strict-local * @emails oncall+draft_js */ 'use strict'; const {OrderedSet} = require('immutable'); module.exports = { /* $FlowFixMe(>=0.85.0 site=www,mobile) This comment suppresses an error * found when Flow v0.85 was deployed. To see the error, delete this comment * and run Flow. */ BOLD: OrderedSet.of('BOLD'), /* $FlowFixMe(>=0.85.0 site=www,mobile) This comment suppresses an error * found when Flow v0.85 was deployed. To see the error, delete this comment * and run Flow. */ BOLD_ITALIC: OrderedSet.of('BOLD', 'ITALIC'), /* $FlowFixMe(>=0.85.0 site=www,mobile) This comment suppresses an error * found when Flow v0.85 was deployed. To see the error, delete this comment * and run Flow. */ BOLD_ITALIC_UNDERLINE: OrderedSet.of('BOLD', 'ITALIC', 'UNDERLINE'), /* $FlowFixMe(>=0.85.0 site=www,mobile) This comment suppresses an error * found when Flow v0.85 was deployed. To see the error, delete this comment * and run Flow. */ BOLD_UNDERLINE: OrderedSet.of('BOLD', 'UNDERLINE'), /* $FlowFixMe(>=0.85.0 site=www,mobile) This comment suppresses an error * found when Flow v0.85 was deployed. To see the error, delete this comment * and run Flow. */ CODE: OrderedSet.of('CODE'), /* $FlowFixMe(>=0.85.0 site=www,mobile) This comment suppresses an error * found when Flow v0.85 was deployed. To see the error, delete this comment * and run Flow. */ ITALIC: OrderedSet.of('ITALIC'), /* $FlowFixMe(>=0.85.0 site=www,mobile) This comment suppresses an error * found when Flow v0.85 was deployed. To see the error, delete this comment * and run Flow. */ ITALIC_UNDERLINE: OrderedSet.of('ITALIC', 'UNDERLINE'), /* $FlowFixMe(>=0.85.0 site=www,mobile) This comment suppresses an error * found when Flow v0.85 was deployed. To see the error, delete this comment * and run Flow. */ NONE: OrderedSet(), /* $FlowFixMe(>=0.85.0 site=www,mobile) This comment suppresses an error * found when Flow v0.85 was deployed. To see the error, delete this comment * and run Flow. */ STRIKETHROUGH: OrderedSet.of('STRIKETHROUGH'), /* $FlowFixMe(>=0.85.0 site=www,mobile) This comment suppresses an error * found when Flow v0.85 was deployed. To see the error, delete this comment * and run Flow. */ UNDERLINE: OrderedSet.of('UNDERLINE'), };
/** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @format * @flow strict-local * @emails oncall+draft_js */ 'use strict'; const {OrderedSet} = require('immutable'); module.exports = { BOLD: OrderedSet.of('BOLD'), BOLD_ITALIC: OrderedSet.of('BOLD', 'ITALIC'), BOLD_ITALIC_UNDERLINE: OrderedSet.of('BOLD', 'ITALIC', 'UNDERLINE'), BOLD_UNDERLINE: OrderedSet.of('BOLD', 'UNDERLINE'), CODE: OrderedSet.of('CODE'), ITALIC: OrderedSet.of('ITALIC'), ITALIC_UNDERLINE: OrderedSet.of('ITALIC', 'UNDERLINE'), NONE: OrderedSet(), STRIKETHROUGH: OrderedSet.of('STRIKETHROUGH'), UNDERLINE: OrderedSet.of('UNDERLINE'), };
JavaScript
0
22a2270702def2540f2f5055168ff8ed21c46297
add 'whoami' API
js/common.js
js/common.js
/* Generate random string */ function generateString(len) { var string = ""; var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for (var i = 0; i < len; i++) { string += possible.charAt(Math.floor(Math.random() * possible.length)); } // Done. return string; } /* Show/Hide DIV section. */ function toggleDiv(divelem, blockornone) { if (null == divelem) return ; if (blockornone) { divelem.style.display = blockornone; } else { if (divelem.style.display === "none") { divelem.style.display = "block"; } else { divelem.style.display = "none"; } } } /* Set cookie function. */ function setCookie(cname, cvalue, exdays) { var cookie = cname + "=" + cvalue; if (0 < exdays) { var d = new Date(); d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000)); var expires = "expires="+d.toUTCString(); cookie += ";" + expires; } cookie += ";path=/"; // Set the cookie. document.cookie = cookie; } /* Get cookie function. */ function getCookie(cname) { var name = cname + "="; var ca = document.cookie.split(';'); for(var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return ""; } /* HTTP GET function. */ function httpGet(url, callback) { var xmlHttp = new XMLHttpRequest(); if (null == xmlHttp ) return ; xmlHttp.onreadystatechange = function() { if ((4 == xmlHttp.readyState) && (200 == xmlHttp.status)) callback(xmlHttp.responseText); } xmlHttp.open("GET", url, true); xmlHttp.send(null); }
/* Generate random string */ function generateString(len) { var string = ""; var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for (var i = 0; i < len; i++) { string += possible.charAt(Math.floor(Math.random() * possible.length)); } // Done. return string; } /* Show/Hide DIV section. */ function toggleDiv(divelem, blockornone) { if (null == divelem) return ; if (blockornone) { divelem.style.display = blockornone; } else { if (divelem.style.display === "none") { divelem.style.display = "block"; } else { divelem.style.display = "none"; } } } /* Set cookie function. */ function setCookie(cname, cvalue, exdays) { var cookie = cname + "=" + cvalue; if (0 < exdays) { var d = new Date(); d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000)); var expires = "expires="+d.toUTCString(); cookie += ";" + expires; } cookie += ";path=/"; // Set the cookie. document.cookie = cookie; } /* Get cookie function. */ function getCookie(cname) { var name = cname + "="; var ca = document.cookie.split(';'); for(var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return ""; } /* HTTP GET function. */ function httpGet(url, callback) { var xmlHttp = new XMLHttpRequest(); if (null == xmlHttp ) return ; xmlHttp.onreadystatechange = function() { if ((4 == xmlHttp.readyState) && (200 == xmlHttp.status)) callback(xmlHttp.responseText); } xmlHttp.open("GET", url, true); xmlHttp.send(null); }
JavaScript
0.000241
0f62c0fff3e29bb56e1a450330cb024fd9cf3f36
add barpolar mock to svg mock list
test/jasmine/assets/mock_lists.js
test/jasmine/assets/mock_lists.js
// list of mocks that should include *all* plotly.js trace modules var svgMockList = [ ['1', require('@mocks/1.json')], ['4', require('@mocks/4.json')], ['5', require('@mocks/5.json')], ['10', require('@mocks/10.json')], ['11', require('@mocks/11.json')], ['17', require('@mocks/17.json')], ['21', require('@mocks/21.json')], ['22', require('@mocks/22.json')], ['airfoil', require('@mocks/airfoil.json')], ['annotations-autorange', require('@mocks/annotations-autorange.json')], ['axes_enumerated_ticks', require('@mocks/axes_enumerated_ticks.json')], ['axes_visible-false', require('@mocks/axes_visible-false.json')], ['bar_and_histogram', require('@mocks/bar_and_histogram.json')], ['basic_error_bar', require('@mocks/basic_error_bar.json')], ['binding', require('@mocks/binding.json')], ['cheater_smooth', require('@mocks/cheater_smooth.json')], ['finance_style', require('@mocks/finance_style.json')], ['geo_first', require('@mocks/geo_first.json')], ['layout_image', require('@mocks/layout_image.json')], ['layout-colorway', require('@mocks/layout-colorway.json')], ['polar_categories', require('@mocks/polar_categories.json')], ['polar_direction', require('@mocks/polar_direction.json')], ['polar_wind-rose', require('@mocks/polar_wind-rose.json')], ['range_selector_style', require('@mocks/range_selector_style.json')], ['range_slider_multiple', require('@mocks/range_slider_multiple.json')], ['sankey_energy', require('@mocks/sankey_energy.json')], ['scattercarpet', require('@mocks/scattercarpet.json')], ['shapes', require('@mocks/shapes.json')], ['splom_iris', require('@mocks/splom_iris.json')], ['table_wrapped_birds', require('@mocks/table_wrapped_birds.json')], ['ternary_fill', require('@mocks/ternary_fill.json')], ['text_chart_arrays', require('@mocks/text_chart_arrays.json')], ['transforms', require('@mocks/transforms.json')], ['updatemenus', require('@mocks/updatemenus.json')], ['violin_side-by-side', require('@mocks/violin_side-by-side.json')], ['world-cals', require('@mocks/world-cals.json')], ['typed arrays', { data: [{ x: new Float32Array([1, 2, 3]), y: new Float32Array([1, 2, 1]) }] }] ]; var glMockList = [ ['gl2d_heatmapgl', require('@mocks/gl2d_heatmapgl.json')], ['gl2d_line_dash', require('@mocks/gl2d_line_dash.json')], ['gl2d_parcoords_2', require('@mocks/gl2d_parcoords_2.json')], ['gl2d_pointcloud-basic', require('@mocks/gl2d_pointcloud-basic.json')], ['gl3d_annotations', require('@mocks/gl3d_annotations.json')], ['gl3d_set-ranges', require('@mocks/gl3d_set-ranges.json')], ['gl3d_world-cals', require('@mocks/gl3d_world-cals.json')], ['gl3d_cone-autorange', require('@mocks/gl3d_cone-autorange.json')], ['gl3d_streamtube-simple', require('@mocks/gl3d_streamtube-simple.json')], ['glpolar_style', require('@mocks/glpolar_style.json')], ]; var mapboxMockList = [ ['scattermapbox', require('@mocks/mapbox_bubbles-text.json')] ]; module.exports = { svg: svgMockList, gl: glMockList, mapbox: mapboxMockList, all: svgMockList.concat(glMockList).concat(mapboxMockList) };
// list of mocks that should include *all* plotly.js trace modules var svgMockList = [ ['1', require('@mocks/1.json')], ['4', require('@mocks/4.json')], ['5', require('@mocks/5.json')], ['10', require('@mocks/10.json')], ['11', require('@mocks/11.json')], ['17', require('@mocks/17.json')], ['21', require('@mocks/21.json')], ['22', require('@mocks/22.json')], ['airfoil', require('@mocks/airfoil.json')], ['annotations-autorange', require('@mocks/annotations-autorange.json')], ['axes_enumerated_ticks', require('@mocks/axes_enumerated_ticks.json')], ['axes_visible-false', require('@mocks/axes_visible-false.json')], ['bar_and_histogram', require('@mocks/bar_and_histogram.json')], ['basic_error_bar', require('@mocks/basic_error_bar.json')], ['binding', require('@mocks/binding.json')], ['cheater_smooth', require('@mocks/cheater_smooth.json')], ['finance_style', require('@mocks/finance_style.json')], ['geo_first', require('@mocks/geo_first.json')], ['layout_image', require('@mocks/layout_image.json')], ['layout-colorway', require('@mocks/layout-colorway.json')], ['polar_categories', require('@mocks/polar_categories.json')], ['polar_direction', require('@mocks/polar_direction.json')], ['range_selector_style', require('@mocks/range_selector_style.json')], ['range_slider_multiple', require('@mocks/range_slider_multiple.json')], ['sankey_energy', require('@mocks/sankey_energy.json')], ['scattercarpet', require('@mocks/scattercarpet.json')], ['shapes', require('@mocks/shapes.json')], ['splom_iris', require('@mocks/splom_iris.json')], ['table_wrapped_birds', require('@mocks/table_wrapped_birds.json')], ['ternary_fill', require('@mocks/ternary_fill.json')], ['text_chart_arrays', require('@mocks/text_chart_arrays.json')], ['transforms', require('@mocks/transforms.json')], ['updatemenus', require('@mocks/updatemenus.json')], ['violin_side-by-side', require('@mocks/violin_side-by-side.json')], ['world-cals', require('@mocks/world-cals.json')], ['typed arrays', { data: [{ x: new Float32Array([1, 2, 3]), y: new Float32Array([1, 2, 1]) }] }] ]; var glMockList = [ ['gl2d_heatmapgl', require('@mocks/gl2d_heatmapgl.json')], ['gl2d_line_dash', require('@mocks/gl2d_line_dash.json')], ['gl2d_parcoords_2', require('@mocks/gl2d_parcoords_2.json')], ['gl2d_pointcloud-basic', require('@mocks/gl2d_pointcloud-basic.json')], ['gl3d_annotations', require('@mocks/gl3d_annotations.json')], ['gl3d_set-ranges', require('@mocks/gl3d_set-ranges.json')], ['gl3d_world-cals', require('@mocks/gl3d_world-cals.json')], ['gl3d_cone-autorange', require('@mocks/gl3d_cone-autorange.json')], ['gl3d_streamtube-simple', require('@mocks/gl3d_streamtube-simple.json')], ['glpolar_style', require('@mocks/glpolar_style.json')], ]; var mapboxMockList = [ ['scattermapbox', require('@mocks/mapbox_bubbles-text.json')] ]; module.exports = { svg: svgMockList, gl: glMockList, mapbox: mapboxMockList, all: svgMockList.concat(glMockList).concat(mapboxMockList) };
JavaScript
0
e06a75327f6a7fe9c706d72d3d92b50ca4d0c0b3
use PhetFont(20)
js/bucket/BucketFront.js
js/bucket/BucketFront.js
// Copyright 2002-2013, University of Colorado Boulder /* * The front of a bucket (does not include the hole) */ define( function( require ) { 'use strict'; // Includes var Color = require( 'SCENERY/util/Color' ); var inherit = require( 'PHET_CORE/inherit' ); var LinearGradient = require( 'SCENERY/util/LinearGradient' ); var Matrix3 = require( 'DOT/Matrix3' ); var Node = require( 'SCENERY/nodes/Node' ); var Path = require( 'SCENERY/nodes/Path' ); var PhetFont = require( 'SCENERY_PHET/PhetFont' ); var Text = require( 'SCENERY/nodes/Text' ); /** * Constructor. * * @param {Bucket} bucket - Model of a bucket, type definition found in phetcommon/model as of this writing. * @param {ModelViewTransform2} modelViewTransform * @param {Object} [options] * @constructor */ var BucketFront = function BucketFront( bucket, modelViewTransform, options ) { // Invoke super constructor. Node.call( this, { cursor: 'pointer' } ); options = _.extend( { labelFont: new PhetFont( 20 ) }, options ); var scaleMatrix = Matrix3.scaling( modelViewTransform.getMatrix().m00(), modelViewTransform.getMatrix().m11() ); var transformedShape = bucket.containerShape.transformed( scaleMatrix ); var baseColor = new Color( bucket.baseColor ); var frontGradient = new LinearGradient( transformedShape.bounds.getMinX(), 0, transformedShape.bounds.getMaxX(), 0 ); frontGradient.addColorStop( 0, baseColor.colorUtilsBrighter( 0.5 ).toCSS() ); frontGradient.addColorStop( 1, baseColor.colorUtilsDarker( 0.5 ).toCSS() ); this.addChild( new Path( transformedShape, { fill: frontGradient } ) ); // Create and add the label, centered on the front. var label = new Text( bucket.captionText, { font: options.labelFont, fill: bucket.captionColor } ); // Scale the label to fit if too large. label.scale( Math.min( 1, Math.min( ( ( transformedShape.bounds.width * 0.75 ) / label.width ), ( transformedShape.bounds.height * 0.8 ) / label.height ) ) ); label.centerX = transformedShape.bounds.getCenterX(); label.centerY = transformedShape.bounds.getCenterY(); this.addChild( label ); // Set initial position. this.translation = modelViewTransform.modelToViewPosition( bucket.position ); }; // Inherit from base type. inherit( Node, BucketFront ); return BucketFront; } );
// Copyright 2002-2013, University of Colorado Boulder /* * The front of a bucket (does not include the hole) */ define( function( require ) { 'use strict'; // Includes var Color = require( 'SCENERY/util/Color' ); var inherit = require( 'PHET_CORE/inherit' ); var LinearGradient = require( 'SCENERY/util/LinearGradient' ); var Matrix3 = require( 'DOT/Matrix3' ); var Node = require( 'SCENERY/nodes/Node' ); var Path = require( 'SCENERY/nodes/Path' ); var PhetFont = require( 'SCENERY_PHET/PhetFont' ); var Text = require( 'SCENERY/nodes/Text' ); /** * Constructor. * * @param {Bucket} bucket - Model of a bucket, type definition found in phetcommon/model as of this writing. * @param {ModelViewTransform2} modelViewTransform * @param {Object} [options] * @constructor */ var BucketFront = function BucketFront( bucket, modelViewTransform, options ) { // Invoke super constructor. Node.call( this, { cursor: 'pointer' } ); options = _.extend( { labelFont: new PhetFont( { size: 20 } ) }, options ); var scaleMatrix = Matrix3.scaling( modelViewTransform.getMatrix().m00(), modelViewTransform.getMatrix().m11() ); var transformedShape = bucket.containerShape.transformed( scaleMatrix ); var baseColor = new Color( bucket.baseColor ); var frontGradient = new LinearGradient( transformedShape.bounds.getMinX(), 0, transformedShape.bounds.getMaxX(), 0 ); frontGradient.addColorStop( 0, baseColor.colorUtilsBrighter( 0.5 ).toCSS() ); frontGradient.addColorStop( 1, baseColor.colorUtilsDarker( 0.5 ).toCSS() ); this.addChild( new Path( transformedShape, { fill: frontGradient } ) ); // Create and add the label, centered on the front. var label = new Text( bucket.captionText, { font: options.labelFont, fill: bucket.captionColor } ); // Scale the label to fit if too large. label.scale( Math.min( 1, Math.min( ( ( transformedShape.bounds.width * 0.75 ) / label.width ), ( transformedShape.bounds.height * 0.8 ) / label.height ) ) ); label.centerX = transformedShape.bounds.getCenterX(); label.centerY = transformedShape.bounds.getCenterY(); this.addChild( label ); // Set initial position. this.translation = modelViewTransform.modelToViewPosition( bucket.position ); }; // Inherit from base type. inherit( Node, BucketFront ); return BucketFront; } );
JavaScript
0
a2ed81716fb7d6d38f92154e0b79b4e91b5e0f61
Fix task test
test/js/unit/tasks/routes_test.js
test/js/unit/tasks/routes_test.js
pavlov.specify('Project Task List Route Tests', function() { describe('App.ProjectTasksIndexRoute Class', function () { it('should be an Ember.Route', function() { assert(App.ProjectTasksIndexRoute).isDefined(); assert(Ember.Route.detect(App.ProjectTasksIndexRoute)).isTrue(); }); }); describe('App.ProjectTaskListRoute Instance', function () { var route; before(function () { Ember.run( function () { route = App.ProjectTasksIndexRoute.create(); }); }); it('should have an empty model property', function() { var model = route.model(); assert(model).isEmptyArray(); }); it('should add project tasks to controller when calling setupController'); }); });
pavlov.specify('Project Task List Route Tests', function() { describe('App.ProjectTaskListRoute Class', function () { it('should be an Ember.Route', function() { assert(App.ProjectTaskListRoute).isDefined(); assert(Ember.Route.detect(App.ProjectTaskListRoute)).isTrue(); }); }); describe('App.ProjectTaskListRoute Instance', function () { var route; before(function () { Ember.run( function () { route = App.ProjectTaskListRoute.create(); }); }); it('should have an empty model property', function() { var model = route.model(); assert(model).isEmptyArray(); }); it('should add project tasks to controller when calling setupController'); }); });
JavaScript
0.999999
edc3fe89d10802fc1f08a72629cf7f1a4f95aef6
Remove done TODO
middleware/process-aoi.js
middleware/process-aoi.js
'use strict' const fork = require('child_process').fork const path = require('path') const async = require('async') const queue = require('../lib/queue') const redis = require('../lib/redis') const UPLOAD_PATH = path.join(__dirname,'../uploaded_aois') exports.runner = function (options){ return function (req, res, next) { var project_id = req.body.project_id var subject_set_id = req.body.subject_set_id var repeat = req.body.repeat var interval = req.body.interval var redirect_uri = req.query.redirect if (options.useQueue) { // Create job data var jobInfo = { aoi_file: path.join(UPLOAD_PATH, req.file.filename), project_id: project_id, subject_set_id: subject_set_id, user_id: req.user.get('id') } // Send job to redis queue queue.push(jobInfo, repeat, interval, function(err, job_ids) { console.log('jobs sent', job_ids) // Create records for each repeat of job async.map(job_ids, (job_id, done) => { var job = Object.assign({}, { id: job_id }, jobInfo) redis.set('job:'+job_id, JSON.stringify(job), done) }, (err, jobs) => { if (err) return next(err) // Add job id to user's job list redis.rpush('user:'+req.user.get('id')+':jobs', job_ids, (err, status) => { if (err) return next(err) res.redirect(redirect_uri) }) }) }) // send job to message queue } else { res.redirect(redirect_uri) var script = 'generate-subjects' //'build-status-simulator' //'generate-subjects' var aoi_file = req.file.path var job = fork(script, [ '--job-id', 'jobid.'+Math.floor(Math.random()*(9999-1000)+1000), // generate a random job id '--mosaics', // TO DO: these probably shouldn't be hard-coded // 'https://api.planet.com/v0/mosaics/nepal_unrestricted_mosaic/quads/', // 'https://api.planet.com/v0/mosaics/nepal_3mo_pre_eq_mag_6_mosaic/quads/', 'https://api.planet.com/v0/mosaics/open_california_re_20131201_20140228/quads/', 'https://api.planet.com/v0/mosaics/open_california_re_20141201_20150228/quads/', '--project', project_id, '--subject-set', subject_set_id, '--user-id', req.user.get('id'), aoi_file ]) } } }
'use strict' const fork = require('child_process').fork const path = require('path') const async = require('async') const queue = require('../lib/queue') const redis = require('../lib/redis') const UPLOAD_PATH = path.join(__dirname,'../uploaded_aois') exports.runner = function (options){ return function (req, res, next) { var project_id = req.body.project_id var subject_set_id = req.body.subject_set_id var repeat = req.body.repeat var interval = req.body.interval var redirect_uri = req.query.redirect if (options.useQueue) { // Create job data var jobInfo = { aoi_file: path.join(UPLOAD_PATH, req.file.filename), project_id: project_id, subject_set_id: subject_set_id, user_id: req.user.get('id') } // Send job to redis queue queue.push(jobInfo, repeat, interval, function(err, job_ids) { console.log('jobs sent', job_ids) // Create records for each repeat of job async.map(job_ids, (job_id, done) => { var job = Object.assign({}, { id: job_id }, jobInfo) redis.set('job:'+job_id, JSON.stringify(job), done) }, (err, jobs) => { if (err) return next(err) // Add job id to user's job list // TODO get oauth working so we know which user this is redis.rpush('user:'+req.user.get('id')+':jobs', job_ids, (err, status) => { if (err) return next(err) res.redirect(redirect_uri) }) }) }) // send job to message queue } else { res.redirect(redirect_uri) var script = 'generate-subjects' //'build-status-simulator' //'generate-subjects' var aoi_file = req.file.path var job = fork(script, [ '--job-id', 'jobid.'+Math.floor(Math.random()*(9999-1000)+1000), // generate a random job id '--mosaics', // TO DO: these probably shouldn't be hard-coded // 'https://api.planet.com/v0/mosaics/nepal_unrestricted_mosaic/quads/', // 'https://api.planet.com/v0/mosaics/nepal_3mo_pre_eq_mag_6_mosaic/quads/', 'https://api.planet.com/v0/mosaics/open_california_re_20131201_20140228/quads/', 'https://api.planet.com/v0/mosaics/open_california_re_20141201_20150228/quads/', '--project', project_id, '--subject-set', subject_set_id, '--user-id', req.user.get('id'), aoi_file ]) } } }
JavaScript
0.000009
8dce649933212445a8210ed9d53a64b972ad4b9e
Use last_value as a fallback if model value isn't set - Did this to avoid repeated value set of datetime value which causes browser to freeze. This happens only with the datetime control is used in filters (with a default value) and is not linked with a form.
frappe/public/js/frappe/form/controls/datetime.js
frappe/public/js/frappe/form/controls/datetime.js
frappe.ui.form.ControlDatetime = class ControlDatetime extends frappe.ui.form.ControlDate { set_formatted_input(value) { if (this.timepicker_only) return; if (!this.datepicker) return; if (!value) { this.datepicker.clear(); return; } else if (value === "Today") { value = this.get_now_date(); } value = this.format_for_input(value); this.$input && this.$input.val(value); this.datepicker.selectDate(frappe.datetime.user_to_obj(value)); } get_start_date() { let value = frappe.datetime.convert_to_user_tz(this.value); return frappe.datetime.str_to_obj(value); } set_date_options() { super.set_date_options(); this.today_text = __("Now"); let sysdefaults = frappe.boot.sysdefaults; this.date_format = frappe.defaultDatetimeFormat; let time_format = sysdefaults && sysdefaults.time_format ? sysdefaults.time_format : 'HH:mm:ss'; $.extend(this.datepicker_options, { timepicker: true, timeFormat: time_format.toLowerCase().replace("mm", "ii") }); } get_now_date() { return frappe.datetime.now_datetime(true); } parse(value) { if (value) { value = frappe.datetime.user_to_str(value, false); if (!frappe.datetime.is_system_time_zone()) { value = frappe.datetime.convert_to_system_tz(value, true); } return value; } } format_for_input(value) { if (!value) return ""; return frappe.datetime.str_to_user(value, false); } set_description() { const description = this.df.description; const time_zone = this.get_user_time_zone(); if (!this.df.hide_timezone) { // Always show the timezone when rendering the Datetime field since the datetime value will // always be in system_time_zone rather then local time. if (!description) { this.df.description = time_zone; } else if (!description.includes(time_zone)) { this.df.description += '<br>' + time_zone; } } super.set_description(); } get_user_time_zone() { return frappe.boot.time_zone ? frappe.boot.time_zone.user : frappe.sys_defaults.time_zone; } set_datepicker() { super.set_datepicker(); if (this.datepicker.opts.timeFormat.indexOf('s') == -1) { // No seconds in time format const $tp = this.datepicker.timepicker; $tp.$seconds.parent().css('display', 'none'); $tp.$secondsText.css('display', 'none'); $tp.$secondsText.prev().css('display', 'none'); } } get_model_value() { let value = super.get_model_value(); if (!value && !this.doc) { value = this.last_value; } return frappe.datetime.get_datetime_as_string(value); } };
frappe.ui.form.ControlDatetime = class ControlDatetime extends frappe.ui.form.ControlDate { set_formatted_input(value) { if (this.timepicker_only) return; if (!this.datepicker) return; if (!value) { this.datepicker.clear(); return; } else if (value === "Today") { value = this.get_now_date(); } value = this.format_for_input(value); this.$input && this.$input.val(value); this.datepicker.selectDate(frappe.datetime.user_to_obj(value)); } get_start_date() { let value = frappe.datetime.convert_to_user_tz(this.value); return frappe.datetime.str_to_obj(value); } set_date_options() { super.set_date_options(); this.today_text = __("Now"); let sysdefaults = frappe.boot.sysdefaults; this.date_format = frappe.defaultDatetimeFormat; let time_format = sysdefaults && sysdefaults.time_format ? sysdefaults.time_format : 'HH:mm:ss'; $.extend(this.datepicker_options, { timepicker: true, timeFormat: time_format.toLowerCase().replace("mm", "ii") }); } get_now_date() { return frappe.datetime.now_datetime(true); } parse(value) { if (value) { value = frappe.datetime.user_to_str(value, false); if (!frappe.datetime.is_system_time_zone()) { value = frappe.datetime.convert_to_system_tz(value, true); } return value; } } format_for_input(value) { if (!value) return ""; return frappe.datetime.str_to_user(value, false); } set_description() { const description = this.df.description; const time_zone = this.get_user_time_zone(); if (!this.df.hide_timezone) { // Always show the timezone when rendering the Datetime field since the datetime value will // always be in system_time_zone rather then local time. if (!description) { this.df.description = time_zone; } else if (!description.includes(time_zone)) { this.df.description += '<br>' + time_zone; } } super.set_description(); } get_user_time_zone() { return frappe.boot.time_zone ? frappe.boot.time_zone.user : frappe.sys_defaults.time_zone; } set_datepicker() { super.set_datepicker(); if (this.datepicker.opts.timeFormat.indexOf('s') == -1) { // No seconds in time format const $tp = this.datepicker.timepicker; $tp.$seconds.parent().css('display', 'none'); $tp.$secondsText.css('display', 'none'); $tp.$secondsText.prev().css('display', 'none'); } } get_model_value() { let value = super.get_model_value(); return frappe.datetime.get_datetime_as_string(value); } };
JavaScript
0
9bf9699084a6c32aa4dc7b9b9cd65362501f628b
fix site title typo
config/env/all.js
config/env/all.js
'use strict'; module.exports = { app: { title: 'BraveHerder', description: 'Brave Frontier Unit Database with MongoDB, Express, AngularJS, and Node.js', keywords: 'Brave Frontier, Units, Characters, Database, Team Building, BraverHerder' }, port: process.env.PORT || 3000, templateEngine: 'swig', sessionSecret: 'MEAN', sessionCollection: 'sessions', assets: { lib: { css: [ 'public/lib/bootstrap/dist/css/bootstrap.css', 'public/lib/bootstrap/dist/css/bootstrap-theme.css', ], js: [ 'public/lib/angular/angular.js', 'public/lib/angular-resource/angular-resource.js', 'public/lib/angular-cookies/angular-cookies.js', 'public/lib/angular-animate/angular-animate.js', 'public/lib/angular-touch/angular-touch.js', 'public/lib/angular-sanitize/angular-sanitize.js', 'public/lib/angular-ui-router/release/angular-ui-router.js', 'public/lib/angular-ui-utils/ui-utils.js', 'public/lib/angular-bootstrap/ui-bootstrap-tpls.js', 'public/js/lazy.js', ] }, css: [ 'public/modules/**/css/*.css' ], js: [ 'public/config.js', 'public/application.js', 'public/modules/*/*.js', 'public/modules/*/*[!tests]*/*.js' ], tests: [ 'public/lib/angular-mocks/angular-mocks.js', 'public/modules/*/tests/*.js' ] } };
'use strict'; module.exports = { app: { title: 'BraverHerder', description: 'Brave Frontier Unit Database with MongoDB, Express, AngularJS, and Node.js', keywords: 'Brave Frontier, Units, Characters, Database, Team Building, BraverHerder' }, port: process.env.PORT || 3000, templateEngine: 'swig', sessionSecret: 'MEAN', sessionCollection: 'sessions', assets: { lib: { css: [ 'public/lib/bootstrap/dist/css/bootstrap.css', 'public/lib/bootstrap/dist/css/bootstrap-theme.css', ], js: [ 'public/lib/angular/angular.js', 'public/lib/angular-resource/angular-resource.js', 'public/lib/angular-cookies/angular-cookies.js', 'public/lib/angular-animate/angular-animate.js', 'public/lib/angular-touch/angular-touch.js', 'public/lib/angular-sanitize/angular-sanitize.js', 'public/lib/angular-ui-router/release/angular-ui-router.js', 'public/lib/angular-ui-utils/ui-utils.js', 'public/lib/angular-bootstrap/ui-bootstrap-tpls.js', 'public/js/lazy.js', ] }, css: [ 'public/modules/**/css/*.css' ], js: [ 'public/config.js', 'public/application.js', 'public/modules/*/*.js', 'public/modules/*/*[!tests]*/*.js' ], tests: [ 'public/lib/angular-mocks/angular-mocks.js', 'public/modules/*/tests/*.js' ] } };
JavaScript
0.000098
ee6368d20cf9b9fc296c4cc9207d2b13c48d6d4c
Test cases for constructor.
test/patterns/constructor.test.js
test/patterns/constructor.test.js
/* global describe, it, expect */ var Constructor = require('../../lib/patterns/constructor'); describe('Constructor', function() { function Animal(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) { this._a0 = a0; this._a1 = a1; this._a2 = a2; this._a3 = a3; this._a4 = a4; this._a5 = a5; this._a6 = a6; this._a7 = a7; this._a8 = a8; this._a9 = a9; } var ctor = new Constructor('animal', Animal); it('should instantiate with 1 argument', function() { var inst = ctor.instantiate('0') expect(inst).to.be.an('object'); expect(inst._a0).to.equal('0'); expect(inst._a1).to.be.undefined; expect(inst._a2).to.be.undefined; expect(inst._a3).to.be.undefined; expect(inst._a4).to.be.undefined; expect(inst._a5).to.be.undefined; expect(inst._a6).to.be.undefined; expect(inst._a7).to.be.undefined; expect(inst._a8).to.be.undefined; expect(inst._a9).to.be.undefined; }); it('should throw an error', function() { expect(function() { ctor.instantiate('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10'); }).to.throw(Error, "Constructor for object 'animal' requires too many arguments"); }); });
/* global describe, it, expect */ var Constructor = require('../../lib/patterns/constructor'); describe('Constructor', function() { describe('instantiated with too many arguments', function() { function Animal(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) { } var ctor = new Constructor('animal', [], Animal); it('should throw an error', function() { expect(function() { ctor.instantiate('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10') }).to.throw(Error, "Constructor for object 'animal' requires too many arguments"); }); }); });
JavaScript
0
7432f216bb357c2aeba176d0a47eeabd974a3056
add handler for missing configuration errors
js/controllers/signin.js
js/controllers/signin.js
'use strict'; angular.module('copay.signin').controller('SigninController', function($scope, $rootScope, $location, walletFactory, controllerUtils, Passphrase) { var cmp = function(o1, o2){ var v1 = o1.show.toLowerCase(), v2 = o2.show.toLowerCase(); return v1 > v2 ? 1 : ( v1 < v2 ) ? -1 : 0; }; $rootScope.videoInfo = {}; $scope.loading = $scope.failure = false; $scope.wallets = walletFactory.getWallets().sort(cmp); $scope.selectedWalletId = $scope.wallets.length ? $scope.wallets[0].id : null; $scope.openPassword = ''; $scope.open = function(form) { if (form && form.$invalid) { $rootScope.$flashMessage = { message: 'Please, enter required fields', type: 'error'}; return; } $scope.loading = true; var password = form.openPassword.$modelValue; console.log('## Obtaining passphrase...'); Passphrase.getBase64Async(password, function(passphrase){ console.log('## Passphrase obtained'); var w, errMsg; try{ var w = walletFactory.open($scope.selectedWalletId, { passphrase: passphrase}); } catch (e){ errMsg = e.message; }; if (!w) { $scope.loading = $scope.failure = false; $rootScope.$flashMessage = { message: errMsg || 'Wrong password', type: 'error'}; $rootScope.$digest(); return; } installStartupHandlers(w); controllerUtils.startNetwork(w); }); }; $scope.join = function(form) { if (form && form.$invalid) { $rootScope.$flashMessage = { message: 'Please, enter required fields', type: 'error'}; return; } $scope.loading = true; walletFactory.network.on('badSecret', function() { }); Passphrase.getBase64Async($scope.joinPassword, function(passphrase){ walletFactory.joinCreateSession($scope.connectionId, $scope.nickname, passphrase, function(err,w) { $scope.loading = false; if (err || !w) { if (err === 'joinError') $rootScope.$flashMessage = { message: 'Can not find peer'}; else if (err === 'walletFull') $rootScope.$flashMessage = { message: 'The wallet is full', type: 'error'}; else if (err === 'badSecret') $rootScope.$flashMessage = { message: 'Bad secret secret string', type: 'error'}; else $rootScope.$flashMessage = { message: 'Unknown error', type: 'error'}; controllerUtils.onErrorDigest(); } else { controllerUtils.startNetwork(w); installStartupHandlers(w); } }); }); }; function installStartupHandlers(wallet) { wallet.on('connectionError', function(err) { $scope.failure = true; }); wallet.on('ready', function() { $scope.loading = false; }); } });
'use strict'; angular.module('copay.signin').controller('SigninController', function($scope, $rootScope, $location, walletFactory, controllerUtils, Passphrase) { var cmp = function(o1, o2){ var v1 = o1.show.toLowerCase(), v2 = o2.show.toLowerCase(); return v1 > v2 ? 1 : ( v1 < v2 ) ? -1 : 0; }; $rootScope.videoInfo = {}; $scope.loading = $scope.failure = false; $scope.wallets = walletFactory.getWallets().sort(cmp); $scope.selectedWalletId = $scope.wallets.length ? $scope.wallets[0].id : null; $scope.openPassword = ''; $scope.open = function(form) { if (form && form.$invalid) { $rootScope.$flashMessage = { message: 'Please, enter required fields', type: 'error'}; return; } $scope.loading = true; var password = form.openPassword.$modelValue; console.log('## Obtaining passphrase...'); Passphrase.getBase64Async(password, function(passphrase){ console.log('## Passphrase obtained'); var w = walletFactory.open($scope.selectedWalletId, { passphrase: passphrase}); if (!w) { $scope.loading = $scope.failure = false; $rootScope.$flashMessage = { message: 'Wrong password', type: 'error'}; $rootScope.$digest(); return; } installStartupHandlers(w); controllerUtils.startNetwork(w); }); }; $scope.join = function(form) { if (form && form.$invalid) { $rootScope.$flashMessage = { message: 'Please, enter required fields', type: 'error'}; return; } $scope.loading = true; walletFactory.network.on('badSecret', function() { }); Passphrase.getBase64Async($scope.joinPassword, function(passphrase){ walletFactory.joinCreateSession($scope.connectionId, $scope.nickname, passphrase, function(err,w) { $scope.loading = false; if (err || !w) { if (err === 'joinError') $rootScope.$flashMessage = { message: 'Can not find peer'}; else if (err === 'walletFull') $rootScope.$flashMessage = { message: 'The wallet is full', type: 'error'}; else if (err === 'badSecret') $rootScope.$flashMessage = { message: 'Bad secret secret string', type: 'error'}; else $rootScope.$flashMessage = { message: 'Unknown error', type: 'error'}; controllerUtils.onErrorDigest(); } else { controllerUtils.startNetwork(w); installStartupHandlers(w); } }); }); }; function installStartupHandlers(wallet) { wallet.on('connectionError', function(err) { $scope.failure = true; }); wallet.on('ready', function() { $scope.loading = false; }); } });
JavaScript
0.000001
372991c7efb80d2b04c3c6a09d600d512769b959
Capitalize a character in a string
lib/commands/ember-cli-jsdoc.js
lib/commands/ember-cli-jsdoc.js
'use strict'; module.exports = { name: 'ember-cli-jsdoc', run: function() { var exec = require( 'child_process' ).exec; var rsvp = require( 'rsvp' ); var path = require( 'path' ); var chalk = require( 'chalk' ); var cmdPath = ( Number( process.version.match( /^v(\d+)/ )[1] ) >= 5 ) ? path.join( 'node_modules', '.bin', 'jsdoc' ) : path.join( 'node_modules', 'ember-cli-jsdoc', 'node_modules', '.bin', 'jsdoc' ); return new rsvp.Promise( function( resolve, reject ) { exec( cmdPath + ' -c jsdoc.json', { cwd: process.cwd() }, function( error, stdout, stderr ) { console.log( stderr ); var shouldReject = false; if ( error ) { console.log( chalk.red( 'EMBER-CLI-JSDOC: ERRORS have occurred during documentation generation' ) ); shouldReject = true; } if ( /WARNING/.test( stderr ) ) { console.log( chalk.yellow( 'EMBER-CLI-JSDOC: WARNINGS have occurred during documentation generation' ) ); } if ( shouldReject ) { reject(); } else { console.log( chalk.green( 'EMBER-CLI-JSDOC: Documentation was successfully generated' ) ); resolve(); } }); }); } }
'use strict'; module.exports = { name: 'ember-cli-jsdoc', run: function() { var exec = require( 'child_process' ).exec; var rsvp = require( 'rsvp' ); var path = require( 'path' ); var chalk = require( 'chalk' ); var cmdPath = ( Number( process.version.match( /^v(\d+)/ )[1] ) >= 5 ) ? path.join( 'node_modules', '.bin', 'jsdoc' ) : path.join( 'node_modules', 'ember-cli-jsdoc', 'node_modules', '.bin', 'jsdoc' ); return new rsvp.Promise( function( resolve, reject ) { exec( cmdPath + ' -c jsdoc.json', { cwd: process.cwd() }, function( error, stdout, stderr ) { console.log( stderr ); var shouldReject = false; if ( error ) { console.log( chalk.red( 'EMBER-CLI-JSDOC: ERRORs have occurred during documentation generation' ) ); shouldReject = true; } if ( /WARNING/.test( stderr ) ) { console.log( chalk.yellow( 'EMBER-CLI-JSDOC: WARNINGS have occurred during documentation generation' ) ); } if ( shouldReject ) { reject(); } else { console.log( chalk.green( 'EMBER-CLI-JSDOC: Documentation was successfully generated' ) ); resolve(); } }); }); } }
JavaScript
1
21ef434850c956e3df1ff655c94853c56b0200d3
add allStepsCompleted prop to component
components/progressTracker/ProgressTracker.js
components/progressTracker/ProgressTracker.js
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import theme from './theme.css'; import Box from '../box'; import ProgressStep from './ProgressStep'; class ProgressTracker extends PureComponent { render() { const { color, children, activeStep, allStepsCompleted } = this.props; const classNames = cx(theme['progress-tracker']); return ( <Box className={classNames}> {React.Children.map(children, (child, index) => { const currentActiveStep = activeStep < 0 ? 0 : activeStep; return React.cloneElement(child, { active: allStepsCompleted ? false : index === currentActiveStep, completed: allStepsCompleted || index < currentActiveStep, color, }); })} </Box> ); } } ProgressTracker.propTypes = { /** Whether or not all steps are completed */ allStepsCompleted: PropTypes.bool, /** The number of the step which is currently active */ activeStep: PropTypes.number.isRequired, /** The steps to display inside the progress tracker */ children: PropTypes.node, /** Color theme of the progress tracker. */ color: PropTypes.oneOf(['neutral', 'mint', 'aqua', 'violet', 'gold', 'ruby']), }; ProgressTracker.defaultProps = { activeStep: 0, color: 'neutral', }; ProgressTracker.ProgressStep = ProgressStep; export default ProgressTracker;
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import theme from './theme.css'; import Box from '../box'; import ProgressStep from './ProgressStep'; class ProgressTracker extends PureComponent { render() { const { color, children, activeStep } = this.props; const classNames = cx(theme['progress-tracker']); return ( <Box className={classNames}> {React.Children.map(children, (child, index) => { const currentActiveStep = activeStep < 0 ? 0 : activeStep; return React.cloneElement(child, { active: index === currentActiveStep, completed: index < currentActiveStep, color, }); })} </Box> ); } } ProgressTracker.propTypes = { /** The number of the step which is currently active */ activeStep: PropTypes.number.isRequired, /** The steps to display inside the progress tracker */ children: PropTypes.node, /** Color theme of the progress tracker. */ color: PropTypes.oneOf(['neutral', 'mint', 'aqua', 'violet', 'gold', 'ruby']), }; ProgressTracker.defaultProps = { activeStep: 0, color: 'neutral', }; ProgressTracker.ProgressStep = ProgressStep; export default ProgressTracker;
JavaScript
0
ea76a4b3f63f0d6ddddca7c428ea497ed7da0f6a
Test attribute is set correctly for Nam = Val
tests/commands/sgaTests.js
tests/commands/sgaTests.js
var sga = require("__buttercup/classes/commands/command.sga.js"); module.exports = { setUp: function(cb) { this.command = new sga(); (cb)(); }, errors: { groupNotFoundForId: function(test) { var fakeSearching = { findGroupByID: function(a, b) { return false; } }; this.command.injectSearching(fakeSearching); var errorThrown = false; try { this.command.execute({ }, 0, '', ''); } catch (e) { if (e.message === 'Group not found for ID') { errorThrown = true; } } finally { test.strictEqual(errorThrown, true, 'Error thrown'); test.done(); } } }, setAttribute: { setsAttributeValueValForNameNam: function(test) { var attributeName = 'Nam', attributeValue = 'Val'; var fakeGroup = { attributes: {} }; var fakeSearching = { findGroupByID: function(a, b) { return fakeGroup; } }; this.command.injectSearching(fakeSearching); this.command.execute({ }, 0, attributeName, attributeValue); test.strictEqual(fakeGroup.attributes[attributeName], attributeValue, 'Attribute value is correctly set. ([' + attributeName + '] = ' + attributeValue + ')'); test.done(); } } };
var sga = require("__buttercup/classes/commands/command.sga.js"); module.exports = { setUp: function(cb) { this.command = new sga(); (cb)(); }, errors: { groupNotFoundForId: function(test) { var fakeSearching = { findGroupByID: function(a, b) { return false; } }; this.command.injectSearching(fakeSearching); var errorThrown = false; try { this.command.execute({ }, 0, '', ''); } catch (e) { if (e.message === 'Group not found for ID') { errorThrown = true; } } finally { test.strictEqual(errorThrown, true, 'Error thrown'); test.done(); } } }, };
JavaScript
0.000261
f20f7aa9f6708bf1a7171d76136737f3009df032
fix theatre mode
common/content/theatre-mode.js
common/content/theatre-mode.js
(function (){ var theatreBtnSelector = '[data-a-target="player-theatre-mode-button"]'; const MAX_TRIES = 400; function waitUntilVisible(selector, callback){ var tries = 0; var tm = setInterval(function (){ var el = document.querySelector(selector); if ( ++tries > MAX_TRIES ) { clearInterval(tm); callback("timeout error"); } if ( el && el.offsetHeight > 0 ) { clearInterval(tm); callback(); } }, 50) } function wait(fn, callback){ if ( fn() ) { return callback(); } else { setTimeout(function (){ wait(fn, callback) }, 250); } } function turnOn(){ var turnOnBtn = document.querySelector(theatreBtnSelector); if ( turnOnBtn ) { turnOnBtn.click(); } } document.addEventListener("DOMContentLoaded", function (){ var hash = window.location.search; // no iframes var ref = document.referrer || ""; //inside player's iframe if ( /mode=theatre/i.test(ref) || /mode=theatre/i.test(hash) ) { waitUntilVisible(theatreBtnSelector, function (err){ if ( !err ) { turnOn(); } }) } }) })();
(function (){ var theatreBtnSelector = '.qa-theatre-mode-button'; const MAX_TRIES = 400; function waitUntilVisible(selector, callback){ var tries = 0; var tm = setInterval(function (){ var el = document.querySelector(selector); if ( ++tries > MAX_TRIES ) { clearInterval(tm); callback("timeout error"); } if ( el && el.offsetHeight > 0 ) { clearInterval(tm); callback(); } }, 50) } function wait(fn, callback){ if ( fn() ) { return callback(); } else { setTimeout(function (){ wait(fn, callback) }, 250); } } function turnOn(){ var turnOnBtn = document.querySelector(theatreBtnSelector); if ( turnOnBtn ) { turnOnBtn.click(); } } document.addEventListener("DOMContentLoaded", function (){ var hash = window.location.search; // no iframes var ref = document.referrer || ""; //inside player's iframe if ( /mode=theater/i.test(ref) || /mode=theater/i.test(hash) ) { waitUntilVisible(theatreBtnSelector, function (err){ if ( !err ) { turnOn(); } }) } }) })();
JavaScript
0.000001
d9a98bb71830aab192d2e37368bb69dbbf04b07d
Add application started global var
www/lib/global.js
www/lib/global.js
var recipes = null; var recipe_images = null; var favs = []; var interval_ready_id = null; var registered = false; var last_updated = "1984-01-01"; var application_started = false; Storage.prototype.setObj = function(key, obj) { return this.setItem(key, JSON.stringify(obj)); }; Storage.prototype.getObj = function(key) { return JSON.parse(this.getItem(key)); };
var recipes = null; var recipe_images = null; var favs = []; var interval_ready_id = null; var registered = false; var last_updated = "1984-01-01"; Storage.prototype.setObj = function(key, obj) { return this.setItem(key, JSON.stringify(obj)); }; Storage.prototype.getObj = function(key) { return JSON.parse(this.getItem(key)); };
JavaScript
0
d279fd6705936c8d944a49612a9415d7b876c606
package script updates
package-scripts.js
package-scripts.js
const { series, crossEnv, concurrent, rimraf } = require('nps-utils'); const { config: { port: E2E_PORT } } = require('./test/protractor.conf'); module.exports = { scripts: { default: 'nps webpack', test: { default: 'nps test.jest', jest: { default: series( rimraf('test/coverage-jest'), crossEnv('BABEL_TARGET=node jest') ), accept: crossEnv('BABEL_TARGET=node jest -u'), watch: crossEnv('BABEL_TARGET=node jest --watch'), }, karma: { default: series( rimraf('test/coverage-karma'), 'karma start test/karma.conf.js' ), watch: 'karma start test/karma.conf.js --auto-watch --no-single-run', debug: 'karma start test/karma.conf.js --auto-watch --no-single-run --debug' }, lint: { default: 'eslint .', fix: 'eslint --fix' }, react: { default: crossEnv('BABEL_TARGET=node jest --no-cache --config jest.React.json --notify'), accept: crossEnv('BABEL_TARGET=node jest -u --no-cache --config jest.React.json --notify'), watch: crossEnv('BABEL_TARGET=node jest --watch --no-cache --config jest.React.json --notify') }, all: concurrent({ browser: series.nps('test.karma', 'e2e'), jest: 'nps test.jest', lint: 'nps test.lint' }) }, e2e: { default: `${concurrent({ webpack: `webpack-dev-server --inline --port=${E2E_PORT}`, protractor: 'nps e2e.whenReady' })} --kill-others --success first`, protractor: { install: 'webdriver-manager update', default: series( 'nps e2e.protractor.install', 'protractor test/protractor.conf.js' ), debug: series( 'nps e2e.protractor.install', 'protractor test/protractor.conf.js --elementExplorer' ) }, whenReady: series( `wait-on --timeout 120000 http-get://localhost:${E2E_PORT}/index.html`, 'nps e2e.protractor' ) }, build: 'nps webpack.build', webpack: { default: 'nps webpack.server', build: { before: rimraf('dist'), default: 'nps webpack.build.production', development: { default: series( 'nps webpack.build.before', 'webpack --progress -d' ), extractCss: series( 'nps webpack.build.before', 'webpack --progress -d --env.extractCss' ), serve: series.nps( 'webpack.build.development', 'serve' ) }, production: { inlineCss: series( 'nps webpack.build.before', crossEnv('NODE_ENV=production webpack --progress -p --env.production') ), default: series( 'nps webpack.build.before', crossEnv('NODE_ENV=production webpack --progress -p --env.production --env.extractCss') ), serve: series.nps( 'webpack.build.production', 'serve' ) } }, server: { default: 'webpack-dev-server -d --inline --env.server', extractCss: 'webpack-dev-server -d --inline --env.server --env.extractCss', hmr: 'webpack-dev-server -d --inline --hot --env.server' } }, serve: 'pushstate-server dist' } };
const { series, crossEnv, concurrent, rimraf } = require('nps-utils'); const { config: { port: E2E_PORT } } = require('./test/protractor.conf'); module.exports = { scripts: { default: 'nps webpack', test: { default: 'nps test.jest', jest: { default: crossEnv('BABEL_TARGET=node jest'), accept: crossEnv('BABEL_TARGET=node jest -u'), watch: crossEnv('BABEL_TARGET=node jest --watch') }, karma: { default: series( rimraf('test/coverage-karma'), 'karma start test/karma.conf.js' ), watch: 'karma start test/karma.conf.js --auto-watch --no-single-run', debug: 'karma start test/karma.conf.js --auto-watch --no-single-run --debug' }, lint: { default: 'eslint .', fix: 'eslint --fix' }, react: { default: crossEnv('BABEL_TARGET=node jest --no-cache --config jest.React.json --notify'), accept: crossEnv('BABEL_TARGET=node jest -u --no-cache --config jest.React.json --notify'), watch: crossEnv('BABEL_TARGET=node jest --watch --no-cache --config jest.React.json --notify') }, all: concurrent({ browser: series.nps('test.karma', 'e2e'), jest: 'nps test.jest', lint: 'nps test.lint' }) }, e2e: { default: `${concurrent({ webpack: `webpack-dev-server --inline --port=${E2E_PORT}`, protractor: 'nps e2e.whenReady' })} --kill-others --success first`, protractor: { install: 'webdriver-manager update', default: series( 'nps e2e.protractor.install', 'protractor test/protractor.conf.js' ), debug: series( 'nps e2e.protractor.install', 'protractor test/protractor.conf.js --elementExplorer' ) }, whenReady: series( `wait-on --timeout 120000 http-get://localhost:${E2E_PORT}/index.html`, 'nps e2e.protractor' ) }, build: 'nps webpack.build', webpack: { default: 'nps webpack.server', build: { before: rimraf('dist'), default: 'nps webpack.build.production', development: { default: series( 'nps webpack.build.before', 'webpack --progress -d' ), extractCss: series( 'nps webpack.build.before', 'webpack --progress -d --env.extractCss' ), serve: series.nps( 'webpack.build.development', 'serve' ) }, production: { inlineCss: series( 'nps webpack.build.before', crossEnv('NODE_ENV=production webpack --progress -p --env.production') ), default: series( 'nps webpack.build.before', crossEnv('NODE_ENV=production webpack --progress -p --env.production --env.extractCss') ), serve: series.nps( 'webpack.build.production', 'serve' ) } }, server: { default: 'webpack-dev-server -d --inline --env.server', extractCss: 'webpack-dev-server -d --inline --env.server --env.extractCss', hmr: 'webpack-dev-server -d --inline --hot --env.server' } }, serve: 'pushstate-server dist' } };
JavaScript
0.000001
d4eda0963cc512bf46005f89ce9e5e0e78ee15ad
Deal with more complex wrappings, get first three tests passing.
wapper.js
wapper.js
var Wapper = { split: function(range) { var startParent = range.startContainer var endParent = range.endContainer if (startParent == endParent) { // Achtung! Zero-length selection. if (range.startOffset == range.endOffset) return endParent.splitText(range.endOffset) var middle = startParent.splitText(range.startOffset) return [middle] } else { var commonAncestor = range.commonAncestorContainer var between = [] if (commonAncestor == startParent.parentNode) { // Common scenario where selection contains a few text and element // nodes within a block-level element - a <p> for instance. var current = startParent.splitText(range.startOffset) var after = endParent.splitText(range.endOffset) for (current; current != after; current = current.nextSibling) { between.push(current) } } else { // More complex scenario where the selection spans multiple elements. endParent.splitText(range.endOffset) var start = startParent.splitText(range.startOffset) var end = endParent // Ascend DOM until parent is a child of the common ancestor. function rootNode(node) { while (node.parentNode.parentNode != commonAncestor) { node = node.parentNode } return node } var startRoot = rootNode(start) var endRoot = rootNode(end) var current current = startRoot for (current; current; current = current.nextSibling) { between.push(current) } var tail = [] current = endRoot for (current; current; current = current.previousSibling) { tail.unshift(current) } current = startRoot.parentNode while(current.nextSibling != endRoot.parentNode) { between.push(current = current.nextSibling) } between = between.concat(tail) } return between } }, wrap: function(range) { var elems = this.split(range) var currentParent var groups = [] function createWrapper() { return document.createElement("span") } // Group contained nodes by shared parent. for (var i = 0; i < elems.length; i++) { var elem = elems[i] if (elem.parentNode == currentParent) { groups[groups.length - 1].push(elem) } else { groups.push([elem]) } currentParent = elem.parentNode } for (var g = 0; g < groups.length; g++) { var children = groups[g] var wrapper = createWrapper() children[0].parentNode.insertBefore(wrapper, children[0]) for (var c = 0; c < children.length; c++) { wrapper.appendChild(children[c]) } } } }
var Wapper = { split: function(range) { var startParent = range.startContainer var endParent = range.endContainer if (startParent == endParent) { // Achtung! Zero-length selection. if (range.startOffset == range.endOffset) return endParent.splitText(range.endOffset) var middle = startParent.splitText(range.startOffset) return [middle] } else { var commonAncestor = range.commonAncestorContainer var between = [] if (commonAncestor == startParent.parentNode) { // Common scenario where selection contains a few text and element // nodes within a block-level element - a <p> for instance. var current = startParent.splitText(range.startOffset) var after = endParent.splitText(range.endOffset) for (current; current != after; current = current.nextSibling) { between.push(current) } } else { // More complex scenario where the selection spans multiple elements. endParent.splitText(range.endOffset) var start = startParent.splitText(range.startOffset) var end = endParent // Ascend DOM until parent is a child of the common ancestor. function rootNode(node) { while (node.parentNode.parentNode != commonAncestor) { node = node.parentNode } return node } var startRoot = rootNode(start) var endRoot = rootNode(end) var current current = startRoot for (current; current; current = current.nextSibling) { between.push(current) } var tail = [] current = endRoot for (current; current; current = current.previousSibling) { tail.unshift(current) } current = startRoot.parentNode while(current.nextSibling != endRoot.parentNode) { between.push(current = current.nextSibling) } between = between.concat(tail) } return between } }, wrap: function(range) { var elems = this.split(range) function createWrapper() { return document.createElement("span") } for (var i = 0; i < elems.length; i++) { var wrapper = createWrapper() var elem = elems[i] wrapper.appendChild(elem.cloneNode(true)) elem.parentNode.replaceChild(wrapper, elem) } } }
JavaScript
0
aba326e0f9ed0ba8b1708532ec80dc95ede7f89d
add support for inlined view-kind definitions in application kinds
source/kernel/ViewController.js
source/kernel/ViewController.js
//*@public /** The _enyo.ViewController_ is an abstract class designed to allow a controller to own a _view_ and designate its state rather than the other way around. It has the ability to render its _view_ into the DOM on demand. */ enyo.kind({ //*@public name: "enyo.ViewController", //*@public kind: "enyo.Controller", //*@public /** The _view_ property can be assigned a string path or a reference to a _view_ that this controller will use when its _render_ or _renderInto_ methods are called. */ view: null, //*@public /** The _renderTarget_ can be a string representation such as _document.body_ (a special case in JavaScript) or a node's id attribute e.g. `#mydiv`. */ renderTarget: "document.body", //*@protected create: function () { var ctor = this.get("viewKind"); this.view = new ctor(); this.inherited(arguments); }, //*@public /** Call this method to render the selected _view_ into the designated _renderTarget_. */ render: function () { var target = this.get("target"); var view = this.get("view"); view.renderInto(target); }, //*@public /** Pass this method the target node to render the _view_ into immediately. */ renderInto: function (target) { this.set("renderTarget", target); this.render(); }, //*@protected target: enyo.Computed(function () { var target = this.renderTarget; if ("string" === typeof target) { if ("#" === target[0]) { target = target.slice(1); target = enyo.dom.byId(target); } else { target = enyo.getPath(target); } if (!target) { target = enyo.dom.byId(target); } } if (!target) { throw "Cannot find requested render target!"; } return target; }, "renderTarget"), //*@protected viewKind: enyo.Computed(function () { var view = this.view; if ("object" === typeof view && view.kind) { view = enyo.kind(view); } else if ("string" === typeof view) { view = enyo.getPath(view); } if (!view) { throw "Cannot find the requested view!"; } return view; }, "view") });
//*@public /** The _enyo.ViewController_ is an abstract class designed to allow a controller to own a _view_ and designate its state rather than the other way around. It has the ability to render its _view_ into the DOM on demand. */ enyo.kind({ //*@public name: "enyo.ViewController", //*@public kind: "enyo.Controller", //*@public /** The _view_ property can be assigned a string path or a reference to a _view_ that this controller will use when its _render_ or _renderInto_ methods are called. */ view: null, //*@public /** The _renderTarget_ can be a string representation such as _document.body_ (a special case in JavaScript) or a node's id attribute e.g. `#mydiv`. */ renderTarget: "document.body", //*@protected constructor: function () { this.inherited(arguments); }, //*@protected create: function () { var ctor = this.get("viewKind"); this.view = new ctor(); this.inherited(arguments); }, //*@public /** Call this method to render the selected _view_ into the designated _renderTarget_. */ render: function () { var target = this.get("target"); var view = this.get("view"); view.renderInto(target); }, //*@public /** Pass this method the target node to render the _view_ into immediately. */ renderInto: function (target) { this.set("renderTarget", target); this.render(); }, //*@protected target: enyo.Computed(function () { var target = this.renderTarget; if ("string" === typeof target) { if ("#" === target[0]) { target = target.slice(1); target = enyo.dom.byId(target); } else { target = enyo.getPath(target); } if (!target) { target = enyo.dom.byId(target); } } if (!target) { throw "Cannot find requested render target!"; } return target; }, "renderTarget"), //*@protected viewKind: enyo.Computed(function () { var view = this.view; if ("string" === typeof view) { view = enyo.getPath(view); } if (!view) { throw "Cannot find the requested view!"; } return view; }, "view") });
JavaScript
0
343f00ec43c8726babbfb8b03938a3f358367197
rewrite translator to use string concatenation instead of buffer+join
lib/compressor/ast/translate.js
lib/compressor/ast/translate.js
function each(list) { return list.map(translate).join(''); } function eachDelim(list, delimeter) { return list.map(translate).join(delimeter); } function translate(node) { switch (node.type) { case 'Atrule': var result = '@' + node.name; if (node.expression && !node.expression.sequence.isEmpty()) { result += ' ' + translate(node.expression); } if (node.block) { return result + '{' + translate(node.block) + '}'; } else { return result + ';'; } case 'Declaration': return translate(node.property) + ':' + translate(node.value); case 'Attribute': return '[' + translate(node.name) + (node.operator || '') + (node.value ? translate(node.value) : '') + ']'; case 'FunctionalPseudo': return ':' + node.name + '(' + eachDelim(node.arguments, ',') + ')'; case 'Function': return node.name + '(' + eachDelim(node.arguments, ',') + ')'; case 'Block': return eachDelim(node.declarations, ';'); case 'Ruleset': return node.selector ? translate(node.selector) + '{' + translate(node.block) + '}' : '{' + translate(node.block) + '}'; case 'Selector': return eachDelim(node.selectors, ','); case 'Negation': return ':not(' + eachDelim(node.sequence, ',') + ')'; case 'Braces': return node.open + each(node.sequence) + node.close; case 'Value': return node.important ? each(node.sequence) + '!important' : each(node.sequence); case 'Argument': case 'AtruleExpression': case 'SimpleSelector': return each(node.sequence); case 'StyleSheet': return each(node.rules); case 'Url': return 'url(' + translate(node.value) + ')'; case 'Progid': return translate(node.value); case 'Property': case 'Combinator': case 'Identifier': return node.name; case 'PseudoClass': return ':' + node.name; case 'PseudoElement': return '::' + node.name; case 'Class': return '.' + node.name; case 'Dimension': return node.value + node.unit; case 'Id': return '#' + node.name; case 'Hash': return '#' + node.value; case 'Nth': case 'Number': case 'String': case 'Operator': case 'Raw': return node.value; case 'Percentage': return node.value + '%'; case 'Space': return ' '; case 'Comment': return '/*' + node.value + '*/'; default: console.warn('Unknown node type:', node); } } module.exports = translate;
function each(list, buffer) { list.each(function(data) { translate(data, buffer); }); } function eachDelim(list, buffer, delimeter) { list.each(function(data, item) { translate(data, buffer); if (item.next) { buffer.push(delimeter); } }); } function translate(node, buffer) { switch (node.type) { case 'Atrule': buffer.push('@', node.name); if (node.expression && !node.expression.sequence.isEmpty()) { buffer.push(' '); translate(node.expression, buffer); } if (node.block) { buffer.push('{'); translate(node.block, buffer); buffer.push('}'); } else { buffer.push(';'); } break; case 'Declaration': translate(node.property, buffer); buffer.push(':'); translate(node.value, buffer); break; case 'Attribute': buffer.push('['); translate(node.name, buffer); if (node.operator) { buffer.push(node.operator); } if (node.value) { translate(node.value, buffer); } buffer.push(']'); break; case 'FunctionalPseudo': buffer.push(':', node.name, '('); eachDelim(node.arguments, buffer, ','); buffer.push(')'); break; case 'Function': buffer.push(node.name, '('); eachDelim(node.arguments, buffer, ','); buffer.push(')'); break; case 'Block': eachDelim(node.declarations, buffer, ';'); break; case 'Ruleset': if (node.selector) { translate(node.selector, buffer); } buffer.push('{'); translate(node.block, buffer); buffer.push('}'); break; case 'Selector': eachDelim(node.selectors, buffer, ','); break; case 'Negation': buffer.push(':not('); eachDelim(node.sequence, buffer, ','); buffer.push(')'); break; case 'Braces': buffer.push(node.open); each(node.sequence, buffer); buffer.push(node.close); break; case 'Value': each(node.sequence, buffer); if (node.important) { buffer.push('!important'); } break; case 'Argument': case 'AtruleExpression': case 'SimpleSelector': each(node.sequence, buffer); break; case 'StyleSheet': each(node.rules, buffer); break; case 'Url': buffer.push('url('); translate(node.value, buffer); buffer.push(')'); break; case 'Progid': translate(node.value, buffer); break; case 'Property': case 'Combinator': case 'Identifier': buffer.push(node.name); break; case 'PseudoClass': buffer.push(':', node.name); break; case 'PseudoElement': buffer.push('::', node.name); break; case 'Class': buffer.push('.', node.name); break; case 'Dimension': buffer.push(node.value, node.unit); break; case 'Id': buffer.push('#', node.name); break; case 'Hash': buffer.push('#', node.value); break; case 'Nth': case 'Number': case 'String': case 'Operator': case 'Raw': buffer.push(node.value); break; case 'Percentage': buffer.push(node.value, '%'); break; case 'Space': buffer.push(' '); break; case 'Comment': buffer.push('/*', node.value, '*/'); break; default: console.warn('Unknown node type:', node); } } module.exports = function(node) { var buffer = []; translate(node, buffer); return buffer.join(''); };
JavaScript
0.000001
92a922c89bae8cf188ef160ac0023f4592a9fc7d
Support params when deriving mark:set commands
defaultschema.js
defaultschema.js
import {SchemaSpec, Schema, Block, Textblock, Inline, Text, Attribute, MarkType} from "./schema" // ;; The default top-level document node type. export class Doc extends Block { static get kinds() { return "doc" } } // ;; The default blockquote node type. export class BlockQuote extends Block {} // ;; The default ordered list node type. Has a single attribute, // `order`, which determines the number at which the list starts // counting, and defaults to 1. export class OrderedList extends Block { get contains() { return "list_item" } get attrs() { return {order: new Attribute({default: "1"})} } } // ;; The default bullet list node type. export class BulletList extends Block { get contains() { return "list_item" } } // ;; The default list item node type. export class ListItem extends Block { static get kinds() { return "list_item" } } // ;; The default horizontal rule node type. export class HorizontalRule extends Block { get contains() { return null } } // ;; The default heading node type. Has a single attribute // `level`, which indicates the heading level, and defaults to 1. export class Heading extends Textblock { get attrs() { return {level: new Attribute({default: "1"})} } } // ;; The default code block / listing node type. Only // allows unmarked text nodes inside of it. export class CodeBlock extends Textblock { get contains() { return "text" } get containsMarks() { return false } get isCode() { return true } } // ;; The default paragraph node type. export class Paragraph extends Textblock { get defaultTextblock() { return true } } // ;; The default inline image node type. Has these // attributes: // // - **`src`** (required): The URL of the image. // - **`alt`**: The alt text. // - **`title`**: The title of the image. export class Image extends Inline { get attrs() { return { src: new Attribute, alt: new Attribute({default: ""}), title: new Attribute({default: ""}) } } } // ;; The default hard break node type. export class HardBreak extends Inline { get selectable() { return false } get isBR() { return true } } // ;; The default emphasis mark type. export class EmMark extends MarkType { static get rank() { return 51 } } // ;; The default strong mark type. export class StrongMark extends MarkType { static get rank() { return 52 } } // ;; The default link mark type. Has these attributes: // // - **`href`** (required): The link target. // - **`title`**: The link's title. export class LinkMark extends MarkType { static get rank() { return 53 } get attrs() { return { href: new Attribute, title: new Attribute({default: ""}) } } } // ;; The default code font mark type. export class CodeMark extends MarkType { static get rank() { return 101 } get isCode() { return true } } // :: SchemaSpec // The specification for the default schema. const defaultSpec = new SchemaSpec({ doc: Doc, blockquote: BlockQuote, ordered_list: OrderedList, bullet_list: BulletList, list_item: ListItem, horizontal_rule: HorizontalRule, paragraph: Paragraph, heading: Heading, code_block: CodeBlock, text: Text, image: Image, hard_break: HardBreak }, { em: EmMark, strong: StrongMark, link: LinkMark, code: CodeMark }) // :: Schema // ProseMirror's default document schema. export const defaultSchema = new Schema(defaultSpec)
import {SchemaSpec, Schema, Block, Textblock, Inline, Text, Attribute, MarkType} from "./schema" // ;; The default top-level document node type. export class Doc extends Block { static get kinds() { return "doc" } } // ;; The default blockquote node type. export class BlockQuote extends Block {} // ;; The default ordered list node type. Has a single attribute, // `order`, which determines the number at which the list starts // counting, and defaults to 1. export class OrderedList extends Block { get contains() { return "list_item" } get isList() { return true } get attrs() { return {order: new Attribute({default: "1"})} } } // ;; The default bullet list node type. export class BulletList extends Block { get contains() { return "list_item" } get isList() { return true } } // ;; The default list item node type. export class ListItem extends Block { static get kinds() { return "list_item" } } // ;; The default horizontal rule node type. export class HorizontalRule extends Block { get contains() { return null } } // ;; The default heading node type. Has a single attribute // `level`, which indicates the heading level, and defaults to 1. export class Heading extends Textblock { get attrs() { return {level: new Attribute({default: "1"})} } } // ;; The default code block / listing node type. Only // allows unmarked text nodes inside of it. export class CodeBlock extends Textblock { get contains() { return "text" } get containsMarks() { return false } get isCode() { return true } } // ;; The default paragraph node type. export class Paragraph extends Textblock { get defaultTextblock() { return true } } // ;; The default inline image node type. Has these // attributes: // // - **`src`** (required): The URL of the image. // - **`alt`**: The alt text. // - **`title`**: The title of the image. export class Image extends Inline { get attrs() { return { src: new Attribute, alt: new Attribute({default: ""}), title: new Attribute({default: ""}) } } } // ;; The default hard break node type. export class HardBreak extends Inline { get selectable() { return false } get isBR() { return true } } // ;; The default emphasis mark type. export class EmMark extends MarkType { static get rank() { return 51 } } // ;; The default strong mark type. export class StrongMark extends MarkType { static get rank() { return 52 } } // ;; The default link mark type. Has these attributes: // // - **`href`** (required): The link target. // - **`title`**: The link's title. export class LinkMark extends MarkType { static get rank() { return 53 } get attrs() { return { href: new Attribute, title: new Attribute({default: ""}) } } } // ;; The default code font mark type. export class CodeMark extends MarkType { static get rank() { return 101 } get isCode() { return true } } // :: SchemaSpec // The specification for the default schema. const defaultSpec = new SchemaSpec({ doc: Doc, blockquote: BlockQuote, ordered_list: OrderedList, bullet_list: BulletList, list_item: ListItem, horizontal_rule: HorizontalRule, paragraph: Paragraph, heading: Heading, code_block: CodeBlock, text: Text, image: Image, hard_break: HardBreak }, { em: EmMark, strong: StrongMark, link: LinkMark, code: CodeMark }) // :: Schema // ProseMirror's default document schema. export const defaultSchema = new Schema(defaultSpec)
JavaScript
0
78789e7b62e11c1e242037481b03dc03185eca93
Add vote results back to entries
voting-server/src/core.js
voting-server/src/core.js
import {List, Map} from 'immutable'; export function setEntries(state, entries) { return state.set('entries', List(entries)); } function getWinners(vote) { if (!vote) { return []; } const [movieA, movieB] = vote.get('pair'); const movieAVotes = vote.getIn(['tally', movieA], 0); const movieBVotes = vote.getIn(['tally', movieB], 0); if (movieAVotes > movieBVotes) { return [movieA]; } else if (movieAVotes < movieBVotes) { return [movieB]; } else { return [movieA, movieB]; } } export function next(state) { const entries = state.get('entries').concat(getWinners(state.get('vote'))); return state.merge({ vote: Map({pair: entries.take(2)}), entries: entries.skip(2) }); } export function vote(state, entry) { // Pretty accessor syntax for updating a value inside a nested dictionary return state.updateIn(['vote', 'tally', entry], 0, tally => tally + 1); }
import {List, Map} from 'immutable'; export function setEntries(state, entries) { return state.set('entries', List(entries)); } export function next(state) { const entries = state.get('entries'); return state.merge({ vote: Map({pair: entries.take(2)}), entries: entries.skip(2) }); } export function vote(state, entry) { // Pretty accessor syntax for updating a value inside a nested dictionary return state.updateIn(['vote', 'tally', entry], 0, tally => tally + 1); }
JavaScript
0
7863ee5594e25a757c685179d5f86032721fed69
Add google analythics and facebook pixel widget
js/custom.js
js/custom.js
(function($){ "use strict"; // ______________ SUPERFISH jQuery('#navigation').superfish({ speed : 1, animation: false, animationOut: false }); // ______________ MOBILE MENU $(function(){ $('#navigation').slicknav({ label: "", closedSymbol: "&#8594;", openedSymbol: "&#8595;" }); }); // ______________ HOME PAGE WORDS ROTATOR $("#js-rotating").Morphext({ animation: "bounceInLeft", separator: ",", speed: 6000 }); $('#js-rotating').show(); // ______________ ANIMATE EFFECTS var wow = new WOW( { boxClass: 'wow', animateClass: 'animated', offset: 0, mobile: false } ); wow.init(); // SMOOTH SCROLL________________________// $(function() { $('a[href*=\\#]:not([href=\\#])').click(function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); if (target.length) { $('html,body').animate({ scrollTop: target.offset().top }, 1000); return false; } } }); }); // ______________ BACK TO TOP BUTTON $(window).scroll(function () { if ($(this).scrollTop() > 300) { $('#back-to-top').fadeIn('slow'); } else { $('#back-to-top').fadeOut('slow'); } }); $('#back-to-top').click(function(){ $("html, body").animate({ scrollTop: 0 }, 600); return false; }); var googleforms_popup = new Foundation.Reveal($('#googleforms-modal')); $('#googleforms-action').click(function(){ googleforms_popup.open(); }); $('.close-googleforms-modal').click(function(){ googleforms_popup.close(); }); var video_popup = new Foundation.Reveal($('#video-modal')); $('#video-action').click(function(){ video_popup.open(); }); $('.close-video-modal').click(function(){ video_popup.close(); }); })(jQuery); // Google Analytics (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-86896105-1', 'auto'); ga('send', 'pageview'); // Facebook Pixel Code !function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod? n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n; n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0; t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window, document,'script','https://connect.facebook.net/en_US/fbevents.js'); fbq('init', '663531177160564'); fbq('track', 'PageView');
(function($){ "use strict"; // ______________ SUPERFISH jQuery('#navigation').superfish({ speed : 1, animation: false, animationOut: false }); // ______________ MOBILE MENU $(function(){ $('#navigation').slicknav({ label: "", closedSymbol: "&#8594;", openedSymbol: "&#8595;" }); }); // ______________ HOME PAGE WORDS ROTATOR $("#js-rotating").Morphext({ animation: "bounceInLeft", separator: ",", speed: 6000 }); $('#js-rotating').show(); // ______________ ANIMATE EFFECTS var wow = new WOW( { boxClass: 'wow', animateClass: 'animated', offset: 0, mobile: false } ); wow.init(); // SMOOTH SCROLL________________________// $(function() { $('a[href*=\\#]:not([href=\\#])').click(function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); if (target.length) { $('html,body').animate({ scrollTop: target.offset().top }, 1000); return false; } } }); }); // ______________ BACK TO TOP BUTTON $(window).scroll(function () { if ($(this).scrollTop() > 300) { $('#back-to-top').fadeIn('slow'); } else { $('#back-to-top').fadeOut('slow'); } }); $('#back-to-top').click(function(){ $("html, body").animate({ scrollTop: 0 }, 600); return false; }); var googleforms_popup = new Foundation.Reveal($('#googleforms-modal')); $('#googleforms-action').click(function(){ googleforms_popup.open(); }); $('.close-googleforms-modal').click(function(){ googleforms_popup.close(); }); var video_popup = new Foundation.Reveal($('#video-modal')); $('#video-action').click(function(){ video_popup.open(); }); $('.close-video-modal').click(function(){ video_popup.close(); }); })(jQuery);
JavaScript
0
7e89d60fb7f4c5f99f2e1793d086303949968ab3
Add `large` to the size prop values
src/components/iconButton/IconButton.js
src/components/iconButton/IconButton.js
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Box from '../box'; import Icon from '../icon'; import cx from 'classnames'; import buttonTheme from '../button/theme.css'; import theme from './theme.css'; class IconButton extends Component { handleMouseUp = (event) => { this.blur(); if (this.props.onMouseUp) { this.props.onMouseUp(event); } }; handleMouseLeave = (event) => { this.blur(); if (this.props.onMouseLeave) { this.props.onMouseLeave(event); } }; blur() { if (this.buttonNode.blur) { this.buttonNode.blur(); } } render() { const { children, className, disabled, element, icon, size, color, selected, type, ...others } = this.props; const classNames = cx( buttonTheme['button-base'], theme['icon-button'], theme[`is-${size}`], { [theme['is-disabled']]: disabled, [theme['is-selected']]: selected, }, className, ); const props = { ...others, ref: (node) => { this.buttonNode = node; }, className: classNames, disabled: element === 'button' ? disabled : null, element: element, onMouseUp: this.handleMouseUp, onMouseLeave: this.handleMouseLeave, type: element === 'button' ? type : null, 'data-teamleader-ui': 'button', }; return ( <Box {...props}> <Icon color={color === 'white' ? 'neutral' : color} tint={color === 'white' ? 'lightest' : 'darkest'}> {icon} </Icon> {children} </Box> ); } } IconButton.propTypes = { children: PropTypes.node, className: PropTypes.string, disabled: PropTypes.bool, /** A custom element to be rendered */ element: PropTypes.oneOfType([PropTypes.element, PropTypes.string]), icon: PropTypes.element, onMouseLeave: PropTypes.func, onMouseUp: PropTypes.func, /** If true, component will be shown in a selected state */ selected: PropTypes.bool, size: PropTypes.oneOf(['small', 'medium', 'large']), color: PropTypes.oneOf(['neutral', 'white', 'mint', 'violet', 'ruby', 'gold', 'aqua']), type: PropTypes.string, }; IconButton.defaultProps = { className: '', element: 'button', size: 'medium', color: 'neutral', type: 'button', }; export default IconButton;
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Box from '../box'; import Icon from '../icon'; import cx from 'classnames'; import buttonTheme from '../button/theme.css'; import theme from './theme.css'; class IconButton extends Component { handleMouseUp = (event) => { this.blur(); if (this.props.onMouseUp) { this.props.onMouseUp(event); } }; handleMouseLeave = (event) => { this.blur(); if (this.props.onMouseLeave) { this.props.onMouseLeave(event); } }; blur() { if (this.buttonNode.blur) { this.buttonNode.blur(); } } render() { const { children, className, disabled, element, icon, size, color, selected, type, ...others } = this.props; const classNames = cx( buttonTheme['button-base'], theme['icon-button'], theme[`is-${size}`], { [theme['is-disabled']]: disabled, [theme['is-selected']]: selected, }, className, ); const props = { ...others, ref: (node) => { this.buttonNode = node; }, className: classNames, disabled: element === 'button' ? disabled : null, element: element, onMouseUp: this.handleMouseUp, onMouseLeave: this.handleMouseLeave, type: element === 'button' ? type : null, 'data-teamleader-ui': 'button', }; return ( <Box {...props}> <Icon color={color === 'white' ? 'neutral' : color} tint={color === 'white' ? 'lightest' : 'darkest'}> {icon} </Icon> {children} </Box> ); } } IconButton.propTypes = { children: PropTypes.node, className: PropTypes.string, disabled: PropTypes.bool, /** A custom element to be rendered */ element: PropTypes.oneOfType([PropTypes.element, PropTypes.string]), icon: PropTypes.element, onMouseLeave: PropTypes.func, onMouseUp: PropTypes.func, /** If true, component will be shown in a selected state */ selected: PropTypes.bool, size: PropTypes.oneOf(['small', 'medium']), color: PropTypes.oneOf(['neutral', 'white', 'mint', 'violet', 'ruby', 'gold', 'aqua']), type: PropTypes.string, }; IconButton.defaultProps = { className: '', element: 'button', size: 'medium', color: 'neutral', type: 'button', }; export default IconButton;
JavaScript
0.000006
9739dd717a7a284f15814ec0fe52a77efb1f2856
Move stylesheet to react-atlas package when building for production.
scripts/buildPackages.js
scripts/buildPackages.js
var fs = require("fs"); var path = require("path"); var spawn = require("cross-spawn"); var glob = require("glob"); var path = require("path"); // get packages paths var packages = glob.sync(path.join(__dirname, "../packages/react-atlas*/"), { realpath: true }); packages.push(packages.shift()); packages.forEach(function(pack) { // ensure path has package.json if(!fs.existsSync(path.join(pack, "package.json"))) return; if(process.env.NODE_ENV === 'production') { spawn.sync(pack + '/node_modules/webpack/bin/webpack.js', ['-p'], { env: process.env, cwd: pack, stdio: "inherit" }); } else { spawn.sync(pack + '/node_modules/webpack/bin/webpack.js', { env: process.env, cwd: pack, stdio: "inherit" }); } }); /* If we are building for production move the stylesheet from react-atlas-default-theme/lib to react-atlas/lib */ if(process.env.NODE_ENV === 'production') { var oldPath = path.join(__dirname, "../packages/react-atlas-default-theme/lib/atlasThemes.min.css"); var newPath = path.join(__dirname, "../packages/react-atlas/lib/atlasThemes.min.css") fs.renameSync(oldPath, newPath); }
var fs = require("fs"); var path = require("path"); var spawn = require("cross-spawn"); var glob = require("glob"); var path = require("path"); // get packages paths var packages = glob.sync(path.join(__dirname, "../packages/react-atlas*/"), { realpath: true }); packages.push(packages.shift()); packages.forEach(function(pack) { // ensure path has package.json if(!fs.existsSync(path.join(pack, "package.json"))) return; if(process.env.NODE_ENV === 'production') { spawn.sync(pack + '/node_modules/webpack/bin/webpack.js', ['-p'], { env: process.env, cwd: pack, stdio: "inherit" }); } else { spawn.sync(pack + '/node_modules/webpack/bin/webpack.js', { env: process.env, cwd: pack, stdio: "inherit" }); } });
JavaScript
0
cdee4b6c176d0e59a7882a9801256ab7a4211071
add some classic rules, fix typo
src/components/profile/profile.style.js
src/components/profile/profile.style.js
import styled, { css } from 'styled-components'; import Portrait from '../portrait'; import baseTheme from '../../style/themes/base'; import { THEMES } from '../../style/themes'; const portraitSizes = { 'extra-small': { dimensions: 24, nameSize: '13px', emailSize: '12px', lineHeight: '12px', marginLeft: '16px' }, small: { dimensions: 32, nameSize: '14px', emailsize: '12px', lineHeight: '16px', marginLeft: '16px' }, 'medium-small': { dimensions: 40, nameSize: '14px', emailSize: '14px', lineHeight: '16px', marginLeft: '16px' }, medium: { dimensions: 56, nameSize: '14px', emailSize: '14px', lineHeight: '20px', marginLeft: '24px' }, 'medium-large': { dimensions: 72, nameSize: '20px', emailSize: '14px', lineHeight: '22px', marginLeft: '24px' }, large: { dimensions: 104, nameSize: '24px', emailSize: '20px', lineHeight: '26px', marginLeft: '32px' }, 'extra-large': { dimensions: 128, nameSize: '24px', emailSize: '20px', lineHeight: '30px', marginLeft: '40px' } }; const ProfileNameStyle = styled.span` font-weight: bold; display: inline-block; font-size: ${props => portraitSizes[props.size].nameSize}; ${({ theme }) => theme.name === THEMES.classic && css` display: inline; `}; `; const ProfileEmailStyle = styled.span` font-size: ${({ size }) => portraitSizes[size].emailSize}; ${({ theme }) => theme.name === THEMES.classic && css` font-size: 14px; `}; `; const ProfileStyle = styled.div` white-space: nowrap; color: ${({ theme }) => theme.text.color}; ${({ theme }) => theme.name === THEMES.classic && css` color: rgba(0, 0, 0, 0.85); ${({ large }) => large && css` ${ProfileNameStyle} { font-size: 20px; font-weight: 400; line-height: 21px; } `} `}; `; const ProfileDetailsStyle = styled.div` vertical-align: middle; display: inline-block; line-height: ${({ size }) => portraitSizes[size].lineHeight}; margin-left: ${({ size }) => portraitSizes[size].marginLeft}; ${({ theme }) => theme.name === THEMES.classic && css` line-height: 16px; margin-left: 14px; `}; `; const ProfileAvatarStyle = styled(Portrait)` display: inline-block; `; ProfileStyle.defaultProps = { theme: baseTheme }; ProfileNameStyle.defaultProps = { size: 'medium-small', theme: baseTheme }; ProfileEmailStyle.defaultProps = { size: 'medium-small', theme: baseTheme }; ProfileDetailsStyle.defaultProps = { size: 'medium-small', theme: baseTheme }; export { ProfileStyle, ProfileNameStyle, ProfileDetailsStyle, ProfileAvatarStyle, ProfileEmailStyle };
import styled, { css } from 'styled-components'; import Portrait from '../portrait'; import baseTheme from '../../style/themes/base'; import { THEMES } from '../../style/themes'; const portraitSizes = { 'extra-small': { dimensions: 24, nameSize: '13px', emailSize: '12px', lineHeight: '12px', marginLeft: '16px' }, small: { dimensions: 32, nameSize: '14px', emailsize: '12px', lineHeight: '16px', marginLeft: '16px' }, 'medium-small': { dimensions: 40, nameSize: '14px', emailSize: '14px', lineHeight: '16px', marginLeft: '16px' }, medium: { dimensions: 56, nameSize: '14px', emailSize: '14px', lineHeight: '20px', marginLEft: '24px' }, 'medium-large': { dimensions: 72, nameSize: '20px', emailSize: '14px', lineHeight: '22px', marginLeft: '24px' }, large: { dimensions: 104, nameSize: '24px', emailSize: '20px', lineHeight: '26px', marginLeft: '32px' }, 'extra-large': { dimensions: 128, nameSize: '24px', emailSize: '20px', lineHeight: '30px', marginLeft: '40px' } }; const ProfileNameStyle = styled.span` font-weight: bold; display: inline-block; font-size: ${props => portraitSizes[props.size].nameSize}; `; const ProfileEmailStyle = styled.span` font-size: ${({ size }) => portraitSizes[size].emailSize}; `; const ProfileStyle = styled.div` white-space: nowrap; color: ${({ theme }) => theme.text.color}; ${({ large }) => large && css` ${ProfileNameStyle} { font-size: 20px; font-weight: 400; line-height: 21px; } `} ${({ theme }) => theme.name === THEMES.classic && css` color: rgba(0, 0, 0, 0.85); `}; `; const ProfileDetailsStyle = styled.div` margin-left: 14px; vertical-align: middle; display: inline-block; line-height: 16px; line-height: ${({ size }) => portraitSizes[size].lineHeight}; margin-left: ${({ size }) => portraitSizes[size].marginLeft}; `; const ProfileAvatarStyle = styled(Portrait)` display: inline-block; `; ProfileStyle.defaultProps = { theme: baseTheme }; ProfileNameStyle.defaultProps = { size: 'medium-small' }; ProfileEmailStyle.defaultProps = { size: 'medium-small' }; ProfileDetailsStyle.defaultProps = { size: 'medium-small' }; export { ProfileStyle, ProfileNameStyle, ProfileDetailsStyle, ProfileAvatarStyle, ProfileEmailStyle };
JavaScript
0.000022
11c375e047ab0222d012bb60b4b220dd2779f212
Revert to 3.0 tests
test/unit/edit/uiGridCell.spec.js
test/unit/edit/uiGridCell.spec.js
describe('ui.grid.edit GridCellDirective', function () { var gridUtil; var scope; var element; var uiGridConstants; var recompile; beforeEach(module('ui.grid.edit')); beforeEach(inject(function ($rootScope, $compile, $controller, _gridUtil_, $templateCache, gridClassFactory, uiGridEditService, _uiGridConstants_) { gridUtil = _gridUtil_; uiGridConstants = _uiGridConstants_; $templateCache.put('ui-grid/uiGridCell', '<div class="ui-grid-cell-contents">{{COL_FIELD CUSTOM_FILTERS}}</div>'); $templateCache.put('ui-grid/edit/editableCell', '<div editable_cell_directive></div>'); $templateCache.put('ui-grid/edit/cellTextEditor', '<input ng-input="COL_FIELD" ng-model="COL_FIELD" ng-blur="stopEdit()" />'); scope = $rootScope.$new(); var grid = gridClassFactory.createGrid(); grid.options.columnDefs = [ {field: 'col1', enableCellEdit: true} ]; grid.options.data = [ {col1: 'val'} ]; grid.registerColumnBuilder(uiGridEditService.editColumnBuilder); grid.buildColumns(); grid.modifyRows(grid.options.data); scope.grid = grid; scope.col = grid.columns[0]; scope.row = grid.rows[0]; recompile = function () { $compile(element)(scope); $rootScope.$digest(); }; })); describe('ui.grid.edit uiGridCell and uiGridTextEditor full workflow', function () { var displayHtml; beforeEach(function () { element = angular.element('<div ui-grid-cell/>'); recompile(); displayHtml = element.html(); expect(element.text()).toBe('val'); //invoke edit element.dblclick(); expect(element.find('input')).toBeDefined(); }); it('should stop editing on enter', function () { //stop edit var event = jQuery.Event("keydown"); event.keyCode = uiGridConstants.keymap.ENTER; element.find('input').trigger(event); //back to beginning expect(element.html()).toBe(displayHtml); }); it('should stop editing on esc', function () { //stop edit var event = jQuery.Event("keydown"); event.keyCode = uiGridConstants.keymap.ESC; element.find('input').trigger(event); //back to beginning expect(element.html()).toBe(displayHtml); }); it('should stop when grid scrolls', function () { //stop edit scope.$broadcast(uiGridConstants.events.GRID_SCROLL); scope.$digest(); //back to beginning expect(element.html()).toBe(displayHtml); }); }); });
// describe('ui.grid.edit GridCellDirective', function () { // var gridUtil; // var scope; // var element; // var uiGridConstants; // var recompile; // beforeEach(module('ui.grid.edit')); // beforeEach(inject(function ($rootScope, $compile, $controller, _gridUtil_, $templateCache, gridClassFactory, uiGridEditService, _uiGridConstants_) { // gridUtil = _gridUtil_; // uiGridConstants = _uiGridConstants_; // $templateCache.put('ui-grid/uiGridCell', '<div class="ui-grid-cell-contents">{{COL_FIELD CUSTOM_FILTERS}}</div>'); // $templateCache.put('ui-grid/edit/editableCell', '<div editable_cell_directive></div>'); // $templateCache.put('ui-grid/edit/cellTextEditor', '<input ng-input="COL_FIELD" ng-model="COL_FIELD" ng-blur="stopEdit()" />'); // scope = $rootScope.$new(); // var grid = gridClassFactory.createGrid(); // grid.options.columnDefs = [ // {field: 'col1', enableCellEdit: true} // ]; // grid.options.data = [ // {col1: 'val'} // ]; // grid.registerColumnBuilder(uiGridEditService.editColumnBuilder); // grid.buildColumns(); // grid.modifyRows(grid.options.data); // scope.grid = grid; // scope.col = grid.columns[0]; // scope.row = grid.rows[0]; // recompile = function () { // $compile(element)(scope); // $rootScope.$digest(); // }; // })); // describe('ui.grid.edit uiGridCell and uiGridTextEditor full workflow', function () { // var displayHtml; // beforeEach(function () { // element = angular.element('<div ui-grid-cell/>'); // recompile(); // displayHtml = element.html(); // expect(element.text()).toBe('val'); // //invoke edit // element.dblclick(); // expect(element.find('input')).toBeDefined(); // }); // it('should stop editing on enter', function () { // //stop edit // var event = jQuery.Event("keydown"); // event.keyCode = uiGridConstants.keymap.ENTER; // element.find('input').trigger(event); // //back to beginning // expect(element.html()).toBe(displayHtml); // }); // it('should stop editing on esc', function () { // //stop edit // var event = jQuery.Event("keydown"); // event.keyCode = uiGridConstants.keymap.ESC; // element.find('input').trigger(event); // //back to beginning // expect(element.html()).toBe(displayHtml); // }); // it('should stop when grid scrolls', function () { // //stop edit // scope.$broadcast(uiGridConstants.events.GRID_SCROLL); // scope.$digest(); // //back to beginning // expect(element.html()).toBe(displayHtml); // }); // }); // });
JavaScript
0.000373
73372fbc0dba9520484c94550e4519977ad0070d
Update characteristic.js
RC/ble/characteristic.js
RC/ble/characteristic.js
var util = require('util'); var bleno = require('bleno'); var redis = require("redis"); var BlenoCharacteristic = bleno.Characteristic; var characterID = '9a10ba1d-cd1c-4f00-9cca-1f3178d5fe8a'; var DBCCharacteristic = function() { DBCCharacteristic.super_.call(this, { uuid: characterID, properties: ['read', 'write', 'notify'], value: null }); this._value = new Buffer(0); this._updateValueCallback = null; }; util.inherits(DBCCharacteristic, BlenoCharacteristic); DBCCharacteristic.prototype.onReadRequest = function(offset, callback) { console.log('DBCCharacteristic - onReadRequest: value = ' + this._value.toString('hex')); callback(this.RESULT_SUCCESS, this._value); }; DBCCharacteristic.prototype.onWriteRequest = function(data, offset, withoutResponse, callback) { this._value = data; //console.log('DBCCharacteristic - onWriteRequest: value = ' + this._value.toString('hex')); console.log('DBCCharacteristic - onWriteRequest: value = ' + this._value); client.send(this._value, 0, this._value.length, 41234, "localhost"); if (this._updateValueCallback) { console.log('DBCCharacteristic - onWriteRequest: notifying'); this._updateValueCallback(this._value); } callback(this.RESULT_SUCCESS); }; DBCCharacteristic.prototype.onSubscribe = function(maxValueSize, updateValueCallback) { console.log('DBCCharacteristic - onSubscribe'); this._updateValueCallback = updateValueCallback; }; DBCCharacteristic.prototype.onUnsubscribe = function() { console.log('DBCCharacteristic - onUnsubscribe'); this._updateValueCallback = null; }; module.exports = DBCCharacteristic;
var util = require('util'); var bleno = require('bleno'); var redis = require("redis"); var BlenoCharacteristic = bleno.Characteristic; var DBCCharacteristic = function() { EchoCharacteristic.super_.call(this, { uuid: 'ac5636ee-3d36-4afe-9662-ec47fbfe1dd0', properties: ['read', 'write', 'notify'], value: null }); this._value = new Buffer(0); this._updateValueCallback = null; }; util.inherits(DBCCharacteristic, BlenoCharacteristic); DBCCharacteristic.prototype.onReadRequest = function(offset, callback) { console.log('EchoCharacteristic - onReadRequest: value = ' + this._value.toString('hex')); callback(this.RESULT_SUCCESS, this._value); }; DBCCharacteristic.prototype.onWriteRequest = function(data, offset, withoutResponse, callback) { this._value = data; //console.log('EchoCharacteristic - onWriteRequest: value = ' + this._value.toString('hex')); console.log('EchoCharacteristic - onWriteRequest: value = ' + this._value); client.send(this._value, 0, this._value.length, 41234, "localhost"); if (this._updateValueCallback) { console.log('EchoCharacteristic - onWriteRequest: notifying'); this._updateValueCallback(this._value); } callback(this.RESULT_SUCCESS); }; DBCCharacteristic.prototype.onSubscribe = function(maxValueSize, updateValueCallback) { console.log('EchoCharacteristic - onSubscribe'); this._updateValueCallback = updateValueCallback; }; DBCCharacteristic.prototype.onUnsubscribe = function() { console.log('EchoCharacteristic - onUnsubscribe'); this._updateValueCallback = null; }; module.exports = DBCCharacteristic;
JavaScript
0.000001
e9e9987070099eeff6614316675596cfeabdf42b
fix month issue
lib/entities/banktransaction.js
lib/entities/banktransaction.js
var _ = require('lodash') , Entity = require('./entity') , logger = require('../logger') , ContactSchema = require('./contact').ContactSchema , Contact = require('./contact') , LineItemSchema = require('./shared').LineItemSchema var BankTransactionSchema = new Entity.SchemaObject({ Contact: { type: ContactSchema , toObject: 'always'}, Date: {type: Date, toObject: 'always'}, LineAmountTypes: {type: String, toObject: 'always'}, LineItems: {type: Array, arrayType: LineItemSchema, toObject: 'always'}, SubTotal: {type: Number}, TotalTax: {type: Number}, Total: {type: Number}, UpdatedDateUTC: {type: Date}, FullyPaidOnDate: {type: Date}, BankTransactionID: {type: String}, IsReconciled: {type: Boolean, toObject: 'always'}, CurrencyCode: {type: String, toObject: 'always'}, Url: {type: String, toObject: 'always'}, Reference: {type: String, toObject: 'always'}, BankAccount: { type: { AccountID: {type: String, toObject: 'always'} }, toObject: 'always'}, Type: {type: String, toObject: 'always'} }); var BankTransaction = Entity.extend(BankTransactionSchema, { constructor: function (application, data, options) { logger.debug('BankTransaction::constructor'); this.Entity.apply(this, arguments); }, initialize: function (data, options) { }, changes: function (options) { return this._super(options); }, _toObject: function (options) { return this._super(options); }, fromXmlObj: function (obj) { var self = this; _.extend(self, _.omit(obj, 'LineItems','Contact')); if (obj.LineItems) { var lineItems = this.application.asArray(obj.LineItems.LineItem); _.each(lineItems, function (lineItem) { self.LineItems.push(lineItem); }) } if (obj.Contact) _.extend(self.Contact, new Contact().fromXmlObj(obj.Contact)) return this; }, toXml: function () { var transaction = _.omit(this.toObject(),'Contact','LineItems'); transaction.BankAccount = this.BankAccount.toObject(); transaction.Date = this.Date.getFullYear()+'-'+(this.Date.getMonth()+1)+'-'+this.Date.getDate(); transaction.Contact = this.Contact.toObject(); transaction.LineItems = []; this.LineItems.forEach(function (lineItem){ transaction.LineItems.push({LineItem: lineItem.toObject()}); }); return this.application.js2xml(transaction, 'BankTransaction'); }, save:function(cb) { var xml = '<BankTransactions>' + this.toXml() + '</BankTransactions>'; //console.log(xml); //cb(); return this.application.putOrPostEntity('put', 'BankTransactions', xml, {}, cb); } }); module.exports = BankTransaction;
var _ = require('lodash') , Entity = require('./entity') , logger = require('../logger') , ContactSchema = require('./contact').ContactSchema , Contact = require('./contact') , LineItemSchema = require('./shared').LineItemSchema var BankTransactionSchema = new Entity.SchemaObject({ Contact: { type: ContactSchema , toObject: 'always'}, Date: {type: Date, toObject: 'always'}, LineAmountTypes: {type: String, toObject: 'always'}, LineItems: {type: Array, arrayType: LineItemSchema, toObject: 'always'}, SubTotal: {type: Number}, TotalTax: {type: Number}, Total: {type: Number}, UpdatedDateUTC: {type: Date}, FullyPaidOnDate: {type: Date}, BankTransactionID: {type: String}, IsReconciled: {type: Boolean, toObject: 'always'}, CurrencyCode: {type: String, toObject: 'always'}, Url: {type: String, toObject: 'always'}, Reference: {type: String, toObject: 'always'}, BankAccount: { type: { AccountID: {type: String, toObject: 'always'} }, toObject: 'always'}, Type: {type: String, toObject: 'always'} }); var BankTransaction = Entity.extend(BankTransactionSchema, { constructor: function (application, data, options) { logger.debug('BankTransaction::constructor'); this.Entity.apply(this, arguments); }, initialize: function (data, options) { }, changes: function (options) { return this._super(options); }, _toObject: function (options) { return this._super(options); }, fromXmlObj: function (obj) { var self = this; _.extend(self, _.omit(obj, 'LineItems','Contact')); if (obj.LineItems) { var lineItems = this.application.asArray(obj.LineItems.LineItem); _.each(lineItems, function (lineItem) { self.LineItems.push(lineItem); }) } if (obj.Contact) _.extend(self.Contact, new Contact().fromXmlObj(obj.Contact)) return this; }, toXml: function () { var transaction = _.omit(this.toObject(),'Contact','LineItems'); transaction.BankAccount = this.BankAccount.toObject(); transaction.Date = this.Date.getFullYear()+'-'+this.Date.getMonth()+'-'+this.Date.getDate(); transaction.Contact = this.Contact.toObject(); transaction.LineItems = []; this.LineItems.forEach(function (lineItem){ transaction.LineItems.push({LineItem: lineItem.toObject()}); }); return this.application.js2xml(transaction, 'BankTransaction'); }, save:function(cb) { var xml = '<BankTransactions>' + this.toXml() + '</BankTransactions>'; //console.log(xml); //cb(); return this.application.putOrPostEntity('put', 'BankTransactions', xml, {}, cb); } }); module.exports = BankTransaction;
JavaScript
0.000001
65695cf8b0356d5f290ba75d2830e0998368ead2
add missing type field
components/SentenTree/index.js
components/SentenTree/index.js
import { select } from 'd3-selection'; import VisComponent from '../../VisComponent'; import { SentenTreeBuilder, SentenTreeVis } from 'sententree/dist/SentenTree'; export default class SentenTree extends VisComponent { static get options () { return [ { name: 'data', description: 'The data table.', type: 'table', format: 'objectlist' }, { name: 'id', description: 'The field containing the identifier of each row.', type: 'string', domain: { mode: 'field', from: 'data', fieldTypes: ['string', 'integer', 'number'] } }, { name: 'text', description: 'The field containing the text sample.', type: 'string', domain: { mode: 'field', from: 'data', fieldTypes: ['string'] } }, { name: 'count', description: 'The field containing the count for each text sample.', type: 'string', domain: { mode: 'field', from: 'data', fieldTypes: ['integer'] } }, { name: 'graphs', description: 'The number of graphs to compute and render.', type: 'integer', format: 'integer', default: 3 } ]; } constructor (el, {data, id = null, text = 'text', count = 'count', graphs = 3}) { super(el); // Empty element. select(el) .selectAll('*') .remove(); // Transform input data into correct form. this.data = data.map((d, i) => ({ id: id ? d[id] : i, text: d[text], count: d[count] !== undefined ? d[count] : 1 })); const model = new SentenTreeBuilder() .buildModel(this.data); this.vis = new SentenTreeVis(el) .data(model.getRenderedGraphs(graphs)); } render () {} }
import { select } from 'd3-selection'; import VisComponent from '../../VisComponent'; import { SentenTreeBuilder, SentenTreeVis } from 'sententree/dist/SentenTree'; export default class SentenTree extends VisComponent { static get options () { return [ { name: 'data', description: 'The data table.', type: 'table', format: 'objectlist' }, { name: 'id', description: 'The field containing the identifier of each row.', type: 'string', domain: { mode: 'field', from: 'data', fieldTypes: ['string', 'integer', 'number'] } }, { name: 'text', description: 'The field containing the text sample.', domain: { mode: 'field', from: 'data', fieldTypes: ['string'] } }, { name: 'count', description: 'The field containing the count for each text sample.', type: 'string', domain: { mode: 'field', from: 'data', fieldTypes: ['integer'] } }, { name: 'graphs', description: 'The number of graphs to compute and render.', type: 'integer', format: 'integer', default: 3 } ]; } constructor (el, {data, id = null, text = 'text', count = 'count', graphs = 3}) { super(el); // Empty element. select(el) .selectAll('*') .remove(); // Transform input data into correct form. this.data = data.map((d, i) => ({ id: id ? d[id] : i, text: d[text], count: d[count] !== undefined ? d[count] : 1 })); const model = new SentenTreeBuilder() .buildModel(this.data); this.vis = new SentenTreeVis(el) .data(model.getRenderedGraphs(graphs)); } render () {} }
JavaScript
0.000001
096063db0de5ce44725c8ec10993af3521b7f3d2
Add update to dataTableStyles for more verbose styling
src/globalStyles/dataTableStyles.js
src/globalStyles/dataTableStyles.js
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2019 */ import { Dimensions } from 'react-native'; import { BACKGROUND_COLOR, BLUE_WHITE, LIGHT_GREY, WARM_GREY, DARK_GREY, SUSSOL_ORANGE, } from './colors'; import { APP_FONT_FAMILY } from './fonts'; export const dataTableColors = { checkableCellDisabled: LIGHT_GREY, checkableCellChecked: SUSSOL_ORANGE, checkableCellUnchecked: WARM_GREY, editableCellUnderline: WARM_GREY, }; export const dataTableStyles = { text: { fontFamily: APP_FONT_FAMILY, fontSize: Dimensions.get('window').width / 100, color: DARK_GREY, }, header: { backgroundColor: 'white', flexDirection: 'row', }, headerCell: { height: 40, borderRightWidth: 2, borderBottomWidth: 2, backgroundColor: 'white', borderColor: BLUE_WHITE, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', }, row: { backgroundColor: BACKGROUND_COLOR, flex: 1, flexDirection: 'row', height: 45, }, alternateRow: { backgroundColor: 'white', flex: 1, flexDirection: 'row', height: 45, }, expansion: { padding: 15, borderTopWidth: 2, borderBottomWidth: 2, borderColor: BLUE_WHITE, }, expansionWithInnerPage: { padding: 2, paddingBottom: 5, borderTopWidth: 2, borderBottomWidth: 2, borderColor: BLUE_WHITE, }, cell: { borderRightWidth: 2, borderColor: BLUE_WHITE, flex: 1, justifyContent: 'center', }, rightMostCell: { borderRightWidth: 0, }, checkableCell: { justifyContent: 'center', alignItems: 'center', }, button: { alignItems: 'center', justifyContent: 'center', height: 30, borderWidth: 1, borderRadius: 4, padding: 15, margin: 5, borderColor: SUSSOL_ORANGE, }, cellContainer: { left: { borderRightWidth: 2, borderColor: '#ecf3fc', flex: 1, justifyContent: 'center', }, right: { borderRightWidth: 2, borderColor: '#ecf3fc', flex: 1, justifyContent: 'center', }, center: { borderRightWidth: 2, borderColor: '#ecf3fc', flex: 1, justifyContent: 'center' }, }, cellText: { left: { marginLeft: 20, textAlign: 'left', fontFamily: APP_FONT_FAMILY, fontSize: Dimensions.get('window').width / 100, color: DARK_GREY, }, right: { marginRight: 20, textAlign: 'right', fontFamily: APP_FONT_FAMILY, fontSize: Dimensions.get('window').width / 100, color: DARK_GREY, }, center: { textAlign: 'center', fontFamily: APP_FONT_FAMILY, fontSize: Dimensions.get('window').width / 100, color: DARK_GREY, }, }, touchableCellContainer: { borderRightWidth: 2, borderColor: '#ecf3fc', flex: 1, alignItems: 'center', justifyContent: 'center', }, editableCellTextView: { borderBottomColor: '#cbcbcb', borderBottomWidth: 1, flex: 1, flexDirection: 'row', width: '88%', maxHeight: '65%', justifyContent: 'center', alignItems: 'center', alignSelf: 'center', marginRight: 20, }, editableCellText: { textAlign: 'right', fontFamily: APP_FONT_FAMILY, fontSize: Dimensions.get('window').width / 100, color: DARK_GREY, }, };
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2019 */ import { Dimensions } from 'react-native'; import { BACKGROUND_COLOR, BLUE_WHITE, LIGHT_GREY, WARM_GREY, DARK_GREY, SUSSOL_ORANGE, } from './colors'; import { APP_FONT_FAMILY } from './fonts'; export const dataTableColors = { checkableCellDisabled: LIGHT_GREY, checkableCellChecked: SUSSOL_ORANGE, checkableCellUnchecked: WARM_GREY, editableCellUnderline: WARM_GREY, }; export const dataTableStyles = { text: { fontFamily: APP_FONT_FAMILY, fontSize: Dimensions.get('window').width / 100, color: DARK_GREY, }, header: { backgroundColor: 'white', }, headerCell: { height: 40, borderRightWidth: 2, borderBottomWidth: 2, backgroundColor: 'white', borderColor: BLUE_WHITE, }, row: { backgroundColor: BACKGROUND_COLOR, }, expansion: { padding: 15, borderTopWidth: 2, borderBottomWidth: 2, borderColor: BLUE_WHITE, }, expansionWithInnerPage: { padding: 2, paddingBottom: 5, borderTopWidth: 2, borderBottomWidth: 2, borderColor: BLUE_WHITE, }, cell: { borderRightWidth: 2, borderColor: BLUE_WHITE, }, rightMostCell: { borderRightWidth: 0, }, checkableCell: { justifyContent: 'center', alignItems: 'center', }, button: { alignItems: 'center', justifyContent: 'center', height: 30, borderWidth: 1, borderRadius: 4, padding: 15, margin: 5, borderColor: SUSSOL_ORANGE, }, };
JavaScript
0
5416fc7e98d1cfc1fe841536c363433807f7f602
load results sooner
ReleaseDisplay/js/app.js
ReleaseDisplay/js/app.js
function moreHeadlines(strAPI) { "use strict"; //Call StellBioTech NewsRelease $.getJSON(strAPI, function (pressReleases) { pressReleases.news.forEach(function (headline) { var $panel = $('<div class="panel panel-default">'), $h2 = $("<h2>"), $p = $("<p>"); $panel.hide(); $h2.text(headline.title); $p.text(headline.published); $panel.append($h2); $panel.append($p); $(".releases").append($panel); $panel.fadeIn(); }); }); } var main = function () { "use strict"; //control api output with limit & offset var limit = 10, offset = 0, didScroll = false, $win = $(window), url = "http://www.stellarbiotechnologies.com/media/press-releases/json?limit=" + limit.toString() + "&offset=" + offset.toString(); moreHeadlines(url); //on end of document, load more headlines $win.scroll(function () { didScroll = true; }); setInterval(function() { //check if near end of dom if ( didScroll ) { didScroll = false; if ($win.scrollTop() + $win.height() > $(document).height() - 500) { offset += 10; limit = 10; url = "http://www.stellarbiotechnologies.com/media/press-releases/json?limit=" + limit.toString() + "&offset=" + offset.toString(); //request more headlines at new offset moreHeadlines(url); } } //end if }, 100); }; $(document).ready(main);
function moreHeadlines(strAPI) { "use strict"; //Call StellBioTech NewsRelease $.getJSON(strAPI, function (pressReleases) { pressReleases.news.forEach(function (headline) { var $panel = $('<div class="panel panel-default">'), $h2 = $("<h2>"), $p = $("<p>"); $panel.hide(); $h2.text(headline.title); $p.text(headline.published); $panel.append($h2); $panel.append($p); $(".releases").append($panel); $panel.fadeIn(); }); }); } var main = function () { "use strict"; //control api output with limit & offset var limit = 10, offset = 0, didScroll = false, $win = $(window), url = "http://www.stellarbiotechnologies.com/media/press-releases/json?limit=" + limit.toString() + "&offset=" + offset.toString(); moreHeadlines(url); //on end of document, load more headlines $win.scroll(function () { didScroll = true; }); setInterval(function() { //check if near end of dom if ( didScroll ) { didScroll = false; if ($win.scrollTop() + $win.height() > $(document).height() - 200) { offset += 10; limit = 10; url = "http://www.stellarbiotechnologies.com/media/press-releases/json?limit=" + limit.toString() + "&offset=" + offset.toString(); //request more headlines at new offset moreHeadlines(url); } } //end if }, 100); }; $(document).ready(main);
JavaScript
0
d82cd9b7bd03708f4940b4508acd0394713b8869
fix post order when new posts appear between loading index and expanding
js/expand.js
js/expand.js
/* *expand.js * https://github.com/savetheinternet/Tinyboard/blob/master/js/expand.js * * Released under the MIT license * Copyright (c) 2012 Michael Save <savetheinternet@tinyboard.org> * * Usage: * $config['additional_javascript'][] = 'js/jquery.min.js'; * $config['additional_javascript'][] = 'js/expand.js'; * */ $(document).ready(function(){ if($('div.banner').length != 0) return; // not index $('div.post.op span.omitted').each(function() { $(this) .html($(this).text().replace(/Click reply to view\./, '<a href="javascript:void(0)">Click to expand</a>.')) .find('a').click(function() { var thread = $(this).parent().parent().parent(); var id = thread.attr('id').replace(/^thread_/, ''); $.ajax({ url: thread.find('p.intro a.post_no:first').attr('href'), context: document.body, success: function(data) { var last_expanded = false; $(data).find('div.post.reply').each(function() { var post_in_doc = thread.find('#' + $(this).attr('id')); if(post_in_doc.length == 0) { if(last_expanded) { $(this).addClass('expanded').insertAfter(last_expanded).before('<br class="expanded">'); } else { $(this).addClass('expanded').insertAfter(thread.find('div.post:first')).after('<br class="expanded">'); } last_expanded = $(this); } else { last_expanded = post_in_doc; } }); $('<span class="omitted"><a href="javascript:void(0)">Hide expanded replies</a>.</span>') .insertAfter(thread.find('span.omitted').css('display', 'none')) .click(function() { thread.find('.expanded').remove(); $(this).prev().css('display', ''); $(this).remove(); }); } }); }); }); });
/* *expand.js * https://github.com/savetheinternet/Tinyboard/blob/master/js/expand.js * * Released under the MIT license * Copyright (c) 2012 Michael Save <savetheinternet@tinyboard.org> * * Usage: * $config['additional_javascript'][] = 'js/jquery.min.js'; * $config['additional_javascript'][] = 'js/expand.js'; * */ $(document).ready(function(){ if($('div.banner').length != 0) return; // not index $('div.post.op span.omitted').each(function() { $(this) .html($(this).text().replace(/Click reply to view\./, '<a href="javascript:void(0)">Click to expand</a>.')) .find('a').click(function() { var thread = $(this).parent().parent().parent(); var id = thread.attr('id').replace(/^thread_/, ''); $.ajax({ url: thread.find('p.intro a.post_no:first').attr('href'), context: document.body, success: function(data) { var last_expanded = false; $(data).find('div.post.reply').each(function() { if(thread.find('#' + $(this).attr('id')).length == 0) { if(last_expanded) { $(this).addClass('expanded').insertAfter(last_expanded).before('<br class="expanded">'); } else { $(this).addClass('expanded').insertAfter(thread.find('div.post:first')).after('<br class="expanded">'); } last_expanded = $(this); } }); $('<span class="omitted"><a href="javascript:void(0)">Hide expanded replies</a>.</span>') .insertAfter(thread.find('span.omitted').css('display', 'none')) .click(function() { thread.find('.expanded').remove(); $(this).prev().css('display', ''); $(this).remove(); }); } }); }); }); });
JavaScript
0
9a3dc17fae2b4806402c54fd28b78e796a2c92a0
Update spec/unit/BridgedClient.spec.js
spec/unit/BridgedClient.spec.js
spec/unit/BridgedClient.spec.js
"use strict"; const { BridgedClient, BridgedClientStatus } = require("../../lib/irc/BridgedClient.js"); const STATE_DISC = { status: BridgedClientStatus.DISCONNECTED } const STATE_CONN = { status: BridgedClientStatus.CONNECTED, client: {} } const STATE_CONN_MAX5 = { status: BridgedClientStatus.CONNECTED, client: { supported: { nicklength: 5 } } } describe("BridgedClient", function() { describe("getValidNick", function() { it("should not change a valid nick", function() { expect(BridgedClient.getValidNick("foobar", true, STATE_DISC)).toBe("foobar"); }); it("should remove invalid characters", function() { expect(BridgedClient.getValidNick("f+/\u3052oobar", false, STATE_DISC)).toBe("foobar"); }); it("will allow nicks that start with a special character", function() { expect(BridgedClient.getValidNick("foo-bar", false, STATE_DISC)).toBe("foo-bar"); expect(BridgedClient.getValidNick("[foobar]", false, STATE_DISC)).toBe("[foobar]"); expect(BridgedClient.getValidNick("{foobar}", false, STATE_DISC)).toBe("{foobar}"); expect(BridgedClient.getValidNick("-foobar", false, STATE_DISC)).toBe("M-foobar"); expect(BridgedClient.getValidNick("12345", false, STATE_DISC)).toBe("M12345"); }); it("throw if nick invalid", function() { expect(() => BridgedClient.getValidNick("f+/\u3052oobar", true, STATE_DISC)).toThrowError(); expect(() => BridgedClient.getValidNick("a".repeat(20), true, STATE_CONN)).toThrowError(); expect(() => BridgedClient.getValidNick("-foobar", true, STATE_CONN)).toThrowError(); }); it("don't truncate nick if disconnected", function() { expect(BridgedClient.getValidNick("a".repeat(20), false, STATE_DISC)).toBe("a".repeat(20)); }); it("truncate nick", function() { expect(BridgedClient.getValidNick("a".repeat(20), false, STATE_CONN)).toBe("a".repeat(9)); }); it("truncate nick with custom max", function() { expect(BridgedClient.getValidNick("a".repeat(20), false, STATE_CONN_MAX5)).toBe("a".repeat(5)); }); }); });
"use strict"; const { BridgedClient, BridgedClientStatus } = require("../../lib/irc/BridgedClient.js"); const STATE_DISC = { status: BridgedClientStatus.DISCONNECTED } const STATE_CONN = { status: BridgedClientStatus.CONNECTED, client: {} } const STATE_CONN_MAX5 = { status: BridgedClientStatus.CONNECTED, client: { supported: { nicklength: 5 } } } describe("BridgedClient", function() { describe("getValidNick", function() { it("should not change a valid nick", function() { expect(BridgedClient.getValidNick("foobar", true, STATE_DISC)).toBe("foobar"); }); it("should remove invalid characters", function() { expect(BridgedClient.getValidNick("f+/\u3052oobar", false, STATE_DISC)).toBe("foobar"); }); it("nick must start with letter of special character", function() { expect(BridgedClient.getValidNick("foo-bar", false, STATE_DISC)).toBe("foo-bar"); expect(BridgedClient.getValidNick("[foobar]", false, STATE_DISC)).toBe("[foobar]"); expect(BridgedClient.getValidNick("{foobar}", false, STATE_DISC)).toBe("{foobar}"); expect(BridgedClient.getValidNick("-foobar", false, STATE_DISC)).toBe("M-foobar"); expect(BridgedClient.getValidNick("12345", false, STATE_DISC)).toBe("M12345"); }); it("throw if nick invalid", function() { expect(() => BridgedClient.getValidNick("f+/\u3052oobar", true, STATE_DISC)).toThrowError(); expect(() => BridgedClient.getValidNick("a".repeat(20), true, STATE_CONN)).toThrowError(); expect(() => BridgedClient.getValidNick("-foobar", true, STATE_CONN)).toThrowError(); }); it("don't truncate nick if disconnected", function() { expect(BridgedClient.getValidNick("a".repeat(20), false, STATE_DISC)).toBe("a".repeat(20)); }); it("truncate nick", function() { expect(BridgedClient.getValidNick("a".repeat(20), false, STATE_CONN)).toBe("a".repeat(9)); }); it("truncate nick with custom max", function() { expect(BridgedClient.getValidNick("a".repeat(20), false, STATE_CONN_MAX5)).toBe("a".repeat(5)); }); }); });
JavaScript
0
2abce000bee32d936ce36d3440b0211fd19cc642
Add timestamp to location messages
vor-backend/app/index.js
vor-backend/app/index.js
'use strict'; const Rx = require('rx'); const Cache = require('app/cache'); const viewRoute = require('app/views/routes'); const views = require('app/views'); module.exports = function (app, router, configs, sharedConfigs) { // listen socket connections const socketConnectionSource$ = Rx.Observable.fromEvent(app.io.sockets, 'connection'); // listen socket messages const socketMessageSource$ = socketConnectionSource$ .flatMap(socket => Rx.Observable.fromEvent(socket, 'message')); // split location messages let [ deviceSource$, messageSource$ ] = socketMessageSource$ .partition(message => message.type === 'location'); // Add timestamp to every location message. deviceSource$.subscribe(message => message.date = (new Date()).toJSON()); // listen socket 'init' messages const socketInitSource$ = socketConnectionSource$ .flatMap(socket => Rx.Observable.fromEvent( socket, 'init', event => socket // we need socket to emit cache content only to one client ) ); // Post interface for messages // TODO: At the moment Arduinos' have limited websocket support. Remove when unnecessary. const postMessageSubject = new Rx.Subject(); const postMessageRoute = router.post('/messages', (req, res) => { try { const json = JSON.parse(req.body); postMessageSubject.onNext(json); res.send('OK'); } catch (error) { res.status(500).send(`Error: ${error}`); } }); app.use('/messages', postMessageRoute); // set up cache storage const cache = new Cache(configs.CACHE_PREFIX, configs.CACHE_TTL); // subscribe init socketInitSource$ .flatMap(socket => { return Rx.Observable.zip(Rx.Observable.return(socket), cache.getAll()); }) .subscribe( ([socket, messages]) => { socket.emit('init', { beacons: sharedConfigs.BEACONS, // send configured beacons data messages: messages }); console.log(`Server - fetched ${messages.length} messages from cache : ${new Date}`); }, error => console.error(`Error - init stream: ${error} : ${new Date}`) ); // subscribe messages postMessageSubject .merge(messageSource$) .flatMap(message => cache.store(message)) .do(message => console.log(`Server - stored ${message.type} : ${new Date}`)) .merge(deviceSource$) // merge location without storing it .subscribe( message => { app.io.emit('message', message); console.log(`Server - emit ${message.type} : ${new Date}`); }, error => console.error(`Error - message stream: ${error} : ${new Date}`) ); // the test page app.use('/', viewRoute(router)); views.renderTestPage(app); return app; };
'use strict'; const Rx = require('rx'); const Cache = require('app/cache'); const viewRoute = require('app/views/routes'); const views = require('app/views'); module.exports = function (app, router, configs, sharedConfigs) { // listen socket connections const socketConnectionSource$ = Rx.Observable.fromEvent(app.io.sockets, 'connection'); // listen socket messages const socketMessageSource$ = socketConnectionSource$ .flatMap(socket => Rx.Observable.fromEvent(socket, 'message')); // split location messages let [ deviceSource$, messageSource$ ] = socketMessageSource$ .partition(message => message.type === 'location'); // listen socket 'init' messages const socketInitSource$ = socketConnectionSource$ .flatMap(socket => Rx.Observable.fromEvent( socket, 'init', event => socket // we need socket to emit cache content only to one client ) ); // Post interface for messages // TODO: At the moment Arduinos' have limited websocket support. Remove when unnecessary. const postMessageSubject = new Rx.Subject(); const postMessageRoute = router.post('/messages', (req, res) => { try { const json = JSON.parse(req.body); postMessageSubject.onNext(json); res.send('OK'); } catch (error) { res.status(500).send(`Error: ${error}`); } }); app.use('/messages', postMessageRoute); // set up cache storage const cache = new Cache(configs.CACHE_PREFIX, configs.CACHE_TTL); // subscribe init socketInitSource$ .flatMap(socket => { return Rx.Observable.zip(Rx.Observable.return(socket), cache.getAll()); }) .subscribe( ([socket, messages]) => { socket.emit('init', { beacons: sharedConfigs.BEACONS, // send configured beacons data messages: messages }); console.log(`Server - fetched ${messages.length} messages from cache : ${new Date}`); }, error => console.error(`Error - init stream: ${error} : ${new Date}`) ); // subscribe messages postMessageSubject .merge(messageSource$) .flatMap(message => cache.store(message)) .do(message => console.log(`Server - stored ${message.type} : ${new Date}`)) .merge(deviceSource$) // merge location without storing it .subscribe( message => { app.io.emit('message', message); console.log(`Server - emit ${message.type} : ${new Date}`); }, error => console.error(`Error - message stream: ${error} : ${new Date}`) ); // the test page app.use('/', viewRoute(router)); views.renderTestPage(app); return app; };
JavaScript
0.000015
d601aa88189b3dfed546c196f40e3df7566a596c
Update app.js
web/app.js
web/app.js
//core libraries var express = require('express'); var http = require('http'); var path = require('path'); var connect = require('connect'); var app = express(); //this route will serve as the data api (whether it is the api itself or a proxy to one) var api = require('./routes/api'); //express configuration //Eexpress.js intended for use as data style api so we don't need jade, only going to load index html file, everything else will be handled by angular.js //app.set('views', __dirname + '/views'); //app.set('view engine', 'jade'); app.set('port', process.env.PORT || 3857); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); //make sure content is properly gzipped app.use(connect.compress()); //setup url mappings app.use('/components', express.static(__dirname + '/components')); app.use('/app', express.static(__dirname + '/app')); app.use('/json', express.static(__dirname + '/json')); app.use('/source_files', express.static(__dirname + '/source_files')); app.use(app.router); //include the routes for the internal api require('./api-setup.js').setup(app, api); app.get('*', function(req, res) { res.sendfile("index.html"); }); http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); });
//core libraries var express = require('express'); var http = require('http'); var path = require('path'); var connect = require('connect'); var app = express(); //this route will serve as the data api (whether it is the api itself or a proxy to one) var api = require('./routes/api'); //express configuration //Eexpress.js intended for use as data style api so we don't need jade, only going to load index html file, everything else will be handled by angular.js //app.set('views', __dirname + '/views'); //app.set('view engine', 'jade'); app.set('port', process.env.PORT || 3000); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); //make sure content is properly gzipped app.use(connect.compress()); //setup url mappings app.use('/components', express.static(__dirname + '/components')); app.use('/app', express.static(__dirname + '/app')); app.use('/json', express.static(__dirname + '/json')); app.use('/source_files', express.static(__dirname + '/source_files')); app.use(app.router); //include the routes for the internal api require('./api-setup.js').setup(app, api); app.get('*', function(req, res) { res.sendfile("index.html"); }); http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); });
JavaScript
0.000002
55822ac3a8ce0d762d38c76583b1e63dcb869397
Fix `environment.js`
tests/dummy/config/environment.js
tests/dummy/config/environment.js
/* jshint node: true */ module.exports = function(environment) { var backendUrl = 'https://northwindodata.azurewebsites.net'; var ENV = { modulePrefix: 'ember-app', environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created backendUrl: backendUrl, // It's a custom property, used to prevent duplicate backend urls in sources. backendUrls: { root: backendUrl, api: backendUrl + '/odata' }, // Custom property with components settings. components: { // Settings for flexberry-file component. flexberryFile: { // URL of file upload controller. uploadUrl: backendUrl + '/api/File', // Max file size in bytes for uploading files. maxUploadFileSize: null, // Flag: indicates whether to upload file on controllers modelPreSave event. uploadOnModelPreSave: true, // Flag: indicates whether to show upload button or not. showUploadButton: true, // Flag: indicates whether to show modal dialog on upload errors or not. showModalDialogOnUploadError: true, // Flag: indicates whether to show modal dialog on download errors or not. showModalDialogOnDownloadError: true, } }, // Enable flexberryAuthService. flexberryAuthService: true } }; // Read more about CSP: // http://www.ember-cli.com/#content-security-policy // https://github.com/rwjblue/ember-cli-content-security-policy // http://content-security-policy.com ENV.contentSecurityPolicy = { 'style-src': "'self' 'unsafe-inline' https://fonts.googleapis.com", 'font-src': "'self' data: https://fonts.gstatic.com", 'connect-src': "'self' " + ENV.APP.backendUrls.root }; // Read more about ember-i18n: https://github.com/jamesarosen/ember-i18n. ENV.i18n = { // Should be defined to avoid ember-i18n deprecations. // Locale will be changed then to navigator current locale (in instance initializer). defaultLocale: 'en' }; // Read more about ember-moment: https://github.com/stefanpenner/ember-moment. // Locale will be changed then to same as ember-i18n locale (and will be changed every time when i18n locale changes). ENV.moment = { outputFormat: 'L' }; 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; };
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'ember-app', environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created backendUrl: 'http://flexberry-ember-dummy.azurewebsites.net/odata' } }; 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; };
JavaScript
0.000029
70e1e3c920ccd1a127c2ba2081afffec30f2cd8f
Remove unused utility functions
js/helper.js
js/helper.js
(function(app) { 'use strict'; var helper = {}; helper.encodePath = function(str) { return str.split('/').map(function(s) { return encodeURIComponent(s); }).join('/'); }; helper.clamp = function(number, lower, upper) { return Math.min(Math.max(number, lower), upper); }; helper.extend = function(obj, src) { Object.keys(src).forEach(function(key) { obj[key] = src[key]; }); return obj; }; helper.omit = function(obj, keys) { return Object.keys(obj).reduce(function(ret, key) { if (keys.indexOf(key) === -1) { ret[key] = obj[key]; } return ret; }, {}); }; helper.sortBy = function(array, iteratee) { return array.sort(function(a, b) { var l = iteratee(a); var r = iteratee(b); if (l < r) { return -1; } if (l > r) { return 1; } return 0; }); }; helper.remove = function(array, item) { var index = array.indexOf(item); if (index < 0 || index >= array.length) { throw new RangeError('Invalid index'); } array.splice(index, 1); }; helper.moveToBack = function(array, item) { helper.remove(array, item); array.push(item); }; helper.findIndex = function(array, callback) { for (var i = 0, len = array.length; i < len; i++) { if (callback(array[i], i, array)) { return i; } } return -1; }; helper.findLastIndex = function(array, callback) { for (var i = array.length - 1; i >= 0; i--) { if (callback(array[i], i, array)) { return i; } } return -1; }; helper.find = function(array, callback) { var index = helper.findIndex(array, callback); return (index !== -1 ? array[index] : null); }; helper.findLast = function(array, callback) { var index = helper.findLastIndex(array, callback); return (index !== -1 ? array[index] : null); }; helper.flatten = function(array) { return Array.prototype.concat.apply([], array); }; helper.wrapper = function() { var Wrapper = function(self, wrapper) { return Object.defineProperty(wrapper, 'unwrap', { value: Wrapper.unwrap.bind(self) }); }; Wrapper.unwrap = function(key) { return (key === Wrapper.KEY ? this : null); }; Wrapper.KEY = {}; return Wrapper; }; if (typeof module !== 'undefined' && module.exports) { module.exports = helper; } else { app.helper = helper; } })(this.app || (this.app = {}));
(function(app) { 'use strict'; var helper = {}; helper.encodePath = function(str) { return str.split('/').map(function(s) { return encodeURIComponent(s); }).join('/'); }; helper.clamp = function(number, lower, upper) { return Math.min(Math.max(number, lower), upper); }; helper.inherits = function(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true, }, }); return ctor; }; helper.toArray = function(value) { return Array.prototype.slice.call(value); }; helper.extend = function(obj, src) { Object.keys(src).forEach(function(key) { obj[key] = src[key]; }); return obj; }; helper.omit = function(obj, keys) { return Object.keys(obj).reduce(function(ret, key) { if (keys.indexOf(key) === -1) { ret[key] = obj[key]; } return ret; }, {}); }; helper.sortBy = function(array, iteratee) { return array.sort(function(a, b) { var l = iteratee(a); var r = iteratee(b); if (l < r) { return -1; } if (l > r) { return 1; } return 0; }); }; helper.remove = function(array, item) { var index = array.indexOf(item); if (index < 0 || index >= array.length) { throw new RangeError('Invalid index'); } array.splice(index, 1); }; helper.moveToBack = function(array, item) { helper.remove(array, item); array.push(item); }; helper.findIndex = function(array, callback) { for (var i = 0, len = array.length; i < len; i++) { if (callback(array[i], i, array)) { return i; } } return -1; }; helper.findLastIndex = function(array, callback) { for (var i = array.length - 1; i >= 0; i--) { if (callback(array[i], i, array)) { return i; } } return -1; }; helper.find = function(array, callback) { var index = helper.findIndex(array, callback); return (index !== -1 ? array[index] : null); }; helper.findLast = function(array, callback) { var index = helper.findLastIndex(array, callback); return (index !== -1 ? array[index] : null); }; helper.flatten = function(array) { return Array.prototype.concat.apply([], array); }; helper.wrapper = function() { var Wrapper = function(self, wrapper) { return Object.defineProperty(wrapper, 'unwrap', { value: Wrapper.unwrap.bind(self) }); }; Wrapper.unwrap = function(key) { return (key === Wrapper.KEY ? this : null); }; Wrapper.KEY = {}; return Wrapper; }; if (typeof module !== 'undefined' && module.exports) { module.exports = helper; } else { app.helper = helper; } })(this.app || (this.app = {}));
JavaScript
0.000001
0d41b41ed9f7a5114804c462b4fca17195f599eb
Rename command db to command store
xpl-db.js
xpl-db.js
/*jslint node: true, vars: true, nomen: true */ 'use strict'; var Xpl = require("xpl-api"); var commander = require('commander'); var os = require('os'); var debug = require('debug')('xpl-db'); var Mysql = require('./lib/mysql'); var Server = require('./lib/server'); commander.version(require("./package.json").version); commander.option("-a, --deviceAliases <aliases>", "Devices aliases"); commander.option("--httpPort <port>", "REST server port", parseInt); Mysql.fillCommander(commander); Xpl.fillCommander(commander); var Store = Mysql; commander.command("create").action(() => { var store = new Store(commander); store.create(function(error) { if (error) { console.error(error); return; } }); }); commander.command("rest").action(() => { var server = new Server(commander, store); server.listen((error) => { if (error) { console.error(error); } }); }); commander.command("store").action(() => { var deviceAliases = Xpl.loadDeviceAliases(commander.deviceAliases); var store = new Store(commander, deviceAliases); store.connect((error) => { if (error) { console.error(error); return; } try { if (!commander.xplSource) { var hostName = os.hostname(); if (hostName.indexOf('.') > 0) { hostName = hostName.substring(0, hostName.indexOf('.')); } commander.xplSource = "db." + hostName; } var xpl = new Xpl(commander); xpl.on("error", (error) => { console.error("XPL error", error); }); xpl.bind((error) => { if (error) { console.error("Can not open xpl bridge ", error); process.exit(2); return; } console.log("Xpl bind succeed "); var processMessage = (message) => { if (message.bodyName === "sensor.basic") { store.save(message, (error) => { if (error) { console.error('error connecting: ', error, error.stack); return; } }); return; } } xpl.on("xpl:xpl-trig", processMessage); xpl.on("xpl:xpl-stat", processMessage); xpl.on("message", function(message, packet, address) { }); }); } catch (x) { console.error(x); } }); }); commander.parse(process.argv);
/*jslint node: true, vars: true, nomen: true */ 'use strict'; var Xpl = require("xpl-api"); var commander = require('commander'); var os = require('os'); var debug = require('debug')('xpl-db'); var Mysql = require('./lib/mysql'); var Server = require('./lib/server'); commander.version(require("./package.json").version); commander.option("-a, --deviceAliases <aliases>", "Devices aliases"); commander.option("--httpPort <port>", "REST server port", parseInt); Mysql.fillCommander(commander); Xpl.fillCommander(commander); var Store = Mysql; commander.command("create").action(() => { var store = new Store(commander); store.create(function(error) { if (error) { console.error(error); return; } }); }); commander.command("rest").action(() => { var server = new Server(commander, store); server.listen((error) => { if (error) { console.error(error); } }); }); commander.command("db").action(() => { var deviceAliases = Xpl.loadDeviceAliases(commander.deviceAliases); var store = new Store(commander, deviceAliases); store.connect((error) => { if (error) { console.error(error); return; } try { if (!commander.xplSource) { var hostName = os.hostname(); if (hostName.indexOf('.') > 0) { hostName = hostName.substring(0, hostName.indexOf('.')); } commander.xplSource = "db." + hostName; } var xpl = new Xpl(commander); xpl.on("error", (error) => { console.error("XPL error", error); }); xpl.bind((error) => { if (error) { console.error("Can not open xpl bridge ", error); process.exit(2); return; } console.log("Xpl bind succeed "); var processMessage = (message) => { if (message.bodyName === "sensor.basic") { store.save(message, (error) => { if (error) { console.error('error connecting: ', error, error.stack); return; } }); return; } } xpl.on("xpl:xpl-trig", processMessage); xpl.on("xpl:xpl-stat", processMessage); xpl.on("message", function(message, packet, address) { }); }); } catch (x) { console.error(x); } }); }); commander.parse(process.argv);
JavaScript
0.999251
9157ef7be18368030ebd69e7d9e5bd519e2be159
fix resolving node_modules
src/defaults/compiler_config_factory.js
src/defaults/compiler_config_factory.js
// @flow export default function defaultConfigFactory(env: string): WebpackConfig { const config = { output: { filename: '[name].[chunkhash].js', path: '~public/assets', chunkFilename: '[name].[chunkhash].chunk.js', }, resolve: { modules: [ 'node_modules', '~app/assets', '~lib/assets', ], extensions: ['.js', '.json', '.jsx'] }, devtool: '', target: 'web', }; if (env === 'development') { config.output.filename = '[name].js'; config.output.chunkFilename = '[name].chunk.js'; } return config; }
// @flow export default function defaultConfigFactory(env: string): WebpackConfig { const config = { output: { filename: '[name].[chunkhash].js', path: '~public/assets', chunkFilename: '[name].[chunkhash].chunk.js', }, resolve: { modules: [ '~app/assets', '~lib/assets', ], extensions: ['.js', '.json', '.jsx'] }, devtool: '', target: 'web', }; if (env === 'development') { config.output.filename = '[name].js'; config.output.chunkFilename = '[name].chunk.js'; } return config; }
JavaScript
0.000008
05ab1f5f7daed94b2527c62b74c2cafe6a896963
Fix merging tests
tests/integration/mergingTests.js
tests/integration/mergingTests.js
var lib = require("../../source/module.js"); var Workspace = lib.Workspace, Archive = lib.Archive, createCredentials = lib.createCredentials, encodingTools = lib.tools.encoding; const E = encodingTools.encodeStringValue; module.exports = { setUp: function(cb) { var diffArchiveA = new Archive(), diffArchiveB = new Archive(), commonCommands = [ 'cgr 0 1', 'tgr 1 "Main Group"', 'pad 1', 'cgr 1 2', 'tgr 2 "Secondary Group"', 'pad 2', 'cen 1 1', 'sep 1 title "My first entry"', 'cgr 0 4', 'pad 10', 'dgr 4', 'pad 3', 'sep 1 username "anonymous"', 'sep 1 password "retro"', 'sea 1 "test" "test"', 'pad 4', 'cmm "after pad"' ], diffCommandsA = [ 'cgr 1 3', 'tgr 3 "Third group"', 'pad 5', 'cmm "diff a"', 'dgr 3', 'pad 8', 'dgr 1', 'pad 9' ], diffCommandsB = [ 'cen 1 2', 'sep 2 title "My second entry"', 'pad 6', 'sem 2 "country" "AU"', 'pad 7' ]; commonCommands.concat(diffCommandsA).forEach(function(command) { diffArchiveA._getWestley().execute(command); }); commonCommands.concat(diffCommandsB).forEach(function(command) { diffArchiveB._getWestley().execute(command); }); this.diffArchiveA = diffArchiveA; this.diffArchiveB = diffArchiveB; this.diffWorkspace = new Workspace(); this.diffWorkspace.setPrimaryArchive( diffArchiveB, { load: function() { return Promise.resolve(diffArchiveA); } }, createCredentials.fromPassword("fake") ); cb(); }, testMock: function(test) { var diffArchiveA = this.diffArchiveA; this.diffWorkspace.primary.datasource.load().then(function(archive) { test.strictEqual(archive, diffArchiveA, "Mock should return correct archive"); test.done(); }) .catch(function(err) { console.error("Error:", err); }); }, testNonDeletion: function(test) { var workspace = this.diffWorkspace; workspace.mergeSaveablesFromRemote() .then(function() { var mergedHistory = workspace.primary.archive._getWestley().getHistory(); test.ok(mergedHistory.indexOf(`tgr 3 "Third group"`) > 0, "Merged from group A"); test.ok(mergedHistory.indexOf(`sep 2 title "My second entry"`) > 0, "Merged from group B"); test.ok(mergedHistory.indexOf('pad 4') > 0, "Merged base"); test.ok(mergedHistory.indexOf('dgr 1') < 0, "Filtered out deletion commands"); test.ok(mergedHistory.indexOf('dgr 4') > 0, "Shared deletion commands persist"); test.done(); }) .catch(function(err) { console.error("Error:", err); }); } };
var lib = require("../../source/module.js"); var Workspace = lib.Workspace, Archive = lib.Archive, createCredentials = lib.createCredentials; //var Comparator = require(GLOBAL.root + "/system/ArchiveComparator.js"); module.exports = { setUp: function(cb) { var diffArchiveA = new Archive(), diffArchiveB = new Archive(), commonCommands = [ 'cgr 0 1', 'tgr 1 "Main Group"', 'pad 1', 'cgr 1 2', 'tgr 2 "Secondary Group', 'pad 2', 'cen 1 1', 'sep 1 title "My first entry"', 'cgr 0 4', 'pad 10', 'dgr 4', 'pad 3', 'sep 1 username "anonymous"', 'sep 1 password "retro"', 'sea 1 "test" "test"', 'pad 4', 'cmm "after pad"' ], diffCommandsA = [ 'cgr 1 3', 'tgr 3 "Third group"', 'pad 5', 'cmm "diff a"', 'dgr 3', 'pad 8', 'dgr 1', 'pad 9' ], diffCommandsB = [ 'cen 1 2', 'sep 2 title "My second entry"', 'pad 6', 'sem 2 "country" "AU"', 'pad 7' ]; commonCommands.concat(diffCommandsA).forEach(function(command) { diffArchiveA._getWestley().execute(command); }); commonCommands.concat(diffCommandsB).forEach(function(command) { diffArchiveB._getWestley().execute(command); }); this.diffArchiveA = diffArchiveA; this.diffArchiveB = diffArchiveB; this.diffWorkspace = new Workspace(); this.diffWorkspace.setPrimaryArchive( diffArchiveB, { load: function() { return Promise.resolve(diffArchiveA); } }, createCredentials.fromPassword("fake") ); cb(); }, testMock: function(test) { var diffArchiveA = this.diffArchiveA; this.diffWorkspace.primary.datasource.load().then(function(archive) { test.strictEqual(archive, diffArchiveA, "Mock should return correct archive"); test.done(); }) .catch(function(err) { console.error("Error:", err); }); }, testNonDeletion: function(test) { var workspace = this.diffWorkspace; workspace.mergeSaveablesFromRemote() .then(function() { var mergedHistory = workspace.primary.archive._getWestley().getHistory(); test.ok(mergedHistory.indexOf('tgr 3 "Third group"') > 0, "Merged from group A"); test.ok(mergedHistory.indexOf('sep 2 title "My second entry"') > 0, "Merged from group B"); test.ok(mergedHistory.indexOf('pad 4') > 0, "Merged base"); test.ok(mergedHistory.indexOf('dgr 1') < 0, "Filtered out deletion commands"); test.ok(mergedHistory.indexOf('dgr 4') > 0, "Shared deletion commands persist"); test.done(); }) .catch(function(err) { console.error("Error:", err); }); } };
JavaScript
0.000047
808436f17334010440b414cf82b01e8049f5b63b
Delete obsolete todo.
features/opensocial-current/jsonperson.js
features/opensocial-current/jsonperson.js
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ /** * Base interface for json based person objects. * * @private * @constructor */ var JsonPerson = function(opt_params) { opt_params = opt_params || {}; JsonPerson.constructObject(opt_params, "bodyType", opensocial.BodyType); JsonPerson.constructObject(opt_params, "currentLocation", opensocial.Address); JsonPerson.constructObject(opt_params, "dateOfBirth", Date); JsonPerson.constructObject(opt_params, "name", opensocial.Name); JsonPerson.constructObject(opt_params, "profileSong", opensocial.Url); JsonPerson.constructObject(opt_params, "profileVideo", opensocial.Url); JsonPerson.constructArrayObject(opt_params, "addresses", opensocial.Address); JsonPerson.constructArrayObject(opt_params, "emails", opensocial.Email); JsonPerson.constructArrayObject(opt_params, "jobs", opensocial.Organization); JsonPerson.constructArrayObject(opt_params, "phoneNumbers", opensocial.Phone); JsonPerson.constructArrayObject(opt_params, "schools", opensocial.Organization); JsonPerson.constructArrayObject(opt_params, "urls", opensocial.Url); JsonPerson.constructEnum(opt_params, "gender"); JsonPerson.constructEnum(opt_params, "smoker"); JsonPerson.constructEnum(opt_params, "drinker"); JsonPerson.constructEnum(opt_params, "networkPresence"); JsonPerson.constructEnumArray(opt_params, "lookingFor"); opensocial.Person.call(this, opt_params, opt_params['isOwner'], opt_params['isViewer']); }; JsonPerson.inherits(opensocial.Person); // Converts the fieldName into an instance of an opensocial.Enum JsonPerson.constructEnum = function(map, fieldName) { var fieldValue = map[fieldName]; if (fieldValue) { map[fieldName] = new opensocial.Enum(fieldValue.key, fieldValue.displayValue); } } // Converts the fieldName into an array of instances of an opensocial.Enum JsonPerson.constructEnumArray = function(map, fieldName) { var fieldValue = map[fieldName]; if (fieldValue) { for (var i = 0; i < fieldValue.length; i++) { fieldValue[i] = new opensocial.Enum(fieldValue[i].key, fieldValue[i].displayValue); } } } // Converts the fieldName into an instance of the specified object JsonPerson.constructObject = function(map, fieldName, className) { var fieldValue = map[fieldName]; if (fieldValue) { map[fieldName] = new className(fieldValue); } } JsonPerson.constructArrayObject = function(map, fieldName, className) { var fieldValue = map[fieldName]; if (fieldValue) { for (var i = 0; i < fieldValue.length; i++) { fieldValue[i] = new className(fieldValue[i]); } } } JsonPerson.prototype.getDisplayName = function() { return this.getField("displayName"); }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ /** * Base interface for json based person objects. * * @private * @constructor */ var JsonPerson = function(opt_params) { opt_params = opt_params || {}; // TODO: doesn't handle drinker, smoker, or gender yet JsonPerson.constructObject(opt_params, "bodyType", opensocial.BodyType); JsonPerson.constructObject(opt_params, "currentLocation", opensocial.Address); JsonPerson.constructObject(opt_params, "dateOfBirth", Date); JsonPerson.constructObject(opt_params, "name", opensocial.Name); JsonPerson.constructObject(opt_params, "profileSong", opensocial.Url); JsonPerson.constructObject(opt_params, "profileVideo", opensocial.Url); JsonPerson.constructArrayObject(opt_params, "addresses", opensocial.Address); JsonPerson.constructArrayObject(opt_params, "emails", opensocial.Email); JsonPerson.constructArrayObject(opt_params, "jobs", opensocial.Organization); JsonPerson.constructArrayObject(opt_params, "phoneNumbers", opensocial.Phone); JsonPerson.constructArrayObject(opt_params, "schools", opensocial.Organization); JsonPerson.constructArrayObject(opt_params, "urls", opensocial.Url); JsonPerson.constructEnum(opt_params, "gender"); JsonPerson.constructEnum(opt_params, "smoker"); JsonPerson.constructEnum(opt_params, "drinker"); JsonPerson.constructEnum(opt_params, "networkPresence"); JsonPerson.constructEnumArray(opt_params, "lookingFor"); opensocial.Person.call(this, opt_params, opt_params['isOwner'], opt_params['isViewer']); }; JsonPerson.inherits(opensocial.Person); // Converts the fieldName into an instance of an opensocial.Enum JsonPerson.constructEnum = function(map, fieldName) { var fieldValue = map[fieldName]; if (fieldValue) { map[fieldName] = new opensocial.Enum(fieldValue.key, fieldValue.displayValue); } } // Converts the fieldName into an array of instances of an opensocial.Enum JsonPerson.constructEnumArray = function(map, fieldName) { var fieldValue = map[fieldName]; if (fieldValue) { for (var i = 0; i < fieldValue.length; i++) { fieldValue[i] = new opensocial.Enum(fieldValue[i].key, fieldValue[i].displayValue); } } } // Converts the fieldName into an instance of the specified object JsonPerson.constructObject = function(map, fieldName, className) { var fieldValue = map[fieldName]; if (fieldValue) { map[fieldName] = new className(fieldValue); } } JsonPerson.constructArrayObject = function(map, fieldName, className) { var fieldValue = map[fieldName]; if (fieldValue) { for (var i = 0; i < fieldValue.length; i++) { fieldValue[i] = new className(fieldValue[i]); } } } JsonPerson.prototype.getDisplayName = function() { return this.getField("displayName"); }
JavaScript
0.001851
b88216b42291988a767e9e2be8c6e3f931ed549a
Use MinimalModule in testModuleFactory
tests/js/app/testModuleFactory.js
tests/js/app/testModuleFactory.js
// Copyright 2015 Endless Mobile, Inc. const Lang = imports.lang; const GObject = imports.gi.GObject; const Minimal = imports.tests.minimal; const ModuleFactory = imports.app.moduleFactory; const MOCK_APP_JSON = { version: 2, modules: { 'test': { type: 'TestModule' }, }, }; const MockWarehouse = new Lang.Class({ Name: 'MockWarehouse', Extends: GObject.Object, _init: function (props={}) { this.parent(props); }, type_to_class: function (module_name) { return Minimal.MinimalModule; }, }); describe('Module factory', function () { let module_factory; let warehouse; beforeEach(function () { warehouse = new MockWarehouse(); module_factory = new ModuleFactory.ModuleFactory({ app_json: MOCK_APP_JSON, warehouse: warehouse, }); }); it ('constructs', function () {}); it ('returns correct module constructor', function () { spyOn(warehouse, 'type_to_class').and.callThrough(); module_factory.create_named_module('test'); expect(warehouse.type_to_class).toHaveBeenCalledWith('TestModule'); }); });
// Copyright 2015 Endless Mobile, Inc. const Lang = imports.lang; const GObject = imports.gi.GObject; const ModuleFactory = imports.app.moduleFactory; const Module = imports.app.interfaces.module; const MOCK_APP_JSON = { version: 2, modules: { 'test': { type: 'TestModule' }, }, }; const TestModule = new Lang.Class({ Name: 'TestModule', Extends: GObject.Object, Implements: [ Module.Module ], Properties: { 'factory': GObject.ParamSpec.override('factory', Module.Module), 'factory-name': GObject.ParamSpec.override('factory-name', Module.Module), }, _init: function (props={}) { this.parent(props); }, }); const MockWarehouse = new Lang.Class({ Name: 'MockWarehouse', Extends: GObject.Object, _init: function (props={}) { this.parent(props); }, type_to_class: function (module_name) { return TestModule; }, }); describe('Module factory', function () { let module_factory; let warehouse; beforeEach(function () { warehouse = new MockWarehouse(); module_factory = new ModuleFactory.ModuleFactory({ app_json: MOCK_APP_JSON, warehouse: warehouse, }); }); it ('constructs', function () {}); it ('returns correct module constructor', function () { spyOn(warehouse, 'type_to_class').and.callThrough(); module_factory.create_named_module('test'); expect(warehouse.type_to_class).toHaveBeenCalledWith('TestModule'); }); });
JavaScript
0
7e6902ca10f94d61df0df348bdda937b89aff8b6
update to make sure that sub-classed binding kinds will have the appropriate values
source/kernel/AutoBindingSupport.js
source/kernel/AutoBindingSupport.js
(function () { var remapped = { bindFrom: "from", bindTo: "to", bindTransform: "transform", bindOneWay: "oneWay", bindAutoSync: "autoSync", bindDebug: "debug" }; var defaults = { to: ".content", transform: null, oneWay: true, autoSync: false, debug: false }; enyo.kind({ // ........................... // PUBLIC PROPERTIES //*@public name: "enyo.AutoBindingSupport", //*@public kind: "enyo.Mixin", // ........................... // PROTECTED PROPERTIES //*@protected _did_setup_auto_bindings: false, // ........................... // COMPUTED PROPERTIES // ........................... // PUBLIC METHODS // ........................... // PROTECTED METHODS //*@protected create: function () { var cache = this._auto_cache = {}; var ctor = this._binding_ctor = enyo.getPath(this.defaultBindingKind); var keys = enyo.keys(defaults); if (ctor !== enyo.Binding) { cache.defaults = enyo.mixin(enyo.clone(defaults), enyo.only(keys, ctor.prototype, true)); } else cache.defaults = defaults; this.setupAutoBindings(); }, //*@protected autoBinding: function () { var bind = this.binding.apply(this, arguments); bind.autoBindingId = enyo.uid("autoBinding"); }, //*@protected autoBindings: enyo.Computed(function () { return enyo.filter(this.bindings || [], function (bind) { return bind && bind.autoBindingId; }); }), //*@protected setupAutoBindings: function () { if (this._did_setup_auto_bindings) return; if (!this.controller) return; var controls = this.get("bindableControls"); var idx = 0; var len = controls.length; var controller = this.controller; var control; var props; for (; idx < len; ++idx) { control = controls[idx]; props = this.bindProperties(control); this.autoBinding(props, {source: controller, target: control}); } this._did_setup_auto_bindings = true; }, //*@protected bindProperties: function (control) { var cache = this._auto_cache.defaults; return enyo.mixin(enyo.clone(cache), enyo.remap(remapped, control)); }, //*@protected bindableControls: enyo.Computed(function (control) { var cache = this._auto_cache["bindableControls"]; if (cache) return enyo.clone(cache); var bindable = []; var control = control || this; var controls = control.controls || []; var idx = 0; var len = controls.length; for (; idx < len; ++idx) { bindable = bindable.concat(this.bindableControls(controls[idx])); } if ("bindFrom" in control) bindable.push(control); if (this === control) this._auto_cache["bindableControls"] = enyo.clone(bindable); return bindable; }), //*@protected controllerDidChange: enyo.Observer(function () { this.inherited(arguments); if (this.controller) { if (!this._did_setup_auto_bindings) { this.setupAutoBindings(); } } }, "controller") // ........................... // OBSERVERS }); }());
(function () { var remapped = { bindFrom: "from", bindTo: "to", bindTransform: "transform", bindOneWay: "oneWay", bindAutoSync: "autoSync", bindDebug: "debug" }; var defaults = { to: ".content", transform: null, oneWay: true, autoSync: false, debug: false }; enyo.kind({ // ........................... // PUBLIC PROPERTIES //*@public name: "enyo.AutoBindingSupport", //*@public kind: "enyo.Mixin", // ........................... // PROTECTED PROPERTIES //*@protected _did_setup_auto_bindings: false, // ........................... // COMPUTED PROPERTIES // ........................... // PUBLIC METHODS // ........................... // PROTECTED METHODS //*@protected create: function () { var cache = this._auto_cache = {}; var ctor = this._binding_ctor = enyo.getPath(this.defaultBindingKind); var keys = enyo.keys(defaults); if (ctor !== enyo.Binding) { cache.defaults = enyo.mixin(enyo.clone(defaults), enyo.only(keys, ctor.prototype)); } else cache.defaults = defaults; this.setupAutoBindings(); }, //*@protected autoBinding: function () { var bind = this.binding.apply(this, arguments); bind.autoBindingId = enyo.uid("autoBinding"); }, //*@protected autoBindings: enyo.Computed(function () { return enyo.filter(this.bindings || [], function (bind) { return bind && bind.autoBindingId; }); }), //*@protected setupAutoBindings: function () { if (this._did_setup_auto_bindings) return; if (!this.controller) return; var controls = this.get("bindableControls"); var idx = 0; var len = controls.length; var controller = this.controller; var control; var props; for (; idx < len; ++idx) { control = controls[idx]; props = this.bindProperties(control); this.autoBinding(props, {source: controller, target: control}); } this._did_setup_auto_bindings = true; }, //*@protected bindProperties: function (control) { var cache = this._auto_cache.defaults; return enyo.mixin(enyo.clone(cache), enyo.remap(remapped, control)); }, //*@protected bindableControls: enyo.Computed(function (control) { var cache = this._auto_cache["bindableControls"]; if (cache) return enyo.clone(cache); var bindable = []; var control = control || this; var controls = control.controls || []; var idx = 0; var len = controls.length; for (; idx < len; ++idx) { bindable = bindable.concat(this.bindableControls(controls[idx])); } if ("bindFrom" in control) bindable.push(control); if (this === control) this._auto_cache["bindableControls"] = enyo.clone(bindable); return bindable; }), //*@protected controllerDidChange: enyo.Observer(function () { this.inherited(arguments); if (this.controller) { if (!this._did_setup_auto_bindings) { this.setupAutoBindings(); } } }, "controller") // ........................... // OBSERVERS }); }());
JavaScript
0
583e57d876f683e9b77ff9df19611b38f0d77740
Add Keyelems method to Map
web/client/scripts/map.js
web/client/scripts/map.js
/*--------------------------------------------------------------------------- Copyright 2013 Microsoft Corporation. This is free software; you can redistribute it and/or modify it under the terms of the Apache License, Version 2.0. A copy of the License can be found in the file "license.txt" at the root of this distribution. ---------------------------------------------------------------------------*/ if (typeof define !== 'function') { var define = require('amdefine')(module) } define([],function() { var Map = (function() { function Map() { }; Map.prototype.clear = function() { var self = this; self.forEach( function(name,value) { self.remove(name); }); } Map.prototype.persist = function() { return this; }; Map.prototype.copy = function() { var self = this; var map = new Map(); self.forEach( function(name,value) { map.set(name,value); }); return map; } Map.prototype.set = function( name, value ) { this["/" + name] = value; } Map.prototype.get = function( name ) { return this["/" + name]; } Map.prototype.getOrCreate = function( name, def ) { var self = this; if (!self.contains(name)) self.set(name,def); return self.get(name); } Map.prototype.contains = function( name ) { return (this.get(name) !== undefined); } Map.prototype.remove = function( name ) { delete this["/" + name]; } // apply action to each element. breaks early if action returns "false". Map.prototype.forEach = function( action ) { var self = this; for (var key in self) { if (key.substr(0,1) === "/") { var res = action(key.substr(1), self[key]); if (res===false) return; } }; } // return a new map where action is applied to every element Map.prototype.map = function( action ) { var self = this; var res = new Map(); self.forEach( function(name,elem) { res.set(name,action(elem)); }); return res; } Map.prototype.elems = function() { var self = this; var res = []; self.forEach( function(name,elem) { res.push(elem); }); return res; } Map.prototype.keyElems = function() { var self = this; var res = []; self.forEach( function(name,elem) { res.push( {key:name,value:elem} ); }); return res; } return Map; })(); return Map; });
/*--------------------------------------------------------------------------- Copyright 2013 Microsoft Corporation. This is free software; you can redistribute it and/or modify it under the terms of the Apache License, Version 2.0. A copy of the License can be found in the file "license.txt" at the root of this distribution. ---------------------------------------------------------------------------*/ if (typeof define !== 'function') { var define = require('amdefine')(module) } define([],function() { var Map = (function() { function Map() { }; Map.prototype.clear = function() { var self = this; self.forEach( function(name,value) { self.remove(name); }); } Map.prototype.persist = function() { return this; }; Map.prototype.copy = function() { var self = this; var map = new Map(); self.forEach( function(name,value) { map.set(name,value); }); return map; } Map.prototype.set = function( name, value ) { this["/" + name] = value; } Map.prototype.get = function( name ) { return this["/" + name]; } Map.prototype.getOrCreate = function( name, def ) { var self = this; if (!self.contains(name)) self.set(name,def); return self.get(name); } Map.prototype.contains = function( name ) { return (this.get(name) !== undefined); } Map.prototype.remove = function( name ) { delete this["/" + name]; } // apply action to each element. breaks early if action returns "false". Map.prototype.forEach = function( action ) { var self = this; for (var key in self) { if (key.substr(0,1) === "/") { var res = action(key.substr(1), self[key]); if (res===false) return; } }; } // return a new map where action is applied to every element Map.prototype.map = function( action ) { var self = this; var res = new Map(); self.forEach( function(name,elem) { res.set(name,action(elem)); }); return res; } Map.prototype.elems = function() { var self = this; var res = []; self.forEach( function(name,elem) { res.push(elem); }); return res; } return Map; })(); return Map; });
JavaScript
0
6bb997cda18613a56a02e7c22bee4844642c5fc0
allow extension properties on any chat type
src/extplug/plugins/custom-chat-type.js
src/extplug/plugins/custom-chat-type.js
define(function (require, exports, module) { const { around } = require('meld'); const Events = require('plug/core/Events'); const ChatView = require('plug/views/rooms/chat/ChatView'); const util = require('plug/util/util'); const emoji = require('plug/util/emoji'); const settings = require('plug/store/settings'); const Plugin = require('../Plugin'); /** * The ChatType Plugin adds a "custom" chat type. Any chat messages * passed through the ChatView "onReceived" handler will be affected, * so in particular all "chat:receive" events are handled properly. * * A chat message with "custom" in its type property can take a few * additional options: * * * the "badge" property can contain an emoji name (eg ":eyes:") or * an icon class (eg "icon-plugdj") as well as the standard badge * names. * * the "color" property takes a CSS colour, which will be used for * the message text. * * the "timestamp" property always defaults to the current time if * it is left empty. * * This is especially useful for showing notifications in chat. * The "type" property can be a list of CSS class names, if it contains * "custom", (eg `{ type: "custom inline my-notification" }`) so you * can use those classes to style your message as well. Note that you * cannot add additional classes for the other message types. */ const ChatTypePlugin = Plugin.extend({ enable() { // chatView.onReceived will still be the old method after adding advice // so the event listener should also be swapped out let chatView = this.ext.appView.room.chat; if (chatView) { Events.off('chat:receive', chatView.onReceived); } this._chatTypeAdvice = around(ChatView.prototype, 'onReceived', this.onReceived); if (chatView) { Events.on('chat:receive', chatView.onReceived, chatView); } }, disable() { // remove custom chat type advice, and restore // the original event listener let chatView = this.ext.appView.room.chat; if (chatView) { Events.off('chat:receive', chatView.onReceived); } this._chatTypeAdvice.remove(); if (chatView) { Events.on('chat:receive', chatView.onReceived, chatView); } }, // bound to the ChatView instance onReceived(joinpoint) { let message = joinpoint.args[0]; if (message.type.split(' ').indexOf('custom') !== -1) { // plug.dj has some nice default styling on "update" messages message.type += ' update'; } if (!message.timestamp) { message.timestamp = util.getChatTimestamp(settings.settings.chatTimestamps === 24); } // insert the chat message element joinpoint.proceed(); if (message.badge) { // emoji badge if (/^:(.*?):$/.test(message.badge)) { let badgeBox = this.$chatMessages.children().last().find('.badge-box'); let emojiName = message.badge.slice(1, -1); if (emoji.map[emojiName]) { badgeBox.find('i').remove(); badgeBox.append( $('<span />').addClass('emoji-glow extplug-badji').append( $('<span />').addClass('emoji emoji-' + emoji.map[emojiName]) ) ); } } // icon badge else if (/^icon-(.*?)$/.test(message.badge)) { let badgeBox = this.$chatMessages.children().last().find('.badge-box'); badgeBox.find('i') .removeClass() .addClass('icon').addClass(message.badge); } } if (message.color) { this.$chatMessages.children().last().find('.msg .text').css('color', message.color); } } }); module.exports = ChatTypePlugin; });
define(function (require, exports, module) { const { around } = require('meld'); const Events = require('plug/core/Events'); const ChatView = require('plug/views/rooms/chat/ChatView'); const util = require('plug/util/util'); const emoji = require('plug/util/emoji'); const settings = require('plug/store/settings'); const Plugin = require('../Plugin'); /** * The ChatType Plugin adds a "custom" chat type. Any chat messages * passed through the ChatView "onReceived" handler will be affected, * so in particular all "chat:receive" events are handled properly. * * A chat message with "custom" in its type property can take a few * additional options: * * * the "badge" property can contain an emoji name (eg ":eyes:") or * an icon class (eg "icon-plugdj") as well as the standard badge * names. * * the "color" property takes a CSS colour, which will be used for * the message text. * * the "timestamp" property always defaults to the current time if * it is left empty. * * This is especially useful for showing notifications in chat. * The "type" property can be a list of CSS class names, if it contains * "custom", (eg `{ type: "custom inline my-notification" }`) so you * can use those classes to style your message as well. Note that you * cannot add additional classes for the other message types. */ const ChatTypePlugin = Plugin.extend({ enable() { // chatView.onReceived will still be the old method after adding advice // so the event listener should also be swapped out let chatView = this.ext.appView.room.chat; if (chatView) { Events.off('chat:receive', chatView.onReceived); } this._chatTypeAdvice = around(ChatView.prototype, 'onReceived', this.onReceived); if (chatView) { Events.on('chat:receive', chatView.onReceived, chatView); } }, disable() { // remove custom chat type advice, and restore // the original event listener let chatView = this.ext.appView.room.chat; if (chatView) { Events.off('chat:receive', chatView.onReceived); } this._chatTypeAdvice.remove(); if (chatView) { Events.on('chat:receive', chatView.onReceived, chatView); } }, // bound to the ChatView instance onReceived(joinpoint) { let message = joinpoint.args[0]; if (message.type.split(' ').indexOf('custom') !== -1) { // plug.dj has some nice default styling on "update" messages message.type += ' update'; if (!message.timestamp) { message.timestamp = util.getChatTimestamp(settings.settings.chatTimestamps === 24); } // insert the chat message element joinpoint.proceed(); if (message.badge) { // emoji badge if (/^:(.*?):$/.test(message.badge)) { let badgeBox = this.$chatMessages.children().last().find('.badge-box'); let emojiName = message.badge.slice(1, -1); if (emoji.map[emojiName]) { badgeBox.find('i').remove(); badgeBox.append( $('<span />').addClass('emoji-glow extplug-badji').append( $('<span />').addClass('emoji emoji-' + emoji.map[emojiName]) ) ); } } // icon badge else if (/^icon-(.*?)$/.test(message.badge)) { let badgeBox = this.$chatMessages.children().last().find('.badge-box'); badgeBox.find('i') .removeClass() .addClass('icon').addClass(message.badge); } } if (message.color) { this.$chatMessages.children().last().find('.msg .text').css('color', message.color); } } else { joinpoint.proceed(); } } }); module.exports = ChatTypePlugin; });
JavaScript
0
ac260edac48a842054e8c49d3d8c0df157b83e6b
fix publish script
scripts/publish-to-s3.js
scripts/publish-to-s3.js
require('dotenv').config() const AWS = require('aws-sdk') const path = require('path') const fs = require('fs') const { promisify } = require('util') const pkg = require('../package.json') const getVersionTypes = version => [ version, version.replace(/^(\d+\.\d+)\.\d+/, '$1.x'), version.replace(/^(\d+)\.\d+\.\d+/, '$1.x') ] const BASE_PATH = 'widget/' const VERSION_TYPES = getVersionTypes(pkg.version) const BUCKET = process.env.BUCKET const ACCESS_KEY = process.env.ACCESS_KEY const SECRET_KEY = process.env.SECRET_KEY if (!BUCKET || !ACCESS_KEY || !SECRET_KEY) { console.log("don't found credentials skip publish to s3") process.exit(0) } const UPLOAD_CONFIG = { ACL: 'public-read', Bucket: BUCKET, ContentType: 'application/javascript; charset=utf-8' } const S3 = new AWS.S3({ credentials: new AWS.Credentials(ACCESS_KEY, SECRET_KEY) }) const baseS3upload = promisify(S3.upload.bind(S3)) const readFilePr = promisify(fs.readFile) const readFile = filePath => { const absolutePath = path.resolve(__dirname, '../', filePath) return readFilePr(absolutePath, 'utf-8') } const uploadToS3 = (data, path, { dry } = {}) => { let promise = Promise.resolve() if (dry) { console.log('DRY RUN.') } else { promise = baseS3upload( Object.assign({}, UPLOAD_CONFIG, { Body: data, Key: path }) ) } console.log(`uploading ${data.length}B to ${path}`) return promise } const uploadFile = (data, fileName, options) => { return Promise.all( VERSION_TYPES.map(version => uploadToS3(data, `${BASE_PATH}${version}/uploadcare/${fileName}`, options) ) ) } // main part starts here Promise.all( pkg.files.map(filePath => { const name = path.basename(filePath) return Promise.all([readFile(name), name]) }) ) .then(files => Promise.all( files.map(([data, name]) => uploadFile(data, name, { dry: false })) ) ) .catch(error => { console.error('Error: \n', error.message) process.exit(1) })
require('dotenv').config() const AWS = require('aws-sdk') const path = require('path') const fs = require('fs') const { promisify } = require('util') const pkg = require('../package.json') const getVersionTypes = version => [ version, version.replace(/^(\d+\.\d+)\.\d+/, '$1.x'), version.replace(/^(\d+)\.\d+\.\d+/, '$1.x') ] const BASE_PATH = 'widget/' const VERSION_TYPES = getVersionTypes(pkg.version) const BUCKET = process.env.BUCKET const ACCESS_KEY = process.env.ACCESS_KEY const SECRET_KEY = process.env.SECRET_KEY if (!BUCKET || !ACCESS_KEY || !SECRET_KEY) { console.log("don't found credentials skip publish to s3") process.exit(0) } const UPLOAD_CONFIG = { ACL: 'public-read', Bucket: BUCKET, ContentType: 'application/javascript; charset=utf-8' } const S3 = new AWS.S3({ credentials: new AWS.Credentials(ACCESS_KEY, SECRET_KEY) }) const baseS3upload = promisify(S3.upload.bind(S3)) const readFilePr = promisify(fs.readFile) const readFile = filePath => { const absolutePath = path.resolve(__dirname, '../', filePath) return readFilePr(absolutePath, 'utf-8') } const uploadToS3 = (data, path, { dry } = {}) => { let promise = Promise.resolve() if (dry) { console.log('DRY RUN.') } else { promise = baseS3upload( Object.assign({}, UPLOAD_CONFIG, { Body: data, Key: path }) ) } console.log(`uploading ${data.length}B to ${path}`) return promise } const uploadFile = (data, fileName, options) => { return Promise.all( VERSION_TYPES.map(version => uploadToS3(data, `${BASE_PATH}${version}/uploadcare/${fileName}`, options) ) ) } // main part starts here Promise.all(pkg.files.map(name => Promise.all([readFile(name), name]))) .then(files => Promise.all(files.map(([data, name]) => uploadFile(data, name, { dry: false }))) ) .catch(error => { console.error('Error: \n', error.message) process.exit(1) })
JavaScript
0.000013
62eed47760a012473a76a2c7a502f93099d85074
Fix a deprecation notice (#13904)
scripts/release-build.js
scripts/release-build.js
'use strict'; const fs = require('fs').promises; const path = require('path'); const directory = './build/'; const verbatimFiles = ['LICENSE', 'README.md', 'index.d.ts', 'types.d.ts']; // Returns a string representing data ready for writing to JSON file function createDataBundle() { const bcd = require('../index.js'); const string = JSON.stringify(bcd); return string; } // Returns a promise for writing the data to JSON file async function writeData() { const dest = path.resolve(directory, 'data.json'); const data = createDataBundle(); await fs.writeFile(dest, data); } async function writeIndex() { const dest = path.resolve(directory, 'index.js'); const content = `module.exports = require("./data.json");\n`; await fs.writeFile(dest, content); } // Returns an array of promises for copying of all files that don't need transformation async function copyFiles() { for (const file of verbatimFiles) { const src = path.join('./', file); const dest = path.join(directory, file); await fs.copyFile(src, dest); } } function createManifest() { const full = require('../package.json'); const minimal = { main: 'index.js' }; const minimalKeys = [ 'name', 'version', 'description', 'repository', 'keywords', 'author', 'license', 'bugs', 'homepage', 'types', ]; for (const key of minimalKeys) { if (key in full) { minimal[key] = full[key]; } else { throw `Could not create a complete manifest! ${key} is missing!`; } } return JSON.stringify(minimal); } async function writeManifest() { const dest = path.resolve(directory, 'package.json'); const manifest = createManifest(); await fs.writeFile(dest, manifest); } async function main() { // Remove existing files, if there are any await fs .rm(directory, { force: true, recursive: true, }) .catch(e => { // Missing folder is not an issue since we wanted to delete it anyway if (e.code !== 'ENOENT') throw e; }); // Crate a new directory await fs.mkdir(directory); await writeManifest(); await writeData(); await writeIndex(); await copyFiles(); console.log('Data bundle is ready'); } // This is needed because NodeJS does not support top-level await. // Also, make sure to log all errors and exit with failure code. main().catch(e => { console.error(e); process.exit(1); });
'use strict'; const fs = require('fs').promises; const path = require('path'); const directory = './build/'; const verbatimFiles = ['LICENSE', 'README.md', 'index.d.ts', 'types.d.ts']; // Returns a string representing data ready for writing to JSON file function createDataBundle() { const bcd = require('../index.js'); const string = JSON.stringify(bcd); return string; } // Returns a promise for writing the data to JSON file async function writeData() { const dest = path.resolve(directory, 'data.json'); const data = createDataBundle(); await fs.writeFile(dest, data); } async function writeIndex() { const dest = path.resolve(directory, 'index.js'); const content = `module.exports = require("./data.json");\n`; await fs.writeFile(dest, content); } // Returns an array of promises for copying of all files that don't need transformation async function copyFiles() { for (const file of verbatimFiles) { const src = path.join('./', file); const dest = path.join(directory, file); await fs.copyFile(src, dest); } } function createManifest() { const full = require('../package.json'); const minimal = { main: 'index.js' }; const minimalKeys = [ 'name', 'version', 'description', 'repository', 'keywords', 'author', 'license', 'bugs', 'homepage', 'types', ]; for (const key of minimalKeys) { if (key in full) { minimal[key] = full[key]; } else { throw `Could not create a complete manifest! ${key} is missing!`; } } return JSON.stringify(minimal); } async function writeManifest() { const dest = path.resolve(directory, 'package.json'); const manifest = createManifest(); await fs.writeFile(dest, manifest); } async function main() { // Remove existing files, if there are any await fs .rmdir(directory, { force: true, recursive: true, }) .catch(e => { // Missing folder is not an issue since we wanted to delete it anyway if (e.code !== 'ENOENT') throw e; }); // Crate a new directory await fs.mkdir(directory); await writeManifest(); await writeData(); await writeIndex(); await copyFiles(); console.log('Data bundle is ready'); } // This is needed because NodeJS does not support top-level await. // Also, make sure to log all errors and exit with failure code. main().catch(e => { console.error(e); process.exit(1); });
JavaScript
0.000207
231173a99ffe129efac872a6646e61684924c309
Fix babel always enabled HMR
src/internals/webpack/features/babel.js
src/internals/webpack/features/babel.js
import findCacheDir from 'find-cache-dir'; import findBabelConfig from 'find-babel-config'; import frameworkMetadata from '../../../shared/framework-metadata'; import { resolveProject } from '../../../shared/resolve'; import { getDefault } from '../../../shared/util/ModuleUtil'; import BaseFeature from '../BaseFeature'; export default class BabelFeature extends BaseFeature { getFeatureName() { return 'babel'; } visit(webpack) { webpack.injectRules({ test: BaseFeature.FILE_TYPE_JS, loader: 'babel-loader', exclude: /node_modules/, options: this.getTransformedBabelConfig(), }); } getTransformedBabelConfig() { const config = this.getBabelConfig(); // use the app's .babelrc if (!config) { return config; } if (this.isDev()) { config.presets.push('react-hmre'); } // This is a feature of `babel-loader` for webpack (not Babel itself). // It enables caching build results in ./node_modules/.cache/reworkjs/babel // directory for faster rebuilds. We use findCacheDir() because of: // https://github.com/facebookincubator/create-react-app/issues/483 config.cacheDirectory = `${findCacheDir({ name: frameworkMetadata.name, })}/babel`; return config; } getBabelConfig() { // FIXME note: might break with Babel 7 due to new support for babelrc.js const { config } = findBabelConfig.sync(resolveProject('.')); if (config == null) { return getDefault(this.getOptionalDependency('@reworkjs/babel-preset-reworkjs'))(); } // no need to load it, babel will do it on its own. return null; } }
import findCacheDir from 'find-cache-dir'; import findBabelConfig from 'find-babel-config'; import frameworkMetadata from '../../../shared/framework-metadata'; import { resolveProject } from '../../../shared/resolve'; import { getDefault } from '../../../shared/util/ModuleUtil'; import BaseFeature from '../BaseFeature'; export default class BabelFeature extends BaseFeature { getFeatureName() { return 'babel'; } visit(webpack) { webpack.injectRules({ test: BaseFeature.FILE_TYPE_JS, loader: 'babel-loader', exclude: /node_modules/, options: this.getTransformedBabelConfig(), }); } getTransformedBabelConfig() { const config = this.getBabelConfig(); // use the app's .babelrc if (!config) { return config; } if (this.isDev) { config.presets.push('react-hmre'); } // This is a feature of `babel-loader` for webpack (not Babel itself). // It enables caching build results in ./node_modules/.cache/reworkjs/babel // directory for faster rebuilds. We use findCacheDir() because of: // https://github.com/facebookincubator/create-react-app/issues/483 config.cacheDirectory = `${findCacheDir({ name: frameworkMetadata.name, })}/babel`; return config; } getBabelConfig() { // FIXME note: might break with Babel 7 due to new support for babelrc.js const { config } = findBabelConfig.sync(resolveProject('.')); if (config == null) { return getDefault(this.getOptionalDependency('@reworkjs/babel-preset-reworkjs'))(); } // no need to load it, babel will do it on its own. return null; } }
JavaScript
0
c980d16691cc1b13f9cbf76c2d3819cbe674df66
enable source maps on production
config/webpack.js
config/webpack.js
import path from './path' import * as Env from './env' import webpack from 'webpack' import ProgressPlugin from '../src/hacks/webpack-progress' let config = { context: path('src'), resolve: { alias: { bemuse: path('src'), }, extensions: ['', '.webpack.js', '.web.js', '.js', '.jsx'] }, resolveLoader: { alias: { bemuse: path('src'), }, }, entry: { boot: './boot' }, output: { path: path('dist', 'build'), publicPath: 'build/', filename: '[name].js', chunkFilename: '[name]-[chunkhash].js', }, devServer: { contentBase: false, publicPath: '/build/', stats: { colors: true }, }, module: { loaders: [ { test: /\.jsx?$/, include: [path('src'), path('spec')], loader: 'babel?modules=common&experimental=true', }, { test: /\.pegjs$/, loader: 'pegjs', }, { test: /\.scss$/, loader: 'style!css!autoprefixer?browsers=last 2 version' + '!sass?outputStyle=expanded' + '!bemuse/hacks/sass-import-rewriter', }, { test: /\.css$/, loader: 'style!css!autoprefixer?browsers=last 2 version', }, { test: /\.jade$/, loader: 'jade', }, { test: /\.png$/, loader: 'url-loader?limit=100000&mimetype=image/png', }, { test: /\.jpg$/, loader: 'file-loader', }, { test: /\.(?:mp3|mp4|ogg|m4a)$/, loader: 'file-loader', }, { test: /\.(otf|eot|svg|ttf|woff|woff2)(?:$|\?)/, loader: 'url-loader?limit=8192' }, ], postLoaders: [], preLoaders: [], }, plugins: [ new CompileProgressPlugin(), new ProgressPlugin(), ], } function CompileProgressPlugin() { var old = '' return new webpack.ProgressPlugin(function(percentage, message) { var text = '[' for (var i = 0; i < 20; i++) text += percentage >= i / 20 ? '=' : ' ' text += '] ' + message var clear = '' for (i = 0; i < old.length; i++) clear += '\r \r' process.stderr.write(clear + text) old = text }) } if (process.env.SOURCE_MAPS === 'true' || Env.production()) { config.devtool = 'source-map' } if (Env.test() || process.env.BEMUSE_COV === 'true') { config.module.preLoaders.push({ test: /\.js$/, include: [path('src')], exclude: [ path('src', 'test'), path('src', 'polyfill'), path('src', 'boot', 'loader.js'), ], loader: 'isparta-instrumenter', }) } if (Env.production()) { config.plugins.push( new webpack.optimize.UglifyJsPlugin(), new webpack.optimize.OccurenceOrderPlugin() ) } export default config
import path from './path' import * as Env from './env' import webpack from 'webpack' import ProgressPlugin from '../src/hacks/webpack-progress' let config = { context: path('src'), resolve: { alias: { bemuse: path('src'), }, extensions: ['', '.webpack.js', '.web.js', '.js', '.jsx'] }, resolveLoader: { alias: { bemuse: path('src'), }, }, entry: { boot: './boot' }, output: { path: path('dist', 'build'), publicPath: 'build/', filename: '[name].js', chunkFilename: '[name]-[chunkhash].js', }, devServer: { contentBase: false, publicPath: '/build/', stats: { colors: true }, }, module: { loaders: [ { test: /\.jsx?$/, include: [path('src'), path('spec')], loader: 'babel?modules=common&experimental=true', }, { test: /\.pegjs$/, loader: 'pegjs', }, { test: /\.scss$/, loader: 'style!css!autoprefixer?browsers=last 2 version' + '!sass?outputStyle=expanded' + '!bemuse/hacks/sass-import-rewriter', }, { test: /\.css$/, loader: 'style!css!autoprefixer?browsers=last 2 version', }, { test: /\.jade$/, loader: 'jade', }, { test: /\.png$/, loader: 'url-loader?limit=100000&mimetype=image/png', }, { test: /\.jpg$/, loader: 'file-loader', }, { test: /\.(?:mp3|mp4|ogg|m4a)$/, loader: 'file-loader', }, { test: /\.(otf|eot|svg|ttf|woff|woff2)(?:$|\?)/, loader: 'url-loader?limit=8192' }, ], postLoaders: [], preLoaders: [], }, plugins: [ new CompileProgressPlugin(), new ProgressPlugin(), ], } function CompileProgressPlugin() { var old = '' return new webpack.ProgressPlugin(function(percentage, message) { var text = '[' for (var i = 0; i < 20; i++) text += percentage >= i / 20 ? '=' : ' ' text += '] ' + message var clear = '' for (i = 0; i < old.length; i++) clear += '\r \r' process.stderr.write(clear + text) old = text }) } if (process.env.SOURCE_MAPS === 'true') { config.devtool = 'source-map' } if (Env.test() || process.env.BEMUSE_COV === 'true') { config.module.preLoaders.push({ test: /\.js$/, include: [path('src')], exclude: [ path('src', 'test'), path('src', 'polyfill'), path('src', 'boot', 'loader.js'), ], loader: 'isparta-instrumenter', }) } if (Env.production()) { config.plugins.push( new webpack.optimize.UglifyJsPlugin(), new webpack.optimize.OccurenceOrderPlugin() ) } export default config
JavaScript
0.000001
abc24a1bf969fbac588078e056ffc238c8b04a3a
Revert "Apply eslint feedback to models/question.js."
models/question.js
models/question.js
'use strict'; module.exports = function(sequelize, DataTypes) { var Question = sequelize.define('Question', { title: DataTypes.TEXT }, { classMethods: { associate: function(models) { // associations can be defined here models.Question.hasMany(models.Choice); models.Question.hasMany(models.Response); } } }); return Question; };
function exports(sequelize, DataTypes) { const Question = sequelize.define('Question', { title: DataTypes.TEXT, }, { classMethods: { associate(models) { // associations can be defined here models.Question.hasMany(models.Choice); models.Question.hasMany(models.Response); }, }, }); return Question; } module.exports = exports;
JavaScript
0
73f357e4ed6f4e62a196282ce74a9ce43dba0630
Update moves.js
mods/nuv2/moves.js
mods/nuv2/moves.js
exports.BattleMovedex = { "waterpulse": { inherit: true, basePower: 80 } }, "submission": { inherit: true, accuracy: 100, basePower: 120, category: "Physical", secondary: { chance: 10, volatileStatus: 'flinch' } }, "lunardance": { num: 461, accuracy: true, basePower: 0, category: "Status", desc: "The user faints and the Pokemon brought out to replace it has its HP and PP fully restored along with having any major status condition cured. Fails if the user is the last unfainted Pokemon in its party.", shortDesc: "User faints. Replacement is fully healed, with PP.", id: "lunardance", isViable: true, name: "Lunar Dance", pp: 20, priority: 0, isSnatchable: true, boosts: { spa: 1, spe: 1 }, secondary: false, target: "self", type: "Psychic" }, "airslash": { inherit: true, basePower: 90, } }, };
exports.BattleMovedex = { "waterpulse": { inherit: true, basePower: 80 } }, "submission": { inherit: true, accuracy: 100, basePower: 120, category: "Physical", secondary: { chance: 10, volatileStatus: 'flinch' } }, "lunardance": { num: 461, accuracy: true, basePower: 0, category: "Status", desc: "The user faints and the Pokemon brought out to replace it has its HP and PP fully restored along with having any major status condition cured. Fails if the user is the last unfainted Pokemon in its party.", shortDesc: "User faints. Replacement is fully healed, with PP.", id: "lunardance", isViable: true, name: "Lunar Dance", pp: 20, priority: 0, isSnatchable: true, boosts: { spa: 1, spe: 1, }, secondary: false, target: "self", type: "Psychic" }, "airslash": { inherit: true, basePower: 90, } }, };
JavaScript
0.000001
db2f5186a6abf20b4bdab6628671ab5da38a0c3a
Make ships slower
src/common/Ship.js
src/common/Ship.js
'use strict'; const Serializer = require('incheon').serialize.Serializer; const DynamicObject = require('incheon').serialize.DynamicObject; const Point = require('incheon').Point; class Ship extends DynamicObject { static get netScheme() { return Object.assign({ showThrust: { type: Serializer.TYPES.INT32 } }, super.netScheme); } toString() { return `${this.isBot?'Bot':'Player'}::Ship::${super.toString()}`; } get bendingAngleLocalMultiple() { return 0.0; } copyFrom(sourceObj) { super.copyFrom(sourceObj); this.showThrust = sourceObj.showThrust; } syncTo(other) { super.syncTo(other); this.showThrust = other.showThrust; } constructor(id, gameEngine, x, y) { super(id, x, y); this.class = Ship; this.gameEngine = gameEngine; this.showThrust = 0; }; destroy() { if (this.fireLoop) { this.fireLoop.destroy(); } } get maxSpeed() { return 3.0; } attachAI() { this.isBot = true; this.gameEngine.on('preStep', ()=>{ this.steer(); }); let fireLoopTime = Math.round(250 + Math.random() * 100); this.fireLoop = this.gameEngine.timer.loop(fireLoopTime, () => { if (this.target && this.distanceToTarget(this.target) < 400) { this.gameEngine.makeMissile(this); } }); } distanceToTarget(target) { let dx = this.x - target.x; let dy = this.y - target.y; return Math.sqrt(dx * dx + dy * dy); } steer() { let closestTarget = null; let closestDistance = Infinity; for (let objId of Object.keys(this.gameEngine.world.objects)) { let obj = this.gameEngine.world.objects[objId]; let distance = this.distanceToTarget(obj); if (obj != this && distance < closestDistance) { closestTarget = obj; closestDistance = distance; } } this.target = closestTarget; if (this.target) { let desiredVelocity = new Point(); desiredVelocity.copyFrom(this.target).subtract(this.x, this.y); let turnRight = -shortestArc(Math.atan2(desiredVelocity.y, desiredVelocity.x), Math.atan2(Math.sin(this.angle*Math.PI/180), Math.cos(this.angle*Math.PI/180))); if (turnRight > 0.05) { this.isRotatingRight = true; } else if (turnRight < -0.05) { this.isRotatingLeft = true; } else { this.isAccelerating = true; this.showThrust = 5; } } } } function shortestArc(a, b) { if (Math.abs(b-a) < Math.PI) return b-a; if (b>a) return b-a-Math.PI*2; return b-a+Math.PI*2; } module.exports = Ship;
'use strict'; const Serializer = require('incheon').serialize.Serializer; const DynamicObject = require('incheon').serialize.DynamicObject; const Point = require('incheon').Point; class Ship extends DynamicObject { static get netScheme() { return Object.assign({ showThrust: { type: Serializer.TYPES.INT32 } }, super.netScheme); } toString() { return `${this.isBot?'Bot':'Player'}::Ship::${super.toString()}`; } get bendingAngleLocalMultiple() { return 0.0; } copyFrom(sourceObj) { super.copyFrom(sourceObj); this.showThrust = sourceObj.showThrust; } syncTo(other) { super.syncTo(other); this.showThrust = other.showThrust; } constructor(id, gameEngine, x, y) { super(id, x, y); this.class = Ship; this.gameEngine = gameEngine; this.showThrust = 0; }; destroy() { if (this.fireLoop) { this.fireLoop.destroy(); } } get maxSpeed() { return 5.0; } attachAI() { this.isBot = true; this.gameEngine.on('preStep', ()=>{ this.steer(); }); let fireLoopTime = Math.round(250 + Math.random() * 100); this.fireLoop = this.gameEngine.timer.loop(fireLoopTime, () => { if (this.target && this.distanceToTarget(this.target) < 400) { this.gameEngine.makeMissile(this); } }); } distanceToTarget(target) { let dx = this.x - target.x; let dy = this.y - target.y; return Math.sqrt(dx * dx + dy * dy); } steer() { let closestTarget = null; let closestDistance = Infinity; for (let objId of Object.keys(this.gameEngine.world.objects)) { let obj = this.gameEngine.world.objects[objId]; let distance = this.distanceToTarget(obj); if (obj != this && distance < closestDistance) { closestTarget = obj; closestDistance = distance; } } this.target = closestTarget; if (this.target) { let desiredVelocity = new Point(); desiredVelocity.copyFrom(this.target).subtract(this.x, this.y); let turnRight = -shortestArc(Math.atan2(desiredVelocity.y, desiredVelocity.x), Math.atan2(Math.sin(this.angle*Math.PI/180), Math.cos(this.angle*Math.PI/180))); if (turnRight > 0.05) { this.isRotatingRight = true; } else if (turnRight < -0.05) { this.isRotatingLeft = true; } else { this.isAccelerating = true; this.showThrust = 5; } } } } function shortestArc(a, b) { if (Math.abs(b-a) < Math.PI) return b-a; if (b>a) return b-a-Math.PI*2; return b-a+Math.PI*2; } module.exports = Ship;
JavaScript
0.000301
075e1e2c933cfa30d41b124d08136a5c551ad363
Add percentage to sentiment
modules/concern.js
modules/concern.js
/** * concern.js * * !concern * Toggles whether the bot should interrupt charged conversations * with an unhelpful message. */ var isEmotional = require('emotional_alert') var nox = false var colors = require('irc').colors var verbose = false // TODO: cvar module.exports = { commands: { sentiment: { help: 'Runs a phrase through very nuanced sentiment analysis', command: (bot, msg) => { let result = isEmotional(msg.body) if (result.bayes) { let percentage = (result.bayes.proba * 100).toFixed(2) return [ result.bayes.prediction, colors.wrap('light_gray', `(${percentage}%)`) ].join(' ') } return 'no sentiment found' } }, rawconcern: { help: 'Runs a phrase through the emotional alert system', command: (bot, msg) => { return JSON.stringify(isEmotional(msg.body)) } }, concern: { help: 'Toggles announcements of concern', command: function () { if (!nox) { nox = true return 'adopting air of unconcern' } nox = false return 'concerning myself with matters' } } }, events: { message: function (bot, nick, to, text) { if (!nox) { var x = isEmotional(text) if (x.emotional) { if (x.winner) { var adj = { 0: '', 1: 'slightly ', 2: 'rather ', 3: 'quite ', 4: 'very ', 5: 'extremely ', 6: 'copiously ', 7: 'agonizingly ' } x.adj = adj[x.emotional] === undefined ? 'a tad ' : adj[x.emotional] switch (x.winner) { case 'anger': x.hwinner = 'angry' break case 'stress': x.hwinner = 'stressed' break case 'sad': /* falls through */ default: x.hwinner = x.winner } bot.shout(to, nick + ': you seem ' + x.adj + x.hwinner + ' (score: ' + x.emotional + ')') } else if (verbose) { // danger phrase bot.shout(to, nick + ': that is a worrying thing to say') } } } } } }
/** * concern.js * * !concern * Toggles whether the bot should interrupt charged conversations * with an unhelpful message. */ var isEmotional = require('emotional_alert') var nox = false var verbose = false // TODO: cvar module.exports = { commands: { sentiment: { help: 'Runs a phrase through very nuanced sentiment analysis', command: (bot, msg) => { let result = isEmotional(msg.body) if (result.bayes.prediction) return result.bayes.prediction return 'no sentiment found' } }, rawconcern: { help: 'Runs a phrase through the emotional alert system', command: (bot, msg) => { return JSON.stringify(isEmotional(msg.body)) } }, concern: { help: 'Toggles announcements of concern', command: function () { if (!nox) { nox = true return 'adopting air of unconcern' } nox = false return 'concerning myself with matters' } } }, events: { message: function (bot, nick, to, text) { if (!nox) { var x = isEmotional(text) if (x.emotional) { if (x.winner) { var adj = { 0: '', 1: 'slightly ', 2: 'rather ', 3: 'quite ', 4: 'very ', 5: 'extremely ', 6: 'copiously ', 7: 'agonizingly ' } x.adj = adj[x.emotional] === undefined ? 'a tad ' : adj[x.emotional] switch (x.winner) { case 'anger': x.hwinner = 'angry' break case 'stress': x.hwinner = 'stressed' break case 'sad': /* falls through */ default: x.hwinner = x.winner } bot.shout(to, nick + ': you seem ' + x.adj + x.hwinner + ' (score: ' + x.emotional + ')') } else if (verbose) { // danger phrase bot.shout(to, nick + ': that is a worrying thing to say') } } } } } }
JavaScript
0.999979
e594c41dc2a51be0b9aed0c23a64a39cb866c17b
Remove test.only
test.js
test.js
'use strict' var test = require('tape') var read = require('read-all-stream') var toStream = require('string-to-stream') var child = require('child_process') var htmlify = require('./') test('api', function (t) { t.plan(3) var html = toStream('var foo = "bar"').pipe(htmlify()) read(html, 'utf8', function (err, html) { if (err) return t.end(err) t.ok(/<html>/.test(html)) t.ok(~html.indexOf('var foo = "bar"')) t.notOk(~html.indexOf('inline')) }) }) test('cli', function (t) { t.plan(1) child.exec('echo "THESCRIPT" | node cli.js', function (err, stdout) { if (err) return t.end(err) t.ok(~stdout.indexOf('THESCRIPT')) }) })
'use strict' var test = require('tape') var read = require('read-all-stream') var toStream = require('string-to-stream') var child = require('child_process') var htmlify = require('./') test.only('api', function (t) { t.plan(3) var html = toStream('var foo = "bar"').pipe(htmlify()) read(html, 'utf8', function (err, html) { if (err) return t.end(err) t.ok(/<html>/.test(html)) t.ok(~html.indexOf('var foo = "bar"')) t.notOk(~html.indexOf('inline')) }) }) test('cli', function (t) { t.plan(1) child.exec('echo "THESCRIPT" | node cli.js', function (err, stdout) { if (err) return t.end(err) t.ok(~stdout.indexOf('THESCRIPT')) }) })
JavaScript
0.000001
e05f001cc78be58b3b126aed9878f74222127479
Check for property and value support for CSS custom properites (#2387)
feature-detects/css/customproperties.js
feature-detects/css/customproperties.js
/*! { "name": "CSS Custom Properties", "property": "customproperties", "caniuse": "css-variables", "tags": ["css"], "builderAliases": ["css_customproperties"], "notes": [{ "name": "MDN Docs", "href": "https://developer.mozilla.org/en-US/docs/Web/CSS/--*" },{ "name": "W3C Spec", "href": "https://drafts.csswg.org/css-variables/" }] } !*/ define(['Modernizr'], function(Modernizr) { var supportsFn = (window.CSS && window.CSS.supports.bind(window.CSS)) || (window.supportsCSS); Modernizr.addTest('customproperties', !!supportsFn && (supportsFn('--f:0') || supportsFn('--f', 0))); });
/*! { "name": "CSS Custom Properties", "property": "customproperties", "caniuse": "css-variables", "tags": ["css"], "builderAliases": ["css_customproperties"], "notes": [{ "name": "MDN Docs", "href": "https://developer.mozilla.org/en-US/docs/Web/CSS/--*" },{ "name": "W3C Spec", "href": "https://drafts.csswg.org/css-variables/" }] } !*/ define(['Modernizr'], function(Modernizr) { var supportsFn = (window.CSS && window.CSS.supports.bind(window.CSS)) || (window.supportsCSS); Modernizr.addTest('customproperties', !!supportsFn && supportsFn('--f:0')); });
JavaScript
0
b0c8d20c6e20db218c2a7afea4f18dada911aa70
document behaviour of entrypoint adder method
webpack/addEntrypoints.js
webpack/addEntrypoints.js
/** * Merge in `entry` array to a webpack config * * :WARNING: the order in which you apply multiple calls to this method matters! * Webpack is rather particular about the order of entrypoints. * We do the concatenation in reverse so that entries added later come last, which * means the final (app-specific) entrypoint can be added in the dependant project * after all the core entrypoints have been injected in shared configs. * * @see withEntry.js * * @package: Everledger JS Toolchain * @author: pospi <sam@everledger.io> * @since: 2016-10-06 * @flow */ const { curry } = require('ramda'); const rConcatArrayKey = require('../helpers/rConcatArrayKey'); module.exports = curry(entryFile => rConcatArrayKey('entry', entryFile));
/** * Merge in `entry` array to a webpack config * * @see withEntry.js * * @package: Everledger JS Toolchain * @author: pospi <sam@everledger.io> * @since: 2016-10-06 * @flow */ const { curry } = require('ramda'); const rConcatArrayKey = require('../helpers/rConcatArrayKey'); module.exports = curry(entryFile => rConcatArrayKey('entry', entryFile));
JavaScript
0
5ef67b34d911cb245c77d221a2358352a12d0910
Changing 409 to 400
features/step_definitions/mypassword.js
features/step_definitions/mypassword.js
const { defineSupportCode } = require('cucumber'); const chai = require('chai'); const dhis2 = require('../support/utils.js'); const assert = chai.assert; defineSupportCode(function ({Given, When, Then, Before, After}) { Before({tags: '@createUser'}, function () { this.userId = dhis2.generateUniqIds(); this.requestData = { id: this.userId, firstName: 'Bobby', surname: 'Tables', userCredentials: { username: 'bobby', password: '!XPTOqwerty1', userInfo: { id: this.userId } } }; this.userUsername = this.requestData.userCredentials.username; this.userPassword = this.requestData.userCredentials.password; return dhis2.sendApiRequest({ url: dhis2.generateUrlForResourceType(dhis2.resourceTypes.USER), requestData: this.requestData, method: 'post', onSuccess: function (response) { assert.equal(response.status, 200, 'Status should be 200'); } }); }); After({tags: '@createUser'}, function () { const world = this; return dhis2.sendApiRequest({ url: dhis2.generateUrlForResourceTypeWithId(dhis2.resourceTypes.USER, world.userId), method: 'delete', onSuccess: function (response) { assert.equal(response.status, 200, 'Status should be 200'); return dhis2.sendApiRequest({ url: dhis2.generateUrlForResourceTypeWithId(dhis2.resourceTypes.USER, world.userId), onError: function (error) { assert.equal(error.response.status, 404, 'Status should be 404'); } }); } }); }); When(/^I change my password to (.+)$/, function (password) { const world = this; world.oldPassword = world.userPassword; world.newPassword = password; return dhis2.sendApiRequest({ url: dhis2.apiEndpoint() + '/me', onSuccess: function (response) { assert.equal(response.status, 200, 'Status should be 200'); world.requestData = response.data; world.requestData.userCredentials.password = password; return dhis2.sendApiRequest({ url: dhis2.apiEndpoint() + '/me', requestData: world.requestData, method: 'put', onSuccess: function (response) { world.userPassword = password; }, preventDefaultOnError: true }, world); } }, world); }); Then(/^I should see a message that my password was successfully changed$/, function () { assert.equal(this.responseStatus, 200, 'Status should be 200'); }); Then(/^I should not be able to login using the old password$/, function () { this.userPassword = this.oldPassword; return dhis2.sendApiRequest({ url: dhis2.apiEndpoint() + '/me', onError: function (error) { assert.equal(error.response.status, 401, 'Authentication should have failed.'); } }, this); }); Then(/^I should be able to login using the new password$/, function () { this.userPassword = this.newPassword; return dhis2.sendApiRequest({ url: dhis2.apiEndpoint() + '/me', onSuccess: function (response) { assert.equal(response.status, 200, 'Response Status was not ok'); assert.isOk(response.data.id, 'User id should have been returned'); } }, this); }); Then(/^I should receive error message (.+)$/, function (errorMessage) { checkForErrorMessage(errorMessage, this); }); Given(/^My username is (.+)$/, function (username) { assert.equal(this.userUsername, username, 'Username should be: ' + username); }); }); const checkForErrorMessage = (message, world) => { assert.equal(world.responseStatus, 400, 'Status should be 400'); assert.equal(world.responseData.status, 'ERROR', 'Status should be ERROR'); assert.equal(world.responseData.message, message); };
const { defineSupportCode } = require('cucumber'); const chai = require('chai'); const dhis2 = require('../support/utils.js'); const assert = chai.assert; defineSupportCode(function ({Given, When, Then, Before, After}) { Before({tags: '@createUser'}, function () { this.userId = dhis2.generateUniqIds(); this.requestData = { id: this.userId, firstName: 'Bobby', surname: 'Tables', userCredentials: { username: 'bobby', password: '!XPTOqwerty1', userInfo: { id: this.userId } } }; this.userUsername = this.requestData.userCredentials.username; this.userPassword = this.requestData.userCredentials.password; return dhis2.sendApiRequest({ url: dhis2.generateUrlForResourceType(dhis2.resourceTypes.USER), requestData: this.requestData, method: 'post', onSuccess: function (response) { assert.equal(response.status, 200, 'Status should be 200'); } }); }); After({tags: '@createUser'}, function () { const world = this; return dhis2.sendApiRequest({ url: dhis2.generateUrlForResourceTypeWithId(dhis2.resourceTypes.USER, world.userId), method: 'delete', onSuccess: function (response) { assert.equal(response.status, 200, 'Status should be 200'); return dhis2.sendApiRequest({ url: dhis2.generateUrlForResourceTypeWithId(dhis2.resourceTypes.USER, world.userId), onError: function (error) { assert.equal(error.response.status, 404, 'Status should be 404'); } }); } }); }); When(/^I change my password to (.+)$/, function (password) { const world = this; world.oldPassword = world.userPassword; world.newPassword = password; return dhis2.sendApiRequest({ url: dhis2.apiEndpoint() + '/me', onSuccess: function (response) { assert.equal(response.status, 200, 'Status should be 200'); world.requestData = response.data; world.requestData.userCredentials.password = password; return dhis2.sendApiRequest({ url: dhis2.apiEndpoint() + '/me', requestData: world.requestData, method: 'put', onSuccess: function (response) { world.userPassword = password; }, preventDefaultOnError: true }, world); } }, world); }); Then(/^I should see a message that my password was successfully changed$/, function () { assert.equal(this.responseStatus, 200, 'Status should be 200'); }); Then(/^I should not be able to login using the old password$/, function () { this.userPassword = this.oldPassword; return dhis2.sendApiRequest({ url: dhis2.apiEndpoint() + '/me', onError: function (error) { assert.equal(error.response.status, 401, 'Authentication should have failed.'); } }, this); }); Then(/^I should be able to login using the new password$/, function () { this.userPassword = this.newPassword; return dhis2.sendApiRequest({ url: dhis2.apiEndpoint() + '/me', onSuccess: function (response) { assert.equal(response.status, 200, 'Response Status was not ok'); assert.isOk(response.data.id, 'User id should have been returned'); } }, this); }); Then(/^I should receive error message (.+)$/, function (errorMessage) { checkForErrorMessage(errorMessage, this); }); Given(/^My username is (.+)$/, function (username) { assert.equal(this.userUsername, username, 'Username should be: ' + username); }); }); const checkForErrorMessage = (message, world) => { assert.equal(world.responseStatus, 409, 'Status should be 409'); assert.equal(world.responseData.status, 'ERROR', 'Status should be ERROR'); assert.equal(world.responseData.message, message); };
JavaScript
0.999685
7d5d327f1582ebd2b0569b4d01fb72e4b5a47a02
change build api name
newspaperjs/lib/source.js
newspaperjs/lib/source.js
const _ = require('lodash') const extractor = require('./extractor'); const article = require('./article'); const network = require('./network') const path = require('path') /** * * @param {string} url - News website url you want to build * @param {array} cateOfInterest - News categories you interested in * @return {promise} */ exports.getCategoriesUrl = async function(url, cateOfInterest) { return await extractor.getCategoryUrls(url, cateOfInterest); } /** * @param {array} categoriesUrl - Url of categories you interested in * @return {promise} */ exports.getArticlesUrl = async function(categoriesUrl){ let obj = {}, finalResult = []; if(categoriesUrl.length > 0){ for(let cateUrl of categoriesUrl){ let result = eachCat(cateUrl); _.set(obj, 'category', extractor.getCategoryName(cateUrl)); _.set(obj, 'articlesUrl', await result); finalResult.push(obj); } return finalResult; }else{ return new Error("Unable to get categories url...") } } function eachCat(cateUrl){ return extractor.getArticlesUrl(cateUrl) }
const _ = require('lodash') const extractor = require('./extractor'); const article = require('./article'); const network = require('./network') const path = require('path') /** * * @param {string} url - News website url you want to build * @param {array} cateOfInterest - News categories you interested in * @return {promise} */ exports.getCategoriesUrl = async function(url, cateOfInterest) { return await extractor.getCategoryUrls(url, cateOfInterest); } /** * @param {array} categoriesUrl - Url of categories you interested in * @return {promise} */ exports.getArticleUrl = async function(categoriesUrl){ let obj = {}, finalResult = []; if(categoriesUrl.length > 0){ for(let cateUrl of categoriesUrl){ let result = eachCat(cateUrl); _.set(obj, 'category', extractor.getCategoryName(cateUrl)); _.set(obj, 'articlesUrl', await result); finalResult.push(obj); } return finalResult; }else{ return new Error("Unable to get categories url...") } } function eachCat(cateUrl){ return extractor.getArticlesUrl(cateUrl) }
JavaScript
0.000001
c982f8cebf53ed624ab250f7051f4c924e692780
Use chat_random; add post command.
scripts/almanaccheler.js
scripts/almanaccheler.js
// Description: // Script per inviare carte del mercante in fiera // // Commands: // // Notes: // <optional notes required for the script> // // Author: // batt module.exports = function (robot) { var room = "C02AN2FPY" // chat_random var CronJob = require('cron').CronJob; var job = new CronJob('00 30 09 * * 1-5', function() { var img_list = robot.brain.get('img_list') || null; if (img_list === null) { return; } var idx = robot.brain.get('img_idx'); var max_idx= robot.brain.get('img_cnt'); robot.messageRoom(room, img_list[idx]); idx++; if (idx >= max_idx) { idx = 0; } robot.brain.set('img_idx', idx); }, function () { /* This function is executed when the job stops */ }, true, /* Start the job right now */ "Europe/Rome" /* Time zone of this job. */ ); job.start(); var shuffle = function(a) { var j, x, i; for (i = a.length; i; i--) { j = Math.floor(Math.random() * i); x = a[i - 1]; a[i - 1] = a[j]; a[j] = x; } return a; } robot.respond(/load (.*)/i, function (res) { var url = res.match[1].trim() robot.http(url) .get()(function(err, resp, body) { if (err) { res.reply(err); } else { var img = body.split('\n'); img = shuffle(img); robot.brain.set('img_list', img); robot.brain.set('img_idx', 0); robot.brain.set('img_cnt', img.length); res.reply("Caricate " + img.length + " immagini:\n" + img.join('\n')); } }); }); var randomImg = function(res, chat_room) { var img_list = robot.brain.get('img_list') || null; if (img_list === null) { res.reply("Immagini non impostate!"); return; } var rnd = Math.floor(Math.random()*img_list.length); if (chat_room != null) { res.reply(img_list[rnd]); } else { robot.messageRoom(chat_room, img_list[rnd]); } } robot.respond(/pug bomb/i, function (res) { randomImg(res); }); robot.respond(/pug me/i, function (res) { randomImg(res); }); robot.respond(/ciao/i, function (res) { randomImg(res); }); robot.respond(/post (.*)/i, function (res) { var chat_room = res.match[1].trim(); randomImg(res, chat_room); }); robot.respond(/dici (.*)/i, function (res) { if (res.message.user.name == "batt") { robot.messageRoom(room, res.match[1].trim()); } }); };
// Description: // Script per inviare carte del mercante in fiera // // Commands: // // Notes: // <optional notes required for the script> // // Author: // batt module.exports = function (robot) { var room = "G4GJDGVE3" var CronJob = require('cron').CronJob; var job = new CronJob('00 30 * * * 1-5', function() { var img_list = robot.brain.get('img_list') || null; if (img_list === null) { return; } var idx = robot.brain.get('img_idx'); var max_idx= robot.brain.get('img_cnt'); robot.messageRoom(room, img_list[idx]); idx++; if (idx >= max_idx) { idx = 0; } robot.brain.set('img_idx', idx); }, function () { /* This function is executed when the job stops */ }, true, /* Start the job right now */ "Europe/Rome" /* Time zone of this job. */ ); job.start(); var shuffle = function(a) { var j, x, i; for (i = a.length; i; i--) { j = Math.floor(Math.random() * i); x = a[i - 1]; a[i - 1] = a[j]; a[j] = x; } return a; } robot.respond(/load (.*)/i, function (res) { var url = res.match[1].trim() robot.http(url) .get()(function(err, resp, body) { if (err) { res.reply(err); } else { var img = body.split('\n'); img = shuffle(img); robot.brain.set('img_list', img); robot.brain.set('img_idx', 0); robot.brain.set('img_cnt', img.length); res.reply("Caricate " + img.length + " immagini:\n" + img.join('\n')); } }); }); var randomImg = function(res) { var img_list = robot.brain.get('img_list') || null; if (img_list === null) { res.reply("Immagini non impostate!"); return; } var rnd = Math.floor(Math.random()*img_list.length); res.reply(img_list[rnd]); } robot.respond(/pug bomb/i, function (res) { randomImg(res); }); robot.respond(/pug me/i, function (res) { randomImg(res); }); robot.respond(/ciao/i, function (res) { randomImg(res); }); robot.respond(/dici (.*)/i, function (res) { if (res.message.user.name == "batt") { robot.messageRoom(room, res.match[1].trim()); } }); };
JavaScript
0
3b31d35d40b6d8740e1c4a4fa98ebf422ee05d12
disable DataTables pagination (task #2274)
webroot/js/data-tables.js
webroot/js/data-tables.js
(function($) { $(document).ready(function() { $('.table-datatable').DataTable({ paging: false }); }); })(jQuery);
(function($) { $(document).ready(function() { $('.table-datatable').DataTable(); }); })(jQuery);
JavaScript
0
0459e92233ab41bf2689c4643f4b500c6fda2668
Switch away from checkboxes and use an explicit resolved flag.
src/common/main.js
src/common/main.js
(function(){ if(window.location.hostname === 'github.com' && window.location.pathname.match(/\/pull\/\d+$/)) { var RESOLVED_EMOJI = ':white_check_mark:'; var RESOLVED_EMOJI_SELECTOR = '.emoji[alt="' + RESOLVED_EMOJI + '"]'; var queryParents = function(element, selector) { var parent = element.parentNode if(parent === window) return null; if(parent.matches(selector)) return parent; return queryParents(parent, selector); }; var buildStatusItem = function(commentID, text) { var inner = [ '<a class="build-status-details right" href="#' + commentID + '">Show</a>', '<span aria-hidden="true" class="octicon octicon-x build-status-icon text-error"></span>', '<span class="text-muted css-truncate css-truncate-target">', '<strong class="text-emphasized"> Unresolved Comment</strong>', ' — ' + text.trim(), '</span>' ].join(''); var statusItem = document.createElement('div'); statusItem.classList.add('build-status-item'); statusItem.classList.add('pr-helper-addition'); statusItem.innerHTML = inner; return statusItem; }; var addStatusItems = function(items) { var statusContainer = document.querySelector('.branch-action-body .branch-action-item.js-details-container'); var statusList = statusContainer.querySelector('.build-statuses-list'); statusContainer.classList.add('open'); items.forEach(function(item) { statusList.appendChild(item); }); }; var nodeListMatchesSelector = function(nodeList, selector) { nodeList = Array.prototype.slice.call(nodeList); return nodeList.findIndex(function(item) { return item instanceof Element && item.matches(selector); }) !== -1; } var commentOnConversation = function(conversation, text) { var commentForm = conversation.querySelector('.inline-comment-form form'); var textarea = commentForm.querySelector('textarea'); jQuery(textarea).val(text).change(); jQuery(commentForm).submit(); } var rebuild = function () { // Cleanup old additions. Array.prototype.slice.call( document.querySelectorAll('.pr-helper-addition') ).forEach(function(oldAddition) { oldAddition.remove() }); // Find unresolved conversations var allConversations = Array.prototype.slice.call( document.querySelectorAll('.timeline-inline-comments') ); var unresolvedConversations = allConversations.filter(function(conversation) { var lastComment = conversation.querySelector('.comment-holder > .comment:last-of-type'); return !lastComment.querySelector(RESOLVED_EMOJI_SELECTOR); }); // Add `Resolve` buttons. unresolvedConversations.forEach(function(conversation){ var actionsView = conversation.querySelector('.inline-comment-form-actions'); var resolveButton = document.createElement('button'); resolveButton.innerHTML = "Resolve"; resolveButton.classList.add('btn'); resolveButton.classList.add('pr-helper-addition'); resolveButton.style.marginLeft = "5px"; resolveButton.addEventListener('click', function() { commentOnConversation(conversation, RESOLVED_EMOJI + ' Resolved'); }); actionsView.appendChild(resolveButton); }); // Warn of unresolved conversations. if(unresolvedConversations.length > 0) { addStatusItems( unresolvedConversations.map(function(conversation) { var firstComment = conversation.querySelector('.comment-holder > .comment:first-of-type'); return buildStatusItem( firstComment.id, firstComment.querySelector('.comment-body').textContent ); }) ); } } // Look for on the fly changes to task-lists. var MutationObserver = window.MutationObserver || window.WebKitMutationObserver; var taskObserver = new MutationObserver(function(mutations) { var filteredMutations = mutations.filter(function(mutation) { return mutation.type === 'childList' && ( nodeListMatchesSelector(mutation.addedNodes, '.comment') || //, .task-list, .task-list *') || nodeListMatchesSelector(mutation.removedNodes, '.comment') ) }); if(filteredMutations.length > 0) rebuild(); }); taskObserver.observe(document.body, { childList: true, subtree: true }); // Handle PJAX reload. var pjaxObserver = new MutationObserver(function(mutations) { if(mutations.findIndex(function(mutation) { return !!mutation.addedNodes.length }) !== -1) { console.log('New Content Ready'); rebuild(); } }); pjaxObserver.observe(document.querySelector('#js-repo-pjax-container'), { childList: true }); // Initial run. rebuild(); } })();
(function(){ if(window.location.hostname === 'github.com' && window.location.pathname.match(/\/pull\/\d+$/)) { var queryParents = function(element, selector) { var parent = element.parentNode if(parent === window) return null; if(parent.matches(selector)) return parent; return queryParents(parent, selector); }; var buildStatusItem = function(commentID, text) { var inner = [ '<a class="build-status-details right" href="#' + commentID + '">Show</a>', '<span aria-hidden="true" class="octicon octicon-x build-status-icon text-error"></span>', '<span class="text-muted css-truncate css-truncate-target">', '<strong class="text-emphasized"> Incomplete Task</strong>', ' — ' + text, '</span>' ].join(''); var statusItem = document.createElement('div'); statusItem.classList.add('build-status-item'); statusItem.classList.add('pr-helper-item'); statusItem.innerHTML = inner; return statusItem; }; var nodeListMatchesSelector = function(nodeList, selector) { nodeList = Array.prototype.slice.call(nodeList); return nodeList.findIndex(function(item) { return item instanceof Element && item.matches(selector); }) !== -1; } var rebuildIssues = function () { // Cleanup old PR comment status items. var oldIssues = document.querySelectorAll('.pr-helper-item'); oldIssues = Array.prototype.slice.call(oldIssues); oldIssues.forEach(function(oldIssue) { oldIssue.remove() }); // Scan and update comment status items. var unresolvedIssues = document.querySelectorAll('#discussion_bucket .task-list-item-checkbox[type=checkbox]:not([checked])'); unresolvedIssues = Array.prototype.slice.call(unresolvedIssues); if(unresolvedIssues.length > 0) { var statusContainer = document.querySelector('.branch-action-body .branch-action-item.js-details-container'); var statusList = statusContainer.querySelector('.build-statuses-list'); statusContainer.classList.add('open'); unresolvedIssues.forEach(function(issueCheckbox) { var issueComment = queryParents(issueCheckbox, '.comment'); statusList.appendChild(buildStatusItem( issueComment.id, issueCheckbox.parentNode.textContent.trim() )); }); } } // Look for on the fly changes to task-lists. var MutationObserver = window.MutationObserver || window.WebKitMutationObserver; var taskObserver = new MutationObserver(function(mutations) { var filteredMutations = mutations.filter(function(mutation) { return mutation.type === 'childList' && ( nodeListMatchesSelector(mutation.addedNodes, '.comment, .task-list, .task-list *') || nodeListMatchesSelector(mutation.removedNodes, '.comment') ) }); if(filteredMutations.length > 0) rebuildIssues(); }); taskObserver.observe(document.body, { childList: true, subtree: true }); // Handle PJAX reload. var pjaxObserver = new MutationObserver(function(mutations) { if(mutations.findIndex(function(mutation) { return !!mutation.addedNodes.length }) !== -1) { console.log('New Content Ready'); rebuildIssues(); } }); pjaxObserver.observe(document.querySelector('#js-repo-pjax-container'), { childList: true }); // Initial run. rebuildIssues(); } })();
JavaScript
0
4b54a10c64247b96f05cb274eb52ecfb6f40c02b
update frp.config.js v2.0.0
frp.config.js
frp.config.js
'use strict'; // https://github.com/frontainer/frontplate-cli/wiki/6.%E8%A8%AD%E5%AE%9A module.exports = function(production) { global.FRP_SRC = 'src'; global.FRP_DEST = 'public'; return { clean: {}, html: {}, style: production ? {} : {}, script: production ? {} : {}, server: {}, copy: {}, sprite: [], test: {} } };
'use strict'; // https://github.com/frontainer/frontplate-cli/wiki/6.%E8%A8%AD%E5%AE%9A module.exports = function(production) { global.FRP_DEST = global.FRP_DEST || 'public'; return { clean: {}, html: {}, style: production ? {} : {}, script: production ? {} : {}, server: {}, copy: {}, sprite: [], test: {} } };
JavaScript
0
d3cbed16f2bcdf087fc7109e037c48459d30b425
Fix ffmpeg path access (#847)
ffmpeg-convert-audio/functions/index.js
ffmpeg-convert-audio/functions/index.js
/** * Copyright 2017 Google Inc. All Rights Reserved. * * 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. */ 'use strict'; const functions = require('firebase-functions'); const { Storage } = require('@google-cloud/storage'); const path = require('path'); const os = require('os'); const fs = require('fs'); const ffmpeg = require('fluent-ffmpeg'); const ffmpeg_static = require('ffmpeg-static'); const gcs = new Storage(); // Makes an ffmpeg command return a promise. function promisifyCommand(command) { return new Promise((resolve, reject) => { command.on('end', resolve).on('error', reject).run(); }); } /** * When an audio is uploaded in the Storage bucket We generate a mono channel audio automatically using * node-fluent-ffmpeg. */ exports.generateMonoAudio = functions.storage.object().onFinalize(async (object) => { const fileBucket = object.bucket; // The Storage bucket that contains the file. const filePath = object.name; // File path in the bucket. const contentType = object.contentType; // File content type. // Exit if this is triggered on a file that is not an audio. if (!contentType.startsWith('audio/')) { functions.logger.log('This is not an audio.'); return null; } // Get the file name. const fileName = path.basename(filePath); // Exit if the audio is already converted. if (fileName.endsWith('_output.flac')) { functions.logger.log('Already a converted audio.'); return null; } // Download file from bucket. const bucket = gcs.bucket(fileBucket); const tempFilePath = path.join(os.tmpdir(), fileName); // We add a '_output.flac' suffix to target audio file name. That's where we'll upload the converted audio. const targetTempFileName = fileName.replace(/\.[^/.]+$/, '') + '_output.flac'; const targetTempFilePath = path.join(os.tmpdir(), targetTempFileName); const targetStorageFilePath = path.join(path.dirname(filePath), targetTempFileName); await bucket.file(filePath).download({destination: tempFilePath}); functions.logger.log('Audio downloaded locally to', tempFilePath); // Convert the audio to mono channel using FFMPEG. let command = ffmpeg(tempFilePath) .setFfmpegPath(ffmpeg_static) .audioChannels(1) .audioFrequency(16000) .format('flac') .output(targetTempFilePath); await promisifyCommand(command); functions.logger.log('Output audio created at', targetTempFilePath); // Uploading the audio. await bucket.upload(targetTempFilePath, {destination: targetStorageFilePath}); functions.logger.log('Output audio uploaded to', targetStorageFilePath); // Once the audio has been uploaded delete the local file to free up disk space. fs.unlinkSync(tempFilePath); fs.unlinkSync(targetTempFilePath); return functions.logger.log('Temporary files removed.', targetTempFilePath); });
/** * Copyright 2017 Google Inc. All Rights Reserved. * * 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. */ 'use strict'; const functions = require('firebase-functions'); const { Storage } = require('@google-cloud/storage'); const path = require('path'); const os = require('os'); const fs = require('fs'); const ffmpeg = require('fluent-ffmpeg'); const ffmpeg_static = require('ffmpeg-static'); const gcs = new Storage(); // Makes an ffmpeg command return a promise. function promisifyCommand(command) { return new Promise((resolve, reject) => { command.on('end', resolve).on('error', reject).run(); }); } /** * When an audio is uploaded in the Storage bucket We generate a mono channel audio automatically using * node-fluent-ffmpeg. */ exports.generateMonoAudio = functions.storage.object().onFinalize(async (object) => { const fileBucket = object.bucket; // The Storage bucket that contains the file. const filePath = object.name; // File path in the bucket. const contentType = object.contentType; // File content type. // Exit if this is triggered on a file that is not an audio. if (!contentType.startsWith('audio/')) { functions.logger.log('This is not an audio.'); return null; } // Get the file name. const fileName = path.basename(filePath); // Exit if the audio is already converted. if (fileName.endsWith('_output.flac')) { functions.logger.log('Already a converted audio.'); return null; } // Download file from bucket. const bucket = gcs.bucket(fileBucket); const tempFilePath = path.join(os.tmpdir(), fileName); // We add a '_output.flac' suffix to target audio file name. That's where we'll upload the converted audio. const targetTempFileName = fileName.replace(/\.[^/.]+$/, '') + '_output.flac'; const targetTempFilePath = path.join(os.tmpdir(), targetTempFileName); const targetStorageFilePath = path.join(path.dirname(filePath), targetTempFileName); await bucket.file(filePath).download({destination: tempFilePath}); functions.logger.log('Audio downloaded locally to', tempFilePath); // Convert the audio to mono channel using FFMPEG. let command = ffmpeg(tempFilePath) .setFfmpegPath(ffmpeg_static.path) .audioChannels(1) .audioFrequency(16000) .format('flac') .output(targetTempFilePath); await promisifyCommand(command); functions.logger.log('Output audio created at', targetTempFilePath); // Uploading the audio. await bucket.upload(targetTempFilePath, {destination: targetStorageFilePath}); functions.logger.log('Output audio uploaded to', targetStorageFilePath); // Once the audio has been uploaded delete the local file to free up disk space. fs.unlinkSync(tempFilePath); fs.unlinkSync(targetTempFilePath); return functions.logger.log('Temporary files removed.', targetTempFilePath); });
JavaScript
0
d14e397c8bcd79cb72f18a579492ae7a37dcba61
Fix identing of include code
quickstarts/uppercase/functions/index.js
quickstarts/uppercase/functions/index.js
/** * Copyright 2016 Google Inc. All Rights Reserved. * * 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. */ 'use strict'; // [START all] // [START import] const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(functions.config().firebase); // [END import] // [START addMessage] // Take the text parameter passed to this HTTP endpoint and insert it into the // Realtime Database under the path /messages/:pushId/original // [START addMessageTrigger] exports.addMessage = functions.https.onRequest((req, res) => { // [END addMessageTrigger] // Grab the text parameter. const original = req.query.text; // Push it into the Realtime Database then send a response admin.database().ref('/messages').push({original: original}).then(snapshot => { // Redirect with 303 SEE OTHER to the URL of the pushed object in the Firebase console. res.redirect(303, snapshot.ref); }); }); // [END addMessage] // [START makeUppercase] // Listens for new messages added to /messages/:pushId/original and creates an // uppercase version of the message to /messages/:pushId/uppercase // [START makeUppercaseTrigger] exports.makeUppercase = functions.database.ref('/messages/{pushId}/original') .onWrite(event => { // [END makeUppercaseTrigger] // [START makeUppercaseBody] // Grab the current value of what was written to the Realtime Database. const original = event.data.val(); console.log('Uppercasing', event.params.pushId, original); const uppercase = original.toUpperCase(); // You must return a Promise when performing asynchronous tasks inside a Functions such as // writing to the Firebase Realtime Database. // Setting an "uppercase" sibling in the Realtime Database returns a Promise. return event.data.ref.parent.child('uppercase').set(uppercase); // [END makeUppercaseBody] }); // [END makeUppercase] // [END all]
/** * Copyright 2016 Google Inc. All Rights Reserved. * * 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. */ 'use strict'; // [START all] // [START import] const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(functions.config().firebase); // [END import] // [START addMessage] // Take the text parameter passed to this HTTP endpoint and insert it into the // Realtime Database under the path /messages/:pushId/original // [START addMessageTrigger] exports.addMessage = functions.https.onRequest((req, res) => { // [END addMessageTrigger] // Grab the text parameter. const original = req.query.text; // Push it into the Realtime Database then send a response admin.database().ref('/messages').push({original: original}).then(snapshot => { // Redirect with 303 SEE OTHER to the URL of the pushed object in the Firebase console. res.redirect(303, snapshot.ref); }); }); // [END addMessage] // [START makeUppercase] // Listens for new messages added to /messages/:pushId/original and creates an // uppercase version of the message to /messages/:pushId/uppercase // [START makeUppercaseTrigger] exports.makeUppercase = functions.database.ref('/messages/{pushId}/original') .onWrite(event => { // [END makeUppercaseTrigger] // [START makeUppercaseBody] // Grab the current value of what was written to the Realtime Database. const original = event.data.val(); console.log('Uppercasing', event.params.pushId, original); const uppercase = original.toUpperCase(); // You must return a Promise when performing asynchronous tasks inside a Functions such as // writing to the Firebase Realtime Database. // Setting an "uppercase" sibling in the Realtime Database returns a Promise. return event.data.ref.parent.child('uppercase').set(uppercase); }); // [END makeUppercaseBody] // [END makeUppercase] // [END all]
JavaScript
0.000144