commit
stringlengths
40
40
old_file
stringlengths
4
150
new_file
stringlengths
4
150
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
501
message
stringlengths
15
4.06k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
diff
stringlengths
0
4.35k
e6de9cdbc7ee08097b041550fc1b1edd60a98619
src/sanity/inputResolver/inputResolver.js
src/sanity/inputResolver/inputResolver.js
import array from 'role:@sanity/form-builder/input/array?' import boolean from 'role:@sanity/form-builder/input/boolean?' import date from 'role:@sanity/form-builder/input/date?' import email from 'role:@sanity/form-builder/input/email?' import geopoint from 'role:@sanity/form-builder/input/geopoint?' import number from 'role:@sanity/form-builder/input/number?' import object from 'role:@sanity/form-builder/input/object?' import reference from 'role:@sanity/form-builder/input/reference?' import string from 'role:@sanity/form-builder/input/string?' import text from 'role:@sanity/form-builder/input/text?' import url from 'role:@sanity/form-builder/input/url?' import DefaultReference from '../inputs/Reference' const coreTypes = { array, boolean, date, email, geopoint, number, object, reference: reference || DefaultReference, string, text, url } const inputResolver = (field, fieldType) => { const inputRole = coreTypes[field.type] || coreTypes[fieldType.name] return field.input || inputRole } export default inputResolver
import array from 'role:@sanity/form-builder/input/array?' import boolean from 'role:@sanity/form-builder/input/boolean?' import date from 'role:@sanity/form-builder/input/date?' import email from 'role:@sanity/form-builder/input/email?' import geopoint from 'role:@sanity/form-builder/input/geopoint?' import number from 'role:@sanity/form-builder/input/number?' import object from 'role:@sanity/form-builder/input/object?' import reference from 'role:@sanity/form-builder/input/reference?' import string from 'role:@sanity/form-builder/input/string?' import text from 'role:@sanity/form-builder/input/text?' import url from 'role:@sanity/form-builder/input/url?' import DefaultReference from '../inputs/Reference' const primitiveTypes = { array, boolean, date, number, object, reference: reference || DefaultReference, string } const bundledTypes = { email, geopoint, text, url } const coreTypes = Object.assign({}, primitiveTypes, bundledTypes) const inputResolver = (field, fieldType) => { const inputRole = coreTypes[field.type] || coreTypes[fieldType.name] return field.input || inputRole } export default inputResolver
Split up vars for consistency with official Sanity terms
Split up vars for consistency with official Sanity terms
JavaScript
mit
sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity
--- +++ @@ -12,19 +12,22 @@ import DefaultReference from '../inputs/Reference' -const coreTypes = { +const primitiveTypes = { array, boolean, date, - email, - geopoint, number, object, reference: reference || DefaultReference, - string, + string +} +const bundledTypes = { + email, + geopoint, text, url } +const coreTypes = Object.assign({}, primitiveTypes, bundledTypes) const inputResolver = (field, fieldType) => { const inputRole = coreTypes[field.type] || coreTypes[fieldType.name]
7b37439270e372ec4baf226330cdaa1610608d49
app/assets/javascripts/home.js
app/assets/javascripts/home.js
# Place all the behaviors and hooks related to the matching controller here. # All this logic will automatically be available in application.js. # You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/
// Place all the behaviors and hooks related to the matching controller here. // All this logic will automatically be available in application.js. // You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/
Remove HipsterScript-style comments from JS sources.
Remove HipsterScript-style comments from JS sources.
JavaScript
agpl-3.0
teikei/teikei,teikei/teikei,teikei/teikei,sjockers/teikei,sjockers/teikei,sjockers/teikei
--- +++ @@ -1,3 +1,3 @@ -# Place all the behaviors and hooks related to the matching controller here. -# All this logic will automatically be available in application.js. -# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/ + // Place all the behaviors and hooks related to the matching controller here. + // All this logic will automatically be available in application.js. + // You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/
fed23fcd236419462e5e5ee8f71db0d88eedfbe3
parseCloudCode/parse/cloud/main.js
parseCloudCode/parse/cloud/main.js
// Use Parse.Cloud.define to define as many cloud functions as you want. // For example: Parse.Cloud.define("hello", function(request, response) { response.success("Doms Cloud Code!"); });
// Use Parse.Cloud.define to define as many cloud functions as you want. // For example: Parse.Cloud.define("hello", function(request, response) { console.log("hello5"); response.success("Doms Cloud Code"); }); //test function Parse.Cloud.beforeSave("MatchScore", function(request, response) { if (request.object.get("P10Score") > 3) { response.error("Games are first to 3"); //return response.error(JSON.stringify({code: ErrorCodes["450"], message: "Games are first to 3"})); } else { response.success(); } }); //User opt in/out of leaderboard Parse.Cloud.define("joinLeaderboard", function(request, response) { //set the leaderboard flag to true var currentUser = Parse.User.current(); currentUser.set("Leaderboard", true); currentUser.save(); var AddLeaderboard = Parse.Object.extend("LeaderBoard"); var AddLeaderboard = Parse.Object.extend("LeaderBoard"); var query = new Parse.Query(AddLeaderboard); query.notEqualTo("Ranking", 0); query.count().then(function(count) { //success console.log(count); return count; }).then (function(count) { var currentUser = Parse.User.current(); var addLeaderboard = new AddLeaderboard(); var newPlayerRanking = count + 1; addLeaderboard.save({Ranking: newPlayerRanking, playerID: currentUser}, { success: function(object) { console.log("User added to the leaderboard55"); response.success("Learderboard Joined!!") }, error: function(model, error) { console.error("Error User could not be added to the leaderboard"); } }); }, function(error) { //error console.log("error5"); response.error("error5"); }); });
Add user to the leaderboard
Add user to the leaderboard adds the user to the bottom of the leaderboard in last place
JavaScript
mit
Mccoy123/sotonSquashAppCloudCode,Mccoy123/sotonSquashAppCloudCode
--- +++ @@ -2,5 +2,52 @@ // Use Parse.Cloud.define to define as many cloud functions as you want. // For example: Parse.Cloud.define("hello", function(request, response) { - response.success("Doms Cloud Code!"); +console.log("hello5"); +response.success("Doms Cloud Code"); }); + +//test function +Parse.Cloud.beforeSave("MatchScore", function(request, response) { + if (request.object.get("P10Score") > 3) { + response.error("Games are first to 3"); + //return response.error(JSON.stringify({code: ErrorCodes["450"], message: "Games are first to 3"})); + } else { + response.success(); + } +}); + +//User opt in/out of leaderboard + Parse.Cloud.define("joinLeaderboard", function(request, response) { + //set the leaderboard flag to true + var currentUser = Parse.User.current(); + currentUser.set("Leaderboard", true); + currentUser.save(); + var AddLeaderboard = Parse.Object.extend("LeaderBoard"); + + var AddLeaderboard = Parse.Object.extend("LeaderBoard"); + var query = new Parse.Query(AddLeaderboard); + query.notEqualTo("Ranking", 0); + query.count().then(function(count) { + //success + console.log(count); + return count; + }).then (function(count) { + var currentUser = Parse.User.current(); + var addLeaderboard = new AddLeaderboard(); + var newPlayerRanking = count + 1; + addLeaderboard.save({Ranking: newPlayerRanking, playerID: currentUser}, { + success: function(object) { + console.log("User added to the leaderboard55"); + response.success("Learderboard Joined!!") + }, + error: function(model, error) { + console.error("Error User could not be added to the leaderboard"); + } + }); + }, function(error) { + //error + console.log("error5"); + response.error("error5"); + }); + }); +
24cfc6510cf954c3181dd60f403ebb743ca6a7a1
src/server/test/timeIntervalTests.js
src/server/test/timeIntervalTests.js
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ const moment = require('moment'); const mocha = require('mocha'); const chai = require('chai'); const chaiAsPromised = require('chai-as-promised'); chai.use(chaiAsPromised); const expect = chai.expect; const { TimeInterval } = require('../../common/TimeInterval'); mocha.describe('Time Intervals', () => { mocha.it('can be created', async () => { const start = moment('1970-01-01 00:01:00'); const end = moment('2069-12-31 00:01:00'); const ti = new TimeInterval(start, end); expect(ti.toString()).to.equal('1970-01-01T06:01:00Z_2069-12-31T06:01:00Z'); }); });
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ const moment = require('moment'); const mocha = require('mocha'); const chai = require('chai'); const chaiAsPromised = require('chai-as-promised'); chai.use(chaiAsPromised); const expect = chai.expect; const { TimeInterval } = require('../../common/TimeInterval'); mocha.describe('Time Intervals', () => { mocha.it('can be created', async () => { const start = moment('1970-01-01T00:01:00Z'); const end = moment('2069-12-31T00:01:00Z'); const ti = new TimeInterval(start, end); expect(ti.toString()).to.equal('1970-01-01T00:01:00Z_2069-12-31T00:01:00Z'); }); });
Fix TimeInterval test by acknowledging time zones
Fix TimeInterval test by acknowledging time zones
JavaScript
mpl-2.0
OpenEnergyDashboard/OED,OpenEnergyDashboard/OED,OpenEnergyDashboard/OED,OpenEnergyDashboard/OED
--- +++ @@ -13,10 +13,10 @@ mocha.describe('Time Intervals', () => { mocha.it('can be created', async () => { - const start = moment('1970-01-01 00:01:00'); - const end = moment('2069-12-31 00:01:00'); + const start = moment('1970-01-01T00:01:00Z'); + const end = moment('2069-12-31T00:01:00Z'); const ti = new TimeInterval(start, end); - expect(ti.toString()).to.equal('1970-01-01T06:01:00Z_2069-12-31T06:01:00Z'); + expect(ti.toString()).to.equal('1970-01-01T00:01:00Z_2069-12-31T00:01:00Z'); }); });
7dd2cfca7e87cd1d2d84c9685e1dbf4ad4c5a8a5
packages/lingui-cli/src/lingui-add-locale.js
packages/lingui-cli/src/lingui-add-locale.js
const fs = require('fs') const path = require('path') const chalk = require('chalk') const program = require('commander') const getConfig = require('lingui-conf').default const plurals = require('make-plural') const config = getConfig() program.parse(process.argv) function validateLocales (locales) { const unknown = locales.filter(locale => !(locale in plurals)) if (unknown.length) { console.log(chalk.red(`Unknown locale(s): ${unknown.join(', ')}.`)) process.exit(1) } } function addLocale (locales) { if (!fs.existsSync(config.localeDir)) { fs.mkdirSync(config.localeDir) } locales.forEach(locale => { const localeDir = path.join(config.localeDir, locale) if (fs.existsSync(localeDir)) { console.log(chalk.yellow(`Locale ${chalk.underline(locale)} already exists.`)) } else { fs.mkdirSync(localeDir) console.log(chalk.green(`Added locale ${chalk.underline(locale)}.`)) } }) } validateLocales(program.args) addLocale(program.args) console.log() console.log(`(use "${chalk.yellow('lingui extract')}" to extract messages)`)
const fs = require('fs') const path = require('path') const chalk = require('chalk') const program = require('commander') const getConfig = require('lingui-conf').default const plurals = require('make-plural') const config = getConfig() function validateLocales (locales) { const unknown = locales.filter(locale => !(locale in plurals)) if (unknown.length) { console.log(chalk.red(`Unknown locale(s): ${unknown.join(', ')}.`)) process.exit(1) } } function addLocale (locales) { if (!fs.existsSync(config.localeDir)) { fs.mkdirSync(config.localeDir) } locales.forEach(locale => { const localeDir = path.join(config.localeDir, locale) if (fs.existsSync(localeDir)) { console.log(chalk.yellow(`Locale ${chalk.underline(locale)} already exists.`)) } else { fs.mkdirSync(localeDir) console.log(chalk.green(`Added locale ${chalk.underline(locale)}.`)) } }) } program .description('Add target locales. Remove locale by removing <locale> directory from your localeDir (e.g. ./locale)') .arguments('<locale...>') .on('--help', function () { console.log('\n Examples:\n') console.log(' # Add single locale') console.log(' $ lingui add-locale en') console.log('') console.log(' # Add multiple locales') console.log(' $ lingui add-locale en es fr ru') }) .parse(process.argv) if (!program.args.length) program.help() validateLocales(program.args) addLocale(program.args) console.log() console.log(`(use "${chalk.yellow('lingui extract')}" to extract messages)`)
Add help to add-locale command
fix: Add help to add-locale command
JavaScript
mit
lingui/js-lingui,lingui/js-lingui
--- +++ @@ -6,8 +6,6 @@ const plurals = require('make-plural') const config = getConfig() - -program.parse(process.argv) function validateLocales (locales) { const unknown = locales.filter(locale => !(locale in plurals)) @@ -34,8 +32,24 @@ }) } +program + .description('Add target locales. Remove locale by removing <locale> directory from your localeDir (e.g. ./locale)') + .arguments('<locale...>') + .on('--help', function () { + console.log('\n Examples:\n') + console.log(' # Add single locale') + console.log(' $ lingui add-locale en') + console.log('') + console.log(' # Add multiple locales') + console.log(' $ lingui add-locale en es fr ru') + }) + .parse(process.argv) + +if (!program.args.length) program.help() + validateLocales(program.args) addLocale(program.args) + console.log() console.log(`(use "${chalk.yellow('lingui extract')}" to extract messages)`)
ededc73fd74777d0d44b3d1613414fe3787a6c9f
lib/cartodb/middleware/allow-query-params.js
lib/cartodb/middleware/allow-query-params.js
module.exports = function allowQueryParams(params) { return function allowQueryParamsMiddleware(req, res, next) { req.context.allowedQueryParams = params; next(); }; };
module.exports = function allowQueryParams(params) { if (!Array.isArray(params)) { throw new Error('allowQueryParams must receive an Array of params'); } return function allowQueryParamsMiddleware(req, res, next) { req.context.allowedQueryParams = params; next(); }; };
Throw on invalid params argument
Throw on invalid params argument
JavaScript
bsd-3-clause
CartoDB/Windshaft-cartodb,CartoDB/Windshaft-cartodb,CartoDB/Windshaft-cartodb,CartoDB/Windshaft-cartodb
--- +++ @@ -1,4 +1,7 @@ module.exports = function allowQueryParams(params) { + if (!Array.isArray(params)) { + throw new Error('allowQueryParams must receive an Array of params'); + } return function allowQueryParamsMiddleware(req, res, next) { req.context.allowedQueryParams = params; next();
3fb83189ad65c6cd0ca13bf1e7ecfe41ca0eed8c
dev/amdDev.js
dev/amdDev.js
'use strict'; require.config({ paths: { raphael: '../raphael' //you will need eve if you use the nodeps version /*eve: '../bower_components/eve/eve'*/ } }); require(['raphael'], function(Raphael) { var paper = Raphael(0, 0, 640, 720, "container"); paper.circle(100, 100, 100); //example // Work here });
'use strict'; require.config({ paths: { raphael: '../raphael' //you will need eve if you use the nodeps version /*eve: '../bower_components/eve/eve'*/ } }); require(['raphael'], function(Raphael) { var paper = Raphael(0, 0, 640, 720, "container"); paper.circle(100, 100, 100).attr({'fill':'270-#FAE56B:0-#E56B6B:100'}); //example // Work here });
Add gradient to test page
Add gradient to test page
JavaScript
mit
DmitryBaranovskiy/raphael,DmitryBaranovskiy/raphael,danielgindi/raphael,danielgindi/raphael
--- +++ @@ -10,7 +10,7 @@ require(['raphael'], function(Raphael) { var paper = Raphael(0, 0, 640, 720, "container"); - paper.circle(100, 100, 100); //example + paper.circle(100, 100, 100).attr({'fill':'270-#FAE56B:0-#E56B6B:100'}); //example // Work here });
83cd7781120c105b8eeffe3b957d6a5a1b365cdf
app/assets/javascripts/vivus/application.js
app/assets/javascripts/vivus/application.js
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // // WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD // GO AFTER THE REQUIRES BELOW. // //= require jquery //= require highlight.pack //= require_tree . $(document).ready(function() { $('pre').each(function(i, el) { hljs.highlightBlock(el); }); $('code').each(function(i, el) { hljs.highlightBlock(el); }); $('.vivus-documentation h1').each(function(i, el) { $('#vivus-navigation ul').append("<li><a href='#" + i + "'>" + $(el).text() + "</a></li>"); $(el).prepend("<a name='" + i + "'></a>"); }) });
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // // WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD // GO AFTER THE REQUIRES BELOW. // //= require jquery //= require highlight.pack //= require_tree . $(document).ready(function() { $('pre').each(function(i, el) { hljs.highlightBlock(el); }); $('code').each(function(i, el) { hljs.highlightBlock(el); }); $('.vivus-documentation h1').each(function(i, el) { $('#vivus-navigation ul').append("<li><a href='#" + $(el).text().toLowerCase().replace(/ /g, '-') + "'>" + $(el).text() + "</a></li>"); $(el).prepend("<a name='" + $(el).text().toLowerCase().replace(/ /g, '-') + "'></a>"); }) });
Fix the navigation generating js
Fix the navigation generating js
JavaScript
mit
markcipolla/vivus,markcipolla/vivus,markcipolla/vivus
--- +++ @@ -24,7 +24,7 @@ }); $('.vivus-documentation h1').each(function(i, el) { - $('#vivus-navigation ul').append("<li><a href='#" + i + "'>" + $(el).text() + "</a></li>"); - $(el).prepend("<a name='" + i + "'></a>"); + $('#vivus-navigation ul').append("<li><a href='#" + $(el).text().toLowerCase().replace(/ /g, '-') + "'>" + $(el).text() + "</a></li>"); + $(el).prepend("<a name='" + $(el).text().toLowerCase().replace(/ /g, '-') + "'></a>"); }) });
869da6419922b8b827cafbafebaf45b35af785e4
runner/test.js
runner/test.js
/** * @license * Copyright (c) 2014 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt * Code distributed by Google as part of the polymer project is also * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */ var _ = require('lodash'); var events = require('events'); var CleanKill = require('./cleankill'); var CliReporter = require('./clireporter'); var config = require('./config'); var steps = require('./steps'); module.exports = function test(options, done) { options = _.merge(config.defaults(), options); var emitter = new events.EventEmitter(); new CliReporter(emitter, options.output, options); // Add plugin reporters _.values(options.plugins).forEach(function(plugin) { if (plugin.reporter) { new plugin.reporter(emitter, options.output, plugin); } }); var cleanOptions = _.omit(options, 'output'); emitter.emit('log:debug', 'Configuration:', cleanOptions); steps.runTests(options, emitter, function(error) { CleanKill.close(done.bind(null, error)); }); return emitter; };
/** * @license * Copyright (c) 2014 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt * Code distributed by Google as part of the polymer project is also * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */ var _ = require('lodash'); var events = require('events'); var CleanKill = require('./cleankill'); var CliReporter = require('./clireporter'); var config = require('./config'); var steps = require('./steps'); module.exports = function test(options, done) { options = _.merge(config.defaults(), options); var emitter = new events.EventEmitter(); new CliReporter(emitter, options.output, options); // Add plugin event listeners _.values(options.plugins).forEach(function(plugin) { if (plugin.listener) { new plugin.listener(emitter, options.output, plugin); } }); var cleanOptions = _.omit(options, 'output'); emitter.emit('log:debug', 'Configuration:', cleanOptions); steps.runTests(options, emitter, function(error) { CleanKill.close(done.bind(null, error)); }); return emitter; };
Rename 'reporter' plugin hook to 'listener' as it's more semantic
Rename 'reporter' plugin hook to 'listener' as it's more semantic
JavaScript
bsd-3-clause
Polymer/web-component-tester,sankethkatta/web-component-tester,hvdb/web-component-tester,GabrielDuque/web-component-tester,hypnoce/web-component-tester,sankethkatta/web-component-tester,robdodson/web-component-tester,marcinkubicki/web-component-tester,hvdb/web-component-tester,Polymer/tools,rasata/web-component-tester,Polymer/tools,marcinkubicki/web-component-tester,marcinkubicki/web-component-tester,jimsimon/web-component-tester,Polymer/tools,fearphage/web-component-tester,GabrielDuque/web-component-tester,robdodson/web-component-tester,apowers313/web-component-tester,wibblymat/web-component-tester,jimsimon/web-component-tester,Polymer/web-component-tester,rasata/web-component-tester,hvdb/web-component-tester,sankethkatta/web-component-tester,apowers313/web-component-tester,fluxio/web-component-tester,fearphage/web-component-tester,fearphage/web-component-tester,hypnoce/web-component-tester,Polymer/web-component-tester,wibblymat/web-component-tester,Polymer/tools,fluxio/web-component-tester
--- +++ @@ -21,10 +21,10 @@ new CliReporter(emitter, options.output, options); - // Add plugin reporters + // Add plugin event listeners _.values(options.plugins).forEach(function(plugin) { - if (plugin.reporter) { - new plugin.reporter(emitter, options.output, plugin); + if (plugin.listener) { + new plugin.listener(emitter, options.output, plugin); } });
7c326ab8b6cadbc12e01c98c5e0789cb12dc5969
src/AppRouter.js
src/AppRouter.js
import React from 'react'; import { Router, Route, hashHistory, IndexRoute } from 'react-router'; import App from './App'; import RecentTracks from './components/RecentTracks'; import TopArtists from './components/TopArtists'; let AppRouter = React.createClass ({ render() { return ( <Router history={hashHistory}> <Route path="/" component={App}> <IndexRoute component={RecentTracks}/> <Route path="/recent-tracks" component={RecentTracks} /> <Route path="/top-artists" component={TopArtists} /> </Route> </Router> ); } }); export default AppRouter;
import React from 'react'; import { Router, Route, browserHistory, IndexRoute } from 'react-router'; import App from './App'; import RecentTracks from './components/RecentTracks'; import TopArtists from './components/TopArtists'; let AppRouter = React.createClass ({ render() { return ( <Router history={browserHistory}> <Route path="/" component={App}> <IndexRoute component={RecentTracks}/> <Route path="/recent-tracks" component={RecentTracks} /> <Route path="/top-artists" component={TopArtists} /> </Route> </Router> ); } }); export default AppRouter;
Use browserHistory to get rid of url queries
Use browserHistory to get rid of url queries
JavaScript
bsd-3-clause
jeromelachaud/Last.fm-Activities-React,jeromelachaud/Last.fm-Activities-React
--- +++ @@ -2,7 +2,7 @@ import { Router, Route, - hashHistory, + browserHistory, IndexRoute } from 'react-router'; import App from './App'; @@ -13,7 +13,7 @@ render() { return ( - <Router history={hashHistory}> + <Router history={browserHistory}> <Route path="/" component={App}> <IndexRoute component={RecentTracks}/> <Route path="/recent-tracks" component={RecentTracks} />
fa588af379d1f779ed501048e132b33241428bc6
app/components/quantity-widget-component.js
app/components/quantity-widget-component.js
var DEFAULT_MIN = 1; var DEFAULT_MAX = 3; App.QuantityWidgetComponent = Ember.Component.extend({ tagName: 'div', classNameBindings: [ ':quantity-widget', 'isMin', 'isMax' ], attributeBindings: [ 'name:data-icon' ], actions: { increment: function () { if (this.get('isMax')) return; this.set('quantity', this.incrementProperty('quantity') ); }, decrement: function () { if (this.get('isMin')) return; this.set('quantity', this.decrementProperty('quantity') ); } }, quantity: DEFAULT_MIN, // pass in your own to override. max: DEFAULT_MAX, min: DEFAULT_MIN, isMin: function () { return this.get('quantity') === this.get('min'); }.property('quantity'), isMax: function () { return this.get('quantity') >= this.get('max'); }.property('quantity') });
var DEFAULT_MIN = 1; var DEFAULT_MAX = 3; App.QuantityWidgetComponent = Ember.Component.extend({ tagName: 'div', classNameBindings: [ ':quantity-widget', 'isMin', 'isMax' ], attributeBindings: [ 'name:data-icon' ], actions: { increment: function () { if (this.get('isMax')) return; this.set('quantity', this.incrementProperty('quantity') ); }, decrement: function () { if (this.get('isMin')) return; this.set('quantity', this.decrementProperty('quantity') ); } }, quantity: DEFAULT_MIN, // pass in your own to override. max: DEFAULT_MAX, min: DEFAULT_MIN, isMin: function () { return this.get('quantity') === this.get('min'); }.property('quantity'), isMax: function () { return this.get('quantity') >= this.get('max'); }.property('quantity'), maxTooltip: function () { return '%@ is the maximum quantity.'.fmt(this.get('max')); }.property('max') });
Update quantity widget tooltips per prototype
Update quantity widget tooltips per prototype
JavaScript
mit
dollarshaveclub/ember-uni-form,dollarshaveclub/ember-uni-form
--- +++ @@ -30,6 +30,9 @@ isMax: function () { return this.get('quantity') >= this.get('max'); - }.property('quantity') + }.property('quantity'), + maxTooltip: function () { + return '%@ is the maximum quantity.'.fmt(this.get('max')); + }.property('max') });
84997448d9c3b932c5d7349eea6d6de3877b9bfa
.storybook/preview.js
.storybook/preview.js
import { addParameters, addDecorator, setCustomElements, withA11y } from '@open-wc/demoing-storybook'; async function run() { const customElements = await ( await fetch(new URL('../custom-elements.json', import.meta.url)) ).json(); setCustomElements(customElements); addDecorator(withA11y); addParameters({ a11y: { config: {}, options: { checks: { 'color-contrast': { options: { noScroll: true } } }, restoreScroll: true } }, docs: { iframeHeight: '200px' } }); } run();
import { addParameters, addDecorator, setCustomElements, withA11y, } from '@open-wc/demoing-storybook'; async function run() { const customElements = await ( await fetch(new URL('../custom-elements.json', import.meta.url)) ).json(); setCustomElements(customElements); addDecorator(withA11y); addParameters({ a11y: { config: {}, options: { checks: { 'color-contrast': { options: { noScroll: true } } }, restoreScroll: true, }, }, docs: { iframeHeight: '200px', }, }); } run();
Fix linting errors in generated code
[style] Fix linting errors in generated code
JavaScript
mit
rpatterson/nOrg,rpatterson/nOrg
--- +++ @@ -2,7 +2,7 @@ addParameters, addDecorator, setCustomElements, - withA11y + withA11y, } from '@open-wc/demoing-storybook'; async function run() { @@ -18,12 +18,12 @@ config: {}, options: { checks: { 'color-contrast': { options: { noScroll: true } } }, - restoreScroll: true - } + restoreScroll: true, + }, }, docs: { - iframeHeight: '200px' - } + iframeHeight: '200px', + }, }); }
ffc9c2475174ea4d87c7f389f77631f2c7cd9a35
app/javascript/app/reducers/auth-reducer.js
app/javascript/app/reducers/auth-reducer.js
import { AUTH_USER, UNAUTH_USER, AUTH_ERROR, SET_USER_DATA, SET_CREDIT_CARDS, SET_DEFAULT_CARD } from '../constants/'; const initialState = { authenticated: false, errors: null, user: null, creditCardDefault: null, creditCards: null }; const AuthReducer = (state=initialState, action) => { switch (action.type) { case AUTH_USER: return { ...state, authenticated: true, errors: [] }; case UNAUTH_USER: return { ...state, user: null, authenticated: false, errors: [] } case AUTH_ERROR: return { ...state, errors: action.payload }; case SET_USER_DATA: return { ...state, user: action.payload, errors: [] }; case SET_CREDIT_CARDS: return { ...state, creditCards: action.payload }; case SET_DEFAULT_CARD: return { ...state, creditCardDefault: action.payload } default: return state; } } export default AuthReducer;
import { AUTH_USER, UNAUTH_USER, AUTH_ERROR, SET_USER_DATA, SET_CREDIT_CARDS, SET_DEFAULT_CARD, ADD_CREDIT_CARD } from '../constants/'; const initialState = { authenticated: false, errors: null, user: null, creditCardDefault: null, creditCards: null }; const AuthReducer = (state=initialState, action) => { switch (action.type) { case AUTH_USER: return { ...state, authenticated: true, errors: [] }; case UNAUTH_USER: return { ...state, user: null, authenticated: false, errors: [] } case AUTH_ERROR: return { ...state, errors: action.payload }; case SET_USER_DATA: return { ...state, user: action.payload, errors: [] }; case SET_CREDIT_CARDS: return { ...state, creditCards: action.payload }; case SET_DEFAULT_CARD: return { ...state, creditCardDefault: action.payload } case ADD_CREDIT_CARD: return { ...state, creditCards: [ ...state.creditCards, action.payload ] }; default: return state; } } export default AuthReducer;
Refactor auth reducer to handler the new auth-card actions
Refactor auth reducer to handler the new auth-card actions
JavaScript
mit
GiancarlosIO/ecommerce-book-app,GiancarlosIO/ecommerce-book-app,GiancarlosIO/ecommerce-book-app
--- +++ @@ -4,7 +4,8 @@ AUTH_ERROR, SET_USER_DATA, SET_CREDIT_CARDS, - SET_DEFAULT_CARD + SET_DEFAULT_CARD, + ADD_CREDIT_CARD } from '../constants/'; const initialState = { @@ -51,6 +52,14 @@ ...state, creditCardDefault: action.payload } + case ADD_CREDIT_CARD: + return { + ...state, + creditCards: [ + ...state.creditCards, + action.payload + ] + }; default: return state; }
dd9345272923cc723eede78af5fb61797237df13
lib/buster-util.js
lib/buster-util.js
if (typeof buster == "undefined") { var buster = {}; } buster.util = (function () { var toString = Object.prototype.toString; var div = typeof document != "undefined" && document.createElement("div"); return { isNode: function (obj) { if (!div) { return false; } try { div.appendChild(obj); div.removeChild(obj); } catch (e) { return false; } return true; }, isElement: function (obj) { return obj && this.isNode(obj) && obj.nodeType === 1; }, isArguments: function (obj) { if (typeof obj != "object" || typeof obj.length != "number" || toString.call(obj) == "[object Array]") { return false; } if (typeof obj.callee == "function") { return true; } try { obj[obj.length] = 6; delete obj[obj.length]; } catch (e) { return true; } return false; }, keys: Object.keys || function (object) { var keys = []; for (var prop in object) { if (Object.prototype.hasOwnProperty.call(object, prop)) { keys.push(prop); } } return keys; } }; }()); if (typeof module != "undefined") { module.exports = buster.util; }
if (typeof buster == "undefined") { var buster = {}; } buster.util = (function () { var toString = Object.prototype.toString; var div = typeof document != "undefined" && document.createElement("div"); return { isNode: function (obj) { if (!div) { return false; } try { div.appendChild(obj); div.removeChild(obj); } catch (e) { return false; } return true; }, isElement: function (obj) { return obj && this.isNode(obj) && obj.nodeType === 1; }, isArguments: function (obj) { if (typeof obj != "object" || typeof obj.length != "number" || toString.call(obj) == "[object Array]") { return false; } if (typeof obj.callee == "function") { return true; } try { obj[obj.length] = 6; delete obj[obj.length]; } catch (e) { return true; } return false; }, keys: function (object) { var keys = []; for (var prop in object) { if (Object.prototype.hasOwnProperty.call(object, prop)) { keys.push(prop); } } return keys; } }; }()); if (typeof module != "undefined") { module.exports = buster.util; }
Fix keys implementation - Object.keys does not work on functions
Fix keys implementation - Object.keys does not work on functions
JavaScript
bsd-3-clause
geddski/buster-core,busterjs/buster-core,busterjs/buster-core
--- +++ @@ -46,7 +46,7 @@ return false; }, - keys: Object.keys || function (object) { + keys: function (object) { var keys = []; for (var prop in object) {
72d231edb93d2a9bf6ead440c9b46d6b35d70717
seequmber/testResults/testResults.js
seequmber/testResults/testResults.js
'use strict'; function TestResults(dataTable) { var Cucumber = require('cucumber'); var TestResult = require('./testResult'); var maximums = [0, 0, 0, 0]; var testCollection = Cucumber.Type.Collection(); (function rowToTestResult() { dataTable.getRows().syncForEach(function(row) { var testResult = new TestResult(row.raw()[0], row.raw()[1], row.raw()[2], row.raw()[3]); testCollection.add(testResult); row.raw().forEach(function(element, index) { if (maximums[index] < element.length) { maximums[index] = element.length; } }); }); })(); var self = { getTestResults: function getTestResults() { var newTests = Cucumber.Type.Collection(); testCollection.syncForEach(function(test) { newTests.add(test); }); return newTests; }, attachTest: function attachTest(test) { testCollection.add(test); }, getMaximums: function getMaximums() { return maximums; }, raw: function raw() { var rawTests = []; testCollection.syncForEach(function(test) { rawTests.push(test.raw()); }); return rawTests; } }; return self; } module.exports = TestResults;
'use strict'; function TestResults(dataTable) { var Cucumber = require('cucumber'); var TestResult = require('./testResult'); var maximums = [0, 0, 0, 0]; var testCollection = Cucumber.Type.Collection(); (function rowToTestResult() { var rows = dataTable.getRows(); rows = rows.sort(function(a, b) { return (a.raw()[1]) < (b.raw()[1]); }); rows.syncForEach(function(row) { var testResult = new TestResult(row.raw()[0], row.raw()[1], row.raw()[2], row.raw()[3]); testCollection.add(testResult); row.raw().forEach(function(element, index) { if (maximums[index] < element.length) { maximums[index] = element.length; } }); }); })(); var self = { getTestResults: function getTestResults() { var newTests = Cucumber.Type.Collection(); testCollection.syncForEach(function(test) { newTests.add(test); }); return newTests; }, attachTest: function attachTest(test) { testCollection.add(test); }, getMaximums: function getMaximums() { return maximums; }, raw: function raw() { var rawTests = []; testCollection.syncForEach(function(test) { rawTests.push(test.raw()); }); return rawTests; } }; return self; } module.exports = TestResults;
Sort test results according to version
Sort test results according to version
JavaScript
mit
seeq12/seequcumber,seeq12/seequcumber,seeq12/seequcumber
--- +++ @@ -8,7 +8,12 @@ var testCollection = Cucumber.Type.Collection(); (function rowToTestResult() { - dataTable.getRows().syncForEach(function(row) { + var rows = dataTable.getRows(); + rows = rows.sort(function(a, b) { + return (a.raw()[1]) < (b.raw()[1]); + }); + + rows.syncForEach(function(row) { var testResult = new TestResult(row.raw()[0], row.raw()[1], row.raw()[2], row.raw()[3]); testCollection.add(testResult); row.raw().forEach(function(element, index) {
eff1b5b49924d1313470a645d00a2d5ddab2c735
ember_modules/routes/tasks.js
ember_modules/routes/tasks.js
var route = Ember.Route.extend({ model: function() { return this.store.all('task'); }, afterModel: function(tasks, transition) { if (transition.targetName == "tasks.index") { if($(document).width() > 700) { Ember.run.next(this, function(){ var task = this.controllerFor('tasks') .get('pendingTasks.firstObject'); if(task) { this.transitionTo('task', tasks.get('firstObject')); } }) } else { this.transitionToRoute('mobileTasks'); } } }, actions: { error: function(reason, tsn) { var application = this.controllerFor('application'); application.get('handleError').bind(application)(reason, tsn); } } }); module.exports = route;
var route = Ember.Route.extend({ model: function() { return this.store.all('task'); }, afterModel: function(tasks, transition) { if (transition.targetName == "tasks.index" || transition.targetName == "tasks") { if($(document).width() > 700) { Ember.run.next(this, function(){ var task = this.controllerFor('tasks') .get('pendingTasks.firstObject'); if(task) { this.transitionTo('task', tasks.get('firstObject')); } }) } else { this.transitionToRoute('mobileTasks'); } } }, actions: { error: function(reason, tsn) { var application = this.controllerFor('application'); application.get('handleError').bind(application)(reason, tsn); } } }); module.exports = route;
Check for multiple target routes for deciding when to transition.
Check for multiple target routes for deciding when to transition.
JavaScript
agpl-3.0
coddingtonbear/inthe.am,coddingtonbear/inthe.am,coddingtonbear/inthe.am,coddingtonbear/inthe.am,coddingtonbear/inthe.am
--- +++ @@ -3,7 +3,7 @@ return this.store.all('task'); }, afterModel: function(tasks, transition) { - if (transition.targetName == "tasks.index") { + if (transition.targetName == "tasks.index" || transition.targetName == "tasks") { if($(document).width() > 700) { Ember.run.next(this, function(){ var task = this.controllerFor('tasks')
14eaff77c0293e55005a30ae64b4bffeb16c9ce3
src/client/components/Text.js
src/client/components/Text.js
import React from 'react' import _ from 'lodash' import fp from 'lodash/fp' export default props => { const { children: text } = props const linkPattern = /([a-z]+:\/\/[^,\s]+)/g const parts = fp.filter(s => s !== '')(text.split(linkPattern)) const textNodes = _.map(parts, (part, i) => { if (linkPattern.test(part)) { return <a key={i} href={part} target='_blank'>{part}</a> } else { return <span key={i}>{part}</span> } }) return <span>{textNodes}</span> }
import React from 'react' import _ from 'lodash' import fp from 'lodash/fp' export default props => { const { children: text } = props // Anything starting with one or more word characters followed by :// is considered a link. const linkPattern = /(\w+:\/\/\S+)/g const parts = fp.filter(s => s !== '')(text.split(linkPattern)) const textNodes = _.map(parts, (part, i) => { if (linkPattern.test(part)) { return <a key={i} href={part} target='_blank'>{part}</a> } else { return <span key={i}>{part}</span> } }) return <span>{textNodes}</span> }
Simplify regex for finding links
Simplify regex for finding links
JavaScript
mit
daGrevis/msks,daGrevis/msks,daGrevis/msks
--- +++ @@ -5,7 +5,8 @@ export default props => { const { children: text } = props - const linkPattern = /([a-z]+:\/\/[^,\s]+)/g + // Anything starting with one or more word characters followed by :// is considered a link. + const linkPattern = /(\w+:\/\/\S+)/g const parts = fp.filter(s => s !== '')(text.split(linkPattern))
7893445133fc85c7305ffba75a34936624bf3ca5
addon/components/object-list-view-input-cell.js
addon/components/object-list-view-input-cell.js
import BaseComponent from './flexberry-base'; export default BaseComponent.extend({ tagName: 'td', classNames: [], column: null, record: null });
import BaseComponent from './flexberry-base'; export default BaseComponent.extend({ tagName: 'td', classNames: [], column: null, record: null, didInsertElement: function() { var _this = this; this.$('input').change(function() { _this.record.set(_this.column.propName, _this.$(this).val()); }); } });
Add support of two way binding
Add support of two way binding in object-list-view-input-cell component
JavaScript
mit
Flexberry/ember-flexberry,Flexberry/ember-flexberry,Flexberry/ember-flexberry,Flexberry/ember-flexberry
--- +++ @@ -4,5 +4,12 @@ tagName: 'td', classNames: [], column: null, - record: null + record: null, + + didInsertElement: function() { + var _this = this; + this.$('input').change(function() { + _this.record.set(_this.column.propName, _this.$(this).val()); + }); + } });
b6bb30f5d90885b60c1406ccf211511dbb347a80
src/decoding/createDataStream.js
src/decoding/createDataStream.js
import dissolve from 'dissolve' function createDataStream() { return dissolve() .loop(function() { this .uint32("length") .int8("type") .tap(function() { if (this.vars.length) { this.buffer("data", this.vars.length); } }) .tap(function() { this.push(this.vars); this.vars = {}; }); }); }
import dissolve from 'dissolve' function createDataStream() { return dissolve() .loop(function() { this .uint32("length") .int8("type") .tap(function() { if (this.vars.length) { this.buffer("payload", this.vars.length); } }) .tap(function() { this.push(this.vars); this.vars = {}; }); }); }
Modify binary payload to be called payload instead of data
Modify binary payload to be called payload instead of data
JavaScript
apache-2.0
RobCoIndustries/pipboylib
--- +++ @@ -8,7 +8,7 @@ .int8("type") .tap(function() { if (this.vars.length) { - this.buffer("data", this.vars.length); + this.buffer("payload", this.vars.length); } }) .tap(function() {
a4311dc96f20b7f13275df7828c7c5a4b7b8dc52
config.js
config.js
export default { authToken: process.env.AUTH_TOKEN || 'secret', env: process.env.NODE_ENV, host: process.env.HOST || 'localhost', github: { apiUrl: 'https://api.github.com', username: process.env.GITHUB_USERNAME || 'username' }, mongo: { url: process.env.MONGO_URL || 'mongodb://localhost:27017/FranVarney' }, port: process.env.PORT || 8000 }
export default { authToken: process.env.AUTH_TOKEN || 'secret', env: process.env.NODE_ENV, host: process.env.HOST || 'localhost', github: { apiUrl: 'https://api.github.com', username: process.env.GITHUB_USERNAME || 'username' }, jobs: { frequency: { githubActivity: process.env.JOBS_FREQUENCY_GITHUB || '00 */1 * * * *' // '00 00 03 * * *' } }, mongo: { url: process.env.MONGO_URL || 'mongodb://localhost:27017/FranVarney' }, port: process.env.PORT || 8000 }
Add github activity job frequency option
Add github activity job frequency option
JavaScript
mit
franvarney/franvarney-api
--- +++ @@ -6,6 +6,11 @@ apiUrl: 'https://api.github.com', username: process.env.GITHUB_USERNAME || 'username' }, + jobs: { + frequency: { + githubActivity: process.env.JOBS_FREQUENCY_GITHUB || '00 */1 * * * *' // '00 00 03 * * *' + } + }, mongo: { url: process.env.MONGO_URL || 'mongodb://localhost:27017/FranVarney' },
c0a49738fbd196f8f79fda0d265268b3fc8b095d
src/frontend/html-renderer.js
src/frontend/html-renderer.js
import React from 'react'; import renderHTML from 'react-render-html'; import SocketClient from './socket-client'; import PropTypes from 'prop-types'; class HTMLRenderer extends React.Component { constructor(props) { super(props); this.state = { html: '' }; } componentDidMount() { this.socketClient = new SocketClient(this.props.location); this.socketClient.onData(html => this.setState({ html })); } componentDidUpdate() { if (this.props.onUpdate) { this.props.onUpdate(); } } render() { return React.createElement('div', null, renderHTML(this.state.html)); } } HTMLRenderer.propTypes = { location: PropTypes.shape({ host: PropTypes.string.isRequired, pathname: PropTypes.string.isRequired, }).isRequired, onUpdate: PropTypes.func, }; export default HTMLRenderer;
import React from 'react'; import renderHTML from 'react-render-html'; import SocketClient from './socket-client'; import PropTypes from 'prop-types'; class HTMLRenderer extends React.Component { constructor(props) { super(props); this.state = { html: '' }; } componentDidMount() { this.socketClient = new SocketClient(this.props.location); this.socketClient.onData(html => this.setState({ html })); } componentDidUpdate() { if (this.props.onUpdate) { this.props.onUpdate(); } } render() { return React.createElement('div', null, renderHTML(this.state.html)); } } HTMLRenderer.propTypes = { location: PropTypes.shape({ host: PropTypes.string.isRequired, pathname: PropTypes.string.isRequired, }).isRequired, onUpdate: PropTypes.func, }; export default HTMLRenderer;
Add line breaks between methods in HTMLRenderer
Add line breaks between methods in HTMLRenderer
JavaScript
mit
noraesae/pen
--- +++ @@ -8,15 +8,18 @@ super(props); this.state = { html: '' }; } + componentDidMount() { this.socketClient = new SocketClient(this.props.location); this.socketClient.onData(html => this.setState({ html })); } + componentDidUpdate() { if (this.props.onUpdate) { this.props.onUpdate(); } } + render() { return React.createElement('div', null, renderHTML(this.state.html)); }
d2cab051760db8de79c6b59b3e67f28b11fe6c35
src/js/View.js
src/js/View.js
import '@webcomponents/webcomponentsjs'; class View extends HTMLElement { static wrapped() { const Cls = document.registerElement(this.name, this); return (params) => Object.assign(new Cls(), params); } createdCallback() { if (!this.constructor.html) { return; } const template = new DOMParser().parseFromString(this.constructor.html, 'text/html'); const content = document.importNode(template.head.firstChild.content, true); this.appendChild(content); } } export default View;
import '@webcomponents/webcomponentsjs'; class View extends HTMLElement { static wrapped() { customElements.define(this.name, this); return (params) => Object.assign(new this(), params); } constructor() { super(); if (!this.constructor.html) { return; } const template = new DOMParser().parseFromString(this.constructor.html, 'text/html'); const content = document.importNode(template.head.firstChild.content, true); this.appendChild(content); } } export default View;
Update to proper customElements spec
Update to proper customElements spec
JavaScript
mit
HiFiSamurai/ui-toolkit,HiFiSamurai/ui-toolkit
--- +++ @@ -2,11 +2,13 @@ class View extends HTMLElement { static wrapped() { - const Cls = document.registerElement(this.name, this); - return (params) => Object.assign(new Cls(), params); + customElements.define(this.name, this); + return (params) => Object.assign(new this(), params); } - createdCallback() { + constructor() { + super(); + if (!this.constructor.html) { return; }
1174726f0e8d814afcd751b162e9d8b5cb1c8235
examples/filebrowser/webpack.conf.js
examples/filebrowser/webpack.conf.js
var ContextReplacementPlugin = require("webpack/lib/ContextReplacementPlugin"); module.exports = { entry: './build/index.js', output: { path: './build', filename: 'bundle.js' }, node: { fs: "empty" }, bail: true, debug: true, module: { loaders: [ { test: /\.css$/, loader: 'style-loader!css-loader' }, ] }, plugins: [ new ContextReplacementPlugin( /codemirror\/mode.*$/, /codemirror\/mode.*\.js$/ ) ] }
var ContextReplacementPlugin = require("webpack/lib/ContextReplacementPlugin"); module.exports = { entry: './build/index.js', output: { path: './build', filename: 'bundle.js' }, node: { fs: "empty" }, bail: true, debug: true, module: { loaders: [ { test: /\.css$/, loader: 'style-loader!css-loader' }, { test: /\.html$/, loader: "file?name=[name].[ext]" } ] } }
Fix the codemirror bundle handling
Fix the codemirror bundle handling
JavaScript
bsd-3-clause
eskirk/jupyterlab,TypeFox/jupyterlab,TypeFox/jupyterlab,eskirk/jupyterlab,jupyter/jupyterlab,charnpreetsingh185/jupyterlab,TypeFox/jupyterlab,charnpreetsingh185/jupyterlab,charnpreetsingh185/jupyterlab,charnpreetsingh185/jupyterlab,eskirk/jupyterlab,eskirk/jupyterlab,jupyter/jupyter-js-ui,jupyter/jupyter-js-ui,TypeFox/jupyterlab,TypeFox/jupyterlab,jupyter/jupyterlab,eskirk/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,charnpreetsingh185/jupyterlab,jupyter/jupyter-js-ui
--- +++ @@ -15,12 +15,7 @@ module: { loaders: [ { test: /\.css$/, loader: 'style-loader!css-loader' }, + { test: /\.html$/, loader: "file?name=[name].[ext]" } ] - }, - plugins: [ - new ContextReplacementPlugin( - /codemirror\/mode.*$/, - /codemirror\/mode.*\.js$/ - ) - ] + } }
37fb836e41d16631cef9a10321de1a578a92904d
src/constants/controlTypes.js
src/constants/controlTypes.js
// @flow import { RGB_NEAREST, RGB_APPROX, LAB_NEAREST } from "constants/color"; export const BOOL = "BOOL"; export const ENUM = "ENUM"; export const RANGE = "RANGE"; export const STRING = "STRING"; export const PALETTE = "PALETTE"; export const COLOR_ARRAY = "COLOR_ARRAY"; export const COLOR_DISTANCE_ALGORITHM = { type: ENUM, options: [ { name: "RGB", value: RGB_NEAREST }, { name: "RGB (perceptual approx.)", value: RGB_APPROX }, { name: "Lab", value: LAB_NEAREST } ], default: LAB_NEAREST };
// @flow import { RGB_NEAREST, RGB_APPROX, LAB_NEAREST } from "constants/color"; export const BOOL = "BOOL"; export const ENUM = "ENUM"; export const RANGE = "RANGE"; export const STRING = "STRING"; export const PALETTE = "PALETTE"; export const COLOR_ARRAY = "COLOR_ARRAY"; export const COLOR_DISTANCE_ALGORITHM = { type: ENUM, options: [ { name: "RGB", value: RGB_NEAREST }, { name: "RGB (perceptual approx.)", value: RGB_APPROX }, { name: "Lab", value: LAB_NEAREST } ], default: RGB_APPROX };
Switch default color distance algorithm for user to RGB_APPROX
Switch default color distance algorithm for user to RGB_APPROX LAB_NEAREST can be really slow
JavaScript
mit
gyng/ditherer,gyng/ditherer,gyng/ditherer
--- +++ @@ -16,5 +16,5 @@ { name: "RGB (perceptual approx.)", value: RGB_APPROX }, { name: "Lab", value: LAB_NEAREST } ], - default: LAB_NEAREST + default: RGB_APPROX };
8dc281e7ddd4ec10f499cf19bb5743ebfa951179
app/components/participant-checkbox.js
app/components/participant-checkbox.js
import Ember from 'ember'; import { task } from 'ember-concurrency'; export default Ember.Component.extend({ store: Ember.inject.service(), flashMessages: Ember.inject.service(), isDisabled: false, isSelected: Ember.computed( 'member', 'participants.@each.member', function(){ let mapped = this.get('participants').mapBy('member.id'); if (mapped.includes(this.get('member.id'))) { return true; } else { return false; } }), toggleParticipant: task(function* (property, value){ if (value) { let newParticipant = this.get('store').createRecord('participant', { member: this.get('member'), entry: this.get('model'), }); try { yield newParticipant.save(); this.get('flashMessages').success("Saved"); } catch(e) { e.errors.forEach((error) => { this.get('flashMessages').danger(error.detail); }); newParticipant.deleteRecord(); } } else { let participant = this.get('model.participants').findBy('contest.id', this.get('contest.id')); if (participant) { try { yield participant.destroyRecord(); this.get('flashMessages').success("Saved"); } catch(e) { e.errors.forEach((error) => { this.get('flashMessages').danger(error.detail); }); } } } }).restartable(), });
import Ember from 'ember'; import { task } from 'ember-concurrency'; export default Ember.Component.extend({ store: Ember.inject.service(), flashMessages: Ember.inject.service(), isDisabled: false, isSelected: Ember.computed( 'member', 'participants.@each.member', function(){ let mapped = this.get('participants').mapBy('member.id'); if (mapped.includes(this.get('member.id'))) { return true; } else { return false; } }), toggleParticipant: task(function* (property, value){ if (value) { let newParticipant = this.get('store').createRecord('participant', { member: this.get('member'), entry: this.get('model'), }); try { yield newParticipant.save(); this.get('flashMessages').success("Saved"); } catch(e) { e.errors.forEach((error) => { this.get('flashMessages').danger(error.detail); }); newParticipant.deleteRecord(); } } else { let participant = this.get('model.participants').findBy('member.id', this.get('member.id')); if (participant) { try { yield participant.destroyRecord(); this.get('flashMessages').success("Saved"); } catch(e) { e.errors.forEach((error) => { this.get('flashMessages').danger(error.detail); }); } } } }).restartable(), });
Fix double-no clicking on participants
Fix double-no clicking on participants
JavaScript
bsd-2-clause
barberscore/barberscore-web,barberscore/barberscore-web,barberscore/barberscore-web
--- +++ @@ -32,7 +32,7 @@ newParticipant.deleteRecord(); } } else { - let participant = this.get('model.participants').findBy('contest.id', this.get('contest.id')); + let participant = this.get('model.participants').findBy('member.id', this.get('member.id')); if (participant) { try { yield participant.destroyRecord();
c3943b7962770cf4e3379fa29eb6dcf9958d0297
src/js/events/MarathonActions.js
src/js/events/MarathonActions.js
import ActionTypes from '../constants/ActionTypes'; var AppDispatcher = require('./AppDispatcher'); var Config = require('../config/Config'); var RequestUtil = require('../utils/RequestUtil'); module.exports = { fetchApps: RequestUtil.debounceOnError( Config.getRefreshRate(), function (resolve, reject) { return function () { var url = Config.rootUrl + '/marathon/v2/apps'; RequestUtil.json({ url: url, success: function (response) { AppDispatcher.handleServerAction({ type: ActionTypes.REQUEST_MARATHON_APPS_SUCCESS, data: response }); resolve(); }, error: function (e) { AppDispatcher.handleServerAction({ type: ActionTypes.REQUEST_MARATHON_APPS_ERROR, data: e.message }); reject(); }, hangingRequestCallback: function () { AppDispatcher.handleServerAction({ type: ActionTypes.REQUEST_MARATHON_APPS_ONGOING }); } }); }; }, {delayAfterCount: Config.delayAfterErrorCount} ) };
import ActionTypes from '../constants/ActionTypes'; var AppDispatcher = require('./AppDispatcher'); var Config = require('../config/Config'); var RequestUtil = require('../utils/RequestUtil'); module.exports = { fetchApps: RequestUtil.debounceOnError( Config.getRefreshRate(), function (resolve, reject) { return function () { const embed = 'embed=group.groups&embed=group.apps&' + 'embed=group.apps.deployments&embed=group.apps.counts'; let url = `${Config.rootUrl}/marathon/v2/groups?${embed}`; RequestUtil.json({ url: url, success: function (response) { AppDispatcher.handleServerAction({ type: ActionTypes.REQUEST_MARATHON_APPS_SUCCESS, data: response }); resolve(); }, error: function (e) { AppDispatcher.handleServerAction({ type: ActionTypes.REQUEST_MARATHON_APPS_ERROR, data: e.message }); reject(); }, hangingRequestCallback: function () { AppDispatcher.handleServerAction({ type: ActionTypes.REQUEST_MARATHON_APPS_ONGOING }); } }); }; }, {delayAfterCount: Config.delayAfterErrorCount} ) };
Change marathon endpoint to groups
Change marathon endpoint to groups
JavaScript
apache-2.0
dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui
--- +++ @@ -9,7 +9,9 @@ Config.getRefreshRate(), function (resolve, reject) { return function () { - var url = Config.rootUrl + '/marathon/v2/apps'; + const embed = 'embed=group.groups&embed=group.apps&' + + 'embed=group.apps.deployments&embed=group.apps.counts'; + let url = `${Config.rootUrl}/marathon/v2/groups?${embed}`; RequestUtil.json({ url: url,
58ac6e0986e0123732a7eb85c12c151fac028f4a
src/js/bpm-counter.js
src/js/bpm-counter.js
class BpmCounter { constructor() { this.numTaps = 0; this.bpm = 0; this.startTapTime = new Date(); } restart() { this.numTaps = 0; this.bpm = 0; } tick() { if (this.numTaps === 0) { this.startTapTime = new Date(); } this.numTaps++; let currentTime = new Date(); let timeDifferenceInMS = currentTime - this.startTapTime; this.bpm = this.numTaps / (timeDifferenceInMS / 1000) * 60; } }
class BpmCounter { constructor() { this.numTaps = 0; this.bpm = 0; this.startTapTime = new Date(); } restart() { this.numTaps = 0; this.bpm = 0; } tick() { if (this.numTaps === 0) { this.startTapTime = new Date(); } this.numTaps++; let currentTime = new Date(); let timeDifferenceInMS = currentTime - this.startTapTime; if (timeDifferenceInMS === 0) { this.bpm = "First tap"; } else { this.bpm = this.numTaps / (timeDifferenceInMS / 1000) * 60; } } }
Fix bug where the first tap gave a bpm of infinity
Fix bug where the first tap gave a bpm of infinity
JavaScript
mit
khwang/plum,khwang/plum
--- +++ @@ -21,6 +21,10 @@ let timeDifferenceInMS = currentTime - this.startTapTime; - this.bpm = this.numTaps / (timeDifferenceInMS / 1000) * 60; + if (timeDifferenceInMS === 0) { + this.bpm = "First tap"; + } else { + this.bpm = this.numTaps / (timeDifferenceInMS / 1000) * 60; + } } }
53f0ff80ae2adea22fa7821bd78b57a4920e272c
webapp/display/changes/jobstep_details.js
webapp/display/changes/jobstep_details.js
import React, { PropTypes } from 'react'; import APINotLoaded from 'es6!display/not_loaded'; import ChangesUI from 'es6!display/changes/ui'; import * as api from 'es6!server/api'; import custom_content_hook from 'es6!utils/custom_content'; /* * Shows artifacts for a jobstep */ export var JobstepDetails = React.createClass({ propTypes: { jobstepID: PropTypes.string, }, getInitialState: function() { return {}; }, componentDidMount: function() { api.fetch(this, { artifacts: `/api/0/jobsteps/${this.props.jobstepID}/artifacts/` }); }, render: function() { var { jobstepID, className, ...props} = this.props; if (!api.isLoaded(this.state.artifacts)) { return <APINotLoaded calls={this.state.artifacts} />; } var artifacts = this.state.artifacts.getReturnedData(); className = (className || "") + " jobstepDetails"; return <div {...props} className={className}> {this.renderArtifacts(artifacts)} </div>; }, renderArtifacts(artifacts) { var markup = []; if (artifacts.length > 0) { markup.push(<div className="lb marginTopM">Artifacts</div>); _.each(artifacts, a => { markup.push( <div> <a className="external" target="_blank" href={a.url}> {a.name} </a> </div> ); }); } return markup; } });
import React, { PropTypes } from 'react'; import APINotLoaded from 'es6!display/not_loaded'; import ChangesUI from 'es6!display/changes/ui'; import * as api from 'es6!server/api'; import custom_content_hook from 'es6!utils/custom_content'; /* * Shows artifacts for a jobstep */ export var JobstepDetails = React.createClass({ propTypes: { jobstepID: PropTypes.string, }, getInitialState: function() { return {}; }, componentDidMount: function() { api.fetch(this, { details: `/api/0/jobsteps/${this.props.jobstepID}/artifacts/` }); }, render: function() { var { jobstepID, className, ...props} = this.props; if (!api.isLoaded(this.state.details)) { return <APINotLoaded calls={this.state.details} />; } var details = this.state.details.getReturnedData(); className = (className || "") + " jobstepDetails"; return <div {...props} className={className}> {this.renderArtifacts(details.artifacts)} </div>; }, renderArtifacts(artifacts) { var markup = []; if (artifacts.length > 0) { markup.push(<div className="lb marginTopM">Artifacts</div>); _.each(artifacts, a => { markup.push( <div> <a className="external" target="_blank" href={a.url}> {a.name} </a> </div> ); }); } return markup; } });
Fix artifact display on job steps (which broke because the API changes to return an object rather than a list)
Fix artifact display on job steps (which broke because the API changes to return an object rather than a list) Test Plan: manual =( Reviewers: mkedia, kylec Reviewed By: kylec Subscribers: changesbot Differential Revision: https://tails.corp.dropbox.com/D143542
JavaScript
apache-2.0
dropbox/changes,dropbox/changes,dropbox/changes,dropbox/changes
--- +++ @@ -21,22 +21,22 @@ componentDidMount: function() { api.fetch(this, { - artifacts: `/api/0/jobsteps/${this.props.jobstepID}/artifacts/` + details: `/api/0/jobsteps/${this.props.jobstepID}/artifacts/` }); }, render: function() { var { jobstepID, className, ...props} = this.props; - if (!api.isLoaded(this.state.artifacts)) { - return <APINotLoaded calls={this.state.artifacts} />; + if (!api.isLoaded(this.state.details)) { + return <APINotLoaded calls={this.state.details} />; } - var artifacts = this.state.artifacts.getReturnedData(); + var details = this.state.details.getReturnedData(); className = (className || "") + " jobstepDetails"; return <div {...props} className={className}> - {this.renderArtifacts(artifacts)} + {this.renderArtifacts(details.artifacts)} </div>; },
4233edea9f06647e77033222f113392b44049f53
Server.js
Server.js
const util = require('util'); const Koa = require('koa'); const bodyParser = require('koa-bodyparser'); const request = require('./request'); class Server { constructor(verbose) { this.app = new Koa(); this.app.use(async (ctx, next) => { try { await next(); } catch (error) { ctx.status = 400; ctx.body = {error: error.message}; } }); this.app.use(bodyParser({ enableTypes: ['json'], strict: true, })); this.app.use(async (ctx) => { let url = ctx.request.body.url; if (!url) throw new Error('Missing parameter url'); let options = ctx.request.body.options; if (verbose) { if (options) { console.log(url, util.inspect(options, {depth: null, breakLength: Infinity})); } else { console.log(url); } } options = Object.assing({forever: true, gzip: true}, options); ctx.body = await request(url, options); }); } listen(port = 80, address) { return new Promise((resolve, reject) => { try { this.app.listen(port, address, () => { resolve(); }); } catch (error) { reject(error); } }); } } module.exports = Server;
const util = require('util'); const Koa = require('koa'); const bodyParser = require('koa-bodyparser'); const request = require('./request'); class Server { constructor(verbose) { this.app = new Koa(); this.app.use(async (ctx, next) => { try { await next(); } catch (error) { ctx.status = 400; ctx.body = {error: error.message}; } }); this.app.use(bodyParser({ enableTypes: ['json'], strict: true, })); this.app.use(async (ctx) => { let url = ctx.request.body.url; if (!url) throw new Error('Missing parameter url'); let options = ctx.request.body.options; if (verbose) { if (options) { console.log(url, util.inspect(options, {depth: null, breakLength: Infinity})); } else { console.log(url); } } options = Object.assing({forever: true, gzip: true}, options); try { ctx.body = await request(url, options); } catch (error) { ctx.status = 502; ctx.body = {error: error.message}; } }); } listen(port = 80, address) { return new Promise((resolve, reject) => { try { this.app.listen(port, address, () => { resolve(); }); } catch (error) { reject(error); } }); } } module.exports = Server;
Return HTTP 502 and error message if upstream server error.
Return HTTP 502 and error message if upstream server error.
JavaScript
mit
quentinadam/node-request-server
--- +++ @@ -34,7 +34,12 @@ } } options = Object.assing({forever: true, gzip: true}, options); - ctx.body = await request(url, options); + try { + ctx.body = await request(url, options); + } catch (error) { + ctx.status = 502; + ctx.body = {error: error.message}; + } }); }
ab838c82bd48a01a99c152b2392518382d9181e3
app/controllers/dashboard/session-manager/index.js
app/controllers/dashboard/session-manager/index.js
import Ember from 'ember'; export default Ember.Controller.extend({ sortProperties: [ 'statusSort:asc', 'organizationKindSort:asc', 'nomen:asc', ], sortedSessions: Ember.computed.sort( 'model', 'sortProperties' ), actions: { sortBy(sortProperties) { this.set('sortProperties', [sortProperties]); }, } });
import Ember from 'ember'; export default Ember.Controller.extend({ sortProperties: [ 'statusSort:asc', 'organizationKindSort:asc', 'nomen:asc', ], uniqueSessions: Ember.computed.uniq( 'model', ), sortedSessions: Ember.computed.sort( 'uniqueSessions', 'sortProperties' ), actions: { sortBy(sortProperties) { this.set('sortProperties', [sortProperties]); }, } });
Fix duplicates on session manager
Fix duplicates on session manager
JavaScript
bsd-2-clause
barberscore/barberscore-web,barberscore/barberscore-web,barberscore/barberscore-web
--- +++ @@ -6,8 +6,11 @@ 'organizationKindSort:asc', 'nomen:asc', ], + uniqueSessions: Ember.computed.uniq( + 'model', + ), sortedSessions: Ember.computed.sort( - 'model', + 'uniqueSessions', 'sortProperties' ), actions: {
566df4420093daf02422cbf344d49d0da089e583
src/lib/fileUpload.js
src/lib/fileUpload.js
var ssh2 = require('ssh2'); var SocketIOFileUpload = require('socketio-file-upload'); var completeFileUpload = function(client, sshCredentials) { return function(event) { var credentials = sshCredentials(client.instance); var connection = ssh2(); connection.on('end', function() { }); connection.on('ready', function() { connection.sftp(function(err, sftp) { if (err) { console.log("There was an error while connecting via sftp: " + err); } var stream = sftp.createWriteStream(event.file.name); stream.write(client.fileUploadBuffer.toString()); stream.end(function() { connection.end(); }); client.fileUploadBuffer = ""; }); }); connection.connect(credentials); }; }; module.exports = function(logExceptOnTest, sshCredentials) { return { attachUploadListenerToSocket: function(client, socket) { var uploader = new SocketIOFileUpload(); uploader.listen(socket); uploader.on("error", function(event) { console.error("Error in upload " + event); }); uploader.on("start", function(event) { client.fileUploadBuffer = ""; logExceptOnTest('File upload ' + event.file.name); }); uploader.on("progress", function(event) { client.fileUploadBuffer += event.buffer; }); uploader.on("complete", completeFileUpload(client, sshCredentials)); } }; };
var ssh2 = require('ssh2'); var SocketIOFileUpload = require('socketio-file-upload'); var completeFileUpload = function(client, sshCredentials) { return function(event) { var credentials = sshCredentials(client.instance); var connection = ssh2(); connection.on('end', function() { }); connection.on('ready', function() { connection.sftp(function(err, sftp) { if (err) { console.log("There was an error while connecting via sftp: " + err); } var stream = sftp.createWriteStream(event.file.name); stream.write(client.fileUploadBuffer); stream.end(function() { connection.end(); }); client.fileUploadBuffer = ""; }); }); connection.connect(credentials); }; }; module.exports = function(logExceptOnTest, sshCredentials) { return { attachUploadListenerToSocket: function(client, socket) { var uploader = new SocketIOFileUpload(); uploader.listen(socket); uploader.on("error", function(event) { console.error("Error in upload " + event); }); uploader.on("start", function(event) { client.fileUploadBuffer = ""; logExceptOnTest('File upload name:' + event.file.name); logExceptOnTest('File upload encoding: ' + event.file.encoding); }); uploader.on("progress", function(event) { client.fileUploadBuffer = event.buffer; }); uploader.on("complete", completeFileUpload(client, sshCredentials)); } }; };
Fix bug with uploading octed data like images
Fix bug with uploading octed data like images
JavaScript
mit
antonleykin/InteractiveShell,antonleykin/InteractiveShell,antonleykin/InteractiveShell,fhinkel/InteractiveShell,fhinkel/InteractiveShell,fhinkel/InteractiveShell,fhinkel/InteractiveShell
--- +++ @@ -15,7 +15,7 @@ console.log("There was an error while connecting via sftp: " + err); } var stream = sftp.createWriteStream(event.file.name); - stream.write(client.fileUploadBuffer.toString()); + stream.write(client.fileUploadBuffer); stream.end(function() { connection.end(); }); @@ -39,11 +39,12 @@ uploader.on("start", function(event) { client.fileUploadBuffer = ""; - logExceptOnTest('File upload ' + event.file.name); + logExceptOnTest('File upload name:' + event.file.name); + logExceptOnTest('File upload encoding: ' + event.file.encoding); }); uploader.on("progress", function(event) { - client.fileUploadBuffer += event.buffer; + client.fileUploadBuffer = event.buffer; }); uploader.on("complete", completeFileUpload(client, sshCredentials));
4c5483125fcd12e111cffe1a1cadf67b8777ff7e
src/nbsp-positions.js
src/nbsp-positions.js
'use strict'; var execall = require('regexp.execall'); module.exports = function (text) { return execall(/ \w{1,2} [^ ]/g, text).map(function (match) { return match.index + match[0].length - 2; }); };
'use strict'; var execall = require('regexp.execall'); module.exports = function (text) { return execall(/(^|\s\W*)(\w{1,2})(?= [^ ])/g, text) .filter(function (match) { return !/\d/.test(match[1]); }) .map(function (match) { return match.index + match[0].length; }); };
Improve regular expression's overlapping and details
Improve regular expression's overlapping and details
JavaScript
mit
eush77/nbsp-advisor
--- +++ @@ -4,7 +4,11 @@ module.exports = function (text) { - return execall(/ \w{1,2} [^ ]/g, text).map(function (match) { - return match.index + match[0].length - 2; - }); + return execall(/(^|\s\W*)(\w{1,2})(?= [^ ])/g, text) + .filter(function (match) { + return !/\d/.test(match[1]); + }) + .map(function (match) { + return match.index + match[0].length; + }); };
d64d4fd171002890c5bc3a5e2ea697e03b37c59d
src/dom_components/view/ToolbarButtonView.js
src/dom_components/view/ToolbarButtonView.js
var Backbone = require('backbone'); module.exports = Backbone.View.extend({ events() { return ( this.model.get('events') || { mousedown: 'handleClick' } ); }, attributes() { return this.model.get('attributes'); }, initialize(opts) { this.editor = opts.config.editor; }, handleClick(event) { event.preventDefault(); event.stopPropagation(); this.execCommand(event); }, execCommand(event) { const opts = { event }; const command = this.model.get('command'); const editor = this.editor; if (typeof command === 'function') { command(editor, null, opts); } if (typeof command === 'string') { editor.runCommand(command, opts); } }, render() { var config = this.editor.getConfig(); this.el.className += ' ' + config.stylePrefix + 'toolbar-item'; return this; } });
var Backbone = require('backbone'); module.exports = Backbone.View.extend({ events() { return ( this.model.get('events') || { mousedown: 'handleClick' } ); }, attributes() { return this.model.get('attributes'); }, initialize(opts) { this.editor = opts.config.editor; }, handleClick(event) { event.preventDefault(); event.stopPropagation(); this.execCommand(event); }, execCommand(event) { const opts = { event }; const command = this.model.get('command'); const editor = this.editor; if (typeof command === 'function') { command(editor, null, opts); } if (typeof command === 'string') { editor.runCommand(command, opts); } }, render() { const { editor, $el, model } = this; const label = model.get('label'); const pfx = editor.getConfig('stylePrefix'); $el.addClass(`${pfx}toolbar-item`); label && $el.append(label); return this; } });
Add the possibility to append `label` on component toolbar buttons
Add the possibility to append `label` on component toolbar buttons
JavaScript
bsd-3-clause
QuorumDMS/grapesjs,artf/grapesjs,artf/grapesjs,QuorumDMS/grapesjs,artf/grapesjs
--- +++ @@ -38,8 +38,11 @@ }, render() { - var config = this.editor.getConfig(); - this.el.className += ' ' + config.stylePrefix + 'toolbar-item'; + const { editor, $el, model } = this; + const label = model.get('label'); + const pfx = editor.getConfig('stylePrefix'); + $el.addClass(`${pfx}toolbar-item`); + label && $el.append(label); return this; } });
5fee62511ed5e733d501e86ac8fe8e0516ba8a54
src/util/maintenance/index.js
src/util/maintenance/index.js
const AssignedSchedule = require('../../structs/db/AssignedSchedule.js') const pruneGuilds = require('./pruneGuilds.js') const pruneFeeds = require('./pruneFeeds.js') const pruneFormats = require('./pruneFormats.js') const pruneFailCounters = require('./pruneFailCounters.js') const pruneSubscribers = require('./pruneSubscribers.js') const pruneCollections = require('./pruneCollections.js') const flushRedis = require('./flushRedis.js') /** * @param {Set<string>} guildIds * @param {import('discord.js').Client} bot */ async function prunePreInit (guildIds, bot) { await Promise.all([ AssignedSchedule.deleteAll(), flushRedis(), pruneGuilds(guildIds) ]) await pruneFeeds(guildIds) await Promise.all([ pruneFormats(), pruneFailCounters() ]) if (bot) { await pruneSubscribers(bot) } // Prune collections should not be called here until schedules were assigned } async function prunePostInit () { await pruneCollections() } module.exports = { flushRedis, prunePreInit, prunePostInit, pruneGuilds, pruneFeeds, pruneFormats, pruneFailCounters, pruneSubscribers, pruneCollections }
const AssignedSchedule = require('../../structs/db/AssignedSchedule.js') const pruneGuilds = require('./pruneGuilds.js') const pruneFeeds = require('./pruneFeeds.js') const pruneFormats = require('./pruneFormats.js') const pruneFailCounters = require('./pruneFailCounters.js') const pruneSubscribers = require('./pruneSubscribers.js') const pruneCollections = require('./pruneCollections.js') const flushRedis = require('./flushRedis.js') const checkLimits = require('./checkLimits.js') const checkPermissions = require('./checkPermissions.js') /** * @param {Set<string>} guildIds * @param {import('discord.js').Client} bot */ async function prunePreInit (guildIds, bot) { await Promise.all([ AssignedSchedule.deleteAll(), flushRedis(), pruneGuilds(guildIds) ]) await pruneFeeds(guildIds) await Promise.all([ pruneFormats(), pruneFailCounters() ]) if (bot) { await pruneSubscribers(bot) } // Prune collections should not be called here until schedules were assigned } async function prunePostInit () { await pruneCollections() } module.exports = { flushRedis, prunePreInit, prunePostInit, pruneGuilds, pruneFeeds, pruneFormats, pruneFailCounters, pruneSubscribers, pruneCollections, checkLimits, checkPermissions }
Add missing funcs to util maintenance
Add missing funcs to util maintenance
JavaScript
mit
synzen/Discord.RSS,synzen/Discord.RSS
--- +++ @@ -6,6 +6,8 @@ const pruneSubscribers = require('./pruneSubscribers.js') const pruneCollections = require('./pruneCollections.js') const flushRedis = require('./flushRedis.js') +const checkLimits = require('./checkLimits.js') +const checkPermissions = require('./checkPermissions.js') /** * @param {Set<string>} guildIds @@ -41,5 +43,7 @@ pruneFormats, pruneFailCounters, pruneSubscribers, - pruneCollections + pruneCollections, + checkLimits, + checkPermissions }
78fc9a890a4bb46eae99cc3ccbe8eaf2e0a07068
src/parser/shaman/enhancement/modules/features/Checklist/Component.js
src/parser/shaman/enhancement/modules/features/Checklist/Component.js
import React from 'react'; import PropTypes from 'prop-types'; import Checklist from 'parser/shared/modules/features/Checklist2'; import Rule from 'parser/shared/modules/features/Checklist2/Rule'; import Requirement from 'parser/shared/modules/features/Checklist2/Requirement'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; const DowntimeDescription = () => ( <> You should try to avoid doing nothing during the fight. If you have to move, try casting something instant with range like <SpellLink id={SPELLS.FLAMETONGUE.id} /> or <SpellLink id={SPELLS.ROCKBITER.id} /> </> ); class EnhancementShamanChecklist extends React.PureComponent { static propTypes = { castEfficiency: PropTypes.object.isRequired, combatant: PropTypes.shape({ hasTalent: PropTypes.func.isRequired, hasTrinket: PropTypes.func.isRequired, }).isRequired, thresholds: PropTypes.object.isRequired, }; render() { const { combatant, castEfficiency, thresholds } = this.props; return ( <Checklist> <Rule name="Always be casting" description={DowntimeDescription} > <Requirement name="Downtime" thresholds={thresholds.alwaysBeCasting} /> </Rule> </Checklist> ); } } export default EnhancementShamanChecklist;
import React from 'react'; import PropTypes from 'prop-types'; import Checklist from 'parser/shared/modules/features/Checklist2'; import Rule from 'parser/shared/modules/features/Checklist2/Rule'; import Requirement from 'parser/shared/modules/features/Checklist2/Requirement'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; const DowntimeDescription = () => ( <> You should try to avoid doing nothing during the fight. If you have to move, try casting something instant with range like <SpellLink id={SPELLS.FLAMETONGUE.id} /> or <SpellLink id={SPELLS.ROCKBITER.id} /> </> ); class EnhancementShamanChecklist extends React.PureComponent { static propTypes = { castEfficiency: PropTypes.object.isRequired, combatant: PropTypes.shape({ hasTalent: PropTypes.func.isRequired, hasTrinket: PropTypes.func.isRequired, }).isRequired, thresholds: PropTypes.object.isRequired, }; render() { const { combatant, castEfficiency, thresholds } = this.props; return ( <Checklist> <Rule name="Always be casting" description={<DowntimeDescription />} > <Requirement name="Downtime" thresholds={thresholds.alwaysBeCasting} /> </Rule> </Checklist> ); } } export default EnhancementShamanChecklist;
Fix DowntimeDescription not showing on checklist
Fix DowntimeDescription not showing on checklist
JavaScript
agpl-3.0
anom0ly/WoWAnalyzer,ronaldpereira/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer,anom0ly/WoWAnalyzer,yajinni/WoWAnalyzer,fyruna/WoWAnalyzer,FaideWW/WoWAnalyzer,fyruna/WoWAnalyzer,anom0ly/WoWAnalyzer,sMteX/WoWAnalyzer,anom0ly/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer,ronaldpereira/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer,yajinni/WoWAnalyzer,fyruna/WoWAnalyzer,sMteX/WoWAnalyzer,Juko8/WoWAnalyzer,Juko8/WoWAnalyzer,ronaldpereira/WoWAnalyzer,FaideWW/WoWAnalyzer,Juko8/WoWAnalyzer,sMteX/WoWAnalyzer,FaideWW/WoWAnalyzer,yajinni/WoWAnalyzer,yajinni/WoWAnalyzer
--- +++ @@ -29,7 +29,7 @@ <Checklist> <Rule name="Always be casting" - description={DowntimeDescription} + description={<DowntimeDescription />} > <Requirement name="Downtime" thresholds={thresholds.alwaysBeCasting} /> </Rule>
3de08c1740dac5c258d7291aba11f996c6e27c47
bin/gh.js
bin/gh.js
#!/usr/bin/env node /* * Copyright 2013 Eduardo Lundgren, All Rights Reserved. * * Code licensed under the BSD License: * https://github.com/eduardolundgren/blob/master/LICENSE.md * * @author Eduardo Lundgren <eduardolundgren@gmail.com> */ var async = require('async'), fs = require('fs'), nopt = require('nopt'), base = require('../lib/base'), git = require('../lib/git'), commandFilePath, commandImpl, logger, operations, options, parsed, remain; logger = base.logger; operations = []; parsed = nopt(process.argv), remain = parsed.argv.remain; if (!remain.length) { logger.oops('usage: gh [command] [payload] [--flags]'); } commandFilePath = __dirname + '/../lib/cmds/' + remain[0] + '.js'; if (fs.existsSync(commandFilePath)) { commandImpl = require(commandFilePath).Impl; options = nopt( commandImpl.DETAILS.options, commandImpl.DETAILS.shorthands, process.argv, 2); operations.push(git.getRepositoryName); operations.push(git.getCurrentBranch); async.parallel(operations, function(err, results) { new commandImpl().run(options, results[0], results[1]); }); } else { logger.oops('command not found'); }
#!/usr/bin/env node /* * Copyright 2013 Eduardo Lundgren, All Rights Reserved. * * Code licensed under the BSD License: * https://github.com/eduardolundgren/blob/master/LICENSE.md * * @author Eduardo Lundgren <eduardolundgren@gmail.com> */ var async = require('async'), fs = require('fs'), nopt = require('nopt'), base = require('../lib/base'), git = require('../lib/git'), commandFilePath, commandImpl, logger, operations, options, parsed, remain; logger = base.logger; operations = []; parsed = nopt(process.argv), remain = parsed.argv.remain; if (!remain.length) { logger.oops('usage: gh [command] [payload] [--flags]'); } commandFilePath = __dirname + '/../lib/cmds/' + remain[0] + '.js'; if (fs.existsSync(commandFilePath)) { commandImpl = require(commandFilePath).Impl; options = nopt( commandImpl.DETAILS.options, commandImpl.DETAILS.shorthands, process.argv, 2); operations.push(git.getRepositoryName); operations.push(git.getCurrentBranch); async.parallel(operations, function(err, results) { new commandImpl(options, results[0], results[1]).run(); }); } else { logger.oops('command not found'); }
Change constructor to receive (options, repo, branch)
Change constructor to receive (options, repo, branch)
JavaScript
bsd-3-clause
tomzx/gh,TomzxForks/gh,oouyang/gh,TomzxForks/gh,oouyang/gh,dustinryerson/gh,dustinryerson/gh,modulexcite/gh,modulexcite/gh,tomzx/gh,henvic/gh,henvic/gh
--- +++ @@ -44,7 +44,7 @@ operations.push(git.getCurrentBranch); async.parallel(operations, function(err, results) { - new commandImpl().run(options, results[0], results[1]); + new commandImpl(options, results[0], results[1]).run(); }); } else {
abdee493c6b6a9811eae773bf07512834e228afa
server/api/conversion/index.js
server/api/conversion/index.js
'use strict'; var express = require('express'); var controller = require('./conversion.controller'); var router = express.Router(); router.post('/import', controller.import); router.post('/export/:format(cml,pdb,mol,mol2,smiles,hin)', controller.export); module.exports = router;
'use strict'; var express = require('express'); var controller = require('./conversion.controller'); var router = express.Router(); router.post('/import', controller.import); router.post('/export/:format(cml|pdb|mol|mol2|smiles|hin)', controller.export); module.exports = router;
Fix pattern for export formats
fixed: Fix pattern for export formats
JavaScript
apache-2.0
mohebifar/chemozart,mohebifar/chemozart,U4ICKleviathan/chemozart,U4ICKleviathan/chemozart
--- +++ @@ -6,6 +6,6 @@ var router = express.Router(); router.post('/import', controller.import); -router.post('/export/:format(cml,pdb,mol,mol2,smiles,hin)', controller.export); +router.post('/export/:format(cml|pdb|mol|mol2|smiles|hin)', controller.export); module.exports = router;
5205890e7806ea1997d02e8bb2b1554e34418d04
site/assets/_folder-of-crap.js
site/assets/_folder-of-crap.js
$(".container").addClass("tk-proxima-nova"); $(".page-header").addClass("tk-league-gothic"); $("td:nth-child(2)").each(function() { $(this).text(moment($.trim($(this).text()), "DD-MMM-YYYY HH:mm").fromNow()); });
$("td:nth-child(2)").each(function() { $(this).text(moment($.trim($(this).text()), "DD-MMM-YYYY HH:mm").fromNow()); });
Change how Typekit fonts are applied.
Change how Typekit fonts are applied. Prevent the FOUC that sometimes occurs by having Typekit apply fonts instead of handling it ourselves.
JavaScript
mit
damiendart/robotinaponcho,damiendart/robotinaponcho,damiendart/robotinaponcho
--- +++ @@ -1,5 +1,3 @@ -$(".container").addClass("tk-proxima-nova"); -$(".page-header").addClass("tk-league-gothic"); $("td:nth-child(2)").each(function() { $(this).text(moment($.trim($(this).text()), "DD-MMM-YYYY HH:mm").fromNow()); });
1b5cde782e42cf48c29a09921b1aec62c5be876a
eloquent_js/chapter09/ch09_ex03.js
eloquent_js/chapter09/ch09_ex03.js
let number = /^[+-]?\d*(\d\.|\.\d)?\d*([eE][+-]?\d+)?$/;
let number = /^[+-]?(\d+(\.\d*)?|\.\d+)([Ee][+-]?\d+)?$/;
Add chapter 9, exercise 3
Add chapter 9, exercise 3
JavaScript
mit
bewuethr/ctci
--- +++ @@ -1 +1 @@ -let number = /^[+-]?\d*(\d\.|\.\d)?\d*([eE][+-]?\d+)?$/; +let number = /^[+-]?(\d+(\.\d*)?|\.\d+)([Ee][+-]?\d+)?$/;
d648388d8c9297efb610e86904853b937c051582
eloquent_js/chapter11/ch11_ex01.js
eloquent_js/chapter11/ch11_ex01.js
async function locateScalpel(nest) { let curNest = nest.name; for (;;) { let scalpelLoc = await anyStorage(nest, curNest, "scalpel"); if (scalpelLoc == curNest) return curNest; curNest = scalpelLoc; } } function locateScalpel2(nest) { let next = nest.name; function getNext(next) { return anyStorage(nest, next, "scalpel") .then(val => val == next ? next : getNext(val)); } return getNext(next); } locateScalpel(bigOak).then(console.log); // → Butcher's Shop locateScalpel2(bigOak).then(console.log); // → Butcher's Shop
async function locateScalpel(nest) { let current = nest.name; for (;;) { let next = await anyStorage(nest, current, "scalpel"); if (next == current) { return next; } current = next; } } function locateScalpel2(nest) { function next(current) { return anyStorage(nest, current, "scalpel") .then(value => value == current ? value : next(value)); } return next(nest.name); }
Add chapter 11, exercise 1
Add chapter 11, exercise 1
JavaScript
mit
bewuethr/ctci
--- +++ @@ -1,22 +1,21 @@ async function locateScalpel(nest) { - let curNest = nest.name; - for (;;) { - let scalpelLoc = await anyStorage(nest, curNest, "scalpel"); - if (scalpelLoc == curNest) return curNest; - curNest = scalpelLoc; - } + let current = nest.name; + + for (;;) { + let next = await anyStorage(nest, current, "scalpel"); + if (next == current) { + return next; + } + + current = next; + } } function locateScalpel2(nest) { - let next = nest.name; - function getNext(next) { - return anyStorage(nest, next, "scalpel") - .then(val => val == next ? next : getNext(val)); - } - return getNext(next); + function next(current) { + return anyStorage(nest, current, "scalpel") + .then(value => value == current ? value : next(value)); + } + + return next(nest.name); } - -locateScalpel(bigOak).then(console.log); -// → Butcher's Shop -locateScalpel2(bigOak).then(console.log); -// → Butcher's Shop
d959e87e16280eb4cbcb7ca80b64c89cacde2662
addon/components/simple-table-cell.js
addon/components/simple-table-cell.js
import Ember from 'ember'; import layout from '../templates/components/simple-table-cell'; export default Ember.Component.extend({ layout, tagName: 'th', classNameBindings: ['columnsClass'], attributeBindings: ['rowspan', 'colspan', 'columnsStyle:style'], columnsClass: Ember.computed.alias('columns.classes'), columnsStyle: Ember.computed('columns.style', { get() { return Ember.String.htmlSafe(this.get('columns.style')); } }), actions: { sortBy(key) { return this.get('sortAction')(key); } } });
import Ember from 'ember'; import layout from '../templates/components/simple-table-cell'; export default Ember.Component.extend({ layout, tagName: 'th', classNameBindings: ['columnsClass'], attributeBindings: ['rowspan', 'colspan', 'columnsStyle:style'], columnsClass: Ember.computed('columns.classes', { get() { let columns = this.get('columns'); let column = Ember.isArray(columns) ? columns[0] : columns; return Ember.String.htmlSafe(column.classes); } }), columnsStyle: Ember.computed('columns.style', { get() { let columns = this.get('columns'); let column = Ember.isArray(columns) ? columns[0] : columns; return Ember.String.htmlSafe(column.style); } }), actions: { sortBy(key) { return this.get('sortAction')(key); } } });
Fix styles and classes for grouped columns
Fix styles and classes for grouped columns
JavaScript
mit
Baltazore/ember-simple-table,Baltazore/ember-simple-table
--- +++ @@ -8,10 +8,18 @@ classNameBindings: ['columnsClass'], attributeBindings: ['rowspan', 'colspan', 'columnsStyle:style'], - columnsClass: Ember.computed.alias('columns.classes'), + columnsClass: Ember.computed('columns.classes', { + get() { + let columns = this.get('columns'); + let column = Ember.isArray(columns) ? columns[0] : columns; + return Ember.String.htmlSafe(column.classes); + } + }), columnsStyle: Ember.computed('columns.style', { get() { - return Ember.String.htmlSafe(this.get('columns.style')); + let columns = this.get('columns'); + let column = Ember.isArray(columns) ? columns[0] : columns; + return Ember.String.htmlSafe(column.style); } }),
2c1b1b6d2b35ce363ca950e57d11e0e33b95dac2
fetch-node.js
fetch-node.js
'use strict'; var fetch = require('node-fetch'); var URL = require('url').URL; function wrapFetchForNode(fetch) { // Support schemaless URIs on the server for parity with the browser. // https://github.com/matthew-andrews/isomorphic-fetch/pull/10 return function (u, options) { if (u instanceof URL) { return fetch(u, options); } if (u instanceof fetch.Request) { return fetch(u, options); } var url = u.slice(0, 2) === '//' ? 'https:' + u : u; return fetch(url, options); }; } module.exports = function (context) { // This modifies the global `node-fetch` object, which isn't great, since // different callers to `fetch-ponyfill` which pass a different Promise // implementation would each expect to have their implementation used. But, // given the way `node-fetch` is implemented, this is the only way to make // it work at all. if (context && context.Promise) { fetch.Promise = context.Promise; } return { fetch: wrapFetchForNode(fetch), Headers: fetch.Headers, Request: fetch.Request, Response: fetch.Response }; };
'use strict'; var fetch = require('node-fetch'); var URL = require('url').URL; function wrapFetchForNode(fetch) { // Support schemaless URIs on the server for parity with the browser. // https://github.com/matthew-andrews/isomorphic-fetch/pull/10 return function (u, options) { if (typeof u === 'string' && u.slice(0, 2) === '//') { return fetch('https:' + u, options); } return fetch(u, options); }; } module.exports = function (context) { // This modifies the global `node-fetch` object, which isn't great, since // different callers to `fetch-ponyfill` which pass a different Promise // implementation would each expect to have their implementation used. But, // given the way `node-fetch` is implemented, this is the only way to make // it work at all. if (context && context.Promise) { fetch.Promise = context.Promise; } return { fetch: wrapFetchForNode(fetch), Headers: fetch.Headers, Request: fetch.Request, Response: fetch.Response }; };
Change to treat the string as a special case
Change to treat the string as a special case
JavaScript
mit
qubyte/fetch-ponyfill,qubyte/fetch-ponyfill
--- +++ @@ -7,17 +7,11 @@ // Support schemaless URIs on the server for parity with the browser. // https://github.com/matthew-andrews/isomorphic-fetch/pull/10 return function (u, options) { - if (u instanceof URL) { - return fetch(u, options); + if (typeof u === 'string' && u.slice(0, 2) === '//') { + return fetch('https:' + u, options); } - if (u instanceof fetch.Request) { - return fetch(u, options); - } - - var url = u.slice(0, 2) === '//' ? 'https:' + u : u; - - return fetch(url, options); + return fetch(u, options); }; }
3515ea1cf459874f3a487e7c30fc585eb21f1f7f
app/assets/scripts/utils/constants.js
app/assets/scripts/utils/constants.js
'use strict'; import { t } from '../utils/i18n'; export const fileTypesMatrix = { 'admin-bounds': { display: t('Administrative Boundaries'), description: t('A GeoJSON containing polygons with the administrative boundaries.') }, origins: { display: t('Population data'), description: t('A GeoJSON with population point data. This will be used as the Origin in the analysis.') }, poi: { display: t('Points of Interest'), description: t('GeoJSON for the Points of Interest (eg. banks or hospitals). These are the destinations in the analysis.') }, 'road-network': { display: t('Road Network'), description: t('The underlying road network in OSM XML format.') }, profile: { display: t('Profile'), description: t('A lua file with the OSRM Profile.') } };
'use strict'; import { t } from '../utils/i18n'; export const fileTypesMatrix = { 'admin-bounds': { display: t('Administrative Boundaries'), description: t('A GeoJSON containing polygons with the administrative boundaries.'), helpPath: '/help#administrative-boundaries' }, origins: { display: t('Population data'), description: t('A GeoJSON with population point data. This will be used as the Origin in the analysis.'), helpPath: '/help#population-data' }, poi: { display: t('Points of Interest'), description: t('GeoJSON for the Points of Interest (eg. banks or hospitals). These are the destinations in the analysis.'), helpPath: '/help#points-of-interest' }, 'road-network': { display: t('Road Network'), description: t('The underlying road network in OSM XML format.'), helpPath: '/help#road-network' }, profile: { display: t('Profile'), description: t('A lua file with the OSRM Profile.'), helpPath: '/help#profile' } };
Add help path to poi data
Add help path to poi data
JavaScript
mit
WorldBank-Transport/rra-frontend,WorldBank-Transport/rra-frontend,WorldBank-Transport/rra-frontend
--- +++ @@ -4,22 +4,27 @@ export const fileTypesMatrix = { 'admin-bounds': { display: t('Administrative Boundaries'), - description: t('A GeoJSON containing polygons with the administrative boundaries.') + description: t('A GeoJSON containing polygons with the administrative boundaries.'), + helpPath: '/help#administrative-boundaries' }, origins: { display: t('Population data'), - description: t('A GeoJSON with population point data. This will be used as the Origin in the analysis.') + description: t('A GeoJSON with population point data. This will be used as the Origin in the analysis.'), + helpPath: '/help#population-data' }, poi: { display: t('Points of Interest'), - description: t('GeoJSON for the Points of Interest (eg. banks or hospitals). These are the destinations in the analysis.') + description: t('GeoJSON for the Points of Interest (eg. banks or hospitals). These are the destinations in the analysis.'), + helpPath: '/help#points-of-interest' }, 'road-network': { display: t('Road Network'), - description: t('The underlying road network in OSM XML format.') + description: t('The underlying road network in OSM XML format.'), + helpPath: '/help#road-network' }, profile: { display: t('Profile'), - description: t('A lua file with the OSRM Profile.') + description: t('A lua file with the OSRM Profile.'), + helpPath: '/help#profile' } };
28590b794f879b426d9aaf1247ddbed2ae30170e
client/app/redux/reducers/series/series.test.js
client/app/redux/reducers/series/series.test.js
import assert from 'assert'; import series from './series'; import * as TYPES from '../../actions/types'; describe('A series reducer for redux state', () => { //Test states const seriesDefaultState = {}; const seriesWithTicker = { GOOGL: [] }; //Test actions const testAddSeries = { type: TYPES.ADD_SERIES, ticker: 'GOOGL', data: [], } const testInvalidAction = { type: 'INVALID_ACTION', } it('should return a default state when no arguments are supplied', () => { assert.deepEqual(series(), seriesDefaultState ); }) it('should add an empty series attribute if it is missing from the supplied state', () => { assert.deepEqual(series({}), seriesDefaultState); }) it('should return an unchanged state when no actions are supplied', () => { assert.deepEqual(series(seriesDefaultState), seriesDefaultState); }) it('should return an unchanged state when an invalid action is supplied', () => { assert.deepEqual(series(seriesDefaultState, testInvalidAction), seriesDefaultState); }) it('should return a new state based on a passed action', () => { assert.deepEqual(series(seriesDefaultState, testAddSeries), seriesWithTicker); }) it('should return a new object', () => { assert(series({}) !== {}); }) })
import assert from 'assert'; import series from './series'; import * as TYPES from '../../actions/types'; describe('A series reducer for redux state', () => { //Test states const seriesDefaultState = {}; const seriesWithTicker = { GOOGL: [] }; //Test actions const testAddSeries = { type: TYPES.ADD_SERIES, ticker: 'GOOGL', data: [], } const testDelSeries = { type: TYPES.DEL_SERIES, ticker: 'GOOGL', } const testInvalidAction = { type: 'INVALID_ACTION', } it('should return a default state when no arguments are supplied', () => { assert.deepEqual(series(), seriesDefaultState ); }) it('should add an empty series attribute if it is missing from the supplied state', () => { assert.deepEqual(series({}), seriesDefaultState); }) it('should return an unchanged state when no actions are supplied', () => { assert.deepEqual(series(seriesDefaultState), seriesDefaultState); }) it('should return an unchanged state when an invalid action is supplied', () => { assert.deepEqual(series(seriesDefaultState, testInvalidAction), seriesDefaultState); }) it('should return a new state based on a ADD_SERIES action', () => { assert.deepEqual(series(seriesDefaultState, testAddSeries), seriesWithTicker); }) it('should return a new state based on a DEL_SERIES action', () => { assert.deepEqual(series(seriesDefaultState, testDelSeries), seriesDefaultState); }) it('should return a new object', () => { assert(series({}) !== {}); }) })
Test coverage for DEL_SERIES action
Test coverage for DEL_SERIES action
JavaScript
mit
fongelias/cofin,fongelias/cofin
--- +++ @@ -14,6 +14,10 @@ type: TYPES.ADD_SERIES, ticker: 'GOOGL', data: [], + } + const testDelSeries = { + type: TYPES.DEL_SERIES, + ticker: 'GOOGL', } const testInvalidAction = { type: 'INVALID_ACTION', @@ -35,8 +39,12 @@ assert.deepEqual(series(seriesDefaultState, testInvalidAction), seriesDefaultState); }) - it('should return a new state based on a passed action', () => { + it('should return a new state based on a ADD_SERIES action', () => { assert.deepEqual(series(seriesDefaultState, testAddSeries), seriesWithTicker); + }) + + it('should return a new state based on a DEL_SERIES action', () => { + assert.deepEqual(series(seriesDefaultState, testDelSeries), seriesDefaultState); }) it('should return a new object', () => {
f447483548193175cbb68780ba5a4b146183c964
__tests__/app.test.js
__tests__/app.test.js
/* eslint-env jest */ const { exec } = require('child_process') const request = require('supertest') let app // start a mongo instance loaded with test data using docker beforeAll(async () => { await exec('docker run --name scraper_test_db -d --rm -p 27017:27017 mongo') await exec('docker cp dump/ scraper_test_db:/dump') await exec('docker exec scraper_test_db mongorestore /dump') app = await require('../app') await twoSeconds() }) afterAll(done => exec('docker kill scraper_test_db', done)) describe('courses endpoint', () => { test('/courses succeeds', async () => { const response = await request(app).get('/courses') expect(response.type).toBe('application/json') expect(response.statusCode).toBe(200) }) test('/courses returns an Array', async () => { const response = await request(app).get('/courses') expect(Array.isArray(response.body)).toBeTruthy() }) }) function twoSeconds () { return new Promise(resolve => { setTimeout(() => { resolve() }, 2000) }) }
/* eslint-env jest */ const util = require('util') const exec = util.promisify(require('child_process').exec) const request = require('supertest') let app // start a mongo instance loaded with test data using docker beforeAll(async () => { await exec('docker run --name scraper_test_db -d --rm -p 27017:27017 mongo') await exec('docker cp __tests__/dump/ scraper_test_db:/dump') await exec('docker exec scraper_test_db mongorestore /dump') app = require('../app') await twoSeconds() }) afterAll(done => exec('docker kill scraper_test_db', done)) describe('courses endpoint', () => { test('/courses succeeds', async () => { const response = await request(app).get('/courses') expect(response.type).toBe('application/json') expect(response.statusCode).toBe(200) }) test('/courses returns an Array', async () => { const response = await request(app).get('/courses') expect(Array.isArray(response.body)).toBeTruthy() }) }) function twoSeconds () { return new Promise(resolve => { setTimeout(() => { resolve() }, 2000) }) }
Test db should have data now
Test db should have data now Didn’t realize that child_process functions don’t return promises
JavaScript
apache-2.0
classmere/api
--- +++ @@ -1,15 +1,16 @@ /* eslint-env jest */ -const { exec } = require('child_process') +const util = require('util') +const exec = util.promisify(require('child_process').exec) const request = require('supertest') let app // start a mongo instance loaded with test data using docker beforeAll(async () => { await exec('docker run --name scraper_test_db -d --rm -p 27017:27017 mongo') - await exec('docker cp dump/ scraper_test_db:/dump') + await exec('docker cp __tests__/dump/ scraper_test_db:/dump') await exec('docker exec scraper_test_db mongorestore /dump') - app = await require('../app') + app = require('../app') await twoSeconds() })
3797f5b68e1426135dbc60729610087a3502d2ed
spec/install/get-email-spec.js
spec/install/get-email-spec.js
'use strict'; const fs = require('fs'); const GetEmail = require('../../lib/install/get-email'); describe('GetEmail', () => { let step; beforeEach(() => { step = new GetEmail(); }); describe('.start()', () => { describe('when the user has a .gitconfig file', () => { beforeEach(() => { spyOn(fs, 'readFileSync').andReturn(`[user] email = some.email@company.com`); }); it('returns a promise that is resolved with the user email', () => { waitsForPromise(() => step.start().then(data => { expect(data.email).toEqual('some.email@company.com'); })); }); }); describe('when the user has a .gitconfig file without an email', () => { beforeEach(() => { spyOn(fs, 'readFileSync').andReturn(''); }); it('returns a promise that is resolved with null', () => { waitsForPromise(() => step.start().then(data => { expect(data).toEqual({email: undefined}); })); }); }); describe('when the user has no .gitconfig file', () => { beforeEach(() => { spyOn(fs, 'readFileSync').andCallFake(() => { throw new Error(); }); }); it('returns a promise that is resolved with null', () => { waitsForPromise(() => step.start().then(data => { expect(data).toEqual({email: undefined}); })); }); }); }); });
'use strict'; const fs = require('fs'); const GetEmail = require('../../lib/install/get-email'); describe('GetEmail', () => { let step; beforeEach(() => { step = new GetEmail(); }); describe('.start()', () => { afterEach(() => { fs.readFileSync.andCallThrough(); }); describe('when the user has a .gitconfig file', () => { beforeEach(() => { spyOn(fs, 'readFileSync').andReturn(`[user] email = some.email@company.com`); }); it('returns a promise that is resolved with the user email', () => { waitsForPromise(() => step.start().then(data => { expect(data.email).toEqual('some.email@company.com'); })); }); }); describe('when the user has a .gitconfig file without an email', () => { beforeEach(() => { spyOn(fs, 'readFileSync').andReturn(''); }); it('returns a promise that is resolved with null', () => { waitsForPromise(() => step.start().then(data => { expect(data).toEqual({email: undefined}); })); }); }); describe('when the user has no .gitconfig file', () => { beforeEach(() => { spyOn(fs, 'readFileSync').andCallFake(() => { throw new Error(); }); }); it('returns a promise that is resolved with null', () => { waitsForPromise(() => step.start().then(data => { expect(data).toEqual({email: undefined}); })); }); }); }); });
Fix tests relying on fs spies
:green_heart: Fix tests relying on fs spies
JavaScript
bsd-3-clause
kiteco/kite-installer
--- +++ @@ -11,6 +11,10 @@ }); describe('.start()', () => { + afterEach(() => { + fs.readFileSync.andCallThrough(); + }); + describe('when the user has a .gitconfig file', () => { beforeEach(() => { spyOn(fs, 'readFileSync').andReturn(`[user]
f22f904a07059b3060d6818b926ec6aaf9571f71
src/operator/create/fromArray.js
src/operator/create/fromArray.js
const fromArray = array => createObservable((push, end) => { array.forEach(value => { push(value); }); end(); });
const fromArray = array => createObservable((push, end) => { if (array == null) { array = []; } array.forEach(value => { push(value); }); end(); });
Allow observable creation with no argument
Allow observable creation with no argument
JavaScript
mit
hhelwich/observable,hhelwich/observable
--- +++ @@ -1,4 +1,7 @@ const fromArray = array => createObservable((push, end) => { + if (array == null) { + array = []; + } array.forEach(value => { push(value); }); end(); });
ffb8c1d6a86d60ebc6306db8e46762c480512f7f
interface_config.js
interface_config.js
var interfaceConfig = { CANVAS_EXTRA: 104, CANVAS_RADIUS: 7, SHADOW_COLOR: '#00ccff', INITIAL_TOOLBAR_TIMEOUT: 20000, TOOLBAR_TIMEOUT: 4000, DEFAULT_REMOTE_DISPLAY_NAME: "Fellow Jitster", DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME: "Speaker", SHOW_JITSI_WATERMARK: true, JITSI_WATERMARK_LINK: "http://jitsi.org", SHOW_BRAND_WATERMARK: false, BRAND_WATERMARK_LINK: "", SHOW_POWERED_BY: false, GENERATE_ROOMNAMES_ON_WELCOME_PAGE: true };
var interfaceConfig = { CANVAS_EXTRA: 104, CANVAS_RADIUS: 7, SHADOW_COLOR: '#ffffff', INITIAL_TOOLBAR_TIMEOUT: 20000, TOOLBAR_TIMEOUT: 4000, DEFAULT_REMOTE_DISPLAY_NAME: "Fellow Jitster", DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME: "Speaker", SHOW_JITSI_WATERMARK: true, JITSI_WATERMARK_LINK: "http://jitsi.org", SHOW_BRAND_WATERMARK: false, BRAND_WATERMARK_LINK: "", SHOW_POWERED_BY: false, GENERATE_ROOMNAMES_ON_WELCOME_PAGE: true };
Change the color of the audio levels indicator.
Change the color of the audio levels indicator.
JavaScript
apache-2.0
dwanghf/jitsi-meet,jitsi/jitsi-meet,bgrozev/jitsi-meet,nwittstruck/jitsi-meet,bgrozev/jitsi-meet,learnium/jitsi-meet,gerges/jitsi-meet,gerges/jitsi-meet,gpolitis/jitsi-meet,Aharobot/jitsi-meet,bickelj/jitsi-meet,JiYou/jitsi-meet,IpexCloud/jitsi-meet,dyweb/jitsi-meet,luciash/jitsi-meet-bootstrap,gpolitis/jitsi-meet,gpolitis/jitsi-meet,pstros/jitsi-meet,kosmosby/jitsi-meet,dyweb/jitsi-meet,gpolitis/jitsi-meet,JiYou/jitsi-meet,bhatvv/jitsi-meet,kosmosby/jitsi-meet,bgrozev/jitsi-meet,dyweb/jitsi-meet,bhatvv/jitsi-meet,pstros/jitsi-meet,micahflee/jitsi-meet,gpolitis/jitsi-meet,learnium/jitsi-meet,isymchych/jitsi-meet,NxTec/jitsi-meet,procandi/jitsi-meet,jitsi/jitsi-meet,procandi/jitsi-meet,buzzyboy/jitsi-meet,jitsi/jitsi-meet,tsunli/jitsi-meet,bgrozev/jitsi-meet,buzzyboy/jitsi-meet,NxTec/jitsi-meet,IpexCloud/jitsi-meet,bgrozev/jitsi-meet,isymchych/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,bickelj/jitsi-meet,tsareg/jitsi-meet,tsunli/jitsi-meet,learnium/jitsi-meet,b100w11/jitsi-meet,dwanghf/jitsi-meet,luciash/jitsi-meet-bootstrap,buzzyboy/jitsi-meet,b100w11/jitsi-meet,jitsi/jitsi-meet,magatz/jitsi-meet-mod,Aharobot/jitsi-meet,micahflee/jitsi-meet,jitsi/jitsi-meet,gerges/jitsi-meet,kosmosby/jitsi-meet,jitsi/jitsi-meet,Aharobot/jitsi-meet,procandi/jitsi-meet,bhatvv/jitsi-meet,magatz/jitsi-meet-mod,gpolitis/jitsi-meet,tsunli/jitsi-meet,gpolitis/jitsi-meet,dwanghf/jitsi-meet,NxTec/jitsi-meet,bgrozev/jitsi-meet,JiYou/jitsi-meet,tsareg/jitsi-meet,jitsi/jitsi-meet,b100w11/jitsi-meet
--- +++ @@ -1,7 +1,7 @@ var interfaceConfig = { CANVAS_EXTRA: 104, CANVAS_RADIUS: 7, - SHADOW_COLOR: '#00ccff', + SHADOW_COLOR: '#ffffff', INITIAL_TOOLBAR_TIMEOUT: 20000, TOOLBAR_TIMEOUT: 4000, DEFAULT_REMOTE_DISPLAY_NAME: "Fellow Jitster",
bc861e0d9ac49bbba0fdd4288f67463a9aca36af
lib/builder-registry.js
lib/builder-registry.js
'use babel' import fs from 'fs-plus' import path from 'path' export default class BuilderRegistry { getBuilder (filePath) { const builders = this.getAllBuilders() const candidates = builders.filter((builder) => builder.canProcess(filePath)) switch (candidates.length) { case 0: return null case 1: return candidates[0] } return this.resolveAmbigiousBuilders(candidates) } getAllBuilders () { const moduleDir = path.join(__dirname, 'builders') const entries = fs.readdirSync(moduleDir) const builders = entries.map((entry) => require(path.join(moduleDir, entry))) return builders } resolveAmbigiousBuilders (builders) { const names = builders.map((builder) => builder.name) const indexOfLatexmk = names.indexOf('LatexmkBuilder') const indexOfTexify = names.indexOf('TexifyBuilder') if (names.length === 2 && indexOfLatexmk >= 0 && indexOfTexify >= 0) { switch (atom.config.get('latex.builder')) { case 'latexmk': return builders[indexOfLatexmk] case 'texify': return builders[indexOfTexify] } } throw Error('Unable to resolve ambigous builder registration') } }
'use babel' import _ from 'lodash' import fs from 'fs-plus' import path from 'path' import MagicParser from './parsers/magic-parser' export default class BuilderRegistry { getBuilder (filePath) { const builders = this.getAllBuilders() const candidates = builders.filter((builder) => builder.canProcess(filePath)) switch (candidates.length) { case 0: return null case 1: return candidates[0] } return this.resolveAmbiguousBuilders(candidates, this.getBuilderFromMagic(filePath)) } getBuilderFromMagic (filePath) { const magic = new MagicParser(filePath).parse() if (magic && magic.builder) { return magic.builder } return null } getAllBuilders () { const moduleDir = path.join(__dirname, 'builders') const entries = fs.readdirSync(moduleDir) const builders = entries.map((entry) => require(path.join(moduleDir, entry))) return builders } resolveAmbiguousBuilders (builders, builderOverride) { const name = builderOverride || atom.config.get('latex.builder') const namePattern = new RegExp(`^${name}Builder$`, 'i') const builder = _.find(builders, builder => builder.name.match(namePattern)) if (builder) return builder latex.log.warning(`Unable to resolve builder named ${name} using fallback ${builders[0].name}.`) return builders[0] } }
Use TeX magic to allow bulder override
Use TeX magic to allow bulder override
JavaScript
mit
thomasjo/atom-latex,thomasjo/atom-latex,thomasjo/atom-latex
--- +++ @@ -1,7 +1,9 @@ 'use babel' +import _ from 'lodash' import fs from 'fs-plus' import path from 'path' +import MagicParser from './parsers/magic-parser' export default class BuilderRegistry { getBuilder (filePath) { @@ -12,7 +14,16 @@ case 1: return candidates[0] } - return this.resolveAmbigiousBuilders(candidates) + return this.resolveAmbiguousBuilders(candidates, this.getBuilderFromMagic(filePath)) + } + + getBuilderFromMagic (filePath) { + const magic = new MagicParser(filePath).parse() + if (magic && magic.builder) { + return magic.builder + } + + return null } getAllBuilders () { @@ -23,17 +34,14 @@ return builders } - resolveAmbigiousBuilders (builders) { - const names = builders.map((builder) => builder.name) - const indexOfLatexmk = names.indexOf('LatexmkBuilder') - const indexOfTexify = names.indexOf('TexifyBuilder') - if (names.length === 2 && indexOfLatexmk >= 0 && indexOfTexify >= 0) { - switch (atom.config.get('latex.builder')) { - case 'latexmk': return builders[indexOfLatexmk] - case 'texify': return builders[indexOfTexify] - } - } + resolveAmbiguousBuilders (builders, builderOverride) { + const name = builderOverride || atom.config.get('latex.builder') + const namePattern = new RegExp(`^${name}Builder$`, 'i') + const builder = _.find(builders, builder => builder.name.match(namePattern)) - throw Error('Unable to resolve ambigous builder registration') + if (builder) return builder + + latex.log.warning(`Unable to resolve builder named ${name} using fallback ${builders[0].name}.`) + return builders[0] } }
43d297eadf58327bfefe81ced42bdb23099548fe
lib/dujs/domainscope.js
lib/dujs/domainscope.js
/* * DomainScope module * @lastmodifiedBy ChengFuLin(chengfulin0806@gmail.com) * @lastmodifiedDate 2015-07-28 */ var Scope = require('./scope'); /** * DomainScope * @param {Object} cfg Graph of the domain scope * @constructor */ function DomainScope(cfg) { "use strict"; Scope.call(this, cfg, Scope.DOMAIN_SCOPE_NAME, Scope.DOMAIN_TYPE, null); } DomainScope.prototype = Object.create(Scope.prototype); Object.defineProperty(DomainScope.prototype, 'constructor', { value: DomainScope }); /* start-public-data-members */ Object.defineProperties(DomainScope.prototype, { /** * Array of build-in objects * @type {Array} * @memberof DomainScope.prototype * @inheritdoc */ builtInObjects: { get: function () { "use strict"; /* manual */ return [ {name: "localStorage", def: "localStorage"} ]; } } }); /* end-public-data-members */ module.exports = DomainScope;
/* * DomainScope module * @lastmodifiedBy ChengFuLin(chengfulin0806@gmail.com) * @lastmodifiedDate 2015-07-28 */ var Scope = require('./scope'); /** * DomainScope * @constructor */ function DomainScope() { "use strict"; Scope.call(this, null, Scope.DOMAIN_SCOPE_NAME, Scope.DOMAIN_TYPE, null); } DomainScope.prototype = Object.create(Scope.prototype); Object.defineProperty(DomainScope.prototype, 'constructor', { value: DomainScope }); /* start-public-data-members */ Object.defineProperties(DomainScope.prototype, { /** * Array of build-in objects * @type {Array} * @memberof DomainScope.prototype * @inheritdoc */ builtInObjects: { get: function () { "use strict"; /* manual */ return [ {name: "localStorage", def: "localStorage"} ]; } } }); /* end-public-data-members */ module.exports = DomainScope;
Refactor to be constructed without parameters
Refactor to be constructed without parameters
JavaScript
mit
chengfulin/dujs,chengfulin/dujs
--- +++ @@ -7,12 +7,11 @@ /** * DomainScope - * @param {Object} cfg Graph of the domain scope * @constructor */ -function DomainScope(cfg) { +function DomainScope() { "use strict"; - Scope.call(this, cfg, Scope.DOMAIN_SCOPE_NAME, Scope.DOMAIN_TYPE, null); + Scope.call(this, null, Scope.DOMAIN_SCOPE_NAME, Scope.DOMAIN_TYPE, null); } DomainScope.prototype = Object.create(Scope.prototype);
1624dadd1dd621ae631e73db85385dce79138d71
lib/material/endgame.js
lib/material/endgame.js
'use strict'; var generate = require('../generate'); exports.endgames = [ 'nefarious purposes', 'a Washington takeover', 'a terrorist plot', 'world domination', 'a plot against the queen' ]; exports.get = generate.random(exports.endgames);
'use strict'; var generate = require('../generate'); exports.endgames = [ 'a plot against the queen', 'a terrorist plot', 'a Washington takeover', 'nefarious purposes', 'world domination', ]; exports.get = generate.random(exports.endgames);
Make sorting and trailing commas consistent
Make sorting and trailing commas consistent
JavaScript
mit
rowanmanning/conspire
--- +++ @@ -3,11 +3,11 @@ var generate = require('../generate'); exports.endgames = [ + 'a plot against the queen', + 'a terrorist plot', + 'a Washington takeover', 'nefarious purposes', - 'a Washington takeover', - 'a terrorist plot', 'world domination', - 'a plot against the queen' ]; exports.get = generate.random(exports.endgames);
8e44baa3db6723dd83cf8bd5d9686c3d2eb33be1
src/lib/Knekt.js
src/lib/Knekt.js
/** * Created by Alex on 29/01/2017. */ import Hapi from 'hapi'; export class Knekt { constructor() { this._server = new Hapi.Server(); this.plugins = []; } setConnection(host, port) { this._server.connection({host: host, port: port}); } listen() { this._server.start((err) => { if (err) { throw err; } console.log(`Knekt running at ${this._server.info.uri} !`); }); } register(plugins) { plugins.forEach((plugin) => { this.plugins.push(new plugin(this)); }); } addRoute(parameters) { this._server.route(parameters); } }
/** * Created by Alex on 29/01/2017. */ import Hapi from 'hapi'; //core routes import Descriptor from './routes/descriptor'; export class Knekt { constructor() { this._server = new Hapi.Server(); this.plugins = []; } setConnection(host, port) { this._server.connection({host: host, port: port}); } listen() { this._server.start((err) => { if (err) { throw err; } this._registerCoreRoutes(); console.log(`Knekt running at ${this._server.info.uri} !`); }); } register(plugins) { plugins.forEach((plugin) => { this.plugins.push(new plugin(this).properties); }); } addRoute(parameters) { this._server.route(parameters); } _registerCoreRoutes() { this._server.route(Descriptor(this)); } }
Update to register descriptor route
Update to register descriptor route
JavaScript
mit
goKnekt/Knekt-Server
--- +++ @@ -2,6 +2,9 @@ * Created by Alex on 29/01/2017. */ import Hapi from 'hapi'; + + //core routes + import Descriptor from './routes/descriptor'; export class Knekt { constructor() { @@ -18,17 +21,22 @@ if (err) { throw err; } + this._registerCoreRoutes(); console.log(`Knekt running at ${this._server.info.uri} !`); }); } register(plugins) { plugins.forEach((plugin) => { - this.plugins.push(new plugin(this)); + this.plugins.push(new plugin(this).properties); }); } addRoute(parameters) { this._server.route(parameters); } + + _registerCoreRoutes() { + this._server.route(Descriptor(this)); + } }
0575210aeacc6a984df7a9b9224154a5900d3ad8
src/components/PlaylistManager/Panel/ShufflePlaylistButton.js
src/components/PlaylistManager/Panel/ShufflePlaylistButton.js
import React from 'react'; import PropTypes from 'prop-types'; import { useTranslator } from '@u-wave/react-translate'; import CircularProgress from '@material-ui/core/CircularProgress'; import Tooltip from '@material-ui/core/Tooltip'; import IconButton from '@material-ui/core/IconButton'; import ShuffleIcon from '@material-ui/icons/Shuffle'; const { useCallback, useState } = React; const HARDCODED_LOADING_SIZE = 24; // FIXME derive this from some mui property? function ShuffleButton({ onShuffle }) { const [isLoading, setLoading] = useState(false); const { t } = useTranslator(); const onClick = useCallback(() => { setLoading(true); onShuffle().finally(() => { setTimeout(() => { setLoading(false); }, 10000); }); }, [onShuffle]); return ( <Tooltip title={t('playlists.shuffle')} placement="top"> <IconButton className="PlaylistMeta-iconButton" onClick={onClick} > {isLoading ? ( <CircularProgress size={HARDCODED_LOADING_SIZE} /> ) : ( <ShuffleIcon /> )} </IconButton> </Tooltip> ); } ShuffleButton.propTypes = { onShuffle: PropTypes.func.isRequired, }; export default ShuffleButton;
import React from 'react'; import PropTypes from 'prop-types'; import { useTranslator } from '@u-wave/react-translate'; import CircularProgress from '@material-ui/core/CircularProgress'; import Tooltip from '@material-ui/core/Tooltip'; import IconButton from '@material-ui/core/IconButton'; import ShuffleIcon from '@material-ui/icons/Shuffle'; const { useCallback, useState } = React; const HARDCODED_LOADING_SIZE = 24; // FIXME derive this from some mui property? function ShuffleButton({ onShuffle }) { const [isLoading, setLoading] = useState(false); const { t } = useTranslator(); const onClick = useCallback(() => { setLoading(true); onShuffle().finally(() => { setLoading(false); }); }, [onShuffle]); return ( <Tooltip title={t('playlists.shuffle')} placement="top"> <IconButton className="PlaylistMeta-iconButton" onClick={onClick} > {isLoading ? ( <CircularProgress size={HARDCODED_LOADING_SIZE} /> ) : ( <ShuffleIcon /> )} </IconButton> </Tooltip> ); } ShuffleButton.propTypes = { onShuffle: PropTypes.func.isRequired, }; export default ShuffleButton;
Remove setTimeout left over from debugging.
Remove setTimeout left over from debugging.
JavaScript
mit
u-wave/web,u-wave/web
--- +++ @@ -16,9 +16,7 @@ const onClick = useCallback(() => { setLoading(true); onShuffle().finally(() => { - setTimeout(() => { - setLoading(false); - }, 10000); + setLoading(false); }); }, [onShuffle]);
202038131d2843815c5062950e4dd14dfb8cac6c
src/app/relay/TeamMenuRelay.js
src/app/relay/TeamMenuRelay.js
import React, { Component, PropTypes } from 'react'; import Relay from 'react-relay'; import TeamRoute from './TeamRoute'; import Can from '../components/Can'; import CheckContext from '../CheckContext'; import { teamSubdomain } from '../helpers'; class TeamMenu extends Component { render() { const { team } = this.props; const history = new CheckContext(this).getContextStore().history; return ( <Can permissions={team.permissions} permission="update Team"> <li className="header-actions__menu-item" onClick={history.push.bind(this, '/members')}>Manage team...</li> </Can> ); } } TeamMenu.contextTypes = { store: React.PropTypes.object }; const TeamMenuContainer = Relay.createContainer(TeamMenu, { fragments: { team: () => Relay.QL` fragment on Team { id, dbid, name, permissions, } ` }, }); class TeamMenuRelay extends Component { render() { if (teamSubdomain()) { const route = new TeamRoute({ teamId: '' }); return (<Relay.RootContainer Component={TeamMenuContainer} route={route} />); } else { return null; } } } export default TeamMenuRelay;
import React, { Component, PropTypes } from 'react'; import Relay from 'react-relay'; import TeamRoute from './TeamRoute'; import Can from '../components/Can'; import CheckContext from '../CheckContext'; import { teamSubdomain } from '../helpers'; class TeamMenu extends Component { render() { const { team } = this.props; const history = new CheckContext(this).getContextStore().history; return ( <Can permissions={team.permissions} permission="update Team"> <li className="header-actions__menu-item" onClick={history.push.bind(this, '/members')}>Manage team</li> </Can> ); } } TeamMenu.contextTypes = { store: React.PropTypes.object }; const TeamMenuContainer = Relay.createContainer(TeamMenu, { fragments: { team: () => Relay.QL` fragment on Team { id, dbid, name, permissions, } ` }, }); class TeamMenuRelay extends Component { render() { if (teamSubdomain()) { const route = new TeamRoute({ teamId: '' }); return (<Relay.RootContainer Component={TeamMenuContainer} route={route} />); } else { return null; } } } export default TeamMenuRelay;
Update copy for team management link
Update copy for team management link
JavaScript
mit
meedan/check-web,meedan/check-web,meedan/check-web
--- +++ @@ -12,7 +12,7 @@ return ( <Can permissions={team.permissions} permission="update Team"> - <li className="header-actions__menu-item" onClick={history.push.bind(this, '/members')}>Manage team...</li> + <li className="header-actions__menu-item" onClick={history.push.bind(this, '/members')}>Manage team</li> </Can> ); }
c19971d7e5d141af526645118f9e909545178047
client.js
client.js
var CodeMirror = require('codemirror') , bindCodemirror = require('gulf-codemirror') module.exports = setup module.exports.consumes = ['editor'] module.exports.provides = [] function setup(plugin, imports, register) { var editor = imports.editor editor.registerEditor('CodeMirror', 'text', 'An extensible and performant code editor' , function(editorEl) { var cm = CodeMirror(function(el) { editorEl.appendChild(el) el.style['height'] = '100%' el.style['width'] = '100%' }) editorEl.style['height'] = '100%' return bindCodemirror(cm) }) register() }
var CodeMirror = require('codemirror') , bindCodemirror = require('gulf-codemirror') module.exports = setup module.exports.consumes = ['editor'] module.exports.provides = [] function setup(plugin, imports, register) { var editor = imports.editor editor.registerEditor('CodeMirror', 'text', 'An extensible and performant code editor' , function(editorEl) { var cm = CodeMirror(function(el) { editorEl.appendChild(el) el.style['height'] = '100%' el.style['width'] = '100%' }) editorEl.style['height'] = '100%' return Promise.resolve(bindCodemirror(cm)) }) register() }
Fix setup function: Should return promise
Fix setup function: Should return promise
JavaScript
mpl-2.0
hivejs/hive-editor-text-codemirror
--- +++ @@ -18,7 +18,7 @@ editorEl.style['height'] = '100%' - return bindCodemirror(cm) + return Promise.resolve(bindCodemirror(cm)) }) register() }
f066554b77700604f9f5e8de76e2c976d91ab7b0
feature-detects/css/shapes.js
feature-detects/css/shapes.js
define(['Modernizr', 'createElement', 'docElement'], function( Modernizr, createElement, docElement ) { // http://www.w3.org/TR/css3-exclusions // http://www.w3.org/TR/css3-exclusions/#shapes // Examples: http://html.adobe.com/webstandards/cssexclusions // Separate test for CSS shapes as WebKit has just implemented this alone Modernizr.addTest('shapes', function () { var prefixedProperty = Modernizr.prefixed('shapeInside'); if (!prefixedProperty) return false; var shapeInsideProperty = prefixedProperty.replace(/([A-Z])/g, function (str, m1) { return '-' + m1.toLowerCase(); }).replace(/^ms-/, '-ms-'); return Modernizr.testStyles('#modernizr { ' + shapeInsideProperty + ':rectangle(0,0,0,0) }', function (elem) { // Check against computed value var styleObj = window.getComputedStyle ? getComputedStyle(elem, null) : elem.currentStyle; return styleObj[prefixed('shapeInside', docElement.style, false)] == 'rectangle(0px, 0px, 0px, 0px)'; }); }); });
define(['Modernizr', 'createElement', 'docElement', 'prefixed', 'testStyles'], function( Modernizr, createElement, docElement, prefixed, testStyles ) { // http://www.w3.org/TR/css3-exclusions // http://www.w3.org/TR/css3-exclusions/#shapes // Examples: http://html.adobe.com/webstandards/cssexclusions // Separate test for CSS shapes as WebKit has just implemented this alone Modernizr.addTest('shapes', function () { var prefixedProperty = prefixed('shapeInside'); if (!prefixedProperty) return false; var shapeInsideProperty = prefixedProperty.replace(/([A-Z])/g, function (str, m1) { return '-' + m1.toLowerCase(); }).replace(/^ms-/, '-ms-'); return testStyles('#modernizr { ' + shapeInsideProperty + ':rectangle(0,0,0,0) }', function (elem) { // Check against computed value var styleObj = window.getComputedStyle ? getComputedStyle(elem, null) : elem.currentStyle; return styleObj[prefixed('shapeInside', docElement.style, false)] == 'rectangle(0px, 0px, 0px, 0px)'; }); }); });
Add testStyles and prefixed to the depedencies.
Add testStyles and prefixed to the depedencies.
JavaScript
mit
Modernizr/Modernizr,Modernizr/Modernizr
--- +++ @@ -1,17 +1,17 @@ -define(['Modernizr', 'createElement', 'docElement'], function( Modernizr, createElement, docElement ) { +define(['Modernizr', 'createElement', 'docElement', 'prefixed', 'testStyles'], function( Modernizr, createElement, docElement, prefixed, testStyles ) { // http://www.w3.org/TR/css3-exclusions // http://www.w3.org/TR/css3-exclusions/#shapes // Examples: http://html.adobe.com/webstandards/cssexclusions // Separate test for CSS shapes as WebKit has just implemented this alone Modernizr.addTest('shapes', function () { - var prefixedProperty = Modernizr.prefixed('shapeInside'); + var prefixedProperty = prefixed('shapeInside'); if (!prefixedProperty) return false; var shapeInsideProperty = prefixedProperty.replace(/([A-Z])/g, function (str, m1) { return '-' + m1.toLowerCase(); }).replace(/^ms-/, '-ms-'); - return Modernizr.testStyles('#modernizr { ' + shapeInsideProperty + ':rectangle(0,0,0,0) }', function (elem) { + return testStyles('#modernizr { ' + shapeInsideProperty + ':rectangle(0,0,0,0) }', function (elem) { // Check against computed value var styleObj = window.getComputedStyle ? getComputedStyle(elem, null) : elem.currentStyle; return styleObj[prefixed('shapeInside', docElement.style, false)] == 'rectangle(0px, 0px, 0px, 0px)';
60cda85ccf90bae9911ba49a710f2f10f79dab3c
funnel/assets/js/rsvp_list.js
funnel/assets/js/rsvp_list.js
import 'footable'; $(() => { $('.participants').footable({ sorting: { enabled: true, }, }); });
import 'footable'; $(() => { $('.participants').footable({ paginate: false, sorting: true, }); });
Disable pagination in rsvp page
Disable pagination in rsvp page
JavaScript
agpl-3.0
hasgeek/funnel,hasgeek/funnel,hasgeek/funnel,hasgeek/funnel,hasgeek/funnel
--- +++ @@ -2,8 +2,7 @@ $(() => { $('.participants').footable({ - sorting: { - enabled: true, - }, + paginate: false, + sorting: true, }); });
b98a7e399a90115907fd13e5edbeb28475c4ed3e
public/scripts/global.js
public/scripts/global.js
App.populator('feed', function (page, data) { $(page).find('.app-title').text(data.title); $.getJSON('/data/feed/' + data.id + '/articles', function (articles) { articles.forEach(function (article) { var li = $('<li class="app-button">' + article.title + '</li>'); li.on('click', function () { App.load('article', article); }); $(page).find('.app-list').append(li); }); }); }); App.populator('article', function (page, data) { $(page).find('.app-title').text(data.title.substring(0, 20)); $.getJSON('/data/article/' + data.url, function (article) { var content = '<p><strong>' + article.title + '</strong><br/>' + '<a href="' + article.url + '">' + article.url + '</a></p>' + article.content; $(page).find('.app-content').html(content); }); });
App.populator('feed', function (page, data) { $(page).find('.app-title').text(data.title); $.getJSON('/data/feed/' + data.id + '/articles', function (articles) { articles.forEach(function (article) { var li = $('<li class="app-button">' + article.title + '</li>'); li.on('click', function () { App.load('article', article); }); $(page).find('.app-list').append(li); }); }); }); App.populator('article', function (page, data) { $(page).find('.app-title').text(data.title.substring(0, 30)); $.getJSON('/data/article/' + data.url, function (article) { var content = '<p><strong>' + article.title + '</strong><br/>' + '<a href="' + article.url + '">' + article.url + '</a></p>' + article.content; $(page).find('.app-content').html(content); }); });
Change title limit to 30 chars.
Change title limit to 30 chars.
JavaScript
mit
cliffano/feedpaper,cliffano/feedpaper,cliffano/feedpaper
--- +++ @@ -12,7 +12,7 @@ }); App.populator('article', function (page, data) { - $(page).find('.app-title').text(data.title.substring(0, 20)); + $(page).find('.app-title').text(data.title.substring(0, 30)); $.getJSON('/data/article/' + data.url, function (article) { var content = '<p><strong>' + article.title + '</strong><br/>' +
26c03b575dad5dbe4720b147279bdadde24f0748
packages/postcss-merge-longhand/src/index.js
packages/postcss-merge-longhand/src/index.js
import postcss from 'postcss'; import margin from './lib/decl/margin'; import padding from './lib/decl/padding'; import borders from './lib/decl/borders'; import columns from './lib/decl/columns'; const processors = [ margin, padding, borders, columns, ]; export default postcss.plugin('postcss-merge-longhand', () => { return css => { let abort = false; css.walkRules(rule => { processors.forEach(p => { const res = p.explode(rule); if (res === false) { abort = true; } }); if (abort) { return; } processors.slice().reverse().forEach(p => p.merge(rule)); }); }; });
import postcss from 'postcss'; import margin from './lib/decl/margin'; import padding from './lib/decl/padding'; import borders from './lib/decl/borders'; import columns from './lib/decl/columns'; const processors = [ margin, padding, borders, columns, ]; export default postcss.plugin('postcss-merge-longhand', () => { return css => { css.walkRules(rule => { let abort = false; processors.forEach(p => { const res = p.explode(rule); if (typeof res === 'boolean') { abort = true; } }); if (abort) { return; } processors.slice().reverse().forEach(p => p.merge(rule)); }); }; });
Resolve issue with running plugin on multiple rules.
Resolve issue with running plugin on multiple rules.
JavaScript
mit
ben-eb/cssnano
--- +++ @@ -13,11 +13,11 @@ export default postcss.plugin('postcss-merge-longhand', () => { return css => { - let abort = false; css.walkRules(rule => { + let abort = false; processors.forEach(p => { const res = p.explode(rule); - if (res === false) { + if (typeof res === 'boolean') { abort = true; } });
28320eeeb420ce13c5e00d670a82aab889ecc5c6
app/assets/javascripts/main.js
app/assets/javascripts/main.js
"use strict"; $(document).on("turbolinks:load", function() { //equivalent of $(document).ready() console.log("JS loaded.") addSpace(); var $grid = initMasonry(); // layout Masonry after each image loads $grid.imagesLoaded().progress( function() { $grid.masonry('layout'); }); }); function initMasonry() { return $('.masonry-grid').masonry({ //returns the jquery masonry grid to be stored as a variable // options itemSelector: '.card', // columnWidth: 280, //with no columnWidth set, will take size of first element in grid horizontalOrder: true, isFitWidth: true, //breaks columns like media queries gutter: 20, transitionDuration: '0.3s' }); } function addSpace() { var spaceBetween = $(".custom-footer").offset().top - $(".navbar").offset().top; //get space between header and footer var target = 600; if (spaceBetween < target) { //if space between header and footer < x var numOfSpaces = (target - spaceBetween) / 35; for(var i = 0; i < numOfSpaces; i++) { $("#main-container").append("<p>&nbsp</p>"); //add space above footer } } }
"use strict"; $(document).on("ready turbolinks:load", function() { //equivalent of $(document).ready() console.log("JS loaded.") addSpace(); var $grid = initMasonry(); // layout Masonry after each image loads $grid.imagesLoaded().progress( function() { $grid.masonry('layout'); }); }); function initMasonry() { return $('.masonry-grid').masonry({ //returns the jquery masonry grid to be stored as a variable // options itemSelector: '.card', // columnWidth: 280, //with no columnWidth set, will take size of first element in grid horizontalOrder: true, isFitWidth: true, //breaks columns like media queries gutter: 20, transitionDuration: '0.3s' }); } function addSpace() { var spaceBetween = $(".custom-footer").offset().top - $(".navbar").offset().top; //get space between header and footer var target = 600; if (spaceBetween < target) { //if space between header and footer < x var numOfSpaces = (target - spaceBetween) / 35; for(var i = 0; i < numOfSpaces; i++) { $("#main-container").append("<p>&nbsp</p>"); //add space above footer } } }
Adjust JS document ready function
Adjust JS document ready function
JavaScript
mit
MitulMistry/rails-storyplan,MitulMistry/rails-storyplan,MitulMistry/rails-storyplan
--- +++ @@ -1,6 +1,6 @@ "use strict"; -$(document).on("turbolinks:load", function() { //equivalent of $(document).ready() +$(document).on("ready turbolinks:load", function() { //equivalent of $(document).ready() console.log("JS loaded.") addSpace(); var $grid = initMasonry();
8d3779a37df7d199753e350b83bbe884fdae8fa8
sencha-workspace/SlateAdmin/app/model/person/progress/NoteRecipient.js
sencha-workspace/SlateAdmin/app/model/person/progress/NoteRecipient.js
/*jslint browser: true, undef: true, white: false, laxbreak: true *//*global Ext,Slate*/ Ext.define('SlateAdmin.model.person.progress.NoteRecipient', { extend: 'Ext.data.Model', idProperty: 'ID', groupField: 'RelationshipGroup', fields: [ 'FullName', 'Email', 'Label', 'Status', { name: 'selected', type: 'boolean', convert: function (v, record) { var selected = !Ext.isEmpty(record.get('Status')); return selected; } }, { name: 'PersonID', type: 'integer' }, { name: 'RelationshipGroup', convert: function (v) { return v ? v : 'Other'; } }, { name: 'ID', type: 'integer' } ], proxy: { type: 'slaterecords', api: { read: '/notes/progress/recipients', update: '/notes/save', create: '/notes/save', destory: '/notes/save' }, reader: { type: 'json', rootProperty: 'data' }, writer: { type: 'json', rootProperty: 'data', writeAllFields: false, allowSingle: false } } });
/*jslint browser: true, undef: true, white: false, laxbreak: true *//*global Ext,Slate*/ Ext.define('SlateAdmin.model.person.progress.NoteRecipient', { extend: 'Ext.data.Model', idProperty: 'ID', groupField: 'RelationshipGroup', fields: [ 'FullName', 'Email', 'Label', 'Status', { name: 'selected', type: 'boolean', convert: function (v, record) { var selected = !Ext.isEmpty(record.get('Status')); return selected; } }, { name: 'PersonID', type: 'integer' }, { name: 'RelationshipGroup', convert: function (v) { return v ? v : 'Other'; } }, { name: 'ID', type: 'integer' } ], proxy: { type: 'slaterecords', startParam: null, limitParam: null, api: { read: '/notes/progress/recipients', update: '/notes/save', create: '/notes/save', destory: '/notes/save' }, reader: { type: 'json', rootProperty: 'data' }, writer: { type: 'json', rootProperty: 'data', writeAllFields: false, allowSingle: false } } });
Disable start/limit params on recipients request
Disable start/limit params on recipients request
JavaScript
mit
SlateFoundation/slate-admin,SlateFoundation/slate,SlateFoundation/slate-admin,SlateFoundation/slate,SlateFoundation/slate,SlateFoundation/slate,SlateFoundation/slate,SlateFoundation/slate-admin,SlateFoundation/slate-admin,SlateFoundation/slate-admin
--- +++ @@ -32,6 +32,8 @@ ], proxy: { type: 'slaterecords', + startParam: null, + limitParam: null, api: { read: '/notes/progress/recipients', update: '/notes/save',
c0227b60be16470032ab03ff29ae88047fca7479
src/formatISODuration/index.js
src/formatISODuration/index.js
import requiredArgs from '../_lib/requiredArgs/index.js' /** * @name formatISODuration * @category Common Helpers * @summary Format a Duration Object according to ISO 8601 Duration standards (https://www.digi.com/resources/documentation/digidocs/90001437-13/reference/r_iso_8601_duration_format.htm) * * @param {Duration} duration * * @returns {String} The ISO 8601 Duration string * @throws {TypeError} Requires 1 argument * @throws {Error} Argument must be an object * * @example * // Get the ISO 8601 Duration between January 15, 1929 and April 4, 1968. * const result = formatISODuration({ years: 39, months: 2, days: 20, hours: 7, minutes: 5, seconds: 0 }) * // => 'P39Y2M20DT0H0M0S' */ export default function formatISODuration(duration) { requiredArgs(1, arguments) if (typeof duration !== 'object') throw new Error('Duration must be an object') const { years = 0, months = 0, days = 0, hours = 0, minutes = 0, seconds = 0 } = duration return `P${years}Y${months}M${days}DT${hours}H${minutes}M${seconds}S` }
import requiredArgs from '../_lib/requiredArgs/index.js' /** * @name formatISODuration * @category Common Helpers * @summary Format a duration object according as ISO 8601 duration string * * @description * Format a duration object according to the ISO 8601 duration standard (https://www.digi.com/resources/documentation/digidocs/90001437-13/reference/r_iso_8601_duration_format.htm) * * @param {Duration} duration - the duration to format * * @returns {String} The ISO 8601 duration string * @throws {TypeError} Requires 1 argument * @throws {Error} Argument must be an object * * @example * // Format the given duration as ISO 8601 string * const result = formatISODuration({ years: 39, months: 2, days: 20, hours: 7, minutes: 5, seconds: 0 }) * // => 'P39Y2M20DT0H0M0S' */ export default function formatISODuration(duration) { requiredArgs(1, arguments) if (typeof duration !== 'object') throw new Error('Duration must be an object') const { years = 0, months = 0, days = 0, hours = 0, minutes = 0, seconds = 0 } = duration return `P${years}Y${months}M${days}DT${hours}H${minutes}M${seconds}S` }
Fix formatISODuration documentation (ci skip)
Fix formatISODuration documentation (ci skip)
JavaScript
mit
date-fns/date-fns,date-fns/date-fns,date-fns/date-fns
--- +++ @@ -3,16 +3,19 @@ /** * @name formatISODuration * @category Common Helpers - * @summary Format a Duration Object according to ISO 8601 Duration standards (https://www.digi.com/resources/documentation/digidocs/90001437-13/reference/r_iso_8601_duration_format.htm) + * @summary Format a duration object according as ISO 8601 duration string * - * @param {Duration} duration + * @description + * Format a duration object according to the ISO 8601 duration standard (https://www.digi.com/resources/documentation/digidocs/90001437-13/reference/r_iso_8601_duration_format.htm) * - * @returns {String} The ISO 8601 Duration string + * @param {Duration} duration - the duration to format + * + * @returns {String} The ISO 8601 duration string * @throws {TypeError} Requires 1 argument * @throws {Error} Argument must be an object * * @example - * // Get the ISO 8601 Duration between January 15, 1929 and April 4, 1968. + * // Format the given duration as ISO 8601 string * const result = formatISODuration({ years: 39, months: 2, days: 20, hours: 7, minutes: 5, seconds: 0 }) * // => 'P39Y2M20DT0H0M0S' */
951638fe79b179096c11912d3a15283bc0b13dd8
app/services/data/get-caseload-progress.js
app/services/data/get-caseload-progress.js
const config = require('../../../knexfile').web const knex = require('knex')(config) const orgUnitFinder = require('../helpers/org-unit-finder') module.exports = function (id, type) { var orgUnit = orgUnitFinder('name', type) var table = orgUnit.caseProgressView return knex(table) .where(table + '.id', id) .select(table + '.community_last_16_weeks AS communityLast16Weeks', table + '.license_last_16_weeks AS licenseLast16Weeks', table + '.total_cases AS totalCases', table + '.warrants_total AS warrantsTotal', table + '.overdue_terminations_total AS overdueTerminationsTotal', table + '.unpaid_work_total AS unpaidWorkTotal') .then(function (results) { return results }) }
const config = require('../../../knexfile').web const knex = require('knex')(config) const orgUnitFinder = require('../helpers/org-unit-finder') module.exports = function (id, type) { var orgUnit = orgUnitFinder('name', type) var table = orgUnit.caseProgressView return knex(table) .where('id', id) .select('name', 'community_last_16_weeks AS communityLast16Weeks', 'license_last_16_weeks AS licenseLast16Weeks', 'total_cases AS totalCases', 'warrants_total AS warrantsTotal', 'overdue_terminations_total AS overdueTerminationsTotal', 'unpaid_work_total AS unpaidWorkTotal') .then(function (results) { return results }) }
Update case progress query to include name
636: Update case progress query to include name
JavaScript
mit
ministryofjustice/wmt-web,ministryofjustice/wmt-web
--- +++ @@ -7,13 +7,14 @@ var table = orgUnit.caseProgressView return knex(table) - .where(table + '.id', id) - .select(table + '.community_last_16_weeks AS communityLast16Weeks', - table + '.license_last_16_weeks AS licenseLast16Weeks', - table + '.total_cases AS totalCases', - table + '.warrants_total AS warrantsTotal', - table + '.overdue_terminations_total AS overdueTerminationsTotal', - table + '.unpaid_work_total AS unpaidWorkTotal') + .where('id', id) + .select('name', + 'community_last_16_weeks AS communityLast16Weeks', + 'license_last_16_weeks AS licenseLast16Weeks', + 'total_cases AS totalCases', + 'warrants_total AS warrantsTotal', + 'overdue_terminations_total AS overdueTerminationsTotal', + 'unpaid_work_total AS unpaidWorkTotal') .then(function (results) { return results })
739f618adf2fa1a971092ce6bedd913c95cc2600
assets/js/components/surveys/SurveyQuestionSingleSelectChoice.js
assets/js/components/surveys/SurveyQuestionSingleSelectChoice.js
/** * SurveyQuestionSingleSelectChoice component. * * Site Kit by Google, Copyright 2021 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. */ const SurveyQuestionSingleSelectChoice = () => { return <div>SurveyQuestionSingleSelectChoice</div>; }; export default SurveyQuestionSingleSelectChoice;
/** * SurveyQuestionSingleSelectChoice component. * * Site Kit by Google, Copyright 2021 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'; /** * Internal dependencies */ import Radio from '../Radio'; /* eslint-disable camelcase */ const SurveyQuestionSingleSelectChoice = ( { value, setValue, // writeIn, // setWriteIn, choice, } ) => { const { answer_ordinal, text } = choice; const isChecked = value === answer_ordinal; return ( <Radio value={ answer_ordinal } checked={ isChecked } name={ text } onClick={ () => setValue( answer_ordinal ) } /> ); }; SurveyQuestionSingleSelectChoice.propTypes = { value: PropTypes.string.isRequired, setValue: PropTypes.func.isRequired, writeIn: PropTypes.string.isRequired, setWriteIn: PropTypes.func.isRequired, choice: PropTypes.shape( { answer_ordinal: PropTypes.oneOfType( [ PropTypes.string, PropTypes.number, ] ), text: PropTypes.string, write_in: PropTypes.bool, } ), }; export default SurveyQuestionSingleSelectChoice;
Add radio button and link up to state.
Add radio button and link up to state.
JavaScript
apache-2.0
google/site-kit-wp,google/site-kit-wp,google/site-kit-wp,google/site-kit-wp
--- +++ @@ -16,8 +16,50 @@ * limitations under the License. */ -const SurveyQuestionSingleSelectChoice = () => { - return <div>SurveyQuestionSingleSelectChoice</div>; +/** + * External dependencies + */ +import PropTypes from 'prop-types'; + +/** + * Internal dependencies + */ +import Radio from '../Radio'; + +/* eslint-disable camelcase */ + +const SurveyQuestionSingleSelectChoice = ( { + value, + setValue, + // writeIn, + // setWriteIn, + choice, +} ) => { + const { answer_ordinal, text } = choice; + const isChecked = value === answer_ordinal; + return ( + <Radio + value={ answer_ordinal } + checked={ isChecked } + name={ text } + onClick={ () => setValue( answer_ordinal ) } + /> + ); +}; + +SurveyQuestionSingleSelectChoice.propTypes = { + value: PropTypes.string.isRequired, + setValue: PropTypes.func.isRequired, + writeIn: PropTypes.string.isRequired, + setWriteIn: PropTypes.func.isRequired, + choice: PropTypes.shape( { + answer_ordinal: PropTypes.oneOfType( [ + PropTypes.string, + PropTypes.number, + ] ), + text: PropTypes.string, + write_in: PropTypes.bool, + } ), }; export default SurveyQuestionSingleSelectChoice;
7782fc4d22078f0b741d20678143bd8d80876609
git/routes.js
git/routes.js
var router = require("express").Router(); var db = require("./db"); router.get("/", function (req, res) { var o = { map: function () { if (this.parents.length === 1) { for (var i = 0; i < this.files.length; i++) { emit(this.author, { additions: this.files[i].additions, deletions: this.files[i].deletions }); } } }, reduce: function (key, values) { var obj = {additions: 0, deletions: 0}; values.map(function (value) { obj.additions += value.additions; obj.deletions += value.deletions; }); return obj; } }; db.Commit.mapReduce(o, function (err, results) { if (err) { res.send(err); } else { res.send(results); } }); }); module.exports = router;
var router = require("express").Router(); var db = require("./db"); router.get("/", function (req, res) { var o = { map: function () { if (this.parents.length === 1) { for (var i = 0; i < this.files.length; i++) { emit(this.author, { additions: this.files[i].additions, deletions: this.files[i].deletions }); } } }, reduce: function (key, values) { var obj = {additions: 0, deletions: 0}; values.map(function (value) { obj.additions += value.additions; obj.deletions += value.deletions; }); return obj; }, out: { replace: 'PersonReduce' } }; db.Commit.mapReduce(o, function (err, model) { if (err) { res.send(err); } else { model.find().populate({ path: "_id", model: "Person" }).exec(function (err, results) { if (err) { res.send(err); } else { var data = results.map(function (result) { return { author: result._id.name, additions: result.value.additions, deletions: result.value.deletions }; }); res.send(data); } }); } }); }); module.exports = router;
Return more sane data through API
Return more sane data through API
JavaScript
mit
bjornarg/dev-dashboard,bjornarg/dev-dashboard
--- +++ @@ -21,14 +21,33 @@ obj.deletions += value.deletions; }); return obj; + }, + out: { + replace: 'PersonReduce' } }; - db.Commit.mapReduce(o, function (err, results) { + db.Commit.mapReduce(o, function (err, model) { if (err) { res.send(err); } else { - res.send(results); + model.find().populate({ + path: "_id", + model: "Person" + }).exec(function (err, results) { + if (err) { + res.send(err); + } else { + var data = results.map(function (result) { + return { + author: result._id.name, + additions: result.value.additions, + deletions: result.value.deletions + }; + }); + res.send(data); + } + }); } }); });
824a95776d93c5fe6314d11d17e7f810d2994414
accounts-anonymous-client.js
accounts-anonymous-client.js
AccountsAnonymous.login = function (callback) { callback = callback || function () {}; if (Meteor.userId()) { callback(new Meteor.Error('accounts-anonymous-already-logged-in', "You can't login anonymously while you are already logged in.")); return; } Accounts.callLoginMethod({ methodArguments: [{ anonymous: true }], userCallback: function (error, result) { if (error) { callback && callback(error); } else { callback && callback(); } } }); }
AccountsAnonymous.login = function (callback) { callback = callback || function () {}; if (Meteor.userId()) { callback(new Meteor.Error(AccountsAnonymous._ALREADY_LOGGED_IN_ERROR, "You can't login anonymously while you are already logged in.")); return; } Accounts.callLoginMethod({ methodArguments: [{ anonymous: true }], userCallback: function (error, result) { if (error) { callback && callback(error); } else { callback && callback(); } } }); }
Use constant for error message.
Use constant for error message.
JavaScript
mit
brettle/meteor-accounts-anonymous
--- +++ @@ -1,7 +1,7 @@ AccountsAnonymous.login = function (callback) { callback = callback || function () {}; if (Meteor.userId()) { - callback(new Meteor.Error('accounts-anonymous-already-logged-in', + callback(new Meteor.Error(AccountsAnonymous._ALREADY_LOGGED_IN_ERROR, "You can't login anonymously while you are already logged in.")); return; }
fe17a2b4115bdedd639b4c26a9a54ee33dbb5bf7
addon/array-pager.js
addon/array-pager.js
import Em from 'ember'; import ArraySlice from 'array-slice'; var get = Em.get; var set = Em.set; var ArrayPager = ArraySlice.extend({ // 1-based page: function (key, page) { var limit = get(this, 'limit'); var offset; // default value if (arguments.length <= 1) { offset = get(this, 'offset') || 0; return Math.ceil(offset / limit) || 1; } // setter // no negative pages page = Math.max(page - 1, 0); offset = (limit * page) || 0; set(this, 'offset', offset); return page + 1; }.property('offset', 'limit'), // 1-based pages: function () { var limit = get(this, 'limit'); var length = get(this, 'content.length'); var pages = Math.ceil(length / limit) || 1; if (pages === Infinity) { pages = 0; } return pages; }.property('content.length', 'limit') }); ArrayPager.computed = { page: function (prop, page, limit) { return Em.computed(prop, function () { return ArrayPager.create({ content: get(this, prop), page: page, limit: limit }); }); } }; export default ArrayPager;
import Em from 'ember'; import ArraySlice from 'array-slice'; var computed = Em.computed; var get = Em.get; var set = Em.set; var ArrayPager = ArraySlice.extend({ // 1-based page: computed('offset', 'limit', function (key, page) { var limit = get(this, 'limit'); var offset; // default value if (arguments.length <= 1) { offset = get(this, 'offset') || 0; return Math.ceil(offset / limit) || 1; } // setter // no negative pages page = Math.max(page - 1, 0); offset = (limit * page) || 0; set(this, 'offset', offset); return page + 1; }), // 1-based pages: computed('content.length', 'limit', function () { var limit = get(this, 'limit'); var length = get(this, 'content.length'); var pages = Math.ceil(length / limit) || 1; if (pages === Infinity) { pages = 0; } return pages; }) }); ArrayPager.computed = { page: function (prop, page, limit) { return computed(function () { return ArrayPager.create({ content: get(this, prop), page: page, limit: limit }); }); } }; export default ArrayPager;
Use `Ember.computed` instead of `Function.prototype.property`
Use `Ember.computed` instead of `Function.prototype.property`
JavaScript
mit
j-/ember-cli-array-pager,j-/ember-cli-array-pager
--- +++ @@ -1,11 +1,12 @@ import Em from 'ember'; import ArraySlice from 'array-slice'; +var computed = Em.computed; var get = Em.get; var set = Em.set; var ArrayPager = ArraySlice.extend({ // 1-based - page: function (key, page) { + page: computed('offset', 'limit', function (key, page) { var limit = get(this, 'limit'); var offset; // default value @@ -19,10 +20,10 @@ offset = (limit * page) || 0; set(this, 'offset', offset); return page + 1; - }.property('offset', 'limit'), + }), // 1-based - pages: function () { + pages: computed('content.length', 'limit', function () { var limit = get(this, 'limit'); var length = get(this, 'content.length'); var pages = Math.ceil(length / limit) || 1; @@ -30,12 +31,12 @@ pages = 0; } return pages; - }.property('content.length', 'limit') + }) }); ArrayPager.computed = { page: function (prop, page, limit) { - return Em.computed(prop, function () { + return computed(function () { return ArrayPager.create({ content: get(this, prop), page: page,
a433c763359129ba034309097681368e7f2b38e8
app/assets/javascripts/application.js
app/assets/javascripts/application.js
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require_tree .
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require angular //= require angular-rails-templates //= require angular-app //= require_tree ./angular-app/templates //= require_tree ./angular-app/modules //= require_tree ./angular-app/filters //= require_tree ./angular-app/directives //= require_tree ./angular-app/models //= require_tree ./angular-app/services //= require_tree ./angular-app/controllers
Add angular assets to asset pipeline
Add angular assets to asset pipeline
JavaScript
mit
godspeedyoo/rails-angular-skeleton,godspeedyoo/rails-angular-skeleton,godspeedyoo/sc2tracker,godspeedyoo/sc2tracker,godspeedyoo/rails-angular-skeleton,godspeedyoo/sc2tracker
--- +++ @@ -12,4 +12,14 @@ // //= require jquery //= require jquery_ujs -//= require_tree . +//= require angular +//= require angular-rails-templates + +//= require angular-app +//= require_tree ./angular-app/templates +//= require_tree ./angular-app/modules +//= require_tree ./angular-app/filters +//= require_tree ./angular-app/directives +//= require_tree ./angular-app/models +//= require_tree ./angular-app/services +//= require_tree ./angular-app/controllers
204820f700ed8f8c89e50b310b7f1433bec4402e
js/analytics.js
js/analytics.js
/** * @constructor */ function Analytics() { this.service_ = null; } Analytics.prototype.start = function(settings) { if (this.service_) { throw 'Analytics should be started only once per session.'; } this.service_ = analytics.getService('text_app'); var propertyId = 'UA-48886257-1'; if (chrome.runtime.getManifest()['name'].indexOf('Dev') >= 0) { propertyId = 'UA-48886257-2'; } this.tracker_ = this.service_.getTracker(propertyId); this.reportSettings_(settings); this.tracker_.sendAppView('main'); }; Analytics.prototype.reportSettings_ = function(settings) { this.tracker_.set('dimension1', settings.get('spacestab').toString()); this.tracker_.set('dimension2', settings.get('tabsize').toString()); this.tracker_.set('dimension3', Math.round(settings.get('fontsize')).toString()); this.tracker_.set('dimension4', settings.get('sidebaropen').toString()); this.tracker_.set('dimension5', settings.get('theme')); };
/** * @constructor */ function Analytics() { this.service_ = null; } Analytics.prototype.start = function(settings) { if (this.service_) { throw 'Analytics should be started only once per session.'; } this.service_ = analytics.getService('text_app'); var propertyId = 'UA-48886257-2'; if (chrome.runtime.id === 'mmfbcljfglbokpmkimbfghdkjmjhdgbg') { propertyId = 'UA-48886257-1'; } this.tracker_ = this.service_.getTracker(propertyId); this.reportSettings_(settings); this.tracker_.sendAppView('main'); }; Analytics.prototype.reportSettings_ = function(settings) { this.tracker_.set('dimension1', settings.get('spacestab').toString()); this.tracker_.set('dimension2', settings.get('tabsize').toString()); this.tracker_.set('dimension3', Math.round(settings.get('fontsize')).toString()); this.tracker_.set('dimension4', settings.get('sidebaropen').toString()); this.tracker_.set('dimension5', settings.get('theme')); };
Use chrome.runtime.id instead of name to select Analytics property.
Use chrome.runtime.id instead of name to select Analytics property.
JavaScript
bsd-3-clause
codex8/text-app,modulexcite/text-app,l3dlp/text-app,zkendall/WordBinder,l3dlp/text-app,zkendall/WordBinder,codex8/text-app,modulexcite/text-app,modulexcite/text-app,l3dlp/text-app,codex8/text-app,zkendall/WordBinder
--- +++ @@ -11,9 +11,9 @@ } this.service_ = analytics.getService('text_app'); - var propertyId = 'UA-48886257-1'; - if (chrome.runtime.getManifest()['name'].indexOf('Dev') >= 0) { - propertyId = 'UA-48886257-2'; + var propertyId = 'UA-48886257-2'; + if (chrome.runtime.id === 'mmfbcljfglbokpmkimbfghdkjmjhdgbg') { + propertyId = 'UA-48886257-1'; } this.tracker_ = this.service_.getTracker(propertyId);
8fdb62c51eab8f19cb5e6e7b3dac6bf28f017411
packages/components/containers/themes/CustomThemeModal.js
packages/components/containers/themes/CustomThemeModal.js
import React, { useState } from 'react'; import { c } from 'ttag'; import PropTypes from 'prop-types'; import { FormModal, PrimaryButton, Label, Alert, TextArea } from 'react-components'; const CustomThemeModal = ({ onSave, theme: initialTheme = '', ...rest }) => { const [theme, setTheme] = useState(initialTheme); const handleChange = ({ target }) => setTheme(target.value); const handleSubmit = async () => { await onSave(theme); rest.onClose(); }; return ( <FormModal submit={<PrimaryButton type="submit">{c('Action').t`Save`}</PrimaryButton>} onSubmit={handleSubmit} title={c('Title').t`Custom mode`} small {...rest} > <Alert type="warning">{c('Warning') .t`Custom modes from third parties can potentially betray your privacy. Only use modes from trusted sources.`}</Alert> <Label className="mb1" htmlFor="themeTextarea">{c('Label').t`CSS code`}</Label> <TextArea className="mb1" id="themeTextarea" value={theme} placeholder={c('Action').t`Insert CSS code here`} onChange={handleChange} /> </FormModal> ); }; CustomThemeModal.propTypes = { onSave: PropTypes.func.isRequired, theme: PropTypes.string }; export default CustomThemeModal;
import React, { useState } from 'react'; import { c } from 'ttag'; import PropTypes from 'prop-types'; import { FormModal, PrimaryButton, Label, Alert, TextArea } from 'react-components'; const CustomThemeModal = ({ onSave, theme: initialTheme = '', ...rest }) => { const [theme, setTheme] = useState(initialTheme); const handleChange = ({ target }) => setTheme(target.value); const handleSubmit = async () => { await onSave(theme); rest.onClose(); }; return ( <FormModal submit={<PrimaryButton type="submit">{c('Action').t`Save`}</PrimaryButton>} onSubmit={handleSubmit} title={c('Title').t`Custom mode`} {...rest} > <Alert type="warning">{c('Warning') .t`Custom modes from third parties can potentially betray your privacy. Only use modes from trusted sources.`}</Alert> <Label className="bl mb0-5" htmlFor="themeTextarea">{c('Label').t`CSS code`}</Label> <TextArea className="mb1" id="themeTextarea" value={theme} placeholder={c('Action').t`Insert CSS code here`} onChange={handleChange} /> </FormModal> ); }; CustomThemeModal.propTypes = { onSave: PropTypes.func.isRequired, theme: PropTypes.string }; export default CustomThemeModal;
Use larger modal for Custom CSS
[MAILWEB-801] Use larger modal for Custom CSS
JavaScript
mit
ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient
--- +++ @@ -17,12 +17,11 @@ submit={<PrimaryButton type="submit">{c('Action').t`Save`}</PrimaryButton>} onSubmit={handleSubmit} title={c('Title').t`Custom mode`} - small {...rest} > <Alert type="warning">{c('Warning') .t`Custom modes from third parties can potentially betray your privacy. Only use modes from trusted sources.`}</Alert> - <Label className="mb1" htmlFor="themeTextarea">{c('Label').t`CSS code`}</Label> + <Label className="bl mb0-5" htmlFor="themeTextarea">{c('Label').t`CSS code`}</Label> <TextArea className="mb1" id="themeTextarea"
8e0822de5b362f9cd5d421269084dd8c23829f98
test/e2e/scenarios.js
test/e2e/scenarios.js
'use strict'; /* http://docs.angularjs.org/guide/dev_guide.e2e-testing */ describe('ng-grid', function() { beforeEach(function() { browser().navigateTo('../../workbench/index.html'); }); describe('templates', function() { browser().navigateTo('../../workbench/templating/external.html'); it('should not cause a $digest or $apply error when fetching the template completes after the data $http request does', function() { }); it('should load external templates before building the grid', function() { // todo: rows should have data when external template is defined }); it('should only load the same external template once', function() { // todo }); }); });
'use strict'; /* http://docs.angularjs.org/guide/dev_guide.e2e-testing */ describe('ng-grid', function() { // beforeEach(function() { // browser().navigateTo('../../workbench/index.html'); // }); describe('templates', function() { beforeEach(function() { browser().navigateTo('../../workbench/templating/external.html'); }); it('should not cause a $digest or $apply error when fetching the template completes after the data $http request does', function() { }); it('should load external templates before building the grid', function() { // todo: rows should have data when external template is defined }); it('should only load the same external template once', function() { // todo }); }); });
Fix for "browser is not defined" error
Fix for "browser is not defined" error The `browser` variable is not available outside a beforeEach() call.
JavaScript
mit
ciccio86/ui-grid,PaulL1/ng-grid,zen4s/ng-grid,b2io/ng-grid,louwie17/ui-grid,pkdevbox/ui-grid,dietergoetelen/ui-grid,zen4s/ng-grid,ingshtrom/ui-grid,edivancamargo/ui-grid,edmondpr/ng-grid,Stiv/ui-grid,angular-ui/ng-grid,JLLeitschuh/ui-grid,louwie17/ui-grid,SomeKittens/ui-grid,yccteam/ui-grid,Phalynx/ng-grid,ntgn81/ui-grid,280455936/ng-grid,Lukasz-Wisniewski/ui-grid,c1240539157/ui-grid,hahn-kev/ui-grid,Stiv/ui-grid,eeiswerth/ng-grid,mportuga/ui-grid,como-quesito/ui-grid,Cosium/ui-grid,htettwin/ui-grid,DexStr/ng-grid,scottlepp/ui-grid,ingshtrom/ui-grid,salarmehr/ng-grid,zamboney/ui-grid,zuohaocheng/ui-grid,nsartor/ui-grid,zuohaocheng/ui-grid,Julius1985/ui-grid,xiaojie123/ng-grid,abgaryanharutyun/ng-grid,zuohaocheng/ui-grid,klieber/ui-grid,InteractiveIntelligence/ng-grid,ntmuigrid/ntmuigrid,b2io/ng-grid,FugleMonkey/ng-grid,solvebio/ng-grid,Servoy/ng-grid,jbarrus/ng-grid,cell-one/ui-grid,kamikasky/ui-grid,zhaokunfay/ui-grid,AgDude/ng-grid,triersistemas/tr-grid,eeiswerth/ng-grid,dietergoetelen/ui-grid,therealtomas/ui-grid,Julius1985/ui-grid,solvebio/ng-grid,Namek/ui-grid,amyboyd/ng-grid,imbalind/ui-grid,pzw224/ui-grid,aw2basc/ui-grid,masterpowers/ui-grid,500tech/ng-grid,swalters/ng-grid,vidakovic/ui-grid,PeopleNet/ng-grid-fork,ppossanzini/ui-grid,dpinho17/ui-grid,dbckr/ui-grid,InteractiveIntelligence/ng-grid,Lukasz-Wisniewski/ui-grid,xiaojie123/ng-grid,angular-ui/ng-grid-legacy,yccteam/ui-grid,machinemetrics/ui-grid,Stiv/ui-grid,bartkiewicz/ui-grid,b2io/ng-grid,frantisekjandos/ui-grid,bartkiewicz/ui-grid,ciccio86/ui-grid,louwie17/ui-grid,YonatanKra/ui-grid,thomsonreuters/ng-grid,Khamull/ui-grid,machinemetrics/ui-grid,domakas/ui-grid,robpurcell/ui-grid,domakas/ui-grid,abgaryanharutyun/ng-grid,suryasingh/ng-grid,eeiswerth/ng-grid,pkdevbox/ui-grid,angular-ui/ng-grid-legacy,Lukasz-Wisniewski/ui-grid,dbckr/ui-grid,edmondpr/ng-grid,klieber/ui-grid,280455936/ng-grid,mirik123/ng-grid,zuzusik/ui-grid,jbarrus/ng-grid,Servoy/ng-grid,ppossanzini/ui-grid,AgDude/ng-grid,zuzusik/ui-grid,mage-eag/ui-grid,seafoam6/ui-grid,zamboney/ui-grid,Cosium/ui-grid,aw2basc/ui-grid,jiangzhixiao/ui-grid,kenwilcox/ui-grid,FernCreek/ng-grid,mage-eag/ui-grid,sandwich99/ng-grid,cell-one/ui-grid,Servoy/ng-grid,amyboyd/ng-grid,sandwich99/ng-grid,likaiwalkman/ui-grid,luisdesig/ui-grid,jintoppy/ui-grid,ntmuigrid/ntmuigrid,dpinho17/ui-grid,thomsonreuters/ng-grid,imbalind/ui-grid,salarmehr/ng-grid,cell-one/ui-grid,dpinho17/ui-grid,machinemetrics/ui-grid,mage-eag/ui-grid,brucebetts/ui-grid,c1240539157/ui-grid,rightscale/ng-grid,luisdesig/ui-grid,salarmehr/ng-grid,DexStr/ng-grid,Namek/ui-grid,SomeKittens/ui-grid,kennypowers1987/ui-grid,wesleycho/ui-grid,zhaokunfay/ui-grid,hahn-kev/ui-grid,amyboyd/ng-grid,rightscale/ng-grid,solvebio/ng-grid,zamboney/ui-grid,benoror/ui-grid,edmondpr/ng-grid,kennypowers1987/ui-grid,nishant8BITS/ng-grid,AdverseEvents/ui-grid,FugleMonkey/ng-grid,mboriani/ClearFilters,DexStr/ng-grid,Namek/ui-grid,kenwilcox/ui-grid,lookfirst/ui-grid,wesleycho/ui-grid,lookfirst/ui-grid,yccteam/ui-grid,280455936/ng-grid,hahn-kev/ui-grid,FernCreek/ng-grid,AdverseEvents/ui-grid,zhaokunfay/ui-grid,YonatanKra/ui-grid,dietergoetelen/ui-grid,JLLeitschuh/ui-grid,nishant8BITS/ng-grid,mirik123/ng-grid,angular-ui/ui-grid,suryasingh/ng-grid,kenwilcox/ui-grid,masterpowers/ui-grid,mportuga/ui-grid,zmon/ui-grid,brucebetts/ui-grid,alex87/ui-grid,benoror/ui-grid,luisdesig/ui-grid,scottlepp/ui-grid,scottlepp/ui-grid,dlgski/ui-grid,frantisekjandos/ui-grid,abgaryanharutyun/ng-grid,sandwich99/ng-grid,ingshtrom/ui-grid,500tech/ng-grid,kamikasky/ui-grid,htettwin/ui-grid,likaiwalkman/ui-grid,pzw224/ui-grid,angular-ui/ui-grid,JLLeitschuh/ui-grid,triersistemas/tr-grid,zen4s/ng-grid,benoror/ui-grid,PeopleNet/ng-grid-fork,aw2basc/ui-grid,YonatanKra/ui-grid,bjossi86/ui-grid,nsartor/ui-grid,Julius1985/ui-grid,c1240539157/ui-grid,angular-ui/ng-grid,JayHuang/ng-grid,bjossi86/ui-grid,cityglobal/ui-grid,AgDude/ng-grid,suryasingh/ng-grid,vidakovic/ui-grid,mboriani/ClearFilters,reupen/ui-grid,Khamull/ui-grid,btesser/ng-grid,kennypowers1987/ui-grid,triersistemas/tr-grid,pkdevbox/ui-grid,swalters/ng-grid,JayHuang/ng-grid,DmitryEfimenko/ui-grid,Phalynx/ng-grid,como-quesito/ui-grid,ntgn81/ui-grid,500tech/ng-grid,masterpowers/ui-grid,reupen/ui-grid,btesser/ng-grid,mirik123/ng-grid,robpurcell/ui-grid,brucebetts/ui-grid,zmon/ui-grid,JayHuang/ng-grid,dlgski/ui-grid,reupen/ui-grid,zmon/ui-grid,jmptrader/ui-grid,PaulL1/ng-grid,ppossanzini/ui-grid,seafoam6/ui-grid,mboriani/ClearFilters,edivancamargo/ui-grid,angular-ui/ui-grid,nsartor/ui-grid,wesleycho/ui-grid,vidakovic/ui-grid,DmitryEfimenko/ui-grid,jintoppy/ui-grid,lookfirst/ui-grid,robpurcell/ui-grid,angular-ui/ng-grid-legacy,kamikasky/ui-grid,bartkiewicz/ui-grid,jintoppy/ui-grid,cityglobal/ui-grid,como-quesito/ui-grid,FugleMonkey/ng-grid,FernCreek/ng-grid,therealtomas/ui-grid,zuzusik/ui-grid,frantisekjandos/ui-grid,bjossi86/ui-grid,jmptrader/ui-grid,jiangzhixiao/ui-grid,ntgn81/ui-grid,alex87/ui-grid,dbckr/ui-grid,DmitryEfimenko/ui-grid,imbalind/ui-grid,ciccio86/ui-grid,pzw224/ui-grid,alex87/ui-grid,jbarrus/ng-grid,cityglobal/ui-grid,xiaojie123/ng-grid,likaiwalkman/ui-grid,htettwin/ui-grid,nishant8BITS/ng-grid,AdverseEvents/ui-grid,InteractiveIntelligence/ng-grid,jiangzhixiao/ui-grid,domakas/ui-grid,SomeKittens/ui-grid,btesser/ng-grid,angular-ui/ng-grid,edivancamargo/ui-grid,jmptrader/ui-grid,dlgski/ui-grid,klieber/ui-grid,mportuga/ui-grid,Cosium/ui-grid,therealtomas/ui-grid,seafoam6/ui-grid,Khamull/ui-grid,ntmuigrid/ntmuigrid,Phalynx/ng-grid
--- +++ @@ -3,12 +3,15 @@ /* http://docs.angularjs.org/guide/dev_guide.e2e-testing */ describe('ng-grid', function() { - beforeEach(function() { - browser().navigateTo('../../workbench/index.html'); - }); + + // beforeEach(function() { + // browser().navigateTo('../../workbench/index.html'); + // }); describe('templates', function() { - browser().navigateTo('../../workbench/templating/external.html'); + beforeEach(function() { + browser().navigateTo('../../workbench/templating/external.html'); + }); it('should not cause a $digest or $apply error when fetching the template completes after the data $http request does', function() {
36ac9e32d2b4fa5f8df837b956f8e73287395c86
bin/reviewServer.js
bin/reviewServer.js
#!/usr/bin/env node 'use strict'; /** * Binary to run the main server. * (C) 2015 Alex Fernández. */ // requires var stdio = require('stdio'); var Log = require('log'); var reviewServer = require('../lib/reviewServer'); // globals var log = new Log('info'); var credentials = {}; // init try { credentials = require('../credentials.json'); } catch(exception) { log.info('Please enter default values in a file called credentials.json'); } var options = stdio.getopt({ token: {key: 't', args: 1, description: 'Consumer token for Trello'}, key: {key: 'k', args: 1, description: 'Key for Trello'}, secret: {key: 's', args: 1, description: 'Secret value to access the server'}, port: {key: 'p', args: 1, description: 'Port to start the server', default: 6003}, quiet: {key: 'q', description: 'Do not log any messages'}, debug: {key: 'd', description: 'Log debug messages'}, }); credentials.overwriteWith(options); reviewServer.start(credentials);
#!/usr/bin/env node 'use strict'; /** * Binary to run the main server. * (C) 2015 Alex Fernández. */ // requires var stdio = require('stdio'); var Log = require('log'); var reviewServer = require('../lib/reviewServer'); // globals var log = new Log('info'); var credentials = {}; // init try { credentials = require('../credentials.json'); } catch(exception) { log.info('Please enter default values in a file called credentials.json'); } var options = stdio.getopt({ token: {key: 't', args: 1, description: 'Consumer token for Trello'}, key: {key: 'k', args: 1, description: 'Key for Trello'}, secret: {key: 's', args: 1, description: 'Secret value to access the server'}, port: {key: 'p', args: 1, description: 'Port to start the server', default: 7431}, quiet: {key: 'q', description: 'Do not log any messages'}, debug: {key: 'd', description: 'Log debug messages'}, }); credentials.overwriteWith(options); reviewServer.start(credentials);
Change default port to 7431.
Change default port to 7431.
JavaScript
mit
alexfernandez/trello-reviewer
--- +++ @@ -28,7 +28,7 @@ token: {key: 't', args: 1, description: 'Consumer token for Trello'}, key: {key: 'k', args: 1, description: 'Key for Trello'}, secret: {key: 's', args: 1, description: 'Secret value to access the server'}, - port: {key: 'p', args: 1, description: 'Port to start the server', default: 6003}, + port: {key: 'p', args: 1, description: 'Port to start the server', default: 7431}, quiet: {key: 'q', description: 'Do not log any messages'}, debug: {key: 'd', description: 'Log debug messages'}, });
3c3c4381d1d0dff38184d2543cff92f5c6be45be
bin/reviewServer.js
bin/reviewServer.js
#!/usr/bin/env node 'use strict'; /** * Binary to run the main server. * (C) 2015 Alex Fernández. */ // requires var stdio = require('stdio'); var reviewServer = require('../lib/reviewServer'); // init var options = stdio.getopt({ token: {key: 't', args: 1, mandatory: true, description: 'Consumer token for Trello'}, key: {key: 'k', args: 1, mandatory: true, description: 'Key for Trello'}, secret: {key: 's', args: 1, mandatory: true, description: 'Secret value to access the server'}, port: {key: 'p', args: 1, description: 'Port to start the server', default: 6003}, quiet: {key: 'q', description: 'Do not log any messages'}, debug: {key: 'd', description: 'Log debug messages'}, }); reviewServer.start(options);
#!/usr/bin/env node 'use strict'; /** * Binary to run the main server. * (C) 2015 Alex Fernández. */ // requires var stdio = require('stdio'); var Log = require('log'); var reviewServer = require('../lib/reviewServer'); // globals var log = new Log('info'); // init try { var credentials = require('./credentials.json'); } catch(exception) { log.info('Please enter default values in a file called credentials.json'); } var options = stdio.getopt({ token: {key: 't', args: 1, description: 'Consumer token for Trello'}, key: {key: 'k', args: 1, description: 'Key for Trello'}, secret: {key: 's', args: 1, description: 'Secret value to access the server'}, port: {key: 'p', args: 1, description: 'Port to start the server', default: 6003}, quiet: {key: 'q', description: 'Do not log any messages'}, debug: {key: 'd', description: 'Log debug messages'}, }); credentials.overwriteWith(options); reviewServer.start(credentials);
Use credentials as default values, complain if not found.
Use credentials as default values, complain if not found.
JavaScript
mit
alexfernandez/trello-reviewer
--- +++ @@ -8,17 +8,30 @@ // requires var stdio = require('stdio'); +var Log = require('log'); var reviewServer = require('../lib/reviewServer'); +// globals +var log = new Log('info'); + // init +try +{ + var credentials = require('./credentials.json'); +} +catch(exception) +{ + log.info('Please enter default values in a file called credentials.json'); +} var options = stdio.getopt({ - token: {key: 't', args: 1, mandatory: true, description: 'Consumer token for Trello'}, - key: {key: 'k', args: 1, mandatory: true, description: 'Key for Trello'}, - secret: {key: 's', args: 1, mandatory: true, description: 'Secret value to access the server'}, + token: {key: 't', args: 1, description: 'Consumer token for Trello'}, + key: {key: 'k', args: 1, description: 'Key for Trello'}, + secret: {key: 's', args: 1, description: 'Secret value to access the server'}, port: {key: 'p', args: 1, description: 'Port to start the server', default: 6003}, quiet: {key: 'q', description: 'Do not log any messages'}, debug: {key: 'd', description: 'Log debug messages'}, }); +credentials.overwriteWith(options); -reviewServer.start(options); +reviewServer.start(credentials);
df8b1d826bbbe45a9b21738ea0c4d6c4fe4b7c49
lib/engine/index.js
lib/engine/index.js
const path = require('path') module.exports = function engine (config) { require('./driver')(config) config.engine.on('init', function (processType) { // processType will be 'runner','processor', or 'main' // Useful for detecting what module you are in if (processType === 'main') { // if (!config.common.storage.db.users.count()) { // importDB(config) // } } if (processType === 'runtime') { patchRuntimeGlobals(config) } }) } function patchRuntimeGlobals (config) { let pathToModule = path.join(path.dirname(require.main.filename), 'runtime/user-globals.js') let userGlobals = require(pathToModule) let newUserGlobals = require('./runtime/user-globals.js') Object.assign(userGlobals, newUserGlobals) }
const path = require('path') module.exports = function (config) { if (config.engine.driver) { // TODO: For some reason this is missing on runtimes, this needs // investigated as it makes on('playerSandbox') never trigger require('./driver')(config) } config.engine.on('init', function (processType) { console.log('INIT', processType) // processType will be 'runner','processor', or 'main' // Useful for detecting what module you are in if (processType === 'main') { // if (!config.common.storage.db.users.count()) { // importDB(config) // } } if (processType === 'runtime') { patchRuntimeGlobals(config) } }) } function patchRuntimeGlobals (config) { let pathToModule = path.join(path.dirname(require.main.filename), 'user-globals.js') let userGlobals = require(pathToModule) let newUserGlobals = require('./runtime/user-globals.js') Object.assign(userGlobals, newUserGlobals) }
Fix user global patching. Work around wierd runtime error
Fix user global patching. Work around wierd runtime error
JavaScript
mit
ScreepsMods/screepsmod-mongo
--- +++ @@ -1,8 +1,13 @@ const path = require('path') -module.exports = function engine (config) { - require('./driver')(config) +module.exports = function (config) { + if (config.engine.driver) { + // TODO: For some reason this is missing on runtimes, this needs + // investigated as it makes on('playerSandbox') never trigger + require('./driver')(config) + } config.engine.on('init', function (processType) { + console.log('INIT', processType) // processType will be 'runner','processor', or 'main' // Useful for detecting what module you are in if (processType === 'main') { @@ -17,7 +22,7 @@ } function patchRuntimeGlobals (config) { - let pathToModule = path.join(path.dirname(require.main.filename), 'runtime/user-globals.js') + let pathToModule = path.join(path.dirname(require.main.filename), 'user-globals.js') let userGlobals = require(pathToModule) let newUserGlobals = require('./runtime/user-globals.js') Object.assign(userGlobals, newUserGlobals)
9f7b8362fbc99bc3c2832413de7963e19a21637f
app/assets/javascripts/sw.js
app/assets/javascripts/sw.js
console.log('Started', self); self.addEventListener('install', function(event) { self.skipWaiting(); console.log('Installed', event); }); self.addEventListener('activate', function(event) { console.log('Activated', event); }); self.addEventListener('push', function(event) { console.log('Push message', event); var title = 'Push message'; event.waitUntil( self.registration.showNotification(title, { body: 'The Message', tag: 'my-tag' })); }); self.addEventListener('notificationclick', function(event) { console.log('Notification click: tag ', event.notification.tag); event.notification.close(); var url = 'https://www.google.com/'; event.waitUntil( clients.matchAll({ type: 'window' }) .then(function(windowClients) { for (var i = 0; i < windowClients.length; i++) { var client = windowClients[i]; if (client.url === url && 'focus' in client) { return client.focus(); } } if (clients.openWindow) { return clients.openWindow(url); } }) ); });
console.log('Started', self); self.addEventListener('install', function(event) { self.skipWaiting(); console.log('Installed', event); }); self.addEventListener('activate', function(event) { console.log('Activated', event); }); self.addEventListener('push', function(event) { var title = 'Push message'; event.waitUntil( self.registration.showNotification(title, { body: 'The Message', icon: 'assets/launcher-icon-4x.png', tag: 'my-tag' })); }); self.addEventListener('notificationclick', function(event) { console.log('Notification click: tag ', event.notification.tag); event.notification.close(); var url = 'https://www.google.com/'; if (clients.openWindow) { return clients.openWindow(url); } });
Add notification icon and delete code that didn't work
Add notification icon and delete code that didn't work
JavaScript
mit
coreyja/glassy-collections,coreyja/glassy-collections,coreyja/glassy-collections
--- +++ @@ -7,11 +7,11 @@ console.log('Activated', event); }); self.addEventListener('push', function(event) { - console.log('Push message', event); var title = 'Push message'; event.waitUntil( self.registration.showNotification(title, { body: 'The Message', + icon: 'assets/launcher-icon-4x.png', tag: 'my-tag' })); }); @@ -19,20 +19,7 @@ console.log('Notification click: tag ', event.notification.tag); event.notification.close(); var url = 'https://www.google.com/'; - event.waitUntil( - clients.matchAll({ - type: 'window' - }) - .then(function(windowClients) { - for (var i = 0; i < windowClients.length; i++) { - var client = windowClients[i]; - if (client.url === url && 'focus' in client) { - return client.focus(); - } - } - if (clients.openWindow) { - return clients.openWindow(url); - } - }) - ); + if (clients.openWindow) { + return clients.openWindow(url); + } });
21fd5924b841f9926b8ba6ca57b387539222fe54
lib/parse/readme.js
lib/parse/readme.js
var _ = require('lodash'); var marked = require('marked'); var textRenderer = require('marked-text-renderer'); function extractFirstNode(nodes, nType) { return _.chain(nodes) .filter(function(node) { return node.type == nType; }) .pluck("text") .first() .value(); } function parseReadme(src) { var nodes, title, description; var renderer = textRenderer(); // Parse content nodes = marked.lexer(src); var title = extractFirstNode(nodes, "heading"); var description = extractFirstNode(nodes, "paragraph"); var convert = _.compose( function(text) { return _.unescape(text.replace(/(\r\n|\n|\r)/gm, "")); }, _.partialRight(marked, _.extend({}, marked.defaults, { renderer: renderer })) ); return { title: convert(title), description: convert(description) }; } // Exports module.exports = parseReadme;
var _ = require('lodash'); var marked = require('marked'); var textRenderer = require('marked-text-renderer'); function extractFirstNode(nodes, nType) { return _.chain(nodes) .filter(function(node) { return node.type == nType; }) .pluck("text") .first() .value(); } function parseReadme(src) { var nodes, title, description; var renderer = textRenderer(); // Parse content nodes = marked.lexer(src); title = extractFirstNode(nodes, "heading") || ''; description = extractFirstNode(nodes, "paragraph") || ''; var convert = _.compose( function(text) { return _.unescape(text.replace(/(\r\n|\n|\r)/gm, "")); }, function(text) { return marked.parse(text, _.extend({}, marked.defaults, { renderer: renderer })); } ); return { title: convert(title), description: convert(description) }; } // Exports module.exports = parseReadme;
Fix generate failing on README parsing
Fix generate failing on README parsing Failed if no title or description could be extracted
JavaScript
apache-2.0
CN-Sean/gitbook,OriPekelman/gitbook,hujianfei1989/gitbook,iamchenxin/gitbook,JohnTroony/gitbook,xxxhycl2010/gitbook,qingying5810/gitbook,bjlxj2008/gitbook,JozoVilcek/gitbook,kamyu104/gitbook,strawluffy/gitbook,ferrior30/gitbook,yaonphy/SwiftBlog,shibe97/gitbook,gencer/gitbook,palerdot/gitbook,mautic/documentation,haamop/documentation,youprofit/gitbook,megumiteam/documentation,bjlxj2008/gitbook,iamchenxin/gitbook,CN-Sean/gitbook,npracht/documentation,snowsnail/gitbook,switchspan/gitbook,vehar/gitbook,ryanswanson/gitbook,intfrr/gitbook,hujianfei1989/gitbook,mruse/gitbook,bradparks/gitbook,2390183798/gitbook,Abhikos/gitbook,GitbookIO/gitbook,shibe97/gitbook,nycitt/gitbook,sunlianghua/gitbook,youprofit/gitbook,npracht/documentation,ferrior30/gitbook,jocr1627/gitbook,haamop/documentation,codepiano/gitbook,gaearon/gitbook,sunlianghua/gitbook,ZachLamb/gitbook,justinleoye/gitbook,tzq668766/gitbook,iflyup/gitbook,hongbinz/gitbook,grokcoder/gitbook,lucciano/gitbook,gencer/gitbook,Keystion/gitbook,athiruban/gitbook,thelastmile/gitbook,webwlsong/gitbook,xiongjungit/gitbook,wewelove/gitbook,2390183798/gitbook,anrim/gitbook,lucciano/gitbook,switchspan/gitbook,wewelove/gitbook,mruse/gitbook,xcv58/gitbook,FKV587/gitbook,intfrr/gitbook,mautic/documentation,codepiano/gitbook,a-moses/gitbook,tshoper/gitbook,escopecz/documentation,guiquanz/gitbook,boyXiong/gitbook,megumiteam/documentation,qingying5810/gitbook,athiruban/gitbook,sudobashme/gitbook,rohan07/gitbook,bradparks/gitbook,palerdot/gitbook,gaearon/gitbook,snowsnail/gitbook,xxxhycl2010/gitbook,FKV587/gitbook,nycitt/gitbook,thelastmile/gitbook,gdbooks/gitbook,justinleoye/gitbook,jasonslyvia/gitbook,jasonslyvia/gitbook,minghe/gitbook,xiongjungit/gitbook,tzq668766/gitbook,alex-dixon/gitbook,ZachLamb/gitbook,iflyup/gitbook,jocr1627/gitbook,escopecz/documentation,webwlsong/gitbook,hongbinz/gitbook,gdbooks/gitbook,xcv58/gitbook,alex-dixon/gitbook,kamyu104/gitbook,a-moses/gitbook,OriPekelman/gitbook,rohan07/gitbook,grokcoder/gitbook,vehar/gitbook,JohnTroony/gitbook,boyXiong/gitbook,minghe/gitbook,sudobashme/gitbook,guiquanz/gitbook,tshoper/gitbook
--- +++ @@ -20,16 +20,18 @@ // Parse content nodes = marked.lexer(src); - var title = extractFirstNode(nodes, "heading"); - var description = extractFirstNode(nodes, "paragraph"); + title = extractFirstNode(nodes, "heading") || ''; + description = extractFirstNode(nodes, "paragraph") || ''; var convert = _.compose( function(text) { return _.unescape(text.replace(/(\r\n|\n|\r)/gm, "")); }, - _.partialRight(marked, _.extend({}, marked.defaults, { - renderer: renderer - })) + function(text) { + return marked.parse(text, _.extend({}, marked.defaults, { + renderer: renderer + })); + } ); return {
7e15fe42282c594260e7185760246a50f9ee7e50
lib/socketErrors.js
lib/socketErrors.js
var createError = require('createerror'); var httpErrors = require('httperrors'); var socketCodesMap = require('./socketCodesMap'); var _ = require('lodash'); var SocketError = createError({ name: 'SocketError' }); function createSocketError(errorCode) { var statusCode = socketCodesMap[errorCode] || 'Unknown'; var options = _.defaults({ name: errorCode, code: errorCode, statusCode: statusCode, status: statusCode }, _.omit(httpErrors(statusCode), 'message')); var socketError = createError(options, SocketError); socketErrors[errorCode] = socketError; return socketError; } var socketErrors = module.exports = function (err) { var errorName; if (socketErrors.hasOwnProperty(err.code)) { errorName = err.code; } else { errorName = 'NotSocketError'; } return new socketErrors[errorName](err); }; module.exports.SocketError = SocketError; // create an Unknown error sentinel socketErrors.NotSocketError = createSocketError('NotSocketError'); // create a new socket error for each error code Object.keys(socketCodesMap).forEach(createSocketError);
var createError = require('createerror'); var httpErrors = require('httperrors'); var socketCodesMap = require('./socketCodesMap'); var _ = require('lodash'); var SocketError = createError({ name: 'SocketError' }); function createSocketError(errorCode) { var statusCode = socketCodesMap[errorCode] || 'Unknown'; var options = _.defaults({ name: errorCode, code: errorCode, statusCode: statusCode, status: statusCode }, _.omit(httpErrors(statusCode), 'message')); var socketError = createError(options, SocketError); socketErrors[errorCode] = socketError; return socketError; } var socketErrors = module.exports = function (err) { var errorName; if (socketErrors.hasOwnProperty(err.code)) { errorName = err.code; } else { errorName = 'NotSocketError'; } return new socketErrors[errorName](err); }; // export the base class module.exports.SocketError = SocketError; // create an Unknown error sentinel socketErrors.NotSocketError = createSocketError('NotSocketError'); // create a new socket error for each error code Object.keys(socketCodesMap).forEach(createSocketError);
Add a small comment to an export.
Add a small comment to an export.
JavaScript
bsd-3-clause
alexjeffburke/node-socketerrors
--- +++ @@ -34,6 +34,7 @@ return new socketErrors[errorName](err); }; +// export the base class module.exports.SocketError = SocketError; // create an Unknown error sentinel
c6594d95ad6a2f694837561df71ec0997ae50fa9
app/reducers/alertMessage.js
app/reducers/alertMessage.js
import _ from 'lodash'; import { OPEN_ALERT_MESSAGE, CLOSE_ALERT_MESSAGE, } from '../actions/actionTypes'; const initialState = { show: false, messages: { th: '', en: '', }, technical: { message: '', code: '', }, }; const getInitialState = () => ({ ...initialState, }); export default (state = getInitialState(), action) => { switch (action.type) { case OPEN_ALERT_MESSAGE: return { ...state, show: true, // messages: action.messages, }; case CLOSE_ALERT_MESSAGE: return getInitialState(); default: return state; } };
import _ from 'lodash'; import { OPEN_ALERT_MESSAGE, CLOSE_ALERT_MESSAGE, } from '../actions/actionTypes'; const initialState = { show: false, title: { th: '', en: '' }, messages: { th: '', en: '', }, technical: { message: '', code: '', }, }; const getInitialState = () => ({ ...initialState, }); export default (state = getInitialState(), action) => { switch (action.type) { case OPEN_ALERT_MESSAGE: return { ...state, show: true, title: action.data.title, messages: action.data.messages, technical: action.data.technical, }; case CLOSE_ALERT_MESSAGE: return getInitialState(); default: return state; } };
Add alert message reducer format
Add alert message reducer format
JavaScript
mit
hlex/vms,hlex/vms
--- +++ @@ -7,6 +7,10 @@ const initialState = { show: false, + title: { + th: '', + en: '' + }, messages: { th: '', en: '', @@ -26,7 +30,9 @@ return { ...state, show: true, - // messages: action.messages, + title: action.data.title, + messages: action.data.messages, + technical: action.data.technical, }; case CLOSE_ALERT_MESSAGE: return getInitialState();
b6296f0ff62ec2a9e8e123c57d2e696b2bbc62c8
test/unit/supported-formulas.js
test/unit/supported-formulas.js
import SUPPORTED_FORMULAS from '../../src/supported-formulas'; describe('.SUPPORTED_FORMULAS', () => { it('should be defined', () => { expect(SUPPORTED_FORMULAS.length).to.eq(391); }); });
import SUPPORTED_FORMULAS from '../../src/supported-formulas'; describe('.SUPPORTED_FORMULAS', () => { it('should be defined', () => { expect(SUPPORTED_FORMULAS.length).to.eq(392); }); });
Update unit test for supported formula
Update unit test for supported formula
JavaScript
mit
kevb/formula-parser,kevb/formula-parser
--- +++ @@ -2,6 +2,6 @@ describe('.SUPPORTED_FORMULAS', () => { it('should be defined', () => { - expect(SUPPORTED_FORMULAS.length).to.eq(391); + expect(SUPPORTED_FORMULAS.length).to.eq(392); }); });
b9cc15c3e8329b61c0984e9ca70069f9f3e764a7
api/models/Places.js
api/models/Places.js
/** * Places.js * * @description :: TODO: You might write a short summary of how this model works and what it represents here. * @docs :: http://sailsjs.org/documentation/concepts/models-and-orm/models */ module.exports = { //connection: 'db_server', //configurations to disale UpdateAt and CreatedAt Waterline Columns tableName: 'places', autoCreatedAt: false, autoUpdatedAt: false, attributes: { id: { type: 'integer', autoIncrement: true, unique: true, primaryKey: true }, company_id: { type: 'integer', required: true }, name: { type: 'string', required: true }, description: { type: 'text', required: true }, created_at: { type: 'datetime' }, updated_at: { type: 'datetime' }, updated_by_user: { type: 'integer', columnName: 'updated_by_user_id', required: true } } };
/** * Places.js * * @description :: TODO: You might write a short summary of how this model works and what it represents here. * @docs :: http://sailsjs.org/documentation/concepts/models-and-orm/models */ module.exports = { //connection: 'db_server', //configurations to disale UpdateAt and CreatedAt Waterline Columns tableName: 'places', autoCreatedAt: false, autoUpdatedAt: false, attributes: { id: { type: 'integer', autoIncrement: true, unique: true, primaryKey: true }, company_id: { type: 'integer', required: true }, name: { type: 'string', required: true }, description: { type: 'text' }, created_at: { type: 'datetime' }, updated_at: { type: 'datetime' }, updated_by_user: { type: 'integer', columnName: 'updated_by_user_id', required: true } } };
Refactor [description] property to not require
Refactor [description] property to not require
JavaScript
mit
FernandoPucci/GerPro,FernandoPucci/GerPro
--- +++ @@ -28,8 +28,7 @@ required: true }, description: { - type: 'text', - required: true + type: 'text' }, created_at: { type: 'datetime'
57c466b4ee66259f80be6cd5d1d858051f462118
imports/api/payments/collection.js
imports/api/payments/collection.js
import { Mongo } from 'meteor/mongo'; import moment from 'moment'; const Payments = new Mongo.Collection('payments'); Payments.refund = (orderId) => { if (orderId) { const payment = Payments.findOne({ order_id: orderId }); if (payment && payment.charge.id) { import StripeHelper from '../cards/server/stripe_helper'; StripeHelper.refundCharge(payment.charge.id); } } }; Payments.recentPaymentCompleted = email => Payments.findOne({ email, status: 'completed', timestamp: { $gte: moment().subtract(10, 'minutes').toDate(), }, }); Payments.deny({ insert() { return true; }, update() { return true; }, remove() { return true; }, }); export default Payments;
import { Mongo } from 'meteor/mongo'; import moment from 'moment'; const Payments = new Mongo.Collection('payments'); Payments.refund = (orderId) => { if (orderId) { const payment = Payments.findOne({ order_id: orderId }); if (payment && payment.charge.id) { import StripeHelper from '../cards/server/stripe_helper'; StripeHelper.refundCharge(payment.charge.id); } } }; Payments.recentPaymentCompleted = (email) => { const recentPayments = Payments.find({ email, status: 'completed', timestamp: { $gte: moment().subtract(10, 'minutes').toDate(), }, }, { sort: { timestamp: -1, }, }).fetch(); return recentPayments ? recentPayments[0] : null; }; Payments.deny({ insert() { return true; }, update() { return true; }, remove() { return true; }, }); export default Payments;
Use most recent payment when sending final charged to Shopify
Use most recent payment when sending final charged to Shopify
JavaScript
mit
hwillson/shopify-hosted-payments,hwillson/shopify-hosted-payments
--- +++ @@ -13,13 +13,20 @@ } }; -Payments.recentPaymentCompleted = email => Payments.findOne({ - email, - status: 'completed', - timestamp: { - $gte: moment().subtract(10, 'minutes').toDate(), - }, -}); +Payments.recentPaymentCompleted = (email) => { + const recentPayments = Payments.find({ + email, + status: 'completed', + timestamp: { + $gte: moment().subtract(10, 'minutes').toDate(), + }, + }, { + sort: { + timestamp: -1, + }, + }).fetch(); + return recentPayments ? recentPayments[0] : null; +}; Payments.deny({ insert() { return true; },
a7e8bb0e37d1981bb287345c5ab575cedd1b4708
test/integration/endpoints.js
test/integration/endpoints.js
var fs = require('fs'), fileModule = require('file'), testDir = '/tests', testFileName = 'integration_test.js'; process.env.INTEGRATION = true; describe('endpoint', function() { it('should load the server and set everything up properly',function(done){ this.timeout(1000); //Server should not take more than 1 sek to boot var app = require(process.cwd() + '/server'); app.on('ready',function(){ fileModule.walkSync('./endpoints', function(dirPath, dirs, files){ if (dirPath.indexOf(testDir) < 0) return; files.forEach(function(file){ if (file != testFileName) return; var path = dirPath + '/' + file; if (!fs.existsSync(path)) return; require('../../' + path); }); }); done(); }); }); });
var fs = require('fs'), path = require('path'), fileModule = require('file'), testDir = '/tests', testFileName = 'integration_test.js'; process.env.INTEGRATION = true; describe('endpoint', function() { it('should load the server and set everything up properly',function(done){ this.timeout(1000); //Server should not take more than 1 sek to boot var app = require(process.cwd() + '/server'); app.on('ready',function(){ fileModule.walkSync('./endpoints', function(dirPath, dirs, files){ if (dirPath.indexOf(testDir) < 0) return; files.forEach(function(file){ if (file != testFileName) return; var fullPath = dirPath + '/' + file; if (!fs.existsSync(fullPath)) return; if (path.extname(fullPath) !== '.js') return; require('../../' + fullPath); }); }); done(); }); }); });
Check the file extension before requiring a test.
Check the file extension before requiring a test. My vim swap files kept getting caught in the test runner so I made the change to only load up .js files.
JavaScript
mit
apis-is/apis
--- +++ @@ -1,7 +1,9 @@ var fs = require('fs'), + path = require('path'), fileModule = require('file'), testDir = '/tests', testFileName = 'integration_test.js'; + process.env.INTEGRATION = true; @@ -16,9 +18,10 @@ if (dirPath.indexOf(testDir) < 0) return; files.forEach(function(file){ if (file != testFileName) return; - var path = dirPath + '/' + file; - if (!fs.existsSync(path)) return; - require('../../' + path); + var fullPath = dirPath + '/' + file; + if (!fs.existsSync(fullPath)) return; + if (path.extname(fullPath) !== '.js') return; + require('../../' + fullPath); }); }); done();
ad926871ed5df6e2d7e22e99236cd615ce713e2d
git-deploy.js
git-deploy.js
// include flightplan.js var plan = require('flightplan'); // Plan to git deploy via ssh remote plan.remote('gitDeploy', function(remote) { var webRoot = plan.runtime.options.webRoot; // git pull remote.with('cd ' + webRoot, function() { remote.exec('git pull'); }); });
module.exports = function () { /* @method remotGitDeploy Takes a flightplan instance and transport @param remote {Object} Flightplan transport instance @param webRoot {string} path to run git pull on the remote server e.g. /var/www/project */ var remotGitDeploy = function (remote, webRoot) { // git pull remote.with('cd ' + webRoot, function() { remote.exec('git pull'); }); }; /* @method addToPlan Takes a flightplan instance and adds a task called gitDeploy @param plan {Object} Flightplan instance @param plan.runtime.options.webRoot {String} Remote path to run git pull */ var addToPlan = function (plan) { // Plan to git deploy via ssh remote var webRoot = plan.runtime.options.webRoot; plan.remote('gitDeploy', function(remote) { remoteGitDeploy(remote, webRoot); }); }; return { addToPlan: addToPlan, remoteGitDeploy: remoteGitDeploy }; }
Update module to return two different methods for adding the deploy script
Update module to return two different methods for adding the deploy script
JavaScript
mit
grahamgilchrist/flightplan-git-deploy
--- +++ @@ -1,12 +1,36 @@ -// include flightplan.js -var plan = require('flightplan'); +module.exports = function () { -// Plan to git deploy via ssh remote -plan.remote('gitDeploy', function(remote) { - var webRoot = plan.runtime.options.webRoot; + /* + @method remotGitDeploy + Takes a flightplan instance and transport + @param remote {Object} Flightplan transport instance + @param webRoot {string} path to run git pull on the remote server + e.g. /var/www/project + */ + var remotGitDeploy = function (remote, webRoot) { + // git pull + remote.with('cd ' + webRoot, function() { + remote.exec('git pull'); + }); + }; + + /* + @method addToPlan + Takes a flightplan instance and adds a task called gitDeploy + @param plan {Object} Flightplan instance + @param plan.runtime.options.webRoot {String} Remote path to run git pull + */ + var addToPlan = function (plan) { + // Plan to git deploy via ssh remote + var webRoot = plan.runtime.options.webRoot; - // git pull - remote.with('cd ' + webRoot, function() { - remote.exec('git pull'); - }); -}); + plan.remote('gitDeploy', function(remote) { + remoteGitDeploy(remote, webRoot); + }); + }; + + return { + addToPlan: addToPlan, + remoteGitDeploy: remoteGitDeploy + }; +}
88be0d0fa047a6b7e9b13db8c59683db85e6794a
app/scripts/themes.js
app/scripts/themes.js
angular.module('GLClient.themes', []) .factory('Templates', function() { var selected_theme = 'default'; return { 'home': 'templates/' + selected_theme + '/views/home.html', 'about': 'templates/' + selected_theme + '/views/about.html', 'status': 'templates/' + selected_theme + '/views/status.html', 'submission': { 'form': 'templates/' + selected_theme + '/views/submission/form.html', 'main': 'templates/' + selected_theme + '/views/submission/main.html' } }; } );
angular.module('GLClient.themes', []) .factory('Templates', function() { // XXX do not add the "default" string to this file as it is used by // build-custom-glclient.sh for matching. var selected_theme = 'default'; return { 'home': 'templates/' + selected_theme + '/views/home.html', 'about': 'templates/' + selected_theme + '/views/about.html', 'status': 'templates/' + selected_theme + '/views/status.html', 'submission': { 'form': 'templates/' + selected_theme + '/views/submission/form.html', 'main': 'templates/' + selected_theme + '/views/submission/main.html' } }; } );
Add note about quirk related to build-custom-glclient.sh
Add note about quirk related to build-custom-glclient.sh
JavaScript
agpl-3.0
vodkina/GlobaLeaks,vodkina/GlobaLeaks,vodkina/GlobaLeaks,vodkina/GlobaLeaks
--- +++ @@ -1,5 +1,7 @@ angular.module('GLClient.themes', []) .factory('Templates', function() { + // XXX do not add the "default" string to this file as it is used by + // build-custom-glclient.sh for matching. var selected_theme = 'default'; return {
72048194677c0ac8c0276c1066e816d31ed43cb5
test/test-creation.js
test/test-creation.js
/*global describe, beforeEach, it*/ 'use strict'; var path = require('path'); var helpers = require('yeoman-generator').test; describe('plugin generator', function () { beforeEach(function (done) { helpers.testDirectory(path.join(__dirname, 'temp'), function (err) { if (err) { return done(err); } this.app = helpers.createGenerator('plugin:app', [ '../../app' ]); done(); }.bind(this)); }); it('creates expected files', function (done) { var expected = [ // add files you expect to exist here. '.jshintrc', '.editorconfig' ]; helpers.mockPrompt(this.app, { 'someOption': true }); this.app.options['skip-install'] = true; this.app.run({}, function () { helpers.assertFiles(expected); done(); }); }); });
/*global describe, beforeEach, it*/ 'use strict'; var path = require('path'); var helpers = require('yeoman-generator').test; describe('plugin generator', function () { beforeEach(function (done) { helpers.testDirectory(path.join(__dirname, 'temp'), function (err) { if (err) { return done(err); } this.app = helpers.createGenerator('plugin:app', [ '../../app' ]); done(); }.bind(this)); }); it('creates expected files', function (done) { var expected = [ // add files you expect to exist here. '.jshintrc', '.editorconfig', '.gitignore', '.npmignore', 'LICENSE-MIT', 'bower.json', 'test/main.js', 'index.js' ]; helpers.mockPrompt(this.app, { pluginName: 'myPlugin', fullName: 'assemble-plugin-myPlugin', description: 'The best plugin ever', user: 'assemble', stages: ['render:after:pages'], homepage: 'https://github.com/assemble/assemble-plugin-myPlugin', repositoryUrl: 'https://github.com/assemble/assemble-plugin-myPlugin.git', bugUrl: 'https://github.com/assemble/assemble-plugin-myPlugin/issues', licenseType: 'MIT', licenseUrl: 'https://github.com/assemble/assemble-plugin-myPlugin/blob/master/LICENSE-MIT', contributors: 'assemble' }); this.app.options['skip-install'] = true; this.app.run({}, function () { helpers.assertFile(expected); done(); }); }); });
Update test mockPromt and expected
Update test mockPromt and expected
JavaScript
mit
assemble/generator-plugin
--- +++ @@ -6,6 +6,7 @@ describe('plugin generator', function () { + beforeEach(function (done) { helpers.testDirectory(path.join(__dirname, 'temp'), function (err) { if (err) { @@ -20,18 +21,37 @@ }); it('creates expected files', function (done) { + var expected = [ // add files you expect to exist here. '.jshintrc', - '.editorconfig' + '.editorconfig', + '.gitignore', + '.npmignore', + 'LICENSE-MIT', + 'bower.json', + 'test/main.js', + 'index.js' ]; helpers.mockPrompt(this.app, { - 'someOption': true + pluginName: 'myPlugin', + fullName: 'assemble-plugin-myPlugin', + description: 'The best plugin ever', + user: 'assemble', + stages: ['render:after:pages'], + homepage: 'https://github.com/assemble/assemble-plugin-myPlugin', + repositoryUrl: 'https://github.com/assemble/assemble-plugin-myPlugin.git', + bugUrl: 'https://github.com/assemble/assemble-plugin-myPlugin/issues', + licenseType: 'MIT', + licenseUrl: 'https://github.com/assemble/assemble-plugin-myPlugin/blob/master/LICENSE-MIT', + contributors: 'assemble' }); + this.app.options['skip-install'] = true; + this.app.run({}, function () { - helpers.assertFiles(expected); + helpers.assertFile(expected); done(); }); });
6e81e98a48eeb01bf69e89c3192c48424f364f51
examples/playground/webpack.config.js
examples/playground/webpack.config.js
var webpack = require('webpack') module.exports = { context: __dirname, entry: [ "./index", "webpack-dev-server/client?http://localhost:8080", "webpack/hot/only-dev-server", ], output: { path: __dirname + "/public", filename: "bundle.js" }, module: { loaders: [{ test: /\.khufu$/, loaders: ['babel', '../../src/loader'], exclude: /node_modules/, }, { test: /\.js$/, loaders: ['babel'], exclude: /node_modules/, }], }, resolve: { modulesDirectories: ["/usr/local/lib/node_modules", "../.."], }, resolveLoader: { modulesDirectories: ["/usr/local/lib/node_modules"], }, devServer: { contentBase: '.', hot: true, }, khufu: { static_attrs: false, // for normal hot reload }, plugins: [ new webpack.NoErrorsPlugin(), ], }
var webpack = require('webpack') var DEV = process.env['NODE_ENV'] != 'production'; module.exports = { context: __dirname, entry: DEV ? [ "./index", "webpack-dev-server/client?http://localhost:8080", "webpack/hot/only-dev-server", ] : "./index", output: { path: __dirname + "/public", filename: "bundle.js" }, module: { loaders: [{ test: /\.khufu$/, loaders: ['babel', '../../src/loader'], exclude: /node_modules/, }, { test: /\.js$/, loaders: ['babel'], exclude: /node_modules/, }], }, resolve: { modulesDirectories: ["/usr/local/lib/node_modules", "../.."], }, resolveLoader: { modulesDirectories: ["/usr/local/lib/node_modules"], }, devServer: { contentBase: '.', hot: true, }, khufu: { static_attrs: !DEV, }, plugins: [ new webpack.NoErrorsPlugin(), ], }
Add non-hot-reload build support for playground
Add non-hot-reload build support for playground
JavaScript
apache-2.0
tailhook/khufu
--- +++ @@ -1,11 +1,12 @@ var webpack = require('webpack') +var DEV = process.env['NODE_ENV'] != 'production'; module.exports = { context: __dirname, - entry: [ + entry: DEV ? [ "./index", "webpack-dev-server/client?http://localhost:8080", "webpack/hot/only-dev-server", - ], + ] : "./index", output: { path: __dirname + "/public", filename: "bundle.js" @@ -32,7 +33,7 @@ hot: true, }, khufu: { - static_attrs: false, // for normal hot reload + static_attrs: !DEV, }, plugins: [ new webpack.NoErrorsPlugin(),
e212a38b3032b1ad19debbb5d7b3b183cc6b9670
webapp/routes/temperature_api.js
webapp/routes/temperature_api.js
'use strict'; const router = require('express').Router(); const temperatureapi = require('../api/temperature'); const requiresApiAuthorization = require('../auth/requiresApiAuthorization'); router.get('/api/temperature/currentTemperature', requiresApiAuthorization(), temperatureapi.getCurrentTemperature); module.exports = router;
'use strict'; const router = require('express').Router(); const temperatureapi = require('../api/temperature'); const requiresApiAuthorization = require('../auth/requiresApiAuthorization'); const auth = require('../auth/Authentication'); router.get('/api/temperature/currentTemperature', requiresApiAuthorization(), temperatureapi.getCurrentTemperature); router.get('/api/temperature/', auth.getBearerHandler(), temperatureapi.getCurrentTemperature); module.exports = router;
Add token authenticated temperature route
Add token authenticated temperature route
JavaScript
apache-2.0
rossharper/raspberrysauce,rossharper/raspberrysauce
--- +++ @@ -3,7 +3,10 @@ const router = require('express').Router(); const temperatureapi = require('../api/temperature'); const requiresApiAuthorization = require('../auth/requiresApiAuthorization'); +const auth = require('../auth/Authentication'); router.get('/api/temperature/currentTemperature', requiresApiAuthorization(), temperatureapi.getCurrentTemperature); +router.get('/api/temperature/', auth.getBearerHandler(), temperatureapi.getCurrentTemperature); + module.exports = router;
1d92056ea7405c5d8d9da577c2baf5d581236bf1
src/server/lib/findFilePath.js
src/server/lib/findFilePath.js
import path from "path"; import config from "config"; export default function findPath(configName) { let configRoot = process.env.FILE_PATH || "files"; if (config.paths && config.paths.files) { configRoot = config.paths.files; } let configPath = path.join(configRoot, configName); if (config.paths && config.paths[configName]) { configPath = config.paths[configName]; } if (configPath[0] !== "/") { configPath = path.join(__dirname, "..", "..", "..", configPath); } return configPath; }
import path from "path"; import config from "config"; export default function findPath(configName) { const configRoot = process.env.FILE_PATH || "files"; let configPath = path.join(configRoot, configName); if (config.paths && config.paths[configName]) { configPath = config.paths[configName]; } if (configPath[0] !== "/") { configPath = path.join(__dirname, "..", "..", "..", configPath); } return configPath; }
Fix shared file path config reading
Fix shared file path config reading
JavaScript
agpl-3.0
strekmann/nidarholmjs,strekmann/nidarholmjs,strekmann/nidarholmjs,strekmann/nidarholmjs
--- +++ @@ -3,10 +3,7 @@ import config from "config"; export default function findPath(configName) { - let configRoot = process.env.FILE_PATH || "files"; - if (config.paths && config.paths.files) { - configRoot = config.paths.files; - } + const configRoot = process.env.FILE_PATH || "files"; let configPath = path.join(configRoot, configName); if (config.paths && config.paths[configName]) { configPath = config.paths[configName];
6b50ec716db9b529220500a1ae3d5db2e80f1d83
ci/tagElmRelease.js
ci/tagElmRelease.js
const execSync = require('child_process').execSync; /** A semantic release "publish" plugin to create git tags and publish using elm-package */ async function tagElmRelease(config, context) { const newVersion = context.nextRelease.version; exec(`git tag -a ${newVersion} -m "elm-package release ${newVersion}"`); exec(`git push --tags`); exec(`elm-package publish`); } function exec(command, context) { context.logger.log(`Running: ${command}`); execSync(command); } module.exports = tagElmRelease;
const execSync = require('child_process').execSync; /** A semantic release "publish" plugin to create git tags and publish using elm-package */ async function tagElmRelease(config, context) { function exec(command) { context.logger.log(`Running: ${command}`); execSync(command); } const newVersion = context.nextRelease.version; exec(`git tag -a ${newVersion} -m "elm-package release ${newVersion}"`); exec(`git push --tags`); exec(`elm-package publish`); } module.exports = tagElmRelease;
Fix error with elm deployments
fix(ci): Fix error with elm deployments Note: this update does not change any user facing code and is related to our continuous integration / semantic release process only. I am tagging it as "fix" so we can continue to test the release process.
JavaScript
bsd-3-clause
cultureamp/elm-css-modules-loader,cultureamp/elm-css-modules-loader
--- +++ @@ -4,15 +4,15 @@ A semantic release "publish" plugin to create git tags and publish using elm-package */ async function tagElmRelease(config, context) { + function exec(command) { + context.logger.log(`Running: ${command}`); + execSync(command); + } + const newVersion = context.nextRelease.version; exec(`git tag -a ${newVersion} -m "elm-package release ${newVersion}"`); exec(`git push --tags`); exec(`elm-package publish`); } -function exec(command, context) { - context.logger.log(`Running: ${command}`); - execSync(command); -} - module.exports = tagElmRelease;
0d4f743d87898f101d47a733572f55eae1128be9
lib/actions/upload-actions.js
lib/actions/upload-actions.js
// @flow import type { FetchJSON } from '../utils/fetch-json'; import type { UploadMultimediaResult } from '../types/media-types'; async function uploadMultimedia( fetchJSON: FetchJSON, multimedia: Object, onProgress: (percent: number) => void, abortHandler: (abort: () => void) => void, ): Promise<UploadMultimediaResult> { const response = await fetchJSON( 'upload_multimedia', { multimedia }, { blobUpload: true, onProgress, abortHandler }, ); return { id: response.id, uri: response.uri }; } const assignMediaServerIDToMessageActionType = "ASSIGN_MEDIA_SERVER_ID_TO_MESSAGE"; const assignMediaServerURIToMessageActionType = "ASSIGN_MEDIA_SERVER_URI_TO_MESSAGE"; export { uploadMultimedia, assignMediaServerIDToMessageActionType, assignMediaServerURIToMessageActionType, };
// @flow import type { FetchJSON } from '../utils/fetch-json'; import type { UploadMultimediaResult } from '../types/media-types'; async function uploadMultimedia( fetchJSON: FetchJSON, multimedia: Object, onProgress: (percent: number) => void, abortHandler: (abort: () => void) => void, ): Promise<UploadMultimediaResult> { const response = await fetchJSON( 'upload_multimedia', { multimedia: [ multimedia ] }, { blobUpload: true, onProgress, abortHandler }, ); return { id: response.id, uri: response.uri }; } const assignMediaServerIDToMessageActionType = "ASSIGN_MEDIA_SERVER_ID_TO_MESSAGE"; const assignMediaServerURIToMessageActionType = "ASSIGN_MEDIA_SERVER_URI_TO_MESSAGE"; export { uploadMultimedia, assignMediaServerIDToMessageActionType, assignMediaServerURIToMessageActionType, };
Fix bug in multimedia upload
[lib] Fix bug in multimedia upload `uploadBlob` expects an array of multimedia, not a single one.
JavaScript
bsd-3-clause
Ashoat/squadcal,Ashoat/squadcal,Ashoat/squadcal,Ashoat/squadcal,Ashoat/squadcal,Ashoat/squadcal,Ashoat/squadcal
--- +++ @@ -11,7 +11,7 @@ ): Promise<UploadMultimediaResult> { const response = await fetchJSON( 'upload_multimedia', - { multimedia }, + { multimedia: [ multimedia ] }, { blobUpload: true, onProgress, abortHandler }, ); return { id: response.id, uri: response.uri };
c1893a257a0685934607946f4c24758796eb74bf
lib/formatters/codeclimate.js
lib/formatters/codeclimate.js
'use strict'; module.exports = function (err, data) { if (err) { return 'Debug output: %j' + JSON.stringify(data) + '\n' + JSON.stringify(err); } if (!data.length) { return; } var returnString = ''; for (var i = 0, il = data.length; i < il; ++i) { returnString += JSON.stringify({ type: 'issue', check_name: 'Vulnerable module "' + data[i].module + '" identified', description: '`' + data[i].module + '` ' + data[i].title, categories: ['Security'], remediation_points: 300000, content: { body: data[i].content }, location: { path: 'npm-shrinkwrap.json', lines: { begin: data[i].line.start, end: data[i].line.end } } }) + '\0\n'; } return returnString; };
'use strict'; module.exports = function (err, data) { if (err) { return err.stack; } if (!data.length) { return; } var returnString = ''; for (var i = 0, il = data.length; i < il; ++i) { returnString += JSON.stringify({ type: 'issue', check_name: 'Vulnerable module "' + data[i].module + '" identified', description: '`' + data[i].module + '` ' + data[i].title, categories: ['Security'], remediation_points: 300000, content: { body: data[i].content }, location: { path: 'npm-shrinkwrap.json', lines: { begin: data[i].line.start, end: data[i].line.end } } }) + '\0\n'; } return returnString; };
Return error message in Code Climate runs
Return error message in Code Climate runs Stringifying an Error object results in {} so the formatter was not returning the actual underlying error with the Code Climate formatter. This change returns the error so that they user can take action if an analysis run fails. This change returns the Error stack which includes a helpful error message and the backtrace for debugging purposes.
JavaScript
apache-2.0
requiresafe/cli,chetanddesai/nsp,nodesecurity/nsp,ABaldwinHunter/nsp-classic,ABaldwinHunter/nsp
--- +++ @@ -3,7 +3,7 @@ module.exports = function (err, data) { if (err) { - return 'Debug output: %j' + JSON.stringify(data) + '\n' + JSON.stringify(err); + return err.stack; } if (!data.length) {
1588f4b832ba791ce295c2367c92b7607817fa48
lib/atom-dataset-provider/options.js
lib/atom-dataset-provider/options.js
/*:tabSize=2:indentSize=2:noTabs=true:mode=javascript:*/ var commander = require('commander'), path = require('path'); var version = JSON.parse(require('fs') .readFileSync(path.join(__dirname, '..', '..', 'package.json'))) .version; var stringToPattern = function(strPattern) { if (strPattern.charAt(0) == '/') strPattern = strPattern.slice(1, strPattern.length-1); return new RegExp(strPattern); }; var Options = function() { return (new commander.Command) .version(version) .option('-d, --directory <dir>', '<dir> to monitor', '.') .option('-p, --port <port>', '<port> to serve on', parseInt, 4000) .option('--title <title>', '<title> for feed', require('os').hostname()) .option('--group-pattern <pattern>', '<pattern> with capture to group by. eg. /^(.*)\.\w+$/', stringToPattern, /^(.*)\.\w+$/); } exports = module.exports = Options;
/*:tabSize=2:indentSize=2:noTabs=true:mode=javascript:*/ var commander = require('commander'), path = require('path'); var version = JSON.parse(require('fs') .readFileSync(path.join(__dirname, '..', '..', 'package.json'))) .version; var stringToPattern = function(strPattern) { if (strPattern.charAt(0) == '/') strPattern = strPattern.slice(1, strPattern.length-1); return new RegExp(strPattern); }; var Options = function() { return (new commander.Command) .version(version) .option('-d, --directory <dir>', '<dir> to monitor', '.') .option('-p, --port <port>', '<port> to serve on', parseInt, 4000) .option('--title <title>', '<title> for feed', require('os').hostname()) .option('--group-pattern <pattern>', '<pattern> with capture to group by. eg. /^(.*)\\.\\w+$/', stringToPattern, /^(.*)\.\w+$/); } exports = module.exports = Options;
Correct minor typo in group-pattern help.
Correct minor typo in group-pattern help.
JavaScript
mit
tjdett/atom-dataset-provider
--- +++ @@ -20,7 +20,7 @@ .option('-p, --port <port>', '<port> to serve on', parseInt, 4000) .option('--title <title>', '<title> for feed', require('os').hostname()) .option('--group-pattern <pattern>', - '<pattern> with capture to group by. eg. /^(.*)\.\w+$/', + '<pattern> with capture to group by. eg. /^(.*)\\.\\w+$/', stringToPattern, /^(.*)\.\w+$/); }
5d4ee69a7d577d2906b08d228bd883afbb22caae
config.js
config.js
export default { "url": process.env.CRN_SERVER_URL, "port": 8111, "location": process.env.CRN_SERVER_LOCATION, "headers": { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, POST, OPTIONS, PUT, PATCH, DELETE", "Access-Control-Allow-Headers": "content-type, Authorization" }, "scitran": { "url": "http://localhost:8110/api/", "secret": process.env.SCITRAN_CORE_DRONE_SECRET, "fileStore": process.env.CRN_SERVER_CORE_FILE_STORE }, "agave": { "url": process.env.CRN_SERVER_AGAVE_URL, "username": process.env.CRN_SERVER_AGAVE_USERNAME, "password": process.env.CRN_SERVER_AGAVE_PASSWORD, "clientName": process.env.CRN_SERVER_AGAVE_CLIENT_NAME, "clientDescription": process.env.CRN_SERVER_AGAVE_CLIENT_DESCRIPTION, "consumerKey": process.env.CRN_SERVER_AGAVE_CONSUMER_KEY, "consumerSecret": process.env.CRN_SERVER_AGAVE_CONSUMER_SECRET, "storage": process.env.CRN_SERVER_AGAVE_STORAGE }, "mongo": { "url": "mongodb://localhost:27017/crn" } };
let config = { "url": process.env.CRN_SERVER_URL, "port": 8111, "location": process.env.CRN_SERVER_LOCATION, "headers": { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, POST, OPTIONS, PUT, PATCH, DELETE", "Access-Control-Allow-Headers": "content-type, Authorization" }, "scitran": { "url": "http://localhost:8110/api/", "secret": process.env.SCITRAN_CORE_DRONE_SECRET, "fileStore": process.env.CRN_SERVER_CORE_FILE_STORE }, "agave": { "url": process.env.CRN_SERVER_AGAVE_URL, "username": process.env.CRN_SERVER_AGAVE_USERNAME, "password": process.env.CRN_SERVER_AGAVE_PASSWORD, "clientName": process.env.CRN_SERVER_AGAVE_CLIENT_NAME, "clientDescription": process.env.CRN_SERVER_AGAVE_CLIENT_DESCRIPTION, "consumerKey": process.env.CRN_SERVER_AGAVE_CONSUMER_KEY, "consumerSecret": process.env.CRN_SERVER_AGAVE_CONSUMER_SECRET, "storage": process.env.CRN_SERVER_AGAVE_STORAGE }, "mongo": { "url": "mongodb://localhost:27017/crn" } }; console.log(config); export default config;
Add logging for docker debugging
Add logging for docker debugging
JavaScript
mit
poldracklab/crn_server,poldracklab/crn_server
--- +++ @@ -1,4 +1,4 @@ -export default { +let config = { "url": process.env.CRN_SERVER_URL, "port": 8111, "location": process.env.CRN_SERVER_LOCATION, @@ -26,3 +26,6 @@ "url": "mongodb://localhost:27017/crn" } }; + +console.log(config); +export default config;
70405b476543b96bbeeb3299ac83c3ffd9aa86be
lib/honyomi/web/public/js/honyomi.js
lib/honyomi/web/public/js/honyomi.js
$(document).ready(function() { $('.star').click(function() { // Toggle a display of star $(this).toggleClass('favorited'); var isFavorited = $(this).hasClass('favorited'); // Get a page info var id = $(this).attr('honyomi-id'); var page_no = $(this).attr('honyomi-page-no'); // ajax $.post( '/command', { kind: 'favorite', id: id, page_no: page_no, favorited: isFavorited }, function(data) { // Return a result of POST } ); }); });
$(document).ready(function() { $(document).on('click', '.star', function(e) { // Toggle a display of star $(this).toggleClass('favorited'); var isFavorited = $(this).hasClass('favorited'); // Get a page info var id = $(this).attr('honyomi-id'); var page_no = $(this).attr('honyomi-page-no'); // ajax $.post( '/command', { kind: 'favorite', id: id, page_no: page_no, favorited: isFavorited }, function(data) { // Return a result of POST } ); e.preventDefault(); }); });
Support the AutoPagerize in the click event
Support the AutoPagerize in the click event
JavaScript
mit
ongaeshi/honyomi,ongaeshi/honyomi,ongaeshi/honyomi
--- +++ @@ -1,5 +1,5 @@ $(document).ready(function() { - $('.star').click(function() { + $(document).on('click', '.star', function(e) { // Toggle a display of star $(this).toggleClass('favorited'); var isFavorited = $(this).hasClass('favorited'); @@ -21,5 +21,7 @@ // Return a result of POST } ); + + e.preventDefault(); }); });
a50bbdcd25e3618112f6515ca64fc2c6fa67f1c3
front_end/app/screens/ShoppingList.js
front_end/app/screens/ShoppingList.js
import React, {Component} from 'react'; import { View, Text, ScrollView, Button } from 'react-native'; import axios from 'axios'; import colors from '../config/colors'; import { UserItem } from '../components/UserItem'; class ShoppingList extends Component { constructor(props) { super(props); this.state = { userItems: [] }; this.getUserItems = this.getUserItems.bind(this); this.handleButtonPress = this.handleButtonPress.bind(this); } componentDidMount() { this.getUserItems(); } getUserItems() { axios.get('http://localhost:3000/user_items') .then(response => { this.setState({userItems: response.data}) }) .catch(error => { console.log(error); }); } handleButtonPress() { this.props.navigation.navigate('PickStop'); }; render() { return ( <View style={{ backgroundColor: colors.background }}> <ScrollView style={{ backgroundColor: colors.background}}> {this.state.userItems.map((userItem, idx) => ( <UserItem user_item={userItem} getUserItems={this.getUserItems} key={idx} /> ))} </ScrollView> <Button onPress={() => this.handleButtonPress()} title="Find Yo' Stop!" color={colors.buttonText} backgroundColor={colors.buttonBackground} accessibilityLabel="Find Your Stop for One Stop Shopping" style={{height: 600}} /> </View> ); } } export default ShoppingList;
import React, {Component} from 'react'; import { View, Text, ScrollView } from 'react-native'; import { Button } from 'native-base'; import axios from 'axios'; import colors from '../config/colors'; import { UserItem } from '../components/UserItem'; class ShoppingList extends Component { constructor(props) { super(props); this.state = { userItems: [] }; this.getUserItems = this.getUserItems.bind(this); this.handleButtonPress = this.handleButtonPress.bind(this); } componentDidMount() { this.getUserItems(); } getUserItems() { axios.get('http://localhost:3000/user_items') .then(response => { this.setState({userItems: response.data}) }) .catch(error => { console.log(error); }); } handleButtonPress() { this.props.navigation.navigate('PickStop'); }; render() { return ( <View style={{ backgroundColor: colors.background }}> <ScrollView style={{ backgroundColor: colors.background}}> {this.state.userItems.map((userItem, idx) => ( <UserItem user_item={userItem} getUserItems={this.getUserItems} key={idx} /> ))} </ScrollView> <Button full onPress={() => this.handleButtonPress()}> <Text>Find Yo' Stop!</Text> </Button> </View> ); } } export default ShoppingList;
Add button full component to shopping list
Add button full component to shopping list
JavaScript
mit
DaniGlass/OneStopShop,DaniGlass/OneStopShop,DaniGlass/OneStopShop,DaniGlass/OneStopShop,DaniGlass/OneStopShop
--- +++ @@ -1,5 +1,6 @@ import React, {Component} from 'react'; -import { View, Text, ScrollView, Button } from 'react-native'; +import { View, Text, ScrollView } from 'react-native'; +import { Button } from 'native-base'; import axios from 'axios'; import colors from '../config/colors'; @@ -43,14 +44,9 @@ <UserItem user_item={userItem} getUserItems={this.getUserItems} key={idx} /> ))} </ScrollView> - <Button - onPress={() => this.handleButtonPress()} - title="Find Yo' Stop!" - color={colors.buttonText} - backgroundColor={colors.buttonBackground} - accessibilityLabel="Find Your Stop for One Stop Shopping" - style={{height: 600}} - /> + <Button full onPress={() => this.handleButtonPress()}> + <Text>Find Yo' Stop!</Text> + </Button> </View> ); }
8a81c825a2687f988cd231f458fbc16d39e7c3fa
frontend/app/routes/questions/show.js
frontend/app/routes/questions/show.js
import Ember from 'ember'; export default Ember.Route.extend({ model: function(params) { return this.store.find('question', params.id); } });
import Ember from 'ember'; export default Ember.Route.extend({ model: function(params) { return this.store.find('question', params.id); }, actions: { didTransition: function() { this.get('controller').set('isEditing', false); } } });
Reset controller state on didTransition
Reset controller state on didTransition
JavaScript
mit
LaunchAcademy/rescue_mission,LaunchAcademy/rescue_mission,LaunchAcademy/rescue_mission
--- +++ @@ -3,5 +3,11 @@ export default Ember.Route.extend({ model: function(params) { return this.store.find('question', params.id); + }, + + actions: { + didTransition: function() { + this.get('controller').set('isEditing', false); + } } });
00b8cf436ea49f4939d1c0790ac19789f713153f
js/app.js
js/app.js
import React from "react"; import { render } from "react-dom"; import { applyRouterMiddleware, Router, Route, browserHistory, IndexRoute } from "react-router"; import { useScroll } from 'react-router-scroll'; import App from "./components/App.react"; import TagList from "./components/TagList.react"; import NotFound from "./components/NotFound"; import PluginList from "./components/PluginList.react"; import { syncHistoryWithStore } from "react-router-redux"; import store from "./stores/CreateStore"; import { Provider } from "react-redux"; import "whatwg-fetch"; import Css from "../css/main.css"; import Tags from "./tags"; const history = syncHistoryWithStore(browserHistory, store); var routes = ( <Router history={history} render={applyRouterMiddleware(useScroll())}> <Route path="/" component={App}> <IndexRoute component={TagList} /> { Tags.map((tag) => <Route key={tag} path={`tag/${tag}`} component={PluginList} tag={tag} />) } <Route path="*" component={NotFound} /> </Route> </Router> ) render( <Provider store={store}> {routes} </Provider>, document.getElementById('app') );
import React from "react"; import { render } from "react-dom"; import { applyRouterMiddleware, Router, Route, browserHistory, IndexRoute } from "react-router"; import { useScroll } from 'react-router-scroll'; import App from "./components/App.react"; import TagList from "./components/TagList.react"; import NotFound from "./components/NotFound"; import PluginList from "./components/PluginList.react"; import { syncHistoryWithStore } from "react-router-redux"; import store from "./stores/CreateStore"; import { Provider } from "react-redux"; import "whatwg-fetch"; import globalStyes from './global-styles'; import Tags from "./tags"; const history = syncHistoryWithStore(browserHistory, store); var routes = ( <Router history={history} render={applyRouterMiddleware(useScroll())}> <Route path="/" component={App}> <IndexRoute component={TagList} /> { Tags.map((tag) => <Route key={tag} path={`tag/${tag}`} component={PluginList} tag={tag} />) } <Route path="*" component={NotFound} /> </Route> </Router> ) render( <Provider store={store}> {routes} </Provider>, document.getElementById('app') );
Remove css import, add global styles
Remove css import, add global styles
JavaScript
mit
mxstbr/postcss.parts,mxstbr/postcss.parts
--- +++ @@ -15,21 +15,21 @@ import { Provider } from "react-redux"; import "whatwg-fetch"; -import Css from "../css/main.css"; +import globalStyes from './global-styles'; import Tags from "./tags"; const history = syncHistoryWithStore(browserHistory, store); var routes = ( - <Router history={history} render={applyRouterMiddleware(useScroll())}> - <Route path="/" component={App}> - <IndexRoute component={TagList} /> - { - Tags.map((tag) => <Route key={tag} path={`tag/${tag}`} component={PluginList} tag={tag} />) - } - <Route path="*" component={NotFound} /> - </Route> - </Router> + <Router history={history} render={applyRouterMiddleware(useScroll())}> + <Route path="/" component={App}> + <IndexRoute component={TagList} /> + { + Tags.map((tag) => <Route key={tag} path={`tag/${tag}`} component={PluginList} tag={tag} />) + } + <Route path="*" component={NotFound} /> + </Route> + </Router> ) render(
7d49a20492e4a92afb07c194195856292b72a589
lib/modules/storage/utils/omit_undefined.js
lib/modules/storage/utils/omit_undefined.js
import _ from 'lodash'; function omitUndefined(obj) { const result = {}; _.forOwn(obj, function(value, key) { if (_.isPlainObject(value)) { result[key] = omitUndefined(value); } else if (!_.isUndefined(value)) { result[key] = value; } }); return result; } export default omitUndefined;
import _ from 'lodash'; function omitUndefined(obj) { return _.transform(obj, function(result, value, key) { if (_.isPlainObject(value)) { result[key] = omitUndefined(value); } else if (!_.isUndefined(value)) { result[key] = value; } }); } export default omitUndefined;
Use _.transform instead of _.reduce
Use _.transform instead of _.reduce
JavaScript
mit
jagi/meteor-astronomy
--- +++ @@ -1,8 +1,7 @@ import _ from 'lodash'; function omitUndefined(obj) { - const result = {}; - _.forOwn(obj, function(value, key) { + return _.transform(obj, function(result, value, key) { if (_.isPlainObject(value)) { result[key] = omitUndefined(value); } @@ -10,7 +9,6 @@ result[key] = value; } }); - return result; } export default omitUndefined;
72f827e84ba5e696d0bacdb8b900018c7a51dc55
main-process/native-ui/dialogs/open-file.js
main-process/native-ui/dialogs/open-file.js
var ipc = require('electron').ipcMain; var dialog = require('electron').dialog; module.exports.setup = function () { ipc.on('open-file-dialog', function (event) { var files = dialog.showOpenDialog({properties: ['openFile', 'openDirectory']}); if (files) { event.sender.send('selected-directory', files); } }); };
var ipc = require('electron').ipcMain; var dialog = require('electron').dialog; module.exports.setup = function () { ipc.on('open-file-dialog', function (event) { dialog.showOpenDialog({properties: ['openFile', 'openDirectory']}, function (files) { if (files) { event.sender.send('selected-directory', files); } }); }); };
Use callback for dialog API
Use callback for dialog API
JavaScript
mit
PanCheng111/XDF_Personal_Analysis,PanCheng111/XDF_Personal_Analysis,blep/electron-api-demos,electron/electron-api-demos,blep/electron-api-demos,electron/electron-api-demos,blep/electron-api-demos,blep/electron-api-demos,electron/electron-api-demos,PanCheng111/XDF_Personal_Analysis
--- +++ @@ -3,7 +3,8 @@ module.exports.setup = function () { ipc.on('open-file-dialog', function (event) { - var files = dialog.showOpenDialog({properties: ['openFile', 'openDirectory']}); - if (files) { event.sender.send('selected-directory', files); } + dialog.showOpenDialog({properties: ['openFile', 'openDirectory']}, function (files) { + if (files) { event.sender.send('selected-directory', files); } + }); }); };
6c2e22850f428e208acda085417e54bc911b3ddb
config/policies.js
config/policies.js
/** * Policy Mappings * (sails.config.policies) * * Policies are simple functions which run **before** your controllers. * You can apply one or more policies to a given controller, or protect * its actions individually. * * Any policy file (e.g. `api/policies/authenticated.js`) can be accessed * below by its filename, minus the extension, (e.g. "authenticated") * * For more information on how policies work, see: * http://sailsjs.org/#!/documentation/concepts/Policies * * For more information on configuring policies, check out: * http://sailsjs.org/#!/documentation/reference/sails.config/sails.config.policies.html */ module.exports.policies = { // Default behavior request authentication '*': ['jwtAuth', false], // Public routes AuthController: { ipLogin: true, oauthLogin: true, oauthLoginSubmit: true, jwtLogin: true, }, // Authenticated routes MessageController: { find: ['jwtAuth'], findOne: ['jwtAuth'], create: ['jwtAuth'], getChannels: ['jwtAuth'], }, };
/** * Policy Mappings * (sails.config.policies) * * Policies are simple functions which run **before** your controllers. * You can apply one or more policies to a given controller, or protect * its actions individually. * * Any policy file (e.g. `api/policies/authenticated.js`) can be accessed * below by its filename, minus the extension, (e.g. "authenticated") * * For more information on how policies work, see: * http://sailsjs.org/#!/documentation/concepts/Policies * * For more information on configuring policies, check out: * http://sailsjs.org/#!/documentation/reference/sails.config/sails.config.policies.html */ module.exports.policies = { // Default behavior request authentication '*': ['jwtAuth', false], // Public routes AuthController: { ipLogin: true, oauthLogin: true, oauthLoginSubmit: true, jwtLogin: true, }, // Authenticated routes MessageController: { find: ['jwtAuth'], create: ['jwtAuth'], getChannels: ['jwtAuth'], }, };
Remove old route from config
Remove old route from config
JavaScript
mit
ungdev/flux2-server,ungdev/flux2-server,ungdev/flux2-server
--- +++ @@ -32,7 +32,6 @@ // Authenticated routes MessageController: { find: ['jwtAuth'], - findOne: ['jwtAuth'], create: ['jwtAuth'], getChannels: ['jwtAuth'], },