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
2cdd4c7744783ee7dba209163a6d76c1b95f4df3
test/e2e/complainSpec.js
test/e2e/complainSpec.js
'use strict' var config = require('config') describe('/#/complain', function () { protractor.beforeEach.login({ email: 'admin@' + config.get('application.domain'), password: 'admin123' }) describe('challenge "uploadSize"', function () { it('should be possible to upload files greater 100 KB', function () { browser.executeScript(function () { var over100KB = Array.apply(null, new Array(10101)).map(String.prototype.valueOf, '1234567890') var blob = new Blob(over100KB, { type: 'application/pdf' }) var data = new FormData() data.append('file', blob, 'invalidSizeForClient.pdf') var request = new XMLHttpRequest() request.open('POST', '/file-upload') request.send(data) }) }) protractor.expect.challengeSolved({ challenge: 'Upload Size' }) }) describe('challenge "uploadType"', function () { it('should be possible to upload files with other extension than .pdf', function () { browser.executeScript(function () { var data = new FormData() var blob = new Blob([ 'test' ], { type: 'application/x-msdownload' }) data.append('file', blob, 'invalidTypeForClient.exe') var request = new XMLHttpRequest() request.open('POST', '/file-upload') request.send(data) }) }) protractor.expect.challengeSolved({ challenge: 'Upload Type' }) }) })
'use strict' var config = require('config') describe('/#/complain', function () { protractor.beforeEach.login({ email: 'admin@' + config.get('application.domain'), password: 'admin123' }) describe('challenge "uploadSize"', function () { it('should be possible to upload files greater 100 KB', function () { browser.executeScript(function () { var over100KB = Array.apply(null, new Array(11000)).map(String.prototype.valueOf, '1234567890') var blob = new Blob(over100KB, { type: 'application/pdf' }) var data = new FormData() data.append('file', blob, 'invalidSizeForClient.pdf') var request = new XMLHttpRequest() request.open('POST', '/file-upload') request.send(data) }) }) protractor.expect.challengeSolved({ challenge: 'Upload Size' }) }) describe('challenge "uploadType"', function () { it('should be possible to upload files with other extension than .pdf', function () { browser.executeScript(function () { var data = new FormData() var blob = new Blob([ 'test' ], { type: 'application/x-msdownload' }) data.append('file', blob, 'invalidTypeForClient.exe') var request = new XMLHttpRequest() request.open('POST', '/file-upload') request.send(data) }) }) protractor.expect.challengeSolved({ challenge: 'Upload Type' }) }) })
Increase file size for upload-size test (to prevent occasional failure on some machines)
Increase file size for upload-size test (to prevent occasional failure on some machines)
JavaScript
mit
bkimminich/juice-shop,bonze/juice-shop,bkimminich/juice-shop,oviroman/disertatieiap2017,bkimminich/juice-shop,m4l1c3/juice-shop,bkimminich/juice-shop,bonze/juice-shop,m4l1c3/juice-shop,bonze/juice-shop,oviroman/disertatieiap2017,bonze/juice-shop,bonze/juice-shop,oviroman/disertatieiap2017,bkimminich/juice-shop,m4l1c3/juice-shop,oviroman/disertatieiap2017,m4l1c3/juice-shop,bkimminich/juice-shop,m4l1c3/juice-shop,oviroman/disertatieiap2017
--- +++ @@ -8,7 +8,7 @@ describe('challenge "uploadSize"', function () { it('should be possible to upload files greater 100 KB', function () { browser.executeScript(function () { - var over100KB = Array.apply(null, new Array(10101)).map(String.prototype.valueOf, '1234567890') + var over100KB = Array.apply(null, new Array(11000)).map(String.prototype.valueOf, '1234567890') var blob = new Blob(over100KB, { type: 'application/pdf' }) var data = new FormData()
a029cc96bcb46bbd4ae0fa54646962a835e0d106
test/e2e/pages/invite.js
test/e2e/pages/invite.js
'use strict'; var Chance = require('chance'), chance = new Chance(); class InvitePage { constructor () { this.titleEl = element(by.css('.project-title')); this.message = chance.sentence(); this.AddPeopleBtn = element(by.css('.invite-button')); this.inviteBtn = element(by.css('[ng-click="inviteUsers()"]')); } get () { browser.wait(protractor.ExpectedConditions.visibilityOf(this.AddPeopleBtn)); this.AddPeopleBtn.click(); } invite (who) { this.inputInvite = element(by.css('.selectize-input input')); this.inviteOption = () => element(by.css('.create[data-selectable], .cachedOption[data-selectable]')); browser.wait(protractor.ExpectedConditions.visibilityOf(this.inputInvite)); this.inputInvite.click(); this.inputInvite.sendKeys(who); browser.wait(protractor.ExpectedConditions.presenceOf(this.inviteOption())); browser.wait(protractor.ExpectedConditions.visibilityOf(this.inviteOption())); this.inviteOption().click(); this.focusedInvite = element(by.css('.selectize-input input:focus')); // to blur input in email invite case. this.inputInvite.sendKeys(protractor.Key.TAB); browser.wait(protractor.ExpectedConditions.visibilityOf(this.inviteBtn)); return this.inviteBtn.click(); } } module.exports = InvitePage;
'use strict'; var Chance = require('chance'), chance = new Chance(); class InvitePage { constructor () { this.titleEl = element(by.css('.project-title')); this.message = chance.sentence(); this.AddPeopleBtn = element(by.css('.invite-button')); this.inviteBtn = element(by.css('[ng-click="inviteUsers()"]')); } get () { browser.wait(protractor.ExpectedConditions.visibilityOf(this.AddPeopleBtn)); this.AddPeopleBtn.click(); } invite (who) { this.inputInvite = element(by.css('.selectize-input input')); this.inviteOption = () => element(by.css('.create[data-selectable], .cachedOption[data-selectable]')); browser.wait(protractor.ExpectedConditions.visibilityOf(this.inputInvite)); this.inputInvite.click(); this.inputInvite.sendKeys(who); browser.wait(protractor.ExpectedConditions.presenceOf(this.inviteOption())); browser.wait(protractor.ExpectedConditions.visibilityOf(this.inviteOption())); this.inviteOption().click(); this.focusedInvite = element(by.css('.selectize-input input:focus')); // to blur input in email invite case. this.inputInvite.sendKeys(protractor.Key.TAB); browser.wait(protractor.ExpectedConditions.elementToBeClickable(this.inviteBtn)); return this.inviteBtn.click(); } } module.exports = InvitePage;
Use protractor EC.elementToBeClickable to fix the tests
Use protractor EC.elementToBeClickable to fix the tests
JavaScript
agpl-3.0
P2Pvalue/pear2pear,Grasia/teem,Grasia/teem,P2Pvalue/teem,Grasia/teem,P2Pvalue/teem,P2Pvalue/pear2pear,P2Pvalue/teem
--- +++ @@ -46,7 +46,7 @@ // to blur input in email invite case. this.inputInvite.sendKeys(protractor.Key.TAB); - browser.wait(protractor.ExpectedConditions.visibilityOf(this.inviteBtn)); + browser.wait(protractor.ExpectedConditions.elementToBeClickable(this.inviteBtn)); return this.inviteBtn.click(); }
de1bdcd5b4a8f7336fbbe3b42bbf67a3bca2d1f0
src/components/posts_index.js
src/components/posts_index.js
import React, { Component } from 'react'; class PostsIndex extends Component { render() { return ( <div> Posts Index </div> ); } } export default PostsIndex;
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { fetchPosts } from '../actions'; class PostsIndex extends Component { componentDidMount() { this.props.fetchPosts(); } render() { return ( <div> Posts Index </div> ); } } export default connect(null, { fetchPosts })(PostsIndex);
Connect fetchPosts action creator to PostsIndex
Connect fetchPosts action creator to PostsIndex
JavaScript
mit
heatherpark/blog,heatherpark/blog
--- +++ @@ -1,6 +1,12 @@ import React, { Component } from 'react'; +import { connect } from 'react-redux'; +import { fetchPosts } from '../actions'; class PostsIndex extends Component { + componentDidMount() { + this.props.fetchPosts(); + } + render() { return ( <div> @@ -10,4 +16,5 @@ } } -export default PostsIndex; +export default connect(null, { fetchPosts })(PostsIndex); +
640b87a80ce137fceab5410c5e431204e8e0aca0
src/Atok_properties.js
src/Atok_properties.js
// Public properties this.buffer = null this.length = 0 this.offset = 0 this.markedOffset = -1 // Flag indicating whether the buffer should be kept when write() ends // Private properties this._tokenizing = false this._ruleIndex = 0 this._resetRuleIndex = false this._stringDecoder = this._encoding ? new StringDecoder(this._encoding) : null this._rulesToResolve = false this._group = -1 this._groupStart = 0 this._groupEnd = 0 this._groupStartPrev = [] //if(keepRules) if (!keepRules) { //endif this.currentRule = null // Name of the current rule this._rules = [] // Rules to be checked against this._defaultHandler = null // Matched token default handler this._savedRules = {} // Saved rules //if(keepRules) } //endif
// Public properties this.buffer = null this.length = 0 this.offset = 0 this.markedOffset = -1 // Flag indicating whether the buffer should be kept when write() ends // Private properties this._tokenizing = false this._ruleIndex = 0 this._resetRuleIndex = false this._stringDecoder = new StringDecoder(this._encoding) this._rulesToResolve = false this._group = -1 this._groupStart = 0 this._groupEnd = 0 this._groupStartPrev = [] //if(keepRules) if (!keepRules) { //endif this.currentRule = null // Name of the current rule this._rules = [] // Rules to be checked against this._defaultHandler = null // Matched token default handler this._savedRules = {} // Saved rules //if(keepRules) } //endif
Set string decoder by default
Set string decoder by default
JavaScript
mit
pierrec/node-atok
--- +++ @@ -8,7 +8,7 @@ this._tokenizing = false this._ruleIndex = 0 this._resetRuleIndex = false - this._stringDecoder = this._encoding ? new StringDecoder(this._encoding) : null + this._stringDecoder = new StringDecoder(this._encoding) this._rulesToResolve = false this._group = -1 this._groupStart = 0
29652896b0d2bccaa6b74cc11ff1ce2f154af330
test/specs/4loop.spec.js
test/specs/4loop.spec.js
const FourLoop = require('../../index'); describe('4loop', () => { it('callback executed on obj', (expect) => { let wasCallbackHit = false; const callback = function callback(){ wasCallbackHit = true; }; FourLoop({ cats: 'rule' }, callback); expect(wasCallbackHit).toBe(true); }); it('callback executed on array', (expect) => { let wasCallbackHit = false; const callback = function callback(){ wasCallbackHit = true; }; FourLoop(['cats', 'rule'], callback); expect(wasCallbackHit).toBe(true); }); it('callback executed on number', (expect) => { let wasCallbackHit = false; const callback = function callback(){ wasCallbackHit = true; }; FourLoop(['cats', 'rule'].length, callback); expect(wasCallbackHit).toBe(true); }); });
const FourLoop = require('../../index'); describe('4loop', () => { describe('ensures callbacks were executed', () => { it('called the callback executed on obj', (expect) => { let wasCallbackHit = false; const callback = function callback(){ wasCallbackHit = true; }; FourLoop({ cats: 'rule' }, callback); expect(wasCallbackHit).toBe(true); }); it('called the callback executed on array', (expect) => { let wasCallbackHit = false; const callback = function callback(){ wasCallbackHit = true; }; FourLoop(['cats', 'rule'], callback); expect(wasCallbackHit).toBe(true); }); it('called the callback executed on number', (expect) => { let wasCallbackHit = false; const callback = function callback(){ wasCallbackHit = true; }; FourLoop(['cats', 'rule'].length, callback); expect(wasCallbackHit).toBe(true); }); it('called the callback executed on set', (expect) => { const mySet = new Set(['foo', 'bar', { baz: 'cats' }]); let wasCallbackHit = false; const callback = function callback(){ wasCallbackHit = true; }; FourLoop(mySet, callback); expect(wasCallbackHit).toBe(true); }); it('called the callback executed on map', (expect) => { const myMap = new Map([['foo', 'bar'], ['baz', 'cats'], ['dogs', undefined]]); let wasCallbackHit = false; const callback = function callback(){ wasCallbackHit = true; }; FourLoop(myMap, callback); expect(wasCallbackHit).toBe(true); }); }); });
Add callback tests for map and sets
RB: Add callback tests for map and sets
JavaScript
mit
raymondborkowski/4loop
--- +++ @@ -1,28 +1,52 @@ const FourLoop = require('../../index'); describe('4loop', () => { - it('callback executed on obj', (expect) => { - let wasCallbackHit = false; - const callback = function callback(){ - wasCallbackHit = true; - }; - FourLoop({ cats: 'rule' }, callback); - expect(wasCallbackHit).toBe(true); - }); - it('callback executed on array', (expect) => { - let wasCallbackHit = false; - const callback = function callback(){ - wasCallbackHit = true; - }; - FourLoop(['cats', 'rule'], callback); - expect(wasCallbackHit).toBe(true); - }); - it('callback executed on number', (expect) => { - let wasCallbackHit = false; - const callback = function callback(){ - wasCallbackHit = true; - }; - FourLoop(['cats', 'rule'].length, callback); - expect(wasCallbackHit).toBe(true); + describe('ensures callbacks were executed', () => { + it('called the callback executed on obj', (expect) => { + let wasCallbackHit = false; + const callback = function callback(){ + wasCallbackHit = true; + }; + FourLoop({ cats: 'rule' }, callback); + expect(wasCallbackHit).toBe(true); + }); + it('called the callback executed on array', (expect) => { + let wasCallbackHit = false; + const callback = function callback(){ + wasCallbackHit = true; + }; + FourLoop(['cats', 'rule'], callback); + expect(wasCallbackHit).toBe(true); + }); + it('called the callback executed on number', (expect) => { + let wasCallbackHit = false; + const callback = function callback(){ + wasCallbackHit = true; + }; + FourLoop(['cats', 'rule'].length, callback); + expect(wasCallbackHit).toBe(true); + }); + it('called the callback executed on set', (expect) => { + const mySet = new Set(['foo', 'bar', { baz: 'cats' }]); + let wasCallbackHit = false; + + const callback = function callback(){ + wasCallbackHit = true; + }; + + FourLoop(mySet, callback); + expect(wasCallbackHit).toBe(true); + }); + it('called the callback executed on map', (expect) => { + const myMap = new Map([['foo', 'bar'], ['baz', 'cats'], ['dogs', undefined]]); + let wasCallbackHit = false; + + const callback = function callback(){ + wasCallbackHit = true; + }; + + FourLoop(myMap, callback); + expect(wasCallbackHit).toBe(true); + }); }); });
bcf5db2ca80da33637deafb80cdefdc813f29c80
src/SMS/drivers/Log.js
src/SMS/drivers/Log.js
const CatLog = require('cat-log'); const logger = new CatLog('adonis:sms'); class Log { constructor (Config) { this.config = Config; } send (message, config) { if (config) this.config = config; logger.info(`SMS log driver send. from=${message.from} to=${message.to} text=${message.text}`); return Promise.resolve(); } } module.exports = Log;
const CatLog = require('cat-log'); const logger = new CatLog('adonis:sms'); class Log { constructor (Config) { this.config = Config; } send (message, config) { if (config) this.config = config; logger.info(`SMS log driver send. from=${message.from} to=${message.to}`); logger.info('β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”'); logger.info(message.text); logger.info('β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”'); return Promise.resolve(); } } module.exports = Log;
Change log output format for better legibility
Change log output format for better legibility
JavaScript
mit
nrempel/adonis-sms
--- +++ @@ -8,7 +8,10 @@ send (message, config) { if (config) this.config = config; - logger.info(`SMS log driver send. from=${message.from} to=${message.to} text=${message.text}`); + logger.info(`SMS log driver send. from=${message.from} to=${message.to}`); + logger.info('β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”'); + logger.info(message.text); + logger.info('β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”'); return Promise.resolve(); } }
158b0264092a458d26387a3c5b0a92253f7ee49a
knexfile.js
knexfile.js
import { merge } from 'lodash' require('dotenv').load() if (!process.env.DATABASE_URL) { throw new Error('process.env.DATABASE_URL must be set') } const url = require('url').parse(process.env.DATABASE_URL) var user, password if (url.auth) { const i = url.auth.indexOf(':') user = url.auth.slice(0, i) password = url.auth.slice(i + 1) } const defaults = { client: 'pg', connection: { host: url.hostname, port: url.port, user: user, password: password, database: url.pathname.substring(1) }, migrations: { tableName: 'knex_migrations' } } module.exports = { test: defaults, development: defaults, staging: defaults, production: merge({connection: {ssl: true}}, defaults) }
require('dotenv').load() // LEJ: ES6 import not working for a commandline run of knex, // replacing with require // (e.g. knex seed:run) // // import { merge } from 'lodash' const _ = require('lodash') const merge = _.merge if (!process.env.DATABASE_URL) { throw new Error('process.env.DATABASE_URL must be set') } const url = require('url').parse(process.env.DATABASE_URL) var user, password if (url.auth) { const i = url.auth.indexOf(':') user = url.auth.slice(0, i) password = url.auth.slice(i + 1) } const defaults = { client: 'pg', connection: { host: url.hostname, port: url.port, user: user, password: password, database: url.pathname.substring(1) }, migrations: { tableName: 'knex_migrations' } } module.exports = { test: defaults, development: defaults, staging: defaults, production: merge({connection: {ssl: true}}, defaults) }
Make seeds runnable on CLI
Make seeds runnable on CLI
JavaScript
apache-2.0
Hylozoic/hylo-node,Hylozoic/hylo-node
--- +++ @@ -1,5 +1,12 @@ -import { merge } from 'lodash' require('dotenv').load() + +// LEJ: ES6 import not working for a commandline run of knex, +// replacing with require +// (e.g. knex seed:run) +// +// import { merge } from 'lodash' +const _ = require('lodash') +const merge = _.merge if (!process.env.DATABASE_URL) { throw new Error('process.env.DATABASE_URL must be set')
cf14244c4afcad892177ae0457ee256c0866a35e
share/spice/flash_version/flash_version.js
share/spice/flash_version/flash_version.js
(function(env) { "use strict"; env.ddg_spice_flash_version = function() { if(!FlashDetect) { return Spice.failed('flash_version'); } Spice.add({ data: { installed: FlashDetect.installed, raw: FlashDetect.raw }, id: 'flash_version', name: 'Software', meta: { sourceName: 'Adobe', sourceUrl: 'https://get.adobe.com/flashplayer/', sourceIcon: true }, templates: { group: 'base', options: { content: Spice.flash_version.content, moreAt: true } } }); }; }(this));
(function(env) { "use strict"; env.ddg_spice_flash_version = function() { DDG.require('flash_detect.js', function(){ if(!FlashDetect) { return Spice.failed('flash_version'); } Spice.add({ data: { installed: FlashDetect.installed, raw: FlashDetect.raw }, id: 'flash_version', name: 'Software', meta: { sourceName: 'Adobe', sourceUrl: 'https://get.adobe.com/flashplayer/', sourceIcon: true }, templates: { group: 'base', options: { content: Spice.flash_version.content, moreAt: true } } }); }); }; }(this));
Use DDG.require for 'flash_detect.js' file
FlashVersion: Use DDG.require for 'flash_detect.js' file
JavaScript
apache-2.0
whalenrp/zeroclickinfo-spice,deserted/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,deserted/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,deserted/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,imwally/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,lerna/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,levaly/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,P71/zeroclickinfo-spice,levaly/zeroclickinfo-spice,soleo/zeroclickinfo-spice,imwally/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,levaly/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,soleo/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,lernae/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,imwally/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,P71/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,lerna/zeroclickinfo-spice,imwally/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,deserted/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,soleo/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,deserted/zeroclickinfo-spice,lerna/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,soleo/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,lernae/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,soleo/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,lerna/zeroclickinfo-spice,soleo/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,P71/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,levaly/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,P71/zeroclickinfo-spice,imwally/zeroclickinfo-spice,lernae/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,deserted/zeroclickinfo-spice,lerna/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,levaly/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,lernae/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,lernae/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,levaly/zeroclickinfo-spice,lernae/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice
--- +++ @@ -3,29 +3,33 @@ env.ddg_spice_flash_version = function() { - if(!FlashDetect) { - return Spice.failed('flash_version'); - } - - Spice.add({ - data: { - installed: FlashDetect.installed, - raw: FlashDetect.raw - }, - id: 'flash_version', - name: 'Software', - meta: { - sourceName: 'Adobe', - sourceUrl: 'https://get.adobe.com/flashplayer/', - sourceIcon: true - }, - templates: { - group: 'base', - options: { - content: Spice.flash_version.content, - moreAt: true + DDG.require('flash_detect.js', function(){ + + if(!FlashDetect) { + return Spice.failed('flash_version'); + } + + Spice.add({ + data: { + installed: FlashDetect.installed, + raw: FlashDetect.raw + }, + id: 'flash_version', + name: 'Software', + meta: { + sourceName: 'Adobe', + sourceUrl: 'https://get.adobe.com/flashplayer/', + sourceIcon: true + }, + templates: { + group: 'base', + options: { + content: Spice.flash_version.content, + moreAt: true + } } - } + }); + }); }; }(this));
4b97b778be2513076d4e0820b8aa807b549372b6
basic/scripts/presets.js
basic/scripts/presets.js
/** * Basic presets: swiss direct matchings, round similar to chess, and ko * with a matched cadrage. Simple rankings * * @return Presets * @author Erik E. Lorenz <erik@tuvero.de> * @license MIT License * @see LICENSE */ define(function() { var Presets; Presets = { target: 'basic', systems: { swiss: { ranking: ['wins', 'headtohead', 'saldo'], mode: 'ranks' }, ko: { mode: 'matched' }, round: { ranking: ['wins', 'sonneborn', 'headtohead', 'points'] } }, ranking: { components: ['buchholz', 'finebuchholz', 'points', 'saldo', 'sonneborn', 'numgames', 'wins', 'headtohead', 'threepoint'] }, registration: { minteamsize: 1, maxteamsize: 1, teamsizeicon: false }, names: { playernameurl: '', dbplayername: 'tuverobasicplayers', apitoken: 'apitoken', teamsfile: 'tuvero-anmeldungen.txt' } }; return Presets; });
/** * Basic presets: swiss direct matchings, round similar to chess, and ko * with a matched cadrage. Simple rankings * * @return Presets * @author Erik E. Lorenz <erik@tuvero.de> * @license MIT License * @see LICENSE */ define(function() { var Presets; Presets = { target: 'basic', systems: { swiss: { ranking: ['wins', 'headtohead', 'saldo'], mode: 'ranks' }, ko: { mode: 'matched' }, round: { ranking: ['wins', 'sonneborn', 'headtohead', 'points'] } }, ranking: { components: ['buchholz', 'finebuchholz', 'points', 'saldo', 'sonneborn', 'numgames', 'wins', 'headtohead', 'threepoint', 'twopoint'] }, registration: { minteamsize: 1, maxteamsize: 1, teamsizeicon: false }, names: { playernameurl: '', dbplayername: 'tuverobasicplayers', apitoken: 'apitoken', teamsfile: 'tuvero-anmeldungen.txt' } }; return Presets; });
Enable twopoint in Tuvero Basic
Enable twopoint in Tuvero Basic
JavaScript
mit
elor/tuvero
--- +++ @@ -27,7 +27,7 @@ }, ranking: { components: ['buchholz', 'finebuchholz', 'points', 'saldo', 'sonneborn', - 'numgames', 'wins', 'headtohead', 'threepoint'] + 'numgames', 'wins', 'headtohead', 'threepoint', 'twopoint'] }, registration: { minteamsize: 1,
a7505099d6cd97bbe9737abeb9cf45a9d0e4e0da
src/core/AudioletDestination.js
src/core/AudioletDestination.js
/** * @depends AudioletGroup.js */ var AudioletDestination = new Class({ Extends: AudioletGroup, initialize: function(audiolet, sampleRate, numberOfChannels, bufferSize) { AudioletGroup.prototype.initialize.apply(this, [audiolet, 1, 0]); this.device = new AudioletDevice(audiolet, sampleRate, numberOfChannels, bufferSize); audiolet.device = this.device; // Shortcut this.scheduler = new Scheduler(audiolet); audiolet.scheduler = this.scheduler; // Shortcut this.blockSizeLimiter = new BlockSizeLimiter(audiolet, Math.pow(2, 12)); audiolet.blockSizeLimiter = this.blockSizeLimiter; // Shortcut this.upMixer = new UpMixer(audiolet, this.device.numberOfChannels); this.inputs[0].connect(this.blockSizeLimiter); this.blockSizeLimiter.connect(this.scheduler); this.scheduler.connect(this.upMixer); this.upMixer.connect(this.device); } });
/** * @depends AudioletGroup.js */ var AudioletDestination = new Class({ Extends: AudioletGroup, initialize: function(audiolet, sampleRate, numberOfChannels, bufferSize) { AudioletGroup.prototype.initialize.apply(this, [audiolet, 1, 0]); this.device = new AudioletDevice(audiolet, sampleRate, numberOfChannels, bufferSize); audiolet.device = this.device; // Shortcut this.scheduler = new Scheduler(audiolet); audiolet.scheduler = this.scheduler; // Shortcut this.blockSizeLimiter = new BlockSizeLimiter(audiolet, Math.pow(2, 15)); audiolet.blockSizeLimiter = this.blockSizeLimiter; // Shortcut this.upMixer = new UpMixer(audiolet, this.device.numberOfChannels); this.inputs[0].connect(this.blockSizeLimiter); this.blockSizeLimiter.connect(this.scheduler); this.scheduler.connect(this.upMixer); this.upMixer.connect(this.device); } });
Make maximum buffer size larger. Should perform a little better, at the expense of higher memory usage, and a higher minimum delay length.
Make maximum buffer size larger. Should perform a little better, at the expense of higher memory usage, and a higher minimum delay length.
JavaScript
apache-2.0
Kosar79/Audiolet,Kosar79/Audiolet,mcanthony/Audiolet,kn0ll/Audiolet,oampo/Audiolet,oampo/Audiolet,bobby-brennan/Audiolet,mcanthony/Audiolet,bobby-brennan/Audiolet,kn0ll/Audiolet,Kosar79/Audiolet
--- +++ @@ -14,7 +14,7 @@ audiolet.scheduler = this.scheduler; // Shortcut this.blockSizeLimiter = new BlockSizeLimiter(audiolet, - Math.pow(2, 12)); + Math.pow(2, 15)); audiolet.blockSizeLimiter = this.blockSizeLimiter; // Shortcut this.upMixer = new UpMixer(audiolet, this.device.numberOfChannels);
b3760d224632e989dfdeb0b57755d30e87b2bbf2
package.js
package.js
Package.describe({ name: 'sanjo:karma', summary: 'Integrates Karma into Meteor', version: '1.6.1', git: 'https://github.com/Sanjo/meteor-karma.git' }) Npm.depends({ 'karma': '0.13.3', 'karma-chrome-launcher': '0.2.0', 'karma-firefox-launcher': '0.1.6', 'karma-jasmine': '0.3.6', 'karma-babel-preprocessor': '5.2.1', 'karma-coffee-preprocessor': '0.3.0', 'karma-phantomjs-launcher': '0.2.0', 'karma-sauce-launcher': '0.2.14', 'fs-extra': '0.22.1' }) Package.onUse(function (api) { api.versionsFrom('1.0.3.2') api.use('coffeescript', 'server') api.use('underscore', 'server') api.use('check', 'server') api.use('practicalmeteor:loglevel@1.1.0_2', 'server') api.use('sanjo:meteor-files-helpers@1.1.0_2', 'server') api.use('sanjo:long-running-child-process@1.0.2', 'server') api.addFiles('main.js', 'server') api.export('Karma') api.export('KarmaInternals') })
Package.describe({ name: 'sanjo:karma', summary: 'Integrates Karma into Meteor', version: '1.6.1', git: 'https://github.com/Sanjo/meteor-karma.git' }) Npm.depends({ 'karma': '0.13.3', 'karma-chrome-launcher': '0.2.0', 'karma-firefox-launcher': '0.1.6', 'karma-jasmine': '0.3.6', 'karma-babel-preprocessor': '5.2.1', 'karma-coffee-preprocessor': '0.3.0', 'karma-phantomjs-launcher': '0.2.0', 'karma-sauce-launcher': '0.2.14', 'fs-extra': '0.22.1' }) Package.onUse(function (api) { api.versionsFrom('1.1.0.2') api.use('practicalmeteor:loglevel@1.1.0_3', 'server') api.use('sanjo:meteor-files-helpers@1.1.0_6', 'server') api.use('sanjo:long-running-child-process@1.1.1', 'server') api.addFiles('main.js', 'server') api.export('Karma') api.export('KarmaInternals') })
Remove unused dependencies and updates used dependencies
Remove unused dependencies and updates used dependencies
JavaScript
mit
michelalbers/meteor-karma,Sanjo/meteor-karma
--- +++ @@ -18,13 +18,10 @@ }) Package.onUse(function (api) { - api.versionsFrom('1.0.3.2') - api.use('coffeescript', 'server') - api.use('underscore', 'server') - api.use('check', 'server') - api.use('practicalmeteor:loglevel@1.1.0_2', 'server') - api.use('sanjo:meteor-files-helpers@1.1.0_2', 'server') - api.use('sanjo:long-running-child-process@1.0.2', 'server') + api.versionsFrom('1.1.0.2') + api.use('practicalmeteor:loglevel@1.1.0_3', 'server') + api.use('sanjo:meteor-files-helpers@1.1.0_6', 'server') + api.use('sanjo:long-running-child-process@1.1.1', 'server') api.addFiles('main.js', 'server')
12f58924dc7f0dc6644671a0f39d1df3678c0681
lib/vain.js
lib/vain.js
'use strict'; /***** * Vain * * A view-first templating engine for Node.js. *****/ var jsdom = require('jsdom'), $ = require('jquery')(jsdom.jsdom().createWindow()), snippetRegistry = {}; /** * Register a snippet in the snippet registry. **/ exports.registerSnippet = function(snippetName, snippetFn) { snippetRegistry[snippetName] = snippetFn; }; /** * Process the given markup. **/ exports.render = function(input, options, fn) { if ('function' === typeof options) { fn = options; options = undefined; } options = options || {}; var $template = $("<div />").append(input), snippetHandlers = options.snippets || {}; $.extend(snippetHandlers, snippetRegistry); $template.find("[data-vain]").each(function() { var snippetName = $(this).data('vain'); if ('function' === typeof snippetHandlers[snippetName]) { snippetHandlers[snippetName]($, this); } $(this).removeAttr("data-vain"); }); return $template.html(); }; /** * Process a given file. **/ exports.renderFile = function(path, options, fn) { // }; // Express support. exports.__express = exports.renderFile;
'use strict'; /***** * Vain * * A view-first templating engine for Node.js. *****/ var jsdom = require('jsdom'), $ = require('jquery')(jsdom.jsdom().createWindow()), snippetRegistry = {}; /** * Register a snippet in the snippet registry. **/ exports.registerSnippet = function(snippetName, snippetFn) { snippetRegistry[snippetName] = snippetFn; }; /** * Process the given markup. **/ exports.render = function(input, options, fn) { if ('function' === typeof options) { fn = options; options = undefined; } options = options || {}; if ('function' === typeof fn) { var result; try { result = exports.render(input, options); } catch (exception) { return fn(exception); } return fn(null, result); } var $template = $("<div />").append(input), snippetHandlers = options.snippets || {}; $.extend(snippetHandlers, snippetRegistry); $template.find("[data-vain]").each(function() { var snippetName = $(this).data('vain'); if ('function' === typeof snippetHandlers[snippetName]) { snippetHandlers[snippetName]($, this); } $(this).removeAttr("data-vain"); }); return $template.html(); }; /** * Process a given file. **/ exports.renderFile = function(path, options, fn) { // }; // Express support. exports.__express = exports.renderFile;
Add handling of fn callback for render.
Add handling of fn callback for render.
JavaScript
apache-2.0
farmdawgnation/vain
--- +++ @@ -27,6 +27,18 @@ options = options || {}; + if ('function' === typeof fn) { + var result; + + try { + result = exports.render(input, options); + } catch (exception) { + return fn(exception); + } + + return fn(null, result); + } + var $template = $("<div />").append(input), snippetHandlers = options.snippets || {}; $.extend(snippetHandlers, snippetRegistry);
6cfd4dcee23e66d1b454a53d572abe252f7af5ed
addon/components/bootstrap-datepicker.js
addon/components/bootstrap-datepicker.js
import Ember from 'ember'; export default Ember.Component.extend({ tagName: 'input', setupBootstrapDatepicker: function() { var self = this, element = this.$(), value = this.get('value'); element. datepicker({ autoclose: this.get('autoclose') || true, format: this.get('format') || 'dd.mm.yyyy', weekStart: this.get('weekStart') || 1, todayHighlight: this.get('todayHighlight') || false, todayBtn: this.get('todayBtn') || false, language: this.get('language') || 'en' }). on('changeDate', function(event) { Ember.run(function() { self.didSelectDate(event); }); }); if (value) { element.datepicker('setDate', new Date(value)); }; }.on('didInsertElement'), teardownBootstrapDatepicker: function() { // no-op }.on('willDestroyElement'), didSelectDate: function(event) { var date = this.$().datepicker('getUTCDate'); this.set('value', date.toISOString()); } });
import Ember from 'ember'; export default Ember.TextField.extend({ setupBootstrapDatepicker: function() { var self = this, element = this.$(), value = this.get('value'); element. datepicker({ autoclose: this.get('autoclose') || true, format: this.get('format') || 'dd.mm.yyyy', weekStart: this.get('weekStart') || 1, todayHighlight: this.get('todayHighlight') || false, todayBtn: this.get('todayBtn') || false, language: this.get('language') || 'en' }). on('changeDate', function(event) { Ember.run(function() { self.didSelectDate(event); }); }); if (value) { element.datepicker('setDate', new Date(value)); }; }.on('didInsertElement'), teardownBootstrapDatepicker: function() { // no-op }.on('willDestroyElement'), didSelectDate: function(event) { var date = this.$().datepicker('getUTCDate'); this.set('value', date.toISOString()); } });
Use Ember.TextField instead of generic Ember.Component
Use Ember.TextField instead of generic Ember.Component Datepicker is an input field, so it much better to use Ember.TextField. It automatically gives attributes like `name`, `size`, `placeholder` and etc. This also closes #2
JavaScript
mit
aravindranath/ember-cli-datepicker,aravindranath/ember-cli-datepicker,Hanastaroth/ember-cli-bootstrap-datepicker,aldhsu/ember-cli-bootstrap-datepicker,NichenLg/ember-cli-bootstrap-datepicker,jesenko/ember-cli-bootstrap-datepicker,aldhsu/ember-cli-bootstrap-datepicker,topaxi/ember-bootstrap-datepicker,jesenko/ember-cli-bootstrap-datepicker,lazybensch/ember-cli-bootstrap-datepicker,maladon/ember-cli-bootstrap-datepicker,maladon/ember-cli-bootstrap-datepicker,Hanastaroth/ember-cli-bootstrap-datepicker,NichenLg/ember-cli-bootstrap-datepicker,soulim/ember-cli-bootstrap-datepicker,lazybensch/ember-cli-bootstrap-datepicker,aravindranath/ember-cli-datepicker,jesenko/ember-cli-bootstrap-datepicker,jelhan/ember-cli-bootstrap-datepicker,NichenLg/ember-cli-bootstrap-datepicker,aldhsu/ember-cli-bootstrap-datepicker,maladon/ember-cli-bootstrap-datepicker,soulim/ember-cli-bootstrap-datepicker,topaxi/ember-bootstrap-datepicker,jelhan/ember-cli-bootstrap-datepicker,jelhan/ember-cli-bootstrap-datepicker,soulim/ember-cli-bootstrap-datepicker,lazybensch/ember-cli-bootstrap-datepicker,Hanastaroth/ember-cli-bootstrap-datepicker
--- +++ @@ -1,8 +1,6 @@ import Ember from 'ember'; -export default Ember.Component.extend({ - tagName: 'input', - +export default Ember.TextField.extend({ setupBootstrapDatepicker: function() { var self = this, element = this.$(),
e725c9cd3df163549efda41a957a18e8ef3dba44
src/plugins/canonize/index.js
src/plugins/canonize/index.js
const { next, hookEnd, call } = require('hooter/effects') function canonize(command) { let { fullName, config, options } = command if (!config) { return command } command = Object.assign({}, command) command.outputName = fullName.slice(0, -1).concat(config.name) if (options && options.length) { command.options = options.map((option) => { let outputName = option.config ? option.config.name : option.name return Object.assign({}, option, { outputName }) }) } return command } function* processHandler(_, command, ...args) { command = yield call(canonize, command) return yield next(_, command, ...args) } module.exports = function* canonizePlugin() { yield hookEnd('process', processHandler) }
const { next, hookEnd, call } = require('hooter/effects') function canonize(command) { let { fullName, config, options } = command if (config) { command = Object.assign({}, command) command.outputName = fullName.slice(0, -1).concat(config.name) } if (options && options.length) { command = config ? command : Object.assign({}, command) command.options = options.map((option) => { if (!option.config) { return option } return Object.assign({}, option, { outputName: option.config.name, }) }) } return command } function* processHandler(_, command, ...args) { command = yield call(canonize, command) return yield next(_, command, ...args) } module.exports = function* canonizePlugin() { yield hookEnd('process', processHandler) }
Rework canonize plugin so that it doesn't set output names when no config
Rework canonize plugin so that it doesn't set output names when no config
JavaScript
isc
alex-shnayder/comanche
--- +++ @@ -4,17 +4,21 @@ function canonize(command) { let { fullName, config, options } = command - if (!config) { - return command + if (config) { + command = Object.assign({}, command) + command.outputName = fullName.slice(0, -1).concat(config.name) } - command = Object.assign({}, command) - command.outputName = fullName.slice(0, -1).concat(config.name) + if (options && options.length) { + command = config ? command : Object.assign({}, command) + command.options = options.map((option) => { + if (!option.config) { + return option + } - if (options && options.length) { - command.options = options.map((option) => { - let outputName = option.config ? option.config.name : option.name - return Object.assign({}, option, { outputName }) + return Object.assign({}, option, { + outputName: option.config.name, + }) }) }
0c1b581a46c5655b111ef7027ce2076bc4fe6162
src/test/data/SimpleTestModelSchema.js
src/test/data/SimpleTestModelSchema.js
define([ ], function ( ) { return { "id": "TestData/SimpleTestModelSchema", "description": "A simple model for testing", "$schema": "http://json-schema.org/draft-03/schema", "type": "object", "properties": { "modelNumber": { "type": "string", "maxLength": 4, "description": "The number of the model.", "required": true }, "optionalprop": { "type": "string", "description": "an optional property.", "optional": true } } }; });
define({ "id": "TestData/SimpleTestModelSchema", "description": "A simple model for testing", "$schema": "http://json-schema.org/draft-03/schema", "type": "object", "properties": { "modelNumber": { "type": "string", "maxLength": 4, "description": "The number of the model.", "pattern": "[0-9]", "required": true }, "optionalprop": { "type": "string", "description": "an optional property." } } });
Add pattern validation to test model.
Add pattern validation to test model.
JavaScript
apache-2.0
atsid/schematic-js,atsid/schematic-js
--- +++ @@ -1,24 +1,19 @@ -define([ -], function ( -) { - - return { - "id": "TestData/SimpleTestModelSchema", - "description": "A simple model for testing", - "$schema": "http://json-schema.org/draft-03/schema", - "type": "object", - "properties": { - "modelNumber": { - "type": "string", - "maxLength": 4, - "description": "The number of the model.", - "required": true - }, - "optionalprop": { - "type": "string", - "description": "an optional property.", - "optional": true - } +define({ + "id": "TestData/SimpleTestModelSchema", + "description": "A simple model for testing", + "$schema": "http://json-schema.org/draft-03/schema", + "type": "object", + "properties": { + "modelNumber": { + "type": "string", + "maxLength": 4, + "description": "The number of the model.", + "pattern": "[0-9]", + "required": true + }, + "optionalprop": { + "type": "string", + "description": "an optional property." } - }; + } });
53ecb8eca3b8ecff7da77ece3b81bedf91d74674
config/webpack.config.js
config/webpack.config.js
const webpack = require('webpack'), HtmlWebpackPlugin = require('html-webpack-plugin'), path = require('path'), babelCfg = require("./babel.config"), paths = { root: path.join(__dirname, '../'), app: path.join(__dirname, '../app/'), dist: path.join(__dirname, '../dist/') }; module.exports = { resolve: { alias: { cx: paths.root + 'node_modules/cx-core/src/', app: paths.app //uncomment the line below to alias cx-react to cx-preact or some other React replacement library //'cx-react': 'cx-preact', } }, module: { loaders: [{ test: /\.js$/, //add here any ES6 based library include: /(app|intl-io|cx-core|cx|redux|redux-thunk|lodash)/, loader: 'babel', query: babelCfg }] }, entry: { vendor: ['cx-react'], app: paths.app + 'index.js' }, output: { path: paths.dist, filename: "[name].js" }, plugins: [ new webpack.optimize.CommonsChunkPlugin({ names: ["vendor"], minChunks: Infinity }), new HtmlWebpackPlugin({ template: paths.app + 'index.html', hash: true }) ] };
const webpack = require('webpack'), HtmlWebpackPlugin = require('html-webpack-plugin'), path = require('path'), babelCfg = require("./babel.config"), paths = { root: path.join(__dirname, '../'), app: path.join(__dirname, '../app/'), dist: path.join(__dirname, '../dist/') }; module.exports = { resolve: { alias: { cx: paths.root + 'node_modules/cx-core/src/', app: paths.app //uncomment the line below to alias cx-react to cx-preact or some other React replacement library //'cx-react': 'cx-preact', } }, module: { loaders: [{ test: /\.js$/, //add here any ES6 based library include: /(app|intl-io|cx-core|cx|redux|redux-thunk|lodash)/, loader: 'babel', query: babelCfg }] }, entry: { //vendor: ['cx-react'], app: paths.app + 'index.js' }, output: { path: paths.dist, filename: "[name].js" }, plugins: [ // new webpack.optimize.CommonsChunkPlugin({ // names: ["vendor"], // minChunks: Infinity // }), new HtmlWebpackPlugin({ template: paths.app + 'index.html', hash: true }) ] };
Use single dist js file
Use single dist js file
JavaScript
mit
mstijak/tdo,mstijak/tdo,mstijak/tdo
--- +++ @@ -28,7 +28,7 @@ }] }, entry: { - vendor: ['cx-react'], + //vendor: ['cx-react'], app: paths.app + 'index.js' }, output: { @@ -36,10 +36,10 @@ filename: "[name].js" }, plugins: [ - new webpack.optimize.CommonsChunkPlugin({ - names: ["vendor"], - minChunks: Infinity - }), + // new webpack.optimize.CommonsChunkPlugin({ + // names: ["vendor"], + // minChunks: Infinity + // }), new HtmlWebpackPlugin({ template: paths.app + 'index.html', hash: true
ee05d7c98ef9052fa27cc78a517c861577369d89
comparisons/utils/array_each/ie8.js
comparisons/utils/array_each/ie8.js
function forEach(array, fn) { for (i = 0; i < array.length; i++) fn(array[i], i); } forEach(array, function(item, i){ });
function forEach(array, fn) { for (var i = 0; i < array.length; i++) fn(array[i], i); } forEach(array, function(item, i){ });
Fix implicit creation of global variable
Fix implicit creation of global variable
JavaScript
mit
faustinoloeza/youmightnotneedjquery,gnarf/youmightnotneedjquery,sirLisko/youmightnotneedjquery,prashen/youmightnotneedjquery,kk9599/youmightnotneedjquery,giacomocerquone/youmightnotneedjquery,sdempsey/youmightnotneedjquery,faustinoloeza/youmightnotneedjquery,prashen/youmightnotneedjquery,maxmaximov/youmightnotneedjquery,HubSpot/youmightnotneedjquery,feateds/youmightnotneedjquery,sirLisko/youmightnotneedjquery,giacomocerquone/youmightnotneedjquery,kk9599/youmightnotneedjquery,gnarf/youmightnotneedjquery,HubSpot/youmightnotneedjquery,sdempsey/youmightnotneedjquery,feateds/youmightnotneedjquery,maxmaximov/youmightnotneedjquery
--- +++ @@ -1,5 +1,5 @@ function forEach(array, fn) { - for (i = 0; i < array.length; i++) + for (var i = 0; i < array.length; i++) fn(array[i], i); }
029788ef9eab50ee2ebdbc76940898f4c85f63c1
app/dashboard/concepts/concept/config.js
app/dashboard/concepts/concept/config.js
'use strict'; angular .module('report-editor') .config(function ($stateProvider) { $stateProvider .state('dashboard.concepts.concept', { url: '/:concepts/:label', templateUrl: '/dashboard/concepts/concept/concept.html', controller: 'DashboardConceptCtrl', resolve: { facts: ['$stateParams', 'API', 'Session', function($stateParams, API, Session){ $stateParams.concepts = $stateParams.concepts.split(','); return API.Queries.listFacts({ token: Session.getToken(), edinetcode: $stateParams.edinetcode, concept: $stateParams.concepts, fiscalYear: 'ALL', fiscalPeriod: 'FY', 'jppfs-cor:ConsolidatedOrNonConsolidatedAxis': 'ALL', 'jppfs-cor:ConsolidatedOrNonConsolidatedAxis::default': 'jppfs-cor:NonConsolidatedMember' }).then(function(response){ return response.FactTable; }); }] } }); }) ;
'use strict'; angular .module('report-editor') .config(function ($stateProvider) { $stateProvider .state('dashboard.concepts.concept', { url: '/:concepts/:label', templateUrl: '/dashboard/concepts/concept/concept.html', controller: 'DashboardConceptCtrl', resolve: { facts: ['$stateParams', 'API', 'Session', function($stateParams, API, Session){ $stateParams.concepts = $stateParams.concepts.split(','); return API.Queries.listFacts({ token: Session.getToken(), edinetcode: $stateParams.edinetcode, concept: $stateParams.concepts, fiscalYear: 'ALL', fiscalPeriod: 'FY', 'jppfs-cor:ConsolidatedOrNonConsolidatedAxis': 'ALL', 'jppfs-cor:ConsolidatedOrNonConsolidatedAxis::default': 'jppfs-cor:NonConsolidatedMember', "tse-ed-t:ResultForecastAxis": ["tse-ed-t:ForecastMember", "xbrl28:EDINETReportedValue"], "tse-ed-t:ResultForecastAxis::default": "xbrl28:EDINETReportedValue", "tse-ed-t:ConsolidatedNonconsolidatedAxis": "ALL", "tse-ed-t:PreviousCurrentAxis": "ALL", "tse-ed-t:ConsolidatedNonconsolidatedAxis::default": "NONE", "tse-ed-t:PreviousCurrentAxis::default": "NONE", "fsa:ArchiveFiscalPeriod": "ALL", "fsa:ArchiveFiscalYear": "ALL" }).then(function(response){ console.log(response.FactTable); return response.FactTable; }); }] } }); }) ;
Add forecast dimensions to the dashboard
:new: Add forecast dimensions to the dashboard
JavaScript
apache-2.0
AndreSteenveld/cellstore,AndreSteenveld/cellstore,AndreSteenveld/cellstore
--- +++ @@ -18,8 +18,18 @@ fiscalYear: 'ALL', fiscalPeriod: 'FY', 'jppfs-cor:ConsolidatedOrNonConsolidatedAxis': 'ALL', - 'jppfs-cor:ConsolidatedOrNonConsolidatedAxis::default': 'jppfs-cor:NonConsolidatedMember' + 'jppfs-cor:ConsolidatedOrNonConsolidatedAxis::default': 'jppfs-cor:NonConsolidatedMember', + + "tse-ed-t:ResultForecastAxis": ["tse-ed-t:ForecastMember", "xbrl28:EDINETReportedValue"], + "tse-ed-t:ResultForecastAxis::default": "xbrl28:EDINETReportedValue", + "tse-ed-t:ConsolidatedNonconsolidatedAxis": "ALL", + "tse-ed-t:PreviousCurrentAxis": "ALL", + "tse-ed-t:ConsolidatedNonconsolidatedAxis::default": "NONE", + "tse-ed-t:PreviousCurrentAxis::default": "NONE", + "fsa:ArchiveFiscalPeriod": "ALL", + "fsa:ArchiveFiscalYear": "ALL" }).then(function(response){ + console.log(response.FactTable); return response.FactTable; }); }]
c3c93a694cdbb854da2211db6ce61826078dbfdc
mock/frame/api.js
mock/frame/api.js
const Router = require('express').Router(), Util = require('../common/util.js'); // ε―Όθˆͺζ θœε• Router.route('/navigation/menuTree') .get(function(request, response) { let protocal = Util.protocal(); protocal.head.status = 200; protocal.head.message = 'http response sucess'; protocal.body = Util.json('/frame/data/navigation-menuTree.json'); response.json(protocal); }); // ζ³¨ι”€ε½“ε‰η”¨ζˆ· Router.route('/logout') .get(function(request, response) { let protocal = Util.Protocal(); protocal.head.status = 200; protocal.head.message = 'http response sucess'; response.json(protocal); }); module.exports = Router;
const Router = require('express').Router(), Util = require('../common/util.js'); // ε―Όθˆͺζ θœε• Router.route('/navigation/menuTree') .get(function(request, response) { let protocal = Util.protocal(); protocal.head.status = 200; protocal.head.message = 'http response sucess'; protocal.body = Util.json('/frame/data/navigation-menuTree.json'); response.json(protocal); }); // ζ³¨ι”€ε½“ε‰η”¨ζˆ· Router.route('/logout') .post(function(request, response) { let protocal = Util.protocal(); protocal.head.status = 200; protocal.head.message = 'ζΈ©ι¦¨ζη€ΊοΌšζ‚¨ε·²η»ι€€ε‡Ίη³»η»Ÿ!'; response.json(protocal); }); module.exports = Router;
Fix bug for API 404 error
Fix bug for API 404 error
JavaScript
mit
uinika/saga,uinika/saga
--- +++ @@ -13,10 +13,10 @@ // ζ³¨ι”€ε½“ε‰η”¨ζˆ· Router.route('/logout') - .get(function(request, response) { - let protocal = Util.Protocal(); + .post(function(request, response) { + let protocal = Util.protocal(); protocal.head.status = 200; - protocal.head.message = 'http response sucess'; + protocal.head.message = 'ζΈ©ι¦¨ζη€ΊοΌšζ‚¨ε·²η»ι€€ε‡Ίη³»η»Ÿ!'; response.json(protocal); });
a388030c1974528db0c521ef61376d3152217a86
prototype.spawn.js
prototype.spawn.js
module.exports = function () { StructureSpawn.prototype.createCustomCreep = function(energy, roleName) { var numberOfParts = Math.floor(energy / 350); var body = []; for (let i = 0; i < numberOfParts; i++) { body.push(WORK); } for (let i = 0; i < numberOfParts; i++) { body.push(WORK); } for (let i = 0; i < numberOfParts; i++) { body.push(CARRY); } for (let i = 0; i < numberOfParts; i++) { body.push(MOVE); } for (let i = 0; i < numberOfParts; i++) { body.push(MOVE); } return this.createCreep(body, undefined, {role: roleName, working: false }); }; };
module.exports = function () { StructureSpawn.prototype.createCustomCreep = function(energy, roleName) { var numberOfParts = Math.floor(energy / 350); var body = []; for (let i = 0; i < numberOfParts; i++) { body.push(WORK); } for (let i = 0; i < numberOfParts; i++) { body.push(WORK); } for (let i = 0; i < numberOfParts; i++) { body.push(CARRY); } for (let i = 0; i < numberOfParts; i++) { body.push(MOVE); } for (let i = 0; i < numberOfParts; i++) { body.push(MOVE); } return this.createCreep(body, undefined, {role: roleName, working: false }); }; };
WORK WORK CARRY MOVE MOVEx2+Bracket fixings
WORK WORK CARRY MOVE MOVEx2+Bracket fixings
JavaScript
mit
Raltrwx/Ralt-Screeps
--- +++ @@ -7,17 +7,17 @@ body.push(WORK); } for (let i = 0; i < numberOfParts; i++) { - body.push(WORK); - } + body.push(WORK); + } for (let i = 0; i < numberOfParts; i++) { - body.push(CARRY); - } + body.push(CARRY); + } for (let i = 0; i < numberOfParts; i++) { - body.push(MOVE); - } + body.push(MOVE); + } for (let i = 0; i < numberOfParts; i++) { - body.push(MOVE); - } + body.push(MOVE); + } return this.createCreep(body, undefined, {role: roleName, working: false }); };
541560e6b624119218729d70889197eddd184ca5
server/trello-microservice/test/index.js
server/trello-microservice/test/index.js
import mongoose from 'mongoose'; import sinon from 'sinon'; import { dbTest } from '../src/config/database'; let isConnected; const prepareServer = (user, done) => { let passportMiddleweare = require('../src/utils/passportMiddleweare'); let stub = sinon.stub(passportMiddleweare, 'authenticatedWithToken'); stub.callsFake((req, res, next) => { req.user = user; return next(); }); delete require.cache[require.resolve('../src/app')]; let app = require('../src/app').default; let server = app.listen(30001, (err) => { if (mongoose.connection.readyState === 0) { dbTest.connect(); } user.save().then(user => done(server, stub, app)); }); }; export default prepareServer;
import mongoose from 'mongoose'; import sinon from 'sinon'; import { dbTest } from '../src/config/database'; import getLogger from '../src/libs/winston'; import { port } from '../src/config/config'; const log = getLogger(module); const prepareServer = (user, done) => { let passportMiddleweare = require('../src/utils/passportMiddleweare'); let stub = sinon.stub(passportMiddleweare, 'authenticatedWithToken'); stub.callsFake((req, res, next) => { req.user = user; return next(); }); delete require.cache[require.resolve('../src/app')]; let app = require('../src/app').default; let server = app.listen(port, (err) => { log.info(`Test server is listening on ${port}`); if (mongoose.connection.readyState === 0) { dbTest.connect(); } user.save().then(user => done(server, stub, app)); }); }; export default prepareServer;
Add logs to the test server
Add logs to the test server
JavaScript
mit
Madmous/madClones,Madmous/Trello-Clone,Madmous/madClones,Madmous/Trello-Clone,Madmous/Trello-Clone,Madmous/madClones,Madmous/madClones
--- +++ @@ -2,8 +2,10 @@ import sinon from 'sinon'; import { dbTest } from '../src/config/database'; +import getLogger from '../src/libs/winston'; +import { port } from '../src/config/config'; -let isConnected; +const log = getLogger(module); const prepareServer = (user, done) => { let passportMiddleweare = require('../src/utils/passportMiddleweare'); @@ -19,7 +21,9 @@ delete require.cache[require.resolve('../src/app')]; let app = require('../src/app').default; - let server = app.listen(30001, (err) => { + let server = app.listen(port, (err) => { + log.info(`Test server is listening on ${port}`); + if (mongoose.connection.readyState === 0) { dbTest.connect(); }
abc62ab2de05943faec14b077590bb27994e984c
journal.js
journal.js
function write(prefix, args) { var timestamp = (new Date()).toString(); args.unshift(prefix, timestamp); console.log.apply(this, args); } var debug = function() { write("D", Array.prototype.slice.call(arguments)); }; var info = function() { write("I", Array.prototype.slice.call(arguments)); }; var error = function() { write("E", Array.prototype.slice.call(arguments)); }; var warn = function() { write("W", Array.prototype.slice.call(arguments)); }; var fail = function() { write("F", Array.prototype.slice.call(arguments)); }; module.exports = { debug: debug, info: info, error: error, warn: warn, fail: fail };
// Total available default levels. // logs are assigned as level to denote // levels of importance of criticality. var levels = { DEBUG: 1, INFO: 2, ERROR: 3, WARN: 4, FAIL: 5 }; // What are we currently interested in? var interest_ = 1; // Line prefixes provide easy visual markers // for human parsing and reading, along with // helping programmatic filtering. var prefixes = {}; prefixes[levels.DEBUG ] = "D"; prefixes[levels.INFO ] = "I"; prefixes[levels.ERROR ] = "E"; prefixes[levels.WARN ] = "W"; prefixes[levels.FAIL ] = "F"; function isInterested_(level) { return level >= interest_; } function setInterest(level) { interest_ = level; } function write(level, args) { var timestamp, prefix; if ( isInterested_(level) ) { timestamp = (new Date()).toString(); prefix = prefixes[level] || ""; args.unshift(prefix, timestamp); console.log.apply(this, args); } } var debug = function() { write(levels.DEBUG, Array.prototype.slice.call(arguments)); }; var info = function() { write(levels.INFO, Array.prototype.slice.call(arguments)); }; var error = function() { write(levels.ERROR, Array.prototype.slice.call(arguments)); }; var warn = function() { write(levels.WARN, Array.prototype.slice.call(arguments)); }; var fail = function() { write(levels.FAIL, Array.prototype.slice.call(arguments)); }; module.exports = { // Log handlers debug: debug, info: info, error: error, warn: warn, fail: fail, // Set to filter only specified level or higher. setInterest: setInterest, // Enumeration of levels for ease of use. levels: levels };
Implement support for setting interest level.
Implement support for setting interest level.
JavaScript
mit
soondobu/journal.js
--- +++ @@ -1,34 +1,80 @@ -function write(prefix, args) { - var timestamp = (new Date()).toString(); - args.unshift(prefix, timestamp); - console.log.apply(this, args); + +// Total available default levels. +// logs are assigned as level to denote +// levels of importance of criticality. +var levels = { + DEBUG: 1, + INFO: 2, + ERROR: 3, + WARN: 4, + FAIL: 5 +}; + +// What are we currently interested in? +var interest_ = 1; + +// Line prefixes provide easy visual markers +// for human parsing and reading, along with +// helping programmatic filtering. +var prefixes = {}; +prefixes[levels.DEBUG ] = "D"; +prefixes[levels.INFO ] = "I"; +prefixes[levels.ERROR ] = "E"; +prefixes[levels.WARN ] = "W"; +prefixes[levels.FAIL ] = "F"; + +function isInterested_(level) { + return level >= interest_; +} + +function setInterest(level) { + interest_ = level; +} + +function write(level, args) { + var timestamp, + prefix; + if ( isInterested_(level) ) { + timestamp = (new Date()).toString(); + prefix = prefixes[level] || ""; + args.unshift(prefix, timestamp); + console.log.apply(this, args); + } } var debug = function() { - write("D", Array.prototype.slice.call(arguments)); + write(levels.DEBUG, Array.prototype.slice.call(arguments)); }; var info = function() { - write("I", Array.prototype.slice.call(arguments)); + write(levels.INFO, Array.prototype.slice.call(arguments)); }; var error = function() { - write("E", Array.prototype.slice.call(arguments)); + write(levels.ERROR, Array.prototype.slice.call(arguments)); }; var warn = function() { - write("W", Array.prototype.slice.call(arguments)); + write(levels.WARN, Array.prototype.slice.call(arguments)); }; var fail = function() { - write("F", Array.prototype.slice.call(arguments)); + write(levels.FAIL, Array.prototype.slice.call(arguments)); }; module.exports = { - debug: debug, - info: info, - error: error, - warn: warn, - fail: fail + + // Log handlers + debug: debug, + info: info, + error: error, + warn: warn, + fail: fail, + + // Set to filter only specified level or higher. + setInterest: setInterest, + + // Enumeration of levels for ease of use. + levels: levels };
6be2707275df736cff451e8f461e43073488d8df
src/browser/services/cookie-storage.js
src/browser/services/cookie-storage.js
export default class CookieStorage { constructor(storageName = '_token') { this.cache = {}; this.storageName = storageName; } getItem(key) { if (this.cache[key]) { return Promise.resolve(this.cache[key]); } const data = this._getCookie(); if (!data[key]) { return Promise.reject(); } this.cache[key] = data[key]; return Promise.resolve(data[key]); } removeItem(key) { const data = this._getCookie(); if (!data[key]) { return Promise.resolve(); } delete this.cache[key]; delete data[key]; this._setCookie(data); return Promise.resolve(); } setItem(key, value) { const data = this._getCookie(); delete this.cache[key]; data[key] = value; this._setCookie(data); return Promise.resolve(); } _getCookie() { const data = new RegExp(`(?:^|; )${encodeURIComponent(this.storageName)}=([^;]*)`).exec(document.cookie); return data ? JSON.parse(decodeURIComponent(data[1])) : {}; } _setCookie(data) { document.cookie = `${this.storageName}=${encodeURIComponent(JSON.stringify(data))}`; } }
export default class CookieStorage { constructor(storageName = '_token') { this.cache = {}; this.storageName = storageName; } getItem(key) { if (this.cache[key]) { return Promise.resolve(this.cache[key]); } const data = this._getCookie(); if (!data[key]) { return Promise.reject(); } this.cache[key] = data[key]; return Promise.resolve(data[key]); } removeItem(key) { const data = this._getCookie(); if (!data[key]) { return Promise.resolve(); } delete this.cache[key]; delete data[key]; this._setCookie(data); return Promise.resolve(); } setItem(key, value) { const data = this._getCookie(); delete this.cache[key]; data[key] = value; this._setCookie(data); return Promise.resolve(); } _getCookie() { const data = new RegExp(`(?:^|; )${encodeURIComponent(this.storageName)}=([^;]*)`).exec(document.cookie); return data ? JSON.parse(decodeURIComponent(data[1])) : {}; } _setCookie(data) { document.cookie = `${this.storageName}=${encodeURIComponent(JSON.stringify(data))};path=/`; } }
Update cookie definition to use root path
Update cookie definition to use root path
JavaScript
mit
uphold/uphold-sdk-javascript,uphold/uphold-sdk-javascript
--- +++ @@ -54,6 +54,6 @@ } _setCookie(data) { - document.cookie = `${this.storageName}=${encodeURIComponent(JSON.stringify(data))}`; + document.cookie = `${this.storageName}=${encodeURIComponent(JSON.stringify(data))};path=/`; } }
9d132a41b7a669ba3d06d7eb959b4ba2f370e766
client/gulpfile.babel.js
client/gulpfile.babel.js
import gulp from 'gulp'; import defaults from 'lodash/defaults'; import plumber from 'gulp-plumber'; import webpack from 'webpack-stream'; import jscs from 'gulp-jscs'; import jshint from 'gulp-jshint'; import { JSXHINT as linter } from 'jshint-jsx'; import webpackPrd from './conf/webpack.prd.config'; import webpackDev from './conf/webpack.dev.config'; const env = process.env.NODE_ENV || 'dev'; const webpackConf = { 'dev': webpackDev, 'prd': webpackPrd }[env]; const paths = { js: [ '*.js', 'src/**/*.js' ] }; gulp.task('build:scripts', () => { return webpack(webpackConf) .pipe(gulp.dest('./dist')); }); gulp.task('watch:scripts', () => { return webpack(defaults(webpackConf, { watch: true, keepalive: true })); }); gulp.task('lint', () => { return gulp.src(paths.js) .pipe(plumber()) .pipe(jscs()) .pipe(jshint({linter: linter})) .pipe(jshint.reporter('jshint-stylish')); }); gulp.task('watch:lint', () => { gulp.watch(paths.js, ['lint']); }); gulp.task('watch', ['watch:lint', 'watch:scripts']); gulp.task('build', ['build:scripts']); gulp.task('default', ['build']);
import gulp from 'gulp'; import defaults from 'lodash/defaults'; import plumber from 'gulp-plumber'; import webpack from 'webpack-stream'; import jscs from 'gulp-jscs'; import jshint from 'gulp-jshint'; import { JSXHINT as linter } from 'jshint-jsx'; import webpackPrd from './conf/webpack.prd.config'; import webpackDev from './conf/webpack.dev.config'; const env = process.env.NODE_ENV || 'dev'; const webpackConf = { 'dev': webpackDev, 'prd': webpackPrd }[env]; const paths = { js: [ '*.js', 'src/**/*.js' ] }; gulp.task('build:scripts', () => { return webpack(webpackConf) .pipe(gulp.dest('./dist')); }); gulp.task('watch:scripts', () => { return webpack(defaults(webpackConf, { watch: true, keepalive: true })); }); gulp.task('lint', () => { return gulp.src(paths.js) .pipe(plumber()) .pipe(jscs()) .pipe(jshint({linter: linter})) .pipe(jshint.reporter('jshint-stylish')); }); gulp.task('watch:lint', () => { gulp.watch(paths.js, ['lint']); }); gulp.task('test', []); gulp.task('watch', ['watch:lint', 'watch:scripts']); gulp.task('build', ['build:scripts']); gulp.task('ci', ['lint', 'build', 'test']); gulp.task('default', ['build', 'test']);
Add a ci gulp task
Add a ci gulp task
JavaScript
bsd-2-clause
praekelt/molo,praekelt/molo,praekelt/molo,praekelt/molo
--- +++ @@ -55,8 +55,8 @@ }); +gulp.task('test', []); gulp.task('watch', ['watch:lint', 'watch:scripts']); gulp.task('build', ['build:scripts']); - - -gulp.task('default', ['build']); +gulp.task('ci', ['lint', 'build', 'test']); +gulp.task('default', ['build', 'test']);
05c2639761fffe630ed36ff0724c5d1153a46c64
test/local-state-test.js
test/local-state-test.js
var tape = require("tape"), jsdom = require("jsdom"), d3 = Object.assign(require("../"), require("d3-selection")); /************************************* ************ Components ************* *************************************/ // Local state. var spinnerCreated= false, spinnerDestroyed = false, spinnerTimerState = "", spinnerText = "", spinner = d3.component("div") .create(function (setState){ spinnerTimerState = "running"; setState({ timer: spinnerTimerState, cleanup: function (){ spinnerTimerState = "stopped"; setState({ timer: spinnerTimerState }); } }); }) .render(function (selection, props, state){ spinnerText = "Timer is " + state.timer; selection.text(spinnerText); }) .destroy(function(state){ state.cleanup(); }); /************************************* ************** Tests **************** *************************************/ tape("Local state.", function(test) { var div = d3.select(jsdom.jsdom().body).append("div"); test.end(); });
var tape = require("tape"), jsdom = require("jsdom"), d3 = Object.assign(require("../"), require("d3-selection")); /************************************* ************ Components ************* *************************************/ // Local state. var spinnerCreated= false, spinnerDestroyed = false, spinnerTimerState = "", spinnerText = "", spinner = d3.component("div") .create(function (setState){ spinnerTimerState = "running"; setState({ timer: spinnerTimerState, cleanup: function (){ spinnerTimerState = "stopped"; setState({ timer: spinnerTimerState }); } }); }) .render(function (selection, props, state){ spinnerText = "Timer is " + state.timer; selection.text(spinnerText); }) .destroy(function(state){ state.cleanup(); }); /************************************* ************** Tests **************** *************************************/ tape("Local state.", function(test) { var div = d3.select(jsdom.jsdom().body).append("div"); // Create. div.call(spinner); test.equal(spinnerCreated, true); test.equal(spinnerDestroyed, false); test.equal(spinnerTimerState = "running"); test.equal(spinnerText = "Timer is running"); test.equal(div.html(), "<div>Timer is running</div>"); // Destroy. div.call(spinner, []); test.equal(spinnerCreated, true); test.equal(spinnerDestroyed, true); test.equal(spinnerTimerState = "stopped"); test.equal(spinnerText = "Timer is running"); test.equal(div.html(), ""); test.end(); });
Add test for local state
Add test for local state
JavaScript
bsd-3-clause
curran/d3-component
--- +++ @@ -38,5 +38,21 @@ tape("Local state.", function(test) { var div = d3.select(jsdom.jsdom().body).append("div"); + // Create. + div.call(spinner); + test.equal(spinnerCreated, true); + test.equal(spinnerDestroyed, false); + test.equal(spinnerTimerState = "running"); + test.equal(spinnerText = "Timer is running"); + test.equal(div.html(), "<div>Timer is running</div>"); + + // Destroy. + div.call(spinner, []); + test.equal(spinnerCreated, true); + test.equal(spinnerDestroyed, true); + test.equal(spinnerTimerState = "stopped"); + test.equal(spinnerText = "Timer is running"); + test.equal(div.html(), ""); + test.end(); });
74c1bd9785f65aaf88834dede0a4ab83a4f9827f
test/lib/parser/ftl/serializer_test.js
test/lib/parser/ftl/serializer_test.js
'use strict'; import fs from 'fs'; import path from 'path'; import assert from 'assert'; import FTLParser from '../../../../src/lib/format/ftl/ast/parser'; import FTLSerializer from '../../../../src/lib/format/ftl/ast/serializer'; var parse = FTLParser.parseResource; function readFile(path) { return new Promise(function(resolve, reject) { fs.readFile(path, 'utf8', (err, data) => { resolve(data); }); }); } function testSerialize(path1) { return Promise.all([ readFile(path1), ]).then(([source1]) => { let ftl = parse(source1); let out = FTLSerializer.serialize(ftl); let ftl2 = parse(out); assert.deepEqual(ftl.body, ftl2.body, `Serialized output for ${path1} should be the same`); }); } var basePath = './test/lib/fixtures/parser/ftl'; describe('FTL Serializer', function() { it('fixtures work', function(done) { fs.readdir(basePath, (err, paths) => { let tests = []; paths.forEach(fileName => { if (!fileName.endsWith('.ftl') || fileName.indexOf('error') !== -1) { return; } let ftlPath = path.join(basePath, fileName); tests.push(testSerialize(ftlPath)); }); Promise.all(tests).then(() => { done() }, (err) => { done(err) }); }); }); });
'use strict'; import fs from 'fs'; import path from 'path'; import assert from 'assert'; import FTLParser from '../../../../src/lib/format/ftl/ast/parser'; import FTLSerializer from '../../../../src/lib/format/ftl/ast/serializer'; var parse = FTLParser.parseResource; function readFile(path) { return new Promise(function(resolve, reject) { fs.readFile(path, 'utf8', (err, data) => { resolve(data); }); }); } function testSerialize(path1) { return Promise.all([ readFile(path1), ]).then(([source1]) => { let ftl = parse(source1); let out = FTLSerializer.serialize(ftl.body); let ftl2 = parse(out); assert.deepEqual(ftl.body, ftl2.body, `Serialized output for ${path1} should be the same`); }); } var basePath = './test/lib/fixtures/parser/ftl'; describe('FTL Serializer', function() { it('fixtures work', function(done) { fs.readdir(basePath, (err, paths) => { let tests = []; paths.forEach(fileName => { if (!fileName.endsWith('.ftl') || fileName.indexOf('error') !== -1) { return; } let ftlPath = path.join(basePath, fileName); tests.push(testSerialize(ftlPath)); }); Promise.all(tests).then(() => { done() }, (err) => { done(err) }); }); }); });
Fix serializer test with proper argument to FTLSerializer
Fix serializer test with proper argument to FTLSerializer
JavaScript
apache-2.0
projectfluent/fluent.js,zbraniecki/fluent.js,projectfluent/fluent.js,zbraniecki/fluent.js,l20n/l20n.js,stasm/l20n.js,projectfluent/fluent.js,zbraniecki/l20n.js
--- +++ @@ -22,7 +22,7 @@ readFile(path1), ]).then(([source1]) => { let ftl = parse(source1); - let out = FTLSerializer.serialize(ftl); + let out = FTLSerializer.serialize(ftl.body); let ftl2 = parse(out); assert.deepEqual(ftl.body, ftl2.body, `Serialized output for ${path1} should be the same`);
bbdbf72361d97bd9306fd46da28cb06565b14af6
client/src/actions/fullListingActions.js
client/src/actions/fullListingActions.js
import { GET_CURRENT_LISTING_SUCCESS, FETCHING_LISTING, CHANGE_CONTACT_FIELD } from '../constants'; import { changeCenter, addMapMarker } from './googleMapActions'; import { fetchCurrentListing } from './api'; const startFetchListing = () => ({ type: FETCHING_LISTING, }); export const changeContactField = (field, value) => ({ type: CHANGE_CONTACT_FIELD, field, value, }); export const getCurrentListingSuccess = payload => ({ type: GET_CURRENT_LISTING_SUCCESS, payload, }); export const getCurrentListing = listingId => (dispatch) => { dispatch(startFetchListing()); fetchCurrentListing(listingId) .then((res) => { res.json() .then((data) => { dispatch(changeCenter(data)); dispatch(addMapMarker(data)); dispatch(getCurrentListingSuccess(data)); }); }); };
import { GET_CURRENT_LISTING_SUCCESS, FETCHING_LISTING, CHANGE_CONTACT_FIELD, POST_CONTACT_MESSAGE_SUCCESS } from '../constants'; import { changeCenter, addMapMarker } from './googleMapActions'; import { fetchCurrentListing, postContactMessage } from './api'; const startFetchListing = () => ({ type: FETCHING_LISTING, }); export const changeContactField = (field, value) => ({ type: CHANGE_CONTACT_FIELD, field, value, }); export const getCurrentListingSuccess = payload => ({ type: GET_CURRENT_LISTING_SUCCESS, payload, }); export const postContactMessageSuccess = payload => ({ type: POST_CONTACT_MESSAGE_SUCCESS, payload, }); export const getCurrentListing = listingId => (dispatch) => { dispatch(startFetchListing()); fetchCurrentListing(listingId) .then((res) => { res.json() .then((data) => { dispatch(changeCenter(data)); dispatch(addMapMarker(data)); dispatch(getCurrentListingSuccess(data)); }); }); }; export const sendMessage = data => (dispatch, getState) => { postContactMessage(data) .then((res) => { res.json() .then((payload) => { dispatch(postContactMessageSuccess(payload)); }); }); };
Add actions to handle posting a message
Add actions to handle posting a message
JavaScript
mit
Velocies/raptor-ads,wolnewitz/raptor-ads,bwuphan/raptor-ads,Darkrender/raptor-ads,Velocies/raptor-ads,wolnewitz/raptor-ads,Darkrender/raptor-ads,bwuphan/raptor-ads
--- +++ @@ -1,6 +1,6 @@ -import { GET_CURRENT_LISTING_SUCCESS, FETCHING_LISTING, CHANGE_CONTACT_FIELD } from '../constants'; +import { GET_CURRENT_LISTING_SUCCESS, FETCHING_LISTING, CHANGE_CONTACT_FIELD, POST_CONTACT_MESSAGE_SUCCESS } from '../constants'; import { changeCenter, addMapMarker } from './googleMapActions'; -import { fetchCurrentListing } from './api'; +import { fetchCurrentListing, postContactMessage } from './api'; const startFetchListing = () => @@ -21,6 +21,12 @@ payload, }); +export const postContactMessageSuccess = payload => + ({ + type: POST_CONTACT_MESSAGE_SUCCESS, + payload, + }); + export const getCurrentListing = listingId => (dispatch) => { dispatch(startFetchListing()); @@ -34,3 +40,14 @@ }); }); }; + +export const sendMessage = data => + (dispatch, getState) => { + postContactMessage(data) + .then((res) => { + res.json() + .then((payload) => { + dispatch(postContactMessageSuccess(payload)); + }); + }); + };
ab0306fd4c49f967bb1d21c9dd22042a26fb4812
test/unit/testNewFile.js
test/unit/testNewFile.js
'use strict'; var jf = require('../../'), expect = require('chai').expect, fs = require('fs'); const testFilePath = './' + Math.random() + '.json'; describe('The initialValue', function () { it('should be equal to defined in json.filed.', function (done) { jf .newFile( testFilePath ) .io( function( obj ) { expect(obj).to.eql(jf.initialValue()); } ) .pass( () => { jf .newFile( testFilePath, function( err ){ expect( err ).to.be.an.instanceof( jf.JsonFiledError ); done(); } ) .exec(); }) .exec(); }); });
'use strict'; var jf = require('../../'), expect = require('chai').expect, fs = require('fs'); const testFilePath = './' + Math.random() + '.json'; describe('newFile executer', function () { it('should create new file and if already exists, raise error.', function (done) { jf .newFile( testFilePath ) .io( function( obj ) { expect(obj).to.eql(jf.initialValue()); } ) .pass( () => { jf .newFile( testFilePath, function( err ){ expect( err ).to.be.an.instanceof( jf.JsonFiledError ); done(); } ) .exec(); }) .exec(); }); });
Fix mistaken comment in test
Fix mistaken comment in test
JavaScript
bsd-3-clause
7k8m/json.filed,7k8m/json.filed
--- +++ @@ -5,8 +5,8 @@ fs = require('fs'); const testFilePath = './' + Math.random() + '.json'; -describe('The initialValue', function () { - it('should be equal to defined in json.filed.', function (done) { +describe('newFile executer', function () { + it('should create new file and if already exists, raise error.', function (done) { jf .newFile( testFilePath ) .io(
e2a2cded975f53463e2a83d2c38f0e285e186e7e
tests/Data.tests/testCookies/client.js
tests/Data.tests/testCookies/client.js
//test cookie passing var http = require("http"); var fs = require("fs"); var querystring = require("querystring"); express = require('express'), connect = require('connect'), sys = require('sys'), app = express.createServer(); var stdin = process.openStdin(); stdin.setEncoding('utf8'); stdin.on('data', function (chunk) { var processInfo = JSON.parse(chunk); process.chdir(processInfo.workingDirectory); app.listen(processInfo.port, function() { var returnedInfo = {port: processInfo.port}; console.log(JSON.stringify(returnedInfo)); }); }); app.get('/test', function(req, res) { res.cookie('rememberme', 'yes', { maxAge: 900000 }); res.writeHead(200, { 'Content-Type': 'text/html' }); // res.cookie('locker_proxy_cookie_test', 'works'); res.end(); });
//test cookie passing var http = require("http"); var fs = require("fs"); var querystring = require("querystring"); express = require('express'), connect = require('connect'), sys = require('sys'), app = express.createServer(); var stdin = process.openStdin(); stdin.setEncoding('utf8'); stdin.on('data', function (chunk) { var processInfo = JSON.parse(chunk); process.chdir(processInfo.workingDirectory); app.listen(processInfo.port, function() { console.log(JSON.stringify({port: app.address().port})); }); }); app.get('/test', function(req, res) { console.log("Cookie test"); res.cookie('rememberme', 'yes', { maxAge: 900000 }); res.writeHead(200, { 'Content-Type': 'text/html' }); // res.cookie('locker_proxy_cookie_test', 'works'); res.end(); });
Return our actual port to avoid some potential conflicts
Return our actual port to avoid some potential conflicts
JavaScript
bsd-3-clause
LockerProject/Locker,LockerProject/Locker,quartzjer/Locker,LockerProject/Locker,quartzjer/Locker,othiym23/locker,LockerProject/Locker,othiym23/locker,Singly/hallway,othiym23/locker,quartzjer/Locker,othiym23/locker,quartzjer/Locker,LockerProject/Locker,quartzjer/Locker,othiym23/locker,Singly/hallway
--- +++ @@ -14,14 +14,14 @@ var processInfo = JSON.parse(chunk); process.chdir(processInfo.workingDirectory); app.listen(processInfo.port, function() { - var returnedInfo = {port: processInfo.port}; - console.log(JSON.stringify(returnedInfo)); + console.log(JSON.stringify({port: app.address().port})); }); }); app.get('/test', function(req, res) { + console.log("Cookie test"); res.cookie('rememberme', 'yes', { maxAge: 900000 }); res.writeHead(200, { 'Content-Type': 'text/html'
6d1330848d4eb59b3308f5166b14dbb6de850869
servers.js
servers.js
var fork = require('child_process').fork; var async = require('async'); var amountConcurrentServers = process.argv[2] || 50; var port = initialPortServer(); var servers = []; var path = __dirname; for(var i = 0; i < amountConcurrentServers; i++) { var portForServer = port + i; var serverIdentifier = i; console.log('Creating server: ' + serverIdentifier + ' - ' + portForServer + ' - ' + serverIdentifier); servers[i] = fork( path +'/server.js', [portForServer, serverIdentifier]); } process.on('exit', function() { console.log('exit process'); for(var i = 0; i < amountConcurrentServers; i++) { servers[i].kill(); } }); function initialPortServer() { if(process.argv[3]) { return parseInt(process.argv[3]); } return 3000; }
var fork = require('child_process').fork; var amountConcurrentServers = process.argv[2] || 50; var port = initialPortServer(); var servers = []; var path = __dirname; for(var i = 0; i < amountConcurrentServers; i++) { var portForServer = port + i; var serverIdentifier = i; console.log('Creating server: ' + serverIdentifier + ' - ' + portForServer + ' - ' + serverIdentifier); servers[i] = fork( path +'/server.js', [portForServer, serverIdentifier]); } process.on('exit', function() { console.log('exit process'); for(var i = 0; i < amountConcurrentServers; i++) { servers[i].kill(); } }); function initialPortServer() { if(process.argv[3]) { return parseInt(process.argv[3]); } return 3000; }
Remove async library for server
Remove async library for server
JavaScript
mit
eltortuganegra/server-websocket-benchmark,eltortuganegra/server-websocket-benchmark
--- +++ @@ -1,5 +1,4 @@ var fork = require('child_process').fork; -var async = require('async'); var amountConcurrentServers = process.argv[2] || 50; var port = initialPortServer(); var servers = [];
ac5bf5d50ac0213497d65ffd44264b5a860c2075
src/posts/js/post.controller.js
src/posts/js/post.controller.js
/*global angular*/ angular.module('post') /** * @ngdoc controller * @name post.controller:PostMainController * * @description * # main post controller * * The main post controller * */ .controller('PostMainController', ["PostManager", function (PostManager) { "use strict"; var scope = this; scope.text = "Hello world !"; scope.init = function () { scope.getPosts(); }; scope.getPosts = function () { return PostManager.getPosts() .then(function (posts) { return posts; }); }; }]);
/*global angular*/ angular.module('post') /** * @ngdoc controller * @name post.controller:PostMainController * * @description * # main post controller * * The main post controller * */ .controller('PostMainController', ["PostManager", function (PostManager) { "use strict"; var scope = this; scope.text = "Hello world !"; scope.init = function () { scope.getPosts(); }; scope.getPosts = function () { return PostManager.getPosts() .then(function (posts) { return posts; }); }; }]);
Indent code after changing editor to netbeans.
Indent code after changing editor to netbeans.
JavaScript
mit
anisdjer/angularjs-ci,anisdjer/angularjs-ci
--- +++ @@ -1,16 +1,16 @@ /*global angular*/ angular.module('post') /** - * @ngdoc controller - * @name post.controller:PostMainController - * - * @description - * # main post controller - * - * The main post controller - * - */ - .controller('PostMainController', ["PostManager", function (PostManager) { + * @ngdoc controller + * @name post.controller:PostMainController + * + * @description + * # main post controller + * + * The main post controller + * + */ + .controller('PostMainController', ["PostManager", function (PostManager) { "use strict"; var scope = this; scope.text = "Hello world !";
690ea735f598db2a605a012347e4b9f1b2490874
new/src/config/.entry.js
new/src/config/.entry.js
/** DO NOT MODIFY **/ import React, { Component } from "react"; import { render } from "react-dom"; import { Root } from "gluestick-shared"; import routes from "./routes"; import store from "./.store"; // Make sure that webpack considers new dependencies introduced in the Index // file import "../../Index.js"; export default class Entry extends Component { static defaultProps = { store: store() }; render () { const { routingContext, radiumConfig, store } = this.props; return ( <Root routingContext={routingContext} radiumConfig={radiumConfig} routes={routes} store={store} /> ); } } Entry.start = function () { render(<Entry radiumConfig={{userAgent: window.navigator.userAgent}} />, document.getElementById("main")); };
/** DO NOT MODIFY **/ import React, { Component } from "react"; import { render } from "react-dom"; import { Root } from "gluestick-shared"; import { match } from "react-router"; import routes from "./routes"; import store from "./.store"; // Make sure that webpack considers new dependencies introduced in the Index // file import "../../Index.js"; export default class Entry extends Component { static defaultProps = { store: store() }; render () { const { routingContext, radiumConfig, store } = this.props; return ( <Root routingContext={routingContext} radiumConfig={radiumConfig} routes={routes} store={store} /> ); } } Entry.start = function () { match({routes, location: window.location.pathname}, (error, redirectLocation, renderProps) => { render(<Entry radiumConfig={{userAgent: window.navigator.userAgent}} {...renderProps} />, document.getElementById("main")); }); };
Add support for async routes
Add support for async routes
JavaScript
mit
TrueCar/gluestick,TrueCar/gluestick,TrueCar/gluestick
--- +++ @@ -3,6 +3,7 @@ import { render } from "react-dom"; import { Root } from "gluestick-shared"; +import { match } from "react-router"; import routes from "./routes"; import store from "./.store"; @@ -29,6 +30,8 @@ } Entry.start = function () { - render(<Entry radiumConfig={{userAgent: window.navigator.userAgent}} />, document.getElementById("main")); + match({routes, location: window.location.pathname}, (error, redirectLocation, renderProps) => { + render(<Entry radiumConfig={{userAgent: window.navigator.userAgent}} {...renderProps} />, document.getElementById("main")); + }); };
52e2a715811dccdb3e6a0ab464e188f2dfc9c228
extension/content/firebug/trace/debug.js
extension/content/firebug/trace/debug.js
/* See license.txt for terms of usage */ define([ "firebug/lib/trace" ], function(FBTrace) { // ********************************************************************************************* // // Debug APIs const Cc = Components.classes; const Ci = Components.interfaces; var consoleService = Cc["@mozilla.org/consoleservice;1"].getService(Ci["nsIConsoleService"]); var Debug = {}; //************************************************************************************************ // Debug Logging Debug.ERROR = function(exc) { if (typeof(FBTrace) !== undefined) { if (exc.stack) exc.stack = exc.stack.split('\n'); FBTrace.sysout("Debug.ERROR: " + exc, exc); } if (consoleService) consoleService.logStringMessage("FIREBUG ERROR: " + exc); } // ********************************************************************************************* // /** * Dump the current stack trace. * @param {Object} message displayed for the log. */ Debug.STACK_TRACE = function(message) { var result = []; for (var frame = Components.stack, i = 0; frame; frame = frame.caller, i++) { if (i < 1) continue; var fileName = unescape(frame.filename ? frame.filename : ""); var lineNumber = frame.lineNumber ? frame.lineNumber : ""; result.push(fileName + ":" + lineNumber); } FBTrace.sysout(message, result); } return Debug; // ********************************************************************************************* // });
/* See license.txt for terms of usage */ define([ "firebug/lib/trace" ], function(FBTrace) { // ********************************************************************************************* // // Debug APIs const Cc = Components.classes; const Ci = Components.interfaces; var consoleService = Cc["@mozilla.org/consoleservice;1"].getService(Ci["nsIConsoleService"]); var Debug = {}; //************************************************************************************************ // Debug Logging Debug.ERROR = function(exc) { if (typeof(FBTrace) !== undefined) { if (exc.stack) exc.stack = exc.stack.split('\n'); FBTrace.sysout("Debug.ERROR: " + exc, exc); } if (consoleService) consoleService.logStringMessage("FIREBUG ERROR: " + exc); } // ********************************************************************************************* // return Debug; // ********************************************************************************************* // });
Remove tracing helper it's already in StackFrame.getStackDump
[1.8] Remove tracing helper it's already in StackFrame.getStackDump http://code.google.com/p/fbug/source/detail?r=10854
JavaScript
bsd-3-clause
firebug/tracing-console,firebug/tracing-console
--- +++ @@ -34,26 +34,6 @@ // ********************************************************************************************* // -/** - * Dump the current stack trace. - * @param {Object} message displayed for the log. - */ -Debug.STACK_TRACE = function(message) -{ - var result = []; - for (var frame = Components.stack, i = 0; frame; frame = frame.caller, i++) - { - if (i < 1) - continue; - - var fileName = unescape(frame.filename ? frame.filename : ""); - var lineNumber = frame.lineNumber ? frame.lineNumber : ""; - - result.push(fileName + ":" + lineNumber); - } - FBTrace.sysout(message, result); -} - return Debug; // ********************************************************************************************* //
73deeee9d2741a156eaf3aebb9449efb9c7172c2
src/services/contact-service.js
src/services/contact-service.js
import {HttpClient} from 'aurelia-http-client'; import {ContactModel} from 'src/models/contact-model'; var CONTACT_MANAGER_API_HOST = 'http://api-contact-manager.herokuapp.com'; var CONTACTS_URL = CONTACT_MANAGER_API_HOST + '/contacts'; var CONTACT_URL = CONTACT_MANAGER_API_HOST + '/contacts/${id}'; export class ContactService { static inject() { return [HttpClient]; } constructor(http){ this.http = http; } getAll(){ return this.http.get(CONTACTS_URL).then(response => { return response.content.map(data => { return new ContactModel(data); }); }); } getById(id){ var contactUrl = CONTACT_URL.replace('${id}', id); return this.http.get(contactUrl).then(response => { return new ContactModel(response.content); }); } create(contact){ return this.http.post(CONTACTS_URL, contact).then(response => { return new ContactModel(response.content); }); } update(contact){ var contactUrl = CONTACT_URL.replace('${id}', contact.id); return this.http.put(contactUrl, contact).then(response => { return new ContactModel(response.content); }); } delete(contact){ var contactUrl = CONTACT_URL.replace('${id}', contact.id); return this.http.delete(contactUrl).then(response => { return true; }); } }
import {HttpClient} from 'aurelia-http-client'; import {ContactModel} from 'src/models/contact-model'; var CONTACT_MANAGER_API_HOST = 'http://api-contact-manager.herokuapp.com'; var CONTACTS_URL = CONTACT_MANAGER_API_HOST + '/contacts'; var CONTACT_URL = CONTACT_MANAGER_API_HOST + '/contacts/${id}'; export class ContactService { static inject() { return [HttpClient]; } constructor(http){ this.http = http; this.http.configure((requestBuilder) => { requestBuilder.withCredentials(true); }) } getAll(){ return this.http.get(CONTACTS_URL).then(response => { return response.content.map(data => { return new ContactModel(data); }); }); } getById(id){ var contactUrl = CONTACT_URL.replace('${id}', id); return this.http.get(contactUrl).then(response => { return new ContactModel(response.content); }); } create(contact){ return this.http.post(CONTACTS_URL, contact).then(response => { return new ContactModel(response.content); }); } update(contact){ var contactUrl = CONTACT_URL.replace('${id}', contact.id); return this.http.put(contactUrl, contact).then(response => { return new ContactModel(response.content); }); } delete(contact){ var contactUrl = CONTACT_URL.replace('${id}', contact.id); return this.http.delete(contactUrl).then(response => { return true; }); } }
Send requests with credentials to use session
Send requests with credentials to use session
JavaScript
mit
dmytroyarmak/aurelia-contact-manager,dmytroyarmak/aurelia-contact-manager
--- +++ @@ -9,6 +9,9 @@ static inject() { return [HttpClient]; } constructor(http){ this.http = http; + this.http.configure((requestBuilder) => { + requestBuilder.withCredentials(true); + }) } getAll(){
778095edb330788119b7bc839782934b3a8a1ac2
gulpfile.js
gulpfile.js
'use strict'; let gulp = require('gulp'); let server = require('gulp-express'); let paths = { scripts: ['app.js', 'routes/**/*.js', 'public/**/*.js', 'gulpfile.js'] }; gulp.task('run', () => { server.run(['bin/www']); }); gulp.task('watch', () => { gulp.watch([paths.scripts, ['run']]); }); gulp.task('default', ['watch', 'run']);
'use strict'; let gulp = require('gulp'); let server = require('gulp-express'); let shell = require('gulp-shell'); let del = require('del'); let paths = { scripts: ['app.js', 'routes/**/*.js', 'public/**/*.js', 'gulpfile.js'] }; gulp.task('clean', () => { return del(['build']); }); gulp.task('run', () => { server.run(['bin/www']); }); gulp.task('watch', () => { gulp.watch([paths.scripts, ['run']]); }); gulp.task('default', ['watch', 'run']); gulp.task('electron', ['clean'], () => { return gulp.src(['main.js', './views/**/**', './public/**/**']) .pipe(gulp.dest('build/electron')); });
Add gulp electron and gulp clean
Add gulp electron and gulp clean
JavaScript
mit
WithCampKr/annyang_node_demo,WithCampKr/annyang_node_demo
--- +++ @@ -2,9 +2,16 @@ let gulp = require('gulp'); let server = require('gulp-express'); +let shell = require('gulp-shell'); +let del = require('del'); + let paths = { scripts: ['app.js', 'routes/**/*.js', 'public/**/*.js', 'gulpfile.js'] }; + +gulp.task('clean', () => { + return del(['build']); +}); gulp.task('run', () => { server.run(['bin/www']); @@ -15,3 +22,8 @@ }); gulp.task('default', ['watch', 'run']); + +gulp.task('electron', ['clean'], () => { + return gulp.src(['main.js', './views/**/**', './public/**/**']) + .pipe(gulp.dest('build/electron')); +});
f56d7bce09119f7eebe82951107b651e47685e45
gulpfile.js
gulpfile.js
var gulp = require('gulp'), tsc = require('gulp-tsc'), tape = require('gulp-tape'), tapSpec = require('tap-spec'), del = require('del'), runSequence = require('run-sequence'), istanbul = require('gulp-istanbul'); gulp.task("test:clean", function(done) { del(['build-test/**']).then(function(paths) { console.log("=====\nDeleted the following files:\n" + paths.join('\n')+ "\n====="); done(); }); }); gulp.task("test:build", function (done) { gulp.src('test/**/*.ts') .pipe(tsc()) .pipe(gulp.dest('build-test/')) .on('end', done); }); gulp.task("test:istanbul-hook", function () { return gulp.src('build-test/src/**/*.js') .pipe(istanbul()) .pipe(istanbul.hookRequire()); }); gulp.task("test:run", function (done) { gulp.src('build-test/test/**/*.test.js') .pipe(tape({ reporter: tapSpec() })) .pipe(istanbul.writeReports()) .on('end', done); }); gulp.task("test", function (done) { runSequence('test:clean', 'test:build', 'test:istanbul-hook', 'test:run', done); });
var gulp = require('gulp'), tsc = require('gulp-tsc'), tape = require('gulp-tape'), tapSpec = require('tap-spec'), del = require('del'), runSequence = require('run-sequence'), istanbul = require('gulp-istanbul'); gulp.task("test:clean", function(done) { del(['build-test/**']).then(function(paths) { console.log("=====\nDeleted the following files:\n" + paths.join('\n')+ "\n====="); done(); }); }); gulp.task("test:build", function (done) { gulp.src('test/**/*.ts') .pipe(tsc()) .pipe(gulp.dest('build-test/')) .on('end', done); }); gulp.task("test:istanbul-hook", function () { return gulp.src('build-test/src/**/*.js') .pipe(istanbul()) .pipe(istanbul.hookRequire()); }); gulp.task("test:run", function (done) { gulp.src('build-test/test/**/*.test.js') .pipe(tape({ reporter: tapSpec() })) .pipe(istanbul.writeReports({ reporters: [ 'lcov', 'json', 'text-summary' ] })) .on('end', done); }); gulp.task("test", function (done) { runSequence('test:clean', 'test:build', 'test:istanbul-hook', 'test:run', done); });
Use coverage summary rather than full coverage breakdown
Use coverage summary rather than full coverage breakdown
JavaScript
mit
Jameskmonger/isaac-crypto
--- +++ @@ -31,7 +31,9 @@ .pipe(tape({ reporter: tapSpec() })) - .pipe(istanbul.writeReports()) + .pipe(istanbul.writeReports({ + reporters: [ 'lcov', 'json', 'text-summary' ] + })) .on('end', done); });
21b0e4157e794d35a4868f3484966111882c70b4
src/components/pages/PeoplePage/http.js
src/components/pages/PeoplePage/http.js
import _ from 'lodash'; import {API_PATH} from 'power-ui/conf'; import {urlToRequestObjectWithHeaders, isTruthy} from 'power-ui/utils'; // Handle all HTTP networking logic of this page function PeoplePageHTTP(sources) { const PEOPLE_URL = `${API_PATH}/people/`; const atomicResponse$ = sources.HTTP .filter(response$ => _.startsWith(response$.request.url, PEOPLE_URL)) .mergeAll() .filter(response => isTruthy(response.body)) .shareReplay(1); const request$ = atomicResponse$ .filter(response => response.body.next) .map(response => response.body.next.replace('limit=5', 'limit=40')) .startWith(PEOPLE_URL + '?limit=5') .map(urlToRequestObjectWithHeaders); const response$ = atomicResponse$ .map(response => response.body.results) .scan((acc, curr) => acc.concat(curr)); return {request$, response$}; // sink } export default PeoplePageHTTP;
import _ from 'lodash'; import {API_PATH} from 'power-ui/conf'; import {urlToRequestObjectWithHeaders, isTruthy} from 'power-ui/utils'; // Handle all HTTP networking logic of this page function PeoplePageHTTP(sources) { const PEOPLE_URL = `${API_PATH}/people/`; const atomicResponse$ = sources.HTTP .filter(response$ => _.startsWith(response$.request.url, PEOPLE_URL)) .mergeAll() .filter(response => isTruthy(response.body)) .shareReplay(1); const request$ = atomicResponse$ .filter(response => response.body.next) .map(response => response.body.next.replace('limit=5', 'limit=40')) // TODO get real time range from sources somehow .startWith(PEOPLE_URL + '?limit=5&range_start=2015-09-01&range_end=2015-11-30') .map(urlToRequestObjectWithHeaders); const response$ = atomicResponse$ .map(response => response.body.results) .scan((acc, curr) => acc.concat(curr)); return {request$, response$}; // sink } export default PeoplePageHTTP;
Add temporary selection of time range
Add temporary selection of time range While we still don't have the time range filter
JavaScript
apache-2.0
petuomin/power-ui,futurice/power-ui,futurice/power-ui,petuomin/power-ui
--- +++ @@ -15,7 +15,8 @@ const request$ = atomicResponse$ .filter(response => response.body.next) .map(response => response.body.next.replace('limit=5', 'limit=40')) - .startWith(PEOPLE_URL + '?limit=5') + // TODO get real time range from sources somehow + .startWith(PEOPLE_URL + '?limit=5&range_start=2015-09-01&range_end=2015-11-30') .map(urlToRequestObjectWithHeaders); const response$ = atomicResponse$
5695fb2fde82b7e60c647ab60ef7d59f23ba48b3
src/plugins/position/selectors/index.js
src/plugins/position/selectors/index.js
import { createSelector } from 'reselect'; import * as dataSelectors from '../../../selectors/dataSelectors'; export const positionSettingsSelector = state => state.get('positionSettings'); export const getRenderedDataSelector = state => state.get('renderedData'); /** Gets the number of viisble rows based on the height of the container and the rowHeight */ export const visibleRecordCountSelector = createSelector( positionSettingsSelector, (positionSettings) => { const rowHeight = positionSettings.get('rowHeight'); const height = positionSettings.get('height'); return Math.ceil(height / rowHeight); } );
import { createSelector } from 'reselect'; import * as dataSelectors from '../../../selectors/dataSelectors'; export const positionSettingsSelector = state => state.get('positionSettings'); export const getRenderedDataSelector = state => state.get('renderedData'); /** Gets the number of viisble rows based on the height of the container and the rowHeight */ export const visibleRecordCountSelector = createSelector( positionSettingsSelector, (positionSettings) => { const rowHeight = positionSettings.get('rowHeight'); const height = positionSettings.get('height'); return Math.ceil(height / rowHeight); } ); // From what i can tell from the original virtual scrolling plugin... // 1. We want to get the visible record count // 2. Get the size of the dataset we're working with (whether thats local or remote) // 3. Figure out the renderedStart and End display index // 4. Show only the records that'd fall in the render indexes
Add comment about how to proceed
Add comment about how to proceed
JavaScript
mit
GriddleGriddle/Griddle,joellanciaux/Griddle,ttrentham/Griddle,joellanciaux/Griddle,GriddleGriddle/Griddle
--- +++ @@ -17,3 +17,9 @@ return Math.ceil(height / rowHeight); } ); + +// From what i can tell from the original virtual scrolling plugin... +// 1. We want to get the visible record count +// 2. Get the size of the dataset we're working with (whether thats local or remote) +// 3. Figure out the renderedStart and End display index +// 4. Show only the records that'd fall in the render indexes
5d894d920aad8d4a3cea7f40033899523d629e87
src/services/video-catalog/get-video.js
src/services/video-catalog/get-video.js
import Promise from 'bluebird'; import { GetVideoResponse, VideoLocationType } from './protos'; import { toCassandraUuid, toProtobufTimestamp, toProtobufUuid } from '../common/protobuf-conversions'; import { NotFoundError } from '../common/grpc-errors'; import { getCassandraClient } from '../../common/cassandra'; /** * Gets the details of a specific video from the catalog. */ export function getVideo(call, cb) { return Promise.try(() => { let { request } = call; let client = getCassandraClient(); let requestParams = [ toCassandraUuid(request.videoId) ]; return client.executeAsync('SELECT * FROM videos WHERE videoid = ?', requestParams); }) .then(resultSet => { let row = resultSet.first(); if (row === null) { throw new NotFoundError(`A video with id ${request.videoId.value} was not found`); } return new GetVideoResponse({ videoId: toProtobufUuid(row.videoid), userId: toProtobufUuid(row.userid), name: row.name, description: row.description, location: row.location, locationType: row.location_type, tags: row.tags, addedDate: toProtobufTimestamp(row.added_date) }); }) .asCallback(cb); };
import Promise from 'bluebird'; import { GetVideoResponse, VideoLocationType } from './protos'; import { toCassandraUuid, toProtobufTimestamp, toProtobufUuid } from '../common/protobuf-conversions'; import { NotFoundError } from '../common/grpc-errors'; import { getCassandraClient } from '../../common/cassandra'; /** * Gets the details of a specific video from the catalog. */ export function getVideo(call, cb) { return Promise.try(() => { let { request } = call; let client = getCassandraClient(); let requestParams = [ toCassandraUuid(request.videoId) ]; return client.executeAsync('SELECT * FROM videos WHERE videoid = ?', requestParams); }) .then(resultSet => { let row = resultSet.first(); if (row === null) { throw new NotFoundError(`A video with id ${request.videoId.value} was not found`); } return new GetVideoResponse({ videoId: toProtobufUuid(row.videoid), userId: toProtobufUuid(row.userid), name: row.name, description: row.description, location: row.location, locationType: row.location_type, tags: row.tags === null ? [] : row.tags, addedDate: toProtobufTimestamp(row.added_date) }); }) .asCallback(cb); };
Handle null tags when getting video
Handle null tags when getting video - Grpc doesn't allow null for fields and cassandra may return null for tags
JavaScript
apache-2.0
KillrVideo/killrvideo-nodejs,KillrVideo/killrvideo-nodejs
--- +++ @@ -30,7 +30,7 @@ description: row.description, location: row.location, locationType: row.location_type, - tags: row.tags, + tags: row.tags === null ? [] : row.tags, addedDate: toProtobufTimestamp(row.added_date) }); })
bb106effe740a1c6f48408cf613257d07e154586
test/Bugs/Bug_resetisdead.js
test/Bugs/Bug_resetisdead.js
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- function test(p1, p2, p3, p4) { var a = p1 + p3; var b = p2 + p4; if ((p1 + p2) > (p3 + p4) & a > b) { return 1; } if ((p1 + p2) > (p3 + p4) | (p1 + p3) > (p2 + p4)) { return 2; } return 3; } test(1, 20, 3, -1); test(5, 4, 2, -2); WScript.Echo("PASSED");
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- function test(p1, p2, p3, p4) { var a = p1 + p3; var b = p2 + p4; if ((p1 + p2) > (p3 + p4) & a > b) { return 1; } if ((p1 + p2) > (p3 + p4) | (p1 + p3) > (p2 + p4)) { return 2; } return 3; } test(1, 20, 3, -1); test(5, 4, 2, -2); test(15, 3, -11, 4); WScript.Echo("PASSED");
Add an extra call in test script to trigger JIT
Add an extra call in test script to trigger JIT
JavaScript
mit
mrkmarron/ChakraCore,mrkmarron/ChakraCore,Microsoft/ChakraCore,mrkmarron/ChakraCore,Microsoft/ChakraCore,Microsoft/ChakraCore,Microsoft/ChakraCore,Microsoft/ChakraCore,mrkmarron/ChakraCore,mrkmarron/ChakraCore,Microsoft/ChakraCore,mrkmarron/ChakraCore,mrkmarron/ChakraCore
--- +++ @@ -16,5 +16,6 @@ test(1, 20, 3, -1); test(5, 4, 2, -2); +test(15, 3, -11, 4); WScript.Echo("PASSED");
40cbe25e6da39e9261987f3e22fb4b3e00fb3d8c
test/features/router/misc.js
test/features/router/misc.js
'use strict'; // mocha defines to avoid JSHint breakage /* global describe, it, before, beforeEach, after, afterEach */ var assert = require('../../utils/assert.js'); var preq = require('preq'); var server = require('../../utils/server.js'); describe('router - misc', function() { this.timeout(20000); before(function () { return server.start(); }); it('should deny access to /{domain}/sys', function() { return preq.get({ uri: server.config.hostPort + '/en.wikipedia.org/sys/table' }).catch(function(err) { assert.deepEqual(err.status, 403); }); }); });
'use strict'; // mocha defines to avoid JSHint breakage /* global describe, it, before, beforeEach, after, afterEach */ var assert = require('../../utils/assert.js'); var preq = require('preq'); var server = require('../../utils/server.js'); describe('router - misc', function() { this.timeout(20000); before(function () { return server.start(); }); it('should deny access to /{domain}/sys', function() { return preq.get({ uri: server.config.hostPort + '/en.wikipedia.org/sys/table' }).catch(function(err) { assert.deepEqual(err.status, 403); }); }); it('should set a request ID for each sub-request and return it', function() { var slice = server.config.logStream.slice(); return preq.get({ uri: server.config.bucketURL + '/html/Foobar', headers: { 'Cache-Control': 'no-cache' } }).then(function(res) { slice.halt(); var reqId = res.headers['x-request-id']; assert.notDeepEqual(reqId, undefined, 'Request ID not returned'); slice.get().forEach(function(line) { var a = JSON.parse(line); if(a.req || a.request_id) { assert.deepEqual(a.request_id, reqId, 'Request ID mismatch'); } }); }); }); it('should honour the provided request ID', function() { var reqId = 'b6c17ea83d634b31bb28d60aae1caaac'; var slice = server.config.logStream.slice(); return preq.get({ uri: server.config.bucketURL + '/html/Foobar', headers: { 'X-Request-Id': reqId } }).then(function(res) { slice.halt(); assert.deepEqual(res.headers['x-request-id'], reqId, 'Returned request ID does not match the sent one'); slice.get().forEach(function(line) { var a = JSON.parse(line); if(a.req || a.request_id) { assert.deepEqual(a.request_id, reqId, 'Request ID mismatch'); } }); }); }); });
Add tests for the request ID generation and retrieval
Add tests for the request ID generation and retrieval
JavaScript
apache-2.0
wikimedia/hyperswitch,wikimedia/mediawiki-services-restbase,cscott/restbase,milimetric/restbase,gwicke/restbase,inverno/restbase,Pchelolo/restbase,gwicke/restbase,d00rman/restbase,milimetric/restbase,cscott/restbase,eevans/restbase,wikimedia/restbase,physikerwelt/restbase,physikerwelt/restbase,wikimedia/mediawiki-services-restbase,inverno/restbase,eevans/restbase,wikimedia/restbase,Krenair/restbase,Krenair/restbase,d00rman/restbase,Pchelolo/restbase
--- +++ @@ -8,10 +8,10 @@ var server = require('../../utils/server.js'); describe('router - misc', function() { + this.timeout(20000); before(function () { return server.start(); }); - it('should deny access to /{domain}/sys', function() { return preq.get({ @@ -20,5 +20,45 @@ assert.deepEqual(err.status, 403); }); }); - + + it('should set a request ID for each sub-request and return it', function() { + var slice = server.config.logStream.slice(); + return preq.get({ + uri: server.config.bucketURL + '/html/Foobar', + headers: { + 'Cache-Control': 'no-cache' + } + }).then(function(res) { + slice.halt(); + var reqId = res.headers['x-request-id']; + assert.notDeepEqual(reqId, undefined, 'Request ID not returned'); + slice.get().forEach(function(line) { + var a = JSON.parse(line); + if(a.req || a.request_id) { + assert.deepEqual(a.request_id, reqId, 'Request ID mismatch'); + } + }); + }); + }); + + it('should honour the provided request ID', function() { + var reqId = 'b6c17ea83d634b31bb28d60aae1caaac'; + var slice = server.config.logStream.slice(); + return preq.get({ + uri: server.config.bucketURL + '/html/Foobar', + headers: { + 'X-Request-Id': reqId + } + }).then(function(res) { + slice.halt(); + assert.deepEqual(res.headers['x-request-id'], reqId, 'Returned request ID does not match the sent one'); + slice.get().forEach(function(line) { + var a = JSON.parse(line); + if(a.req || a.request_id) { + assert.deepEqual(a.request_id, reqId, 'Request ID mismatch'); + } + }); + }); + }); + });
e148ca00d64217fc7918dbdd7d5f6aaf5c6ac986
app/server.js
app/server.js
/* eslint-disable no-console */ const express = require('express'); const bodyParser = require('body-parser'); const app = express(); const port = process.env.PORT || 3000; const api = require('../lib/api'); app.all('/*', (req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'X-Requested-With'); next(); }); app.use(bodyParser.json({ limit: '5mb' })); app.use(bodyParser.urlencoded({ extended: true })); app.use('/api/v1', api); app.listen(port, () => { console.log(`Listening on port ${port}`); }); /* eslint-enable no-console */
/* eslint-disable no-console */ const express = require('express'); const bodyParser = require('body-parser'); const app = express(); const port = process.env.PORT || 3000; const api = require('../lib/api'); app.all('/*', (req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'X-Requested-With'); next(); }); app.use(bodyParser.json({ limit: '5mb' })); app.use(bodyParser.urlencoded({ extended: true })); app.use('/api/v1', api); app.use('/embed/v1', api); app.use('/embed/api/v1', api); app.listen(port, () => { console.log(`Listening on port ${port}`); }); /* eslint-enable no-console */
Update to use extra endpoints
Update to use extra endpoints
JavaScript
mit
deseretdigital/embeddable-api
--- +++ @@ -16,6 +16,8 @@ app.use(bodyParser.urlencoded({ extended: true })); app.use('/api/v1', api); +app.use('/embed/v1', api); +app.use('/embed/api/v1', api); app.listen(port, () => { console.log(`Listening on port ${port}`);
2f453b6c5b95b37218cd6d8dbb1ad9c1b5ed69ec
js/ector.js
js/ector.js
$(window).load(function () { var Ector = require('ector'); ector = new Ector(); var previousResponseNodes = null; var user = { username: "Guy"}; var msgtpl = $('#msgtpl').html(); var lastmsg = false; $('#msgtpl').remove(); var message; $('#send').on('click', function () { var d = new Date(); var entry = $('#message').val(); message = { user: user, message: entry, h: d.getHours(), m: d.getMinutes() }; $('#message').attr('value',''); // FIXME $('#messages').append('<div class="message">' + Mustache.render(msgtpl, message) + '</div>'); $('#messages').animate({scrollTop : $('#messages').prop('scrollHeight')}, 500); ector.addEntry(entry); ector.linkNodesToLastSentence(previousResponseNodes); var response = ector.generateResponse(); // console.log('%s: %s', ector.name, response.sentence); previousResponseNodes = response.nodes; d = new Date(); message = { user: {username: ector.name}, message: response.sentence, h: d.getHours(), m: d.getMinutes() }; $('#messages').append('<div class="message">' + Mustache.render(msgtpl, message) + '</div>'); $('#messages').animate({scrollTop : $('#messages').prop('scrollHeight')}, 500); return false; }); });
$(window).load(function () { var Ector = require('ector'); ector = new Ector(); var previousResponseNodes = null; var user = { username: "Guy"}; var msgtpl = $('#msgtpl').html(); var lastmsg = false; $('#msgtpl').remove(); var message; $('#send').on('click', function () { var d = new Date(); var entry = $('#message').val(); message = { user: user, message: entry, h: d.getHours(), m: d.getMinutes() }; $('#message').attr('value',''); $('#messages').append('<div class="message">' + Mustache.render(msgtpl, message) + '</div>'); $('#messages').animate({scrollTop : $('#messages').prop('scrollHeight')}, 500); ector.addEntry(entry); ector.linkNodesToLastSentence(previousResponseNodes); var response = ector.generateResponse(); // console.log('%s: %s', ector.name, response.sentence); previousResponseNodes = response.nodes; d = new Date(); message = { user: {username: ector.name}, message: response.sentence, h: d.getHours(), m: d.getMinutes() }; $('#messages').append('<div class="message">' + Mustache.render(msgtpl, message) + '</div>'); $('#messages').animate({scrollTop : $('#messages').prop('scrollHeight')}, 500); return false; }); });
Remove the comment (line already fixed)
Remove the comment (line already fixed)
JavaScript
mit
parmentf/browser-ector
--- +++ @@ -17,7 +17,7 @@ h: d.getHours(), m: d.getMinutes() }; - $('#message').attr('value',''); // FIXME + $('#message').attr('value',''); $('#messages').append('<div class="message">' + Mustache.render(msgtpl, message) + '</div>'); $('#messages').animate({scrollTop : $('#messages').prop('scrollHeight')}, 500);
7ee39396d9b053e19a02eb538c757fede5a20ee2
test/test.require-blocks-on-newline.js
test/test.require-blocks-on-newline.js
var Checker = require('../lib/checker'); var assert = require('assert'); describe('rules/require-blocks-on-newline', function() { var checker; beforeEach(function() { checker = new Checker(); checker.registerDefaultRules(); }); it('should report missing newline after opening brace', function() { checker.configure({ requireBlocksOnNewline: true }); assert(checker.checkString('if (true) {abc();\n}').getErrorCount() === 1); }); it('should report missing newline before closing brace', function() { checker.configure({ requireBlocksOnNewline: true }); assert(checker.checkString('if (true) {\nabc();}').getErrorCount() === 1); }); it('should report missing newlines in both cases', function() { checker.configure({ requireBlocksOnNewline: true }); assert(checker.checkString('if (true) {abc();}').getErrorCount() === 2); }); it('should not report with no spaces', function() { checker.configure({ requireBlocksOnNewline: true }); assert(checker.checkString('if (true) {\nabc();\n}').isEmpty()); }); it('should not report empty function definitions', function() { checker.configure({ requireBlocksOnNewline: true }); assert(checker.checkString('var a = function() {};').isEmpty()); }); });
var Checker = require('../lib/checker'); var assert = require('assert'); describe('rules/require-blocks-on-newline', function() { var checker; beforeEach(function() { checker = new Checker(); checker.registerDefaultRules(); checker.configure({ requireBlocksOnNewline: true }); }); it('should report missing newline after opening brace', function() { assert(checker.checkString('if (true) {abc();\n}').getErrorCount() === 1); }); it('should report missing newline before closing brace', function() { assert(checker.checkString('if (true) {\nabc();}').getErrorCount() === 1); }); it('should report missing newlines in both cases', function() { assert(checker.checkString('if (true) {abc();}').getErrorCount() === 2); }); it('should not report with no spaces', function() { assert(checker.checkString('if (true) {\nabc();\n}').isEmpty()); }); it('should not report empty function definitions', function() { assert(checker.checkString('var a = function() {};').isEmpty()); }); });
Move checker.configure(...) line to beforeeach
Move checker.configure(...) line to beforeeach
JavaScript
mit
ValYouW/node-jscs,SimenB/node-jscs,natemara/node-jscs,pm5/node-jscs,hafeez-syed/node-jscs,ronkorving/node-jscs,allain/node-jscs,yous/node-jscs,paladox/node-jscs,romanblanco/node-jscs,lukeapage/node-jscs,markelog/node-jscs,kaicataldo/node-jscs,kadamwhite/node-jscs,yejodido/node-jscs,fishbar/node-jscs,zxqfox/node-jscs,yomed/node-jscs,irnc/node-jscs,jamesreggio/node-jscs,FGRibreau/node-jscs,xwp/node-jscs,SimenB/node-jscs,indexzero/node-jscs,ValYouW/node-jscs,pm5/node-jscs,alawatthe/node-jscs,kangax/node-jscs,mcanthony/node-jscs,ptarjan/node-jscs,bjdixon/node-jscs,stevemao/node-jscs,elijahmanor/node-jscs,marian-r/node-jscs,jamesreggio/node-jscs,bengourley/node-jscs,jscs-dev/node-jscs,nantunes/node-jscs,benjaffe/node-jscs,markelog/node-jscs,addyosmani/node-jscs,seegno/node-jscs,oredi/node-jscs,hzoo/node-jscs,christophehurpeau/node-jscs,1999/node-jscs,faceleg/node-jscs,dreef3/node-jscs,jdforrester/node-jscs,zxqfox/node-jscs,ecomfe/edp-jscs,gibson042/node-jscs,jscs-dev/node-jscs,TheSavior/node-jscs,hzoo/node-jscs,Slayer95/node-jscs,MunGell/node-jscs,iamstarkov/node-jscs,ficristo/node-jscs,kylepaulsen/node-jscs,elijahmanor/node-jscs,existentialism/node-jscs,mrjoelkemp/node-jscs,kylepaulsen/node-jscs,aptiko/node-jscs,Krinkle/node-jscs,kaicataldo/node-jscs,bjdixon/node-jscs,Qix-/node-jscs,lukeapage/node-jscs,BigBlueHat/node-jscs,ficristo/node-jscs,arschmitz/node-jscs,indexzero/node-jscs,mcanthony/node-jscs
--- +++ @@ -6,25 +6,21 @@ beforeEach(function() { checker = new Checker(); checker.registerDefaultRules(); + checker.configure({ requireBlocksOnNewline: true }); }); it('should report missing newline after opening brace', function() { - checker.configure({ requireBlocksOnNewline: true }); assert(checker.checkString('if (true) {abc();\n}').getErrorCount() === 1); }); it('should report missing newline before closing brace', function() { - checker.configure({ requireBlocksOnNewline: true }); assert(checker.checkString('if (true) {\nabc();}').getErrorCount() === 1); }); it('should report missing newlines in both cases', function() { - checker.configure({ requireBlocksOnNewline: true }); assert(checker.checkString('if (true) {abc();}').getErrorCount() === 2); }); it('should not report with no spaces', function() { - checker.configure({ requireBlocksOnNewline: true }); assert(checker.checkString('if (true) {\nabc();\n}').isEmpty()); }); it('should not report empty function definitions', function() { - checker.configure({ requireBlocksOnNewline: true }); assert(checker.checkString('var a = function() {};').isEmpty()); }); });
23ee4cadc3fd6f7ffe86dcb2eddca59c8cea7920
core/server/controllers/frontend.js
core/server/controllers/frontend.js
/** * Main controller for Ghost frontend */ /*global require, module */ var Ghost = require('../../ghost'), api = require('../api'), ghost = new Ghost(), frontendControllers; frontendControllers = { 'homepage': function (req, res) { // Parse the page number var pageParam = req.params.page !== undefined ? parseInt(req.params.page, 10) : 1; // No negative pages if (pageParam < 1) { return res.redirect("/page/1/"); } api.posts.browse({page: pageParam}).then(function (page) { // If page is greater than number of pages we have, redirect to last page if (pageParam > page.pages) { return res.redirect("/page/" + (page.pages) + "/"); } // Render the page of posts ghost.doFilter('prePostsRender', page.posts, function (posts) { res.render('index', {posts: posts, pagination: {page: page.page, prev: page.prev, next: page.next, limit: page.limit, total: page.total, pages: page.pages}}); }); }); }, 'single': function (req, res) { api.posts.read({'slug': req.params.slug}).then(function (post) { ghost.doFilter('prePostsRender', post.toJSON(), function (post) { res.render('post', {post: post}); }); }); } }; module.exports = frontendControllers;
/** * Main controller for Ghost frontend */ /*global require, module */ var Ghost = require('../../ghost'), api = require('../api'), ghost = new Ghost(), frontendControllers; frontendControllers = { 'homepage': function (req, res) { // Parse the page number var pageParam = req.params.page !== undefined ? parseInt(req.params.page, 10) : 1; // No negative pages if (pageParam < 1) { return res.redirect("/page/1/"); } api.posts.browse({page: pageParam}).then(function (page) { var maxPage = page.pages; // A bit of a hack for situations with no content. if (maxPage === 0) { maxPage = 1; page.pages = 1; } // If page is greater than number of pages we have, redirect to last page if (pageParam > maxPage) { return res.redirect("/page/" + maxPage + "/"); } // Render the page of posts ghost.doFilter('prePostsRender', page.posts, function (posts) { res.render('index', {posts: posts, pagination: {page: page.page, prev: page.prev, next: page.next, limit: page.limit, total: page.total, pages: page.pages}}); }); }); }, 'single': function (req, res) { api.posts.read({'slug': req.params.slug}).then(function (post) { ghost.doFilter('prePostsRender', post.toJSON(), function (post) { res.render('post', {post: post}); }); }); } }; module.exports = frontendControllers;
Fix redirect loop when no content
Fix redirect loop when no content
JavaScript
mit
exsodus3249/Ghost,acburdine/Ghost,epicmiller/pages,virtuallyearthed/Ghost,memezilla/Ghost,veyo-care/Ghost,KnowLoading/Ghost,Brunation11/Ghost,camilodelvasto/herokughost,JonathanZWhite/Ghost,hnarayanan/narayanan.co,ghostchina/Ghost.zh,lukaszklis/Ghost,ignasbernotas/nullifer,mhhf/ghost-latex,Kaenn/Ghost,Yarov/yarov,situkangsayur/Ghost,bastianbin/Ghost,pollbox/ghostblog,NikolaiIvanov/Ghost,Polyrhythm/dolce,sunh3/Ghost,ygbhf/Ghost,dggr/Ghost-sr,jeonghwan-kim/Ghost,ClarkGH/Ghost,zhiyishou/Ghost,makapen/Ghost,johnnymitch/Ghost,xiongjungit/Ghost,benstoltz/Ghost,katrotz/blog.katrotz.space,vloom/blog,Trendy/Ghost,dbalders/Ghost,mnitchie/Ghost,wemakeweb/Ghost,sajmoon/Ghost,sceltoas/Ghost,yangli1990/Ghost,madole/diverse-learners,atandon/Ghost,praveenscience/Ghost,stridespace/Ghost,sfpgmr/Ghost,zeropaper/Ghost,ErisDS/Ghost,bitjson/Ghost,JulienBrks/Ghost,RoopaS/demo-intern,beautyOfProgram/Ghost,Dnlyc/Ghost,johngeorgewright/blog.j-g-w.info,rameshponnada/Ghost,barbastan/Ghost,jomofrodo/ccb-ghost,Japh/Ghost,disordinary/Ghost,Klaudit/Ghost,yanntech/Ghost,k2byew/Ghost,optikalefx/Ghost,adam-paterson/blog,phillipalexander/Ghost,lanffy/Ghost,skleung/blog,schematical/Ghost,singular78/Ghost,Japh/shortcoffee,bsansouci/Ghost,allspiritseve/mindlikewater,AlexKVal/Ghost,mhhf/ghost-latex,avh4/blog.avh4.net,francisco-filho/Ghost,smedrano/Ghost,petersucks/blog,halfdan/Ghost,Sebastian1011/Ghost,atandon/Ghost,cwonrails/Ghost,IbrahimAmin/Ghost,davidmenger/nodejsfan,skmezanul/Ghost,mdbw/ghost,singular78/Ghost,Remchi/Ghost,mattvh/Ghost,chevex/undoctrinate,edsadr/Ghost,handcode7/Ghost,jin/Ghost,cysys/ghost-openshift,omaracrystal/Ghost,e10/Ghost,letsjustfixit/Ghost,Jai-Chaudhary/Ghost,virtuallyearthed/Ghost,etanxing/Ghost,marchdoe/derose,ckousik/Ghost,jaswilli/Ghost,ivanoats/ivanstorck.com,mttschltz/ghostblog,Feitianyuan/Ghost,vainglori0us/urban-fortnight,mtvillwock/Ghost,mohanambati/Ghost,claudiordgz/Ghost,NovaDevelopGroup/Academy,dqj/Ghost,shannonshsu/Ghost,duyetdev/islab,makapen/Ghost,nneko/Ghost,TryGhost/Ghost,camilodelvasto/localghost,jgladch/taskworksource,tadityar/Ghost,yangli1990/Ghost,ladislas/ghost,bbmepic/Ghost,alanmoo/moo-on-the-web,blankmaker/Ghost,rollokb/Ghost,hyokosdeveloper/Ghost,omaracrystal/Ghost,hoxoa/Ghost,techfashionlife/blog,thomasalrin/Ghost,v3rt1go/Ghost,wallmarkets/Ghost,tyrikio/Ghost,JulienBrks/Ghost,notno/Ghost,sunh3/Ghost,lowkeyfred/Ghost,TryGhost/Ghost,jparyani/GhostSS,yanntech/Ghost,sergeylukin/Ghost,ghostchina/website,psychobunny/Ghost,laispace/laiblog,hawkrives/Wraith,notno/Ghost,Smile42RU/Ghost,mtvillwock/Ghost,greyhwndz/Ghost,Sing-Li/GhostSS,tksander/Ghost,gleneivey/Ghost,novaugust/Ghost,jiachenning/Ghost,BayPhillips/Ghost,alecho/Ghost,shrimpy/Ghost,netputer/Ghost,trunk-studio/Ghost,rafaelstz/Ghost,shrimpy/Ghost,jgillich/Ghost,Azzurrio/Ghost,zackslash/Ghost,alecho/Ghost,daimaqiao/Ghost-Bridge,ghostchina/Ghost-zh,wemakeweb/Ghost,mohanambati/Ghost,gcamana/Ghost,rameshponnada/Ghost,r1N0Xmk2/Ghost,daihuaye/Ghost,ryanbrunner/crafters,consoleblog/consoleblog,augbog/Ghost,MadeOnMars/Ghost,achimos/ghost_as,ITJesse/Ghost-zh,Yarov/yarov,jeonghwan-kim/Ghost,Jonekee/Ghost,mattchupp/blog,ryanorsinger/tryghost,prosenjit-itobuz/Ghost,kmeurer/GhostAzureSetup,tanbo800/Ghost,aroneiermann/GhostJade,techfashionlife/blog,Netazoic/bad-gateway,panezhang/Ghost,vainglori0us/urban-fortnight,hoxoa/Ghost,rizkyario/Ghost,krahman/Ghost,lf2941270/Ghost,arvidsvensson/Ghost,tandrewnichols/ghost,fredeerock/atlabghost,netputer/Ghost,scopevale/wethepeopleweb.org,julianromera/Ghost,petersucks/blog,chris-yoon90/Ghost,acburdine/Ghost,davidblurton/salmondesign-old,riyadhalnur/Ghost,manishchhabra/Ghost,daimaqiao/Ghost-Bridge,jomahoney/Ghost,qdk0901/Ghost,delgermurun/Ghost,alexandrachifor/Ghost,r14r/fork_nodejs_ghost,choskim/Ghost,javorszky/Ghost,ManRueda/Ghost,pedroha/Ghost,delgermurun/Ghost,uniqname/everydaydelicious,ryanbrunner/crafters,sebgie/Ghost,yujingz/yujignz.com,rchrd2/Ghost,floofydoug/Ghost,devleague/uber-hackathon,andrewconnell/Ghost,floofydoug/Ghost,aroneiermann/GhostJade,eduardojmatos/eduardomatos.me,davegw/dgw-website,theonlypat/Ghost,Feitianyuan/Ghost,ballPointPenguin/Ghost,Bunk/Ghost,lukaszklis/Ghost,rmoorman/Ghost,10hacks/blog,kortemy/Ghost,lowkeyfred/Ghost,BlueHatbRit/Ghost,flomotlik/Ghost,daihuaye/Ghost,psychobunny/Ghost,ThorstenHans/Ghost,ddeveloperr/Ghost,lf2941270/Ghost,melissaroman/ghost-blog,disordinary/Ghost,greenboxindonesia/Ghost,tidyui/Ghost,mayconxhh/Ghost,icowan/Ghost,xiongjungit/Ghost,yujingz/yujignz.com,telco2011/Ghost,kevinansfield/Ghost,jorgegilmoreira/ghost,ericbenson/GhostAzureSetup,jacostag/Ghost,klinker-apps/ghost,woodyrew/Ghost,tksander/Ghost,Gargol/Ghost,klinker-apps/ghost,dggr/Ghost-sr,AlexKVal/Ghost,mdbw/ghost,cqricky/Ghost,jiangjian-zh/Ghost,ljhsai/Ghost,YY030913/Ghost,mattchupp/blog,bisoe/Ghost,davidmenger/nodejsfan,denzelwamburu/denzel.xyz,camilodelvasto/herokughost,kwangkim/Ghost,lcamacho/Ghost,kolorahl/Ghost,rafaelstz/Ghost,llv22/Ghost,k2byew/Ghost,cysys/ghost-openshift,SachaG/bjjbot-blog,adam-paterson/blog,tmp-reg/Ghost,ManRueda/Ghost,cwonrails/Ghost,duyetdev/islab,telco2011/Ghost,TribeMedia/Ghost,skmezanul/Ghost,carlosmtx/Ghost,allspiritseve/mindlikewater,AileenCGN/Ghost,rito/Ghost,tanbo800/Ghost,influitive/crafters,NodeJSBarenko/Ghost,ericbenson/GhostAzureSetup,JonSmith/Ghost,cwonrails/Ghost,Loyalsoldier/Ghost,diogogmt/Ghost,prosenjit-itobuz/Ghost,tchapi/igneet-blog,sifatsultan/js-ghost,flpms/ghost-ad,nmukh/Ghost,dymx101/Ghost,Loyalsoldier/Ghost,IbrahimAmin/Ghost,TryGhost/Ghost,lukekhamilton/Ghost,etdev/blog,patterncoder/patterncoder,skleung/blog,dqj/Ghost,codeincarnate/Ghost,optikalefx/Ghost,dylanchernick/ghostblog,ghostchina/Ghost.zh,InnoD-WebTier/hardboiled_ghost,Netazoic/bad-gateway,yundt/seisenpenji,carlyledavis/Ghost,kaiqigong/Ghost,kevinansfield/Ghost,RufusMbugua/TheoryOfACoder,jorgegilmoreira/ghost,rwjblue/Ghost,davidenq/Ghost-Blog,handcode7/Ghost,edurangel/Ghost,davidenq/Ghost-Blog,bosung90/Ghost,trepafi/ghost-base,Dnlyc/Ghost,thehogfather/Ghost,STANAPO/Ghost,janvt/Ghost,ManRueda/manrueda-blog,kmeurer/Ghost,thinq4yourself/Unmistakable-Blog,maverickcoders/blog,carlyledavis/Ghost,Coding-House/Ghost,developer-prosenjit/Ghost,katrotz/blog.katrotz.space,Trendy/Ghost,dYale/blog,PDXIII/Ghost-FormMailer,liftup/ghost,pbevin/Ghost,javimolla/Ghost,kaiqigong/Ghost,JohnONolan/Ghost,mnitchie/Ghost,jamesyothers/Ghost,PepijnSenders/whatsontheotherside,ashishapy/ghostpy,vainglori0us/urban-fortnight,jin/Ghost,rouanw/Ghost,sajmoon/Ghost,darvelo/Ghost,phillipalexander/Ghost,halfdan/Ghost,jomahoney/Ghost,trunk-studio/Ghost,situkangsayur/Ghost,jgillich/Ghost,mohanambati/Ghost,bastianbin/Ghost,DesenTao/Ghost,TribeMedia/Ghost,pensierinmusica/Ghost,codeincarnate/Ghost,smaty1/Ghost,NovaDevelopGroup/Academy,kortemy/Ghost,SkynetInc/steam,ngosinafrica/SiteForNGOs,mattvh/Ghost,Empeeric/justanidea,obsoleted/Ghost,Romdeau/Ghost,mttschltz/ghostblog,UnbounDev/Ghost,karmakaze/Ghost,ljhsai/Ghost,PaulBGD/Ghost-Plus,NovaDevelopGroup/Academy,ASwitlyk/Ghost,arvidsvensson/Ghost,cicorias/Ghost,lanffy/Ghost,FredericBernardo/Ghost,marchdoe/derose,jomofrodo/ccb-ghost,kmeurer/Ghost,Shauky/Ghost,JohnONolan/Ghost,lethalbrains/Ghost,pensierinmusica/Ghost,cncodog/Ghost-zh-codog,jparyani/GhostSS,hnq90/Ghost,NamedGod/Ghost,Alxandr/Blog,rchrd2/Ghost,NamedGod/Ghost,qdk0901/Ghost,karmakaze/Ghost,PeterCxy/Ghost,JohnONolan/Ghost,ckousik/Ghost,Rovak/Ghost,tuan/Ghost,AnthonyCorrado/Ghost,jaguerra/Ghost,ddeveloperr/Ghost,diancloud/Ghost,morficus/Ghost,olsio/Ghost,novaugust/Ghost,jamesyothers/Ghost,ashishapy/ghostpy,leonli/ghost,10hacks/blog,devleague/uber-hackathon,axross/ghost,lukw00/Ghost,lethalbrains/Ghost,ryansukale/ux.ryansukale.com,r14r/fork_nodejs_ghost,anijap/PhotoGhost,Netazoic/bad-gateway,YY030913/Ghost,chris-yoon90/Ghost,praveenscience/Ghost,Elektro1776/javaPress,smaty1/Ghost,ngosinafrica/SiteForNGOs,barbastan/Ghost,dggr/Ghost-sr,hnq90/Ghost,wspandihai/Ghost,Japh/shortcoffee,LeandroNascimento/Ghost,zackslash/Ghost,bigertech/Ghost,thehogfather/Ghost,neynah/GhostSS,neynah/GhostSS,InnoD-WebTier/hardboiled_ghost,cncodog/Ghost-zh-codog,influitive/crafters,weareleka/blog,Japh/Ghost,zhiyishou/Ghost,ASwitlyk/Ghost,denzelwamburu/denzel.xyz,davidblurton/salmondesign-old,yundt/seisenpenji,edsadr/Ghost,wallmarkets/Ghost,load11/ghost,rizkyario/Ghost,andrewconnell/Ghost,schneidmaster/theventriloquist.us,rollokb/Ghost,hilerchyn/Ghost,UsmanJ/Ghost,manishchhabra/Ghost,mlabieniec/ghost-env,uploadcare/uploadcare-ghost-demo,letsjustfixit/Ghost,sebgie/Ghost,djensen47/Ghost,ClarkGH/Ghost,janvt/Ghost,Netazoic/bad-gateway,icowan/Ghost,zumobi/Ghost,beautyOfProgram/Ghost,ignasbernotas/nullifer,dbalders/Ghost,gleneivey/Ghost,kwangkim/Ghost,aschmoe/jesse-ghost-app,shannonshsu/Ghost,telco2011/Ghost,1kevgriff/Ghost,GarrethDottin/Habits-Design,veyo-care/Ghost,johngeorgewright/blog.j-g-w.info,leonli/ghost,bitjson/Ghost,cysys/ghost-openshift,nmukh/Ghost,choskim/GhostAzure,GroupxDev/javaPress,benstoltz/Ghost,ThorstenHans/Ghost,PeterCxy/Ghost,schematical/Ghost,freele/ghost,oimou-house/blog,mikecastro26/ghost-custom,laispace/laiblog,rizkyario/Ghost,bosung90/Ghost,metadevfoundation/Ghost,UnbounDev/Ghost,ErisDS/Ghost,stridespace/Ghost,imjerrybao/Ghost,JonathanZWhite/Ghost,zuphu/GhostBlog,vloom/blog,VillainyStudios/Ghost,SachaG/bjjbot-blog,PDXIII/Ghost-FormMailer,madole/diverse-learners,patrickdbakke/ghost-spa,gabfssilva/Ghost,jamesslock/Ghost,DesenTao/Ghost,GarrethDottin/Habits-Design,leninhasda/Ghost,LeandroNascimento/Ghost,ananthhh/Ghost,dai-shi/Ghost,camilodelvasto/localghost,ErisDS/Ghost,Alxandr/Blog,allanjsx/Ghost,aschmoe/jesse-ghost-app,letsjustfixit/Ghost,no1lov3sme/Ghost,singular78/Ghost,Remchi/Ghost,jiangjian-zh/Ghost,MadeOnMars/Ghost,dbalders/Ghost,etdev/blog,ladislas/ghost,greenboxindonesia/Ghost,bbmepic/Ghost,SkynetInc/steam,liftup/ghost,morficus/Ghost,PepijnSenders/whatsontheotherside,leonli/ghost,devleague/uber-hackathon,FredericBernardo/Ghost,francisco-filho/Ghost,rito/Ghost,johnnymitch/Ghost,cobbspur/Ghost,claudiordgz/Ghost,thomasalrin/Ghost,jamesslock/Ghost,achimos/ghost_as,Romdeau/Ghost,dgem/Ghost,cqricky/Ghost,akveo/akveo-blog,ineitzke/Ghost,kortemy/Ghost,syaiful6/Ghost,mlabieniec/ghost-env,kaychaks/kaushikc.org,syaiful6/Ghost,ITJesse/Ghost-zh,UsmanJ/Ghost,hnarayanan/narayanan.co,load11/ghost,Smile42RU/Ghost,pathayes/FoodBlog,ballPointPenguin/Ghost,ryansukale/ux.ryansukale.com,ManRueda/manrueda-blog,Rovak/Ghost,Kikobeats/Ghost,katiefenn/Ghost,v3rt1go/Ghost,edurangel/Ghost,pollbox/ghostblog,InnoD-WebTier/hardboiled_ghost,axross/ghost,ygbhf/Ghost,Klaudit/Ghost,cicorias/Ghost,ananthhh/Ghost,blankmaker/Ghost,exsodus3249/Ghost,neynah/GhostSS,Jonekee/Ghost,hawkrives/Wraith,diogogmt/Ghost,tidyui/Ghost,jaguerra/Ghost,tyrikio/Ghost,fredeerock/atlabghost,Bunk/Ghost,Azzurrio/Ghost,allanjsx/Ghost,vlmhco/personal-blog,Gargol/Ghost,GroupxDev/javaPress,BlueHatbRit/Ghost,laispace/laiblog,Kikobeats/Ghost,melissaroman/ghost-blog,aexmachina/blog-old,RufusMbugua/TheoryOfACoder,nneko/Ghost,javimolla/Ghost,panezhang/Ghost,cgiffard/Ghost,kevinansfield/Ghost,weareleka/blog,JonSmith/Ghost,choskim/Ghost,Brunation11/Ghost,jorgegilmoreira/ghost,schneidmaster/theventriloquist.us,javorszky/Ghost,anijap/PhotoGhost,sifatsultan/js-ghost,velimir0xff/Ghost,dylanchernick/ghostblog,choskim/ghost_exp,sangcu/Ghost,ManRueda/Ghost,lukekhamilton/Ghost,ManRueda/manrueda-blog,ivantedja/ghost,augbog/Ghost,epicmiller/pages,medialab/Ghost,zeropaper/Ghost,rouanw/Ghost,davidenq/Ghost-Blog,developer-prosenjit/Ghost,allanjsx/Ghost,velimir0xff/Ghost,Alxandr/Blog,etanxing/Ghost,ivanoats/ivanstorck.com,nakamuraapp/new-ghost,Sebastian1011/Ghost,rtorino/me-etc,leninhasda/Ghost,woodyrew/Ghost,Kikobeats/Ghost,tandrewnichols/ghost,lukw00/Ghost,memezilla/Ghost,novaugust/Ghost,cncodog/Ghost-zh-codog,e10/Ghost,Elektro1776/javaPress,sergeylukin/Ghost,Elektro1776/javaPress,MrMaksimize/sdg1,sangcu/Ghost,rmoorman/Ghost,julianromera/Ghost,jparyani/GhostSS,kolorahl/Ghost,gabfssilva/Ghost,uploadcare/uploadcare-ghost-demo,Jai-Chaudhary/Ghost,bsansouci/Ghost,flpms/ghost-ad,theonlypat/Ghost,acburdine/Ghost,gcamana/Ghost,diancloud/Ghost,GroupxDev/javaPress,Kaenn/Ghost,wangjun/Ghost,flomotlik/Ghost,sfpgmr/Ghost,sebgie/Ghost,llv22/Ghost,bisoe/Ghost,pbevin/Ghost,sceltoas/Ghost,zumobi/Ghost,jacostag/Ghost,choskim/GhostAzure,AnthonyCorrado/Ghost,daimaqiao/Ghost-Bridge,davegw/dgw-website,Xibao-Lv/Ghost,obsoleted/Ghost,djensen47/Ghost,KnowLoading/Ghost,patterncoder/patterncoder,hyokosdeveloper/Ghost,tadityar/Ghost,NikolaiIvanov/Ghost,kaychaks/kaushikc.org,sankumsek/Ghost-ashram,dai-shi/Ghost,carlosmtx/Ghost,Kaenn/Ghost,BayPhillips/Ghost,ineitzke/Ghost,akveo/akveo-blog,metadevfoundation/Ghost,imjerrybao/Ghost,vishnuharidas/Ghost,ghostchina/Ghost-zh,greyhwndz/Ghost,no1lov3sme/Ghost,dYale/blog,maverickcoders/blog,PaulBGD/Ghost-Plus,Aaron1992/Ghost,olsio/Ghost,wangjun/Ghost,wspandihai/Ghost,medialab/Ghost,jiachenning/Ghost,jaswilli/Ghost,mlabieniec/ghost-env,Xibao-Lv/Ghost,thinq4yourself/Unmistakable-Blog,jomofrodo/ccb-ghost,dgem/Ghost,pedroha/Ghost,smedrano/Ghost,VillainyStudios/Ghost,darvelo/Ghost,r1N0Xmk2/Ghost,STANAPO/Ghost,pathayes/FoodBlog,mayconxhh/Ghost,hilerchyn/Ghost,stridespace/Ghost,dymx101/Ghost,maverickcoders/blog,riyadhalnur/Ghost,Coding-House/Ghost,tmp-reg/Ghost
--- +++ @@ -21,9 +21,17 @@ } api.posts.browse({page: pageParam}).then(function (page) { + var maxPage = page.pages; + + // A bit of a hack for situations with no content. + if (maxPage === 0) { + maxPage = 1; + page.pages = 1; + } + // If page is greater than number of pages we have, redirect to last page - if (pageParam > page.pages) { - return res.redirect("/page/" + (page.pages) + "/"); + if (pageParam > maxPage) { + return res.redirect("/page/" + maxPage + "/"); } // Render the page of posts
72903d6e02d58b5e3441e302c0c7f253d2a7cc9e
test/color-finderSpec.js
test/color-finderSpec.js
/** * Created by alex on 11/30/15. */ describe('ColorFinder class', function () { it('should get default config value', function () { expect(ColorFinder.getConfig('maxColorValue')).toBe(230); }); it('should update config value', function () { expect(ColorFinder.setConfig('maxColorValue', 200).getConfig('maxColorValue')).toBe(200); }); });
/** * Created by alex on 11/30/15. */ describe('ColorFinder class', function () { it('should get default config value', function () { expect(ColorFinder.getConfig('maxColorValue')).toBe(230); }); it('should update config value', function () { expect(ColorFinder.setConfig('maxColorValue', 200).getConfig('maxColorValue')).toBe(200); }); it('should throw error if config key unknown', function () { expect(function () { ColorFinder.setConfig('customConfig', 'OK?'); }).toThrow(new Error('ColorFinder: setConfig: Invalid config key')); }); });
Add one more test to init travis
Add one more test to init travis
JavaScript
mit
gund/color-finder,gund/color-finder
--- +++ @@ -12,4 +12,10 @@ expect(ColorFinder.setConfig('maxColorValue', 200).getConfig('maxColorValue')).toBe(200); }); + it('should throw error if config key unknown', function () { + expect(function () { + ColorFinder.setConfig('customConfig', 'OK?'); + }).toThrow(new Error('ColorFinder: setConfig: Invalid config key')); + }); + });
8d5ea01c20eff5dcb344e51cfc422236c95ad789
test/integration/ripple_transactions.js
test/integration/ripple_transactions.js
var RippleGateway = require('../../lib/http_client.js').Gateway; var crypto = require('crypto'); var assert = require('assert'); function rand() { return crypto.randomBytes(32).toString('hex'); } describe('RippleTransactions', function(){ describe('on behalf of a user', function(){ it.skip('should create a payment to a ripple account', function(){ // POST /payments done(); }); it.skip('should not be able to send a payment to the gateway', function(){ // POST /payments done(); }); it.skip('should list all payments made to or from a user', function(){ // GET /payments done(); }); }); describe('on behalf of an admin', function(){ it.skip('should create payment to a ripple account', function(){ // POST /payments done(); }); it.skip('should list payments sent to or from a hosted wallet', function(){ // GET /payments done(); }); it.skip('should list all payments made to or from all hosted wallets', function(){ // GET /payments done(); }); }); });
var RippleGateway = require('../../lib/http_client.js').Gateway; var crypto = require('crypto'); var assert = require('assert'); function rand() { return crypto.randomBytes(32).toString('hex'); } describe('RippleTransactions', function(){ describe('on behalf of a user', function(){ before(function(done){ client = new RippleGateway.Client({ api: 'https://localhost:4000' }); client.user = rand(); client.secret = rand(); client.createUser({}, function(err, resp){ if (err) { throw new Error(err); } user = resp; done(); }); }); it('should create a payment to a ripple account', function(done){ var paymentOptions = { to_account: 'rNeSkJhcxDaqzZCAvSfQrxwPJ2Kjddrj4a', from_account: 'rNeSkJhcxDaqzZCAvSfQrxwPJ2Kjddrj4a', from_tag: '2', amount: '1', currency: 'USD' }; client.sendPayment(paymentOptions, function(err, payment){ console.log(err, payment); assert(!err); assert(payment.id > 0); done(); }); }); it('should not be able to send a payment to the gateway', function(done){ // POST /payments assert(true); done(); }); it.skip('should list all payments made to or from a user', function(done){ // GET /payments done(); }); }); describe('on behalf of an admin', function(){ it.skip('should create payment to a ripple account', function(done){ // POST /payments done(); }); it.skip('should list payments sent to or from a hosted wallet', function(done){ // GET /payments done(); }); it.skip('should list all payments made to or from all hosted wallets', function(done){ // GET /payments done(); }); }); });
Add example test for sending payment.
[TEST] Add example test for sending payment.
JavaScript
isc
crazyquark/gatewayd,xdv/gatewayd,zealord/gatewayd,xdv/gatewayd,zealord/gatewayd,Parkjeahwan/awegeeks,whotooktwarden/gatewayd,Parkjeahwan/awegeeks,crazyquark/gatewayd,whotooktwarden/gatewayd
--- +++ @@ -7,17 +7,42 @@ describe('on behalf of a user', function(){ - it.skip('should create a payment to a ripple account', function(){ + before(function(done){ + client = new RippleGateway.Client({ + api: 'https://localhost:4000' + }); + client.user = rand(); + client.secret = rand(); + client.createUser({}, function(err, resp){ + if (err) { throw new Error(err); } + user = resp; + done(); + }); + }); + + it('should create a payment to a ripple account', function(done){ + var paymentOptions = { + to_account: 'rNeSkJhcxDaqzZCAvSfQrxwPJ2Kjddrj4a', + from_account: 'rNeSkJhcxDaqzZCAvSfQrxwPJ2Kjddrj4a', + from_tag: '2', + amount: '1', + currency: 'USD' + }; + client.sendPayment(paymentOptions, function(err, payment){ + console.log(err, payment); + assert(!err); + assert(payment.id > 0); + done(); + }); + }); + + it('should not be able to send a payment to the gateway', function(done){ // POST /payments + assert(true); done(); }); - it.skip('should not be able to send a payment to the gateway', function(){ - // POST /payments - done(); - }); - - it.skip('should list all payments made to or from a user', function(){ + it.skip('should list all payments made to or from a user', function(done){ // GET /payments done(); }); @@ -26,17 +51,17 @@ describe('on behalf of an admin', function(){ - it.skip('should create payment to a ripple account', function(){ + it.skip('should create payment to a ripple account', function(done){ // POST /payments done(); }); - it.skip('should list payments sent to or from a hosted wallet', function(){ + it.skip('should list payments sent to or from a hosted wallet', function(done){ // GET /payments done(); }); - it.skip('should list all payments made to or from all hosted wallets', function(){ + it.skip('should list all payments made to or from all hosted wallets', function(done){ // GET /payments done(); });
fbfdc3d6eabd194d558717716b4397ad9f693dbc
controllers/api/posts.js
controllers/api/posts.js
var router = require( 'express' ).Router() var Post = require( '../../models/post' ) var websockets = require( '../../websockets' ) router.get( '/', function( req, res, next ) { Post.find() .sort( '-date' ) .exec( function( err, posts ) { if ( err ) { return next( err ) } res.json( posts ) }) }) router.post( '/', function( req, res, next ) { var post = new Post({ body: req.body.body }) post.username = req.auth.username post.save( function ( err, post ) { if ( err ) { return next( err ) } websockets.broadcast( 'new_post', post ) res.json( 201, post ) }) }) module.exports = router
var router = require( 'express' ).Router() var Post = require( '../../models/post' ) var websockets = require( '../../websockets' ) router.get( '/', function( req, res, next ) { Post.find() .sort( '-date' ) .exec( function( err, posts ) { if ( err ) { return next( err ) } res.json( posts ) }) }) router.post( '/', function( req, res, next ) { var post = new Post({ body: req.body.body }) post.username = req.auth.username post.save( function ( err, post ) { if ( err ) { return next( err ) } websockets.broadcast( 'new_post', post ) res.status( 201).json( post ) }) }) module.exports = router
Change post json handling on success
Change post json handling on success
JavaScript
mit
Driftologist/texturepot,Driftologist/texturepot
--- +++ @@ -20,7 +20,7 @@ post.save( function ( err, post ) { if ( err ) { return next( err ) } websockets.broadcast( 'new_post', post ) - res.json( 201, post ) + res.status( 201).json( post ) }) })
289c01cbfffbafff6cf0d968e188730085015a39
spec/baristaModelSpec.js
spec/baristaModelSpec.js
var Barista = require(process.cwd() + '/lib/barista.js'), Backbone = require('backbone'), ExampleApp = require(process.cwd() + '/spec/ex1/exampleApp1.js'), context = describe; describe('Barista.Model', function() { var model; beforeEach(function() { Barista.config(ExampleApp); }); describe('isA', function() { it('returns true with arg \'Backbone.Model\'', function() { var newModel = new Barista.Model(); expect(newModel.isA('Backbone.Model')).toBe(true); }); it('returns true with arg\'Barista.Model\'', function() { var newModel = new Barista.Model(); expect(newModel.isA('Barista.Model')).toBe(true); }); it('returns false with another argument', function() { var newModel = new Barista.Model(); expect(newModel.isA('Barista.Collection')).toBe(false); }); }); describe('sync', function() { beforeEach(function() { model = new Barista.TaskModel(); spyOn(Backbone, 'sync'); }); it('does not call Backbone.sync', function() { model.sync(); expect(Backbone.sync).not.toHaveBeenCalled(); }); }); describe('get', function() { }); });
var Barista = require(process.cwd() + '/lib/barista.js'), Backbone = require('backbone'), ExampleApp = require(process.cwd() + '/spec/ex1/exampleApp1.js'), context = describe; describe('Barista.Model', function() { var model; beforeEach(function() { Barista.config(ExampleApp); }); describe('isA', function() { it('returns true with arg \'Backbone.Model\'', function() { var newModel = new Barista.Model(); expect(newModel.isA('Backbone.Model')).toBe(true); }); it('returns true with arg\'Barista.Model\'', function() { var newModel = new Barista.Model(); expect(newModel.isA('Barista.Model')).toBe(true); }); it('returns false with another argument', function() { var newModel = new Barista.Model(); expect(newModel.isA('Barista.Collection')).toBe(false); }); }); describe('sync', function() { beforeEach(function() { model = new Barista.TaskModel(); spyOn(Backbone, 'sync'); }); it('does not call Backbone.sync', function() { model.sync(); expect(Backbone.sync).not.toHaveBeenCalled(); }); }); describe('get', function() { beforeEach(function() { model = new Barista.TaskModel({title: 'Foobar'}); }); it('retrieves the object\'s attribute', function() { expect(model.get('title')).toBe('Foobar'); }); }); });
Add specs for the sync method of the model prototype
Add specs for the sync method of the model prototype
JavaScript
mit
danascheider/barista,danascheider/barista,danascheider/barista
--- +++ @@ -40,6 +40,12 @@ }); describe('get', function() { - + beforeEach(function() { + model = new Barista.TaskModel({title: 'Foobar'}); + }); + + it('retrieves the object\'s attribute', function() { + expect(model.get('title')).toBe('Foobar'); + }); }); });
567d28fcdaf9215a446ddea7346cd12352090ee0
config/test.js
config/test.js
module.exports = { database: 'factory-girl-sequelize', options: { dialect: 'sqlite', storage: 'test/tmp/test.db', logging: null } };
module.exports = { database: 'factory-girl-sequelize', options: { dialect: 'sqlite', storage: ':memory:', logging: null } };
Change to use in-memory SQLite
Change to use in-memory SQLite
JavaScript
mit
aexmachina/factory-girl-sequelize
--- +++ @@ -2,7 +2,7 @@ database: 'factory-girl-sequelize', options: { dialect: 'sqlite', - storage: 'test/tmp/test.db', + storage: ':memory:', logging: null } };
d81186e2455bcdb5dddf13953ed6a169ee951fde
tests/helpers/mock-bluetooth.js
tests/helpers/mock-bluetooth.js
/* global navigator, Promise*/ import Ember from 'ember'; const Mock = Ember.Object.extend({ available: true, name: null, value: null, isAvailable(value) { return this._setAndMock('available', value); }, deviceName(deviceName) { return this._setAndMock('name', deviceName); }, characteristicValue(value) { return this._setAndMock('value', value); }, _setAndMock(key, value) { this.set(key, value); this._mock(); return this; }, _mock() { let isAvailable = this.get('available'); let deviceName = this.get('name'); let characteristicValue = this.get('value'); let bluetooth; if (isAvailable) { bluetooth = { requestDevice: function() { return Promise.resolve({ name: deviceName, gatt: function() { return Promise.resolve({ getPrimaryService: function() { return Promise.resolve({ getCharacteristic: function() { return Promise.resolve({ readValue: function() { return Promise.resolve({ getUint8: function() { return characteristicValue; } }); } }); } }); } }); } }); } }; } this._createGetter(bluetooth); }, _createGetter(value) { navigator.__defineGetter__('bluetooth', function(){ return value; }); } }); export default function mockBluetooth() { let instance = Mock.create(); return instance; }
/* global navigator, Promise*/ import Ember from 'ember'; const Mock = Ember.Object.extend({ available: true, name: null, value: null, isAvailable(value) { return this._setAndMock('available', value); }, deviceName(deviceName) { return this._setAndMock('name', deviceName); }, characteristicValue(value) { return this._setAndMock('value', value); }, _setAndMock(key, value) { this.set(key, value); this._mock(); return this; }, _mock() { let isAvailable = this.get('available'); let deviceName = this.get('name'); let characteristicValue = this.get('value'); let bluetooth; if (isAvailable) { bluetooth = { requestDevice: function() { return Promise.resolve({ name: deviceName, gatt: { connect: function() { return Promise.resolve({ getPrimaryService: function() { return Promise.resolve({ getCharacteristic: function() { return Promise.resolve({ readValue: function() { return Promise.resolve({ getUint8: function() { return characteristicValue; } }); } }); } }); } }); } } }); } }; } this._createGetter(bluetooth); }, _createGetter(value) { navigator.__defineGetter__('bluetooth', function(){ return value; }); } }); export default function mockBluetooth() { let instance = Mock.create(); return instance; }
Add connect function to mockBluetooth
Add connect function to mockBluetooth
JavaScript
mit
wyeworks/ember-bluetooth,wyeworks/ember-bluetooth
--- +++ @@ -39,24 +39,26 @@ requestDevice: function() { return Promise.resolve({ name: deviceName, - gatt: function() { - return Promise.resolve({ - getPrimaryService: function() { - return Promise.resolve({ - getCharacteristic: function() { - return Promise.resolve({ - readValue: function() { - return Promise.resolve({ - getUint8: function() { - return characteristicValue; - } - }); - } - }); - } - }); - } - }); + gatt: { + connect: function() { + return Promise.resolve({ + getPrimaryService: function() { + return Promise.resolve({ + getCharacteristic: function() { + return Promise.resolve({ + readValue: function() { + return Promise.resolve({ + getUint8: function() { + return characteristicValue; + } + }); + } + }); + } + }); + } + }); + } } }); }
489ae0075ed61f524f6f716e08f7a9a25f5b5d4d
config/stage-disco.js
config/stage-disco.js
const amoCDN = 'https://addons-cdn.allizom.org'; const staticHost = 'https://addons-discovery-cdn.allizom.org'; module.exports = { staticHost, CSP: { directives: { scriptSrc: [staticHost], styleSrc: [staticHost], imgSrc: [ "'self'", 'data:', amoCDN, staticHost, ], mediaSrc: [staticHost], }, }, };
const amoCDN = 'https://addons-stage-cdn.allizom.org'; const staticHost = 'https://addons-discovery-cdn.allizom.org'; module.exports = { staticHost, CSP: { directives: { scriptSrc: [staticHost], styleSrc: [staticHost], imgSrc: [ "'self'", 'data:', amoCDN, staticHost, ], mediaSrc: [staticHost], }, }, };
Update amoCDN for disco stage config
Update amoCDN for disco stage config
JavaScript
mpl-2.0
squarewave/addons-frontend,tsl143/addons-frontend,jasonthomas/addons-frontend,aviarypl/mozilla-l10n-addons-frontend,mozilla/addons-frontend,aviarypl/mozilla-l10n-addons-frontend,squarewave/addons-frontend,tsl143/addons-frontend,tsl143/addons-frontend,muffinresearch/addons-frontend,kumar303/addons-frontend,kumar303/addons-frontend,mozilla/addons-frontend,kumar303/addons-frontend,aviarypl/mozilla-l10n-addons-frontend,mstriemer/addons-frontend,mozilla/addons-frontend,aviarypl/mozilla-l10n-addons-frontend,muffinresearch/addons-frontend,tsl143/addons-frontend,squarewave/addons-frontend,jasonthomas/addons-frontend,mstriemer/addons-frontend,jasonthomas/addons-frontend,mozilla/addons-frontend,muffinresearch/addons-frontend,kumar303/addons-frontend,mstriemer/addons-frontend
--- +++ @@ -1,4 +1,4 @@ -const amoCDN = 'https://addons-cdn.allizom.org'; +const amoCDN = 'https://addons-stage-cdn.allizom.org'; const staticHost = 'https://addons-discovery-cdn.allizom.org'; module.exports = {
8c7ee77516f4f07906be059edf20fc62d8716465
src/server/utils/areObjectValuesDefined.js
src/server/utils/areObjectValuesDefined.js
export default function areObjectValuesDefined(obj) { return Object.keys(obj) .map((key) => obj[key]) .reduce((prev, value) => { return prev && value !== undefined; }, true); }
/** * Checks if all values in a object are defined * @param {Object} obj The object * @return {boolean} */ export default function areObjectValuesDefined(obj) { return Object.keys(obj) .map((key) => obj[key]) .every(isDefined); } function isDefined(value) { return value !== undefined; }
Use every() instead of reduce()
Use every() instead of reduce()
JavaScript
mit
danistefanovic/hooka
--- +++ @@ -1,7 +1,14 @@ +/** + * Checks if all values in a object are defined + * @param {Object} obj The object + * @return {boolean} + */ export default function areObjectValuesDefined(obj) { return Object.keys(obj) .map((key) => obj[key]) - .reduce((prev, value) => { - return prev && value !== undefined; - }, true); + .every(isDefined); } + +function isDefined(value) { + return value !== undefined; +}
693eb566a96d9d634b31d78a50305ef2efcfc724
src/private/emscripten_api/emscripten_precache_api.js
src/private/emscripten_api/emscripten_precache_api.js
function EmscriptenPrecacheApi(apiPointer, cwrap, runtime) { var _apiPointer = apiPointer; var _beginPrecacheOperation = null; var _cancelPrecacheOperation = null; var _cancelCallback = null; var _completeCallback = null; this.registerCallbacks = function(completeCallback, cancelCallback) { if (_completeCallback !== null) { runtime.removeFunction(_completeCallback); } _completeCallback = runtime.addFunction(completeCallback); if (_cancelCallback !== null) { runtime.removeFunction(_cancelCallback); } _cancelCallback = runtime.addFunction(cancelCallback); }; this.beginPrecacheOperation = function(operationId, operation) { _beginPrecacheOperation = _beginPrecacheOperation || cwrap("beginPrecacheOperation", null, ["number", "number", "number", "number", "number", "number", "number"]); var latlong = operation.getCentre(); _beginPrecacheOperation(_apiPointer, operationId, latlong.lat, latlong.lng, operation.getRadius(), _completeCallback, _cancelCallback); }; this.cancelPrecacheOperation = function(operationId) { _cancelPrecacheOperation = _cancelPrecacheOperation || cwrap("cancelPrecacheOperation", null, ["number", "number"]); _cancelPrecacheOperation(_apiPointer, operationId); }; } module.exports = EmscriptenPrecacheApi;
function EmscriptenPrecacheApi(apiPointer, cwrap, runtime) { var _apiPointer = apiPointer; var _beginPrecacheOperation = null; var _cancelPrecacheOperation = null; var _cancelCallback = null; var _completeCallback = null; this.registerCallbacks = function(completeCallback, cancelCallback) { if (_completeCallback !== null) { runtime.removeFunction(_completeCallback); } _completeCallback = runtime.addFunction(completeCallback); if (_cancelCallback !== null) { runtime.removeFunction(_cancelCallback); } _cancelCallback = runtime.addFunction(cancelCallback); }; this.beginPrecacheOperation = function(operationId, operation) { _beginPrecacheOperation = _beginPrecacheOperation || cwrap("beginPrecacheOperation", null, ["number", "number", "number", "number", "number", "number", "number"]); var latlong = operation.getCentre(); _beginPrecacheOperation(_apiPointer, operationId, latlong.lat, latlong.lng, operation.getRadius(), _completeCallback, _cancelCallback); }; this.cancelPrecacheOperation = function(operationId) { _cancelPrecacheOperation = _cancelPrecacheOperation || cwrap("cancelPrecacheOperation___", null, ["number", "number"]); _cancelPrecacheOperation(_apiPointer, operationId); }; } module.exports = EmscriptenPrecacheApi;
Test that a broken function binding is detected when testing interop, and halts deployment.
Test that a broken function binding is detected when testing interop, and halts deployment.
JavaScript
bsd-2-clause
eegeo/eegeo.js,eegeo/eegeo.js
--- +++ @@ -26,7 +26,7 @@ }; this.cancelPrecacheOperation = function(operationId) { - _cancelPrecacheOperation = _cancelPrecacheOperation || cwrap("cancelPrecacheOperation", null, ["number", "number"]); + _cancelPrecacheOperation = _cancelPrecacheOperation || cwrap("cancelPrecacheOperation___", null, ["number", "number"]); _cancelPrecacheOperation(_apiPointer, operationId); }; }
440977ecd2079e617f79793d88929127b1d9b23b
src-js/alltests.js
src-js/alltests.js
/* * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var _allTests = [ "twig_test.html", "twig/environment_test.html", "twig/filter_test.html", "twig/markup_test.html", "templates/template_tests.html" ];
/* * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var _allTests = [ "twig_test.html", "twig/environment_test.html", "twig/markup_test.html", "templates/template_tests.html" ];
Remove references to filter tests
Remove references to filter tests
JavaScript
apache-2.0
br0wn/twig.js,basekit/twig.js,br0wn/twig.js,br0wn/twig.js,basekit/twig.js,schmittjoh/twig.js,basekit/twig.js,schmittjoh/twig.js,schmittjoh/twig.js
--- +++ @@ -17,7 +17,6 @@ var _allTests = [ "twig_test.html", "twig/environment_test.html", - "twig/filter_test.html", "twig/markup_test.html", "templates/template_tests.html" ];
dac5dc426d678cfe7be6b9ca1a2d6c118949f77d
lib/middleware/legacy-account-upgrade.js
lib/middleware/legacy-account-upgrade.js
"use strict"; var format = require('util').format; var config = require('config'); function upgradeLegacyAccount(req, res, next) { if (!req.session.legacyInstanceId) { return next(); } // User is trying to upgrade their account var instanceId = req.session.legacyInstanceId; delete req.session.legacyInstanceId; var Permission = req.popit.permissions(); Permission.create({ account: req.user.id, instance: instanceId, role: 'owner', }, function(err) { if (err) { return next(err); } req.flash('info', 'Account successfully upgraded'); var Instance = req.popit.master().model('Instance'); Instance.findById(instanceId, function(err, instance) { if (err) { return next(err); } // Redirect to the instance the user was trying to log into res.redirect(format(config.instance_server.base_url_format, instance.slug)); }); }); } module.exports = upgradeLegacyAccount;
"use strict"; var format = require('util').format; var config = require('config'); function upgradeLegacyAccount(req, res, next) { if (!req.session.legacyInstanceId) { return next(); } // User is trying to upgrade their account var instanceId = req.session.legacyInstanceId; delete req.session.legacyInstanceId; var Permission = req.popit.permissions(); Permission.create({ account: req.user.id, instance: instanceId, role: 'owner', }, function(err) { if (err) { return next(err); } req.flash('info', 'Account successfully upgraded'); var Instance = req.popit.master().model('Instance'); Instance.findById(instanceId, function(err, instance) { if (err) { return next(err); } if (!instance) { return res.redirect('/instances'); } // Redirect to the instance the user was trying to log into res.redirect(format(config.instance_server.base_url_format, instance.slug)); }); }); } module.exports = upgradeLegacyAccount;
Fix legacy upgrade with missing instance
Fix legacy upgrade with missing instance If the user is trying to upgrade their account and for some reason the instance has been deleted in the meantime then we simply redirect to the main listing of instances.
JavaScript
agpl-3.0
Sinar/popit,openstate/popit,Sinar/popit,Sinar/popit,mysociety/popit,mysociety/popit,Sinar/popit,openstate/popit,mysociety/popit,mysociety/popit,openstate/popit,mysociety/popit,openstate/popit
--- +++ @@ -25,6 +25,9 @@ if (err) { return next(err); } + if (!instance) { + return res.redirect('/instances'); + } // Redirect to the instance the user was trying to log into res.redirect(format(config.instance_server.base_url_format, instance.slug)); });
87e05a837d74c7a6c1cd566711d005b45089016b
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var jshint = require('gulp-jshint'); var jasmine = require('gulp-jasmine'); var uglify = require('gulp-uglify'); var rename = require('gulp-rename'); gulp.task('lint', function () { gulp.src('./*.js') .pipe(jshint('jshintrc.json')) .pipe(jshint.reporter('jshint-stylish')); }); gulp.task('test', function () { gulp.src('test.js') .pipe(jasmine()); }); gulp.task('uglify', function () { gulp.src('lambada.js') .pipe(uglify()) .pipe(rename('lambada.min.js')) .pipe(gulp.dest('.')); }); gulp.task('default', ['lint', 'test']);
var gulp = require('gulp'); var jshint = require('gulp-jshint'); var jasmine = require('gulp-jasmine'); var uglify = require('gulp-uglify'); var rename = require('gulp-rename'); gulp.task('lint', function () { return gulp.src('./*.js') .pipe(jshint('jshintrc.json')) .pipe(jshint.reporter('jshint-stylish')); }); gulp.task('test', function () { return gulp.src('test.js') .pipe(jasmine()); }); gulp.task('uglify', function () { return gulp.src('lambada.js') .pipe(uglify()) .pipe(rename('lambada.min.js')) .pipe(gulp.dest('.')); }); gulp.task('default', ['lint', 'test']);
Return the stream for each task
Return the stream for each task
JavaScript
mit
rbonvall/lambada
--- +++ @@ -5,18 +5,18 @@ var rename = require('gulp-rename'); gulp.task('lint', function () { - gulp.src('./*.js') + return gulp.src('./*.js') .pipe(jshint('jshintrc.json')) .pipe(jshint.reporter('jshint-stylish')); }); gulp.task('test', function () { - gulp.src('test.js') + return gulp.src('test.js') .pipe(jasmine()); }); gulp.task('uglify', function () { - gulp.src('lambada.js') + return gulp.src('lambada.js') .pipe(uglify()) .pipe(rename('lambada.min.js')) .pipe(gulp.dest('.'));
e59cd3ab355207093b86084c32fdcf29e7054cbc
gulpfile.js
gulpfile.js
var gulp = require('gulp'), eslint = require('gulp-eslint'), mocha = require('gulp-mocha'), flow = require('gulp-flowtype'), babel = require('babel/register'); gulp.task('lint', function() { return gulp.src(['src/*.js', 'src/__tests__/*.js']) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failOnError()); }); gulp.task('typecheck', function() { return gulp.src(['src/*.js', 'src/__tests__/*.js']) .pipe(flow({ all: false, weak: false, declarations: './build/flow', killFlow: false, beep: true, abort: false })); }); gulp.task('test', ['lint'], function() { global.expect = require('chai').expect; global.sinon = require('sinon'); return gulp.src(['src/__tests__/{,*/}*-test.js']) .pipe(mocha({ compilers: { js: babel }, reporter: 'spec', ui: 'bdd' })); }); gulp.task('default', ['lint', 'test']);
var gulp = require('gulp'), eslint = require('gulp-eslint'), mocha = require('gulp-mocha'), flow = require('gulp-flowtype'), babel = require('babel/register'); gulp.task('lint', function() { return gulp.src(['src/*.js', 'src/__tests__/*.js']) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failOnError()); }); gulp.task('typecheck', function() { return gulp.src(['src/*.js', 'src/__tests__/*.js']) .pipe(flow({ all: false, weak: false, declarations: './build/flow', killFlow: false, beep: true, abort: false })); }); gulp.task('test', ['lint'], function() { global.expect = require('chai').expect; global.sinon = require('sinon'); global.document = { location: { pathname: '' } }; global.window = { addEventListener() {} }; return gulp.src(['src/__tests__/{,*/}*-test.js']) .pipe(mocha({ compilers: { js: babel }, reporter: 'spec', ui: 'bdd' })); }); gulp.task('default', ['lint', 'test']);
Add window and document to globals for tests
Add window and document to globals for tests
JavaScript
mit
ameyms/switchboard
--- +++ @@ -27,6 +27,15 @@ global.expect = require('chai').expect; global.sinon = require('sinon'); + global.document = { + location: { + pathname: '' + } + }; + + global.window = { + addEventListener() {} + }; return gulp.src(['src/__tests__/{,*/}*-test.js']) .pipe(mocha({
d41a53734f7577d1f64af7eceae523599a662669
gulpfile.js
gulpfile.js
var gulp = require('gulp'), jsdoc = require('gulp-jsdoc'), ghPages = require('gulp-gh-pages'), docsSrcDir = './assets/js/**/*.js', docsDestDir = './docs/js', jsDocTask; jsDocTask = function() { return gulp.src(docsSrcDir) .pipe( jsdoc(docsDestDir, { path: './node_modules/jaguarjs-jsdoc', applicationName: 'Dough JavaScript', cleverLinks: true, copyright: 'Copyright Money Advice Service &copy;', linenums: true, collapseSymbols: false }, { plugins: ['plugins/markdown'], } ) ); }; gulp.task('deploy', function() { return gulp.src(docsDestDir + '/**/*') .pipe(ghPages()); }); gulp.task('default', ['jsdoc']); gulp.task('build', ['jsdoc', 'deploy']); gulp.task('jsdoc', jsDocTask); gulp.task('watch', function() { jsDocTask(); gulp.watch(docsSrcDir, ['jsdoc']); });
var gulp = require('gulp'), jsdoc = require('gulp-jsdoc'), ghPages = require('gulp-gh-pages'), docsSrcDir = './assets/js/**/*.js', docsDestDir = './docs/js', jsDocTask; jsDocTask = function() { return gulp.src([docsSrcDir, './README.md']) .pipe( jsdoc(docsDestDir, { path: './node_modules/jaguarjs-jsdoc', applicationName: 'Dough JavaScript', cleverLinks: true, copyright: 'Copyright Money Advice Service &copy;', linenums: true, collapseSymbols: false }, { plugins: ['plugins/markdown'], } ) ); }; gulp.task('deploy', function() { return gulp.src(docsDestDir + '/**/*') .pipe(ghPages()); }); gulp.task('default', ['jsdoc']); gulp.task('build', ['jsdoc', 'deploy']); gulp.task('jsdoc', jsDocTask); gulp.task('watch', function() { jsDocTask(); gulp.watch(docsSrcDir, ['jsdoc']); });
Use the Dough README on docs landing page
Use the Dough README on docs landing page
JavaScript
mit
moneyadviceservice/dough,moneyadviceservice/dough,moneyadviceservice/dough,moneyadviceservice/dough
--- +++ @@ -6,7 +6,7 @@ jsDocTask; jsDocTask = function() { - return gulp.src(docsSrcDir) + return gulp.src([docsSrcDir, './README.md']) .pipe( jsdoc(docsDestDir, {
af6d16e6b6732b17365bae023b6990a15b4ec049
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var files = ['index.js', 'test/*.js', 'gulpfile.js']; gulp.task('lint', function (done) { var eslint = require('gulp-eslint'); return gulp.src(files) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()).on('error', done); }); gulp.task('test', function (done) { var mocha = require('gulp-mocha'); return gulp.src('test/*.js', { read: false }) .pipe(mocha()).on('error', done); }); gulp.task('default', ['lint', 'test']); gulp.task('watch', function() { gulp.watch(files, ['lint', 'test']); });
var gulp = require('gulp'); var files = ['index.js', 'lib/*.js', 'test/*.js', 'gulpfile.js']; gulp.task('lint', function (done) { var eslint = require('gulp-eslint'); return gulp.src(files) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()).on('error', done); }); gulp.task('test', function (done) { var mocha = require('gulp-mocha'); return gulp.src('test/*.js', { read: false }) .pipe(mocha()).on('error', done); }); gulp.task('default', ['lint', 'test']); gulp.task('watch', function() { gulp.watch(files, ['lint', 'test']); });
Split code into lib subfolder
Split code into lib subfolder
JavaScript
mit
cbas/postcss-imperial
--- +++ @@ -1,6 +1,6 @@ var gulp = require('gulp'); -var files = ['index.js', 'test/*.js', 'gulpfile.js']; +var files = ['index.js', 'lib/*.js', 'test/*.js', 'gulpfile.js']; gulp.task('lint', function (done) { var eslint = require('gulp-eslint');
de0a700dabe20f24a9939c642977fda8a43353cc
gulpfile.js
gulpfile.js
var gulp= require('gulp') var dts = require('dts-generator'); gulp.task('default', function(){ dts .generate({ name: 'uservice', baseDir: './module', excludes: ['./typings/node/node.d.ts', './typings/typescript/lib.es6.d.ts'], files: [ './index.ts' ], out: './uservice.d.ts' }); })
var gulp= require('gulp') var dts = require('dts-generator'); gulp.task('default', function(){ dts .generate({ name: 'uservices', baseDir: './module', excludes: ['./typings/node/node.d.ts', './typings/typescript/lib.es6.d.ts'], files: [ './index.ts' ], out: './uservices.d.ts' }); })
Fix name to consistent uservices
Fix name to consistent uservices
JavaScript
mit
christyharagan/uservices,christyharagan/uservices
--- +++ @@ -3,10 +3,10 @@ gulp.task('default', function(){ dts .generate({ - name: 'uservice', + name: 'uservices', baseDir: './module', excludes: ['./typings/node/node.d.ts', './typings/typescript/lib.es6.d.ts'], files: [ './index.ts' ], - out: './uservice.d.ts' + out: './uservices.d.ts' }); })
2440066e35307d9f4b7d25b715150638c703166a
lib/validate/validate_layout_property.js
lib/validate/validate_layout_property.js
'use strict'; var validate = require('./validate'); var ValidationError = require('../error/validation_error'); module.exports = function validateLayoutProperty(options) { var key = options.key; var style = options.style; var styleSpec = options.styleSpec; var value = options.value; var propertyKey = options.objectKey; var layerSpec = styleSpec['layout_' + options.layerType]; if (options.valueSpec || layerSpec[propertyKey]) { var errors = []; if (options.layerType === 'symbol') { if (propertyKey === 'icon-image' && !style.sprite) { errors.push(new ValidationError(key, value, 'use of "icon-image" requires a style "sprite" property')); } else if (propertyKey === 'text-field' && !style.glyphs) { errors.push(new ValidationError(key, value, 'use of "text-field" requires a style "glyphs" property')); } } return errors.concat(validate({ key: options.key, value: value, valueSpec: options.valueSpec || layerSpec[propertyKey], style: style, styleSpec: styleSpec })); } else { return [new ValidationError(key, value, 'unknown property "%s"', propertyKey)]; } };
'use strict'; var validate = require('./validate'); var ValidationError = require('../error/validation_error'); module.exports = function validateLayoutProperty(options) { var key = options.key; var style = options.style; var styleSpec = options.styleSpec; var value = options.value; var propertyKey = options.objectKey; var layerSpec = styleSpec['layout_' + options.layerType]; if (options.valueSpec || layerSpec[propertyKey]) { var errors = []; if (options.layerType === 'symbol') { if (propertyKey === 'icon-image' && style && !style.sprite) { errors.push(new ValidationError(key, value, 'use of "icon-image" requires a style "sprite" property')); } else if (propertyKey === 'text-field' && style && !style.glyphs) { errors.push(new ValidationError(key, value, 'use of "text-field" requires a style "glyphs" property')); } } return errors.concat(validate({ key: options.key, value: value, valueSpec: options.valueSpec || layerSpec[propertyKey], style: style, styleSpec: styleSpec })); } else { return [new ValidationError(key, value, 'unknown property "%s"', propertyKey)]; } };
Fix exception caused by calling validateLayoutProperty without passing a style
Fix exception caused by calling validateLayoutProperty without passing a style
JavaScript
isc
pka/mapbox-gl-style-spec,pka/mapbox-gl-style-spec
--- +++ @@ -15,9 +15,9 @@ var errors = []; if (options.layerType === 'symbol') { - if (propertyKey === 'icon-image' && !style.sprite) { + if (propertyKey === 'icon-image' && style && !style.sprite) { errors.push(new ValidationError(key, value, 'use of "icon-image" requires a style "sprite" property')); - } else if (propertyKey === 'text-field' && !style.glyphs) { + } else if (propertyKey === 'text-field' && style && !style.glyphs) { errors.push(new ValidationError(key, value, 'use of "text-field" requires a style "glyphs" property')); } }
26b699534b64370c22cb6fbb99b0a9146111854d
ember-cli-build.js
ember-cli-build.js
/* eslint-env node */ 'use strict' const EmberApp = require('ember-cli/lib/broccoli/ember-app') const cssnext = require('postcss-cssnext') module.exports = function(defaults) { let app = new EmberApp(defaults, { postcssOptions: { compile: { enabled: false }, filter: { enabled: true, plugins: [ { module: cssnext, options: { browsers: [ '> 1%', 'last 3 versions', 'Firefox ESR' ] } } ] } } }) app.import('bower_components/xss/dist/xss.js') return app.toTree() }
/* eslint-env node */ 'use strict' const EmberApp = require('ember-cli/lib/broccoli/ember-app') const cssnext = require('postcss-cssnext') module.exports = function(defaults) { let app = new EmberApp(defaults, { postcssOptions: { compile: { enabled: false }, filter: { enabled: true, map: { inline: false }, plugins: [ { module: cssnext, options: { browsers: [ '> 1%', 'last 3 versions', 'Firefox ESR' ] } } ] } } }) app.import('bower_components/xss/dist/xss.js') return app.toTree() }
Disable inline sourcemaps in postcss
Disable inline sourcemaps in postcss
JavaScript
mit
opensource-challenge/opensource-challenge-client,opensource-challenge/opensource-challenge-client
--- +++ @@ -12,6 +12,7 @@ }, filter: { enabled: true, + map: { inline: false }, plugins: [ { module: cssnext,
819a6bf697b4c7c7c7b523be58be832a697a9b45
lib/tasks/nodejs/NodeWatchBuildTask.js
lib/tasks/nodejs/NodeWatchBuildTask.js
"use strict"; const Task = require('../Task'), gulp = require('gulp'), path = require('path'), nodemon = require('gulp-nodemon'), ProjectType = require('../../ProjectType'), _ = require('lodash'); class NodeWatchBuildTask extends Task { constructor(buildManager, taskRunner) { super(buildManager, taskRunner); this.command = "watch-build"; this.availableTo = [ProjectType.NODEJS]; } action() { return nodemon(_.merge({ script: 'bootstrapper.' + (this._buildManager.options.typescript ? "ts" : "js"), ext: 'js json ts', execMap: { "ts": path.resolve(__dirname, "../../../node_modules/ts-node/dist/bin/ts-node.js") } }, this._buildManager.options.nodemon)); } } module.exports = NodeWatchBuildTask;
"use strict"; const Task = require('../Task'), gulp = require('gulp'), path = require('path'), ProjectType = require('../../ProjectType'), _ = require('lodash'); class NodeWatchBuildTask extends Task { constructor(buildManager, taskRunner) { super(buildManager, taskRunner); this.command = "watch-build"; this.availableTo = [ProjectType.NODEJS]; } action() { return require('gulp-nodemon')(_.merge({ script: 'bootstrapper.' + (this._buildManager.options.typescript ? "ts" : "js"), ext: 'js json ts', execMap: { "ts": path.resolve(__dirname, "../../../node_modules/ts-node/dist/bin/ts-node.js") } }, this._buildManager.options.nodemon)); } } module.exports = NodeWatchBuildTask;
Fix double ctr+c when exiting watch-build
Fix double ctr+c when exiting watch-build
JavaScript
mit
mtfranchetto/smild,mtfranchetto/smild,mtfranchetto/smild
--- +++ @@ -3,7 +3,6 @@ const Task = require('../Task'), gulp = require('gulp'), path = require('path'), - nodemon = require('gulp-nodemon'), ProjectType = require('../../ProjectType'), _ = require('lodash'); @@ -16,7 +15,7 @@ } action() { - return nodemon(_.merge({ + return require('gulp-nodemon')(_.merge({ script: 'bootstrapper.' + (this._buildManager.options.typescript ? "ts" : "js"), ext: 'js json ts', execMap: {
0e8a21eea09024ba9fbfca0ac2efebc87253d46f
demo/assets/js/script.js
demo/assets/js/script.js
/*jslint devel: true, browser: true, indent: 2, nomen: true */ /*global define */ define([], function () { 'use strict'; console.log('it works'); });
/*jslint devel: true, browser: true, indent: 2, nomen: true */ /*global define */ define([], function () { 'use strict'; // console.log('it works'); });
Comment out annoying debug code.
Comment out annoying debug code.
JavaScript
mit
brianmcallister/m
--- +++ @@ -4,5 +4,5 @@ define([], function () { 'use strict'; - console.log('it works'); + // console.log('it works'); });
ddaed5d7e81798b4ed4e5db2872469e4468db1b8
server/common/set_language.js
server/common/set_language.js
// Store the preference locale in cookies and (if available) session to use // on next requests. 'use strict'; var _ = require('lodash'); var LOCALE_COOKIE_MAX_AGE = 0xFFFFFFFF; // Maximum 32-bit unsigned integer. module.exports = function (N, apiPath) { N.validate(apiPath, { locale: { type: 'string' } }); N.wire.on(apiPath, function set_language(env, callback) { var locale = env.params.locale; if (!_.contains(N.config.locales.enabled, env.params.locale)) { // User sent a non-existent or disabled locale - reply with the default. locale = N.config.locales['default']; } env.extras.setCookie('locale', locale, { path: '/' , maxAge: LOCALE_COOKIE_MAX_AGE }); if (env.session) { env.session.locale = locale; } if (env.session && env.session.user_id) { N.models.users.User.findByIdAndUpdate(env.session.user_id, { locale: locale }, callback); } else { callback(); } }); };
// Store the preference locale in cookies and (if available) session to use // on next requests. 'use strict'; var _ = require('lodash'); var LOCALE_COOKIE_MAX_AGE = 0xFFFFFFFF; // Maximum 32-bit unsigned integer. module.exports = function (N, apiPath) { N.validate(apiPath, { locale: { type: 'string' } }); N.wire.on(apiPath, function set_language(env, callback) { var locale = env.params.locale; if (!_.contains(N.config.locales.enabled, env.params.locale)) { // User sent a non-existent or disabled locale - reply with the default. locale = N.config.locales['default']; } env.extras.setCookie('locale', locale, { path: '/' , maxAge: LOCALE_COOKIE_MAX_AGE }); if (env.session) { env.session.locale = locale; } if (env.session && env.session.user_id) { N.models.users.User.update({ _id: env.session.user_id }, { locale: locale }, callback); } else { callback(); } }); };
Update user locale without fetching user's account.
Update user locale without fetching user's account.
JavaScript
mit
nodeca/nodeca.users
--- +++ @@ -34,7 +34,7 @@ } if (env.session && env.session.user_id) { - N.models.users.User.findByIdAndUpdate(env.session.user_id, { locale: locale }, callback); + N.models.users.User.update({ _id: env.session.user_id }, { locale: locale }, callback); } else { callback(); }
d2d6fbddfbdfe74671f4813d7f3b80582ee11928
gulpfile.js
gulpfile.js
var name = require('./package.json').moduleName, fs = require('fs'), gulp = require('gulp'), plugins = require('gulp-load-plugins')() var head = fs.readFileSync('./node_modules/@electerious/modulizer/head.js', { encoding: 'utf8' }), foot = fs.readFileSync('./node_modules/@electerious/modulizer/foot.js', { encoding: 'utf8' }) var catchError = function(err) { console.log(err.toString()) this.emit('end') } gulp.task('scripts', function() { gulp.src('./src/scripts/*.js') .pipe(plugins.header(head, { name: name })) .pipe(plugins.footer(foot)) .pipe(plugins.babel()) .pipe(plugins.concat(name + '.min.js', { newLine: "\n" })) .pipe(plugins.uglify()) .on('error', catchError) .pipe(gulp.dest('./dist')) }) gulp.task('default', ['scripts']) gulp.task('watch', ['scripts'], function() { gulp.watch('./src/scripts/*.js', ['scripts']) })
var name = require('./package.json').moduleName, fs = require('fs'), gulp = require('gulp'), plugins = require('gulp-load-plugins')() var head = fs.readFileSync('./node_modules/@electerious/modulizer/head.js', { encoding: 'utf8' }), foot = fs.readFileSync('./node_modules/@electerious/modulizer/foot.js', { encoding: 'utf8' }) var catchError = function(err) { console.log(err.toString()) this.emit('end') } gulp.task('scripts', function() { gulp.src('./src/scripts/*.js') .pipe(plugins.header(head, { name: name })) .pipe(plugins.footer(foot)) .pipe(plugins.babel()) .pipe(plugins.concat(name + '.min.js', { newLine: "\n" })) .pipe(plugins.uglify()) .on('error', catchError) .pipe(gulp.dest('./dist')) }) gulp.task('default', ['scripts']) gulp.task('watch', ['scripts'], function() { gulp.watch('./src/scripts/**/*.js', ['scripts']) })
Include sub-folders when watching for changes
Include sub-folders when watching for changes
JavaScript
mit
electerious/scrollSnap,electerious/scrollSnap
--- +++ @@ -30,6 +30,6 @@ gulp.task('watch', ['scripts'], function() { - gulp.watch('./src/scripts/*.js', ['scripts']) + gulp.watch('./src/scripts/**/*.js', ['scripts']) })
2c6bfb27c4b7122ac76db7bd5a1edc1939567fb7
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var mocha = require('gulp-mocha'); var coffee = require('gulp-coffee'); var concat = require('gulp-concat'); require('coffee-script/register'); gulp.task('test', function(){ return gulp.src('./test/**/*.coffee') .pipe(mocha()); }); gulp.task('bundle', function(done) { gulp.src('./src/**/*.coffee') .pipe(coffee({bare: true})) .pipe(gulp.dest('lib')); done(); }); gulp.task('watch', function() { gulp.watch([ '**/*.coffee' ], [ 'bundle', 'test' ]); }); gulp.task('default', ['watch']);
var gulp = require('gulp'); var mocha = require('gulp-mocha'); var coffee = require('gulp-coffee'); var concat = require('gulp-concat'); require('coffee-script/register'); gulp.task('test', ['bundle'], function(){ return gulp.src('./test/**/*.coffee') .pipe(mocha()); }); gulp.task('bundle', function() { return gulp.src('./src/**/*.coffee') .pipe(coffee({bare: true})) .pipe(gulp.dest('lib')); }); gulp.task('watch', function() { gulp.watch([ '**/*.coffee' ], [ 'bundle', 'test' ]); }); gulp.task('default', ['watch']);
Set 'bundle' as a dependency to 'test'
Set 'bundle' as a dependency to 'test' Set 'bundle' as a dependency to 'test'
JavaScript
mit
casesandberg/react-map-styles
--- +++ @@ -6,16 +6,15 @@ -gulp.task('test', function(){ +gulp.task('test', ['bundle'], function(){ return gulp.src('./test/**/*.coffee') .pipe(mocha()); }); -gulp.task('bundle', function(done) { - gulp.src('./src/**/*.coffee') +gulp.task('bundle', function() { + return gulp.src('./src/**/*.coffee') .pipe(coffee({bare: true})) .pipe(gulp.dest('lib')); - done(); }); gulp.task('watch', function() {
1ff930c6b1662558ad6f9ec5a400327f552e42b1
lib/main.js
lib/main.js
const async = require('./async') module.exports = function(providers, cb) { function setup(values) { const currentValues = results.reduce(( pre, cur ) => Object.assign(pre, cur), {}) cb(null, { get: key => currentValues[key], getDynamic: key => () => currentValues[key], all: currentValues } ) } async.merge(providers.map(provider => (cb) => provider.read(cb)), results => { const errors = result.filter(r => r.err !== undefined) if(errors.length > 0) { cb(errors[0]) } else { setup(results.map(r => r.res)) } }) }
const async = require('./async') module.exports = function(providers, cb) { function setup(values) { const currentValues = results.reduce(( pre, cur ) => Object.assign(pre, cur), {}) cb(null, { get: key => currentValues[key], getDynamic: key => () => currentValues[key], all: currentValues } ) } async.merge(providers.map(provider => provider.read), results => { const errors = result.filter(r => r.err !== undefined) if(errors.length > 0) { cb(errors[0]) } else { setup(results.map(r => r.res)) } }) }
Simplify passing read to merge call
Simplify passing read to merge call
JavaScript
apache-2.0
reneweb/dvar,reneweb/dvar
--- +++ @@ -14,7 +14,7 @@ ) } - async.merge(providers.map(provider => (cb) => provider.read(cb)), results => { + async.merge(providers.map(provider => provider.read), results => { const errors = result.filter(r => r.err !== undefined) if(errors.length > 0) {
ddb525f99c03dd70c41325eca6e00ddfd454fcdd
middleware/get_macaroon_user_secret.js
middleware/get_macaroon_user_secret.js
var MacaroonAuthUtils = require("../utils/macaroon_auth.js"); module.exports = function(options) { return function getMacaroonUserSecret(req, res, next) { if(typeof options.collection !== "undefined" && options.collection !== ""){ var userId = ""; if(req.method == "GET" || req.method == "DELETE"){ userId = req.query.userId; } else{ userId = req.body.userId; } if(typeof userId !== "undefined" && userId !== ""){ var collection = req.db.collection(options.collection); collection.findOne({userId: userId}) .then(function(user){ if(user !== null){ console.log("Setting macaroonUserSecret for user: " + user.userId); var macaroonSecret = MacaroonAuthUtils.calculateMacaroonSecret(user.macaroonSecret); req.macaroonSecret = macaroonSecret; } else{ console.log("Setting macaroonUserSecret to null for user"); req.macaroonUserSecret = null; } next(); }).catch(function (error) { console.log("Promise rejected:"); console.log(error); res.sendStatus("401"); }); } else{ console.log("userId not found. Setting macaroonUserSecret to null: " + userId); req.macaroonUserSecret = null; next(); } } else{ var error = new Error("Error configuring getMacaroonUserSecret") console.log(error); res.sendStatus("401"); } }; };
var mAuthMint = require("mauth").mAuthMint; module.exports = function(options) { return function getMacaroonUserSecret(req, res, next) { if(typeof options.collection !== "undefined" && options.collection !== ""){ var userId = ""; if(req.method == "GET" || req.method == "DELETE"){ userId = req.query.userId; } else{ userId = req.body.userId; } if(typeof userId !== "undefined" && userId !== ""){ var collection = req.db.collection(options.collection); collection.findOne({userId: userId}) .then(function(user){ if(user !== null){ console.log("Setting macaroonUserSecret for user: " + user.userId); var macaroonSecret = mAuthMint.calculateMacaroonSecret(user.macaroonSecret); req.macaroonSecret = macaroonSecret; } else{ console.log("Setting macaroonUserSecret to null for user"); req.macaroonUserSecret = null; } next(); }).catch(function (error) { console.log("Promise rejected:"); console.log(error); res.sendStatus("401"); }); } else{ console.log("userId not found. Setting macaroonUserSecret to null: " + userId); req.macaroonUserSecret = null; next(); } } else{ var error = new Error("Error configuring getMacaroonUserSecret") console.log(error); res.sendStatus("401"); } }; };
Fix require to use new mauth package
Fix require to use new mauth package
JavaScript
bsd-3-clause
Saganus/macaroons-express-demo,Saganus/macaroons-express-demo
--- +++ @@ -1,4 +1,4 @@ -var MacaroonAuthUtils = require("../utils/macaroon_auth.js"); +var mAuthMint = require("mauth").mAuthMint; module.exports = function(options) { return function getMacaroonUserSecret(req, res, next) { @@ -17,7 +17,7 @@ .then(function(user){ if(user !== null){ console.log("Setting macaroonUserSecret for user: " + user.userId); - var macaroonSecret = MacaroonAuthUtils.calculateMacaroonSecret(user.macaroonSecret); + var macaroonSecret = mAuthMint.calculateMacaroonSecret(user.macaroonSecret); req.macaroonSecret = macaroonSecret; } else{
fc9513427abdd10d65fc2381c4a4945bbc32c9af
webpack/shared.config.js
webpack/shared.config.js
const CleanWebpackPlugin = require("clean-webpack-plugin") const path = require("path") const webpack = require("webpack") const dist = path.join(process.cwd(), "public") const src = path.join(process.cwd(), "src") //module.exports = { dist, src } module.exports = { entry: [path.join(src, "index.js")], module: { rules: [ { test: /\.(graphql|gql)?$/, use: "raw-loader" }, { exclude: /node_modules/, test: /\.js?$/, use: [ { loader: "babel-loader" } ] }, { test: /\.y(a?)ml$/, use: ["json-loader", "yaml-loader"] } ] }, node: { __filename: true, __dirname: true }, output: { path: dist, filename: "server.js" }, plugins: [ new CleanWebpackPlugin(dist), new webpack.IgnorePlugin(/vertx/), new webpack.NamedModulesPlugin(), new webpack.NoEmitOnErrorsPlugin() ], target: "node" }
const CleanWebpackPlugin = require("clean-webpack-plugin") const path = require("path") const webpack = require("webpack") const dist = path.join(process.cwd(), "public") const src = path.join(process.cwd(), "src") //module.exports = { dist, src } module.exports = { entry: [path.join(src, "index.js")], module: { rules: [ { test: /\.(graphql|gql)?$/, use: "raw-loader" }, { exclude: /node_modules/, test: /\.js?$/, use: [ { loader: "babel-loader" } ] }, { test: /\.y(a?)ml$/, use: ["json-loader", "yaml-loader"] } ] }, node: { __filename: true, __dirname: true }, output: { path: dist, filename: "server.js" }, plugins: [ new CleanWebpackPlugin(dist, { root: process.cwd() }), new webpack.IgnorePlugin(/vertx/), new webpack.NamedModulesPlugin(), new webpack.NoEmitOnErrorsPlugin() ], target: "node" }
Change project root variable in clean plugin
Change project root variable in clean plugin
JavaScript
mit
DevNebulae/ads-pt-api
--- +++ @@ -35,8 +35,10 @@ }, output: { path: dist, filename: "server.js" }, plugins: [ - new CleanWebpackPlugin(dist), - new webpack.IgnorePlugin(/vertx/), + new CleanWebpackPlugin(dist, { + root: process.cwd() + }), + new webpack.IgnorePlugin(/vertx/), new webpack.NamedModulesPlugin(), new webpack.NoEmitOnErrorsPlugin() ],
fefcc30a9cf75496f118c5cfaf09760297f319c7
lib/pint.js
lib/pint.js
"use strict" var _ = require('underscore'), fs = require('fs'), sys = require('sys'), exec = require('child_process').exec, program = require('commander'); var path = require('path'), fs = require('fs'), lib = path.join(path.dirname(fs.realpathSync(__filename)), '../lib'); // CLI program.version('0.0.1') .parse(process.argv); // Exec new Gruntfile var execGrunt = function () { var pintConfig = require(path.join(process.cwd(), 'Pint.js')); var gruntfileTemplate = fs.readFileSync(path.join(lib, 'templates/Gruntfile.tmpl'), 'utf8'); // Stringify config but remove open and closing braces var config=JSON.stringify(pintConfig.build.config); config = config.substring(1, config.length - 1) fs.writeFileSync("./Gruntfile.js", _.template(gruntfileTemplate)({ gruntTasks : config })) exec("grunt", function(err, stdout) { sys.puts(stdout.trim()); exec("rm -rf Gruntfile.js", function(err, stdout) { sys.puts(stdout.trim()); }); }); }; exports.drink = execGrunt;
"use strict" var _ = require('underscore'), fs = require('fs'), sys = require('sys'), exec = require('child_process').exec, program = require('commander'), path = require('path'); var pintPath = path.join(__dirname, '..'), targetPath = process.cwd() // CLI program.version('0.0.1') .parse(process.argv); // Exec new Gruntfile var execGrunt = function () { var pintConfig = require(path.join(process.cwd(), 'Pint.js')); var gruntfileTemplate = fs.readFileSync(path.join(pintPath, 'lib/templates/Gruntfile.tmpl'), 'utf8'); // Stringify config but remove open and closing braces var config=JSON.stringify(pintConfig.build.config); config = config.substring(1, config.length - 1) fs.writeFileSync(path.join(targetPath, "Pintfile.js"), _.template(gruntfileTemplate)({ gruntTasks : config })) exec("grunt --gruntfile Pintfile.js", function(err, stdout) { sys.puts(stdout.trim()); exec("rm -rf Pintfile.js", function(err, stdout) { sys.puts(stdout.trim()); }); }); }; exports.drink = execGrunt;
Change files to be Pintfiles so as not to conflict with Grunt
Change files to be Pintfiles so as not to conflict with Grunt
JavaScript
mit
baer/pint
--- +++ @@ -4,11 +4,11 @@ fs = require('fs'), sys = require('sys'), exec = require('child_process').exec, - program = require('commander'); + program = require('commander'), + path = require('path'); -var path = require('path'), - fs = require('fs'), - lib = path.join(path.dirname(fs.realpathSync(__filename)), '../lib'); +var pintPath = path.join(__dirname, '..'), + targetPath = process.cwd() // CLI program.version('0.0.1') @@ -17,20 +17,20 @@ // Exec new Gruntfile var execGrunt = function () { var pintConfig = require(path.join(process.cwd(), 'Pint.js')); - var gruntfileTemplate = fs.readFileSync(path.join(lib, 'templates/Gruntfile.tmpl'), 'utf8'); + var gruntfileTemplate = fs.readFileSync(path.join(pintPath, 'lib/templates/Gruntfile.tmpl'), 'utf8'); // Stringify config but remove open and closing braces var config=JSON.stringify(pintConfig.build.config); config = config.substring(1, config.length - 1) - fs.writeFileSync("./Gruntfile.js", _.template(gruntfileTemplate)({ + fs.writeFileSync(path.join(targetPath, "Pintfile.js"), _.template(gruntfileTemplate)({ gruntTasks : config })) - exec("grunt", function(err, stdout) { + exec("grunt --gruntfile Pintfile.js", function(err, stdout) { sys.puts(stdout.trim()); - exec("rm -rf Gruntfile.js", function(err, stdout) { + exec("rm -rf Pintfile.js", function(err, stdout) { sys.puts(stdout.trim()); }); });
c4c331cbce72af7d298b8f221648bc2bd8a5c6e8
wave/war/swellrt-beta.js
wave/war/swellrt-beta.js
// SwellRT bootstrap script // A fake SwellRT object to register on ready handlers // before the GWT module is loaded window.swellrt = { onReady: function(handler) { if (!handler || typeof handler !== "function") return; if (!window._lh) window._lh = []; window._lh.push(handler); } } var scripts = document.getElementsByTagName('script'); var thisScript = scripts[scripts.length -1]; if (thisScript) { var p = document.createElement('a'); p.href = thisScript.src; // Polyfill for ES6 proxy/reflect if (!window.Proxy || !window.Reflect) { var reflectSrc = p.protocol + "//" +p.host + "/reflect.js"; document.write("<script src='"+reflectSrc+"'></script>"); } var scriptSrc = p.protocol + "//" +p.host + "/swellrt_beta/swellrt_beta.nocache.js"; document.write("<script src='"+scriptSrc+"'></script>"); }
// SwellRT bootstrap script // A fake SwellRT object to register on ready handlers // before the GWT module is loaded window.swellrt = { onReady: function(handler) { if (!handler || typeof handler !== "function") return; if (window.swellrt.runtime) { handler.apply(window, window.swellrt.runtime.get()); } else { if (!window._lh) window._lh = []; window._lh.push(handler); } } } var scripts = document.getElementsByTagName('script'); var thisScript = scripts[scripts.length -1]; if (thisScript) { var p = document.createElement('a'); p.href = thisScript.src; // Polyfill for ES6 proxy/reflect if (!window.Proxy || !window.Reflect) { try { var reflectSrc = p.protocol + "//" +p.host + "/reflect.js"; document.write("<script src='"+reflectSrc+"'></script>"); } catch (e) { console.log("No proxies supported: "+e); } } var scriptSrc = p.protocol + "//" +p.host + "/swellrt_beta/swellrt_beta.nocache.js"; document.write("<script src='"+scriptSrc+"'></script>"); } else { console.log("Unable to inject swellrt script!"); }
Fix code launching onReady() handlers
Fix code launching onReady() handlers
JavaScript
apache-2.0
P2Pvalue/swellrt,P2Pvalue/swellrt,P2Pvalue/swellrt,Grasia/swellrt,P2Pvalue/swellrt,Grasia/swellrt,Grasia/swellrt,Grasia/swellrt
--- +++ @@ -3,18 +3,20 @@ // A fake SwellRT object to register on ready handlers // before the GWT module is loaded - window.swellrt = { onReady: function(handler) { if (!handler || typeof handler !== "function") return; - - if (!window._lh) - window._lh = []; - - window._lh.push(handler); - } + + if (window.swellrt.runtime) { + handler.apply(window, window.swellrt.runtime.get()); + } else { + if (!window._lh) + window._lh = []; + window._lh.push(handler); + } + } } var scripts = document.getElementsByTagName('script'); @@ -27,12 +29,17 @@ // Polyfill for ES6 proxy/reflect if (!window.Proxy || !window.Reflect) { - var reflectSrc = p.protocol + "//" +p.host + "/reflect.js"; - document.write("<script src='"+reflectSrc+"'></script>"); + try { + var reflectSrc = p.protocol + "//" +p.host + "/reflect.js"; + document.write("<script src='"+reflectSrc+"'></script>"); + } catch (e) { + console.log("No proxies supported: "+e); + } } var scriptSrc = p.protocol + "//" +p.host + "/swellrt_beta/swellrt_beta.nocache.js"; document.write("<script src='"+scriptSrc+"'></script>"); +} else { + console.log("Unable to inject swellrt script!"); } -
1cba85bfc369fea8168ef3f7bed0d1747c131e8f
generator/index.js
generator/index.js
var path = require('path'); var util = require('util'); var yeoman = require('yeoman-generator'); module.exports = TestGenerator; // TestGenerator stubs out a very basic test suite during the generation // process of a new generator. // // XXX: // - consider adding _.string API to generators prototype function TestGenerator() { yeoman.generators.NamedBase.apply(this, arguments); // dasherize the thing this.filename = this.dasherize(this.name).replace(/:/, '-'); this.argument('files', { type: Array, banner: 'app/file/to/test.js test/something.js ...' }); this.option('internal', { desc: 'Enable this flag when generating from yeoman-generators repo' }); this.option('prefix', { desc: 'Specify an alternate base directory', defaults: 'test/generators/' }); this.pkg = this.options.internal ? '../..' : 'yeoman-generators'; } util.inherits(TestGenerator, yeoman.generators.NamedBase); TestGenerator.prototype.createTestSuite = function() { this.template('test.js', path.join(this.options.prefix, 'test-' + this.filename + '.js')); };
var path = require('path'); var util = require('util'); var yeoman = require('yeoman-generator'); module.exports = TestGenerator; // TestGenerator stubs out a very basic test suite during the generation // process of a new generator. // // XXX: // - consider adding _.string API to generators prototype function TestGenerator() { yeoman.generators.NamedBase.apply(this, arguments); // dasherize the thing this.filename = this._.dasherize(this.name).replace(/:/, '-'); this.argument('files', { type: Array, banner: 'app/file/to/test.js test/something.js ...' }); this.option('internal', { desc: 'Enable this flag when generating from yeoman-generators repo' }); this.option('prefix', { desc: 'Specify an alternate base directory', defaults: 'test/generators/' }); this.pkg = this.options.internal ? '../..' : 'yeoman-generators'; } util.inherits(TestGenerator, yeoman.generators.NamedBase); TestGenerator.prototype.createTestSuite = function() { this.template('test.js', path.join(this.options.prefix, 'test-' + this.filename + '.js')); };
Update dasherized name to use this._
Update dasherized name to use this._
JavaScript
bsd-2-clause
yeoman/generator-mocha,yeoman/generator-mocha
--- +++ @@ -15,7 +15,7 @@ yeoman.generators.NamedBase.apply(this, arguments); // dasherize the thing - this.filename = this.dasherize(this.name).replace(/:/, '-'); + this.filename = this._.dasherize(this.name).replace(/:/, '-'); this.argument('files', { type: Array,
60bcaf4ec4f4ecf4f0add2d2823eaa8dbcfdb738
lib/plugins/ticker/coinbase/coinbase.js
lib/plugins/ticker/coinbase/coinbase.js
const _ = require('lodash/fp') const axios = require('axios') const BN = require('../../../bn') function getBuyPrice (obj) { const currencyPair = obj.currencyPair return axios({ method: 'get', url: `https://api.coinbase.com/v2/prices/${currencyPair}/buy`, headers: {'CB-Version': '2017-07-10'} }) .then(r => r.data) } function getSellPrice (obj) { const currencyPair = obj.currencyPair return axios({ method: 'get', url: `https://api.coinbase.com/v2/prices/${currencyPair}/sell`, headers: {'CB-Version': '2017-07-10'} }) .then(r => r.data) } function ticker (account, fiatCode, cryptoCode) { return Promise.resolve() .then(() => { if (!_.includes(cryptoCode, ['BTC', 'ETH', 'LTC', 'BCH', 'ZEC'])) { throw new Error('Unsupported crypto: ' + cryptoCode) } }) .then(() => { const currencyPair = `${cryptoCode}-${fiatCode}` const promises = [ getBuyPrice({currencyPair}), getSellPrice({currencyPair}) ] return Promise.all(promises) }) .then(([buyPrice, sellPrice]) => ({ rates: { ask: BN(buyPrice.data.amount), bid: BN(sellPrice.data.amount) } })) } module.exports = { ticker }
const _ = require('lodash/fp') const axios = require('axios') const BN = require('../../../bn') function getBuyPrice (obj) { const currencyPair = obj.currencyPair return axios({ method: 'get', url: `https://api.coinbase.com/v2/prices/${currencyPair}/buy`, headers: {'CB-Version': '2017-07-10'} }) .then(r => r.data) } function getSellPrice (obj) { const currencyPair = obj.currencyPair return axios({ method: 'get', url: `https://api.coinbase.com/v2/prices/${currencyPair}/sell`, headers: {'CB-Version': '2017-07-10'} }) .then(r => r.data) } function ticker (account, fiatCode, cryptoCode) { return Promise.resolve() .then(() => { if (!_.includes(cryptoCode, ['BTC', 'ETH', 'LTC', 'BCH', 'ZEC', 'DASH'])) { throw new Error('Unsupported crypto: ' + cryptoCode) } }) .then(() => { const currencyPair = `${cryptoCode}-${fiatCode}` const promises = [ getBuyPrice({currencyPair}), getSellPrice({currencyPair}) ] return Promise.all(promises) }) .then(([buyPrice, sellPrice]) => ({ rates: { ask: BN(buyPrice.data.amount), bid: BN(sellPrice.data.amount) } })) } module.exports = { ticker }
Add DASH to Coinbase ticker
Add DASH to Coinbase ticker
JavaScript
unlicense
lamassu/lamassu-server,naconner/lamassu-server,naconner/lamassu-server,naconner/lamassu-server,lamassu/lamassu-server,lamassu/lamassu-server
--- +++ @@ -28,7 +28,7 @@ function ticker (account, fiatCode, cryptoCode) { return Promise.resolve() .then(() => { - if (!_.includes(cryptoCode, ['BTC', 'ETH', 'LTC', 'BCH', 'ZEC'])) { + if (!_.includes(cryptoCode, ['BTC', 'ETH', 'LTC', 'BCH', 'ZEC', 'DASH'])) { throw new Error('Unsupported crypto: ' + cryptoCode) } })
722a07de86d32807dd0968ff0cf0b7bb93f88d97
spec/api-deprecations-spec.js
spec/api-deprecations-spec.js
const assert = require('assert') const deprecations = require('electron').deprecations describe('deprecations', function () { beforeEach(function () { deprecations.setHandler(null) process.throwDeprecation = true }) it('allows a deprecation handler function to be specified', function () { var messages = [] deprecations.setHandler(function (message) { messages.push(message) }) require('electron').webFrame.registerUrlSchemeAsSecure('some-scheme') assert.deepEqual(messages, ['registerUrlSchemeAsSecure is deprecated. Use registerURLSchemeAsSecure instead.']) }) it('throws an exception if no deprecation handler is specified', function () { assert.throws(function () { require('electron').webFrame.registerUrlSchemeAsPrivileged('some-scheme') }, 'registerUrlSchemeAsPrivileged is deprecated. Use registerURLSchemeAsPrivileged instead.') }) })
const assert = require('assert') const deprecations = require('electron').deprecations describe('deprecations', function () { beforeEach(function () { deprecations.setHandler(null) process.throwDeprecation = true }) it('allows a deprecation handler function to be specified', function () { var messages = [] deprecations.setHandler(function (message) { messages.push(message) }) require('electron').deprecate.log('this is deprecated') assert.deepEqual(messages, ['this is deprecated']) }) it('throws an exception if no deprecation handler is specified', function () { assert.throws(function () { require('electron').webFrame.registerUrlSchemeAsPrivileged('some-scheme') }, 'registerUrlSchemeAsPrivileged is deprecated. Use registerURLSchemeAsPrivileged instead.') }) })
Add explicit call to deprecate.log
Add explicit call to deprecate.log
JavaScript
mit
electron/electron,aichingm/electron,tonyganch/electron,jhen0409/electron,the-ress/electron,brave/electron,tonyganch/electron,Gerhut/electron,leethomas/electron,dongjoon-hyun/electron,Gerhut/electron,thompsonemerson/electron,Gerhut/electron,miniak/electron,noikiy/electron,leethomas/electron,shiftkey/electron,dongjoon-hyun/electron,the-ress/electron,shiftkey/electron,tonyganch/electron,kokdemo/electron,thomsonreuters/electron,deed02392/electron,voidbridge/electron,brave/electron,gabriel/electron,brave/muon,renaesop/electron,jhen0409/electron,gabriel/electron,thomsonreuters/electron,kcrt/electron,stevekinney/electron,thomsonreuters/electron,leethomas/electron,bpasero/electron,deed02392/electron,posix4e/electron,brave/muon,rreimann/electron,preco21/electron,voidbridge/electron,kokdemo/electron,gabriel/electron,leethomas/electron,electron/electron,tinydew4/electron,bpasero/electron,shiftkey/electron,bbondy/electron,miniak/electron,deed02392/electron,brenca/electron,Floato/electron,seanchas116/electron,tonyganch/electron,joaomoreno/atom-shell,tinydew4/electron,rajatsingla28/electron,bpasero/electron,brenca/electron,aichingm/electron,leethomas/electron,tonyganch/electron,rreimann/electron,minggo/electron,stevekinney/electron,twolfson/electron,tinydew4/electron,preco21/electron,bpasero/electron,biblerule/UMCTelnetHub,renaesop/electron,renaesop/electron,gerhardberger/electron,biblerule/UMCTelnetHub,jhen0409/electron,gerhardberger/electron,stevekinney/electron,aliib/electron,tonyganch/electron,brave/muon,posix4e/electron,kcrt/electron,bpasero/electron,aliib/electron,brenca/electron,jhen0409/electron,brave/muon,biblerule/UMCTelnetHub,electron/electron,miniak/electron,bbondy/electron,twolfson/electron,brave/electron,bbondy/electron,twolfson/electron,rajatsingla28/electron,thomsonreuters/electron,rajatsingla28/electron,miniak/electron,preco21/electron,gabriel/electron,aliib/electron,aliib/electron,seanchas116/electron,minggo/electron,gabriel/electron,gerhardberger/electron,preco21/electron,minggo/electron,stevekinney/electron,kokdemo/electron,voidbridge/electron,MaxWhere/electron,brave/electron,seanchas116/electron,renaesop/electron,thompsonemerson/electron,joaomoreno/atom-shell,the-ress/electron,wan-qy/electron,Floato/electron,wan-qy/electron,posix4e/electron,brenca/electron,bbondy/electron,kcrt/electron,twolfson/electron,wan-qy/electron,MaxWhere/electron,brave/muon,biblerule/UMCTelnetHub,aichingm/electron,leethomas/electron,kokdemo/electron,aichingm/electron,bbondy/electron,brenca/electron,gerhardberger/electron,renaesop/electron,kcrt/electron,minggo/electron,dongjoon-hyun/electron,brave/electron,Gerhut/electron,Floato/electron,preco21/electron,brave/muon,Floato/electron,noikiy/electron,rreimann/electron,twolfson/electron,stevekinney/electron,the-ress/electron,Gerhut/electron,thompsonemerson/electron,kokdemo/electron,posix4e/electron,electron/electron,seanchas116/electron,noikiy/electron,deed02392/electron,voidbridge/electron,noikiy/electron,jhen0409/electron,seanchas116/electron,gerhardberger/electron,wan-qy/electron,posix4e/electron,noikiy/electron,the-ress/electron,aliib/electron,twolfson/electron,rreimann/electron,seanchas116/electron,joaomoreno/atom-shell,stevekinney/electron,kcrt/electron,rreimann/electron,joaomoreno/atom-shell,miniak/electron,wan-qy/electron,thomsonreuters/electron,voidbridge/electron,noikiy/electron,electron/electron,wan-qy/electron,shiftkey/electron,tinydew4/electron,rajatsingla28/electron,thompsonemerson/electron,thompsonemerson/electron,Floato/electron,electron/electron,gerhardberger/electron,thomsonreuters/electron,bpasero/electron,minggo/electron,Gerhut/electron,gabriel/electron,renaesop/electron,MaxWhere/electron,deed02392/electron,tinydew4/electron,biblerule/UMCTelnetHub,kcrt/electron,rreimann/electron,bpasero/electron,gerhardberger/electron,rajatsingla28/electron,bbondy/electron,minggo/electron,electron/electron,shiftkey/electron,preco21/electron,joaomoreno/atom-shell,brenca/electron,joaomoreno/atom-shell,dongjoon-hyun/electron,biblerule/UMCTelnetHub,jhen0409/electron,thompsonemerson/electron,brave/electron,tinydew4/electron,aichingm/electron,dongjoon-hyun/electron,miniak/electron,aliib/electron,dongjoon-hyun/electron,the-ress/electron,rajatsingla28/electron,MaxWhere/electron,deed02392/electron,voidbridge/electron,MaxWhere/electron,MaxWhere/electron,the-ress/electron,Floato/electron,shiftkey/electron,kokdemo/electron,aichingm/electron,posix4e/electron
--- +++ @@ -14,9 +14,9 @@ messages.push(message) }) - require('electron').webFrame.registerUrlSchemeAsSecure('some-scheme') + require('electron').deprecate.log('this is deprecated') - assert.deepEqual(messages, ['registerUrlSchemeAsSecure is deprecated. Use registerURLSchemeAsSecure instead.']) + assert.deepEqual(messages, ['this is deprecated']) }) it('throws an exception if no deprecation handler is specified', function () {
76e5c44b4bfa07dceb8e5c2b24583334542ecd7c
services/user-service.js
services/user-service.js
var cote = require('cote'), models = require('../models'); var userResponder = new cote.Responder({ name: 'user responder', namespace: 'user', respondsTo: ['create'] }); var userPublisher = new cote.Publisher({ name: 'user publisher', namespace: 'user', broadcasts: ['update'] }); userResponder.on('*', console.log); userResponder.on('create', function(req, cb) { models.User.create({}, cb); updateUsers(); }); userResponder.on('list', function(req, cb) { var query = req.query || {}; models.User.find(query, cb); }); function updateUsers() { models.User.find(function(err, users) { userPublisher.publish('update', users); }); }
var cote = require('cote'), models = require('../models'); var userResponder = new cote.Responder({ name: 'user responder', namespace: 'user', respondsTo: ['create'] }); var userPublisher = new cote.Publisher({ name: 'user publisher', namespace: 'user', broadcasts: ['update'] }); userResponder.on('*', console.log); userResponder.on('create', function(req, cb) { models.User.create({}, cb); updateUsers(); }); userResponder.on('list', function(req, cb) { var query = req.query || {}; models.User.find(query, cb); }); userResponder.on('get', function(req, cb) { models.User.get(req.id, cb); }); function updateUsers() { models.User.find(function(err, users) { userPublisher.publish('update', users); }); }
Add get API to user service
Add get API to user service
JavaScript
mit
dashersw/cote-workshop,dashersw/cote-workshop
--- +++ @@ -26,6 +26,10 @@ models.User.find(query, cb); }); +userResponder.on('get', function(req, cb) { + models.User.get(req.id, cb); +}); + function updateUsers() { models.User.find(function(err, users) { userPublisher.publish('update', users);
a7d9fd9a03d96a517cdad5a4126c3b8f9db4b7b9
.storybook/utils/index.js
.storybook/utils/index.js
export const INTRODUCTION = '1. Introduction'; export const PRIMITIVES = '2. Primitives'; export const FOUNDATION = '3. Foundation'; export const LOW_LEVEL_BLOCKS = '4. Low level blocks'; export const MID_LEVEL_BLOCKS = '5. Mid level blocks'; export const COMPOSITIONS = '6. Compositions'; export const PLAYGROUND = '7. Playground';
export const INTRODUCTION = '1. Introduction'; export const PRIMITIVES = '2. Primitives'; export const FOUNDATION = '3. Foundation'; export const LOW_LEVEL_BLOCKS = '4. Low level blocks'; export const MID_LEVEL_BLOCKS = '5. Mid level blocks'; export const COMPOSITIONS = '6. Compositions'; export const PLAYGROUND = '7. Playground'; export const addStoryInGroup = (groupTitle, storyTitle) => `${groupTitle} / ${storyTitle}`;
Add function to compose the story title based on group name
Add function to compose the story title based on group name
JavaScript
mit
teamleadercrm/teamleader-ui
--- +++ @@ -5,3 +5,5 @@ export const MID_LEVEL_BLOCKS = '5. Mid level blocks'; export const COMPOSITIONS = '6. Compositions'; export const PLAYGROUND = '7. Playground'; + +export const addStoryInGroup = (groupTitle, storyTitle) => `${groupTitle} / ${storyTitle}`;
3838fc789467d5488623d79d986791c79a31134f
app/routes.js
app/routes.js
import React from 'react' import { Router, Route, browserHistory } from 'react-router' // views. import Layout from './views/Layout' import Home from './views/Home' import About from './views/About' const Routes = () => { return ( <Router history={browserHistory}> <Route component={Layout}> <Route name='home' path='/' component={Home} /> <Route name='about' path='/about' component={About} /> </Route> </Router> ) } export default Routes
import React from 'react' import { Router, Route, browserHistory } from 'react-router' import Layout from './views/Layout' import Home from './views/Home' import About from './views/About' const Routes = () => { return ( <Router history={browserHistory}> <Route component={Layout}> <Route name='home' path='/' component={Home} /> <Route name='about' path='/about' component={About} /> </Route> </Router> ) } export default Routes
Remove the unnecessary comment from the store.js file.
Remove the unnecessary comment from the store.js file.
JavaScript
mit
rhberro/the-react-client,rhberro/the-react-client
--- +++ @@ -1,8 +1,8 @@ import React from 'react' import { Router, Route, browserHistory } from 'react-router' -// views. import Layout from './views/Layout' + import Home from './views/Home' import About from './views/About'
31f3e1b1fee376bde552365d92ec51211d1718ae
webpack.common.config.js
webpack.common.config.js
const {resolve} = require('path'); const webpack =require('webpack'); module.exports = { entry: [ './index.tsx' ], output:{ filename: 'bundle.js', path: resolve(__dirname, 'static'), publicPath: '' }, resolve:{ extensions: ['js', '.jsx', '.ts', '.tsx', '.css'] }, context: resolve(__dirname, 'src'), devtool: 'inline-source-map', devServer:{ hot: true, contentBase: resolve(__dirname, 'static'), publicPath: '' }, module: { rules:[{ test: /\.(ts|tsx)$/, use: ['awesome-typescript-loader'] },{ test: /\.css$/, use: ['style-loader', 'css-loader'] } ] }, plugins: [] }
const {resolve} = require('path'); const webpack =require('webpack'); module.exports = { entry: [ './index.tsx' ], output:{ filename: 'bundle.js', path: resolve(__dirname, 'static'), publicPath: '' }, resolve:{ extensions: ['.js', '.jsx', '.ts', '.tsx', '.css'] }, context: resolve(__dirname, 'src'), devtool: 'inline-source-map', devServer:{ hot: true, contentBase: resolve(__dirname, 'static'), publicPath: '' }, module: { rules:[{ test: /\.(ts|tsx)$/, use: ['awesome-typescript-loader'] },{ test: /\.css$/, use: ['style-loader', 'css-loader'] } ] }, plugins: [] };
Fix typo for js file.
Fix typo for js file.
JavaScript
mit
bernalrs/react-typescript-webpack2,bernalrs/react-typescript-webpack2,bernalrs/react-typescript-webpack2
--- +++ @@ -11,7 +11,7 @@ publicPath: '' }, resolve:{ - extensions: ['js', '.jsx', '.ts', '.tsx', '.css'] + extensions: ['.js', '.jsx', '.ts', '.tsx', '.css'] }, context: resolve(__dirname, 'src'), devtool: 'inline-source-map', @@ -31,4 +31,4 @@ ] }, plugins: [] -} +};
88b940117ccc0ce7e88ed03f4e642f70b9835ee6
gpm-dlv/js/main.js
gpm-dlv/js/main.js
(function() { var element = null; var nav_elements = document.querySelectorAll('li.nav-item-container'); for (var i = 0; i < nav_elements.length; i++) { var current = nav_elements[i]; if (current.innerHTML == 'My Library') { element = current; break; } } if (element != null) { chrome.storage.sync.get({'gpmDefaultLibraryView': 'albums'}, function(item) { element.setAttribute('data-type', item.gpmDefaultLibraryView); }); } else { console.log('No element found; did Google change the page?'); } })();
(function() { var element = null; var nav_elements = document.querySelectorAll('.nav-item-container'); for (var i = 0; i < nav_elements.length; i++) { var current = nav_elements[i]; if (current.innerHTML == 'My Library') { element = current; break; } } if (element != null) { chrome.storage.sync.get({'gpmDefaultLibraryView': 'albums'}, function(item) { element.setAttribute('data-type', item.gpmDefaultLibraryView); }); } else { console.log('No element found; did Google change the page?'); } })();
Fix selector after Google change
Fix selector after Google change
JavaScript
mit
bluekeyes/gpm-dlv,bluekeyes/gpm-dlv
--- +++ @@ -1,6 +1,6 @@ (function() { var element = null; - var nav_elements = document.querySelectorAll('li.nav-item-container'); + var nav_elements = document.querySelectorAll('.nav-item-container'); for (var i = 0; i < nav_elements.length; i++) { var current = nav_elements[i];
a3f9c48c28f7d4ab46667b97f4c55123021c1c7d
bin/cliapp.js
bin/cliapp.js
#! /usr/bin/env node var yargs = require("yargs"); console.log(yargs.parse(process.argv.slice(2))); //var argv = require("yargs").argv; //process.argv.slice(2).forEach(function (val, index, array) { // console.log(index + ': ' + val); //}); // function readStdIn(callback) { // var called = false, data = "", finish = function (content) { // if (!called) { // process.stdin.pause(); // callback(content); // called = true; // } // }; // process.stdin.on("error", function () { // finish(); // }); // process.stdin.on("end", function () { // //finish(data); // }); // process.stdin.on("readable", function () { // var chunk = this.read(); // if (chunk === null) { // finish(data); // } else { // data += chunk; // } // }); // } // // readStdIn(function (fromStdIn) { // console.log(fromStdIn); // console.log(fromStdIn.length); // //console.log(argv); // });
#! /usr/bin/env node var App = require("../lib/app").App; var app = new App(); app.run();
Clean up CLI entry point script.
Clean up CLI entry point script.
JavaScript
mit
pjdietz/rester-client,pjdietz/rester-client
--- +++ @@ -1,39 +1,6 @@ #! /usr/bin/env node -var yargs = require("yargs"); -console.log(yargs.parse(process.argv.slice(2))); +var App = require("../lib/app").App; -//var argv = require("yargs").argv; -//process.argv.slice(2).forEach(function (val, index, array) { -// console.log(index + ': ' + val); -//}); - -// function readStdIn(callback) { -// var called = false, data = "", finish = function (content) { -// if (!called) { -// process.stdin.pause(); -// callback(content); -// called = true; -// } -// }; -// process.stdin.on("error", function () { -// finish(); -// }); -// process.stdin.on("end", function () { -// //finish(data); -// }); -// process.stdin.on("readable", function () { -// var chunk = this.read(); -// if (chunk === null) { -// finish(data); -// } else { -// data += chunk; -// } -// }); -// } -// -// readStdIn(function (fromStdIn) { -// console.log(fromStdIn); -// console.log(fromStdIn.length); -// //console.log(argv); -// }); +var app = new App(); +app.run();
9553367d007ad813bf42051af94bc671619fc308
boot/redis.js
boot/redis.js
var URL = require('url') , redis = require('redis'); module.exports = function (config) { var client, url, port, host, db, pass; if (config = config || {}) { try { url = URL.parse(config && config.url || process.env.REDIS_PORT || 'redis://localhost:6379'); port = url.port; host = url.hostname; db = config.db; auth = config && config.auth; options = { no_ready_check: true } client = redis.createClient(port, host, options); if (auth) { client.auth(auth, function () {}); } if (db) { client.select(db); } } catch (e) { throw new Error(e); } } return module.exports = client; };
var URL = require('url') , redis = require('redis'); module.exports = function (config) { var client, url, port, host, db, auth, options; if (config = config || {}) { try { url = URL.parse(config && config.url || process.env.REDIS_PORT || 'redis://localhost:6379'); port = url.port; host = url.hostname; db = config.db; auth = config && config.auth; options = { no_ready_check: true }; client = redis.createClient(port, host, options); if (auth) { client.auth(auth, function () {}); } if (db) { client.select(db); } } catch (e) { throw new Error(e); } } return module.exports = client; };
Define variables that are used but not defined
fix(boot): Define variables that are used but not defined
JavaScript
mit
henrjk/connect,anvilresearch/connect,tonyevans/connect,henrjk/connect,tonyevans/connect,anvilresearch/connect,EternalDeiwos/connect,henrjk/connect,tonyevans/connect,jawaid/connect,EternalDeiwos/connect,EternalDeiwos/connect,anvilresearch/connect,jawaid/connect,msamblanet/connect,msamblanet/connect
--- +++ @@ -2,7 +2,7 @@ , redis = require('redis'); module.exports = function (config) { - var client, url, port, host, db, pass; + var client, url, port, host, db, auth, options; if (config = config || {}) { try { @@ -15,7 +15,7 @@ options = { no_ready_check: true - } + }; client = redis.createClient(port, host, options);
33d56f057c974d466102b8bd05a7b0a99cbb0c5e
app/scripts/app/controllers/item/edit.js
app/scripts/app/controllers/item/edit.js
var ItemEditController = Em.ObjectController.extend({ setComplete: function () { var complete = this.get('canonicalModel.complete'); this.set('model.complete', complete); }.observes('canonicalModel.complete'), actions: { cancel: function () { this.get('model').destroy(); this.transitionToRoute('items'); }, save: function () { var self = this, item = this.get('model'); this.api.edit('items', item).then(function (data) { var id = Ember.get(data, 'id'); self.store.load('items', data); self.send('refresh'); self.transitionToRoute('item.index', self.store.find('items', id)); }).catch(function () { alert('Sorry, something went wrong saving your edited item! Please try again later.'); }); }, } }); export default ItemEditController;
var ItemEditController = Em.ObjectController.extend({ setComplete: function () { var model = this.get('model'), complete; // this observer fires even when this controller is not part of the active route. // this is because route controllers are singletons and persist. // since changing routes destroys the temp model we used for editing, we must // avoid accessing or mutating it until we know it's fresh (on entering the route). if (model.isDestroyed) { return; } complete = this.get('canonicalModel.complete'); model.set('complete', complete); }.observes('canonicalModel.complete'), actions: { cancel: function () { this.get('model').destroy(); this.transitionToRoute('items'); }, save: function () { var self = this, item = this.get('model'); this.api.edit('items', item).then(function (data) { var id = Ember.get(data, 'id'); self.store.load('items', data); self.send('refresh'); self.transitionToRoute('item.index', self.store.find('items', id)); }).catch(function () { alert('Sorry, something went wrong saving your edited item! Please try again later.'); }); }, } }); export default ItemEditController;
Fix ItemEditController observer accessing model when model was destroyed
Fix ItemEditController observer accessing model when model was destroyed
JavaScript
mit
darvelo/wishlist,darvelo/wishlist
--- +++ @@ -1,7 +1,18 @@ var ItemEditController = Em.ObjectController.extend({ setComplete: function () { - var complete = this.get('canonicalModel.complete'); - this.set('model.complete', complete); + var model = this.get('model'), + complete; + + // this observer fires even when this controller is not part of the active route. + // this is because route controllers are singletons and persist. + // since changing routes destroys the temp model we used for editing, we must + // avoid accessing or mutating it until we know it's fresh (on entering the route). + if (model.isDestroyed) { + return; + } + + complete = this.get('canonicalModel.complete'); + model.set('complete', complete); }.observes('canonicalModel.complete'), actions: {
9b7f8f849643c6503b3e78ba41525865ce0da91b
app/scripts/app/controllers/item/edit.js
app/scripts/app/controllers/item/edit.js
var ItemEditController = Em.ObjectController.extend({ complete: function (key, value) { if (arguments.length > 1) { return value; } return this.get('canonicalModel.complete'); }.property('canonicalModel.complete'), actions: { cancel: function () { this.get('model').destroy(); this.transitionToRoute('items'); }, save: function () { var self = this, item = this.get('model'); this.api.edit('items', item).then(function (data) { var id = Ember.get(data, 'id'); self.store.load('items', data); self.send('refresh'); self.transitionToRoute('item.index', self.store.find('items', id)); }).catch(function () { alert('Sorry, something went wrong saving your edited item! Please try again later.'); }); }, } }); export default ItemEditController;
var ItemEditController = Em.ObjectController.extend({ setComplete: function () { var complete = this.get('canonicalModel.complete'); this.set('model.complete', complete); }.observes('canonicalModel.complete'), actions: { cancel: function () { this.get('model').destroy(); this.transitionToRoute('items'); }, save: function () { var self = this, item = this.get('model'); this.api.edit('items', item).then(function (data) { var id = Ember.get(data, 'id'); self.store.load('items', data); self.send('refresh'); self.transitionToRoute('item.index', self.store.find('items', id)); }).catch(function () { alert('Sorry, something went wrong saving your edited item! Please try again later.'); }); }, } }); export default ItemEditController;
Fix saving item `complete` field
Fix saving item `complete` field
JavaScript
mit
darvelo/wishlist,darvelo/wishlist
--- +++ @@ -1,11 +1,8 @@ var ItemEditController = Em.ObjectController.extend({ - complete: function (key, value) { - if (arguments.length > 1) { - return value; - } - - return this.get('canonicalModel.complete'); - }.property('canonicalModel.complete'), + setComplete: function () { + var complete = this.get('canonicalModel.complete'); + this.set('model.complete', complete); + }.observes('canonicalModel.complete'), actions: { cancel: function () {
44b69f28d261efc2295cbc79b68b36471b53a3ca
webroot/js/elements/login-dialog.ctrl.js
webroot/js/elements/login-dialog.ctrl.js
(function() { 'use strict'; angular .module('app') .controller('LoginDialogController', ['$mdDialog', function($mdDialog) { var vm = this; vm.showDialog = showDialog; /////////////////////////////////////////////////////////////////////////// function showDialog(url) { $mdDialog.show({ controller: DialogController, templateUrl: get_tatoeba_root_url() + '/users/login_dialog_template?redirect=' + url, parent: angular.element(document.body), clickOutsideToClose:true }); } function DialogController($scope, $mdDialog) { $scope.close = function() { $mdDialog.cancel(); }; } }]); })();
(function() { 'use strict'; angular .module('app') .controller('LoginDialogController', ['$mdDialog', function($mdDialog) { var vm = this; vm.showDialog = showDialog; /////////////////////////////////////////////////////////////////////////// function showDialog(url) { $mdDialog.show({ controller: DialogController, templateUrl: get_tatoeba_root_url() + '/users/login_dialog_template?redirect=' + url, parent: angular.element(document.body), clickOutsideToClose: true, fullscreen: true }); } function DialogController($scope, $mdDialog) { $scope.close = function() { $mdDialog.cancel(); }; } }]); })();
Make login dialog fullscreen on -xs and -sm breakpoints
Make login dialog fullscreen on -xs and -sm breakpoints
JavaScript
agpl-3.0
Tatoeba/tatoeba2,Tatoeba/tatoeba2,Tatoeba/tatoeba2,Tatoeba/tatoeba2,Tatoeba/tatoeba2
--- +++ @@ -15,7 +15,8 @@ controller: DialogController, templateUrl: get_tatoeba_root_url() + '/users/login_dialog_template?redirect=' + url, parent: angular.element(document.body), - clickOutsideToClose:true + clickOutsideToClose: true, + fullscreen: true }); }
bacbc61e1f74fc8e40544c7e6e2434d68509c773
lib/exec.js
lib/exec.js
'use strict'; const shell = require('shelljs'); const cmd = require('./cmd'); // Execute msbuild.exe with passed arguments module.exports = function exec(args) { process.exit(shell.exec(cmd(args)).code); }
'use strict'; const shell = require('shelljs'); const cmd = require('./cmd'); // Execute msbuild.exe with passed arguments module.exports = function exec(args) { const result = shell.exec(cmd(args)).code; if (result !== 0) { console.log(); console.log(`MSBuild failed. ERRORLEVEL '${result}'.'`) process.exit(result); } console.log('MSBuild successfully completed.'); }
Fix handling of MSBuild errors
Fix handling of MSBuild errors
JavaScript
mit
TimMurphy/npm-msbuild
--- +++ @@ -5,5 +5,11 @@ // Execute msbuild.exe with passed arguments module.exports = function exec(args) { - process.exit(shell.exec(cmd(args)).code); + const result = shell.exec(cmd(args)).code; + if (result !== 0) { + console.log(); + console.log(`MSBuild failed. ERRORLEVEL '${result}'.'`) + process.exit(result); + } + console.log('MSBuild successfully completed.'); }
0d705644e49cab96f5ffd4b4337d2ac8d5cbb053
lib/deps.js
lib/deps.js
var canihaz = require('canihaz'), fs = require('fs'), p = require('path'); /** * Install dependency modules that are not yet installed, and needed for executing the tasks. * * @param {Array} depNames: an array of dependency module names * @param {String} dir: application directory where node_modules dir is located * @param {Function} cb: standard cb(err, result) callback */ function install(depNames, dir, cb) { fs.readdir(p.join(dir, 'node_modules'), function(err, installed) { var uninstalled = []; depNames.forEach(function (depName) { if (installed.indexOf(depName) === -1) { uninstalled.push(depName); } }); if (uninstalled.length > 0) { console.log('[deps] Installing modules: %s (might take a while)', uninstalled .join(', ')); canihaz({ key: 'optDependencies' }).apply(this, depNames.concat(cb)); } else { cb(); } }); } exports.install = install;
var canihaz = require('canihaz'), fs = require('fs'), p = require('path'); /** * Install dependency modules that are not yet installed, and needed for executing the tasks. * * @param {Array} depNames: an array of dependency module names * @param {String} dir: application directory where node_modules dir is located * @param {Function} cb: standard cb(err, result) callback */ function install(depNames, dir, cb) { fs.readdir(p.join(dir, 'node_modules'), function(err, installed) { var uninstalled = []; depNames.forEach(function (depName) { if (installed.indexOf(depName) === -1) { uninstalled.push(depName); } }); if (uninstalled.length > 0) { console.log('[deps] Installing modules: %s (might take a while, once-off only)', uninstalled .join(', ')); canihaz({ key: 'optDependencies' }).apply(this, depNames.concat(cb)); } else { cb(); } }); } exports.install = install;
Add note that lazy-installed modules are once-off only.
Add note that lazy-installed modules are once-off only.
JavaScript
mit
cliffano/bob
--- +++ @@ -18,7 +18,7 @@ } }); if (uninstalled.length > 0) { - console.log('[deps] Installing modules: %s (might take a while)', uninstalled .join(', ')); + console.log('[deps] Installing modules: %s (might take a while, once-off only)', uninstalled .join(', ')); canihaz({ key: 'optDependencies' }).apply(this, depNames.concat(cb)); } else { cb();
329ab24aed5a9848e98d6a504ad8b2997142c23b
lib/main.js
lib/main.js
var buffer = require("./buffer"); /** * @namespace Splat */ module.exports = { makeBuffer: buffer.makeBuffer, flipBufferHorizontally: buffer.flipBufferHorizontally, flipBufferVertically: buffer.flipBufferVertically, ads: require("./ads"), AStar: require("./astar"), BinaryHeap: require("./binary-heap"), Game: require("./game"), iap: require("./iap"), Input: require("./input"), leaderboards: require("./leaderboards"), math: require("./math"), openUrl: require("./openUrl"), NinePatch: require("./ninepatch"), Particles: require("./particles"), saveData: require("./save-data"), Scene: require("./scene"), components: { animation: require("./components/animation"), camera: require("./components/camera"), friction: require("./components/friction"), image: require("./components/image"), movement2d: require("./components/movement-2d"), playableArea: require("./components/playable-area"), playerController2d: require("./components/player-controller-2d"), position: require("./components/position"), size: require("./components/size"), timers: require("./components/timers"), velocity: require("./components/velocity") } };
var buffer = require("./buffer"); /** * @namespace Splat */ module.exports = { makeBuffer: buffer.makeBuffer, flipBufferHorizontally: buffer.flipBufferHorizontally, flipBufferVertically: buffer.flipBufferVertically, ads: require("./ads"), AStar: require("./astar"), BinaryHeap: require("./binary-heap"), Game: require("./game"), iap: require("./iap"), Input: require("./input"), leaderboards: require("./leaderboards"), math: require("./math"), openUrl: require("./openUrl"), NinePatch: require("./ninepatch"), Particles: require("./particles"), saveData: require("./save-data"), Scene: require("./scene") };
Remove big export of components
Remove big export of components
JavaScript
mit
SplatJS/splat-ecs
--- +++ @@ -20,19 +20,5 @@ NinePatch: require("./ninepatch"), Particles: require("./particles"), saveData: require("./save-data"), - Scene: require("./scene"), - - components: { - animation: require("./components/animation"), - camera: require("./components/camera"), - friction: require("./components/friction"), - image: require("./components/image"), - movement2d: require("./components/movement-2d"), - playableArea: require("./components/playable-area"), - playerController2d: require("./components/player-controller-2d"), - position: require("./components/position"), - size: require("./components/size"), - timers: require("./components/timers"), - velocity: require("./components/velocity") - } + Scene: require("./scene") };
6f3d8b949133178a7f7202a060fcc35b19f4cac2
src/root.js
src/root.js
import React from 'react'; const Root = (props) => { return ( <div>{props.children}</div> ); }; Root.displayName = 'Root'; export default Root;
import React, { Children } from 'react'; const Root = ({ children }) => Children.only(children); Root.displayName = 'Root'; export default Root;
Remove <div/> from Root and add Children.only
Remove <div/> from Root and add Children.only
JavaScript
artistic-2.0
raulmatei/frux-table-test,raulmatei/frux-table-test
--- +++ @@ -1,11 +1,6 @@ -import React from 'react'; +import React, { Children } from 'react'; -const Root = (props) => { - return ( - <div>{props.children}</div> - ); -}; +const Root = ({ children }) => Children.only(children); Root.displayName = 'Root'; - export default Root;
1461598f43ec70e9cfea8313406b3c5482d7032b
src/image/transform/bitDepth.js
src/image/transform/bitDepth.js
import Image from '../image'; export default function bitDepth(newBitDepth = 8) { this.checkProcessable('bitDepth', { bitDepth: [8, 16] }); if (![8,16].includes(newBitDepth)) throw Error('You need to specify the new bitDepth as 8 or 16'); if (this.bitDepth === newBitDepth) return this.clone(); let newImage = Image.createFrom(this, {bitDepth: newBitDepth}); if (newBitDepth === 8) { for (let i = 0; i < this.data.length; i++) { newImage.data[i] = this.data[i] >> 8; } } else { for (let i = 0; i < this.data.length; i++) { newImage.data[i] = this.data[i] << 8 | this.data[i]; } } return newImage; }
import Image from '../image'; export default function bitDepth(newBitDepth = 8) { this.checkProcessable('bitDepth', { bitDepth: [8, 16] }); if (!~[8,16].indexOf(newBitDepth)) throw Error('You need to specify the new bitDepth as 8 or 16'); if (this.bitDepth === newBitDepth) return this.clone(); let newImage = Image.createFrom(this, {bitDepth: newBitDepth}); if (newBitDepth === 8) { for (let i = 0; i < this.data.length; i++) { newImage.data[i] = this.data[i] >> 8; } } else { for (let i = 0; i < this.data.length; i++) { newImage.data[i] = this.data[i] << 8 | this.data[i]; } } return newImage; }
Remove includes to be compatible with currently released chrome
Remove includes to be compatible with currently released chrome
JavaScript
mit
image-js/ij,image-js/core,image-js/ij,image-js/image-js,image-js/core,image-js/image-js,image-js/ij
--- +++ @@ -6,7 +6,7 @@ bitDepth: [8, 16] }); - if (![8,16].includes(newBitDepth)) throw Error('You need to specify the new bitDepth as 8 or 16'); + if (!~[8,16].indexOf(newBitDepth)) throw Error('You need to specify the new bitDepth as 8 or 16'); if (this.bitDepth === newBitDepth) return this.clone();
7bed9dc2f607264f7499251119a36e9bd530b2f9
HelloWorld/lib/myPanel.js
HelloWorld/lib/myPanel.js
/* See license.txt for terms of usage */ "use strict"; const self = require("sdk/self"); const { Cu, Ci } = require("chrome"); const { Panel } = require("dev/panel.js"); const { Class } = require("sdk/core/heritage"); const { Tool } = require("dev/toolbox"); /** * This object represents a new {@Toolbox} panel */ const MyPanel = Class( /** @lends MyPanel */ { extends: Panel, label: "My Panel", tooltip: "My panel tooltip", icon: "./icon-16.png", url: "./myPanel.html", /** * Executed by the framework when an instance of this panel is created. * There is one instance of this panel per {@Toolbox}. The panel is * instantiated when selected in the toolbox for the first time. */ initialize: function(options) { }, /** * Executed by the framework when the panel is destroyed. */ dispose: function() { }, /** * Executed by the framework when the panel content iframe is * constructed. Allows e.g to connect the backend through * `debuggee` object */ setup: function(options) { // TODO: connect to backend using options.debuggee }, }); const myTool = new Tool({ name: "MyTool", panels: { myPanel: MyPanel } });
/* See license.txt for terms of usage */ "use strict"; const self = require("sdk/self"); const { Cu, Ci } = require("chrome"); const { Panel } = require("dev/panel.js"); const { Class } = require("sdk/core/heritage"); const { Tool } = require("dev/toolbox"); /** * This object represents a new {@Toolbox} panel */ const MyPanel = Class( /** @lends MyPanel */ { extends: Panel, label: "My Panel", tooltip: "My panel tooltip", icon: "./icon-16.png", url: "./myPanel.html", /** * Executed by the framework when an instance of this panel is created. * There is one instance of this panel per {@Toolbox}. The panel is * instantiated when selected in the toolbox for the first time. */ initialize: function(options) { }, /** * Executed by the framework when the panel is destroyed. */ dispose: function() { }, /** * Executed by the framework when the panel content iframe is * constructed. Allows e.g to connect the backend through * `debuggee` object */ setup: function(options) { console.log("MyPanel.setup" + options.debuggee); this.debuggee = options.debuggee; // TODO: connect to backend using options.debuggee }, onReady: function() { console.log("MyPanel.onReady " + this.debuggee); } }); const myTool = new Tool({ name: "MyTool", panels: { myPanel: MyPanel } });
Set debuggee in HelloWorld example
Set debuggee in HelloWorld example
JavaScript
bsd-3-clause
firebug/devtools-extension-examples,firebug/devtools-extension-examples
--- +++ @@ -42,8 +42,16 @@ * `debuggee` object */ setup: function(options) { + console.log("MyPanel.setup" + options.debuggee); + + this.debuggee = options.debuggee; + // TODO: connect to backend using options.debuggee }, + + onReady: function() { + console.log("MyPanel.onReady " + this.debuggee); + } }); const myTool = new Tool({
ec86eded4c14b5b82a36dd731c272a43b8565ea6
test/bin.js
test/bin.js
(function() { 'use strict'; var cli = require('casper').create().cli; var parapsych = require(cli.raw.get('rootdir') + '/dist/parapsych').create(require); parapsych.set('cli', cli) .set('initUrl', '/') .set('initSel', 'body'); describe('/', function() { it('should pass --grep filter' , function() { this.test.assertEquals(this.fetchText('body').trim(), 'Hello World'); }); it('should not pass --grep filter' , function() { this.test.assertEquals(true, false); }); }); parapsych.done(); })();
(function() { 'use strict'; var cli = require('casper').create().cli; var parapsych = require(cli.raw.get('rootdir') + '/dist/parapsych').create(require); parapsych.set('cli', cli) .set('initUrl', '/') .set('initSel', 'body'); describe('group 1', function() { it('should pass --grep filter' , function() { this.test.assertEquals(this.fetchText('body').trim(), 'Hello World'); }); it('should not pass --grep filter' , function() { this.test.assertEquals(true, false); }); }); describe('group 2', function() { it('should pass --grep filter' , function() { this.test.assertEquals(this.fetchText('body').trim(), 'Hello World'); }); it('should not pass --grep filter' , function() { this.test.assertEquals(true, false); }); }); parapsych.done(); })();
Add a 2nd describe() block to auto-start logic
Add a 2nd describe() block to auto-start logic
JavaScript
mit
codeactual/conjure,codeactual/conjure
--- +++ @@ -8,7 +8,17 @@ .set('initUrl', '/') .set('initSel', 'body'); - describe('/', function() { + describe('group 1', function() { + it('should pass --grep filter' , function() { + this.test.assertEquals(this.fetchText('body').trim(), 'Hello World'); + }); + + it('should not pass --grep filter' , function() { + this.test.assertEquals(true, false); + }); + }); + + describe('group 2', function() { it('should pass --grep filter' , function() { this.test.assertEquals(this.fetchText('body').trim(), 'Hello World'); });
aa3925cdf7d3427541d0d50a08bef0f628aabd2c
test/ResultItem.js
test/ResultItem.js
'use strict'; var Component = require('../ui/Component'); function ResultItem() { ResultItem.super.apply(this, arguments); } ResultItem.Prototype = function() { this.shouldRerender = function() { return false; }; this.render = function($$) { var test = this.props.test; var result = this.props.result; var el = $$('div').addClass('sc-test-result'); var header = $$('div'); if (!test._skip) { if (result.ok) { header.append($$('span').addClass('se-status sm-ok').append("\u2713")); } else { header.append($$('span').addClass('se-status sm-not-ok').append("\u26A0")); } } header.append($$('span').addClass('se-description').append(result.name)); el.append(header); if (!test._skip && !result.ok && result.operator === "equal") { var diff = $$('div').addClass('se-diff'); var expected = $$('div').addClass('se-expected') .append('Expected:') .append($$('pre').append(String(result.expected))); var actual = $$('div').addClass('se-actual') .append('Actual:') .append($$('pre').append(String(result.actual))); diff.append(expected, actual); el.append(diff); } return el; }; }; Component.extend(ResultItem); module.exports = ResultItem;
'use strict'; var Component = require('../ui/Component'); function ResultItem() { ResultItem.super.apply(this, arguments); } ResultItem.Prototype = function() { this.shouldRerender = function() { return false; }; this.render = function($$) { var test = this.props.test; var result = this.props.result; var el = $$('div').addClass('sc-test-result'); var header = $$('div'); if (!test._skip) { if (result.ok) { header.append($$('span').addClass('se-status sm-ok').append("\u2713")); } else { header.append($$('span').addClass('se-status sm-not-ok').append("\u26A0")); } } header.append($$('span').addClass('se-description').append(String(result.name))); el.append(header); if (!test._skip && !result.ok && result.operator === "equal") { var diff = $$('div').addClass('se-diff'); var expected = $$('div').addClass('se-expected') .append('Expected:') .append($$('pre').append(String(result.expected))); var actual = $$('div').addClass('se-actual') .append('Actual:') .append($$('pre').append(String(result.actual))); diff.append(expected, actual); el.append(diff); } return el; }; }; Component.extend(ResultItem); module.exports = ResultItem;
Fix in test result renderer.
Fix in test result renderer.
JavaScript
mit
podviaznikov/substance,substance/substance,substance/substance,michael/substance-1,andene/substance,michael/substance-1,stencila/substance,podviaznikov/substance,andene/substance
--- +++ @@ -25,7 +25,7 @@ header.append($$('span').addClass('se-status sm-not-ok').append("\u26A0")); } } - header.append($$('span').addClass('se-description').append(result.name)); + header.append($$('span').addClass('se-description').append(String(result.name))); el.append(header); if (!test._skip && !result.ok && result.operator === "equal") {
bd0b72d850975ba74e3b7eb785fc169ab08c4c8c
feature-detects/emoji.js
feature-detects/emoji.js
// Requires a Modernizr build with `canvastest` included // http://www.modernizr.com/download/#-canvas-canvastext Modernizr.addTest('emoji', function() { if (!Modernizr.canvastext) return false; var node = document.createElement('canvas'), ctx = node.getContext('2d'); ctx.textBaseline = 'top'; ctx.font = '32px Arial'; ctx.fillText('\ud83d\ude03', 0, 0); // "smiling face with open mouth" emoji return ctx.getImageData(16, 16, 1, 1).data[0] != 0; });
// Requires a Modernizr build with `canvastext` included // http://www.modernizr.com/download/#-canvas-canvastext Modernizr.addTest('emoji', function() { if (!Modernizr.canvastext) return false; var node = document.createElement('canvas'), ctx = node.getContext('2d'); ctx.textBaseline = 'top'; ctx.font = '32px Arial'; ctx.fillText('\ud83d\ude03', 0, 0); // "smiling face with open mouth" emoji return ctx.getImageData(16, 16, 1, 1).data[0] != 0; });
Fix longstanding typo. SORRY GUISE
Fix longstanding typo. SORRY GUISE
JavaScript
mit
Modernizr/Modernizr,Modernizr/Modernizr
--- +++ @@ -1,4 +1,4 @@ -// Requires a Modernizr build with `canvastest` included +// Requires a Modernizr build with `canvastext` included // http://www.modernizr.com/download/#-canvas-canvastext Modernizr.addTest('emoji', function() { if (!Modernizr.canvastext) return false;
d6b84881d747f2fe6f2fe61a5e762c04ac821ae5
client/app/controllers/boltController.js
client/app/controllers/boltController.js
angular.module('bolt.controller', []) .controller('BoltController', function($scope, Geo){ })
angular.module('bolt.controller', []) .controller('BoltController', function($scope, $window){ $scope.session = $window.localStorage; })
Add user session to bolt $scope
Add user session to bolt $scope
JavaScript
mit
gm758/Bolt,boisterousSplash/Bolt,gm758/Bolt,thomasRhoffmann/Bolt,elliotaplant/Bolt,thomasRhoffmann/Bolt,boisterousSplash/Bolt,elliotaplant/Bolt
--- +++ @@ -1,5 +1,5 @@ angular.module('bolt.controller', []) -.controller('BoltController', function($scope, Geo){ - +.controller('BoltController', function($scope, $window){ + $scope.session = $window.localStorage; })
113f8c74b6780af1def3c07d1c87b266223930dc
test/Voice-test.js
test/Voice-test.js
import Voice from '../lib/Voice'; import NexmoStub from './NexmoStub'; var voiceAPIs = [ 'sendTTSMessage', 'sendTTSPromptWithCapture', 'sendTTSPromptWithConfirm', 'call' ]; describe('Voice Object', function () { it('should implement all v1 APIs', function() { NexmoStub.checkAllFunctionsAreDefined(voiceAPIs, Voice); }); it('should proxy the function call to the underlying `nexmo` object', function() { NexmoStub.checkAllFunctionsAreCalled(voiceAPIs, Voice); }); });
import Voice from '../lib/Voice'; import NexmoStub from './NexmoStub'; var voiceAPIs = { 'sendTTSMessage': 'sendTTSMessage', 'sendTTSPromptWithCapture': 'sendTTSPromptWithCapture', 'sendTTSPromptWithConfirm': 'sendTTSPromptWithConfirm', 'call': 'call' }; describe('Voice Object', function () { it('should implement all v1 APIs', function() { NexmoStub.checkAllFunctionsAreDefined(voiceAPIs, Voice); }); it('should proxy the function call to the underlying `nexmo` object', function() { NexmoStub.checkAllFunctionsAreCalled(voiceAPIs, Voice); }); });
Update Voice tests with mappings
Update Voice tests with mappings
JavaScript
mit
Nexmo/nexmo-node
--- +++ @@ -2,12 +2,12 @@ import NexmoStub from './NexmoStub'; -var voiceAPIs = [ - 'sendTTSMessage', - 'sendTTSPromptWithCapture', - 'sendTTSPromptWithConfirm', - 'call' -]; +var voiceAPIs = { + 'sendTTSMessage': 'sendTTSMessage', + 'sendTTSPromptWithCapture': 'sendTTSPromptWithCapture', + 'sendTTSPromptWithConfirm': 'sendTTSPromptWithConfirm', + 'call': 'call' +}; describe('Voice Object', function () {
eba9d1a3a4615726c2ef6db72bf9cd508c6a0489
gulpfile.js/tasks/css.js
gulpfile.js/tasks/css.js
'use strict'; // Modules // =============================================== var gulp = require('gulp'), gutil = require('gulp-util'), browserSync = require("browser-sync"), paths = require('../paths'); // Copy CSS to build folder // =============================================== gulp.task('css', function() { return gulp.src(paths.css.input) // Save files .pipe(gulp.dest(paths.css.output)) .on('end', function() { gutil.log(gutil.colors.magenta('css'), ':', gutil.colors.green('finished')); gutil.log(gutil.colors.magenta('browserSync'), ':', gutil.colors.green('reload')); browserSync.reload(); }) });
'use strict'; // Modules // =============================================== var gulp = require('gulp'), paths = require('../paths'), gutil = require('gulp-util'), browserSync = require("browser-sync"), debug = require('gulp-debug'); // Copy CSS to build folder // =============================================== gulp.task('css', function() { return gulp.src(paths.css.input) // Show name of file in pipe .pipe(debug({title: 'css:'})) // Save files .pipe(gulp.dest(paths.css.output)) .on('end', function() { gutil.log(gutil.colors.magenta('css'), ':', gutil.colors.green('finished')); gutil.log(gutil.colors.magenta('browserSync'), ':', gutil.colors.green('reload')); browserSync.reload(); }) });
Add info about CSS files to console
Add info about CSS files to console
JavaScript
mit
ilkome/front-end,ilkome/frontend,ilkome/front-end,ilkome/frontend
--- +++ @@ -3,15 +3,19 @@ // Modules // =============================================== var gulp = require('gulp'), + paths = require('../paths'), gutil = require('gulp-util'), browserSync = require("browser-sync"), - paths = require('../paths'); + debug = require('gulp-debug'); // Copy CSS to build folder // =============================================== gulp.task('css', function() { return gulp.src(paths.css.input) + + // Show name of file in pipe + .pipe(debug({title: 'css:'})) // Save files .pipe(gulp.dest(paths.css.output))
32a0847fa95609901cb97ac28003a148e8ad559a
app/components/__tests__/Preview-test.js
app/components/__tests__/Preview-test.js
import React from 'react'; import { shallow, render } from 'enzyme'; import { expect } from 'chai'; // see: https://github.com/mochajs/mocha/issues/1847 const { describe, it } = global; import Preview from '../Preview'; describe('<Preview />', () => { it('renders a block with preview css class', () => { const wrapper = shallow(<Preview raw={""} />); expect(wrapper.find('.preview')).to.have.length(1); }); it('renders content', () => { const wrapper = render(<Preview raw={"foo"} />); expect(wrapper.find('.rendered').text()).to.contain('foo'); }); it('converts markdown into HTML', () => { const wrapper = render(<Preview raw={"*italic*"} />); expect(wrapper.find('.rendered').html()).to.contain('<em>italic</em>'); }); it('converts Emoji', () => { const wrapper = render(<Preview raw={" :)"} />); expect(wrapper.find('.rendered').html()).to.contain( '<img align="absmiddle" alt=":smile:" class="emoji" src="https://github.global.ssl.fastly.net/images/icons/emoji//smile.png" title=":smile:"></p>' ); }); });
import React from 'react'; import { shallow, render } from 'enzyme'; import { expect } from 'chai'; // see: https://github.com/mochajs/mocha/issues/1847 const { describe, it } = global; import Preview from '../Preview'; describe('<Preview />', () => { it('renders a block with preview css class', () => { const wrapper = shallow(<Preview raw={""} />); expect(wrapper.find('.preview')).to.have.length(1); }); it('renders content', () => { const wrapper = render(<Preview raw={"foo"} />); expect(wrapper.find('.rendered').text()).to.contain('foo'); }); it('converts markdown into HTML', () => { const wrapper = render(<Preview raw={"*italic*"} />); expect(wrapper.find('.rendered').html()).to.contain('<em>italic</em>'); }); it('converts Emoji', () => { const wrapper = render(<Preview raw={" :)"} />); expect(wrapper.find('.rendered').html()).to.contain( '<img align="absmiddle" alt=":smile:" class="emoji" src="https://github.global.ssl.fastly.net/images/icons/emoji//smile.png" title=":smile:">' ); }); it('highlights code blocks', () => { const wrapper = render(<Preview raw={"```python\nprint()```"} />); expect(wrapper.find('.rendered').html()).to.contain( '<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">()</span></span>\n</code></pre>' ); }); });
Add test for highlight.js rendering
Add test for highlight.js rendering
JavaScript
mit
PaulDebus/monod,TailorDev/monod,TailorDev/monod,TailorDev/monod,PaulDebus/monod,PaulDebus/monod
--- +++ @@ -28,7 +28,14 @@ it('converts Emoji', () => { const wrapper = render(<Preview raw={" :)"} />); expect(wrapper.find('.rendered').html()).to.contain( - '<img align="absmiddle" alt=":smile:" class="emoji" src="https://github.global.ssl.fastly.net/images/icons/emoji//smile.png" title=":smile:"></p>' + '<img align="absmiddle" alt=":smile:" class="emoji" src="https://github.global.ssl.fastly.net/images/icons/emoji//smile.png" title=":smile:">' + ); + }); + + it('highlights code blocks', () => { + const wrapper = render(<Preview raw={"```python\nprint()```"} />); + expect(wrapper.find('.rendered').html()).to.contain( + '<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">()</span></span>\n</code></pre>' ); }); });
4394772d90e017a0fad11f5292f819cd2790ae71
api/app/features/events/eventHandler.js
api/app/features/events/eventHandler.js
const Boom = require('boom'); const hostService = require('../../domain/services/host-service'); const eventService = require('../../domain/services/event-service'); module.exports = { create(request, reply) { const { user } = request.payload; const { event } = request.payload; return hostService .createHost(user) .then((userId) => { const eventDetails = Object.assign({}, { userId }, event); return eventService.createEvent(eventDetails); }); } };
const Boom = require('boom'); const hostService = require('../../domain/services/host-service'); const eventService = require('../../domain/services/event-service'); module.exports = { create(request, reply) { return hostService .createHost(request.payload.user) .then(({ _id: userId }) => { return eventService.createEvent(userId, request.payload.event); }) .then(url => reply(url).code(201)) .catch((err) => { const statusCode = _getErrorStatusCode(err); reply(err).code(statusCode); }); } }; function _getErrorStatusCode(err) { return ('name' in err) ? 500 : 422; }
Add little error management in event route
Add little error management in event route
JavaScript
agpl-3.0
Hypernikao/who-brings-what
--- +++ @@ -4,14 +4,19 @@ module.exports = { create(request, reply) { - const { user } = request.payload; - const { event } = request.payload; - return hostService - .createHost(user) - .then((userId) => { - const eventDetails = Object.assign({}, { userId }, event); - return eventService.createEvent(eventDetails); + .createHost(request.payload.user) + .then(({ _id: userId }) => { + return eventService.createEvent(userId, request.payload.event); + }) + .then(url => reply(url).code(201)) + .catch((err) => { + const statusCode = _getErrorStatusCode(err); + reply(err).code(statusCode); }); } }; + +function _getErrorStatusCode(err) { + return ('name' in err) ? 500 : 422; +}