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
2bdfb9c7c5c51c86c46fcf724ffe0ce08ea0ebed
server/routes/index.js
server/routes/index.js
var _ = require('underscore'); var routes = [ 'users', 'building', 'units' ]; module.exports.mount = function(app) { _(routes).each(function(route){ require('./'+route+'_routes').mount(app); }); };
var _ = require('underscore'); var routes = [ 'users', 'building' ]; module.exports.mount = function(app) { _(routes).each(function(route){ require('./'+route+'_routes').mount(app); }); };
Fix server fatal error (loading non existant route)
Fix server fatal error (loading non existant route)
JavaScript
mit
romain-grelet/HackersWars,romain-grelet/HackersWars
--- +++ @@ -2,8 +2,7 @@ var routes = [ 'users', - 'building', - 'units' + 'building' ]; module.exports.mount = function(app) {
e43c291da3d14ac64a36254b8055ab4c750d790e
gulpfile.js
gulpfile.js
var gulp = require("gulp"), plugins = require("gulp-load-plugins")(), pkg = require("./package.json"), paths = { src: { css: "./src/main/resources/static/sass" }, dist: { css: "./src/main/resources/static/css" } }, config = { autoprefixer: { browsers: ["last 2 versions", "> 1%"] } }; // Build the Sass gulp.task("build:css", function() { return gulp.src(paths.src.css + "/**/*") // Prevents Sass from hanging on errors (syntax error, etc.) .pipe(plugins.plumber()) .pipe(plugins.sourcemaps.init()) // Need to use sass.sync() to work with Plumber correctly .pipe(plugins.sass.sync()) .pipe(plugins.autoprefixer(config.autoprefixer)) .pipe(gulp.dest(paths.dist.css)); }); // Clean the Sass build directory gulp.task("clean:css", function() { return gulp.src(paths.dist.css, { read: false }) .pipe(plugins.clean()); }) gulp.task("build", ["build:css"]); gulp.task("clean", ["clean:css"]); gulp.task("watch", function() { gulp.src(paths.src.css+ "/**/*", ["build:css"]); });
var gulp = require("gulp"), plugins = require("gulp-load-plugins")(), pkg = require("./package.json"), paths = { src: { css: "./src/main/resources/static/sass" }, dist: { css: "./src/main/resources/static/css" } }, config = { autoprefixer: { browsers: ["last 2 versions", "> 1%"] } }; // Build the Sass gulp.task("build:css", function() { return gulp.src(paths.src.css + "/**/*") // Prevents Sass from hanging on errors (syntax error, etc.) .pipe(plugins.plumber()) .pipe(plugins.sourcemaps.init()) // Need to use sass.sync() to work with Plumber correctly .pipe(plugins.sass.sync()) .pipe(plugins.autoprefixer(config.autoprefixer)) .pipe(plugins.sourcemaps.write("./")) .pipe(gulp.dest(paths.dist.css)); }); // Clean the Sass build directory gulp.task("clean:css", function() { return gulp.src(paths.dist.css, { read: false }) .pipe(plugins.clean()); }) gulp.task("build", ["build:css"]); gulp.task("clean", ["clean:css"]); gulp.task("watch", function() { gulp.src(paths.src.css+ "/**/*", ["build:css"]); });
Fix sourcemaps so they write to separate .map file
Fix sourcemaps so they write to separate .map file
JavaScript
mit
MTUHIDE/CoCoTemp,MTUHIDE/CoCoTemp,MTUHIDE/CoCoTemp,MTUHIDE/CoCoTemp,MTUHIDE/CoCoTemp
--- +++ @@ -24,6 +24,7 @@ // Need to use sass.sync() to work with Plumber correctly .pipe(plugins.sass.sync()) .pipe(plugins.autoprefixer(config.autoprefixer)) + .pipe(plugins.sourcemaps.write("./")) .pipe(gulp.dest(paths.dist.css)); });
ed290020fef0bd0708b3ca2f73b847927f9a4090
js/components/developer/payment-info-screen/index.js
js/components/developer/payment-info-screen/index.js
import React, { Component } from 'react'; import { View, Alert } from 'react-native'; import { Text, ListItem, Thumbnail, Body, Left, Form, Content, Button } from 'native-base'; import paymentInfoScreenStyle from './paymentInfoScreenStyle'; const alertMessage1 = 'För Kortet .... .... .... 4499\n'; const alertMessage2 = 'För Kortet .... .... .... 3232\n'; export default class PaymentInfoScreen extends Component { render() { return ( <Content> <Form> <ListItem avatar onPress={() => Alert.alert('Bekräfta Betalning', alertMessage1)}> <Left> <Thumbnail source={require('./master.png')} /> </Left> <Body> <Text> .... .... .... 4499</Text> <Text note>Master Card</Text> </Body> </ListItem> <ListItem avatar onPress={() => Alert.alert('Bekräfta Betalning', alertMessage2)}> <Left> <Thumbnail source={require('./visa.png')} /> </Left> <Body> <Text> .... .... .... 3232</Text> <Text note>Visa Card</Text> </Body> </ListItem> </Form> <View style={paymentInfoScreenStyle.addCardButton}> <Button block light> <Text>Lägg Till Kort</Text> </Button> </View> </Content> ); } }
import React, { Component } from 'react'; import { View, Alert } from 'react-native'; import { Text, ListItem, Thumbnail, Body, Left, Form, Content, Button } from 'native-base'; import paymentInfoScreenStyle from './paymentInfoScreenStyle'; const alertMessage1 = 'För Kortet .... .... .... 4499\n'; const alertMessage2 = 'För Kortet .... .... .... 3232\n'; export default class PaymentInfoScreen extends Component { static navigationOptions = { title: 'Payment Information', }; render() { return ( <Content> <Form> <ListItem avatar onPress={() => Alert.alert('Bekräfta Betalning', alertMessage1)}> <Left> <Thumbnail source={require('./master.png')} /> </Left> <Body> <Text> .... .... .... 4499</Text> <Text note>Master Card</Text> </Body> </ListItem> <ListItem avatar onPress={() => Alert.alert('Bekräfta Betalning', alertMessage2)}> <Left> <Thumbnail source={require('./visa.png')} /> </Left> <Body> <Text> .... .... .... 3232</Text> <Text note>Visa Card</Text> </Body> </ListItem> </Form> <View style={paymentInfoScreenStyle.addCardButton}> <Button block light> <Text>Lägg Till Kort</Text> </Button> </View> </Content> ); } }
Add missing title to navigation options in payment info screen
Add missing title to navigation options in payment info screen
JavaScript
mit
justarrived/p2p-client,justarrived/p2p-client,justarrived/p2p-client,justarrived/p2p-client
--- +++ @@ -8,6 +8,9 @@ export default class PaymentInfoScreen extends Component { + static navigationOptions = { + title: 'Payment Information', + }; render() { return (
94e5e9279953a4098ef01695586c4bea155cb1a2
Library/Application-Support/Firefox/Profiles/robgant.default/gm_scripts/Remove_Position_Fixed/Remove_Position_Fixed.user.js
Library/Application-Support/Firefox/Profiles/robgant.default/gm_scripts/Remove_Position_Fixed/Remove_Position_Fixed.user.js
// ==UserScript== // @name Remove Position Fixed // @namespace name.robgant // @description Makes anything on the page with position fixed become static // @include * // @version 1 // @grant GM_registerMenuCommand // @grant GM_getValue // @grant GM_setValue // ==/UserScript== function unfix_position() { // console.log("Unfixing Positions!!"); Array.forEach( document.querySelectorAll("div, header, section, nav") ,function(el) { if (window.getComputedStyle(el).position === 'fixed') { el.style.position = 'static'; el.style.cssText += ';position:static !important;'; } } ); } GM_registerMenuCommand("Position Unfixed", unfix_position); function set_default_unfix() { var domain = window.location.host; GM_setValue(domain, true); } GM_registerMenuCommand("Default Unfixed", set_default_unfix); var domain = window.location.host; if (GM_getValue(domain, false)) { // console.log("Default Unfixed Position"); window.addEventListener("scroll", function(evt){ unfix_position(); window.removeEventListener("scroll", arguments.callee); }, false); } //else { console.log("Not Default Unfixed Position"); }
// ==UserScript== // @name Remove Position Fixed // @namespace name.robgant // @description Makes some things on the page with position fixed become static. Adds a menu command to run the script. // @include * // @grant GM_registerMenuCommand // @grant GM_getValue // @grant GM_setValue // ==/UserScript== function unfix_position() { // console.log("Unfixing Positions!!"); Array.forEach( document.querySelectorAll("div, header, section, nav") ,function(el) { if (window.getComputedStyle(el).position === 'fixed') { el.style.position = 'static'; el.style.cssText += ';position:static !important;'; } } ); } GM_registerMenuCommand("Position Unfixed", unfix_position); function set_default_unfix() { var domain = window.location.host; GM_setValue(domain, true); } GM_registerMenuCommand("Default Unfixed", set_default_unfix); var domain = window.location.host; if (GM_getValue(domain, false)) { // console.log("Default Unfixed Position"); window.addEventListener("scroll", function(evt){ window.setTimeout(unfix_position, 800); window.removeEventListener("scroll", arguments.callee); }, false); } //else { console.log("Not Default Unfixed Position"); }
Use a timeout to handle position fixed only on scroll
Use a timeout to handle position fixed only on scroll
JavaScript
mit
rgant/homedir,rgant/homedir,rgant/homedir
--- +++ @@ -1,9 +1,8 @@ // ==UserScript== // @name Remove Position Fixed // @namespace name.robgant -// @description Makes anything on the page with position fixed become static +// @description Makes some things on the page with position fixed become static. Adds a menu command to run the script. // @include * -// @version 1 // @grant GM_registerMenuCommand // @grant GM_getValue // @grant GM_setValue @@ -35,7 +34,7 @@ if (GM_getValue(domain, false)) { // console.log("Default Unfixed Position"); window.addEventListener("scroll", function(evt){ - unfix_position(); + window.setTimeout(unfix_position, 800); window.removeEventListener("scroll", arguments.callee); }, false); }
68c44fd31849d23e3576f2e115db94fcffe2af3d
tests/bin/scheduler.spec.js
tests/bin/scheduler.spec.js
/* eslint-env node, mocha */ const expect = require('chai').expect const scheduler = require('../../src/bin/scheduler.js') describe('bin > scheduler', () => { it('can run the scheduler server', () => { expect(scheduler).to.exist }) })
/* eslint-env node, mocha */ const expect = require('chai').expect const proxyquire = require('proxyquire').noCallThru() const scheduler = proxyquire('../../src/bin/scheduler.js', { '../config/jobs.js': [] }) describe('bin > scheduler', () => { it('can run the scheduler server', () => { expect(scheduler).to.exist }) })
Make sure workers are not getting executed for tests
Make sure workers are not getting executed for tests
JavaScript
agpl-3.0
gw2efficiency/gw2-api.com
--- +++ @@ -1,6 +1,9 @@ /* eslint-env node, mocha */ const expect = require('chai').expect -const scheduler = require('../../src/bin/scheduler.js') +const proxyquire = require('proxyquire').noCallThru() +const scheduler = proxyquire('../../src/bin/scheduler.js', { + '../config/jobs.js': [] +}) describe('bin > scheduler', () => { it('can run the scheduler server', () => {
fc5bdfad980dc5c47512ba81f5ecf087db7e467b
lib/models.js
lib/models.js
'use strict'; const Path = require('path'); const Glob = require('glob'); async function getFiles(paths, ignored) { const opts = { nodir: true, dot: false, }; if (!Array.isArray(paths)) paths = [paths]; if (ignored) opts.ignore = ignored; return paths.reduce((acc, pattern) => { const joinPaths = Array.prototype.concat.bind([], acc); const paths = Glob.sync(pattern, opts); return joinPaths(paths); }, []); } async function load(files, fn) { if (!files) return Promise.resolve([]); if (!Array.isArray(files)) files = [files]; return files.reduce((acc, file) => { const models = {}; const filepath = Path.isAbsolute(file) ? file : Path.join(process.cwd(), file); const Model = fn(filepath); models[Model.name] = Model; return Object.assign({}, acc, models); }, {}); } async function applyRelations(models) { if (!models || typeof models !== 'object') throw new Error(`Can't apply relationships on invalid models object`); Object.keys(models).forEach(name => { if (models[name].hasOwnProperty('associate')) { models[name].associate(models); } }); return models; } module.exports = { getFiles, load, applyRelations, };
'use strict'; const Path = require('path'); const Glob = require('glob'); async function getFiles(paths, ignored) { const opts = { nodir: true, dot: false, }; if (!Array.isArray(paths)) paths = [paths]; if (ignored) opts.ignore = ignored; return paths.reduce((acc, pattern) => { const joinPaths = Array.prototype.concat.bind([], acc); const paths = Glob.sync(pattern, opts); return joinPaths(paths); }, []); } async function load(files, fn) { if (!files) return []; if (!Array.isArray(files)) files = [files]; return files.reduce((acc, file) => { const models = {}; const filepath = Path.isAbsolute(file) ? file : Path.join(process.cwd(), file); const Model = fn(filepath); models[Model.name] = Model; return Object.assign({}, acc, models); }, {}); } async function applyRelations(models) { if (!models || typeof models !== 'object') throw new Error(`Can't apply relationships on invalid models object`); Object.keys(models).forEach(name => { if (models[name].hasOwnProperty('associate')) { models[name].associate(models); } }); return models; } module.exports = { getFiles, load, applyRelations, };
Remove unnecessary use of Promise.resolve
Remove unnecessary use of Promise.resolve
JavaScript
mit
valtlfelipe/hapi-sequelizejs,valtlfelipe/hapi-sequelizejs
--- +++ @@ -20,7 +20,7 @@ } async function load(files, fn) { - if (!files) return Promise.resolve([]); + if (!files) return []; if (!Array.isArray(files)) files = [files]; return files.reduce((acc, file) => {
33c372227420154621ed4c187d5f9d479857b51a
src/_includes/scripts/in-page-nav.js
src/_includes/scripts/in-page-nav.js
const observer = new IntersectionObserver(entries => { const intersectingEntries = entries.filter(e => e.isIntersecting); for (const entry of intersectingEntries) { const previouslyActive = document.querySelector('.pageNav a.is-active'); if (previouslyActive) { previouslyActive.classList.remove('is-active'); } const id = entry.target.getAttribute('id') const newActive = document.querySelector(`.pageNav a[href="#${id}"]`); newActive.classList.add('is-active'); newActive.scrollIntoView({ block: 'nearest' }); } }, { rootMargin: `0% 0% -90% 0%` } ); //track headings with an id if (document.querySelector('.pageNav')) { for (const heading of document.querySelectorAll(':is(h2,h3,h4)[id]')) { observer.observe(heading) } }
const observer = new IntersectionObserver(entries => { const intersectingEntries = entries.filter(e => e.isIntersecting); for (const entry of intersectingEntries) { const previouslyActive = document.querySelector('.pageNav a.is-active'); if (previouslyActive) { previouslyActive.classList.remove('is-active'); } const id = entry.target.getAttribute('id') const newActive = document.querySelector(`.pageNav a[href="#${id}"]`); newActive.classList.add('is-active'); } }, { rootMargin: `0% 0% -90% 0%` } ); //track headings with an id if (document.querySelector('.pageNav')) { for (const heading of document.querySelectorAll(':is(h2,h3,h4)[id]')) { observer.observe(heading) } }
Remove scrollIntoView() to fix scroll jank preventing users from scrolling
Remove scrollIntoView() to fix scroll jank preventing users from scrolling
JavaScript
apache-2.0
WPO-Foundation/webpagetest-docs,WPO-Foundation/webpagetest-docs
--- +++ @@ -9,7 +9,6 @@ const id = entry.target.getAttribute('id') const newActive = document.querySelector(`.pageNav a[href="#${id}"]`); newActive.classList.add('is-active'); - newActive.scrollIntoView({ block: 'nearest' }); } }, { rootMargin: `0% 0% -90% 0%` } );
2a2b6a6d421855b20ee40f71695d897433eb41d2
javascripts/hints/hints.js
javascripts/hints/hints.js
// Model BustinBash.Hints.Model = function() {} // View BustinBash.Hints.View = function() {} BustinBash.Hints.View.prototype = { render: function(hint) { var source = $("#hints-template").html(); var template = Handlebars.compile(source); var context = {hint: hint} var text = template(context); $('.hints').html(text) } } // Controller BustinBash.Hints.Controller = function(view) { this.view = view; } BustinBash.Hints.Controller.prototype = { init: function() { this.bindListeners(); }, bindListeners: function() { $(document).on('changeLevel', function(event, data) { this.data = data }.bind(this)); $('#hint').on('click', function() { this.displayHint(this.data.Hint); }.bind(this)); }, displayHint: function(hint) { this.view.render(hint) } }
// View BustinBash.Hints.View = function() {} BustinBash.Hints.View.prototype = { render: function(hint) { var source = $("#hints-template").html(); var template = Handlebars.compile(source); var context = {hint: hint} var text = template(context); $('.hints').html(text) }, hideHint: function(){ $('#hint').hide() } } // Controller BustinBash.Hints.Controller = function(view) { this.view = view; } BustinBash.Hints.Controller.prototype = { init: function() { this.bindListeners(); }, bindListeners: function() { $(document).on('changeLevel', function(event, data) { this.data = data }.bind(this)); $('#hint').on('click', function() { this.displayHint(this.data.Hint); }.bind(this)); }, displayHint: function(hint) { this.view.render(hint) this.view.hideHint() } }
Hide hint button on click
Hide hint button on click
JavaScript
mit
BustinBash/BustinBash,BustinBash/bustinbash.github.io
--- +++ @@ -1,6 +1,3 @@ -// Model -BustinBash.Hints.Model = function() {} - // View BustinBash.Hints.View = function() {} @@ -11,6 +8,10 @@ var context = {hint: hint} var text = template(context); $('.hints').html(text) + }, + + hideHint: function(){ + $('#hint').hide() } } @@ -33,5 +34,6 @@ }, displayHint: function(hint) { this.view.render(hint) + this.view.hideHint() } }
5caaf488fe4d156dda95c99773e5d969a79a99de
sample/WebHook-GitHub/index.js
sample/WebHook-GitHub/index.js
module.exports = function (context) { context.log('GitHub WebHook triggered!'); context.done(null, 'New GitHub comment: ' + context.req.body.comment.body); }
module.exports = function (context) { context.log('GitHub WebHook triggered! ' + context.req.body.comment.body); context.done(null, 'New GitHub comment: ' + context.req.body.comment.body); }
Add more logging to GitHub sample
Add more logging to GitHub sample
JavaScript
mit
fabiocav/azure-webjobs-sdk-script,fabiocav/azure-webjobs-sdk-script,Azure/azure-webjobs-sdk-script,Azure/azure-webjobs-sdk-script,fabiocav/azure-webjobs-sdk-script,fabiocav/azure-webjobs-sdk-script,Azure/azure-webjobs-sdk-script,Azure/azure-webjobs-sdk-script
--- +++ @@ -1,4 +1,4 @@ module.exports = function (context) { - context.log('GitHub WebHook triggered!'); + context.log('GitHub WebHook triggered! ' + context.req.body.comment.body); context.done(null, 'New GitHub comment: ' + context.req.body.comment.body); }
af94e5976370f46979e31e8d9254ff2bca873ad7
loopback/server/server.js
loopback/server/server.js
var loopback = require('loopback'); var boot = require('loopback-boot'); var app = module.exports = loopback(); app.start = function() { // start the web server return app.listen(function() { app.emit('started'); var baseUrl = app.get('url').replace(/\/$/, ''); console.log('Web server listening at: %s', baseUrl); if (app.get('loopback-component-explorer')) { var explorerPath = app.get('loopback-component-explorer').mountPath; console.log('Browse your REST API at %s%s', baseUrl, explorerPath); } }); }; // Bootstrap the application, configure models, datasources and middleware. // Sub-apps like REST API are mounted via boot scripts. boot(app, __dirname, function(err) { if (err) throw err; // start the server if `$ node server.js` if (require.main === module) app.start(); });
var loopback = require('loopback'); var boot = require('loopback-boot'); var explorer = require('loopback-component-explorer'); var path = require('path'); var app = module.exports = loopback(); //app.use(customBaseUrl+'/explorer', loopback.rest()); app.start = function() { // start the web server var customBaseUrl=''; process.argv.forEach(function(element){ var valueArray = element.split('='); if (valueArray[0]='loopback-custom-base-url') { customBaseUrl=valueArray[1]; } }); console.log('Setting explorer mount point to: '+customBaseUrl+'/explorer'); app.use(customBaseUrl+'/explorer', explorer.routes(app, { basePath: customBaseUrl+'/api', uiDirs: [ path.resolve(__dirname, 'public') ] })); return app.listen(function() { app.emit('started'); var baseUrl = app.get('url').replace(/\/$/, ''); console.log('Web server listening at: %s', baseUrl); if (app.get('loopback-component-explorer')) { var explorerPath = app.get('loopback-component-explorer').mountPath; console.log('Browse your REST API at %s%s', baseUrl, explorerPath); } }); }; // Bootstrap the application, configure models, datasources and middleware. // Sub-apps like REST API are mounted via boot scripts. boot(app, __dirname, function(err) { if (err) throw err; // start the server if `$ node server.js` if (require.main === module) app.start(); });
Add support for custom explorer URL
Add support for custom explorer URL
JavaScript
mit
EdinburghCityScope/cityscope-loopback-docker,EdinburghCityScope/cityscope-loopback-docker
--- +++ @@ -1,10 +1,32 @@ var loopback = require('loopback'); var boot = require('loopback-boot'); +var explorer = require('loopback-component-explorer'); +var path = require('path'); var app = module.exports = loopback(); + +//app.use(customBaseUrl+'/explorer', loopback.rest()); + app.start = function() { // start the web server + + var customBaseUrl=''; + process.argv.forEach(function(element){ + var valueArray = element.split('='); + if (valueArray[0]='loopback-custom-base-url') + { + customBaseUrl=valueArray[1]; + } + }); + console.log('Setting explorer mount point to: '+customBaseUrl+'/explorer'); + + app.use(customBaseUrl+'/explorer', explorer.routes(app, { + basePath: customBaseUrl+'/api', + uiDirs: [ + path.resolve(__dirname, 'public') + ] + })); return app.listen(function() { app.emit('started'); var baseUrl = app.get('url').replace(/\/$/, '');
12c7502e43e97be742540e8214a47d29761ff3df
app/scripts/views/detail.js
app/scripts/views/detail.js
define( ["backbone", "backbone.marionette", "communicator", "medium.editor", "jquery", "erfgeoviewer.common", "tpl!template/detail.html"], function( Backbone, Marionette, Communicator, MediumEditor, $, App, Template ) { return Marionette.ItemView.extend( { template: Template, layout: null, dom: {}, events: { "click .change-style": function(e) { e.preventDefault(); } }, initialize: function( o ) { this.model = o.model; Communicator.mediator.on( "map:tile-layer-clicked", this.hideFlyout, this); }, onShow: function() { var editables = $(".editable", this.$el).get(); var self = this; if (this.editor) this.editor.destroy(); if (App.mode == "mapmaker") { this.editor = new MediumEditor(editables, { buttons: ['bold', 'italic', 'underline', 'anchor'], disableReturn: true }); this.editor.subscribe('editableInput', function (event, editable) { var field = $(editable).attr('id').substr(5); self.model.set(field, $(editable).html()); }); } } } ); } );
define( ["backbone", "backbone.marionette", "communicator", "medium.editor", "jquery", "erfgeoviewer.common", "tpl!template/detail.html"], function( Backbone, Marionette, Communicator, MediumEditor, $, App, Template ) { return Marionette.ItemView.extend( { template: Template, layout: null, dom: {}, events: { "click .change-style": function(e) { e.preventDefault(); } }, initialize: function( o ) { this.model = o.model; Communicator.mediator.on( "map:tile-layer-clicked", this.hideFlyout, this); }, onShow: function() { var editables = $(".editable", this.$el).get(); var self = this; var timeout; if (this.editor) this.editor.destroy(); if (App.mode == "mapmaker") { this.editor = new MediumEditor(editables, { buttons: ['bold', 'italic', 'underline', 'anchor'], disableReturn: true }); this.editor.subscribe('editableInput', function (event, editable) { clearTimeout(timeout); timeout = setTimeout(function() { var field = $(editable).attr('id').substr(5); self.model.set(field, $(editable).html()); }, 1000); }); } } } ); } );
Fix browser hanging because of fast typing in editor.
Fix browser hanging because of fast typing in editor.
JavaScript
mit
TotalActiveMedia/erfgeoviewer,TotalActiveMedia/erfgeoviewer,TotalActiveMedia/erfgeoviewer
--- +++ @@ -23,6 +23,8 @@ onShow: function() { var editables = $(".editable", this.$el).get(); var self = this; + var timeout; + if (this.editor) this.editor.destroy(); if (App.mode == "mapmaker") { this.editor = new MediumEditor(editables, { @@ -30,8 +32,11 @@ disableReturn: true }); this.editor.subscribe('editableInput', function (event, editable) { - var field = $(editable).attr('id').substr(5); - self.model.set(field, $(editable).html()); + clearTimeout(timeout); + timeout = setTimeout(function() { + var field = $(editable).attr('id').substr(5); + self.model.set(field, $(editable).html()); + }, 1000); }); } }
8caa0c9514dfeb6b6a7f79d870aebd6bc3a1acb1
app/src/js/utils/ApiUtil.js
app/src/js/utils/ApiUtil.js
var xhr = require('../lib/xhr'); var { API, ActionTypes } = require('../Constants'); var ServerActionCreators = require('../actions/ServerActionCreators'); var ApiUtils = { loadVisitors () { // xhr.getJSON(`${API}/visitors`, (err, res) => { ServerActionCreators.loadedVisitors(["Brian", "Jeremy", "Kendal"]); // }); }, deleteVisitor (visitor) { // xhr.deleteJSON(`$(API/visitors/${visitor.id}`, (err, res) => { ServerActionCreators.deletedVisitor(visitor); // }); }, loadActivities () { ServerActionCreators.loadedActivities([ {name: "SO", notes: "Get the wings"}, {name: "Bear Brewing", notes: "ESB Nitro is amazing"}, {name: "Sextant", notes: "Cappuccino, mocha or cold brew"}, {name: "Laguna", notes: "Awesome hookah / open late night life"} ]); } }; module.exports = ApiUtils;
var xhr = require('../lib/xhr'); var { API, ActionTypes } = require('../Constants'); var ServerActionCreators = require('../actions/ServerActionCreators'); var ApiUtils = { loadVisitors () { // xhr.getJSON(`${API}/visitors`, (err, res) => { ServerActionCreators.loadedVisitors(["Brian", "Jeremy", "Kendal"]); // }); }, deleteVisitor (visitor) { // xhr.deleteJSON(`$(API/visitors/${visitor.id}`, (err, res) => { ServerActionCreators.deletedVisitor(visitor); // }); }, loadActivities () { ServerActionCreators.loadedActivities([ {name: "SO", notes: "Get the wings"}, {name: "ThirstyBear Brewing Co", notes: "ESB Nitro is amazing"}, {name: "Sextant", notes: "Cappuccino, mocha or cold brew"}, {name: "Laguna", notes: "Awesome hookah / open late night life"}, {name: "Sightglass", notes: "Picturesque, cappuccino is amazing"}, {name: "Golden Gate Park", notes: "Rent bikes, go to the beach"}, {name: "Garaje", notes: "Fish/shrimp tacos or pulled pork"}, {name: "Alembic", notes: "Last word - can be loud"}, {name: "Osaka Sushi", notes: "Sunday happy hour at 4pm"}, {name: "Green Chile", notes: "Best breakfast burritos"}, {name: "Cafe Chaat", notes: "Go-to Indian food"}, {name: "The Chieftain", notes: "Irish breakfast and a Magners"} ]); } }; module.exports = ApiUtils;
Increase number of seed activities to make demo more realistic for typical use case
Increase number of seed activities to make demo more realistic for typical use case
JavaScript
mit
jeremymcintyre/vetted,jeremymcintyre/vetted
--- +++ @@ -18,9 +18,17 @@ loadActivities () { ServerActionCreators.loadedActivities([ {name: "SO", notes: "Get the wings"}, - {name: "Bear Brewing", notes: "ESB Nitro is amazing"}, + {name: "ThirstyBear Brewing Co", notes: "ESB Nitro is amazing"}, {name: "Sextant", notes: "Cappuccino, mocha or cold brew"}, - {name: "Laguna", notes: "Awesome hookah / open late night life"} + {name: "Laguna", notes: "Awesome hookah / open late night life"}, + {name: "Sightglass", notes: "Picturesque, cappuccino is amazing"}, + {name: "Golden Gate Park", notes: "Rent bikes, go to the beach"}, + {name: "Garaje", notes: "Fish/shrimp tacos or pulled pork"}, + {name: "Alembic", notes: "Last word - can be loud"}, + {name: "Osaka Sushi", notes: "Sunday happy hour at 4pm"}, + {name: "Green Chile", notes: "Best breakfast burritos"}, + {name: "Cafe Chaat", notes: "Go-to Indian food"}, + {name: "The Chieftain", notes: "Irish breakfast and a Magners"} ]); }
55f010c72438fcc227fd1bd967467ca13f9ea64e
specs/services/people_spec.js
specs/services/people_spec.js
/** * @author Hamza Waqas <hamzawaqas@live.com> * @since 2/9/14 */ var linkedin = require('../../')('75gyccfxufrozz', 'HKwSAPg0z7oGYfh5') token = process.env.IN_TOKEN; jasmine.getEnv().defaultTimeoutInterval = 20000; linkedin = linkedin.init(token); describe('API: People Test Suite', function() { it('should retrieve profile of current user', function(done) { linkedin.people.me(function(err, data) { done(); }); }); it('should invite someone to connect', function(done) { linkedin.people.invite({ "recipients": { "values": [{ "person": { "_path": "/people/email=glavin.wiechert@gmail.com", "first-name": "Glavin", "last-name": "Wiechert" } }] }, "subject": "Invitation to connect.", "body": "Say yes!", "item-content": { "invitation-request": { "connect-type": "friend" } } }, function(err, data) { console.log(err, data); }); }); });
/** * @author Hamza Waqas <hamzawaqas@live.com> * @since 2/9/14 */ var linkedin = require('../../')('75gyccfxufrozz', 'HKwSAPg0z7oGYfh5') token = process.env.IN_TOKEN; jasmine.getEnv().defaultTimeoutInterval = 20000; linkedin = linkedin.init(token); describe('API: People Test Suite', function() { it('should retrieve profile of current user', function(done) { linkedin.people.me(function(err, data) { done(); }); }); it('should invite someone to connect', function(done) { linkedin.people.invite({ "recipients": { "values": [{ "person": { "_path": "/people/email=glavin.wiechert@gmail.com", "first-name": "Glavin", "last-name": "Wiechert" } }] }, "subject": "Invitation to connect.", "body": "Say yes!", "item-content": { "invitation-request": { "connect-type": "friend" } } }, function(err, data) { done(); }); }); });
Remove console.log and add in done() for people spec.
Remove console.log and add in done() for people spec.
JavaScript
mit
ArkeologeN/node-linkedin
--- +++ @@ -37,7 +37,7 @@ } } }, function(err, data) { - console.log(err, data); + done(); }); }); });
c4463eb8130561cfdfeb2114d87ca1e10a1857a9
gatsby-node.js
gatsby-node.js
exports.modifyWebpackConfig = function (config) { config.loader('jpg', { test: /\.jpg$/, loader: 'url?limit=10000', }) config.loader('png', { test: /\.png$/, loader: 'url?limit=10000', }) config.loader('pug', { test: /\.pug$/, loader: 'pug', }) return config }
exports.modifyWebpackConfig = function (config) { config.merge({ output: { publicPath: '/', }, }) config.loader('jpg', { test: /\.jpg$/, loader: 'url?limit=10000', }) config.loader('png', { test: /\.png$/, loader: 'url?limit=10000', }) config.loader('pug', { test: /\.pug$/, loader: 'pug', }) return config }
Fix public path in production build
Fix public path in production build
JavaScript
mit
jsis/jsconf.is,jsis/jsconf.is
--- +++ @@ -1,4 +1,10 @@ exports.modifyWebpackConfig = function (config) { + config.merge({ + output: { + publicPath: '/', + }, + }) + config.loader('jpg', { test: /\.jpg$/, loader: 'url?limit=10000',
9f361436f851a6006930cb3b2cd92b39a0500ef5
src/components/Posts/index.js
src/components/Posts/index.js
import _ from 'underscore'; import React from 'react'; import equip from './equip'; import PostsGrid from '../StaticResponsiveGrid'; import Post from './Post'; const Posts = ({ style, posts, added }) => { const postCards = _.mapObject(posts, (post, id) => { const props = { post, style, added, }; return ( <div key={id}> <Post {...props} /> </div> ); }); return ( <PostsGrid itemWidth={style.width} itemHeight={style.height} maxWidth={1600} items={_.values(postCards)} /> ); }; export default equip(Posts);
import _ from 'underscore'; import React from 'react'; import equip from './equip'; import PostsGrid from '../StaticResponsiveGrid'; import Post from './Post'; const Posts = ({ style, posts, added }) => { let i = -1; const postCards = _.mapObject(posts, (post) => { const props = { post, style, added, }; i++; return ( <div key={i}> <Post {...props} /> </div> ); }); return ( <PostsGrid itemWidth={style.width} itemHeight={style.height} maxWidth={1600} items={_.values(postCards)} /> ); }; export default equip(Posts);
Put in a temporary fix for the layout system.
Put in a temporary fix for the layout system.
JavaScript
mit
RayBenefield/halo-forge,RayBenefield/halo-forge,RayBenefield/halo-forge
--- +++ @@ -5,14 +5,16 @@ import Post from './Post'; const Posts = ({ style, posts, added }) => { - const postCards = _.mapObject(posts, (post, id) => { + let i = -1; + const postCards = _.mapObject(posts, (post) => { const props = { post, style, added, }; + i++; return ( - <div key={id}> + <div key={i}> <Post {...props} /> </div> );
63cd6edade8821c647f1a1f488d84c9fd5186f96
js/module.js
js/module.js
$(function() { var readme = $('.readme'); var converter = new Showdown.converter(); for(var i=0;i<readme.length;i++) { var readmeElm = $(readme[i]); var module = readmeElm.data('module'); var path = 'hands-on-exercises/M' + module; $.ajax({ url: '/' + path + '/readme.md' }).success(function(content) { content = "## Where to find the code\n\n" + "All code for this module can be found under `" + path + "`.\n\n" + "Please visit the directory by running the command `cd "+path+"`.\n\n----\n\n" + content; content = content.replace('# Module ' + module, ''); var html = converter.makeHtml(content); readmeElm.html(html); }).error(function() { var content = "## Installation Required\n\n" + 'Please install the demo-app by running `./scripts/install.sh` and then refresh this page'; var html = converter.makeHtml(content); readmeElm.html(html); }); } });
$(function() { var readme = $('.readme'); var converter = new Showdown.converter(); for(var i=0;i<readme.length;i++) { var readmeElm = $(readme[i]); var module = readmeElm.data('module'); var path = 'hands-on-exercises/M' + module; $.ajax({ url: '/' + path + '/README.md' }).success(function(content) { content = "## Where to find the code\n\n" + "All code for this module can be found under `" + path + "`.\n\n" + "Please visit the directory by running the command `cd "+path+"`.\n\n----\n\n" + content; content = content.replace('# Module ' + module, ''); var html = converter.makeHtml(content); readmeElm.html(html); }).error(function() { var content = "## Installation Required\n\n" + 'Please install the demo-app by running `./scripts/install.sh` and then refresh this page'; var html = converter.makeHtml(content); readmeElm.html(html); }); } });
Fix Ajax request not looking for the good lowercase README.md while they are all named in uppercace 'hands-on-exercises'
Fix Ajax request not looking for the good lowercase README.md while they are all named in uppercace 'hands-on-exercises'
JavaScript
mit
nishant8BITS/video-exercises,angularjs-foundation/video-exercises,nishant8BITS/video-exercises,angularjs-foundation/video-exercises,angularjs-foundation/video-exercises,nishant8BITS/video-exercises
--- +++ @@ -6,7 +6,7 @@ var module = readmeElm.data('module'); var path = 'hands-on-exercises/M' + module; $.ajax({ - url: '/' + path + '/readme.md' + url: '/' + path + '/README.md' }).success(function(content) { content = "## Where to find the code\n\n" + "All code for this module can be found under `" + path + "`.\n\n" +
bc980ffd82cc591a4fc1658ae12f3685cef0f7bf
lib/generators/half_pipe/templates/tasks/options/sass.js
lib/generators/half_pipe/templates/tasks/options/sass.js
module.exports = { options: { require: ['sass-css-importer'], loadPath: ['<%%= bowerOpts.directory || "bower_components" %>'], bundleExec: true }, debug: { src: '<%%= dirs.tmp %>/prepare/assets/styles/main.scss', dest: '<%%= dirs.tmp %>/public/assets/styles/main.css', options: { style: 'expanded', sourcemaps: 'true' } }, "public": { src: '<%%= dirs.tmp %>/prepare/assets/styles/main.scss', dest: '<%%= dirs.tmp %>/public/assets/styles/main.css', options: { style: 'compressed' } } };
module.exports = { options: { require: ['sass-css-importer'], loadPath: ['<%%= bowerOpts.directory || "bower_components" %>'], bundleExec: true }, debug: { src: '<%%= dirs.tmp %>/prepare/assets/styles/main.scss', dest: '<%%= dirs.tmp %>/public/assets/styles/main.css', options: { style: 'expanded', sourcemap: 'true' } }, "public": { src: '<%%= dirs.tmp %>/prepare/assets/styles/main.scss', dest: '<%%= dirs.tmp %>/public/assets/styles/main.css', options: { style: 'compressed' } } };
Fix typo in sourcemap option
Fix typo in sourcemap option
JavaScript
mit
half-pipe/half-pipe,half-pipe/half-pipe
--- +++ @@ -9,7 +9,7 @@ dest: '<%%= dirs.tmp %>/public/assets/styles/main.css', options: { style: 'expanded', - sourcemaps: 'true' + sourcemap: 'true' } }, "public": {
ccb997fa2ce75b5574b11b0631d52e8528bd5a15
extension/background.js
extension/background.js
var tabs = {}; chrome.extension.onRequest.addListener(function(request, sender, callback) { var tabId = request.tabId; if (!(tabId in tabs)) { chrome.tabs.executeScript(tabId, { file: 'generated_accessibility.js' }, function() { if (chrome.extension.lastError) { callback({ error: chrome.extension.lastError.message }); return; } }); tabs[tabId] = true; callback(); } });
var tabs = {}; chrome.extension.onRequest.addListener(function(request, sender, callback) { var tabId = request.tabId; if (!(tabId in tabs)) { chrome.tabs.executeScript(tabId, { file: 'generated_accessibility.js' }, function() { if (chrome.extension.lastError) { callback({ error: chrome.extension.lastError.message }); return; } }); tabs[tabId] = true; } callback(); });
Fix bug where audit wouldn't show up after closing and re-opening devtools.
Fix bug where audit wouldn't show up after closing and re-opening devtools.
JavaScript
apache-2.0
modulexcite/accessibility-developer-tools,ckundo/accessibility-developer-tools,japacible/accessibility-developer-tools,Khan/accessibility-developer-tools,seksanman/accessibility-developer-tools,dylanb/accessibility-developer-tools-extension,GabrielDuque/accessibility-developer-tools,ricksbrown/accessibility-developer-tools,hmrc/accessibility-developer-tools,hmrc/accessibility-developer-tools,googlearchive/accessibility-developer-tools-extension,minorninth/accessibility-developer-tools,t9nf/accessibility-developer-tools,t9nf/accessibility-developer-tools,GoogleChrome/accessibility-developer-tools-extension,GabrielDuque/accessibility-developer-tools,modulexcite/accessibility-developer-tools-extension,GoogleChrome/accessibility-developer-tools-extension,GabrielDuque/accessibility-developer-tools,ricksbrown/accessibility-developer-tools,modulexcite/accessibility-developer-tools,pivotal-cf/accessibility-developer-tools,Khan/accessibility-developer-tools,t9nf/accessibility-developer-tools,ricksbrown/accessibility-developer-tools,googlearchive/accessibility-developer-tools-extension,kristapsmelderis/accessibility-developer-tools,dylanb/accessibility-developer-tools-extension,japacible/accessibility-developer-tools-extension,seksanman/accessibility-developer-tools,seksanman/accessibility-developer-tools,kristapsmelderis/accessibility-developer-tools,GoogleChrome/accessibility-developer-tools,ckundo/accessibility-developer-tools,GoogleChrome/accessibility-developer-tools,hmrc/accessibility-developer-tools,garcialo/accessibility-developer-tools,kublaj/accessibility-developer-tools,alice/accessibility-developer-tools,japacible/accessibility-developer-tools,modulexcite/accessibility-developer-tools-extension,japacible/accessibility-developer-tools-extension,GoogleChrome/accessibility-developer-tools,japacible/accessibility-developer-tools,minorninth/accessibility-developer-tools,garcialo/accessibility-developer-tools,kublaj/accessibility-developer-tools,modulexcite/accessibility-developer-tools,garcialo/accessibility-developer-tools,pivotal-cf/accessibility-developer-tools,alice/accessibility-developer-tools,kublaj/accessibility-developer-tools,ckundo/accessibility-developer-tools,kristapsmelderis/accessibility-developer-tools,pivotal-cf/accessibility-developer-tools,Khan/accessibility-developer-tools,alice/accessibility-developer-tools
--- +++ @@ -11,6 +11,6 @@ } }); tabs[tabId] = true; - callback(); } + callback(); });
25872df03668db7b36488776dbfd5de630a357f8
src/protocols/handlers/http/args.js
src/protocols/handlers/http/args.js
'use strict'; const { parse: parseContentType } = require('content-type'); const { findFormat } = require('../../../formats'); const { parsePreferHeader } = require('./headers'); // Using `Prefer: return=minimal` request header results in `args.silent` true. const silent = function ({ specific: { req: { headers: requestheaders } } }) { const preferHeader = parsePreferHeader({ requestheaders }); const hasMinimalPreference = preferHeader.return === 'minimal'; if (hasMinimalPreference) { return true; } }; // Using `Content-Type` or `Accept-Encoding` results in `args.format` // Note that since `args.format` is for both input and output, any of the // two headers can be used. `Content-Type` has priority. const format = function ({ specific }) { const contentType = getContentType({ specific }); const { name } = findFormat({ type: 'payload', mime: contentType }); return name; }; const getContentType = function ({ specific: { req: { headers } } }) { const contentType = headers['content-type']; if (!contentType) { return; } const { type } = parseContentType(contentType); return type; }; // HTTP-specific ways to set arguments const args = { silent, format, }; module.exports = { args, };
'use strict'; const { parse: parseContentType } = require('content-type'); const { findFormat } = require('../../../formats'); const { parsePreferHeader } = require('./headers'); // Using `Prefer: return=minimal` request header results in `args.silent` true. const silent = function ({ specific: { req: { headers: requestheaders } } }) { const preferHeader = parsePreferHeader({ requestheaders }); const hasMinimalPreference = preferHeader.return === 'minimal'; if (hasMinimalPreference) { return true; } }; // Using `Content-Type` or `Accept-Encoding` results in `args.format` // Note that since `args.format` is for both input and output, any of the // two headers can be used. `Content-Type` has priority. const format = function ({ specific }) { const { type: contentType } = getContentType({ specific }); const { name } = findFormat({ type: 'payload', mime: contentType }); return name; }; const getContentType = function ({ specific: { req: { headers } } }) { const contentType = headers['content-type']; if (!contentType) { return; } return parseContentType(contentType); }; // Use similar logic as `args.format`, but for `args.charset` const charset = function ({ specific }) { const { parameters: { charset: name } } = getContentType({ specific }); return name; }; // HTTP-specific ways to set arguments const args = { silent, format, charset, }; module.exports = { args, };
Add Content-Type handling for charset
Add Content-Type handling for charset
JavaScript
apache-2.0
autoserver-org/autoserver,autoserver-org/autoserver
--- +++ @@ -18,7 +18,7 @@ // Note that since `args.format` is for both input and output, any of the // two headers can be used. `Content-Type` has priority. const format = function ({ specific }) { - const contentType = getContentType({ specific }); + const { type: contentType } = getContentType({ specific }); const { name } = findFormat({ type: 'payload', mime: contentType }); return name; @@ -28,14 +28,20 @@ const contentType = headers['content-type']; if (!contentType) { return; } - const { type } = parseContentType(contentType); - return type; + return parseContentType(contentType); +}; + +// Use similar logic as `args.format`, but for `args.charset` +const charset = function ({ specific }) { + const { parameters: { charset: name } } = getContentType({ specific }); + return name; }; // HTTP-specific ways to set arguments const args = { silent, format, + charset, }; module.exports = {
d167d0339c25ad4c8c34646b26d7fe041421eba0
client-vendor/after-body/jquery.clickFeedback/jquery.clickFeedback.js
client-vendor/after-body/jquery.clickFeedback/jquery.clickFeedback.js
/* * Author: CM * Dependencies: jquery.transit.js */ (function($) { document.addEventListener('mousedown', function(event) { var $elem = $(event.target).closest('.clickFeedback'); if ($elem.length) { var buttonOffset = $elem.offset(); var feedbackSize = 2 * Math.sqrt(Math.pow($elem.outerWidth(), 2) + Math.pow($elem.outerHeight(), 2)); var posX = event.pageX; var posY = event.pageY; var $feedback = $('<div class="clickFeedback-ripple" />'); $feedback.css({ width: feedbackSize, height: feedbackSize, left: posX - buttonOffset.left - (feedbackSize / 2), top: posY - buttonOffset.top - (feedbackSize / 2) }); $elem.append($feedback); $feedback.transition({ scale: 1 }, '200ms', 'in').transition({ opacity: 0 }, '200ms', 'out', function() { $feedback.remove(); }); } }); })(jQuery);
/* * Author: CM * Dependencies: jquery.transit.js */ (function($) { document.addEventListener('mousedown', function(event) { var $elem = $(event.target).closest('.clickFeedback:not(:disabled)'); if ($elem.length) { var buttonOffset = $elem.offset(); var feedbackSize = 2 * Math.sqrt(Math.pow($elem.outerWidth(), 2) + Math.pow($elem.outerHeight(), 2)); var posX = event.pageX; var posY = event.pageY; var $feedback = $('<div class="clickFeedback-ripple" />'); $feedback.css({ width: feedbackSize, height: feedbackSize, left: posX - buttonOffset.left - (feedbackSize / 2), top: posY - buttonOffset.top - (feedbackSize / 2) }); $elem.append($feedback); $feedback.transition({ scale: 1 }, '200ms', 'in').transition({ opacity: 0 }, '200ms', 'out', function() { $feedback.remove(); }); } }); })(jQuery);
Exclude disabled buttons from click feedback
Exclude disabled buttons from click feedback
JavaScript
mit
fauvel/CM,njam/CM,njam/CM,vogdb/cm,cargomedia/CM,cargomedia/CM,cargomedia/CM,vogdb/cm,njam/CM,fauvel/CM,fauvel/CM,vogdb/cm,cargomedia/CM,fauvel/CM,njam/CM,njam/CM,vogdb/cm,fauvel/CM,vogdb/cm
--- +++ @@ -5,7 +5,7 @@ (function($) { document.addEventListener('mousedown', function(event) { - var $elem = $(event.target).closest('.clickFeedback'); + var $elem = $(event.target).closest('.clickFeedback:not(:disabled)'); if ($elem.length) { var buttonOffset = $elem.offset();
147bf69d1932156e8e0cf97ef5485bed48e21ace
src/start/heyneighbor-server-base.js
src/start/heyneighbor-server-base.js
// Socket import '../modules/socket/socket-server'; // Auth modules import '../modules/facebook/facebook'; import '../modules/google/google'; import '../modules/session/session'; import '../modules/signin/signin'; import '../modules/signup/signup'; import '../modules/resource/resource'; import '../modules/belong/belong'; /* ########### */ import '../modules/relations/relations'; import '../modules/guard/guard-server'; import './../modules/count/count'; import './../modules/note/note'; import './../modules/upload/upload'; import '../modules/score/score'; import '../modules/gcm/gcm-server'; import '../modules/postgres/postgres'; import '../modules/image-upload/image-upload'; // import "./../modules/ui/ui-server"; import '../modules/http/http'; // if fired before socket server then the http/init listener might not be listening.. // Email server import '../modules/email/email-daemon';
// Socket import '../modules/socket/socket-server'; // Auth modules import '../modules/facebook/facebook'; import '../modules/google/google'; import '../modules/session/session'; import '../modules/signin/signin'; import '../modules/signup/signup'; import '../modules/resource/resource'; import '../modules/belong/belong'; /* ########### */ import '../modules/relations/relations'; import '../modules/guard/guard-server'; import './../modules/count/count'; import './../modules/note/note'; import '../modules/score/score'; import '../modules/gcm/gcm-server'; import '../modules/postgres/postgres'; import '../modules/image-upload/image-upload'; // import "./../modules/ui/ui-server"; import '../modules/http/http'; // if fired before socket server then the http/init listener might not be listening.. // Email server import '../modules/email/email-daemon';
Remove the old upload module
Remove the old upload module
JavaScript
agpl-3.0
belng/pure,scrollback/pure,Anup-Allamsetty/pure,scrollback/pure,belng/pure,scrollback/pure,belng/pure,Anup-Allamsetty/pure,Anup-Allamsetty/pure,belng/pure,Anup-Allamsetty/pure,scrollback/pure
--- +++ @@ -16,7 +16,6 @@ import '../modules/guard/guard-server'; import './../modules/count/count'; import './../modules/note/note'; -import './../modules/upload/upload'; import '../modules/score/score'; import '../modules/gcm/gcm-server'; import '../modules/postgres/postgres';
38e659a1724561be7bb9ffc1608db1b7a35d1ee4
js/Protocol.js
js/Protocol.js
function verifyStructure(template, struct) { for (key in template) { if (!keyExists(key, struct)) { console.log("Could not find expected key:", key, "in provided structure"); return false; } else { if (!compareType(template[key], struct[key])) { console.log("Unexpected type in struct.", "Template." + key, getType(template[key]), "!=", "struct." + key, getType(struct[key])); return false; } if (compareType(template[key], {})) { if (!verifyStructure(template[key], struct[key])) { console.log("Failed to verify sub-object with key:", key); return false; } } } } return true; } function compareType(struct1, struct2) { return getType(struct1) == getType(struct2); } function keyExists(key, struct) { return getType(struct[key]) != "[object Undefined]"; } function getType(struct) { return Object.prototype.toString.call(struct); }
function verifyStructure(template, struct) { for (key in template) { if (!keyExists(key, struct)) { console.log("Could not find expected key:", key, "in provided structure"); return false; } else { if (!compareType(template[key], struct[key])) { console.log("Unexpected type in struct.", "Template." + key, getType(template[key]), "!=", "struct." + key, getType(struct[key])); return false; } if (compareType(template[key], {})) { if (!verifyStructure(template[key], struct[key])) { console.log("Failed to verify sub-object with key:", key); return false; } } else if (compareType(template[key], [])) { var templateElement = template[key][0]; var structElement = struct[key][0]; if (!compareType(templateElement, structElement)) { console.log("Unexpected type in array.", "Template." + key, getType(templateElement), "!=", "struct." + key, getType(structElement)); return false; } if (compareType(templateElement, {})) { if (!verifyStructure(templateElement, structElement)) { console.log("Failed to verify sub-object with key:", key); return false; } } } } } return true; } function compareType(struct1, struct2) { return getType(struct1) == getType(struct2); } function keyExists(key, struct) { return getType(struct[key]) != "[object Undefined]"; } function getType(struct) { return Object.prototype.toString.call(struct); }
Add type checking to array elements
Add type checking to array elements
JavaScript
mit
Tactique/jswars
--- +++ @@ -12,6 +12,19 @@ if (!verifyStructure(template[key], struct[key])) { console.log("Failed to verify sub-object with key:", key); return false; + } + } else if (compareType(template[key], [])) { + var templateElement = template[key][0]; + var structElement = struct[key][0]; + if (!compareType(templateElement, structElement)) { + console.log("Unexpected type in array.", "Template." + key, getType(templateElement), "!=", "struct." + key, getType(structElement)); + return false; + } + if (compareType(templateElement, {})) { + if (!verifyStructure(templateElement, structElement)) { + console.log("Failed to verify sub-object with key:", key); + return false; + } } } }
82bc5a9e7432ac3f53166c10cad96bdade178644
src/shared/containers/User-Pic-Page/User-Pic-Page.js
src/shared/containers/User-Pic-Page/User-Pic-Page.js
import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import * as profileActions from '../../modules/profile'; class UserPicPage extends Component { static needs = [profileActions.fetchProfile] render() { const { imgUrl, followers, hasError, } = this.props; const errorHtml = hasError ? (<div>No Such User!!</div>) : undefined; return ( <div className="user-pic-page"> <div>Followers: {followers}</div> <img src={imgUrl} /> {errorHtml} </div> ); } } UserPicPage.propTypes = { name: PropTypes.string, imgUrl: PropTypes.string, followers: PropTypes.number, hasError: PropTypes.bool, fetchProfile: PropTypes.func, }; function mapStateToProps(state) { return Object.assign( {}, state.profile ); } function mapDispatchToProps(dispatch) { return Object.assign( {}, bindActionCreators(profileActions, dispatch) ); } export default connect( mapStateToProps, mapDispatchToProps )(UserPicPage);
import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import * as profileActions from '../../modules/profile'; class UserPicPage extends Component { componentDidMount() { this.props.fetchProfile(); } static needs = [profileActions.fetchProfile] render() { const { imgUrl, followers, hasError, } = this.props; const errorHtml = hasError ? (<div>No Such User!!</div>) : undefined; return ( <div className="user-pic-page"> <div>Followers: {followers}</div> <img src={imgUrl} /> {errorHtml} </div> ); } } UserPicPage.propTypes = { name: PropTypes.string, imgUrl: PropTypes.string, followers: PropTypes.number, hasError: PropTypes.bool, fetchProfile: PropTypes.func, }; function mapStateToProps(state) { return Object.assign( {}, state.profile ); } function mapDispatchToProps(dispatch) { return Object.assign( {}, bindActionCreators(profileActions, dispatch) ); } export default connect( mapStateToProps, mapDispatchToProps )(UserPicPage);
Add client initial request through component did mount
Add client initial request through component did mount
JavaScript
mit
Rhadow/isomorphic-react-example,Rhadow/isomorphic-react-example
--- +++ @@ -4,6 +4,9 @@ import * as profileActions from '../../modules/profile'; class UserPicPage extends Component { + componentDidMount() { + this.props.fetchProfile(); + } static needs = [profileActions.fetchProfile] render() { const {
cb546b2d0e3bd800d44656fbd664a74f2176a31e
lib/scrapper/exceptionScrapper.js
lib/scrapper/exceptionScrapper.js
/*global $*/ module.exports = function(page) { return page.evaluate(function() { const exception = $(".strong.title")[0].childNodes[1].textContent; const info = $(".info.normal")[0].textContent; return { exception: exception, info: info }; }); };
/*global $*/ module.exports = function(page) { return page.evaluate(function() { var exception; const info = document.querySelector(".info.normal").textContent; const exceptionChildNodes = document.querySelector(".strong.title").childNodes; for (var i = 0; i < exceptionChildNodes.length; i++) { if (exceptionChildNodes[i].nodeType === Node.TEXT_NODE) { exception = exceptionChildNodes[i].textContent; break; } } return { exception: exception, info: info }; }); };
Use vanilla JS in exception scrapper
Use vanilla JS in exception scrapper
JavaScript
mit
ninjaprox/github-webhooks,ninjaprox/github-webhooks
--- +++ @@ -1,12 +1,21 @@ /*global $*/ module.exports = function(page) { return page.evaluate(function() { - const exception = $(".strong.title")[0].childNodes[1].textContent; - const info = $(".info.normal")[0].textContent; + var exception; + const info = document.querySelector(".info.normal").textContent; + const exceptionChildNodes = document.querySelector(".strong.title").childNodes; - return { - exception: exception, - info: info - }; - }); + for (var i = 0; i < exceptionChildNodes.length; i++) { + if (exceptionChildNodes[i].nodeType === Node.TEXT_NODE) { + exception = exceptionChildNodes[i].textContent; + + break; + } + } + + return { + exception: exception, + info: info + }; + }); };
e07aab5d97c4e78085f02a0b34948815e41ea23a
client/src/common/Drawer.js
client/src/common/Drawer.js
import Drawer from 'antd/lib/drawer'; import React, { useEffect } from 'react'; function DrawerWrapper({ title, visible, onClose, width, placement, children }) { useEffect(() => { if (visible) { function handler(event) { if (event.code === 'Escape') { onClose(); return false; } } window.addEventListener('keydown', handler); return () => window.removeEventListener('keydown', handler); } }, [visible]); return ( <Drawer title={title} visible={visible} width={width} destroyOnClose={true} onClose={onClose} placement={placement} bodyStyle={{ height: 'calc(90vh - 55px)', overflow: 'auto' }} > {children} </Drawer> ); } export default DrawerWrapper;
import Drawer from 'antd/lib/drawer'; import React, { useEffect } from 'react'; function DrawerWrapper({ title, visible, onClose, width, placement, children }) { useEffect(() => { if (visible) { function handler(event) { if (event.code === 'Escape') { onClose(); return false; } } window.addEventListener('keydown', handler); return () => window.removeEventListener('keydown', handler); } }, [visible]); return ( <Drawer title={title} visible={visible} width={width} destroyOnClose={true} onClose={onClose} placement={placement} bodyStyle={{ height: 'calc(100vh - 55px)', overflow: 'auto' }} > {children} </Drawer> ); } export default DrawerWrapper;
Fix drawer height (use full vertical height)
Fix drawer height (use full vertical height)
JavaScript
mit
rickbergfalk/sqlpad,rickbergfalk/sqlpad,rickbergfalk/sqlpad
--- +++ @@ -31,7 +31,7 @@ onClose={onClose} placement={placement} bodyStyle={{ - height: 'calc(90vh - 55px)', + height: 'calc(100vh - 55px)', overflow: 'auto' }} >
2f5b9831eab4add95356322950a7e21748def386
test/fixtures/if-statement/source.js
test/fixtures/if-statement/source.js
console.log('Do something always'); if (module.hot) { console.log('Do something, when hot reload available'); } if (module.hot) { console.log('Do something, when hot reload available'); } else { console.log('Do something, when hot reload unavailable'); }
console.log('Do something always'); if (module.hot) { console.log('Do something, when hot reload available'); } if (module.hot) console.log('Do something, when hot reload available'); if (module.hot) { console.log('Do something, when hot reload available'); } else { console.log('Do something, when hot reload unavailable'); }
Add additional example for tests
Add additional example for tests
JavaScript
mit
demiazz/babel-plugin-remove-module-hot
--- +++ @@ -4,6 +4,8 @@ console.log('Do something, when hot reload available'); } +if (module.hot) console.log('Do something, when hot reload available'); + if (module.hot) { console.log('Do something, when hot reload available'); } else {
e50b256c4b90bc1056e0436d1848ac4ebc1d7843
console.meta.js
console.meta.js
// ==UserScript== // @id iitc-plugin-console@hansolo669 // @name IITC plugin: console // @category Debug // @version 0.0.1 // @namespace https://github.com/hansolo669/iitc-tweaks // @updateURL https://iitc.reallyawesomedomain.com/console.meta.js // @downloadURL https://iitc.reallyawesomedomain.com/console.user.js // @description Utility to pipe the standard console back into IITC and esailly eval snippets // @include https://www.ingress.com/intel* // @include http://www.ingress.com/intel* // @match https://www.ingress.com/intel* // @match http://www.ingress.com/intel* // @include https://www.ingress.com/mission/* // @include http://www.ingress.com/mission/* // @match https://www.ingress.com/mission/* // @match http://www.ingress.com/mission/* // @grant none // ==/UserScript==
// ==UserScript== // @id iitc-plugin-console@hansolo669 // @name IITC plugin: console // @category Debug // @version 0.0.2 // @namespace https://github.com/hansolo669/iitc-tweaks // @updateURL https://iitc.reallyawesomedomain.com/console.meta.js // @downloadURL https://iitc.reallyawesomedomain.com/console.user.js // @description Utility to pipe the standard console back into IITC and esailly eval snippets // @include https://*.ingress.com/intel* // @include http://*.ingress.com/intel* // @match https://*.ingress.com/intel* // @match http://*.ingress.com/intel* // @include https://*.ingress.com/mission/* // @include http://*.ingress.com/mission/* // @match https://*.ingress.com/mission/* // @match http://*.ingress.com/mission/* // @grant none // ==/UserScript==
Fix for intel routing changes
Fix for intel routing changes
JavaScript
mit
hansolo669/iitc-tweaks,hansolo669/iitc-tweaks
--- +++ @@ -2,18 +2,18 @@ // @id iitc-plugin-console@hansolo669 // @name IITC plugin: console // @category Debug -// @version 0.0.1 +// @version 0.0.2 // @namespace https://github.com/hansolo669/iitc-tweaks // @updateURL https://iitc.reallyawesomedomain.com/console.meta.js // @downloadURL https://iitc.reallyawesomedomain.com/console.user.js // @description Utility to pipe the standard console back into IITC and esailly eval snippets -// @include https://www.ingress.com/intel* -// @include http://www.ingress.com/intel* -// @match https://www.ingress.com/intel* -// @match http://www.ingress.com/intel* -// @include https://www.ingress.com/mission/* -// @include http://www.ingress.com/mission/* -// @match https://www.ingress.com/mission/* -// @match http://www.ingress.com/mission/* +// @include https://*.ingress.com/intel* +// @include http://*.ingress.com/intel* +// @match https://*.ingress.com/intel* +// @match http://*.ingress.com/intel* +// @include https://*.ingress.com/mission/* +// @include http://*.ingress.com/mission/* +// @match https://*.ingress.com/mission/* +// @match http://*.ingress.com/mission/* // @grant none // ==/UserScript==
81c29fc446cc63c830e7f9ee7e452f6dc5a721c5
server/zanata-frontend/src/frontend/app/containers/TestModal/index.js
server/zanata-frontend/src/frontend/app/containers/TestModal/index.js
import React, { Component } from 'react' import { Modal } from '../../components' import { Button } from 'react-bootstrap' class TestModal extends Component { constructor () { super() this.state = { show: false } } hideModal () { console.info('test') this.setState({show: false}) } showModal () { this.setState({show: true}) } /* eslint-disable react/jsx-no-bind */ render () { return ( <div> <Button bsStyle='default' onClick={() => this.showModal()}>Launch Modal</Button> <Modal show={this.state.show} onHide={this.hideModal}> <Modal.Header> <Modal.Title>Example Modal</Modal.Title> </Modal.Header> <Modal.Body>Hi There</Modal.Body> <Modal.Footer> <Button bsStyle='link' onClick={() => this.hideModal()}>Cancel</Button> <Button bsStyle='primary' onClick={() => this.hideModal()}> Submit </Button> </Modal.Footer> </Modal> </div>) } /* eslint-enable react/jsx-no-bind */ } export default TestModal
import React, { Component } from 'react' import { Modal } from '../../components' import { Button } from 'react-bootstrap' class TestModal extends Component { constructor () { super() this.state = { show: false } } hideModal () { this.setState({show: false}) } showModal () { this.setState({show: true}) } /* eslint-disable react/jsx-no-bind */ render () { console.info(this) return ( <div> <Button bsStyle='default' onClick={() => this.showModal()}>Launch Modal</Button> <Modal show={this.state.show} onHide={() => this.hideModal()}> <Modal.Header> <Modal.Title>Example Modal</Modal.Title> </Modal.Header> <Modal.Body>Hi There</Modal.Body> <Modal.Footer> <Button bsStyle='link' onClick={() => this.hideModal()}>Cancel</Button> <Button bsStyle='primary' onClick={() => this.hideModal()}> Submit </Button> </Modal.Footer> </Modal> </div>) } /* eslint-enable react/jsx-no-bind */ } export default TestModal
Fix hide model on clicking
Fix hide model on clicking
JavaScript
lgpl-2.1
zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform
--- +++ @@ -12,7 +12,6 @@ } hideModal () { - console.info('test') this.setState({show: false}) } showModal () { @@ -20,13 +19,14 @@ } /* eslint-disable react/jsx-no-bind */ render () { + console.info(this) return ( <div> <Button bsStyle='default' onClick={() => this.showModal()}>Launch Modal</Button> <Modal show={this.state.show} - onHide={this.hideModal}> + onHide={() => this.hideModal()}> <Modal.Header> <Modal.Title>Example Modal</Modal.Title> </Modal.Header>
b949257b76fb278bf5badc36ce0d4dc9b75b5c7a
lib/fetcher.js
lib/fetcher.js
var feedRead = require('feed-read'); var readabilitySax = require('readabilitySAX'); var _url = require('url'); function fetchFeed(url, cb) { console.log('[.] Fetching feed: ' + url); feedRead(url, function(err, articles) { if (err) { console.error('[x] Unable to fetch feed: ' + url, err); cb(); } else { var articlesList = []; articles.forEach(function (article) { // append link to feed host if link doesn't contain protocol if (!article.link.match(/^http/)) { if (!article.link.match(/^\//)) { article.link = '/' + article.link; } elems = _url.parse(url); article.link = url.replace(new RegExp(elems.path), '') + article.link; } articlesList.push({ url : article.link, title: article.title }); }); cb(null, articlesList); } }); } function fetchArticle(url, cb) { console.log('[.] Fetching article: ' + url); readabilitySax.get(url, function (result) { cb({ url : url, source : _url.parse(url).hostname, title : result.title, content: result.html }); }); } exports.fetchFeed = fetchFeed; exports.fetchArticle = fetchArticle;
var feedRead = require('feed-read'); var readabilitySax = require('readabilitySAX'); var _url = require('url'); function fetchFeed(url, cb) { console.log('[.] Fetching feed: ' + url); feedRead(url, function(err, articles) { if (err) { console.error('[x] Unable to fetch feed: ' + url, err); cb(err); } else { var articlesList = []; articles.forEach(function (article) { // append link to feed host if link doesn't contain protocol if (!article.link.match(/^http/)) { if (!article.link.match(/^\//)) { article.link = '/' + article.link; } elems = _url.parse(url); article.link = url.replace(new RegExp(elems.path), '') + article.link; } articlesList.push({ url : article.link, title: article.title }); }); cb(null, articlesList); } }); } function fetchArticle(url, cb) { console.log('[.] Fetching article: ' + url); readabilitySax.get(url, function (result) { cb({ url : url, source : _url.parse(url).hostname, title : result.title, content: result.html }); }); } exports.fetchFeed = fetchFeed; exports.fetchArticle = fetchArticle;
Fix error propagation on feed fetching.
Fix error propagation on feed fetching.
JavaScript
mit
cliffano/feedpaper,cliffano/feedpaper,cliffano/feedpaper
--- +++ @@ -8,7 +8,7 @@ feedRead(url, function(err, articles) { if (err) { console.error('[x] Unable to fetch feed: ' + url, err); - cb(); + cb(err); } else { var articlesList = [];
00802027b63b94cf196f7bb1b4e54c463a0e551f
lib/heights.js
lib/heights.js
var _ = require('lodash') var fs = require('fs') var gzip = require('gzip-size') var filesize = require('filesize') var cssstats = require('cssstats') var module = require('tachyons-heights/package.json') var moduleCss = fs.readFileSync('node_modules/tachyons-heights/tachyons-heights.min.css', 'utf8') var moduleObj = cssstats(moduleCss) var moduleSize = filesize(moduleObj.gzipSize) var srcCSS = fs.readFileSync('./src/_heights.css', 'utf8') var template = fs.readFileSync('./templates/docs/heights/index.html', 'utf8') var tpl = _.template(template) var html = tpl({ moduleVersion: module.version, moduleSize: moduleSize, moduleObj: moduleObj, srcCSS: srcCSS }) fs.writeFileSync('./docs/layout/heights/index.html', html)
var _ = require('lodash') var fs = require('fs') var gzip = require('gzip-size') var filesize = require('filesize') var cssstats = require('cssstats') var module = require('tachyons-heights/package.json') var moduleCss = fs.readFileSync('node_modules/tachyons-heights/tachyons-heights.min.css', 'utf8') var moduleObj = cssstats(moduleCss) var moduleSize = filesize(moduleObj.gzipSize) var srcCSS = fs.readFileSync('./src/_heights.css', 'utf8') var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8') var template = fs.readFileSync('./templates/docs/heights/index.html', 'utf8') var tpl = _.template(template) var html = tpl({ moduleVersion: module.version, moduleSize: moduleSize, moduleObj: moduleObj, srcCSS: srcCSS, navDocs: navDocs }) fs.writeFileSync('./docs/layout/heights/index.html', html)
Update with reference to global nav partial
Update with reference to global nav partial
JavaScript
mit
topherauyeung/portfolio,pietgeursen/pietgeursen.github.io,matyikriszta/moonlit-landing-page,topherauyeung/portfolio,fenderdigital/css-utilities,cwonrails/tachyons,fenderdigital/css-utilities,tachyons-css/tachyons,getfrank/tachyons,topherauyeung/portfolio
--- +++ @@ -10,6 +10,8 @@ var moduleSize = filesize(moduleObj.gzipSize) var srcCSS = fs.readFileSync('./src/_heights.css', 'utf8') +var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8') + var template = fs.readFileSync('./templates/docs/heights/index.html', 'utf8') var tpl = _.template(template) @@ -17,7 +19,8 @@ moduleVersion: module.version, moduleSize: moduleSize, moduleObj: moduleObj, - srcCSS: srcCSS + srcCSS: srcCSS, + navDocs: navDocs }) fs.writeFileSync('./docs/layout/heights/index.html', html)
a9267b8ff1039700abe7bb0aed88de8d5bbdd44d
src/test/ed/lang/python/date1_test.js
src/test/ed/lang/python/date1_test.js
/** * Copyright (C) 2008 10gen Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ local.src.test.ed.lang.python.date1_helper(); assert( pyDate instanceof Date );
/** * Copyright (C) 2008 10gen Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ local.src.test.ed.lang.python.date1_helper(); assert( pyDate instanceof Date ); var jsDate = new Date(); assert( Math.abs(jsDate.getTime() - pyDate.getTime()) < 2000 , 'time zone changed' ); print( Math.abs(jsDate.getTime() - pyDate.getTime() ) );
Make sure time zone doesn't change too much.
Make sure time zone doesn't change too much.
JavaScript
apache-2.0
babble/babble,babble/babble,babble/babble,babble/babble,babble/babble,babble/babble
--- +++ @@ -17,3 +17,8 @@ local.src.test.ed.lang.python.date1_helper(); assert( pyDate instanceof Date ); +var jsDate = new Date(); +assert( Math.abs(jsDate.getTime() - pyDate.getTime()) < 2000 , + 'time zone changed' ); + +print( Math.abs(jsDate.getTime() - pyDate.getTime() ) );
036d0100f56f90d4a0d83d360ff8455006055aa2
create/javascript/inject.js
create/javascript/inject.js
var createEditor; var author; function injectCreate(id) { $("#" + id).load("create/html/createHTML", function() { injectCreateEditor(); // Generate a random number from 1 to 10000 author = Math.floor((Math.random() * 10000) + 1); }); } function injectCreateEditor() { Range = ace.require('ace/range').Range; createEditor = ace.edit("editor"); createEditor.setTheme("ace/theme/github"); // Set this to RESOLVE mode var ResolveMode = ace.require("ace/mode/resolve").Mode; createEditor.session.setMode(new ResolveMode()); // Gets rid of a weird Ace Editor bug //createEditor.$blockScrolling = Infinity; createEditor.getSession().on('change', removeAllVCMarkers); createEditor.setFontSize(18); }
var createEditor; var author; function injectCreate(id) { $("#" + id).load("create/html/createHTML", function() { injectCreateEditor(); // Check to see if we already have an author ID if (localStorage.getItem('author')) { // Reuse the same author ID author = localStorage.getItem('todos'); } else { // Generate a random number from 1 to 10000 author = Math.floor((Math.random() * 10000) + 1); localStorage.setItem('author', author); } }); } function injectCreateEditor() { Range = ace.require('ace/range').Range; createEditor = ace.edit("editor"); createEditor.setTheme("ace/theme/github"); // Set this to RESOLVE mode var ResolveMode = ace.require("ace/mode/resolve").Mode; createEditor.session.setMode(new ResolveMode()); // Gets rid of a weird Ace Editor bug //createEditor.$blockScrolling = Infinity; createEditor.getSession().on('change', removeAllVCMarkers); createEditor.setFontSize(18); }
Store the author id in the local storage
Store the author id in the local storage
JavaScript
bsd-3-clause
ClemsonRSRG/bydesign,ClemsonRSRG/beginToReason,ClemsonRSRG/beginToReason,ClemsonRSRG/bydesign,ClemsonRSRG/beginToReason
--- +++ @@ -5,8 +5,16 @@ $("#" + id).load("create/html/createHTML", function() { injectCreateEditor(); - // Generate a random number from 1 to 10000 - author = Math.floor((Math.random() * 10000) + 1); + // Check to see if we already have an author ID + if (localStorage.getItem('author')) { + // Reuse the same author ID + author = localStorage.getItem('todos'); + } + else { + // Generate a random number from 1 to 10000 + author = Math.floor((Math.random() * 10000) + 1); + localStorage.setItem('author', author); + } }); }
8554ba7671c41302ef47c0cfa4d1ed18b9c5f9f0
tests/spec/SpecHelper.js
tests/spec/SpecHelper.js
var pager; var items = 100; var itemsOnPage = 10; var pageCount = items/itemsOnPage; beforeEach(function() { $('<div id="pager"></div>').appendTo('body').pagination({ items: items, itemsOnPage: itemsOnPage }); pager = $('#pager'); this.addMatchers({ toBePaged: function() { return ( this.actual.hasClass('simple-pagination') && this.actual.find('li').length > 0 ); }, toBeOnPage: function(expected_page) { actual_page = this.actual.find('li.active span').not('.prev').not('.next').html(); return actual_page == expected_page; }, toBeDisabled: function() { return this.actual.find('li').length == this.actual.find('li.disabled').length; } }); }); afterEach(function () { pager.remove(); });
var pager; var items = 100; var itemsOnPage = 10; var pageCount = items/itemsOnPage; beforeEach(function() { $('<div id="pager" class="pager"></div>').appendTo('body').pagination({ items: items, itemsOnPage: itemsOnPage }); pager = $('#pager'); this.addMatchers({ toBePaged: function() { return ( this.actual.hasClass('simple-pagination') && this.actual.find('li').length > 0 ); }, toBeOnPage: function(expected_page) { actual_page = this.actual.find('li.active span').not('.prev').not('.next').html(); return actual_page == expected_page; }, toBeDisabled: function() { return this.actual.find('li').length == this.actual.find('li.disabled').length; } }); }); afterEach(function () { $('.pager').remove(); });
Remove all .pager instances after each test
Remove all .pager instances after each test
JavaScript
mit
jochouen/simplePagination.js,mapgears/simplePagination.js,mapgears/simplePagination.js,drafter911/simplePagination.js,jochouen/simplePagination.js,drafter911/simplePagination.js,flaviusmatis/simplePagination.js,flaviusmatis/simplePagination.js
--- +++ @@ -5,7 +5,7 @@ beforeEach(function() { - $('<div id="pager"></div>').appendTo('body').pagination({ + $('<div id="pager" class="pager"></div>').appendTo('body').pagination({ items: items, itemsOnPage: itemsOnPage }); @@ -29,5 +29,5 @@ }); afterEach(function () { - pager.remove(); + $('.pager').remove(); });
75c605206b2de49eaee95eeb345c14edc33bae4c
eMission/www/listview-js/app.js
eMission/www/listview-js/app.js
// Ionic Starter App // angular.module is a global place for creating, registering and retrieving Angular modules // 'starter' is the name of this angular module example (also set in a <body> attribute in index.html) // the 2nd parameter is an array of 'requires' // 'starter.controllers' is found in controllers.js angular.module('starter',['ionic', 'starter.controllers', 'starter.directives']) .config(function($ionicConfigProvider) { // note that you can also chain configs $ionicConfigProvider.tabs.position('bottom'); }) .run(function($ionicPlatform) { $ionicPlatform.ready(function() { // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard // for form inputs) if (window.cordova && window.cordova.plugins.Keyboard) { cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); } if (window.StatusBar) { StatusBar.styleDefault(); } var db = window.sqlitePlugin.openDatabase({name: "TripSections.db", location: 0, createFromLocation: 1}); tripSectionDbHelper.getJSON(db, function(jsonTripList) { tripList = tripSectionDbHelper.getUncommitedSections(jsonTripList); console.log("Retrieved trips count = "+tripList.length); }); }); })
// Ionic Starter App // angular.module is a global place for creating, registering and retrieving Angular modules // 'starter' is the name of this angular module example (also set in a <body> attribute in index.html) // the 2nd parameter is an array of 'requires' // 'starter.controllers' is found in controllers.js angular.module('starter',['ionic', 'starter.controllers', 'starter.directives', 'leaflet-directive']) .config(function($ionicConfigProvider) { // note that you can also chain configs $ionicConfigProvider.tabs.position('bottom'); }) .run(function($ionicPlatform) { $ionicPlatform.ready(function() { // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard // for form inputs) if (window.cordova && window.cordova.plugins.Keyboard) { cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); } if (window.StatusBar) { StatusBar.styleDefault(); } /* BEGIN DEVICE VERSION var db = window.sqlitePlugin.openDatabase({name: "userCacheDB", location: 0, createFromLocation: 1}); UserCacheHelper.getDocument(db, "diary/trips", function(tripListArray) { console.log("In main, tripListArray has = "+tripListArray.length+" entries"); tripListStr = tripListArray[0]; tripList = JSON.parse(tripListStr) console.log("In main, tripList has "+tripList.length+" entries"); // console.log("In main, first entry is "+JSON.stringify(tripList[0])); }); */ }); })
Comment out the second read to the database for debug purposes
Comment out the second read to the database for debug purposes I retain it just in case weird stuff happens to the database again, but we certainly don't need to read it again.
JavaScript
bsd-3-clause
e-mission/e-mission-phone-cordova-plugins,shankari/e-mission-phone-cordova-plugins,e-mission/e-mission-phone-cordova-plugins,shankari/e-mission-phone-cordova-plugins,e-mission/e-mission-phone-cordova-plugins
--- +++ @@ -4,7 +4,7 @@ // 'starter' is the name of this angular module example (also set in a <body> attribute in index.html) // the 2nd parameter is an array of 'requires' // 'starter.controllers' is found in controllers.js -angular.module('starter',['ionic', 'starter.controllers', 'starter.directives']) +angular.module('starter',['ionic', 'starter.controllers', 'starter.directives', 'leaflet-directive']) .config(function($ionicConfigProvider) { // note that you can also chain configs @@ -21,10 +21,16 @@ if (window.StatusBar) { StatusBar.styleDefault(); } - var db = window.sqlitePlugin.openDatabase({name: "TripSections.db", location: 0, createFromLocation: 1}); - tripSectionDbHelper.getJSON(db, function(jsonTripList) { - tripList = tripSectionDbHelper.getUncommitedSections(jsonTripList); - console.log("Retrieved trips count = "+tripList.length); + /* + BEGIN DEVICE VERSION + var db = window.sqlitePlugin.openDatabase({name: "userCacheDB", location: 0, createFromLocation: 1}); + UserCacheHelper.getDocument(db, "diary/trips", function(tripListArray) { + console.log("In main, tripListArray has = "+tripListArray.length+" entries"); + tripListStr = tripListArray[0]; + tripList = JSON.parse(tripListStr) + console.log("In main, tripList has "+tripList.length+" entries"); + // console.log("In main, first entry is "+JSON.stringify(tripList[0])); }); + */ }); })
6db19163c19a629edacdc90e066821c7db32cacf
modules/telegram/telegramTypes.js
modules/telegram/telegramTypes.js
'use strict' var tgTypes = {}; tgTypes.InlineKeyboardMarkup = function (rowWidth) { this['inline_keyboard'] = [[]]; var rowWidth = (rowWidth > 8 ? 8 : rowWidth) || 8; //Currently maximum supported in one row //Closure to make this property private this._rowWidth = function () { return rowWidth; }; }; tgTypes.InlineKeyboardMarkup.prototype.add = function (text, field, fieldValue) { this['inline_keyboard'][this._lastRow()].push( { 'text': text, [field]: fieldValue } ); if (this._isRowFull()) { this.newRow(); }; return this; }; tgTypes.InlineKeyboardMarkup.prototype.newRow = function () { this['inline_keyboard'].push([]); return this; }; tgTypes.InlineKeyboardMarkup.prototype._isRowFull = function () { if (this['inline_keyboard'][this._lastRow()] === this._rowWidth()-1) { return true; }; }; tgTypes.InlineKeyboardMarkup.prototype._lastRow = function () { return this['inline_keyboard'].length-1; }; module.exports = tgTypes;
'use strict' var tgTypes = {}; tgTypes.InlineKeyboardMarkup = function (rowWidth) { this['inline_keyboard'] = [[]]; var rowWidth = (rowWidth > 8 ? 8 : rowWidth) || 8; //Currently maximum supported in one row //Closure to make this property private this._rowWidth = function () { return rowWidth; }; }; tgTypes.InlineKeyboardMarkup.prototype.add = function (text, field, fieldValue) { this['inline_keyboard'][this._lastRow()].push( { 'text': text, [field]: fieldValue } ); if (this._isRowFull()) { this.newRow(); }; return this; }; tgTypes.InlineKeyboardMarkup.prototype.newRow = function () { this['inline_keyboard'].push([]); return this; }; tgTypes.InlineKeyboardMarkup.prototype._isRowFull = function () { if (this['inline_keyboard'][this._lastRow()].length === this._rowWidth()) { return true; }; }; tgTypes.InlineKeyboardMarkup.prototype._lastRow = function () { return this['inline_keyboard'].length-1; }; module.exports = tgTypes;
Fix logic error in inlineKeyboard
Fix logic error in inlineKeyboard
JavaScript
mit
TheBeastOfCaerbannog/last-fm-bot
--- +++ @@ -31,7 +31,7 @@ }; tgTypes.InlineKeyboardMarkup.prototype._isRowFull = function () { - if (this['inline_keyboard'][this._lastRow()] === this._rowWidth()-1) { + if (this['inline_keyboard'][this._lastRow()].length === this._rowWidth()) { return true; }; };
72cf0eef7e9600c806ae22325bb545938fbda4c7
test-projects/multi-embed-test-project/gulpfile.babel.js
test-projects/multi-embed-test-project/gulpfile.babel.js
var gulp = require('gulp'); var embedDefs = [ { componentPath: 'src/js/components/hello-world.jsx', webPath: 'hello-world/' }, { componentPath: 'src/js/components/hello-world-two.jsx', webPath: 'hello-world-two' } ]; var opts = { embedDefs: embedDefs, paths: ['node_modules/lucify-commons', 'test_modules/module1'], publishFromFolder: 'dist', defaultBucket: 'lucify-dev', maxAge: 3600, assetContext: 'embed/', baseUrl: 'http://dev.lucify.com/' }; var builder = require('../../index.js'); // lucify-component-builder builder(gulp, opts);
var gulp = require('gulp'); var embedDefs = [ { componentPath: 'src/js/components/hello-world.jsx', path: '/hello-world' }, { componentPath: 'src/js/components/hello-world-two.jsx', path: '/hello-world-two' } ]; var opts = { embedDefs: embedDefs, paths: ['node_modules/lucify-commons', 'test_modules/module1'], publishFromFolder: 'dist', defaultBucket: 'lucify-dev', maxAge: 3600, assetContext: 'embed/', baseUrl: 'http://dev.lucify.com/' }; var builder = require('../../index.js'); // lucify-component-builder builder(gulp, opts);
Modify embedDefs path attribute naming
Modify embedDefs path attribute naming
JavaScript
mit
lucified/lucify-component-builder,lucified/lucify-component-builder,lucified/lucify-component-builder
--- +++ @@ -4,11 +4,11 @@ var embedDefs = [ { componentPath: 'src/js/components/hello-world.jsx', - webPath: 'hello-world/' + path: '/hello-world' }, { componentPath: 'src/js/components/hello-world-two.jsx', - webPath: 'hello-world-two' + path: '/hello-world-two' } ];
50314c21bf0fe1a4fa7aa3349b3d952af2540a25
chrome/test/data/extensions/samples/subscribe/feed_finder.js
chrome/test/data/extensions/samples/subscribe/feed_finder.js
find(); window.addEventListener("focus", find); function find() { if (window == top) { // Find all the RSS link elements. var result = document.evaluate( '//link[@rel="alternate"][contains(@type, "rss") or ' + 'contains(@type, "atom") or contains(@type, "rdf")]', document, null, 0, null); var feeds = []; var item; while (item = result.iterateNext()) feeds.push(item.href); chromium.extension.connect().postMessage(feeds); } }
find(); window.addEventListener("focus", find); function find() { if (window == top) { // Find all the RSS link elements. var result = document.evaluate( '//link[@rel="alternate"][contains(@type, "rss") or ' + 'contains(@type, "atom") or contains(@type, "rdf")]', document, null, 0, null); var feeds = []; var item; while (item = result.iterateNext()) feeds.push(item.href); chrome.extension.connect().postMessage(feeds); } }
Fix an occurence of 'chromium' that didn't get changed to 'chrome'
Fix an occurence of 'chromium' that didn't get changed to 'chrome' Review URL: http://codereview.chromium.org/115049 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@15486 0039d316-1c4b-4281-b951-d872f2087c98
JavaScript
bsd-3-clause
ropik/chromium,adobe/chromium,adobe/chromium,yitian134/chromium,ropik/chromium,yitian134/chromium,adobe/chromium,yitian134/chromium,yitian134/chromium,gavinp/chromium,gavinp/chromium,gavinp/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,ropik/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,ropik/chromium,adobe/chromium,gavinp/chromium,yitian134/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,ropik/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,ropik/chromium,yitian134/chromium,adobe/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,adobe/chromium,adobe/chromium,adobe/chromium,ropik/chromium,ropik/chromium,gavinp/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,yitian134/chromium
--- +++ @@ -14,6 +14,6 @@ while (item = result.iterateNext()) feeds.push(item.href); - chromium.extension.connect().postMessage(feeds); + chrome.extension.connect().postMessage(feeds); } }
28de90037a64dcb7ff9bdfb32557090c49c53e3c
website/static/js/pages/resetpassword-page.js
website/static/js/pages/resetpassword-page.js
/** * Reset Password page */ 'use strict'; var $ = require('jquery'); var SetPassword = require('js/setPassword'); var verificationKey = window.contextVars.verification_key; var resetUrl = '/api/v1/resetpassword/' + verificationKey + '/'; var redirectrUrl = '/login/'; $(document).ready(function() { new SetPassword('#resetPasswordForm', 'reset', resetUrl, '', redirectrUrl); });
/** * Reset Password page */ 'use strict'; var $ = require('jquery'); var SetPassword = require('js/setPassword'); var verificationKey = window.contextVars.verification_key; var resetUrl = '/resetpassword/' + verificationKey + '/'; $(document).ready(function() { new SetPassword('#resetPasswordForm', 'reset', resetUrl, ''); });
Update post URL and viewModel params
Update post URL and viewModel params
JavaScript
apache-2.0
cwisecarver/osf.io,acshi/osf.io,Johnetordoff/osf.io,rdhyee/osf.io,aaxelb/osf.io,TomBaxter/osf.io,HalcyonChimera/osf.io,cwisecarver/osf.io,cslzchen/osf.io,felliott/osf.io,mfraezz/osf.io,aaxelb/osf.io,emetsger/osf.io,crcresearch/osf.io,brianjgeiger/osf.io,Nesiehr/osf.io,DanielSBrown/osf.io,CenterForOpenScience/osf.io,sloria/osf.io,mluo613/osf.io,mfraezz/osf.io,wearpants/osf.io,alexschiller/osf.io,samchrisinger/osf.io,mattclark/osf.io,mluo613/osf.io,pattisdr/osf.io,rdhyee/osf.io,TomBaxter/osf.io,amyshi188/osf.io,samchrisinger/osf.io,pattisdr/osf.io,laurenrevere/osf.io,mfraezz/osf.io,laurenrevere/osf.io,SSJohns/osf.io,CenterForOpenScience/osf.io,aaxelb/osf.io,alexschiller/osf.io,felliott/osf.io,saradbowman/osf.io,SSJohns/osf.io,alexschiller/osf.io,adlius/osf.io,acshi/osf.io,binoculars/osf.io,Nesiehr/osf.io,erinspace/osf.io,erinspace/osf.io,adlius/osf.io,chrisseto/osf.io,HalcyonChimera/osf.io,DanielSBrown/osf.io,felliott/osf.io,icereval/osf.io,wearpants/osf.io,samchrisinger/osf.io,chrisseto/osf.io,Johnetordoff/osf.io,monikagrabowska/osf.io,samchrisinger/osf.io,HalcyonChimera/osf.io,caneruguz/osf.io,caneruguz/osf.io,saradbowman/osf.io,acshi/osf.io,DanielSBrown/osf.io,Johnetordoff/osf.io,amyshi188/osf.io,monikagrabowska/osf.io,hmoco/osf.io,Johnetordoff/osf.io,mattclark/osf.io,wearpants/osf.io,icereval/osf.io,chennan47/osf.io,hmoco/osf.io,TomBaxter/osf.io,CenterForOpenScience/osf.io,binoculars/osf.io,emetsger/osf.io,brianjgeiger/osf.io,alexschiller/osf.io,emetsger/osf.io,chennan47/osf.io,HalcyonChimera/osf.io,adlius/osf.io,brianjgeiger/osf.io,brianjgeiger/osf.io,baylee-d/osf.io,amyshi188/osf.io,crcresearch/osf.io,leb2dg/osf.io,baylee-d/osf.io,wearpants/osf.io,erinspace/osf.io,adlius/osf.io,emetsger/osf.io,leb2dg/osf.io,alexschiller/osf.io,mattclark/osf.io,amyshi188/osf.io,laurenrevere/osf.io,cslzchen/osf.io,cwisecarver/osf.io,mluo613/osf.io,monikagrabowska/osf.io,caseyrollins/osf.io,caneruguz/osf.io,baylee-d/osf.io,aaxelb/osf.io,pattisdr/osf.io,sloria/osf.io,cslzchen/osf.io,mfraezz/osf.io,Nesiehr/osf.io,monikagrabowska/osf.io,leb2dg/osf.io,cslzchen/osf.io,rdhyee/osf.io,monikagrabowska/osf.io,mluo613/osf.io,chennan47/osf.io,SSJohns/osf.io,caseyrollins/osf.io,leb2dg/osf.io,hmoco/osf.io,rdhyee/osf.io,cwisecarver/osf.io,caneruguz/osf.io,SSJohns/osf.io,acshi/osf.io,chrisseto/osf.io,mluo613/osf.io,binoculars/osf.io,acshi/osf.io,caseyrollins/osf.io,CenterForOpenScience/osf.io,sloria/osf.io,DanielSBrown/osf.io,felliott/osf.io,hmoco/osf.io,Nesiehr/osf.io,crcresearch/osf.io,chrisseto/osf.io,icereval/osf.io
--- +++ @@ -6,10 +6,9 @@ var SetPassword = require('js/setPassword'); var verificationKey = window.contextVars.verification_key; -var resetUrl = '/api/v1/resetpassword/' + verificationKey + '/'; -var redirectrUrl = '/login/'; +var resetUrl = '/resetpassword/' + verificationKey + '/'; $(document).ready(function() { - new SetPassword('#resetPasswordForm', 'reset', resetUrl, '', redirectrUrl); + new SetPassword('#resetPasswordForm', 'reset', resetUrl, ''); });
5d850a80e5d335d57bc321e827aade916c0b7f66
js/custom/pet-search.js
js/custom/pet-search.js
$(function(){ var $form = $('#pet-search-form'), $container = $('.homepage-box-list'); $form.on('submit', function(e) { e.preventDefault(); var action = $(this).attr('action'), params = $(this).serialize(); $.get(action, params).then(function(output){ $container.fadeOut('fast', function(){ $(this).html(output).fadeIn('fast'); }); }); }); $form.on('change', ':input', function() { $form.submit(); }); });
$(function(){ var $form = $('#pet-search-form'), $inputs = $form.find(':input'), $container = $('.homepage-box-list'); $form.on('submit', function(e) { e.preventDefault(); var action = $(this).attr('action'), params = $(this).serialize(); $inputs.attr('disabled', true); $.get(action, params).then(function(output){ $container.fadeOut('fast', function(){ $(this).html(output).fadeIn('fast'); $inputs.attr('disabled', false); }); }); }); $form.on('change', ':input', function() { $form.submit(); }); });
Disable search form while loading
Disable search form while loading
JavaScript
mit
aviaron/touzik,aviaron/touzik
--- +++ @@ -1,6 +1,7 @@ $(function(){ var $form = $('#pet-search-form'), + $inputs = $form.find(':input'), $container = $('.homepage-box-list'); $form.on('submit', function(e) { @@ -9,9 +10,12 @@ var action = $(this).attr('action'), params = $(this).serialize(); + $inputs.attr('disabled', true); + $.get(action, params).then(function(output){ $container.fadeOut('fast', function(){ $(this).html(output).fadeIn('fast'); + $inputs.attr('disabled', false); }); }); });
bebb1b0f8e2a26b4026baa1a697aef709d6231d8
app/feeds/new/index/route.js
app/feeds/new/index/route.js
import Ember from 'ember'; export default Ember.Route.extend({ beforeModel: function(){ this.store.unloadAll(); }, createFeedFromGtfsService: Ember.inject.service('create-feed-from-gtfs'), model: function() { this.get('createFeedFromGtfsService').createFeedModel(); return this.get('createFeedFromGtfsService').feedModel; } });
import Ember from 'ember'; export default Ember.Route.extend({ beforeModel: function(){ // this.store.unloadAll(); }, createFeedFromGtfsService: Ember.inject.service('create-feed-from-gtfs'), model: function() { console.log('feeds.new.index model'); var oldModel = this.get('createFeedFromGtfsService').feedModel; this.store.unloadAll(); var newModel = this.get('createFeedFromGtfsService').createFeedModel(); if (oldModel != null && oldModel.get('errors.length') > 0) { console.log('setting url:', oldModel.get('url')); newModel.set('url', oldModel.get('url')); oldModel.get('errors').errorsFor('url').forEach(function(error){ console.log(error.attribute, error.message); newModel.get('errors').add(error.attribute, error.message); }); } return newModel } });
Copy over errors from bad response
Copy over errors from bad response
JavaScript
mit
transitland/feed-registry,transitland/feed-registry
--- +++ @@ -2,11 +2,22 @@ export default Ember.Route.extend({ beforeModel: function(){ - this.store.unloadAll(); + // this.store.unloadAll(); }, createFeedFromGtfsService: Ember.inject.service('create-feed-from-gtfs'), model: function() { - this.get('createFeedFromGtfsService').createFeedModel(); - return this.get('createFeedFromGtfsService').feedModel; + console.log('feeds.new.index model'); + var oldModel = this.get('createFeedFromGtfsService').feedModel; + this.store.unloadAll(); + var newModel = this.get('createFeedFromGtfsService').createFeedModel(); + if (oldModel != null && oldModel.get('errors.length') > 0) { + console.log('setting url:', oldModel.get('url')); + newModel.set('url', oldModel.get('url')); + oldModel.get('errors').errorsFor('url').forEach(function(error){ + console.log(error.attribute, error.message); + newModel.get('errors').add(error.attribute, error.message); + }); + } + return newModel } });
370676fbefb12fc56280f6e19d9a747802df7feb
app/scripts/contentscript.js
app/scripts/contentscript.js
'use strict'; (function($){ $('#js-discussion-header').text('foo bar'); })(jQuery);
'use strict'; (function($){ var $container = $('#js-repo-pjax-container'); var issueTitle = $container.find('#js-discussion-header .js-issue-title').text(); if (/(\[wip\]|\[do\s*not\s*merge\])/i.test(issueTitle)) { var $buttonMerge = $container.find('#js-pull-merging button.merge-branch-action.js-details-target'); $buttonMerge.attr('disabled', true); $buttonMerge.text("WIP! You can't merge!"); } })(jQuery);
Add You can't merge! logic
Add You can't merge! logic
JavaScript
mit
togusafish/sanemat-_-do-not-merge-wip-for-github,sanemat/do-not-merge-wip-for-github,togusafish/sanemat-_-do-not-merge-wip-for-github,sanemat/do-not-merge-wip-for-github,Fryguy/do-not-merge-wip-for-github,togusafish/sanemat-_-do-not-merge-wip-for-github,Fryguy/do-not-merge-wip-for-github,sanemat/do-not-merge-wip-for-github,Fryguy/do-not-merge-wip-for-github
--- +++ @@ -1,5 +1,11 @@ 'use strict'; (function($){ - $('#js-discussion-header').text('foo bar'); + var $container = $('#js-repo-pjax-container'); + var issueTitle = $container.find('#js-discussion-header .js-issue-title').text(); + if (/(\[wip\]|\[do\s*not\s*merge\])/i.test(issueTitle)) { + var $buttonMerge = $container.find('#js-pull-merging button.merge-branch-action.js-details-target'); + $buttonMerge.attr('disabled', true); + $buttonMerge.text("WIP! You can't merge!"); + } })(jQuery);
68a8107c4b61aa68b0c8cf75396a780a1598c232
app/scripts/scenes/loader.js
app/scripts/scenes/loader.js
import files from '@/constants/assets'; import fontConfig from '@/constants/bitmap-fonts'; export default class Loader extends Phaser.Scene { /** * Takes care of loading the main game assets. * * @extends Phaser.Scene */ constructor() { super({key: 'Loader', files}); } /** * Called when this scene is initialized. * * @protected * @param {object} [data={}] - Initialization parameters. */ init(/* data */) { // Register our custom bitmap font in he game system cache. this.cache.bitmapFont.add( fontConfig.image, Phaser.GameObjects.RetroFont.Parse(this, fontConfig) ); // We are done here. Launch the game menu. this.scene.start('Menu'); } }
import files from '@/constants/assets'; import fontConfig from '@/constants/bitmap-fonts'; export default class Loader extends Phaser.Scene { /** * Takes care of loading the main game assets. * * @extends Phaser.Scene */ constructor() { super({key: 'Loader', pack: {files}}); } /** * Called when this scene is initialized. * * @protected * @param {object} [data={}] - Initialization parameters. */ init(/* data */) { // Register our custom bitmap font in he game system cache. this.cache.bitmapFont.add( fontConfig.image, Phaser.GameObjects.RetroFont.Parse(this, fontConfig) ); // We are done here. Launch the game menu. this.scene.start('Menu'); } }
Load files using the new `pack` scene configuration.
Load files using the new `pack` scene configuration.
JavaScript
mit
rblopes/phaser-3-snake-game,rblopes/phaser-3-snake-game
--- +++ @@ -8,7 +8,7 @@ * @extends Phaser.Scene */ constructor() { - super({key: 'Loader', files}); + super({key: 'Loader', pack: {files}}); } /**
3a438493f2a36ceba3edb25eacfeea13da3db2fc
app/components/settings/area-detail/styles.js
app/components/settings/area-detail/styles.js
import Theme from 'config/theme'; import { StyleSheet } from 'react-native'; export default StyleSheet.create({ container: { flex: 1, backgroundColor: Theme.background.main, paddingTop: 10 }, containerContent: { paddingBottom: 20 }, content: { paddingTop: 0, paddingBottom: 30 }, buttonContainer: { padding: 10 }, imageContainer: { backgroundColor: Theme.background.modal }, image: { width: 360, height: 200, resizeMode: 'cover' } });
import Theme from 'config/theme'; import { StyleSheet } from 'react-native'; export default StyleSheet.create({ container: { flex: 1, backgroundColor: Theme.background.main, paddingTop: 10 }, containerContent: { paddingBottom: 20 }, content: { paddingTop: 0, paddingBottom: 30 }, buttonContainer: { padding: 10 }, imageContainer: { backgroundColor: Theme.background.modal, alignItems: 'center', justifyContent: 'center' }, image: { width: 360, height: 200, resizeMode: 'cover' } });
Align images to center for bigger screens
Align images to center for bigger screens
JavaScript
mit
Vizzuality/forest-watcher,Vizzuality/forest-watcher,Vizzuality/forest-watcher,Vizzuality/forest-watcher,Vizzuality/forest-watcher
--- +++ @@ -18,7 +18,9 @@ padding: 10 }, imageContainer: { - backgroundColor: Theme.background.modal + backgroundColor: Theme.background.modal, + alignItems: 'center', + justifyContent: 'center' }, image: { width: 360,
aa34d647542b6a7a4e4f4d15f32776cb7f975eb1
lib/laravel/download.js
lib/laravel/download.js
(function(exports) { "use strict"; var request = require('request'); var Sink = require('pipette').Sink; var unzipper = require('../process-zip'); var fs = require('fs'); exports.downloadLaravel = function(grunt, init, done) { unzipper.processZip(request('https://github.com/laravel/laravel/archive/master.zip'), { fromdir: 'laravel-master/', todir: 'build/', verbose: function(msg) { grunt.verbose.writeln(msg); }, complete: done, rename: function(file) { var matches = /^(.*)\.md$/.exec(file); if (matches) { return matches[1] + '-Laravel.md'; } if (/build\/public\/.htaccess$/.test(file)) { // need to append this file because it already exists (comes with h5bp) new Sink(this).on('data', function(buffer) { var htaccess = '\n' + '# ----------------------------------------------------------------------\n' + '# Laravel framework\n' + '# ----------------------------------------------------------------------\n' + buffer.toString(); fs.appendFileSync(file, htaccess); }); } return file; } }); }; })(typeof exports === 'object' && exports || this);
(function(exports) { "use strict"; var request = require('request'); var Sink = require('pipette').Sink; var unzipper = require('../process-zip'); var fs = require('fs'); exports.downloadLaravel = function(grunt, init, done) { unzipper.processZip(request('https://github.com/laravel/laravel/archive/master.zip'), { fromdir: 'laravel-master/', todir: 'build/', verbose: function(msg) { grunt.verbose.writeln(msg); }, complete: done, rename: function(file) { var matches = /^(.*)\.md$/.exec(file); if (matches) { return matches[1] + '-Laravel.md'; } if (/build\/public\/.htaccess$/.test(file)) { // need to append this file because it already exists (comes with h5bp) new Sink(this).on('data', function(buffer) { // need to add an exception for pages served via DirectoryIndex // before the line containing // RewriteRule ^(.*)/$ // insert // RewriteCond %{REQUEST_FILENAME}/index.html !-f var htaccess = buffer.toString().replace(/(RewriteRule \^\(\.\*\)\/\$[^\r\n]*)/g, 'RewriteCond %{REQUEST_FILENAME}/index.html !-f\n $1'); htaccess = '\n' + '# ----------------------------------------------------------------------\n' + '# Laravel framework\n' + '# ----------------------------------------------------------------------\n' + htaccess; fs.appendFileSync(file, htaccess); }); } return file; } }); }; })(typeof exports === 'object' && exports || this);
Update Laravel .htaccess to fix redirect loop on DirectoryIndex pages such as /tests/
Update Laravel .htaccess to fix redirect loop on DirectoryIndex pages such as /tests/
JavaScript
mit
TheMonkeys/monkeybones,TheMonkeys/monkeybones,TheMonkeys/monkeybones
--- +++ @@ -21,11 +21,18 @@ if (/build\/public\/.htaccess$/.test(file)) { // need to append this file because it already exists (comes with h5bp) new Sink(this).on('data', function(buffer) { - var htaccess = '\n' + + // need to add an exception for pages served via DirectoryIndex + // before the line containing + // RewriteRule ^(.*)/$ + // insert + // RewriteCond %{REQUEST_FILENAME}/index.html !-f + var htaccess = buffer.toString().replace(/(RewriteRule \^\(\.\*\)\/\$[^\r\n]*)/g, 'RewriteCond %{REQUEST_FILENAME}/index.html !-f\n $1'); + + htaccess = '\n' + '# ----------------------------------------------------------------------\n' + '# Laravel framework\n' + '# ----------------------------------------------------------------------\n' + - buffer.toString(); + htaccess; fs.appendFileSync(file, htaccess); }); }
0bf372d7da96953f07f0bcd1db3ff86f7c68612d
app/actions/session.js
app/actions/session.js
import axios from 'axios' import { API } from '../constants' export const LOGIN = 'LOGIN' export const LOGIN_SUCCESS = 'LOGIN_SUCCESS' export const LOGIN_FAILURE = 'LOGIN_FAILURE' export const login = () => async (dispatch, state) => { dispatch({ type: LOGIN }) try { const response = await axios.post(`http://localhost:8000/login`, state().form.login.values) dispatch({ type: LOGIN_SUCCESS, token: response.data['token'] }) } catch ({ response }) { dispatch({ type: LOGIN_FAILURE, error: response.data }) } }
import axios from 'axios' import { API } from '../constants' export const LOGIN = 'LOGIN' export const LOGIN_SUCCESS = 'LOGIN_SUCCESS' export const LOGIN_FAILURE = 'LOGIN_FAILURE' export const login = creds => async dispatch => { dispatch({ type: LOGIN }) try { const response = await axios.post(`http://localhost:8000/login`, creds) dispatch({ type: LOGIN_SUCCESS, token: response.data['token'] }) } catch (err) { const response = err.response const error = response ? response.data : err.message dispatch({ type: LOGIN_FAILURE, error }) } }
Refactor for redux-form data and better error checking
Refactor for redux-form data and better error checking
JavaScript
mit
danielzy95/oaa-chat,danielzy95/oaa-chat
--- +++ @@ -5,12 +5,14 @@ export const LOGIN_SUCCESS = 'LOGIN_SUCCESS' export const LOGIN_FAILURE = 'LOGIN_FAILURE' -export const login = () => async (dispatch, state) => { +export const login = creds => async dispatch => { dispatch({ type: LOGIN }) try { - const response = await axios.post(`http://localhost:8000/login`, state().form.login.values) + const response = await axios.post(`http://localhost:8000/login`, creds) dispatch({ type: LOGIN_SUCCESS, token: response.data['token'] }) - } catch ({ response }) { - dispatch({ type: LOGIN_FAILURE, error: response.data }) + } catch (err) { + const response = err.response + const error = response ? response.data : err.message + dispatch({ type: LOGIN_FAILURE, error }) } }
333a26104f1d0bb6e8b756d57c1e0be496b95fe2
lib/util/apiResponse.js
lib/util/apiResponse.js
'use strict'; function ApiResponse () { }; ApiResponse.error = function (err) { var result = {}; result = { ok: false }; if (err instanceof Error) { result.error = err.toString(); } else { result.error = err; } return result; }; ApiResponse.success = function (data) { var result = data || {}; result.ok = true; return result; }; module.exports = ApiResponse;
'use strict'; function ApiResponse () { }; ApiResponse.error = function (err, info = {}) { var result = { ok: false, info }; if (err instanceof Error) { result.error = err.toString(); } else { result.error = err; } return result; }; ApiResponse.success = function (data) { var result = data || {}; result.ok = true; return result; }; module.exports = ApiResponse;
Change a method to receiving additional information
Change a method to receiving additional information
JavaScript
mit
crowi/crowi,crowi/crowi,crowi/crowi
--- +++ @@ -3,11 +3,10 @@ function ApiResponse () { }; -ApiResponse.error = function (err) { - var result = {}; - - result = { - ok: false +ApiResponse.error = function (err, info = {}) { + var result = { + ok: false, + info }; if (err instanceof Error) {
9ab1175c02d935e38a6a3a411b40b31cf5bc9f19
scripts/global.webpack.js
scripts/global.webpack.js
var $ = require('npm-zepto'); var Cookies = require('js-cookie'); $(function () { var cookiesElement = $('#cookies'); if (Cookies.get('cookies_closed')) { cookiesElement.hide(); } else { var marginElement = cookiesElement.prev(); var closeButton = $('<button class="btn">Close</button>').on('click', function () { Cookies.set('cookies_closed', true); cookiesElement.hide(); marginElement.css('margin-bottom', 'inherit'); }); cookiesElement .addClass('js-enabled') .find('.block-container') .append(closeButton); marginElement.css('margin-bottom', cookiesElement.height()); } });
var $ = require('npm-zepto'); var Cookies = require('js-cookie'); $(function () { var cookiesElement = $('#cookies'); if (Cookies.get('cookies_closed')) { cookiesElement.hide(); } else { var marginElement = cookiesElement.prev(); var closeButton = $('<button class="btn">Close</button>').on('click', function () { Cookies.set('cookies_closed', true, { expires: 3650 }); cookiesElement.hide(); marginElement.css('margin-bottom', 'inherit'); }); cookiesElement .addClass('js-enabled') .find('.block-container') .append(closeButton); marginElement.css('margin-bottom', cookiesElement.height()); } });
Set cookies to expire in ten years
Set cookies to expire in ten years
JavaScript
mit
megoth/icanhasweb,megoth/icanhasweb
--- +++ @@ -8,7 +8,7 @@ } else { var marginElement = cookiesElement.prev(); var closeButton = $('<button class="btn">Close</button>').on('click', function () { - Cookies.set('cookies_closed', true); + Cookies.set('cookies_closed', true, { expires: 3650 }); cookiesElement.hide(); marginElement.css('margin-bottom', 'inherit'); });
4098c1bda28e2fb4e22b8ce3e14a391c46f8eafb
server/game/cards/07-WotW/IuchiDaiyu.js
server/game/cards/07-WotW/IuchiDaiyu.js
const DrawCard = require('../../drawcard.js'); class IuchiDaiyu extends DrawCard { setupCardAbilities(ability) { this.action({ title: '+1 military for each faceup province', condition: () => this.game.isDuringConflict(), target: { gameAction: ability.actions.cardLastingEffect(context => ({ effect: ability.effects.modifyMilitarySkill(context.player.getNumberOfOpponentsFaceupProvinces()) })) }, effect: 'give {0} +1{1} for each faceup non-stronghold province their opponent controls (+{2}{1})', effectArgs: context => ['military', context.player.getNumberOfOpponentsFaceupProvinces()] }); } } IuchiDaiyu.id = 'iuchi-daiyu'; module.exports = IuchiDaiyu;
const DrawCard = require('../../drawcard.js'); const AbilityDsl = require('../../abilitydsl'); class IuchiDaiyu extends DrawCard { setupCardAbilities() { this.action({ title: '+1 military for each faceup province', condition: () => this.game.isDuringConflict(), target: { gameAction: AbilityDsl.actions.cardLastingEffect(context => ({ effect: AbilityDsl.effects.modifyMilitarySkill(context.player.getNumberOfOpponentsFaceupProvinces()) })) }, effect: 'give {0} +1{1} for each faceup non-stronghold province their opponent controls (+{2}{1})', effectArgs: context => ['military', context.player.getNumberOfOpponentsFaceupProvinces()] }); } } IuchiDaiyu.id = 'iuchi-daiyu'; module.exports = IuchiDaiyu;
Update Iuchi Daiyu to use AbilityDsl
Update Iuchi Daiyu to use AbilityDsl
JavaScript
mit
jeremylarner/ringteki,jeremylarner/ringteki,gryffon/ringteki,jeremylarner/ringteki,gryffon/ringteki,gryffon/ringteki
--- +++ @@ -1,13 +1,14 @@ const DrawCard = require('../../drawcard.js'); +const AbilityDsl = require('../../abilitydsl'); class IuchiDaiyu extends DrawCard { - setupCardAbilities(ability) { + setupCardAbilities() { this.action({ title: '+1 military for each faceup province', condition: () => this.game.isDuringConflict(), target: { - gameAction: ability.actions.cardLastingEffect(context => ({ - effect: ability.effects.modifyMilitarySkill(context.player.getNumberOfOpponentsFaceupProvinces()) + gameAction: AbilityDsl.actions.cardLastingEffect(context => ({ + effect: AbilityDsl.effects.modifyMilitarySkill(context.player.getNumberOfOpponentsFaceupProvinces()) })) }, effect: 'give {0} +1{1} for each faceup non-stronghold province their opponent controls (+{2}{1})',
f091824ece25a6384951e215065fa7e2de5c8e97
src/store/create-api-server.js
src/store/create-api-server.js
import Firebase from 'firebase' import LRU from 'lru-cache' let api if (process.__API__) { api = process.__API__ } else { api = process.__API__ = new Firebase('https://hacker-news.firebaseio.com/v0') // fetched item cache api.cachedItems = LRU({ max: 1000, maxAge: 1000 * 60 * 15 // 15 min cache }) // cache the latest story ids api.cachedIds = {} ;['top', 'new', 'show', 'ask', 'job'].forEach(type => { api.child(`${type}stories`).on('value', snapshot => { api.cachedIds[type] = snapshot.val() }) }) } export default api
import Firebase from 'firebase' import LRU from 'lru-cache' let api const config = { databaseURL: 'https://hacker-news.firebaseio.com' } const version = '/v0' if (process.__API__) { api = process.__API__ } else { Firebase.initializeApp(config) api = process.__API__ = Firebase.database().ref(version) // fetched item cache api.cachedItems = LRU({ max: 1000, maxAge: 1000 * 60 * 15 // 15 min cache }) // cache the latest story ids api.cachedIds = {} ;['top', 'new', 'show', 'ask', 'job'].forEach(type => { api.child(`${type}stories`).on('value', snapshot => { api.cachedIds[type] = snapshot.val() }) }) } export default api
Update server to latest Firebase
Update server to latest Firebase
JavaScript
mit
IRlyDontKnow/sylius-shop,keisei77/vue-hackernews-2.0,IRlyDontKnow/sylius-shop,valentinvieriu/visual-hacker-news,Ryan-PEK/tbz-mock,Ryan-PEK/tbz-mock,keisei77/vue-hackernews-2.0,valentinvieriu/visual-hacker-news
--- +++ @@ -2,11 +2,16 @@ import LRU from 'lru-cache' let api +const config = { + databaseURL: 'https://hacker-news.firebaseio.com' +} +const version = '/v0' if (process.__API__) { api = process.__API__ } else { - api = process.__API__ = new Firebase('https://hacker-news.firebaseio.com/v0') + Firebase.initializeApp(config) + api = process.__API__ = Firebase.database().ref(version) // fetched item cache api.cachedItems = LRU({
babeb444b2d2bff649d9100ffef3de89d6ca7247
reconfigure/coordinator.js
reconfigure/coordinator.js
function Coordinator (consensus) { this._listeners = [] this._consensus = consensus } Coordinator.prototype.listen = function (url, callback) { // <- listen, POST, -> get them started if (this._listeners.indexOf(url) < 0) { this._listeners.push(url) this._consensus.addListener(url, function (error, act) { if (!act) { callback(null, false) } else { callback(null, act.node.value == url) } }) } else { callback(null, false) } } Coordinator.prototype.unlisten = function (url, callback) { var len = this._listeners.length this._listeners = this._listeners.filter(function (el) { return (url !== el) }) if (!(len == this._listeners.length)) { this._consensus.removeListener(url, function (error, act) { if (!act) { callback(null, false) } else { callback(null, true) } }) } else {callback(null, false)} } /* Coordinator.prototype.update = cadence(function (async) { async.forEach(function (urls) { async(function () { // http POST and service is missing }, function (body, response) { if (!response.okay) { setTimeout(function () { }, 60000) } }, function () { }) })(this._listeners) }) */ /* Coordinator.prototype.set = cadence(function (async) { function (callback) { self.update(callback) } }) Coordinator.prototype.list = cadence(function (async) { }) */ module.exports = Coordinator
function Coordinator (consensus) { this._consensus = consensus } Coordinator.prototype.listen = function (url, callback) { // <- listen, POST, -> get them started this._consensus.addListener(url, function (error, act) { if (!act) { callback(null, false) } else { callback(null, act.node.value == url) } }) } Coordinator.prototype.unlisten = function (url, callback) { this._consensus.removeListener(url, function (error, act) { if (!act) { callback(null, false) } else { callback(null, true) } }) } /* Coordinator.prototype.update = cadence(function (async) { async.forEach(function (urls) { async(function () { // http POST and service is missing }, function (body, response) { if (!response.okay) { setTimeout(function () { }, 60000) } }, function () { }) })(this._listeners) }) */ /* Coordinator.prototype.set = cadence(function (async) { function (callback) { self.update(callback) } }) Coordinator.prototype.list = cadence(function (async) { }) */ module.exports = Coordinator
Remove local index of listeners.
Remove local index of listeners.
JavaScript
mit
demarius/reconfigure,bigeasy/reconfigure,bigeasy/reconfigure,demarius/reconfigure
--- +++ @@ -1,38 +1,25 @@ function Coordinator (consensus) { - this._listeners = [] this._consensus = consensus } Coordinator.prototype.listen = function (url, callback) { // <- listen, POST, -> get them started - if (this._listeners.indexOf(url) < 0) { - this._listeners.push(url) - this._consensus.addListener(url, function (error, act) { - if (!act) { - callback(null, false) - } else { - callback(null, act.node.value == url) - } - }) - } else { - callback(null, false) - } + this._consensus.addListener(url, function (error, act) { + if (!act) { + callback(null, false) + } else { + callback(null, act.node.value == url) + } + }) } Coordinator.prototype.unlisten = function (url, callback) { - var len = this._listeners.length - this._listeners = this._listeners.filter(function (el) { - return (url !== el) + this._consensus.removeListener(url, function (error, act) { + if (!act) { + callback(null, false) + } else { + callback(null, true) + } }) - - if (!(len == this._listeners.length)) { - this._consensus.removeListener(url, function (error, act) { - if (!act) { - callback(null, false) - } else { - callback(null, true) - } - }) - } else {callback(null, false)} } /*
8ef11ed11f09b9f4ce7d53234fdb6100c7fe8451
test/fixtures/index.js
test/fixtures/index.js
module.exports = function() { return []; };
var sample_xform = require('./sample_xform'); module.exports = function() { return [ { request: { method: "GET", url: "http://www.example.org/xform00", params: {}, }, response: { code: "200", data: sample_xform, }, }, ]; };
Add fixture for getting an xform from an external server
Add fixture for getting an xform from an external server
JavaScript
bsd-3-clause
praekelt/go-jsbox-xform,praekelt/go-jsbox-xform
--- +++ @@ -1,3 +1,17 @@ +var sample_xform = require('./sample_xform'); + module.exports = function() { - return []; + return [ + { + request: { + method: "GET", + url: "http://www.example.org/xform00", + params: {}, + }, + response: { + code: "200", + data: sample_xform, + }, + }, + ]; };
0ff9feb094a91e29fb2aacc6655ac5d1cb83cc94
test/helpers/get-tmp-dir.js
test/helpers/get-tmp-dir.js
/* * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ 'use strict'; var path = require('path'); var fse = require('fs-extra'); var uuid = require('uuid').v1; module.exports = function(path_) { var tmpDir = path_ || path.join(__dirname, '..', 'tmp', uuid()); fse.mkdirpSync(tmpDir); return tmpDir; };
/* * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ 'use strict'; var path = require('path'); var fse = require('fs-extra'); var uuid = require('uuid').v1; module.exports = function(path_) { var tmpDir = path_ || path.join(__dirname, '..', 'tmp', uuid()); fse.mkdirpSync(tmpDir); if (!process.env.NO_REMOVE_TMP) { process.once('exit', function() { fse.removeSync(tmpDir); }); } return tmpDir; };
Remove a tmp directory unless told not to
Remove a tmp directory unless told not to
JavaScript
artistic-2.0
nearform/nscale-kernel,nearform/nscale-kernel
--- +++ @@ -21,5 +21,12 @@ module.exports = function(path_) { var tmpDir = path_ || path.join(__dirname, '..', 'tmp', uuid()); fse.mkdirpSync(tmpDir); + + if (!process.env.NO_REMOVE_TMP) { + process.once('exit', function() { + fse.removeSync(tmpDir); + }); + } + return tmpDir; };
57fe26161d7af3f85d6bf3a009d8a915cdae6690
tools/tests/apps/once/once.js
tools/tests/apps/once/once.js
process.stdout.write("once test\n"); if (process.env.RUN_ONCE_OUTCOME === "exit") process.exit(123); if (process.env.RUN_ONCE_OUTCOME === "kill") { process.kill(process.pid, 'SIGKILL'); } if (process.env.RUN_ONCE_OUTCOME === "hang") { // The outstanding timeout will prevent node from exiting setTimeout(function () {}, 365 * 24 * 60 * 60); } if (process.env.RUN_ONCE_OUTCOME === "mongo") { var test = new Mongo.Collection('test'); var triesLeft = 10; function tryInsert() { try { test.insert({ value: 86 }); } catch (e) { if (--triesLeft <= 0) { throw e; } console.log("insert failed; retrying:", String(e.stack || e)); setTimeout(tryInsert, 1000); return; } process.exit(test.findOne().value); } Meteor.startup(tryInsert); }
process.stdout.write("once test\n"); if (process.env.RUN_ONCE_OUTCOME === "exit") process.exit(123); if (process.env.RUN_ONCE_OUTCOME === "kill") { process.kill(process.pid, 'SIGKILL'); } if (process.env.RUN_ONCE_OUTCOME === "hang") { // The outstanding timeout will prevent node from exiting setTimeout(function () {}, 365 * 24 * 60 * 60); } if (process.env.RUN_ONCE_OUTCOME === "mongo") { var test = new Mongo.Collection('test'); var triesLeft = 10; function tryInsert() { try { test.insert({ value: 86 }); } catch (e) { if (--triesLeft <= 0) { throw e; } console.log("insert failed; retrying:", String(e.stack || e)); Meteor.setTimeout(tryInsert, 1000); return; } process.exit(test.findOne().value); } Meteor.startup(tryInsert); }
Use Meteor.setTimeout to re-run tryInsert function.
Use Meteor.setTimeout to re-run tryInsert function.
JavaScript
mit
Hansoft/meteor,mjmasn/meteor,mjmasn/meteor,mjmasn/meteor,Hansoft/meteor,Hansoft/meteor,mjmasn/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,mjmasn/meteor,Hansoft/meteor,mjmasn/meteor,mjmasn/meteor
--- +++ @@ -25,7 +25,7 @@ } console.log("insert failed; retrying:", String(e.stack || e)); - setTimeout(tryInsert, 1000); + Meteor.setTimeout(tryInsert, 1000); return; }
c765aab5a03cdf25bdc6ce5043aa0d8748695fc6
src/authentication/authenticator/get.js
src/authentication/authenticator/get.js
/** * This file is reserved for future development * * Not ready for use */ 'use strict'; /** * Module dependencies. */ import { Router } from 'express'; import { clone } from 'lodash'; module.exports = class CoreGETAuthenticator { /** * Do not override the constructor * * @param {string} name * @param {Object} settings * @param {Object} dependencies */ constructor(name, settings, dependencies) { this.router = Router(); this.settings = clone(settings); this.dependencies = dependencies; this.define(); } /** * Override this with a function to define router configuration */ define() { // Example: this.router.use(...) } };
/** * This file is reserved for future development * * Not ready for use */ 'use strict'; /** * Module dependencies. */ import { Router } from 'express'; import { clone } from 'lodash'; module.exports = class CoreGETAuthenticator { /** * Do not override the constructor * * @param {string} name * @param {Object} settings * @param {Object} dependencies */ constructor(name, settings, dependencies) { this.router = Router(); this.settings = clone(settings); this.dependencies = dependencies; } /** * Override this with a function to define an authenticator route */ hubToAuthenticator() { /** * Example code: * * return (req, res, next) => { * * } */ } };
Use proper method name in `CoreGETAuthenticator`
Use proper method name in `CoreGETAuthenticator`
JavaScript
mit
HiFaraz/identity-desk
--- +++ @@ -23,14 +23,18 @@ this.router = Router(); this.settings = clone(settings); this.dependencies = dependencies; - - this.define(); } /** - * Override this with a function to define router configuration + * Override this with a function to define an authenticator route */ - define() { - // Example: this.router.use(...) + hubToAuthenticator() { + /** + * Example code: + * + * return (req, res, next) => { + * + * } + */ } };
0c76938a634617427c715b9f36a0a14e58576b1a
src/client/components/TabNav/reducer.js
src/client/components/TabNav/reducer.js
import { TAB_NAV__SELECT } from '../../actions' export default (state = {}, { type, ...action }) => type === 'TAB_NAV__SELECT' ? action : state
import { TAB_NAV__SELECT } from '../../actions' export default (state = {}, { type, ...action }) => type === TAB_NAV__SELECT ? action : state
Fix the string literal action type
Fix the string literal action type
JavaScript
mit
uktrade/data-hub-frontend,uktrade/data-hub-frontend,uktrade/data-hub-fe-beta2,uktrade/data-hub-frontend,uktrade/data-hub-fe-beta2
--- +++ @@ -1,4 +1,4 @@ import { TAB_NAV__SELECT } from '../../actions' export default (state = {}, { type, ...action }) => - type === 'TAB_NAV__SELECT' ? action : state + type === TAB_NAV__SELECT ? action : state
6a5a2cb92b9c2614fd9df1e79657fa4c1191a094
server/boot/mercadopago.js
server/boot/mercadopago.js
'use strict'; var MP = require('mercadopago'); module.exports = function(app) { app.mp = new MP(process.env.MP_ID, process.env.MP_SECRET); if(process.env.MP_SANDBOX) { app.mp.sandboxMode(true); } var at = app.mp.getAccessToken() .then(function(accessToken) { app.mp.accessToken = accessToken; console.log('Successfully injected MercadoPago credentials in app'); }, function(err) { console.log('Unhandled MP error: ' + err.message); }); };
'use strict'; var MP = require('mercadopago'); module.exports = function(app) { app.mp = new MP(process.env.MP_ID, process.env.MP_SECRET); if(process.env.MP_SANDBOX) { app.mp.sandboxMode(true); } var at = app.mp.getAccessToken() .then(function(accessToken) { app.mp.accessToken = accessToken; console.log('Successfully injected MercadoPago credentials in app'); }, function(err) { console.log('Unhandled MP error: ' + err.message); }); app.use('/sandbox', function(req, res) { var preference = { "items": [ { "title": "Test", "quantity": 1, "currency_id": "USD", "unit_price": 10.5 } ] }; // Sandbox preference point app.mp.createPreference(preference).then(function(data) { if(data.status === 201) { res.redirect(data.response.sandbox_init_point); } }, function(err) { throw new err; }); }); };
Add sandbox route for payment testing
Add sandbox route for payment testing
JavaScript
mit
rtroncoso/node-payments,rtroncoso/node-payments
--- +++ @@ -15,4 +15,26 @@ }, function(err) { console.log('Unhandled MP error: ' + err.message); }); + + app.use('/sandbox', function(req, res) { + var preference = { + "items": [ + { + "title": "Test", + "quantity": 1, + "currency_id": "USD", + "unit_price": 10.5 + } + ] + }; + + // Sandbox preference point + app.mp.createPreference(preference).then(function(data) { + if(data.status === 201) { + res.redirect(data.response.sandbox_init_point); + } + }, function(err) { + throw new err; + }); + }); };
a5a03944ab4454aa3fac8acdf8d10e2a0ad2db3e
src/modules/Datasets/components/LinksSection/LinksSection.js
src/modules/Datasets/components/LinksSection/LinksSection.js
import React from 'react' import { linkList } from './LinksSection.css' const LinksSection = ({links, style}) => { return ( <div> <h3>Liens</h3> {links.length ? ( <ul className={linkList}> {links.map( (link, idx) => <li key={idx}><a style={style} href={link.href}>{link.name}</a></li>)} </ul> ) : <div>Aucun lien disponible</div> } </div> ) } export default LinksSection
import React from 'react' import { linkList } from './LinksSection.css' const LinksSection = ({links, style}) => { // Some links have no name, use href as fallback const getName = (link) => link.name ? link.name : link.href; return ( <div> <h3>Liens</h3> {links.length ? ( <ul className={linkList}> {links.map( (link, idx) => <li key={idx}><a style={style} href={link.href}>{getName(link)}</a></li>)} </ul> ) : <div>Aucun lien disponible</div> } </div> ) } export default LinksSection
Use href if there is no name
Use href if there is no name
JavaScript
mit
sgmap/inspire,sgmap/inspire
--- +++ @@ -2,12 +2,15 @@ import { linkList } from './LinksSection.css' const LinksSection = ({links, style}) => { + // Some links have no name, use href as fallback + const getName = (link) => link.name ? link.name : link.href; + return ( <div> <h3>Liens</h3> {links.length ? ( <ul className={linkList}> - {links.map( (link, idx) => <li key={idx}><a style={style} href={link.href}>{link.name}</a></li>)} + {links.map( (link, idx) => <li key={idx}><a style={style} href={link.href}>{getName(link)}</a></li>)} </ul> ) : <div>Aucun lien disponible</div> }
7c023921755c3781dffecea0fcb886580271d5be
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 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 // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require turbolinks //= 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 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 // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require turbolinks //= require jquery-star-rating //= require_tree . $(document).ready(function(){ $('#search').keyup(function(event){ $('#toolSearch').submit(); }); });
Add toolSearch keyup textacular functionality to app.js. Require jquery star rating to app.js
Add toolSearch keyup textacular functionality to app.js. Require jquery star rating to app.js
JavaScript
mit
epicoding/epicoding,epicoding/epicoding,dunphyben/epicoding,dunphyben/epicoding
--- +++ @@ -13,4 +13,11 @@ //= require jquery //= require jquery_ujs //= require turbolinks +//= require jquery-star-rating //= require_tree . + +$(document).ready(function(){ + $('#search').keyup(function(event){ + $('#toolSearch').submit(); + }); +});
c659dbeda8895bcf852b4870b34d5bee444e5e40
app/assets/javascripts/application.js
app/assets/javascripts/application.js
// This is a manifest file that'll be compiled into including all the files listed below. // Add new JavaScript/Coffee code in separate files in this directory and they'll automatically // be included in the compiled file accessible from http://example.com/assets/application.js // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // //= require jquery_ujs //= require jquery.ui.all //= require vendor/jquery/magna-charta.min //= require vendor/sorttable //= require vendor/object-create-polyfill // //= require shared_mustache //= require templates // //= require govuk //= require_tree ./common //= require_tree ./application // //= require govuk_publishing_components/components/feedback
// This is a manifest file that'll be compiled into including all the files listed below. // Add new JavaScript/Coffee code in separate files in this directory and they'll automatically // be included in the compiled file accessible from http://example.com/assets/application.js // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // //= require jquery_ujs //= require jquery.ui.all //= require vendor/jquery/magna-charta.min //= require vendor/sorttable //= require vendor/object-create-polyfill // //= require shared_mustache //= require templates // //= require govuk //= require_tree ./common //= require_tree ./application // //= require govuk_publishing_components/all_components
Add all JavaScript dependencies from govuk_publishing_components
Add all JavaScript dependencies from govuk_publishing_components
JavaScript
mit
alphagov/whitehall,alphagov/whitehall,alphagov/whitehall,alphagov/whitehall
--- +++ @@ -17,4 +17,4 @@ //= require_tree ./common //= require_tree ./application // -//= require govuk_publishing_components/components/feedback +//= require govuk_publishing_components/all_components
02e3bbf6941d7f39755c7ed9780074d6ec30fda1
app/assets/javascripts/outpost/outpost.js
app/assets/javascripts/outpost/outpost.js
//= require jquery //= require underscore //= require backbone //= require moment //= require jquery_ujs //= require spin //= require jquery-ui-1.10.0.custom.min //= require date.min //= require select2 //= require bootstrap-transition //= require bootstrap-dropdown //= require bootstrap-modal //= require bootstrap-tab //= require bootstrap-scrollspy //= require bootstrap-alert //= require bootstrap-affix //= require bootstrap-tooltip //= require bootstrap-datepicker //= require ckeditor-jquery //= require ckeditor/plugins/mediaembed/plugin //= require ckeditor/plugins/codemirror/plugin //= require outpost/base //= require outpost/templates //= require outpost/notification //= require outpost/field_manager //= require outpost/date_time_input //= require outpost/auto_slug_field //= require outpost/field_counter //= require outpost/index_manager //= require outpost/global_plugins
//= require jquery //= require underscore //= require backbone //= require moment //= require jquery_ujs //= require spin //= require jquery-ui-1.10.0.custom.min //= require date.min //= require select2 //= require bootstrap-transition //= require bootstrap-dropdown //= require bootstrap-modal //= require bootstrap-tab //= require bootstrap-scrollspy //= require bootstrap-alert //= require bootstrap-affix //= require bootstrap-tooltip //= require bootstrap-datepicker //= require ckeditor-jquery //= require ckeditor/plugins/mediaembed/plugin //= require ckeditor/plugins/codemirror/plugin //= require outpost/base //= require outpost/templates //= require outpost/notification //= require outpost/field_manager //= require outpost/date_time_input //= require outpost/auto_slug_field //= require outpost/field_counter //= require outpost/preview //= require outpost/index_manager //= require outpost/global_plugins
Add preview to default JS
Add preview to default JS
JavaScript
mit
SCPR/outpost,Ravenstine/outpost,SCPR/outpost,SCPR/outpost,bricker/outpost,Ravenstine/outpost,Ravenstine/outpost,bricker/outpost
--- +++ @@ -31,5 +31,6 @@ //= require outpost/date_time_input //= require outpost/auto_slug_field //= require outpost/field_counter +//= require outpost/preview //= require outpost/index_manager //= require outpost/global_plugins
49d5a5e1cceea7e7e76a8d2968cc1922cbdc1b84
client/network/server-url.js
client/network/server-url.js
const baseUrl = process.env.SB_SERVER ? process.env.SB_SERVER : process.webpackEnv.SB_SERVER // Returns an absolute server URL for a path, if necessary (if running in Electron). If it's not // necessary (in the browser), the path will be returned unmodified export function makeServerUrl(path) { if (!IS_ELECTRON) { return path } const slashedPath = (path.length === 0 || path.startsWith('/') ? '' : '/') + path return baseUrl + slashedPath }
const baseUrl = process?.env?.SB_SERVER ? process.env.SB_SERVER : process.webpackEnv.SB_SERVER // Returns an absolute server URL for a path, if necessary (if running in Electron). If it's not // necessary (in the browser), the path will be returned unmodified export function makeServerUrl(path) { if (!IS_ELECTRON) { return path } const slashedPath = (path.length === 0 || path.startsWith('/') ? '' : '/') + path return baseUrl + slashedPath }
Use process.env more safely with Webpack 5.
Use process.env more safely with Webpack 5.
JavaScript
mit
ShieldBattery/ShieldBattery,ShieldBattery/ShieldBattery,ShieldBattery/ShieldBattery,ShieldBattery/ShieldBattery,ShieldBattery/ShieldBattery
--- +++ @@ -1,4 +1,4 @@ -const baseUrl = process.env.SB_SERVER ? process.env.SB_SERVER : process.webpackEnv.SB_SERVER +const baseUrl = process?.env?.SB_SERVER ? process.env.SB_SERVER : process.webpackEnv.SB_SERVER // Returns an absolute server URL for a path, if necessary (if running in Electron). If it's not // necessary (in the browser), the path will be returned unmodified
8ae19d5a47aecdfed43a6cb90f4c2a00f81ff401
app/assets/javascripts/filter/cite.js
app/assets/javascripts/filter/cite.js
module.filter('cite', [ 'pageService', function (page) { return function (volume) { if (!angular.isObject(volume) || angular.isUndefined(volume.access) || angular.isUndefined(volume.name) || angular.isUndefined(volume.id)) { return ''; } var names = []; angular.forEach(volume.access, function (access) { if (angular.isUndefined(access.access) || access.access < page.permission.ADMIN) { return; } var parts = access.party.name.split(' '), name = parts.pop(); if (parts.length > 0) { name += ', ' + parts.map(function (n) { return n.charAt(0); }).join('. ') + '.'; } names.push(name); }); names = names.join(', '); // var created = page.$filter('date')(new Date(volume.creation), 'yyyy'); var retrieved = page.$filter('date')(new Date(), 'longDate'); // return page.$filter('escape')(names) + ', ' + created + '. ' + page.$filter('escape')(volume.name) + '. <em>Databrary</em>. Retrieved ' + retrieved + ' from <a href="http://databrary.org/volume/' + volume.id + '" title="' + page.$filter('escape')(volume.name) + '">http://databrary.org/volume/' + volume.id + '</a>.'; }; } ]);
module.filter('cite', [ 'pageService', function (page) { return function (volume) { if (!angular.isObject(volume) || angular.isUndefined(volume.access) || angular.isUndefined(volume.name) || angular.isUndefined(volume.id)) { return ''; } var names = []; angular.forEach(volume.access, function (access) { if (angular.isUndefined(access.individual) || access.individual < page.permission.ADMIN) { return; } var parts = access.party.name.split(' '), name = parts.pop(); if (parts.length > 0) { name += ', ' + parts.map(function (n) { return n.charAt(0); }).join('. ') + '.'; } names.push(name); }); names = names.join(', '); // var created = page.$filter('date')(new Date(volume.creation), 'yyyy'); var retrieved = page.$filter('date')(new Date(), 'longDate'); // return page.$filter('escape')(names) + ', ' + created + '. ' + page.$filter('escape')(volume.name) + '. <em>Databrary</em>. Retrieved ' + retrieved + ' from <a href="http://databrary.org/volume/' + volume.id + '" title="' + page.$filter('escape')(volume.name) + '">http://databrary.org/volume/' + volume.id + '</a>.'; }; } ]);
Fix authors in databrary citation
Fix authors in databrary citation
JavaScript
agpl-3.0
databrary/databrary,databrary/databrary,databrary/databrary,databrary/databrary
--- +++ @@ -8,7 +8,7 @@ var names = []; angular.forEach(volume.access, function (access) { - if (angular.isUndefined(access.access) || access.access < page.permission.ADMIN) { + if (angular.isUndefined(access.individual) || access.individual < page.permission.ADMIN) { return; }
2cdf5a49e4f9716c8f2ced2d6a2d01a53392cb0d
app/routes/meetings/MeetingCreateRoute.js
app/routes/meetings/MeetingCreateRoute.js
// @flow import { compose } from 'redux'; import { connect } from 'react-redux'; import { push } from 'connected-react-router'; import MeetingEditor from './components/MeetingEditor'; import { createMeeting, inviteUsersAndGroups, } from 'app/actions/MeetingActions'; import moment from 'moment-timezone'; import { LoginPage } from 'app/components/LoginForm'; import replaceUnlessLoggedIn from 'app/utils/replaceUnlessLoggedIn'; import { EDITOR_EMPTY } from 'app/utils/constants'; const time = (hours, minutes) => moment().startOf('day').add({ hours, minutes }).toISOString(); const mapStateToProps = (state, props) => { return { user: props.currentUser, initialValues: { startTime: time(17, 15), endTime: time(20), report: EDITOR_EMPTY, useMazemap: true, }, }; }; const mapDispatchToProps = { handleSubmitCallback: createMeeting, inviteUsersAndGroups, push, }; export default compose( replaceUnlessLoggedIn(LoginPage), connect(mapStateToProps, mapDispatchToProps) )(MeetingEditor);
// @flow import { compose } from 'redux'; import { connect } from 'react-redux'; import { push } from 'connected-react-router'; import MeetingEditor from './components/MeetingEditor'; import { createMeeting, inviteUsersAndGroups, } from 'app/actions/MeetingActions'; import moment from 'moment-timezone'; import { LoginPage } from 'app/components/LoginForm'; import replaceUnlessLoggedIn from 'app/utils/replaceUnlessLoggedIn'; import { EDITOR_EMPTY } from 'app/utils/constants'; import config from 'app/config'; const time = (hours, minutes) => moment() .tz(config.timezone) .startOf('day') .add({ hours, minutes }) .toISOString(); const mapStateToProps = (state, props) => { return { user: props.currentUser, initialValues: { startTime: time(17, 15), endTime: time(20), report: EDITOR_EMPTY, useMazemap: true, }, }; }; const mapDispatchToProps = { handleSubmitCallback: createMeeting, inviteUsersAndGroups, push, }; export default compose( replaceUnlessLoggedIn(LoginPage), connect(mapStateToProps, mapDispatchToProps) )(MeetingEditor);
Use correct timezone for meeting initial values
Use correct timezone for meeting initial values
JavaScript
mit
webkom/lego-webapp,webkom/lego-webapp,webkom/lego-webapp
--- +++ @@ -11,9 +11,14 @@ import { LoginPage } from 'app/components/LoginForm'; import replaceUnlessLoggedIn from 'app/utils/replaceUnlessLoggedIn'; import { EDITOR_EMPTY } from 'app/utils/constants'; +import config from 'app/config'; const time = (hours, minutes) => - moment().startOf('day').add({ hours, minutes }).toISOString(); + moment() + .tz(config.timezone) + .startOf('day') + .add({ hours, minutes }) + .toISOString(); const mapStateToProps = (state, props) => { return {
30d78335dd4c62cb8841e790a570330c65d7a9ec
MAB.DotIgnore/gulpfile.js
MAB.DotIgnore/gulpfile.js
/// <binding AfterBuild='nuget-pack' /> "use strict"; var gulp = require('gulp'), path = require('path'), exec = require('child_process').exec, fs = require('fs'); var solutionFolder = path.resolve(__dirname, '..'); var projectFolder = path.join(solutionFolder, 'MAB.DotIgnore'); var distFolder = path.join(solutionFolder, 'dist'); if (!fs.existsSync(distFolder)) { fs.mkdirSync(distFolder); } gulp.task('nuget-pack', function (callback) { exec('nuget pack MAB.DotIgnore.csproj -Symbols -OutputDirectory ' + distFolder + ' -Prop Configuration=Release', { cwd: projectFolder }, function (err, stdout, stderr) { console.log(stdout); console.log(stderr); callback(err); }); });
/// <binding AfterBuild='nuget-pack' /> "use strict"; var gulp = require('gulp'), path = require('path'), exec = require('child_process').exec, fs = require('fs'); var solutionFolder = path.resolve(__dirname, '..'); var projectFolder = path.join(solutionFolder, 'MAB.DotIgnore'); var distFolder = path.join(solutionFolder, 'dist'); if (!fs.existsSync(distFolder)) { fs.mkdirSync(distFolder); } gulp.task('nuget-clean', function (callback) { exec('del *.nupkg', { cwd: distFolder }, function (err, stdout, stderr) { console.log(stdout); console.log(stderr); callback(err); }); }); gulp.task('nuget-pack', ['nuget-clean'], function (callback) { exec('nuget pack MAB.DotIgnore.csproj -Symbols -OutputDirectory ' + distFolder + ' -Prop Configuration=Release', { cwd: projectFolder }, function (err, stdout, stderr) { console.log(stdout); console.log(stderr); callback(err); }); });
Add clean task to gulp config
Add clean task to gulp config
JavaScript
mit
markashleybell/MAB.DotIgnore,markashleybell/MAB.DotIgnore
--- +++ @@ -14,7 +14,17 @@ fs.mkdirSync(distFolder); } -gulp.task('nuget-pack', function (callback) { + +gulp.task('nuget-clean', function (callback) { + exec('del *.nupkg', { cwd: distFolder }, function (err, stdout, stderr) { + console.log(stdout); + console.log(stderr); + callback(err); + }); +}); + + +gulp.task('nuget-pack', ['nuget-clean'], function (callback) { exec('nuget pack MAB.DotIgnore.csproj -Symbols -OutputDirectory ' + distFolder + ' -Prop Configuration=Release', { cwd: projectFolder }, function (err, stdout, stderr) { console.log(stdout); console.log(stderr);
c1115f64d64726a1d3e0e96d24166c53b2425a85
js/data_structures.js
js/data_structures.js
var colors = ["red", "blue", "magenta", "yellow"] var names = ["Dan", "Dave", "Eleanor", "Rupert"] colors.push("green") names.push("Nathaniel") happyHorses = {} for (i = 0; i < names.length; i++) { happyHorses[names[i]] = colors[i] } console.log(happyHorses)
var colors = ["red", "blue", "magenta", "yellow"] var names = ["Dan", "Dave", "Eleanor", "Rupert"] colors.push("green") names.push("Nathaniel") happyHorses = {} for (i = 0; i < names.length; i++) { happyHorses[names[i]] = colors[i] } console.log(happyHorses) // ———————————————————————————————————————————————————————— function Car(color, manual, make) { console.log("Our new car:", this); this.color = color; this.manual = manual; this.make = make; this.drive = function() {console.log(this.color + " " + this.make + " went vroom!");}; console.log("Have fun driving your new car :)") } var firstCar = new Car("black", true, "Honda"); var secondCar = new Car("green", false, "Toyota") var thirdCar = new Car("silver", false, "Lexus") console.log(Car) firstCar.drive(); thirdCar.drive();
Add constructor function for Cars
Add constructor function for Cars
JavaScript
mit
elliedori/phase-0-tracks,elliedori/phase-0-tracks,elliedori/phase-0-tracks
--- +++ @@ -11,3 +11,47 @@ } console.log(happyHorses) + +// ———————————————————————————————————————————————————————— + +function Car(color, manual, make) { + console.log("Our new car:", this); + + this.color = color; + this.manual = manual; + this.make = make; + + this.drive = function() {console.log(this.color + " " + this.make + " went vroom!");}; + + console.log("Have fun driving your new car :)") +} + +var firstCar = new Car("black", true, "Honda"); +var secondCar = new Car("green", false, "Toyota") +var thirdCar = new Car("silver", false, "Lexus") + +console.log(Car) +firstCar.drive(); +thirdCar.drive(); + + + + + + + + + + + + + + + + + + + + + +
a0cd69cf0181b0afffa0c7414c7515a81852baca
js/hal/http/client.js
js/hal/http/client.js
HAL.Http.Client = function(opts) { this.vent = opts.vent; $.ajaxSetup({ headers: { 'Accept': 'application/hal+json, application/json, */*; q=0.01' } }); }; HAL.Http.Client.prototype.get = function(url) { var self = this; this.vent.trigger('location-change', { url: url }); var jqxhr = $.ajax({ url: url, dataType: 'json', success: function(resource, textStatus, jqXHR) { self.vent.trigger('response', { resource: resource, jqxhr: jqXHR, headers: jqXHR.getAllResponseHeaders() }); } }).error(function() { self.vent.trigger('fail-response', { jqxhr: jqxhr }); }); }; HAL.Http.Client.prototype.request = function(opts) { var self = this; opts.dataType = 'json'; self.vent.trigger('location-change', { url: opts.url }); return jqxhr = $.ajax(opts); }; HAL.Http.Client.prototype.updateDefaultHeaders = function(headers) { this.defaultHeaders = headers; $.ajaxSetup({ headers: headers }); }; HAL.Http.Client.prototype.getDefaultHeaders = function() { return this.defaultHeaders; };
HAL.Http.Client = function(opts) { this.vent = opts.vent; this.defaultHeaders = { 'Accept': 'application/hal+json, application/json, */*; q=0.01' }; }; HAL.Http.Client.prototype.get = function(url) { var self = this; this.vent.trigger('location-change', { url: url }); var jqxhr = $.ajax({ url: url, dataType: 'json', headers: this.defaultHeaders, success: function(resource, textStatus, jqXHR) { self.vent.trigger('response', { resource: resource, jqxhr: jqXHR, headers: jqXHR.getAllResponseHeaders() }); } }).error(function() { self.vent.trigger('fail-response', { jqxhr: jqxhr }); }); }; HAL.Http.Client.prototype.request = function(opts) { var self = this; opts.dataType = 'json'; self.vent.trigger('location-change', { url: opts.url }); return jqxhr = $.ajax(opts); }; HAL.Http.Client.prototype.updateDefaultHeaders = function(headers) { this.defaultHeaders = headers; }; HAL.Http.Client.prototype.getDefaultHeaders = function() { return this.defaultHeaders; };
Fix for $.ajaxSetup not working in Chrome. Usage is not recommended. This caused changes to custom request headers to be ignored. Calling ajaxSetup wasn't updating the headers used by the next AJAX call.
Fix for $.ajaxSetup not working in Chrome. Usage is not recommended. This caused changes to custom request headers to be ignored. Calling ajaxSetup wasn't updating the headers used by the next AJAX call.
JavaScript
mit
gregturn/hal-browser,Mediahead-AG/node-hal-browser,flamilton/hal-browser,mikekelly/hal-browser,mikekelly/hal-browser,jlegrone/express-hal-browser,MGDIS/hal-browser,MGDIS/hal-browser,ziodave/hal-browser,ziodave/hal-browser,gregturn/hal-browser,flamilton/hal-browser,jlegrone/express-hal-browser
--- +++ @@ -1,6 +1,6 @@ HAL.Http.Client = function(opts) { this.vent = opts.vent; - $.ajaxSetup({ headers: { 'Accept': 'application/hal+json, application/json, */*; q=0.01' } }); + this.defaultHeaders = { 'Accept': 'application/hal+json, application/json, */*; q=0.01' }; }; HAL.Http.Client.prototype.get = function(url) { @@ -9,6 +9,7 @@ var jqxhr = $.ajax({ url: url, dataType: 'json', + headers: this.defaultHeaders, success: function(resource, textStatus, jqXHR) { self.vent.trigger('response', { resource: resource, @@ -30,7 +31,6 @@ HAL.Http.Client.prototype.updateDefaultHeaders = function(headers) { this.defaultHeaders = headers; - $.ajaxSetup({ headers: headers }); }; HAL.Http.Client.prototype.getDefaultHeaders = function() {
f2ac151d17454b20345bb42adc31143089d089d5
js/src/layers/Path.js
js/src/layers/Path.js
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. const vectorlayer = require('./VectorLayer.js'); export class LeafletPathModel extends vectorlayer.LeafletVectorLayerModel { defaults() { return { ...super.defaults(), _view_name: 'LeafletPathView', _model_name: 'LeafletPathModel', stroke: true, color: '#0033FF', weight: 5, fill: true, fill_color: null, fill_opacity: 0.2, dash_array: null, line_cap: 'round', line_join: 'round', pointer_events: '', class_name: '' }; } } export class LeafletPathView extends vectorlayer.LeafletVectorLayerView { model_events() { super.model_events(); this.obj.setStyle(this.get_options()); } }
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. const vectorlayer = require('./VectorLayer.js'); export class LeafletPathModel extends vectorlayer.LeafletVectorLayerModel { defaults() { return { ...super.defaults(), _view_name: 'LeafletPathView', _model_name: 'LeafletPathModel', stroke: true, color: '#0033FF', weight: 5, fill: true, fill_color: null, fill_opacity: 0.2, dash_array: null, line_cap: 'round', line_join: 'round', pointer_events: '', class_name: '' }; } } export class LeafletPathView extends vectorlayer.LeafletVectorLayerView { model_events() { super.model_events(); var key; var o = this.model.get('options'); for (var i = 0; i < o.length; i++) { key = o[i]; this.listenTo( this.model, 'change:' + key, function() { this.obj.setStyle(this.get_options()); }, this ); } this.obj.setStyle(this.get_options()); } }
Add back call to setStyle on options
Add back call to setStyle on options
JavaScript
mit
ellisonbg/leafletwidget,ellisonbg/leafletwidget
--- +++ @@ -27,6 +27,19 @@ export class LeafletPathView extends vectorlayer.LeafletVectorLayerView { model_events() { super.model_events(); + var key; + var o = this.model.get('options'); + for (var i = 0; i < o.length; i++) { + key = o[i]; + this.listenTo( + this.model, + 'change:' + key, + function() { + this.obj.setStyle(this.get_options()); + }, + this + ); + } this.obj.setStyle(this.get_options()); } }
dbff1b629627610e45ed00d9f7bc9728ba6205e4
app/assets/javascripts/git_import.js
app/assets/javascripts/git_import.js
/* global miqSparkleOn miqSparkleOff showErrorMessage clearMessages */ var GitImport = { retrieveDatastoreClickHandler: function() { $('.git-retrieve-datastore').click(function(event) { event.preventDefault(); miqSparkleOn(); clearMessages(); $.post('retrieve_git_datastore', $('#retrieve-git-datastore-form').serialize(), function(data) { var parsedData = JSON.parse(data); var messages = parsedData.message; if (messages && messages.level === "error") { showErrorMessage(messages.message); miqSparkleOff(); } else { GitImport.pollForGitTaskCompletion(parsedData); } }); }); }, pollForGitTaskCompletion: function(gitData) { $.get('check_git_task', gitData, function(data) { var parsedData = JSON.parse(data); if (parsedData.state) { setTimeout(GitImport.pollForGitTaskCompletion, 1500, gitData); } else { GitImport.gitTaskCompleted(parsedData); } }); }, gitTaskCompleted: function(data) { if (data.success) { var postMessageData = { git_repo_id: data.git_repo_id, git_branches: data.git_branches, git_tags: data.git_tags, message: data.message }; parent.postMessage(postMessageData, '*'); } else { parent.postMessage({message: data.message}, '*'); } }, };
/* global miqSparkleOn miqSparkleOff showErrorMessage clearMessages */ var GitImport = { TASK_POLL_TIMEOUT: 1500, retrieveDatastoreClickHandler: function() { $('.git-retrieve-datastore').click(function(event) { event.preventDefault(); miqSparkleOn(); clearMessages(); $.post('retrieve_git_datastore', $('#retrieve-git-datastore-form').serialize(), function(data) { var parsedData = JSON.parse(data); var messages = parsedData.message; if (messages && messages.level === 'error') { showErrorMessage(messages.message); miqSparkleOff(); } else { GitImport.pollForGitTaskCompletion(parsedData); } }); }); }, pollForGitTaskCompletion: function(gitData) { $.get('check_git_task', gitData, function(data) { var parsedData = JSON.parse(data); if (parsedData.state) { setTimeout(GitImport.pollForGitTaskCompletion, GitImport.TASK_POLL_TIMEOUT, gitData); } else { GitImport.gitTaskCompleted(parsedData); } }); }, gitTaskCompleted: function(data) { if (data.success) { var postMessageData = { git_repo_id: data.git_repo_id, git_branches: data.git_branches, git_tags: data.git_tags, message: data.message }; parent.postMessage(postMessageData, '*'); } else { parent.postMessage({message: data.message}, '*'); } }, };
Add constant for the poll timeout value and fix quotes
Add constant for the poll timeout value and fix quotes https://bugzilla.redhat.com/show_bug.cgi?id=1393982
JavaScript
apache-2.0
hstastna/manageiq,gmcculloug/manageiq,mresti/manageiq,jvlcek/manageiq,israel-hdez/manageiq,mzazrivec/manageiq,d-m-u/manageiq,NickLaMuro/manageiq,aufi/manageiq,fbladilo/manageiq,djberg96/manageiq,ilackarms/manageiq,ilackarms/manageiq,jrafanie/manageiq,NaNi-Z/manageiq,djberg96/manageiq,NaNi-Z/manageiq,mfeifer/manageiq,gerikis/manageiq,tzumainn/manageiq,mresti/manageiq,jameswnl/manageiq,pkomanek/manageiq,jameswnl/manageiq,agrare/manageiq,gerikis/manageiq,syncrou/manageiq,ailisp/manageiq,jntullo/manageiq,syncrou/manageiq,mkanoor/manageiq,jntullo/manageiq,ilackarms/manageiq,josejulio/manageiq,pkomanek/manageiq,gmcculloug/manageiq,branic/manageiq,andyvesel/manageiq,mkanoor/manageiq,jntullo/manageiq,tinaafitz/manageiq,NaNi-Z/manageiq,lpichler/manageiq,yaacov/manageiq,jvlcek/manageiq,aufi/manageiq,josejulio/manageiq,romanblanco/manageiq,skateman/manageiq,branic/manageiq,kbrock/manageiq,skateman/manageiq,matobet/manageiq,d-m-u/manageiq,tinaafitz/manageiq,fbladilo/manageiq,branic/manageiq,juliancheal/manageiq,billfitzgerald0120/manageiq,hstastna/manageiq,juliancheal/manageiq,ManageIQ/manageiq,chessbyte/manageiq,billfitzgerald0120/manageiq,durandom/manageiq,romanblanco/manageiq,durandom/manageiq,mzazrivec/manageiq,mresti/manageiq,lpichler/manageiq,billfitzgerald0120/manageiq,pkomanek/manageiq,chessbyte/manageiq,andyvesel/manageiq,juliancheal/manageiq,jvlcek/manageiq,kbrock/manageiq,djberg96/manageiq,mkanoor/manageiq,NickLaMuro/manageiq,israel-hdez/manageiq,borod108/manageiq,gmcculloug/manageiq,mkanoor/manageiq,NickLaMuro/manageiq,matobet/manageiq,branic/manageiq,agrare/manageiq,tzumainn/manageiq,chessbyte/manageiq,aufi/manageiq,yaacov/manageiq,d-m-u/manageiq,tzumainn/manageiq,mfeifer/manageiq,fbladilo/manageiq,aufi/manageiq,ManageIQ/manageiq,lpichler/manageiq,matobet/manageiq,d-m-u/manageiq,durandom/manageiq,jameswnl/manageiq,israel-hdez/manageiq,hstastna/manageiq,tinaafitz/manageiq,durandom/manageiq,jrafanie/manageiq,fbladilo/manageiq,gerikis/manageiq,tzumainn/manageiq,gmcculloug/manageiq,andyvesel/manageiq,mfeifer/manageiq,kbrock/manageiq,ailisp/manageiq,hstastna/manageiq,borod108/manageiq,tinaafitz/manageiq,pkomanek/manageiq,skateman/manageiq,yaacov/manageiq,mfeifer/manageiq,billfitzgerald0120/manageiq,borod108/manageiq,jrafanie/manageiq,chessbyte/manageiq,romanblanco/manageiq,israel-hdez/manageiq,juliancheal/manageiq,skateman/manageiq,syncrou/manageiq,mresti/manageiq,ilackarms/manageiq,josejulio/manageiq,mzazrivec/manageiq,jntullo/manageiq,kbrock/manageiq,syncrou/manageiq,jameswnl/manageiq,djberg96/manageiq,lpichler/manageiq,ManageIQ/manageiq,yaacov/manageiq,NickLaMuro/manageiq,jrafanie/manageiq,NaNi-Z/manageiq,agrare/manageiq,jvlcek/manageiq,gerikis/manageiq,mzazrivec/manageiq,romanblanco/manageiq,josejulio/manageiq,matobet/manageiq,andyvesel/manageiq,ailisp/manageiq,agrare/manageiq,ManageIQ/manageiq,borod108/manageiq,ailisp/manageiq
--- +++ @@ -1,6 +1,8 @@ /* global miqSparkleOn miqSparkleOff showErrorMessage clearMessages */ var GitImport = { + TASK_POLL_TIMEOUT: 1500, + retrieveDatastoreClickHandler: function() { $('.git-retrieve-datastore').click(function(event) { event.preventDefault(); @@ -10,7 +12,7 @@ $.post('retrieve_git_datastore', $('#retrieve-git-datastore-form').serialize(), function(data) { var parsedData = JSON.parse(data); var messages = parsedData.message; - if (messages && messages.level === "error") { + if (messages && messages.level === 'error') { showErrorMessage(messages.message); miqSparkleOff(); } else { @@ -24,7 +26,7 @@ $.get('check_git_task', gitData, function(data) { var parsedData = JSON.parse(data); if (parsedData.state) { - setTimeout(GitImport.pollForGitTaskCompletion, 1500, gitData); + setTimeout(GitImport.pollForGitTaskCompletion, GitImport.TASK_POLL_TIMEOUT, gitData); } else { GitImport.gitTaskCompleted(parsedData); }
45db233a6873720d33027c2a9ce5e78260ce50bb
src/lib/server/getHead.js
src/lib/server/getHead.js
/*eslint-disable react/no-danger*/ import React from "react"; import serialize from "serialize-javascript"; import path from "path"; import process from "process"; // Make sure path ends in forward slash let assetPath = require(path.resolve(path.join(process.cwd(), "src", "config", "application"))).default.assetPath; if (assetPath.substr(-1) !== "/") { assetPath = assetPath + "/"; } const isProduction = process.env.NODE_ENV === "production"; export default (config, entryPoint, assets) => { const tags = []; let key = 0; if (isProduction) { tags.push(<link key={key++} rel="stylesheet" type="text/css" href={`${config.assetPath}/${entryPoint}.css`} />); } tags.push( <script key={key++} type="text/javascript" dangerouslySetInnerHTML={{__html: `window.__GS_PUBLIC_PATH__ = ${serialize(assetPath)}; window.__GS_ENVIRONMENT__ = ${serialize(process.env.NODE_ENV)}`}}></script> ); return tags; };
/*eslint-disable react/no-danger*/ import React from "react"; import serialize from "serialize-javascript"; import path from "path"; import process from "process"; // Make sure path ends in forward slash let assetPath = require(path.resolve(path.join(process.cwd(), "src", "config", "application"))).default.assetPath; if (assetPath.substr(-1) !== "/") { assetPath = assetPath + "/"; } const isProduction = process.env.NODE_ENV === "production"; // eslint-disable-next-line no-unused-vars export default (config, entryPoint, assets) => { const tags = []; let key = 0; if (isProduction) { tags.push(<link key={key++} rel="stylesheet" type="text/css" href={`${config.assetPath}/${entryPoint}.css`} />); } tags.push( <script key={key++} type="text/javascript" dangerouslySetInnerHTML={{__html: `window.__GS_PUBLIC_PATH__ = ${serialize(assetPath)}; window.__GS_ENVIRONMENT__ = ${serialize(process.env.NODE_ENV)}`}}></script> ); return tags; };
Disable lint for line with unused var
Disable lint for line with unused var
JavaScript
mit
TrueCar/gluestick,TrueCar/gluestick,TrueCar/gluestick
--- +++ @@ -12,6 +12,7 @@ const isProduction = process.env.NODE_ENV === "production"; +// eslint-disable-next-line no-unused-vars export default (config, entryPoint, assets) => { const tags = []; let key = 0;
31517b7b52a62ed1127b7139cbda1a4c48d07bd8
src/containers/Settings.js
src/containers/Settings.js
import React, { Component } from 'react'; import Layout from 'react-toolbox/lib/layout/Layout'; import Panel from 'react-toolbox/lib/layout/Panel'; import { Settings as BackgroundSettings } from '@modules/background'; class Settings extends Component { render() { return ( <Layout> <Panel> <div style={{ flex: 1, overflowY: 'auto', padding: '1.8rem' }}> <section> <BackgroundSettings /> </section> </div> </Panel> </Layout> ); } } export default Settings
import React, { Component } from 'react'; import Layout from 'react-toolbox/lib/layout/Layout'; import Panel from 'react-toolbox/lib/layout/Panel'; import { Settings as BackgroundSettings } from '@modules/background'; import { Settings as ClockSettings } from '@modules/clock'; class Settings extends Component { render() { return ( <Layout> <Panel> <div style={{ flex: 1, overflowY: 'auto', padding: '1.8rem' }}> <section> <BackgroundSettings /> </section> <section> <ClockSettings /> </section> </div> </Panel> </Layout> ); } } export default Settings
Add Clock settings to the list of settings
:zap: Add Clock settings to the list of settings
JavaScript
mit
emadalam/mesmerized,emadalam/mesmerized
--- +++ @@ -2,6 +2,7 @@ import Layout from 'react-toolbox/lib/layout/Layout'; import Panel from 'react-toolbox/lib/layout/Panel'; import { Settings as BackgroundSettings } from '@modules/background'; +import { Settings as ClockSettings } from '@modules/clock'; class Settings extends Component { render() { @@ -12,6 +13,9 @@ <section> <BackgroundSettings /> </section> + <section> + <ClockSettings /> + </section> </div> </Panel> </Layout>
0826e837e08b9f989269a3584d84fa02251cbf71
src/client.js
src/client.js
import React from "react"; import ReactDOM from "react-dom"; import {Router} from "react-router"; import Transmit from "react-transmit"; import routes from "views/routes"; /** * Fire-up React Router. */ const reactRoot = window.document.getElementById("react-root"); Transmit.render(Router, {routes}, reactRoot); /** * Detect whether the server-side render has been discarded due to an invalid checksum. */ if (process.env.NODE_ENV !== "production") { if (!reactRoot.firstChild || !reactRoot.firstChild.attributes || !reactRoot.firstChild.attributes["data-react-checksum"]) { console.error("Server-side React render was discarded. Make sure that your initial render does not contain any client-side code."); } }
import React from "react"; import ReactDOM from "react-dom"; import {Router} from "react-router"; import Transmit from "react-transmit"; import routes from "views/routes"; import createBrowserHistory from 'history/lib/createBrowserHistory'; /** * Fire-up React Router. */ const reactRoot = window.document.getElementById("react-root"); Transmit.render(Router, {routes, history:createBrowserHistory()}, reactRoot); /** * Detect whether the server-side render has been discarded due to an invalid checksum. */ if (process.env.NODE_ENV !== "production") { if (!reactRoot.firstChild || !reactRoot.firstChild.attributes || !reactRoot.firstChild.attributes["data-react-checksum"]) { console.error("Server-side React render was discarded. Make sure that your initial render does not contain any client-side code."); } }
Fix for missing browser history
Fix for missing browser history
JavaScript
bsd-3-clause
RickWong/react-isomorphic-starterkit,ryancbarry/react-isomorphic-starterkit,joezcool02/PuzzLR,fforres/coworks_old,AnthonyWhitaker/react-isomorphic-starterkit
--- +++ @@ -3,14 +3,13 @@ import {Router} from "react-router"; import Transmit from "react-transmit"; import routes from "views/routes"; - +import createBrowserHistory from 'history/lib/createBrowserHistory'; /** * Fire-up React Router. */ const reactRoot = window.document.getElementById("react-root"); - -Transmit.render(Router, {routes}, reactRoot); +Transmit.render(Router, {routes, history:createBrowserHistory()}, reactRoot); /** * Detect whether the server-side render has been discarded due to an invalid checksum.
0fc1c9217674f368abe4e1fdc2af65db89ca4236
koans/AboutExpects.js
koans/AboutExpects.js
describe("About Expects", function() { // We shall contemplate truth by testing reality, via spec expectations. it("should expect true", function() { expect(true).toBeTruthy(); // This should be true }); // To understand reality, we must compare our expectations against reality. it("should expect equality", function() { var expectedValue = 2; var actualValue = 1 + 1; expect(actualValue === expectedValue).toBeTruthy(); }); // Some ways of asserting equality are better than others. it("should assert equality a better way", function() { var expectedValue = 2; var actualValue = 1 + 1; // toEqual() compares using common sense equality. expect(actualValue).toEqual(expectedValue); }); // Sometimes you need to be precise about what you "type". it("should assert equality with ===", function() { var expectedValue = '2'; var actualValue = (1 + 1).toString(); // toBe() will always use === to compare. expect(actualValue).toBe(expectedValue); }); // Sometimes we will ask you to fill in the values. it("should have filled in values", function() { expect(1 + 1).toEqual(2); }); });
describe("About Expects", function() { // We shall contemplate truth by testing reality, via spec expectations. it("should expect true", function() { expect(false).toBeTruthy(); // This should be true }); // To understand reality, we must compare our expectations against reality. it("should expect equality", function() { var expectedValue = FILL_ME_IN; var actualValue = 1 + 1; expect(actualValue === expectedValue).toBeTruthy(); }); // Some ways of asserting equality are better than others. it("should assert equality a better way", function() { var expectedValue = FILL_ME_IN; var actualValue = 1 + 1; // toEqual() compares using common sense equality. expect(actualValue).toEqual(expectedValue); }); // Sometimes you need to be precise about what you "type". it("should assert equality with ===", function() { var expectedValue = FILL_ME_IN; var actualValue = (1 + 1).toString(); // toBe() will always use === to compare. expect(actualValue).toBe(expectedValue); }); // Sometimes we will ask you to fill in the values. it("should have filled in values", function() { expect(1 + 1).toEqual(FILL_ME_IN); }); });
Revert "Complete the Expects Koans"
Revert "Complete the Expects Koans" This reverts commit d41553a5d48d0d5f10e9f90e0cf4f84e1faf1a73.
JavaScript
mit
LesliePajuelo/javascript-koans,LesliePajuelo/javascript-koans,LesliePajuelo/javascript-koans
--- +++ @@ -2,12 +2,12 @@ // We shall contemplate truth by testing reality, via spec expectations. it("should expect true", function() { - expect(true).toBeTruthy(); // This should be true + expect(false).toBeTruthy(); // This should be true }); // To understand reality, we must compare our expectations against reality. it("should expect equality", function() { - var expectedValue = 2; + var expectedValue = FILL_ME_IN; var actualValue = 1 + 1; expect(actualValue === expectedValue).toBeTruthy(); @@ -15,7 +15,7 @@ // Some ways of asserting equality are better than others. it("should assert equality a better way", function() { - var expectedValue = 2; + var expectedValue = FILL_ME_IN; var actualValue = 1 + 1; // toEqual() compares using common sense equality. @@ -24,7 +24,7 @@ // Sometimes you need to be precise about what you "type". it("should assert equality with ===", function() { - var expectedValue = '2'; + var expectedValue = FILL_ME_IN; var actualValue = (1 + 1).toString(); // toBe() will always use === to compare. @@ -33,6 +33,6 @@ // Sometimes we will ask you to fill in the values. it("should have filled in values", function() { - expect(1 + 1).toEqual(2); + expect(1 + 1).toEqual(FILL_ME_IN); }); });
5e5c79a72d8dd5206c8d3c738f839e8af6f5d4cf
lib/background.js
lib/background.js
var path = require('path'); var nightwatch = require('nightwatch'); var originalArgv = JSON.parse(process.argv[2]); nightwatch.cli(function(argv) { for (var key in originalArgv) { if (key === 'env' && originalArgv[key].indexOf(',') > -1 && argv['parallel-mode'] === true) { continue; } argv[key] = originalArgv[key]; } if (argv.test) { argv.test = path.resolve(argv.test); } nightwatch.runner(argv); });
var path = require('path'); var nightwatch = require('nightwatch'); var originalArgv = JSON.parse(process.argv[2]); var log = require('fancy-log'); nightwatch.cli(function(argv) { for (var key in originalArgv) { if (key === 'env' && originalArgv[key].indexOf(',') > -1 && argv['parallel-mode'] === true) { continue; } argv[key] = originalArgv[key]; } if (argv.test) { argv.test = path.resolve(argv.test); } const runner = nightwatch.CliRunner(argv); runner.setup() .startWebDriver() .then(() => { return runner.runTests(); }) .then(() => { return runner.stopWebDriver(); }).catch(err => { log.error(err); }); });
Adjust to the new api of Nightwatch
Adjust to the new api of Nightwatch Updating Nightwatch from 0.9.x to 1.0.x changed Nightwatch API a little, so adjust gulp-nightwatch to the new api of Nightwatch.
JavaScript
mit
tatsuyafw/gulp-nightwatch,StoneCypher/gulp-nightwatch
--- +++ @@ -1,6 +1,7 @@ var path = require('path'); var nightwatch = require('nightwatch'); var originalArgv = JSON.parse(process.argv[2]); +var log = require('fancy-log'); nightwatch.cli(function(argv) { for (var key in originalArgv) { @@ -14,5 +15,15 @@ argv.test = path.resolve(argv.test); } - nightwatch.runner(argv); + const runner = nightwatch.CliRunner(argv); + runner.setup() + .startWebDriver() + .then(() => { + return runner.runTests(); + }) + .then(() => { + return runner.stopWebDriver(); + }).catch(err => { + log.error(err); + }); });
3714de66c50c14a063cfb8f61b3e3b45b7c1b9e6
src/modulator/compiled.js
src/modulator/compiled.js
compiler.modulator.compiled = def( [ ephox.bolt.module.modulator.compiled, compiler.tools.io ], function (delegate, io) { var create = function () { var instance = delegate.create.apply(null, arguments); var can = function () { return instance.can.apply(null, arguments); }; var get = function (id) { var spec = instance.get.apply(null, arguments); var url = spec.url; var serial = spec.serial; var render = function () { return io.read(url); }; var load = function (define) { // FIX sort out implicit definition behaviour. define(id, [], function () {}); }; return { serial: serial, url: url, load: load, render: render }; }; return { can: can, get: get }; }; return { create: create }; } );
compiler.modulator.compiled = def( [ ephox.bolt.kernel.modulator.compiled, compiler.tools.io ], function (delegate, io) { var create = function () { var instance = delegate.create.apply(null, arguments); var can = function () { return instance.can.apply(null, arguments); }; var get = function (id) { var spec = instance.get.apply(null, arguments); var url = spec.url; var serial = spec.serial; var render = function () { return io.read(url); }; var load = function (define) { // FIX sort out implicit definition behaviour. define(id, [], function () {}); }; return { serial: serial, url: url, load: load, render: render }; }; return { can: can, get: get }; }; return { create: create }; } );
Fix up reference to moved module.
Fix up reference to moved module.
JavaScript
bsd-3-clause
boltjs/bolt,boltjs/bolt,boltjs/bolt,boltjs/bolt
--- +++ @@ -1,6 +1,6 @@ compiler.modulator.compiled = def( [ - ephox.bolt.module.modulator.compiled, + ephox.bolt.kernel.modulator.compiled, compiler.tools.io ],
c3c34ad993ce0e480d8ef5f9a4750eebe5847920
frontend/app/scripts/app.js
frontend/app/scripts/app.js
'use strict'; angular.module('osscdnApp', ['ngAnimate', 'ui.router', 'ngDropdowns', 'semverSort', 'ngClipboard', 'angular-flash.service', 'angular-flash.flash-alert-directive']) .config(function($stateProvider, $urlRouterProvider, flashProvider, ngClipProvider) { $urlRouterProvider.otherwise('/'); $stateProvider.state('libraries', { url: '/:name', templateUrl: 'views/main.html', controller: 'MainCtrl' }); ngClipProvider.setPath('//oss.maxcdn.com/libs/zeroclipboard/1.3.1/ZeroClipboard.swf'); flashProvider.successClassnames.push('alert-success'); });
'use strict'; angular.module('osscdnApp', ['ngAnimate', 'ui.router', 'ngDropdowns', 'semverSort', 'ngClipboard', 'angular-flash.service', 'angular-flash.flash-alert-directive']) .config(function($stateProvider, $urlRouterProvider, flashProvider, ngClipProvider) { $urlRouterProvider.otherwise('/'); $stateProvider.state('libraries', { url: '/:name', templateUrl: 'views/main.html', controller: 'MainCtrl' }); ngClipProvider.setPath('//oss.maxcdn.com/zeroclipboard/1.3.3/ZeroClipboard.swf'); flashProvider.successClassnames.push('alert-success'); });
Update ZeroClipboard to the newest version available at CDN
Update ZeroClipboard to the newest version available at CDN @XhmikosR, No 1.3.4 yet. I guess next time we'll update to 2.x.
JavaScript
mit
MaxCDN/osscdn,Tionx/osscdn,Tionx/osscdn,MaxCDN/osscdn
--- +++ @@ -11,7 +11,7 @@ controller: 'MainCtrl' }); - ngClipProvider.setPath('//oss.maxcdn.com/libs/zeroclipboard/1.3.1/ZeroClipboard.swf'); + ngClipProvider.setPath('//oss.maxcdn.com/zeroclipboard/1.3.3/ZeroClipboard.swf'); flashProvider.successClassnames.push('alert-success'); });
0e90e4d1ef6ff07839a4a2d0a3547d45c19b1c43
templates/front/angular/js/front-app.js
templates/front/angular/js/front-app.js
var dataLoaderRunner = [ 'dataLoader', function (dataLoader) { return dataLoader(); } ]; angular.module('${appName}', ['ngRoute']) .config(function ($routeProvider, $locationProvider) { $routeProvider .when('/tweets', { templateUrl: '/html/tweets/getIndex.html', controller: 'tweetsController', resolve: { data: dataLoaderRunner } }) .otherwise({ redirectTo: '/tweets' }); $locationProvider.html5Mode(true); }) .service('dataLoader', function ($location, $http) { return function () { return $http.get( '/api' + $location.path() ).then(function (res) { return res.data; }); }; });
var dataLoaderRunner = [ 'dataLoader', function (dataLoader) { return dataLoader(); } ]; angular.module('${appName}', ['ngRoute']) .config(function ($routeProvider, $locationProvider) { $routeProvider .when('/tweets', { templateUrl: '/html/tweets/getIndex.html', controller: 'tweetsController', resolve: { data: dataLoaderRunner } }) .otherwise({ redirectTo: '/tweets' }); $locationProvider.html5Mode({ enabled: true, requireBase: false }); }) .service('dataLoader', function ($location, $http) { return function () { return $http.get( '/api' + $location.path() ).then(function (res) { return res.data; }); }; });
Declare html5mode in ng template properly
Declare html5mode in ng template properly
JavaScript
mit
JonAbrams/synth,leeric92/synth,leeric92/synth,JonAbrams/synth
--- +++ @@ -19,7 +19,10 @@ redirectTo: '/tweets' }); - $locationProvider.html5Mode(true); + $locationProvider.html5Mode({ + enabled: true, + requireBase: false + }); }) .service('dataLoader', function ($location, $http) { return function () {
8b5f0684bd7dfffc40630782cff50eba79391945
browserscripts/userTimings.js
browserscripts/userTimings.js
(function() { /** * Browsertime (http://www.browsertime.com) * Copyright (c) 2014, Peter Hedenskog, Tobias Lidskog * and other contributors * Released under the Apache 2.0 License */ // someway the get entries by type isn't working in IE using Selenium, // will spend time fixing this later, now just return empty if (navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > 0) { return { measures: [], marks: [] }; } else { return { measures: (window.performance && window.performance.getEntriesByType) ? window.performance.getEntriesByType( 'measure') : [], marks: (window.performance && window.performance.getEntriesByType) ? window.performance.getEntriesByType('mark') : [] }; } })();
(function() { /** * Browsertime (http://www.browsertime.com) * Copyright (c) 2014, Peter Hedenskog, Tobias Lidskog * and other contributors * Released under the Apache 2.0 License */ // someway the get entries by type isn't working in IE using Selenium, // will spend time fixing this later, now just return empty if (navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > 0) { return { measures: [], marks: [] }; } else { // FIXME marks exported from Firefox include "toJSON": "function toJSON() {\n [native code]\n}" return { measures: (window.performance && window.performance.getEntriesByType) ? window.performance.getEntriesByType( 'measure') : [], marks: (window.performance && window.performance.getEntriesByType) ? window.performance.getEntriesByType('mark') : [] }; } })();
Add fixme comment for user timings on Firefox.
Add fixme comment for user timings on Firefox.
JavaScript
apache-2.0
tobli/browsertime,sitespeedio/browsertime,sitespeedio/browsertime,sitespeedio/browsertime,sitespeedio/browsertime
--- +++ @@ -14,6 +14,7 @@ marks: [] }; } else { + // FIXME marks exported from Firefox include "toJSON": "function toJSON() {\n [native code]\n}" return { measures: (window.performance && window.performance.getEntriesByType) ? window.performance.getEntriesByType( 'measure') : [],
2782adc92f11af17e62eca0ee3f6df2f88a9f0c8
.eslintrc.js
.eslintrc.js
module.exports = { parser: "babel-eslint", env: { es6: true, node: true, }, extends: "eslint:recommended", parserOptions: { sourceType: "module", ecmaFeatures: { experimentalObjectRestSpread: true, }, }, globals: { atom: true, }, rules: { "comma-dangle": [0], "no-this-before-super": [2], "constructor-super": [2], indent: [2, 2], "linebreak-style": [2, "unix"], "no-var": [1], "prefer-const": [1], "no-const-assign": [2], "no-unused-vars": [2], semi: [2, "never"], "no-extra-semi": [0], }, }
module.exports = { parser: "babel-eslint", env: { es6: true, node: true, }, extends: "eslint:recommended", parserOptions: { sourceType: "module", ecmaFeatures: { experimentalObjectRestSpread: true, }, }, globals: { atom: true, }, rules: { "comma-dangle": [0], "no-this-before-super": [2], "constructor-super": [2], // prettier handles indentation, and they disagree on some of the code in // find-destination-spec.jw // indent: [2, 2], "linebreak-style": [2, "unix"], "no-var": [1], "prefer-const": [1], "no-const-assign": [2], "no-unused-vars": [2], semi: [2, "never"], "no-extra-semi": [0], }, }
Disable the indent rule in eslint
Disable the indent rule in eslint
JavaScript
mit
AsaAyers/js-hyperclick,AsaAyers/js-hyperclick
--- +++ @@ -18,7 +18,9 @@ "comma-dangle": [0], "no-this-before-super": [2], "constructor-super": [2], - indent: [2, 2], + // prettier handles indentation, and they disagree on some of the code in + // find-destination-spec.jw + // indent: [2, 2], "linebreak-style": [2, "unix"], "no-var": [1], "prefer-const": [1],
db6f71d87d82ecb36f3dcf4f8ff4734961a6f97e
client/components/interface/Navbar.js
client/components/interface/Navbar.js
import React, { PureComponent } from 'react' import { Link } from 'react-router' class Navbar extends PureComponent { render() { return( <header className='page-header'> <span><Link to='/'>SlimPoll</Link></span> <nav className='navbar'> <li><Link to="/all-polls">Polls</Link></li> <li><Link to="/create-poll">Create a poll</Link></li> <li><Link to="/my-polls">View your polls</Link></li> </nav> </header> ) } } export default Navbar
import React, { PureComponent } from 'react' import { connect } from 'react-redux' import { Link } from 'react-router' import signOut from '../../actions/users/sign-out' class Navbar extends PureComponent { checkLoginStatus() { return !!this.props.currentUser ? this.renderSignOut() : this.renderSignIn() } renderSignOut() { return <li onClick={this.props.signOut}><a>Sign Out</a></li> } renderSignIn() { return <li><Link to='/sign-in'>Sign In</Link></li> } render() { return( <header className='page-header'> <span><Link to='/'>SlimPoll</Link></span> <nav className='navbar'> <li><Link to="/all-polls">Polls</Link></li> <li><Link to="/create-poll">Create a poll</Link></li> <li><Link to="/my-polls">View your polls</Link></li> { this.checkLoginStatus() } </nav> </header> ) } } const mapStateToProps = ({ currentUser }) => ({ currentUser }) export default connect(mapStateToProps, { signOut })(Navbar)
Add sign in/sign out to navbar
Add sign in/sign out to navbar
JavaScript
mit
SanderSijbrandij/slimpoll,SanderSijbrandij/slimpoll
--- +++ @@ -1,7 +1,22 @@ import React, { PureComponent } from 'react' +import { connect } from 'react-redux' import { Link } from 'react-router' +import signOut from '../../actions/users/sign-out' + class Navbar extends PureComponent { + checkLoginStatus() { + return !!this.props.currentUser ? this.renderSignOut() : this.renderSignIn() + } + + renderSignOut() { + return <li onClick={this.props.signOut}><a>Sign Out</a></li> + } + + renderSignIn() { + return <li><Link to='/sign-in'>Sign In</Link></li> + } + render() { return( <header className='page-header'> @@ -10,10 +25,11 @@ <li><Link to="/all-polls">Polls</Link></li> <li><Link to="/create-poll">Create a poll</Link></li> <li><Link to="/my-polls">View your polls</Link></li> + { this.checkLoginStatus() } </nav> </header> ) } } - -export default Navbar +const mapStateToProps = ({ currentUser }) => ({ currentUser }) +export default connect(mapStateToProps, { signOut })(Navbar)
b7ad749b3a50aa0188efaff9ede44b91a347dac8
.eslintrc.js
.eslintrc.js
module.exports = { extends: [ 'eslint-config-xo-space/esnext', 'eslint-config-prettier', 'eslint-config-prettier/standard', ], env: { node: true, }, rules: { 'comma-dangle': [ 'error', 'always-multiline', ], } };
const extentions = ['.ts', '.tsx', '.js', '.jsx', '.vue', '.json', '.node']; module.exports = { env: { node: true, browser: true, commonjs: true, serviceworker: true, }, extends: ['eslint:recommended', 'plugin:node/recommended', 'plugin:prettier/recommended'], plugins: ['@typescript-eslint'], parser: '@typescript-eslint/parser', parserOptions: { sourceType: 'module', project: './tsconfig.json', useJSXTextNode: true, extraFileExtensions: extentions, }, settings: { node: { tryExtensions: extentions, }, }, rules: { 'no-unused-vars': 'off', '@typescript-eslint/no-unused-vars': 'error', camelcase: 'off', '@typescript-eslint/camelcase': 'error', '@typescript-eslint/adjacent-overload-signatures': 'error', 'node/no-missing-import': [ 'error', { allowModules: [], resolvePaths: ['./src'], tryExtensions: extentions, }, ], 'node/no-unsupported-features/es-syntax': 'off', }, };
Update eslint config for typescript
Update eslint config for typescript
JavaScript
mit
khirayama/micro-emitter,khirayama/micro-emitter,khirayama/MicroEmitter
--- +++ @@ -1,16 +1,42 @@ +const extentions = ['.ts', '.tsx', '.js', '.jsx', '.vue', '.json', '.node']; + module.exports = { - extends: [ - 'eslint-config-xo-space/esnext', - 'eslint-config-prettier', - 'eslint-config-prettier/standard', - ], env: { node: true, + browser: true, + commonjs: true, + serviceworker: true, + }, + extends: ['eslint:recommended', 'plugin:node/recommended', 'plugin:prettier/recommended'], + plugins: ['@typescript-eslint'], + parser: '@typescript-eslint/parser', + parserOptions: { + sourceType: 'module', + project: './tsconfig.json', + useJSXTextNode: true, + extraFileExtensions: extentions, + }, + settings: { + node: { + tryExtensions: extentions, + }, }, rules: { - 'comma-dangle': [ + 'no-unused-vars': 'off', + '@typescript-eslint/no-unused-vars': 'error', + + camelcase: 'off', + '@typescript-eslint/camelcase': 'error', + + '@typescript-eslint/adjacent-overload-signatures': 'error', + 'node/no-missing-import': [ 'error', - 'always-multiline', + { + allowModules: [], + resolvePaths: ['./src'], + tryExtensions: extentions, + }, ], - } + 'node/no-unsupported-features/es-syntax': 'off', + }, };
3eb418792854093555fd535ef14b5115b007ddcd
lib/EditorInserter.js
lib/EditorInserter.js
'use babel'; import { TextEditor } from 'atom'; export default class EditorInserter { setText(text) { this.insertionText = text; } performInsertion() { if (!this.insertionText) { console.error("No text to insert."); return; } this.textEditor = atom.workspace.getActiveTextEditor(); this.textEditor.insertText(this.insertionText); } }
'use babel'; import { TextEditor } from 'atom'; export default class EditorInserter { setText(text) { this.insertionText = text; } performInsertion() { if (!this.insertionText) { console.error("No text to insert."); return; } this.textEditor = atom.workspace.getActiveTextEditor(); //Break up lines var lines = this.insertionText.split("\n"); //Start by inserting the first line this.textEditor.insertText(lines[0]); //Go back to the very beginning of the line and save the tab spacing var tabSpacing = " "; //Now prepend this tab spacing to all other lines and concatenate them var concatenation = ""; for (let i = 1; i < lines.length; i++) { concatenation += tabSpacing + lines[i]; } //Finally, insert this concatenation to complete the insertion this.textEditor.insertText(concatenation); } }
Break up lines then insert tabs to lines after 1st
Break up lines then insert tabs to lines after 1st
JavaScript
mit
Coteh/syntaxdb-atom-plugin
--- +++ @@ -13,6 +13,18 @@ return; } this.textEditor = atom.workspace.getActiveTextEditor(); - this.textEditor.insertText(this.insertionText); + //Break up lines + var lines = this.insertionText.split("\n"); + //Start by inserting the first line + this.textEditor.insertText(lines[0]); + //Go back to the very beginning of the line and save the tab spacing + var tabSpacing = " "; + //Now prepend this tab spacing to all other lines and concatenate them + var concatenation = ""; + for (let i = 1; i < lines.length; i++) { + concatenation += tabSpacing + lines[i]; + } + //Finally, insert this concatenation to complete the insertion + this.textEditor.insertText(concatenation); } }
d5d9044686a1ee5eaa01ced5e013029f5b61d63f
lib/cartodb/models/dataview/factory.js
lib/cartodb/models/dataview/factory.js
var dataviews = require('./'); module.exports = class DataviewFactory { static get dataviews() { return Object.keys(dataviews).reduce((allDataviews, dataviewClassName) => { allDataviews[dataviewClassName.toLowerCase()] = dataviews[dataviewClassName]; return allDataviews; }, {}); } static getDataview (query, dataviewDefinition) { var type = dataviewDefinition.type; if (!this.dataviews[type]) { throw new Error('Invalid dataview type: "' + type + '"'); } return new this.dataviews[type](query, dataviewDefinition.options, dataviewDefinition.sql); } };
const dataviews = require('./'); module.exports = class DataviewFactory { static get dataviews() { return Object.keys(dataviews).reduce((allDataviews, dataviewClassName) => { allDataviews[dataviewClassName.toLowerCase()] = dataviews[dataviewClassName]; return allDataviews; }, {}); } static getDataview (query, dataviewDefinition) { const type = dataviewDefinition.type; if (!this.dataviews[type]) { throw new Error('Invalid dataview type: "' + type + '"'); } return new this.dataviews[type](query, dataviewDefinition.options, dataviewDefinition.sql); } };
Use const keyword to declare variables
Use const keyword to declare variables
JavaScript
bsd-3-clause
CartoDB/Windshaft-cartodb,CartoDB/Windshaft-cartodb,CartoDB/Windshaft-cartodb,CartoDB/Windshaft-cartodb
--- +++ @@ -1,4 +1,4 @@ -var dataviews = require('./'); +const dataviews = require('./'); module.exports = class DataviewFactory { static get dataviews() { @@ -9,7 +9,7 @@ } static getDataview (query, dataviewDefinition) { - var type = dataviewDefinition.type; + const type = dataviewDefinition.type; if (!this.dataviews[type]) { throw new Error('Invalid dataview type: "' + type + '"'); }
1e8d4fb77ba001dda3d3dad9f476a026a54afe01
src/js/app.js
src/js/app.js
var $ = require('./jquery'); var jQueryVersion = require('./lib.js'); $(function() { console.log(jQueryVersion()); })();
var $ = require('jquery'); var jQueryVersion = require('./lib.js'); $(function() { console.log(jQueryVersion()); })();
Update require to use npm jquery not a local version
Update require to use npm jquery not a local version
JavaScript
isc
bitfyre/contacts,bitfyre/boilerplate,bitfyre/drinkmachine
--- +++ @@ -1,4 +1,4 @@ -var $ = require('./jquery'); +var $ = require('jquery'); var jQueryVersion = require('./lib.js'); $(function() {
b8f41f761328ed42bf02019b73b98870cb003775
server/api/nodes/nodeController.js
server/api/nodes/nodeController.js
var Node = require('./nodeModel.js'), handleError = require('../../util.js').handleError, handleQuery = require('../queryHandler.js'); module.exports = { createNode : function (req, res, next) { var newNode = req.body; // Support /nodes and /roadmaps/roadmapID/nodes newNode.parentRoadmap = newNode.parentRoadmap || req.params.roadmapID; Node(newNode).save() .then(function(dbResults){ res.status(201).json(dbResults); }) .catch(handleError(next)); }, getNodeByID : function (req, res, next) { var _id = req.params.nodeID; Node.findById(_id) .then(function(dbResults){ res.json(dbResults); }) .catch(handleError(next)); }, updateNode : function (req, res, next) { }, deleteNode : function (req, res, next) { } };
var Node = require('./nodeModel.js'), handleError = require('../../util.js').handleError, handleQuery = require('../queryHandler.js'); module.exports = { createNode : function (req, res, next) { var newNode = req.body; // Support /nodes and /roadmaps/roadmapID/nodes newNode.parentRoadmap = newNode.parentRoadmap || req.params.roadmapID; Node(newNode).save() .then(function(dbResults){ res.status(201).json(dbResults); }) .catch(handleError(next)); }, getNodeByID : function (req, res, next) { var _id = req.params.nodeID; Node.findById(_id) .then(function(dbResults){ res.json(dbResults); }) .catch(handleError(next)); }, updateNode : function (req, res, next) { var _id = req.params.nodeID; var updateCommand = req.body; Node.findByIdAndUpdate(_id, updateCommand) .then(function(dbResults){ res.json(dbResults); }) .catch(handleError(next)); }, deleteNode : function (req, res, next) { } };
Add route handler for PUT /api/nodes/:nodeID
Add route handler for PUT /api/nodes/:nodeID
JavaScript
mit
sreimer15/RoadMapToAnything,cyhtan/RoadMapToAnything,RoadMapToAnything/RoadMapToAnything,cyhtan/RoadMapToAnything,delventhalz/RoadMapToAnything,GMeyr/RoadMapToAnything,delventhalz/RoadMapToAnything,RoadMapToAnything/RoadMapToAnything,sreimer15/RoadMapToAnything,GMeyr/RoadMapToAnything
--- +++ @@ -25,7 +25,13 @@ }, updateNode : function (req, res, next) { - + var _id = req.params.nodeID; + var updateCommand = req.body; + Node.findByIdAndUpdate(_id, updateCommand) + .then(function(dbResults){ + res.json(dbResults); + }) + .catch(handleError(next)); }, deleteNode : function (req, res, next) {
d4651c7889b0aaf5b699e459dfaf06352acb0e9e
js/models/Expectation.js
js/models/Expectation.js
var Expectation = Backbone.Model.extend({ initialize: function(){ }, defaults: { complete: false, }, validate: function(attributes){ if(attributes.title === undefined){ return "Remember to set a title for your expectation."; } }, delete: function() { this.destroy(); }, toggle: function() { this.set({complete: !this.get('complete')}); } });
var Expectation = Backbone.Model.extend({ initialize: function(){ }, defaults: { complete: false, }, validate: function(attributes){ if(attributes.title === undefined){ return "Remember to set a title for your expectation."; } }, delete: function() { this.destroy(); }, toggle: function() { this.save({ complete: !this.get('complete') }); } });
Add localStorage save on expectation complete.
Add localStorage save on expectation complete.
JavaScript
mit
Zinston/projectexpect,Zinston/projectexpect,Zinston/projectexpect
--- +++ @@ -18,6 +18,8 @@ }, toggle: function() { - this.set({complete: !this.get('complete')}); + this.save({ + complete: !this.get('complete') + }); } });
b6266d3dd099c42d27265abaf46ebe40df0b676c
software/var/www/html/cyths/js/cyths-i18n.js
software/var/www/html/cyths/js/cyths-i18n.js
// 2016-10-21 V 1.0.0 // - Initial release // // i18next configuration // var i18nextOptions = { // evtl. use language-detector https://github.com/i18next/i18next-browser-languageDetector lng: navigator.language || navigator.userLanguage, fallbackLng: 'en', load: 'currentOnly', backend: { // i18nextLoadPath must be declared as a global variable loadPath: i18nextLoadPath } } // // i18next initialization // i18next.use( i18nextXHRBackend ).init( i18nextOptions , function(err, t) { // For options see: https://github.com/i18next/jquery-i18next#initialize-the-plugin jqueryI18next.init( i18next , $ ); // Start localizing, details: https://github.com/i18next/jquery-i18next#usage-of-selector-function $( 'head, body' ).localize(); });
// // Author: CYOSP // Created: 2016-10-21 // Version: 1.1.0 // // 2016-10-22 V 1.1.0 // - Execute cythsInit function (if it exists) // after internationalization // 2016-10-21 V 1.0.0 // - Initial release // // i18next configuration // var i18nextOptions = { // evtl. use language-detector https://github.com/i18next/i18next-browser-languageDetector lng: navigator.language || navigator.userLanguage, fallbackLng: 'en', load: 'currentOnly', backend: { // i18nextLoadPath must be declared as a global variable loadPath: i18nextLoadPath } } // // i18next initialization // i18next.use( i18nextXHRBackend ).init( i18nextOptions , function(err, t) { // For options see: https://github.com/i18next/jquery-i18next#initialize-the-plugin jqueryI18next.init( i18next , $ ); // Start localizing, details: https://github.com/i18next/jquery-i18next#usage-of-selector-function $( 'head, body' ).localize(); // Internationalization is performed // Call CYTHS init function if defined if( typeof cythsInit !== 'undefined' && $.isFunction( cythsInit ) ) { cythsInit(); } });
Call cythsInit function after internationalization
Call cythsInit function after internationalization
JavaScript
bsd-3-clause
cyosp/CYTHS,cyosp/CYTHS,cyosp/CYTHS,cyosp/CYTHS,cyosp/CYTHS
--- +++ @@ -1,3 +1,12 @@ +// +// Author: CYOSP +// Created: 2016-10-21 +// Version: 1.1.0 +// + +// 2016-10-22 V 1.1.0 +// - Execute cythsInit function (if it exists) +// after internationalization // 2016-10-21 V 1.0.0 // - Initial release @@ -27,4 +36,11 @@ // Start localizing, details: https://github.com/i18next/jquery-i18next#usage-of-selector-function $( 'head, body' ).localize(); + + // Internationalization is performed + // Call CYTHS init function if defined + if( typeof cythsInit !== 'undefined' && $.isFunction( cythsInit ) ) + { + cythsInit(); + } });
9429f118db1da076c372fec4e935ef3050bc8079
lib/__tests__/findUsedIdentifiers-test.js
lib/__tests__/findUsedIdentifiers-test.js
import findUsedIdentifiers from '../findUsedIdentifiers'; import parse from '../parse'; it('finds used variables', () => { expect( findUsedIdentifiers( parse( ` api.something(); const foo = 'foo'; foo(); bar(); `, ), ), ).toEqual(new Set(['api', 'foo', 'bar'])); }); it('knows about jsx', () => { expect( findUsedIdentifiers( parse( ` <Foo bar={far.foo()}/> `, ), ), ).toEqual(new Set(['far', 'React', 'Foo'])); }); it('knows about flow annotations', () => { expect( findUsedIdentifiers( parse( ` class Foo { bar: Car; } `, ), ), ).toEqual(new Set(['Car'])); }); it('treats items in arrays as used', () => { expect( findUsedIdentifiers( parse( ` [Foo, Bar] `, ), ), ).toEqual(new Set(['Foo', 'Bar'])); }); it('treats items used as arguments as used', () => { expect( findUsedIdentifiers( parse( ` foo(Foo, Bar); `, ), ), ).toEqual(new Set(['foo', 'Foo', 'Bar'])); });
import findUsedIdentifiers from '../findUsedIdentifiers'; import parse from '../parse'; it('finds used variables', () => { expect( findUsedIdentifiers( parse( ` api.something(); const foo = 'foo'; foo(); bar(); `, ), ), ).toEqual(new Set(['api', 'foo', 'bar'])); }); it('knows about jsx', () => { expect( findUsedIdentifiers( parse( ` <Foo bar={far.foo()}/> `, ), ), ).toEqual(new Set(['far', 'React', 'Foo'])); }); it('knows about flow annotations', () => { expect( findUsedIdentifiers( parse( ` class Foo { bar: Car; } `, ), ), ).toEqual(new Set(['Car'])); }); it('knows about export declarations', () => { expect( findUsedIdentifiers( parse( ` export { foo as bar } export { baz } `, ), ), ).toEqual(new Set(['foo', 'baz'])); }); it('treats items in arrays as used', () => { expect( findUsedIdentifiers( parse( ` [Foo, Bar] `, ), ), ).toEqual(new Set(['Foo', 'Bar'])); }); it('treats items used as arguments as used', () => { expect( findUsedIdentifiers( parse( ` foo(Foo, Bar); `, ), ), ).toEqual(new Set(['foo', 'Foo', 'Bar'])); });
Add test for export declarations to findUsedIdentifiers
Add test for export declarations to findUsedIdentifiers I recently added some test that changed how identifiers were visited, and I just wanted to make sure I didn't break anything for the findUsedIdentifiers module.
JavaScript
mit
trotzig/import-js,trotzig/import-js,trotzig/import-js,Galooshi/import-js
--- +++ @@ -42,6 +42,19 @@ ).toEqual(new Set(['Car'])); }); +it('knows about export declarations', () => { + expect( + findUsedIdentifiers( + parse( + ` + export { foo as bar } + export { baz } + `, + ), + ), + ).toEqual(new Set(['foo', 'baz'])); +}); + it('treats items in arrays as used', () => { expect( findUsedIdentifiers(
f9cdaafa737eee65a9743b40bdc1dfd4f5859ab4
lib/rules/opinions.js
lib/rules/opinions.js
'use strict'; /** * Rules in this file are ultimately random choices. * * No human should have to type on a keyboard to comply. * If it can't be --fix'ed, it doesn't belong in here. */ module.exports = { 'prettier/prettier': [ 'error', { singleQuote: true, trailingComma: 'es5', }, ], 'lines-around-directive': ['error', 'always'], 'import/newline-after-import': 'error', };
'use strict'; /** * Rules in this file are ultimately random choices. * * No human should have to type on a keyboard to comply. * If it can't be --fix'ed, it doesn't belong in here. */ module.exports = { /** * Everything reported by prettier will be fixed by prettier. * * See: https://github.com/prettier/eslint-plugin-prettier */ 'prettier/prettier': [ 'error', { singleQuote: true, trailingComma: 'es5', }, ], /** * After 'use strict' there's a newline. * * See: https://eslint.org/docs/rules/lines-around-directive */ 'lines-around-directive': ['error', 'always'], /** * After the last require/import statement, there's a newline. * * See: https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/newline-after-import.md */ 'import/newline-after-import': 'error', };
Add links to opinion rules
docs: Add links to opinion rules
JavaScript
bsd-3-clause
groupon/javascript
--- +++ @@ -7,6 +7,11 @@ * If it can't be --fix'ed, it doesn't belong in here. */ module.exports = { + /** + * Everything reported by prettier will be fixed by prettier. + * + * See: https://github.com/prettier/eslint-plugin-prettier + */ 'prettier/prettier': [ 'error', { @@ -14,6 +19,18 @@ trailingComma: 'es5', }, ], + + /** + * After 'use strict' there's a newline. + * + * See: https://eslint.org/docs/rules/lines-around-directive + */ 'lines-around-directive': ['error', 'always'], + + /** + * After the last require/import statement, there's a newline. + * + * See: https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/newline-after-import.md + */ 'import/newline-after-import': 'error', };
9a679fb9bed5c813c33886572b81bc1e4bcd2f6a
lib/search-tickets.js
lib/search-tickets.js
'use strict'; function searchTickets (args, callback) { var seneca = this; var ticketsEntity = seneca.make$('cd/tickets'); var query = args.query || {}; if (!query.limit$) query.limit$ = 'NULL'; ticketsEntity.list$(query, callback); } module.exports = searchTickets;
'use strict'; var async = require('async'); function searchTickets (args, callback) { var seneca = this; var ticketsEntity = seneca.make$('cd/tickets'); var plugin = args.role; async.waterfall([ loadTickets, getNumberOfApplications, getNumberOfApprovedApplications ], callback); function loadTickets (done) { var query = args.query || {}; if (!query.limit$) query.limit$ = 'NULL'; ticketsEntity.list$(query, done); } function getNumberOfApplications (tickets, done) { async.map(tickets, function (ticket, cb) { seneca.act({role: plugin, cmd: 'searchApplications', query: {ticketId: ticket.id, deleted: 0}}, function(err, applications) { if (err) return cb(err); ticket.totalApplications = applications.length; cb(null,ticket); }); }, done); } function getNumberOfApprovedApplications (tickets, done) { async.map(tickets, function (ticket, cb) { seneca.act({role: plugin, cmd: 'searchApplications', query: {ticketId: ticket.id, deleted: 0, status: "approved"}}, function(err, applications) { if (err) return cb(err); ticket.approvedApplications = applications.length; cb(null,ticket); }); }, done); } } module.exports = searchTickets;
Add approvedApplications and totalApplications to tickets
Add approvedApplications and totalApplications to tickets This is groundwork for resolving CoderDojo/community-platform#778. It allows us to see how many applications there are for a given ticket type.
JavaScript
mit
CoderDojo/cp-events-service,CoderDojo/cp-events-service
--- +++ @@ -1,11 +1,43 @@ 'use strict'; + +var async = require('async'); function searchTickets (args, callback) { var seneca = this; var ticketsEntity = seneca.make$('cd/tickets'); - var query = args.query || {}; - if (!query.limit$) query.limit$ = 'NULL'; - ticketsEntity.list$(query, callback); + var plugin = args.role; + + async.waterfall([ + loadTickets, + getNumberOfApplications, + getNumberOfApprovedApplications + ], callback); + + function loadTickets (done) { + var query = args.query || {}; + if (!query.limit$) query.limit$ = 'NULL'; + ticketsEntity.list$(query, done); + } + + function getNumberOfApplications (tickets, done) { + async.map(tickets, function (ticket, cb) { + seneca.act({role: plugin, cmd: 'searchApplications', query: {ticketId: ticket.id, deleted: 0}}, function(err, applications) { + if (err) return cb(err); + ticket.totalApplications = applications.length; + cb(null,ticket); + }); + }, done); + } + + function getNumberOfApprovedApplications (tickets, done) { + async.map(tickets, function (ticket, cb) { + seneca.act({role: plugin, cmd: 'searchApplications', query: {ticketId: ticket.id, deleted: 0, status: "approved"}}, function(err, applications) { + if (err) return cb(err); + ticket.approvedApplications = applications.length; + cb(null,ticket); + }); + }, done); + } } module.exports = searchTickets;
fd684ddab77fc5cef3d8f1b688662e8cfce695cb
validate_doc_update.js
validate_doc_update.js
function (newDoc, oldDoc, userCtx) { function forbidden(message) { throw({forbidden : message}); }; function unauthorized(message) { throw({unauthorized : message}); }; if (userCtx.roles.indexOf('hf_app_admins') == -1) { // admin can edit anything, only check when not admin... if (newDoc._deleted) { forbidden("You must be an administrator to delete a document."); } else if (userCtx.roles.indexOf('hf_app_writers') == -1) { forbidden("You must have write access to change a document."); } } }; //@ sourceURL=/validate_doc_update.js
function (newDoc, oldDoc, userCtx) { function forbidden(message) { throw({forbidden : message}); }; function unauthorized(message) { throw({unauthorized : message}); }; if ((userCtx.roles.indexOf('_admin') == -1) && (userCtx.roles.indexOf('hf_app_admins') == -1)) { // admin can edit anything, only check when not admin... if (newDoc._deleted) { forbidden("You must be an administrator to delete a document."); } else if (userCtx.roles.indexOf('hf_app_writers') == -1) { forbidden("You must have write access to change a document."); } } }; //@ sourceURL=/validate_doc_update.js
Repair validation needed for replication.
Repair validation needed for replication.
JavaScript
apache-2.0
shmakes/hf-app-review,shmakes/hf-app-review
--- +++ @@ -7,7 +7,8 @@ throw({unauthorized : message}); }; - if (userCtx.roles.indexOf('hf_app_admins') == -1) { + if ((userCtx.roles.indexOf('_admin') == -1) + && (userCtx.roles.indexOf('hf_app_admins') == -1)) { // admin can edit anything, only check when not admin... if (newDoc._deleted) { forbidden("You must be an administrator to delete a document.");
280796f433e3aca870b6a66521ed7021fe441236
server/import/import_scripts/category_mapping.js
server/import/import_scripts/category_mapping.js
module.exports = { "Dagens bedrift": "PRESENTATIONS", "Fest og moro": "NIGHTLIFE", "Konsert": "MUSIC", "Kurs og events": "PRESENTATIONS", "Revy og teater": "PERFORMANCES", "Foredrag": "PRESENTATIONS", "Møte": "DEBATE", "Happening": "NIGHTLIFE", "Kurs": "OTHER", "Show": "PERFORMANCES", "Fotballkamp": "SPORT", "Film": "PRESENTATIONS", "Samfundsmøte": "DEBATE", "Excenteraften": "DEBATE", "Temafest": "NIGHTLIFE", "Bokstavelig talt": "DEBATE", "Quiz": "OTHER", "DJ": "MUSIC", "Teater": "PERFORMANCES", "Annet": "OTHER", "Kurs": "PRESENTATIONS", "Omvising": "PRESENTATIONS", "Samfunn": "DEBATE", "Festival": "PERFORMANCES", "Sport": "SPORT", "Forestilling": "PERFORMANCES", "Utstilling" : "EXHIBITIONS", "Festmøte" : "DEBATE" };
module.exports = { "Dagens bedrift": "PRESENTATIONS", "Fest og moro": "NIGHTLIFE", "Konsert": "MUSIC", "Kurs og events": "PRESENTATIONS", "Revy og teater": "PERFORMANCES", "Foredrag": "PRESENTATIONS", "Møte": "DEBATE", "Happening": "NIGHTLIFE", "Kurs": "OTHER", "Show": "PERFORMANCES", "Fotballkamp": "SPORT", "Film": "PRESENTATIONS", "Samfundsmøte": "DEBATE", "Excenteraften": "DEBATE", "Temafest": "NIGHTLIFE", "Bokstavelig talt": "DEBATE", "Quiz": "OTHER", "DJ": "MUSIC", "Teater": "PERFORMANCES", "Annet": "OTHER", "Kurs": "PRESENTATIONS", "Omvising": "PRESENTATIONS", "Samfunn": "DEBATE", "Festival": "PERFORMANCES", "Sport": "SPORT", "Forestilling": "PERFORMANCES", "Utstilling" : "EXHIBITIONS", "Festmøte" : "DEBATE", "Onsdagsdebatt" : "DEBATE" };
Add category mapping for "onsdagsdebatt"
Add category mapping for "onsdagsdebatt"
JavaScript
apache-2.0
Studentmediene/Barteguiden,Studentmediene/Barteguiden
--- +++ @@ -26,5 +26,6 @@ "Sport": "SPORT", "Forestilling": "PERFORMANCES", "Utstilling" : "EXHIBITIONS", - "Festmøte" : "DEBATE" + "Festmøte" : "DEBATE", + "Onsdagsdebatt" : "DEBATE" };
8bf06d0e91954e646d76cc89e40421d8be9354f0
focus-file-webpack.config.js
focus-file-webpack.config.js
const path = require('path'); module.exports = { entry: [ './src/component/index' ], output: { path: path.join(__dirname, 'dist'), filename: 'focus-file.js', publicPath: '/dist/', libraryTarget: 'var', library: 'FocusFile' }, loaders: [], plugins: [], directory: path.join(__dirname, 'src'), port: 3000 };
const path = require('path'); module.exports = { entry: [ './src/component/index' ], output: { path: path.join(__dirname, 'dist'), filename: 'focus-file.js', publicPath: '/dist/', libraryTarget: 'var', library: 'FocusFile' }, loaders: [ { test: /\.css$/, loader: 'style!css' } ], plugins: [], directory: path.join(__dirname, 'src'), port: 3000 };
Add missing loader for CSS
[webpack] Add missing loader for CSS
JavaScript
mit
KleeGroup/focus-file,pierr/focus-file,pierr/focus-file,KleeGroup/focus-file
--- +++ @@ -10,7 +10,12 @@ libraryTarget: 'var', library: 'FocusFile' }, - loaders: [], + loaders: [ + { + test: /\.css$/, + loader: 'style!css' + } + ], plugins: [], directory: path.join(__dirname, 'src'), port: 3000
23acaf0ad26a220519bea094337b58ce067d5219
src/components/HighlightedMarkdown/Code.js
src/components/HighlightedMarkdown/Code.js
import React, {PureComponent, PropTypes} from 'react' import {highlightElement} from 'prismjs' import 'prismjs/themes/prism.css' import 'prismjs/components/prism-css' import 'prismjs/components/prism-javascript' import 'prismjs/components/prism-bash' export default class Code extends PureComponent { static propTypes = { lang: PropTypes.string, text: PropTypes.string } componentDidMount() { const {lang, text} = this.props this.code.textContent = text if (lang) highlightElement(this.code) } onRef = (ref) => { this.code = ref } render() { const {lang} = this.props return <code ref={this.onRef} className={`language-${lang}`} /> } }
import React, {PureComponent, PropTypes} from 'react' import {highlightElement} from 'prismjs' import 'prismjs/themes/prism.css' import 'prismjs/components/prism-css' import 'prismjs/components/prism-javascript' import 'prismjs/components/prism-bash' export default class Code extends PureComponent { static propTypes = { lang: PropTypes.string, text: PropTypes.string } componentDidMount() { const {lang, text} = this.props this.code.textContent = text if (lang) highlightElement(this.code) } onRef = (ref) => { this.code = ref } render() { // Fix the difference between github and prism syntax highlighting const lang = this.props.lang === 'es6' ? 'javascript' : this.props.lang return <code ref={this.onRef} className={`language-${lang}`} /> } }
Fix es6 highlight for prism
Fix es6 highlight for prism
JavaScript
mit
cssinjs/cssinjs
--- +++ @@ -22,7 +22,9 @@ } render() { - const {lang} = this.props + // Fix the difference between github and prism syntax highlighting + const lang = this.props.lang === 'es6' ? 'javascript' : this.props.lang + return <code ref={this.onRef} className={`language-${lang}`} /> } }
931460365417ffc356984622d32d34caa04812e4
src/direct-linking/content_script/index.js
src/direct-linking/content_script/index.js
import { bodyLoader } from 'src/util/loader' import { remoteFunction } from 'src/util/webextensionRPC' import * as rendering from './rendering' import * as interactions from './interactions' export async function init() { await bodyLoader() remoteFunction('followAnnotationRequest')() } export function setupAnchorFallbackOverlay() {} browser.runtime.onMessage.addListener(request => { if (request.type !== 'direct-link') { return } ;(async () => { const highlightSuccessful = await rendering.highlightAnnotation({ annotation: request.annotation, }) if (highlightSuccessful) { interactions.scrollToHighlight() } else { setupAnchorFallbackOverlay() } })() }) init()
import { bodyLoader } from 'src/util/loader' import { remoteFunction } from 'src/util/webextensionRPC' import * as rendering from './rendering' import * as interactions from './interactions' export async function init() { await bodyLoader() setTimeout(() => { remoteFunction('followAnnotationRequest')() }, 500) } export function setupAnchorFallbackOverlay() {} browser.runtime.onMessage.addListener(request => { if (request.type !== 'direct-link') { return } ;(async () => { const highlightSuccessful = await rendering.highlightAnnotation({ annotation: request.annotation, }) if (highlightSuccessful) { interactions.scrollToHighlight() } else { setupAnchorFallbackOverlay() } })() }) init()
Add delay to anchoring code
Add delay to anchoring code
JavaScript
mit
WorldBrain/WebMemex,WorldBrain/WebMemex
--- +++ @@ -5,7 +5,9 @@ export async function init() { await bodyLoader() - remoteFunction('followAnnotationRequest')() + setTimeout(() => { + remoteFunction('followAnnotationRequest')() + }, 500) } export function setupAnchorFallbackOverlay() {}
71d3d909d1c2b3192cb6b44735aef1fd89c5e00b
webpack.prod.config.js
webpack.prod.config.js
var path = require('path'); var webpack = require('webpack'); var webpackStripLoader = require('strip-loader'); module.exports = { plugins: [ new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('production') } }) ], entry: ['./js/App.js'], output: { path: __dirname + '/public', filename: 'bundle.js' }, module: { rules: [{ test: /.jsx?$/, use: 'babel-loader', exclude: /node_modules/ }, { test: /\.css$/, use: ['style-loader', 'css-loader', 'postcss-loader'] }, { test: /\.(eot|svg|ttf|woff|woff2)$/, use: 'file-loader?name=fonts/[name].[ext]' }, { test: /\.png$/, use: 'url-loader' }, { test: [/\.js$/, /\.jsx$/], exclude: /node_modules/, use: webpackStripLoader.loader('console.log') } ] } };
var path = require('path'); var webpack = require('webpack'); var webpackStripLoader = require('strip-loader'); module.exports = { plugins: [ new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('production') } }) ], entry: ['./js/App.js'], output: { path: __dirname + '/public', filename: 'bundle.js' }, devtool: 'source-map', module: { rules: [{ test: /.jsx?$/, use: 'babel-loader', exclude: /node_modules/ }, { test: /\.css$/, use: ['style-loader', 'css-loader', 'postcss-loader'] }, { test: /\.(eot|svg|ttf|woff|woff2)$/, use: 'file-loader?name=fonts/[name].[ext]' }, { test: /\.png$/, use: 'url-loader' }, { test: [/\.js$/, /\.jsx$/], exclude: /node_modules/, use: webpackStripLoader.loader('console.log') } ] } };
Add source map to prod
Add source map to prod
JavaScript
mit
PathwayCommons/pathways-search,PathwayCommons/pathways-search
--- +++ @@ -15,6 +15,7 @@ path: __dirname + '/public', filename: 'bundle.js' }, + devtool: 'source-map', module: { rules: [{ test: /.jsx?$/,
b0a80a810dfc8381be3d1290e61283e8461ca2ac
src/main/resources/dotty_res/scripts/ux.js
src/main/resources/dotty_res/scripts/ux.js
window.addEventListener("DOMContentLoaded", () => { document.getElementById("leftToggler").onclick = function() { document.getElementById("leftColumn").classList.toggle("open"); } hljs.registerLanguage('scala', highlightDotty); hljs.registerAliases(['dotty', 'scala3'], 'scala'); hljs.initHighlighting(); });
window.addEventListener("DOMContentLoaded", () => { var e = document.getElementById("leftToggler"); if (e) { e.onclick = function() { document.getElementById("leftColumn").classList.toggle("open"); }; } hljs.registerLanguage('scala', highlightDotty); hljs.registerAliases(['dotty', 'scala3'], 'scala'); hljs.initHighlighting(); });
Make all Scala snippets highlighted
Make all Scala snippets highlighted Element with id `leftToggler` doesn't exist on some pages, which could sometimes throw an error before hljs syntax for Scala is loaded, which prevented it from working properly.
JavaScript
apache-2.0
sjrd/dotty,sjrd/dotty,sjrd/dotty,dotty-staging/dotty,sjrd/dotty,sjrd/dotty,lampepfl/dotty,dotty-staging/dotty,lampepfl/dotty,dotty-staging/dotty,dotty-staging/dotty,lampepfl/dotty,lampepfl/dotty,lampepfl/dotty,dotty-staging/dotty
--- +++ @@ -1,6 +1,9 @@ window.addEventListener("DOMContentLoaded", () => { - document.getElementById("leftToggler").onclick = function() { - document.getElementById("leftColumn").classList.toggle("open"); + var e = document.getElementById("leftToggler"); + if (e) { + e.onclick = function() { + document.getElementById("leftColumn").classList.toggle("open"); + }; } hljs.registerLanguage('scala', highlightDotty); hljs.registerAliases(['dotty', 'scala3'], 'scala');
c173cc7a8bd057b9ebbbbd39cb4321bfce1a5fe4
test/index.js
test/index.js
var config = require('./config'); var should = require('should'); var nock = require('nock'); var up = require('../index')(config); var baseApi = nock('https://jawbone.com:443'); describe('up', function(){ describe('.moves', function(){ describe('.get()', function(){ it('should call correct url', function(done){ var api = baseApi.matchHeader('Accept', 'application/json') .get('/nudge/api/v.1.1/users/@me/moves?') .reply(200, 'OK!'); up.moves.get({}, function(err, body) { (err === null).should.be.true; body.should.equal('OK!'); api.isDone().should.be.true; api.pendingMocks().should.be.empty; done(); }); }); }); describe('.get({ xid: 123 })', function(){ it('should return correct url', function(done){ var api = baseApi.matchHeader('Accept', 'application/json') .get('/nudge/api/v.1.1/moves/123') .reply(200, 'OK!'); up.moves.get({ xid: 123 }, function(err, body) { (err === null).should.be.true; body.should.equal('OK!'); api.isDone().should.be.true; api.pendingMocks().should.be.empty; done(); }); }); }); }); });
var config = require('./config'); var should = require('should'); var nock = require('nock'); var up = require('../index')(config); nock.disableNetConnect(); var baseApi = nock('https://jawbone.com:443'); describe('up', function(){ describe('.moves', function(){ describe('.get()', function(){ it('should call correct url', function(done){ var api = baseApi.matchHeader('Accept', 'application/json') .get('/nudge/api/v.1.1/users/@me/moves?') .reply(200, 'OK!'); up.moves.get({}, function(err, body) { (err === null).should.be.true; body.should.equal('OK!'); api.done(); done(); }); }); }); describe('.get({ xid: 123 })', function(){ it('should return correct url', function(done){ var api = baseApi.matchHeader('Accept', 'application/json') .get('/nudge/api/v.1.1/moves/123') .reply(200, 'OK!'); up.moves.get({ xid: 123 }, function(err, body) { (err === null).should.be.true; body.should.equal('OK!'); api.done(); done(); }); }); }); }); });
Fix usage of Nock in unit tests - much cleaner now
Fix usage of Nock in unit tests - much cleaner now
JavaScript
mit
ryanseys/node-jawbone-up,banaee/node-jawbone-up
--- +++ @@ -3,6 +3,7 @@ var nock = require('nock'); var up = require('../index')(config); +nock.disableNetConnect(); var baseApi = nock('https://jawbone.com:443'); describe('up', function(){ @@ -17,8 +18,7 @@ (err === null).should.be.true; body.should.equal('OK!'); - api.isDone().should.be.true; - api.pendingMocks().should.be.empty; + api.done(); done(); }); @@ -35,8 +35,7 @@ (err === null).should.be.true; body.should.equal('OK!'); - api.isDone().should.be.true; - api.pendingMocks().should.be.empty; + api.done(); done(); });
5ab848471a67b8821730229f51ed16a929d7d99b
058_LengthOfLastWord.js
058_LengthOfLastWord.js
// https://leetcode.com/problems/length-of-last-word/#/description /** * @param {string} s * @return {number} */ var lengthOfLastWord = function (s) { if (!s) return 0; s = s.trimRight(); var arr = s.split(' '); return arr[arr.length - 1].length; }; var s = "Hello World"; console.log(lengthOfLastWord(s)); s = "HelloWorld"; console.log(lengthOfLastWord(s)); s = ""; console.log(lengthOfLastWord(s)); s = " aaa"; console.log(lengthOfLastWord(s)); s = "a"; console.log(lengthOfLastWord(s));
// https://leetcode.com/problems/length-of-last-word/#/description /** * @param {string} s * @return {number} */ // Simple var lengthOfLastWord2 = function (s) { if (!s) return 0; s = s.trimRight(); var arr = s.split(' '); return arr[arr.length - 1].length; }; // Improve var lengthOfLastWord = function (s) { if (!s) return 0; var started = false; var length = 0; for (var i = s.length - 1; i >= 0; i--) { if (s[i] !== ' ' && !started) { started = true; } if (!started) continue; if (started && s[i] === ' ') { break; } length++; } return length; }; var s = "Hello World"; console.log(lengthOfLastWord(s)); s = "HelloWorld"; console.log(lengthOfLastWord(s)); s = ""; console.log(lengthOfLastWord(s)); s = " aaa"; console.log(lengthOfLastWord(s)); s = "a"; console.log(lengthOfLastWord(s)); s = " "; console.log(lengthOfLastWord(s));
Improve Length Of Last Word
Improve Length Of Last Word
JavaScript
mit
lon-yang/leetcode,lon-yang/leetcode
--- +++ @@ -4,11 +4,31 @@ * @param {string} s * @return {number} */ -var lengthOfLastWord = function (s) { +// Simple +var lengthOfLastWord2 = function (s) { if (!s) return 0; s = s.trimRight(); var arr = s.split(' '); return arr[arr.length - 1].length; +}; + + +// Improve +var lengthOfLastWord = function (s) { + if (!s) return 0; + var started = false; + var length = 0; + for (var i = s.length - 1; i >= 0; i--) { + if (s[i] !== ' ' && !started) { + started = true; + } + if (!started) continue; + if (started && s[i] === ' ') { + break; + } + length++; + } + return length; }; var s = "Hello World"; @@ -25,3 +45,6 @@ s = "a"; console.log(lengthOfLastWord(s)); + +s = " "; +console.log(lengthOfLastWord(s));
902a1d9946864c11da8e982d626e4d6393e6fb21
e2e-tests/scenarios.js
e2e-tests/scenarios.js
'use strict'; describe('My App', function() { it('should automatically redirect to /home when location hash/fragment is empty', function() { browser.get('index.html'); expect(browser.getLocationAbsUrl()).toMatch("/home"); }); describe('Home', function() { beforeEach(function() { browser.get('index.html#!/home'); }); it('should render home when user navigates to /home', function() { expect(element.all(by.css('[ng-view] p')).first().getText()). toMatch(/Hello World!/); }); }); describe('Contact', function() { beforeEach(function() { browser.get('index.html#!/contact'); }); it('should render contact when user navigates to /contact', function() { expect(element.all(by.css('[ng-view] p')).first().getText()). toMatch(/This is the partial for Contact/); }); }); });
'use strict'; describe('My App', function() { it('should automatically redirect to /home when location hash/fragment is empty', function() { browser.get('index.html'); browser.sleep(3000); expect(browser.getLocationAbsUrl()).toMatch("/home"); }); describe('Home', function() { it('should render home when user navigates to /home', function() { expect(element.all(by.css('[ng-view] h3')).first().getText()). toMatch(/Home/); }); }); describe('Contact', function() { it('should render contact when user navigates to /contact', function() { browser.get('index.html#!/contact'); browser.sleep(3000); expect(element.all(by.css('[ng-view] h3')).first().getText()). toMatch(/Contact/); }); it('should write on inputs and read a success message', function() { var name = element(by.model('name')); name.clear(); name.sendKeys('Aitor'); browser.sleep(1000); var surname = element(by.model('surname')); surname.clear(); surname.sendKeys('Rodríguez'); browser.sleep(1000); var company = element(by.model('company')); company.clear(); company.sendKeys('Pisos.com'); browser.sleep(1000); element(by.css('.btn-primary.send-contact')).click(); expect(element.all(by.css('[ng-view] p')).first().getText()). toMatch(/Contact form sended successfully. Wait the reply now./); browser.sleep(5000); }); }); });
Add more tests cases and sleeps to view tests slowly
Add more tests cases and sleeps to view tests slowly
JavaScript
mit
AitorRodriguez990/angular-testing-examples,AitorRodriguez990/angular-testing-examples
--- +++ @@ -1,30 +1,48 @@ 'use strict'; describe('My App', function() { - it('should automatically redirect to /home when location hash/fragment is empty', function() { - browser.get('index.html'); - expect(browser.getLocationAbsUrl()).toMatch("/home"); - }); - - describe('Home', function() { - beforeEach(function() { - browser.get('index.html#!/home'); + it('should automatically redirect to /home when location hash/fragment is empty', function() { + browser.get('index.html'); + browser.sleep(3000); + expect(browser.getLocationAbsUrl()).toMatch("/home"); }); - it('should render home when user navigates to /home', function() { - expect(element.all(by.css('[ng-view] p')).first().getText()). - toMatch(/Hello World!/); - }); - }); - - describe('Contact', function() { - beforeEach(function() { - browser.get('index.html#!/contact'); + describe('Home', function() { + it('should render home when user navigates to /home', function() { + expect(element.all(by.css('[ng-view] h3')).first().getText()). + toMatch(/Home/); + }); }); - it('should render contact when user navigates to /contact', function() { - expect(element.all(by.css('[ng-view] p')).first().getText()). - toMatch(/This is the partial for Contact/); + describe('Contact', function() { + it('should render contact when user navigates to /contact', function() { + browser.get('index.html#!/contact'); + browser.sleep(3000); + expect(element.all(by.css('[ng-view] h3')).first().getText()). + toMatch(/Contact/); + }); + + it('should write on inputs and read a success message', function() { + var name = element(by.model('name')); + name.clear(); + name.sendKeys('Aitor'); + browser.sleep(1000); + + var surname = element(by.model('surname')); + surname.clear(); + surname.sendKeys('Rodríguez'); + browser.sleep(1000); + + var company = element(by.model('company')); + company.clear(); + company.sendKeys('Pisos.com'); + browser.sleep(1000); + + element(by.css('.btn-primary.send-contact')).click(); + expect(element.all(by.css('[ng-view] p')).first().getText()). + toMatch(/Contact form sended successfully. Wait the reply now./); + + browser.sleep(5000); + }); }); - }); });
f38ab411a600468a870a69eec657216091e8a046
src/shared/components/tooltip/util/checkEdges.js
src/shared/components/tooltip/util/checkEdges.js
export default function checkEdges(tooltipEl) { const tooltipBounds = tooltipEl.getBoundingClientRect(); const bodyBounds = document.body.getBoundingClientRect(); if (tooltipBounds.left === 0) { tooltipEl.style.left = `${parseInt(tooltipEl.style.left, 10) + 10}px`; } else if (tooltipBounds.left + tooltipBounds.width > bodyBounds.width - 10) { tooltipEl.style.left = `${parseInt(tooltipEl.style.left, 10) - 10}px`; } if (tooltipBounds.top === 0) { tooltipEl.style.top = `${parseInt(tooltipEl.style.top, 10) + 10}px`; } else if (tooltipBounds.top + tooltipBounds.height > bodyBounds.height - 10) { tooltipEl.style.top = `${parseInt(tooltipEl.style.top, 10) - 10}px`; } }
export default function checkEdges(tooltipEl) { const tooltipBounds = tooltipEl.getBoundingClientRect(); const bodyBounds = document.body.getBoundingClientRect(); if (tooltipBounds.left < 10) { tooltipEl.style.left = `${parseInt(tooltipEl.style.left, 10) + 10}px`; } else if (tooltipBounds.left + tooltipBounds.width > bodyBounds.width - 10) { tooltipEl.style.left = `${parseInt(tooltipEl.style.left, 10) - 10}px`; } if (tooltipBounds.top < 10) { tooltipEl.style.top = `${parseInt(tooltipEl.style.top, 10) + 10}px`; } else if (tooltipBounds.top + tooltipBounds.height > bodyBounds.height - 10) { tooltipEl.style.top = `${parseInt(tooltipEl.style.top, 10) - 10}px`; } }
Fix left & top edges for tooltips.
Fix left & top edges for tooltips.
JavaScript
mit
npms-io/npms-www,npms-io/npms-www
--- +++ @@ -2,13 +2,13 @@ const tooltipBounds = tooltipEl.getBoundingClientRect(); const bodyBounds = document.body.getBoundingClientRect(); - if (tooltipBounds.left === 0) { + if (tooltipBounds.left < 10) { tooltipEl.style.left = `${parseInt(tooltipEl.style.left, 10) + 10}px`; } else if (tooltipBounds.left + tooltipBounds.width > bodyBounds.width - 10) { tooltipEl.style.left = `${parseInt(tooltipEl.style.left, 10) - 10}px`; } - if (tooltipBounds.top === 0) { + if (tooltipBounds.top < 10) { tooltipEl.style.top = `${parseInt(tooltipEl.style.top, 10) + 10}px`; } else if (tooltipBounds.top + tooltipBounds.height > bodyBounds.height - 10) { tooltipEl.style.top = `${parseInt(tooltipEl.style.top, 10) - 10}px`;