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
6f2d1ebec42aaa1ed9edf32e33018b89840bb7f5
modules/hn/index.js
modules/hn/index.js
var hn = require('hacker-news-api'); var ent = require('ent'); var qs = require('querystring'); var S = require('string'); var hnRegex = /^https?:\/\/news\.ycombinator\.com\/(.*)/; module.exports.url = function(url, reply) { var m; if((m = hnRegex.exec(url))) { if(m[1].indexOf('?') == -1) { return; //Don't handle naked links yet, only stories } var qsToParse = m[1].split('?'); var query = qs.parse(qsToParse[qsToParse.length - 1]); var id = parseInt(query.id, 10); if(typeof id !== 'number' || isNaN(id)) return; hn.item(id, function(err, res) { if(err) return reply("Unable to get HN store info"); if(res.type == 'story') { return reply("HackerNews - " + res.title + " - Posted by: " + res.author); //Todo, created-at info } else if(res.type == 'comment') { var toSay = res.author + " wrote: " + ent.decode(res.text); toSay = S(toSay).stripTags().s; if(toSay.length < 500) return reply(toSay); } }); } };
var hn = require('hacker-news-api'); var ent = require('ent'); var qs = require('querystring'); var S = require('string'); var hnRegex = /^https?:\/\/news\.ycombinator\.com\/(.*)/; module.exports.url = function(url, reply) { var m; if((m = hnRegex.exec(url))) { if(m[1].indexOf('?') == -1) { return; //Don't handle naked links yet, only stories } var qsToParse = m[1].split('?'); var query = qs.parse(qsToParse[qsToParse.length - 1]); var id = parseInt(query.id, 10); if(typeof id !== 'number' || isNaN(id)) return; hn.item(id, function(err, res) { if(err) return reply("Unable to get HN store info"); if(res.type == 'story') { return reply("HackerNews - " + res.title + " - Posted by: " + res.author); //Todo, created-at info } else if(res.type == 'comment') { var toSay = res.author + " wrote: " + ent.decode(res.text); toSay = S(toSay).stripTags().replaceAll('\n',' | ').s; if(toSay.length < 500) return reply(toSay); } }); } };
Replace HN newlines similar to t_t
Replace HN newlines similar to t_t
JavaScript
mit
brhoades/EuIrcBot,LinuxMercedes/EuIrcBot,brhoades/EuIrcBot,gmackie/EuIrcBot,gmackie/EuIrcBot,euank/EuIrcBot,LinuxMercedes/EuIrcBot,euank/EuIrcBot
--- +++ @@ -26,7 +26,7 @@ return reply("HackerNews - " + res.title + " - Posted by: " + res.author); //Todo, created-at info } else if(res.type == 'comment') { var toSay = res.author + " wrote: " + ent.decode(res.text); - toSay = S(toSay).stripTags().s; + toSay = S(toSay).stripTags().replaceAll('\n',' | ').s; if(toSay.length < 500) return reply(toSay); } });
14ac3febd59136b5309f6b170c4a64f42df4529e
models/user.js
models/user.js
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var bcrypt = require('bcrypt-nodejs'); var UserSchema = new Schema({ email: String, password: String, firstName: String, lastName: String }); UserSchema.methods.isValidPassword = function(password){ return bcrypt.compareSync(password, this.password); }; UserSchema.methods.setPassword = function(password){ this.password = bcrypt.hashSync(password, 10); }; module.exports = mongoose.model('User',UserSchema);
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var bcrypt = require('bcrypt-nodejs'); var UserSchema = new Schema({ email: String, password: String, firstName: String, lastName: String }); UserSchema.methods.isValidPassword = function(password){ return bcrypt.compareSync(password, this.password); }; UserSchema.methods.setPassword = function(password){ this.password = bcrypt.hashSync(password, bcrypt.genSaltSync(10)); }; module.exports = mongoose.model('User',UserSchema);
Fix broken API usage of the new bcrypt-nodejs lib
Fix broken API usage of the new bcrypt-nodejs lib
JavaScript
mit
revov/uci-gui,revov/uci-gui
--- +++ @@ -14,7 +14,7 @@ }; UserSchema.methods.setPassword = function(password){ - this.password = bcrypt.hashSync(password, 10); + this.password = bcrypt.hashSync(password, bcrypt.genSaltSync(10)); }; module.exports = mongoose.model('User',UserSchema);
0314d4a3cbbee5f69deea275497a0bfb9343e78f
lib/hijack/async.js
lib/hijack/async.js
var Fibers = Npm.require('fibers'); var originalYield = Fibers.yield; Fibers.yield = function() { var kadiraInfo = Kadira._getInfo(); if(kadiraInfo) { var eventId = Kadira.tracer.event(kadiraInfo.trace, 'async');; if(eventId) { Fibers.current._apmEventId = eventId; } } originalYield(); }; var originalRun = Fibers.prototype.run; Fibers.prototype.run = function(val) { if(this._apmEventId) { var kadiraInfo = Kadira._getInfo(this); if(kadiraInfo) { Kadira.tracer.eventEnd(kadiraInfo.trace, this._apmEventId); this._apmEventId = null; } } originalRun.call(this, val); };
var Fibers = Npm.require('fibers'); var originalYield = Fibers.yield; Fibers.yield = function() { var kadiraInfo = Kadira._getInfo(); if(kadiraInfo) { var eventId = Kadira.tracer.event(kadiraInfo.trace, 'async');; if(eventId) { Fibers.current._apmEventId = eventId; } } return originalYield(); }; var originalRun = Fibers.prototype.run; Fibers.prototype.run = function(val) { if(this._apmEventId) { var kadiraInfo = Kadira._getInfo(this); if(kadiraInfo) { Kadira.tracer.eventEnd(kadiraInfo.trace, this._apmEventId); this._apmEventId = null; } } return originalRun.call(this, val); };
Add support for Meteor 1.2
Add support for Meteor 1.2
JavaScript
mit
chatr/kadira,meteorhacks/kadira
--- +++ @@ -10,7 +10,7 @@ } } - originalYield(); + return originalYield(); }; var originalRun = Fibers.prototype.run; @@ -22,5 +22,5 @@ this._apmEventId = null; } } - originalRun.call(this, val); + return originalRun.call(this, val); };
dcea9b4539ba2b16b3d2a7ee8ecebb86d2f30122
lib/utils.js
lib/utils.js
"use strict" module.exports = (function(obj) { var cli = require("cli"), json = require("jsonfile"); function returnUnicArrays(arr) { try { var filteredArray = arr.filter(function(item, pos) { return arr.indexOf(item) == pos; }); } catch (e) { showError(e); } return filteredArray; } function writeJson(filePath, obj) { json.writeFileSync(filePath, obj, {spaces: 2}, function (err) { cli.error(err); }) cli.ok("File created in: " + filePath); } function showError(msg) { cli.err(msg); process.exit(1); } return { returnUnicArrays: returnUnicArrays, writeJson: writeJson, showError: showError } })();
"use strict" module.exports = (function(obj) { var cli = require("cli"), json = require("jsonfile"); function returnUnicArrays(arr) { try { var filteredArray = arr.filter(function(item, pos) { return arr.indexOf(item) == pos; }); } catch (e) { showError(e); } return filteredArray; } function writeJson(filePath, obj) { json.writeFileSync(filePath, obj, {spaces: 2}, function (err) { cli.error(err); }) cli.ok("File created in: \x1b[92m" + filePath); } function showError(msg) { cli.err(msg); process.exit(1); } return { returnUnicArrays: returnUnicArrays, writeJson: writeJson, showError: showError } })();
Add color to feedback msg
Add color to feedback msg
JavaScript
mit
klaytonfaria/zweepr
--- +++ @@ -18,7 +18,7 @@ json.writeFileSync(filePath, obj, {spaces: 2}, function (err) { cli.error(err); }) - cli.ok("File created in: " + filePath); + cli.ok("File created in: \x1b[92m" + filePath); } function showError(msg) {
f2779249c0cffb3f54b26437c35fdc5b206014d5
lib/oxide_client.js
lib/oxide_client.js
var _ = require('lodash'), dgram = require('dgram'); function Client (opts) { opts = _.defaults(_.pick(opts, Object.keys(Client.defaults)), Client.defaults); for (var key in opts) { Object.defineProperty(this, key, { value: opts[key] }) } } Client.prototype.connect = function () { return this.socket = dgram.createSocket(this.type); } Client.defaults = { host: '127.0.0.1', port: 2003, type: 'udp4' } module.exports = Client;
var _ = require('lodash'), dgram = require('dgram'); function Client (opts) { this.queue = []; opts = _.defaults(_.pick(opts, Object.keys(Client.defaults)), Client.defaults); for (var key in opts) { Object.defineProperty(this, key, { value: opts[key] }) } Object.defineProperty(this, 'connected', function () { return typeof this.socket !== 'undefined'; }) } Client.prototype.connect = function () { return this.socket = dgram.createSocket(this.type); } Client.prototype.send = function (protocol) { if (this.queue.length === 0) { return; } else { if (!this.connected) return; var tempQueue = this.queue.slice(0); this._writeToSocket(protocol, tempQueue, function (err) { if (err) { throw err; } else { this.queue.splice(0, tempQueue.length, tempQueue); } }); } } Client.prototype._writeToSocket = function (protocol, metrics, callback) { var formatted = protocol.format(metrics); this.socket.send(formatted, formatted.length, this.port, this.host, function (err, bytes) { callback(err); }); } Client.defaults = { host: '127.0.0.1', port: 2003, type: 'udp4' } module.exports = Client;
Implement the _writeToSocket and send methods on client
Implement the _writeToSocket and send methods on client
JavaScript
mit
MCProHosting/oxide
--- +++ @@ -2,15 +2,44 @@ dgram = require('dgram'); function Client (opts) { + this.queue = []; opts = _.defaults(_.pick(opts, Object.keys(Client.defaults)), Client.defaults); for (var key in opts) { Object.defineProperty(this, key, { value: opts[key] }) } + + Object.defineProperty(this, 'connected', function () { + return typeof this.socket !== 'undefined'; + }) } Client.prototype.connect = function () { return this.socket = dgram.createSocket(this.type); +} + +Client.prototype.send = function (protocol) { + if (this.queue.length === 0) { + return; + } else { + if (!this.connected) return; + + var tempQueue = this.queue.slice(0); + this._writeToSocket(protocol, tempQueue, function (err) { + if (err) { + throw err; + } else { + this.queue.splice(0, tempQueue.length, tempQueue); + } + }); + } +} + +Client.prototype._writeToSocket = function (protocol, metrics, callback) { + var formatted = protocol.format(metrics); + this.socket.send(formatted, formatted.length, this.port, this.host, function (err, bytes) { + callback(err); + }); } Client.defaults = {
b34f5b45348dcd6b9f7853825ab982f99c55888f
lib/src/getStats.js
lib/src/getStats.js
'use strict'; var through2 = require('through2'); var fs = require('graceful-fs'); function getStats() { return through2.obj(fetchStats); } function fetchStats(file, enc, cb) { fs.stat(file.path, function (err, stat) { if (stat) { file.stat = stat; } cb(err, file); }); } module.exports = getStats;
'use strict'; var through2 = require('through2'); var fs = require('graceful-fs'); function getStats() { return through2.obj(fetchStats); } function fetchStats(file, enc, cb) { fs.lstat(file.path, function (err, stat) { if (stat) { file.stat = stat; } cb(err, file); }); } module.exports = getStats;
Replace `fs.stat` call with `fs.lstat`
Update: Replace `fs.stat` call with `fs.lstat`
JavaScript
mit
erikkemperman/vinyl-fs,wearefractal/vinyl-fs,gulpjs/vinyl-fs
--- +++ @@ -8,7 +8,7 @@ } function fetchStats(file, enc, cb) { - fs.stat(file.path, function (err, stat) { + fs.lstat(file.path, function (err, stat) { if (stat) { file.stat = stat; }
d2906d68cd6a075d92fa6582918c8497e19c7133
app/assets/javascripts/comics_collection.js
app/assets/javascripts/comics_collection.js
(function() { window.collections.comics = Backbone.Collection.extend({ url: '/comics' }); })();
(function() { window.collections.comics = Backbone.Collection.extend({ url: '/' }); })();
Fix url to the root
Fix url to the root
JavaScript
mit
jboyens/comics,jboyens/comics
--- +++ @@ -1,5 +1,5 @@ (function() { window.collections.comics = Backbone.Collection.extend({ - url: '/comics' + url: '/' }); })();
169824100f88f017d1793b70a69198a8f9047fe3
katas/es6/language/destructuring/string.js
katas/es6/language/destructuring/string.js
// 11: destructuring - string // To do: make all tests pass, leave the assert lines unchanged! describe('destructuring also works on strings', () => { it('destructure every character', () => { const [a, b, c] = 'abc'; assert.deepEqual([a, b, c], ['a', 'b', 'c']); }); it('missing characters are undefined', () => { const [a, b, c] = 'ab'; assert.equal(c, void 0); }); it('unicode character work too', () => { const [a, space, coffee] = 'a ☕'; assert.equal(coffee, '\u{2615}'); }); });
// 11: destructuring - string // To do: make all tests pass, leave the assert lines unchanged! describe('destructuring also works on strings', () => { it('destructure every character', () => { let a, b, c = 'abc'; assert.deepEqual([a, b, c], ['a', 'b', 'c']); }); it('missing characters are undefined', () => { const [a, c] = 'ab'; assert.equal(c, void 0); }); it('unicode character work too', () => { const [space, coffee] = 'a ☕'; assert.equal(coffee, '\u{2615}'); }); });
Make it worth a kata, make it fail :).
Make it worth a kata, make it fail :).
JavaScript
mit
Semigradsky/katas,cmisenas/katas,JonathanPrince/katas,JonathanPrince/katas,JonathanPrince/katas,cmisenas/katas,tddbin/katas,ehpc/katas,Semigradsky/katas,ehpc/katas,rafaelrocha/katas,Semigradsky/katas,tddbin/katas,tddbin/katas,rafaelrocha/katas,cmisenas/katas,rafaelrocha/katas,ehpc/katas
--- +++ @@ -5,17 +5,17 @@ it('destructure every character', () => { - const [a, b, c] = 'abc'; + let a, b, c = 'abc'; assert.deepEqual([a, b, c], ['a', 'b', 'c']); }); it('missing characters are undefined', () => { - const [a, b, c] = 'ab'; + const [a, c] = 'ab'; assert.equal(c, void 0); }); it('unicode character work too', () => { - const [a, space, coffee] = 'a ☕'; + const [space, coffee] = 'a ☕'; assert.equal(coffee, '\u{2615}'); });
433f26766615c97744acda90d6007bb776d9c88c
assets/js/modules/index.js
assets/js/modules/index.js
/** * All modules. * * Site Kit by Google, Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Internal dependencies */ import './adsense'; import './analytics/index.legacy'; import './optimize'; import './pagespeed-insights'; import './pagespeed-insights/index.legacy'; import './search-console'; import './search-console/index.legacy'; import './tagmanager';
/** * All modules. * * Site Kit by Google, Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Internal dependencies */ import './adsense'; import './analytics/index.legacy'; import './optimize'; import './pagespeed-insights/index.legacy'; import './search-console/index.legacy'; import './tagmanager';
Fix incorrect inclusion (old modules asset should only load legacy files after migration).
Fix incorrect inclusion (old modules asset should only load legacy files after migration).
JavaScript
apache-2.0
google/site-kit-wp,google/site-kit-wp,google/site-kit-wp,google/site-kit-wp
--- +++ @@ -22,8 +22,6 @@ import './adsense'; import './analytics/index.legacy'; import './optimize'; -import './pagespeed-insights'; import './pagespeed-insights/index.legacy'; -import './search-console'; import './search-console/index.legacy'; import './tagmanager';
d3614fd4f03f22657171ffcd494a4a83df663cdb
atmessager/lib/telegram.js
atmessager/lib/telegram.js
var logger = require('log4js').getLogger('APP_LOG'); var request = require('request'); function sendMessage(config, receiver, message, botname, callback) { var chat_id = config.receivers[receiver].chat_id; var token = config.bots[botname].token; request.post({ url: 'https://api.telegram.org/bot' + token + '/sendMessage', form: { chat_id: chat_id, text: message } }, function(err, res, body) { body = JSON.parse(body); if (err) { logger.error(err); callback(err, null); return; } if (body['error_code']) { logger.error(body['description']); err = { error: body['error_code'], description: body['description'] }; callback(err, null); return; } logger.info('Message sent!'); var successMessage = { receiver: receiver, botname: botname, message: message, sendTime: new Date() }; callback(null, successMessage); }); } module.exports = { 'sendMessage': sendMessage };
var logger = require('log4js').getLogger('APP_LOG'); var request = require('request'); function sendMessage(config, receiver, message, botname, callback) { var chat_id = config.receivers[receiver].chat_id; var token = config.bots[botname].token; request.post({ url: 'https://api.telegram.org/bot' + token + '/sendMessage', form: { chat_id: chat_id, text: message } }, function(err, res, body) { body = JSON.parse(body); if (err) { logger.error(err); callback(err, null); return; } if (body['error_code']) { logger.error(body['description']); err = { error_code: body['error_code'], description: body['description'] }; callback(err, null); return; } logger.info('Message sent!'); var successMessage = { receiver: receiver, botname: botname, message: message, sendTime: new Date() }; callback(null, successMessage); }); } module.exports = { 'sendMessage': sendMessage };
Change "error" to "error_code" in error object
Change "error" to "error_code" in error object
JavaScript
apache-2.0
dollars0427/ATMessager,dollars0427/ATMessager
--- +++ @@ -28,7 +28,7 @@ logger.error(body['description']); err = { - error: body['error_code'], + error_code: body['error_code'], description: body['description'] };
46af09e348b688341a2b08a35448df536cbedfac
app/assets/javascripts/foundation_extras.js
app/assets/javascripts/foundation_extras.js
(function() { "use strict"; App.FoundationExtras = { initialize: function() { $(document).foundation(); } }; }).call(this);
(function() { "use strict"; App.FoundationExtras = { initialize: function() { $(document).foundation(); }, destroy: function() { if ($(".sticky").length > 0) { $(".sticky").foundation("_destroy"); } } }; $(document).on("turbolinks:before-visit", App.FoundationExtras.destroy); }).call(this);
Destroy Sticky elements before leaving the page
Destroy Sticky elements before leaving the page When Foundation initializes a page that has any sticky element, it loads a window scroll listener into window object to handle the sticky element positioning when scrolling. This works great until user moves to a page without sticky elements and the window listeners remain attached to the window object on this new page too when there is no need to run the scrollListener and there is no sticky elements so the window scroll listener cannot find the sticky object on that page a lot of errors are thrown when user scrolls. With this approach we are destroying sticky elements before leaving the page which also remove the Sticky scrollListener from the window object. I do not know how to write a test to demonstrate this fix, but at least there is some steps to reproduce this behavior: 0. Undo this commit 1. Go to any proposal page 2. Click on any link (with Turbolinks enabled) 3. Scroll the page 4. Check the console log. Yo will find as error occurrences as pixels you scrolled.
JavaScript
agpl-3.0
consul/consul,consul/consul,consul/consul,consul/consul,consul/consul
--- +++ @@ -3,6 +3,13 @@ App.FoundationExtras = { initialize: function() { $(document).foundation(); + }, + destroy: function() { + if ($(".sticky").length > 0) { + $(".sticky").foundation("_destroy"); + } } }; + + $(document).on("turbolinks:before-visit", App.FoundationExtras.destroy); }).call(this);
413595ce25477495c7891288eca5c1c249ec83f5
src/Libraries/ReactNative/I18nManager.js
src/Libraries/ReactNative/I18nManager.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @providesModule I18nManager * @flow * @format */ 'use strict'; type I18nManagerStatus = { isRTL: boolean, doLeftAndRightSwapInRTL: boolean, allowRTL: (allowRTL: boolean) => {}, forceRTL: (forceRTL: boolean) => {}, swapLeftAndRightInRTL: (flipStyles: boolean) => {}, }; const I18nManager: I18nManagerStatus = { isRTL: false, doLeftAndRightSwapInRTL: true, allowRTL: () => {}, forceRTL: () => {}, swapLeftAndRightInRTL: () => {}, }; module.exports = I18nManager;
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow * @format */ 'use strict'; type I18nManagerStatus = { isRTL: boolean, doLeftAndRightSwapInRTL: boolean, allowRTL: (allowRTL: boolean) => {}, forceRTL: (forceRTL: boolean) => {}, swapLeftAndRightInRTL: (flipStyles: boolean) => {}, }; const I18nManager: I18nManagerStatus = { isRTL: false, doLeftAndRightSwapInRTL: true, allowRTL: () => {}, forceRTL: () => {}, swapLeftAndRightInRTL: () => {}, }; module.exports = I18nManager;
Remove providesModule that can lead to Haste dups.
Remove providesModule that can lead to Haste dups.
JavaScript
mit
Root-App/react-native-mock-render
--- +++ @@ -4,7 +4,6 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * - * @providesModule I18nManager * @flow * @format */
292c0376e79156ab1db3cc4417715aa18f8e26ad
src/state/initialState.js
src/state/initialState.js
import Immutable from 'immutable'; import { parseGrounds, parseEntities } from 'state/utils/parseLevel'; import * as level1 from 'state/levels/level-01'; export const initialState = Immutable.fromJS({ time: 120, player: { row: 49, col: 22 }, tapes: [], grounds: parseGrounds(level1.grounds), entities: parseEntities(level1.entities), powerups: [], hasWon: false });
import Immutable from 'immutable'; import { parseGrounds, parseEntities } from 'state/utils/parseLevel'; import * as level1 from 'state/levels/level-01'; export const initialState = Immutable.fromJS({ time: 120, player: { row: 49, col: 22, direction: 'left' }, tapes: [], grounds: parseGrounds(level1.grounds), entities: parseEntities(level1.entities), powerups: [], hasWon: false });
Add player direction to initial state
Add player direction to initial state
JavaScript
mit
mattesja/mygame,mattesja/mygame,stevenhauser/i-have-to-return-some-videotapes,stevenhauser/i-have-to-return-some-videotapes
--- +++ @@ -11,7 +11,8 @@ time: 120, player: { row: 49, - col: 22 + col: 22, + direction: 'left' }, tapes: [], grounds: parseGrounds(level1.grounds),
4f751563c76bcea37fdf3e0623a037670476077b
plugins/InfiniteScroll/infinitescroll.js
plugins/InfiniteScroll/infinitescroll.js
jQuery(document).ready(function($){ $('notices_primary').infinitescroll({ nextSelector : "li.nav_next a", loadingImg : $('address .url')[0].href+'plugins/InfiniteScroll/ajax-loader.gif', text : "<em>Loading the next set of posts...</em>", donetext : "<em>Congratulations, you\'ve reached the end of the Internet.</em>", navSelector : "div.pagination", contentSelector : "#notices_primary", itemSelector : "ol.notices" }); });
jQuery(document).ready(function($){ $('notices_primary').infinitescroll({ nextSelector : "li.nav_next a", loadingImg : $('address .url')[0].href+'plugins/InfiniteScroll/ajax-loader.gif', text : "<em>Loading the next set of posts...</em>", donetext : "<em>Congratulations, you\'ve reached the end of the Internet.</em>", navSelector : "div.pagination", contentSelector : "#notices_primary", itemSelector : "ol.notices" },function(){ NoticeAttachments(); }); });
Make notice attachment lightbox work after an infinite scroll happens
Make notice attachment lightbox work after an infinite scroll happens
JavaScript
agpl-3.0
bankonme/gnu-social,zh/statusnet,UngPirat/freesocial,foocorp/gnu-social,brion/StatusNet,faulteh/gnu-social,furtherfield/gnu-social,xebia/statusnet-oauth2,bankonme/gnu-social,csarven/statusnet,charnimda/lgbtpzn-social,xebia/statusnet-oauth2,faulteh/gnu-social,xebia/statusnet-oauth2,zcopley/zcopleys-statusnet-clone,charlycoste/StatusNet,d3vgru/StatusNet,zh/statusnet,znarf/statusnet-ladistribution,gnusocial/mainline,sikevux/bsk-social,charnimda/lgbtpzn-social,foocorp/gnu-social,studio666/gnu-social,zcopley/StatusNet,brion/StatusNet,csarven/statusnet,csarven/statusnet,zcopley/StatusNet,charlycoste/StatusNet,znarf/statusnet-ladistribution,faulteh/gnu-social,foocorp/gnu-social,shashi/StatusNet,eXcomm/gnu-social,chimo/social,eXcomm/gnu-social,znarf/statusnet-ladistribution,minmb/statusnet,zcopley/StatusNet,csarven/statusnet,studio666/gnu-social,eXcomm/gnu-social,charnimda/lgbtpzn-social,bankonme/gnu-social,shashi/StatusNet,Piratas/tortuga,Piratas/tortuga,minmb/statusnet,d3vgru/StatusNet,eXcomm/gnu-social,d3vgru/StatusNet,studio666/gnu-social,bankonme/gnu-social,chimo/social,Piratas/tortuga,faulteh/gnu-social,sikevux/bsk-social,zh/statusnet,studio666/gnu-social,Piratas/tortuga,furtherfield/gnu-social,minmb/statusnet,UngPirat/freesocial,furtherfield/gnu-social,brion/StatusNet,furtherfield/gnu-social,zcopley/zcopleys-statusnet-clone,sikevux/bsk-social,gnusocial/mainline,gnusocial/mainline,zcopley/zcopleys-statusnet-clone,UngPirat/freesocial,chimo/social,gnusocial/mainline,shashi/StatusNet,charlycoste/StatusNet,sikevux/bsk-social
--- +++ @@ -7,6 +7,8 @@ navSelector : "div.pagination", contentSelector : "#notices_primary", itemSelector : "ol.notices" + },function(){ + NoticeAttachments(); }); });
6fb985cb7a1e1f6edeaf91829eb2e7b77de9806f
controller.js
controller.js
var Controller = function(shape) { this.gameBoard = new tetrisBoard(); this.gameView = new browserView({gameBoard: this.gameBoard}); } Controller.prototype.startGame = function() { this.gameBoard.blit(); this.gameView.animate(); this.gameBoard.cycleDropBlock(); }
var Controller = function(shape) { this.gameBoard = new TetrisBoard(); this.gameView = new BrowserView({gameBoard: this.gameBoard}); } Controller.prototype.startGame = function() { this.gameBoard.blit(); this.gameView.animate(); this.gameBoard.cycleDropBlock(); }
Correct class constructor calls to be capitalized
Correct class constructor calls to be capitalized
JavaScript
mit
RoyTuesday/tetrelementis,peternatewood/tetrelementis,peternatewood/tetrelementis,RoyTuesday/tetrelementis
--- +++ @@ -1,6 +1,6 @@ var Controller = function(shape) { - this.gameBoard = new tetrisBoard(); - this.gameView = new browserView({gameBoard: this.gameBoard}); + this.gameBoard = new TetrisBoard(); + this.gameView = new BrowserView({gameBoard: this.gameBoard}); } Controller.prototype.startGame = function() { this.gameBoard.blit();
dcb19ef5aaa9cecb689bae83f7a2923d7e61c4d8
src/typeStrategies/url.js
src/typeStrategies/url.js
const url = { _regex: { default: /^(?:https?:\/\/)?[^\s\/\.]+(?:\.[a-z]{2,})+(?:\/\S*)?$/i }, default: context => { if (context.value === null || context.value && !context.value.toString().match(url._regex.default)) { context.fail('Value must be a valid URL') } } } export default url
const url = { _regex: { default: /^(?:https?:\/\/)?[^\s\/\.]+(?:\.[a-z0-9]{2,})+(?:\/\S*)?$/i }, default: context => { if (context.value === null || context.value && !context.value.toString().match(url._regex.default)) { context.fail('Value must be a valid URL') } } } export default url
Fix regex to allow numbers in domains
Fix regex to allow numbers in domains
JavaScript
mit
TechnologyAdvice/obey
--- +++ @@ -1,6 +1,6 @@ const url = { _regex: { - default: /^(?:https?:\/\/)?[^\s\/\.]+(?:\.[a-z]{2,})+(?:\/\S*)?$/i + default: /^(?:https?:\/\/)?[^\s\/\.]+(?:\.[a-z0-9]{2,})+(?:\/\S*)?$/i }, default: context => { if (context.value === null || context.value && !context.value.toString().match(url._regex.default)) {
007eff6d9b3fba33af9910ad66c1692e70b99d75
test/rdfa.js
test/rdfa.js
var jQuery = require('jquery'); var VIE = require('../vie.js'); // Until https://github.com/tmpvar/jsdom/issues/issue/81 is fixed VIE.RDFa.predicateSelector = '[property]'; exports['test inheriting subject'] = function(test) { var html = jQuery('<div about="http://dbpedia.org/resource/Albert_Einstein"><span property="foaf:name">Albert Einstein<span><span property="dbp:dateOfBirth" datatype="xsd:date">1879-03-14</span><div rel="dbp:birthPlace" resource="http://dbpedia.org/resource/Germany" /><span about="http://dbpedia.org/resource/Germany" property="dbp:conventionalLongName">Federal Republic of Germany</span></div>'); var entities = VIE.RDFa.readEntities(html); test.equal(entities.length, 2, "This RDFa defines two entities but they don't get parsed to JSON"); var entities = VIE.RDFaEntities.getInstances(html); test.equal(entities.length, 2, "This RDFa defines two entities but they don't get to Backbone"); test.done(); };
var jQuery = require('jquery'); var VIE = require('../vie.js'); // Until https://github.com/tmpvar/jsdom/issues/issue/81 is fixed VIE.RDFa.predicateSelector = '[property]'; exports['test inheriting subject'] = function(test) { var html = jQuery('<div about="http://dbpedia.org/resource/Albert_Einstein"><span property="foaf:name">Albert Einstein</span><span property="dbp:dateOfBirth" datatype="xsd:date">1879-03-14</span><div rel="dbp:birthPlace" resource="http://dbpedia.org/resource/Germany" /><span about="http://dbpedia.org/resource/Germany" property="dbp:conventionalLongName">Federal Republic of Germany</span></div>'); var jsonldEntities = VIE.RDFa.readEntities(html); test.equal(jsonldEntities.length, 2, "This RDFa defines two entities but they don't get parsed to JSON"); test.equal(jsonldEntities[1]['foaf:name'], 'Albert Einstein'); test.equal(jsonldEntities[0]['dbp:conventionalLongName'], 'Federal Republic of Germany'); var backboneEntities = VIE.RDFaEntities.getInstances(html); test.equal(backboneEntities.length, 2, "This RDFa defines two entities but they don't get to Backbone"); test.equal(backboneEntities[1].get('foaf:name'), 'Albert Einstein'); test.equal(backboneEntities[0].get('dbp:conventionalLongName'), 'Federal Republic of Germany'); test.done(); };
Test getting properties as well
Test getting properties as well
JavaScript
mit
bergie/VIE,bergie/VIE
--- +++ @@ -5,13 +5,19 @@ VIE.RDFa.predicateSelector = '[property]'; exports['test inheriting subject'] = function(test) { - var html = jQuery('<div about="http://dbpedia.org/resource/Albert_Einstein"><span property="foaf:name">Albert Einstein<span><span property="dbp:dateOfBirth" datatype="xsd:date">1879-03-14</span><div rel="dbp:birthPlace" resource="http://dbpedia.org/resource/Germany" /><span about="http://dbpedia.org/resource/Germany" property="dbp:conventionalLongName">Federal Republic of Germany</span></div>'); + var html = jQuery('<div about="http://dbpedia.org/resource/Albert_Einstein"><span property="foaf:name">Albert Einstein</span><span property="dbp:dateOfBirth" datatype="xsd:date">1879-03-14</span><div rel="dbp:birthPlace" resource="http://dbpedia.org/resource/Germany" /><span about="http://dbpedia.org/resource/Germany" property="dbp:conventionalLongName">Federal Republic of Germany</span></div>'); - var entities = VIE.RDFa.readEntities(html); - test.equal(entities.length, 2, "This RDFa defines two entities but they don't get parsed to JSON"); + var jsonldEntities = VIE.RDFa.readEntities(html); + test.equal(jsonldEntities.length, 2, "This RDFa defines two entities but they don't get parsed to JSON"); - var entities = VIE.RDFaEntities.getInstances(html); - test.equal(entities.length, 2, "This RDFa defines two entities but they don't get to Backbone"); + test.equal(jsonldEntities[1]['foaf:name'], 'Albert Einstein'); + test.equal(jsonldEntities[0]['dbp:conventionalLongName'], 'Federal Republic of Germany'); + + var backboneEntities = VIE.RDFaEntities.getInstances(html); + test.equal(backboneEntities.length, 2, "This RDFa defines two entities but they don't get to Backbone"); + + test.equal(backboneEntities[1].get('foaf:name'), 'Albert Einstein'); + test.equal(backboneEntities[0].get('dbp:conventionalLongName'), 'Federal Republic of Germany'); test.done(); };
bfb84e6a4d4cf8e710d3e54075e2f3da0651d63d
server/methods/templates/deleteTemplate.js
server/methods/templates/deleteTemplate.js
Meteor.methods({ 'deleteTemplate'(templateId) { console.log("### DELETING TEMPLATE ###"); check(templateId, Match.Any); Template.remove(templateId); console.log(JSON.stringify({ resource: "template", action: "delete", details: { id: templateId, }, requester: Meteor.userId() })); } //End deleteTemplate method });
Meteor.methods({ 'deleteTemplate'(templateId) { console.log("### DELETING TEMPLATE ###"); check(templateId, Match.Any); const templateObject = Template.findOne(templateId); if (templateObject.owner != Meteor.userId()) { throw new Meteor.Error(401, "This user is not authorized to complete this request"); } else { Template.remove(templateId); } console.log(JSON.stringify({ resource: "template", action: "delete", details: { id: templateId, }, requester: Meteor.userId() })); } //End deleteTemplate method });
Support for Shared Templates (Beta) - Only allow deletion if current user is Owner
Support for Shared Templates (Beta) - Only allow deletion if current user is Owner
JavaScript
mit
kmcroft13/cloud-templates,kmcroft13/box-templates,kmcroft13/cloud-templates,kmcroft13/box-templates
--- +++ @@ -3,8 +3,13 @@ 'deleteTemplate'(templateId) { console.log("### DELETING TEMPLATE ###"); check(templateId, Match.Any); - - Template.remove(templateId); + const templateObject = Template.findOne(templateId); + + if (templateObject.owner != Meteor.userId()) { + throw new Meteor.Error(401, "This user is not authorized to complete this request"); + } else { + Template.remove(templateId); + } console.log(JSON.stringify({ resource: "template",
9f0fa5056dcf0ea3d3f9db3f1afeb58caa340d77
src/components/Members/MembersPreview.js
src/components/Members/MembersPreview.js
import React, { Component, PropTypes } from 'react'; import { Link } from 'react-router'; class MembersPreview extends Component { render() { const {displayName, searchImg, intro, slug} = this.props; return ( <div className="col-xs-12 col-sm-4 col-md-3"> <div className="thumbnail" style={{ height: '300px', background: 'rgba(243,243,243,1)', border: '0', borderRadius: '0', padding: '20px 10px', }}> <div style={{ maxHeight: '95%', overflowY: 'auto', }}> { searchImg && <img src={searchImg.url} style={{ maxHeight: '125px', margin: 'auto', display: 'block', }}/> } <div className="caption"> <h4 className="nomargin" style={{ textAlign: 'center', }}> <Link to={ `/members/${slug}` }>{displayName}</Link> </h4> <p dangerouslySetInnerHTML={{ __html: intro }} /> </div> </div> </div> </div> ); } } MembersPreview.propTypes = { displayName: PropTypes.string.isRequired, searchImg: PropTypes.shape({ url: PropTypes.string.isRequired, height: PropTypes.number, width: PropTypes.number, }), intro: PropTypes.string, slug: PropTypes.string.isRequired, usState: PropTypes.string, }; export default MembersPreview;
import React, { Component, PropTypes } from 'react'; import { Link } from 'react-router'; class MembersPreview extends Component { render() { const {displayName, searchImg, intro, slug} = this.props; return ( <div className="col-xs-12 col-sm-4 col-md-3"> <div className="thumbnail" style={{ height: '300px', background: 'rgba(243,243,243,1)', border: '0', borderRadius: '0', padding: '20px 10px', }}> <div style={{ maxHeight: '95%', overflowY: 'auto', }}> { searchImg && <Link to={ `/members/${slug}` }> <img src={searchImg.url} style={{ maxHeight: '125px', margin: 'auto', display: 'block', }} /> </Link> } <div className="caption"> <h4 className="nomargin" style={{ textAlign: 'center', }}> <Link to={ `/members/${slug}` }>{displayName}</Link> </h4> <p dangerouslySetInnerHTML={{ __html: intro }} /> </div> </div> </div> </div> ); } } MembersPreview.propTypes = { displayName: PropTypes.string.isRequired, searchImg: PropTypes.shape({ url: PropTypes.string.isRequired, height: PropTypes.number, width: PropTypes.number, }), intro: PropTypes.string, slug: PropTypes.string.isRequired, usState: PropTypes.string, }; export default MembersPreview;
Make images clickable on members search
Make images clickable on members search
JavaScript
cc0-1.0
cape-io/acf-client,cape-io/acf-client
--- +++ @@ -21,11 +21,16 @@ }}> { searchImg && - <img src={searchImg.url} style={{ - maxHeight: '125px', - margin: 'auto', - display: 'block', - }}/> + <Link to={ `/members/${slug}` }> + <img + src={searchImg.url} + style={{ + maxHeight: '125px', + margin: 'auto', + display: 'block', + }} + /> + </Link> } <div className="caption"> <h4 className="nomargin" style={{
ffc5324d21065acff2cff65277d208c86ffa6809
media/lib/routes.js
media/lib/routes.js
Router.route('/media', {name: 'mediaMenu'}); Router.route('/media/static/:filepath*', function () { if (settings.findOne({key: 'mediainternalserver'}).value) { // var mime = Npm.require('mime'); var fs = Npm.require('fs'); var filepath = settings.findOne({key: 'mediadir'}).value + '/' + this.params.filepath; try { var stats = fs.statSync(filepath); } catch (e) { this.next(); return; } if (!stats.isFile()) { this.next(); return; } var headers = { 'Cache-Control': 'max-age=2592000' // Cache for 30 days. }; this.response.writeHead(200, headers); var stream = fs.createReadStream(filepath); return stream.pipe(this.response); } }, {where: 'server'});
Router.route('/media', {name: 'mediaMenu'}); Router.route('/media/static/:filepath*', function () { if (settings.findOne({key: 'mediainternalserver'}).value) { var fs = Npm.require('fs'); var filepath = settings.findOne({key: 'mediadir'}).value + '/' + this.params.filepath; try { var stats = fs.statSync(filepath); } catch (e) { this.next(); return; } if (!stats.isFile()) { this.next(); return; } var headers = { 'Cache-Control': 'max-age=2592000', // Cache for 30 days. 'Content-Length': stats.size }; this.response.writeHead(200, headers); var stream = fs.createReadStream(filepath); return stream.pipe(this.response); } }, {where: 'server'});
Set static file Content-Length header
Set static file Content-Length header
JavaScript
mit
cedarsuite/cedarserver,monty5811/cedarserver,monty5811/cedarserver,cedarsuite/cedarserver
--- +++ @@ -2,7 +2,6 @@ Router.route('/media/static/:filepath*', function () { if (settings.findOne({key: 'mediainternalserver'}).value) { - // var mime = Npm.require('mime'); var fs = Npm.require('fs'); var filepath = settings.findOne({key: 'mediadir'}).value + '/' + this.params.filepath; @@ -20,7 +19,8 @@ } var headers = { - 'Cache-Control': 'max-age=2592000' // Cache for 30 days. + 'Cache-Control': 'max-age=2592000', // Cache for 30 days. + 'Content-Length': stats.size }; this.response.writeHead(200, headers);
58bd59fa0829a48bf07f6a39d106514de1d43aad
grunt/karma.js
grunt/karma.js
module.exports = { options: { configFile: 'karma-unit.conf.js' }, // Sinle run unit: { singleRun: true, preprocessors: { 'src/**/*.js': ['coverage'] }, reporters: ['dots', 'coverage'], coverageReporter: { type : 'text-summary' }, }, // Create coverage report coverage: { singleRun: true, preprocessors: { 'src/**/*.js': ['coverage'] }, reporters: ['dots', 'coverage'], coverageReporter: { type : 'html', dir: 'coverage/' }, }, // TDD tdd: {} };
module.exports = { options: { configFile: 'karma-unit.conf.js' }, // Sinle run unit: { singleRun: true, preprocessors: { 'src/**/*.js': ['coverage'] }, reporters: ['dots', 'coverage'], coverageReporter: { type : 'text-summary' }, }, // Create coverage report coverage: { singleRun: true, preprocessors: { '<%= dir.src %>/**/*.js': ['coverage'] }, reporters: ['dots', 'coverage'], coverageReporter: { type : 'html', dir: '<%= dir.coverage %>/' }, }, // TDD tdd: {} };
Use dir set bei grunt.config.
refactor(grunt): Use dir set bei grunt.config.
JavaScript
mit
sebald/ed,mps-gmbh/ed,mps-gmbh/ed,sebald/ed,sebald/ed,mps-gmbh/ed
--- +++ @@ -19,12 +19,12 @@ coverage: { singleRun: true, preprocessors: { - 'src/**/*.js': ['coverage'] + '<%= dir.src %>/**/*.js': ['coverage'] }, reporters: ['dots', 'coverage'], coverageReporter: { type : 'html', - dir: 'coverage/' + dir: '<%= dir.coverage %>/' }, },
77d27e84389b43548b32053ab08efc79bdfe2484
node/serveAssets.js
node/serveAssets.js
const {readFileSync} = require('fs') const {resolve} = require('path') function createRequestDecorator (stats) { return (req, res, next) => { res.locals = res.locals || Object.create(null) res.locals.webpackClientStats = stats next && next() } } function serveAssets (router, options = {}) { if (typeof options === 'string') { options = {outputPath: options} } if (typeof arguments[2] === 'function') { options.requestDecorator = arguments[2] } const { hideStats = true, outputPath, publicPath = '/', statsFilename = 'stats.json', serveStatic, requestDecorator = createRequestDecorator } = options const statsPath = resolve(outputPath, statsFilename) const stats = JSON.parse(readFileSync(statsPath, 'utf8')) const decorateRequest = requestDecorator(stats) const serve = serveStatic(outputPath) if (hideStats) { router.use(publicPath + statsFilename, (req, res) => { res.sendStatus(403) }) } router.use(publicPath, serve) router.use(decorateRequest) } exports = module.exports = serveAssets.bind() exports.createRequestDecorator = createRequestDecorator exports.serveAssets = serveAssets
const {readFileSync} = require('fs') const {resolve} = require('path') function createRequestDecorator (stats) { return (req, res, next) => { res.locals = res.locals || Object.create(null) res.locals.webpackClientStats = stats next && next() } } function serveAssets (router, options = {}) { if (typeof options === 'string') { options = {outputPath: options} } if (typeof arguments[2] === 'function') { options.requestDecorator = arguments[2] } const { hideSourceMaps = true, hideStats = true, outputPath, publicPath = '/', statsFilename = 'stats.json', serveStatic, requestDecorator = createRequestDecorator } = options const statsPath = resolve(outputPath, statsFilename) const stats = JSON.parse(readFileSync(statsPath, 'utf8')) const decorateRequest = requestDecorator(stats) const serve = serveStatic(outputPath) if (hideSourceMaps) { router.use(publicPath, (req, res, next) => { if (req.url.endsWith('.map')) { return res.sendStatus(403) } next() }) } if (hideStats) { router.use(publicPath + statsFilename, (req, res) => { res.sendStatus(403) }) } router.use(publicPath, serve) router.use(decorateRequest) } exports = module.exports = serveAssets.bind() exports.createRequestDecorator = createRequestDecorator exports.serveAssets = serveAssets
Add option hideSourceMaps to hide source maps
Add option hideSourceMaps to hide source maps
JavaScript
mit
enten/udk,enten/udk
--- +++ @@ -20,6 +20,7 @@ } const { + hideSourceMaps = true, hideStats = true, outputPath, publicPath = '/', @@ -34,6 +35,16 @@ const decorateRequest = requestDecorator(stats) const serve = serveStatic(outputPath) + if (hideSourceMaps) { + router.use(publicPath, (req, res, next) => { + if (req.url.endsWith('.map')) { + return res.sendStatus(403) + } + + next() + }) + } + if (hideStats) { router.use(publicPath + statsFilename, (req, res) => { res.sendStatus(403)
6366bdb1eb597098bf48a9722413391cb3e48be4
client/js/directives/fancy-box-directive.js
client/js/directives/fancy-box-directive.js
"use strict"; angular.module("hikeio"). directive("fancybox", function() { return { link: function (scope, element, attrs) { scope.$on("$routeChangeStart", function () { $.fancybox.close(); }); $(element).find(attrs.fancybox).fancybox({ padding: 10, nextEffect : "none", prevEffect : "none", closeEffect : "none", closeBtn : true, arrows : false, keys : true, nextClick : true }); } }; });
"use strict"; angular.module("hikeio"). directive("fancybox", function() { return { link: function (scope, element, attrs) { scope.$on("$routeChangeStart", function () { $.fancybox.close(); }); $(element).find(attrs.fancybox).fancybox({ padding: 2, nextEffect : "none", prevEffect : "none", closeEffect : "none", closeBtn : true, arrows : false, keys : true, nextClick : true }); } }; });
Reduce padding on fancybox images.
Reduce padding on fancybox images.
JavaScript
mit
zaknelson/hike.io,zaknelson/hike.io,zaknelson/hike.io,zaknelson/hike.io
--- +++ @@ -8,7 +8,7 @@ $.fancybox.close(); }); $(element).find(attrs.fancybox).fancybox({ - padding: 10, + padding: 2, nextEffect : "none", prevEffect : "none", closeEffect : "none",
8405b28f9fa1d2383fdd8d74f84e50465e212253
coroutine.js
coroutine.js
// Coroutine function that returns a promise that resolves when the coroutine // is finished. Accepts a generator function, and assumes that everything // yielded from the generator function is a promise. module.exports = function coroutine(generatorFunction) { let gen = generatorFunction() return new Promise(resolve => { // Handle every single value yielded by the generator function. function step(value) { let result = gen.next(value) if (result.done) { // Generator is done, so handle its return value. resolve(result.value) } else { // Generator is not done, so result.value is a promise. let promise = result.value // When the promise is done, run this function again. promise.then(newValue => step(newValue)) } } step(undefined) }) }
// Coroutine function that returns a promise that resolves when the coroutine // is finished. Accepts a generator function, and assumes that everything // yielded from the generator function is a promise. module.exports = function coroutine(generatorFunction) { let gen = generatorFunction() return new Promise(resolve => { // Handle every single result yielded by the generator function. function next(result) { if (result.done) { // Generator is done, so resolve to its return value. resolve(result.value) } else { // Generator is not done, so result.value is a promise. let promise = result.value // When the promise is done, run this function again. promise.then(newValue => { let newResult = gen.next(newValue) next(newResult) }) } } next(gen.next()) }) }
Refactor so that next() takes the return value of gen.next()
Refactor so that next() takes the return value of gen.next()
JavaScript
apache-2.0
feihong/node-examples,feihong/node-examples
--- +++ @@ -4,20 +4,24 @@ // yielded from the generator function is a promise. module.exports = function coroutine(generatorFunction) { let gen = generatorFunction() + return new Promise(resolve => { - // Handle every single value yielded by the generator function. - function step(value) { - let result = gen.next(value) + // Handle every single result yielded by the generator function. + function next(result) { if (result.done) { - // Generator is done, so handle its return value. + // Generator is done, so resolve to its return value. resolve(result.value) } else { // Generator is not done, so result.value is a promise. let promise = result.value // When the promise is done, run this function again. - promise.then(newValue => step(newValue)) + promise.then(newValue => { + let newResult = gen.next(newValue) + next(newResult) + }) } } - step(undefined) + + next(gen.next()) }) }
c28ff2df33608af767cc8056540fd153c5ef2c63
jest.config.js
jest.config.js
module.exports = { testURL: 'http://localhost/', moduleFileExtensions: ['js', 'jsx', 'json', 'styl'], setupFiles: ['<rootDir>/test/jestLib/setup.js'], moduleDirectories: ['src', 'node_modules'], moduleNameMapper: { '^redux-cozy-client$': '<rootDir>/src/lib/redux-cozy-client', '^cozy-doctypes$': 'cozy-logger/dist/index.js', '\\.(png|gif|jpe?g|svg)$': '<rootDir>/test/__mocks__/fileMock.js', // identity-obj-proxy module is installed by cozy-scripts styles: 'identity-obj-proxy', '\.styl$': 'identity-obj-proxy' }, transformIgnorePatterns: ['node_modules/(?!cozy-ui|cozy-harvest-lib)'], globals: { __ALLOW_HTTP__: false, __TARGET__: 'browser', __SENTRY_TOKEN__: 'token', cozy: {} } }
module.exports = { testURL: 'http://localhost/', moduleFileExtensions: ['js', 'jsx', 'json', 'styl'], setupFiles: ['<rootDir>/test/jestLib/setup.js'], moduleDirectories: ['src', 'node_modules'], moduleNameMapper: { '^redux-cozy-client$': '<rootDir>/src/lib/redux-cozy-client', '^cozy-doctypes$': 'cozy-logger/dist/index.js', '\\.(png|gif|jpe?g|svg)$': '<rootDir>/test/__mocks__/fileMock.js', // identity-obj-proxy module is installed by cozy-scripts styles: 'identity-obj-proxy', '.styl$': 'identity-obj-proxy', '^cozy-client$': 'cozy-client/dist/index' }, transformIgnorePatterns: ['node_modules/(?!cozy-ui|cozy-harvest-lib)'], globals: { __ALLOW_HTTP__: false, __TARGET__: 'browser', __SENTRY_TOKEN__: 'token', cozy: {} } }
Add the alias for jest
fix(tests): Add the alias for jest
JavaScript
agpl-3.0
cozy/cozy-home,cozy/cozy-home,cozy/cozy-home
--- +++ @@ -9,7 +9,8 @@ '\\.(png|gif|jpe?g|svg)$': '<rootDir>/test/__mocks__/fileMock.js', // identity-obj-proxy module is installed by cozy-scripts styles: 'identity-obj-proxy', - '\.styl$': 'identity-obj-proxy' + '.styl$': 'identity-obj-proxy', + '^cozy-client$': 'cozy-client/dist/index' }, transformIgnorePatterns: ['node_modules/(?!cozy-ui|cozy-harvest-lib)'], globals: {
828b9def79d0a5c39a925051b0b958c2b452c228
Test.js
Test.js
// For conditions of distribution and use, see copyright notice in LICENSE var client = new WebSocketClient(); var scene = new Scene(); var syncManager = new SyncManager(client, scene); var loginData = {"name": "Test User"}; syncManager.logDebug = true; client.connect("localhost", 2345, loginData); /* setTimeout(printEntityNames, 2000); function printEntityNames() { for (var entityId in scene.entities) { var entity = scene.entities[entityId]; console.log(entity.name); } } */
// For conditions of distribution and use, see copyright notice in LICENSE var client = new WebSocketClient(); var scene = new Scene(); var syncManager = new SyncManager(client, scene); var loginData = {"username": "Test User"}; syncManager.logDebug = true; client.connect("localhost", 2345, loginData); /* setTimeout(printEntityNames, 2000); function printEntityNames() { for (var entityId in scene.entities) { var entity = scene.entities[entityId]; console.log(entity.name); } } */
Fix login property name used in the test login.
Fix login property name used in the test login.
JavaScript
apache-2.0
playsign/WebTundra,playsign/WebTundra,AlphaStaxLLC/WebTundra,AlphaStaxLLC/WebTundra,realXtend/WebTundra,AlphaStaxLLC/WebTundra,realXtend/WebTundra
--- +++ @@ -3,7 +3,7 @@ var client = new WebSocketClient(); var scene = new Scene(); var syncManager = new SyncManager(client, scene); -var loginData = {"name": "Test User"}; +var loginData = {"username": "Test User"}; syncManager.logDebug = true; client.connect("localhost", 2345, loginData);
02029c252511edfa3090111bc700944869fa55a3
test/steps/pages/board.js
test/steps/pages/board.js
var massahHelper = require('massah/helper') , helper = massahHelper.application.helper module.exports = (function() { var library = massahHelper.getLibrary() .then('the user has the access level (.*)', function(level) { var driver = this.driver driver.element('a[title="Settings"]').click() driver.wait(function() { return driver.element('a.change-access-level').isDisplayed(function(displayed) { if (!displayed) return false driver.element('a.change-access-level').html(function(label) { label.should.equal( 'Change access\n' + level ) }) return true }) }, 5000, 'Waiting for access level label') }) return library })()
var massahHelper = require('massah/helper') , helper = massahHelper.application.helper module.exports = (function() { var library = massahHelper.getLibrary() .then('the user has the access level (.*)', function(level) { var driver = this.driver driver.element('a[title="Settings"]').click() driver.wait(function() { return driver.element('a.change-access-level').isDisplayed(function(displayed) { if (!displayed) return false driver.element('a.change-access-level').html(function(label) { label.should.equal( 'Change access <p class="ui-li-aside">' + level + '</p>' ) }) return true }) }, 5000, 'Waiting for access level label') }) return library })()
Fix label checking for access level
Fix label checking for access level
JavaScript
apache-2.0
pinittome/pinitto.me,pinittome/pinitto.me,pinittome/pinitto.me
--- +++ @@ -12,7 +12,8 @@ if (!displayed) return false driver.element('a.change-access-level').html(function(label) { label.should.equal( - 'Change access\n' + level + 'Change access <p class="ui-li-aside">' + + level + '</p>' ) }) return true
575d14749b4eabcd7463c0f6c13acfa4fd681d94
multitest.js
multitest.js
#!/usr/bin/env node 'use strict' const main = require('./lib/main') if (require.main === module) { main() }
#!/usr/bin/env node 'use strict' const main = require('./lib/main') if (require.main === module) { process.exit(main()) }
Use main return value as process exit code
Use main return value as process exit code
JavaScript
isc
jcollado/multitest
--- +++ @@ -4,5 +4,5 @@ const main = require('./lib/main') if (require.main === module) { - main() + process.exit(main()) }
8d63b47a04d3841e89a359928f9ad27c214822ed
module/tests/automated.js
module/tests/automated.js
/* global module, asyncTest, ok, start */ module("forge.httpd"); asyncTest("Test that content is being served via https", 1, function () { if (window.location.protocol == "https:") { ok(true, "Expected 'https:'"); start(); } else { ok(false, "Expected 'https:', got: " + window.location.protocol); start(); } }); asyncTest("Test that content is being served from localhost", 1, function () { if (window.location.hostname == "toolkit-local.com") { ok(true, "Expected 'toolkit-local.com'"); start(); } else { ok(false, "Expected 'toolkit-local.com', got: " + window.location.hostname); start(); } });
/* global module, asyncTest, ok, start, $, forge */ module("forge.httpd"); asyncTest("Test that content is being served via https", 1, function () { if (window.location.protocol == "https:") { ok(true, "Expected 'https:'"); start(); } else { ok(false, "Expected 'https:', got: " + window.location.protocol); start(); } }); asyncTest("Test that content is being served from localhost", 1, function () { if (window.location.hostname == "localhost") { ok(true, "Expected 'localhost'"); start(); } else { ok(false, "Expected 'localhost', got: " + window.location.hostname); start(); } }); var numrequests = 512; asyncTest("Test that we can make a lot of requests", numrequests, function () { var url = window.location.protocol + "//" + window.location.host + "/src/fixtures/httpd/icon-512.png"; forge.logging.log("Using url: " + url); var count = 0; var options = { url: url, success: function () { count++; ok(true); if (count === numrequests) { start(); } }, error: function (error) { count++; ok(false, "Error: " + JSON.stringify(error)); if (count === numrequests) { start(); } } }; for (var i = 0; i < numrequests; i++) { options.url = url + "?count=" + i; $.ajax(options); } });
Add a simple stress test to the unit tests
Add a simple stress test to the unit tests
JavaScript
bsd-2-clause
trigger-corp/trigger.io-httpd,trigger-corp/trigger.io-httpd
--- +++ @@ -1,4 +1,4 @@ -/* global module, asyncTest, ok, start */ +/* global module, asyncTest, ok, start, $, forge */ module("forge.httpd"); @@ -13,11 +13,41 @@ }); asyncTest("Test that content is being served from localhost", 1, function () { - if (window.location.hostname == "toolkit-local.com") { - ok(true, "Expected 'toolkit-local.com'"); + if (window.location.hostname == "localhost") { + ok(true, "Expected 'localhost'"); start(); } else { - ok(false, "Expected 'toolkit-local.com', got: " + window.location.hostname); + ok(false, "Expected 'localhost', got: " + window.location.hostname); start(); } }); + +var numrequests = 512; + +asyncTest("Test that we can make a lot of requests", numrequests, function () { + var url = window.location.protocol + "//" + + window.location.host + "/src/fixtures/httpd/icon-512.png"; + forge.logging.log("Using url: " + url); + var count = 0; + var options = { + url: url, + success: function () { + count++; + ok(true); + if (count === numrequests) { + start(); + } + }, + error: function (error) { + count++; + ok(false, "Error: " + JSON.stringify(error)); + if (count === numrequests) { + start(); + } + } + }; + for (var i = 0; i < numrequests; i++) { + options.url = url + "?count=" + i; + $.ajax(options); + } +});
22f147c995a48cb1a0a592060a712e727aaac92e
core/client/views/posts.js
core/client/views/posts.js
import {mobileQuery, responsiveAction} from 'ghost/utils/mobile'; var PostsView = Ember.View.extend({ target: Ember.computed.alias('controller'), classNames: ['content-view-container'], tagName: 'section', mobileInteractions: function () { Ember.run.scheduleOnce('afterRender', this, function () { var self = this; $(window).resize(function () { if (!mobileQuery.matches) { self.send('resetContentPreview'); } }); // ### Show content preview when swiping left on content list $('.manage').on('click', '.content-list ol li', function (event) { responsiveAction(event, '(max-width: 800px)', function () { self.send('showContentPreview'); }); }); // ### Hide content preview $('.manage').on('click', '.content-preview .button-back', function (event) { responsiveAction(event, '(max-width: 800px)', function () { self.send('hideContentPreview'); }); }); }); }.on('didInsertElement'), }); export default PostsView;
import {mobileQuery, responsiveAction} from 'ghost/utils/mobile'; var PostsView = Ember.View.extend({ target: Ember.computed.alias('controller'), classNames: ['content-view-container'], tagName: 'section', mobileInteractions: function () { Ember.run.scheduleOnce('afterRender', this, function () { var self = this; $(window).resize(function () { if (!mobileQuery.matches) { self.send('resetContentPreview'); } }); // ### Show content preview when swiping left on content list $('.manage').on('click', '.content-list ol li', function (event) { responsiveAction(event, '(max-width: 800px)', function () { self.send('showContentPreview'); }); }); // ### Hide content preview $('.manage').on('click', '.content-preview .button-back', function (event) { responsiveAction(event, '(max-width: 800px)', function () { self.send('hideContentPreview'); }); }); $('[data-off-canvas]').attr('href', this.get('controller.ghostPaths.blogRoot')); }); }.on('didInsertElement'), }); export default PostsView;
Fix Ghost icon is not clickable
Fix Ghost icon is not clickable closes #3623 - Initialization of the link was done on login page where the ‚burger‘ did not exist. - initialization in application needs to be done to make it work on refresh
JavaScript
mit
developer-prosenjit/Ghost,cicorias/Ghost,Klaudit/Ghost,obsoleted/Ghost,kolorahl/Ghost,sergeylukin/Ghost,imjerrybao/Ghost,BayPhillips/Ghost,phillipalexander/Ghost,bastianbin/Ghost,ignasbernotas/nullifer,Elektro1776/javaPress,Romdeau/Ghost,augbog/Ghost,kortemy/Ghost,schneidmaster/theventriloquist.us,dggr/Ghost-sr,optikalefx/Ghost,atandon/Ghost,shannonshsu/Ghost,wallmarkets/Ghost,Yarov/yarov,dggr/Ghost-sr,Kaenn/Ghost,tyrikio/Ghost,ngosinafrica/SiteForNGOs,mattchupp/blog,jiachenning/Ghost,rchrd2/Ghost,rameshponnada/Ghost,lcamacho/Ghost,beautyOfProgram/Ghost,handcode7/Ghost,ManRueda/Ghost,hyokosdeveloper/Ghost,denzelwamburu/denzel.xyz,patrickdbakke/ghost-spa,VillainyStudios/Ghost,JohnONolan/Ghost,xiongjungit/Ghost,gcamana/Ghost,MrMaksimize/sdg1,rafaelstz/Ghost,letsjustfixit/Ghost,adam-paterson/blog,Romdeau/Ghost,olsio/Ghost,bitjson/Ghost,dylanchernick/ghostblog,skmezanul/Ghost,ghostchina/Ghost-zh,zumobi/Ghost,Yarov/yarov,cncodog/Ghost-zh-codog,diancloud/Ghost,MadeOnMars/Ghost,johngeorgewright/blog.j-g-w.info,woodyrew/Ghost,kaychaks/kaushikc.org,Jai-Chaudhary/Ghost,dymx101/Ghost,cncodog/Ghost-zh-codog,JohnONolan/Ghost,smaty1/Ghost,laispace/laiblog,anijap/PhotoGhost,ygbhf/Ghost,ineitzke/Ghost,lukaszklis/Ghost,novaugust/Ghost,no1lov3sme/Ghost,chris-yoon90/Ghost,GroupxDev/javaPress,hoxoa/Ghost,novaugust/Ghost,virtuallyearthed/Ghost,Netazoic/bad-gateway,carlyledavis/Ghost,JohnONolan/Ghost,chris-yoon90/Ghost,sceltoas/Ghost,ananthhh/Ghost,hilerchyn/Ghost,flomotlik/Ghost,Jai-Chaudhary/Ghost,hyokosdeveloper/Ghost,smedrano/Ghost,kortemy/Ghost,zhiyishou/Ghost,novaugust/Ghost,FredericBernardo/Ghost,greenboxindonesia/Ghost,javorszky/Ghost,ivanoats/ivanstorck.com,notno/Ghost,javimolla/Ghost,tmp-reg/Ghost,psychobunny/Ghost,petersucks/blog,thehogfather/Ghost,TryGhost/Ghost,jeonghwan-kim/Ghost,obsoleted/Ghost,wangjun/Ghost,ErisDS/Ghost,thinq4yourself/Unmistakable-Blog,davidmenger/nodejsfan,freele/ghost,v3rt1go/Ghost,ivantedja/ghost,wangjun/Ghost,mlabieniec/ghost-env,praveenscience/Ghost,SachaG/bjjbot-blog,Remchi/Ghost,NamedGod/Ghost,jacostag/Ghost,wallmarkets/Ghost,sifatsultan/js-ghost,optikalefx/Ghost,aroneiermann/GhostJade,Netazoic/bad-gateway,kwangkim/Ghost,mhhf/ghost-latex,dgem/Ghost,NikolaiIvanov/Ghost,UnbounDev/Ghost,rizkyario/Ghost,mdbw/ghost,rollokb/Ghost,cicorias/Ghost,davidenq/Ghost-Blog,STANAPO/Ghost,NovaDevelopGroup/Academy,adam-paterson/blog,mattchupp/blog,flpms/ghost-ad,bitjson/Ghost,gcamana/Ghost,riyadhalnur/Ghost,morficus/Ghost,karmakaze/Ghost,edurangel/Ghost,sangcu/Ghost,InnoD-WebTier/hardboiled_ghost,YY030913/Ghost,daihuaye/Ghost,Japh/Ghost,rmoorman/Ghost,dai-shi/Ghost,panezhang/Ghost,daihuaye/Ghost,BayPhillips/Ghost,bosung90/Ghost,daimaqiao/Ghost-Bridge,tanbo800/Ghost,liftup/ghost,jiangjian-zh/Ghost,ngosinafrica/SiteForNGOs,sfpgmr/Ghost,makapen/Ghost,sajmoon/Ghost,anijap/PhotoGhost,AnthonyCorrado/Ghost,janvt/Ghost,TribeMedia/Ghost,IbrahimAmin/Ghost,patterncoder/patterncoder,Sebastian1011/Ghost,sankumsek/Ghost-ashram,cwonrails/Ghost,madole/diverse-learners,duyetdev/islab,virtuallyearthed/Ghost,wemakeweb/Ghost,ladislas/ghost,smedrano/Ghost,johngeorgewright/blog.j-g-w.info,ManRueda/manrueda-blog,FredericBernardo/Ghost,Alxandr/Blog,ananthhh/Ghost,rito/Ghost,allanjsx/Ghost,ballPointPenguin/Ghost,ClarkGH/Ghost,wspandihai/Ghost,mhhf/ghost-latex,lowkeyfred/Ghost,mlabieniec/ghost-env,PepijnSenders/whatsontheotherside,bosung90/Ghost,zeropaper/Ghost,ivanoats/ivanstorck.com,pensierinmusica/Ghost,camilodelvasto/herokughost,lowkeyfred/Ghost,jaguerra/Ghost,tidyui/Ghost,PeterCxy/Ghost,delgermurun/Ghost,arvidsvensson/Ghost,zackslash/Ghost,Rovak/Ghost,acburdine/Ghost,icowan/Ghost,patterncoder/patterncoder,situkangsayur/Ghost,Bunk/Ghost,edsadr/Ghost,cysys/ghost-openshift,aroneiermann/GhostJade,bigertech/Ghost,wemakeweb/Ghost,veyo-care/Ghost,jamesslock/Ghost,ManRueda/Ghost,Bunk/Ghost,kevinansfield/Ghost,tanbo800/Ghost,rollokb/Ghost,pollbox/ghostblog,mtvillwock/Ghost,etdev/blog,telco2011/Ghost,jomofrodo/ccb-ghost,jamesslock/Ghost,Gargol/Ghost,situkangsayur/Ghost,PeterCxy/Ghost,jorgegilmoreira/ghost,lukekhamilton/Ghost,syaiful6/Ghost,dai-shi/Ghost,aexmachina/blog-old,gabfssilva/Ghost,rizkyario/Ghost,zumobi/Ghost,skleung/blog,r14r/fork_nodejs_ghost,letsjustfixit/Ghost,weareleka/blog,lanffy/Ghost,dqj/Ghost,lukekhamilton/Ghost,imjerrybao/Ghost,hnq90/Ghost,developer-prosenjit/Ghost,UsmanJ/Ghost,no1lov3sme/Ghost,ashishapy/ghostpy,weareleka/blog,olsio/Ghost,dbalders/Ghost,dbalders/Ghost,krahman/Ghost,arvidsvensson/Ghost,ballPointPenguin/Ghost,achimos/ghost_as,sebgie/Ghost,ignasbernotas/nullifer,leonli/ghost,tandrewnichols/ghost,liftup/ghost,nneko/Ghost,petersucks/blog,smaty1/Ghost,woodyrew/Ghost,handcode7/Ghost,exsodus3249/Ghost,shrimpy/Ghost,laispace/laiblog,carlyledavis/Ghost,davidenq/Ghost-Blog,vloom/blog,lukw00/Ghost,Azzurrio/Ghost,schematical/Ghost,pedroha/Ghost,kmeurer/Ghost,floofydoug/Ghost,pbevin/Ghost,InnoD-WebTier/hardboiled_ghost,karmakaze/Ghost,Feitianyuan/Ghost,axross/ghost,ericbenson/GhostAzureSetup,devleague/uber-hackathon,Kikobeats/Ghost,Xibao-Lv/Ghost,theonlypat/Ghost,achimos/ghost_as,morficus/Ghost,sifatsultan/js-ghost,melissaroman/ghost-blog,augbog/Ghost,psychobunny/Ghost,Brunation11/Ghost,omaracrystal/Ghost,fredeerock/atlabghost,diancloud/Ghost,vainglori0us/urban-fortnight,singular78/Ghost,axross/ghost,sajmoon/Ghost,kortemy/Ghost,acburdine/Ghost,nneko/Ghost,bisoe/Ghost,ManRueda/manrueda-blog,yangli1990/Ghost,r14r/fork_nodejs_ghost,leninhasda/Ghost,LeandroNascimento/Ghost,jgillich/Ghost,darvelo/Ghost,schematical/Ghost,BlueHatbRit/Ghost,k2byew/Ghost,riyadhalnur/Ghost,IbrahimAmin/Ghost,camilodelvasto/localghost,NovaDevelopGroup/Academy,lethalbrains/Ghost,jorgegilmoreira/ghost,ghostchina/Ghost.zh,jeonghwan-kim/Ghost,memezilla/Ghost,manishchhabra/Ghost,pbevin/Ghost,lf2941270/Ghost,laispace/laiblog,aschmoe/jesse-ghost-app,barbastan/Ghost,tchapi/igneet-blog,Elektro1776/javaPress,Shauky/Ghost,darvelo/Ghost,stridespace/Ghost,rouanw/Ghost,epicmiller/pages,llv22/Ghost,phillipalexander/Ghost,alexandrachifor/Ghost,tmp-reg/Ghost,melissaroman/ghost-blog,Dnlyc/Ghost,AileenCGN/Ghost,javimolla/Ghost,daimaqiao/Ghost-Bridge,netputer/Ghost,katrotz/blog.katrotz.space,icowan/Ghost,sebgie/Ghost,JonSmith/Ghost,dylanchernick/ghostblog,benstoltz/Ghost,GroupxDev/javaPress,netputer/Ghost,alecho/Ghost,rizkyario/Ghost,denzelwamburu/denzel.xyz,jiachenning/Ghost,ladislas/ghost,UsmanJ/Ghost,TryGhost/Ghost,v3rt1go/Ghost,cobbspur/Ghost,fredeerock/atlabghost,kevinansfield/Ghost,tadityar/Ghost,beautyOfProgram/Ghost,e10/Ghost,memezilla/Ghost,blankmaker/Ghost,PDXIII/Ghost-FormMailer,ClarkGH/Ghost,claudiordgz/Ghost,bsansouci/Ghost,SkynetInc/steam,dggr/Ghost-sr,katiefenn/Ghost,Trendy/Ghost,mohanambati/Ghost,julianromera/Ghost,Remchi/Ghost,dymx101/Ghost,akveo/akveo-blog,lukw00/Ghost,TryGhost/Ghost,omaracrystal/Ghost,YY030913/Ghost,shannonshsu/Ghost,allspiritseve/mindlikewater,praveenscience/Ghost,kmeurer/Ghost,rchrd2/Ghost,ddeveloperr/Ghost,mttschltz/ghostblog,Coding-House/Ghost,Japh/shortcoffee,influitive/crafters,bbmepic/Ghost,mayconxhh/Ghost,lethalbrains/Ghost,MadeOnMars/Ghost,leonli/ghost,leonli/ghost,AlexKVal/Ghost,kaiqigong/Ghost,TribeMedia/Ghost,PaulBGD/Ghost-Plus,jin/Ghost,prosenjit-itobuz/Ghost,janvt/Ghost,velimir0xff/Ghost,blankmaker/Ghost,panezhang/Ghost,Klaudit/Ghost,dYale/blog,lukaszklis/Ghost,VillainyStudios/Ghost,ericbenson/GhostAzureSetup,tyrikio/Ghost,metadevfoundation/Ghost,ryanbrunner/crafters,cqricky/Ghost,madole/diverse-learners,tidyui/Ghost,SkynetInc/steam,julianromera/Ghost,ghostchina/Ghost.zh,delgermurun/Ghost,r1N0Xmk2/Ghost,disordinary/Ghost,LeandroNascimento/Ghost,jparyani/GhostSS,notno/Ghost,andrewconnell/Ghost,Elektro1776/javaPress,ashishapy/ghostpy,codeincarnate/Ghost,yanntech/Ghost,schneidmaster/theventriloquist.us,cncodog/Ghost-zh-codog,e10/Ghost,rafaelstz/Ghost,ErisDS/Ghost,jparyani/GhostSS,Japh/Ghost,flpms/ghost-ad,duyetdev/islab,NamedGod/Ghost,Kikobeats/Ghost,jgillich/Ghost,vainglori0us/urban-fortnight,kmeurer/GhostAzureSetup,hoxoa/Ghost,GroupxDev/javaPress,pensierinmusica/Ghost,mnitchie/Ghost,telco2011/Ghost,uniqname/everydaydelicious,jomahoney/Ghost,singular78/Ghost,pathayes/FoodBlog,mlabieniec/ghost-env,camilodelvasto/herokughost,johnnymitch/Ghost,veyo-care/Ghost,lf2941270/Ghost,ThorstenHans/Ghost,scopevale/wethepeopleweb.org,Coding-House/Ghost,manishchhabra/Ghost,devleague/uber-hackathon,djensen47/Ghost,gleneivey/Ghost,load11/ghost,ITJesse/Ghost-zh,sceltoas/Ghost,jiangjian-zh/Ghost,wspandihai/Ghost,Rovak/Ghost,carlosmtx/Ghost,kolorahl/Ghost,mnitchie/Ghost,qdk0901/Ghost,atandon/Ghost,BlueHatbRit/Ghost,ddeveloperr/Ghost,gleneivey/Ghost,mohanambati/Ghost,influitive/crafters,RufusMbugua/TheoryOfACoder,edurangel/Ghost,PDXIII/Ghost-FormMailer,InnoD-WebTier/hardboiled_ghost,mtvillwock/Ghost,jomahoney/Ghost,load11/ghost,davidenq/Ghost-Blog,etanxing/Ghost,allanjsx/Ghost,letsjustfixit/Ghost,barbastan/Ghost,ckousik/Ghost,diogogmt/Ghost,KnowLoading/Ghost,JonSmith/Ghost,ryanbrunner/crafters,Azzurrio/Ghost,jaguerra/Ghost,syaiful6/Ghost,jomofrodo/ccb-ghost,stridespace/Ghost,Kaenn/Ghost,vishnuharidas/Ghost,cwonrails/Ghost,lanffy/Ghost,diogogmt/Ghost,Trendy/Ghost,gabfssilva/Ghost,trunk-studio/Ghost,nmukh/Ghost,ljhsai/Ghost,flomotlik/Ghost,ITJesse/Ghost-zh,qdk0901/Ghost,klinker-apps/ghost,dqj/Ghost,ljhsai/Ghost,katrotz/blog.katrotz.space,yundt/seisenpenji,pollbox/ghostblog,RoopaS/demo-intern,cysys/ghost-openshift,kaiqigong/Ghost,metadevfoundation/Ghost,ineitzke/Ghost,thinq4yourself/Unmistakable-Blog,PaulBGD/Ghost-Plus,yangli1990/Ghost,andrewconnell/Ghost,vainglori0us/urban-fortnight,ryansukale/ux.ryansukale.com,sebgie/Ghost,tadityar/Ghost,davidmenger/nodejsfan,vloom/blog,allspiritseve/mindlikewater,mayconxhh/Ghost,ghostchina/Ghost-zh,Netazoic/bad-gateway,jacostag/Ghost,AnthonyCorrado/Ghost,Netazoic/bad-gateway,mttschltz/ghostblog,nakamuraapp/new-ghost,neynah/GhostSS,thomasalrin/Ghost,devleague/uber-hackathon,kaychaks/kaushikc.org,Alxandr/Blog,trunk-studio/Ghost,makapen/Ghost,etdev/blog,bisoe/Ghost,jin/Ghost,exsodus3249/Ghost,SachaG/bjjbot-blog,ghostchina/website,theonlypat/Ghost,Gargol/Ghost,Xibao-Lv/Ghost,k2byew/Ghost,JonathanZWhite/Ghost,Kaenn/Ghost,thehogfather/Ghost,ThorstenHans/Ghost,jorgegilmoreira/ghost,sunh3/Ghost,sunh3/Ghost,greenboxindonesia/Ghost,nmukh/Ghost,Sebastian1011/Ghost,Kikobeats/Ghost,cysys/ghost-openshift,JonathanZWhite/Ghost,benstoltz/Ghost,bbmepic/Ghost,uploadcare/uploadcare-ghost-demo,ygbhf/Ghost,skmezanul/Ghost,singular78/Ghost,RufusMbugua/TheoryOfACoder,floofydoug/Ghost,prosenjit-itobuz/Ghost,tksander/Ghost,aschmoe/jesse-ghost-app,kwangkim/Ghost,dYale/blog,ASwitlyk/Ghost,greyhwndz/Ghost,r1N0Xmk2/Ghost,KnowLoading/Ghost,Dnlyc/Ghost,edsadr/Ghost,DesenTao/Ghost,DesenTao/Ghost,NikolaiIvanov/Ghost,rito/Ghost,sergeylukin/Ghost,zeropaper/Ghost,jparyani/GhostSS,rameshponnada/Ghost,kevinansfield/Ghost,JulienBrks/Ghost,ManRueda/Ghost,ckousik/Ghost,mohanambati/Ghost,uploadcare/uploadcare-ghost-demo,llv22/Ghost,bastianbin/Ghost,ErisDS/Ghost,Aaron1992/Ghost,johnnymitch/Ghost,dbalders/Ghost,jaswilli/Ghost,chevex/undoctrinate,Smile42RU/Ghost,rouanw/Ghost,ryansukale/ux.ryansukale.com,francisco-filho/Ghost,xiongjungit/Ghost,jomofrodo/ccb-ghost,JulienBrks/Ghost,acburdine/Ghost,yanntech/Ghost,PepijnSenders/whatsontheotherside,klinker-apps/ghost,AlexKVal/Ghost,tuan/Ghost,leninhasda/Ghost,NovaDevelopGroup/Academy,hnarayanan/narayanan.co,UnbounDev/Ghost,javorszky/Ghost,yundt/seisenpenji,telco2011/Ghost,epicmiller/pages,Smile42RU/Ghost,camilodelvasto/localghost,disordinary/Ghost,greyhwndz/Ghost,Polyrhythm/dolce,NodeJSBarenko/Ghost,ASwitlyk/Ghost,Alxandr/Blog,akveo/akveo-blog,skleung/blog,stridespace/Ghost,zhiyishou/Ghost,tandrewnichols/ghost,GarrethDottin/Habits-Design,Loyalsoldier/Ghost,Feitianyuan/Ghost,Japh/shortcoffee,djensen47/Ghost,ManRueda/manrueda-blog,hnarayanan/narayanan.co,alecho/Ghost,sangcu/Ghost,trepafi/ghost-base,sfpgmr/Ghost,Brunation11/Ghost,mdbw/ghost,pathayes/FoodBlog,jgladch/taskworksource,dgem/Ghost,hnq90/Ghost,Loyalsoldier/Ghost,velimir0xff/Ghost,hilerchyn/Ghost,neynah/GhostSS,cqricky/Ghost,shrimpy/Ghost,allanjsx/Ghost,GarrethDottin/Habits-Design,thomasalrin/Ghost,rmoorman/Ghost,STANAPO/Ghost,tksander/Ghost,daimaqiao/Ghost-Bridge,zackslash/Ghost,francisco-filho/Ghost,claudiordgz/Ghost,cwonrails/Ghost,carlosmtx/Ghost,neynah/GhostSS,jaswilli/Ghost,etanxing/Ghost,bsansouci/Ghost,pedroha/Ghost,codeincarnate/Ghost
--- +++ @@ -28,6 +28,7 @@ self.send('hideContentPreview'); }); }); + $('[data-off-canvas]').attr('href', this.get('controller.ghostPaths.blogRoot')); }); }.on('didInsertElement'), });
e2a3192f9ad1cc3ecd19001038bb7883c5f252eb
step.js
step.js
export class Step { constructor(name, from, to, pos, param = null) { this.name = name this.from = from this.to = to this.pos = pos this.param = param } } const steps = Object.create(null) export function defineStep(name, impl) { steps[name] = impl } export function applyStep(doc, step) { if (!(step.name in steps)) throw new Error("Undefined transform " + step.name) return steps[step.name].apply(doc, step) } export function invertStep(step, oldDoc, map) { return steps[step.name].invert(step, oldDoc, map) }
import {Pos, Node} from "../model" export class Step { constructor(name, from, to, pos, param = null) { this.name = name this.from = from this.to = to this.pos = pos this.param = param } toJSON() { return { name: this.name, from: this.from, to: this.to, pos: this.pos, param: objectToJSON(this.param) } } static fromJSON(json) { return new Step( json.name, json.from && Pos.fromJSON(json.from), json.to && Pos.fromJSON(json.to), json.pos && Pos.fromJSON(json.pos), objectFromJSON(json.param)) } } function objectToJSON(obj) { if (!obj || typeof obj != "object") return obj if (Array.isArray(obj)) return obj.map(objectToJSON) if (obj.toJSON) return obj.toJSON() let result = {} for (let prop in obj) result[prop] = objectToJSON(obj[prop]) return result } function objectFromJSON(json) { if (!json || typeof json != "object") return json if (Array.isArray(json)) return json.map(objectFromJSON) if (json.attrs && json.content) return Node.fromJSON(json) let result = {} for (let prop in json) result[prop] = objectFromJSON(json[prop]) return result } const steps = Object.create(null) export function defineStep(name, impl) { steps[name] = impl } export function applyStep(doc, step) { if (!(step.name in steps)) throw new Error("Undefined transform " + step.name) return steps[step.name].apply(doc, step) } export function invertStep(step, oldDoc, map) { return steps[step.name].invert(step, oldDoc, map) }
Move Step jsonification into Step class, collab code into index.js file
Move Step jsonification into Step class, collab code into index.js file
JavaScript
mit
ProseMirror/prosemirror-transform
--- +++ @@ -1,3 +1,5 @@ +import {Pos, Node} from "../model" + export class Step { constructor(name, from, to, pos, param = null) { this.name = name @@ -6,6 +8,43 @@ this.pos = pos this.param = param } + + toJSON() { + return { + name: this.name, + from: this.from, + to: this.to, + pos: this.pos, + param: objectToJSON(this.param) + } + } + + static fromJSON(json) { + return new Step( + json.name, + json.from && Pos.fromJSON(json.from), + json.to && Pos.fromJSON(json.to), + json.pos && Pos.fromJSON(json.pos), + objectFromJSON(json.param)) + } +} + +function objectToJSON(obj) { + if (!obj || typeof obj != "object") return obj + if (Array.isArray(obj)) return obj.map(objectToJSON) + if (obj.toJSON) return obj.toJSON() + let result = {} + for (let prop in obj) result[prop] = objectToJSON(obj[prop]) + return result +} + +function objectFromJSON(json) { + if (!json || typeof json != "object") return json + if (Array.isArray(json)) return json.map(objectFromJSON) + if (json.attrs && json.content) return Node.fromJSON(json) + let result = {} + for (let prop in json) result[prop] = objectFromJSON(json[prop]) + return result } const steps = Object.create(null)
696605c6aeb63181371bd747e6db0109a9a3376e
test.js
test.js
'use strict'; const expect = require('chai').expect; const sinon = require('sinon'); const proxyquire = require('proxyquire'); const Plugin = require('.'); describe('rsvg-brunch', function () { // Brunch will automatically supply the default public directory path if it is // not explicitly overridden by the user const defaultConfig = {paths: {public: 'public'}}; it('should initialize with empty brunch config', function () { const plugin = new Plugin(defaultConfig); expect(plugin).to.be.ok; }); it('should initialize with empty plugins config', function () { const plugin = new Plugin( Object.assign({}, defaultConfig, {plugins: {}})); expect(plugin).to.be.ok; }); it('should initialize with empty plugin config', function () { const plugin = new Plugin( Object.assign({}, defaultConfig, {plugins: {rsvg: {}}})); expect(plugin).to.be.ok; }); it('should require Rsvg module if installed', function () { const plugin = new Plugin(defaultConfig); expect(plugin).to.have.property('Rsvg'); }); it('should catch error if system librsvg is not installed', function () { let loggerWarnSpy = sinon.spy(); // Cause require('librsvg').Rsvg to throw an error let ProxiedPlugin = proxyquire('.', { librsvg: null, loggy: {warn: loggerWarnSpy} }); const plugin = new ProxiedPlugin(defaultConfig); expect(plugin).not.to.have.property('Rsvg'); sinon.assert.calledOnce(loggerWarnSpy); }); });
'use strict'; const expect = require('chai').expect; const sinon = require('sinon'); const proxyquire = require('proxyquire'); const Plugin = require('.'); describe('rsvg-brunch', function () { // Brunch will automatically supply the default public directory path if it is // not explicitly overridden by the user const defaultConfig = {paths: {public: 'public'}}; it('should initialize with empty brunch config', function () { const plugin = new Plugin(defaultConfig); expect(plugin).to.be.ok; }); it('should initialize with empty plugins config', function () { const plugin = new Plugin( Object.assign({}, defaultConfig, {plugins: {}})); expect(plugin).to.be.ok; }); it('should initialize with empty plugin config', function () { const plugin = new Plugin( Object.assign({}, defaultConfig, {plugins: {rsvg: {}}})); expect(plugin).to.be.ok; }); it('should require Rsvg module if installed', function () { const plugin = new Plugin(defaultConfig); expect(plugin).to.have.property('Rsvg'); }); it('should catch error if system librsvg is not installed', function () { let loggerWarnSpy = sinon.spy(); let ProxiedPlugin = proxyquire('.', { librsvg: null, loggy: {warn: loggerWarnSpy} }); const plugin = new ProxiedPlugin(defaultConfig); expect(plugin).not.to.have.property('Rsvg'); sinon.assert.calledOnce(loggerWarnSpy); }); });
Remove unnecessary librsvg proxy comment
Remove unnecessary librsvg proxy comment
JavaScript
mit
caleb531/rsvg-brunch
--- +++ @@ -35,7 +35,6 @@ it('should catch error if system librsvg is not installed', function () { let loggerWarnSpy = sinon.spy(); - // Cause require('librsvg').Rsvg to throw an error let ProxiedPlugin = proxyquire('.', { librsvg: null, loggy: {warn: loggerWarnSpy}
c031c1b7e14a97812f12f0ec02800a9285d954c7
client/app/controllers/new-portion-order.js
client/app/controllers/new-portion-order.js
import Ember from 'ember'; export default Ember.Controller.extend({ session: Ember.inject.service(), notifications: Ember.inject.service(), actions: { addToOrder(order, account, attrs) { const isManager = (this.get('session.account.id') === order.get('manager.id')); const portion = this.store.createRecord('portion', attrs); portion.set('order', order); portion.set('owner', account); if (isManager) { portion.set('paid', true); } portion.save().then(() => { order.addPortion(portion); if (isManager) { portion.updateOrderMoney(); } order.save(); }); this.get('notifications').subscribeOrderNotification(order.id); this.transitionToRoute('orders'); } } });
import Ember from 'ember'; export default Ember.Controller.extend({ session: Ember.inject.service(), notifications: Ember.inject.service(), actions: { addToOrder(order, account, attrs) { const isManager = (this.get('session.account.id') === order.get('manager.id')); const portion = this.store.createRecord('portion', attrs); portion.set('order', order); portion.set('owner', account); if (isManager) { portion.set('paid', true); } portion.save().then(() => { order.addPortion(portion); if (isManager) { portion.updateOrderMoney(); } order.save(); }); this.get('notifications').subscribeOrderNotification(order.id); this.transitionToRoute('order', order.id); } } });
Change transition route to exact order
Change transition route to exact order
JavaScript
mit
yandex-shri-minsk-2016/yummy-time,yandex-shri-minsk-2016/yummy-time,yandex-shri-minsk-2016/yummy-time
--- +++ @@ -24,7 +24,7 @@ }); this.get('notifications').subscribeOrderNotification(order.id); - this.transitionToRoute('orders'); + this.transitionToRoute('order', order.id); } } });
22d71c6921e11eed3491867318427e97ddb30770
server/code/serverSetup.js
server/code/serverSetup.js
const config = require('config'), _ = require('lodash'), fs = require('fs'), path = require('path'); const SETUPSTATUSFILE = 'setup-status.json'; function isSetupNecessary() { let result = true; const cfgPath = path.join(process.env.NODE_CONFIG_DIR_HOST, SETUPSTATUSFILE); // Does file exist? if (fs.existsSync(cfgPath)) { try { // Does it have the right keys? const setupCFG = JSON.parse(fs.readFileSync(cfgPath)); if (_.get(setupCFG, 'setupComplete', false)) { result = false; } } catch(exc) { // Any error accessing the file means that setup is required. console.debug(exc.message); } } return result; } function run() { if (isSetupNecessary()) { console.info('Setup IS necessary.'); } else { console.info('Setup is NOT necessary.'); } } exports.run = run;
const config = require('config'), _ = require('lodash'), fs = require('fs'), path = require('path'), util = require('util'), push = require('couchdb-push'); const SETUPSTATUSFILE = 'setup-status.json'; const SETUPSTATUSPATH = path.join(process.env.NODE_CONFIG_DIR_HOST, SETUPSTATUSFILE); function isSetupNecessary() { let result = true; // Does file exist? console.debug(`Looking for ${SETUPSTATUSPATH}`); if (fs.existsSync(SETUPSTATUSPATH)) { try { // Does it have the right keys? const setupCFG = JSON.parse(fs.readFileSync(SETUPSTATUSPATH)); if (_.get(setupCFG, 'setupComplete', false)) { result = false; } } catch(exc) { // Any error accessing the file means that setup is required. console.debug(exc.message); } } return result; } function setupAsync(cfg) { return new Promise((resolve, reject) => { const promisePush = util.promisify(push); // TODO: use credentials const dbURL = `${cfg.get('couchdbServer')}/${cfg.get('databaseName')}`; console.debug(dbURL, cfg.defaults.designdoc); promisePush(dbURL, cfg.defaults.designdoc).then(() => { resolve('!'); }).catch((msgData) => { reject(msgData); }); }); } /** * Run the setup process. * @return {Promise} */ function run(svrConfig) { const promiseSetup = new Promise((resolve, reject) => { if (isSetupNecessary()) { console.info('Setup IS necessary.'); // TODO // setupAsync(svrConfig).then(() => { resolve('!done'); // }).catch((msgData) => { // reject(msgData); // }); } else { console.info('Setup is NOT necessary.'); resolve('done'); } }); return promiseSetup; } exports.run = run; exports.isSetupNecessary = isSetupNecessary;
Add setup process, use Promises
Add setup process, use Promises WIP: need to use credentials when updating the db, so this module is probably not the right way to do it *automatically*.
JavaScript
agpl-3.0
tephyr/simpleshelf,tephyr/simpleshelf,tephyr/simpleshelf,tephyr/simpleshelf
--- +++ @@ -1,19 +1,22 @@ const config = require('config'), _ = require('lodash'), fs = require('fs'), - path = require('path'); + path = require('path'), + util = require('util'), + push = require('couchdb-push'); const SETUPSTATUSFILE = 'setup-status.json'; +const SETUPSTATUSPATH = path.join(process.env.NODE_CONFIG_DIR_HOST, SETUPSTATUSFILE); function isSetupNecessary() { let result = true; - const cfgPath = path.join(process.env.NODE_CONFIG_DIR_HOST, SETUPSTATUSFILE); // Does file exist? - if (fs.existsSync(cfgPath)) { + console.debug(`Looking for ${SETUPSTATUSPATH}`); + if (fs.existsSync(SETUPSTATUSPATH)) { try { // Does it have the right keys? - const setupCFG = JSON.parse(fs.readFileSync(cfgPath)); + const setupCFG = JSON.parse(fs.readFileSync(SETUPSTATUSPATH)); if (_.get(setupCFG, 'setupComplete', false)) { result = false; } @@ -26,12 +29,44 @@ return result; } -function run() { - if (isSetupNecessary()) { - console.info('Setup IS necessary.'); - } else { - console.info('Setup is NOT necessary.'); - } +function setupAsync(cfg) { + return new Promise((resolve, reject) => { + const promisePush = util.promisify(push); + + // TODO: use credentials + const dbURL = `${cfg.get('couchdbServer')}/${cfg.get('databaseName')}`; + console.debug(dbURL, cfg.defaults.designdoc); + + promisePush(dbURL, cfg.defaults.designdoc).then(() => { + resolve('!'); + }).catch((msgData) => { + reject(msgData); + }); + }); +} + +/** + * Run the setup process. + * @return {Promise} + */ +function run(svrConfig) { + const promiseSetup = new Promise((resolve, reject) => { + if (isSetupNecessary()) { + console.info('Setup IS necessary.'); + // TODO + // setupAsync(svrConfig).then(() => { + resolve('!done'); + // }).catch((msgData) => { + // reject(msgData); + // }); + } else { + console.info('Setup is NOT necessary.'); + resolve('done'); + } + }); + + return promiseSetup; } exports.run = run; +exports.isSetupNecessary = isSetupNecessary;
d394c7e4dc8d9286034d08c5445e95d2a0cf6891
util.js
util.js
function quote(s) { return "\"" + s.replace(/([\\\"])/, "\\$1") + "\""; } function maybe_quote(s) { if (/[\\\"]/.test(s)) return quote(s); else return s; } function repr(x, max_depth) { if (max_depth == undefined) max_depth = 1; if (x === null) { return "null"; } else if (x instanceof java.lang.Iterable) { var elems = []; var i = x.iterator(); while (i.hasNext()) elems.push(repr(i.next())); return x["class"] + ":[ " + elems.join(", ") + " ]"; } else if (typeof x == "object") { if ("hashCode" in x) // Guess that it's a Java object. return String(x); if (max_depth <= 0) return "{...}"; var elems = []; for (var k in x) elems.push(maybe_quote(k) + ": " + repr(x[k], max_depth - 1)); return "{ " + elems.join(", ") + " }"; } else if (typeof x == "string") { return quote(x); } else { return String(x); } }
function quote(s) { return "\"" + s.replace(/([\\\"])/, "\\$1") + "\""; } function maybe_quote(s) { if (/^[_A-Za-z][_A-Za-z0-9]*$/.test(s)) return s; else return quote(s); } function repr(x, max_depth) { if (max_depth == undefined) max_depth = 1; if (x === null) { return "null"; } else if (x instanceof java.lang.Iterable) { var elems = []; var i = x.iterator(); while (i.hasNext()) elems.push(repr(i.next())); return x["class"] + ":[ " + elems.join(", ") + " ]"; } else if (typeof x == "object") { if ("hashCode" in x) // Guess that it's a Java object. return String(x); if (max_depth <= 0) return "{...}"; var elems = []; for (var k in x) elems.push(maybe_quote(k) + ": " + repr(x[k], max_depth - 1)); return "{ " + elems.join(", ") + " }"; } else if (typeof x == "string") { return quote(x); } else { return String(x); } }
Fix the identifier-ness test in maybe_quote.
Fix the identifier-ness test in maybe_quote.
JavaScript
mit
arlolra/flashproxy,infinity0/flashproxy,infinity0/flashproxy,glamrock/flashproxy,infinity0/flashproxy,arlolra/flashproxy,arlolra/flashproxy,infinity0/flashproxy,glamrock/flashproxy,arlolra/flashproxy,glamrock/flashproxy,arlolra/flashproxy,glamrock/flashproxy,glamrock/flashproxy,infinity0/flashproxy,glamrock/flashproxy,infinity0/flashproxy,arlolra/flashproxy,arlolra/flashproxy
--- +++ @@ -3,10 +3,10 @@ } function maybe_quote(s) { - if (/[\\\"]/.test(s)) + if (/^[_A-Za-z][_A-Za-z0-9]*$/.test(s)) + return s; + else return quote(s); - else - return s; } function repr(x, max_depth) {
88fe77b133eb5e9b09acc80d41e3b2f2b12097b2
src/js/wallet/wallet.deposit.controller.js
src/js/wallet/wallet.deposit.controller.js
(function () { 'use strict'; function WavesWalletDepositController ($scope, events, coinomatService, dialogService, notificationService, applicationContext, bitcoinUriService) { var deposit = this; deposit.bitcoinAddress = ''; deposit.bitcoinAmount = ''; deposit.bitcoinUri = ''; deposit.refreshUri = function () { var params = null; if (deposit.bitcoinAmount > 0) { params = { amount: deposit.bitcoinAmount }; } deposit.bitcoinUri = bitcoinUriService.generate(deposit.bitcoinAddress, params); }; $scope.$on(events.WALLET_DEPOSIT, function (event, eventData) { deposit.assetBalance = eventData.assetBalance; deposit.currency = deposit.assetBalance.currency.displayName; if (deposit.assetBalance.currency.id !== Currency.BTC.id) { $scope.home.featureUnderDevelopment(); return; } dialogService.open('#deposit-dialog'); coinomatService.getDepositDetails(deposit.assetBalance.currency, applicationContext.account.address) .then(function (depositDetails) { deposit.bitcoinAddress = depositDetails.address; deposit.bitcoinUri = bitcoinUriService.generate(deposit.bitcoinAddress); }) .catch(function (exception) { notificationService.error(exception.message); }); }); } WavesWalletDepositController.$inject = ['$scope', 'wallet.events', 'coinomatService', 'dialogService', 'notificationService', 'applicationContext', 'bitcoinUriService']; angular .module('app.wallet') .controller('walletDepositController', WavesWalletDepositController); })();
(function () { 'use strict'; function WavesWalletDepositController ($scope, events, coinomatService, dialogService, notificationService, applicationContext, bitcoinUriService) { var deposit = this; deposit.bitcoinAddress = ''; deposit.bitcoinAmount = ''; deposit.bitcoinUri = ''; deposit.refreshUri = function () { var params = null; if (deposit.bitcoinAmount >= 0.01) { params = { amount: deposit.bitcoinAmount }; } deposit.bitcoinUri = bitcoinUriService.generate(deposit.bitcoinAddress, params); }; $scope.$on(events.WALLET_DEPOSIT, function (event, eventData) { deposit.assetBalance = eventData.assetBalance; deposit.currency = deposit.assetBalance.currency.displayName; if (deposit.assetBalance.currency.id !== Currency.BTC.id) { $scope.home.featureUnderDevelopment(); return; } dialogService.open('#deposit-dialog'); coinomatService.getDepositDetails(deposit.assetBalance.currency, applicationContext.account.address) .then(function (depositDetails) { deposit.bitcoinAddress = depositDetails.address; deposit.bitcoinUri = bitcoinUriService.generate(deposit.bitcoinAddress); }) .catch(function (exception) { notificationService.error(exception.message); }); }); } WavesWalletDepositController.$inject = ['$scope', 'wallet.events', 'coinomatService', 'dialogService', 'notificationService', 'applicationContext', 'bitcoinUriService']; angular .module('app.wallet') .controller('walletDepositController', WavesWalletDepositController); })();
Set minimal deposit amount in accordance with description
Set minimal deposit amount in accordance with description
JavaScript
mit
wavesplatform/WavesGUI,beregovoy68/WavesGUI,wavesplatform/WavesGUI,beregovoy68/WavesGUI,wavesplatform/WavesGUI,beregovoy68/WavesGUI,wavesplatform/WavesGUI,beregovoy68/WavesGUI
--- +++ @@ -10,7 +10,7 @@ deposit.refreshUri = function () { var params = null; - if (deposit.bitcoinAmount > 0) { + if (deposit.bitcoinAmount >= 0.01) { params = { amount: deposit.bitcoinAmount };
bcd6742b0cc7a2e17da8c7e727573e99c30c4f45
variables.js
variables.js
'use strict'; export const buyIn = 20; export const startingSeconds = 15 * 60; export const smallBlinds = [ 100, 200, 300, 400, 500, 800, 1000, 1500, 2000, 3000, 5000]; export function payouts( pot ) { if ( pot <= 80 ) { return [ pot, 0, 0 ]; } else if ( pot <= 140 ) { return [ pot - 30, 30, 0 ]; } else if ( pot <= 180 ) { return [ pot - 60, 40, 20 ]; } else { return [ pot - 80, 60, 20 ]; } };
'use strict'; export const buyIn = 20; export const startingSeconds = 15 * 60; export const smallBlinds = [ 100, 200, 300, 400, 500, 800, 1000, 1500, 2000, 3000, 5000]; export function payouts( pot ) { return [ pot * 0.5, pot * 0.3, pot * 0.2 ]; }
Update payout structure to 50-30-20
Update payout structure to 50-30-20
JavaScript
mit
pattern/react-poker,pattern/react-poker
--- +++ @@ -1,17 +1,12 @@ 'use strict'; -export const buyIn = 20; +export const buyIn = 20; + export const startingSeconds = 15 * 60; + export const smallBlinds = [ 100, 200, 300, 400, 500, 800, 1000, 1500, 2000, 3000, 5000]; + export function payouts( pot ) { - if ( pot <= 80 ) { - return [ pot, 0, 0 ]; - } else if ( pot <= 140 ) { - return [ pot - 30, 30, 0 ]; - } else if ( pot <= 180 ) { - return [ pot - 60, 40, 20 ]; - } else { - return [ pot - 80, 60, 20 ]; - } -}; + return [ pot * 0.5, pot * 0.3, pot * 0.2 ]; +}
a26b63a37cc3027bb37cb1a381b0e89fea231ca0
spec/fixtures/test-data/test-performance.js
spec/fixtures/test-data/test-performance.js
const moment = require('moment'); const formatString = 'YYYY-MM-DD HH:mm:ss'; module.exports = { current: true, id: 1, name: 'Bowling Green Game', openAt: moment().format(formatString), closeAt: moment().format(formatString), performDate: moment().startOf('day').add({ days: 5, hours: 12 }).format(formatString) };
const moment = require('moment'); module.exports = { current: true, id: 1, name: 'Bowling Green Game', openAt: new Date().toISOString(), closeAt: moment().add({ minutes: 1 }).format(), performDate: moment().startOf('day').add({ days: 5, hours: 12 }).format() };
Make test performance challenge window 1 minute long
Make test performance challenge window 1 minute long
JavaScript
mit
osumb/challenges,osumb/challenges,osumb/challenges,osumb/challenges
--- +++ @@ -1,11 +1,10 @@ const moment = require('moment'); -const formatString = 'YYYY-MM-DD HH:mm:ss'; module.exports = { current: true, id: 1, name: 'Bowling Green Game', - openAt: moment().format(formatString), - closeAt: moment().format(formatString), - performDate: moment().startOf('day').add({ days: 5, hours: 12 }).format(formatString) + openAt: new Date().toISOString(), + closeAt: moment().add({ minutes: 1 }).format(), + performDate: moment().startOf('day').add({ days: 5, hours: 12 }).format() };
938211a21bd73c73cdc9e877a93cee732c628dd0
mailman-discard-and-ban.user.js
mailman-discard-and-ban.user.js
// ==UserScript== // @name Mailman discard // @namespace http://bd808.com/userscripts/ // @description Automatically selects "Discard" and ticks the "Add" and "Discards" checkboxes on Mailman admin requests for pending messages // @match *://*/mailman/admindb/* // @match *://*/lists/admindb/* // @version 0.1 // @author Bryan Davis // @license MIT License; http://opensource.org/licenses/MIT // @downloadURL https://bd808.github.io/userscripts/mailman-discard-and-ban.user.js // @updateURL https://bd808.github.io/userscripts/mailman-discard-and-ban.user.js // @grant none // @run-at document-end // ==/UserScript== (function() { var inputs = document.getElementsByTagName('input'), len = inputs.length; for (var i = 0; i < len; i++) { var input = inputs[i]; if ( input.name.toLowerCase().match(/^senderaction/) && input.value == '3' ) { input.checked = true; } else if (input.name.toLowerCase().match(/^senderfilterp/)) { input.checked = true; } } })();
// ==UserScript== // @name Mailman discard // @namespace http://bd808.com/userscripts/ // @description Automatically selects "Discard" and ticks the "Add" and "Discards" checkboxes on Mailman admin requests for pending messages // @match https?://*/mailman/admindb/* // @match https?://*/lists/admindb/* // @version 0.2 // @author Bryan Davis // @license MIT License; http://opensource.org/licenses/MIT // @downloadURL https://bd808.github.io/userscripts/mailman-discard-and-ban.user.js // @updateURL https://bd808.github.io/userscripts/mailman-discard-and-ban.user.js // @grant none // @run-at document-end // ==/UserScript== (function() { var inputs = document.getElementsByTagName('input'), len = inputs.length; for (var i = 0; i < len; i++) { var input = inputs[i]; if ( input.name.toLowerCase().match(/^senderaction/) && input.value == '3' ) { input.checked = true; } else if (input.name.toLowerCase().match(/^senderfilterp/)) { input.checked = true; } } })();
Make @match work with newer greasemonkey
mailman: Make @match work with newer greasemonkey Using a wildcard for the protocol no longer works.
JavaScript
mit
bd808/userscripts,bd808/userscripts
--- +++ @@ -2,9 +2,9 @@ // @name Mailman discard // @namespace http://bd808.com/userscripts/ // @description Automatically selects "Discard" and ticks the "Add" and "Discards" checkboxes on Mailman admin requests for pending messages -// @match *://*/mailman/admindb/* -// @match *://*/lists/admindb/* -// @version 0.1 +// @match https?://*/mailman/admindb/* +// @match https?://*/lists/admindb/* +// @version 0.2 // @author Bryan Davis // @license MIT License; http://opensource.org/licenses/MIT // @downloadURL https://bd808.github.io/userscripts/mailman-discard-and-ban.user.js
7224ef8129d87b2b2fe80e604d0f9bdf739d4ed4
module/eCampWeb/vue/src/main.js
module/eCampWeb/vue/src/main.js
import Vue from 'vue' import CampDetails from './components/camp-details' new Vue({ el: '#camp-details', render(h) { return h(CampDetails, { props: this.$el.dataset } ); }, });
import Vue from 'vue' import CampDetails from './components/camp-details' const vueApps = { 'camp-details': CampDetails, }; for (let id in vueApps) { if (!vueApps.hasOwnProperty(id)) continue; if (document.getElementById(id)) { new Vue({ el: '#' + id, render(h) { return h(vueApps[id], { props: this.$el.dataset }); } }); } }
Make root component handling more generic
Make root component handling more generic
JavaScript
agpl-3.0
pmattmann/ecamp3,ecamp/ecamp3,pmattmann/ecamp3,pmattmann/ecamp3,usu/ecamp3,usu/ecamp3,usu/ecamp3,pmattmann/ecamp3,ecamp/ecamp3,usu/ecamp3,ecamp/ecamp3,ecamp/ecamp3
--- +++ @@ -1,9 +1,18 @@ import Vue from 'vue' import CampDetails from './components/camp-details' -new Vue({ - el: '#camp-details', - render(h) { - return h(CampDetails, { props: this.$el.dataset } ); - }, -}); +const vueApps = { + 'camp-details': CampDetails, +}; + +for (let id in vueApps) { + if (!vueApps.hasOwnProperty(id)) continue; + if (document.getElementById(id)) { + new Vue({ + el: '#' + id, + render(h) { + return h(vueApps[id], { props: this.$el.dataset }); + } + }); + } +}
b9b6b177d5ff43a393c152fd8b0ed518002e67f9
modules/finders/index.js
modules/finders/index.js
/* eslint-disable global-require */ module.exports = { 'Bungie.net': require( './Bungie.net.js' ), MiggyRSS: require( './MiggyRSS.js' ), Reddit: require( './Reddit.js' ), rsi: require( './rsi.js' ), Steam: require( './Steam.js' ), Discourse: require( './Discourse.js' ), };
/* eslint-disable global-require */ module.exports = { 'Bungie.net': require( './Bungie.net.js' ), MiggyRSS: require( './MiggyRSS.js' ), Reddit: require( './Reddit.js' ), rsi: require( './rsi.js' ), Steam: require( './Steam.js' ), // Discourse: require( './Discourse.js' ), };
Disable Discourse The endpoints we use are not generic
Disable Discourse The endpoints we use are not generic
JavaScript
mit
post-tracker/finder
--- +++ @@ -6,5 +6,5 @@ Reddit: require( './Reddit.js' ), rsi: require( './rsi.js' ), Steam: require( './Steam.js' ), - Discourse: require( './Discourse.js' ), + // Discourse: require( './Discourse.js' ), };
9638172ebf656409613df191590559f4e2adce5e
npm-build/development.js
npm-build/development.js
var Lanes = ( global.Lanes || (global.Lanes = {}) ); Lanes.Vendor = ( Lanes.Vendor || {} ); Lanes.Vendor.ReactProxy = require("react-proxy"); Lanes.Vendor.ReactTestUtils = require('react-addons-test-utils'); Lanes.Vendor.deepForceUpdate = require('react-deep-force-update');
var Lanes = ( global.Lanes || (global.Lanes = {}) ); Lanes.Vendor = ( Lanes.Vendor || {} ); Lanes.Vendor.ReactProxy = require("react-proxy").default; Lanes.Vendor.ReactTestUtils = require('react-addons-test-utils'); Lanes.Vendor.deepForceUpdate = require('react-deep-force-update');
Work around es7 exprots from new version
Work around es7 exprots from new version
JavaScript
mit
argosity/lanes,argosity/hippo,argosity/hippo,argosity/lanes,argosity/lanes,argosity/hippo
--- +++ @@ -1,6 +1,6 @@ var Lanes = ( global.Lanes || (global.Lanes = {}) ); Lanes.Vendor = ( Lanes.Vendor || {} ); -Lanes.Vendor.ReactProxy = require("react-proxy"); +Lanes.Vendor.ReactProxy = require("react-proxy").default; Lanes.Vendor.ReactTestUtils = require('react-addons-test-utils'); Lanes.Vendor.deepForceUpdate = require('react-deep-force-update');
9c7c632269afff96fc41f6c3663fd20fde3b795e
indico/htdocs/js/indico/angular/filters.js
indico/htdocs/js/indico/angular/filters.js
/* This file is part of Indico. * Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN). * * Indico is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 3 of the * License, or (at your option) any later version. * * Indico is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Indico; if not, see <http://www.gnu.org/licenses/>. */ var ndFilters = angular.module("ndFilters", []); ndFilters.filter("i18n", function() { return function(input) { return $T(input); }; }); ndFilters.filter("range", function() { return function(input, min, max) { min = parseInt(min, 10) || 0; max = parseInt(max, 10); for (var i=min; i<=max; i++) { input.push(i); } return input; }; });
/* This file is part of Indico. * Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN). * * Indico is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 3 of the * License, or (at your option) any later version. * * Indico is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Indico; if not, see <http://www.gnu.org/licenses/>. */ var ndFilters = angular.module("ndFilters", []); ndFilters.filter("i18n", function() { return function(input) { var str = $T.gettext(input); if (arguments.length > 1) { str = str.format.apply(str, [].slice.call(arguments, 1)); } return str; }; }); ndFilters.filter("range", function() { return function(input, min, max) { min = parseInt(min, 10) || 0; max = parseInt(max, 10); for (var i=min; i<=max; i++) { input.push(i); } return input; }; });
Change i18n angular filter to interpolate strings
Change i18n angular filter to interpolate strings
JavaScript
mit
DirkHoffmann/indico,mic4ael/indico,indico/indico,OmeGak/indico,indico/indico,DirkHoffmann/indico,ThiefMaster/indico,mic4ael/indico,pferreir/indico,ThiefMaster/indico,OmeGak/indico,pferreir/indico,OmeGak/indico,mvidalgarcia/indico,pferreir/indico,DirkHoffmann/indico,mic4ael/indico,mvidalgarcia/indico,DirkHoffmann/indico,mic4ael/indico,OmeGak/indico,mvidalgarcia/indico,ThiefMaster/indico,ThiefMaster/indico,mvidalgarcia/indico,pferreir/indico,indico/indico,indico/indico
--- +++ @@ -19,7 +19,11 @@ ndFilters.filter("i18n", function() { return function(input) { - return $T(input); + var str = $T.gettext(input); + if (arguments.length > 1) { + str = str.format.apply(str, [].slice.call(arguments, 1)); + } + return str; }; });
74a45aa89391182f432b19b1b3c25338e189c9c9
app/assets/javascripts/tax-disc-ab-test.js
app/assets/javascripts/tax-disc-ab-test.js
//= require govuk/multivariate-test /*jslint browser: true, * indent: 2, * white: true */ /*global $, GOVUK */ $(function () { GOVUK.taxDiscBetaPrimary = function () { $('.primary-apply').html($('#beta-primary').html()); $('.secondary-apply').html($('#dvla-secondary').html()); }; if(window.location.href.indexOf("/tax-disc") > -1) { new GOVUK.MultivariateTest({ name: 'tax-disc-50-50', customVarIndex: 20, cohorts: { tax_disc_beta_control: { callback: function () { } }, tax_disc_beta: { callback: GOVUK.taxDiscBetaPrimary } } }); } });
//= require govuk/multivariate-test /*jslint browser: true, * indent: 2, * white: true */ /*global $, GOVUK */ $(function () { GOVUK.taxDiscBetaPrimary = function () { $('.primary-apply').html($('#beta-primary').html()); $('.secondary-apply').html($('#dvla-secondary').html()); }; if(window.location.href.indexOf("/tax-disc") > -1) { new GOVUK.MultivariateTest({ name: 'tax-disc-beta', customVarIndex: 20, cohorts: { tax_disc_beta_control: { weight: 50, callback: function () { } }, //50% tax_disc_beta: { weight: 50, callback: GOVUK.taxDiscBetaPrimary } //50% } }); } });
Set the weights for each cohort
Set the weights for each cohort
JavaScript
mit
alphagov/frontend,alphagov/frontend,alphagov/frontend,alphagov/frontend
--- +++ @@ -14,11 +14,11 @@ if(window.location.href.indexOf("/tax-disc") > -1) { new GOVUK.MultivariateTest({ - name: 'tax-disc-50-50', + name: 'tax-disc-beta', customVarIndex: 20, cohorts: { - tax_disc_beta_control: { callback: function () { } }, - tax_disc_beta: { callback: GOVUK.taxDiscBetaPrimary } + tax_disc_beta_control: { weight: 50, callback: function () { } }, //50% + tax_disc_beta: { weight: 50, callback: GOVUK.taxDiscBetaPrimary } //50% } }); }
2d473bc2aa873f71cafdd04e147d5b541a0e164f
src/api/extensions/auth.js
src/api/extensions/auth.js
import config from 'config'; import hapiAuthCookie from 'hapi-auth-cookie'; export default (server, projectConfig) => { server.register(hapiAuthCookie, (err) => { if (err) { throw err; } server.auth.strategy('session', 'cookie', 'optional', { password: config.get('hapi.authCookie.password'), cookie: 'sid', isSecure: false }); }); };
import config from 'config'; import hapiAuthCookie from 'hapi-auth-cookie'; export default (server, projectConfig) => { server.register(hapiAuthCookie, (err) => { if (err) { throw err; } server.auth.strategy('session', 'cookie', 'optional', { password: config.get('hapi.authCookie.password'), cookie: 'sid', isSecure: projectConfig.isProduction }); }); };
Make sid cookie secure in production
Make sid cookie secure in production
JavaScript
mit
apazzolini/rsapp
--- +++ @@ -10,7 +10,7 @@ server.auth.strategy('session', 'cookie', 'optional', { password: config.get('hapi.authCookie.password'), cookie: 'sid', - isSecure: false + isSecure: projectConfig.isProduction }); }); };
65a4352846bb570c33bd918584977f084e147d54
src/components/RouterHistoryContainer.js
src/components/RouterHistoryContainer.js
/** * RouterHistoryContainer is already connected to the router state, so you only * have to pass in `routes`. It also responds to history/click events and * dispatches routeTo actions appropriately. */ import React from 'react'; import createReactClass from 'create-react-class'; import PropTypes from 'prop-types'; import Router from './Router'; import connectRouter from './connectRouter'; import History from './History'; const RouterHistoryContainer = createReactClass({ propTypes: { routes: PropTypes.object.isRequired }, onChangeAddress(url, state) { this.props.routeTo(url, { state, isHistoryChange: true }); }, render() { const { router } = this.props; const url = router.current ? router.current.url : null; const state = router.current ? router.current.state : undefined; const replace = router.current ? router.current.replace : undefined; return ( <div> <Router {...this.props} router={router}/> <History history={this.props.history} url={url} state={state} replace={replace} isWaiting={!!router.next} onChange={this.onChangeAddress} /> </div> ); } }); export default connectRouter(RouterHistoryContainer);
/** * RouterHistoryContainer is already connected to the router state, so you only * have to pass in `routes`. It also responds to history/click events and * dispatches routeTo actions appropriately. */ import React from 'react'; import createReactClass from 'create-react-class'; import PropTypes from 'prop-types'; import Router from './Router'; import connectRouter from './connectRouter'; import History from './History'; const RouterHistoryContainer = createReactClass({ propTypes: { routes: PropTypes.object.isRequired, }, onChangeAddress(url, state) { this.props.routeTo(url, { state, isHistoryChange: true, }); }, render() { const { router } = this.props; const url = router.current ? router.current.url : null; const state = router.current ? router.current.state : undefined; const replace = router.current ? router.current.replace : undefined; return [ <Router key="router" {...this.props} router={router} />, <History key="history" history={this.props.history} url={url} state={state} replace={replace} isWaiting={!!router.next} onChange={this.onChangeAddress} />, ]; }, }); export default connectRouter(RouterHistoryContainer);
Send the minimal amount of DOM to the client
Send the minimal amount of DOM to the client
JavaScript
mit
zapier/redux-router-kit
--- +++ @@ -13,15 +13,14 @@ import History from './History'; const RouterHistoryContainer = createReactClass({ - propTypes: { - routes: PropTypes.object.isRequired + routes: PropTypes.object.isRequired, }, onChangeAddress(url, state) { this.props.routeTo(url, { state, - isHistoryChange: true + isHistoryChange: true, }); }, @@ -32,18 +31,19 @@ const state = router.current ? router.current.state : undefined; const replace = router.current ? router.current.replace : undefined; - return ( - <div> - <Router {...this.props} router={router}/> - <History - history={this.props.history} - url={url} state={state} replace={replace} - isWaiting={!!router.next} - onChange={this.onChangeAddress} - /> - </div> - ); - } + return [ + <Router key="router" {...this.props} router={router} />, + <History + key="history" + history={this.props.history} + url={url} + state={state} + replace={replace} + isWaiting={!!router.next} + onChange={this.onChangeAddress} + />, + ]; + }, }); export default connectRouter(RouterHistoryContainer);
b4e695d3fafccdfaba2b97b685383aa69ebc0a4e
src/protocol/message/compression/index.js
src/protocol/message/compression/index.js
const { KafkaJSNotImplemented } = require('../../../errors') const MESSAGE_CODEC_MASK = 0x3 const RECORD_BATCH_CODEC_MASK = 0x07 const Types = { None: 0, GZIP: 1, Snappy: 2, LZ4: 3, } const Codecs = { [Types.GZIP]: () => require('./gzip'), [Types.Snappy]: () => { throw new KafkaJSNotImplemented('Snappy compression not implemented') }, [Types.LZ4]: () => { throw new KafkaJSNotImplemented('LZ4 compression not implemented') }, } const lookupCodec = type => (Codecs[type] ? Codecs[type]() : null) const lookupCodecByAttributes = attributes => { const codec = Codecs[attributes & MESSAGE_CODEC_MASK] return codec ? codec() : null } const lookupCodecByRecordBatchAttributes = attributes => { const codec = Codecs[attributes & RECORD_BATCH_CODEC_MASK] return codec ? codec() : null } module.exports = { Types, Codecs, lookupCodec, lookupCodecByAttributes, lookupCodecByRecordBatchAttributes, }
const { KafkaJSNotImplemented } = require('../../../errors') const MESSAGE_CODEC_MASK = 0x3 const RECORD_BATCH_CODEC_MASK = 0x07 const Types = { None: 0, GZIP: 1, Snappy: 2, LZ4: 3, ZSTD: 4, } const Codecs = { [Types.GZIP]: () => require('./gzip'), [Types.Snappy]: () => { throw new KafkaJSNotImplemented('Snappy compression not implemented') }, [Types.LZ4]: () => { throw new KafkaJSNotImplemented('LZ4 compression not implemented') }, [Types.ZSTD]: () => { throw new KafkaJSNotImplemented('ZSTD compression not implemented') }, } const lookupCodec = type => (Codecs[type] ? Codecs[type]() : null) const lookupCodecByAttributes = attributes => { const codec = Codecs[attributes & MESSAGE_CODEC_MASK] return codec ? codec() : null } const lookupCodecByRecordBatchAttributes = attributes => { const codec = Codecs[attributes & RECORD_BATCH_CODEC_MASK] return codec ? codec() : null } module.exports = { Types, Codecs, lookupCodec, lookupCodecByAttributes, lookupCodecByRecordBatchAttributes, }
Add support for ZStandard compression.
Add support for ZStandard compression. This is landing in Kafka 2.1.0, due for release 29th October, 2018. References - 1. https://cwiki.apache.org/confluence/display/KAFKA/KIP-110%3A+Add+Codec+for+ZStandard+Compression 2. https://issues.apache.org/jira/browse/KAFKA-4514 3. https://github.com/apache/kafka/pull/2267 4. https://cwiki.apache.org/confluence/pages/viewpage.action?pageId=91554044
JavaScript
mit
tulios/kafkajs,tulios/kafkajs,tulios/kafkajs,tulios/kafkajs
--- +++ @@ -8,6 +8,7 @@ GZIP: 1, Snappy: 2, LZ4: 3, + ZSTD: 4, } const Codecs = { @@ -17,6 +18,9 @@ }, [Types.LZ4]: () => { throw new KafkaJSNotImplemented('LZ4 compression not implemented') + }, + [Types.ZSTD]: () => { + throw new KafkaJSNotImplemented('ZSTD compression not implemented') }, }
c29b6f6da351534deccb5cd7c62f7eceee140fc9
lib/uat_director/javascript/uat_director.js
lib/uat_director/javascript/uat_director.js
$("body").prepend("<div id='uat-bar'><a class='go' href='#'>Show me what to test</a><div class='pop-over hide'><a class='close' href='#'>close</a></div></div>"); $("head").append("<link href='http://github.com/plus2/uat_director/raw/master/lib/uat_director/stylesheets/uat_director.css' media='screen' rel='stylesheet' type='text/css'>"); $(function() { $("#uat-bar a.go").click(function() { $.ajax({ url: '/uat_director', success: function(response) { $(".pop-over").append(response); $(".pop-over").slideDown(); } }); }); $("#uat-bar a.close").click(function() { $(".pop-over").slideUp(function() { $(".pop-over ol").remove(); }); }); });
(function($) { $("body").prepend("<div id='uat-bar'><a class='go' href='#'>Show me what to test</a><div class='pop-over hide'></div></div>"); $("head").append("<link href='http://github.com/plus2/uat_director/raw/master/lib/uat_director/stylesheets/uat_director.css' media='screen' rel='stylesheet' type='text/css'>"); $(function() { $("#uat-bar a.go").click(function() { $.ajax({ url: '/uat_director', success: function(response) { $(".pop-over").append(response); $(".pop-over").slideDown(); } }); }); $("#uat-bar a.close").click(function() { $(".pop-over").slideUp(function() { $(".pop-over ol").remove(); }); }); }); })(jQuery);
Use a closure and remove the close link.
Use a closure and remove the close link.
JavaScript
mit
plus2/whereuat,plus2/whereuat
--- +++ @@ -1,4 +1,5 @@ - $("body").prepend("<div id='uat-bar'><a class='go' href='#'>Show me what to test</a><div class='pop-over hide'><a class='close' href='#'>close</a></div></div>"); +(function($) { + $("body").prepend("<div id='uat-bar'><a class='go' href='#'>Show me what to test</a><div class='pop-over hide'></div></div>"); $("head").append("<link href='http://github.com/plus2/uat_director/raw/master/lib/uat_director/stylesheets/uat_director.css' media='screen' rel='stylesheet' type='text/css'>"); $(function() { $("#uat-bar a.go").click(function() { @@ -17,3 +18,4 @@ }); }); }); +})(jQuery);
8b0b45b41bc26db0771ebd58d521540ac7c490e6
recipes/conversation/config.default.js
recipes/conversation/config.default.js
// User-specific configuration exports.conversationWorkspaceId = ''; // replace with the workspace identifier of your conversation // Create the credentials object for export exports.credentials = {}; // Watson Conversation // https://www.ibm.com/watson/developercloud/conversation.html exports.credentials.conversation = { password: '', username: '' }; // Watson Speech to Text // https://www.ibm.com/watson/developercloud/speech-to-text.html exports.credentials.speech_to_text = { password: '', username: '' }; // Watson Text to Speech // https://www.ibm.com/watson/developercloud/text-to-speech.html exports.credentials.text_to_speech = { password: '', username: '' };
/* User-specific configuration ** IMPORTANT NOTE ******************** * Please ensure you do not interchange your username and password. * Hint: Your username is the lengthy value ~ 36 digits including a hyphen * Hint: Your password is the smaller value ~ 12 characters */ exports.conversationWorkspaceId = ''; // replace with the workspace identifier of your conversation // Create the credentials object for export exports.credentials = {}; // Watson Conversation // https://www.ibm.com/watson/developercloud/conversation.html exports.credentials.conversation = { password: '', username: '' }; // Watson Speech to Text // https://www.ibm.com/watson/developercloud/speech-to-text.html exports.credentials.speech_to_text = { password: '', username: '' }; // Watson Text to Speech // https://www.ibm.com/watson/developercloud/text-to-speech.html exports.credentials.text_to_speech = { password: '', username: '' };
Add note regarding username/password interchange.
Add note regarding username/password interchange.
JavaScript
apache-2.0
ibmtjbot/tjbot,zhix/tjbot,zhix/tjbot,Hachimaki/TJBot,Hachimaki/TJBot,ibmtjbot/tjbot
--- +++ @@ -1,4 +1,11 @@ -// User-specific configuration +/* +User-specific configuration + ** IMPORTANT NOTE ******************** + * Please ensure you do not interchange your username and password. + * Hint: Your username is the lengthy value ~ 36 digits including a hyphen + * Hint: Your password is the smaller value ~ 12 characters +*/ + exports.conversationWorkspaceId = ''; // replace with the workspace identifier of your conversation // Create the credentials object for export
5a1818fd71502a6c325387d1f5f61c76cadc0512
routes/auth.js
routes/auth.js
var User = require('../models/user'); var express = require('express'); var router = express.Router(); router.route('/auth').get(getAuth); router.route('/auth').post(login); router.route('/auth').delete(logout); module.exports = router; function getAuth(req, res) { if(req.session.userId == null) res.json(null); else User.findById(req.session.userId, function(err, user) { res.json(user); }); } function login(req, res) { var user = User.findOne({username : req.body.username, passwordHash : encryptPassword(req.body.password)}, function(err, user) { if(user != null) { console.log("login"); req.session.userId = user._id; req.session.save(); } res.json(user); }); } function logout(req, res) { console.log("logout"); req.session.destroy(function(){res.json(true);}); } function encryptPassword(password) { return '098f6bcd4621d373cade4e832627b4f6'; }
var User = require('../models/user'); var Response = require('../modules/response'); var express = require('express'); var router = express.Router(); router.route('/auth').get(getAuth); router.route('/auth').post(login); router.route('/auth').delete(logout); module.exports = router; function getAuth(req, res) { if(req.session.userId == null) Response(res, "Error : Not Authenticated", null, 0); else User.findById(req.session.userId, function(err, user) { Response(res, "Authenticated", user, 1); }); } function login(req, res) { var user = User.findOne({username : req.body.username, passwordHash : encryptPassword(req.body.password)}, function(err, user) { if (err) Response(res, "Error", err, 0); else if(user != null) { console.log("login"); req.session.userId = user._id; req.session.save(); Response(res, "Authentification successfull", user, 1); } else Response(res, "Error : Authentification failed", null, 0); }); } function logout(req, res) { console.log("logout"); req.session.destroy(function(){ Response(res, "Disconnected", null, 1); }); } function encryptPassword(password) { return '098f6bcd4621d373cade4e832627b4f6'; }
Use Response module to send JSON return messages
Use Response module to send JSON return messages
JavaScript
mit
asso-labeli/labeli-api,asso-labeli/labeli-api,asso-labeli/labeli-api
--- +++ @@ -1,32 +1,41 @@ var User = require('../models/user'); +var Response = require('../modules/response'); + var express = require('express'); var router = express.Router(); router.route('/auth').get(getAuth); router.route('/auth').post(login); router.route('/auth').delete(logout); + module.exports = router; function getAuth(req, res) { if(req.session.userId == null) - res.json(null); + Response(res, "Error : Not Authenticated", null, 0); else - User.findById(req.session.userId, function(err, user) { res.json(user); }); + User.findById(req.session.userId, function(err, user) { + Response(res, "Authenticated", user, 1); + }); } function login(req, res) { - var user = User.findOne({username : req.body.username, passwordHash : encryptPassword(req.body.password)}, function(err, user) + var user = User.findOne({username : req.body.username, + passwordHash : encryptPassword(req.body.password)}, + function(err, user) { - if(user != null) + if (err) Response(res, "Error", err, 0); + else if(user != null) { console.log("login"); req.session.userId = user._id; req.session.save(); + Response(res, "Authentification successfull", user, 1); } - - res.json(user); + else + Response(res, "Error : Authentification failed", null, 0); }); } @@ -34,7 +43,9 @@ function logout(req, res) { console.log("logout"); - req.session.destroy(function(){res.json(true);}); + req.session.destroy(function(){ + Response(res, "Disconnected", null, 1); + }); }
4bdb309eacb34b27cd4f6df4979d823754cb3562
lib/APNPushNotification.js
lib/APNPushNotification.js
var apn = require('apn'); var util = require('util'); var BasePushNotification = require('./BasePushNotification'); connection = new apn.Connection({ cert: '', key: '' }).on('error', console.log.bind(console.log)).on('transmissionError', console.log.bind(console.log)); util.inherits(APNPushNotification, BasePushNotification); /** * Create new APN Push Notification * @param {Object} options * @returns {APNPushNotification} * @constructor */ function APNPushNotification(options) { BasePushNotification.apply(this, arguments); options = extend(true, {}, { device: '', notification: { aps: { alert: "\uD83D\uDCE7 \u2709 You have a new message", sound: 'ping.aiff', badge: 1 }, payload: {} } }, options); this.device = new apn.Device(options.device); this.notification = new apn.Notification(options.notification); } /** * Send push notification to device * @returns {APNPushNotification} */ APNPushNotification.prototype.send = function () { connection.pushNotification(this.notification, this.device); return this; }; module.exports = APNPushNotification;
var apn = require('apn'); var util = require('util'); var BasePushNotification = require('./BasePushNotification'); util.inherits(APNPushNotification, BasePushNotification); /** * Create new APN Push Notification * @param {Object} options * @returns {APNPushNotification} * @constructor */ function APNPushNotification(options) { BasePushNotification.apply(this, arguments); this.setProvider(new apn.Connection({ cert: '', key: '' })); } /** * Create device instance * @param {Object} config * @returns {*} * @private */ APNPushNotification.prototype._createDevice = function (config) { return new apn.Device(config); }; /** * Create notification instance * @param {Object} config * @returns {*} * @private */ APNPushNotification.prototype._createNotification = function (config) { return new apn.Notification(config); }; /** * Send push notification to device * @returns {APNPushNotification} */ APNPushNotification.prototype.send = function () { this .getProvider() .pushNotification(this._createNotification(this.getConfig('notification')), this._createDevice(this.getConfig('device'))); return this; }; module.exports = APNPushNotification;
Rewrite apn push a little bit
Rewrite apn push a little bit
JavaScript
mit
ghaiklor/sails-service-pusher
--- +++ @@ -1,10 +1,6 @@ var apn = require('apn'); var util = require('util'); var BasePushNotification = require('./BasePushNotification'); -connection = new apn.Connection({ - cert: '', - key: '' -}).on('error', console.log.bind(console.log)).on('transmissionError', console.log.bind(console.log)); util.inherits(APNPushNotification, BasePushNotification); @@ -17,28 +13,41 @@ function APNPushNotification(options) { BasePushNotification.apply(this, arguments); - options = extend(true, {}, { - device: '', - notification: { - aps: { - alert: "\uD83D\uDCE7 \u2709 You have a new message", - sound: 'ping.aiff', - badge: 1 - }, - payload: {} - } - }, options); + this.setProvider(new apn.Connection({ + cert: '', + key: '' + })); +} - this.device = new apn.Device(options.device); - this.notification = new apn.Notification(options.notification); -} +/** + * Create device instance + * @param {Object} config + * @returns {*} + * @private + */ +APNPushNotification.prototype._createDevice = function (config) { + return new apn.Device(config); +}; + +/** + * Create notification instance + * @param {Object} config + * @returns {*} + * @private + */ +APNPushNotification.prototype._createNotification = function (config) { + return new apn.Notification(config); +}; /** * Send push notification to device * @returns {APNPushNotification} */ APNPushNotification.prototype.send = function () { - connection.pushNotification(this.notification, this.device); + this + .getProvider() + .pushNotification(this._createNotification(this.getConfig('notification')), this._createDevice(this.getConfig('device'))); + return this; };
3024f5a600747068ae5de791e35294ba7580cc16
lib/browsers-definition.js
lib/browsers-definition.js
module.exports = [ 'ie/7..latest', 'chrome/latest', 'firefox/latest', 'safari/5..latest', 'android/4.4..latest', 'iphone/latest', 'ipad/latest' ]
module.exports = [ 'ie/8..latest', 'chrome/latest', 'firefox/latest', 'safari/6..latest', 'android/4.4..latest', 'iphone/latest', 'ipad/latest' ]
Drop support for IE7 and Safari 5
Drop support for IE7 and Safari 5
JavaScript
bsd-3-clause
PolicyStat/policystat-sauce-browsers
--- +++ @@ -1,8 +1,8 @@ module.exports = [ - 'ie/7..latest', + 'ie/8..latest', 'chrome/latest', 'firefox/latest', - 'safari/5..latest', + 'safari/6..latest', 'android/4.4..latest', 'iphone/latest', 'ipad/latest'
2085fe00e06bdbe55884d14b01c837ff32495dbe
tasks/lib/replacements/@include_nested.js
tasks/lib/replacements/@include_nested.js
/* NESTED INCLUDING MIXINS #gradient > @include vertical($primaryColor, $secondaryColor); #grid > @include gu($rtl); TO =====> @include gradient-vertical($primaryColor, $secondaryColor); @include grid-gu($rtl); */ module.exports = { pattern: /(\s*)\#([\w\-]*)\s*>\s*\@include\s+(.*);/gi, replacement: '$1@include $2-$3;', order: 2 };
/* NESTED INCLUDING MIXINS #gradient > @include vertical($primaryColor, $secondaryColor); #grid > @include gu($rtl); TO =====> @include gradient-vertical($primaryColor, $secondaryColor); @include grid-gu($rtl); */ module.exports = { pattern: /(\s*)\#([\w\-]*)\s*>\s*\@include\s+(.*);/gi, replacement: '$1@include $2-$3;', order: 3 };
Change order of include_nested to remove sort race.
Change order of include_nested to remove sort race.
JavaScript
mit
duvillierA/grunt-less-to-sass
--- +++ @@ -8,5 +8,5 @@ module.exports = { pattern: /(\s*)\#([\w\-]*)\s*>\s*\@include\s+(.*);/gi, replacement: '$1@include $2-$3;', - order: 2 + order: 3 };
877c0dd3828633563de3ad96064765b3e9d47115
bin/gonzales.js
bin/gonzales.js
#!/usr/bin/env node /** * ./bin/gonzales.js filename * ./bin/gonzales.js filename -s */ var gonzales = require('..'), fs = require('fs'), filename = process.argv[2], silent = process.argv[3] === '-s'; if (!filename) { console.log('Please supply a filename. Usage "gonzales file"'); process.exit(); } try { var ast = gonzales.parse(fs.readFileSync(filename).toString()); if (!silent) console.log(ast.toString()); } catch (e) { if (!silent) throw e; }
#!/usr/bin/env node /** * ./bin/gonzales.js filename * ./bin/gonzales.js filename -s */ var gonzales = require('..'), fs = require('fs'), path = require('path'), filename = process.argv[2], silent = process.argv[3] === '-s'; if (!filename) { console.log('Please supply a filename. Usage "gonzales file"'); process.exit(); } var syntax = path.extname(filename).substring(1); var css = fs.readFileSync(filename, 'utf-8'); try { var ast = gonzales.parse(css, {syntax: syntax}); if (!silent) console.log(ast.toString()); } catch (e) { if (!silent) throw e; }
Use file extension as a syntax name
[cli] Use file extension as a syntax name
JavaScript
mit
brendanlacroix/gonzales-pe,tonyganch/gonzales-pe,brendanlacroix/gonzales-pe,tonyganch/gonzales-pe
--- +++ @@ -6,6 +6,7 @@ */ var gonzales = require('..'), fs = require('fs'), + path = require('path'), filename = process.argv[2], silent = process.argv[3] === '-s'; @@ -14,8 +15,11 @@ process.exit(); } +var syntax = path.extname(filename).substring(1); +var css = fs.readFileSync(filename, 'utf-8'); + try { - var ast = gonzales.parse(fs.readFileSync(filename).toString()); + var ast = gonzales.parse(css, {syntax: syntax}); if (!silent) console.log(ast.toString()); } catch (e) { if (!silent) throw e;
c1b608a4001d5893cc1e48b608dcbab197aa6aea
lib/about-status-bar.js
lib/about-status-bar.js
/** @babel */ /** @jsx etch.dom */ import {CompositeDisposable} from 'atom' import etch from 'etch' import EtchComponent from './etch-component' class AboutStatusBar extends EtchComponent { constructor () { super() this.subscriptions = new CompositeDisposable() this.subscriptions.add(atom.tooltips.add(this.element, {title: 'An update will be installed the next time Atom is relaunched.<br/><br/>Click the squirrel icon for more information.'})) } handleClick () { atom.workspace.open('atom://about') } update () { etch.update(this) } render () { return ( <span type='button' className='about-release-notes icon icon-squirrel inline-block' onclick={this.handleClick.bind(this)} /> ) } destroy () { this.subscriptions.dispose() } } export default AboutStatusBar
/** @babel */ /** @jsx etch.dom */ import {CompositeDisposable} from 'atom' import etch from 'etch' import EtchComponent from './etch-component' class AboutStatusBar extends EtchComponent { constructor () { super() this.subscriptions = new CompositeDisposable() this.subscriptions.add(atom.tooltips.add(this.element, {title: 'An update will be installed the next time Atom is relaunched.<br/><br/>Click the squirrel icon for more information.'})) } handleClick () { atom.workspace.open('atom://about') } render () { return ( <span type='button' className='about-release-notes icon icon-squirrel inline-block' onclick={this.handleClick.bind(this)} /> ) } destroy () { super() this.subscriptions.dispose() } } export default AboutStatusBar
Remove unnecessary method overrides from AboutStatusBar
:fire: Remove unnecessary method overrides from AboutStatusBar
JavaScript
mit
mnquintana/atom-about,atom/about
--- +++ @@ -17,10 +17,6 @@ atom.workspace.open('atom://about') } - update () { - etch.update(this) - } - render () { return ( <span type='button' className='about-release-notes icon icon-squirrel inline-block' onclick={this.handleClick.bind(this)} /> @@ -28,6 +24,7 @@ } destroy () { + super() this.subscriptions.dispose() } }
90d6425ba5ad311223915c85cb5ded8f4bf82db0
src/characteristicWrite.js
src/characteristicWrite.js
import { makeCharacteristicEventListener, ReactNativeBluetooth, } from './lib'; const writeCharacteristicValue = (characteristic, buffer, withResponse) => { return new Promise((resolve, reject) => { if (!withResponse) { ReactNativeBluetooth.writeCharacteristicValue(characteristic, buffer.toString('base64'), withResponse); resolve(); return; } const resultMapper = detail => detail; makeCharacteristicEventListener(resolve, reject, ReactNativeBluetooth.CharacteristicWrite, characteristic, resultMapper); ReactNativeBluetooth.writeCharacteristicValue(characteristic, buffer.toString('base64'), withResponse); }); }; export { writeCharacteristicValue, };
import { makeCharacteristicEventListener, ReactNativeBluetooth, } from './lib'; const writeCharacteristicValue = (characteristic, buffer, withResponse) => { return new Promise((resolve, reject) => { if (!withResponse) { ReactNativeBluetooth.writeCharacteristicValue(characteristic, buffer.toString('base64'), withResponse); resolve(); return; } const resultMapper = detail => detail; makeCharacteristicEventListener(resolve, reject, ReactNativeBluetooth.CharacteristicWritten, characteristic, resultMapper); ReactNativeBluetooth.writeCharacteristicValue(characteristic, buffer.toString('base64'), withResponse); }); }; export { writeCharacteristicValue, };
Fix error introduced in refactoring of characteristic write.
Fix error introduced in refactoring of characteristic write.
JavaScript
apache-2.0
sogilis/react-native-bluetooth,sogilis/react-native-bluetooth,sogilis/react-native-bluetooth-manager,sogilis/react-native-bluetooth-manager,sogilis/react-native-bluetooth-manager,sogilis/react-native-bluetooth,sogilis/react-native-bluetooth-manager,sogilis/react-native-bluetooth
--- +++ @@ -13,7 +13,7 @@ const resultMapper = detail => detail; - makeCharacteristicEventListener(resolve, reject, ReactNativeBluetooth.CharacteristicWrite, characteristic, resultMapper); + makeCharacteristicEventListener(resolve, reject, ReactNativeBluetooth.CharacteristicWritten, characteristic, resultMapper); ReactNativeBluetooth.writeCharacteristicValue(characteristic, buffer.toString('base64'), withResponse); });
6948ab430cd6dc8fa5112b637d12a83cb0c8d27a
src/sprites/character/Player/update/move.js
src/sprites/character/Player/update/move.js
import { nextCoord } from '../../../../utils'; import checkCollide from '../../../../collisions'; import { pixelToTile } from '../../../../tiles'; import interfaceWithObjects from '../../Common/interface-objects'; export default function tryMove(direction) { if (this.moving) return; this.face(direction); const moveSpeed = 10; const nextPixelCoord = nextCoord({ x: this.x, y: this.y }, direction, moveSpeed); const collisions = checkCollide.call(this, nextPixelCoord); if (collisions.collides === false) { interfaceWithObjects(collisions.objects, 'collide', this); this.move(nextPixelCoord); } else { this.cursor.move(); } }
import { nextCoord } from '../../../../utils'; import checkCollide from '../../../../collisions'; import { pixelToTile } from '../../../../tiles'; import devtools from '../../../../devtools'; import interfaceWithObjects from '../../Common/interface-objects'; export default function tryMove(direction) { if (this.moving) return; this.face(direction); const moveSpeed = devtools.enabled ? devtools.playerSpeed : 10; const nextPixelCoord = nextCoord({ x: this.x, y: this.y }, direction, moveSpeed); const collisions = checkCollide.call(this, nextPixelCoord); if (collisions.collides === false || (devtools.enabled && devtools.noclip)) { interfaceWithObjects(collisions.objects, 'collide', this); this.move(nextPixelCoord); } else { this.cursor.move(); } }
Add noclip and fast player speed to devtools
Add noclip and fast player speed to devtools
JavaScript
mit
ThomasMays/incremental-forest,ThomasMays/incremental-forest
--- +++ @@ -1,6 +1,8 @@ import { nextCoord } from '../../../../utils'; import checkCollide from '../../../../collisions'; import { pixelToTile } from '../../../../tiles'; + +import devtools from '../../../../devtools'; import interfaceWithObjects from '../../Common/interface-objects'; @@ -9,13 +11,13 @@ this.face(direction); - const moveSpeed = 10; + const moveSpeed = devtools.enabled ? devtools.playerSpeed : 10; const nextPixelCoord = nextCoord({ x: this.x, y: this.y }, direction, moveSpeed); const collisions = checkCollide.call(this, nextPixelCoord); - if (collisions.collides === false) { + if (collisions.collides === false || (devtools.enabled && devtools.noclip)) { interfaceWithObjects(collisions.objects, 'collide', this); this.move(nextPixelCoord);
7875d5954e2562d11a64d84ef69a2c874bf27231
build-darwin.js
build-darwin.js
var fs = require('fs') var exec = require('child_process').exec var pack = JSON.parse(fs.readFileSync('package.json', 'utf-8')) var version = pack.version console.log('Building version ' + version + ' in Brave-darwin-x64') var cmd = 'rm -rf Brave-darwin-x64 && NODE_ENV=production ./node_modules/webpack/bin/webpack.js && rm -f dist/Brave.dmg && ./node_modules/electron-packager/cli.js . Brave --overwrite --ignore="electron-download|electron-rebuild|electron-packager|electron-builder|electron-prebuilt|electron-rebuild|babel-|babel" --platform=darwin --arch=x64 --version=0.35.1 --icon=res/app.icns --app-version=' + version console.log(cmd) exec(cmd, function (err, stdout, stderr) { if (err) console.error(err) console.log(stdout) })
var fs = require('fs') var exec = require('child_process').exec // get our version var pack = JSON.parse(fs.readFileSync('package.json', 'utf-8')) var version = pack.version // get the electron version var electronPrebuiltPack = JSON.parse(fs.readFileSync('./node_modules/electron-prebuilt/package.json', 'utf-8')) var electronVersion = electronPrebuiltPack.version console.log('Building version ' + version + ' in Brave-darwin-x64 with Electron ' + electronVersion) var cmds = [ 'rm -rf Brave-darwin-x64', 'NODE_ENV=production ./node_modules/webpack/bin/webpack.js', 'rm -f dist/Brave.dmg', './node_modules/electron-packager/cli.js . Brave --overwrite --ignore="electron-download|electron-rebuild|electron-packager|electron-builder|electron-prebuilt|electron-rebuild|babel$|babel-(?!polyfill|regenerator-runtime)" --platform=darwin --arch=x64 --version=' + electronVersion + ' --icon=res/app.icns --app-version=' + version ] var cmd = cmds.join(' && ') console.log(cmd) exec(cmd, function (err, stdout, stderr) { if (err) console.error(err) console.log(stdout) })
Use Electron Prebuilt version from package.json
Use Electron Prebuilt version from package.json
JavaScript
mpl-2.0
willy-b/browser-laptop,luixxiul/browser-laptop,darkdh/browser-laptop,Sh1d0w/browser-laptop,timborden/browser-laptop,Sh1d0w/browser-laptop,timborden/browser-laptop,PFCKrutonium/browser-laptop,pmkary/braver,Sh1d0w/browser-laptop,diasdavid/browser-laptop,luixxiul/browser-laptop,MKuenzi/browser-laptop,MKuenzi/browser-laptop,diasdavid/browser-laptop,bkardell/browser-laptop,darkdh/browser-laptop,jonathansampson/browser-laptop,MKuenzi/browser-laptop,timborden/browser-laptop,PFCKrutonium/browser-laptop,manninglucas/browser-laptop,willy-b/browser-laptop,timborden/browser-laptop,darkdh/browser-laptop,pmkary/braver,dcposch/browser-laptop,jonathansampson/browser-laptop,willy-b/browser-laptop,manninglucas/browser-laptop,jonathansampson/browser-laptop,diasdavid/browser-laptop,MKuenzi/browser-laptop,manninglucas/browser-laptop,dcposch/browser-laptop,pmkary/braver,diasdavid/browser-laptop,darkdh/browser-laptop,Sh1d0w/browser-laptop,manninglucas/browser-laptop,jonathansampson/browser-laptop,dcposch/browser-laptop,bkardell/browser-laptop,pmkary/braver,willy-b/browser-laptop,luixxiul/browser-laptop,dcposch/browser-laptop,luixxiul/browser-laptop
--- +++ @@ -1,12 +1,24 @@ var fs = require('fs') var exec = require('child_process').exec +// get our version var pack = JSON.parse(fs.readFileSync('package.json', 'utf-8')) var version = pack.version -console.log('Building version ' + version + ' in Brave-darwin-x64') +// get the electron version +var electronPrebuiltPack = JSON.parse(fs.readFileSync('./node_modules/electron-prebuilt/package.json', 'utf-8')) +var electronVersion = electronPrebuiltPack.version -var cmd = 'rm -rf Brave-darwin-x64 && NODE_ENV=production ./node_modules/webpack/bin/webpack.js && rm -f dist/Brave.dmg && ./node_modules/electron-packager/cli.js . Brave --overwrite --ignore="electron-download|electron-rebuild|electron-packager|electron-builder|electron-prebuilt|electron-rebuild|babel-|babel" --platform=darwin --arch=x64 --version=0.35.1 --icon=res/app.icns --app-version=' + version +console.log('Building version ' + version + ' in Brave-darwin-x64 with Electron ' + electronVersion) + +var cmds = [ + 'rm -rf Brave-darwin-x64', + 'NODE_ENV=production ./node_modules/webpack/bin/webpack.js', + 'rm -f dist/Brave.dmg', + './node_modules/electron-packager/cli.js . Brave --overwrite --ignore="electron-download|electron-rebuild|electron-packager|electron-builder|electron-prebuilt|electron-rebuild|babel$|babel-(?!polyfill|regenerator-runtime)" --platform=darwin --arch=x64 --version=' + electronVersion + ' --icon=res/app.icns --app-version=' + version +] + +var cmd = cmds.join(' && ') console.log(cmd)
c74fa468a78f99c3dc305ed9c535a95e0079dcb8
src/components/Headings.js
src/components/Headings.js
import React from 'react' export const H1 = ({ classes, children }) => ( <h1 className={`${classes} text-3xl font-extrabold tracking-tight text-gray-800 leading-9 sm:leading-10 sm:text-4xl md:text-5xl md:leading-14`} > {children} </h1> ) export const H2 = ({ classes, children }) => ( <h2 className={`${classes} text-2xl font-bold tracking-tight text-gray-800 leading-8`} > {children} </h2> )
import React from 'react' export const H1 = ({ classes, children }) => ( <h1 className={`${ classes ?? '' } text-3xl font-extrabold tracking-tight text-gray-800 leading-9 sm:leading-10 sm:text-4xl md:text-5xl md:leading-14`} > {children} </h1> ) export const H2 = ({ classes, children }) => ( <h2 className={`${ classes ?? '' } text-2xl font-bold tracking-tight text-gray-800 leading-8`} > {children} </h2> )
Fix undefined style corner case
Fix undefined style corner case
JavaScript
mit
dtjv/dtjv.github.io
--- +++ @@ -2,7 +2,9 @@ export const H1 = ({ classes, children }) => ( <h1 - className={`${classes} text-3xl font-extrabold tracking-tight text-gray-800 leading-9 sm:leading-10 sm:text-4xl md:text-5xl md:leading-14`} + className={`${ + classes ?? '' + } text-3xl font-extrabold tracking-tight text-gray-800 leading-9 sm:leading-10 sm:text-4xl md:text-5xl md:leading-14`} > {children} </h1> @@ -10,7 +12,9 @@ export const H2 = ({ classes, children }) => ( <h2 - className={`${classes} text-2xl font-bold tracking-tight text-gray-800 leading-8`} + className={`${ + classes ?? '' + } text-2xl font-bold tracking-tight text-gray-800 leading-8`} > {children} </h2>
83f4844364f200cae38066d7feca7c932bcc88e7
plugins/vega/web_client/views/VegaWidget.js
plugins/vega/web_client/views/VegaWidget.js
import View from 'girder/views/View'; import { AccessType } from 'girder/constants'; import VegaWidgetTemplate from '../templates/vegaWidget.pug'; import '../stylesheets/vegaWidget.styl'; import vg from 'vega'; var VegaWidget = View.extend({ initialize: function (settings) { this.item = settings.item; this.accessLevel = settings.accessLevel; this.item.on('change', function () { this.render(); }, this); this.render(); }, render: function () { var meta = this.item.get('meta'); if (this.accessLevel >= AccessType.READ && meta && meta.vega) { $('#g-app-body-container') .append(VegaWidgetTemplate()); $.ajax({ url: '/api/v1/item/' + this.item.get('_id') + '/download', type: 'GET', dataType: 'json', success: function (spec) { vg.parse.spec(spec, function (chart) { chart({ el: '.g-item-vega-vis', renderer: 'svg' }).update(); }); } }); } else { $('.g-item-vega') .remove(); } } }); export default VegaWidget;
import View from 'girder/views/View'; import { AccessType } from 'girder/constants'; import { restRequest } from 'girder/rest'; import VegaWidgetTemplate from '../templates/vegaWidget.pug'; import '../stylesheets/vegaWidget.styl'; import vg from 'vega'; var VegaWidget = View.extend({ initialize: function (settings) { this.item = settings.item; this.accessLevel = settings.accessLevel; this.item.on('change', function () { this.render(); }, this); this.render(); }, render: function () { var meta = this.item.get('meta'); if (this.accessLevel >= AccessType.READ && meta && meta.vega) { $('#g-app-body-container') .append(VegaWidgetTemplate()); restRequest({ path: '/api/v1/item/' + this.item.get('_id') + '/download', }) .done(function (spec) { vg.parse.spec(spec, function (chart) { chart({ el: '.g-item-vega-vis', renderer: 'svg' }).update(); }); }); } else { $('.g-item-vega') .remove(); } } }); export default VegaWidget;
Use restRequest for Ajax requests to Girder servers
Use restRequest for Ajax requests to Girder servers
JavaScript
apache-2.0
adsorensen/girder,sutartmelson/girder,data-exp-lab/girder,sutartmelson/girder,sutartmelson/girder,RafaelPalomar/girder,manthey/girder,jbeezley/girder,Xarthisius/girder,manthey/girder,jbeezley/girder,kotfic/girder,sutartmelson/girder,Xarthisius/girder,RafaelPalomar/girder,adsorensen/girder,girder/girder,Kitware/girder,girder/girder,RafaelPalomar/girder,Kitware/girder,kotfic/girder,manthey/girder,girder/girder,RafaelPalomar/girder,adsorensen/girder,Kitware/girder,data-exp-lab/girder,data-exp-lab/girder,sutartmelson/girder,Xarthisius/girder,kotfic/girder,kotfic/girder,jbeezley/girder,data-exp-lab/girder,girder/girder,Kitware/girder,adsorensen/girder,kotfic/girder,Xarthisius/girder,manthey/girder,jbeezley/girder,data-exp-lab/girder,RafaelPalomar/girder,Xarthisius/girder,adsorensen/girder
--- +++ @@ -1,5 +1,6 @@ import View from 'girder/views/View'; import { AccessType } from 'girder/constants'; +import { restRequest } from 'girder/rest'; import VegaWidgetTemplate from '../templates/vegaWidget.pug'; import '../stylesheets/vegaWidget.styl'; @@ -22,19 +23,17 @@ if (this.accessLevel >= AccessType.READ && meta && meta.vega) { $('#g-app-body-container') .append(VegaWidgetTemplate()); - $.ajax({ - url: '/api/v1/item/' + this.item.get('_id') + '/download', - type: 'GET', - dataType: 'json', - success: function (spec) { + restRequest({ + path: '/api/v1/item/' + this.item.get('_id') + '/download', + }) + .done(function (spec) { vg.parse.spec(spec, function (chart) { chart({ el: '.g-item-vega-vis', renderer: 'svg' }).update(); }); - } - }); + }); } else { $('.g-item-vega') .remove();
4df5338c87542f6dbf56ba3013bc012b599e333c
js/controllers/specific-tweets.js
js/controllers/specific-tweets.js
const Tweet = require('../models/tweet') const config = require('../config') const mongoose = require('mongoose') const specificTweetsController = function (req, res) { res.set('Access-Control-Allow-Origin', '*') if (!req.params.name) { res.status(400).send('Invalid trend name') return } let query if (!req.query.max_id) { query = {trend: req.params.name} } else { var max_oid = mongoose.Types.ObjectId(req.query.max_id) query = {trend: req.params.name, _id: {$lt: max_oid}} } Tweet.find(query, (err, tweets) => { if (err) { res.status(500).send('Internal error while retreiving tweets') } else { res.type('application/json') res.send(tweets) } }).sort({_id: -1}).limit(config.tweetsPerRequest) } module.exports = specificTweetsController
const Tweet = require('../models/tweet') const config = require('../config') const mongoose = require('mongoose') const specificTweetsController = function (req, res) { res.set('Access-Control-Allow-Origin', '*') if (!req.params.name) { res.status(400).send('Invalid trend name') return } let query if (!req.query.max_id) { query = {trend: req.params.name} } else { var max_oid = mongoose.Types.ObjectId(req.query.max_id) query = {trend: req.params.name, _id: {$lt: max_oid}} } Tweet.find(query, (err, tweets) => { if (err) { res.status(500).send('Internal error while retreiving tweets') } else { let resData = {tweets: tweets} res.json(resData) } }).sort({_id: -1}).limit(config.tweetsPerRequest) } module.exports = specificTweetsController
Make specific tweet endpoint adhere to API schema
Make specific tweet endpoint adhere to API schema
JavaScript
mit
SentiSocial/sentisocial-backend,SentiSocial/backend
--- +++ @@ -22,8 +22,8 @@ if (err) { res.status(500).send('Internal error while retreiving tweets') } else { - res.type('application/json') - res.send(tweets) + let resData = {tweets: tweets} + res.json(resData) } }).sort({_id: -1}).limit(config.tweetsPerRequest) }
3611b33fde572d11101c790b2c2d0d9933b379b9
frontend/src/core/Store.js
frontend/src/core/Store.js
import {createStore, applyMiddleware} from 'redux'; import thunkMiddleware from 'redux-thunk'; import travelApp from 'reducers/Reducers.js'; const createStoreWithMiddleware = applyMiddleware( thunkMiddleware )(createStore); export default createStoreWithMiddleware(travelApp);
import {createStore, compose, applyMiddleware} from 'redux'; import {devTools, persistState} from 'redux-devtools'; import thunkMiddleware from 'redux-thunk'; import travelApp from 'reducers/Reducers.js'; const enhancedCreateStore = compose( applyMiddleware( thunkMiddleware), devTools(), persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/)) )(createStore); export default enhancedCreateStore(travelApp);
Apply devtools as a enhanced create store
Apply devtools as a enhanced create store
JavaScript
agpl-3.0
jilljenn/voyageavecmoi,jilljenn/voyageavecmoi,jilljenn/voyageavecmoi
--- +++ @@ -1,9 +1,13 @@ -import {createStore, applyMiddleware} from 'redux'; +import {createStore, compose, applyMiddleware} from 'redux'; +import {devTools, persistState} from 'redux-devtools'; import thunkMiddleware from 'redux-thunk'; import travelApp from 'reducers/Reducers.js'; -const createStoreWithMiddleware = applyMiddleware( - thunkMiddleware +const enhancedCreateStore = compose( + applyMiddleware( + thunkMiddleware), + devTools(), + persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/)) )(createStore); -export default createStoreWithMiddleware(travelApp); +export default enhancedCreateStore(travelApp);
fc976d49f97fbd5d827edc8190abd1e6b3890b2c
app/directives/validatedInputDirective.js
app/directives/validatedInputDirective.js
core.directive("validatedinput", function() { return { template: '<span ng-include src="view"></span>', restrict: 'E', scope: { "type": "@", "model": "=", "property": "@", "label": "@", "placeholder": "@", "truevalue": "@", "falsevalue": "@", "blur": "&", "results": "=" }, link: function ($scope, element, attr) { $scope.view = attr.view ? attr.view : "bower_components/core/app/views/directives/validatedInput.html"; $scope.keydown = function($event) { if($event.which == 13) { $event.target.blur(); } }; } }; });
core.directive("validatedinput", function() { return { template: '<span ng-include src="view"></span>', restrict: 'E', scope: { "type": "@", "model": "=", "property": "@", "label": "@", "placeholder": "@", "truevalue": "@", "falsevalue": "@", "blur": "&", "results": "=" }, link: function ($scope, element, attr) { $scope.view = attr.view ? attr.view : "bower_components/core/app/views/directives/validatedInput.html"; $scope.keydown = function($event) { // enter(13): submit value to be persisted if($event.which == 13) { $event.target.blur(); } // escape(27): reset value using shadow if($event.which == 27) { $scope.model.refresh(); } }; } }; });
Refresh model when pressing escape within validated input.
Refresh model when pressing escape within validated input.
JavaScript
mit
TAMULib/Weaver-UI-Core,TAMULib/Weaver-UI-Core
--- +++ @@ -17,8 +17,13 @@ $scope.view = attr.view ? attr.view : "bower_components/core/app/views/directives/validatedInput.html"; $scope.keydown = function($event) { + // enter(13): submit value to be persisted if($event.which == 13) { $event.target.blur(); + } + // escape(27): reset value using shadow + if($event.which == 27) { + $scope.model.refresh(); } };
84ab9b7b949235d840fbf19e394fc009b3a06e1b
parse/cloud/main.js
parse/cloud/main.js
require('cloud/app.js'); require('cloud/fuse.min.js'); /* * Provides Cloud Functions for Rice Maps. */ Parse.Cloud.define("placesSearch", function(request, response) { console.log("Search Query: " + request.params.query); // Define Parse cloud query that retrieves all Place objects and matches them to a search var query = new Parse.Query("Place"); query.find({ success: function(results) { // Perform Fuse.js fuzzy search on all Place objects var options = { keys: ['name', 'symbol'] } searcher = new Fuse(results, options); matches = searcher.search(request.params.query) response.success(matches); }, error: function(error) { response.error(error); } }); });
require('cloud/app.js'); var Fuse = require('cloud/fuse.min.js'); /* * Provides Cloud Functions for Rice Maps. */ Parse.Cloud.define("placesSearch", function(request, response) { console.log("Search Query: " + request.params.query); // Define Parse cloud query that retrieves all Place objects and matches them to a search var query = new Parse.Query("Place"); query.find({ success: function(results) { // Perform Fuse.js fuzzy search on all Place objects var options = { keys: ['name', 'symbol'] } searcher = new Fuse(results, options); matches = searcher.search(request.params.query) response.success(matches); }, error: function(error) { response.error(error); } }); });
Modify Fuse require statement to hopefully fit with exporting logic
Modify Fuse require statement to hopefully fit with exporting logic
JavaScript
mit
rice-apps/atlas,rice-apps/atlas,rice-apps/atlas
--- +++ @@ -1,5 +1,5 @@ require('cloud/app.js'); -require('cloud/fuse.min.js'); +var Fuse = require('cloud/fuse.min.js'); /* * Provides Cloud Functions for Rice Maps.
3c2cf102602e5e203f83c8535a2601f4876dcff9
kit/index.js
kit/index.js
const app = require('muffin') const router = app.router router.get('/', function *(next) { console.log('Requested home') yield next }) app.run(router)
const app = require('muffin') const router = app.router router.get('/', function *(next) { console.log('Requested home') yield next }) app.run(router, { render: { defaultLayout: 'default' } })
Set some sample rendering options
Set some sample rendering options
JavaScript
mit
muffinjs/cli,muffin/cli
--- +++ @@ -6,4 +6,8 @@ yield next }) -app.run(router) +app.run(router, { + render: { + defaultLayout: 'default' + } +})
4ce92b03bbda3f6c5d7112c53bed0cfa9205b03a
planner/static/planner/js/new_step_form.js
planner/static/planner/js/new_step_form.js
function set_correct_origin(prev, last) { $(last).find("input[id*='origin_auto']").prop("disabled", true).val($(prev).find("input[id*='destination_auto']").val()); $(last).find("input[type='number'][id*='origin']").val($(prev).find("input[type='number'][id*='destination']").val()); } $(function () { $(".inline." + formset_prefix).formset({ prefix: formset_prefix, // The form prefix for your django formset addCssClass: "btn btn-success btn-block step-add", // CSS class applied to the add link deleteCssClass: "btn btn-success btn-block step-delete", // CSS class applied to the delete link addText: 'Add another question', // Text for the add link deleteText: 'Remove question above', // Text for the delete link formCssClass: 'inline-form', // CSS class applied to each form in a formset added: function (row) { add_autocomplete(row); var forms = $(".inline." + formset_prefix); var prev_form = forms.get(forms.length - 2); set_correct_origin(prev_form, row); }, removed: function (row) { var forms = $(".inline." + formset_prefix); forms.first().find("input").prop("disabled", false); if ($('#id_' + formset_prefix + '-TOTAL_FORMS').val() != 1) { set_correct_origin(forms.get(forms.length - 2), forms.get(forms.length - 1)); } } }) });
function set_correct_origin(prev, last) { $(last).find("input[id*='origin_auto']").prop("disabled", true).val($(prev).find("input[id*='destination_auto']").val()); $(last).find("input[type='number'][id*='origin']").val($(prev).find("input[type='number'][id*='destination']").val()); } $(function () { $(".inline." + formset_prefix).formset({ prefix: formset_prefix, // The form prefix for your django formset addCssClass: "btn btn-success btn-block step-add", // CSS class applied to the add link deleteCssClass: "btn btn-success btn-block step-delete", // CSS class applied to the delete link addText: 'Add another step', // Text for the add link deleteText: 'Remove step above', // Text for the delete link formCssClass: 'inline-form', // CSS class applied to each form in a formset added: function (row) { add_autocomplete(row); var forms = $(".inline." + formset_prefix); var prev_form = forms.get(forms.length - 2); set_correct_origin(prev_form, row); }, removed: function (row) { var forms = $(".inline." + formset_prefix); forms.first().find("input").prop("disabled", false); if ($('#id_' + formset_prefix + '-TOTAL_FORMS').val() != 1) { set_correct_origin(forms.get(forms.length - 2), forms.get(forms.length - 1)); } } }) });
Replace "question" with "step" in Newtrip buttons
Replace "question" with "step" in Newtrip buttons
JavaScript
mit
livingsilver94/getaride,livingsilver94/getaride,livingsilver94/getaride
--- +++ @@ -8,8 +8,8 @@ prefix: formset_prefix, // The form prefix for your django formset addCssClass: "btn btn-success btn-block step-add", // CSS class applied to the add link deleteCssClass: "btn btn-success btn-block step-delete", // CSS class applied to the delete link - addText: 'Add another question', // Text for the add link - deleteText: 'Remove question above', // Text for the delete link + addText: 'Add another step', // Text for the add link + deleteText: 'Remove step above', // Text for the delete link formCssClass: 'inline-form', // CSS class applied to each form in a formset added: function (row) { add_autocomplete(row);
c41f47f32e55029827babc95f8e889c33b3fff95
client/src/containers/ChannelIndexView.js
client/src/containers/ChannelIndexView.js
import React, {Component} from 'react' import {Link} from 'react-router-dom' import Card from '../components/Card' import {connect} from 'react-redux'; import {bindActionCreators} from 'redux' import * as channelsActions from '../actions/channelsActions' class ChannelIndexView extends Component { constructor(props) { super(); this.state = { articles: [] } this.setArticles = this.setArticles.bind(this) this.name = props.channel.name } componentWillMount() { this.setArticles() } componentDidMount() { this.interval = setInterval(this.setArticles, 60000) } componentWillUnmount() { clearInterval(this.interval) } setArticles() { this.props.actions.getArticles(this.props.channel).then(response => { this.setState({ articles: response }) }) } setArticleLink(title) { return encodeURIComponent(title) } render() { const articles = this.state.articles.map((article, index) => { return ( <Link to={`/newsfeed/${this.props.channel.source_id}/${this.setArticleLink(article.title)}`}><h4 className="article-title">{article.title}</h4></Link> ) }) const title = ( <Link to={`/newsfeed/${this.props.channel.source_id}`}>{this.name}</Link> ) return ( <Card title={title} content={articles}/> ) } } const mapDispatchToProps = (dispatch) => { return { actions: bindActionCreators(channelsActions, dispatch) } } const mapStateToProps = (state) => { return {articles: state.articles} } export default connect(mapStateToProps, mapDispatchToProps)(ChannelIndexView)
import React, {Component} from 'react' import {Link} from 'react-router-dom' import Card from '../components/Card' import {connect} from 'react-redux'; class ChannelIndexView extends Component { constructor(props) { super(); this.name = props.channel.name } setArticleLink(title) { return encodeURIComponent(title) } render() { const channelArticles = this.props.articles.find(articleObject => articleObject.name === this.name); const articles = channelArticles.articles.map((article, index) => { return ( <Link to={`/newsfeed/${this.props.channel.source_id}/${this.setArticleLink(article.title)}`}><h4 className="article-title">{article.title}</h4></Link> ) }) const title = ( <Link to={`/newsfeed/${this.props.channel.source_id}`}>{this.name}</Link> ) return ( <Card title={title} content={articles}/> ) } } const mapStateToProps = (state) => { return {articles: state.articles} } export default connect(mapStateToProps)(ChannelIndexView)
Refactor using app state instead of local state
Refactor using app state instead of local state
JavaScript
mit
kevinladkins/newsfeed,kevinladkins/newsfeed,kevinladkins/newsfeed
--- +++ @@ -3,39 +3,15 @@ import {Link} from 'react-router-dom' import Card from '../components/Card' import {connect} from 'react-redux'; -import {bindActionCreators} from 'redux' -import * as channelsActions from '../actions/channelsActions' class ChannelIndexView extends Component { constructor(props) { super(); - this.state = { - articles: [] - } - this.setArticles = this.setArticles.bind(this) this.name = props.channel.name } - componentWillMount() { - this.setArticles() - } - componentDidMount() { - this.interval = setInterval(this.setArticles, 60000) - } - - componentWillUnmount() { - clearInterval(this.interval) - } - - setArticles() { - this.props.actions.getArticles(this.props.channel).then(response => { - this.setState({ - articles: response - }) - }) - } setArticleLink(title) { @@ -43,7 +19,9 @@ } render() { - const articles = this.state.articles.map((article, index) => { + const channelArticles = this.props.articles.find(articleObject => articleObject.name === this.name); + + const articles = channelArticles.articles.map((article, index) => { return ( <Link to={`/newsfeed/${this.props.channel.source_id}/${this.setArticleLink(article.title)}`}><h4 className="article-title">{article.title}</h4></Link> ) @@ -61,14 +39,10 @@ } -const mapDispatchToProps = (dispatch) => { - return { - actions: bindActionCreators(channelsActions, dispatch) - } -} + const mapStateToProps = (state) => { return {articles: state.articles} } -export default connect(mapStateToProps, mapDispatchToProps)(ChannelIndexView) +export default connect(mapStateToProps)(ChannelIndexView)
46962c63a43577a2902045958882b2ecdaa7ad3e
lib/provider-google-contact/helpers/upload.js
lib/provider-google-contact/helpers/upload.js
'use strict'; /** * Upload `contact` (containing contact data) onto Cluestr. * * * @param {Object} contact Contact to upload, plus cluestrClient * @param {Function} cb Callback to call once contacts has been uploaded. */ module.exports = function(contact, cluestrClient, cb) { console.log("Uploading ", contact.url); var identifier = contact.url; if(contact.deleted) { return cluestrClient.deleteDocument(identifier, cb); } // Build contact "the right way" contact = { identifier: identifier, metadatas: contact, semantic_document_type: 'contact', actions: { 'show': contact.url }, user_access: [cluestrClient.accessToken] }; delete contact.metadatas.url; delete contact.metadatas.id; cluestrClient.sendDocument(contact, cb); };
'use strict'; /** * Upload `contact` (containing contact data) onto Cluestr. * * * @param {Object} contact Contact to upload, plus cluestrClient * @param {Object} cluestrClient Client for upload * @param {Object} datas Datas about the current account * @param {Object} contact Contact to upload, plus cluestrClient * @param {Function} cb Callback to call once contacts has been uploaded. */ module.exports = function(contact, cluestrClient, datas, cb) { console.log("Uploading ", contact.url); var identifier = contact.url; if(contact.deleted) { return cluestrClient.deleteDocument(identifier, cb); } // Build contact "the right way" contact = { identifier: identifier, metadatas: contact, semantic_document_type: 'contact', actions: { 'show': contact.url }, user_access: [cluestrClient.accessToken] }; delete contact.metadatas.url; delete contact.metadatas.id; cluestrClient.sendDocument(contact, cb); };
Add datas as parameter for v0.2.4
Add datas as parameter for v0.2.4
JavaScript
mit
AnyFetch/gcontacts-provider.anyfetch.com
--- +++ @@ -6,9 +6,12 @@ * * * @param {Object} contact Contact to upload, plus cluestrClient + * @param {Object} cluestrClient Client for upload + * @param {Object} datas Datas about the current account + * @param {Object} contact Contact to upload, plus cluestrClient * @param {Function} cb Callback to call once contacts has been uploaded. */ -module.exports = function(contact, cluestrClient, cb) { +module.exports = function(contact, cluestrClient, datas, cb) { console.log("Uploading ", contact.url); var identifier = contact.url;
29adca094212de2b38632a70e37d9b59b459e59c
problems/kata/001-todo-backend/001/todo.js
problems/kata/001-todo-backend/001/todo.js
// FIXME: don't use hardcoded params var nano = require('nano')('http://localhost:5984'); var db = nano.db.use('todo'); var todo = {}; todo.getAll = function(callback) { var results = []; db.view('todos', 'all_todos', function(err, body) { for (var row of body.rows) { results.push(row.value); } callback(err, results); }); }; todo.addTask = function(task, callback) { db.insert(task, function(err, body) { if (err) { callback(err); } else { task._id = body.id; task._rev = body.rev; // assign a url based on id and commit back to database // FIXME: don't use hardcoded params task.url = 'http://localhost:3000/' + body.id; todo.insert(task, function(err, body) { if (err) { callback(err); } else { callback(nil, task); } }); } }); }; module.exports = todo;
// FIXME: don't use hardcoded params var nano = require('nano')('http://localhost:5984'); var db = nano.db.use('todo'); var todo = {}; todo.getAll = function(callback) { var results = []; db.view('todos', 'all_todos', function(err, body) { for (var row of body.rows) { results.push(row.value); } callback(err, results); }); }; todo.addTask = function(task, callback) { db.insert(task, function(err, body) { if (err) { callback(err); } else { task._id = body.id; task._rev = body.rev; // assign a url based on id and commit back to database // FIXME: don't use hardcoded params task.url = 'http://localhost:3000/' + body.id; db.insert(task, function(err, body) { callback(err, task); }); } }); }; module.exports = todo;
Fix incorrect call to database and sloppy callback
Fix incorrect call to database and sloppy callback
JavaScript
mit
PurityControl/uchi-komi-js
--- +++ @@ -24,12 +24,8 @@ // assign a url based on id and commit back to database // FIXME: don't use hardcoded params task.url = 'http://localhost:3000/' + body.id; - todo.insert(task, function(err, body) { - if (err) { - callback(err); - } else { - callback(nil, task); - } + db.insert(task, function(err, body) { + callback(err, task); }); } });
f93145b58a5f8cd540b24310deef772bccdeeeb1
lib/index.js
lib/index.js
'use strict'; var config = require('../config/configuration.js'); function htmlReplace(str) { return str.replace(/<\/?[^>]+\/?>/g, ' ').replace(/ +/g, ' ').replace(/ ?\n ?/g, '\n').trim(); } module.exports = function(path, document, changes, finalCb) { if(!document.data.html) { changes.data.html = document.metadata.text; } else if(!document.metadata.text) { changes.metadata.text = htmlReplace(document.data.html); } changes.metadata.text = (changes.metadata.text) ? changes.metadata.text : document.metadata.text; if(document.data.html) { config.separators.html.forEach(function(separator) { var tmpHTML = document.data.html.split(separator)[0]; if(tmpHTML !== document.data.html) { changes.metadata.text = htmlReplace(tmpHTML); } }); } if(changes.metadata.text) { config.separators.text.forEach(function(separator) { var tmpText = changes.metadata.text.split(separator)[0]; if(tmpText !== changes.metadata.text) { changes.metadata.text = tmpText; } }); } finalCb(null, changes); };
'use strict'; var config = require('../config/configuration.js'); function htmlReplace(str) { return str.replace(/<\/?[^>]+\/?>/g, ' ').replace(/ +/g, ' ').replace(/ ?\n ?/g, '\n').trim(); } module.exports = function(path, document, changes, finalCb) { if(!document.data.html) { changes.data.html = document.metadata.text.replace(/\n/g, '<br/>\n'); } else if(!document.metadata.text) { changes.metadata.text = htmlReplace(document.data.html); } changes.metadata.text = (changes.metadata.text) ? changes.metadata.text : document.metadata.text; if(document.data.html) { config.separators.html.forEach(function(separator) { var tmpHTML = document.data.html.split(separator)[0]; if(tmpHTML !== document.data.html) { changes.metadata.text = htmlReplace(tmpHTML); } }); } if(changes.metadata.text) { config.separators.text.forEach(function(separator) { var tmpText = changes.metadata.text.split(separator)[0]; if(tmpText !== changes.metadata.text) { changes.metadata.text = tmpText; } }); } finalCb(null, changes); };
Replace \n by <br/> when we use text as html
Replace \n by <br/> when we use text as html
JavaScript
mit
AnyFetch/embedmail-hydrater.anyfetch.com
--- +++ @@ -8,7 +8,7 @@ module.exports = function(path, document, changes, finalCb) { if(!document.data.html) { - changes.data.html = document.metadata.text; + changes.data.html = document.metadata.text.replace(/\n/g, '<br/>\n'); } else if(!document.metadata.text) { changes.metadata.text = htmlReplace(document.data.html);
536c249f522ee04fa87f6aad5f652b09fdad959f
gulp-tasks/code-quality.js
gulp-tasks/code-quality.js
const path = require('path'); const eslint = require('gulp-eslint'); const config = require('../utils/config'); module.exports = gulp => () => { const stream = gulp.src(path.join(config.pkgdir, 'src/**/*.js')) .pipe(eslint({ configFile: path.join(process.cwd(), '.eslintrc.json'), })) .pipe(eslint.format()); // If not watching, end the stream after linting if there are errors. if (!config.watch) { stream.pipe(eslint.failAfterError()); } return stream; };
const path = require('path'); const eslint = require('gulp-eslint'); const config = require('../utils/config'); module.exports = gulp => () => { const stream = gulp.src(path.join(config.pkgdir, 'src/**/*.js')) .pipe(eslint({ configFile: path.join(process.cwd(), '.eslintrc.json'), })) .pipe(eslint.format()); // If not watching, end the stream after linting if there are errors. if (!config.watch) { return stream.pipe(eslint.failAfterError()); } return stream; };
Fix code quality task for gulp 4
Fix code quality task for gulp 4
JavaScript
mit
odopod/code-library,odopod/code-library
--- +++ @@ -11,7 +11,7 @@ // If not watching, end the stream after linting if there are errors. if (!config.watch) { - stream.pipe(eslint.failAfterError()); + return stream.pipe(eslint.failAfterError()); } return stream;
ae727f6c05c2bf9f27a40ee98eb52fb782098636
node/behaviors/makeMap.js
node/behaviors/makeMap.js
const webModel = require('../webModel'); const webModelFunctions = require('../webModelFunctions'); const robotModel = require('../robotModel'); async function makeMap() { if (webModel.debugging) { console.log('Make Map'); webModelFunctions.scrollingStatusUpdate('Make Map'); } if (robotModel.makeMap.started) { if (robotModel.makeMap.startupComplete) { if (robotModel.makeMap.hasExited) { webModelFunctions.update('status', 'Make Map process is closed.'); webModelFunctions.update('makeMapRunning', false); webModelFunctions.update('makeMap', false); robotModel.makeMap.started = false; webModelFunctions.behaviorStatusUpdate('Make Map: FAILURE'); return false; } else { webModelFunctions.update('status', 'Make Map process started.'); webModelFunctions.update('makeMapRunning', true); if (webModel.pluggedIn) { webModelFunctions.behaviorStatusUpdate('Make Map: Robot is still plugged in!'); } else { webModelFunctions.behaviorStatusUpdate('Make Map: Robot is ready to make a map.'); } return true; } } else { webModelFunctions.update('status', 'Explore process is starting...'); return false; } } else { robotModel.makeMap.start(); webModelFunctions.behaviorStatusUpdate('Make Map'); return false; } } module.exports = makeMap;
const webModel = require('../webModel'); const webModelFunctions = require('../webModelFunctions'); const robotModel = require('../robotModel'); async function makeMap() { if (webModel.debugging) { console.log('Make Map'); webModelFunctions.scrollingStatusUpdate('Make Map'); } if (robotModel.makeMap.started) { if (robotModel.makeMap.startupComplete) { if (robotModel.makeMap.hasExited) { webModelFunctions.update('status', 'Make Map process is closed.'); webModelFunctions.update('makeMapRunning', false); webModelFunctions.update('makeMap', false); robotModel.makeMap.started = false; webModelFunctions.behaviorStatusUpdate('Make Map: FAILURE'); return false; } else { webModelFunctions.update('status', 'Make Map process started.'); webModelFunctions.update('makeMapRunning', true); if (webModel.pluggedIn) { webModelFunctions.behaviorStatusUpdate('Make Map: Robot is still plugged in!'); } else { webModelFunctions.behaviorStatusUpdate('Make Map: Robot is ready to make a map.'); } return true; } } else { webModelFunctions.update('status', 'Make Map is starting...'); return false; } } else { robotModel.makeMap.start(); webModelFunctions.behaviorStatusUpdate('Make Map'); return false; } } module.exports = makeMap;
Correct status output text for Make Map
Correct status output text for Make Map
JavaScript
mit
chrisl8/ArloBot,chrisl8/ArloBot,DTU-R3/ArloBot,DTU-R3/ArloBot,DTU-R3/ArloBot,chrisl8/ArloBot,chrisl8/ArloBot,chrisl8/ArloBot,chrisl8/ArloBot,DTU-R3/ArloBot,DTU-R3/ArloBot,DTU-R3/ArloBot
--- +++ @@ -28,7 +28,7 @@ return true; } } else { - webModelFunctions.update('status', 'Explore process is starting...'); + webModelFunctions.update('status', 'Make Map is starting...'); return false; } } else {
9299388df693c3717bb47353ce1e3d3543a7975e
reviewboard/static/rb/js/utils/textUtils.js
reviewboard/static/rb/js/utils/textUtils.js
(function() { // If `marked` is defined, initialize it with our preferred options if (marked !== undefined) { marked.setOptions({ gfm: true, tables: true, breaks: true, pedantic: false, sanitize: true, smartLists: true, langPrefix : 'language-', highlight: function(code, lang) { // Use google code prettify to render syntax highlighting return prettyPrintOne(_.escape(code), lang, true /* line nos. */); } }); } /* * Format the given text and put it into $el. * * If the given element is expected to be rich text, this will format the text * using Markdown. * * Otherwise, if it's not expected and won't be converted, then it will add * links to review requests and bug trackers but otherwise leave the text alone. */ RB.formatText = function($el, options) { options = options || {}; if ($el.data('rich-text')) { if (options.newText !== undefined) { $el .html(options.newText) .addClass('rich-text') } $el.find('a').attr('target', '_blank'); RB.LinkifyUtils.linkifyChildren($el[0], options.bugTrackerURL); } else if (options.newText !== undefined) { $el.html(RB.LinkifyUtils.linkifyText(options.text, options.bugTrackerURL)); } }; }());
(function() { /* * Format the given text and put it into $el. * * If the given element is expected to be rich text, this will format the text * using Markdown. * * Otherwise, if it's not expected and won't be converted, then it will add * links to review requests and bug trackers but otherwise leave the text alone. */ RB.formatText = function($el, options) { options = options || {}; if ($el.data('rich-text')) { if (options.newText !== undefined) { $el .html(options.newText) .addClass('rich-text'); } $el.find('a').attr('target', '_blank'); RB.LinkifyUtils.linkifyChildren($el[0], options.bugTrackerURL); } else if (options.newText !== undefined) { $el.html(RB.LinkifyUtils.linkifyText(options.text, options.bugTrackerURL)); } }; }());
Fix some issues that were breaking javascript in firefox.
Fix some issues that were breaking javascript in firefox. This fixes a regression introduced when marked.js was removed. Apparently testing global names to see if they're defined doesn't work so well in firefox. This broke pretty much all javascript everywhere. Fortunately, we don't care about setting any marked.js options anymore, so this can just go away. This also fixes a missing semicolon. Testing done: I can edit things on review requests again. Reviewed at https://reviews.reviewboard.org/r/6440/
JavaScript
mit
custode/reviewboard,KnowNo/reviewboard,brennie/reviewboard,KnowNo/reviewboard,reviewboard/reviewboard,bkochendorfer/reviewboard,custode/reviewboard,davidt/reviewboard,sgallagher/reviewboard,sgallagher/reviewboard,beol/reviewboard,chipx86/reviewboard,beol/reviewboard,beol/reviewboard,chipx86/reviewboard,KnowNo/reviewboard,sgallagher/reviewboard,reviewboard/reviewboard,davidt/reviewboard,beol/reviewboard,bkochendorfer/reviewboard,reviewboard/reviewboard,sgallagher/reviewboard,reviewboard/reviewboard,brennie/reviewboard,bkochendorfer/reviewboard,davidt/reviewboard,custode/reviewboard,davidt/reviewboard,brennie/reviewboard,brennie/reviewboard,bkochendorfer/reviewboard,KnowNo/reviewboard,chipx86/reviewboard,custode/reviewboard,chipx86/reviewboard
--- +++ @@ -1,22 +1,4 @@ (function() { - - -// If `marked` is defined, initialize it with our preferred options -if (marked !== undefined) { - marked.setOptions({ - gfm: true, - tables: true, - breaks: true, - pedantic: false, - sanitize: true, - smartLists: true, - langPrefix : 'language-', - highlight: function(code, lang) { - // Use google code prettify to render syntax highlighting - return prettyPrintOne(_.escape(code), lang, true /* line nos. */); - } - }); -} /* @@ -35,7 +17,7 @@ if (options.newText !== undefined) { $el .html(options.newText) - .addClass('rich-text') + .addClass('rich-text'); } $el.find('a').attr('target', '_blank');
c42c732793eb4ee75af7c616ef245e590a47dab7
lib/socket-adaptor.js
lib/socket-adaptor.js
var socketIo = require('socket.io'); function deepClone(base) { if (!base || typeof base != 'object') return base; var cloned = Object.create(null); Object.keys(base).forEach(function(key) { cloned[key] = deepClone(base[key]); }); return cloned; } function buildResultData(envelope) { return { statusCode: envelope.statusCode, body: deepClone(envelope.body) }; } exports.buildResultData = buildResultData; exports.registerHandlers = function(application, server, params) { params = params || {}; if (!connection) throw new Error('Connection to the backend is required!'); function createRequestHandler(command, socket) { return (function(data) { connection.emitMessage(command, data); }); } function createResultHandler(command, socket) { return (function(envelope) { if (/\.result/.test(envelope.type)) { var data = buildResultData(envelope); socket.emit(envelope.type, data); } }); } var io = socketIo.listen(server); io.sockets.on('connection', function(socket) { [ 'status', 'search', 'createtable', 'removetable', 'createcolumn', 'removecolumn', 'loadrecord', 'loadrecords', ].forEach(function(command) { socket.on(command, createRequestHandler(command, socket)); connection.on('message', createResultHandler(command, socket)); }); }); }
var socketIo = require('socket.io'); function deepClone(base) { if (!base || typeof base != 'object') return base; var cloned = Object.create(null); Object.keys(base).forEach(function(key) { cloned[key] = deepClone(base[key]); }); return cloned; } function buildResultData(envelope) { return { statusCode: envelope.statusCode, body: deepClone(envelope.body) }; } exports.buildResultData = buildResultData; exports.registerHandlers = function(application, server, params) { params = params || {}; var connection = params.connection; if (!connection) throw new Error('Connection to the backend is required!'); function createRequestHandler(command, socket) { return (function(data) { connection.emitMessage(command, data); }); } function createResultHandler(command, socket) { return (function(envelope) { if (/\.result/.test(envelope.type)) { var data = buildResultData(envelope); socket.emit(envelope.type, data); } }); } var io = socketIo.listen(server); io.sockets.on('connection', function(socket) { [ 'status', 'search', 'createtable', 'removetable', 'createcolumn', 'removecolumn', 'loadrecord', 'loadrecords', ].forEach(function(command) { socket.on(command, createRequestHandler(command, socket)); connection.on('message', createResultHandler(command, socket)); }); }); }
Define missing local variable "connection"
Define missing local variable "connection"
JavaScript
mit
KitaitiMakoto/express-droonga,KitaitiMakoto/express-droonga,droonga/express-droonga,droonga/express-droonga
--- +++ @@ -21,6 +21,7 @@ exports.registerHandlers = function(application, server, params) { params = params || {}; + var connection = params.connection; if (!connection) throw new Error('Connection to the backend is required!');
5133b16080b85d8933e0f4da8197b7198403e484
routes/rest_views/middleware.js
routes/rest_views/middleware.js
const keystone = require('keystone'); const jwt = require('jsonwebtoken'); /* JWT middleware */ exports.requireJwtAuth = function(req, res, next) { const errorMessage = { badHeader: 'Bad request - missing JWT header', unauthorized: 'Unauthorized - JWT', }; if (!req.headers || !req.headers.authorization || !req.headers.authorization.startsWith("JWT ")) { return res.status(400).json({ error: errorMessage.badHeader }) } const token = req.headers.authorization.substr(4); const secret = keystone._options.rest.jwtSecret; try { var decoded = jwt.verify(token, secret); keystone.list('User').model.findOne({ _id: decoded.user }).exec(function(err, user) { req.user = user; next(); }); return; } catch(err) { // err } // if (req.headers.authorization === ) return next(); return res.status(403).json({ error: errorMessage.unauthorized }); }
const keystone = require('keystone'); const jwt = require('jsonwebtoken'); /* JWT middleware */ exports.requireJwtAuth = function(req, res, next) { const errorMessage = { badHeader: 'Bad request - missing JWT header', unauthorized: 'Unauthorized - JWT', }; // Enable auth with current Keystone's browser session if (req.user) { next(); return; } // Validate JWT header if (!req.headers || !req.headers.authorization || !req.headers.authorization.startsWith("JWT ")) { return res.status(400).json({ error: errorMessage.badHeader }) } const token = req.headers.authorization.substr(4); const secret = keystone._options.rest.jwtSecret; // Decode and verify JWT header try { var decoded = jwt.verify(token, secret); keystone.list('User').model.findOne({ _id: decoded.user }).exec(function(err, user) { req.user = user; next(); }); return; } catch(err) { // err } // Defaults to failure return res.status(403).json({ error: errorMessage.unauthorized }); }
Enable Keystone's session auth for Rest API
Enable Keystone's session auth for Rest API
JavaScript
mit
pista329/keystonejs-test-project,pista329/keystonejs-test-project
--- +++ @@ -12,6 +12,13 @@ unauthorized: 'Unauthorized - JWT', }; + // Enable auth with current Keystone's browser session + if (req.user) { + next(); + return; + } + + // Validate JWT header if (!req.headers || !req.headers.authorization || !req.headers.authorization.startsWith("JWT ")) { return res.status(400).json({ error: errorMessage.badHeader }) } @@ -19,6 +26,7 @@ const token = req.headers.authorization.substr(4); const secret = keystone._options.rest.jwtSecret; + // Decode and verify JWT header try { var decoded = jwt.verify(token, secret); keystone.list('User').model.findOne({ _id: decoded.user }).exec(function(err, user) { @@ -30,6 +38,6 @@ // err } - // if (req.headers.authorization === ) return next(); + // Defaults to failure return res.status(403).json({ error: errorMessage.unauthorized }); }
a097dd790e059eec22f4b9374418ba3284fae4f3
mathChart.js
mathChart.js
var mathChart = { var insertchart = function(canvas,data) { var xmlns="https://www.w3.org/2000/svg" var svg = document.createElementNS(xmlns,"svg"); svg.height = canvas.clientHeight; svg.width = canvas.clientWidth; var path = generatePath(svg,data); for(var i=0; i<path.length; ++i) { svg.appendChild(path[i]); } canvas.appendChild(svg); }; var generatePath(svg, data) { } }
/* mathChart.js author: corehello(corehello@gmail.com) data = { range : [[0,1],[2,3]]; data : [[1,2],[2,3],...]; } */ var mathChart = { var insertchart = function(canvas,data) { var xmlns="https://www.w3.org/2000/svg"; var svg = document.createElementNS(xmlns,"svg"); svg.height = canvas.clientHeight; svg.width = canvas.clientWidth; var path = generatePath(svg,data); for(var i=0; i<path.length; ++i) { svg.appendChild(path[i]); } canvas.appendChild(svg); }; var generatePath = function(svg, data) { var paths=[] for(i=0; i<data.data.length; ++i) { var dd = "" if(i == 0) { dd = dd + "M "+ data.data[i].join(" "); } else { dd = dd + "L "+ data.data[i].join(" "); } path = document.createElementNS("xmlns","path"); path.setAttribute("d", dd); path.setAttribute("stroke", data.color); path.setAttribute("stroke-width", data.width); paths.push(path); } return paths; } }
Write the function to generate every path according to the data
Write the function to generate every path according to the data
JavaScript
mit
corehello/mathChart,corehello/mathChart
--- +++ @@ -1,7 +1,18 @@ +/* + mathChart.js + author: corehello(corehello@gmail.com) + data = + { + range : [[0,1],[2,3]]; + data : [[1,2],[2,3],...]; + } +*/ + + var mathChart = { var insertchart = function(canvas,data) { - var xmlns="https://www.w3.org/2000/svg" + var xmlns="https://www.w3.org/2000/svg"; var svg = document.createElementNS(xmlns,"svg"); svg.height = canvas.clientHeight; svg.width = canvas.clientWidth; @@ -13,8 +24,26 @@ canvas.appendChild(svg); }; - var generatePath(svg, data) + var generatePath = function(svg, data) { - + var paths=[] + for(i=0; i<data.data.length; ++i) + { + var dd = "" + if(i == 0) + { + dd = dd + "M "+ data.data[i].join(" "); + } + else + { + dd = dd + "L "+ data.data[i].join(" "); + } + path = document.createElementNS("xmlns","path"); + path.setAttribute("d", dd); + path.setAttribute("stroke", data.color); + path.setAttribute("stroke-width", data.width); + paths.push(path); + } + return paths; } }
dc43bff790323b658a4f7ccb129a6f164b8eef60
bin/deploy.js
bin/deploy.js
#!/usr/bin/env node const UI = require('console-ui'); const cli = require('cli'); const Project = require('../models/project'); const CommandFactory = require('../commands/command-factory'); const discovery = require('../tasks/discover'); const pkg = require('./package.json'); let options = cli.parse({ environment: [ 'e', 'A configured deployment environment, i.e. "staging", "production".', 'string', 'production'], verbose: ['v', 'Toggle verbosity', 'bool', false], revision: ['r', '("activate" only) revision to activate', 'string', false], activate: ['a', '("deploy" only) directly activate the deployed revision', 'bool', false] }, ['deploy', 'list', 'activate']); let ui = new UI({ inputStream: process.stdin, outputStream: process.stdout, writeLevel: 'INFO' }); ui.write('DeployJS CLI v' + pkg.version); let commandFactory = new CommandFactory(); discovery.list().then(function(dependencies) { let project = new Project(dependencies, ui); return commandFactory.run(cli.command, project, options); }).then(function() { ui.write('DeployJS done!'); }).catch(function(error) { console.log((error && error.message) ? '[ERROR] -- ' + error.message : error); process.exitCode = 1; });
#!/usr/bin/env node const UI = require('console-ui'); const cli = require('cli'); const Project = require('../models/project'); const CommandFactory = require('../commands/command-factory'); const discovery = require('../tasks/discover'); const pkg = require('../package.json'); let options = cli.parse({ environment: [ 'e', 'A configured deployment environment, i.e. "staging", "production".', 'string', 'production'], verbose: ['v', 'Toggle verbosity', 'bool', false], revision: ['r', '("activate" only) revision to activate', 'string', false], activate: ['a', '("deploy" only) directly activate the deployed revision', 'bool', false] }, ['deploy', 'list', 'activate']); let ui = new UI({ inputStream: process.stdin, outputStream: process.stdout, writeLevel: 'INFO' }); ui.write('DeployJS CLI v' + pkg.version); let commandFactory = new CommandFactory(); discovery.list().then(function(dependencies) { let project = new Project(dependencies, ui); return commandFactory.run(cli.command, project, options); }).then(function() { ui.write('DeployJS done!'); }).catch(function(error) { console.log((error && error.message) ? '[ERROR] -- ' + error.message : error); process.exitCode = 1; });
Fix wrong path for package.json
Fix wrong path for package.json
JavaScript
mit
deployjs/deployjs-cli
--- +++ @@ -8,7 +8,7 @@ const discovery = require('../tasks/discover'); -const pkg = require('./package.json'); +const pkg = require('../package.json'); let options = cli.parse({ environment: [ 'e', 'A configured deployment environment, i.e. "staging", "production".', 'string', 'production'],
0f70adee51fb89805952cf99bafb3d8ac0ffdea8
examples/rps/players/js-player.js
examples/rps/players/js-player.js
//initialize things globally if necessary var move = "rock"; function respond(command) { if(command === "move") return Math.random() < 0.5 ? "rock" : "paper"; else return "err"; }
//initialize things globally if necessary var move = "rock"; function respond(command) { if(command === "move") return Math.random() < 0.5 ? "rock" : "scissors"; else return "err"; }
Change jsplayer behavior for more natural ranking
Change jsplayer behavior for more natural ranking
JavaScript
mit
jacksondc/crane,jacksondc/crane,jacksondc/crane
--- +++ @@ -3,7 +3,7 @@ function respond(command) { if(command === "move") - return Math.random() < 0.5 ? "rock" : "paper"; + return Math.random() < 0.5 ? "rock" : "scissors"; else return "err"; }
b5f2976524bfe41893f5d288ea3fb73bfef33081
server/routes/index.js
server/routes/index.js
import userController from '../controllers/users'; import recipeController from '../controllers/recipes'; import Login from '../middleware/ensureLogin'; import User from '../middleware/isuser'; import recipeAdd from '../middleware/validateAddRecipe'; module.exports = (app) => { app.get('/api', (req, res) => res.status(200).send({ message: 'Welcome to the lamest API for now', })); app.post('/api/v1/users/signup', userController.signUp); app.post('/api/v1/users/signin', userController.signIn); app.post('/api/v1/recipes/testAdd', Login.ensureLogin, User.isuser, recipeAdd, recipeController.addRecipe); app.put('/api/v1/recipe/:recipeId', Login.ensureLogin, User.isuser, recipeAdd, recipeController.modifyRecipe); app.get('/api/v1/recipes', Login.ensureLogin, User.isuser, recipeController.getRecipes); };
import userController from '../controllers/users'; import recipeController from '../controllers/recipes'; import Login from '../middleware/ensureLogin'; import User from '../middleware/isuser'; import recipeAdd from '../middleware/validateAddRecipe'; module.exports = (app) => { app.get('/api', (req, res) => res.status(200).send({ message: 'Welcome to the lamest API for now', })); app.post('/api/v1/users/signup', userController.signUp); app.post('/api/v1/users/signin', userController.signIn); app.post('/api/v1/recipes/testAdd', Login.ensureLogin, User.isuser, recipeAdd, recipeController.addRecipe); app.put('/api/v1/recipe/:recipeId', Login.ensureLogin, User.isuser, recipeAdd, recipeController.modifyRecipe); app.get('/api/v1/recipes', recipeController.getRecipes); };
Add API that allows users to retreive all recipes in the application
Add API that allows users to retreive all recipes in the application
JavaScript
mit
Billmike/More-Recipes,Billmike/More-Recipes
--- +++ @@ -12,5 +12,5 @@ app.post('/api/v1/users/signin', userController.signIn); app.post('/api/v1/recipes/testAdd', Login.ensureLogin, User.isuser, recipeAdd, recipeController.addRecipe); app.put('/api/v1/recipe/:recipeId', Login.ensureLogin, User.isuser, recipeAdd, recipeController.modifyRecipe); - app.get('/api/v1/recipes', Login.ensureLogin, User.isuser, recipeController.getRecipes); + app.get('/api/v1/recipes', recipeController.getRecipes); };
849fd9cbdfa2dd1998ae2f6c9f2688bb6978a126
src/scenes/home/header/navDropdown/navDropdown.js
src/scenes/home/header/navDropdown/navDropdown.js
import React from 'react'; import PropTypes from 'prop-types'; import { withRouter } from 'react-router'; import classNames from 'classnames'; import NavItem from '../navItem/navItem'; import styles from './navDropdown.css'; function NavDropdown(props) { const classes = classNames({ [`${styles.child}`]: true, [`${styles.opaque}`]: !(props.location.pathname === '/') }); return ( <div className={styles.parent}> <NavItem text={`${props.text} ${''} ▾`} /> <ul className={styles.content}> {props.children.map(v => ( <li key={v.props.text} className={classes}> {v} </li> ))} </ul> </div> ); } NavDropdown.propTypes = { /* eslint-disable react/forbid-prop-types */ children: PropTypes.arrayOf(PropTypes.object).isRequired, text: PropTypes.string.isRequired, location: PropTypes.object.isRequired /* eslint-disable react/forbid-prop-types */ }; export default withRouter(NavDropdown);
import React from 'react'; import PropTypes from 'prop-types'; import { withRouter } from 'react-router'; import NavItem from '../navItem/navItem'; import styles from './navDropdown.css'; class NavDropdown extends React.Component { constructor(props) { super(props); this.state = { isDesktopScreenSize: true, }; this.updateWindowSize = this.updateWindowSize.bind(this); } componentDidMount() { this.updateWindowSize(); window.addEventListener('resize', this.updateWindowSize); } componentWillUnmount() { window.removeEventListener('resize', this.updateWindowSize); } updateWindowSize() { this.setState({ isDekstopScreenSize: window.innerWidth > 779 }); } // TODO: Utilize isDesktopScreenSize to render just the children so that the sideNav renders things properly without CSS Media Queries render() { return ( <div className={styles.parent}> <NavItem text={`${this.props.text} ${''} ▾`} /> <ul className={styles.content}> {this.props.children.map(v => ( <li key={v.props.text} className={styles.child}> {v} </li> ))} </ul> </div> ); } } NavDropdown.propTypes = { /* eslint-disable-rule react/forbid-prop-types */ children: PropTypes.arrayOf(PropTypes.object).isRequired, text: PropTypes.string.isRequired, /* eslint-disable-rule */ }; export default withRouter(NavDropdown);
Change component to class for state (see full msg)
Change component to class for state (see full msg) Instead of dealing with a CSS MediaQuery cluster bomb to unintuitively force styles, I decided that using local state on this component with windwo resizes to conditionally render drop-downs like drop-downs would be best. When the windows is less than 779px in width, we want the drop-down's to behave like regular nav items (ignore parent container name).
JavaScript
mit
OperationCode/operationcode_frontend,hollomancer/operationcode_frontend,sethbergman/operationcode_frontend,hollomancer/operationcode_frontend,miaket/operationcode_frontend,OperationCode/operationcode_frontend,sethbergman/operationcode_frontend,hollomancer/operationcode_frontend,NestorSegura/operationcode_frontend,miaket/operationcode_frontend,NestorSegura/operationcode_frontend,tskuse/operationcode_frontend,tal87/operationcode_frontend,miaket/operationcode_frontend,tal87/operationcode_frontend,tal87/operationcode_frontend,tskuse/operationcode_frontend,OperationCode/operationcode_frontend,NestorSegura/operationcode_frontend,sethbergman/operationcode_frontend,tskuse/operationcode_frontend
--- +++ @@ -1,36 +1,53 @@ import React from 'react'; import PropTypes from 'prop-types'; import { withRouter } from 'react-router'; -import classNames from 'classnames'; import NavItem from '../navItem/navItem'; import styles from './navDropdown.css'; -function NavDropdown(props) { - const classes = classNames({ - [`${styles.child}`]: true, - [`${styles.opaque}`]: !(props.location.pathname === '/') - }); +class NavDropdown extends React.Component { + constructor(props) { + super(props); + this.state = { + isDesktopScreenSize: true, + }; + this.updateWindowSize = this.updateWindowSize.bind(this); + } - return ( - <div className={styles.parent}> - <NavItem text={`${props.text} ${''} ▾`} /> - <ul className={styles.content}> - {props.children.map(v => ( - <li key={v.props.text} className={classes}> - {v} - </li> - ))} - </ul> - </div> - ); + componentDidMount() { + this.updateWindowSize(); + window.addEventListener('resize', this.updateWindowSize); + } + + componentWillUnmount() { + window.removeEventListener('resize', this.updateWindowSize); + } + + updateWindowSize() { + this.setState({ isDekstopScreenSize: window.innerWidth > 779 }); + } + + // TODO: Utilize isDesktopScreenSize to render just the children so that the sideNav renders things properly without CSS Media Queries + render() { + return ( + <div className={styles.parent}> + <NavItem text={`${this.props.text} ${''} ▾`} /> + <ul className={styles.content}> + {this.props.children.map(v => ( + <li key={v.props.text} className={styles.child}> + {v} + </li> + ))} + </ul> + </div> + ); + } } NavDropdown.propTypes = { - /* eslint-disable react/forbid-prop-types */ + /* eslint-disable-rule react/forbid-prop-types */ children: PropTypes.arrayOf(PropTypes.object).isRequired, text: PropTypes.string.isRequired, - location: PropTypes.object.isRequired - /* eslint-disable react/forbid-prop-types */ + /* eslint-disable-rule */ }; export default withRouter(NavDropdown);
5076878be6bade0457301d6128f30b59662eb75b
lib/require-in-context.js
lib/require-in-context.js
'use strict'; var Module = require('module') , wrap = Module.wrap , readFile = require('fs').readFileSync , dirname = require('path').dirname , vm = require('vm') , createContext = vm.createContext , runInContext = vm.runInContext , errorMsg = require('./is-module-not-found-error') , props = ['require', 'module', 'exports']; module.exports = function (path, context) { var fmodule, r, content, dirpath; console.log(context === global, path); if (context === global) { return require(path); } else { dirpath = dirname(path); fmodule = new Module(path, module); fmodule.filename = path; fmodule.paths = Module._nodeModulePaths(dirpath); try { content = readFile(path, 'utf8'); } catch (e) { throw new Error(errorMsg.pattern.replace(errorMsg.token, path)); } vm.runInContext(wrap(content), context).call(fmodule.exports, fmodule.exports, fmodule.require.bind(fmodule), fmodule, path, dirpath); fmodule.loaded = true; return fmodule.exports; } };
'use strict'; var Module = require('module') , wrap = Module.wrap , readFile = require('fs').readFileSync , dirname = require('path').dirname , vm = require('vm') , createContext = vm.createContext , runInContext = vm.runInContext , errorMsg = require('./is-module-not-found-error') , props = ['require', 'module', 'exports'] , modRequire = Module.prototype.require || function (path) { return Module._load(path, this); }; module.exports = function (path, context) { var fmodule, r, content, dirpath; if ((context === global) || (context.process && (context.process.title === 'node') && (context.pid === global.pid))) { return require(path); } else { dirpath = dirname(path); fmodule = new Module(path, module); fmodule.filename = path; fmodule.paths = Module._nodeModulePaths(dirpath); fmodule.require = modRequire; try { content = readFile(path, 'utf8'); } catch (e) { throw new Error(errorMsg.pattern.replace(errorMsg.token, path)); } vm.runInContext(wrap(content), context).call(fmodule.exports, fmodule.exports, fmodule.require.bind(fmodule), fmodule, path, dirpath); fmodule.loaded = true; return fmodule.exports; } };
Use regular require, when given context is same as current context
Use regular require, when given context is same as current context
JavaScript
mit
medikoo/node-ext
--- +++ @@ -9,18 +9,24 @@ , runInContext = vm.runInContext , errorMsg = require('./is-module-not-found-error') - , props = ['require', 'module', 'exports']; + , props = ['require', 'module', 'exports'] + , modRequire = Module.prototype.require || function (path) { + return Module._load(path, this); + }; module.exports = function (path, context) { var fmodule, r, content, dirpath; - console.log(context === global, path); - if (context === global) { + + if ((context === global) + || (context.process && (context.process.title === 'node') + && (context.pid === global.pid))) { return require(path); } else { dirpath = dirname(path); fmodule = new Module(path, module); fmodule.filename = path; fmodule.paths = Module._nodeModulePaths(dirpath); + fmodule.require = modRequire; try { content = readFile(path, 'utf8'); } catch (e) {
11b093cafe9b89050656b0dbb3337fa1f3bf4610
resources/assets/components/Empty/index.js
resources/assets/components/Empty/index.js
import React from 'react'; import './empty.scss'; const Empty = (props) => ( <div className="container empty"> <div className="empty__image" /> <div className="empty__text"> <h2 className="heading -gamma">{props.header}</h2> <span className="copy">{props.copy ? props.copy : null }</span> </div> </div> ); export default Empty;
import React from 'react'; import PropTypes from 'prop-types'; import './empty.scss'; const Empty = props => ( <div className="container empty"> <div className="empty__image" /> <div className="empty__text"> <h2 className="heading -gamma">{props.header}</h2> <span className="copy">{props.copy ? props.copy : null }</span> </div> </div> ); Empty.propTypes = { header: PropTypes.string, copy: PropTypes.string, }; Empty.defaultProps = { header: 'There are no results!', copy: 'Nothing to see here.', }; export default Empty;
Add proptype validation to Empty component
Add proptype validation to Empty component
JavaScript
mit
DoSomething/rogue,DoSomething/rogue,DoSomething/rogue
--- +++ @@ -1,7 +1,9 @@ import React from 'react'; +import PropTypes from 'prop-types'; + import './empty.scss'; -const Empty = (props) => ( +const Empty = props => ( <div className="container empty"> <div className="empty__image" /> <div className="empty__text"> @@ -11,5 +13,14 @@ </div> ); +Empty.propTypes = { + header: PropTypes.string, + copy: PropTypes.string, +}; + +Empty.defaultProps = { + header: 'There are no results!', + copy: 'Nothing to see here.', +}; export default Empty;
761b9cfb6eca9d57f65b32a683eb0f13dfcbc391
source/modules/guide/core/js/script.js
source/modules/guide/core/js/script.js
/* global hljs */ Wee.fn.make('guide', { /** * Highlight code and bind click events * * @constructor */ _construct: function() { var priv = this.$private; // Setup syntax highlighting priv.highlightCode(); // Bind code toggle and selection $('ref:code').on('dblclick', function() { priv.selectCode(this); }); } }, { /** * Load highlight.js assets and highlight code * * @private */ highlightCode: function() { Wee.assets.load({ root: 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.1.0/', files: [ 'highlight.min.js', 'styles/github.min.css' ], success: function() { hljs.initHighlightingOnLoad(); } }); }, /** * Select all content in a code block * * @private * @param {HTMLElement} el - target code wrapper */ selectCode: function(el) { var range = $._doc.createRange(), sel = $._win.getSelection(); range.selectNodeContents(el); sel.removeAllRanges(); sel.addRange(range); } });
/* global hljs */ Wee.fn.make('guide', { /** * Highlight code and bind click events * * @constructor */ _construct: function() { var priv = this.$private; // Setup syntax highlighting priv.highlightCode(); // Bind code toggle and selection $('ref:code').on('dblclick', function() { priv.selectCode(this); }); } }, { /** * Load highlight.js assets and highlight code * * @private */ highlightCode: function() { Wee.assets.load({ root: 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.2.0/', files: [ 'highlight.min.js', 'styles/github.min.css' ], success: function() { hljs.initHighlightingOnLoad(); } }); }, /** * Select all content in a code block * * @private * @param {HTMLElement} el - target code wrapper */ selectCode: function(el) { var range = $._doc.createRange(), sel = $._win.getSelection(); range.selectNodeContents(el); sel.removeAllRanges(); sel.addRange(range); } });
Update style guide highlight.js from 9.1.0 to 9.2.0
Update style guide highlight.js from 9.1.0 to 9.2.0
JavaScript
apache-2.0
weepower/wee,weepower/wee
--- +++ @@ -25,7 +25,7 @@ */ highlightCode: function() { Wee.assets.load({ - root: 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.1.0/', + root: 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.2.0/', files: [ 'highlight.min.js', 'styles/github.min.css'
4eeb008670002889814cffef1f180096032b9d05
resources/js/validators/customValidator.js
resources/js/validators/customValidator.js
wd.cdv.validators.registerValidator("custom", function(validation, rs){ var validationResult = wd.cdv.validationResult({ name: validation.validationName, type: validation.validationType }); var result = validation.validationFunction.call(this,rs,[]); if (typeof result == "object") { validationResult.setAlert(wd.cdv.alert(result)); } else { validationResult.setAlert(this.parseAlert(result)); print(JSON.stringify(validation)); print(result); switch(result){ case "OK": if(validation.successMessage) validationResult.getAlert().setDescription(validation.successMessage); break; case "CRITICAL": case "ERROR": case "WARNING": default: if(validation.failureMessage) validationResult.getAlert().setDescription(validation.failureMessage); break; } } return validationResult; });
wd.cdv.validators.registerValidator("custom", function(validation, rs){ var validationResult = wd.cdv.validationResult({ name: validation.validationName, type: validation.validationType }); var result = validation.validationFunction.call(this,rs,[]); if (typeof result == "object") { validationResult.setAlert(wd.cdv.alert(result)); } else { validationResult.setAlert(this.parseAlert(result)); switch(result){ case "OK": if(validation.successMessage) validationResult.getAlert().setDescription(validation.successMessage); break; case "CRITICAL": case "ERROR": case "WARNING": default: if(validation.failureMessage) validationResult.getAlert().setDescription(validation.failureMessage); break; } } return validationResult; });
Remove print calls from custom validator
Remove print calls from custom validator Browsers and server-side CDV seem to have a somewhat different idea of what 'print' means. Ooops.
JavaScript
mpl-2.0
pedrofvteixeira/cdv,pedrofvteixeira/cdv,webdetails/cdv,pedrofvteixeira/cdv,webdetails/cdv,webdetails/cdv
--- +++ @@ -10,8 +10,6 @@ validationResult.setAlert(wd.cdv.alert(result)); } else { validationResult.setAlert(this.parseAlert(result)); - print(JSON.stringify(validation)); - print(result); switch(result){ case "OK": if(validation.successMessage) validationResult.getAlert().setDescription(validation.successMessage);
cd06fbc2c9c8241e741b3e1ffc174372dff3669c
src/lib/responsive/setup_responsiveness.js
src/lib/responsive/setup_responsiveness.js
export default chart => { if (chart.responsive) { const { width, height } = chart // preserve original values chart._originWidth = width chart._originHeight = height // setup height calculation const heightRatio = height / width const xTicksRatio = chart.xTicks / width const yTicksRatio = chart.yTicks / height chart._getHeight = width => parseInt(width * heightRatio) // show at least two ticks chart._getXTicks = width => { const ticks = parseInt(width * xTicksRatio) return ticks < 2 ? 2 : ticks > chart.xTicks ? chart.xTicks : ticks } chart._getYTicks = width => { const ticks = parseInt(width * yTicksRatio) return ticks < 2 ? 2 : ticks > chart.yTicks ? chart.yTicks : ticks } // add event listener window.addEventListener('resize', () => { if (chart.updateDimensions(chart)) { chart.resize() } }) } }
export default chart => { if (chart.responsive) { const { width, height } = chart // preserve original values chart._originWidth = width chart._originHeight = height // setup height calculation const heightRatio = height / width const xTicksRatio = chart.xTicks / width const yTicksRatio = chart.yTicks / height chart._getHeight = width => parseInt(width * heightRatio) // show at least two ticks chart._getXTicks = width => { const ticks = parseInt(width * xTicksRatio) return ticks < 2 ? 2 : ticks > chart.xTicks ? chart.xTicks : ticks } chart._getYTicks = height => { const ticks = parseInt(width * yTicksRatio) return ticks < 2 ? 2 : ticks > chart.yTicks ? chart.yTicks : ticks } // add event listener window.addEventListener('resize', () => { if (chart.updateDimensions(chart)) { chart.resize() } }) } }
Fix computation of ticks for yAxis on responsive
Fix computation of ticks for yAxis on responsive
JavaScript
mit
simonwoerpel/d3-playbooks,simonwoerpel/d3-playbooks,simonwoerpel/d3-playbooks
--- +++ @@ -21,7 +21,7 @@ const ticks = parseInt(width * xTicksRatio) return ticks < 2 ? 2 : ticks > chart.xTicks ? chart.xTicks : ticks } - chart._getYTicks = width => { + chart._getYTicks = height => { const ticks = parseInt(width * yTicksRatio) return ticks < 2 ? 2 : ticks > chart.yTicks ? chart.yTicks : ticks }
98783e8c4fc67f5875c4be47c1706cedd1f3ee0e
src/OrthographicCamera.js
src/OrthographicCamera.js
'use strict'; let gl = require('./gl'); let glm = require('gl-matrix'); let mat4 = glm.mat4; let Camera = require('./Camera'); const _name = 'orthographic.camera'; const _left = -1; const _top = -1; const _near = 0.1; const _far = 1; class OrthographicCamera extends Camera { constructor({ name = _name, path, uniforms, background, left = _left, right, bottom, top = _top, near = _near, far = _far } = {}) { super({ name, path, uniforms, background }); this.left = left; this.right = right; this.bottom = bottom; this.top = top; this.near = near; this.far = far; this.inheritance = ['Entity', 'Structure', 'Camera', 'OrthographicCamera']; this.configure(); } configure() { super.configure(); mat4.ortho(this.projectionMatrix, this.left, this.right, this.bottom, this.top, this.near, this.far); mat4.identity(this.modelViewMatrix); } bind(program) { super.bind(program); gl.disable(gl.DEPTH_TEST); gl.viewport(this.left, this.top, this.right, this.bottom); } } module.exports = OrthographicCamera;
'use strict'; let gl = require('./gl'); let glm = require('gl-matrix'); let mat4 = glm.mat4; let Camera = require('./Camera'); const _name = 'orthographic.camera'; const _left = -1; const _bottom = -1; const _near = 0.1; const _far = 1; class OrthographicCamera extends Camera { constructor({ name = _name, path, uniforms, background, left = _left, right, bottom = _bottom, top, near = _near, far = _far } = {}) { super({ name, path, uniforms, background }); this.left = left; this.right = right; this.bottom = bottom; this.top = top; this.near = near; this.far = far; this.inheritance = ['Entity', 'Structure', 'Camera', 'OrthographicCamera']; this.configure(); } configure() { super.configure(); mat4.ortho(this.projectionMatrix, this.left, this.right, this.bottom, this.top, this.near, this.far); mat4.identity(this.modelViewMatrix); } bind(program) { super.bind(program); gl.disable(gl.DEPTH_TEST); gl.viewport(0, 0, this.right, this.top); } } module.exports = OrthographicCamera;
Fix orthographic camera usage of the glViewport method
Fix orthographic camera usage of the glViewport method
JavaScript
mit
allotrop3/four,allotrop3/four
--- +++ @@ -7,13 +7,13 @@ const _name = 'orthographic.camera'; const _left = -1; -const _top = -1; +const _bottom = -1; const _near = 0.1; const _far = 1; class OrthographicCamera extends Camera { - constructor({ name = _name, path, uniforms, background, left = _left, right, bottom, top = _top, near = _near, far = _far } = {}) + constructor({ name = _name, path, uniforms, background, left = _left, right, bottom = _bottom, top, near = _near, far = _far } = {}) { super({ name, path, uniforms, background }); @@ -47,7 +47,7 @@ super.bind(program); gl.disable(gl.DEPTH_TEST); - gl.viewport(this.left, this.top, this.right, this.bottom); + gl.viewport(0, 0, this.right, this.top); } }
0d7c4b7b6a2a9a72a2dca3fbd405097a9a7f180c
package/config/webpack.js
package/config/webpack.js
module.exports = { externals: { 'backbone': 'Backbone', 'backbone.babysitter': 'Backbone.ChildViewContainer', 'cocktail': 'Cocktail', 'jquery': 'jQuery', 'jquery-ui': 'jQuery', 'jquery.minicolors': 'jQuery', 'underscore': '_', 'backbone.marionette': 'Backbone.Marionette', 'iscroll': 'IScroll', 'wysihtml5': 'wysihtml5', 'videojs': 'videojs', } };
module.exports = { externals: { 'backbone': 'Backbone', 'backbone.babysitter': 'Backbone.ChildViewContainer', 'cocktail': 'Cocktail', 'jquery': 'jQuery', 'jquery-ui': 'jQuery', 'jquery.minicolors': 'jQuery', 'underscore': '_', 'backbone.marionette': 'Backbone.Marionette', 'iscroll': 'IScroll', 'wysihtml5': 'wysihtml5', 'videojs': 'videojs', }, // Webpack's chunk loading code references `window` by default - // which is not available in server side rendering context. // // https://github.com/webpack/webpack/blob/c9d4ff7b054fc581c96ce0e53432d44f9dd8ca72/lib/web/JsonpMainTemplatePlugin.js#L493 output: { globalObject: 'this' } };
Fix Webpack build for server side rendering
Fix Webpack build for server side rendering REDMINE-17566
JavaScript
mit
codevise/pageflow,codevise/pageflow,tf/pageflow,tf/pageflow,codevise/pageflow,tf/pageflow,tf/pageflow,codevise/pageflow
--- +++ @@ -11,5 +11,12 @@ 'iscroll': 'IScroll', 'wysihtml5': 'wysihtml5', 'videojs': 'videojs', + }, + // Webpack's chunk loading code references `window` by default - + // which is not available in server side rendering context. + // + // https://github.com/webpack/webpack/blob/c9d4ff7b054fc581c96ce0e53432d44f9dd8ca72/lib/web/JsonpMainTemplatePlugin.js#L493 + output: { + globalObject: 'this' } };
6bfc6f79e8272fb6e564b352dfb5bb858dd69c59
tests/karma.conf.js
tests/karma.conf.js
module.exports = config => { config.set({ frameworks: ['jasmine'], files: ['*.js'], preprocessors: { '*.js': ['webpack'], }, browsers: ['Chrome_fakeDevices'], plugins: [ 'karma-chrome-launcher', 'karma-webpack', 'karma-jasmine', ], webpack: { devtool: 'inline-source-map', }, customLaunchers: { Chrome_fakeDevices: { base: 'Chrome', flags: ['--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream', '--disable-popup-blocking'], }, }, webpackMiddleware: { noInfo: true, }, }); };
module.exports = config => { config.set({ frameworks: ['jasmine'], files: ['*.js'], preprocessors: { '*.js': ['webpack'], }, browsers: [process.env.BROWSER || 'chrome'], plugins: [ 'karma-chrome-launcher', 'karma-webpack', 'karma-jasmine', ], webpack: { devtool: 'inline-source-map', }, customLaunchers: { chrome: { base: 'Chrome', flags: ['--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream', '--disable-popup-blocking'], }, firefox: { base: 'Firefox', prefs: { 'media.navigator.permission.disabled': true, 'media.navigator.streams.fake': true, }, }, }, webpackMiddleware: { noInfo: true, }, }); };
Fix firefox launching from Karma
Fix firefox launching from Karma
JavaScript
mit
aullman/opentok-camera-filters,aullman/opentok-camera-filters
--- +++ @@ -8,7 +8,7 @@ '*.js': ['webpack'], }, - browsers: ['Chrome_fakeDevices'], + browsers: [process.env.BROWSER || 'chrome'], plugins: [ 'karma-chrome-launcher', @@ -21,10 +21,17 @@ }, customLaunchers: { - Chrome_fakeDevices: { + chrome: { base: 'Chrome', flags: ['--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream', '--disable-popup-blocking'], + }, + firefox: { + base: 'Firefox', + prefs: { + 'media.navigator.permission.disabled': true, + 'media.navigator.streams.fake': true, + }, }, },
ea6df9cde188a81998f4d4f9348c985db72a1e69
app/client/templates/posts/post_submit.js
app/client/templates/posts/post_submit.js
Template.postSubmit.events({ 'submit form': function(e) { e.preventDefault(); var post = { url: $(e.target).find('[name=url]').val(), title: $(e.target).find('[name=title]').val() }; post.slug = slugify(post.title); Meteor.call('postInsert', post, function(error, result) { // display the error to the user and abort if (error) return alert(error.reason); Router.go('postPage', {_id: result._id}); }); } });
Template.postSubmit.events({ 'submit form': function(e) { e.preventDefault(); var post = { url: $(e.target).find('[name=url]').val(), title: $(e.target).find('[name=title]').val() }; post.slug = slugify(post.title); Meteor.call('postInsert', post, function(error, result) { // show this result but route anyway if (result.postExists) alert('This link has already been posted'); Router.go('postPage', {_id: result._id}); }); } });
Set alert error instead of stopping
Set alert error instead of stopping
JavaScript
mit
drainpip/music-management-system,drainpip/music-management-system
--- +++ @@ -10,9 +10,9 @@ post.slug = slugify(post.title); Meteor.call('postInsert', post, function(error, result) { - // display the error to the user and abort - if (error) - return alert(error.reason); + // show this result but route anyway + if (result.postExists) + alert('This link has already been posted'); Router.go('postPage', {_id: result._id}); }); }
2800c236e28dafb46a0bd73ba0b2477345d7e2d3
packages/npm/spec/helpers-spec.js
packages/npm/spec/helpers-spec.js
'use babel' const { it } = require(process.env.SPEC_HELPER_SCRIPT) describe('versionFromRange', function() { })
'use babel' const { it } = require(process.env.SPEC_HELPER_SCRIPT) import { exists, versionFromRange } from '../lib/helpers' describe('exists', function() { it('works', async function() { expect(await exists(__filename)).toBe(true) expect(await exists('/tmp/non-existent-file')).toBe(false) }) }) describe('versionFromRange', function() { it('extracts a version from semver range', function() { const version = '^2.2.0' expect(versionFromRange(version)).toEqual(['2.2.0']) }) it('works even on complex ranges', function() { const version = '>=1.4.0 <2.0.0' expect(versionFromRange(version)).toEqual(['1.4.0', '2.0.0']) }) })
Add specs for exists and versionFromRange
:white_check_mark: Add specs for exists and versionFromRange
JavaScript
mpl-2.0
motion/motion,flintjs/flint,motion/motion,flintjs/flint,flintjs/flint
--- +++ @@ -1,7 +1,22 @@ 'use babel' const { it } = require(process.env.SPEC_HELPER_SCRIPT) +import { exists, versionFromRange } from '../lib/helpers' + +describe('exists', function() { + it('works', async function() { + expect(await exists(__filename)).toBe(true) + expect(await exists('/tmp/non-existent-file')).toBe(false) + }) +}) describe('versionFromRange', function() { - + it('extracts a version from semver range', function() { + const version = '^2.2.0' + expect(versionFromRange(version)).toEqual(['2.2.0']) + }) + it('works even on complex ranges', function() { + const version = '>=1.4.0 <2.0.0' + expect(versionFromRange(version)).toEqual(['1.4.0', '2.0.0']) + }) })
c567d818c3ee340fa34159f2997aa10838747bc6
src/civ5saveproperties.js
src/civ5saveproperties.js
export default { "fileSignature": { "byteOffset": 0, "length": 4, "previousProperty": null, "type": "fixedLengthString" }, "saveGameVersion": { "byteOffset": 4, "length": 4, "previousProperty": "fileSignature", "type": "int32" }, "gameVersion": { "byteOffset": 8, "length": null, "previousProperty": "saveGameVersion", "type": "variableLengthString" }, "gameBuild": { "byteOffset": null, "length": null, "previousProperty": "gameVersion", "type": "variableLengthString" } }
export default { "fileSignature": { "byteOffset": 0, "byteOffsetInSection": 0, "length": 4, "previousProperty": null, "section": 1, "sectionByBuild": { "4": 0 }, "type": "fixedLengthString" }, "saveGameVersion": { "byteOffset": 4, "byteOffsetInSection": 4, "length": 4, "previousProperty": "fileSignature", "section": 1, "sectionByBuild": { "4": 0 }, "type": "int32" }, "gameVersion": { "byteOffsetInSection": 8, "length": null, "previousProperty": "saveGameVersion", "section": 1, "sectionByBuild": { "341540": 0 }, "type": "variableLengthString" }, "gameBuild": { "byteOffsetInSection": null, "length": null, "previousProperty": "gameVersion", "section": 1, "sectionByBuild": { "341540": 0 }, "type": "variableLengthString" }, "section17Map": { "byteOffsetInSection": 275, "length": null, "previousProperty": null, "sectionByBuild": { "4": 17, "341540": 18, "395070": 19 }, "type": "variableLengthString" }, "section17Skip1": { "byteOffsetInSection": null, "length": 4, "previousProperty": "section17Map", "sectionByBuild": { "4": 17, "341540": 18, "395070": 19 }, "type": "variableLengthString" }, "maxTurns": { "byteOffsetInSection": null, "length": 2, "previousProperty": "section17Skip1", "sectionByBuild": { "4": 17, "341540": 18, "395070": 19 }, "type": "int16" } }
Add section information and section 17
Add section information and section 17
JavaScript
mit
bmaupin/js-civ5save
--- +++ @@ -1,26 +1,77 @@ export default { "fileSignature": { "byteOffset": 0, + "byteOffsetInSection": 0, "length": 4, "previousProperty": null, + "section": 1, + "sectionByBuild": { + "4": 0 + }, "type": "fixedLengthString" }, "saveGameVersion": { "byteOffset": 4, + "byteOffsetInSection": 4, "length": 4, "previousProperty": "fileSignature", + "section": 1, + "sectionByBuild": { + "4": 0 + }, "type": "int32" }, "gameVersion": { - "byteOffset": 8, - "length": null, + "byteOffsetInSection": 8, + "length": null, "previousProperty": "saveGameVersion", + "section": 1, + "sectionByBuild": { + "341540": 0 + }, "type": "variableLengthString" }, "gameBuild": { - "byteOffset": null, - "length": null, + "byteOffsetInSection": null, + "length": null, "previousProperty": "gameVersion", + "section": 1, + "sectionByBuild": { + "341540": 0 + }, "type": "variableLengthString" + }, + "section17Map": { + "byteOffsetInSection": 275, + "length": null, + "previousProperty": null, + "sectionByBuild": { + "4": 17, + "341540": 18, + "395070": 19 + }, + "type": "variableLengthString" + }, + "section17Skip1": { + "byteOffsetInSection": null, + "length": 4, + "previousProperty": "section17Map", + "sectionByBuild": { + "4": 17, + "341540": 18, + "395070": 19 + }, + "type": "variableLengthString" + }, + "maxTurns": { + "byteOffsetInSection": null, + "length": 2, + "previousProperty": "section17Skip1", + "sectionByBuild": { + "4": 17, + "341540": 18, + "395070": 19 + }, + "type": "int16" } }
42a9803fc2a316631b967b68b5ad3e12c8bb43bf
src/client/modules/map.js
src/client/modules/map.js
var regionStyle = { initial: { fill: '#000000', "fill-opacity": 1, stroke: 'none', "stroke-width": 0, "stroke-opacity": 1 }, hover: { "fill-opacity": 0.8, cursor: 'pointer' }, selected: { fill: 'yellow' } } var map = { init: function(){ return $('#map').vectorMap( { map: 'world_mill', backgroundColor:'#5f5f5f', regionStyle: regionStyle }); } } export default map;
var regionStyle = { initial: { fill: '#8f8f8f', "fill-opacity": 1, stroke: 'none', "stroke-width": 0, "stroke-opacity": 1 }, hover: { "fill-opacity": 0.8, cursor: 'pointer' }, selected: { fill: 'yellow' } } var map = { init: function(){ return $('#map').vectorMap( { map: 'world_mill', backgroundColor:'#5f5f5f', regionStyle: regionStyle }); } } export default map;
Change initial color to diferentiate from non-active countries to active countries
Change initial color to diferentiate from non-active countries to active countries
JavaScript
mit
ferflores/lightning,ferflores/lightning
--- +++ @@ -1,6 +1,6 @@ var regionStyle = { initial: { - fill: '#000000', + fill: '#8f8f8f', "fill-opacity": 1, stroke: 'none', "stroke-width": 0,
43ecb332c85edc585dae35d1c574c065da89ca43
gulp/plugins/gulp-sanitize-translations.js
gulp/plugins/gulp-sanitize-translations.js
var through = require( 'through2' ); var gutil = require( 'gulp-util' ); var PluginError = gutil.PluginError; var sanitize = require( 'sanitize-html' ); const PLUGIN_NAME = 'gulp-sanitize-translations.js'; module.exports = function( options ) { // Creating a stream through which each file will pass var stream = through.obj( function( file, enc, callback ) { if ( file.isBuffer() ) { var content = file.contents.toString(); var parsed = JSON.parse( content ); var lang = Object.keys( parsed )[0]; for ( var i in parsed[ lang ] ) { parsed[ lang ][ i ] = sanitize( parsed[ lang ][ i ] ); } file.contents = new Buffer( JSON.stringify( parsed ), 'utf-8' ); } // Streams not supported. else if ( file.isStream() ) { this.emit( 'error', new gutil.PluginError( PLUGIN_NAME, 'Streaming not supported.' ) ); return callback(); } // Anything else just falls through. this.push( file ); return callback(); } ); // returning the file stream return stream; };
var through = require( 'through2' ); var gutil = require( 'gulp-util' ); var PluginError = gutil.PluginError; var sanitize = require( 'sanitize-html' ); const PLUGIN_NAME = 'gulp-sanitize-translations.js'; module.exports = function( options ) { // Creating a stream through which each file will pass var stream = through.obj( function( file, enc, callback ) { if ( file.isBuffer() ) { var content = file.contents.toString(); var parsed = JSON.parse( content ); var lang = Object.keys( parsed )[0]; for ( var i in parsed[ lang ] ) { if ( Array.isArray( parsed[ lang ][ i ] ) ) { for ( var n in parsed[ lang ][ i ] ) { parsed[ lang ][ i ][ n ] = sanitize( parsed[ lang ][ i ][ n ] ); } } else { parsed[ lang ][ i ] = sanitize( parsed[ lang ][ i ] ); } } file.contents = new Buffer( JSON.stringify( parsed ), 'utf-8' ); } // Streams not supported. else if ( file.isStream() ) { this.emit( 'error', new gutil.PluginError( PLUGIN_NAME, 'Streaming not supported.' ) ); return callback(); } // Anything else just falls through. this.push( file ); return callback(); } ); // returning the file stream return stream; };
Fix translation sanitizing to work for plurals.
Fix translation sanitizing to work for plurals.
JavaScript
mit
gamejolt/frontend-lib,gamejolt/frontend-lib,gamejolt/frontend-lib,gamejolt/frontend-lib
--- +++ @@ -17,7 +17,15 @@ var lang = Object.keys( parsed )[0]; for ( var i in parsed[ lang ] ) { - parsed[ lang ][ i ] = sanitize( parsed[ lang ][ i ] ); + + if ( Array.isArray( parsed[ lang ][ i ] ) ) { + for ( var n in parsed[ lang ][ i ] ) { + parsed[ lang ][ i ][ n ] = sanitize( parsed[ lang ][ i ][ n ] ); + } + } + else { + parsed[ lang ][ i ] = sanitize( parsed[ lang ][ i ] ); + } } file.contents = new Buffer( JSON.stringify( parsed ), 'utf-8' );
4b0590961c42d151a0bc0fffd0afba23ded3c982
client/src/js/settings/selectors.js
client/src/js/settings/selectors.js
import { createSelector } from "reselect"; import { endsWith, flatMap, keys, map, max, pick } from "lodash-es"; import { taskDisplayNames } from "../utils"; const getMaximumTaskLimit = (limits, type) => ( max(map(limits, (value, key) => endsWith(key, type) ? value: 0 )) ); const taskLimitKeys = flatMap(keys(taskDisplayNames), name => [`${name}_proc`, `${name}_mem`]); const taskSpecificLimitSelector = state => pick(state.settings.data, taskLimitKeys); const resourcesSelector = state => state.jobs.resources; export const maxResourcesSelector = createSelector( [resourcesSelector], resources => { const procLimit = resources.proc.length; const memLimit = parseFloat((resources.mem.total / Math.pow(1024, 3)).toFixed(1)); return { procLimit, memLimit }; } ); export const minResourcesSelector = createSelector( [taskSpecificLimitSelector], (limits) => ({ proc: getMaximumTaskLimit(limits, "proc"), mem: getMaximumTaskLimit(limits, "mem") }) );
import { createSelector } from "reselect"; import { endsWith, flatMap, keys, map, max, pick } from "lodash-es"; import { taskDisplayNames } from "../utils"; const getMaximumTaskLimit = (limits, type) => ( max(map(limits, (value, key) => endsWith(key, type) ? value : 0 )) ); const taskLimitKeys = flatMap(keys(taskDisplayNames), name => [`${name}_proc`, `${name}_mem`]); const taskSpecificLimitSelector = state => pick(state.settings.data, taskLimitKeys); const resourcesSelector = state => state.jobs.resources; export const maxResourcesSelector = createSelector( [resourcesSelector], resources => { if (resources === null) { return { maxProc: 1, maxMem: 1 }; } const maxProc = resources.proc.length; const maxMem = Math.floor(resources.mem.total / Math.pow(1024, 3)); return { maxProc, maxMem }; } ); export const minResourcesSelector = createSelector( [taskSpecificLimitSelector], (limits) => ({ minProc: getMaximumTaskLimit(limits, "proc"), minMem: getMaximumTaskLimit(limits, "mem") }) );
Add reselect support for job limit values
Add reselect support for job limit values
JavaScript
mit
virtool/virtool,igboyes/virtool,igboyes/virtool,virtool/virtool
--- +++ @@ -5,7 +5,7 @@ const getMaximumTaskLimit = (limits, type) => ( max(map(limits, (value, key) => - endsWith(key, type) ? value: 0 + endsWith(key, type) ? value : 0 )) ); @@ -18,17 +18,24 @@ export const maxResourcesSelector = createSelector( [resourcesSelector], resources => { - const procLimit = resources.proc.length; - const memLimit = parseFloat((resources.mem.total / Math.pow(1024, 3)).toFixed(1)); + if (resources === null) { + return { + maxProc: 1, + maxMem: 1 + }; + } - return { procLimit, memLimit }; + const maxProc = resources.proc.length; + const maxMem = Math.floor(resources.mem.total / Math.pow(1024, 3)); + + return { maxProc, maxMem }; } ); export const minResourcesSelector = createSelector( [taskSpecificLimitSelector], (limits) => ({ - proc: getMaximumTaskLimit(limits, "proc"), - mem: getMaximumTaskLimit(limits, "mem") + minProc: getMaximumTaskLimit(limits, "proc"), + minMem: getMaximumTaskLimit(limits, "mem") }) );
6a9653aa0b63e3bd0483be3bd0f79a4ac1164085
src/js/controllers/listToMapLinkingController.js
src/js/controllers/listToMapLinkingController.js
"use strict"; let ListToMapLinkingController = function() { let self = {}; function mapMarkerSelected(data) { let parentDiv = $("#serviceList"); let dPanel = d3.selectAll(".serviceEntry") .filter((d) => d["Organization Name"] === data["Organization Name"]); let innerListItem = $(dPanel.nodes()); // parentDiv.animate({ // scrollTop: parentDiv.scrollTop() + (innerListItem.position().top - parentDiv.position().top) - parentDiv.height()/2 + innerListItem.height()/2 // }, 500); let expanded = !dPanel.selectAll(".collapse").classed("in"); data.expanded = expanded; d3.selectAll("#serviceList").selectAll(".serviceEntry").classed("opened", false); dPanel.classed("opened", expanded); // $(".serviceEntry.collapse").collapse("hide"); // $(".collapse", innerListItem).collapse(expanded ? "show" : "hide"); $(".panel-heading", innerListItem).trigger("click"); document.getElementById('serviceList').scrollTop = document.getElementById('serviceList').scrollTop + (innerListItem.position().top - parentDiv.position().top) - parentDiv.height()/2 + innerListItem.height()/2; App.views.map.setSelectedService(expanded ? data : null); } function listServiceSelected(data) { if (data.Latitude.length > 0 && data.Longitude.length > 0) App.views.map.setSelectedService(data); } return { mapMarkerSelected, listServiceSelected }; };
"use strict"; let ListToMapLinkingController = function() { let self = {}; function mapMarkerSelected(data) { let parentDiv = $("#serviceList"); let dPanel = d3.selectAll(".serviceEntry") .filter((d) => d["Organization Name"] === data["Organization Name"]); let innerListItem = $(dPanel.nodes()); // parentDiv.animate({ // scrollTop: parentDiv.scrollTop() + (innerListItem.position().top - parentDiv.position().top) - parentDiv.height()/2 + innerListItem.height()/2 // }, 500); let expanded = !dPanel.selectAll(".collapse").classed("in"); data.expanded = expanded; d3.selectAll("#serviceList").selectAll(".serviceEntry").classed("opened", false); dPanel.classed("opened", expanded); // $(".serviceEntry.collapse").collapse("hide"); // $(".collapse", innerListItem).collapse(expanded ? "show" : "hide"); $(".panel-heading", innerListItem).trigger("click"); document.getElementById('serviceList').scrollTop = document.getElementById('serviceList').scrollTop + (innerListItem.position().top - parentDiv.position().top) - parentDiv.height()/2 + innerListItem.height()/2; App.views.map.setSelectedService(expanded ? data : null); } function listServiceSelected(data) { if (!data || (data && data.Latitude.length > 0 && data.Longitude.length > 0)) App.views.map.setSelectedService(data); } return { mapMarkerSelected, listServiceSelected }; };
Add fix for collapsing services bug
Add fix for collapsing services bug
JavaScript
mit
AndrewTBurks/EnglewoodSocialServices,AndrewTBurks/EnglewoodSocialServices,uic-evl/EnglewoodSocialServices,uic-evl/EnglewoodSocialServices
--- +++ @@ -30,7 +30,7 @@ } function listServiceSelected(data) { - if (data.Latitude.length > 0 && data.Longitude.length > 0) + if (!data || (data && data.Latitude.length > 0 && data.Longitude.length > 0)) App.views.map.setSelectedService(data); }
e4e06bb7cbe3e33862b8031b41c2d32f97da8894
app/js/components/JobListing.js
app/js/components/JobListing.js
import { Component, PropTypes } from 'react' import {Link} from 'react-router' class JobListing extends Component { static propTypes: { title: PropTypes.string.isRequired, description: PropTypes.string.isRequired, url: PropTypes.string.isRequired } constructor(props) { super(props) } render() { return ( <div className="row m-b-1"> <div className="col-md-6"> {this.props.title} </div> <div className="col-md-6"> <Link to={this.props.url} target="_blank" className="btn btn-primary btn-sm"> Read More </Link> </div> </div> ) } } export default JobListing
import { Component, PropTypes } from 'react' import {Link} from 'react-router' class JobListing extends Component { static propTypes: { title: PropTypes.string.isRequired, description: PropTypes.string.isRequired, url: PropTypes.string.isRequired } constructor(props) { super(props) } render() { return ( <div className="row mb-3"> <div className="col-md-6"> {this.props.title} </div> <div className="col-md-6"> <Link to={this.props.url} target="_blank" className="btn btn-primary btn-sm"> Read More </Link> </div> </div> ) } } export default JobListing
Add margin between open job posting rows.
Add margin between open job posting rows.
JavaScript
mit
blockstack/blockstack-site,blockstack/blockstack-site
--- +++ @@ -14,7 +14,7 @@ render() { return ( - <div className="row m-b-1"> + <div className="row mb-3"> <div className="col-md-6"> {this.props.title} </div>
26ff7b3522980e5e49367f5d39c28910588ff3e2
src/mui/input/ImageInputPreview.js
src/mui/input/ImageInputPreview.js
import React, { PropTypes } from 'react'; import FlatButton from 'material-ui/FlatButton'; import { red600 } from 'material-ui/styles/colors'; import RemoveCircle from 'material-ui/svg-icons/content/remove-circle'; const styles = { container: { display: 'inline-block', position: 'relative', }, removeButton: { position: 'absolute', top: '0.5rem', right: '0.5rem', minWidth: '2rem', }, }; export const ImageInputPreview = ({ children, onRemove }) => ( <div style={styles.container}> <FlatButton style={styles.removeButton} icon={<RemoveCircle color={red600} />} onClick={onRemove} /> {children} </div> ); ImageInputPreview.propTypes = { children: PropTypes.element.isRequired, onRemove: PropTypes.func.isRequired, }; export default ImageInputPreview;
import React, { Component, PropTypes } from 'react'; import FlatButton from 'material-ui/FlatButton'; import { pinkA200 } from 'material-ui/styles/colors'; import RemoveCircle from 'material-ui/svg-icons/content/remove-circle'; const styles = { container: { display: 'inline-block', position: 'relative', }, removeButton: { position: 'absolute', top: '0.5rem', right: '0.5rem', minWidth: '2rem', opacity: 0, }, removeButtonHovered: { opacity: 1, }, }; export class ImageInputPreview extends Component { constructor(props) { super(props); this.state = { hovered: false, }; } onMouseOut = () => this.setState({ hovered: false }); onMouseOver = () => this.setState({ hovered: true }); render() { const { children, onRemove } = this.props; const removeButtonStyle = this.state.hovered ? { ...styles.removeButton, ...styles.removeButtonHovered, } : styles.removeButton; return ( <div onMouseOver={this.onMouseOver} onMouseOut={this.onMouseOut} style={styles.container} > <FlatButton style={removeButtonStyle} icon={<RemoveCircle color={pinkA200} />} onClick={onRemove} /> {children} </div> ); } } ImageInputPreview.propTypes = { children: PropTypes.element.isRequired, onRemove: PropTypes.func.isRequired, }; export default ImageInputPreview;
Improve design of image input preview delete button
Improve design of image input preview delete button
JavaScript
mit
matteolc/admin-on-rest,marmelab/admin-on-rest,matteolc/admin-on-rest,marmelab/admin-on-rest
--- +++ @@ -1,8 +1,7 @@ -import React, { PropTypes } from 'react'; +import React, { Component, PropTypes } from 'react'; import FlatButton from 'material-ui/FlatButton'; -import { red600 } from 'material-ui/styles/colors'; +import { pinkA200 } from 'material-ui/styles/colors'; import RemoveCircle from 'material-ui/svg-icons/content/remove-circle'; - const styles = { container: { @@ -14,19 +13,50 @@ top: '0.5rem', right: '0.5rem', minWidth: '2rem', + opacity: 0, + }, + removeButtonHovered: { + opacity: 1, }, }; -export const ImageInputPreview = ({ children, onRemove }) => ( - <div style={styles.container}> - <FlatButton - style={styles.removeButton} - icon={<RemoveCircle color={red600} />} - onClick={onRemove} - /> - {children} - </div> -); +export class ImageInputPreview extends Component { + constructor(props) { + super(props); + this.state = { + hovered: false, + }; + } + + onMouseOut = () => this.setState({ hovered: false }); + onMouseOver = () => this.setState({ hovered: true }); + + render() { + const { children, onRemove } = this.props; + + const removeButtonStyle = this.state.hovered ? { + ...styles.removeButton, + ...styles.removeButtonHovered, + } : styles.removeButton; + + return ( + <div + onMouseOver={this.onMouseOver} + onMouseOut={this.onMouseOut} + style={styles.container} + > + <FlatButton + style={removeButtonStyle} + icon={<RemoveCircle + color={pinkA200} + />} + onClick={onRemove} + /> + {children} + </div> + ); + } +} ImageInputPreview.propTypes = { children: PropTypes.element.isRequired,
2a903cbdc966f0cb23ad8b659d677fa061fc4819
tests/acceptance/specs/todos.spec.js
tests/acceptance/specs/todos.spec.js
import { expect } from 'chai'; import { addTodo } from './common.js'; describe('App', function() { beforeEach(function() { // TODO: refactor this using something like async.series return addTodo(browser, 'buy cheddar') .then(() => addTodo(browser, 'buy chorizo')) .then(() => addTodo(browser, 'buy bacon')); }); describe('todos', function() { it('should not be marked as completed after being added', function() { return browser.getAttribute('.todo .toggle', 'checked') .then(states => { expect(states).to.have.length(3); expect(states.every(state => state === true)).to.be.false; }); }); it('should be marked as completed when checking them', function() { return browser.element('.todo=buy chorizo') .element('.toggle').click() .then(() => browser.element('.todo=buy chorizo') .element('.toggle').getAttribute('checked')) .then(completed => { expect(completed).to.equal('true'); }); }); }); });
import { expect } from 'chai'; import { addTodo } from './common.js'; describe('App', function() { beforeEach(function() { // TODO: refactor this using something like async.series return addTodo(browser, 'buy cheddar') .then(() => addTodo(browser, 'buy chorizo')) .then(() => addTodo(browser, 'buy bacon')); }); describe('todos', function() { it('should not be marked as completed after being added', function() { return browser.getAttribute('.todo .toggle', 'checked') .then(states => { expect(states).to.have.length(3); expect(states.every(state => state === 'true')).to.be.false; }); }); it('should be marked as completed when checking them', function() { return browser.element('.todo=buy chorizo') .element('.toggle').click() .then(() => browser.element('.todo=buy chorizo') .element('.toggle').getAttribute('checked')) .then(completed => { expect(completed).to.equal('true'); }); }); }); });
Use string values for attributes in acceptance tests
Use string values for attributes in acceptance tests
JavaScript
mit
NiGhTTraX/react-test-buffet,NiGhTTraX/react-test-buffet,NiGhTTraX/react-test-buffet
--- +++ @@ -16,7 +16,7 @@ .then(states => { expect(states).to.have.length(3); - expect(states.every(state => state === true)).to.be.false; + expect(states.every(state => state === 'true')).to.be.false; }); });
ab581f23f246aa856d47170cde42aa3ba9b4008f
step-capstone/src/App.js
step-capstone/src/App.js
import React from 'react'; import './styles/App.css'; import TravelObject from './components/TravelObject' class App extends React.Component { render () { return( <div className="App"> <TravelObject type="flight" /> </div> ); } } export default App;
import React from 'react'; import './styles/App.css'; import TravelObject from './components/TravelObject' class App extends React.Component { constructor(props) { super(props); this.state = { data: [] } } fetchData() { return [ { finalized: true, type: "flight", departureAirport: "BOS", arrivalAirport: "SFO", departureDate: "4:00pm EST", arrivalDate: "7:00pm PST", description: "Additional notes" } ] } componentDidMount() { this.setState({ data: this.fetchData() }) } render() { if (this.state.data.length === 0) { return null; } return ( <div className="App"> <TravelObject data={this.state.data[0]} /> </div> ); } } export default App;
Add function to fetch data and fetch data when component is mounted
Add function to fetch data and fetch data when component is mounted
JavaScript
apache-2.0
googleinterns/step98-2020,googleinterns/step98-2020
--- +++ @@ -3,10 +3,43 @@ import TravelObject from './components/TravelObject' class App extends React.Component { - render () { - return( + constructor(props) { + super(props); + this.state = { + data: [] + } + } + + fetchData() { + return [ + { + finalized: true, + type: "flight", + departureAirport: "BOS", + arrivalAirport: "SFO", + departureDate: "4:00pm EST", + arrivalDate: "7:00pm PST", + description: "Additional notes" + } + ] + } + + componentDidMount() { + this.setState({ + data: this.fetchData() + }) + } + + render() { + if (this.state.data.length === 0) { + return null; + } + return ( <div className="App"> - <TravelObject type="flight" /> + + <TravelObject + data={this.state.data[0]} + /> </div> ); }
3233df80aaba2e7a81abbb68643854386f2bad7c
javascripts/init.js
javascripts/init.js
var animate; var Game = Game || {}; var WIDTH = window.innerWidth; var HEIGHT = window.innerHeight; var FPS = 1000 / 30; var engine = new Game.Engine('game', WIDTH, HEIGHT); engine.init(); engine.register(new Game.SnakeGame(WIDTH, HEIGHT, {})); // Use fallbacks for requestAnimationFrame animate = (window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function(callback) { window.setTimeout(callback, FPS); }); // Taken from Mozilla (function() { 'use strict'; function main() { Game.stopLoop = animate(main); engine.step(); } main(); })();
var animate; var Game = Game || {}; var WIDTH = window.innerWidth; var HEIGHT = window.innerHeight; var FPS = 1000 / 30; var engine = new Game.Engine('game', WIDTH, HEIGHT); engine.init(); engine.register(new Game.Snake(WIDTH, HEIGHT, {})); // Use fallbacks for requestAnimationFrame animate = (window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function(callback) { window.setTimeout(callback, FPS); }); // Taken from Mozilla (function() { 'use strict'; function main() { Game.stopLoop = animate(main); engine.step(); } main(); })();
Use new Snake object naming
Use new Snake object naming
JavaScript
mit
msanatan/snake,msanatan/snake,msanatan/snake
--- +++ @@ -6,7 +6,7 @@ var engine = new Game.Engine('game', WIDTH, HEIGHT); engine.init(); -engine.register(new Game.SnakeGame(WIDTH, HEIGHT, {})); +engine.register(new Game.Snake(WIDTH, HEIGHT, {})); // Use fallbacks for requestAnimationFrame animate = (window.requestAnimationFrame ||