commit
stringlengths
40
40
subject
stringlengths
1
3.25k
old_file
stringlengths
4
311
new_file
stringlengths
4
311
old_contents
stringlengths
0
26.3k
lang
stringclasses
3 values
proba
float64
0
1
diff
stringlengths
0
7.82k
c6198e77c167e12c2aa74e571f07dbf8f3f1dfb6
remove test if statement
server.js
server.js
'use strict' const express = require('express') const Slapp = require('slapp') const ConvoStore = require('slapp-convo-beepboop') const Context = require('slapp-context-beepboop') // use `PORT` env var on Beep Boop - default to 3000 locally var port = process.env.PORT || 3000 var slapp = Slapp({ // Beep Boop sets the SLACK_VERIFY_TOKEN env var verify_token: process.env.SLACK_VERIFY_TOKEN, convo_store: ConvoStore(), context: Context() }) // slapp.message('/.*(?:^|[^:])bones.*/i', ['mention', 'direct_message'], (msg) => { // msg.say(':bones-smiley:') // }) // slapp.message('/.*(?:^|[^:])heart.*/i', ['mention', 'direct_message'], (msg) => { // msg.say(':heart-love:') // }) // slapp.message('/.*(?:^|[^:])lungs.*/i', ['mention', 'direct_message'], (msg) => { // msg.say(':lungs-happy:') // }) // slapp.message('/.*(?:^|[^:]brain.*/i', ['mention', 'direct_message'], (msg) => { // msg.say(':brain-idea:') // }) // slapp.message('/.*(?:^|[^:])stomach.*/i', ['mention', 'direct_message'], (msg) => { // msg.say(':stomach-tongue:') // }) slapp.message('bones', ['mention', 'direct_message'], (msg) => { msg.say(':bones-smiley:') }) slapp.message('heart', ['mention', 'direct_message'], (msg) => { if (msg.body.event.text.includes(':heart') return; msg.say(':heart-love:') }) slapp.message('lungs', ['mention', 'direct_message'], (msg) => { msg.say(':lungs-happy:') }) slapp.message('brain', ['mention', 'direct_message'], (msg) => { msg.say(':brain-idea:') }) slapp.message('stomach', ['mention', 'direct_message'], (msg) => { msg.say(':stomach-tongue:') }) // var HELP_TEXT = ` // I will respond to the following messages: // \`help\` - to see this message. // \`hi\` - to demonstrate a conversation that tracks state. // \`thanks\` - to demonstrate a simple response. // \`<type-any-other-text>\` - to demonstrate a random emoticon response, some of the time :wink:. // \`attachment\` - to see a Slack attachment message. // ` // //********************************************* // // Setup different handlers for messages // //********************************************* // // response to the user typing "help" // slapp.message('help', ['mention', 'direct_message'], (msg) => { // msg.say(HELP_TEXT) // }) // // "Conversation" flow that tracks state - kicks off when user says hi, hello or hey // slapp // .message('^(hi|hello|hey)$', ['direct_mention', 'direct_message'], (msg, text) => { // msg // .say(`${text}, how are you?`) // // sends next event from user to this route, passing along state // .route('how-are-you', { greeting: text }) // }) // .route('how-are-you', (msg, state) => { // var text = (msg.body.event && msg.body.event.text) || '' // // user may not have typed text as their next action, ask again and re-route // if (!text) { // return msg // .say("Whoops, I'm still waiting to hear how you're doing.") // .say('How are you?') // .route('how-are-you', state) // } // // add their response to state // state.status = text // msg // .say(`Ok then. What's your favorite color?`) // .route('color', state) // }) // .route('color', (msg, state) => { // var text = (msg.body.event && msg.body.event.text) || '' // // user may not have typed text as their next action, ask again and re-route // if (!text) { // return msg // .say("I'm eagerly awaiting to hear your favorite color.") // .route('color', state) // } // // add their response to state // state.color = text // msg // .say('Thanks for sharing.') // .say(`Here's what you've told me so far: \`\`\`${JSON.stringify(state)}\`\`\``) // // At this point, since we don't route anywhere, the "conversation" is over // }) // // Can use a regex as well // slapp.message(/^(thanks|thank you)/i, ['mention', 'direct_message'], (msg) => { // // You can provide a list of responses, and a random one will be chosen // // You can also include slack emoji in your responses // msg.say([ // "You're welcome :smile:", // 'You bet', // ':+1: Of course', // 'Anytime :sun_with_face: :full_moon_with_face:' // ]) // }) // // demonstrate returning an attachment... // slapp.message('attachment', ['mention', 'direct_message'], (msg) => { // msg.say({ // text: 'Check out this amazing attachment! :confetti_ball: ', // attachments: [{ // text: 'Slapp is a robust open source library that sits on top of the Slack APIs', // title: 'Slapp Library - Open Source', // image_url: 'https://storage.googleapis.com/beepboophq/_assets/bot-1.22f6fb.png', // title_link: 'https://beepboophq.com/', // color: '#7CD197' // }] // }) // }) // // Catch-all for any other responses not handled above // slapp.message('.*', ['direct_mention', 'direct_message'], (msg) => { // // respond only 40% of the time // if (Math.random() < 0.4) { // msg.say([':wave:', ':pray:', ':raised_hands:']) // } // }) // attach Slapp to express server var server = slapp.attachToExpress(express()) // start http server server.listen(port, (err) => { if (err) { return console.error(err) } console.log(`Listening on port ${port}`) })
JavaScript
0.999999
@@ -1218,24 +1218,27 @@ (msg) =%3E %7B%0A + // if (msg.bod @@ -1271,16 +1271,19 @@ art') %0A%09 +// return;%0A
baf922280307a4b76e38cf96c151b7870836bd4f
remove console.log
server.js
server.js
#!/usr/bin/env node const debug = require('debug')('trifid:') const path = require('path') const program = require('commander') const ConfigHandler = require('trifid-core/lib/ConfigHandler') const Trifid = require('trifid-core') program .option('-v, --verbose', 'verbose output', () => true) .option('-c, --config <path>', 'configuration file', process.env.TRIFID_CONFIG) .option('-p, --port <port>', 'listener port', parseInt) .option('--sparql-endpoint-url <url>', 'URL of the SPARQL HTTP query interface') .option('--dataset-base-url <url>', 'Base URL of the dataset') .parse(process.argv) const opts = program.opts() // automatically switch to config-sparql if a SPARQL endpoint URL is given and no config file was defined if (opts.sparqlEndpointUrl && !opts.config) { opts.config = 'config-sparql.json' } else if (!opts.config) { opts.config = 'config.json' } // create a minimal configuration with a baseConfig pointing to the given config file const config = { baseConfig: path.join(process.cwd(), opts.config) } console.log('config', config) // add optional arguments to the configuration if (opts.port) { config.listener = { port: opts.port } } if (opts.sparqlEndpointUrl) { config.sparqlEndpointUrl = opts.sparqlEndpointUrl } if (opts.datasetBaseUrl) { config.datasetBaseUrl = opts.datasetBaseUrl } // load the configuration and start the server const trifid = new Trifid() trifid.configHandler.resolver.use('trifid', ConfigHandler.pathResolver(__dirname)) trifid.init(config).then(() => { if (opts.verbose) { debug('expanded config:') debug(JSON.stringify(trifid.config, null, ' ')) } return trifid.app() }).catch((err) => { debug(err) })
JavaScript
0.000006
@@ -1041,39 +1041,8 @@ %0A%7D%0A%0A -console.log('config', config)%0A%0A // a
2628e6b8b0d3b8abce81d9e584655fae2fac4ea2
update time interval
server.js
server.js
const http = require('http'); const app = require('./lib/app'); require('mongoose'); const findAndUpdate = require('./lib/update-user'); // const User = require('./lib/models/user.model'); require('./lib/connection'); const server = http.createServer(app); const port = process.env.PORT || 3000; server.listen(port, () => { console.log('server is running on ', server.address()); }); setInterval(findAndUpdate, 86400);
JavaScript
0.000004
@@ -136,60 +136,8 @@ ');%0A -// const User = require('./lib/models/user.model');%0A %0A%0Are @@ -365,10 +365,13 @@ e, 86400 +000 );
bc9afa0314df8967faacfdf53ae7de0e842ac4e1
Support for Coffee Script 1.7.0
server.js
server.js
/* * Windows Azure Setup */ global.DEBUG = true; require('coffee-script'); require('./app/init.coffee');
JavaScript
0
@@ -3,27 +3,26 @@ %0A * -Windows Azure Setup +Start Nitro Server %0A */ @@ -49,34 +49,307 @@ e;%0A%0A -require('coffee-script');%0A +// Include the CoffeeScript interpreter so that .coffee files will work%0Avar coffee = require('coffee-script');%0A%0A// Explicitly register the compiler if required. This became necessary in CS 1.7%0Aif (typeof coffee.register !== 'undefined') coffee.register();%0A%0A// Include our application file%0Avar app = requ @@ -373,10 +373,8 @@ offee'); -%0A%0A
17cf5d8b505d76fcd1870cd08e24d931ee8930a9
update grunt config
gruntFile.js
gruntFile.js
/* jshint ignore:start */ 'use strict'; // # Globbing // for performance reasons we're only matching one level down: // 'test/spec/{,*/}*.js' // use this if you want to recursively match all subfolders: // 'test/spec/**/*.js' module.exports = function (grunt) { // Time how long tasks take. Can help when optimizing build times require('time-grunt')(grunt); // Load grunt tasks and config automatically // Read: https://github.com/firstandthird/load-grunt-config require('load-grunt-config')(grunt, { postProcess: function(config){ // Project settings config.yeoman = { // Configurable paths root: '.', src: 'src', test: 'test', dist: 'dist', projectName: 'sstooltip', outputName: 'sstooltip' }; return config; } }); };
JavaScript
0.000001
@@ -815,12 +815,52 @@ %7D%0A %7D); +%0A%0A // For aliases, see grunt/aliases.js %0A%7D;%0A
62c3bc3da6743ce2d69c6b9ec4835f18a416dc14
Fix routing of the application.
ui/src/index.js
ui/src/index.js
import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter } from 'react-router-dom'; import { Provider } from 'react-redux'; import 'bootstrap/dist/css/bootstrap.css'; import registerServiceWorker from './registerServiceWorker'; import WsClient from './WsClient'; import configureStore from './configureStore'; import AppContainer from './App/AppContainer'; import { websocketConnected, websocketDisconnected } from './App/AppActions'; import './index.css'; const wsClient = new WsClient(); const store = configureStore(wsClient); wsClient.setCallbacks({ onConnect: () => store.dispatch(websocketConnected()), onClose: () => store.dispatch(websocketDisconnected()) }); try { /* Start asynchronous connect to the websocket server. WsClient will retry indefinitely if the connection cannot be established. */ wsClient.connect(); } catch (err) { // Silently ignore any errors. They should have been dispatched from WsClient anyway. } ReactDOM.render( <Provider store={store}> <BrowserRouter> <AppContainer /> </BrowserRouter> </Provider>, document.getElementById('root') ); registerServiceWorker();
JavaScript
0
@@ -76,16 +76,23 @@ erRouter +, Route %7D from @@ -107,24 +107,24 @@ outer-dom';%0A - import %7B Pro @@ -597,24 +597,30 @@ nnect: () =%3E + %7B%0A store.dispa @@ -644,16 +644,60 @@ ected()) +;%0A // store.dispatch(fetchRocniky());%0A %7D ,%0A onCl @@ -1026,16 +1026,287 @@ way.%0A%7D%0A%0A +/* Render a pathless %3CRoute%3E so that 'location' is automatically injected as a 'prop'%0A into AppContainer and causes re-render on location change. See:%0A https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/guides/blocked-updates.md%0A */%0A ReactDOM @@ -1368,16 +1368,33 @@ %0A %3C +Route component=%7B AppConta @@ -1397,16 +1397,17 @@ ontainer +%7D /%3E%0A
cdc8e94d470eb9bf9f7ba7d10f34b44da7f65a1c
Fix not passing ResizeObserver entries to measure method, closes #124
src/with-content-rect.js
src/with-content-rect.js
import { Component, createElement } from 'react' import PropTypes from 'prop-types' import ResizeObserver from 'resize-observer-polyfill' import getTypes from './get-types' import getContentRect from './get-content-rect' function withContentRect(types) { return WrappedComponent => class WithContentRect extends Component { static propTypes = { client: PropTypes.bool, offset: PropTypes.bool, scroll: PropTypes.bool, bounds: PropTypes.bool, margin: PropTypes.bool, innerRef: PropTypes.func, onResize: PropTypes.func, } state = { contentRect: { entry: {}, client: {}, offset: {}, scroll: {}, bounds: {}, margin: {}, }, } _animationFrameID = null _resizeObserver = new ResizeObserver(() => { this.measure() }) componentWillUnmount() { if (this._resizeObserver) { this._resizeObserver.disconnect() this._resizeObserver = null } window.cancelAnimationFrame(this._animationFrameID) } measure = entries => { const contentRect = getContentRect( this._node, types || getTypes(this.props) ) if (entries) { contentRect.entry = entries[0].contentRect } this._animationFrameID = window.requestAnimationFrame(() => { if (this._resizeObserver) { this.setState({ contentRect }) } }) if (typeof this.props.onResize === 'function') { this.props.onResize(contentRect) } } _handleRef = node => { if (this._resizeObserver) { if (node) { this._resizeObserver.observe(node) } else { this._resizeObserver.unobserve(this._node) } } this._node = node if (typeof this.props.innerRef === 'function') { this.props.innerRef(node) } } render() { const { innerRef, onResize, ...props } = this.props return createElement(WrappedComponent, { ...props, measureRef: this._handleRef, measure: this.measure, contentRect: this.state.contentRect, }) } } } export default withContentRect
JavaScript
0
@@ -840,34 +840,162 @@ = n -ew ResizeObserver(() =%3E +ull%0A%0A _node = null%0A%0A componentDidMount() %7B%0A this._resizeObserver = new ResizeObserver(this.measure)%0A if (this._node !== null) %7B%0A + @@ -1007,26 +1007,61 @@ his. -measure()%0A %7D) +_resizeObserver.observe(this._node)%0A %7D%0A %7D %0A%0A @@ -1113,32 +1113,41 @@ ._resizeObserver + !== null ) %7B%0A th @@ -1624,32 +1624,41 @@ ._resizeObserver + !== null ) %7B%0A @@ -1892,16 +1892,25 @@ Observer + !== null ) %7B%0A @@ -1923,16 +1923,25 @@ if (node + !== null ) %7B%0A
2455b82f940f2e6561ca6a677c4c0ca6c179202f
resolve "after doc deleted , it can also find" bug
dao/DocDao.js
dao/DocDao.js
/************************************** * 数据库操作类DocDao继承BaseDao * 2016-7-25 **************************************/ var config = require('../config'); //基础类 var BaseDao = require('./BaseDao'); class DocDao extends BaseDao { getList(options, callback) { var page = options.page, limit = options.limit, order = options.order || -1; this.model.find({ is_deleted: false }) .sort({ create_at: order }) .skip((page - 1) * limit) .limit(limit) .exec(callback); } getTitleById(id, callback) { this.model.findOne({ _id: id }, '-_id title', function(err, post) { if (!post) { return callback(err, ''); } callback(err, post.title); }); } getListByCategory(category, options, callback) { var page = options.page, limit = options.limit, order = options.order || -1; this.model.find({ category: category }) .sort({ create_at: order }) .skip((page - 1) * limit) .limit(limit) .exec(callback); } getByIdAndUpdateVisitCount(id, callback) { this.model.findByIdAndUpdate({ _id: id }, { $inc: { visit_count: 1 } }, callback); } incCommentCount(id, callback) { this.model.update({ _id: id }, { $inc: { comment_count: 1 } }, callback); } decCommentCount(id, callback) { this.model.update({ _id: id }, { $inc: { comment_count: -1 } }, callback); } getSearchResult(key, options, callback) { var page = options.page || 1, page_size = options.page_size || 10, order = options.order || -1; this.model.find({ title: { $regex: key } }) .sort({ create_at: order }) .skip((page - 1) * page_size) .limit(page_size) .exec(callback); } getCountByLikeKey(key, callback) { this.model.count({ title: { $regex: key } }, function(err, sumCount) { if (err) { return callback(err); } return callback(null, { sum_count: sumCount, page_count: Math.ceil(sumCount / config.page_num) }); }); } getArchives(options, callback) { var page = options.page, limit = options.limit, order = options.order || -1; this.model.find({}, 'title create_at') .sort({ create_at: order }) .skip((page - 1) * limit) .limit(limit) .exec(callback); } } module.exports = DocDao;
JavaScript
0.000001
@@ -1011,20 +1011,39 @@ category +, is_deleted: false %7D)%0A - @@ -1794,16 +1794,35 @@ x: key %7D +, is_deleted: false %7D)%0A @@ -2054,16 +2054,35 @@ x: key %7D +, is_deleted: false %7D, func @@ -2525,16 +2525,35 @@ l.find(%7B + is_deleted: false %7D, 'titl @@ -2706,16 +2706,103 @@ %0A %7D%0A%0A + count(callback) %7B%0A this.model.count(%7B is_deleted: false %7D, callback);%0A %7D%0A %7D%0Amodule
85c1b6c02d30e8117dc951328cb5cfa6e0c9a21a
Update documentation title
gruntfile.js
gruntfile.js
'use strict'; module.exports = function(grunt) { var pkg = grunt.file.readJSON('package.json'); var docsRepo = 'https://github.com/medullan/jenkins-docker-vagrant-ansible.wiki.git'; var docManifest = { title: "Vagrant Ansible Jenkins", github: pkg.repository.url, files: [] }; // Project configuration. grunt.initConfig({ pkg: pkg, bfdocs: { documentation: { options: { title: 'My Beautiful Documentation', manifest: docManifest, dest: 'docs/', theme: 'default' } } }, clean:{ docs: ['docs','jenkins-docker-vagrant-ansible.wiki'] }, gta: { cloneWiki: { command: 'clone ' + docsRepo, options: { stdout: true } } }, 'gh-pages': { options: { base: 'docs' , message: 'Generated by grunt gh-pages' } , src: ['**/*'] } }); require('load-grunt-tasks')(grunt); // grunt task for refreshing the list of markdown files when cloned from wiki grunt.registerTask('refreshFiles', 'Get refreshed list of files from wiki', function(){ var gruntConfigProp = 'bfdocs'; var markdown = [ 'jenkins-docker-vagrant-ansible.wiki/Home.md', 'jenkins-docker-vagrant-ansible.wiki/*.md', '!jenkins-docker-vagrant-ansible.wiki/_Footer.md' ]; var files = grunt.file.expand(markdown); docManifest.files = files; var bfdocs = grunt.config.get(gruntConfigProp); bfdocs.documentation.options.manifest = docManifest; grunt.config.set(gruntConfigProp, bfdocs); grunt.log.subhead("Complete. Latest documents are ready for processing!"); }); grunt.registerTask('docs', ['clean', 'gta:cloneWiki', 'refreshFiles', 'bfdocs']); grunt.registerTask('deploy', ['docs', 'gh-pages']); // By default, generate and deploy website grunt.registerTask('default', ['deploy']); };
JavaScript
0.000001
@@ -216,16 +216,35 @@ title: %22 +Jenkins Docker CI ( Vagrant @@ -254,16 +254,9 @@ ible - Jenkins +) %22,%0A
e8d71157623538e60f8bde7c04280d4e63b791c8
Return null when data not available
src/vfs.js
src/vfs.js
/** * <h1>VFS Manager</h1> * * <h2>spaceStatus</h2> * * <table> * <thead><td>Code</td><td>Status name</td></thead> * <tr><td>0</td><td>UNKNOWN</td></tr> * <tr><td>1</td><td>ABOVE</td></tr> * <tr><td>2</td><td>BELOW</td></tr> * </table> * * @module vfs * @namespace TVB * @title VFS Manager * @requires tvblob * @author Francesco Facconi francesco.facconi@tvblob.com */ /** * TVBLOB's VFS Manager Class * @class vfs * @namespace TVB * @classDescription TVBLOB's VFS Manager Class * @static */ TVB.vfs = {}; /** * Get space status code (w.r.t. the minimum space threshold set for this storage). * @method getStorageSpaceStatusCode * @return {Number} spaceStatus Code */ TVB.vfs.getStorageSpaceStatusCode = function() { try { TVB.log("Vfs: getStorageSpaceStatusCode()"); var s = new LocalStorage(); return s.getStorageSpaceStatusCode(); } catch (e) { TVB.error("Vfs: getStorageSpaceStatusCode: " + e.message); throw e; } } /** * Get storage space status string (w.r.t. the minimum space threshold set for this storage). * @method getStorageSpaceStatusName * @return {String} spaceStatus Name */ TVB.vfs.getStorageSpaceStatusName = function() { try { TVB.log("Vfs: getStorageSpaceStatusName()"); var s = new LocalStorage(); return s.getStorageSpaceStatusName(); } catch (e) { TVB.error("Vfs: getStorageSpaceStatusName: " + e.message); throw e; } } /** * Get the local storage free space as string. * @method getFreeSpaceAsString * @return {String} a string that can be converted to long and represents free space, null if the information is not available */ TVB.vfs.getFreeSpaceAsString = function() { try { TVB.log("Vfs: getFreeSpaceAsString()"); var s = new LocalStorage(); return s.getFreeSpaceAsString(); } catch (e) { TVB.error("Vfs: getFreeSpaceAsString: " + e.message); throw e; } } /** * Get the local storage free space as string. * @method getFreeSpaceAsString * @return {Number} a float converted from the string that represents free space, null if the information is not available */ TVB.vfs.getFreeSpaceAsFloat = function() { try { TVB.log("Vfs: getFreeSpaceAsFloat()"); var s = new LocalStorage(); return parseInt(s.getFreeSpaceAsString()); } catch (e) { TVB.error("Vfs: getFreeSpaceAsFloat: " + e.message); throw e; } } /** * Get a formatted string that represents the local storage free space. * @method getFreeSpaceAsFormattedString * @return {String} a formatted string to show free space, null if the information is not available */ TVB.vfs.getFreeSpaceAsFormattedString = function() { try { TVB.log("Vfs: getFreeSpaceAsFormattedString()"); var s = new LocalStorage(); return s.getFreeSpaceAsFormattedString(); } catch (e) { TVB.error("Vfs: getFreeSpaceAsFormattedString: " + e.message); throw e; } }
JavaScript
0.000006
@@ -2198,24 +2198,16 @@ ;%0A%09%09 -return parseInt( +var c = s.ge @@ -2226,18 +2226,90 @@ String() -) ; +%0A%09%09if (c == null) %7B%0A%09%09%09return null;%0A%09%09%7D else %7B%0A%09%09%09return parseInt(c);%0A%09%09%7D %0A%09%7D catc
3eca749cf17b9f6c649e688e356dacebc98772b1
Support both English colon and Chinese colon
data/danmu.js
data/danmu.js
var size = { font: { min: 10, ref: 24, max: window.innerHeight/4 }, image: { width: window.innerWidth/3, height: window.innerHeight/3 } } var colors = [ '#00aeef', // blue '#ea428a', // red '#eed500', // yellow '#f5a70d', // orange '#8bcb30', // green '#9962c1', // purple '#333333', // black '#e8e8e8' // white ]; var ctlptn = { all: RegExp('^:([蓝红黄橙绿紫黑白巨大小顶底])'), color: RegExp('^:([蓝红黄橙绿紫黑白])'), size: RegExp('^:([巨大小])'), position: RegExp('^:([顶底])') } $(window).resize(function() { size.font.max = window.innerHeight / 4; size.image.width = window.innerWidth / 3; size.image.height = window.innerHeight / 3; }); self.port.on('setup', function(settings) { size.font.ref = settings.size.font.ref; }); self.port.on('bullet', function(msg) { // Defaults var fontSize = size.font.ref; var color = colors[Math.floor(Math.random() * colors.length)]; var top = 'auto'; var bottom = 'auto'; while (ctlptn.all.test(msg.content.text)) { // Color controls if (ctlptn.color.test(msg.content.text)) { switch (ctlptn.color.exec(msg.content.text)[1]) { case '蓝': color = '#00aeef'; break; case '红': color = '#ea428a'; break; case '黄': color = '#eed500'; break; case '橙': color = '#f5a70d'; break; case '绿': color = '#8bcb30'; break; case '紫': color = '#9962c1'; break; case '黑': color = '#333333'; break; case '白': color = '#eeeeee'; break; } msg.content.text = msg.content.text.replace(ctlptn.color, ''); } // Size controls if (ctlptn.size.test(msg.content.text)) { switch (ctlptn.size.exec(msg.content.text)[1]) { case '大': fontSize *= 1.5; fontSize = (fontSize > size.font.max) ? size.font.max : fontSize; break; case '小': fontSize /= 1.5; fontSize = (fontSize < size.font.min) ? size.font.min : fontSize; break; case '巨': fontSize = size.font.max; break; } msg.content.text = msg.content.text.replace(ctlptn.size, ''); } // Position controls if (ctlptn.position.test(msg.content.text)) { if (ctlptn.position.exec(msg.content.text)[1] == '顶') { top = 12; } else { bottom = 12; } msg.content.text = msg.content.text.replace(ctlptn.position, ''); } } // Make bullet var bullet; if (msg.content.image === '') { bullet = $('<div>' + msg.content.text.replace(/<img/g, '<img height=' + fontSize) + '</div>'); } else { var img = $('<img src="' + msg.content.image + '" />').css({ 'max-width': size.image.width, 'max-height': size.image.height }); bullet = $('<div></div>').append(img); // To fix image position issue fontSize = size.image.height; } bullet.addClass('danmu-bullet').css({ color: color, 'font-size': fontSize, 'font-weight': 'bold', 'white-space': 'nowrap', 'overflow-y': 'visible' }); // Insert first to get proper width and height var fullElement = document.mozFullScreenElement; bullet.hide().appendTo(fullElement ? $(fullElement) : $('body')); if (top == 'auto' && bottom == 'auto') { top = ~~(Math.random() * (window.innerHeight - bullet.height())); } // Place at the right place bullet.css({ 'z-index': 10000, display: 'block', position: 'fixed', top: top, bottom: bottom, left: window.innerWidth, width: bullet.width() }).show(); // Fire the animation bullet.animate({ left: -bullet.width() }, ~~(Math.random() * 15) + 15000, 'linear', function() { if (-$(this).css('left').slice(0, -2) - 100 <= bullet.width()) { $(this).remove(); } } ); });
JavaScript
0
@@ -357,33 +357,36 @@ all: RegExp('%5E -: +%5B:%EF%BC%9A%5D (%5B%E8%93%9D%E7%BA%A2%E9%BB%84%E6%A9%99%E7%BB%BF%E7%B4%AB%E9%BB%91%E7%99%BD%E5%B7%A8%E5%A4%A7%E5%B0%8F%E9%A1%B6%E5%BA%95%5D @@ -408,17 +408,20 @@ egExp('%5E -: +%5B:%EF%BC%9A%5D (%5B%E8%93%9D%E7%BA%A2%E9%BB%84%E6%A9%99%E7%BB%BF%E7%B4%AB @@ -445,17 +445,20 @@ egExp('%5E -: +%5B:%EF%BC%9A%5D (%5B%E5%B7%A8%E5%A4%A7%E5%B0%8F%5D)' @@ -481,17 +481,20 @@ egExp('%5E -: +%5B:%EF%BC%9A%5D (%5B%E9%A1%B6%E5%BA%95%5D)')
3a89bdb8de259de02c1af9eb3e15f510307301dd
update listener
server.js
server.js
var sys = require("sys"), my_http = require("http"), path = require("path"), url = require("url"); var Firebase = require("firebase") my_http.createServer(function(request,response){ var my_path = url.parse(request.url).pathme; var full_path = path.join(process.cwd(),my_path); path.exists(full_path, function(exists){ if(!exists){ response.writeHeader(404, {"Content-Type": "text/plain"}); response.write("404 Not Found\n"); response.end(); } else{ // a reference here doesn't open a connection until r/w ops are invoked var fb = new Firebase("https://improvplusplus.firebaseio.com") } }); }) my_http.createServer(function(request,response){ var my_path = url.parse(request.url).pathname; load_file(my_path,response); }).listen(0.0.0.0:3000);
JavaScript
0
@@ -805,41 +805,8 @@ me;%0A - load_file(my_path,response);%0A %7D).l
e47153b7fd4c0b42d497a866cdbf9982bfc15dd7
add givataiim
data/index.js
data/index.js
var municipalities = { "jerusalem": { "center": [ 31.783476, 35.202637 ], "display": "\u05d9\u05e8\u05d5\u05e9\u05dc\u05d9\u05dd", "fb_link": "https://www.facebook.com/opentaba.jerusalem", "server": "http://opentaba-server.herokuapp.com/", "twitter_link": "https://twitter.com/opentaba_JLM" } };
JavaScript
0.000002
@@ -16,16 +16,181 @@ ies = %7B%0A + %22givataiim%22: %7B%0A %22center%22: %5B%0A 32.071151,%0A 34.80989%0A %5D,%0A %22display%22: %22%5Cu05d2%5Cu05d1%5Cu05e2%5Cu05ea%5Cu05d9%5Cu05d9%5Cu05dd%22%0A %7D,%0A %22jer @@ -533,9 +533,8 @@ %7D%0A%7D; -%0A
7ead01022af37a4b67dd4069156bab23e20da4f1
Fix merge error
gruntfile.js
gruntfile.js
module.exports = function (grunt) { var config = require("./config.js"); // Make sure that Grunt doesn't remove BOM from our utf8 files // on read grunt.file.preserveBOM = true; // Helper function to load the config file function loadConfig(path) { var glob = require('glob'); var object = {}; var key; glob.sync('*', {cwd: path}).forEach(function(option) { key = option.replace(/\.js$/,''); object[key] = require(path + option); }); return object; } // Load task options var gruntConfig = loadConfig('./tasks/options/'); // Package data gruntConfig.pkg = grunt.file.readJSON("package.json"); { expand: true, flatten: true, src: [desktopOutput + "css/*.css"], dest: desktopOutput + "css/" }, { expand: true, flatten: true, src: [phoneOutput + "css/*.css"], dest: phoneOutput + "css/" }, // Project config grunt.initConfig(gruntConfig); // Load all grunt-tasks in package.json require("load-grunt-tasks")(grunt); // Register external tasks grunt.loadTasks("tasks/"); // Task alias's grunt.registerTask("default", ["clean", "less", "concat", "copy", "replace"]); grunt.registerTask("css", ["less"]); grunt.registerTask("base", ["clean:base", "concat:baseDesktop", "concat:basePhone", "concat:baseStringsDesktop", "concat:baseStringsPhone", "replace"]); grunt.registerTask("ui", ["clean:ui", "concat:uiDesktop", "concat:uiPhone", "concat:uiStringsDesktop", "concat:uiStringsPhone", "replace", "less"]); }
JavaScript
0.000006
@@ -693,230 +693,8 @@ );%0A%0A - %7B expand: true, flatten: true, src: %5BdesktopOutput + %22css/*.css%22%5D, dest: desktopOutput + %22css/%22 %7D,%0A %7B expand: true, flatten: true, src: %5BphoneOutput + %22css/*.css%22%5D, dest: phoneOutput + %22css/%22 %7D,%0A
868637fcdc8abf70ec98ac541dab7f07288303a3
Fix grunt watch
gruntfile.js
gruntfile.js
module.exports = function (grunt) { grunt.initConfig({ browserify: { client: { src: ['src/**.js'], dest: 'dist/m4n.js', options: { transform: ['babelify'] } } }, watch: { javascript: { tasks: ['default'] }, }, jshint: { beforeconcat: ['gruntfile.js', 'src/**.js'], options: { esversion: 6 } }, uglify: { options: { report: 'gzip' }, default: { files: { 'dist/m4n.min.js': ['dist/m4n.js'] } } }, clean: [ 'dist/*' ], env: { prod: { NODE_ENV : 'production', BABEL_ENV : 'production' } } }); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-env'); grunt.loadNpmTasks('grunt-browserify'); grunt.registerTask('default', ['clean', 'jshint', 'browserify']); grunt.registerTask('production', ['env:prod', 'clean', 'jshint', 'browserify', 'uglify']); };
JavaScript
0
@@ -280,16 +280,46 @@ efault'%5D +,%0A files: %5B'src/**.js'%5D %0A %7D
df20a743adfea63eec96f4da082d861ee7057f28
Fix minor typo
server.js
server.js
var express = require('express'); var passport = require('passport'); var Strategy = require('passport-local').Strategy; var db = require('./db'); // Configure the local strategy for use by Passport. // // The local strategy require a `verify` function which receives the credentials // (`username` and `password`) submitted by the user. The function must verify // that the password is correct and then invoke `cb` with a user object, which // will be set at `req.user` in route handlers after authentication. passport.use(new Strategy( function(username, password, cb) { db.users.findByUsername(username, function(err, user) { if (err) { return cb(err); } if (!user) { return cb(null, false); } if (user.password != password) { return cb(null, false); } return cb(null, user); }); })); // Configure Passport authenticated session persistence. // // In order to restore authentication state across HTTP requests, Passport needs // to serialize users into and deserialize users out of the session. The // typical implementation of this is as simple as supplying the user ID when // serializing, and querying the user record by ID from the database when // deserializing. passport.serializeUser(function(user, cb) { cb(null, user.id); }); passport.deserializeUser(function(id, cb) { db.users.findById(id, function (err, user) { if (err) { return cb(err); } cb(null, user); }); }); // Create a new Express application. var app = express(); // Configure view engine to render EJS templates. app.set('views', __dirname + '/views'); app.set('view engine', 'ejs'); // Use application-level middleware for common functionality, including // logging, parsing, and session handling. app.use(require('morgan')('combined')); app.use(require('body-parser').urlencoded({ extended: true })); app.use(require('express-session')({ secret: 'keyboard cat', resave: false, saveUninitialized: false })); // Initialize Passport and restore authentication state, if any, from the // session. app.use(passport.initialize()); app.use(passport.session()); // Define routes. app.get('/', function(req, res) { res.render('home', { user: req.user }); }); app.get('/login', function(req, res){ res.render('login'); }); app.post('/login', passport.authenticate('local', { failureRedirect: '/login' }), function(req, res) { res.redirect('/'); }); app.get('/logout', function(req, res){ req.logout(); res.redirect('/'); }); app.get('/profile', require('connect-ensure-login').ensureLoggedIn(), function(req, res){ res.render('profile', { user: req.user }); }); app.listen(3000);
JavaScript
0.999993
@@ -227,16 +227,17 @@ require +s a %60veri
deb23418e8c603daf2a4484d6fe2dc85803c220c
bump service worker cache version
static/javascripts/sw.js
static/javascripts/sw.js
importScripts('/offline-google-analytics/offline-google-analytics-import.js'); goog.offlineGoogleAnalytics.initialize(); const cacheName = 'gcpnext17-v2'; const pathsToCache = [ '/', '/faqs', '/coc', '/static/manifest.json', '/static/stylesheets/fonts.min.css', '/static/stylesheets/main.min.css', '/static/javascripts/main.min.js', '/static/javascripts/sw-register.min.js', '/offline-google-analytics/offline-google-analytics-import.js', '/static/images/logo.png', '/static/images/gdg-logo.png', '/static/fonts/droid-sans/bold.ttf', '/static/fonts/droid-sans/regular.ttf', '/static/fonts/quicksand/bold.woff2' ]; self.addEventListener('install', function(e) { e.waitUntil( caches.open(cacheName) .then(function(cache) { return cache.addAll(pathsToCache); }) .then(function() { return self.skipWaiting(); }) ); }); self.addEventListener('activate', function(e) { e.waitUntil( caches.keys() .then(function(cacheKeys) { return Promise.all(cacheKeys.map(function(cacheKey) { if (cacheKey !== cacheName) { caches.delete(cacheKey); } })); }) .then(function() { self.clients.claim(); }) ); }); self.addEventListener('fetch', function(e) { e.respondWith( caches.match(e.request) .then(function(response) { return response || fetch(e.request); }) ); });
JavaScript
0
@@ -146,17 +146,17 @@ next17-v -2 +3 ';%0Aconst
37b265495b04f113cf678508b59b57ec2adac04b
Revert back `before_punctuation` regex to stable one.
static/js/alert_words.js
static/js/alert_words.js
import _ from "lodash"; import * as people from "./people"; // For simplicity, we use a list for our internal // data, since that matches what the server sends us. let my_alert_words = []; export function set_words(words) { my_alert_words = words; } export function get_word_list() { // People usually only have a couple alert // words, so it's cheap to be defensive // here and give a copy of the list to // our caller (in case they want to sort it // or something). return [...my_alert_words]; } export function has_alert_word(word) { return my_alert_words.includes(word); } export function process_message(message) { // Parsing for alert words is expensive, so we rely on the host // to tell us there any alert words to even look for. if (!message.alerted) { return; } for (const word of my_alert_words) { const clean = _.escapeRegExp(word); const before_punctuation = "(?<=\\s)|^|>|[\\(\\\".,';\\[]"; const after_punctuation = "(?=\\s)|$|<|[\\)\\\"\\?!:.,';\\]!]"; const regex = new RegExp(`(${before_punctuation})(${clean})(${after_punctuation})`, "ig"); message.content = message.content.replace( regex, (match, before, word, after, offset, content) => { // Logic for ensuring that we don't muck up rendered HTML. const pre_match = content.slice(0, offset); // We want to find the position of the `<` and `>` only in the // match and the string before it. So, don't include the last // character of match in `check_string`. This covers the corner // case when there is an alert word just before `<` or `>`. const check_string = pre_match + match.slice(0, -1); const in_tag = check_string.lastIndexOf("<") > check_string.lastIndexOf(">"); // Matched word is inside a HTML tag so don't perform any highlighting. if (in_tag === true) { return before + word + after; } return before + "<span class='alert-word'>" + word + "</span>" + after; }, ); } } export function notifies(message) { // We exclude ourselves from notifications when we type one of our own // alert words into a message, just because that can be annoying for // certain types of workflows where everybody on your team, including // yourself, sets up an alert word to effectively mention the team. return !people.is_current_user(message.sender_email) && message.alerted; } export const initialize = (params) => { my_alert_words = params.alert_words; };
JavaScript
0.000002
@@ -953,16 +953,11 @@ = %22 -(?%3C= %5C%5Cs -) %7C%5E%7C%3E
6ea40a277450276e69f3a31d56fb59bebc00c38b
Return null if no comment in database
static/js/controllers.js
static/js/controllers.js
'use strict'; /* The angular application controllers */ var mycomputerControllers = angular.module('mycomputerControllers', []); /* This controller to get comment from beego api */ mycomputerControllers.controller('HomeController', ['$scope', '$routeParams', '$http', function($scope, $routeParams, $http) { /* Get the comment objects */ $http.get('/api/comment').success(function(data) { /* If the data is empty string, don't return objects */ if(typeof data.Content == "undefined") { $scope.comments = data;//null; } else { $scope.comments = data; } }); }]); /* This controller to get user and items from beego api */ mycomputerControllers.controller('UserItemsController', ['$scope', '$routeParams', '$http', function($scope, $routeParams, $http) { /* Get the user object */ $http.get('/api/' + $routeParams.username).success(function(data) { /* If the data is empty string, don't return objects */ if(typeof data.Name == "undefined") { $scope.user = null; } else { $scope.user = data; } }); /* Get the user item objects */ $http.get('/api/' + $routeParams.username +'/items').success(function(data) { /* If the data is empty string, don't return objects */ if (typeof data[0].Username == "undefined") { $scope.items = null; } else { $scope.items = data; } }); /* Determine whether pop up the form to add item or not */ $scope.adding = false; } ]);
JavaScript
0.000003
@@ -482,15 +482,10 @@ ata. -Content +Id == @@ -529,15 +529,8 @@ s = -data;// null
9792bebf2021e8328ab611cf34ab416cc6817490
update service worker
static/service-worker.js
static/service-worker.js
self.addEventListener('install', function(event) { event.waitUntil( caches .open('v1') .then(function(cache) { return cache.addAll([ '.', 'favicon.ico', 'manifest.json', 'img/code.png', 'img/coffee.png', 'img/logo16.png', 'img/logo32.png', 'img/logo48.png', 'img/logo62.png', 'img/logo72.png', 'img/logo96.png', 'img/logo144.png', 'img/logo168.png', 'img/logo192.png', 'audio/alarm.mp3' ]).then(function() { self.skipWaiting() }) }) ) }) self.addEventListener('fetch', function(event) { event.respondWith( caches.match(event.request).then(function(response) { return response || fetch(event.request) }) ) })
JavaScript
0.000003
@@ -88,17 +88,17 @@ .open('v -1 +2 ')%0A @@ -720,17 +720,10 @@ -caches.ma +fe tch( @@ -737,20 +737,21 @@ equest). -then +catch (functio @@ -752,24 +752,16 @@ unction( -response ) %7B%0A @@ -773,22 +773,17 @@ urn -response %7C%7C fe +caches.ma tch(
eac1caef4bfe291c7983ceafbb0f375f0e290c9e
Update siisen.js
siisen.js
siisen.js
$(function() { // run the currently selected effect function runEffect() { // get effect type from var selectedEffect = $( "#effectTypes" ).val(); // most effect types need no options passed by default var options = {}; // some effects have required parameters if ( selectedEffect === "scale" ) { options = { percent: 60 }; } else if ( selectedEffect === "size" ) { options = { to: { width: 480, height: 385 } }; } // run the effect $( "#effect" ).show( selectedEffect, options, 1100, callback ); }; //callback function to bring a hidden box back function callback() { setTimeout(function() { $( "#effect:visible" ).removeAttr( "style" ).fadeOut(); }, 10000 ); }; // set effect from select menu value $( "#button" ).click(function() { runEffect(); }); $( "#effect" ).hide(); //hide v_nav_bar //$( "#v_nav_bar").show(); $(function() { $( "#accordion" ).accordion(); }) }); // $("#accordion").hide(); $( "#clickme" ).click(function() { $( "#back" ).slideToggle( "slow", function() { // Animation complete. }); });
JavaScript
0
@@ -1056,18 +1056,16 @@ %7D);%0A -// $(%22#acc
a0f85e1024c04d929e2bfbec3492f40fa02e241d
Update logger.js
utils/logger.js
utils/logger.js
/*jslint node: true */ 'use strict'; var fs = require('fs'); var path = require('path'); var winston = require('winston'); var pjson = require('../package.json'); var logDir = "logs"; var env = process.env.NODE_ENV || 'development'; var transports = []; /* Define colours for error level highlighting */ var colours = { debug: 'yellow', verbose: 'green', info: 'cyan', warn: 'magenta', error: 'red' }; winston.addColors(colours); /* Create log directory if missing */ if (!fs.existsSync(logDir)) { fs.mkdirSync(logDir); } /* Output everything to screen */ transports.push(new (winston.transports.Console)({level: 'warn', colorize: true, 'timestamp': false})); /* Write to daily log file, using less detail in production */ winston.add(require('winston-daily-rotate-file'), { name: 'file', json: false, filename: path.join(logDir, pjson.name), datePattern: '.yyyy-MM-dd.txt', level: env === 'development' ? 'debug' : 'info' }); var logger = new winston.Logger({transports: transports}); module.exports = logger;
JavaScript
0.000001
@@ -634,20 +634,21 @@ level: ' -warn +debug ', color @@ -1053,8 +1053,9 @@ logger; +%0A
819f9e7b0bd26a81822834c6c0b12d9dc016975c
Support ancient versions of jQuery.
skewer.js
skewer.js
/** * @fileOverview Live browser interaction with Emacs * @requires jQuery * @version 1.1 */ /** * Connects to Emacs and waits for a request. After handling the * request it sends back the results and queues itself for another * request. * @namespace Holds all of Skewer's functionality. */ function skewer() { function callback(request) { var result = skewer.fn[request.type](request); if (result) { result = JSON.stringify($.extend({ id: request.id, type: request.type, status: 'success', value: '' }, result)); $.post(skewer.host + "/skewer/post", result, callback, 'json'); } else { $.get(skewer.host + "/skewer/get", callback, 'json'); } }; $.get(skewer.host + "/skewer/get", callback, 'json'); } /** * Handlers accept a request object from Emacs and return either a * logical false (no response) or an object to return to Emacs. * @namespace Request handlers. */ skewer.fn = {}; /** * Handles an code evaluation request from Emacs. * @param request The request object sent by Emacs * @returns The result object to be returned to Emacs */ skewer.fn.eval = function(request) { var result = { strict: request.strict }; var start = Date.now(); try { var prefix = request.strict ? '"use strict";\n' : ""; var value = (eval, eval)(prefix + request.eval); // global eval result.value = skewer.safeStringify(value, request.verbose); } catch (error) { result = skewer.errorResult(error, result, request); } result.time = (Date.now() - start) / 1000; return result; }; /** * A keep-alive and connecton testing handler. * @param request The request object sent by Emacs * @returns The result object to be returned to Emacs */ skewer.fn.ping = function(request) { return { type: 'pong', date: Date.now() / 1000, value: request.eval }; }; /** * Establish a new stylesheet with the provided value. */ skewer.fn.css = function(request) { $('body').append($('<style/>').text(request.eval)); return {}; }; /** * Host of the skewer script (CORS support). * @type string */ (function() { var src = $('script[src$="/skewer"]').prop('src'); if (src) { skewer.host = src.match(/\w+:\/\/[^/]+/)[0]; } else { skewer.host = ''; // default to the current host } }()); /** * Stringify a potentially circular object without throwing an exception. * @param object The object to be printed. * @param {boolean} verbose Enable more verbose output. * @returns {string} The printed object. */ skewer.safeStringify = function (object, verbose) { "use strict"; var circular = "#<Circular>"; var seen = []; var stringify = function(obj) { if (obj === true) { return "true"; } else if (obj === false) { return "false"; } else if (obj === undefined) { return "undefined"; } else if (obj === null) { return "null"; } else if (typeof obj === "number") { return obj.toString(); } else if (obj instanceof Array) { if (seen.indexOf(obj) >= 0) { return circular; } else { seen.push(obj); return "[" + obj.map(function(e) { return stringify(e); }).join(", ") + "]"; } } else if (typeof obj === "string") { return JSON.stringify(obj); } else if (typeof obj === "function") { if (verbose) return obj.toString(); else return "Function"; } else if (Object.prototype.toString.call(obj) === '[object Date]') { if (verbose) return JSON.stringify(obj); else return obj.toString(); } else { if (verbose) { if (seen.indexOf(obj) >= 0) return circular; else seen.push(obj); var pairs = []; for (var key in obj) { if (obj.hasOwnProperty(key)) { var pair = JSON.stringify(key) + ":"; pair += stringify(obj[key]); pairs.push(pair); } } return "{" + pairs.join(',') + "}"; } else { try { return obj.toString(); } catch (error) { return ({}).toString(); } } } }; try { return stringify(object); } catch (error) { return skewer.safeStringify(object, false); } }; /** * Log an object to the Skewer REPL in Emacs (console.log). * @param message The object to be logged. */ skewer.log = function(message) { "use strict"; var log = { type: "log", value: skewer.safeStringify(message, true) }; $.post(skewer.host + "/skewer/post", JSON.stringify(log)); }; /** * Report an error event to the REPL. * @param event A jQuery event object. */ skewer.error = function(event) { "use strict"; var log = { type: "error", value: event.originalEvent.message }; $.post(skewer.host + "/skewer/post", JSON.stringify(log)); }; /** * Prepare a result when an error occurs evaluating Javascript code. * @param error The error object given by catch. * @param result The resutl object to return to Emacs. * @param request The request object from Emacs. * @return The result object to send back to Emacs. */ skewer.errorResult = function(error, result, request) { "use strict"; return $.extend({}, result, { value: error.toString(), status: 'error', error: { name: error.name, stack: error.stack, type: error.type, message: error.message, eval: request.eval } }); }; /* Add the event listener. This doesn't work correctly in Firefox. */ $(window).bind('error', skewer.error); $(document).ready(skewer);
JavaScript
0
@@ -2264,24 +2264,81 @@ unction() %7B%0A + /* Avoiding using jQuery's new-ish prop() method. */%0A var src @@ -2371,19 +2371,18 @@ %5D'). -prop(' +get(0). src -') ;%0A
c8d44d227835c3d503bb27c1c99f02caedad1667
Remove skewer-css jQuery.
skewer.js
skewer.js
/** * @fileOverview Live browser interaction with Emacs * @requires jQuery * @version 1.1 */ /** * Connects to Emacs and waits for a request. After handling the * request it sends back the results and queues itself for another * request. * @namespace Holds all of Skewer's functionality. */ function skewer() { function callback(request) { var result = skewer.fn[request.type](request); if (result) { result = skewer.extend({ id: request.id, type: request.type, status: 'success', value: '' }, result); skewer.postJSON(skewer.host + "/skewer/post", result, callback); } else { skewer.getJSON(skewer.host + "/skewer/get", callback); } }; skewer.getJSON(skewer.host + "/skewer/get", callback); } skewer.getJSON = function(url, callback) { var xhr = new XMLHttpRequest(); xhr.onload = function() { if (xhr.status === 200) { callback(JSON.parse(xhr.responseText)); } }; xhr.open('GET', url, true); xhr.send(); }; skewer.postJSON = function(url, object, callback) { var xhr = new XMLHttpRequest(); xhr.onload = function() { if (callback && xhr.status === 200) { callback(JSON.parse(xhr.responseText)); } }; xhr.open('POST', url, true); xhr.setRequestHeader("Content-type", "application/json"); xhr.send(JSON.stringify(object)); }; skewer.extend = function(target, object) { for (var key in object) { if (object.hasOwnProperty(key)) { target[key] = object[key]; } } return target; }; /** * Handlers accept a request object from Emacs and return either a * logical false (no response) or an object to return to Emacs. * @namespace Request handlers. */ skewer.fn = {}; /** * Handles an code evaluation request from Emacs. * @param request The request object sent by Emacs * @returns The result object to be returned to Emacs */ skewer.fn.eval = function(request) { var result = { strict: request.strict }; var start = Date.now(); try { var prefix = request.strict ? '"use strict";\n' : ""; var value = (eval, eval)(prefix + request.eval); // global eval result.value = skewer.safeStringify(value, request.verbose); } catch (error) { result = skewer.errorResult(error, result, request); } result.time = (Date.now() - start) / 1000; return result; }; /** * A keep-alive and connecton testing handler. * @param request The request object sent by Emacs * @returns The result object to be returned to Emacs */ skewer.fn.ping = function(request) { return { type: 'pong', date: Date.now() / 1000, value: request.eval }; }; /** * Establish a new stylesheet with the provided value. */ skewer.fn.css = function(request) { $('body').append($('<style/>').text(request.eval)); return {}; }; /** * Host of the skewer script (CORS support). * @type string */ (function() { var script = document.querySelector('script[src$="/skewer"]'); if (script) { skewer.host = script.src.match(/\w+:\/\/[^/]+/)[0]; } else { skewer.host = ''; // default to the current host } }()); /** * Stringify a potentially circular object without throwing an exception. * @param object The object to be printed. * @param {boolean} verbose Enable more verbose output. * @returns {string} The printed object. */ skewer.safeStringify = function (object, verbose) { "use strict"; var circular = "#<Circular>"; var seen = []; var stringify = function(obj) { if (obj === true) { return "true"; } else if (obj === false) { return "false"; } else if (obj === undefined) { return "undefined"; } else if (obj === null) { return "null"; } else if (typeof obj === "number") { return obj.toString(); } else if (obj instanceof Array) { if (seen.indexOf(obj) >= 0) { return circular; } else { seen.push(obj); return "[" + obj.map(function(e) { return stringify(e); }).join(", ") + "]"; } } else if (typeof obj === "string") { return JSON.stringify(obj); } else if (typeof obj === "function") { if (verbose) return obj.toString(); else return "Function"; } else if (Object.prototype.toString.call(obj) === '[object Date]') { if (verbose) return JSON.stringify(obj); else return obj.toString(); } else { if (verbose) { if (seen.indexOf(obj) >= 0) return circular; else seen.push(obj); var pairs = []; for (var key in obj) { if (obj.hasOwnProperty(key)) { var pair = JSON.stringify(key) + ":"; pair += stringify(obj[key]); pairs.push(pair); } } return "{" + pairs.join(',') + "}"; } else { try { return obj.toString(); } catch (error) { return ({}).toString(); } } } }; try { return stringify(object); } catch (error) { return skewer.safeStringify(object, false); } }; /** * Log an object to the Skewer REPL in Emacs (console.log). * @param message The object to be logged. */ skewer.log = function(message) { "use strict"; var log = { type: "log", value: skewer.safeStringify(message, true) }; skewer.postJSON(skewer.host + "/skewer/post", log); }; /** * Report an error event to the REPL. * @param event A jQuery event object. */ skewer.error = function(event) { "use strict"; var log = { type: "error", value: event.originalEvent.message }; skewer.postJSON(skewer.host + "/skewer/post", log); }; /** * Prepare a result when an error occurs evaluating Javascript code. * @param error The error object given by catch. * @param result The resutl object to return to Emacs. * @param request The request object from Emacs. * @return The result object to send back to Emacs. */ skewer.errorResult = function(error, result, request) { "use strict"; return skewer.extend({}, result, { value: error.toString(), status: 'error', error: { name: error.name, stack: error.stack, type: error.type, message: error.message, eval: request.eval } }); }; window.addEventListener('error', skewer.error); window.addEventListener('load', skewer);
JavaScript
0
@@ -2937,57 +2937,124 @@ -$('body').append($ +var style = document.createElement (' -%3C style -/%3E').text(request.eval) +');%0A style.innerHTML = request.eval;%0A document.body.appendChild(style );%0A
eaa33416d21edb5bbc26204ea751a441526ebb14
update to the correct WAB version
config/wabapp-config.js
config/wabapp-config.js
define({ 'wabVersion': '2.2', 'theme': { 'name': 'cmv' }, 'isRTL': false, 'httpProxy': { 'useProxy': false, 'alwaysUseProxy': false, 'url': '', 'rules': [{ 'urlPrefix': '', 'proxyUrl': '' }] }, 'geometryService': 'https://utility.arcgisonline.com/arcgis/rest/services/Geometry/GeometryServer', 'map': { 'id': 'map', '2D': true, '3D': false, 'itemId': '8bf7167d20924cbf8e25e7b11c7c502c', // ESRI Streets Basemap 'portalUrl': 'https://www.arcgis.com/' } });
JavaScript
0
@@ -23,17 +23,17 @@ on': '2. -2 +4 ',%0A '
b19652ccc20e54ec41e99e6d8f70277a3a5a0fa3
add players button action in UI
src/UI.js
src/UI.js
(function() { var UI = { showComputerMessage: function(callback) { $("#Computer").show("fast", function() { callback(UI.humanPlay); }); }, hideComputerMessage: function() { $("#Computer").hide(); }, showHumanMessage: function() { $("#Human").show(); }, hideHumanMessage: function() { $("#Human").hide(); }, getClass: function(element) { return $(element).attr('class') }, clickSpot: function(callback) { $("tr td").click(function(e) { callback(e.target.id, UI.computerPlay); }); }, clickButton: function(button, callback) { $(button).click(function(e) { if (button == ".player") { return UI.choiceMark(); } if (button == "#Xmark" || button == "#Omark") { Game.currentPlayer = UI.getTextContents(e.target.id); UI.toggleDisplayedButton(".playerMark", ".game"); } else if (button == ".btn-new") { UI.hideButton(".game") UI.unbindClick("button"); UI.unbindClick("tr td"); UI.resetGame(); } else if (button == ".btn-restart") { UI.hideButton(".game") UI.unbindClick("button"); UI.resetGame(); } e.stopPropagation(); callback(e.target); }); }, unbindClick: function(element) { $(element).unbind("click"); }, removeText: function(element) { $(element).empty(); }, getTextContents: function(elementID) { return $("#" + elementID).text() }, setTextContents: function(elementID, TextContents) { $("#" + elementID).text(TextContents); }, spotErrorMessage: function() { alert("That is not an available spot.\nPlease choose a different spot."); }, winMessage: function(winner) { alert("Congratulations.\n"+ winner +" win!!"); }, tieMessage: function() { alert("Game is tied.\nGame Over."); }, inputErrorMessage: function() { alert("You have to choose 'y' or 'n'."); }, askFirstMove: function() { return prompt("Do you require the first move? (y/n)"); }, toggleDisplayedButton: function(hideClass, showClass) { $(hideClass).hide(); $(hideClass).unbind(); $(showClass).show() }, hideButton: function(hideClass1, hideClass2) { $(hideClass1).hide(); $(hideClass2).hide(); }, visualAfterChoice: function(button) { if (this.getClass(button) == "btn-start") { this.toggleDisplayedButton(".btn-start", ".btn-new"); } else { this.toggleDisplayedButton(".btn-restart", ".btn-new"); } }, visualAfterGameOver: function() { this.unbindClick("tr td"); this.toggleDisplayedButton(".btn-new", ".btn-restart"); this.hideComputerMessage(); this.hideHumanMessage(); this.restartGame(); }, visualWhenGameOver: function(currentPlayer) { if(GameRules.gameWin(GameBoard)) { this.winMessage(Game.winner(currentPlayer)); this.visualAfterGameOver(); } else if(GameRules.gameTie(GameBoard)) { this.tieMessage(); this.visualAfterGameOver(); } }, choiceMark: function() { UI.hideButton(".btn-new", ".btn-restart"); UI.toggleDisplayedButton(".menu", ".playerMark"); UI.clickButton("#Xmark", UI.introGame); UI.clickButton("#Omark", UI.introGame); }, mainGame: function() { UI.toggleDisplayedButton(".btn-start", ".menu"); UI.clickButton(".player"); }, introGame: function(button) { UI.newGame(); Game.firstMove(button); Game.playGame(); }, startGame: function() { this.hideButton(".menu"); this.hideButton(".game", ".playerMark"); this.clickButton(".btn-start", UI.mainGame); }, resetGame: function() { this.removeText("tr td"); GameBoard.resetBoard(); }, newGame: function() { this.hideComputerMessage(); this.hideHumanMessage(); this.clickButton(".btn-new", UI.mainGame); }, restartGame: function() { this.clickButton(".btn-restart", UI.mainGame); }, humanPlay: function() { UI.showHumanMessage(); UI.clickSpot(Game.humanChoice) }, computerPlay: function() { UI.showComputerMessage(Game.computerChoice); } }; window.UI = UI; })();
JavaScript
0.000001
@@ -756,32 +756,122 @@ %7D%0A +else if (button == %22.players%22) %7B%0A return UI.choiceMark();%0A %7D%0A else if (button == %22# @@ -3690,24 +3690,58 @@ %22.player%22);%0A + UI.clickButton(%22.players%22);%0A %7D,%0A%0A
b60bd6709441fc75c14aa90669aefe4dc443d15a
Add getQuestionnaires functionality, Fix putQuestionnaire
src/bl.js
src/bl.js
'use strict' const MongoClient = require('mongodb').MongoClient; const ObjectId = require('mongodb').ObjectID; module.exports = (mongodbUrl) => { async function getQuestionnaires() { // TODO: Mongodb-kutsu return new Promise(function(resolve, reject){ setTimeout(function(){ resolve("Hello World"); }, 1000) }); } async function putQuestionnaire(payload) { return new Promise(function(resolve, reject){ let insertQuestionnaire = function(db, callback) { db.collection('questionnaires').insertOne(payload, function(err, result) { console.log("Inserted a questionnaire into the questionnaires collection."); callback(); }); }; MongoClient.connect(mongodbUrl, function(err, db) { insertQuestionnaire(db, function() { db.close(); }); }); let returnJson = new Object(); returnJson.uuid = payload.uuid; returnJson.created = payload.created; returnJson.modified = payload.modified; resolve(JSON.stringify(returnJson)); }); } return { getQuestionnaires: getQuestionnaires, putQuestionnaire: putQuestionnaire }; }
JavaScript
0.000007
@@ -268,77 +268,560 @@ -setTimeout(function()%7B%0A resolve(%22Hello World%22);%0A %7D, 1000) +let findQuestionnaires = function(db, callback) %7B%0A %09let resultsArray = new Array();%0A let cursor = db.collection('questionnaires').find( );%0A cursor.each(function(err, doc) %7B%0A if (doc !== null) %7B%0A %09 resultsArray.push(doc);%0A %7D else %7B%0A callback(resultsArray);%0A %7D%0A %7D);%0A %7D;%0A MongoClient.connect(mongodbUrl, function(err, db) %7B%0A findQuestionnaires(db, function(resultsArray) %7B%0A db.close();%0A resolve(JSON.stringify(resultsArray));%0A %7D);%0A %7D); %0A @@ -829,16 +829,19 @@ %7D);%0A %7D%0A + %0A async @@ -1334,35 +1334,21 @@ -%7D);%0A %7D); + %0A -%0A - let @@ -1370,24 +1370,28 @@ w Object();%0A + return @@ -1414,32 +1414,36 @@ oad.uuid;%0A + + returnJson.creat @@ -1460,24 +1460,28 @@ ad.created;%0A + return @@ -1516,24 +1516,28 @@ fied;%0A + resolve(JSON @@ -1557,24 +1557,46 @@ turnJson));%0A + %7D);%0A %7D);%0A %7D);%0A %7D%0A
b1d13f5a9f6b4bbf806dc19b1035a03286ad7571
update b
src/sk.js
src/sk.js
(function (global, factory) { if (typeof module === "object" && typeof module.exports === "object") { // CMD // all dependencies need to passed as parameters manually, // will not require here. module.exports = factory; } else if (typeof define === 'function' && define.amd) { // AMD. Register as sk // TODO how to define the jquery plugin here? define('sk', ['jsface', 'jquery'], factory); } else { // in browser, global is window. // all dependencies were loaded already. // bootstrap and jquery's plugin are all attached to jquery, // expose $sk and all components to window. factory(global, jsface, jQuery); } }(typeof window !== "undefined" ? window : this, function (window, jsface, jQuery, DO_NOT_EXPOSE_SK_TO_GLOBAL) { var _sk = window.$sk; var $sk = {}; window.$sk = $sk; $sk.noConflict = function () { window.$sk = _sk; return $sk; }; // insert all source code here // sk body here $sk.a = function (array) { return jQuery.isArray(array) ? array : []; }; //just true return true, other return false $sk.b = function (boolean) { return boolean && String(boolean) == "true" && boolean != "true"; }; $sk.d = function (date, defaultDate) { var rtnDate = defaultDate ? defaultDate : new Date(); return (date instanceof Date) ? (date.toString() == "Invalid Date" ? rtnDate : date) : rtnDate; }; //can be to Number than return value of number, other return 0 $sk.n = function (number) { return isNaN(Number(number)) ? 0 : Number(number); }; $sk.inValid = function (obj) { if (obj === undefined || obj == null || isNaN(obj) ) { return false; } else { return true; } }; $sk.o = function (object) { return jQuery.isPlainObject(object) ? object : {}; }; $sk.s = function (string) { return String(string); }; // reset to old $sk if (typeof DO_NOT_EXPOSE_SK_TO_GLOBAL != 'undefined' && DO_NOT_EXPOSE_SK_TO_GLOBAL === true) { window.$sk = _sk; } return $sk; }));
JavaScript
0
@@ -1138,19 +1138,8 @@ turn - boolean && Str @@ -1181,16 +1181,27 @@ = %22true%22 + && boolean ;%0A %7D;%0A%0A
b984bcdd076fa570cfdd7f3b56fae40707058e48
Update copyright
src/ua.js
src/ua.js
/*jslint browser: true, regexp: true, maxerr: 50, indent: 4 */ /** * A UserAgent detection library. * * This library relies on the navigator.userAgent property and hence does not * work for custom UserAgent settings. * * Apart from supporting detection of major browser vendors, the library also * supports detection of various devices. * * Copyright (c) 2012-2013, Gopalarathnam Venkatesan * All rights reserved. * * @module UA */ (function (window, navigator) { "use strict"; var userAgent = (window.navigator && navigator.userAgent) || ""; function detect(pattern) { return function () { return (pattern).test(userAgent); }; } var UA = { /** * Return true if the browser is Chrome or compatible. * * @method isChrome */ isChrome: detect(/webkit\W.*(chrome|chromium)\W/i), /** * Return true if the browser is Firefox. * * @method isFirefox */ isFirefox: detect(/mozilla.*\Wfirefox\W/i), /** * Return true if the browser is using the Gecko engine. * * This is probably a better way to identify Firefox and other browsers * that use XulRunner. * * @method isGecko */ isGecko: detect(/mozilla(?!.*webkit).*\Wgecko\W/i), /** * Return true if the browser is Internet Explorer. * * @method isIE */ isIE: function () { return navigator.appName === "Microsoft Internet Explorer"; } || detect(/\bTrident\b/), /** * Return true if the browser is running on Kindle. * * @method isKindle */ isKindle: detect(/\W(kindle|silk)\W/i), /** * Return true if the browser is running on a mobile device. * * @method isMobile */ isMobile: detect(/(iphone|ipod|((?:android)?.*?mobile)|blackberry|nokia)/i), /** * Return true if we are running on Opera. * * @method isOpera */ isOpera: detect(/opera.*\Wpresto\W/i), /** * Return true if the browser is Safari. * * @method isSafari */ isSafari: detect(/webkit\W(?!.*chrome).*safari\W/i), /** * Return true if the browser is running on a tablet. * * One way to distinguish Android mobiles from tablets is that the * mobiles contain the string "mobile" in their UserAgent string. * If the word "Android" isn't followed by "mobile" then its a * tablet. * * @method isTablet */ isTablet: detect(/(ipad|android(?!.*mobile)|tablet)/i), /** * Return true if the browser is running on a TV! * * @method isTV */ isTV: detect(/googletv|sonydtv/i), /** * Return true if the browser is running on a WebKit browser. * * @method isWebKit */ isWebKit: detect(/webkit\W/i), /** * Return true if the browser is running on an Android browser. * * @method isAndroid */ isAndroid: detect(/android/i), /** * Return true if the browser is running on any iOS device. * * @method isIOS */ isIOS: detect(/(ipad|iphone|ipod)/i), /** * Return true if the browser is running on an iPad. * * @method isIPad */ isIPad: detect(/ipad/i), /** * Return true if the browser is running on an iPhone. * * @method isIPhone */ isIPhone: detect(/iphone/i), /** * Return true if the browser is running on an iPod touch. * * @method isIPod */ isIPod: detect(/ipod/i), /** * Return the complete UserAgent string verbatim. * * @method whoami */ whoami: function () { return userAgent; } }; if ( typeof define === 'function' && define.amd ) { // AMD define( [], function() { return UA; } ); } else { // browser global window.UA = UA; } }(window, navigator));
JavaScript
0
@@ -369,9 +369,9 @@ -201 -3 +4 , Go
de292a848f84d63273fb4c1f125e09a31773ed22
Set format active when inside empty format tag.
toolbar.js
toolbar.js
/** * A Backbone.View for Spytext fields. * * @module spytext/toolbar */ function mapToNodeName(node) { return node.nodeName; } var selectron = require('./selectron'); module.exports = { /** * @lends SpytextToolbar.prototype * @augments Backbone.View */ events: { 'click button[data-command]': 'command', 'click button[data-undo]': 'undo', 'click button[data-redo]': 'redo', mousedown: function(e) { // this is needed to prevent toolbar from stealing focus e.preventDefault(); } }, template: 'spytext-toolbar', /** * Activates or deactivates the toolbar depending on whether a spytext field * is passed */ toggle: function(field) { this.field = field; this.$el.toggleClass('active', !!field); }, undo: function() { this.field.snapback.undo(); this.setActiveStyles(); }, redo: function() { this.field.snapback.redo(); this.setActiveStyles(); }, setActiveStyles: function() { var _toolbar = this; var containedSections = selectron.contained(this.field.el, { sections: true }, true); var containedSectionTags = _.unique(containedSections.map(mapToNodeName)); var containedLists = _.unique(containedSections.filter(function(node) { return node.nodeName === 'LI'; }).map(function(node) { return $(node).closest(_toolbar.field.el.children)[0]; })); var containedListTags = _.unique(containedLists.map(mapToNodeName)); var containedBlocks = containedSections.filter(function(node) { return node.nodeName !== 'LI'; }); var containedBlockTags = _.unique(containedBlocks.map(mapToNodeName)); $('button[data-command="list"]').removeClass('active'); if(containedLists.length === 1) { $('button[data-command="list"][data-option="' + containedListTags[0].toLowerCase() + '"]').addClass('active'); } var alignment = containedBlocks.reduce(function(result, block) { if(result === undefined) return result; var newResult = getComputedStyle(block).textAlign; if(newResult === 'start') newResult = 'left'; if(result === null) result = newResult; return result === newResult ? newResult : undefined; }, null); $('button[data-command="align"]').removeClass('active'); if(alignment) $('button[data-command="align"][data-option="' + alignment + '"]').addClass('active'); $('.spytext-dropdown.block').each(function() { var ul = this; $(ul).removeClass('pseudo pseudo-list pseudo-multiple').find('> li').removeClass('active'); if(containedListTags.length > 0) { $(ul).addClass('pseudo pseudo-list'); } else if(containedBlockTags.length === 1) { $(ul).find('button[data-option="' + containedBlockTags[0].toLowerCase() + '"]').each(function() { $(this.parentNode).addClass('active'); }); } else if(containedBlockTags.length > 1) { $(ul).addClass('pseudo pseudo-multiple'); } }); var commonAncestor = selectron.range().commonAncestorContainer; if(commonAncestor.nodeType === 3) commonAncestor = commonAncestor.parentNode; var containedTextNodes = selectron.contained(commonAncestor, { nodeType: 3 }, true); this.$('button[data-command="format"]').each(function() { var tag = $(this).data('option'); if(!tag) return; tag = tag.toUpperCase(); $(this).toggleClass('active', containedTextNodes.length > 0 && containedTextNodes.every(function(node) { var ancestorTags = $(node).ancestors(null, _toolbar.field.el).toArray().map(mapToNodeName); return ancestorTags.indexOf(tag) > -1; })); }); this.$('button[data-undo]').prop('disabled', this.field.snapback.undoIndex === -1); this.$('button[data-redo]').prop('disabled', this.field.snapback.undoIndex >= (this.field.snapback.undos.length - 1)); this.$('button[data-command="indent"],button[data-command="outdent"]').prop('disabled', containedSectionTags.indexOf('LI') === -1); this.$('button[data-command="align"]').prop('disabled', _.without(containedSectionTags, 'LI').length === 0); }, /** * Calls a command on the field currently attached to the toolbar */ command: function(e) { var command = $(e.currentTarget).attr('data-command'), option = $(e.currentTarget).attr('data-option'); this.field.command(command, option); } };
JavaScript
0
@@ -3226,16 +3226,49 @@ ase();%0A%0A +%09%09%09var rng = selectron.range();%0A%0A %09%09%09$(thi @@ -3292,16 +3292,17 @@ ctive', +( containe @@ -3376,26 +3376,14 @@ %09%09%09%09 -var ancestorTags = +return $(n @@ -3426,85 +3426,142 @@ el). -toArray().map(mapToNodeName);%0A%09%09%09%09return ancestorTags.indexOf(tag) %3E -1;%0A%09%09%09%7D +is(tag);%0A%09%09%09%7D)) %7C%7C rng.collapsed && ($(rng.startContainer).is(tag) %7C%7C $(rng.startContainer).ancestors(null, _toolbar.field.el).is(tag) ));%0A
6b14f1b3b912f204876fa172483e85ac61c50da6
Bring back some AudioManager methods but deprecate them
src/sound/manager.js
src/sound/manager.js
pc.extend(pc, function () { 'use strict'; /** * @private * @function * @name pc.SoundManager.hasAudio * @description Reports whether this device supports the HTML5 Audio tag API * @returns true if HTML5 Audio tag API is supported and false otherwise */ function hasAudio() { return (typeof Audio !== 'undefined'); } /** * @private * @function * @name pc.SoundManager.hasAudioContext * @description Reports whether this device supports the Web Audio API * @returns true if Web Audio is supported and false otherwise */ function hasAudioContext() { return !!(typeof AudioContext !== 'undefined' || typeof webkitAudioContext !== 'undefined'); } /** * @private * @name pc.SoundManager * @class The SoundManager is used to load and play audio. As well as apply system-wide settings * like global volume, suspend and resume. * @description Creates a new sound manager. */ var SoundManager = function () { if (hasAudioContext()) { if (typeof AudioContext !== 'undefined') { this.context = new AudioContext(); } else if (typeof webkitAudioContext !== 'undefined') { this.context = new webkitAudioContext(); } } this.listener = new pc.Listener(this); this._volume = 1; this.suspended = false; pc.events.attach(this); }; SoundManager.hasAudio = hasAudio; SoundManager.hasAudioContext = hasAudioContext; SoundManager.prototype = { suspend: function () { this.suspended = true; this.fire('suspend'); }, resume: function () { this.suspended = false; this.fire('resume'); }, destroy: function () { this.fire('destroy'); if (this.context && this.context.close) { this.context.close(); this.context = null; } } }; Object.defineProperty(SoundManager.prototype, 'volume', { get: function () { return this._volume; }, set: function (volume) { volume = pc.math.clamp(volume, 0, 1); this._volume = volume; this.fire('volumechange', volume); } }); // backwards compatibility pc.AudioManager = SoundManager; return { SoundManager: SoundManager }; }());
JavaScript
0.000204
@@ -2101,24 +2101,587 @@ %7D%0D%0A %7D +,%0D%0A%0D%0A getListener: function () %7B%0D%0A console.warn('DEPRECATED: getListener is deprecated. Get the %22listener%22 field instead.');%0D%0A return this.listener;%0D%0A %7D,%0D%0A%0D%0A getVolume: function () %7B%0D%0A console.warn('DEPRECATED: getVolume is deprecated. Get the %22volume%22 property instead.');%0D%0A return this.volume;%0D%0A %7D,%0D%0A%0D%0A setVolume: function (volume) %7B%0D%0A console.warn('DEPRECATED: setVolume is deprecated. Set the %22volume%22 property instead.');%0D%0A this.volume = volume;%0D%0A %7D, %0D%0A %7D;%0D%0A%0D%0A
dd65459ef6de6d3ff2351cee3a0fac30a8c8e60b
Fix colour picker inputs' design (#7384)
assets/src/edit-story/components/colorPicker/editablePreview.js
assets/src/edit-story/components/colorPicker/editablePreview.js
/* * Copyright 2020 Google LLC * * 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 * * https://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. */ /** * External dependencies */ import PropTypes from 'prop-types'; import styled from 'styled-components'; import { EditableInput } from 'react-color/lib/components/common'; import { useCallback, useMemo, useRef, useLayoutEffect, useState } from 'react'; /** * Internal dependencies */ import { Text, THEME_CONSTANTS, useKeyDownEffect, } from '../../../design-system'; const Preview = styled.button` margin: 0; padding: 0; border: 1px solid ${({ theme }) => theme.colors.border.defaultNormal}; border-radius: 2px; background: transparent; color: ${({ theme }) => theme.colors.fg.primary}; width: 100%; `; function EditablePreview({ label, value, width, format, onChange }) { const [isEditing, setIsEditing] = useState(false); const enableEditing = useCallback(() => setIsEditing(true), []); const disableEditing = useCallback(() => setIsEditing(false), []); const wrapperRef = useRef(null); const editableRef = useRef(); const inputStyles = useMemo( () => ({ input: { textAlign: 'center', textTransform: 'lowercase', width: '100%', padding: '8px 12px', border: '1px solid #5E6668', color: '#E4E5E6', borderRadius: '2px', background: 'transparent', lineHeight: '18px', }, wrap: { lineHeight: 0, maxWidth: `${width}px`, }, }), [width] ); // Handle ESC keypress to toggle input field. //eslint-disable-next-line react-hooks/exhaustive-deps useKeyDownEffect(wrapperRef, { key: 'esc', editable: true }, disableEditing, [ isEditing, ]); const handleOnBlur = (evt) => { // Ignore reason: There's no practical way to simulate the else occuring // istanbul ignore else if (!evt.currentTarget.contains(evt.relatedTarget)) { disableEditing(); } }; useLayoutEffect(() => { if (isEditing && editableRef.current) { editableRef.current.input.focus(); editableRef.current.input.select(); editableRef.current.input.setAttribute('aria-label', label); } }, [isEditing, label]); if (!isEditing) { return ( <Preview aria-label={label} onClick={enableEditing}> <Text size={THEME_CONSTANTS.TYPOGRAPHY.PRESET_SIZES.SMALL}> {format(value)} </Text> </Preview> ); } return ( <div ref={wrapperRef} tabIndex={-1} onBlur={handleOnBlur}> <EditableInput value={value} ref={editableRef} onChange={onChange} onChangeComplete={disableEditing} style={inputStyles} /> </div> ); } EditablePreview.propTypes = { label: PropTypes.string, value: PropTypes.string, width: PropTypes.number.isRequired, onChange: PropTypes.func.isRequired, format: PropTypes.func.isRequired, }; EditablePreview.defaultProps = { label: '', value: '', }; export default EditablePreview;
JavaScript
0
@@ -936,16 +936,32 @@ Effect,%0A + themeHelpers,%0A %7D from ' @@ -1233,16 +1233,349 @@ : 100%25;%0A + padding: 7px;%0A%0A $%7B(%7B theme %7D) =%3E%0A themeHelpers.focusableOutlineCSS(%0A theme.colors.border.focus,%0A theme.colors.bg.secondary%0A )%7D;%0A%60;%0A%0Aconst Wrapper = styled.div%60%0A input %7B%0A $%7B(%7B theme %7D) =%3E%0A themeHelpers.focusableOutlineCSS(%0A theme.colors.border.focus,%0A theme.colors.bg.secondary%0A )%7D;%0A %7D%0A %60;%0A%0Afunc @@ -3081,16 +3081,24 @@ %3CPreview +%0A aria-la @@ -3108,16 +3108,24 @@ =%7Blabel%7D +%0A onClick @@ -3140,16 +3140,55 @@ Editing%7D +%0A onFocus=%7BenableEditing%7D%0A %3E%0A @@ -3336,19 +3336,23 @@ (%0A %3C -div +Wrapper ref=%7Bwr @@ -3580,19 +3580,23 @@ %3E%0A %3C/ -div +Wrapper %3E%0A );%0A%7D
7a9a6f2f5a2b1e1e9dac51b09cd59e533e379222
Fix formatting errors.
public/angular/js/app.js
public/angular/js/app.js
require('./angular', { expose: 'angular' }); require('./angular-ui-router'); require('./ui-bootstrap'); require('./ui-bootstrap-templates'); require('./angular-resource'); angular.module('Aggie', ['ui.router', 'ui.bootstrap', 'ngResource']) .config(['$urlRouterProvider', '$locationProvider', function($urlRouterProvider, $locationProvider) { $locationProvider.html5Mode(true); $urlRouterProvider.otherwise('/'); } ]) .run(['$rootScope', '$location', 'AuthService', function ($rootScope, $location, AuthService) { $rootScope.$watch('currentUser', function(currentUser) { if (!currentUser) { AuthService.getCurrentUser() } }); var needsAuth = function () { return [].indexOf($location.path()) != -1; }; $rootScope.$on('$stateChangeStart', function (event, next, current) { if (needsAuth() && !$rootScope.currentUser) { $location.path('/login'); } }); }]); // Services require('./services/auth'); require('./services/factories'); require('./services/flash'); //Controllers require('./controllers/application'); require('./controllers/login'); require('./controllers/navbar'); require('./controllers/password_reset'); require('./controllers/password_reset_modal'); require('./controllers/report'); require('./controllers/show_report'); // Routes require('./routes'); // Filters require('./filters/report'); // Directives require('./directives/aggie-table');
JavaScript
0.000013
@@ -1006,16 +1006,17 @@ h');%0A%0A// + Controll
342e75ffe939deb48350f37b533479d38622ce46
enhance the regex entension (a bit)
js/jquery.inputmask.regex.extensions.js
js/jquery.inputmask.regex.extensions.js
/* Input Mask plugin extensions http://github.com/RobinHerbots/jquery.inputmask Copyright (c) 2010 - 2013 Robin Herbots Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php) Version: 0.0.0 Regex extensions on the jquery.inputmask base Allows for using regular expressions as a mask */ (function ($) { $.extend($.inputmask.defaults.aliases, { // $(selector).inputmask("Regex", { regex: "[0-9]*"} 'Regex': { mask: "r", greedy: false, repeat: 10, //needs to be computed regex: null, regexSplit: null, definitions: { 'r': { validator: function (chrs, buffer, pos, strict, opts) { function analyseRegex() { //ENHANCE ME opts.regexSplit = []; if (opts.regex.indexOf("*") != (opts.regex.length - 1)) { opts.regex += "{1}"; } opts.regexSplit.push(opts.regex); } if (opts.regexSplit == null) { analyseRegex(); } var cbuffer = buffer.slice(), regexPart = "", isValid = false; cbuffer.splice(pos, 0, chrs); var bufferStr = cbuffer.join(''); for (var i = 0; i < opts.regexSplit.length; i++) { regexPart += opts.regexSplit[i]; var exp = new RegExp("^" + regexPart + "$"); isValid = exp.test(bufferStr); console.log(bufferStr + ' ' + isValid); if (isValid) break; } return isValid; }, cardinality: 1 } } } }); })(jQuery);
JavaScript
0.000001
@@ -817,29 +817,144 @@ -opts.regexSplit = %5B%5D; +var regexSplitRegex = %22%5C%5C%5B.*?%5C%5D%5C%5C*%22;%0A%0A opts.regexSplit = opts.regex.match(new RegExp(regexSplitRegex, %22g%22));%0A %0A @@ -970,32 +970,34 @@ +// if (opts.regex.i @@ -1058,32 +1058,34 @@ +// opts.regex + @@ -1113,32 +1113,34 @@ +// %7D%0A @@ -1145,32 +1145,34 @@ +// opts.regexSplit. @@ -1874,16 +1874,34 @@ isValid + + ' ' + regexPart );%0A
70a16cf788011386a10affcf47ecb133c2072fab
Reset now clone the initialState instead of linking items to the initialState
src/storage/store.js
src/storage/store.js
// @flow import clone from 'clone'; import type { StorableType } from './storable'; import storableFactory from './storable'; export type StoreType = { name: string, reset: () => StoreType, addStorable: (item: StorableType) => StoreType, add: (item: Object) => StoreType, remove: (id: number) => StoreType, update: (id: number, next: StorableType) => StoreType, get: (id: number) => ?StorableType, all: () => Array<StorableType>, createStorable: (object: Object) => StorableType }; const cloneArrayOfStorable = (state: Array<StorableType>) : Array<StorableType> => { return state.map((storable: StorableType) => storable.clone()); }; const createStore = (name: string, initialState: Array<StorableType> = []):StoreType => { let items: Array<StorableType> = cloneArrayOfStorable(initialState); let storeInitialState: Array<StorableType> = cloneArrayOfStorable(initialState); const store: StoreType = { /** * @var string */ name: name, /** * Restore the initial state of the store * @returns {StoreType} */ reset: () => { items = Array.from(storeInitialState); return store; }, /** * Add a storable to the store * @param entity * @returns {StoreType} */ addStorable: (entity: StorableType): StoreType => { items = [ ...items, entity ]; return store; }, /** * Convert an object into a storable and add it to the store * @param entity * @returns {StoreType} */ add: (entity: Object): StoreType => { items = [ ...items, storableFactory.createStorable(entity) ]; return store; }, /** * Remove the storable from the store * @param id * @returns {StoreType} */ remove: (id: number): StoreType => { items = items.filter((entity: StorableType) => entity.getData().id !== id); return store; }, /** * Update the storable with a new storable * @param id * @param next * @returns {StoreType} */ update: (id: number, next: StorableType):StoreType => { items = items.map((storable: StorableType) => { if(storable.getData().id !== id){ return storable; } return next; }); return store; }, /** * Return the storable having the given ID * @param id * @returns {StorableType} */ get: (id: number): ?StorableType => { return items.find((entity: StorableType):boolean => entity.getData().id === id); }, /** * Return the store * @returns {Array<StorableType>} */ all: (): Array<StorableType> => items, /** * Create a storable * @returns {StorableType} */ createStorable: storableFactory.createStorable, }; return store; }; export default { createStore, createStorable: storableFactory.createStorable }
JavaScript
0
@@ -1104,18 +1104,28 @@ s = -Array.from +cloneArrayOfStorable (sto
a21187728b8298849aee644764d271c79821409d
use plugins instead of `renderFile` in write task
generator.js
generator.js
'use strict'; var fs = require('fs'); var path = require('path'); var argv = require('minimist')(process.argv.slice(2)); var utils = require('./lib/utils'); /** * This is an example generator, but it can also be used * to extend other generators. */ module.exports = function(generate, base, env) { var dest = argv.dest || process.cwd(); var async = utils.async; var glob = utils.glob; /** * TODO: User help and defaults */ generate.register('defaults', function(app) { app.task('init', function(cb) { app.build(['prompt', 'templates'], cb); }); app.task('help', function(cb) { console.log('Would you like to choose a generator to run?'); console.log('(implement me!)') cb(); }); app.task('error', function(cb) { console.log('generate > error (implement me!)'); cb(); }); }); /** * Readme task */ generate.task('readme', function(cb) { console.log('generate > readme'); cb(); }); /** * Data store tasks */ generate.register('store', function(app) { app.task('del', function(cb) { generate.store.del({ force: true }); console.log('deleted data store'); cb(); }); }); /** * Default configuration settings */ generate.task('defaultConfig', function(cb) { if (!generate.templates) { generate.create('templates'); } generate.engine(['md', 'text'], require('engine-base')); generate.data({year: new Date().getFullYear()}); cb(); }); /** * User prompts */ generate.task('prompt', function(cb) { var opts = { save: false, force: true }; var pkg = env.user.pkg; if (!pkg || env.user.isEmpty || env.argv.raw.init) { pkg = { name: utils.project(process.cwd()) }; forceQuestions(generate); } generate.questions.setData(pkg || {}); generate.ask(opts, function(err, answers) { if (err) return cb(err); if (!pkg) answers = {}; answers.name = answers.name || utils.project(); answers.varname = utils.namify(answers.name); generate.set('answers', answers); cb(); }); }); /** * Load templates to be rendered */ generate.task('templates', ['defaultConfig'], function(cb) { var opts = { cwd: env.config.cwd, dot: true }; glob('templates/*', opts, function(err, files) { if (err) return cb(err); async.each(files, function(name, next) { var fp = path.join(opts.cwd, name); var contents = fs.readFileSync(fp); generate.template(name, {contents: contents, path: fp}); next(); }, cb); }); }); /** * Write files to disk */ generate.task('write', function() { var data = generate.get('answers'); return generate.toStream('templates') .pipe(generate.renderFile('text', data)) .pipe(generate.dest(rename(dest))); }); /** * Generate a new project */ generate.task('project', ['prompt', 'templates', 'write']); /** * Default task to be run */ generate.task('default', function(cb) { generate.build('defaults:help', cb); }); }; function forceQuestions(generate) { generate.questions.options.forceAll = true; } /** * Rename template files */ function rename(dest) { return function(file) { file.base = file.dest || dest || ''; file.path = path.join(file.base, file.basename); file.basename = file.basename.replace(/^_/, '.'); file.basename = file.basename.replace(/^\$/, ''); return file.base; }; }
JavaScript
0.000001
@@ -1311,81 +1311,8 @@ ) %7B%0A - if (!generate.templates) %7B%0A generate.create('templates');%0A %7D%0A @@ -1368,16 +1368,16 @@ ase'));%0A + gene @@ -1770,14 +1770,8 @@ (pkg - %7C%7C %7B%7D );%0A @@ -1883,62 +1883,8 @@ %7D;%0A%0A - answers.name = answers.name %7C%7C utils.project();%0A @@ -2484,32 +2484,166 @@ %0A %7D);%0A %7D);%0A%0A + generate.plugin('render', function() %7B%0A var data = generate.get('answers');%0A return generate.renderFile('text', data);%0A %7D);%0A%0A /**%0A * Write @@ -2706,48 +2706,8 @@ ) %7B%0A - var data = generate.get('answers');%0A @@ -2755,46 +2755,96 @@ . -pipe(generate.renderFile('text', data) +on('error', console.log)%0A .pipe(generate.pipeline())%0A .on('error', console.log )%0A
1dc3b2a3ccaab5801600ac0346c2654177f61461
Create separate function for vector scaling
viz/js/birds.js
viz/js/birds.js
/** * birds - a project to visualize bird migration flow for Belgium & Netherlands. * * Copyright (c) 2014 LifeWatch - INBO * The MIT License - http://opensource.org/licenses/MIT * * https://github.com/enram/bird-migration-flow-visualization * * Special thanks to Cameron Beccario for his air.js */ (function() { "use strict"; // special document elements var MAP_SVG_ID = "#map-svg"; var FIELD_CANVAS_ID = "#field-canvas"; var DISPLAY_ID = "#display"; /** * An object to perform logging when the browser supports it. */ var log = { debug: function(s) { if (console && console.log) console.log(s); }, info: function(s) { if (console && console.info) console.info(s); }, error: function(e) { if (console && console.error) console.error(e.stack ? e + "\n" + e.stack : e); }, time: function(s) { if (console && console.time) console.time(s); }, timeEnd: function(s) { if (console && console.timeEnd) console.timeEnd(s); } }; /** * An object {width:, height:} that describes the extent of the browser's view in pixels. */ var view = function() { var w = window, d = document.documentElement, b = document.getElementsByTagName("#MAP_SVG_ID")[0]; var x = w.innerWidth || d.clientWidth || b.clientWidth; var y = w.innerHeight || d.clientHeight || b.clientHeight; log.debug("View size width:" + x + " height: "+ y); return {width: x, height: y}; }(); /** * Returns a d3 Albers conical projection (en.wikipedia.org/wiki/Albers_projection) that maps the bounding box * defined by the lower left geographic coordinates (lng0, lat0) and upper right coordinates (lng1, lat1) onto * the view port having (0, 0) as the upper left point and (width, height) as the lower right point. */ function createAlbersProjection(lng0, lat0, lng1, lat1, view) { // Construct a unit projection centered on the bounding box. NOTE: center calculation will not be correct // when the bounding box crosses the 180th meridian. Don't expect that to happen to Tokyo for a while... log.time("Creating projection"); var projection = d3.geo.albers() .rotate([-((lng0 + lng1) / 2), 0]) // rotate the globe from the prime meridian to the bounding box's center .center([0, (lat0 + lat1) / 2]) // set the globe vertically on the bounding box's center .scale(1) .translate([0, 0]); // Project the two longitude/latitude points into pixel space. These will be tiny because scale is 1. var p0 = projection([lng0, lat0]); var p1 = projection([lng1, lat1]); // The actual scale is the ratio between the size of the bounding box in pixels and the size of the view port. // Reduce by 5% for a nice border. var s = 1 / Math.max((p1[0] - p0[0]) / view.width, (p0[1] - p1[1]) / view.height) * 0.95; // Move the center to (0, 0) in pixel space. var t = [view.width / 2, view.height / 2]; log.timeEnd("Projection created"); return projection.scale(s).translate(t); } function createArrow(g, projection, vscale, x, y, v) { g.beginPath(); var start_x = projection([x, y])[0]; var start_y = projection([x, y])[1]; console.log("draw from: " + start_x + ", " + start_y); var end_x = start_x + vscale(v[0]); var end_y = start_y + vscale(v[1]); console.log("draw to: " + end_x + ", " + end_y); g.moveTo(start_x, start_y); g.lineTo(end_x, end_y); g.stroke(); } /** * Returns a promise for a JSON resource (URL) fetched via XHR. If the load fails, the promise rejects with an * object describing the reason: {error: http-status-code, message: http-status-text, resource:}. */ function loadMap() { d3.json("../data/basemap/basemap.topojson", function(error, basemap) { if (error) return console.error(error); var countries = topojson.feature(basemap, basemap.objects.ne_10m_admin_0_countries); //var cities = topojson.feature(basemap, basemap.objects.ne_10m_populated_places_simple); var radars = topojson.feature(basemap, basemap.objects.radars); var albers_projection = createAlbersProjection(basemap.bbox[0], basemap.bbox[1], basemap.bbox[2], basemap.bbox[3], view); var path = d3.geo.path() .projection(albers_projection); var svg = d3.select(MAP_SVG_ID).append("svg") .attr("width", view.width) .attr("height", view.height); svg.append("path") .datum(countries) .attr("d", path); // svg.append("path") // .datum(cities) // .attr("d", path) // .attr("class", "place"); svg.append("path") .datum(radars) .attr("d", path) .attr("class", "radar"); // Create arrow d3.select(FIELD_CANVAS_ID).attr("width", view.width).attr("height", view.height); var g = d3.select(FIELD_CANVAS_ID).node().getContext("2d"); createArrow(g, albers_projection, function(x) {return x}, 4.351829, 50.850383, [100, 100, 1]); }); } loadMap(); })();
JavaScript
0.000002
@@ -475,24 +475,110 @@ #display%22;%0A%0A + /**%0A * Create settings%0A */%0A var settings = %7B%0A%09vectorscale: 0.4%0A %7D;%0A%0A /**%0A @@ -3258,16 +3258,99 @@ %7D %0A%0A + var vectorScale = function(value) %7B%0A%09return value*settings.vectorscale;%0A %7D%0A%0A func @@ -5466,30 +5466,19 @@ on, -function(x) %7Breturn x%7D +vectorScale , 4.
cf864ca3ce92a971e98e758e90877f999bd9d0d4
Reduce highWaterMark
src/stream/JlTransform.js
src/stream/JlTransform.js
const Transform = require('stream').Transform; class JlTransform extends Transform { constructor(inputType, outputType) { super({ objectMode: true }); this.inputType = inputType; this.outputType = outputType; } } JlTransform.RAW = 'JlTransform.RAW'; JlTransform.ANY = 'JlTransform.ANY'; JlTransform.OBJECTS = 'JlTransform.OBJECTS'; JlTransform.ARRAYS_OF_OBJECTS = 'JlTransform.ARRAYS_OF_OBJECTS'; module.exports = JlTransform;
JavaScript
0.99775
@@ -147,16 +147,37 @@ de: true +,%0A%09%09%09highWaterMark: 1 %0A%09%09%7D);%0A%0A
d8ebde24db4d6e7dccf3d1f87a9d0ea128d8b60f
Fix 2 spaces -> 4 spaces
karma.conf.js
karma.conf.js
// Karma configuration var istanbul = require('browserify-istanbul'); 'use strict'; module.exports = function (config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: './', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['browserify', 'mocha', 'chai', 'sinon'], // list of files / patterns to load in the browser files: [ './libs/angular/angular.js', './libs/angular-mocks/angular-mocks.js', // for angular.mock.module and inject. './app/**/*.js' ], // list of files to exclude exclude: [], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { './app/**/!(*spec)*.js': ['browserify'] }, // karma-browserify configuration browserify: { debug: true, transform: ['debowerify', 'html2js-browserify', istanbul({ 'ignore': ['**/*.spec.js', '**/libs/**'] })], // don't forget to register the extensions extensions: ['.js'] }, // test results reporter to use // possible values: 'dots', 'progress', 'spec' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['spec', 'coverage'], coverageReporter: { type: 'html', dir: './reports/coverage' }, // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: [ // 'Chrome', 'PhantomJS' ], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false }); };
JavaScript
0.999997
@@ -1148,16 +1148,18 @@ + 'ignore'
2593ce5d53bd1b5765cf4ffe5edb44e837f809de
fix recursion
getTables.js
getTables.js
module.exports = function(dynamodb, tables, params, pageSize, cb){ params.Limit = pageSize; dynamodb.listTables(params, function(err, data) { if (err) { cb(err) } else if (data.LastEvaluatedTableName){ params.ExclusiveStartTableName = data.LastEvaluatedTableName; tables = tables.concat( data.TableNames ); getTables(dynamodb, tables, params, pageSize, cb); }else { tables = tables.concat( data.TableNames ); cb( null, tables ); } }); }
JavaScript
0.00013
@@ -10,24 +10,46 @@ ports = -function +getTables;%0A%0Afunction getTables (dynamod @@ -80,18 +80,21 @@ ize, cb) + %7B%0A + params @@ -115,16 +115,18 @@ ize;%0A%0A + + dynamodb @@ -153,16 +153,17 @@ function + (err, da @@ -172,16 +172,20 @@ ) %7B%0A + + if (err) @@ -197,16 +197,22 @@ + + cb(err)%0A @@ -207,16 +207,20 @@ cb(err)%0A + %7D el @@ -254,24 +254,25 @@ bleName) + %7B%0A params.E @@ -259,24 +259,30 @@ me) %7B%0A + + params.Exclu @@ -328,24 +328,30 @@ TableName;%0A%0A + tables @@ -359,33 +359,32 @@ = tables.concat( - data.TableNames @@ -378,28 +378,33 @@ a.TableNames - );%0A + getTab @@ -456,16 +456,27 @@ -%7D + %7D else %7B%0A + @@ -500,17 +500,16 @@ .concat( - data.Tab @@ -515,17 +515,16 @@ bleNames - );%0A @@ -528,12 +528,17 @@ + + cb( - null @@ -549,18 +549,23 @@ bles - );%0A + -%7D%0A + %7D%0A %7D)
ff168bf7d0aae48913028422b86f77cf75ef1c89
Update dynamic_form_utils.js
autofill/dynamic_form_utils.js
autofill/dynamic_form_utils.js
/* * Copyright 2018 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ function DynamicallyChangeForm() { RemoveForm('form1'); var new_form = AddNewFormAndFields(); document.getElementsByTagName('body')[0].appendChild(new_form); } //* Removes the initial form. */ function RemoveForm(form_id) { var initial_form = document.getElementById(form_id); initial_form.parentNode.removeChild(initial_form); initial_form.innerHTML = ''; initial_form.remove(); } /** Adds a new form and fields for the dynamic form. */ function AddNewFormAndFields() { var new_form = document.createElement('form'); new_form.setAttribute('method', 'post'); new_form.setAttribute('action', 'https://example.com/') new_form.setAttribute('name', 'addr1.1'); new_form.setAttribute('id', 'form1'); var i = document.createElement('input'); i.setAttribute('type', 'text'); i.setAttribute('name', 'firstname'); i.setAttribute('id', 'firstname'); i.setAttribute('autocomplete', 'given-name'); new_form.appendChild(i); i = document.createElement('input'); i.setAttribute('type', 'text'); i.setAttribute('name', 'address1'); i.setAttribute('id', 'address1'); i.setAttribute('autocomplete', 'address-line1'); new_form.appendChild(i); i = document.createElement('select'); i.setAttribute('name', 'state'); i.setAttribute('id', 'state'); i.setAttribute('autocomplete', 'region'); i.options[0] = new Option('CA', 'CA'); i.options[1] = new Option('MA', 'MA'); i.options[2] = new Option('TX', 'TX'); i.options[3] = new Option('DC', 'DC'); new_form.appendChild(i); i = document.createElement('input'); i.setAttribute('type', 'text'); i.setAttribute('name', 'city'); i.setAttribute('id', 'city'); i.setAttribute('autocomplete', 'locality'); new_form.appendChild(i); i = document.createElement('input'); i.setAttribute('type', 'text'); i.setAttribute('name', 'company'); i.setAttribute('id', 'company'); i.setAttribute('autocomplete', 'organization'); new_form.appendChild(i); i = document.createElement('input'); i.setAttribute('type', 'text'); i.setAttribute('name', 'email'); i.setAttribute('id', 'email'); i.setAttribute('autocomplete', 'email'); new_form.appendChild(i); i = document.createElement('input'); i.setAttribute('type', 'text'); i.setAttribute('name', 'phone'); i.setAttribute('id', 'phone'); i.setAttribute('autocomplete', 'tel'); new_form.appendChild(i); return new_form; }
JavaScript
0.000002
@@ -1890,32 +1890,248 @@ .appendChild(i); +%0A %0A i = document.createElement('input');%0A i.setAttribute('type', 'text');%0A i.setAttribute('name', 'zip');%0A i.setAttribute('id', 'zip');%0A i.setAttribute('autocomplete', 'postal-code');%0A new_form.appendChild(i); %0A%0A i = document
e7d52601676da1b9f8d8216a86c82cd201f6cc0c
make the print button start the operation (#2043)
calebasse/static/js/calebasse.agenda.js
calebasse/static/js/calebasse.agenda.js
function toggle_worker(worker_selector) { $(worker_selector).toggleClass('active'); if (!($.cookie('agenda-tabs'))) { $.cookie('agenda-tabs', new Array(), { path: '/' }); } if ($(worker_selector).hasClass('active')) { var tabs = $.cookie('agenda-tabs'); if ($.inArray($(worker_selector).attr('id'), tabs) == -1) { tabs.push($(worker_selector).attr('id')); $.cookie('agenda-tabs', tabs, { path: '/' }); } } else { var agendatabs = $.cookie('agenda-tabs'); $.each(agendatabs, function (i, value) { if (value == $(worker_selector).attr('id')) { agendatabs.splice(i, 1); } }); $.cookie('agenda-tabs', agendatabs, { path: '/' }); } var target = $($(worker_selector).data('target')); target.toggle(); var tab = $('#link-tab-worker-' + $(worker_selector).data('worker-id')).parent().get(0); var tab_list = $(tab).parent().get(0); $(tab).detach().appendTo(tab_list); return target.find('a.tab'); } function event_dialog(url, title, width, btn_text) { $('#rdv').load(url, function () { function onsuccess(response, status, xhr, form) { var parse = $(response); if ($('.errorlist', parse).length != 0) { $('#rdv').html(response); $('#rdv form').ajaxForm({ success: onsuccess, }); $('#rdv .datepicker-date').datepicker({dateFormat: 'd/m/yy', showOn: 'button'}); console.log('error'); } else { console.log('success'); window.location.reload(true); } } $('#rdv .datepicker-date').datepicker({dateFormat: 'd/m/yy', showOn: 'button'}); $('#id_description').attr('rows', '3'); $('#id_description').attr('cols', '30'); $('form', this).ajaxForm({ success: onsuccess }); $(this).dialog({title: title, width: width, buttons: [ { text: "Fermer", click: function() { $(this).dialog("close"); } }, { text: btn_text, click: function() { $("#rdv form").submit(); } }]}); }); } (function($) { $(function() { $('#tabs').tabs(); $('div.agenda > div').accordion({active: false, autoHeight: false}); $('.person-item').on('click', function() { $('#filtre input').val('') $('#users li').each(function() { $(this).show(); }); var target = toggle_worker(this); if ($(target).is(':visible')) { $(target).click(); } }); $('a.tab').click(function() { $.cookie('active-agenda', $(this).data('id'), { path: '/' }); }); $('a.close-tab').click(function() { $('#' + $(this).data('target')).click() }); if ($.cookie('agenda-tabs')) { $.each($.cookie('agenda-tabs'), function (i, worker_selector) { toggle_worker('#' + worker_selector); }); if ($.cookie('active-agenda')) { var target = $('#link-tab-worker-' + $.cookie('active-agenda')); if (target.is(':visible')) { target.click(); } } } $('.textedit').on('keydown', function() { $('button', this).removeAttr("disabled"); }); $('.textedit button').on('click', function() { var textarea = $(this).prev(); var span = textarea.prev() var btn = $(this) $.ajax({ url: '/api/event/' + $(this).data("event-id") + '/?format=json', type: 'PATCH', contentType: 'application/json', data: '{"description": "' + textarea.val() + '"}', success: function(data) { btn.attr('disabled', 'disabled'); span.html('Commentaire modifiée avec succès'); } }); }); $('.appointment').on('click', function() { $('.textedit span', this).html(''); }); $('.remove-appointment').on('click', function() { var r = confirm("Etes-vous sûr de vouloir supprimer le rendez-vous " + $(this).data('rdv') + " ?"); if (r == true) { $.ajax({ url: '/api/occurrence/' + $(this).data('occurrence-id') + '/', type: 'DELETE', success: function(data) { window.location.reload(true); return false; } }); } return false; }); /* Gestion du filtre sur les utilisateurs */ $('#filtre input').keyup(function() { var filtre = $(this).val(); if (filtre) { $('#users li').each(function() { if ($(this).text().match(new RegExp(filtre, "i"))) { $(this).show(); } else { $(this).hide(); } }); } else { $('#users li').show(); } }); $('.date').datepicker({showOn: 'button'}); $('#add-intervenant-btn').click(function() { var text = $(this).prev().val(); $('#intervenants ul').append('<li><input type="checkbox" value="' + text + '" checked="checked">' + text + '</input></li>'); $(this).prev().val('').focus(); return false; }); $('.newrdv').click(function() { var participants = $('.person-item.active').map(function (i, v) { return $(v).data('worker-id'); }); var qs = $.param({participants: $.makeArray(participants), time: $(this).data('hour') }, true); var new_appointment_url = $(this).data('url') + "?" + qs; event_dialog(new_appointment_url, 'Nouveau rendez-vous', '850px', 'Ajouter'); }); $('.edit-appointment').click(function() { event_dialog("update-rdv/" + $(this).data('occurrence-id') , 'Modifier rendez-vous', '850px', 'Modifier'); return false; }); $('.newevent').click(function() { var participants = $('.person-item.active').map(function (i, v) { return $(v).data('worker-id'); }); var qs = $.param({participants: $.makeArray(participants), time: $(this).data('hour') }, true); event_dialog($(this).data('url') + "?" + qs, 'Nouvel événement', '850px', 'Ajouter'); }); $('.edit-event').click(function() { event_dialog("update-event/" + $(this).data('occurrence-id') , 'Modifier un événement', '850px', 'Modifier'); return false; }); }); })(window.jQuery)
JavaScript
0
@@ -7020,16 +7020,80 @@ %7D);%0A + $('#print-button').click(function() %7B window.print(); %7D);%0A %7D);%0A%7D)
81893cd1f3d41bedc9b65241d189c5151c100ad7
remove unnecessary release npm scripts (#141)
src/tasks/package.js
src/tasks/package.js
/* eslint-disable no-template-curly-in-string */ const path = require('path'); const meta = require('user-meta'); const gitUsername = require('git-username'); const { json, install } = require('mrm-core'); const packages = ['schema-utils', 'loader-utils']; const devPackages = [ // Utilities 'del', 'del-cli', 'cross-env', 'memory-fs', 'standard-version', '@commitlint/cli', '@commitlint/config-conventional', 'conventional-github-releaser', 'husky', // Jest 'jest', 'babel-jest', // Babel 'babel-cli', 'babel-polyfill', 'babel-preset-env', 'babel-plugin-transform-object-rest-spread', // ESLint 'eslint', 'eslint-plugin-import', 'eslint-plugin-prettier', '@webpack-contrib/eslint-config-webpack', 'lint-staged', 'pre-commit', 'prettier', // Webpack 'webpack', ]; module.exports = (config) => { const { name } = meta; const github = gitUsername(); const packageName = path.basename(process.cwd()); const repository = `${github}/${packageName}`; const file = json('package.json'); const existing = file.get(); json('package.json') .set({ name: `${packageName}`, version: existing.version || '1.0.0', description: existing.description || '', license: existing.license || 'MIT', repository: `${repository}`, author: existing.author || `${name}`, homepage: `https://github.com/${repository}`, bugs: `https://github.com/${repository}/issues`, bin: existing.bin || '', main: existing.main || 'dist/cjs.js', engines: { node: `>= ${config.maintLTS} <7.0.0 || >= ${config.activeLTS}`, }, scripts: { start: 'npm run build -- -w', build: "cross-env NODE_ENV=production babel src -d dist --ignore 'src/**/*.test.js' --copy-files", clean: 'del-cli dist', commitlint: 'commitlint', commitmsg: 'commitlint -e $GIT_PARAMS', lint: 'eslint --cache src test', 'ci:lint:commits': 'commitlint --from=${CIRCLE_BRANCH} --to=${CIRCLE_SHA1}', 'lint-staged': 'lint-staged', prebuild: 'npm run clean', prepublish: 'npm run build', release: 'standard-version', 'release:ci': 'conventional-github-releaser -p angular', 'release:validate': 'commitlint --from=$(git describe --tags --abbrev=0) --to=$(git rev-parse HEAD)', security: 'npm audit', test: 'jest', 'test:watch': 'jest --watch', 'test:coverage': "jest --collectCoverageFrom='src/**/*.js' --coverage", 'ci:lint': 'npm run lint && npm run security', 'ci:test': 'npm run test -- --runInBand', 'ci:coverage': 'npm run test:coverage -- --runInBand', defaults: 'webpack-defaults', }, files: existing.files || ['dist/', 'lib/', 'index.js'], peerDependencies: existing.peerDependencies || { webpack: '^4.3.0' }, dependencies: existing.dependencies || {}, devDependencies: existing.devDependencies || {}, keywords: existing.keywords || ['webpack'], jest: { testEnvironment: 'node' }, 'pre-commit': 'lint-staged', 'lint-staged': { '*.js': ['eslint --fix', 'git add'], }, }) .save(); install(packages, { dev: false }); install(devPackages); };
JavaScript
0
@@ -2208,193 +2208,8 @@ n',%0A - 'release:ci': 'conventional-github-releaser -p angular',%0A 'release:validate':%0A 'commitlint --from=$(git describe --tags --abbrev=0) --to=$(git rev-parse HEAD)',%0A
42fa3ea0516cf927339cf66b97e7b534980f17d3
Update the namespace and update url.
gistfile1.js
gistfile1.js
// ==UserScript== // @name Pocketcasts Utils // @namespace http://waxd.nl // @version 0.1 // @description Some utilities for pocketcasts // @author MaienM // @match https://play.pocketcasts.com/* // @grant none // ==/UserScript== // Get the MutationObserver class for this browser. var MutationObserver = window.MutationObserver || window.WebKitMutationObserver; if (MutationObserver == null) { console.error("Your piece of shit browser does not support MutationObserver."); } $(function() { /* * Add a show-all button next to the show-more button. */ // Create the button. var showAll = $('<div class="show_all show_more">Show all</div>'); // Handle it's click. $(showAll).on('click', function() { var showMore = $('div.show_more:not(.show_all)'); // Every time the episodes list changes, click show more if there is still more to show. var listObserver = new MutationObserver(function(mutations, observer) { if ($(showMore).is(':visible')) { $(showMore).click(); } else { listObserver.disconnect(); } }); listObserver.observe($('#podcast_show div.episodes_list')[0], { subtree: true, childList: true, }); // Click it once to start. $(showMore).click(); }); // When needed, add it to the page. var pageObserver = new MutationObserver(function(mutations, observer) { var showMore = $('.show_more'); if ($(showMore).length > 0 && $('.show_all').length == 0) { // Add the button. $(showMore).after(showAll); // When the more button's visiblity changes, update the visibility of the all button as well. var showObserver = new MutationObserver(function(mutations, observer) { if ($(showMore).is(':visible')) { $(showAll).show(); } else { $(showAll).hide(); } }); showObserver.observe(showMore[0], { attributes: true, }); } }); pageObserver.observe($('#content_middle')[0], { subtree: true, childList: true, }); });
JavaScript
0
@@ -71,18 +71,251 @@ http +s :// -waxd.nl +gist.github.com/MaienM/e477e0f4e8ec3c1836a7/raw/25712be7ef9e7008549b4e0aa9dff7bb3871f1fc/gistfile1.js%0A// @updateURL https://gist.githubusercontent.com/MaienM/e477e0f4e8ec3c1836a7/raw/25712be7ef9e7008549b4e0aa9dff7bb3871f1fc/gistfile1.js %0A//
b9c1e04c795efc5ff4209d01174b82c72c1c4483
remove coverage from karma.conf
karma.conf.js
karma.conf.js
'use strict'; // Karma configuration // Generated on Wed Feb 17 2016 17:56:06 GMT+0100 (CET) module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['jasmine'], // list of files / patterns to load in the browser files: [ // bower:js 'app/bower_components/angular/angular.js', 'app/bower_components/angular-animate/angular-animate.js', 'app/bower_components/angular-bootstrap/ui-bootstrap-tpls.js', 'app/bower_components/angular-mocks/angular-mocks.js', 'app/bower_components/angular-ui-router/release/angular-ui-router.js', 'app/bower_components/jquery/dist/jquery.js', 'app/bower_components/bootstrap-sass/assets/javascripts/bootstrap.js', 'app/bower_components/ng-lodash/build/ng-lodash.js', // endbower 'app/index.js', 'app/src/**/*.module.js', 'app/src/**/*.js', 'app/src/**/*.html', ], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { 'app/src/**/*.html': ['ng-html2js'], 'app/src/**/!(*.spec).js': ['coverage'], 'app/index.js': ['coverage'] }, ngHtml2JsPreprocessor: { // strip this from the file path stripPrefix: 'app/', // create a single module that contains templates from all the files moduleName: 'templates' }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress', 'coverage'], coverageReporter: { type: 'html', // output coverage reports dir: 'coverage/' }, // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['PhantomJS', 'Chrome', 'Firefox', 'Safari'], // Chrome, Firefox, Safari // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false, // Concurrency level // how many browser should be started simultaneous concurrency: Infinity }); };
JavaScript
0
@@ -1319,90 +1319,8 @@ '%5D,%0A - 'app/src/**/!(*.spec).js': %5B'coverage'%5D,%0A 'app/index.js': %5B'coverage'%5D%0A @@ -1717,131 +1717,10 @@ ess' +%5D , - 'coverage'%5D,%0A%0A coverageReporter: %7B%0A type: 'html',%0A // output coverage reports%0A dir: 'coverage/'%0A %7D,%0A %0A%0A
d9c09eb3e9535a642ed7ded0b8059fe3b67187be
add working map
public/js/application.js
public/js/application.js
$(document).ready(function() { $.ajax({ type: 'GET', url: 'https://data.cityofnewyork.us/resource/erm2-nwe9.json?descriptor=Loud%20Music/Party', dataType: 'json', cache: true, success: function(data, textStatus, jqXHR){ console.log(data) }, fail: function(jqXHR, textStatus, errorThrown){ console.log(textStatus) } }) });
JavaScript
0.000001
@@ -358,13 +358,236 @@ %7D%0A %7D) +;%0A%0A L.mapbox.accessToken = 'pk.eyJ1Ijoiam1jYXN0cm8iLCJhIjoiY2llcjl2N2x6MDFneHNtbHpubjR3enhlZCJ9.3A7IZVloogRznOfadjSoGg';%0A var map = L.mapbox.map('map', 'jmcastro.cier6sgeg01h9silzqx44aeaw')%0A .setView(%5B40, -74.50%5D, 9);%0A %0A%7D);%0A
f9f4fc03b9a79cf7cf96db0f7e5567c346ed62ca
Resolve js directories
public/gulpfile.babel.js
public/gulpfile.babel.js
/** * Léo Le Bras * http://leolebras.com/ * * Work with Gulp * http://gulpjs.com/ * * Copyright 2014 - 2015 * Released under the MIT license * http://opensource.org/licenses/MIT * * Date of creative : 2014-01-04 * Last updated: 2015-11-27 */ import ExtractTextPlugin from 'extract-text-webpack-plugin'; import base64 from 'gulp-base64'; import babel from 'gulp-babel'; import clean from 'gulp-rimraf'; import cssbeautify from 'gulp-cssbeautify'; import cssnano from 'gulp-cssnano'; import gulp from 'gulp'; import imagemin from 'gulp-imagemin'; import inline from 'gulp-inline-source'; import postcss from 'gulp-postcss'; import sass from 'gulp-sass'; import sourcemaps from 'gulp-sourcemaps'; import uglify from 'gulp-uglify'; import ttf2woff from 'gulp-ttf2woff'; import ttf2woff2 from 'gulp-ttf2woff2'; import watch from 'gulp-watch'; import webpack from 'gulp-webpack'; import argv from 'yargs'; import config from './config.js'; const { srcDir, buildDir, cssDir, imgDir, sassDir, fontsDir, jsDir } = config.dir; // Sass gulp.task('sass', () => { let customFonts = {}, weights = [], fonts = config.fonts.custom; weights[300] = 'Light'; weights[400] = 'Regular'; weights[600] = 'SemiBold'; weights[700] = 'Bold'; weights[800] = 'ExtraBold'; for(let font in fonts) { customFonts[font] = {variants: {}}; fonts[font].map(weight => { let url = {}; config.fonts.formats.split(' ').map(format => { url[format] = `./../fonts/${font.replace(/\s+/g, '')}/${font.replace(/\s+/g, '')}-${weights[weight]}.${format}`; }); customFonts[font]['variants'][weight] = { normal: { url: url } }; }); } return gulp.src([srcDir + 'sass/*.scss']) .pipe(sourcemaps.init()) .pipe(sass.sync().on('error', sass.logError)) .pipe(postcss([ require('autoprefixer')({ browsers: config.css.autoprefixer }), require('postcss-font-magician')({ custom: customFonts, formats: config.fonts.formats }) ])) .pipe(cssbeautify()) .pipe(sourcemaps.write('.')) .pipe(gulp.dest(buildDir + cssDir));; }); // Babel gulp.task('js', () => { let entry = {}; config.javascript.entry.map(item => { entry = { ...entry, [item]: `${config.dir.srcDir}${config.dir.jsDir}${item}` }; }); return gulp.src(`${srcDir + jsDir}*.js`) .pipe(webpack({ devtool: 'source-map', entry: entry, output: { path: config.dir.buildDir + config.dir.jsDir, filename: '[name]', }, watch: argv.argv.watch, module: { loaders: [{ loader: 'babel-loader', query: config.javascript.babel }, { test: /\.vue$/, loader: 'vue' }] } })) .pipe(gulp.dest(buildDir + jsDir)); }); // Images gulp.task('img', () => ( gulp.src(srcDir + imgDir + '**') .pipe(imagemin()) .pipe(gulp.dest(buildDir + imgDir)) )); // HTML gulp.task('html', () => ( gulp.src(srcDir + '*.html') .pipe(gulp.dest(buildDir)) )); // Cleaner gulp.task('clean', () => ( gulp.src(buildDir, { read: false }).pipe(clean()) )); // Fonts gulp.task('fonts', () => { // ttf to woff gulp.src(srcDir + 'fonts/**/*.ttf') .pipe(ttf2woff()) .pipe(gulp.dest(buildDir + fontsDir)); // ttf to woff2 gulp.src(srcDir + 'fonts/**/*.ttf') .pipe(ttf2woff2()) .pipe(gulp.dest(buildDir + fontsDir)); }); // Dev gulp.task('dev', ['clean'], () => { gulp.start('fonts', 'sass', 'img', 'js', 'html'); watch(srcDir + imgDir + '**', () => gulp.start('img')); watch(srcDir + sassDir + '**/*.scss', () => gulp.start('sass')); watch(srcDir + fontsDir + '**/*', () => gulp.start('fonts')); watch(srcDir + '*.html', () => gulp.start('html')); }); // Build gulp.task('build', ['sass', 'img', 'js', 'html'], () => { // Move img files gulp.src(buildDir + imgDir + '**') .pipe(gulp.dest(buildDir + imgDir)); // Move html files + inline scripts gulp.src(buildDir + '*.html') .pipe(inline()) .pipe(gulp.dest(buildDir)); // Move fonts files gulp.src(srcDir + fontsDir + '**/*') .pipe(gulp.dest(buildDir + fontsDir)); // Base64 img in css files files and minify (except css font files) gulp.src(buildDir + cssDir + '*') .pipe(base64({ extensions: ['svg', 'png', 'jpg'] })) .pipe(cssnano()) .pipe(gulp.dest(buildDir + cssDir)); // Uglify js files gulp.src(buildDir + jsDir + '*.js') .pipe(babel(config.javascript.babel)) .pipe(uglify()) .pipe(gulp.dest(buildDir + jsDir)); }); /* _____ _ / ____| | | | | __ _ _| |_ __ | | |_ | | | | | _ \ | |__| | |_| | | |_) | \_____|\__,_|_| __/ . | | |_| */
JavaScript
0
@@ -2771,16 +2771,311 @@ %7D,%0A + resolve: %7B%0A extensions: %5B'', '.js', '.vue'%5D,%0A modulesDirectories: %5B%0A 'node_modules',%0A 'src/js/vendors',%0A 'src/js/helpers',%0A 'src/js/components'%0A %5D%0A %7D,%0A
10edeb80155d0bcdff3207497a63e0e3275fdc9d
test on Mobile Safari 13.0
karma.conf.js
karma.conf.js
/* eslint-disable no-console */ /* eslint-env node */ const { createDefaultConfig } = require('@open-wc/testing-karma'), merge = require('deepmerge'), baseCustomLaunchers = { FirefoxHeadless: { base: 'Firefox', flags: ['-headless'] } }, sauceCustomLaunchers = { slChrome: { base: 'SauceLabs', browserName: 'chrome', browserVersion: 'beta', platformName: 'Windows 10' } }, allCustomLaunchers = { ...baseCustomLaunchers, ...sauceCustomLaunchers }; module.exports = config => { const useSauce = process.env.SAUCE_USERNAME && process.env.SAUCE_ACCESS_KEY, customLaunchers = useSauce ? allCustomLaunchers : baseCustomLaunchers; if (!useSauce) { console.warn('Missing SAUCE_USERNAME/SAUCE_ACCESS_KEY, skipping sauce.'); } config.set( merge(createDefaultConfig(config), { coverageIstanbulReporter: { thresholds: { global: { statements: 90, branches: 85, functions: 100, lines: 90 } } }, customLaunchers, browsers: Object.keys(customLaunchers), files: [{ // runs all files ending with .test in the test folder, // can be overwritten by passing a --grep flag. examples: // // npm run test -- --grep test/foo/bar.test.js // npm run test -- --grep test/bar/* pattern: config.grep ? config.grep : 'test/**/*.test.js', type: 'module' }], esm: { nodeResolve: true }, client: { mocha: { ui: 'tdd' } }, sauceLabs: { testName: 'cosmoz-utils karma tests' }, reporters: ['dots', 'saucelabs'], singleRun: true // you can overwrite/extend the config further }) ); return config; };
JavaScript
0
@@ -388,16 +388,240 @@ ows 10'%0A +%09%09%7D,%0A%09%09slIphoneSimulator: %7B%0A%09%09%09base: 'SauceLabs',%0A%09%09%09browserName: 'Safari',%0A%09%09%09appiumVersion: '1.15.0',%0A%09%09%09deviceName: 'iPhone Simulator',%0A%09%09%09deviceOrientation: 'portrait',%0A%09%09%09platformVersion: '13.0',%0A%09%09%09platformName: 'iOS'%0A %09%09%7D%0A%09%7D,%0A
02aa972ed92949505ce629f5b3608cb649ebbfe9
Fix an error when running gulp test
gulp/test.js
gulp/test.js
var gulp = require('gulp'), gulpLoadPlugins = require('gulp-load-plugins'), karma = require('karma').server; var plugins = gulpLoadPlugins(); var defaultTasks = ['env:test', 'karma:unit', 'mochaTest']; gulp.task('env:test', function () { process.env.NODE_ENV = 'test'; }); gulp.task('karma:unit', function (done) { karma.start({ configFile: __dirname + '/../karma.conf.js', singleRun: true }, done); }); gulp.task('loadTestSchema', function () { require('../server.js'); require('../node_modules/meanio/lib/core_modules/module/util').preload('../packages/**/server', 'model'); }); gulp.task('mochaTest', ['loadTestSchema'], function () { return gulp.src('../packages/**/server/tests/**/*.js', {read: false}) .pipe(plugins.mocha({ reporter: 'spec' })); }); gulp.task('test', defaultTasks);
JavaScript
0.000044
@@ -406,20 +406,45 @@ ue%0A %7D, -done +function () %7B%0A done();%0A %7D );%0A%7D);%0A%0A
cbda2010dab05d6cd21e335936ef010503febaff
use type="tel" for trigger number input keyboard
src/react-numeral-input.js
src/react-numeral-input.js
import React from 'react'; import ReactDOM from 'react-dom'; import numeral from 'numeral'; const reg = /[^0-9km,]+/g; const default_fmt = '0,0'; const getCaretPosition = function(oField, fmt = default_fmt) { let iCaretPos = 0; const prefix = reg.exec(fmt); if (prefix && prefix.length) { iCaretPos += prefix[0].length; } if(document.selection){ oField.focus(); oSel = document.selection.createRange(); oSel.moveStart( 'character', -oField.value.length) iCaretPos = oSel.text.length; }else if (oField.selectionStart || oField.selectionStart == '0') { iCaretPos = oField.selectionStart; } return iCaretPos; }; const setCaretPosition = function(oField, index) { if (oField.setSelectionRange) { oField.setSelectionRange(index, index); } else { range = oField.createTextRange(); range.collapse(true); range.moveEnd('character', index); range.moveStart('character', index); range.select(); } }; const NumeralInput = React.createClass({ displayName: 'NumeralInput', propTypes: { onChange: React.PropTypes.func, fmt: React.PropTypes.string }, getDefaultProps: function() { return { fmt: default_fmt }; }, formatPos: function(val, index) { //unformat val = numeral().unformat(val); //format // val = numeral(val).format(this.props.fmt); let sub = val.substr(0, index-1); let dotCount = sub.split(',').length; let pos = index-dotCount; if (pos<0) { pos = 0; } return pos; }, focusOnChar: function(val, index) { let formatVal = numeral(val).format(this.props.fmt); let dotCount=0; let i = 0; let finalIndex = formatVal.length; while( i < formatVal.length) { let char = formatVal[i]; if( i === (index + dotCount)) { finalIndex = i; break } if( char === ','){ dotCount++; } i++; } if (!finalIndex) { finalIndex = 1; } return finalIndex; }, getInitialState: function() { return { inputStyle: this.props.inputStyle, placeholder: this.props.placeholder, value: this.getNumeralValue(this.props.value) }; }, getNumeralValue: function(val) { if (val) { return numeral(val).format(this.props.fmt); } return ''; }, componentWillReceiveProps: function(nextProps) { if( this.props.value === nextProps.value){ return; } let val = nextProps.value; let formatVal = ''; if (!reg.test(val)) { formatVal = this.getNumeralValue(val); } // formatVal = this.getNumeralValue(val); this.setState( { value: formatVal }, () => { const node = ReactDOM.findDOMNode(this); setCaretPosition(node, this.state.pos, this.props.fmt); }); }, changeHandler: function() { const node = ReactDOM.findDOMNode(this); let pos = getCaretPosition(node, this.props.fmt); let val = node.value; pos = this.formatPos(this.state.value, pos); //1,000,000 -> 1000000 const reTest = reg.test(val); if (!reTest) { val = numeral(val).value(); let oVal = numeral(this.state.val); if ((oVal+'').length < (val+'').length) { pos = this.focusOnChar(val, ++pos); } else if ((oVal+'').length > (val+'').length) { pos = this.focusOnChar(val, --pos); } else { pos = this.focusOnChar(val, pos); } } val = numeral(val).value(); //parentNode onChange function this.setState( { pos: pos, value: val || '' }, () => { if (this.props.onChange) { this.props.onChange(val); } }) }, render: function() { const { fmt, ...rest} = this.props; return ( <input type="text" {...rest} value={this.state.value} onChange = {this.changeHandler} /> ); } }); export default NumeralInput;
JavaScript
0.000003
@@ -3743,18 +3743,17 @@ type=%22te -xt +l %22 %7B...re
13c83991a7007c59658e801ddbcf972786fbd4b5
Add a basic settings object to state.js
src/tracker/state.js
src/tracker/state.js
var STATE = (function(){ var stateChangedEvents = []; var triggerStateChanged = function(changeType, changeDetail){ for(var callback of stateChangedEvents){ callback(changeType, changeDetail); } }; /* * Internal class constructor. */ var CLS = function(){ this.resetState(); }; /* * Resets the state to default values. */ CLS.prototype.resetState = function(){ this._savefile = null; this._isTracking = false; triggerStateChanged("data", "reset"); }; /* * Returns the savefile object, creates a new one if needed. */ CLS.prototype.getSavefile = function(){ if (!this._savefile){ this._savefile = new SAVEFILE(); } return this._savefile; }; /* * Returns true if the database file contains any data. */ CLS.prototype.hasSavedData = function(){ return this._savefile != null; }; /* * Returns true if currently tracking message. */ CLS.prototype.isTracking = function(){ return this._isTracking; }; /* * Toggles the tracking state. */ CLS.prototype.toggleTracking = function(){ this._isTracking = !this._isTracking; triggerStateChanged("tracking", this._isTracking); }; /* * Combines current savefile with the provided one. */ CLS.prototype.uploadSavefile = function(readFile){ this.getSavefile().combineWith(readFile); triggerStateChanged("data", "upload"); }; /* * Triggers a savefile download, if available. */ CLS.prototype.downloadSavefile = function(){ if (this.hasSavedData()){ DOM.downloadTextFile("dht.txt", this._savefile.toJson()); } }; /* * Registers a Discord server and channel. */ CLS.prototype.addDiscordChannel = function(serverName, serverType, channelId, channelName){ var serverIndex = this.getSavefile().findOrRegisterServer(serverName, serverType); if (this.getSavefile().tryRegisterChannel(serverIndex, channelId, channelName) === true){ triggerStateChanged("data", "channel"); } }; /* * Adds all messages from the array to the specified channel. */ CLS.prototype.addDiscordMessages = function(channelId, discordMessageArray){ if (this.getSavefile().addMessagesFromDiscord(channelId, discordMessageArray)){ triggerStateChanged("data", "messages"); } }; /* * Adds a listener that is called whenever the state changes. If trigger is true, the callback is ran after adding it to the listener list. * The callback is a function that takes subject (generic type) and detail (specific type or data). */ CLS.prototype.onStateChanged = function(callback, trigger){ stateChangedEvents.push(callback); trigger && callback(); }; return new CLS(); })();
JavaScript
0.000002
@@ -213,29 +213,561 @@ %7D%0A %7D;%0A %0A + var defineTriggeringProperty = function(obj, type, property)%7B%0A var name = %22_%22+property;%0A %0A Object.defineProperty(obj, property, %7B%0A get: (() =%3E obj%5Bname%5D),%0A set: (value =%3E %7B%0A obj%5Bname%5D = value;%0A triggerStateChanged(type, property);%0A %7D)%0A %7D);%0A %7D;%0A %0A /*%0A * Internal settings class constructor.%0A */%0A var SETTINGS = function()%7B%0A %7D;%0A %0A /*%0A * Resets settings without triggering state changed event.%0A */%0A SETTINGS.prototype._reset = function()%7B%0A this._autoscroll = true;%0A %7D;%0A %0A /*%0A - * Interna @@ -809,32 +809,68 @@ S = function()%7B%0A + this.settings = new SETTINGS();%0A this.resetSt @@ -1004,16 +1004,16 @@ = null;%0A - this @@ -1034,16 +1034,44 @@ false;%0A + this.settings._reset();%0A trig
e4b929506588b5707d2947c4f5b629e8ab540135
Remove Aside
lib/components/pickers/LocationPicker.react.js
lib/components/pickers/LocationPicker.react.js
'use strict'; var React = require('react'); var SingleSelect2 = require('./SingleSelect2.react'); var classNames = require('classnames'); var LocationPicker = React.createClass({ getInitialState() { return{ value: this.props.value || [''], selecting: true }; }, _toggleState(item) { this.setState({selecting: !this.state.selecting}); }, _onResults(value, collection) { this.setState({ value: value }); }, _onClick() { this.props.onSelect(this.state.value); }, render() { return( <div> {this.props.editable ? this.renderSelect() : this.renderLabel()} </div> ); }, renderSelect() { return( <div className='inline-block'> <SingleSelect2 collection={this.props.data} ref='select' value={this.props.value} editable={this.props.editable} onSelect={this._toggleState} onRemove={this._toggleState} onResults={this._onResults} /> {this.state.selecting ? this.renderButton() : null} </div> ); }, renderButton() { return ( <aside> <button className='no-style-btn mock-bttn padding' onClick={this._onClick}> <i className='fa fa-plus'/> </button> </aside> ); }, renderLabel() { return(<label>{this.props.value}</label>); } }); module.exports = LocationPicker;
JavaScript
0.000001
@@ -1128,24 +1128,8 @@ n (%0A - %3Caside%3E%0A @@ -1139,18 +1139,16 @@ button %0A - @@ -1190,18 +1190,16 @@ adding'%0A - @@ -1231,18 +1231,16 @@ - %3Ci class @@ -1265,18 +1265,16 @@ %3E%0A - %3C/button @@ -1279,23 +1279,8 @@ on%3E%0A - %3C/aside%3E%0A
5cfee4759bdb391f6ecc2b9c6d79147d8ae018c2
Make Icebox really not reorderable.
public/javascript/tracklight.js
public/javascript/tracklight.js
$(document).ready(function() { // Fetches all tickets, page by page. Updates tickets already // in the DOM and adds new tickets to the Icebox. function fetchTickets(page) { function fetchTicketsFromPage(page) { $.getJSON("/tickets?page="+page, function(data) { // Add the tickets to the Icebox. $.each(data, function(i, ticket_details) { $("#icebox").append("<li class='ticket-marker' id='ticket_"+ticket_details.id+"_marker' />"); $("#ticket_"+ticket_details.id).oror(function() { return createTicket(ticket_details.id).appendTo($("#icebox")); }).fn('update', ticket_details); }); // Fetch more. if (data.length > 0) fetchTicketsFromPage(page+1); }); } fetchTicketsFromPage(1); } // Creates and returns a new, unloaded ticket. Call #update to load. function createTicket(id) { return $("#ticket_template").clone(true) .attr({id: "ticket_"+id, ticket_id: id}) .fn({ // If ticket_details is not given, details will be fetched. update: function(ticket_details) { var self = $(this); function updateWithDetails(ticket_details) { self.removeClass('loading'); self.find(".title").text(ticket_details.title); self.find(".link").attr({href: ticket_details.url}).text('#'+ticket_details.id); self.find(".requester").text(ticket_details.requester); self.find(".responsible").text(ticket_details.responsible); self.find(".state").text(ticket_details.state); self.find(".description").text(ticket_details.description); self.find(".tags").text(ticket_details.tags); } if (ticket_details != undefined) updateWithDetails(ticket_details); else $.getJSON("/tickets/"+self.attr("ticket_id"), updateWithDetails); return self; } }); } $(".list").fn({ // Moves and creates tickets to match the given list of ticket ids. // After update, the list has exactly those tickets whose ids are given, // and in the given order. update: function(ticket_ids) { var self = $(this); $.each(ticket_ids, function(i, id) { // Find or create ticket by id. var ticket = $("#ticket_"+id).oror(function() { return createTicket(id); }); // Insert in the correct place. if (i == 0) { ticket.prependTo(self); } else { ticket.insertAfter(self.find(".ticket:eq("+(i-1)+")")[0]); } }); // Remove any extra tickets. self.find(".ticket:gt("+(ticket_ids.length-1)+")").remove(); }, save: function() { var ticket_ids = $(this).sortable("serialize") $.post('/lists/'+$(this).attr('id'), ticket_ids); } }).sortable({ connectWith: [".list"], cancel: ".disclosure", change: function(e, ui) { if (ui.placeholder.parent().is("#icebox")) { var id = ui.item.attr("id"); ui.placeholder.insertAfter("#"+id+"_marker"); } }, update: function(e, ui) { $(this).not("#icebox").fn('save'); } }); $(".disclosure").click(function() { var shouldClose = $(this).hasClass("open"); $(this).parent().find(".details").toggle(!shouldClose).end().end().toggleClass("open", !shouldClose); }); // Fetch lists $.getJSON("/lists", function(lists) { // Fetch tickets for lists $.each(lists, function(list, ticket_ids) { $("#"+list).fn('update', ticket_ids); }) }) // Fetch all tickets and add extras to Icebox fetchTickets(); });
JavaScript
0
@@ -2015,16 +2015,388 @@ .list%22). +sortable(%7B%0A connectWith: %5B%22.list%22%5D,%0A cancel: %22.disclosure%22,%0A change: function(e, ui) %7B%0A if (ui.placeholder.parent().is(%22#icebox%22)) %7B%0A var id = ui.item.attr(%22id%22);%0A ui.placeholder.insertAfter(%22#%22+id+%22_marker%22);%0A %7D%0A %7D,%0A update: function(e, ui) %7B%0A $(this).not(%22#icebox%22).fn('save');%0A %7D%0A %7D).not(%22#icebox%22). fn(%7B%0A @@ -3260,365 +3260,8 @@ %7D%0A - %7D).sortable(%7B%0A connectWith: %5B%22.list%22%5D,%0A cancel: %22.disclosure%22,%0A change: function(e, ui) %7B%0A if (ui.placeholder.parent().is(%22#icebox%22)) %7B%0A var id = ui.item.attr(%22id%22);%0A ui.placeholder.insertAfter(%22#%22+id+%22_marker%22);%0A %7D%0A %7D,%0A update: function(e, ui) %7B%0A $(this).not(%22#icebox%22).fn('save');%0A %7D%0A %7D)
567afe992d3e4a6e1a57530d366a853814a77282
change all the parameter name that in relation to unlogin redirect
public/js/admin/login.js
public/js/admin/login.js
/** * 登录脚本 */ var page = { loginFormDom: $("#login-form"), usernameDom: $('#username'), passwordDom: $('#password'), rememberMeDom: $('#remember-me'), toolBarDom: $('.tool-bar'), init: function(){ //初始化公共方法 Public.init(), //初始化 UI 组件 Widgets.init(), this.initDom(), this.initValidator(), this.addEvent(); }, initDom: function(){ var self = this; //添加操作按钮 var jumpUri = 'admin'; var reg = new RegExp("(^|&)" + 'historyUri' + "=([^&]*)(&|$)"); var uriResult = window.location.search.substr(1).match(reg); if (uriResult != null) { jumpUri = unescape(uriResult[2]); } self.toolBarDom.html( Widgets.OperateButtons._button(self, 'login', 'login', 'LOGIN', function(){ window.location = jumpUri; }, 'btn-success col-xs-12') ); }, initValidator: function(){ var self = this; self.loginFormDom.validate({ rules: { username: { required: ["用户名"], }, password: { required: ["密码"], rangelength: [6, 30] } }, errorPlacement : function(error, element) { element.parent().addClass('has-error'); $('#'+element.attr('id')+'-error').html(error.text()); },success: function( error, element){ $(element).parent().removeClass('has-error'); $('#'+$(element).attr('id')+'-error').html(''); } }); }, addEvent: function(){ var self = this; document.onkeydown = function(e){ var ev = document.all ? window.event : e; if(ev.keyCode==13) { ev.keyCode=0; self.toolBarDom.find('#login').click(); return false; } } }, getPostData: function(){ var self = this; var isRememberMe = $('#remember-me').is(':checked'); return { username: self.usernameDom.val(), password: self.passwordDom.val(), remember_me: isRememberMe, }; } }; $(function() { page.init(); });
JavaScript
0.000001
@@ -471,20 +471,23 @@ var -jump +history Uri = 'a @@ -679,20 +679,23 @@ -jump +history Uri = un @@ -884,12 +884,15 @@ n = -jump +history Uri;
01b1ebf71012623351ed79cebac615a684885857
add theme_color to manifest
server/manifest.js
server/manifest.js
"use strict"; // Manifest for web application - https://w3c.github.io/manifest/ var pkg = require("./../package.json"); module.exports = function manifest(req) { var data = { name: pkg.name, lang: "en-US", background_color: "#181818", display: "fullscreen", orientation: "any", icons: [ {src: "logo32.png", sizes: "32x32", type: "image/png"}, {src: "logo120.png", sizes: "120x120", type: "image/png"}, {src: "logo128.png", sizes: "128x128", type: "image/png"}, {src: "logo152.png", sizes: "152x152", type: "image/png"}, {src: "logo180.png", sizes: "180x180", type: "image/png"}, {src: "logo192.png", sizes: "192x192", type: "image/png"} ] }; var proto = (req.connection && req.connection.encrypted) ? "https://" : "http://"; var path = (req.url.match(/(.+)\?!\/manifest\.json/) || [null, "/"])[1]; data.start_url = proto + req.headers["host"] + path; return JSON.stringify(data); };
JavaScript
0
@@ -245,16 +245,44 @@ 81818%22,%0A + theme_color: %22#181818%22,%0A disp
216c292220b403d57a5ccac2b1348255e87ea865
Improve project detection robustness
core/cb.project/main.js
core/cb.project/main.js
// Requires var Q = require('q'); var _ = require('lodash'); var wrench = require('wrench'); var path = require('path'); var utils = require('../utils'); var ProjectType = require('./project').ProjectType; // Supported project types // This list is ordered var SUPPORTED = [ // PaaS require("./appengine"), require("./procfile"), require("./parse"), // Frameworks require("./django"), require("./gradle"), require("./grails"), require("./meteor"), // Languages require("./c"), require("./d"), require("./dart"), require("./go"), require("./clojure"), require("./java"), require("./logo"), require("./php"), require("./node"), require("./play"), require("./python"), require("./ruby"), require("./scala"), require("./lua"), // Fallbacks require("./static"), require("./makefile") ]; // Returns true if lang is supported otherwise false function supports(projectDir, projectType) { // No detector if (!projectType.detector) { return Q(false); } // Detection script return utils.execFile(projectType.detector, [projectDir]) .then( utils.constant(true), utils.constant(false) ); } // Detect the project type for a workspace var detectProjectTypes = function(projectDir) { var _supports = _.partial(supports, projectDir); // Try all our project types, return first supported return Q.all(_.map(SUPPORTED, _supports)) .then(function(supported_list) { var idx = supported_list.indexOf(true); if(idx === -1) { throw new Error("No supported project"); } // List of supported project types return _.chain(SUPPORTED) .filter(function(lang, idx) { return supported_list[idx]; }) .value(); }) .fail(utils.constant([])); }; // Merge into one project type var detectProject = function(workspace, project) { return detectProjectTypes(workspace.root).then(function(_types) { if (!_.size(_types)) { project.clear(); return Q.reject(new Error("No project detected for this workspace")); } // Define new project return project.define(_types); }).then(function() { return project; }); }; // Get project type info by id var getProjectType = function(typeId) { return _.find(SUPPORTED, function(pType) { return pType.id == typeId || _.contains(pType.otherIds, typeId); }); }; // Set project sample // Tke a project type id and replace workspace content with it var useProjectSample = function(root, typeId) { var pType = getProjectType(typeId); if (!pType) return Q.reject(new Error("Invalid project type id")); if (!pType.sample) return Q.reject(new Error("This project type has no sample")); // todo: improve this copy to not delete the directory and recreate it after return Q.nfcall(wrench.copyDirRecursive, pType.sample, root, { 'forceDelete': true }).then(function() { return pType; }); }; function setup(options, imports, register) { var workspace = imports.workspace; var events = imports.events; var logger = imports.logger.namespace("project"); var prev = Q(); // Create the project type var project = new ProjectType(workspace, events, logger); // Do the project detection manually project.detect = _.partial(detectProject, workspace, project); // Detect the project when the fs change var throttled = _.throttle(project.detect, 5*60*1000); events.on("watch.change.update", throttled); events.on("watch.change.create", throttled); events.on("watch.change.delete", throttled); events.on("watch.watching.success", throttled); return Q().then(function() { if (!options.forceProjectSample) return; logger.log("set workspace content with sample", options.forceProjectSample) return useProjectSample(workspace.root, options.forceProjectSample).fail(function(err) { logger.exception(err, false); return Q(); }) }) .then(function() { return { "project": project, "projectTypes": { "SUPPORTED": SUPPORTED, 'add': function addProjectType(module) { SUPPORTED.push(module); return project.detect(); }, 'useSample': function(typeId) { return useProjectSample(workspace.root, typeId).then(function(pType) { // Update project type project.detect(); return pType; }); } } } }); } // Exports module.exports = setup;
JavaScript
0
@@ -1122,16 +1122,30 @@ xecFile( +'/bin/bash', %5B projectT @@ -1158,17 +1158,16 @@ tector, -%5B projectD
401c335ec3d4b9a3f094d92fb05ecc93e31164c8
Add emoji RegExp
src/renderer/MyCompiler.js
src/renderer/MyCompiler.js
import React from 'react' // import Compiler from 'imports?React=react!md2react' import Compiler from 'imports?React=react!../../node_modules/md2react/src/index' import path from 'path' import Highlight from 'react-highlight' let $ = React.createElement; function highlight(code, lang, key) { return <Highlight className={lang}>{code}</Highlight>; } export default class MyCompiler extends Compiler { constructor(opts) { opts.highlight = highlight; super(opts); } compile({md, dirname, search, indication}) { this.dirname = dirname; if (search === '') { this.search = null; } else { this.search = new RegExp(`(${search})`, 'ig'); } this.indication = indication; this.ids = {}; this.marksCount = 0; return super.compile(md); } root(node, defs, key, tableAlign) { return $('div', { key, className: 'markdown-body' }, this.toChildren(node, defs, key)); } text(node, defs, key, tableAlign) { if (!this.search) { return node.value; } let children = []; let words = node.value.split(this.search); words = words.map((word, i) => { if (i % 2 === 0) { return word } return $('mark', { className: this.marksCount === this.indication ? 'indicated' : '', ref: `mark${this.marksCount++}` }, word); }); return $('span', {}, words); } image({src, title, alt}, defs, key, tableAlign) { if(!(/^https?:\/\//.test(src))) { src = path.resolve(this.dirname, src); } return $('img', { key, src: src, title: title, alt: alt }); } link(node, defs, key, tableAlign) { if(!(/^https?:\/\//.test(node.href))) { node.href = path.resolve(this.dirname, node.href); } return $('a', { key, href: node.href, title: node.title }, this.toChildren(node, defs, key)); } heading(node, defs, key, tableAlign) { let text = node.children .filter((child) => { return child.type == 'text' }) .map((child) => { return child.value }) .join(''); let id = text .toLowerCase() .replace(/\s/g, '-') .replace(/[!<>#%@&='"`:;,\.\*\+\(\)\{\}\[\]\\\/\|\?\^\$]+/g, '') if (this.ids[id] == null) { this.ids[id] = 0; } else { this.ids[id]++; id = `${id}-${this.ids[id]}` } return $(('h'+node.depth.toString()), {key}, [ $('a', {key: key+'-a', id: id, className: 'anchor', href: '#'+id}, [ $('span', {key: key+'-a-span', className: 'icon icon-link'}) ]), this.toChildren(node, defs, key) ]); } }
JavaScript
0.999999
@@ -399,16 +399,54 @@ piler %7B%0A + static rEmoji = /:%5B0-9a-z_+-%5D+:/g;%0A%0A constr @@ -455,24 +455,24 @@ tor(opts) %7B%0A - opts.hig @@ -671,16 +671,56 @@ search = + %7B%0A text: search,%0A regExp: new Reg @@ -743,16 +743,24 @@ %60, 'ig') +%0A %7D ;%0A %7D%0A @@ -1058,24 +1058,26 @@ bleAlign) %7B%0A +%0A%0A if (!thi @@ -1084,16 +1084,63 @@ s.search + %7C%7C node.value.indexOf(this.search.text) === -1 ) %7B%0A @@ -1189,16 +1189,16 @@ n = %5B%5D;%0A - let @@ -1233,16 +1233,23 @@ s.search +.regExp );%0A w
09c4808e52aafffe7c4601e655307241d589250f
include css
karma.conf.js
karma.conf.js
// karma.conf.js module.exports = function(config) { config.set({ frameworks: ['jasmine', 'requirejs'], files: [ {pattern: 'tests/common.js', included: true}, {pattern: 'tests/fixtures/*.html', included: false}, {pattern: 'tests/spec/*.js', included: false}, {pattern: 'tests/vendor/**/*.js', included: false}, {pattern: 'tests/utils/*.js', included: false}, {pattern: 'rich/**/*.js', included: false}, {pattern: 'demos/src/static/js/**/*.js', included: false}, {pattern: 'demos/src/static/js/**/*.html', included: false}, {pattern: 'demos/src/static/css/styles.css', included: true}, 'tests/karma-main.js' ], preprocessors: { 'rich/**/*.js': 'coverage' }, exclude: [ '**/karma.conf.js' ], reporters: ['dots'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], singleRun: false }); };
JavaScript
0.000054
@@ -224,32 +224,94 @@ cluded: false%7D,%0A + %7Bpattern: 'tests/fixtures/test.css', included: true%7D,%0A %7Bpattern
f1b173558ffa7a3c5475abd010bcaad9d7d237d8
fix schedule rules to local server time
server/schedule.js
server/schedule.js
const schedule = require('node-schedule') const axios = require('axios') const cheerio = require('cheerio') const Account = require('APP/db').Accounts const transformData = require('./utils').transformData const clearWhiteSpace = require('./utils').clearWhiteSpace const clearFlairWhiteSpace = require('./utils').clearFlairWhiteSpace const clearUsernameLines = require('./utils').clearUsernameLines const weeklyTimelineUpdateRule = new schedule.RecurrenceRule() weeklyTimelineUpdateRule.minute = 55 weeklyTimelineUpdateRule.hour = 15 weeklyTimelineUpdateRule.dayOfWeek = 0 const hourlyStatsUpdateRule = new schedule.RecurrenceRule() hourlyStatsUpdateRule.minute = 0 const fetchLeaderboardsAccountsRule = new schedule.RecurrenceRule() fetchLeaderboardsAccountsRule.minute = 55 fetchLeaderboardsAccountsRule.hour = 15 const weeklyTimelineUpdate = schedule.scheduleJob(weeklyTimelineUpdateRule, function() { Account.findAll() .then(allAccounts => allAccounts.map(account => account.update({ timeline: account.timeline.concat(account.getWeeklyStats()) }))) .catch(console.error) }) const hourlyStatsUpdate = schedule.scheduleJob(hourlyStatsUpdateRule, function() { Account.findAll() .then(allAccounts => allAccounts.map(account => { axios.get(account.url) .then(response => response.data) .then(data => { const newStats = fetchStats(data) account.update({ allTime: newStats[0], rolling300: newStats[1], flairs: newStats[2], name: newStats[3] }) }) })) }) const fetchLeaderboardsAccounts = schedule.scheduleJob(fetchLeaderboardsAccountsRule, function() { axios.get('http://tagpro-radius.koalabeast.com/boards') .then(response => response.data) .then(data => { const $ = cheerio.load(data) fetchLeaderboards($) }) }) function fetchStats(data) { const $ = cheerio.load(data) return [fetchAllTime($), fetchRolling300($), fetchFlairs($), fetchName($), fetchDegrees($)] } function fetchAllTime($) { let dataArr = [] $('#all-stats').find('td').each(function(index, elem) { dataArr.push(elem.firstChild.data) }) dataArr = transformData(dataArr, 'all') return dataArr } function fetchRolling300($) { let dataArr = [] $('#rolling').find('td').each(function(index, elem) { dataArr.push(elem.firstChild.data) }) dataArr = transformData(dataArr, 'rolling') return dataArr } function fetchName($) { return clearWhiteSpace($('.profile-name').text()) } function fetchDegrees($) { return clearWhiteSpace($('.profile-detail').find('td')[5].children[0].data.slice(0, -1)) } function fetchFlairs($) { const dataArr = [] $('#owned-flair').find('.flair-header').each(function(index, elem) { const flairName = clearFlairWhiteSpace(elem.firstChild.data) if (flairName !== 'Remove Flair') dataArr.push({flairName}) }) $('#owned-flair').find('.flair-footer').each(function(index, elem) { let flairCount = clearWhiteSpace(elem.firstChild.next.firstChild.data) flairCount = +flairCount.split(':')[1] || 0 if (index !== dataArr.length) dataArr[index].flairCount = flairCount }) return dataArr } function fetchLeaderboards($) { const accountArr = [] $('#daily').find('a').each(function(index, elem) { accountArr.push({ name: clearUsernameLines(elem.lastChild.data), url: `http://tagpro-radius.koalabeast.com${elem.attribs.href}` }) }) accountArr.forEach(account => Account.findOrCreate({ where: { url: account.url }, defaults: { name: account.name } })) } module.exports = fetchStats
JavaScript
0
@@ -526,17 +526,17 @@ hour = 1 -5 +9 %0AweeklyT @@ -810,17 +810,17 @@ hour = 1 -5 +9 %0A%0A%0Aconst
da7ed22007d80514bce44163732525d230e63e60
Update the karma.conf.js to run once
karma.conf.js
karma.conf.js
module.exports = function(config) { config.set({ basePath: '', frameworks: ['mocha', 'chai', 'sinon'], files: [ './test/**/*.spec.js' ], exclude: [ './test/PolicyEngine.spec.js' ], preprocessors: { './test/**/*.spec.js': ['webpack', 'sourcemap'] }, // webpack configuration webpack: { devtool: 'inline-source-map' }, reporters: ['spec', 'html'], specReporter: { maxLogLines: 5, // limit number of lines logged per test suppressErrorSummary: false, // do not print error summary suppressFailed: false, // do not print information about failed tests suppressPassed: false, // do not print information about passed tests suppressSkipped: false, // do not print information about skipped tests showSpecTiming: true, // print the time elapsed for each spec failFast: false // test would finish with error when a first fail occurs. }, // the default configuration htmlReporter: { outputFile: 'test/units.html', // Optional pageTitle: 'Unit Tests', subPageTitle: 'reThink Project performance tests', groupSuites: true, useCompactStyle: true, useLegacyStyle: true }, plugins: ['karma-spec-reporter', 'karma-webpack', 'karma-sourcemap-loader', 'karma-mocha', 'karma-chai', 'karma-sinon', 'karma-htmlfile-reporter', 'karma-mocha-reporter', 'karma-chrome-launcher'], // customDebugFile: './test/units.html', // customContextFile: './test/units.html', client: { mocha: { reporter: 'html' }, captureConsole: true }, port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['ChromeTravis'], customLaunchers: { ChromeTravis: { base: 'Chrome', flags: [ '--disable-web-security', '--ignore-certificate-errors' ] } }, // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false }); };
JavaScript
0
@@ -2254,20 +2254,19 @@ gleRun: -fals +tru e%0A %7D);%0A
45fee2355f56f24c092ed1969b0e52f243d98e9e
Make comment deletion play nice with editing
public/js/application.js
public/js/application.js
$(document).ready(function() { // This is called after the document has loaded in its entirety // This guarantees that any elements we bind to will exist on the page // when we try to bind to them // See: http://docs.jquery.com/Tutorials:Introducing_$(document).ready() $('.comment-form').on('submit', function(event){ event.preventDefault(); var url = $(this).attr('action'); var data = $(this).serialize(); var request = $.ajax({ url: url, method: 'POST', data: data }); request.done(function(response){ $('.comments ul').append( $('<li id='+response.id+'>' + response.content + " <a class='comment-edit' href='#edit'>Edit</a> <a class='comment-delete' href='#delete'>Delete</a>" + '</li>') ) }); }); $('.comments').on('click', '.comment-edit', function(event){ event.preventDefault(); if ($('.comments').find('#dynaform').attr('action')){ formText = $('#dynaform input[type=text]').val(); $('#dynaform').replaceWith(formText + " <a class='comment-edit' href='#edit'>Edit</a> <a class='comment-delete' href='#delete'>Delete</a>"); }; $listItem = $(this).parent(); commentId = $listItem.attr('id') commentText = $listItem .clone() .children() .remove() .end() .text() .trim(); $listItem.html('<form id="dynaform" action="/comments/'+commentId+'/edit" method="post"><input type="hidden" name="_method" value="put" ><input name="content" type="text" value="'+commentText+'"><input type="submit"></form>'); $listItem.on('submit', '#dynaform', function(event){ event.preventDefault(); url = $(this).attr('action'); data = $(this).serialize(); request = $.ajax({ url: url, method: 'put', data: data }); request.done(function(text){ console.log(text); $listItem.html(text + " <a class='comment-edit' href='#edit'>Edit</a> <a class='comment-delete' href='#delete'>Delete</a>"); }); }); }); $('.comments').on('click', '.comment-delete', function(event){ event.preventDefault(); url = $(this).attr('action') request = $.ajax({ url: url, method: 'delete' }); request.done(function(id){ $('.comments #'+id).remove(); }); }); });
JavaScript
0
@@ -664,26 +664,25 @@ e.content + -%22 +' %3Ca class='co @@ -670,33 +670,33 @@ ent + '%3Ca class= -' +%22 comment-edit' hr @@ -687,38 +687,38 @@ comment-edit -' +%22 href= -' +%22 #edit -' +%22 %3EEdit%3C/a%3E %3Ca @@ -710,35 +710,37 @@ it%22%3EEdit%3C/a%3E - %3Ca +%3Cform class= -' +%22 comment-dele @@ -745,44 +745,159 @@ lete -' href='#delete'%3EDelete%3C/a%3E%22 + '%3C/li +%22 action=%22/comments/'+response.id+'/delete%22 method=%22post%22%3E%3Cinput type=%22hidden%22 name=%22_method%22 value=%22delete%22%3E%3Cinput type=%22submit%22 value=%22Delete%22%3E%3C/form %3E')%0A @@ -1121,24 +1121,71 @@ t%5D').val();%0A + id = $('#dynaform').parent().attr('id')%0A%0A $('#dy @@ -1212,25 +1212,25 @@ (formText + -%22 +' %3Ca class='c @@ -1219,33 +1219,33 @@ xt + ' %3Ca class= -' +%22 comment-edit' hr @@ -1236,38 +1236,38 @@ comment-edit -' +%22 href= -' +%22 #edit -' +%22 %3EEdit%3C/a%3E %3Ca @@ -1259,35 +1259,37 @@ it%22%3EEdit%3C/a%3E - %3Ca +%3Cform class= -' +%22 comment-dele @@ -1294,36 +1294,152 @@ lete -' href='#delete'%3EDelete%3C/a%3E%22 +%22 action=%22/comments/'+id+'/delete%22 method=%22post%22%3E%3Cinput type=%22hidden%22 name=%22_method%22 value=%22delete%22%3E%3Cinput type=%22submit%22 value=%22Delete%22%3E%3C/form%3E' );%0A @@ -2036,24 +2036,64 @@ Default();%0A%0A + id = $(this).parent().attr('id')%0A%0A url = @@ -2357,17 +2357,17 @@ (text + -%22 +' %3Ca clas @@ -2360,33 +2360,33 @@ xt + ' %3Ca class= -' +%22 comment-edit' hr @@ -2385,22 +2385,22 @@ edit -' +%22 href= -' +%22 #edit -' +%22 %3EEdi @@ -2408,19 +2408,21 @@ %3C/a%3E - %3Ca +%3Cform class= -' +%22 comm @@ -2435,36 +2435,152 @@ lete -' href='#delete'%3EDelete%3C/a%3E%22 +%22 action=%22/comments/'+id+'/delete%22 method=%22post%22%3E%3Cinput type=%22hidden%22 name=%22_method%22 value=%22delete%22%3E%3Cinput type=%22submit%22 value=%22Delete%22%3E%3C/form%3E' );%0A
b452560bcaf90ea6e6b01e10797b4991980081e5
Allow specifying AngularJS version for testing using env variable
karma.conf.js
karma.conf.js
module.exports = function(config) { config.set({ basePath: '', frameworks: ['jasmine'], files: [ 'https://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js', 'https://code.angularjs.org/1.2.17/angular-mocks.js', 'src/*.js', 'test/**/*.spec.js' ], exclude: [], preprocessors: {}, reporters: ['progress'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['PhantomJS'], singleRun: false }) }
JavaScript
0
@@ -463,11 +463,286 @@ alse%0A%09%7D) +%0A%0A%09if(process.env.ANGULARJS_VERSION) %7B%0A%09%09config.files%5B0%5D = 'https://ajax.googleapis.com/ajax/libs/angularjs/' +%0A%09%09%09process.env.ANGULARJS_VERSION + '/angular.min.js'%0A%0A%09%09config.files%5B1%5D = 'https://code.angularjs.org/' +%0A%09%09%09process.env.ANGULARJS_VERSION + '/angular-mocks.js'%0A%09%7D %0A%7D%0A
5ff3bac8250e01e9cfa47139abf28e6b86826661
Remove test code
bin/FetchParseGitHubArchive.js
bin/FetchParseGitHubArchive.js
#!/usr/bin/env node //References & Resources //http://www.spacjer.com/blog/2014/02/10/defining-node-dot-js-task-for-heroku-scheduler/ //http://stackoverflow.com/questions/25659134/insert-error-using-node-js-async-series var archive = require('./mikeal-githubarchive.js'); var fs = require('fs'); var util = require('util'); var mongodb = require('mongodb'); var MongoClient = mongodb.MongoClient; var async = require('async'); var assert = require('assert'); var underscore = require('underscore'); var moment = require('moment'); var path = require("path"); GetParse(); //Fetch GitHub Archives, parse 'PushEvent' event notifications and insert into MongoDB //Sample JSON generated //{"078d40cc5":{"created_at":"2014-08-23T15:05:37-07:00","full_name":"ssss"}, // "0b0084e21":{"created_at":"2014-08-23T15:05:37-07:00","full_name":yyyyy"}} function GetParse() { var count = 0; //number of entries var rows = []; var TimeNow = moment().format(); var TimeAgo = moment().subtract(2, 'hours').format("YYYY-MM-DD-H"); //Test 1 - fetch prior URL //TimeAgo ="2014-08-28-10" //10345 var URL = "http://data.githubarchive.org/" + TimeAgo + ".json.gz"; console.log (TimeNow + " processing " + URL); var a = archive(URL, {gzip:true}); //Test 2 - read test file //var npath = path.join(__dirname, '2014-sample.json') //console.log ("Testing sample json ..." + npath); //var a = archive.readFile(npath, {gzip:false}); var com = a.MyParser(function (err, commits) { if (err) return console.log(err); //console.log(JSON.stringify(com.commits)); var tmp = JSON.stringify(com.commits); var result = JSON.parse(tmp); //create array for(var k in result) { //console.log (k); //print keys count ++; rows.push(result[k]); //create array //console.log (result[k]); //print values } console.log ("## entries: " + count); //Insert into MongoDB console.log("## start insert: "+ moment().format()); MongoInsert(rows,count); //Debug - store to external file //var tmp_dir = path.join(process.cwd(), "output/"); //if (!fs.existsSync(tmp_dir)) //fs.mkdirSync(tmp_dir); //var p = tmp_dir + 'PushEvent.json'; //fs.writeFile(p, JSON.stringify(com.commits), function (err) { //if (err) return console.log(err); //}); }); //end MyParser } //end GetParse() function MongoInsert(rows,count) { var connectURL = process.env.connectURL; var mycollection= process.env.mycollection; var db; var col; async.series([ // Connect to DB function(callback) { MongoClient.connect(connectURL,function(error, db2) { if (error) {console.log("db connect error" + error);callback(error,"db connect error"); return;} db = db2; callback(null,"connect success"); }); }, function(callback) { col = db.collection(mycollection); callback(null,"collection success"); }, function(callback) { //console.log ("insert begin ..."); var i = 1; async.whilst( function() { return i <= count }, function(callback) { var mydocument = rows.shift(); //TODO: Check for unique SHA before insert col.insert(mydocument,function(error,result) { if (error) { console.log("insert error:" + error); callback(error); return; } //console.log ("inserted ..."); i++; callback(error); }); //end insert }, function(error) { callback(error,"insert sucess") } ); }, function (callback){ //console.log ("close db"); db.close(); console.log("## end insert: "+ moment().format()); callback(null,"connection closed"); } ], function(error, results) { if (error) { console.log("error"); } //console.log(results); }); }
JavaScript
0.000004
@@ -1016,79 +1016,8 @@ %22);%0A -%09%0A%09//Test 1 - fetch prior URL%0A%09//TimeAgo =%222014-08-28-10%22 //10345 %0A%09%0A %09var @@ -1167,204 +1167,12 @@ %7D);%0A -%0A%09//Test 2 - read test file%0A //var npath = path.join(__dirname, '2014-sample.json')%0A //console.log (%22Testing sample json ...%22 + npath);%0A //var a = archive.readFile(npath, %7Bgzip:false%7D);%0A%0A + @@ -1222,17 +1222,20 @@ ) %7B%0A + -%09 + %09 if (err) @@ -1265,16 +1265,18 @@ );%0A %09 + //consol @@ -1312,24 +1312,26 @@ its));%0A %09 + var tmp = JS @@ -1358,24 +1358,26 @@ mits);%0A %09 + var result = @@ -1399,16 +1399,18 @@ );%0A %09 + //create @@ -1421,16 +1421,18 @@ ay%0A %09 + for(var @@ -1627,16 +1627,18 @@ es%0A %09 + %7D%0A %09c @@ -1793,314 +1793,12 @@ t);%0A -%09 %0A -//Debug - store to external file%0A%09//var tmp_dir = path.join(process.cwd(), %22output/%22);%0A%09//if (!fs.existsSync(tmp_dir))%0A%09 //fs.mkdirSync(tmp_dir);%0A%09//var p = tmp_dir + 'PushEvent.json';%09%0A%09//fs.writeFile(p, JSON.stringify(com.commits), function (err) %7B%0A%09%09//if (err) return console.log(err);%0A%09//%7D);%0A @@ -1816,17 +1816,16 @@ yParser%0A -%0A %7D //end
25d54510ae7f548331da44f2e5c45bf254cded49
fix bad code thanks @andy0130tw
teleirc.js
teleirc.js
#!/usr/bin/env node var fs = require('fs'); var nodeirc = require('irc'); var telegram = require('telegram-bot'); // configs var config = require(process.env.HOME + '/.teleirc_config.js'); var tg_chat_id = null; if (!tg_chat_id) { // try to read tg_chat_id from disk, otherwise get it from first conversation try { tg_chat_id = fs.readFileSync(process.env.HOME + '/.teleirc_chat_id'); console.log('Using chat_id: ' + tg_chat_id); } catch(e) { console.log('\n'); console.log('NOTE!'); console.log('====='); console.log('~/.teleirc_chat_id file not found!'); console.log('Please add your Telegram bot to a Telegram group and have'); console.log('someone send a message to that group.'); console.log('teleirc will then automatically store your group chat_id.\n\n'); } } ////////////////// // IRC Client // ////////////////// var irc = new nodeirc.Client(config.irc_server, config.irc_nick, config.irc_options); irc.on('error', function(error) { console.log('error: ', error); }); var irc_send_msg = function(msg) { console.log(' >> relaying to IRC: ' + msg); irc.say(config.irc_channel, msg); }; irc.on('message', function(user, channel, message) { // is this from the correct channel? if (config.irc_channel.toLowerCase() !== channel.toLowerCase()) { return; } var match = config.irc_hilight_re.exec(message); if (match || config.irc_relay_all) { if (match) { message = match[1].trim(); } var text = '<' + user + '>: ' + message; tg_send_msg(text); } }); // ignore first topic event when joining channel var first_topic_event = true; irc.on('topic', function(channel, topic, nick) { // is this from the correct channel? if (config.irc_channel.toLowerCase() !== channel.toLowerCase()) { return; } if (first_topic_event) { first_topic_event = false; return; } var text = '* Topic for channel ' + config.irc_channel.split(' ')[0] + ':\n' + topic.split(' | ').join('\n') + '\n* set by ' + nick.split('!')[0]; tg_send_msg(text); }); ////////////////// // TG bot API // ////////////////// var tg = new telegram(config.tg_bot_token); tg.start(); var tg_send_msg = function(msg) { console.log(' >> relaying to TG: ' + msg); if (!tg_chat_id) { var err = 'Error: No chat_id set! Add me to a Telegram group ' + 'and say hi so I can find your chat_id!'; irc_send_msg(err); console.log(err); return; } tg.sendMessage({ text: msg, chat_id: parseInt(tg_chat_id) }); }; tg.on('message', function(msg) { if (config.tg_chat !== msg.chat.title) { return; } if (!tg_chat_id) { tg_chat_id = msg.chat.id; console.log('storing chat ID: ' + msg.chat.id); fs.writeFile(process.env.HOME + '/.teleirc_chat_id', msg.chat.id, function(err) { if (err) { console.log('error while storing chat ID:'); console.log(err); } else { console.log('successfully stored chat ID in ~/.teleirc_chat_id'); } }); } var user = msg.from.first_name ? msg.from.first_name : '' + msg.from.last_name ? msg.from.last_name : ''; if (msg.reply_to_message && msg.text) { var text = '@' + msg.reply_to_message.from.username + ', ' + msg.text } else if (msg.audio) { var text = '(Audio)' } else if (msg.document) { var text = '(Document)' } else if (msg.photo) { var text = '(Image, ' + msg.photo.slice(-1)[0].width + 'x' + msg.photo.slice(-1)[0].height + ')' } else if (msg.sticker) { var text = '(Sticker)' + } else if (msg.video) { var text = '(Video, ' + msg.video.duration + 's)' } else if (msg.voice) { var text = '(Voice, ' + msg.audio.duration + 's)' } else if (msg.contact) { var text = '(Contact, ' + "\"" + msg.contact.first_name + " " + msg.contact.last_name + "\"" + ", " + msg.contact.phone_number + ")" } else if (msg.location) { var text = '(Location, lon: ' + msg.location.longitude + ", lat: " + msg.location.latitude + ")" } else if (msg.text) { var text = msg.text; } irc_send_msg('<' + user + '>: ' + text); });
JavaScript
0.000004
@@ -3824,18 +3824,17 @@ ticker)' - + +%0A %7D el
4b1367114829feef9400bea8e9f64b90813bbf88
Update dropin.js
client/dropin.js
client/dropin.js
var app = angular.module('WifiGoApp', []); app.controller('DropinController', ['$scope', '$http', function ($scope, $http) { $scope.message = 'Please use the form below to pay:'; $scope.showDropinContainer = true; $scope.isError = false; $scope.isPaid = false; $scope.getToken = function () { $http({ method: 'POST', url: process.env.WIFI_APP_URL+'/clientoken' }).success(function (data) { console.log(data.client_token); braintree.setup(data.client_token, 'dropin', { container: 'checkout', // Form is not submitted by default when paymentMethodNonceReceived is implemented paymentMethodNonceReceived: function (event, nonce) { $scope.message = 'Processing your payment...'; $scope.showDropinContainer = false; $http({ method: 'POST', url: 'http://localhost:3000/api/v1/process', data: { amount: $scope.amount, payment_method_nonce: nonce } }).success(function (data) { console.log(data.success); if (data.success) { $scope.message = 'Payment authorized, thanks.'; $scope.showDropinContainer = false; $scope.isError = false; $scope.isPaid = true; } else { // implement your solution to handle payment failures $scope.message = 'Payment failed: ' + data.message + ' Please refresh the page and try again.'; $scope.isError = true; } }).error(function (error) { $scope.message = 'Error: cannot connect to server. Please make sure your server is running.'; $scope.showDropinContainer = false; $scope.isError = true; }); } }); }).error(function (error) { $scope.message = 'Error: cannot connect to server. Please make sure your server is running.'; $scope.showDropinContainer = false; $scope.isError = true; }); }; $scope.getToken(); }]); app.controller("UserInfoController", ['$scope', '$http', function ($scope, $http){ $scope.userInfo = {} $scope.userInfo.submitUserInfo=function(item,event){ console.log("form submit"); var dataObject = { "firstName":$scope.userInfo.firstName, "lastName":$scope.userInfo.lastName, "address1":$scope.userInfo.address1, "address2":$scope.userInfo.address2, "city":$scope.userInfo.city, "state":$scope.userInfo.state, "postalcode":$scope.userInfo.postalcode, "country":$scope.userInfo.country } console.log(dataObject); } }]);
JavaScript
0.000001
@@ -368,34 +368,8 @@ url: - process.env.WIFI_APP_URL+ '/cl
128d446f39de93ce63bda3b8ef261446ad6efb0b
fix timestamps when viewing logs
settings/js/log.js
settings/js/log.js
/** * Copyright (c) 2012, Robin Appelman <icewind1991@gmail.com> * This file is licensed under the Affero General Public License version 3 or later. * See the COPYING-README file. */ OC.Log={ levels:['Debug','Info','Warning','Error','Fatal'], loaded:50,//are initially loaded getMore:function(){ $.get(OC.filePath('settings','ajax','getlog.php'),{offset:OC.Log.loaded},function(result){ if(result.status=='success'){ OC.Log.addEntries(result.data); } }); OC.Log.loaded+=50; }, addEntries:function(entries){ for(var i=0;i<entries.length;i++){ var entry=entries[i]; var row=$('<tr/>'); var levelTd=$('<td/>'); levelTd.text(OC.Log.levels[entry.level]); row.append(levelTd); var appTd=$('<td/>'); appTd.text(entry.app); row.append(appTd); var messageTd=$('<td/>'); messageTd.text(entry.message); row.append(messageTd); var timeTd=$('<td/>'); timeTd.text(formatDate(entry.time)); row.append(timeTd); $('#log').append(row); } } } $(document).ready(function(){ $('#moreLog').click(function(){ OC.Log.getMore(); }) });
JavaScript
0.000007
@@ -943,16 +943,21 @@ try.time +*1000 ));%0A%09%09%09r
02140ea64d130788532638040bbbefc6e59967d7
fix the karma refernce to the old define.debug file
karma.conf.js
karma.conf.js
// Karma configuration file // // For all available config options and default values, see: // https://github.com/karma-runner/karma/blob/stable/lib/config.js#L54 module.exports = function (config) { 'use strict'; config.set({ // base path, that will be used to resolve files and exclude basePath: '', frameworks: [ 'mocha' ], // list of files / patterns to load in the browser files: [ 'bower_components/chai/chai.js', 'define.debug.js', 'test/define.js' ], // use dots reporter, as travis terminal does not support escaping sequences // possible values: 'dots', 'progress', 'junit', 'teamcity' // CLI --reporters progress reporters: ['dots'], // enable / disable watching file and executing tests whenever any file changes // CLI --auto-watch --no-auto-watch autoWatch: true, // start these browsers // CLI --browsers Chrome,Firefox,Safari browsers: [ 'Chrome', 'Firefox', 'PhantomJS' ], // if browser does not capture in given timeout [ms], kill it // CLI --capture-timeout 5000 captureTimeout: 20000, // auto run tests on start (when browsers are captured) and exit // CLI --single-run --no-single-run singleRun: false, plugins: [ 'karma-mocha', 'karma-requirejs', 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-ie-launcher', 'karma-safari-launcher', 'karma-phantomjs-launcher' ] }); };
JavaScript
0.000202
@@ -475,14 +475,8 @@ ine. -debug. js',
77b5ea44bba135d23e62c5db9c2c31fca9d23755
Remove debug output
visualizer/app.js
visualizer/app.js
#!/usr/bin/env node "use strict" var q = require('q') var fs = require('fs') var fsp = require('fs-promise') var path = require('path') var Flow = require('./../lib/flow/flow') var Mustache = require('mustache') var express = require('express') var app = express() app.get('/', function (req, res) { const FLOW_DIRECTORY = path.join(process.cwd(), 'flows'); // Read files from query let selectedFiles = req.query['files'] || [] // Make absolute file names let absoluteFileNames = selectedFiles.map(file => path.join(FLOW_DIRECTORY, file) ) let allFiles = fs.readdirSync(FLOW_DIRECTORY) .filter(filename => fs.statSync(path.join(FLOW_DIRECTORY, filename)).isFile() && path.extname(filename) == '.json') console.log('files:', selectedFiles) // Load templates let template = fs.readFileSync(path.join(__dirname, 'views/layout.mustache'), 'utf-8') let partials = { 'flow_selection': fs.readFileSync(path.join(__dirname, 'views/selection.mustache'), 'utf-8'), 'checkpoint_selection': fs.readFileSync(path.join(__dirname, 'views/checkpoint_selection.mustache'), 'utf-8') } let view = { 'file': selectedFiles[0], 'allFiles': allFiles, 'flowDirectory': FLOW_DIRECTORY, 'messages': [], 'flows': [], 'checkpoints': [], 'json': function() { return function(json, render) { return "JSON: " + render(json) } }, 'img': function() { return function(value, render) { let rendered = render(value) + "" let length = rendered.length return length > 0 ? ('<img src="data:image/png;base64,' + rendered + '">') : '' } }, 'device-icon': function() { let iconType = { 'phone': 'mobile', 'tablet': 'tablet', 'desktop': 'desktop' } let faType = iconType[this.type] let screenSize = null if (this.width && this.height) { screenSize = this.width + "x" + this.height } if (faType) { let capitalizeFirstLetter = string => string[0].toUpperCase() + string.slice(1) let title = Mustache.render("{{type}}{{#screenSize}}, {{.}}{{/screenSize}}", { 'type': capitalizeFirstLetter(faType), 'screenSize': screenSize }) return '<i class="fa fa-' + faType + '" aria-hidden="true" title="' + title + '"></i>' } else { return '' } } } q.all(absoluteFileNames.map(fileName => fsp.access(fileName, fs.F_OK) .catch(err => { let message = "Error loading file. " + (err.path || "") console.log(message) view.messages.push(message) res.status(404) }) .then(() => { let flow = Flow.load(fileName) view.flows.push({ devices: flow.deviceArray(), grid: flow.grid() }) view.checkpoints = view.checkpoints.concat(flow.checkpoints().map(c => c.name)) }) )).then(() => { view.checkpoints = view.checkpoints.filter((value, index, self) => { // Is the first value in the array return self.indexOf(value) === index }) console.log('view.checkpoints', view.checkpoints) // Render template let html = Mustache.render(template, view, partials) res.send(html) }).catch(err => { let message = "An error occured. " + err.message console.log(message) view.messages.push(message) res.status(500) }) }); app.use('/public', express.static(path.join(__dirname, '/public'))) app.use('/bower_components', express.static(path.join(__dirname, '/bower_components'))) app.listen(3000, function () { console.log('Listening on port 3000.') })
JavaScript
0.000037
@@ -3256,32 +3256,61 @@ )).then(() =%3E %7B%0A + // Filter duplicates%0A view.che @@ -3480,66 +3480,8 @@ %7D) -%0A console.log('view.checkpoints', view.checkpoints) %0A%0A
729f3b090efdefbeed7166b167f96547a700892e
add missing flow annotation
src/types/RouterConfig.js
src/types/RouterConfig.js
export type RouterConfig = { history?: Object };
JavaScript
0.000002
@@ -1,8 +1,17 @@ +// @flow%0A export t
4ebaca426a7e173ea3736e6434340a22ac733f07
switch to story point values by default
public/js/controllers.js
public/js/controllers.js
'use strict'; /* Controllers */ function ServerCtrl($scope, socket) { $scope.state = "picking"; $scope.sidebar = false; //show initial sidebar? $scope.scoreHistory = []; //debug purpose, create large scoreHistory: //for (var x=0; x<12; x++) { // var users = []; // for (var u=1; u<7; u++) { // users.push({name: "Guest_"+u, score: ((u*3+1)/2)}); // } // $scope.scoreHistory.unshift({round: x+1, users: users}); //} $scope.log = function() { console.log($scope.users); } var checkComplete = function() { var i; for (i = 0; i < $scope.users.length; i++) { var usr = $scope.users[i]; if (typeof(usr)==="object" && usr.scored !== true) { return false; } } return true; } var calcWinScore = function() { var diffs = []; var counts = []; var i, j, score, count, diff; //go through users votes for (i = 0; i < $scope.users.length; i++) { score = $scope.users[i].score+""; //if not contained, push into diffs_array if (diffs.indexOf(score) < 0) { diffs.push(score); } } //diffs contains unique score values //go through diffs and count how many users voted this. for (i = 0; i < diffs.length; i++) { diff = diffs[i]; count = 0; for (j = 0; j < $scope.users.length; j++) { score = $scope.users[j].score+""; if (diff === score) { count++; } } counts[i] = count; } //diffs contains unique score values //counts contains amount of score value //diffs[x] = value, counts[x] = amount console.log(diffs); console.log(counts); var maxPos = Math.max.apply( null, counts ), posInArr = counts.indexOf( maxPos ); var maxcounted = 0; var highest; //check if tie for (i=0; i<counts.length; i++) { var curcount = counts[i]; if (curcount === maxPos) { maxcounted++; } } if (maxcounted > 1) { highest = null; } else { highest = diffs[posInArr]; } console.log('highest: '+highest); var winscore = { "highest": highest }; return highest; } var changeName = function (oldName, newName) { // rename user in list of users var i; for (i = 0; i < $scope.users.length; i++) { if ($scope.users[i].name === oldName) { $scope.users[i].name = newName; } } } socket.on('init', function (data) { $scope.users = data.users; }); socket.on('user:join', function (data) { $scope.users.push({name: data.name, score: data.score}); }); // add a message to the conversation when a user disconnects or leaves the room socket.on('user:left', function (data) { var i, user; for (i = 0; i < $scope.users.length; i++) { user = $scope.users[i]; if (user.name === data.name) { $scope.users.splice(i, 1); break; } } }); // add a message to the conversation when a user disconnects or leaves the room socket.on('score:change', function (data) { console.log('received score: '+data.name+" "+data.score); var i, user; for (i = 0; i < $scope.users.length; i++) { user = $scope.users[i]; if (user.name === data.name) { user.score = data.score user.scored = true; break; } } if (checkComplete()) { console.log('Round finished. Locking Clients for 5sec'); $scope.state = "finished"; //calculate win score var win = calcWinScore(); if (win === null) { $scope.winScore = "Draw!"; } else { $scope.winScore = win; } var copyUsers = angular.copy($scope.users); for (var u=0; u<copyUsers.length; u++) { copyUsers[u].name = copyUsers[u].name.replace(" ", "_"); } var scoreCopy = {round: $scope.scoreHistory.length+1, users: copyUsers}; $scope.scoreHistory.unshift(scoreCopy); //lock clients socket.emit('score:lock'); } }); socket.on('score:unlock', function () { console.log('Reset last scores.'); var i, user; for (i = 0; i < $scope.users.length; i++) { user = $scope.users[i]; user.score = "" user.scored = false; } $scope.state = "picking"; }); socket.on('change:name', function (data) { changeName(data.oldName, data.newName); }); } function AppCtrl($scope, socket) { $scope.cardvalues = [ //0, 0.5, 1, 2, 3, 5, 10, 20, 99 //0, 1, 2, 3, 4, 6, 8, 12, 16, 20, 24, 32, 40, 60 0, 0.5, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 99 ]; $scope.selectedCard = -1; // Socket listeners // ================ socket.on('init', function (data) { $scope.name = data.name; }); $scope.state = "unlock"; socket.on('score:lock', function () { $scope.state = "lock"; }); socket.on('score:unlock', function () { $scope.state = "unlock"; //reset selected card $scope.selectedCard = -1; }); // Methods published to the scope // ============================== $scope.sendScore = function (score, $index) { $scope.selectedCard = $index; console.log('send score change: '+score); socket.emit('score:change', { name: $scope.name, score: score }); }; $scope.changeName = function () { socket.emit('change:name', { name: $scope.newName }, function (result) { if (!result) { alert('There was an error changing your name'); } else { $scope.name = $scope.newName; $scope.newName = ''; } }); }; }
JavaScript
0.000001
@@ -5147,18 +5147,16 @@ -// 0, 0.5, @@ -5171,13 +5171,20 @@ 5, -10, 2 +8, 13, 20, 4 0, 9 @@ -5237,32 +5237,34 @@ 40, 60%0A +// 0, 0.5, 1, 2, 3,
6fe59001ef8eb6b932e05db93323476b6b6ddecd
Create app.js
client/js/app.js
client/js/app.js
// angular.module is a global place for creating, registering and retrieving Angular modules // 'starter' is the name of this angular module example (also set in a <body> attribute in index.html) // the 2nd parameter is an array of 'requires' // 'starter.services' is found in services.js // 'starter.controllers' is found in controllers.js angular.module('starter', ['ionic', 'starter.controllers', 'starter.services', 'ngResource']) .run(function($window, $location, $ionicPlatform, $rootScope, AuthenticationService) { $rootScope.user = { name: $window.sessionStorage.name, is_admin: $window.sessionStorage.is_admin }; if ($rootScope.user.is_admin) { AuthenticationService.isAdmin = true; } $rootScope.$on("$stateChangeStart", function(event, toState) { //redirect only if both isAuthenticated is false and no token is set if (['home', 'login', 'logout', 'register', 'one', 'two', 'three', 'all'].indexOf(toState.name) === -1) { if (!AuthenticationService.isAuthenticated && !$window.localStorage.token) { event.preventDefault(); $location.path("/home"); } } }); $ionicPlatform.ready(function() { // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard // for form inputs) if (window.cordova && window.cordova.plugins.Keyboard) { cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); } if (window.StatusBar) { // org.apache.cordova.statusbar required StatusBar.styleDefault(); } }); }) .config(function($stateProvider, $urlRouterProvider, $httpProvider) { // Ionic uses AngularUI Router which uses the concept of states // Learn more here: https://github.com/angular-ui/ui-router // Set up the various states which the app can be in. // Each state's controller can be found in controllers.js $stateProvider.state('home', { url: "/", templateUrl: "templates/home.html", controller: 'HomeCtrl' }) .state('register', { url: "/register", templateUrl: "templates/two.html", controller: 'RegisterCtrl' }) .state('login', { url: "/one", templateUrl: "templates/one.html", controller: 'LoginCtrl' }) .state('one', { url: "/one", templateURL: "templates/one.html", controller: 'OneCtrl' }) .state('two', { url: "/two", templateURL: "templates/two.html", controller: 'TwoCtrl' }) .state('three', { url: "/three", templateURL: "templates/three.html", controller: 'ThreeCtrl' }) .state('all', { url: "/all", templateURL: "templates/all.html", controller: 'AllCtrl' }) // if none of the above states are matched, use this as the fallback $urlRouterProvider.otherwise('/'); // Register middleware to ensure our auth token is passed to the server $httpProvider.interceptors.push('TokenInterceptor'); })
JavaScript
0.000003
@@ -2120,35 +2120,37 @@ ', %7B%0A url: %22/ -one +login %22,%0A templateU
7372d0a63496d55a64c3ee0cc68e576362964f25
extend custom id generation function test
test/id.js
test/id.js
/** * Created by schwarzkopfb on 14/06/16. */ 'use strict' const test = require('tap'), Database = require('..'), { url } = require('./credentials'), db = new Database, user = { id: Number, // not necessary name: String, timestamp: Date.now } test.tearDown(() => db.unref()) // custom id generator fn db.id = (db, schema, model) => { test.type(db, Database) test.type(schema, Database.Schema) test.type(model, Database.Model) return new Promise((ok, error) => { db.client.incr(`id:${schema.name}`, (err, id) => { if (err) error(err) else ok(id) }) }) } db.define({ user }) .connect(url) // WARNING: this drops all the data in the selected database! db.client.flushdb() test.test('custom id generator function', test => { db.create('user', { name: 'test' }) .save() .then(user => { test.equal(user.id, 1, 'model should have a numeric id') test.end() }) .catch(test.threw) })
JavaScript
0
@@ -892,16 +892,19 @@ function + #1 ', test @@ -904,24 +904,24 @@ , test =%3E %7B%0A - db.creat @@ -1072,16 +1072,33 @@ t.end()%0A + next()%0A %7D) @@ -1123,11 +1123,325 @@ .threw)%0A - %7D)%0A +%0Afunction next() %7B%0A test.test('custom id generator function #2', test =%3E %7B%0A db.create('user', %7B name: 'test2' %7D)%0A .save()%0A .then(user =%3E %7B%0A test.equal(user.id, 2, 'model should have a numeric id')%0A test.end()%0A %7D)%0A .catch(test.threw)%0A %7D)%0A%7D%0A
6e92b191f04be8f6810cfe469a78ff5eb6c59a75
increase mocha timeout
karma.conf.js
karma.conf.js
'use strict'; var util = require('util'); var pkg = require('./package.json'); var extend = util._extend; var geSaLaKaCuLa = require('gesalakacula'); // No Karma options are passed after the double dash option (`--`) // Example : karma start --single-run -- --polyfill // >> { _: [], polyfill: true } var _argv = process.argv; var argv = require('minimist')(_argv.slice(_argv.indexOf('--') + 1)); var options = extend({ travis: process.env.TRAVIS, polyfill: false, saucelabs: false, ie8: false, coverage: false }, argv); if (options.ie8){ console.log('IE8 Mode !\n - polyfill required\n'); options.polyfill = true; } //// module.exports = function (config) { var files = [ 'test/_helper.js', [!options.ie8 ? 'node_modules/traceur/bin/traceur.js' : ''], 'dist/es6-module-loader' + (options.polyfill ? '' : '-sans-promises') + '.src.js', 'test/_browser.js', 'test/custom-loader.js', [!options.ie8 ? 'test/*.spec.js' : 'test/*.normalize.spec.js'], {pattern: 'test/{loader,loads,syntax,worker}/**/*', included: false}, {pattern: 'node_modules/when/es6-shim/Promise.js', included: false}, {pattern: 'dist/es6-module-loader.js', included: false} ]; // Default Config config.set({ basePath: '', frameworks: ['mocha', 'expect'], files: flatten(files), reporters: ['mocha'], browsers: ['Chrome', 'Firefox'], client: { mocha: { reporter: 'html', timeout: 5000 } } }); if (options.coverage) { config.set({ reporters: ['mocha', 'coverage'], preprocessors: { 'dist/es6-module-loader*.src.js': ['coverage'] }, coverageReporter: { type : 'html', dir : 'coverage/' }, browsers: ['Chrome'] }); } if (options.travis) { // TRAVIS config overwrite config.set({ singleRun: true, reporters: ['dots'], customLaunchers: { 'TR_Chrome': { base: 'Chrome', flags: ['--no-sandbox'] } }, browsers: ['TR_Chrome', 'Firefox'] }); } if (options.saucelabs) { var customLaunchers = geSaLaKaCuLa({ 'Windows 7': { 'internet explorer': '9..11' } }); if (options.ie8) { customLaunchers = geSaLaKaCuLa({ 'Windows 7': { 'internet explorer': '8' } }); } var now = new Date(); var buildData = options.travis ? { location: 'TRAVIS', name: process.env.TRAVIS_BUILD_NUMBER, id: process.env.TRAVIS_BUILD_ID } : { location: 'LOCAL', name: now.toString(), id: +now }; var build = util.format('%s #%s (%s)', buildData.location, buildData.name, buildData.id); console.log('SauceLabs Run\n- Build : ' + build + '\n'); config.set({ reporters: ['dots', 'saucelabs'], browserDisconnectTimeout: 10000, browserDisconnectTolerance: 2, browserNoActivityTimeout: 30000, captureTimeout: 120000, browsers: Object.keys(customLaunchers), sauceLabs: { testName: pkg.name, recordScreenshots: false, build: build, tunnelIdentifier: options.travis ? process.env.TRAVIS_JOB_NUMBER : Math.floor(Math.random() * 1000) }, customLaunchers: customLaunchers }); } }; function flatten(arr) { return arr.reduce(function (memo, val) { return memo.concat(util.isArray(val) ? flatten(val) : val ? [val] : []); }, []); }
JavaScript
0.000003
@@ -1475,9 +1475,10 @@ ut: -5 +10 000%0A
f511803a3d2dc360c3795e1a5c80931bf7759d68
Support running licensee on Windows
rules/license-detectable-by-licensee.js
rules/license-detectable-by-licensee.js
// Copyright 2017 TODO Group. All rights reserved. // Licensed under the Apache License, Version 2.0. const spawnSync = require('child_process').spawnSync module.exports = function (targetDir, options) { const expected = '\nLicense: ([^\n]*)' const licenseeOutput = spawnSync('licensee', [targetDir]).stdout if (licenseeOutput == null) { return { failures: [`Licensee is not installed`] } } const results = licenseeOutput.toString().match(expected) if (results != null) { // License: Apache License 2.0 const identified = results[1] return { passes: [`Licensee identified the license for project: ${identified}`] } } else { return { failures: ['Licensee did not identify a license for project'] } } }
JavaScript
0
@@ -96,16 +96,56 @@ n 2.0.%0A%0A +const isWindows = require('is-windows')%0A const sp @@ -316,16 +316,45 @@ awnSync( +isWindows ? 'licensee.bat' : 'license
6baa4a1d911f5ae9fd00107ca4850f7fcd28d631
fix a crawler bug
crawler/src/database.js
crawler/src/database.js
const Promise = require('bluebird'); const pgp = require('pg-promise')({ promiseLib: Promise }); const params = require('./params.js'); const _ = require('lodash'); const dbSchema = { tag: { idColumn: 'tag_id', xrefID: 'instance_tag_xref_id', table: 'tag', dataTable: 'tag_data', xrefTable: 'instance_tag_xref' }, organization: { idColumn: 'organization_id', xrefID: 'instance_organization_xref_id', table: 'organization', dataTable: 'organization_data', xrefTable: 'instance_organization_xref' }, category: { idColumn: 'category_id', xrefID: 'instance_category_xref_id', table: 'category', dataTable: 'category_data', xrefTable: 'instance_category_xref' } }; /** * main entry to save crawled data into database * @param {object} db pgp database object * @param {integer} instanceID instance ID * @param {object} data open data summary * @param {boolean} [insertOnly] indicates whether to insert new data only * @return {object} promise */ exports.saveData = function(db, instanceID, data, insertOnly) { return db.tx(function(tx) { var tagData = {}; var catData = {}; var orgData = {}; var dataCount; let sql = ` SELECT count, tags, categories, organizations FROM view_instance_info WHERE instance_id = $1 `; return tx.oneOrNone(sql, instanceID) .then(function(result) { if (result) { dataCount = result.count; tagData = _.keyBy(result.tags, 'name'); catData = _.keyBy(result.categories, 'name'); orgData = _.keyBy(result.organizations, 'name'); } sql = ` SELECT t.id, t.name, xref.id AS xref_id FROM $2^ AS t LEFT JOIN $1^ AS xref ON t.id = xref.$3^ AND xref.instance_id = $4 `; return Promise.props({ tag: tx.any(sql, [ dbSchema.tag.xrefTable, dbSchema.tag.table, dbSchema.tag.idColumn, instanceID ]), organization: tx.any(sql, [ dbSchema.organization.xrefTable, dbSchema.organization.table, dbSchema.organization.idColumn, instanceID ]), category: tx.any(sql, [ dbSchema.category.xrefTable, dbSchema.category.table, dbSchema.category.idColumn, instanceID ]) }); }) .then(function(result) { let tags = _.keyBy(result.tag, 'name'); let organizations = _.keyBy(result.organization, 'name'); let categories = _.keyBy(result.category, 'name'); let tagUpdates = _.map(data.tags, tag => { return exports.updateItemData( tx, instanceID, tags[tag.display_name], dbSchema.tag, tag.display_name, tag.count, tagData[tag.display_name], insertOnly ); }); let orgUpdates = _.map(data.organizations, organization => { return exports.updateItemData( tx, instanceID, organizations[organization.display_name], dbSchema.organization, organization.display_name, organization.count, orgData[organization.display_name], insertOnly ); }); let catUpdates = _.map(data.categories, category => { return exports.updateItemData( tx, instanceID, categories[category.display_name], dbSchema.category, category.display_name, category.count, catData[category.display_name], insertOnly ); }); return Promise.all(_.concat(tagUpdates, orgUpdates, catUpdates)) .then(updates => { let sql; if (data.count !== dataCount) { sql = ` INSERT INTO instance_data (instance_id, count, create_date, update_date) VALUES (${instanceID}, ${data.count}, now(), now()); `; } else if (!insertOnly) { sql = ` UPDATE instance_data SET update_date = now() WHERE instance_id = ${instanceID} AND count = ${data.count}; `; } updates.push(sql); return tx.none(updates.join('\n')); }); }); }); }; /** * save region data, * @param {object} db pgp database object * @param {integer} instanceID instance ID * @param {object} item data item * @param {object} itemSchema item database schema infor * @param {string} name tag name * @param {integer} count data count * @param {object} lastUpdate latest data for this item * @param {boolean} insertOnly indicates whether to insert only data only * @return {object} promise */ exports.updateItemData = function(db, instanceID, item, itemSchema, name, count, lastUpdate, insertOnly) { let promise, sql; if (!item) { // if the tag doesn't exit at all, insert the new tag sql = ` WITH new_item AS (INSERT INTO $1^ (name) VALUES ($4) RETURNING id) INSERT INTO $2^ ($3^, instance_id) ( SELECT new_item.id, $5 FROM new_item) RETURNING * `; promise = db.one(sql, [itemSchema.table, itemSchema.xrefTable, itemSchema.idColumn, name, instanceID]) .then(function(result) { item = { id: result[itemSchema.idColumn], name: name, xref_id: result.id }; }); } else if (!item.xref_id) { // if the item doesn't exit for this region, insert the new tag to this region sql = 'INSERT INTO $1^ ($2^, instance_id) VALUES ($3, $4) RETURNING *'; promise = db.one(sql, [itemSchema.xrefTable, itemSchema.idColumn, item.id, instanceID]) .then(function(result) { item.xref_id = result.id; }); } else { promise = Promise.resolve(); } return promise.then(() => { if (lastUpdate && lastUpdate.count === count) { if (!insertOnly) { return ` UPDATE ${itemSchema.dataTable} SET update_date = now() WHERE ${itemSchema.xrefID} = ${item.xref_id} AND count = ${count}; `; } return ''; } return ` INSERT INTO ${itemSchema.dataTable} (${itemSchema.xrefID}, count, create_date, update_date) VALUES (${item.xref_id}, ${count}, now(), now()); `; }); }; /** * Refresh mateiral views at the database * @param {object} db pgp database connection object * @return {undefined} */ exports.refresh = function(db) { db = db || pgp(params.dbConnStr); return db.none('REFRESH MATERIALIZED VIEW view_instance_info;'); };
JavaScript
0.00006
@@ -4413,24 +4413,29 @@ let sql + = '' ;%0A%0A @@ -5000,23 +5000,24 @@ -return tx.none( +let updateSQL = upda @@ -5030,14 +5030,125 @@ in(' -%5Cn')); +');%0A%0A if (updateSQL.length %3E 0) %7B%0A return tx.none(updateSQL);%0A %7D %0A
60462bfb941b2793393a0a7ca96ef067602afe58
Add version to menu
main.js
main.js
import electron from 'electron'; import { app, BrowserWindow, Menu, dialog, shell } from 'electron'; import moment from 'moment'; import path from 'path'; import setupEvents from './installers/setupEvents'; let mainWindow = { show: () => { console.log('show'); } }; // temp object while app loads let willQuit = false; function createWindow() { mainWindow = new BrowserWindow({ width: 800, minWidth: 800, height: 600, fullscreenable: true, backgroundColor: '#403F4D', icon: path.join(__dirname, 'assets/png/128x128.png') }); mainWindow.loadURL('file://' + __dirname + '/index.html'); } function manageRefresh() { const time = moment('24:00:00', 'hh:mm:ss').diff(moment(), 'seconds'); setTimeout( midnightTask, time*1000 ); function midnightTask() { mainWindow.reload(); } } function menuSetup() { const menuTemplate = [ { label: 'todometer', submenu: [ { label: 'About', click: () => { dialog.showMessageBox(mainWindow, { type: 'info', title: 'About', message: 'todometer is built by Cassidy Williams', detail: 'You can find her on GitHub and Twitter as @cassidoo, or on her website cassidoo.co.', icon: path.join(__dirname, 'assets/png/64x64.png') }); } }, { label: 'Contribute', click: () => { shell.openExternal('http://github.com/cassidoo/todometer'); } }, { type: 'separator' /* For debugging }, { label: 'Dev tools', click: () => { mainWindow.webContents.openDevTools(); } */ }, { label: 'Quit', accelerator: 'CommandOrControl+Q', click: () => { app.quit(); } } ] }, { label: 'Edit', submenu: [ {role: 'undo'}, {role: 'redo'}, {role: 'cut'}, {role: 'copy'}, {role: 'paste'}, {role: 'delete'}, {role: 'selectall'} ] }, { label: 'View', submenu: [ {role: 'reload'}, {role: 'togglefullscreen'}, {role: 'minimize'}, {role: 'hide'}, {role: 'close'} ] } ]; const menu = Menu.buildFromTemplate(menuTemplate); Menu.setApplicationMenu(menu); } app.on('ready', () => { // Squirrel events have to be handled before anything else if (setupEvents.handleSquirrelEvent()) { // squirrel event handled and app will exit in 1000ms, so don't do anything else return; } createWindow(); menuSetup(); electron.powerMonitor.on('resume', () => { mainWindow.reload(); console.log('reloaded'); }); mainWindow.on('close', (e) => { if (willQuit) { mainWindow = null; } else { e.preventDefault(); mainWindow.hide(); } }); manageRefresh(); }); app.on('activate', () => mainWindow.show()); app.on('before-quit', () => willQuit = true);
JavaScript
0.000001
@@ -1404,16 +1404,25 @@ ntribute + (v1.0.4) ',%0A
2795d431059557d84cd0898b2eb6ab806a895fbf
Fix minute format of downloaded filename
chrome-get-urls-from-tabs-in-windows.js
chrome-get-urls-from-tabs-in-windows.js
var textarea = document.getElementById('copy-area'); var create_download_link; var generate_filename; chrome.windows.getAll({populate:true}, function(windows){ var w_index = 0; chrome.storage.sync.get(function(items) { var format = items.file_format; if (format === 'yaml') { var chrome_tabs = []; windows.forEach(function(window){ textarea.value += "- Window " + w_index + ":\n"; window.tabs.forEach(function(tab){ textarea.value += " - page_title: '" + tab.title.replace('\'', '\'\'') + "'\n"; textarea.value += " url: '" + tab.url + "'\n"; }); textarea.value += "\n"; w_index++; }); } else if (format === 'html') { windows.forEach(function(window){ textarea.value += "Window " + w_index + ":"; window.tabs.forEach(function(tab){ textarea.value += "\n"; textarea.value += "\t* " + tab.title + "\n"; textarea.value += "\t " + tab.url + "\n"; }); textarea.value += "\n\n"; w_index++; }); } else { // format === 'text' windows.forEach(function(window){ textarea.value += "Window " + w_index + ":"; window.tabs.forEach(function(tab){ textarea.value += "\n"; textarea.value += "\t* " + tab.title + "\n"; textarea.value += "\t " + tab.url + "\n"; }); textarea.value += "\n\n"; w_index++; }); } create_download_link(textarea.value); }); }); // Adapted from: // http://stackoverflow.com/a/18197511 create_download_link = function(text) { generate_filename(function(filename) { var download_link = document.createElement('a'); download_link.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text)); download_link.setAttribute('download', filename); download_link.innerHTML = 'Download file'; document.querySelector('body').appendChild(download_link); }); }; generate_filename = function(callback) { chrome.storage.sync.get(function(items) { var format = items.file_format; var d = new Date(); var date_string = d.getFullYear() + '' + ('0' + (d.getMonth() + 1)).slice(-2) + '' + ('0' + d.getDate()).slice(-2) + '-' + ('0' + d.getHours()).slice(-2) + 'h' + d.getMinutes(); var file_extension = ''; if (format === 'yaml') { file_extension = 'yml'; } else if (format === 'html') { file_extension = 'html'; } else { file_extension = 'txt'; } callback('chrome-tabs-' + date_string + '.' + file_extension); }); };
JavaScript
0
@@ -2232,16 +2232,23 @@ h' %0A%09%09%09+ + ('0' + d.getMi @@ -2254,16 +2254,27 @@ inutes() +).slice(-2) ;%0A%09%09%0A%09%09%0A
c68f4f9d09ba368745a1ff6cee72204d4e0178fa
Fix the tests for Amazon S3
test/s3.js
test/s3.js
// -------------------------------------------------------------------------------------------------------------------- // // s3.js - test for AWS Simple Notification Service // // Copyright (c) 2011 AppsAttic Ltd - http://www.appsattic.com/ // Written by Andrew Chilton <chilts@appsattic.com> // // License: http://opensource.org/licenses/MIT // // -------------------------------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------------------------------------------- // requires var tap = require("tap"), test = tap.test, plan = tap.plan, _ = require('underscore'); var amazon; var s3Service; // -------------------------------------------------------------------------------------------------------------------- // basic tests test("load s3", function (t) { s3Service = require("../lib/s3"); t.ok(s3Service, "object loaded"); amazon = require("../lib/amazon"); t.ok(amazon, "object loaded"); t.end(); }); test("create s3 object", function (t) { var s3 = new s3Service.S3('access_key_id', 'secret_access_key', 'aws_account_id', amazon.US_WEST_1); t.equal('access_key_id', s3.accessKeyId(), 'Access Key ID set properly'); t.equal('secret_access_key', s3.secretAccessKey(), 'Secret Access Key set properly'); t.equal('aws_account_id', s3.awsAccountId(), 'AWS Account ID set properly'); t.equal('California', s3.region(), 'Region is set properly'); t.end(); }); test("test all endpoints", function (t) { var s31 = new s3Service.S3('access_key_id', 'secret_access_key', 'aws_account_id', amazon.US_EAST_1); var s32 = new s3Service.S3('access_key_id', 'secret_access_key', 'aws_account_id', amazon.US_WEST_1); var s33 = new s3Service.S3('access_key_id', 'secret_access_key', 'aws_account_id', amazon.EU_WEST_1); var s34 = new s3Service.S3('access_key_id', 'secret_access_key', 'aws_account_id', amazon.AP_SOUTHEAST_1); var s35 = new s3Service.S3('access_key_id', 'secret_access_key', 'aws_account_id', amazon.AP_NORTHEAST_1); t.equal('s3.amazonaws.com', s31.endPoint(), '1) Endpoint is correct'); t.equal('s3.us-west-1.amazonaws.com', s32.endPoint(), '2) Endpoint is correct'); t.equal('s3.eu-west-1.amazonaws.com', s33.endPoint(), '3) Endpoint is correct'); t.equal('s3.ap-southeast-1.amazonaws.com', s34.endPoint(), '4) Endpoint is correct'); t.equal('s3.ap-northeast-1.amazonaws.com', s35.endPoint(), '5) Endpoint is correct'); t.end(); }); test("test strToSign", function (t) { var s3 = new s3Service.S3('access_key_id', 'secret_access_key', 'aws_account_id', amazon.US_WEST_1); var strToSignEmpty1 = s3.strToSign(undefined, undefined, 'GET', '/', {}, []); t.equal(strToSignEmpty1, "GET\n\n\n\n/", 'strToSign of ListBuckets'); // set up some generic headers first var headers = {}; headers.Date = "Mon, 26 Oct 2011 16:07:36 Z"; // test an initial string var strToSign = s3.strToSign('bulk', undefined, 'POST', '/', headers, []); t.equal(strToSign, "POST\n\n\nMon, 26 Oct 2011 16:07:36 Z\n/bulk/", 'strToSign of common params'); // do a subresource test var strToSign2 = s3.strToSign('bulk', undefined, 'POST', '/', headers, [{name:'versioning'}]); t.equal( strToSign2, "POST\n\n\nMon, 26 Oct 2011 16:07:36 Z\n/bulk/?versioning", 'strToSign with subresource of versioning' ); // do a subresource test var strToSign3 = s3.strToSign('bulk', undefined, 'POST', '/', headers, [{name:'website'}]); t.equal( strToSign3, "POST\n\n\nMon, 26 Oct 2011 16:07:36 Z\n/bulk/?website", 'strToSign with subresource of website' ); t.end(); }); test("test signature", function (t) { var s3 = new s3Service.S3('access_key_id', 'secret_access_key', 'aws_account_id', amazon.US_WEST_1); var strToSign = "GET\n\n\nTue, 25 Oct 2011 03:09:21 UTC\n/"; var sig = s3.signature(strToSign); t.equal(sig, 'OFs3nLlSvlN6EaeNy/IluZpS+E8=', 'signature of ListBuckets request'); var strToSign2 = "GET\n\n\nTue, 25 Oct 2011 03:09:21 UTC\n/bulk/?versioning"; var sig2 = s3.signature(strToSign2); t.equal(sig2, 'zxmJifiGCl8WgMu2XLaiEx0o5Wo=', 'signature of ListBuckets request with versioning'); t.end(); }); // --------------------------------------------------------------------------------------------------------------------
JavaScript
0.999595
@@ -2211,17 +2211,17 @@ qual('s3 -. +- us-west- @@ -2296,17 +2296,17 @@ qual('s3 -. +- eu-west- @@ -2381,17 +2381,17 @@ qual('s3 -. +- ap-south @@ -2471,17 +2471,17 @@ qual('s3 -. +- ap-north
151ca1a929fe3ee86b18c9137b45aadfb045606e
remove transports key
karma.conf.js
karma.conf.js
module.exports = (config) => { const configuration = { frameworks: [ 'browserify', 'jasmine', ], files: [ 'packages/**/*.spec.js', ], browsers: [ 'ChromeHeadless', ], transports: ['polling'], customLaunchers: { ChromeTravisCi: { base: 'ChromeHeadless', flags: ['--headless --disable-gpu'], }, }, reporters: [ 'progress', 'coverage', ], coverageReporter: { check: { each: { statements: 100, branches: 100, functions: 100, lines: 100, }, global: { statements: 100, branches: 100, functions: 100, lines: 100, }, }, reporters: [ { type: 'html', dir: 'coverage/', subdir: 'report-html', }, { type: 'text', }, { type: 'json', }, ], instrumenterOptions: { istanbul: { noCompact: true, }, }, }, preprocessors: { 'packages/**/*.spec.js': ['browserify'], }, browserify: { debug: true, transform: [ [ 'babelify', { presets: [ '@babel/preset-env', ], }, ], ], }, }; if (process.env.TRAVIS) { configuration.browsers = [ 'ChromeTravisCi', ]; } config.set(configuration); };
JavaScript
0
@@ -214,37 +214,8 @@ %5D,%0A - transports: %5B'polling'%5D,%0A
042aa373b77f40b6b49e60b96eb36fdb6034e257
Fix the regex to match the license reported by licensee
rules/license-detectable-by-licensee.js
rules/license-detectable-by-licensee.js
// Copyright 2017 TODO Group. All rights reserved. // Licensed under the Apache License, Version 2.0. const isWindows = require('is-windows') const spawnSync = require('child_process').spawnSync module.exports = function (targetDir, options) { const expected = '\nLicense: ([^\n]*)' const licenseeOutput = spawnSync(isWindows() ? 'licensee.bat' : 'licensee', [targetDir]).stdout if (licenseeOutput == null) { return { failures: [`Licensee is not installed`] } } const results = licenseeOutput.toString().match(expected) if (results != null) { // License: Apache License 2.0 const identified = results[1] return { passes: [`Licensee identified the license for project: ${identified}`] } } else { return { failures: ['Licensee did not identify a license for project'] } } }
JavaScript
0
@@ -262,11 +262,9 @@ d = -'%5Cn +/ Lice @@ -278,11 +278,11 @@ %5E%5Cn%5D -*)' ++)/ %0A%0A
264d55a67f3ed05826e2734d1c9ec2ae1bda72fa
add karma-ie-launcher
karma.conf.js
karma.conf.js
module.exports = function(karma) { karma.configure({ // base path, that will be used to resolve files and exclude basePath: '../', // frameworks to use frameworks: ['mocha'], // list of files / patterns to load in the browser files: [ 'PointerGestures/node_modules/chai/chai.js', 'PointerGestures/node_modules/chai-spies/chai-spies.js', 'PointerEvents/src/boot.js', 'PointerEvents/src/PointerEvent.js', 'PointerEvents/src/pointermap.js', 'PointerEvents/src/sidetable.js', 'PointerEvents/src/dispatcher.js', 'PointerEvents/src/installer.js', 'PointerEvents/src/mouse.js', 'PointerEvents/src/touch.js', 'PointerEvents/src/ms.js', 'PointerEvents/src/platform-events.js', 'PointerEvents/src/capture.js', 'PointerGestures/src/PointerGestureEvent.js', 'PointerGestures/src/initialize.js', 'PointerGestures/src/sidetable.js', 'PointerGestures/src/pointermap.js', 'PointerGestures/src/dispatcher.js', 'PointerGestures/src/hold.js', 'PointerGestures/src/track.js', 'PointerGestures/src/flick.js', 'PointerGestures/src/tap.js', 'PointerGestures/tests/setup.js', 'PointerGestures/tests/!(setup).js' ], // list of files to exclude exclude: [], // test results reporter to use // possible values: 'dots', 'progress', 'junit', 'growl', 'coverage' reporters: ['progress'], // web server port port: 9876, // cli runner port runnerPort: 9100, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG logLevel: karma.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: false, // Start these browsers, currently available: // - Chrome // - ChromeCanary // - Firefox // - Opera // - Safari (only Mac) // - PhantomJS // - IE (only Windows) browsers: ['Chrome'], // If browser does not capture in given timeout [ms], kill it captureTimeout: 60000, // Continuous Integration mode // if true, it capture browsers, run tests and exit singleRun: true, // plugins to load plugins: [ 'karma-mocha', 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-script-launcher', 'karma-crbot-reporter' ] }); };
JavaScript
0.007187
@@ -2423,32 +2423,59 @@ efox-launcher',%0A + 'karma-ie-launcher',%0A 'karma-scr
b6c50dffa9377f30fa1947ad664c69661fa4c362
Change QA and CR indicators to colored text
public/js/views/index.js
public/js/views/index.js
define(['jquery', 'appearanceUtils'], function($, utils) { return { // where selector: function(pull) { return pull.state == 'open'; }, // order by sort: function(pull) { return pull.created_at; }, // Allows custom modifications of each pull's display adjust: function(pull, node) { // If the pull is over 30 days old... if (Date.now() - (new Date(pull.created_at)) > 2590000000 ) { // Mark it in red $(node).addClass('bg-warning'); } }, navbar: "#restore-buttons", // Functions to stick status information in indicators at the bottom of each pull indicators: { qa_remaining: function qa_remaining(pull, node) { var required = pull.status.qa_req; var completed = pull.status.QA.length; node.text("QA " + completed + "/" + required); }, cr_remaining: function cr_remaining(pull, node) { var required = pull.status.cr_req; var completed = pull.status.CR.length; node.text("CR " + completed + "/" + required); }, status: function status(pull, node) { if (pull.status.commit_status) { var commit_status = pull.status.commit_status.data; var title = commit_status.description; var url = commit_status.target_url; var state = commit_status.state; var link = $('<a target="_blank" data-toggle="tooltip" data-placement="top" title="' + title + '" href="' + url + '"></a>'); node.append(link); link.tooltip(); switch(commit_status.state) { case 'pending': link.append('<span class="text-muted glyphicon glyphicon-repeat"></span>'); break; case 'success': link.append('<span class="text-success glyphicon glyphicon-ok"></span>'); break; case 'error': link.append('<span class="text-danger glyphicon glyphicon-exclamation-sign"></span>'); break; case 'failure': link.append('<span class="text-warning glyphicon glyphicon-remove"></span>'); break; } } }, user_icon: function user_icon(pull, node) { if (pull.is_mine()) { node.append('<span class="glyphicon glyphicon-user"></span>'); } } }, columns: [ { title: "Special Pulls", id: "uniqPulls", selector: function(pull) { return (pull.deploy_blocked() || pull.status.ready) && !pull.dev_blocked(); }, sort: function(pull) { return pull.deploy_blocked() ? 0 : 1; }, adjust: function(pull, node) { if (pull.deploy_blocked()) { node.addClass('list-group-item-danger'); } }, triggers: { onCreate: function(blob, container) { blob.removeClass('panel-default').addClass('panel-primary'); }, onUpdate: function(blob, container) { utils.hideIfEmpty(container, blob, '.pull'); } }, shrinkToButton: true }, { title: "dev_blocked Pulls", id: "blockPulls", selector: function(pull) { return pull.dev_blocked(); } }, { title: "CR Pulls", id: "crPulls", selector: function(pull) { return !pull.cr_done() && !pull.dev_blocked(); }, indicators: { cr_remaining: function(pull, node) { var required = pull.status.cr_req; var remaining = required - pull.status.CR.length; if (remaining === 1) { node.addClass('label label-danger'); } }, qa_remaining: function(pull, node) { var required = pull.status.qa_req; var remaining = required - pull.status.QA.length; if (remaining === 0) { node.addClass('label label-success'); } } } }, { title: "QA Pulls", id: "qaPulls", selector: function(pull) { return !pull.qa_done() && !pull.dev_blocked(); }, indicators: { qa_remaining: function(pull, node) { var required = pull.status.qa_req; var remaining = required - pull.status.QA.length; if (remaining === 1) { node.addClass('label label-danger'); } }, cr_remaining: function(pull, node) { var required = pull.status.cr_req; var remaining = required - pull.status.CR.length; if (remaining === 0) { node.addClass('label label-success'); } } } } ] }; });
JavaScript
0
@@ -4112,35 +4112,28 @@ e.addClass(' -label label +text -danger');%0A @@ -4416,35 +4416,28 @@ e.addClass(' -label label +text -success');%0A @@ -4965,26 +4965,20 @@ ss(' -label label-danger +text-warning ');%0A @@ -5270,19 +5270,12 @@ ss(' -label label +text -suc
57bd5958c8431494744dac23265d420dbd876fc4
remove electron deprectated api
main.js
main.js
'use strict'; const Electron = require('electron'); const BrowserWindow = require('browser-window'); module.exports = { load () { Editor.Menu.register( 'open-log-file', () => { return [ { label: Editor.T('CONSOLE.editor_log'), params: [], click () { Editor.Ipc.sendToMain('console:open-log-file'); } }, { label: Editor.T('CONSOLE.cocos_console_log'), params: [], click () { Editor.Ipc.sendToMain('app:open-cocos-console-log'); } }, ]; }, true ); }, unload () { Editor.Menu.unregister( 'open-log-file' ); }, messages: { 'open' () { Editor.Panel.open('console'); }, 'open-log-file': function () { Electron.shell.openItem(Editor.logfile); }, 'console:clear' () { Editor.clearLog(); }, 'popup-open-log-menu': function (event, x, y) { let menuTmpl = Editor.Menu.getMenu('open-log-file'); let editorMenu = new Editor.Menu(menuTmpl, event.sender); x = Math.floor(x); y = Math.floor(y); editorMenu.nativeMenu.popup(BrowserWindow.fromWebContents(event.sender), x, y); editorMenu.dispose(); } } };
JavaScript
0.998059
@@ -49,57 +49,8 @@ n'); -%0Aconst BrowserWindow = require('browser-window'); %0A%0Amo @@ -1104,16 +1104,25 @@ u.popup( +Electron. BrowserW
f3c5b5302be6583b474ae157993664b9c764c8dd
add browserify.bundleDelay to karma config
karma.conf.js
karma.conf.js
module.exports = function (karma) { karma.set({ frameworks: ['browserify', 'mocha', 'sinon-chai'], files: [ 'src/**/*.js', 'test/**/*.spec.js', ], preprocessors: { 'src/**/*.js': ['browserify'], 'test/**/*.spec.js': ['browserify'], }, browserify: { debug: true, transform: [ ['babelify', { presets: ['es2015'], sourceMapsAbsolute: true, }], ['browserify-istanbul', { ignore: ['test/**', '**/node_modules/**'], instrumenterConfig: { embedSource: true, }, }], ], }, colors: true, concurrency: 5, logLevel: karma.LOG_DISABLE, singleRun: true, browserDisconnectTimeout: 60 * 1000, browserDisconnectTolerance: 1, browserNoActivityTimeout: 60 * 1000, captureTimeout: 4 * 60 * 1000, }); if (process.env.TRAVIS) { const customLaunchers = require('./saucelabs-browsers'); karma.set({ autoWatch: false, browsers: Object.keys(customLaunchers), coverageReporter: { type: 'lcovonly', dir: 'coverage/', }, customLaunchers, reporters: ['dots', 'saucelabs', 'coverage'], sauceLabs: { testName: 'ScrollReveal', build: process.env.TRAVIS_BUILD_NUMBER || 'manual', tunnelIdentifier: process.env.TRAVIS_BUILD_NUMBER || 'autoGeneratedTunnelID', recordVideo: true, }, }); } else { process.env.PHANTOMJS_BIN = './node_modules/phantomjs-prebuilt/bin/phantomjs'; karma.set({ browsers: ['PhantomJS'], coverageReporter: { type: 'lcov', dir: 'coverage/', }, reporters: ['mocha', 'coverage'], }); } };
JavaScript
0
@@ -291,24 +291,48 @@ owserify: %7B%0A + bundleDelay: 800,%0A debug:
4c7c6e75b4e29eba54a0dfd8c09920d97ae4c853
Fix return highest expense
main.js
main.js
var amountTotal = document.getElementById("sum-total"); var incAmount = document.getElementsByName("incAmount"); var expAmount = document.getElementsByName("expAmount"); var incAmountTotal = 0; var expenseContainer = document.getElementById("expenseContainer"); var mainContainer = document.getElementById("mainContainer"); var diffContainer = document.getElementById("diffContainer") var diff = document.getElementById("diff"); var expAmountTtl = 0 var incomeTotal = document.getElementById("incomeTotal"); var expenseTotal = document.getElementById("expenseTotal"); var expAmountTotal = document.getElementById("expSum-total"); var mainIncome = document.getElementById("mainIncome"); var mainExpense = document.getElementById("mainExpense"); var amountArr = []; var amountArr2 = []; var expAmountArr = []; var expAmountArr2 = []; var incomeSrc = document.getElementsByName("incomeSrc"); var expenseSrc = document.getElementsByName("expense-name"); var highest = 0; var expHighest = 0; function addUp(a, b){ return a + b; }; // Income input function for (var index = 0; index < incAmount.length; index++) { incAmount[index].addEventListener("input", add3); function add3() { for (var i = 0; i < incAmount.length; i++) { amountArr[i] = parseFloat(incAmount[i].value) || 0; incAmountTotal = amountArr.reduce(addUp); amountTotal.innerHTML = incAmountTotal; }; }; }; // Expense Input function for (var i = 0; i < expAmount.length; i++) { expAmount[i].addEventListener("input", expAdd); function expAdd() { for (var i = 0; i < expAmount.length; i++) { expAmountArr[i] = parseFloat(expAmount[i].value) || 0; expAmountTtl = expAmountArr.reduce(addUp); expAmountTotal.innerHTML = expAmountTtl; }; }; }; // Button Handlers var nextBtn = document.getElementById("next-btn"); var backBtn = document.getElementById("back-btn"); var backBtn2 = document.getElementById("back-btn2"); var backBtn3 = document.getElementById("back-btn3"); var calculate = document.getElementById("calculate-btn"); var addFeildInc = document.getElementById("add-btnI"); var addFeildExp = document.getElementById("add-btnE"); // Attempt at adding Feilds functionality var input = document.createElement("input"); input.setAttribute("id", "amount#5") ; input.setAttribute("name", "incAmount"); input.setAttribute("placeholder", "Enter Amount"); input.setAttribute("type", "number"); var incInputs = document.getElementById("incomeInputs"); addFeildInc.addEventListener("click", addInputI); function addInputI(){ // incInputs.innerHTML = "<input type="number" class="form-control" id="amount#4" placeholder="Enter Amount" name="incAmount">"; incInputs.appendChild(input).className= "form-control" ; incAmount = document.getElementsByName("incAmount"); }; // End Attempt // Button Event Listeners nextBtn.addEventListener("click", toExpenses); backBtn.addEventListener("click", toIncome); backBtn2.addEventListener("click", toExpenses); backBtn3.addEventListener("click", toIncome); calculate.addEventListener("click", toDiff) function toExpenses(){ mainContainer.className = "hide"; expenseContainer.className = "container well"; diffContainer.className = "hide"; amountArr2 = amountArr.slice(); amountArr2.sort(function(a , b){ return b - a; }); console.log(amountArr2[0]); }; function toIncome(){ expenseContainer.className = "hide"; mainContainer.className = "container well"; diffContainer.className = "hide"; }; function toDiff(){ expenseContainer.className = "hide"; mainContainer.className = "hide"; diffContainer.className = "container well"; diff.innerHTML = incAmountTotal - expAmountTtl; incomeTotal.innerHTML = incAmountTotal; expenseTotal.innerHTML = expAmountTtl; // Find and Return highest Expense expAmountArr2 = expAmountArr.slice(); expAmountArr2.sort(function(a , b){ return b - a; }); expHighest =expAmountArr2.shift(); var b = expAmountArr.indexOf(expHighest); mainExpense.innerHTML = expenseSrc[b].value + " (" + expHighest + ")" || "No Source Stated" + " (" + expHighest + ")"; // Control logs console.log(expAmountArr); console.log(amountArr2[0]); console.log(highest); console.log(amountArr.indexOf(highest)); // Return highest Income highest = amountArr2.shift(); var a = amountArr.indexOf(highest); mainIncome.innerHTML = incomeSrc[a].value + " (" + highest + ")" || "No Source Stated" + " (" + highest + ")"; };
JavaScript
0.000799
@@ -3885,16 +3885,235 @@ ntTtl;%0A%0A + // Return highest Income%0A highest = amountArr2.shift();%0A var a = amountArr.indexOf(highest);%0A mainIncome.innerHTML = incomeSrc%5Ba%5D.value + %22 (%22 + highest + %22)%22 %7C%7C %22No Source Stated%22 + %22 (%22 + highest + %22)%22;%0A%0A // F @@ -4627,221 +4627,13 @@ -// Return highest Income%0A highest = amountArr2.shift();%0A var a = amountArr.indexOf(highest);%0A mainIncome.innerHTML = incomeSrc%5Ba%5D.value + %22 (%22 + highest + %22)%22 %7C%7C %22No Source Stated%22 + %22 (%22 + highest + %22)%22; +%0A %0A%7D;%0A
b2b3662e2478a166019962bfb0fda9679b8f328e
update import page
src/views/Import.react.js
src/views/Import.react.js
import React, { Component, PropTypes } from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import * as PreviewActions from 'actions/previewPage/PreviewActions'; class ImportView extends Component { constructor(props) { super(props); const { mappingsection, homesection, dispatch } = this.props; console.log(this.state); this.mappedJson; this.jsonpreview = [ { "product":"pen", "ProductId":100, "price":100 }, { "product":"pencile", "ProductId":101, "price":101 }, { "product":"ink", "ProductId":102, "price":102 } ]; this.stringJSon=JSON.stringify(this.jsonpreview,null,4); this.actions = bindActionCreators(PreviewActions, dispatch); console.log("json",this.stringJSon.length); } importJson() { } isBackToThirdStep(e){ this.actions.redirectMapping(); } parseJson(json){ json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) { return '<span>' + match + '</span>'; }); } componentWillReceiveProps(nextProps){ this.props = nextProps; let mappingsection = this.props.mappingsection; if(mappingsection && mappingsection.mappingData){ this.jsonpreview = mappingsection.mappingData; } } render() { return ( <div className="container"> <div className="row">dir <div className="upload-container"> <legend>Json Preview</legend> </div> <div className="col-lg-6"> <div className="row"> <div ng-hide="mappedJson"> <i className="fa fa-spinner fa-pulse"></i> Processing Json</div> <div className="panel panel-default"> <div className="panel-body"> {this.stringJSon} </div> </div> </div> </div> <div className="col-lg-3 col-lg-offset-9 btn-set button-container"> <button className="btn btn-primary pull-right" onClick={this.actions.redirectMapping}>Back</button> <span> </span> <div className="btn btn-primary pull-right" onClick={this.importJson.bind(this)}>Download</div> </div> </div> </div> ) } } function mapStateToProps(state) { const { mappingsection, attributesectionsearch, homesection } = state; return { mappingsection, attributesectionsearch, homesection }; } ImportView.propTypes = { mappingsection: React.PropTypes.object, dispatch: React.PropTypes.func.isRequired }; export default connect(mapStateToProps)(ImportView);
JavaScript
0
@@ -366,593 +366,53 @@ -console.log(this.state);%0A this.mappedJson;%0A this.jsonpreview = %5B%0A %7B%0A %22product%22:%22pen%22,%0A %22ProductId%22:100,%0A %22price%22:100%0A %7D,%0A %7B%0A %22product%22:%22pencile%22,%0A %22ProductId%22:101,%0A %22price%22:101%0A %7D,%0A %7B%0A %22product%22:%22ink%22,%0A %22ProductId%22:102,%0A %22price%22:102%0A %7D%0A%0A %5D +this.jsonpreview = mappingsection.mappingData ;%0A @@ -473,17 +473,16 @@ null,4); - %0A @@ -1403,12 +1403,8 @@ ow%22%3E -dir%0A %0A
f0e7c9a87da54065447577999124b02510314006
second question answered
main.js
main.js
var _ = require('underscore'); var data = require('./items.json'); //Getting prices from the data. // var prices = _.pluck (data, 'price'); //Reducing the prices to a single number //Dividing that by the number of items in the array // var avgPrice = _.reduce(prices, function(a, b); // // console.log(prices) //Second question! //get prices between $14 and $18 //list of prices is already plucked // var priceRange = _.filter(prices, // function(priceList){ // if _.each (prices) >= 14 && <=18; // return true; // } // else { // return false; // } // ); // console.log(priceRange) //get names of said items
JavaScript
0.999955
@@ -94,16 +94,17 @@ data.%0A%0A + // var p @@ -135,16 +135,40 @@ price'); +%0A // console.log(prices) %0A%0A//Redu @@ -352,17 +352,16 @@ estion!%0A -%0A //get pr @@ -388,49 +388,42 @@ $18 -%0A//list of prices is already plucked%0A%0A// +, not using other list of prices%0A%0A var @@ -448,19 +448,14 @@ ter( -prices,%0A// +data,%0A fu @@ -477,184 +477,351 @@ t)%7B%0A -// - if _.each (prices +return Number (priceList.price ) %3E -= 14 && -%3C= +Number (priceList.price) %3C 18;%0A -// - return true;%0A// %7D%0A// else %7B%0A// return false +%7D%0A%0A );%0A//get names of said items%0A%0Avar rangeNames = _.pluck(priceRange, 'title');%0A%0Aconsole.log(%22Items that cost between $14.00 USD and $18.00 USD:%22 + %22 %22 + rangeNames + %22.%22) ;%0A +%0A // - %7D%0A// );%0A// console.log(priceRange)%0A%0A//get names of said items +Question three%0A%0A// var pounds = _.pluck (data, 'currency_code');%0A// console.log(pounds) %0A
e6ff8209d15e4b24a8a33664eff4151731f769e3
Fix comment formatting in main.js
main.js
main.js
/** * @module IsotopeView * @author Benjamin Goering - https://github.com/gobengo */ define(function(require) { var Backbone = require('backbone'), Mustache = require('mustache'), isotope = require('isotope'), ContentTemplate = require('text!streamhub-backbone/templates/Content.html'), ContentView = require('streamhub-backbone/views/ContentView'), sources = require('streamhub-backbone/const/sources'), _ = require('underscore'); /** * IsotopeView, a pluggable View for creating tiled layouts and media walls * @constructor * @class IsotopeView * @alias module:IsotopeView * @augments Backbone.View * @param {Object} opts - Options * @param {Collection} opts.collection - A `Hub.Collection` of `Content` * @param {Object} opts.contentViewOptions - Options to be passed to any `Content` Views this instantiates * This is useful for passing custom templates for Content * @param {Object} opts.sources - An object to configure stuff on a per-source basis * Supports `twitter` and `rss` sub objects with the same opts as this root level * @param {Object} opts.isotope - Options to be passed to isotope on instantiation */ var IsotopeView = Backbone.View.extend({ /** * initializes an `IsotopeView`, and is called automatically on construction * @param {Object} opts - Options to construct with * @see module:IsotopeView * @protected * @todo allow passing custom contentView */ initialize: function (opts) { this._contentViewOpts = opts.contentViewOptions || {}; this._sourceOpts = opts.sources || {}; this._isotopeOpts = opts.isotope || {}; this.$el.addClass(this.className); this.initialCount = 0; this.initialNumToDisplay = opts.initialNumToDisplay || null; this.initialDataItems = []; this.finishInitializing = false; this.collection.on('add', this._addItem, this); this.collection.on('initialDataLoaded', this.render, this); return this; }, /** * @property {String} The default HTML Element to use for this View * @default hub-IsotopeView */ tagName: "div", /** * @property {String} The CSS class that should be added to this View's containing Element * @default hub-IsotopeView */ className: "hub-IsotopeView", /** * Render the initial display of the Collection, including * any initially set Content * @public */ render: function () { var self = this; this.$el.addClass(this.className); // If configured to wait for imagesLoaded after N items if (this.initialNumToDisplay) { // Whenever all images in the view are loaded self.$el.imagesLoaded(function doneWaitingForImages() { // We're done waiting self.finishInitializing = true; if (self.initialDataItems) { // Wait a bit, then insert the rest setTimeout(function() { for(var i=0; i < self.initialDataItems.length; i++) { var insertedEl = self._insertItem(self.initialDataItems[i]); self.$el.isotope('appended', $(insertedEl)); } }, 1500); } }); } // Merge standard isotope options with those passed into constructor var isotopeOptions = _.extend(this._isotopeOpts, { itemSelector: '.hub-item', isAnimated: true, getSortData : { index : function( $item ) { return $item.index(); } }, sortBy : 'index' }); // Initialize the jQuery-Isotope plugin this.$el.isotope(isotopeOptions); // Render Items already in the Collection this.collection.forEach(function(item) { self._insertItem(item, {}); if (self.collection.indexOf(item) == self.collection.length-1) { self.$el.imagesLoaded(function () { self.$el.isotope('reLayout'); }); } }); return this; } }); /** Add Content to the IsotopeView by inserting it in the DOM, then making sure Isotope lays items out correctly @private @param {Content} item - A Content model */ IsotopeView.prototype._addItem = function(item, opts) { if (!this.collection._started && this.initialNumToDisplay !== null) { if (this.initialCount == this.initialNumToDisplay) { this.initialCount++; return; } else if (this.initialCount > this.initialNumToDisplay) { this.initialDataItems.push(item); return; } } var $newItem = this._insertItem(item, opts); if (!$newItem) { console.log("DefaultView: Could not create a hub item element to add to container"); return; } var that = this; $newItem.imagesLoaded(function () { that.$el.isotope( 'reloadItems' ).isotope({ sortBy: 'original-order' }); }); this.initialCount++; }; /** Insert a new ContentView into the DOM @private @param {Content} item - A Content model */ IsotopeView.prototype._insertItem = function (item, opts) { var self = this, newItem = $(document.createElement('div')), json = item.toJSON(); if ( ! json.author) { // TODO: These may be deletes... handle them. console.log("DefaultView: No author for Content, skipping"); return; } function _getContentViewOpts (content) { var opts = {}, configuredOpts = _(opts).extend(self._contentViewOpts), perSourceOpts; if (content.get('source')==sources.TWITTER) { return _(configuredOpts).extend(self._sourceOpts.twitter||{}); } if (content.get('source')==sources.RSS) { return _(configuredOpts).extend(self._sourceOpts.rss||{}); } return configuredOpts; } var cv = new ContentView(_.extend({ model: item, el: newItem }, _getContentViewOpts(item))); newItem .addClass('hub-item') .attr('data-hub-contentId', json.id); if (this.collection._initialized && !this.finishInitializing) { this.$el.prepend(newItem); } else { this.$el.append(newItem); } return newItem; }; return IsotopeView; });
JavaScript
0.000558
@@ -4265,16 +4265,19 @@ );%0A%0A/**%0A + * Add Cont @@ -4352,16 +4352,19 @@ Isotope%0A + * lays @@ -4384,16 +4384,19 @@ rrectly%0A + * @private @@ -4388,32 +4388,35 @@ tly%0A * @private%0A + * @param %7BContent%7D @@ -4430,32 +4430,33 @@ A Content model +%0A */%0AIsotopeView. @@ -5212,16 +5212,19 @@ %7D;%0A%0A/**%0A + * Insert a @@ -5253,16 +5253,19 @@ the DOM%0A + * @private @@ -5265,16 +5265,19 @@ private%0A + * @param %7B @@ -5307,16 +5307,17 @@ nt model +%0A */%0AIsot
247e81bc549a188ed566602117b823e3dec43a8f
change advertising modes menu to broadcasting modes
main.js
main.js
'use strict'; let app = require('app'), BrowserWindow = require('browser-window'), ipc = require('electron').ipcMain, Menu = require('menu'), WebSocketServer = require('ws').Server, wss = new WebSocketServer({ 'port': 1234 }), EddystoneBeacon = require('eddystone-beacon'), mainWindow = null, mdns = require('mdns'), mdnsAd = null, modeBLE = null, modeMDNS = null, activeModes = ''; // Quit when all windows are closed. app.on('window-all-closed', () => { app.quit(); }); function setBleUrl(url, ws) { return new Promise((resolve, reject) => { try { EddystoneBeacon.advertiseUrl(url); activeModes += '<span class="modes">Bluetooth</span>'; mainWindow.webContents.send('status', [`${url} ${activeModes}`, 'Advertising', true]); console.log(`ble advertising: ${url}`); if (ws) { ws.send(`ble advertising: ${url}`); } resolve(); } catch (e) { console.log(`error: ${e}`); mainWindow.webContents.send('status', [e.message, 'Error', false]); if (ws) { ws.send(`error: ${e}`); } reject(); } }); } function setMdnsUrl(url, ws) { return new Promise((resolve, reject) => { try { let urlParts = url.split('/'), protocol = urlParts[0].replace(':', ''), port = protocol === 'https' ? 443 : 80, host = urlParts[2], path = urlParts.filter((part, i) => { return i > 2 ? part : false; }).join('/'); mdnsAd = new mdns.Advertisement(mdns.tcp(protocol), port, { 'name': url, 'txtRecord': { 'path': path }, 'host': host, 'domain': 'local', 'ip': host }); mdnsAd.start(); activeModes += '<span class="modes">mDNS</span>'; mainWindow.webContents.send('status', [`${url} ${activeModes}`, 'Advertising', true]); console.log(`mdns advertising: ${url}`); if (ws) { ws.send(`mdns advertising: ${url}`); } resolve(); } catch (e) { console.log(`error: ${e}`); mainWindow.webContents.send('status', [e.message, 'Error', false]); if (ws) { ws.send(`error: ${e}`); } reject(); } }); } function stopMdns() { if (mdnsAd) { mdnsAd.stop(); } } function setUrl(url, ws) { activeModes = ''; stopMdns(); if (modeBLE.checked || modeMDNS.checked) { if (modeBLE.checked) { setBleUrl(url, ws).then(() => { if (modeMDNS.checked) { setMdnsUrl(url, ws); } }); } if (!modeBLE.checked && modeMDNS.checked) { setMdnsUrl(url, ws); } } else { mainWindow.webContents.send('status', ['Choose at least one advertising mode', 'Error', false]); } } function toggleMode(item) { if (item.checked) { mainWindow.webContents.send('mode', [item.id, true]); } else { mainWindow.webContents.send('mode', [item.id, false]); } } app.on('ready', () => { const menuTemplate = [ { 'label': 'Eddystone', 'submenu': [ { 'label': 'Advertise URL', 'accelerator': 'Command+A', 'click': () => { mainWindow.webContents.send('enter-url', 'go'); } }, { 'label': 'Stop advertising', 'accelerator': 'Command+S', 'click': () => { EddystoneBeacon.stop(); stopMdns(); mainWindow.webContents.send('status', ['Use bookmarklet or <span class="key" aria-label="command">&#8984;</span> + <span class="key">A</span> to enter', 'Waiting', true]); } }, { 'label': 'Quit', 'accelerator': 'Command+Q', 'click': () => { app.quit(); } } ] }, { 'label': 'Edit', 'submenu': [ { 'label': 'Paste', 'accelerator': 'CmdOrCtrl+V', 'selector': 'paste:' } ] }, { 'label': 'Advertising modes', 'submenu': [ { 'label': 'Bluetooth', 'type': 'checkbox', 'id': 'mode-ble', 'checked': true, 'click': item => { toggleMode(item); } }, { 'label': 'mDNS', 'type': 'checkbox', 'id': 'mode-mdns', 'checked': false, 'click': item => { toggleMode(item); } } ] } ]; let menu = Menu.buildFromTemplate(menuTemplate); Menu.setApplicationMenu(menu); modeBLE = menu.items[2].submenu.items[0]; modeMDNS = menu.items[2].submenu.items[1]; mainWindow = new BrowserWindow({'width': 600, 'height': 400, 'resizable': false}); mainWindow.loadURL(`file://${__dirname}/index.html`); mainWindow.on('closed', () => { mainWindow = null; }); mainWindow.webContents.on('did-finish-load', () => { mainWindow.webContents.send('status', ['Use bookmarklet or <span class="key" aria-label="command">&#8984;</span> + <span class="key">A</span> to enter', 'Waiting', true]); }); wss.on('connection', ws => { ws.on('message', url => { console.log(`received: ${url}`); ws.send(`received: ${url}`); setUrl(url, ws); }); }); ipc.on('set-url', (event, arg) => { setUrl(arg); }); ipc.on('set-mode', (event, arg) => { switch (arg) { case 'mode-ble': modeBLE.checked ? modeBLE.checked = false : modeBLE.checked = true; toggleMode(modeBLE); break; case 'mode-mdns': modeMDNS.checked ? modeMDNS.checked = false : modeMDNS.checked = true; toggleMode(modeMDNS); break; default: break; } }); });
JavaScript
0.000001
@@ -3902,24 +3902,25 @@ abel': ' -Advertis +Broadcast ing mode
7bb60f26909d0b415f02684e33115e52a3aa4134
remove repo stats
public/views/repoView.js
public/views/repoView.js
'use strict'; (function(module) { const repoView = {}; // REVIEW: Private methods declared here live only within the scope of the wrapping IIFE. const ui = function() { let $about = $('#about'); // Best practice: Cache the DOM query if it's used more than once. $about.find('ul').empty(); // $about.show().siblings().hide(); }; var render = Handlebars.compile($('#repo-template').text()); repoView.index = function() { ui(); // The jQuery `append` method lets us append an entire array of HTML elements at once: $('#about ul').append( // repos.with('name').map(render) // Want to filter by a different property other than name? repos.with('watchers_count').map(render) ); }; module.repoView = repoView; })(window);
JavaScript
0.000001
@@ -555,18 +555,18 @@ '#about -u l +i ').appen
b45b2875a025feaaa9de6939c567c3fd67bcf66e
Update webpack.config.js
public/webpack.config.js
public/webpack.config.js
const path = require('path'); const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); module.exports = [ { mode: 'production', entry: { front: path.join(__dirname, 'resources', 'javascript', 'index.js'), }, watch: true, output: { path: __dirname + '/dist/', publicPath: '/dist/', filename: "[name].js", }, module: { rules: [ { test: /.jsx?$/, include: [ path.resolve(__dirname, 'resources', 'javascript'), ], exclude: [ path.resolve(__dirname, 'node_modules'), ], loader: 'babel-loader', query: { presets: [ ["@babel/env", { "targets": { "browsers": "last 2 chrome versions" } }], ], }, }, ], }, resolve: { extensions: ['.json', '.js', '.jsx'] }, devtool: 'source-map', optimization: { minimizer: [ new UglifyJsPlugin({ extractComments: true, }), ], }, }, { mode: 'development', entry: [ path.join(__dirname, 'resources', 'scss', 'screen.scss'), ], output: { path: __dirname + '/dist/', publicPath: '/dist/', filename: "[name].css", }, module: { rules: [ { test: /\.s?css$/, use: [ { loader: 'file-loader', options: { name: '[name].css', } }, { loader: 'extract-loader' }, { loader: 'css-loader?-url' }, { loader: 'postcss-loader', options: { plugins: function () { return [ require('precss'), require('autoprefixer'), require('cssnano'), ]; }, }, }, { loader: 'sass-loader' }, ], }, ], }, }, ];
JavaScript
0.000003
@@ -1448,202 +1448,8 @@ r',%0A -%09%09%09%09%09%09%09options: %7B%0A%09%09%09%09%09%09%09%09plugins: function () %7B%0A%09%09%09%09%09%09%09%09%09return %5B%0A%09%09%09%09%09%09%09%09%09%09require('precss'),%0A%09%09%09%09%09%09%09%09%09%09require('autoprefixer'),%0A%09%09%09%09%09%09%09%09%09%09require('cssnano'),%0A%09%09%09%09%09%09%09%09%09%5D;%0A%09%09%09%09%09%09%09%09%7D,%0A%09%09%09%09%09%09%09%7D,%0A %09%09%09%09
92b505ae8dc9d0e94c961248f53e72604aaf54d8
Change default milestonesExpanded setting to `current`
client/app/bundles/course/lesson-plan/reducers/flags.js
client/app/bundles/course/lesson-plan/reducers/flags.js
import actionTypes from '../constants'; const initialState = { canManageLessonPlan: false, milestonesExpanded: 'all', }; export default function (state = initialState, action) { const { type } = action; switch (type) { case actionTypes.LOAD_LESSON_PLAN_SUCCESS: { return { ...state, ...action.flags }; } default: return state; } }
JavaScript
0
@@ -34,16 +34,23 @@ ants';%0A%0A +export const in @@ -121,11 +121,15 @@ d: ' -all +current ',%0A%7D @@ -289,22 +289,33 @@ %7B%0A -return +const nextState = %7B ...st @@ -338,16 +338,163 @@ lags %7D;%0A + if (!nextState.milestonesExpanded) %7B%0A nextState.milestonesExpanded = initialState.milestonesExpanded;%0A %7D%0A return nextState;%0A %7D%0A
c387c73a7aea97b8d95d20ab7ed44504ec351ee2
trim vestigial functionality
main.js
main.js
/*jslint browser: true*/ /*global Tangram, gui */ map = (function () { 'use strict'; var locations = { 'Oakland': [37.8044, -122.2708, 15], 'New York': [40.70531887544228, -74.00976419448853, 15], 'Seattle': [47.5937, -122.3215, 15] }; var map_start_location = locations['New York']; /*** URL parsing ***/ // leaflet-style URL hash pattern: // #[zoom],[lat],[lng] var url_hash = window.location.hash.slice(1, window.location.hash.length).split('/'); if (url_hash.length == 3) { map_start_location = [url_hash[1],url_hash[2], url_hash[0]]; // convert from strings map_start_location = map_start_location.map(Number); } /*** Map ***/ var map = L.map('map', {"keyboardZoomOffset" : .05} ); var layer = Tangram.leafletLayer({ scene: 'scene.yaml', numWorkers: 2, attribution: '<a href="https://mapzen.com/tangram" target="_blank">Tangram</a> | &copy; OSM contributors | <a href="https://mapzen.com/" target="_blank">Mapzen</a>', unloadInvisibleTiles: false, updateWhenIdle: false }); window.layer = layer; var scene = layer.scene; window.scene = scene; // setView expects format ([lat, long], zoom) map.setView(map_start_location.slice(0, 3), map_start_location[2]); var hash = new L.Hash(map); /***** Render loop *****/ window.addEventListener('load', function () { // Scene initialized layer.on('init', function() { }); layer.addTo(map); }); return map; }());
JavaScript
0
@@ -92,24 +92,34 @@ var +map_start_ location s = %7B%0A @@ -114,227 +114,62 @@ tion -s = -%7B%0A 'Oakland': %5B37.8044, -122.2708, 15%5D,%0A 'New York': %5B40.70531887544228, -74.00976419448853, 15%5D,%0A 'Seattle': %5B47.5937, -122.3215, 15%5D%0A %7D;%0A%0A var map_start_location = locations%5B'New York'%5D; +%5B40.70531887544228, -74.00976419448853, 15%5D; // NYC %0A%0A @@ -714,31 +714,8 @@ l',%0A - numWorkers: 2,%0A @@ -886,76 +886,8 @@ /a%3E' -,%0A unloadInvisibleTiles: false,%0A updateWhenIdle: false %0A
2dd36e05760a6beb875af57ecb72b786fa8f88b3
Disable devtools on start
main.js
main.js
'use strict'; const electron = require('electron'); // Module to control application life. const app = electron.app; // Module to create native browser window. const BrowserWindow = electron.BrowserWindow; const Menu = electron.Menu; const MenuItem = electron.MenuItem; // Keep a global reference of the window object, if you don't, the window will // be closed automatically when the JavaScript object is garbage collected. let mainWindow; function createWindow() { // Create the browser window. mainWindow = new BrowserWindow({ width: 1080, height: 760 }); // Disable default menu at start. const menu = new Menu(); mainWindow.setMenu(menu); // and load the index.html of the app. mainWindow.loadURL('file://' + __dirname + '/index.html'); mainWindow.webContents.openDevTools(); // Emitted when the window is closed. mainWindow.on('closed', function() { // Dereference the window object, usually you would store windows // in an array if your app supports multi windows, this is the time // when you should delete the corresponding element. mainWindow = null; }); } // This method will be called when Electron has finished // initialization and is ready to create browser windows. app.on('ready', createWindow); // Quit when all windows are closed. app.on('window-all-closed', function() { // On OS X it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit(); } }); app.on('activate', function() { // On OS X it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (mainWindow === null) { createWindow(); } });
JavaScript
0.000001
@@ -773,24 +773,27 @@ x.html');%0D%0A + // mainWindow.
e9b0c6cab2f41fe26369a6d3105cfce7280cea47
use tasklistData.newChild
client/scripts/task/modals/cam-tasklist-comment-form.js
client/scripts/task/modals/cam-tasklist-comment-form.js
define([ 'angular', 'camunda-bpm-sdk', 'text!./cam-tasklist-comment-form.html' ], function( angular, camSDK, template ) { 'use strict'; var commentCreateModalCtrl = [ '$scope', '$translate', 'Notifications', 'camAPI', 'task', function( $scope, $translate, Notifications, camAPI, task ) { var Task = camAPI.resource('task'); $scope.comment = { message: '' }; $scope.$on('$locationChangeSuccess', function() { $scope.$dismiss(); }); function errorNotification(src, err) { $translate(src).then(function(translated) { Notifications.addError({ status: translated, message: (err ? err.message : ''), exclusive: true }); }); } function successNotification(src) { $translate(src).then(function(translated) { Notifications.addMessage({ duration: 3000, status: translated }); }); } $scope.submit = function() { Task.createComment(task.id, $scope.comment.message, function(err) { if (err) { return errorNotification('COMMENT_SAVE_ERROR', err); } successNotification('COMMENT_SAVE_SUCCESS'); $scope.$close(); }); }; }]; return [ '$modal', '$scope', function( $modal, $scope ) { var commentData = $scope.taskData.newChild($scope); function open(task) { $modal.open({ // creates a child scope of a provided scope scope: $scope, //TODO: extract filter edit modal class to super style sheet windowClass: 'filter-edit-modal', size: 'lg', template: template, controller: commentCreateModalCtrl, resolve: { task: function() { return task; } } }).result.then(function() { commentData.changed('task'); }); } $scope.createComment = function(task) { open(task); }; }]; });
JavaScript
0.000002
@@ -1392,16 +1392,20 @@ ope.task +list Data.new
08cb9c97c18d8491ce018fb02dd7b1ff05e160c7
Fix wrong subtraction name in pathoscope mapping overview
client/src/js/analyses/components/Pathoscope/Mapping.js
client/src/js/analyses/components/Pathoscope/Mapping.js
import numbro from "numbro"; import React from "react"; import { connect } from "react-redux"; import { ProgressBar } from "react-bootstrap"; import { Link } from "react-router-dom"; import styled from "styled-components"; import { Box, Flex, FlexItem, Icon, Label } from "../../../base"; import { getColor } from "../../../base/utils"; import { toThousand } from "../../../utils/utils"; const StyledAnalysisMappingReference = styled.div` align-items: center; display: flex; flex: 0 0 auto; margin-left: 10px; ${Label} { margin-left: 5px; } `; export const AnalysisMappingReference = ({ index, reference }) => ( <StyledAnalysisMappingReference> <Link to={`/refs/${reference.id}`}>{reference.name}</Link> <Label>{index.version}</Label> </StyledAnalysisMappingReference> ); const StyledAnalysisMappingSubtraction = styled(Link)` flex: 0 0 auto; margin-left: 10px; `; export const AnalysisMappingSubtraction = ({ subtraction }) => ( <StyledAnalysisMappingSubtraction to={`/subtractions/${subtraction.id}`}> {subtraction.id} </StyledAnalysisMappingSubtraction> ); const AnalysisMappingLegendIcon = styled(Icon)` color: ${props => getColor(props.color)}; margin-right: 3px; `; const AnalysisMappingLegendLabel = styled.div` align-items: center; display: flex; margin-bottom: 5px; justify-content: space-between; width: 500px; `; const AnalysisMappingLegendCount = styled.div` padding-left: 50px; text-align: right; `; const StyledAnalysisMapping = styled(Box)` margin-bottom: 30px; h3 { align-items: flex-end; display: flex; justify-content: space-between; } `; const AnalysisMappingLegendIconReference = styled.div` display: flex; align-items: center; `; export const AnalysisMapping = ({ index, reference, subtraction, toReference, total, toSubtraction = 0 }) => { const referencePercent = toReference / total; const subtractionPercent = toSubtraction / total; const totalMapped = toReference + toSubtraction; const sumPercent = totalMapped / total; return ( <StyledAnalysisMapping> <h3> {numbro(sumPercent).format({ output: "percent", mantissa: 2 })} mapped <small> {toThousand(totalMapped)} / {toThousand(total)} </small> </h3> <ProgressBar> <ProgressBar now={referencePercent * 100} /> <ProgressBar bsStyle="warning" now={subtractionPercent * 100} /> </ProgressBar> <Flex> <FlexItem> <AnalysisMappingLegendLabel> <AnalysisMappingLegendIconReference> <AnalysisMappingLegendIcon name="circle" color="blue" /> <AnalysisMappingReference reference={reference} index={index} /> </AnalysisMappingLegendIconReference> <AnalysisMappingLegendCount>{toThousand(toReference)}</AnalysisMappingLegendCount> </AnalysisMappingLegendLabel> <AnalysisMappingLegendLabel> <AnalysisMappingLegendIconReference> <AnalysisMappingLegendIcon name="circle" color="yellow" /> <AnalysisMappingSubtraction subtraction={subtraction} /> </AnalysisMappingLegendIconReference> <AnalysisMappingLegendCount>{toThousand(toSubtraction)}</AnalysisMappingLegendCount> </AnalysisMappingLegendLabel> </FlexItem> </Flex> </StyledAnalysisMapping> ); }; const mapStateToProps = state => { const { index, read_count, reference, subtracted_count } = state.analyses.detail; return { index, reference, subtraction: state.samples.detail.subtraction, toReference: read_count, toSubtraction: subtracted_count, total: state.samples.detail.quality.count }; }; export default connect(mapStateToProps)(AnalysisMapping);
JavaScript
0
@@ -3852,16 +3852,29 @@ ed_count +, subtraction %7D = sta @@ -3953,42 +3953,8 @@ -subtraction: state.samples.detail. subt
65152c3d81201e3f2c5673e09d4df5c0c27c5662
Throw error instead of logging to console. (fixes #35)
main.js
main.js
const { app } = require('electron') const chokidar = require('chokidar') const fs = require('fs') const { spawn } = require('child_process') const appPath = app.getAppPath() const ignoredPaths = /node_modules|[/\\]\./ // Main file poses a special case, as its changes are // only effective when the process is restarted (hard reset) // We assume that electron-reload is required by the main // file of the electron application const mainFile = module.parent.filename /** * Creates a callback for hard resets. * * @param {String} eXecutable path to electron executable * @param {String} hardResetMethod method to restart electron * @returns {Function} handler to pass to chokidar */ const createHardresetHandler = (eXecutable, hardResetMethod, argv) => () => { // Detaching child is useful when in Windows to let child // live after the parent is killed const args = (argv || []).concat([appPath]) const child = spawn(eXecutable, args, { detached: true, stdio: 'inherit' }) child.unref() // Kamikaze! // In cases where an app overrides the default closing or quiting actions // firing an `app.quit()` may not actually quit the app. In these cases // you can use `app.exit()` to gracefully close the app. if (hardResetMethod === 'exit') { app.exit() } else { app.quit() } } module.exports = function elecronReload (glob, options = {}) { const browserWindows = [] const watcher = chokidar.watch(glob, Object.assign({ ignored: [ignoredPaths, mainFile] }, options)) // Callback function to be executed: // I) soft reset: reload browser windows const softResetHandler = () => browserWindows.forEach(bw => bw.webContents.reloadIgnoringCache()) // II) hard reset: restart the whole electron process const eXecutable = options.electron const hardResetHandler = createHardresetHandler(eXecutable, options.hardResetMethod, options.argv) // Add each created BrowserWindow to list of maintained items app.on('browser-window-created', (e, bw) => { browserWindows.push(bw) // Remove closed windows from list of maintained items bw.on('closed', function () { const i = browserWindows.indexOf(bw) // Must use current index browserWindows.splice(i, 1) }) }) // Enable default soft reset watcher.on('change', softResetHandler) // Preparing hard reset if electron executable is given in options // A hard reset is only done when the main file has changed if (eXecutable && fs.existsSync(eXecutable)) { const hardWatcher = chokidar.watch(mainFile, Object.assign({ ignored: [ignoredPaths] }, options)) if (options.forceHardReset === true) { // Watch every file for hard reset and not only the main file hardWatcher.add(glob) // Stop our default soft reset watcher.close() } hardWatcher.once('change', hardResetHandler) } else { console.log('Electron could not be found. No hard resets for you!') } }
JavaScript
0
@@ -2500,12 +2500,21 @@ able - && +) %7B%0A if (! fs.e @@ -2534,24 +2534,124 @@ cutable)) %7B%0A + throw new Error('Provided electron executable cannot be found or is not exeecutable!')%0A %7D%0A%0A const ha @@ -2999,91 +2999,8 @@ er)%0A - %7D else %7B%0A console.log('Electron could not be found. No hard resets for you!')%0A %7D%0A
8fbfe5f28641a15674904238cc10be81e96607b4
add more test cases
src/websocket_url.spec.js
src/websocket_url.spec.js
/// <reference path="websocket_url.js"> describe("WebsocketUrl", function() { 'use strict'; it("should understand absolute http urls", function() { expect(websocketUrl("http://example.com/sub/")).toEqual("ws://example.com/sub/"); }); it("should understand absolute https urls", function() { expect(websocketUrl("https://example.com/sub/")).toEqual("wss://example.com/sub/"); }); it("should understand absolute urls", function() { expect(websocketUrl("/funny")).toMatch(/^wss?:\/\/[^\/]*\/funny/); }); it("should understand relative urls", function() { // NOTE: relative url derived from test suite named: "test/SpecRunner.html" expect(websocketUrl("funny")).toMatch(/^wss?:\/\/[^\/]*\.*\/test\/funny/); }); });
JavaScript
0
@@ -507,24 +507,25 @@ %5E%5C/%5D*%5C/funny +$ /);%0A %7D);%0A @@ -730,16 +730,278 @@ t%5C/funny +$/);%0A %7D);%0A it(%22should understand root urls%22, function() %7B%0A expect(websocketUrl(%22/%22)).toMatch(/%5Ewss?:%5C/%5C/%5B%5E%5C/%5D*%5C.*%5C/$/);%0A %7D);%0A it(%22should understand blank urls%22, function() %7B%0A expect(websocketUrl(%22%22)).toMatch(/%5Ewss?:%5C/%5C/%5B%5E%5C/%5D*%5C.*%5C/test%5C/SpecRunner.html$ /);%0A %7D)
f0488296d459e5c15ff7015cdb2398cf885ead26
remove async await
index.ios.js
index.ios.js
/** * @providesModule RNNotifications * @flow */ "use strict"; import { NativeModules, DeviceEventEmitter, NativeAppEventEmitter } from "react-native"; import Map from "core-js/library/es6/map"; import uuid from "uuid"; const NativeRNNotifications = NativeModules.RNNotifications; // eslint-disable-line no-unused-vars import IOSNotification from "./notification.ios"; export const DEVICE_REMOTE_NOTIFICATIONS_REGISTERED_EVENT = "remoteNotificationsRegistered"; export const DEVICE_REMOTE_NOTIFICATIONS_REGISTRATION_FAILED_EVENT = "remoteNotificationsRegistrationFailed"; export const DEVICE_PUSH_KIT_REGISTERED_EVENT = "pushKitRegistered"; export const DEVICE_NOTIFICATION_RECEIVED_FOREGROUND_EVENT = "notificationReceivedForeground"; export const DEVICE_NOTIFICATION_RECEIVED_BACKGROUND_EVENT = "notificationReceivedBackground"; export const DEVICE_NOTIFICATION_OPENED_EVENT = "notificationOpened"; const DEVICE_NOTIFICATION_ACTION_RECEIVED = "notificationActionReceived"; const _exportedEvents = [ DEVICE_REMOTE_NOTIFICATIONS_REGISTERED_EVENT, DEVICE_REMOTE_NOTIFICATIONS_REGISTRATION_FAILED_EVENT, DEVICE_PUSH_KIT_REGISTERED_EVENT, DEVICE_NOTIFICATION_RECEIVED_FOREGROUND_EVENT, DEVICE_NOTIFICATION_RECEIVED_BACKGROUND_EVENT, DEVICE_NOTIFICATION_OPENED_EVENT ]; const _notificationHandlers = new Map(); const _actionHandlers = new Map(); let _actionListener; export class NotificationAction { constructor(options: Object, handler: Function) { this.options = options; this.handler = handler; } } export class NotificationCategory { constructor(options: Object) { this.options = options; } } export default class NotificationsIOS { /** * Attaches a listener to remote notification events while the app is running * in the foreground or the background. * * Valid events are: * * - `remoteNotificationsRegistered` : Fired when the user registers for remote notifications. The handler will be invoked with a hex string representing the deviceToken. * - `notificationReceivedForeground` : Fired when a notification (local / remote) is received when app is on foreground state. * - `notificationReceivedBackground`: Fired when a background notification is received. * - `notificationOpened`: Fired when a notification (local / remote) is opened. */ static addEventListener(type: string, handler: Function) { if (_exportedEvents.indexOf(type) !== -1) { let listener; if (type === DEVICE_REMOTE_NOTIFICATIONS_REGISTERED_EVENT) { listener = DeviceEventEmitter.addListener( DEVICE_REMOTE_NOTIFICATIONS_REGISTERED_EVENT, registration => handler(registration.deviceToken) ); } else if (type === DEVICE_REMOTE_NOTIFICATIONS_REGISTRATION_FAILED_EVENT) { listener = DeviceEventEmitter.addListener( DEVICE_REMOTE_NOTIFICATIONS_REGISTRATION_FAILED_EVENT, error => handler(error) ); } else if (type === DEVICE_PUSH_KIT_REGISTERED_EVENT) { listener = DeviceEventEmitter.addListener( DEVICE_PUSH_KIT_REGISTERED_EVENT, registration => handler(registration.pushKitToken) ); } else { listener = DeviceEventEmitter.addListener( type, notification => handler(new IOSNotification(notification)) ); } _notificationHandlers.set(handler, listener); } } /** * Removes the event listener. Do this in `componentWillUnmount` to prevent * memory leaks */ static removeEventListener(type: string, handler: Function) { if (_exportedEvents.indexOf(type) !== -1) { const listener = _notificationHandlers.get(handler); if (listener) { listener.remove(); _notificationHandlers.delete(handler); } } } static _actionHandlerDispatcher(action: Object) { const actionHandler = _actionHandlers.get(action.identifier); if (actionHandler) { action.notification = new IOSNotification(action.notification); actionHandler(action, () => { NativeRNNotifications.completionHandler(action.completionKey); }); } } /** * Sets the notification categories */ static requestPermissions(categories: Array<NotificationCategory>) { let notificationCategories = []; if (categories) { // subscribe once for all actions _actionListener = NativeAppEventEmitter.addListener(DEVICE_NOTIFICATION_ACTION_RECEIVED, this._actionHandlerDispatcher.bind(this)); notificationCategories = categories.map(category => { return Object.assign({}, category.options, { actions: category.options.actions.map(action => { // subscribe to action event _actionHandlers.set(action.options.identifier, action.handler); return action.options; }) }); }); } NativeRNNotifications.requestPermissionsWithCategories(notificationCategories); } /** * Unregister for all remote notifications received via Apple Push Notification service. */ static abandonPermissions() { NativeRNNotifications.abandonPermissions(); } /** * Removes the event listener. Do this in `componentWillUnmount` to prevent * memory leaks */ static resetCategories() { if (_actionListener) { _actionListener.remove(); } _actionHandlers.clear(); } static setBadgesCount(count: number) { NativeRNNotifications.setBadgesCount(count); } static registerPushKit() { NativeRNNotifications.registerPushKit(); } static backgroundTimeRemaining(callback: Function) { NativeRNNotifications.backgroundTimeRemaining(callback); } static consumeBackgroundQueue() { NativeRNNotifications.consumeBackgroundQueue(); } static log(message: string) { NativeRNNotifications.log(message); } /** * Presenting local notification * * notification is an object containing: * * - `alertBody` : The message displayed in the notification alert. * - `alertTitle` : The message title displayed in the notification. * - `alertAction` : The "action" displayed beneath an actionable notification. Defaults to "view"; * - `soundName` : The sound played when the notification is fired (optional). * - `category` : The category of this notification, required for actionable notifications (optional). * - `userInfo` : An optional object containing additional notification data. * - `fireDate` : The date and time when the system should deliver the notification. if not specified, the notification will be dispatched immediately. */ static localNotification(notification: Object) { const notificationId = uuid.v4(); NativeRNNotifications.localNotification(notification, notificationId); return notificationId; } static cancelLocalNotification(notificationId: String) { NativeRNNotifications.cancelLocalNotification(notificationId); } static cancelAllLocalNotifications() { NativeRNNotifications.cancelAllLocalNotifications(); } static async isRegisteredForRemoteNotifications() { return await NativeRNNotifications.isRegisteredForRemoteNotifications(); } }
JavaScript
0.00005
@@ -7048,14 +7048,8 @@ tic -async isRe @@ -7098,14 +7098,8 @@ urn -await Nati
fa7a3f22444b784052b71d6649bb435421803d0d
Add description and example
src/widgets/IconWidget.js
src/widgets/IconWidget.js
/** * Icon widget. * * See OO.ui.IconElement for more information. * * @class * @extends OO.ui.Widget * @mixins OO.ui.IconElement * @mixins OO.ui.TitledElement * * @constructor * @param {Object} [config] Configuration options */ OO.ui.IconWidget = function OoUiIconWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.IconWidget.super.call( this, config ); // Mixin constructors OO.ui.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) ); OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) ); // Initialization this.$element.addClass( 'oo-ui-iconWidget' ); }; /* Setup */ OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget ); OO.mixinClass( OO.ui.IconWidget, OO.ui.IconElement ); OO.mixinClass( OO.ui.IconWidget, OO.ui.TitledElement ); /* Static Properties */ OO.ui.IconWidget.static.tagName = 'span';
JavaScript
0.000001
@@ -8,66 +8,729 @@ Icon - w +W idget -.%0A *%0A * See OO.ui.IconElement for more information. + is a generic widget for %7B@link OO.ui.IconElement icons%7D. In general, IconWidgets should be used with OO.ui.LabelWidget,%0A * which creates a label that identifies the icon%E2%80%99s function. See the %5BOOjs UI documentation on MediaWiki%5D %5B1%5D%0A * for a list of icons included in the library.%0A *%0A * @example%0A * // An icon widget with a label%0A * var myIcon = new OO.ui.IconWidget(%7B%0A * icon: 'help',%0A * iconTitle: 'Help'%0A * %7D);%0A * // Create a label.%0A * var iconLabel = new OO.ui.LabelWidget(%7B%0A * label: 'Help'%0A * %7D);%0A * $('body').append(myIcon.$element, iconLabel.$element);%0A *%0A * %5B1%5D: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons %0A *%0A