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
b92cee6f761565f235dbd52bbcc60bf68fc4ffb8
src/core/initialize.js
src/core/initialize.js
goog.provide('webfont'); goog.require('webfont.UserAgentParser'); goog.require('webfont.FontModuleLoader'); goog.require('webfont.WebFont'); /** * @typedef {Object.<string, Array.<string>>} */ webfont.FontTestStrings; // Name of the global object. var globalName = 'WebFont'; // Provide an instance of WebFont in the global namespace. var globalNamespaceObject = window[globalName] = (function() { var userAgentParser = new webfont.UserAgentParser(navigator.userAgent, document); var userAgent = userAgentParser.parse(); var fontModuleLoader = new webfont.FontModuleLoader(); return new webfont.WebFont(window, fontModuleLoader, userAgent); })(); // Export the public API. globalNamespaceObject['load'] = globalNamespaceObject.load;
goog.provide('webfont'); goog.require('webfont.UserAgentParser'); goog.require('webfont.FontModuleLoader'); goog.require('webfont.WebFont'); /** * @typedef {Object.<string, Array.<string>>} */ webfont.FontTestStrings; /** * Name of the global object * * @define {string} */ var GLOBAL_NAME = 'WebFont'; // Provide an instance of WebFont in the global namespace. var globalNamespaceObject = window[GLOBAL_NAME] = (function() { var userAgentParser = new webfont.UserAgentParser(navigator.userAgent, document); var userAgent = userAgentParser.parse(); var fontModuleLoader = new webfont.FontModuleLoader(); return new webfont.WebFont(window, fontModuleLoader, userAgent); })(); // Export the public API. globalNamespaceObject['load'] = globalNamespaceObject.load;
Make the name of the global object configurable at compile-time.
Make the name of the global object configurable at compile-time.
JavaScript
apache-2.0
ramghaju/webfontloader,joelrich/webfontloader,JBusch/webfontloader,ahmadruhaifi/webfontloader,ramghaju/webfontloader,sapics/webfontloader,kevinrodbe/webfontloader,typekit/webfontloader,joelrich/webfontloader,exsodus3249/webfontloader,zeixcom/webfontloader,digideskio/webfontloader,Monotype/webfontloader,mettjus/webfontloader,exsodus3249/webfontloader,omo/webfontloader,typekit/webfontloader,zeixcom/webfontloader,JBusch/webfontloader,kevinrodbe/webfontloader,omo/webfontloader,ramghaju/webfontloader,armandocanals/webfontloader,digideskio/webfontloader,sapics/webfontloader,kevinrodbe/webfontloader,joelrich/webfontloader,ahmadruhaifi/webfontloader,mettjus/webfontloader,sapics/webfontloader,JBusch/webfontloader,typekit/webfontloader,Monotype/webfontloader,armandocanals/webfontloader,mettjus/webfontloader,ahmadruhaifi/webfontloader,digideskio/webfontloader,exsodus3249/webfontloader,Monotype/webfontloader,zeixcom/webfontloader,omo/webfontloader,armandocanals/webfontloader
--- +++ @@ -9,11 +9,15 @@ */ webfont.FontTestStrings; -// Name of the global object. -var globalName = 'WebFont'; +/** + * Name of the global object + * + * @define {string} + */ +var GLOBAL_NAME = 'WebFont'; // Provide an instance of WebFont in the global namespace. -var globalNamespaceObject = window[globalName] = (function() { +var globalNamespaceObject = window[GLOBAL_NAME] = (function() { var userAgentParser = new webfont.UserAgentParser(navigator.userAgent, document); var userAgent = userAgentParser.parse(); var fontModuleLoader = new webfont.FontModuleLoader();
0e99f53648cc0eb4401e34f7be4ef2334291ba89
libs/csv-jsonify.js
libs/csv-jsonify.js
var fs = require('fs'); var pkg = require('../package.json'); var debug = require('debug')(pkg.name); var csvParser = require('csv-parse'); exports.fromFile = jsonifyFromFile; function jsonifyFromFile(src, dist, callback, opts) { debug('Start formating src file %s', src); var results = []; var options = { delimiter: ',' }; var parser = csvParser(options, function(err, arr) { if (err) throw err; var separator = opts && opts.separator ? opts.separator : '|'; var defaultKeys = opts && opts.defaultKeys ? opts.defaultKeys : null; var keys = []; arr.forEach(function(item, index) { // The very first line is key line. if (index === 0) { keys = item; return; } var ret = {}; var heads = defaultKeys || keys; // code,name.en|name.zh-cn,nation heads.forEach(function(k, i) { if (k.indexOf(separator) === -1) { ret[k] = item[i]; return; } var subKeys = k.split(separator); var values = item[i].split(separator); subKeys.forEach(function(subkey, j){ if (subkey.indexOf('.') === -1) { ret[subkey] = values[j] return; } var subMasterKey = subkey.split('.')[0]; if (!ret[subMasterKey]) ret[subMasterKey] = {} ret[subMasterKey][subkey.split('.')[1]] = values[j]; }); }); results.push(ret); }); fs.writeFile( dist, JSON.stringify(results), callback || function() { debug('Formating done, writed %s', dist) } ); }); // Create a read stream fs.createReadStream(src).pipe(parser); }
Add lib and new function jsonifyFromFile
Add lib and new function jsonifyFromFile
JavaScript
mit
guo-yu/csv-jsonify,turingou/csv-jsonify
--- +++ @@ -0,0 +1,72 @@ +var fs = require('fs'); +var pkg = require('../package.json'); +var debug = require('debug')(pkg.name); +var csvParser = require('csv-parse'); + +exports.fromFile = jsonifyFromFile; + +function jsonifyFromFile(src, dist, callback, opts) { + debug('Start formating src file %s', src); + + var results = []; + var options = { + delimiter: ',' + }; + + var parser = csvParser(options, function(err, arr) { + if (err) + throw err; + + var separator = opts && opts.separator ? + opts.separator : '|'; + var defaultKeys = opts && opts.defaultKeys ? + opts.defaultKeys : null; + var keys = []; + + arr.forEach(function(item, index) { + // The very first line is key line. + if (index === 0) { + keys = item; + return; + } + + var ret = {}; + var heads = defaultKeys || keys; + + // code,name.en|name.zh-cn,nation + heads.forEach(function(k, i) { + if (k.indexOf(separator) === -1) { + ret[k] = item[i]; + return; + } + + var subKeys = k.split(separator); + var values = item[i].split(separator); + + subKeys.forEach(function(subkey, j){ + if (subkey.indexOf('.') === -1) { + ret[subkey] = values[j] + return; + } + + var subMasterKey = subkey.split('.')[0]; + if (!ret[subMasterKey]) + ret[subMasterKey] = {} + + ret[subMasterKey][subkey.split('.')[1]] = values[j]; + }); + }); + + results.push(ret); + }); + + fs.writeFile( + dist, + JSON.stringify(results), + callback || function() { debug('Formating done, writed %s', dist) } + ); + }); + + // Create a read stream + fs.createReadStream(src).pipe(parser); +}
06612f7ad9876b42329e72ff8247c509b6bf06f4
app/controllers/games/games.around_the_world.server.controller.js
app/controllers/games/games.around_the_world.server.controller.js
'use strict'; /** * Create the scoreboard. Each player starts out with a target of 20. * The only important number on the Around the World scoreboard is the player's * current target. */ var _ = require('lodash'); exports.createScoreboard = function() { var board = { player1_target: 20, player2_target: 20 }; return board; }; /** * Update the scoreboard with the results of the round. This function will * receive the round from the body of the request as well as the * stored game. */ exports.updateGameWithRound = function( round, game ) { var board = game.scoreboard; var thrower = (game.current_thrower.id === game.player1.id) ? 'player1' : 'player2'; var opponent = (game.current_thrower.id === game.player1.id) ? 'player2' : 'player1'; /* For each throw the possibilities are: 1. You did not hit your target. Do nothing 2. You hit your target. 1. You hit a single - go to the next number 2. You hit a double - skip a number 1. Can't skip the bull 3. You hit a triple - skip two numbers 1. Can't skip the bull */for (var index = 1; index <= _.size(round); index++) { var dart = round[index]; var scored = false; if (dart.number === board[thrower + '_target']) { // Hit our target scored = true; // Determine if this was a winning throw if (dart.number === 25) { game.winner = game.current_thrower; } // Figure out what we hit now and what we aim for next. if (dart.multiplier === 1) { if (board[thrower + '_target'] === 1) { board[thrower + '_target'] = 25; } else { board[thrower + '_target'] -= 1; } } else if (dart.multiplier === 2) { if (board[thrower + '_target'] <= 2) { board[thrower + '_target'] = 25; } else { board[thrower + '_target'] -= 2; } } else { // Hit a triple if (board[thrower + '_target'] <= 3) { board[thrower + '_target'] = 25; } else { board[thrower + '_target'] -= 3; } } round[index] = { order: index, target: dart.number, multiplier: dart.multiplier, score: scored, close: scored }; } else { // Missed the target // Log analytics data round[index] = { order: index, target: dart.number, multiplier: dart.multiplier, score: false, close: false }; } } return game; };
Create basic server logic for around the world.
Create basic server logic for around the world.
JavaScript
mit
camuthig/dart_slinger_nodejs,camuthig/dart_slinger_nodejs,camuthig/dart_slinger_nodejs,camuthig/dart_slinger_nodejs
--- +++ @@ -0,0 +1,97 @@ +'use strict'; +/** + * Create the scoreboard. Each player starts out with a target of 20. + * The only important number on the Around the World scoreboard is the player's + * current target. + */ +var _ = require('lodash'); + +exports.createScoreboard = function() { + var board = { + player1_target: 20, + player2_target: 20 + }; + return board; +}; + +/** + * Update the scoreboard with the results of the round. This function will + * receive the round from the body of the request as well as the + * stored game. + */ +exports.updateGameWithRound = function( round, game ) { + var board = game.scoreboard; + var thrower = (game.current_thrower.id === game.player1.id) ? 'player1' : 'player2'; + var opponent = (game.current_thrower.id === game.player1.id) ? 'player2' : 'player1'; + + /* + For each throw the possibilities are: + 1. You did not hit your target. Do nothing + 2. You hit your target. + 1. You hit a single - go to the next number + 2. You hit a double - skip a number + 1. Can't skip the bull + 3. You hit a triple - skip two numbers + 1. Can't skip the bull + */for (var index = 1; index <= _.size(round); index++) { + var dart = round[index]; + var scored = false; + if (dart.number === board[thrower + '_target']) { + // Hit our target + scored = true; + + // Determine if this was a winning throw + if (dart.number === 25) { + game.winner = game.current_thrower; + } + + // Figure out what we hit now and what we aim for next. + if (dart.multiplier === 1) { + if (board[thrower + '_target'] === 1) { + board[thrower + '_target'] = 25; + } + else { + board[thrower + '_target'] -= 1; + } + } + else if (dart.multiplier === 2) { + if (board[thrower + '_target'] <= 2) { + board[thrower + '_target'] = 25; + } + else { + board[thrower + '_target'] -= 2; + } + } + else { + // Hit a triple + if (board[thrower + '_target'] <= 3) { + board[thrower + '_target'] = 25; + } + else { + board[thrower + '_target'] -= 3; + } + } + round[index] = { + order: index, + target: dart.number, + multiplier: dart.multiplier, + score: scored, + close: scored + }; + } + else { + // Missed the target + // Log analytics data + round[index] = { + order: index, + target: dart.number, + multiplier: dart.multiplier, + score: false, + close: false + }; + } + + } + + return game; +};
570ad9987bb63a3d5e06db5c453c439009bf02fd
packages/rocketchat-api/server/helpers/deprecationWarning.js
packages/rocketchat-api/server/helpers/deprecationWarning.js
RocketChat.API.helperMethods.set('deprecationWarning', function _deprecationWarning({ endpoint, versionWillBeRemove, response }) { const warningMessage = `The endpoint ${ endpoint } is deprecated and will be removed after version ${ versionWillBeRemove }`; console.warn(warningMessage); if (process.env.NODE_ENV === 'development') { response.warning = warningMessage; } return response; });
RocketChat.API.helperMethods.set('deprecationWarning', function _deprecationWarning({ endpoint, versionWillBeRemove, response }) { const warningMessage = `The endpoint "${ endpoint }" is deprecated and will be removed after version ${ versionWillBeRemove }`; console.warn(warningMessage); if (process.env.NODE_ENV === 'development') { response.warning = warningMessage; } return response; });
Add quotes in the endpoint deprecation warning
Add quotes in the endpoint deprecation warning
JavaScript
mit
inoio/Rocket.Chat,subesokun/Rocket.Chat,pitamar/Rocket.Chat,fatihwk/Rocket.Chat,pkgodara/Rocket.Chat,VoiSmart/Rocket.Chat,subesokun/Rocket.Chat,pitamar/Rocket.Chat,flaviogrossi/Rocket.Chat,nishimaki10/Rocket.Chat,4thParty/Rocket.Chat,fatihwk/Rocket.Chat,4thParty/Rocket.Chat,VoiSmart/Rocket.Chat,Sing-Li/Rocket.Chat,Sing-Li/Rocket.Chat,subesokun/Rocket.Chat,nishimaki10/Rocket.Chat,galrotem1993/Rocket.Chat,flaviogrossi/Rocket.Chat,Sing-Li/Rocket.Chat,inoio/Rocket.Chat,Sing-Li/Rocket.Chat,subesokun/Rocket.Chat,inoio/Rocket.Chat,pkgodara/Rocket.Chat,4thParty/Rocket.Chat,4thParty/Rocket.Chat,pitamar/Rocket.Chat,nishimaki10/Rocket.Chat,pkgodara/Rocket.Chat,pitamar/Rocket.Chat,flaviogrossi/Rocket.Chat,VoiSmart/Rocket.Chat,galrotem1993/Rocket.Chat,flaviogrossi/Rocket.Chat,fatihwk/Rocket.Chat,galrotem1993/Rocket.Chat,galrotem1993/Rocket.Chat,nishimaki10/Rocket.Chat,pkgodara/Rocket.Chat,fatihwk/Rocket.Chat
--- +++ @@ -1,5 +1,5 @@ RocketChat.API.helperMethods.set('deprecationWarning', function _deprecationWarning({ endpoint, versionWillBeRemove, response }) { - const warningMessage = `The endpoint ${ endpoint } is deprecated and will be removed after version ${ versionWillBeRemove }`; + const warningMessage = `The endpoint "${ endpoint }" is deprecated and will be removed after version ${ versionWillBeRemove }`; console.warn(warningMessage); if (process.env.NODE_ENV === 'development') { response.warning = warningMessage;
1b9f2e6b6eec520b53ba5a46b56fc70ece874b0f
routes/jsonRoute.js
routes/jsonRoute.js
var express = require('express'); var router = express.Router(); var problemsFile = require('../json/problems.json'); var usersFile = require('../json/users.json'); module.exports = function(app, mountPoint) { router.get('/problems', function(req, res) { res.json(problemsFile); }); router.get('/users', function(req, res) { res.json(usersFile); }); app.use(mountPoint, router); }
Add route for test json file
Add route for test json file
JavaScript
mpl-2.0
in-silico/judge-frontend,in-silico/judge-frontend
--- +++ @@ -0,0 +1,14 @@ +var express = require('express'); +var router = express.Router(); +var problemsFile = require('../json/problems.json'); +var usersFile = require('../json/users.json'); + +module.exports = function(app, mountPoint) { + router.get('/problems', function(req, res) { + res.json(problemsFile); + }); + router.get('/users', function(req, res) { + res.json(usersFile); + }); + app.use(mountPoint, router); +}
ceb348594e500ba920d887b833c7a53985379291
test/variable.js
test/variable.js
var expect = require("chai").expect, netcdf4 = require("../build/Release/netcdf4.node"); describe('Variable', function() { it('should read a slice', function() { var file = new netcdf4.File("test/testrh.nc", "r"); var results = Array.from(file.root.variables.var1.readSlice(0, 4)); expect(results).to.deep.equal([420, 197, 391.5, 399]); }); it('should read a strided slice', function() { var file = new netcdf4.File("test/testrh.nc", "r"); var results = Array.from(file.root.variables.var1.readStridedSlice(0, 2, 2)); expect(results).to.deep.equal([420, 391.5]); }); });
Add unit tests for readSlice(), readStridedSlice()
Add unit tests for readSlice(), readStridedSlice()
JavaScript
isc
swillner/netcdf4-js,swillner/netcdf4-js,swillner/netcdf4-js
--- +++ @@ -0,0 +1,16 @@ +var expect = require("chai").expect, + netcdf4 = require("../build/Release/netcdf4.node"); + +describe('Variable', function() { + it('should read a slice', function() { + var file = new netcdf4.File("test/testrh.nc", "r"); + var results = Array.from(file.root.variables.var1.readSlice(0, 4)); + expect(results).to.deep.equal([420, 197, 391.5, 399]); + }); + + it('should read a strided slice', function() { + var file = new netcdf4.File("test/testrh.nc", "r"); + var results = Array.from(file.root.variables.var1.readStridedSlice(0, 2, 2)); + expect(results).to.deep.equal([420, 391.5]); + }); +});
48a00dfae513a3f37cb5d5890b7eb1114db50c26
test/test-connect-non-existing-db.js
test/test-connect-non-existing-db.js
var test = require('tape') var mongojs = require('../') test('connect non existing db', function (t) { var db = mongojs('mongodb://1.0.0.1:23/aiguillage?connectTimeoutMS=100', ['a']) db.runCommand({ping: 1}, function (err) { t.ok(err, 'Should yield an error if non connection to db could be established') db.runCommand({ping: 1}, function (err) { t.ok(err, 'Should yield an error if non connection to db could be established') t.end() }) }) })
Add test to verify that connecting to a non existing database yields an error in the provided operation callback
Add test to verify that connecting to a non existing database yields an error in the provided operation callback
JavaScript
mit
mafintosh/mongojs,lionvs/mongojs,octoblu/mongojs
--- +++ @@ -0,0 +1,16 @@ +var test = require('tape') +var mongojs = require('../') + +test('connect non existing db', function (t) { + var db = mongojs('mongodb://1.0.0.1:23/aiguillage?connectTimeoutMS=100', ['a']) + + db.runCommand({ping: 1}, function (err) { + t.ok(err, 'Should yield an error if non connection to db could be established') + + db.runCommand({ping: 1}, function (err) { + t.ok(err, 'Should yield an error if non connection to db could be established') + + t.end() + }) + }) +})
0ad41500dda4f34c0d53cda6706234559ebbc446
src/layers.js
src/layers.js
"use strict"; var layers = {}; layers.emptyData = { "type": "FeatureCollection", "features": [] }; // Cutouts layer layers.addCutouts = function(map) { map.addSource("cutouts", { "type": "geojson", "data": layers.emptyData }); map.addLayer({ "id": "cutouts-outline", "type": "line", "source": "cutouts", "layout": { "line-join": "round" }, "paint": { "line-color": "#ffcocb", "line-width": 8, "line-opacity": 0.6 } }); map.addLayer({ "id": "cutouts-fill", "type": "fill", "source": "cutouts", "paint": { "fill-opacity": 0 } }); }; // Track layer layers.addTrack = function(map) { map.addSource('track', { "type": 'geojson', "data": layers.emptyData }); map.addLayer({ "id": "track", "type": "line", "source": "track", "layout": { "line-join": "round", "line-cap": "round" }, "paint": { "line-color": "#888888", "line-width": 8, "line-opacity": 0.6, }, }); }; // Milemarkers layers.addMilemarkers = function(map) { map.addSource('milemarkers', { "type": "geojson", "data": layers.emptyData }); map.addLayer({ "id": "milemarkers", "type": "symbol", "source": "milemarkers", "layout": { "icon-image": "marker-11", "text-field": "{title}km", "text-font": ["Open Sans Semibold", "Arial Unicode MS Bold"], "text-offset": [0, 0], "text-anchor": "bottom" } }); }; export default layers;
Refactor layer stuff in own module
Refactor layer stuff in own module
JavaScript
agpl-3.0
sgelb/mapline,sgelb/mapline,sgelb/mapline
--- +++ @@ -0,0 +1,86 @@ +"use strict"; + +var layers = {}; + +layers.emptyData = { + "type": "FeatureCollection", + "features": [] +}; + +// Cutouts layer +layers.addCutouts = function(map) { + map.addSource("cutouts", { + "type": "geojson", + "data": layers.emptyData + }); + + map.addLayer({ + "id": "cutouts-outline", + "type": "line", + "source": "cutouts", + "layout": { + "line-join": "round" + }, + "paint": { + "line-color": "#ffcocb", + "line-width": 8, + "line-opacity": 0.6 + } + }); + + map.addLayer({ + "id": "cutouts-fill", + "type": "fill", + "source": "cutouts", + "paint": { + "fill-opacity": 0 + } + }); +}; + +// Track layer +layers.addTrack = function(map) { + map.addSource('track', { + "type": 'geojson', + "data": layers.emptyData + }); + + map.addLayer({ + "id": "track", + "type": "line", + "source": "track", + "layout": { + "line-join": "round", + "line-cap": "round" + }, + "paint": { + "line-color": "#888888", + "line-width": 8, + "line-opacity": 0.6, + }, + }); +}; + +// Milemarkers +layers.addMilemarkers = function(map) { + map.addSource('milemarkers', { + "type": "geojson", + "data": layers.emptyData + }); + + map.addLayer({ + "id": "milemarkers", + "type": "symbol", + "source": "milemarkers", + "layout": { + "icon-image": "marker-11", + "text-field": "{title}km", + "text-font": ["Open Sans Semibold", "Arial Unicode MS Bold"], + "text-offset": [0, 0], + "text-anchor": "bottom" + } + }); + +}; + +export default layers;
6e3a476f9233db96aa5ee636fe22acfc42d7bd6f
8/crypto_randomBytes-base64-substr.js
8/crypto_randomBytes-base64-substr.js
var crypto = require('crypto'); var buf = crypto.randomBytes(16); var cut_bufhex = buf.toString('base64').substr(0, 8); console.log('Have %d bytes of random string by base64: ', cut_bufhex.length, cut_bufhex);
Add the example to create random 8 bytes with base64.
Add the example to create random 8 bytes with base64.
JavaScript
mit
nicebook/Node.js-Reference,nicebook/Node.js-Reference,nicebook/Node.js-Reference
--- +++ @@ -0,0 +1,5 @@ +var crypto = require('crypto'); + +var buf = crypto.randomBytes(16); +var cut_bufhex = buf.toString('base64').substr(0, 8); +console.log('Have %d bytes of random string by base64: ', cut_bufhex.length, cut_bufhex);
2b8e1c0b11c9245886abf9aa0a990c4f5db0c213
book.js
book.js
var pkg = require('./package.json'); module.exports = { root: './docs', plugins: ['versions'], pluginsConfig: { versions: { type: 'tags' } }, variables: { version: pkg.version } };
Add configuration for inner docs
Add configuration for inner docs
JavaScript
apache-2.0
tshoper/gitbook,gencer/gitbook,strawluffy/gitbook,ryanswanson/gitbook,gencer/gitbook,tshoper/gitbook,GitbookIO/gitbook
--- +++ @@ -0,0 +1,14 @@ +var pkg = require('./package.json'); + +module.exports = { + root: './docs', + plugins: ['versions'], + pluginsConfig: { + versions: { + type: 'tags' + } + }, + variables: { + version: pkg.version + } +};
2b6029f646cde2846b714c955a6338daf47010ce
shop.js
shop.js
var Hapi = require('hapi'); var server = new Hapi.Server(); server.connection({ port: 8080 }); server.start(function (err) { console.log('Server started at: ' + server.info.uri); });
Add most basic hapi.js server possible
Add most basic hapi.js server possible
JavaScript
bsd-2-clause
accosine/Kwik-E-Mart,accosine/Kwik-E-Mart
--- +++ @@ -0,0 +1,11 @@ +var Hapi = require('hapi'); + +var server = new Hapi.Server(); + +server.connection({ + port: 8080 +}); + +server.start(function (err) { + console.log('Server started at: ' + server.info.uri); +});
478b2ca5ce0707981f7295094f0089444fdce60b
file-upload-s3-stream.js
file-upload-s3-stream.js
var http = require('http'); var router = require('routes')(); var Busboy = require('busboy'); var AWS = require('aws-sdk'); var inspect = require('util').inspect; var port = 5000; // Define s3-upload-stream with S3 credentials. var s3Stream = require('s3-upload-stream')(new AWS.S3({ accessKeyId: '', secretAccessKey: '' })); // Handle uploading file to Amazon S3. // Uses the multipart file upload API. function uploadS3 (readStream, key, callback) { var upload = s3Stream.upload({ 'Bucket': '', 'Key': key }); // Handle errors. upload.on('error', function (err) { callback(err); }); // Handle progress. upload.on('part', function (details) { console.log(inspect(details)); }); // Handle upload completion. upload.on('uploaded', function (details) { callback(); }); // Pipe the Readable stream to the s3-upload-stream module. readStream.pipe(upload); } // Define our route for uploading files router.addRoute('/images', function (req, res, params) { if (req.method === 'POST') { // Create an Busyboy instance passing the HTTP Request headers. var busboy = new Busboy({ headers: req.headers }); // Listen for event when Busboy finds a file to stream. busboy.on('file', function (fieldname, file, filename, encoding, mimetype) { // Handle uploading file to Amazon S3. // We are passing 'file' which is a ReadableStream, // 'filename' which is the name of the file // and a callback function to handle success/error. uploadS3(file, filename, function (err) { if (err) { res.statusCode = 500; res.end(err); } else { res.statusCode = 200; res.end('ok'); } }); }); // Pipe the HTTP Request into Busboy. req.pipe(busboy); } }); var server = http.createServer(function (req, res) { // Check if the HTTP Request URL matches on of our routes. var match = router.match(req.url); // We have a match! if (match) match.fn(req, res, match.params); }); server.listen(port, function () { console.log('Listening on port ' + port); });
Add uploading file stream to s3
Add uploading file stream to s3
JavaScript
mit
voidabhi/node-scripts,voidabhi/node-scripts,voidabhi/node-scripts
--- +++ @@ -0,0 +1,84 @@ + +var http = require('http'); +var router = require('routes')(); +var Busboy = require('busboy'); +var AWS = require('aws-sdk'); +var inspect = require('util').inspect; +var port = 5000; + +// Define s3-upload-stream with S3 credentials. +var s3Stream = require('s3-upload-stream')(new AWS.S3({ + accessKeyId: '', + secretAccessKey: '' +})); + +// Handle uploading file to Amazon S3. +// Uses the multipart file upload API. +function uploadS3 (readStream, key, callback) { + var upload = s3Stream.upload({ + 'Bucket': '', + 'Key': key + }); + + // Handle errors. + upload.on('error', function (err) { + callback(err); + }); + + // Handle progress. + upload.on('part', function (details) { + console.log(inspect(details)); + }); + + // Handle upload completion. + upload.on('uploaded', function (details) { + callback(); + }); + + // Pipe the Readable stream to the s3-upload-stream module. + readStream.pipe(upload); +} + + +// Define our route for uploading files +router.addRoute('/images', function (req, res, params) { + if (req.method === 'POST') { + + // Create an Busyboy instance passing the HTTP Request headers. + var busboy = new Busboy({ headers: req.headers }); + + // Listen for event when Busboy finds a file to stream. + busboy.on('file', function (fieldname, file, filename, encoding, mimetype) { + + // Handle uploading file to Amazon S3. + // We are passing 'file' which is a ReadableStream, + // 'filename' which is the name of the file + // and a callback function to handle success/error. + uploadS3(file, filename, function (err) { + if (err) { + res.statusCode = 500; + res.end(err); + } else { + res.statusCode = 200; + res.end('ok'); + } + }); + }); + + // Pipe the HTTP Request into Busboy. + req.pipe(busboy); + } +}); + +var server = http.createServer(function (req, res) { + + // Check if the HTTP Request URL matches on of our routes. + var match = router.match(req.url); + + // We have a match! + if (match) match.fn(req, res, match.params); +}); + +server.listen(port, function () { + console.log('Listening on port ' + port); +});
e19235838da0aff961c8f0bfbe12baf0c3c04391
test/unit/client/callback-on-early-disconnect.js
test/unit/client/callback-on-early-disconnect.js
var helper = require(__dirname + '/test-helper'); var net = require('net'); var pg = require('../../..//lib/index.js'); var server = net.createServer(function(c) { console.log('server connected'); c.destroy(); console.log('server socket destroyed.'); server.close(function() { console.log('server closed'); }); }); server.listen(7777, function() { console.log('server listening'); var client = new pg.Client('postgres://localhost:7777'); console.log('client connecting'); client.connect(assert.calls(function(err) { if (err) console.log("Error on connect: "+err); else console.log('client connected'); assert(err); })); });
Add unit test for callback on early postgresql disconnect
Add unit test for callback on early postgresql disconnect Test adapted by that provided by Jess Sheneberger in #534
JavaScript
mit
brianc/node-postgres,brianc/node-postgres,cricri/node-postgres
--- +++ @@ -0,0 +1,22 @@ +var helper = require(__dirname + '/test-helper'); +var net = require('net'); +var pg = require('../../..//lib/index.js'); + +var server = net.createServer(function(c) { + console.log('server connected'); + c.destroy(); + console.log('server socket destroyed.'); + server.close(function() { console.log('server closed'); }); +}); + +server.listen(7777, function() { + console.log('server listening'); + var client = new pg.Client('postgres://localhost:7777'); + console.log('client connecting'); + client.connect(assert.calls(function(err) { + if (err) console.log("Error on connect: "+err); + else console.log('client connected'); + assert(err); + })); + +});
d2ec2d5c2a9c56b243187a743c49dbb25e65fdf9
examples/context.js
examples/context.js
var aopify = require('../lib/index.js'); // aopify and change the return value to -2 when it would have been -1 // This demonstrates applying advice within the context of an instance. // Obviously don't do this in production. String.prototype.indexOf = aopify(String.prototype.indexOf); String.prototype.indexOf.around = function(options) { var index = options.proceed.apply(this, options.args); return index === -1 ? -2 : index; }; // Examples borrowed from Mozilla // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf console.log('Blue Whale'.indexOf('Blue')); console.log('Blue Whale'.indexOf('Blute')); console.log('Blue Whale'.indexOf('Whale', 0)); console.log('Blue Whale'.indexOf('Whale', 5)); console.log('Blue Whale'.indexOf('Banana', 7)); console.log('Blue Whale'.indexOf('', 9)); console.log('Blue Whale'.indexOf('', 10)); console.log('Blue Whale'.indexOf('', 11)); // Output: // // 0 // -2 // 5 // 5 // -2 // 9 // 10 // 10
Add example showing advice with instance functions
Add example showing advice with instance functions
JavaScript
mit
lehmier/aopify
--- +++ @@ -0,0 +1,32 @@ +var aopify = require('../lib/index.js'); + +// aopify and change the return value to -2 when it would have been -1 +// This demonstrates applying advice within the context of an instance. +// Obviously don't do this in production. +String.prototype.indexOf = aopify(String.prototype.indexOf); +String.prototype.indexOf.around = function(options) { + var index = options.proceed.apply(this, options.args); + return index === -1 ? -2 : index; +}; + +// Examples borrowed from Mozilla +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf +console.log('Blue Whale'.indexOf('Blue')); +console.log('Blue Whale'.indexOf('Blute')); +console.log('Blue Whale'.indexOf('Whale', 0)); +console.log('Blue Whale'.indexOf('Whale', 5)); +console.log('Blue Whale'.indexOf('Banana', 7)); +console.log('Blue Whale'.indexOf('', 9)); +console.log('Blue Whale'.indexOf('', 10)); +console.log('Blue Whale'.indexOf('', 11)); + +// Output: +// +// 0 +// -2 +// 5 +// 5 +// -2 +// 9 +// 10 +// 10
915f4daab0674633c58623afdee3dd529204ec62
files/jquery.once/1.2.6/jquery.once.min.js
files/jquery.once/1.2.6/jquery.once.min.js
/*! jquery-once - v1.2.6 - 9/11/2013 - http://github.com/robloach/jquery-once * (c) 2013 Rob Loach (http://robloach.net) * Licensed GPL-2.0, MIT */ (function(e){"use strict";"object"==typeof exports?e(require("jquery")):"function"==typeof define&&define.amd?define(["jquery"],e):e(jQuery)})(function(e){"use strict";var n={},t=0;e.fn.once=function(r,i){"string"!=typeof r&&(r in n||(n[r]=++t),i||(i=r),r="jquery-once-"+n[r]);var o=r+"-processed",s=this.not("."+o).addClass(o);return e.isFunction(i)?s.each(i):s},e.fn.removeOnce=function(n,t){var r=n+"-processed",i=this.filter("."+r).removeClass(r);return e.isFunction(t)?i.each(t):i}});
Update project jquery-once to 1.2.6
Update project jquery-once to 1.2.6
JavaScript
mit
vvo/jsdelivr,vvo/jsdelivr,vvo/jsdelivr,vvo/jsdelivr,vvo/jsdelivr
--- +++ @@ -0,0 +1,4 @@ +/*! jquery-once - v1.2.6 - 9/11/2013 - http://github.com/robloach/jquery-once + * (c) 2013 Rob Loach (http://robloach.net) + * Licensed GPL-2.0, MIT */ +(function(e){"use strict";"object"==typeof exports?e(require("jquery")):"function"==typeof define&&define.amd?define(["jquery"],e):e(jQuery)})(function(e){"use strict";var n={},t=0;e.fn.once=function(r,i){"string"!=typeof r&&(r in n||(n[r]=++t),i||(i=r),r="jquery-once-"+n[r]);var o=r+"-processed",s=this.not("."+o).addClass(o);return e.isFunction(i)?s.each(i):s},e.fn.removeOnce=function(n,t){var r=n+"-processed",i=this.filter("."+r).removeClass(r);return e.isFunction(t)?i.each(t):i}});
8502379b759eef126b21b67628484e6efe873184
examples/babel/function-name/index.js
examples/babel/function-name/index.js
#!/usr/bin/env babel-node import assert from 'assert'; function foo() { } let bar = function() { }; const baz = function() { }; assert.strictEqual(foo.name, 'foo'); assert.strictEqual(bar.name, 'bar'); assert.strictEqual(baz.name, 'baz'); let hoge = () => { }; const hige = () => { }; assert.strictEqual(hoge.name, 'hoge'); assert.strictEqual(hige.name, 'hige'); const obj = { x: function() { }, y() { }, z: () => { }, }; assert.strictEqual(obj.x.name, 'x'); assert.strictEqual(obj.y.name, 'y'); assert.strictEqual(obj.z.name, 'z');
Add a sample of babel
Add a sample of babel
JavaScript
mit
kjirou/nodejs-codes
--- +++ @@ -0,0 +1,41 @@ +#!/usr/bin/env babel-node + +import assert from 'assert'; + + +function foo() { +} + +let bar = function() { +}; + +const baz = function() { +}; + +assert.strictEqual(foo.name, 'foo'); +assert.strictEqual(bar.name, 'bar'); +assert.strictEqual(baz.name, 'baz'); + + +let hoge = () => { +}; + +const hige = () => { +}; + +assert.strictEqual(hoge.name, 'hoge'); +assert.strictEqual(hige.name, 'hige'); + + +const obj = { + x: function() { + }, + y() { + }, + z: () => { + }, +}; + +assert.strictEqual(obj.x.name, 'x'); +assert.strictEqual(obj.y.name, 'y'); +assert.strictEqual(obj.z.name, 'z');
a7a0de7a1987de2b1a138210e79aeafbf2421612
utils/plot-image-dates.js
utils/plot-image-dates.js
var fs = require("fs"); var path = require("path"); var async = require("async"); var yr = require("yearrange"); var mongoose = require("mongoose"); require("ukiyoe-models")(mongoose); var ExtractedImage = mongoose.model("ExtractedImage"); var dateMin = 1603; var dateMax = 1940; var maxSpan = 40; var dates = {}; var batchSize = 1000; var outputFile = path.resolve(__dirname + "/../data/date-bins.csv"); var processImages = function(images) { images.forEach(function(image) { if (!image.dateCreated || !image.dateCreated.start || !image.dateCreated.end || image.dateCreated.end - image.dateCreated.start >= maxSpan) { return; } for (var d = image.dateCreated.start; d <= image.dateCreated.end; d++) { if (d >= dateMin && d <= dateMax) { dates[d] += 1; } } }); }; var done = function() { var outStream = fs.createWriteStream(outputFile); outStream.write("Year\tCount\n"); Object.keys(dates).forEach(function(key) { var data = [key, dates[key]].join("\t"); outStream.write(data + "\n"); }); outStream.end(); outStream.on("finish", function() { process.stdout.write("DONE\n"); process.exit(0); }); }; mongoose.connect('mongodb://localhost/extract'); mongoose.connection.on('error', function(err) { console.error('Connection Error:', err) }); mongoose.connection.once('open', function() { var pos = 0; for (var d = dateMin; d <= dateMax; d++) { dates[d] = 0; } var query = {"dateCreated.start": {$ne: null}}; ExtractedImage.count(query, function(err, count) { async.whilst( function() { return pos < count; }, function(callback) { process.stdout.write("Getting " + pos + " to " + (pos + batchSize) + "\r"); ExtractedImage.find(query) .limit(batchSize).skip(pos) .exec(function(err, images) { processImages(images); pos += batchSize; callback(err); }); }, function(err) { process.stdout.write("\nProcessing...\n"); done(); } ); }); });
Add utility for binning images by date.
Add utility for binning images by date.
JavaScript
mit
jeresig/ukiyoe-web
--- +++ @@ -0,0 +1,90 @@ +var fs = require("fs"); +var path = require("path"); +var async = require("async"); +var yr = require("yearrange"); +var mongoose = require("mongoose"); +require("ukiyoe-models")(mongoose); + +var ExtractedImage = mongoose.model("ExtractedImage"); + +var dateMin = 1603; +var dateMax = 1940; +var maxSpan = 40; + +var dates = {}; +var batchSize = 1000; +var outputFile = path.resolve(__dirname + "/../data/date-bins.csv"); + +var processImages = function(images) { + images.forEach(function(image) { + if (!image.dateCreated || !image.dateCreated.start || + !image.dateCreated.end || + image.dateCreated.end - image.dateCreated.start >= maxSpan) { + return; + } + + for (var d = image.dateCreated.start; d <= image.dateCreated.end; d++) { + if (d >= dateMin && d <= dateMax) { + dates[d] += 1; + } + } + }); +}; + +var done = function() { + var outStream = fs.createWriteStream(outputFile); + + outStream.write("Year\tCount\n"); + + Object.keys(dates).forEach(function(key) { + var data = [key, dates[key]].join("\t"); + outStream.write(data + "\n"); + }); + + outStream.end(); + outStream.on("finish", function() { + process.stdout.write("DONE\n"); + process.exit(0); + }); +}; + +mongoose.connect('mongodb://localhost/extract'); + +mongoose.connection.on('error', function(err) { + console.error('Connection Error:', err) +}); + +mongoose.connection.once('open', function() { + var pos = 0; + + for (var d = dateMin; d <= dateMax; d++) { + dates[d] = 0; + } + + var query = {"dateCreated.start": {$ne: null}}; + + ExtractedImage.count(query, function(err, count) { + async.whilst( + function() { + return pos < count; + }, + + function(callback) { + process.stdout.write("Getting " + pos + " to " + + (pos + batchSize) + "\r"); + ExtractedImage.find(query) + .limit(batchSize).skip(pos) + .exec(function(err, images) { + processImages(images); + pos += batchSize; + callback(err); + }); + }, + + function(err) { + process.stdout.write("\nProcessing...\n"); + done(); + } + ); + }); +});
ff52256c78cf8e5a0ff265e29a6e71fa193356df
day03-second_largest.js
day03-second_largest.js
// sort() documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort function processData(myArray) { var secondLargest; var length = myArray.length; var index = length - 2; // According to the sort() documentation: // If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings // in Unicode code point order. For example, "Cherry" comes before "banana". In a numeric sort, 9 comes before // 80, but because numbers are converted to strings, "80" comes before "9" in Unicode order. // So, it is necessary to supply a compareFunction myArray.sort( function( a, b ) { return a - b; } ); while( ((secondLargest = myArray[index]) == myArray[length - 1]) && (index >= 0) ) { index--; } console.log( secondLargest ); } // tail starts here process.stdin.resume(); process.stdin.setEncoding("ascii"); _input = ""; process.stdin.on("data", function (input) { _input += input; }); process.stdin.on("end", function () { processData(_input.split('\n')[1].split(' ').map(Number)); });
Add third solution for day 4
Add third solution for day 4
JavaScript
mit
giuliannosbrugnera/7DaysOfJavaScript
--- +++ @@ -0,0 +1,34 @@ +// sort() documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort +function processData(myArray) { + + var secondLargest; + var length = myArray.length; + var index = length - 2; + + // According to the sort() documentation: + // If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings + // in Unicode code point order. For example, "Cherry" comes before "banana". In a numeric sort, 9 comes before + // 80, but because numbers are converted to strings, "80" comes before "9" in Unicode order. + // So, it is necessary to supply a compareFunction + myArray.sort( function( a, b ) { return a - b; } ); + + while( ((secondLargest = myArray[index]) == myArray[length - 1]) && (index >= 0) ) { + index--; + } + + console.log( secondLargest ); + +} + + +// tail starts here +process.stdin.resume(); +process.stdin.setEncoding("ascii"); +_input = ""; +process.stdin.on("data", function (input) { + _input += input; +}); + +process.stdin.on("end", function () { + processData(_input.split('\n')[1].split(' ').map(Number)); +});
e9d97dca46357020b2e2b32e23396a353bab3348
kolibri/plugins/facility_management/assets/src/constants.js
kolibri/plugins/facility_management/assets/src/constants.js
// a name for every URL pattern const PageNames = { CLASS_MGMT_PAGE: 'CLASS_MGMT_PAGE', CLASS_EDIT_MGMT_PAGE: 'CLASS_EDIT_MGMT_PAGE', CLASS_ENROLL_MGMT_PAGE: 'CLASS_ENROLL_MGMT_PAGE', USER_MGMT_PAGE: 'USER_MGMT_PAGE', DATA_EXPORT_PAGE: 'DATA_EXPORT_PAGE', FACILITY_CONFIG_PAGE: 'FACILITY_CONFIG_PAGE', }; // modal names const Modals = { CREATE_CLASS: 'CREATE_CLASS', DELETE_CLASS: 'DELETE_CLASS', EDIT_CLASS_NAME: 'EDIT_CLASS_NAME', REMOVE_USER: 'REMOVE_USER', CONFIRM_ENROLLMENT: 'CONFIRM_ENROLLMENT', CREATE_USER: 'CREATE_USER', EDIT_USER: 'EDIT_USER', RESET_USER_PASSWORD: 'RESET_USER_PASSWORD', DELETE_USER: 'DELETE_USER', }; const defaultFacilityConfig = { learnerCanEditUsername: true, learnerCanEditName: true, learnerCanEditPassword: true, learnerCanSignUp: true, learnerCanDeleteAccount: true, }; const notificationTypes = { PAGELOAD_FAILURE: 'PAGELOAD_FAILURE', SAVE_FAILURE: 'SAVE_FAILURE', SAVE_SUCCESS: 'SAVE_SUCCESS', }; export { PageNames, Modals, defaultFacilityConfig, notificationTypes };
// a name for every URL pattern const PageNames = { CLASS_MGMT_PAGE: 'CLASS_MGMT_PAGE', CLASS_EDIT_MGMT_PAGE: 'CLASS_EDIT_MGMT_PAGE', CLASS_ENROLL_MGMT_PAGE: 'CLASS_ENROLL_MGMT_PAGE', USER_MGMT_PAGE: 'USER_MGMT_PAGE', DATA_EXPORT_PAGE: 'DATA_EXPORT_PAGE', FACILITY_CONFIG_PAGE: 'FACILITY_CONFIG_PAGE', }; // modal names const Modals = { CREATE_CLASS: 'CREATE_CLASS', DELETE_CLASS: 'DELETE_CLASS', EDIT_CLASS_NAME: 'EDIT_CLASS_NAME', REMOVE_USER: 'REMOVE_USER', CONFIRM_ENROLLMENT: 'CONFIRM_ENROLLMENT', CREATE_USER: 'CREATE_USER', EDIT_USER: 'EDIT_USER', RESET_USER_PASSWORD: 'RESET_USER_PASSWORD', DELETE_USER: 'DELETE_USER', }; const defaultFacilityConfig = { learnerCanEditUsername: true, learnerCanEditName: true, learnerCanEditPassword: true, learnerCanSignUp: true, learnerCanDeleteAccount: true, learnerCanLoginWithNoPassword: false, }; const notificationTypes = { PAGELOAD_FAILURE: 'PAGELOAD_FAILURE', SAVE_FAILURE: 'SAVE_FAILURE', SAVE_SUCCESS: 'SAVE_SUCCESS', }; export { PageNames, Modals, defaultFacilityConfig, notificationTypes };
Add the learnerCanLoginWithNoPassword at the default facility config.
Add the learnerCanLoginWithNoPassword at the default facility config.
JavaScript
mit
lyw07/kolibri,indirectlylit/kolibri,mrpau/kolibri,christianmemije/kolibri,learningequality/kolibri,indirectlylit/kolibri,christianmemije/kolibri,DXCanas/kolibri,learningequality/kolibri,lyw07/kolibri,mrpau/kolibri,benjaoming/kolibri,DXCanas/kolibri,benjaoming/kolibri,learningequality/kolibri,jonboiser/kolibri,learningequality/kolibri,christianmemije/kolibri,mrpau/kolibri,christianmemije/kolibri,mrpau/kolibri,benjaoming/kolibri,benjaoming/kolibri,jonboiser/kolibri,DXCanas/kolibri,lyw07/kolibri,indirectlylit/kolibri,jonboiser/kolibri,jonboiser/kolibri,lyw07/kolibri,indirectlylit/kolibri,DXCanas/kolibri
--- +++ @@ -27,6 +27,7 @@ learnerCanEditPassword: true, learnerCanSignUp: true, learnerCanDeleteAccount: true, + learnerCanLoginWithNoPassword: false, }; const notificationTypes = {
4d16eb91005eccf8d4cc862995bccd06000ad198
src/syncher/ObjectAllocation.js
src/syncher/ObjectAllocation.js
class ObjectAllocation { /* private _url: URL _bus: MiniBus */ /** * Create an Object Allocation * @param {URL.URL} url - url from who is sending the message * @param {MiniBus} bus - MiniBus used for address allocation */ constructor(url, bus) { let _this = this; _this._url = url; _this._bus = bus; } /** * get the URL value * @return {string} The url value; */ get url() { return this._url; } /** * Ask for creation of a number of Object addresses, to the domain message node. * @param {Domain} domain - Domain of the message node. * @param {number} number - Number of addresses to request * @returns {Promise<ObjectURL>} A list of ObjectURL's */ create(domain, number) { let _this = this; let msg = { type: 'create', from: _this._url, to: 'domain://msg-node.' + domain + '/object-address-allocation', body: { number: number } }; return new Promise((resolve, reject) => { _this._bus.postMessage(msg, (reply) => { if (reply.body.code === 200) { resolve(reply.body.allocated); } else { reject(reply.body.desc); } }); }); } } export default ObjectAllocation;
Prepare syncher and msg-node integration (not ready)
Prepare syncher and msg-node integration (not ready)
JavaScript
apache-2.0
reTHINK-project/dev-runtime-core,reTHINK-project/dev-runtime-core,reTHINK-project/dev-runtime-core
--- +++ @@ -0,0 +1,51 @@ +class ObjectAllocation { + /* private + _url: URL + _bus: MiniBus + */ + + /** + * Create an Object Allocation + * @param {URL.URL} url - url from who is sending the message + * @param {MiniBus} bus - MiniBus used for address allocation + */ + constructor(url, bus) { + let _this = this; + + _this._url = url; + _this._bus = bus; + } + + /** + * get the URL value + * @return {string} The url value; + */ + get url() { return this._url; } + + /** + * Ask for creation of a number of Object addresses, to the domain message node. + * @param {Domain} domain - Domain of the message node. + * @param {number} number - Number of addresses to request + * @returns {Promise<ObjectURL>} A list of ObjectURL's + */ + create(domain, number) { + let _this = this; + + let msg = { + type: 'create', from: _this._url, to: 'domain://msg-node.' + domain + '/object-address-allocation', + body: { number: number } + }; + + return new Promise((resolve, reject) => { + _this._bus.postMessage(msg, (reply) => { + if (reply.body.code === 200) { + resolve(reply.body.allocated); + } else { + reject(reply.body.desc); + } + }); + }); + } +} + +export default ObjectAllocation;
dbf5ec64c3b9bdec5b011ae41764f132adef9f21
nodejs/opctorch-message-rgb-characteristic.js
nodejs/opctorch-message-rgb-characteristic.js
var util = require('util'); var bleno = require('bleno'); var BlenoCharacteristic = bleno.Characteristic; var BlenoDescriptor = bleno.Descriptor; function OPCTorchMessageRGBCharacteristic(opctorch) { OPCTorchMessageRGBCharacteristic.super_.call(this, { uuid: '69b9ac8b-2f23-471a-ba62-0e3c9e8c0003', properties: ['write', 'writeWithoutResponse'], descriptors: [ new BlenoDescriptor({ uuid: '2901', value: 'set opctorch message RGB value' }) ] }); this.opctorch = opctorch; } util.inherits(OPCTorchMessageRGBCharacteristic, BlenoCharacteristic); OPCTorchMessageRGBCharacteristic.prototype.onWriteRequest = function(data, offset, withoutResponse, callback) { if (offset) { callback(this.RESULT_ATTR_NOT_LONG); } else if (data.length !== 3) { callback(this.RESULT_INVALID_ATTRIBUTE_LENGTH); } else { var r = data.readUInt8(0); var g = data.readUInt8(1); var b = data.readUInt8(2); console.log("RGB characteristic " + r + " " + g + " " + b); this.opctorch.set("text_red", r); this.opctorch.set("text_green", g); this.opctorch.set("text_blue", b); callback(this.RESULT_SUCCESS); } }; module.exports = OPCTorchMessageRGBCharacteristic;
Make it actually work. Use proper UUIDs. Rename text colour characteristic.
Make it actually work. Use proper UUIDs. Rename text colour characteristic.
JavaScript
mit
DanielO/opctorch,DanielO/opctorch,DanielO/opctorch,DanielO/opctorch
--- +++ @@ -0,0 +1,41 @@ +var util = require('util'); + +var bleno = require('bleno'); +var BlenoCharacteristic = bleno.Characteristic; +var BlenoDescriptor = bleno.Descriptor; + +function OPCTorchMessageRGBCharacteristic(opctorch) { + OPCTorchMessageRGBCharacteristic.super_.call(this, { + uuid: '69b9ac8b-2f23-471a-ba62-0e3c9e8c0003', + properties: ['write', 'writeWithoutResponse'], + descriptors: [ + new BlenoDescriptor({ + uuid: '2901', + value: 'set opctorch message RGB value' + }) + ] + }); + + this.opctorch = opctorch; +} + +util.inherits(OPCTorchMessageRGBCharacteristic, BlenoCharacteristic); + +OPCTorchMessageRGBCharacteristic.prototype.onWriteRequest = function(data, offset, withoutResponse, callback) { + if (offset) { + callback(this.RESULT_ATTR_NOT_LONG); + } else if (data.length !== 3) { + callback(this.RESULT_INVALID_ATTRIBUTE_LENGTH); + } else { + var r = data.readUInt8(0); + var g = data.readUInt8(1); + var b = data.readUInt8(2); + console.log("RGB characteristic " + r + " " + g + " " + b); + this.opctorch.set("text_red", r); + this.opctorch.set("text_green", g); + this.opctorch.set("text_blue", b); + callback(this.RESULT_SUCCESS); + } +}; + +module.exports = OPCTorchMessageRGBCharacteristic;
cee55538daa2ad38d043c023ac81d6ba351ef4c4
test/microbot-service.spec.js
test/microbot-service.spec.js
define(['../js/microbot-service.js'], function (microbotService) { 'use strict'; // connect // send // on connection close // double send describe('Service test', function () { it('on call to connect, mirobotService shall connect to a web socket server specified by a addresse and a port', function () { }); it('upon opening of the connection mirobotService shall call a provided handler', function () { }); it('upon closing of the connection mirobotService shall call a provided handler', function () { }); it('on call to send, mirobotService shall be able to send a message', function () { }); it('on error from the web socket serveur, mirobotService shall call a provided error handler', function () { }); it('mirobotService shall be able to send several message synchronously', function () { }); }); });
Add test for mirobot service.
Add test for mirobot service.
JavaScript
apache-2.0
jdmichaud/logofrjs,jdmichaud/logofrjs
--- +++ @@ -0,0 +1,29 @@ +define(['../js/microbot-service.js'], function (microbotService) { + 'use strict'; + + // connect + // send + // on connection close + // double send + + describe('Service test', function () { + it('on call to connect, mirobotService shall connect to a web socket server specified by a addresse and a port', function () { + }); + + it('upon opening of the connection mirobotService shall call a provided handler', function () { + }); + + it('upon closing of the connection mirobotService shall call a provided handler', function () { + }); + + it('on call to send, mirobotService shall be able to send a message', function () { + }); + + it('on error from the web socket serveur, mirobotService shall call a provided error handler', function () { + }); + + it('mirobotService shall be able to send several message synchronously', function () { + }); + + }); +});
428edbb09d5a3a2dcd55bed3df32998735b5fafb
plain-node/url_reader.js
plain-node/url_reader.js
var http = require("http"); var url = require("url"); //port to listen for incoming requests var port = 8000; console.log("Creating the server..."); var server = http.createServer(function (req, res){ res.statusCode = 200; //if you ommit the second param to parse, the query params remain an unparsed string var parsedUrl= url.parse(req.url,true); var responseString = '<html><body><h1>I know what you just requested !</h1>' responseString += '<p>You requested:</p>' ; responseString += '<p>path: ' + parsedUrl.pathname + '</p>' ; var queryParams = parsedUrl.query; for( key in queryParams){ responseString += '<p>queryParam : ' + key ; responseString += ' : ' + queryParams[key] + '</p>' ; } responseString += '<p>And that is all you asked for!</p>' ; res.end(responseString); }); //Now listen for incoming requests server.listen(port ); console.log("Created the server. Dial http port: " + port);
Add simple script to echo url path and params
Add simple script to echo url path and params
JavaScript
mit
samir-joshi/node-exercises
--- +++ @@ -0,0 +1,33 @@ +var http = require("http"); +var url = require("url"); + +//port to listen for incoming requests +var port = 8000; + + +console.log("Creating the server..."); +var server = http.createServer(function (req, res){ + res.statusCode = 200; + + //if you ommit the second param to parse, the query params remain an unparsed string + var parsedUrl= url.parse(req.url,true); + + var responseString = '<html><body><h1>I know what you just requested !</h1>' + responseString += '<p>You requested:</p>' ; + responseString += '<p>path: ' + parsedUrl.pathname + '</p>' ; + + var queryParams = parsedUrl.query; + for( key in queryParams){ + responseString += '<p>queryParam : ' + key ; + responseString += ' : ' + queryParams[key] + '</p>' ; + } + + responseString += '<p>And that is all you asked for!</p>' ; + + res.end(responseString); +}); + +//Now listen for incoming requests +server.listen(port ); + +console.log("Created the server. Dial http port: " + port);
865b5809ba6fcd85cd30ff756f51d5bfb9ed36af
week-7/variables-objects.js
week-7/variables-objects.js
// JavaScript Variables and Objects // I worked [by myself] on this challenge. // __________________________________________ // Write your code below. var secretNumber = 7 var password = "just open the door" var allowedIn = false members = ["John", "Caroline", "ostrich", "Mary", "baby ostrich"]; // __________________________________________ // Test Code: Do not alter code below this line. function assert(test, message, test_number) { if (!test) { console.log(test_number + "false"); throw "ERROR: " + message; } console.log(test_number + "true"); return true; } assert( (typeof secretNumber === 'number'), "The value of secretNumber should be a number.", "1. " ) assert( secretNumber === 7, "The value of secretNumber should be 7.", "2. " ) assert( typeof password === 'string', "The value of password should be a string.", "3. " ) assert( password === "just open the door", "The value of password should be 'just open the door'.", "4. " ) assert( typeof allowedIn === 'boolean', "The value of allowedIn should be a boolean.", "5. " ) assert( allowedIn === false, "The value of allowedIn should be false.", "6. " ) assert( members instanceof Array, "The value of members should be an array", "7. " ) assert( members[0] === "John", "The first element in the value of members should be 'John'.", "8. " ) assert( members[3] === "Mary", "The fourth element in the value of members should be 'Mary'.", "9. " )
Add 7.3 code that passes tests
Add 7.3 code that passes tests
JavaScript
mit
kenworthyc/phase-0,kenworthyc/phase-0,kenworthyc/phase-0
--- +++ @@ -0,0 +1,85 @@ +// JavaScript Variables and Objects + +// I worked [by myself] on this challenge. + +// __________________________________________ +// Write your code below. + +var secretNumber = 7 +var password = "just open the door" +var allowedIn = false +members = ["John", "Caroline", "ostrich", "Mary", "baby ostrich"]; + + + + + + + + +// __________________________________________ + +// Test Code: Do not alter code below this line. + +function assert(test, message, test_number) { + if (!test) { + console.log(test_number + "false"); + throw "ERROR: " + message; + } + console.log(test_number + "true"); + return true; +} + +assert( + (typeof secretNumber === 'number'), + "The value of secretNumber should be a number.", + "1. " +) + +assert( + secretNumber === 7, + "The value of secretNumber should be 7.", + "2. " +) + +assert( + typeof password === 'string', + "The value of password should be a string.", + "3. " +) + +assert( + password === "just open the door", + "The value of password should be 'just open the door'.", + "4. " +) + +assert( + typeof allowedIn === 'boolean', + "The value of allowedIn should be a boolean.", + "5. " +) + +assert( + allowedIn === false, + "The value of allowedIn should be false.", + "6. " +) + +assert( + members instanceof Array, + "The value of members should be an array", + "7. " +) + +assert( + members[0] === "John", + "The first element in the value of members should be 'John'.", + "8. " +) + +assert( + members[3] === "Mary", + "The fourth element in the value of members should be 'Mary'.", + "9. " +)
399d8a83e77c068e95a4de845a595eb3528f6ccf
lib/run.js
lib/run.js
var _ = require("underscore"); var xpi = require("./xpi"); var createProfile = require("./profile"); var runFirefox = require("./firefox"); var console = require("./utils").console; function run (manifest, options) { // Generate XPI and get the path return xpi(manifest, options).then(function (xpiPath) { return runFirefox(_.extend({}, options, { xpi: xpiPath })); }); } module.exports = run;
var _ = require("underscore"); var xpi = require("./xpi"); var createProfile = require("./profile"); var runFirefox = require("./firefox"); var console = require("./utils").console; var fs = require("fs-promise"); function extendWith(source, field) { return function(value) { source[field] = value; return source; } } function removeXPI(options) { return fs.unlink(options.xpi).then(function() { return options; }); } function run (manifest, options) { // Generate XPI and get the path return xpi(manifest, options). then(extendWith(options, "xpi")). then(function(options) { return options.profile || createProfile(options); }). then(extendWith(options, "profile")). then(removeXPI). then(runFirefox) } module.exports = run;
Make sure that generated xpi is always removed.
Make sure that generated xpi is always removed.
JavaScript
mpl-2.0
matraska23/jpm,freaktechnik/jpm,benbasson/jpm,guyzmuch/jpm,alexduch/jpm,mozilla-jetpack/jpm,freaktechnik/jpm,freaktechnik/jpm,mozilla/jpm,nikolas/jpm,Medeah/jpm,jsantell/jpm,benbasson/jpm,nikolas/jpm,kkapsner/jpm,kkapsner/jpm,matraska23/jpm,rpl/jpm,alexduch/jpm,jsantell/jpm,rpl/jpm,alexduch/jpm,johannhof/jpm,mozilla/jpm,wagnerand/jpm,wagnerand/jpm,mozilla/jpm,guyzmuch/jpm,johannhof/jpm,Medeah/jpm,wagnerand/jpm,mozilla-jetpack/jpm,nikolas/jpm,jsantell/jpm,mozilla-jetpack/jpm,Medeah/jpm,rpl/jpm,kkapsner/jpm,johannhof/jpm,benbasson/jpm,matraska23/jpm,guyzmuch/jpm
--- +++ @@ -3,13 +3,30 @@ var createProfile = require("./profile"); var runFirefox = require("./firefox"); var console = require("./utils").console; +var fs = require("fs-promise"); + +function extendWith(source, field) { + return function(value) { + source[field] = value; + return source; + } +} + +function removeXPI(options) { + return fs.unlink(options.xpi).then(function() { + return options; + }); +} function run (manifest, options) { // Generate XPI and get the path - return xpi(manifest, options).then(function (xpiPath) { - return runFirefox(_.extend({}, options, { - xpi: xpiPath - })); - }); + return xpi(manifest, options). + then(extendWith(options, "xpi")). + then(function(options) { + return options.profile || createProfile(options); + }). + then(extendWith(options, "profile")). + then(removeXPI). + then(runFirefox) } module.exports = run;
95e64d24b66e24becfa8899c7b3c66dd80a16cd1
tests/test-parser.js
tests/test-parser.js
"use strict"; var PEG = require("pegjs"), fs = require("fs"), nodeunit = require('nodeunit'), ks_parser_fn = __dirname + '/../lib/kumascript/parser.pegjs', ks_parser_src = fs.readFileSync(ks_parser_fn, 'utf8'), ks_parser = PEG.buildParser(ks_parser_src); module.exports = nodeunit.testCase({ "JSON values are parsed correctly": function (test) { var tokens = ks_parser.parse('{{ f({ "a": "x", "b": -1e2, "c": 0.5, "d": [1,2] }) }}'); test.deepEqual(tokens, [{type: "MACRO", name: "f", args: [{a: "x", b: -1e2, c: 0.5, d: [1, 2]}], offset: 0}], "The macro is parsed correctly"); test.done(); }, "Invalid JSON should cause a syntax error": function (test) { test.throws(function() { ks_parser.parse('{{ f({ x: 1 }) }}'); }, PEG.parser.SyntaxError, "Quotes around property names are required"); test.throws(function() { ks_parser.parse('{{ f({ "x": 01 }) }}'); }, PEG.parser.SyntaxError, "Octal literals are not allowed"); test.throws(function() { ks_parser.parse('{{ f({ "x": [1,] }) }}'); }, PEG.parser.SyntaxError, "Trailing commas are not allowed"); test.done(); }, "JSON strings should be able to contain ')'": function (test) { var tokens = ks_parser.parse('{{ f({ "a": "f)" }) }}'); test.deepEqual(tokens, [{type: "MACRO", name: "f", args: [{a: "f)"}], offset: 0}], "The macro is parsed correctly"); test.done(); } });
Add unit tests for JSON parsing
Add unit tests for JSON parsing
JavaScript
mpl-2.0
jpmedley/kumascript,a2sheppy/kumascript,a2sheppy/kumascript,jpmedley/kumascript
--- +++ @@ -0,0 +1,46 @@ +"use strict"; + +var PEG = require("pegjs"), + fs = require("fs"), + nodeunit = require('nodeunit'), + + ks_parser_fn = __dirname + '/../lib/kumascript/parser.pegjs', + ks_parser_src = fs.readFileSync(ks_parser_fn, 'utf8'), + ks_parser = PEG.buildParser(ks_parser_src); + +module.exports = nodeunit.testCase({ + "JSON values are parsed correctly": function (test) { + var tokens = ks_parser.parse('{{ f({ "a": "x", "b": -1e2, "c": 0.5, "d": [1,2] }) }}'); + test.deepEqual(tokens, + [{type: "MACRO", + name: "f", + args: [{a: "x", b: -1e2, c: 0.5, d: [1, 2]}], + offset: 0}], + "The macro is parsed correctly"); + test.done(); + }, + + "Invalid JSON should cause a syntax error": function (test) { + test.throws(function() { + ks_parser.parse('{{ f({ x: 1 }) }}'); + }, PEG.parser.SyntaxError, "Quotes around property names are required"); + + test.throws(function() { + ks_parser.parse('{{ f({ "x": 01 }) }}'); + }, PEG.parser.SyntaxError, "Octal literals are not allowed"); + + test.throws(function() { + ks_parser.parse('{{ f({ "x": [1,] }) }}'); + }, PEG.parser.SyntaxError, "Trailing commas are not allowed"); + + test.done(); + }, + + "JSON strings should be able to contain ')'": function (test) { + var tokens = ks_parser.parse('{{ f({ "a": "f)" }) }}'); + test.deepEqual(tokens, + [{type: "MACRO", name: "f", args: [{a: "f)"}], offset: 0}], + "The macro is parsed correctly"); + test.done(); + } +});
7fe6cc0901193363865fcbd0b26deeb70c74e62e
scripts/delete-unused-directors.js
scripts/delete-unused-directors.js
// Usage: [MONGOHQ_URL=...] node ./ldelete-unused-directors.js var env = require('../server/env').get() var mongoose = require('mongoose') var schema = require('../server/schema') var Program = schema.Program var Director = schema.Director var _ = require('lodash') var count = 0 var suspicious = 0 var deleted = 0 function isSuspicious(name) { return name.length < 6 || name.split(' ').length < 2 || _.find(name.split(' '), function (n) { return n.length < 3 }) != undefined } mongoose.connect(process.env.MONGOHQ_URL || env.mongoUrl) Director.count({}, function (err, total) { if (err) return console.error(err) var stream = Director.find({}).stream() stream.on('data', function (director) { stream.pause() Program.find({deleted: {$ne: true}, directors: {$in: [director.name]}}, function (err, data) { if (err) console.error(err) if (++count % 100 == 0) console.info('Processed ' + count + '/' + total) if (data.length == 0) { Director.remove({name: director.name}, function (err) { if (err) console.error(err) else { console.info('Removed unused: ' + director.name) deleted++ } stream.resume() }) } else if (isSuspicious(director.name)) { console.info('Suspicious (not removed): ' + director.name) suspicious++ stream.resume() } else { stream.resume() } }) }) stream.on('error', function (err) { console.error('Error: ' + err) }) stream.on('close', function () { console.info('Deleted: ' + deleted) console.info('Suspicious: ' + suspicious) mongoose.disconnect() }) })
Add script to delete unused directors
Add script to delete unused directors
JavaScript
mit
kavi-fi/meku,kavi-fi/meku,kavi-fi/meku
--- +++ @@ -0,0 +1,58 @@ +// Usage: [MONGOHQ_URL=...] node ./ldelete-unused-directors.js + +var env = require('../server/env').get() +var mongoose = require('mongoose') +var schema = require('../server/schema') +var Program = schema.Program +var Director = schema.Director +var _ = require('lodash') +var count = 0 +var suspicious = 0 +var deleted = 0 + +function isSuspicious(name) { + return name.length < 6 || name.split(' ').length < 2 || _.find(name.split(' '), function (n) { return n.length < 3 }) != undefined +} + +mongoose.connect(process.env.MONGOHQ_URL || env.mongoUrl) + +Director.count({}, function (err, total) { + if (err) return console.error(err) + + var stream = Director.find({}).stream() + + stream.on('data', function (director) { + stream.pause() + Program.find({deleted: {$ne: true}, directors: {$in: [director.name]}}, function (err, data) { + if (err) console.error(err) + if (++count % 100 == 0) console.info('Processed ' + count + '/' + total) + if (data.length == 0) { + Director.remove({name: director.name}, function (err) { + if (err) console.error(err) + else { + console.info('Removed unused: ' + director.name) + deleted++ + } + stream.resume() + }) + } else if (isSuspicious(director.name)) { + console.info('Suspicious (not removed): ' + director.name) + suspicious++ + stream.resume() + } else { + stream.resume() + } + }) + }) + + stream.on('error', function (err) { + console.error('Error: ' + err) + }) + + stream.on('close', function () { + console.info('Deleted: ' + deleted) + console.info('Suspicious: ' + suspicious) + mongoose.disconnect() + }) +}) +
62c1e4b308ad956be0d3f1dc27948f333eb2337c
server/game/cards/02.1-ToA/SmokeAndMirrors.js
server/game/cards/02.1-ToA/SmokeAndMirrors.js
const _ = require('underscore'); const DrawCard = require('../../drawcard.js'); class SmokeAndMirrors extends DrawCard { setupCardAbilities() { this.action({ title: 'Move shinobi home', condition: () => this.game.currentConflict, target: { activePromptTitle: 'Choose characters', numCards: 0, multiSelect: true, cardType: 'character', cardCondition: card => { return (card.controller === this.controller && card.isAttacking() && card.hasTrait('shinobi')); } }, handler: context => { this.game.addMessage('{0} uses {1} to send {2} home', this.controller, this, context.target); _.each(context.target, card => this.game.currentConflict.sendHome(card)); } }); } } SmokeAndMirrors.id = 'smoke-and-mirrors'; module.exports = SmokeAndMirrors;
const _ = require('underscore'); const DrawCard = require('../../drawcard.js'); class SmokeAndMirrors extends DrawCard { setupCardAbilities() { this.action({ title: 'Move shinobi home', condition: () => this.game.currentConflict, target: { activePromptTitle: 'Choose characters', numCards: 0, multiSelect: true, cardType: 'character', cardCondition: card => { return (card.controller === this.controller && card.isAttacking() && card.hasTrait('shinobi')); } }, handler: context => { this.game.addMessage('{0} uses {1} to send {2} home', this.controller, this, context.target); this.game.currentConflict.sendHome(context.target); } }); } } SmokeAndMirrors.id = 'smoke-and-mirrors'; module.exports = SmokeAndMirrors;
Use the new sendHome code
Use the new sendHome code Ideally, we'd like all the sendHome events to use the same event window, as they share interrupt and reaction windows.
JavaScript
mit
gryffon/ringteki,jeremylarner/ringteki,gryffon/ringteki,gryffon/ringteki,jeremylarner/ringteki,jeremylarner/ringteki
--- +++ @@ -17,7 +17,7 @@ }, handler: context => { this.game.addMessage('{0} uses {1} to send {2} home', this.controller, this, context.target); - _.each(context.target, card => this.game.currentConflict.sendHome(card)); + this.game.currentConflict.sendHome(context.target); } }); }
8d4f9d395abb6f562edc5a04d7c521279908ce2c
src/setupJest.js
src/setupJest.js
window.fetch = require('jest-fetch-mock'); // Mock the Date object and allows us to use Date.now() and get a consistent date back const mockedCurrentDate = new Date("2017-10-06T13:45:28.975Z"); require('jest-mock-now')(mockedCurrentDate); // Mock document functions (specifically for the CollectionsController component) const mockedGetElement = () => ({ getBoundingClientRect: () => ({ top: 0 }), scrollTop: 0 }); Object.defineProperty(document, 'getElementById', { value: mockedGetElement, });
window.fetch = require('jest-fetch-mock'); // Mock the Date object and allows us to use Date.now() and get a consistent date back const mockedCurrentDate = new Date("2017-10-06T13:45:28.975Z"); require('jest-mock-now')(mockedCurrentDate); // Mock document functions (specifically for the CollectionsController component) const mockedGetElement = () => ({ getBoundingClientRect: () => ({ top: 0 }), scrollTop: 0, scrollIntoView: () => {} }); Object.defineProperty(document, 'getElementById', { value: mockedGetElement, });
Fix breaking unit tests due to missing mock of scrollIntoView function
Fix breaking unit tests due to missing mock of scrollIntoView function
JavaScript
mit
ONSdigital/florence,ONSdigital/florence,ONSdigital/florence,ONSdigital/florence
--- +++ @@ -9,7 +9,8 @@ getBoundingClientRect: () => ({ top: 0 }), - scrollTop: 0 + scrollTop: 0, + scrollIntoView: () => {} }); Object.defineProperty(document, 'getElementById', { value: mockedGetElement,
f82a14815b0d1bd73efcb58a17c8e516d0bc5fcf
_config/templateHelpers.js
_config/templateHelpers.js
module.exports = function() { /** * Set of handlebar helpers that can be used in templates */ return { /** * Get the string value of a JSON object, useful for debugging template data * * @param {Object} obj JSON object * @return {String} Provided object as a string * * @example * {{ json data }} */ json: function(obj) { return JSON.stringify(obj); }, /** * Helper that gives condition checking * * @param {*} v1 First variable * @param {String} operator Type of comparison to be made * @param {*} v2 Second variable to compare * @param {Object} options Handlebars options object, not required to be passed in * @return {Boolean} Condition result * * @example * {{#ifCondition var1 '==' var2}} ..render if condition is true... {{/ifCondition}} */ ifCondition: function (v1, operator, v2, options) { switch (operator) { case '==': return (v1 == v2) ? options.fn(this) : options.inverse(this); case '===': return (v1 === v2) ? options.fn(this) : options.inverse(this); case '<': return (v1 < v2) ? options.fn(this) : options.inverse(this); case '<=': return (v1 <= v2) ? options.fn(this) : options.inverse(this); case '>': return (v1 > v2) ? options.fn(this) : options.inverse(this); case '>=': return (v1 >= v2) ? options.fn(this) : options.inverse(this); case '&&': return (v1 && v2) ? options.fn(this) : options.inverse(this); case '||': return (v1 || v2) ? options.fn(this) : options.inverse(this); default: return options.inverse(this); } } } }
Add tempalte helpers file and doc comments
feat: Add tempalte helpers file and doc comments
JavaScript
mit
cartridge/cartridge-cli,code-computerlove/quarry,code-computerlove/slate-cli,code-computerlove/slate,CodeRichardJohnston/slate-demo,code-computerlove/slate,cartridge/cartridge,CodeRichardJohnston/slate-demo
--- +++ @@ -0,0 +1,55 @@ +module.exports = function() { + + /** + * Set of handlebar helpers that can be used in templates + */ + + return { + /** + * Get the string value of a JSON object, useful for debugging template data + * + * @param {Object} obj JSON object + * @return {String} Provided object as a string + * + * @example + * {{ json data }} + */ + json: function(obj) { + return JSON.stringify(obj); + }, + /** + * Helper that gives condition checking + * + * @param {*} v1 First variable + * @param {String} operator Type of comparison to be made + * @param {*} v2 Second variable to compare + * @param {Object} options Handlebars options object, not required to be passed in + * @return {Boolean} Condition result + * + * @example + * {{#ifCondition var1 '==' var2}} ..render if condition is true... {{/ifCondition}} + */ + ifCondition: function (v1, operator, v2, options) { + switch (operator) { + case '==': + return (v1 == v2) ? options.fn(this) : options.inverse(this); + case '===': + return (v1 === v2) ? options.fn(this) : options.inverse(this); + case '<': + return (v1 < v2) ? options.fn(this) : options.inverse(this); + case '<=': + return (v1 <= v2) ? options.fn(this) : options.inverse(this); + case '>': + return (v1 > v2) ? options.fn(this) : options.inverse(this); + case '>=': + return (v1 >= v2) ? options.fn(this) : options.inverse(this); + case '&&': + return (v1 && v2) ? options.fn(this) : options.inverse(this); + case '||': + return (v1 || v2) ? options.fn(this) : options.inverse(this); + default: + return options.inverse(this); + } + } + } +}
f51ab5dd49be8099309d46ebe25c1ae9c81c944f
lib/devices/chuangmi.plug.v1.js
lib/devices/chuangmi.plug.v1.js
'use strict'; const Device = require('../device'); const PowerChannels = require('./capabilities/power-channels'); class PlugV1 extends Device { static get TYPE() { return 'switch' } constructor(options) { super(options); this.type = PlugV1.TYPE; this.defineProperty('on', { name: 'powerChannel0' }); PowerChannels.extend(this, { channels: 1, set: (channel, power) => this.call(power ? 'set_on' : 'set_off', []) }); this.defineProperty('usb_on', { name: 'powerUSB' }); } get powerUSB() { return this.property('powerUSB'); } setPowerUSB(power) { return this.call(power ? 'set_usb_on' : 'set_usb_off', []) .then(() => power); } } module.exports = PlugV1;
Support for first generation Smart Socket Plug
Support for first generation Smart Socket Plug
JavaScript
mit
aholstenson/miio
--- +++ @@ -0,0 +1,38 @@ +'use strict'; + +const Device = require('../device'); + +const PowerChannels = require('./capabilities/power-channels'); + +class PlugV1 extends Device { + static get TYPE() { return 'switch' } + + constructor(options) { + super(options); + + this.type = PlugV1.TYPE; + + this.defineProperty('on', { + name: 'powerChannel0' + }); + PowerChannels.extend(this, { + channels: 1, + set: (channel, power) => this.call(power ? 'set_on' : 'set_off', []) + }); + + this.defineProperty('usb_on', { + name: 'powerUSB' + }); + } + + get powerUSB() { + return this.property('powerUSB'); + } + + setPowerUSB(power) { + return this.call(power ? 'set_usb_on' : 'set_usb_off', []) + .then(() => power); + } +} + +module.exports = PlugV1;
90dfee70a122d9aae421413f618fd8f964b7e2f3
src/wx-chart.js
src/wx-chart.js
"use strict"; import WxChart from './charts/wxChart'; import WxDoughnut from '../src/charts/doughnut'; import WxLiner from '../src/charts/liner'; export { WxChart, WxDoughnut, WxLiner };
Add scale & line chart
Add scale & line chart
JavaScript
mit
xch89820/wx-chart,xch89820/wx-chart
--- +++ @@ -0,0 +1,7 @@ +"use strict"; + +import WxChart from './charts/wxChart'; +import WxDoughnut from '../src/charts/doughnut'; +import WxLiner from '../src/charts/liner'; + +export { WxChart, WxDoughnut, WxLiner };
6f31970b38ed42ad82093eca68404c7a7e8398c6
tests/ecmascript/test-dev-array-apply-gaps.js
tests/ecmascript/test-dev-array-apply-gaps.js
/* * From: http://www.2ality.com/2012/06/dense-arrays.html */ /*=== sparse array ,, 3 undefined false dense array trick ,, 3 undefined true 0 undefined 1 undefined 2 undefined 0,1,2 apply trick 0,1,2 3 0 true 0 0 1 1 2 2 0,1,2 ===*/ function test() { var arr; print('sparse array'); arr = new Array(3); print(arr); print(arr.length); print(arr[0]); print('0' in arr); arr.forEach(function (v, i) { print(i, v); }); print('dense array trick'); arr = Array.apply(null, Array(3)); print(arr); print(arr.length); print(arr[0]); print('0' in arr); arr.forEach(function (v, i) { print(i, v); }); print(arr.map(function (v, i) { return i; })); print('apply trick'); arr = Array.apply(null, Array(3)).map(Function.prototype.call.bind(Number)); print(arr); print(arr.length); print(arr[0]); print('0' in arr); arr.forEach(function (v, i) { print(i, v); }); print(arr.map(function (v, i) { return i; })); } try { test(); } catch (e) { print(e.stack || e); }
Add testcase for dense array tricks
Add testcase for dense array tricks
JavaScript
mit
jmptrader/duktape,jmptrader/duktape,jmptrader/duktape,markand/duktape,harold-b/duktape,harold-b/duktape,jmptrader/duktape,markand/duktape,harold-b/duktape,markand/duktape,jmptrader/duktape,harold-b/duktape,markand/duktape,markand/duktape,markand/duktape,harold-b/duktape,harold-b/duktape,svaarala/duktape,markand/duktape,svaarala/duktape,jmptrader/duktape,svaarala/duktape,svaarala/duktape,jmptrader/duktape,svaarala/duktape,svaarala/duktape,harold-b/duktape,markand/duktape,jmptrader/duktape,harold-b/duktape,jmptrader/duktape,jmptrader/duktape,markand/duktape,svaarala/duktape,harold-b/duktape,svaarala/duktape,markand/duktape,svaarala/duktape,harold-b/duktape
--- +++ @@ -0,0 +1,65 @@ +/* + * From: http://www.2ality.com/2012/06/dense-arrays.html + */ + +/*=== +sparse array +,, +3 +undefined +false +dense array trick +,, +3 +undefined +true +0 undefined +1 undefined +2 undefined +0,1,2 +apply trick +0,1,2 +3 +0 +true +0 0 +1 1 +2 2 +0,1,2 +===*/ + +function test() { + var arr; + + print('sparse array'); + arr = new Array(3); + print(arr); + print(arr.length); + print(arr[0]); + print('0' in arr); + arr.forEach(function (v, i) { print(i, v); }); + + print('dense array trick'); + arr = Array.apply(null, Array(3)); + print(arr); + print(arr.length); + print(arr[0]); + print('0' in arr); + arr.forEach(function (v, i) { print(i, v); }); + print(arr.map(function (v, i) { return i; })); + + print('apply trick'); + arr = Array.apply(null, Array(3)).map(Function.prototype.call.bind(Number)); + print(arr); + print(arr.length); + print(arr[0]); + print('0' in arr); + arr.forEach(function (v, i) { print(i, v); }); + print(arr.map(function (v, i) { return i; })); +} + +try { + test(); +} catch (e) { + print(e.stack || e); +}
232ea5587c893f6e285911342c00432431f15fce
src/view.help.js
src/view.help.js
class HelpPopup { constructor($dom, store) { this.$view = $dom.find('.popup') this.store = store } show() { const $view = this.$view const store = this.store const popupShown = store.get(STORE.POPUP) const sidebarVisible = $('html').hasClass(PREFIX) if (popupShown || sidebarVisible) { store.set(STORE.POPUP, true) return } $(document).one(EVENT.TOGGLE, hide) setTimeout(() => { store.set(STORE.POPUP, true) $view.addClass('show').click(hide) setTimeout(hide, 6000) }, 500) function hide() { if ($view.hasClass('show')) { $view.removeClass('show').one('transitionend', () => $view.remove()) } } } }
class HelpPopup { constructor($dom, store) { this.$view = $dom.find('.popup') this.store = store } show() { const $view = this.$view const store = this.store const popupShown = store.get(STORE.POPUP) const sidebarVisible = $('html').hasClass(PREFIX) if (popupShown || sidebarVisible) { return hideAndDestroy() } $(document).one(EVENT.TOGGLE, hideAndDestroy) setTimeout(() => { setTimeout(hideAndDestroy, 6000) $view .addClass('show') .click(hideAndDestroy) }, 500) function hideAndDestroy() { store.set(STORE.POPUP, true) if ($view.hasClass('show')) { $view.removeClass('show').one('transitionend', () => $view.remove()) } else { $view.remove() } } } }
Fix bug of previous commit
Fix bug of previous commit
JavaScript
agpl-3.0
treejames/octotree,duylam/octotree,crashbell/octotree,jamez14/octotree,Ephemera/octotree,Ephemera/octotree,buunguyen/octotree,duylam/octotree,buunguyen/octotree,Brightcells/octotree,crashbell/octotree,treejames/octotree,jamez14/octotree,Brightcells/octotree
--- +++ @@ -9,23 +9,27 @@ const store = this.store const popupShown = store.get(STORE.POPUP) const sidebarVisible = $('html').hasClass(PREFIX) - + if (popupShown || sidebarVisible) { - store.set(STORE.POPUP, true) - return + return hideAndDestroy() } - $(document).one(EVENT.TOGGLE, hide) + $(document).one(EVENT.TOGGLE, hideAndDestroy) setTimeout(() => { - store.set(STORE.POPUP, true) - $view.addClass('show').click(hide) - setTimeout(hide, 6000) + setTimeout(hideAndDestroy, 6000) + $view + .addClass('show') + .click(hideAndDestroy) }, 500) - function hide() { + function hideAndDestroy() { + store.set(STORE.POPUP, true) if ($view.hasClass('show')) { $view.removeClass('show').one('transitionend', () => $view.remove()) + } + else { + $view.remove() } } }
f4bc862bb99dbc6655f8604cb70383402cb03907
simul/app/components/messages.js
simul/app/components/messages.js
import React, { Component } from 'react'; import { StyleSheet, Text, View, } from 'react-native'; class Messages extends Component{ render() { return ( <View style={styles.container}> </View> ) } }; var styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', }, title: { fontSize: 20, alignSelf: 'center', margin: 40 }, }); module.exports = Messages;
Create basic skeleton for Messages view
Create basic skeleton for Messages view
JavaScript
mit
sf-red-pandas-2016/simul-react-native,sf-red-pandas-2016/simul-react-native,sf-red-pandas-2016/simul-react-native
--- +++ @@ -0,0 +1,31 @@ +import React, { Component } from 'react'; + +import { + StyleSheet, + Text, + View, +} from 'react-native'; + +class Messages extends Component{ + render() { + return ( + <View style={styles.container}> + </View> + ) + } +}; + +var styles = StyleSheet.create({ + container: { + flex: 1, + justifyContent: 'center', + alignItems: 'center', + }, + title: { + fontSize: 20, + alignSelf: 'center', + margin: 40 + }, +}); + +module.exports = Messages;
5ff780c429302e65666cd8bf718ffaa95bc2e19d
test/integration/triggers/login.js
test/integration/triggers/login.js
/* This file is a part of libertysoil.org website Copyright (C) 2015 Loki Education (Social Enterprise) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* eslint-env node, mocha */ /* global $dbConfig */ import _ from 'lodash'; import expect from '../../../test-helpers/expect'; import initBookshelf from '../../../src/api/db'; import { initState } from '../../../src/store'; import { ActionsTrigger } from '../../../src/triggers'; import ApiClient from '../../../src/api/client' import { API_HOST } from '../../../src/config'; import UserFactory from '../../../test-helpers/factories/user'; import LabelFactory from '../../../test-helpers/factories/label'; import SchoolFactory from '../../../test-helpers/factories/school'; import GeotagFactory from '../../../test-helpers/factories/geotag'; let bookshelf = initBookshelf($dbConfig); let User = bookshelf.model('User'); describe('"login" trigger', () => { it('adds all needed dependencies to current_user', async () => { let store = initState(); let client = new ApiClient(API_HOST); let triggers = new ActionsTrigger(client, store.dispatch); let userAttrs = UserFactory.build(); let user = await new User(_.omit(userAttrs, 'password')).save(null, {method: 'insert'}); user.followed_labels().create(LabelFactory.build()); user.followed_schools().create(SchoolFactory.build()); user.followed_geotags().create(GeotagFactory.build()); await triggers.login(userAttrs.username, userAttrs.password); expect(store.getState().getIn(['current_user', 'followed_tags']).toJS(), 'not to be empty'); expect(store.getState().getIn(['current_user', 'followed_schools']).toJS(), 'not to be empty'); expect(store.getState().getIn(['current_user', 'followed_geotags']).toJS(), 'not to be empty'); }); });
Add tests checking current_user related models
Add tests checking current_user related models
JavaScript
agpl-3.0
Lokiedu/libertysoil-site,Lokiedu/libertysoil-site
--- +++ @@ -0,0 +1,56 @@ +/* + This file is a part of libertysoil.org website + Copyright (C) 2015 Loki Education (Social Enterprise) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. + */ +/* eslint-env node, mocha */ +/* global $dbConfig */ +import _ from 'lodash'; + + +import expect from '../../../test-helpers/expect'; +import initBookshelf from '../../../src/api/db'; +import { initState } from '../../../src/store'; +import { ActionsTrigger } from '../../../src/triggers'; +import ApiClient from '../../../src/api/client' +import { API_HOST } from '../../../src/config'; +import UserFactory from '../../../test-helpers/factories/user'; +import LabelFactory from '../../../test-helpers/factories/label'; +import SchoolFactory from '../../../test-helpers/factories/school'; +import GeotagFactory from '../../../test-helpers/factories/geotag'; + +let bookshelf = initBookshelf($dbConfig); +let User = bookshelf.model('User'); + +describe('"login" trigger', () => { + it('adds all needed dependencies to current_user', async () => { + let store = initState(); + let client = new ApiClient(API_HOST); + let triggers = new ActionsTrigger(client, store.dispatch); + + let userAttrs = UserFactory.build(); + let user = await new User(_.omit(userAttrs, 'password')).save(null, {method: 'insert'}); + + user.followed_labels().create(LabelFactory.build()); + user.followed_schools().create(SchoolFactory.build()); + user.followed_geotags().create(GeotagFactory.build()); + + await triggers.login(userAttrs.username, userAttrs.password); + + expect(store.getState().getIn(['current_user', 'followed_tags']).toJS(), 'not to be empty'); + expect(store.getState().getIn(['current_user', 'followed_schools']).toJS(), 'not to be empty'); + expect(store.getState().getIn(['current_user', 'followed_geotags']).toJS(), 'not to be empty'); + }); +});
b5656bc25865d17b911a012528af614f56582b9c
files/require-css/0.1.7/css.min.js
files/require-css/0.1.7/css.min.js
define(function(){if("undefined"==typeof window)return{load:function(e,t,n){n()}};var e=document.getElementsByTagName("head")[0],t=window.navigator.userAgent.match(/Trident\/([^ ;]*)|AppleWebKit\/([^ ;]*)|Opera\/([^ ;]*)|rv\:([^ ;]*)(.*?)Gecko\/([^ ;]*)|MSIE\s([^ ;]*)|AndroidWebKit\/([^ ;]*)/)||0,n=!1,r=!0;t[1]||t[7]?n=parseInt(t[1])<6||parseInt(t[7])<=9:t[2]||t[8]?r=!1:t[4]&&(n=parseInt(t[4])<18);var o={};o.pluginBuilder="./css-builder";var a,i,s,l=function(){a=document.createElement("style"),e.appendChild(a),i=a.styleSheet||a.sheet},u=0,d=[],c=function(e){u++,32==u&&(l(),u=0),i.addImport(e),a.onload=function(){f()}},f=function(){s();var e=d.shift();return e?(s=e[1],void c(e[0])):void(s=null)},h=function(e,t){if(i&&i.addImport||l(),i&&i.addImport)s?d.push([e,t]):(c(e),s=t);else{a.textContent='@import "'+e+'";';var n=setInterval(function(){try{a.sheet.cssRules,clearInterval(n),t()}catch(e){}},10)}},p=function(t,n){var o=document.createElement("link");if(o.type="text/css",o.rel="stylesheet",r)o.onload=function(){o.onload=function(){},setTimeout(n,7)};else var a=setInterval(function(){for(var e=0;e<document.styleSheets.length;e++){var t=document.styleSheets[e];if(t.href==o.href)return clearInterval(a),n()}},10);o.href=t,e.appendChild(o)};return o.normalize=function(e,t){return".css"==e.substr(e.length-4,4)&&(e=e.substr(0,e.length-4)),t(e)},o.load=function(e,t,r){(n?h:p)(t.toUrl(e+".css"),r)},o});
Update project require-css to 0.1.7
Update project require-css to 0.1.7
JavaScript
mit
markcarver/jsdelivr,bonbon197/jsdelivr,vvo/jsdelivr,RoberMac/jsdelivr,Heark/jsdelivr,alexmojaki/jsdelivr,wallin/jsdelivr,dandv/jsdelivr,ndamofli/jsdelivr,Sneezry/jsdelivr,spud2451/jsdelivr,vousk/jsdelivr,moay/jsdelivr,walkermatt/jsdelivr,megawac/jsdelivr,evilangelmd/jsdelivr,leebyron/jsdelivr,stevelacy/jsdelivr,hubdotcom/jsdelivr,jtblin/jsdelivr,firulais/jsdelivr,petkaantonov/jsdelivr,markcarver/jsdelivr,ndamofli/jsdelivr,wallin/jsdelivr,garrypolley/jsdelivr,cedricbousmanne/jsdelivr,hubdotcom/jsdelivr,megawac/jsdelivr,therob3000/jsdelivr,stevelacy/jsdelivr,korusdipl/jsdelivr,cake654326/jsdelivr,afghanistanyn/jsdelivr,siscia/jsdelivr,zhuwenxuan/qyerCDN,tunnckoCore/jsdelivr,l3dlp/jsdelivr,alexmojaki/jsdelivr,Heark/jsdelivr,tomByrer/jsdelivr,yaplas/jsdelivr,CTres/jsdelivr,MenZil/jsdelivr,Sneezry/jsdelivr,vousk/jsdelivr,vebin/jsdelivr,evilangelmd/jsdelivr,evilangelmd/jsdelivr,labsvisual/jsdelivr,Metrakit/jsdelivr,l3dlp/jsdelivr,afghanistanyn/jsdelivr,dpellier/jsdelivr,asimihsan/jsdelivr,korusdipl/jsdelivr,jtblin/jsdelivr,MenZil/jsdelivr,garrypolley/jsdelivr,royswastik/jsdelivr,ajkj/jsdelivr,dnbard/jsdelivr,algolia/jsdelivr,ajkj/jsdelivr,labsvisual/jsdelivr,oller/jsdelivr,cognitom/jsdelivr,Metrakit/jsdelivr,RoberMac/jsdelivr,ajibolam/jsdelivr,afghanistanyn/jsdelivr,ManrajGrover/jsdelivr,garrypolley/jsdelivr,Third9/jsdelivr,anilanar/jsdelivr,Swatinem/jsdelivr,asimihsan/jsdelivr,zhuwenxuan/qyerCDN,cedricbousmanne/jsdelivr,justincy/jsdelivr,zhuwenxuan/qyerCDN,yyx990803/jsdelivr,ManrajGrover/jsdelivr,spud2451/jsdelivr,Metrakit/jsdelivr,MenZil/jsdelivr,yyx990803/jsdelivr,firulais/jsdelivr,dnbard/jsdelivr,AdityaManohar/jsdelivr,MichaelSL/jsdelivr,stevelacy/jsdelivr,stevelacy/jsdelivr,Kingside/jsdelivr,ramda/jsdelivr,jtblin/jsdelivr,ManrajGrover/jsdelivr,ndamofli/jsdelivr,evilangelmd/jsdelivr,royswastik/jsdelivr,yyx990803/jsdelivr,cake654326/jsdelivr,siscia/jsdelivr,walkermatt/jsdelivr,cedricbousmanne/jsdelivr,Metrakit/jsdelivr,vvo/jsdelivr,vvo/jsdelivr,rtenshi/jsdelivr,petkaantonov/jsdelivr,Sneezry/jsdelivr,cognitom/jsdelivr,evilangelmd/jsdelivr,markcarver/jsdelivr,ramda/jsdelivr,bdukes/jsdelivr,megawac/jsdelivr,RoberMac/jsdelivr,therob3000/jsdelivr,spud2451/jsdelivr,hubdotcom/jsdelivr,vebin/jsdelivr,ajkj/jsdelivr,gregorypratt/jsdelivr,Swatinem/jsdelivr,dnbard/jsdelivr,rtenshi/jsdelivr,anilanar/jsdelivr,therob3000/jsdelivr,gregorypratt/jsdelivr,AdityaManohar/jsdelivr,justincy/jsdelivr,dpellier/jsdelivr,anilanar/jsdelivr,photonstorm/jsdelivr,cognitom/jsdelivr,tunnckoCore/jsdelivr,MichaelSL/jsdelivr,Metrakit/jsdelivr,yaplas/jsdelivr,Third9/jsdelivr,therob3000/jsdelivr,oller/jsdelivr,garrypolley/jsdelivr,ramda/jsdelivr,Swatinem/jsdelivr,yyx990803/jsdelivr,l3dlp/jsdelivr,firulais/jsdelivr,dpellier/jsdelivr,fchasen/jsdelivr,moay/jsdelivr,Sneezry/jsdelivr,firulais/jsdelivr,towerz/jsdelivr,vebin/jsdelivr,ndamofli/jsdelivr,tomByrer/jsdelivr,wallin/jsdelivr,towerz/jsdelivr,jtblin/jsdelivr,l3dlp/jsdelivr,cesarmarinhorj/jsdelivr,Kingside/jsdelivr,algolia/jsdelivr,cedricbousmanne/jsdelivr,MichaelSL/jsdelivr,spud2451/jsdelivr,korusdipl/jsdelivr,moay/jsdelivr,l3dlp/jsdelivr,ajibolam/jsdelivr,vousk/jsdelivr,tunnckoCore/jsdelivr,MichaelSL/jsdelivr,Heark/jsdelivr,alexmojaki/jsdelivr,yaplas/jsdelivr,CTres/jsdelivr,bdukes/jsdelivr,gregorypratt/jsdelivr,labsvisual/jsdelivr,markcarver/jsdelivr,yaplas/jsdelivr,ntd/jsdelivr,walkermatt/jsdelivr,tunnckoCore/jsdelivr,ramda/jsdelivr,CTres/jsdelivr,towerz/jsdelivr,asimihsan/jsdelivr,Kingside/jsdelivr,tomByrer/jsdelivr,fchasen/jsdelivr,tunnckoCore/jsdelivr,Swatinem/jsdelivr,megawac/jsdelivr,vvo/jsdelivr,jtblin/jsdelivr,hubdotcom/jsdelivr,photonstorm/jsdelivr,ajibolam/jsdelivr,ntd/jsdelivr,firulais/jsdelivr,rtenshi/jsdelivr,towerz/jsdelivr,cesarmarinhorj/jsdelivr,RoberMac/jsdelivr,spud2451/jsdelivr,gregorypratt/jsdelivr,labsvisual/jsdelivr,leebyron/jsdelivr,royswastik/jsdelivr,MichaelSL/jsdelivr,asimihsan/jsdelivr,algolia/jsdelivr,therob3000/jsdelivr,dpellier/jsdelivr,Valve/jsdelivr,dandv/jsdelivr,cesarmarinhorj/jsdelivr,yaplas/jsdelivr,cognitom/jsdelivr,oller/jsdelivr,vebin/jsdelivr,Valve/jsdelivr,RoberMac/jsdelivr,CTres/jsdelivr,royswastik/jsdelivr,dnbard/jsdelivr,fchasen/jsdelivr,hubdotcom/jsdelivr,ajibolam/jsdelivr,Third9/jsdelivr,Kingside/jsdelivr,fchasen/jsdelivr,ManrajGrover/jsdelivr,gregorypratt/jsdelivr,leebyron/jsdelivr,afghanistanyn/jsdelivr,ajibolam/jsdelivr,bonbon197/jsdelivr,siscia/jsdelivr,cesarmarinhorj/jsdelivr,vousk/jsdelivr,cake654326/jsdelivr,oller/jsdelivr,bonbon197/jsdelivr,asimihsan/jsdelivr,algolia/jsdelivr,Swatinem/jsdelivr,Heark/jsdelivr,Valve/jsdelivr,dandv/jsdelivr,Kingside/jsdelivr,Valve/jsdelivr,moay/jsdelivr,ntd/jsdelivr,leebyron/jsdelivr,ManrajGrover/jsdelivr,ajkj/jsdelivr,bonbon197/jsdelivr,bonbon197/jsdelivr,oller/jsdelivr,wallin/jsdelivr,cedricbousmanne/jsdelivr,markcarver/jsdelivr,anilanar/jsdelivr,justincy/jsdelivr,dpellier/jsdelivr,afghanistanyn/jsdelivr,CTres/jsdelivr,petkaantonov/jsdelivr,cesarmarinhorj/jsdelivr,ajkj/jsdelivr,dandv/jsdelivr,stevelacy/jsdelivr,yyx990803/jsdelivr,siscia/jsdelivr,dandv/jsdelivr,photonstorm/jsdelivr,Sneezry/jsdelivr,labsvisual/jsdelivr,AdityaManohar/jsdelivr,fchasen/jsdelivr,Heark/jsdelivr,cake654326/jsdelivr,vvo/jsdelivr,MenZil/jsdelivr,ntd/jsdelivr,alexmojaki/jsdelivr,leebyron/jsdelivr,alexmojaki/jsdelivr,cognitom/jsdelivr,photonstorm/jsdelivr,korusdipl/jsdelivr,ndamofli/jsdelivr,moay/jsdelivr,Valve/jsdelivr,tomByrer/jsdelivr,megawac/jsdelivr,walkermatt/jsdelivr,AdityaManohar/jsdelivr,ntd/jsdelivr,anilanar/jsdelivr,Third9/jsdelivr,garrypolley/jsdelivr,towerz/jsdelivr,zhuwenxuan/qyerCDN,walkermatt/jsdelivr,siscia/jsdelivr,MenZil/jsdelivr,vebin/jsdelivr,vousk/jsdelivr,rtenshi/jsdelivr,justincy/jsdelivr,Third9/jsdelivr,rtenshi/jsdelivr,royswastik/jsdelivr,korusdipl/jsdelivr,petkaantonov/jsdelivr,cake654326/jsdelivr,bdukes/jsdelivr,dnbard/jsdelivr,wallin/jsdelivr,AdityaManohar/jsdelivr,bdukes/jsdelivr,justincy/jsdelivr
--- +++ @@ -0,0 +1 @@ +define(function(){if("undefined"==typeof window)return{load:function(e,t,n){n()}};var e=document.getElementsByTagName("head")[0],t=window.navigator.userAgent.match(/Trident\/([^ ;]*)|AppleWebKit\/([^ ;]*)|Opera\/([^ ;]*)|rv\:([^ ;]*)(.*?)Gecko\/([^ ;]*)|MSIE\s([^ ;]*)|AndroidWebKit\/([^ ;]*)/)||0,n=!1,r=!0;t[1]||t[7]?n=parseInt(t[1])<6||parseInt(t[7])<=9:t[2]||t[8]?r=!1:t[4]&&(n=parseInt(t[4])<18);var o={};o.pluginBuilder="./css-builder";var a,i,s,l=function(){a=document.createElement("style"),e.appendChild(a),i=a.styleSheet||a.sheet},u=0,d=[],c=function(e){u++,32==u&&(l(),u=0),i.addImport(e),a.onload=function(){f()}},f=function(){s();var e=d.shift();return e?(s=e[1],void c(e[0])):void(s=null)},h=function(e,t){if(i&&i.addImport||l(),i&&i.addImport)s?d.push([e,t]):(c(e),s=t);else{a.textContent='@import "'+e+'";';var n=setInterval(function(){try{a.sheet.cssRules,clearInterval(n),t()}catch(e){}},10)}},p=function(t,n){var o=document.createElement("link");if(o.type="text/css",o.rel="stylesheet",r)o.onload=function(){o.onload=function(){},setTimeout(n,7)};else var a=setInterval(function(){for(var e=0;e<document.styleSheets.length;e++){var t=document.styleSheets[e];if(t.href==o.href)return clearInterval(a),n()}},10);o.href=t,e.appendChild(o)};return o.normalize=function(e,t){return".css"==e.substr(e.length-4,4)&&(e=e.substr(0,e.length-4)),t(e)},o.load=function(e,t,r){(n?h:p)(t.toUrl(e+".css"),r)},o});
9a55efa6bfe0f301f7e499b92c588dfb03b2b259
eelfortune.js
eelfortune.js
// Solution to "Eel of Fortune" challenge from /r/DailyProgrammer // https://www.reddit.com/r/dailyprogrammer/comments/3ddpms/ // 20150715_challenge_223_intermediate_eel_of_fortune/ function isProblem(text, subword) { var subIndex = 0; for (var i = 0; i < text.length; i++) { if (subword.charAt(subIndex) === text.charAt(i)) { subIndex++; if (subIndex === subword.length) { return true; } } } return false; } function isProblemRegex(text, subword) { var regexArr = new Array(subword.length * 2); for (var i = 0; i < subword; i++) { regexArr[i * 2] = subword.charAt(i); regexArr[i * 2 + 1] = '*'; } var regex = new RegExp(regexArr.join('')); return regex.test(text); }
Add Eel of Fortune problem solution
Add Eel of Fortune problem solution
JavaScript
mit
strburst/js-stuff,strburst/js-stuff
--- +++ @@ -0,0 +1,29 @@ +// Solution to "Eel of Fortune" challenge from /r/DailyProgrammer +// https://www.reddit.com/r/dailyprogrammer/comments/3ddpms/ +// 20150715_challenge_223_intermediate_eel_of_fortune/ +function isProblem(text, subword) { + var subIndex = 0; + + for (var i = 0; i < text.length; i++) { + if (subword.charAt(subIndex) === text.charAt(i)) { + subIndex++; + + if (subIndex === subword.length) { + return true; + } + } + } + + return false; +} + +function isProblemRegex(text, subword) { + var regexArr = new Array(subword.length * 2); + for (var i = 0; i < subword; i++) { + regexArr[i * 2] = subword.charAt(i); + regexArr[i * 2 + 1] = '*'; + } + + var regex = new RegExp(regexArr.join('')); + return regex.test(text); +}
6840bfe052860b4231250ae685eb7378cd4c7f96
test/boolean_test.js
test/boolean_test.js
"use strict"; var React = require("react"); var Helper = require("./helper"); var document = <h1 />; var assertEvaluatesToValue = Helper.assertEvaluatesToValue.bind(null, document); suite("XPathDOM", function () { suite("boolean", function () { test("00", function () { assertEvaluatesToValue("//h1 and //h1", true); }); test("01", function () { assertEvaluatesToValue("//h1 and //foo", false); }); test("02", function () { assertEvaluatesToValue("//h1 or //h1", true); }); test("03", function () { assertEvaluatesToValue("//h1 or //foo", true); }); test("04", function () { assertEvaluatesToValue("//foo or //h1", true); }); test("05", function () { assertEvaluatesToValue("//foo or //bar", false); }); }); });
Add some tests for boolean logic
Add some tests for boolean logic The observant reader will notice that none of these pass either.
JavaScript
mit
badeball/xpath-react,badeball/xpath-react
--- +++ @@ -0,0 +1,37 @@ +"use strict"; + +var React = require("react"); + +var Helper = require("./helper"); + +var document = <h1 />; + +var assertEvaluatesToValue = Helper.assertEvaluatesToValue.bind(null, document); + +suite("XPathDOM", function () { + suite("boolean", function () { + test("00", function () { + assertEvaluatesToValue("//h1 and //h1", true); + }); + + test("01", function () { + assertEvaluatesToValue("//h1 and //foo", false); + }); + + test("02", function () { + assertEvaluatesToValue("//h1 or //h1", true); + }); + + test("03", function () { + assertEvaluatesToValue("//h1 or //foo", true); + }); + + test("04", function () { + assertEvaluatesToValue("//foo or //h1", true); + }); + + test("05", function () { + assertEvaluatesToValue("//foo or //bar", false); + }); + }); +});
31aa31a406a79be10bd34e6f74bbe554de98dcbc
server/modules/readData.js
server/modules/readData.js
// import necessary module import jsonfile from 'jsonfile'; /* Function returns the content of a json file @param file is the file path */ const readData = (file => jsonfile.readFileSync(file)); export default readData;
Add function to read json files
Add function to read json files
JavaScript
mit
amarachukwu-agbo/hello-books,amarachukwu-agbo/hello-books
--- +++ @@ -0,0 +1,7 @@ +// import necessary module +import jsonfile from 'jsonfile'; + +/* Function returns the content of a json file +@param file is the file path */ +const readData = (file => jsonfile.readFileSync(file)); +export default readData;
1698c33d01da5d99f057b92ed72677fb1eebf6a2
node/index.js
node/index.js
// Impots and packages const CONFIG = require('./config/config.js') const WEBSOCKET = CONFIG.WEBSOCKET const Wampy = require('wampy').Wampy // Websockets options const wsOptions = { ws: WEBSOCKET.CLIENT, realm: WEBSOCKET.REALM } // Builds connections objetct const connection = new Wampy(WEBSOCKET.URL) // Exports Config object module.exports.CONFIG = CONFIG // Exports connection object module.exports.connection = connection
Adjust imports for new modules
Adjust imports for new modules
JavaScript
mit
ConnApp/connapp-wamp
--- +++ @@ -0,0 +1,19 @@ +// Impots and packages +const CONFIG = require('./config/config.js') +const WEBSOCKET = CONFIG.WEBSOCKET +const Wampy = require('wampy').Wampy + +// Websockets options +const wsOptions = { + ws: WEBSOCKET.CLIENT, + realm: WEBSOCKET.REALM +} + +// Builds connections objetct +const connection = new Wampy(WEBSOCKET.URL) + +// Exports Config object +module.exports.CONFIG = CONFIG + +// Exports connection object +module.exports.connection = connection
613b3f54bc12f247a2a4489f27c21cc5f02ffd18
bookmarklet.min.js
bookmarklet.min.js
(function(){var e=function(){var e=window.location.href,t=function(){var e=document.querySelectorAll("a.marker");for(var t=0;t<e.length;++t){var n=e[t];n.parentNode.removeChild(n)}},n=function(){var e=document.querySelectorAll("a[name]");for(var t=0;t<e.length;++t){var n=e[t];if(n.href==""){var r=s(n);n.parentNode.insertBefore(r,n.nextSibling)}}},r=function(e){return"#"+e.name},i=function(t){return e+t},s=function(e){var t=r(e),n=document.createElement("a");return n.className="marker",n.innerHTML=r(e),n.href=i(t),n},o=function(){var e="a.marker{background: red;box-shadow: 0 2px #cc0000;border-radius: 8px;padding: 4px 6px 2px 6px;margin-left: 3px;font-family: Helvetica, Arial, sans-serif;font-size: 12px;color: #FFF0F5;text-decoration: none;}",t=document.createElement("style");t.appendChild(document.createTextNode(e)),document.body.appendChild(t)},u=function(){o(),n()};return{highlight:u}}();e.highlight()})();
Add compressed version of the JavaScript
Add compressed version of the JavaScript
JavaScript
mit
jordelver/anchor-highlight
--- +++ @@ -0,0 +1 @@ +(function(){var e=function(){var e=window.location.href,t=function(){var e=document.querySelectorAll("a.marker");for(var t=0;t<e.length;++t){var n=e[t];n.parentNode.removeChild(n)}},n=function(){var e=document.querySelectorAll("a[name]");for(var t=0;t<e.length;++t){var n=e[t];if(n.href==""){var r=s(n);n.parentNode.insertBefore(r,n.nextSibling)}}},r=function(e){return"#"+e.name},i=function(t){return e+t},s=function(e){var t=r(e),n=document.createElement("a");return n.className="marker",n.innerHTML=r(e),n.href=i(t),n},o=function(){var e="a.marker{background: red;box-shadow: 0 2px #cc0000;border-radius: 8px;padding: 4px 6px 2px 6px;margin-left: 3px;font-family: Helvetica, Arial, sans-serif;font-size: 12px;color: #FFF0F5;text-decoration: none;}",t=document.createElement("style");t.appendChild(document.createTextNode(e)),document.body.appendChild(t)},u=function(){o(),n()};return{highlight:u}}();e.highlight()})();
673105e648ad752ce32cd431aba725e98b09e27a
test/routes/camera-control.js
test/routes/camera-control.js
import supertest from "supertest"; import app from "../../app.js"; const request = supertest(app); describe("Routes: Camera Control", () => { it("GET /camera-control", done => { request.get("/camera-control") .expect(200) .end(err => done(err)); }); });
Add Camera Control Route Test
Add Camera Control Route Test
JavaScript
apache-2.0
bartdejonge1996/goto-fail-webserver,bartdejonge1996/goto-fail-webserver
--- +++ @@ -0,0 +1,12 @@ +import supertest from "supertest"; +import app from "../../app.js"; + +const request = supertest(app); + +describe("Routes: Camera Control", () => { + it("GET /camera-control", done => { + request.get("/camera-control") + .expect(200) + .end(err => done(err)); + }); +});
9c290c56fd3c3192d2126a60a39276b7f7870d9c
node/src/main/lib.js
node/src/main/lib.js
'use strict'; var vcapParser = require('./vcap-parser'), bluemix = require('./bluemix/bluemix'); module.exports = { Parser : vcapParser.Parser, bluemix : bluemix.plugins };
Add main module for exporting externally.
Add main module for exporting externally.
JavaScript
mit
mattunderscorechampion/vcap-services-parser
--- +++ @@ -0,0 +1,10 @@ + +'use strict'; + +var vcapParser = require('./vcap-parser'), + bluemix = require('./bluemix/bluemix'); + +module.exports = { + Parser : vcapParser.Parser, + bluemix : bluemix.plugins +};
15697ac9bad50e2037009089e3d69e50128b63a7
spec/prompt-view-list-spec.js
spec/prompt-view-list-spec.js
'use babel' import PromptViewList from '../lib/prompt-view-list'; describe('PromptViewList', () => { describe('when setItem is called', () => { it('changes the selected item', () => { const list = new PromptViewList() list.initialize() list.open(['1', '2', '3']) list.setItem('1') expect(list.getItem()).toBe('1') }) }) })
Add the test case of PromptViewList
Add the test case of PromptViewList ref #34
JavaScript
mit
HiroakiMikami/atom-user-support-helper
--- +++ @@ -0,0 +1,15 @@ +'use babel' + +import PromptViewList from '../lib/prompt-view-list'; + +describe('PromptViewList', () => { + describe('when setItem is called', () => { + it('changes the selected item', () => { + const list = new PromptViewList() + list.initialize() + list.open(['1', '2', '3']) + list.setItem('1') + expect(list.getItem()).toBe('1') + }) + }) +})
6d454ec84ecc170412ab687346d7c588e3fc8a31
alien4cloud-ui/yo/app/scripts/cloud-images/controllers/new_cloud_image.js
alien4cloud-ui/yo/app/scripts/cloud-images/controllers/new_cloud_image.js
'use strict'; angular.module('alienUiApp').controller( 'NewCloudImageController', [ '$scope', '$modalInstance', 'cloudImageServices', function($scope, $modalInstance, cloudImageServices) { $scope.cloudImageFormDescriptor = cloudImageServices.getFormDescriptor(); $scope.cloudImage = {}; $scope.save = function(cloudImage) { cloudImageServices.create({}, angular.toJson(cloudImage)).$promise.then(function(success){ $modalInstance.close(success.data); }); }; $scope.cancel = function() { $modalInstance.dismiss('cancel'); }; } ] );
/* global UTILS */ 'use strict'; angular.module('alienUiApp').controller( 'NewCloudImageController', [ '$scope', '$modalInstance', 'cloudImageServices','$q', function($scope, $modalInstance, cloudImageServices, $q) { $scope.cloudImageFormDescriptor = cloudImageServices.getFormDescriptor(); $scope.cloudImage = {}; $scope.save = function(cloudImage) { return cloudImageServices.create({}, angular.toJson(cloudImage), function success(response) { if (UTILS.isDefinedAndNotNull(response.error)) { var errorsHandle = $q.defer(); return errorsHandle.resolve(response.error); } else { $modalInstance.close(response.data); } }).$promise; }; $scope.cancel = function() { $modalInstance.dismiss('cancel'); }; } ] );
Remove a wrong toaster in new cloud image
Fix: Remove a wrong toaster in new cloud image
JavaScript
apache-2.0
san-tak/alien4cloud,san-tak/alien4cloud,igorng/alien4cloud,PierreLemordant/alien4cloud,ngouagna/alien4cloud,PierreLemordant/alien4cloud,alien4cloud/alien4cloud,loicalbertin/alien4cloud,broly-git/alien4cloud,broly-git/alien4cloud,PierreLemordant/alien4cloud,san-tak/alien4cloud,ngouagna/alien4cloud,loicalbertin/alien4cloud,OresteVisari/alien4cloud,ahgittin/alien4cloud,alien4cloud/alien4cloud,igorng/alien4cloud,igorng/alien4cloud,loicalbertin/alien4cloud,alien4cloud/alien4cloud,xdegenne/alien4cloud,loicalbertin/alien4cloud,xdegenne/alien4cloud,OresteVisari/alien4cloud,ahgittin/alien4cloud,igorng/alien4cloud,broly-git/alien4cloud,ahgittin/alien4cloud,xdegenne/alien4cloud,xdegenne/alien4cloud,OresteVisari/alien4cloud,broly-git/alien4cloud,alien4cloud/alien4cloud,PierreLemordant/alien4cloud,san-tak/alien4cloud,ahgittin/alien4cloud,ngouagna/alien4cloud,ngouagna/alien4cloud,OresteVisari/alien4cloud
--- +++ @@ -1,20 +1,21 @@ +/* global UTILS */ 'use strict'; angular.module('alienUiApp').controller( - 'NewCloudImageController', [ - '$scope', - '$modalInstance', - 'cloudImageServices', - function($scope, $modalInstance, cloudImageServices) { - + 'NewCloudImageController', [ '$scope', '$modalInstance', 'cloudImageServices','$q', + function($scope, $modalInstance, cloudImageServices, $q) { $scope.cloudImageFormDescriptor = cloudImageServices.getFormDescriptor(); - $scope.cloudImage = {}; $scope.save = function(cloudImage) { - cloudImageServices.create({}, angular.toJson(cloudImage)).$promise.then(function(success){ - $modalInstance.close(success.data); - }); + return cloudImageServices.create({}, angular.toJson(cloudImage), function success(response) { + if (UTILS.isDefinedAndNotNull(response.error)) { + var errorsHandle = $q.defer(); + return errorsHandle.resolve(response.error); + } else { + $modalInstance.close(response.data); + } + }).$promise; }; $scope.cancel = function() {
8f25f3530ebe9e8622fbeb0944d651831314aa3e
src/utils/download-as-csv.js
src/utils/download-as-csv.js
import * as Papa from 'papaparse'; const downloadAsCsv = function (arr) { const csv = Papa.unparse(arr); const data = `text/csv;charset=utf-8,${csv}`; const a = document.createElement('a'); a.href = `data:${data}`; a.download = 'hipiler-piles.csv'; a.innerHTML = ''; document.body.appendChild(a); a.click(); a.remove(); }; export default downloadAsCsv;
Add a method for exporting CSV
Add a method for exporting CSV
JavaScript
mit
flekschas/hipiler,flekschas/hipiler,flekschas/hipiler
--- +++ @@ -0,0 +1,15 @@ +import * as Papa from 'papaparse'; + +const downloadAsCsv = function (arr) { + const csv = Papa.unparse(arr); + const data = `text/csv;charset=utf-8,${csv}`; + const a = document.createElement('a'); + a.href = `data:${data}`; + a.download = 'hipiler-piles.csv'; + a.innerHTML = ''; + document.body.appendChild(a); + a.click(); + a.remove(); +}; + +export default downloadAsCsv;
962561892bb72ff4c9e0812ea271e540a80e31a0
test/enotsup.js
test/enotsup.js
var fs = require('fs') var readdir = fs.readdir fs.readdir = function (path, cb) { fs.stat(path, function (er, stat) { if (er) return cb(er) if (!stat.isDirectory()) { er = new Error('ENOTSUP: Operation not supported') er.path = path er.code = 'ENOTSUP' return cb(er) } return readdir.call(fs, path, cb) }) } var glob = require('../') var test = require('tap').test var common = require('../common.js') process.chdir(__dirname + '/fixtures') var pattern = 'a/**/h' var expect = [ 'a/abcdef/g/h', 'a/abcfed/g/h' ] var options = { strict: true } test(pattern + ' ' + JSON.stringify(options), function (t) { var res = glob.sync(pattern, options).sort() t.same(res, expect, 'sync results') var g = glob(pattern, options, function (er, res) { if (er) throw er res = res.sort() t.same(res, expect, 'async results') t.end() }) })
Test for when readdir raises ENOTSUP
Test for when readdir raises ENOTSUP Treat as if it had raised ENOTDIR instead.
JavaScript
isc
isaacs/node-glob,andypatterson/node-glob,jeonghwan-kim/node-glob,lostthetrail/node-glob,behind2/node-glob,wjb12/node-glob,jeonghwan-kim/node-glob,wjb12/node-glob,Nedomas/node-glob,isaacs/node-glob,shinygang/node-glob,shinygang/node-glob,cgvarela/node-glob,andypatterson/node-glob,Nedomas/node-glob,behind2/node-glob,lostthetrail/node-glob,cgvarela/node-glob
--- +++ @@ -0,0 +1,36 @@ +var fs = require('fs') +var readdir = fs.readdir +fs.readdir = function (path, cb) { + fs.stat(path, function (er, stat) { + if (er) + return cb(er) + if (!stat.isDirectory()) { + er = new Error('ENOTSUP: Operation not supported') + er.path = path + er.code = 'ENOTSUP' + return cb(er) + } + return readdir.call(fs, path, cb) + }) +} + +var glob = require('../') +var test = require('tap').test +var common = require('../common.js') +process.chdir(__dirname + '/fixtures') + +var pattern = 'a/**/h' +var expect = [ 'a/abcdef/g/h', 'a/abcfed/g/h' ] +var options = { strict: true } + +test(pattern + ' ' + JSON.stringify(options), function (t) { + var res = glob.sync(pattern, options).sort() + t.same(res, expect, 'sync results') + var g = glob(pattern, options, function (er, res) { + if (er) + throw er + res = res.sort() + t.same(res, expect, 'async results') + t.end() + }) +})
1b42ae0f4147b517f80ff58e828b28d1538677d4
server/providers.js
server/providers.js
module.exports = { "facebook-login": { "provider": "facebook", "module": "passport-facebook", "clientID": process.env.FACEBOOK_CLIENT_ID, "clientSecret": process.env.FACEBOOK_SECRET_ID, "callbackURL": "/auth/facebook/callback", "authPath": "/auth/facebook", "callbackPath": "/auth/facebook/callback", "successRedirect": "/auth/account", "failureRedirect": "/login", "scope": [], "failureFlash": true } };
Add social login provider settings.
Add social login provider settings.
JavaScript
apache-2.0
remp-team/remp-api
--- +++ @@ -0,0 +1,15 @@ +module.exports = { + "facebook-login": { + "provider": "facebook", + "module": "passport-facebook", + "clientID": process.env.FACEBOOK_CLIENT_ID, + "clientSecret": process.env.FACEBOOK_SECRET_ID, + "callbackURL": "/auth/facebook/callback", + "authPath": "/auth/facebook", + "callbackPath": "/auth/facebook/callback", + "successRedirect": "/auth/account", + "failureRedirect": "/login", + "scope": [], + "failureFlash": true + } +};
0910dfedce182dab057f095e3980873f382fc226
src/checkout.js
src/checkout.js
var fs = require('fs'); var nodePath = require('path'); var index = require('./index'); var files = require('./files'); var objects = require('./objects'); var refs = require('./refs'); var diff = require('./diff'); var util = require('./util'); var checkout = module.exports = { readChangedFilesCheckoutWouldOverwrite: function(checkoutHash) { var localChanges = diff.readDiff("HEAD"); var headToBranchChanges = diff.readDiff("HEAD", checkoutHash); return Object.keys(localChanges) .filter(function(path) { return path in headToBranchChanges; }); }, writeCheckout: function(ref) { addModifyDelete("HEAD", refs.readHash(ref)); } }; function addModifyDelete(diffFromRef, diffToRef) { var changes = diff.readDiff(diffFromRef, diffToRef); var checkoutIndex = index.readCommitIndex(diffToRef); Object.keys(changes).forEach(function(path) { if (changes[path] === diff.FILE_STATUS.ADD || changes[path] === diff.FILE_STATUS.MODIFY) { // no line by line for now var content = objects.read(checkoutIndex[path]); files.writeFilesFromTree(util.assocIn({}, path.split(nodePath.sep).concat(content)), files.repoDir()); } else if (changes[path] === diff.FILE_STATUS.DELETE) { fs.unlinkSync(path); } }); };
var fs = require('fs'); var nodePath = require('path'); var index = require('./index'); var files = require('./files'); var objects = require('./objects'); var refs = require('./refs'); var diff = require('./diff'); var util = require('./util'); var checkout = module.exports = { readChangedFilesCheckoutWouldOverwrite: function(checkoutHash) { var localChanges = diff.readDiff("HEAD"); var headToBranchChanges = diff.readDiff("HEAD", checkoutHash); return Object.keys(localChanges) .filter(function(path) { return path in headToBranchChanges; }); }, writeCheckout: function(ref) { addModifyDelete("HEAD", refs.readHash(ref)); refs.write("HEAD", objects.read(ref) ? ref : refs.nameToBranchRef(ref)); } }; function addModifyDelete(diffFromRef, diffToRef) { var changes = diff.readDiff(diffFromRef, diffToRef); var checkoutIndex = index.readCommitIndex(diffToRef); Object.keys(changes).forEach(function(path) { if (changes[path] === diff.FILE_STATUS.ADD || changes[path] === diff.FILE_STATUS.MODIFY) { // no line by line for now var content = objects.read(checkoutIndex[path]); files.writeFilesFromTree(util.assocIn({}, path.split(nodePath.sep).concat(content)), files.repoDir()); } else if (changes[path] === diff.FILE_STATUS.DELETE) { fs.unlinkSync(path); } }); };
Set HEAD to new ref when checking out
Set HEAD to new ref when checking out
JavaScript
mit
harrytruong/gitlet,maryrosecook/gitlet,pirafrank/gitlet,maryrosecook/gitlet,harrytruong/gitlet,pysnow530/gitlet,pirafrank/gitlet
--- +++ @@ -17,6 +17,7 @@ writeCheckout: function(ref) { addModifyDelete("HEAD", refs.readHash(ref)); + refs.write("HEAD", objects.read(ref) ? ref : refs.nameToBranchRef(ref)); } };
2cab856f9bf53f618a1d5273651c2886eb0226b4
src/commands/assign/selectScripts.js
src/commands/assign/selectScripts.js
// node modules import fs from 'fs'; import readline from 'readline'; // npm modules import inquirer from 'inquirer'; // our modules import {config} from '../../utils'; function validatePath(userPath) { try { return fs.statSync(userPath).isFile(); } catch (e) { // Check exception. If ENOENT - no such file or directory ok, file doesn't exist. // Otherwise something else went wrong, we don't have rights to access the file, ... if (e.code !== 'ENOENT') { throw e; } return 'File does not exist. Please enter a valid path.'; } } async function selectScripts() { const certifications = Object.keys(config.certs) .map(cert => ({ name: config.certs[cert].name, checked: false, value: cert, })); const choices = [new inquirer.Separator('\nConfigure scripts for the following projects:')] .concat(certifications); // Clearing the screen. readline.cursorTo(process.stdout, 0, 0); readline.clearScreenDown(process.stdout); const selections = await inquirer.prompt([{ type: 'checkbox', message: 'Select option(s) to toggle ON/OFF:\n', name: 'projectIds', choices, pageSize: 15, }]); const questions = selections.projectIds .map(id => ({ type: 'input', name: id, message: `Input script path for project ${id}`, validate: validatePath, })); const answers = await inquirer.prompt(questions); return answers; } export default selectScripts;
Add scripts to configuration of assign command
Add scripts to configuration of assign command
JavaScript
mit
trolster/urcli,gabraganca/ur-cli,trolster/ur-cli
--- +++ @@ -0,0 +1,55 @@ +// node modules +import fs from 'fs'; +import readline from 'readline'; +// npm modules +import inquirer from 'inquirer'; +// our modules +import {config} from '../../utils'; + +function validatePath(userPath) { + try { + return fs.statSync(userPath).isFile(); + } catch (e) { + // Check exception. If ENOENT - no such file or directory ok, file doesn't exist. + // Otherwise something else went wrong, we don't have rights to access the file, ... + if (e.code !== 'ENOENT') { + throw e; + } + return 'File does not exist. Please enter a valid path.'; + } +} + +async function selectScripts() { + const certifications = Object.keys(config.certs) + .map(cert => ({ + name: config.certs[cert].name, + checked: false, + value: cert, + })); + + const choices = [new inquirer.Separator('\nConfigure scripts for the following projects:')] + .concat(certifications); + + // Clearing the screen. + readline.cursorTo(process.stdout, 0, 0); + readline.clearScreenDown(process.stdout); + + const selections = await inquirer.prompt([{ + type: 'checkbox', + message: 'Select option(s) to toggle ON/OFF:\n', + name: 'projectIds', + choices, + pageSize: 15, + }]); + const questions = selections.projectIds + .map(id => ({ + type: 'input', + name: id, + message: `Input script path for project ${id}`, + validate: validatePath, + })); + const answers = await inquirer.prompt(questions); + return answers; +} + +export default selectScripts;
febdc045d1476eabcfeddd4ff4f734f53d99cabc
lib/glob_test.js
lib/glob_test.js
// Apply glob function to path specified on command line. var glob = require('./glob'); if (process.argv.length != 3) { console.log("Bad usage"); process.exit(1); } glob.glob(process.argv[2], function (err, files) { if (err) { console.log(err); } else { files.forEach(function (file) { console.log(file); }); } });
Add utility for testing glob.js
Add utility for testing glob.js
JavaScript
mit
sstur/nodeftpd,impaler/nodeftpd,phillipgreenii/nodeftpd,oleksiyk/nodeftpd
--- +++ @@ -0,0 +1,19 @@ +// Apply glob function to path specified on command line. + +var glob = require('./glob'); + +if (process.argv.length != 3) { + console.log("Bad usage"); + process.exit(1); +} + +glob.glob(process.argv[2], function (err, files) { + if (err) { + console.log(err); + } + else { + files.forEach(function (file) { + console.log(file); + }); + } +});
5a3202480e1e150c5c2194d57aff74133a5cc096
international.js
international.js
function hello(language) { var hellos = { 'Chinese': '你好世界', 'Dutch': 'Hello wereld', 'English': 'Hello world', 'French': 'Bonjour monde', 'German': 'Hallo Welt', 'Greek': 'γειά σου κόσμος', 'Italian': 'Ciao mondo', 'Japanese': 'こんにちは世界', 'Korean': '안녕하세요 세계', 'Portuguese': 'Olá mundo', 'Russian': 'Здравствулте мир', 'Spanish': 'Hola mundo', 'Latin': 'Salve munde', 'Piglatin': 'Ellohay orldway' }; return hellos[language]; }
Add hello world in some other languages.
Add hello world in some other languages.
JavaScript
mit
tjhorner/illacceptanything,illacceptanything/illacceptanything,oneminot/illacceptanything,TheWhiteLlama/illacceptanything,Depado/illacceptanything,Depado/illacceptanything,tjhorner/illacceptanything,1yvT0s/illacceptanything,gaapt/illacceptanything,ultranaut/illacceptanything,oneminot/illacceptanything,1yvT0s/illacceptanything,TheWhiteLlama/illacceptanything,triggerNZ/illacceptanything,oneminot/illacceptanything,ds84182/illacceptanything,dushmis/illacceptanything,1yvT0s/illacceptanything,oneminot/illacceptanything,dushmis/illacceptanything,triggerNZ/illacceptanything,ultranaut/illacceptanything,ultranaut/illacceptanything,ds84182/illacceptanything,TheWhiteLlama/illacceptanything,paladique/illacceptanything,joelgarciajr84/illacceptanything,dushmis/illacceptanything,Depado/illacceptanything,ultranaut/illacceptanything,tjhorner/illacceptanything,ds84182/illacceptanything,joelgarciajr84/illacceptanything,ultranaut/illacceptanything,joelgarciajr84/illacceptanything,ocanbascil/illacceptanything,gaapt/illacceptanything,gaapt/illacceptanything,Munter/illacceptanything,JeffreyCA/illacceptanything,Munter/illacceptanything,gaapt/illacceptanything,illacceptanything/illacceptanything,tjhorner/illacceptanything,triggerNZ/illacceptanything,JeffreyCA/illacceptanything,dushmis/illacceptanything,triggerNZ/illacceptanything,dushmis/illacceptanything,JeffreyCA/illacceptanything,illacceptanything/illacceptanything,Depado/illacceptanything,Depado/illacceptanything,ds84182/illacceptanything,Munter/illacceptanything,TheWhiteLlama/illacceptanything,Munter/illacceptanything,dushmis/illacceptanything,TheWhiteLlama/illacceptanything,caioproiete/illacceptanything,ds84182/illacceptanything,illacceptanything/illacceptanything,JeffreyCA/illacceptanything,ultranaut/illacceptanything,Depado/illacceptanything,paladique/illacceptanything,ds84182/illacceptanything,ds84182/illacceptanything,ocanbascil/illacceptanything,ocanbascil/illacceptanything,joelgarciajr84/illacceptanything,oneminot/illacceptanything,TheWhiteLlama/illacceptanything,paladique/illacceptanything,joelgarciajr84/illacceptanything,joelgarciajr84/illacceptanything,triggerNZ/illacceptanything,ultranaut/illacceptanything,dushmis/illacceptanything,JeffreyCA/illacceptanything,paladique/illacceptanything,triggerNZ/illacceptanything,TheWhiteLlama/illacceptanything,oneminot/illacceptanything,TheWhiteLlama/illacceptanything,paladique/illacceptanything,ds84182/illacceptanything,JeffreyCA/illacceptanything,TheWhiteLlama/illacceptanything,1yvT0s/illacceptanything,ocanbascil/illacceptanything,TheWhiteLlama/illacceptanything,caioproiete/illacceptanything,ds84182/illacceptanything,1yvT0s/illacceptanything,gaapt/illacceptanything,Depado/illacceptanything,triggerNZ/illacceptanything,caioproiete/illacceptanything,dushmis/illacceptanything,tjhorner/illacceptanything,TheWhiteLlama/illacceptanything,joelgarciajr84/illacceptanything,paladique/illacceptanything,illacceptanything/illacceptanything,illacceptanything/illacceptanything,ocanbascil/illacceptanything,oneminot/illacceptanything,Munter/illacceptanything,1yvT0s/illacceptanything,paladique/illacceptanything,ds84182/illacceptanything,Depado/illacceptanything,caioproiete/illacceptanything,triggerNZ/illacceptanything,dushmis/illacceptanything,JeffreyCA/illacceptanything,caioproiete/illacceptanything,paladique/illacceptanything,dushmis/illacceptanything,caioproiete/illacceptanything,tjhorner/illacceptanything,TheWhiteLlama/illacceptanything,ultranaut/illacceptanything,tjhorner/illacceptanything,dushmis/illacceptanything,tjhorner/illacceptanything,TheWhiteLlama/illacceptanything,paladique/illacceptanything,JeffreyCA/illacceptanything,dushmis/illacceptanything,illacceptanything/illacceptanything,JeffreyCA/illacceptanything,ultranaut/illacceptanything,Depado/illacceptanything,1yvT0s/illacceptanything,ocanbascil/illacceptanything,Munter/illacceptanything,illacceptanything/illacceptanything,caioproiete/illacceptanything,joelgarciajr84/illacceptanything,TheWhiteLlama/illacceptanything,ds84182/illacceptanything,ultranaut/illacceptanything,dushmis/illacceptanything,paladique/illacceptanything,caioproiete/illacceptanything,ultranaut/illacceptanything,dushmis/illacceptanything,TheWhiteLlama/illacceptanything,triggerNZ/illacceptanything,JeffreyCA/illacceptanything,paladique/illacceptanything,illacceptanything/illacceptanything,oneminot/illacceptanything,illacceptanything/illacceptanything,triggerNZ/illacceptanything,JeffreyCA/illacceptanything,triggerNZ/illacceptanything,gaapt/illacceptanything,paladique/illacceptanything,oneminot/illacceptanything,illacceptanything/illacceptanything,ds84182/illacceptanything,JeffreyCA/illacceptanything,ultranaut/illacceptanything,tjhorner/illacceptanything,tjhorner/illacceptanything,ds84182/illacceptanything,ultranaut/illacceptanything,tjhorner/illacceptanything,Munter/illacceptanything,caioproiete/illacceptanything,Munter/illacceptanything,1yvT0s/illacceptanything,oneminot/illacceptanything,caioproiete/illacceptanything,triggerNZ/illacceptanything,caioproiete/illacceptanything,triggerNZ/illacceptanything,tjhorner/illacceptanything,tjhorner/illacceptanything,Munter/illacceptanything,1yvT0s/illacceptanything,paladique/illacceptanything,1yvT0s/illacceptanything,oneminot/illacceptanything,1yvT0s/illacceptanything,1yvT0s/illacceptanything,caioproiete/illacceptanything,ultranaut/illacceptanything,gaapt/illacceptanything,paladique/illacceptanything,1yvT0s/illacceptanything,JeffreyCA/illacceptanything,illacceptanything/illacceptanything,JeffreyCA/illacceptanything,gaapt/illacceptanything,oneminot/illacceptanything,1yvT0s/illacceptanything,Depado/illacceptanything,oneminot/illacceptanything,caioproiete/illacceptanything,illacceptanything/illacceptanything,joelgarciajr84/illacceptanything,dushmis/illacceptanything,caioproiete/illacceptanything,caioproiete/illacceptanything,triggerNZ/illacceptanything,ds84182/illacceptanything,gaapt/illacceptanything,oneminot/illacceptanything,ocanbascil/illacceptanything,illacceptanything/illacceptanything,oneminot/illacceptanything,tjhorner/illacceptanything,ultranaut/illacceptanything,gaapt/illacceptanything,1yvT0s/illacceptanything,tjhorner/illacceptanything,ocanbascil/illacceptanything,paladique/illacceptanything,triggerNZ/illacceptanything,joelgarciajr84/illacceptanything,Munter/illacceptanything,JeffreyCA/illacceptanything,ocanbascil/illacceptanything,ds84182/illacceptanything,illacceptanything/illacceptanything
--- +++ @@ -0,0 +1,19 @@ +function hello(language) { + var hellos = { + 'Chinese': '你好世界', + 'Dutch': 'Hello wereld', + 'English': 'Hello world', + 'French': 'Bonjour monde', + 'German': 'Hallo Welt', + 'Greek': 'γειά σου κόσμος', + 'Italian': 'Ciao mondo', + 'Japanese': 'こんにちは世界', + 'Korean': '안녕하세요 세계', + 'Portuguese': 'Olá mundo', + 'Russian': 'Здравствулте мир', + 'Spanish': 'Hola mundo', + 'Latin': 'Salve munde', + 'Piglatin': 'Ellohay orldway' + }; + return hellos[language]; +}
032d4efde878f8219df5c4f3b2f16179413e03fb
ui/src/App.js
ui/src/App.js
import React, {PropTypes} from 'react' import {connect} from 'react-redux' import {bindActionCreators} from 'redux' import SideNav from 'src/side_nav' import Notifications from 'shared/components/Notifications' import {publishNotification} from 'shared/actions/notifications' const {func, node} = PropTypes const App = React.createClass({ propTypes: { children: node.isRequired, notify: func.isRequired, }, handleAddFlashMessage({type, text}) { const {notify} = this.props notify(type, text) }, render() { return ( <div className="chronograf-root"> <SideNav /> <Notifications /> {this.props.children && React.cloneElement(this.props.children, { addFlashMessage: this.handleAddFlashMessage, })} </div> ) }, }) const mapDispatchToProps = dispatch => ({ notify: bindActionCreators(publishNotification, dispatch), }) export default connect(null, mapDispatchToProps)(App)
import React, {PropTypes} from 'react' import {connect} from 'react-redux' import {bindActionCreators} from 'redux' import SideNav from 'src/side_nav' import Notifications from 'shared/components/Notifications' import {publishNotification} from 'shared/actions/notifications' const {func, node} = PropTypes const App = React.createClass({ propTypes: { children: node.isRequired, notify: func.isRequired, }, handleAddFlashMessage({type, text}) { const {notify} = this.props notify(type, text) }, render() { return ( <div className="chronograf-root"> <Notifications /> <SideNav /> {this.props.children && React.cloneElement(this.props.children, { addFlashMessage: this.handleAddFlashMessage, })} </div> ) }, }) const mapDispatchToProps = dispatch => ({ notify: bindActionCreators(publishNotification, dispatch), }) export default connect(null, mapDispatchToProps)(App)
Fix z-index failure caused by Notifications being below SideNav in DOM
Fix z-index failure caused by Notifications being below SideNav in DOM Signed-off-by: Jared Scheib <06bd14d569e7a29ad7c0a1b3adcce8579ff36322@gmail.com>
JavaScript
mit
mark-rushakoff/influxdb,influxdb/influxdb,influxdb/influxdb,influxdata/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,nooproblem/influxdb,nooproblem/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,influxdata/influxdb,influxdb/influxdb,li-ang/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,li-ang/influxdb,nooproblem/influxdb,influxdb/influxdb
--- +++ @@ -24,8 +24,8 @@ render() { return ( <div className="chronograf-root"> + <Notifications /> <SideNav /> - <Notifications /> {this.props.children && React.cloneElement(this.props.children, { addFlashMessage: this.handleAddFlashMessage,
29060f1c2feaceb32894fe110b7406ae771b4858
use.js
use.js
/** * Created by Ricardo on 3/7/15. */ var Foscam = require('./index'); var foscam = new Foscam({ host: '92.53.192.141', port: 80, usr: 'admin', pwd: 'batea1' }); foscam.zoomOut(2000);
USE EXAMPLE TO TEST THE MODULE
USE EXAMPLE TO TEST THE MODULE
JavaScript
mit
richnologies/foscam
--- +++ @@ -0,0 +1,13 @@ +/** + * Created by Ricardo on 3/7/15. + */ +var Foscam = require('./index'); + +var foscam = new Foscam({ + host: '92.53.192.141', + port: 80, + usr: 'admin', + pwd: 'batea1' +}); + +foscam.zoomOut(2000);
7b64d0ab802082c848dcfb998ab9ceae2fe6c4d1
client/message/__tests__/view-test.js
client/message/__tests__/view-test.js
const React = require('react/addons'); const TestUtils = React.addons.TestUtils; jest.dontMock('../view.jsx'); const Message = require('../view.jsx'); describe('Message', function() { it('renders a message', function() { const message = TestUtils.renderIntoDocument( <Message username='hilbert' own='false' text='Wir müssen wissen — wir werden wissen!' /> ); const li = TestUtils.findRenderedDOMComponentWithTag( message, 'li' ).getDOMNode(); expect(li.textContent).toContain('hilbert'); }); });
Add simple test for message component
Add simple test for message component
JavaScript
mit
sirodoht/ting,mbalamat/ting,gtklocker/ting,sirodoht/ting,sirodoht/ting,gtklocker/ting,odyvarv/ting-1,VitSalis/ting,odyvarv/ting-1,VitSalis/ting,dionyziz/ting,VitSalis/ting,dionyziz/ting,VitSalis/ting,sirodoht/ting,mbalamat/ting,dionyziz/ting,dionyziz/ting,mbalamat/ting,mbalamat/ting,odyvarv/ting-1,gtklocker/ting,odyvarv/ting-1,gtklocker/ting
--- +++ @@ -0,0 +1,23 @@ +const React = require('react/addons'); +const TestUtils = React.addons.TestUtils; + +jest.dontMock('../view.jsx'); + +const Message = require('../view.jsx'); + +describe('Message', function() { + it('renders a message', function() { + const message = TestUtils.renderIntoDocument( + <Message username='hilbert' + own='false' + text='Wir müssen wissen — wir werden wissen!' /> + ); + + const li = TestUtils.findRenderedDOMComponentWithTag( + message, + 'li' + ).getDOMNode(); + + expect(li.textContent).toContain('hilbert'); + }); +});
1ab8d671b679afcb19a4e7e3576dce2ebc022a70
src/get-headlines.js
src/get-headlines.js
/* eslint-env node */ /* eslint-disable no-console */ import fs from 'fs'; import path from 'path'; import dotenv from 'dotenv'; import {getSourcesWithArticles} from './newsapi'; dotenv.config(); const {MOCK_HEADLINES, NEWS_API_KEY} = process.env; const HEADLINES_FILE = path.resolve(__dirname, '../site/headlines.json'); const MOCK_HEADLINES_FILE = path.resolve( __dirname, '../site/mock-headlines.json' ); if (!NEWS_API_KEY) { if (MOCK_HEADLINES === '1') { fs.copyFileSync(MOCK_HEADLINES_FILE, HEADLINES_FILE); } else { console.error('The NEWS_API_KEY environment variable is not set.'); console.error('Use template.env to Create a .env file.'); console.error('You can also set MOCK_HEADLINES to 1 to use mock data.'); process.exit(1); } } else { getSourcesWithArticles(NEWS_API_KEY).then(headlines => { fs.writeFileSync(HEADLINES_FILE, JSON.stringify(headlines)); }); }
/* eslint-env node */ /* eslint-disable no-console */ import fs from 'fs'; import path from 'path'; import dotenv from 'dotenv'; import {getSourcesWithArticles} from './newsapi'; dotenv.config(); const {MOCK_HEADLINES, NEWS_API_KEY} = process.env; const HEADLINES_FILE = path.resolve(__dirname, '../site/headlines.json'); const MOCK_HEADLINES_FILE = path.resolve( __dirname, '../site/mock-headlines.json' ); if (!NEWS_API_KEY) { if (MOCK_HEADLINES === '1') { fs.copyFileSync(MOCK_HEADLINES_FILE, HEADLINES_FILE); console.log('Using mock headlines'); } else { console.error('The NEWS_API_KEY environment variable is not set.'); console.error('Use template.env to Create a .env file.'); console.error('You can also set MOCK_HEADLINES to 1 to use mock data.'); process.exit(1); } } else { getSourcesWithArticles(NEWS_API_KEY).then(headlines => { fs.writeFileSync(HEADLINES_FILE, JSON.stringify(headlines)); console.log('Retrieved real headlines'); }); }
Add status messages to the headlines script
Add status messages to the headlines script
JavaScript
mit
dguo/dailylore,dguo/dailylore,dguo/dailylore,dguo/dailylore
--- +++ @@ -20,6 +20,7 @@ if (!NEWS_API_KEY) { if (MOCK_HEADLINES === '1') { fs.copyFileSync(MOCK_HEADLINES_FILE, HEADLINES_FILE); + console.log('Using mock headlines'); } else { console.error('The NEWS_API_KEY environment variable is not set.'); console.error('Use template.env to Create a .env file.'); @@ -29,5 +30,6 @@ } else { getSourcesWithArticles(NEWS_API_KEY).then(headlines => { fs.writeFileSync(HEADLINES_FILE, JSON.stringify(headlines)); + console.log('Retrieved real headlines'); }); }
ad065293dc6bb8c6415882890794ca5d030b20bd
src/assets/scripts/topic/toc.js
src/assets/scripts/topic/toc.js
/* global debounce, bodau, gotoTop */ (function($) { 'use strict'; function createDiv(className) { return $('<div>', { class: className }); } $('.post').each(function() { var $post = $(this), $heading = $post.find('h2, h3, h4'); if (!$heading.length) return; var $fly = createDiv('toc-fly'), $control = createDiv('toc-control').html('<i class="fa fa-bars" aria-hidden="true"></i>'), $list = createDiv('toc-list'), $win = $(window), postHeadHeight = 131, postTop = 0, postFootTop = 0, tocHeight = 0, tocTop = 0, tocPosition = debounce(function() { var scrollTop = $win.scrollTop(), top = postHeadHeight; if (scrollTop > postFootTop - tocHeight) { top = postFootTop - postTop - tocHeight; } else if (scrollTop > tocTop && scrollTop < postFootTop - tocHeight) { top = postHeadHeight + (scrollTop - tocTop); } $fly.css('top', top); }, 250), checkSize = debounce(function() { postTop = $post.offset().top; postFootTop = $post.find('.post-footer').offset().top - 2; tocHeight = $fly.height(); tocTop = postTop + postHeadHeight; tocPosition(); }, 250); $list.append($('<a>', { class: 'toc-link toc-top', href: '#' + $post.attr('id'), html: '<i class="fa fa-arrow-up" aria-hidden="true"></i> Lên đầu bài viết ' })); $heading.each(function() { var _this = this, $h = $(_this), str = _this.textContent, id = bodau(str); $h.append($('<a>', { class: 'toc-link toc-anchor', href: '#' + id, id: id, html: '<i class="fa fa-anchor" aria-hidden="true"></i>' })); $list.append($('<a>', { class: 'toc-link toc-' + _this.tagName.toLowerCase(), href: '#' + id, text: str })); }); $control.on('click', function() { $fly.toggleClass('active'); checkSize(); }); $post.append($fly.append($list).append($control)); tocHeight = $fly.height(); tocTop = $fly.offset().top; checkSize(); $win.on('load resize', checkSize).on('scroll', tocPosition); }).on('click', '.toc-link', function(e) { e.preventDefault(); var hash = this.hash; history.replaceState(null, null, hash); gotoTop($(hash)); }); })(jQuery);
Add Table of Contents generator
Add Table of Contents generator
JavaScript
mit
baivong/bubcloud
--- +++ @@ -0,0 +1,99 @@ +/* global debounce, bodau, gotoTop */ +(function($) { + 'use strict'; + + function createDiv(className) { + return $('<div>', { + class: className + }); + } + + + $('.post').each(function() { + var $post = $(this), + $heading = $post.find('h2, h3, h4'); + + if (!$heading.length) return; + + var $fly = createDiv('toc-fly'), + $control = createDiv('toc-control').html('<i class="fa fa-bars" aria-hidden="true"></i>'), + $list = createDiv('toc-list'), + + $win = $(window), + postHeadHeight = 131, + postTop = 0, + postFootTop = 0, + tocHeight = 0, + tocTop = 0, + + tocPosition = debounce(function() { + var scrollTop = $win.scrollTop(), + top = postHeadHeight; + + if (scrollTop > postFootTop - tocHeight) { + top = postFootTop - postTop - tocHeight; + } else if (scrollTop > tocTop && scrollTop < postFootTop - tocHeight) { + top = postHeadHeight + (scrollTop - tocTop); + } + + $fly.css('top', top); + }, 250), + + checkSize = debounce(function() { + postTop = $post.offset().top; + postFootTop = $post.find('.post-footer').offset().top - 2; + tocHeight = $fly.height(); + tocTop = postTop + postHeadHeight; + + tocPosition(); + }, 250); + + + $list.append($('<a>', { + class: 'toc-link toc-top', + href: '#' + $post.attr('id'), + html: '<i class="fa fa-arrow-up" aria-hidden="true"></i> Lên đầu bài viết ' + })); + + $heading.each(function() { + var _this = this, + $h = $(_this), + str = _this.textContent, + id = bodau(str); + + $h.append($('<a>', { + class: 'toc-link toc-anchor', + href: '#' + id, + id: id, + html: '<i class="fa fa-anchor" aria-hidden="true"></i>' + })); + + $list.append($('<a>', { + class: 'toc-link toc-' + _this.tagName.toLowerCase(), + href: '#' + id, + text: str + })); + }); + + $control.on('click', function() { + $fly.toggleClass('active'); + + checkSize(); + }); + + $post.append($fly.append($list).append($control)); + tocHeight = $fly.height(); + tocTop = $fly.offset().top; + checkSize(); + + $win.on('load resize', checkSize).on('scroll', tocPosition); + }).on('click', '.toc-link', function(e) { + e.preventDefault(); + + var hash = this.hash; + + history.replaceState(null, null, hash); + gotoTop($(hash)); + }); + +})(jQuery);
3c0417c5696e09187618bdb070527865eb88b15d
src/data/projectData.js
src/data/projectData.js
import Project1 from '../components/projects/Project-1'; import Project2 from '../components/projects/Project-2'; import Project3 from '../components/projects/Project-3'; const projectData = [ { name: 'Project 1', path: 'project-1', jumbotronContent: { img: 'jumbotronImg', blurb: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', }, summary: { type: 'Web Application', role: 'Design & Development', tools: [ 'Tool 1', 'Tool 2', 'Tool 3', 'Tool 4', 'Tech 1', 'Tech 2', 'Tech 3', 'Tech 4', ], projectLink: { text: 'text', href: 'href', }, }, details: Project1, }, { name: 'Project 2', path: 'project-2', jumbotronContent: { img: 'jumbotronImg', blurb: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', }, summary: { type: 'Web Application', role: 'Design & Development', tools: [ 'Tool 1', 'Tool 2', 'Tool 3', 'Tool 4', 'Tech 1', 'Tech 2', 'Tech 3', 'Tech 4', ], projectLink: { text: 'text', href: 'href', }, }, details: Project2, }, { name: 'Project 3', path: 'project-3', jumbotronContent: { img: 'jumbotronImg', blurb: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', }, summary: { type: 'Web Application', role: 'Design & Development', tools: [ 'Tool 1', 'Tool 2', 'Tool 3', 'Tool 4', 'Tech 1', 'Tech 2', 'Tech 3', 'Tech 4', ], projectLink: { text: 'text', href: 'href', }, }, details: Project3, }, ]; export default projectData;
Add project data layer Temporarily fill with fake data
Add project data layer Temporarily fill with fake data
JavaScript
mit
emyarod/afw,emyarod/afw
--- +++ @@ -0,0 +1,89 @@ +import Project1 from '../components/projects/Project-1'; +import Project2 from '../components/projects/Project-2'; +import Project3 from '../components/projects/Project-3'; + +const projectData = [ + { + name: 'Project 1', + path: 'project-1', + jumbotronContent: { + img: 'jumbotronImg', + blurb: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', + }, + summary: { + type: 'Web Application', + role: 'Design & Development', + tools: [ + 'Tool 1', + 'Tool 2', + 'Tool 3', + 'Tool 4', + 'Tech 1', + 'Tech 2', + 'Tech 3', + 'Tech 4', + ], + projectLink: { + text: 'text', + href: 'href', + }, + }, + details: Project1, + }, + { + name: 'Project 2', + path: 'project-2', + jumbotronContent: { + img: 'jumbotronImg', + blurb: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', + }, + summary: { + type: 'Web Application', + role: 'Design & Development', + tools: [ + 'Tool 1', + 'Tool 2', + 'Tool 3', + 'Tool 4', + 'Tech 1', + 'Tech 2', + 'Tech 3', + 'Tech 4', + ], + projectLink: { + text: 'text', + href: 'href', + }, + }, + details: Project2, + }, + { + name: 'Project 3', + path: 'project-3', + jumbotronContent: { + img: 'jumbotronImg', + blurb: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', + }, + summary: { + type: 'Web Application', + role: 'Design & Development', + tools: [ + 'Tool 1', + 'Tool 2', + 'Tool 3', + 'Tool 4', + 'Tech 1', + 'Tech 2', + 'Tech 3', + 'Tech 4', + ], + projectLink: { + text: 'text', + href: 'href', + }, + }, + details: Project3, + }, +]; + +export default projectData;
c44bd1619db437d107e3d05f379689706edd4d57
test/e2e/language-switcher.spec.js
test/e2e/language-switcher.spec.js
describe('language switcher', function() { it('opens a submenu which lets users to choose between german and english', function() { browser.get('/'); browser.wait(function() { return element(by.id('language-switcher')).isPresent(); }, 1000); var languageSwitcher = element(by.id('language-switcher')); expect(languageSwitcher.isPresent()).toBe(true); languageSwitcher.click(); expect(languageSwitcher.all(by.css('li')).get(0).getText()).toBe('Deutsch'); expect(languageSwitcher.all(by.css('li')).get(1).getText()).toBe('English'); }); it('changes the frontends language from german to english', function() { browser.get('/'); browser.wait(function() { return element(by.id('language-switcher')).isPresent(); }, 1000); var languageSwitcher = element(by.id('language-switcher')); expect(languageSwitcher.isPresent()).toBe(true); languageSwitcher.click(); // Set frontends language to german languageSwitcher.all(by.css('li')).get(0).click(); browser.wait(function() { return element(by.id('language-switcher')).isPresent(); }, 1000); expect(element.all(by.css('.navbar-links')).get(3).getText()).toBe('Über Arachne'); expect(element.all(by.css('.all-projects')).get(0).getText()).toBe('Alle Projekte anzeigen'); languageSwitcher.click(); // Set frontends language to english languageSwitcher.all(by.css('li')).get(1).click(); browser.wait(function() { return element(by.id('language-switcher')).isPresent(); }, 1000); expect(element.all(by.css('.navbar-links')).get(3).getText()).toBe('About Arachne'); expect(element.all(by.css('.all-projects')).get(0).getText()).toBe('Show all projects'); }); });
Add tests for language switcher.
Add tests for language switcher.
JavaScript
apache-2.0
codarchlab/arachnefrontend,dainst/arachnefrontend,dainst/arachnefrontend,codarchlab/arachnefrontend
--- +++ @@ -0,0 +1,60 @@ +describe('language switcher', function() { + + it('opens a submenu which lets users to choose between german and english', function() { + + browser.get('/'); + + browser.wait(function() { + return element(by.id('language-switcher')).isPresent(); + }, 1000); + + var languageSwitcher = element(by.id('language-switcher')); + + expect(languageSwitcher.isPresent()).toBe(true); + + languageSwitcher.click(); + + expect(languageSwitcher.all(by.css('li')).get(0).getText()).toBe('Deutsch'); + expect(languageSwitcher.all(by.css('li')).get(1).getText()).toBe('English'); + + }); + + it('changes the frontends language from german to english', function() { + + browser.get('/'); + + browser.wait(function() { + return element(by.id('language-switcher')).isPresent(); + }, 1000); + + var languageSwitcher = element(by.id('language-switcher')); + + expect(languageSwitcher.isPresent()).toBe(true); + + languageSwitcher.click(); + + // Set frontends language to german + languageSwitcher.all(by.css('li')).get(0).click(); + + browser.wait(function() { + return element(by.id('language-switcher')).isPresent(); + }, 1000); + + expect(element.all(by.css('.navbar-links')).get(3).getText()).toBe('Über Arachne'); + expect(element.all(by.css('.all-projects')).get(0).getText()).toBe('Alle Projekte anzeigen'); + + languageSwitcher.click(); + + // Set frontends language to english + languageSwitcher.all(by.css('li')).get(1).click(); + + browser.wait(function() { + return element(by.id('language-switcher')).isPresent(); + }, 1000); + + expect(element.all(by.css('.navbar-links')).get(3).getText()).toBe('About Arachne'); + expect(element.all(by.css('.all-projects')).get(0).getText()).toBe('Show all projects'); + + }); + +});
74e8279a8d2f0506ed17b0d1a678b63eb02266a3
test/helpers/route/pattern.test.js
test/helpers/route/pattern.test.js
var chai = require('chai') , patternHelper = require('../../../lib/helpers/route/pattern'); describe('helpers/route/pattern', function() { describe('path', function() { describe('without placeholder', function() { var pathHelper; before(function(done) { chai.locomotive.helper(patternHelper.path('/songs'), 'test', 'show') .req(function(req) { req.headers.host = 'www.example.com'; }) .create(function(err, helper) { if (err) { return done(err); } pathHelper = helper; return done(); }); }); it('should build correct path', function() { expect(pathHelper()).to.equal('/songs'); }); }); describe('with one placeholder', function() { var pathHelper; before(function(done) { chai.locomotive.helper(patternHelper.path('/songs/:id'), 'test', 'show') .req(function(req) { req.headers.host = 'www.example.com'; }) .create(function(err, helper) { if (err) { return done(err); } pathHelper = helper; return done(); }); }); it('should build correct path with number', function() { expect(pathHelper(7)).to.equal('/songs/7'); expect(pathHelper(0)).to.equal('/songs/0'); }); it('should build correct path with string', function() { expect(pathHelper('mr-jones')).to.equal('/songs/mr-jones'); }); it('should build correct path with object id', function() { expect(pathHelper({ id: 101 })).to.equal('/songs/101'); expect(pathHelper({ id: 0 })).to.equal('/songs/0'); }); it('should throw if incorrect number of arguments', function() { expect(function() { pathHelper() }).to.throw("Incorrect number of arguments passed to route helper for /songs/:id"); }); }); }); });
Test cases for pattern routing helper.
Test cases for pattern routing helper.
JavaScript
mit
1024bit/locomotive,mkontula/maglev,noahlange/railsea,drudge/locomotive,easing/locomotive,emvc/emvc,viadeo/maglev,buildcom/locomotive,jaredhanson/locomotive
--- +++ @@ -0,0 +1,64 @@ +var chai = require('chai') + , patternHelper = require('../../../lib/helpers/route/pattern'); + + +describe('helpers/route/pattern', function() { + + describe('path', function() { + + describe('without placeholder', function() { + var pathHelper; + + before(function(done) { + chai.locomotive.helper(patternHelper.path('/songs'), 'test', 'show') + .req(function(req) { + req.headers.host = 'www.example.com'; + }) + .create(function(err, helper) { + if (err) { return done(err); } + pathHelper = helper; + return done(); + }); + }); + + it('should build correct path', function() { + expect(pathHelper()).to.equal('/songs'); + }); + }); + + describe('with one placeholder', function() { + var pathHelper; + + before(function(done) { + chai.locomotive.helper(patternHelper.path('/songs/:id'), 'test', 'show') + .req(function(req) { + req.headers.host = 'www.example.com'; + }) + .create(function(err, helper) { + if (err) { return done(err); } + pathHelper = helper; + return done(); + }); + }); + + it('should build correct path with number', function() { + expect(pathHelper(7)).to.equal('/songs/7'); + expect(pathHelper(0)).to.equal('/songs/0'); + }); + it('should build correct path with string', function() { + expect(pathHelper('mr-jones')).to.equal('/songs/mr-jones'); + }); + it('should build correct path with object id', function() { + expect(pathHelper({ id: 101 })).to.equal('/songs/101'); + expect(pathHelper({ id: 0 })).to.equal('/songs/0'); + }); + it('should throw if incorrect number of arguments', function() { + expect(function() { + pathHelper() + }).to.throw("Incorrect number of arguments passed to route helper for /songs/:id"); + }); + }); + + }); + +});
a8a645175555cd71cf6408f189890806d8ca0163
migrations/20180107210900_users.js
migrations/20180107210900_users.js
export async function up(knex) { // Replace `mute_all_posts` with `comment_notifications` // Initialize`more.last_comment_notification_at` for each user. const users = await knex('users') .select('id', 'more'); for (const user of users) { if (!user.more) { user.more = {}; } let comment_notifications = 'on'; if (user.more.mute_all_posts) { comment_notifications = 'off'; } const more = { ...users.more, comment_notifications, last_comment_notification_at: new Date().toJSON() }; delete more.mute_all_posts; await knex('users').where('id', user.id).update({ more }); } } export async function down(knex) { const users = await knex('users') .select('id', 'more'); for (const user of users) { if (!user.more) { user.more = {}; } let mute_all_posts = false; if (user.more.comment_notifications === 'off') { mute_all_posts = false; } const more = { ...users.more, mute_all_posts, }; delete more.last_comment_notification_at; delete more.comment_notifications; await knex('users').where('id', user.id).update({ more }); } }
Add migration for comment notifications settings
Add migration for comment notifications settings - Replaced `users.more.mute_all_posts` with `users.more.comment_notification`. - Initialized `users.more.last_comment_notification_at` for each user.
JavaScript
agpl-3.0
Lokiedu/libertysoil-site,Lokiedu/libertysoil-site
--- +++ @@ -0,0 +1,53 @@ +export async function up(knex) { + // Replace `mute_all_posts` with `comment_notifications` + // Initialize`more.last_comment_notification_at` for each user. + const users = await knex('users') + .select('id', 'more'); + + for (const user of users) { + if (!user.more) { + user.more = {}; + } + + let comment_notifications = 'on'; + if (user.more.mute_all_posts) { + comment_notifications = 'off'; + } + + const more = { + ...users.more, + comment_notifications, + last_comment_notification_at: new Date().toJSON() + }; + + delete more.mute_all_posts; + + await knex('users').where('id', user.id).update({ more }); + } +} + +export async function down(knex) { + const users = await knex('users') + .select('id', 'more'); + + for (const user of users) { + if (!user.more) { + user.more = {}; + } + + let mute_all_posts = false; + if (user.more.comment_notifications === 'off') { + mute_all_posts = false; + } + + const more = { + ...users.more, + mute_all_posts, + }; + + delete more.last_comment_notification_at; + delete more.comment_notifications; + + await knex('users').where('id', user.id).update({ more }); + } +}
2429541f344950bde156c0ef849e35b3bd97092e
lib/containers/relay-root-container.js
lib/containers/relay-root-container.js
import React from 'react'; import Relay from 'react-relay'; /** * This is a copy of `RelayRootContainer` from the Relay * codebase, but with an optional `environment` prop * that can be used instead of the singleton `RelayStore`. */ export default function RelayRootContainer({ Component, forceFetch, onReadyStateChange, renderFailure, renderFetched, renderLoading, route, shouldFetch, environment, }) { return ( <Relay.Renderer Container={Component} forceFetch={forceFetch} onReadyStateChange={onReadyStateChange} queryConfig={route} environment={environment || Relay.Store} shouldFetch={shouldFetch} render={({done, error, props, retry, stale}) => { if (error) { if (renderFailure) { return renderFailure(error, retry); } } else if (props) { if (renderFetched) { return renderFetched(props, {done, stale}); } else { return <Component {...props} />; } } else { if (renderLoading) { return renderLoading(); } } return undefined; }} /> ); } RelayRootContainer.propTypes = { Component: Relay.PropTypes.Container, forceFetch: React.PropTypes.bool, onReadyStateChange: React.PropTypes.func, renderFailure: React.PropTypes.func, renderFetched: React.PropTypes.func, renderLoading: React.PropTypes.func, route: Relay.PropTypes.QueryConfig.isRequired, shouldFetch: React.PropTypes.bool, environment: React.PropTypes.object, };
Add RelayRootContainer for using non-global Relay environments
Add RelayRootContainer for using non-global Relay environments
JavaScript
mit
atom/github,atom/github,atom/github
--- +++ @@ -0,0 +1,60 @@ +import React from 'react'; +import Relay from 'react-relay'; + +/** + * This is a copy of `RelayRootContainer` from the Relay + * codebase, but with an optional `environment` prop + * that can be used instead of the singleton `RelayStore`. + */ +export default function RelayRootContainer({ + Component, + forceFetch, + onReadyStateChange, + renderFailure, + renderFetched, + renderLoading, + route, + shouldFetch, + environment, +}) { + return ( + <Relay.Renderer + Container={Component} + forceFetch={forceFetch} + onReadyStateChange={onReadyStateChange} + queryConfig={route} + environment={environment || Relay.Store} + shouldFetch={shouldFetch} + render={({done, error, props, retry, stale}) => { + if (error) { + if (renderFailure) { + return renderFailure(error, retry); + } + } else if (props) { + if (renderFetched) { + return renderFetched(props, {done, stale}); + } else { + return <Component {...props} />; + } + } else { + if (renderLoading) { + return renderLoading(); + } + } + return undefined; + }} + /> + ); +} + +RelayRootContainer.propTypes = { + Component: Relay.PropTypes.Container, + forceFetch: React.PropTypes.bool, + onReadyStateChange: React.PropTypes.func, + renderFailure: React.PropTypes.func, + renderFetched: React.PropTypes.func, + renderLoading: React.PropTypes.func, + route: Relay.PropTypes.QueryConfig.isRequired, + shouldFetch: React.PropTypes.bool, + environment: React.PropTypes.object, +};
0a47827a4393290996ed56a189ce8b3f499395c7
src/theme/style-utils.js
src/theme/style-utils.js
import { css } from 'styled-components'; export const sizes = { giant: 1170, desktop: 992, tablet: 768, phone: 448, }; // iterate through the sizes and create a media template export const media = Object.keys(sizes).reduce((accumulator, label) => { const emSize = sizes[label] / 16; accumulator[label] = (...args) => css` @media (max-width: ${emSize}em) { ${css(...args)}; } `; return accumulator; }, {}); export function truncate(width) { return ` width: ${width}; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; `; }
Add style utils for media queries and truncation
Add style utils for media queries and truncation
JavaScript
mit
jordandrako/jordanjanzen.com,jordandrako/jordanjanzen.com,jordandrako/jordanjanzen.com,jordandrako/jordanjanzen.com
--- +++ @@ -0,0 +1,28 @@ +import { css } from 'styled-components'; + +export const sizes = { + giant: 1170, + desktop: 992, + tablet: 768, + phone: 448, +}; + +// iterate through the sizes and create a media template +export const media = Object.keys(sizes).reduce((accumulator, label) => { + const emSize = sizes[label] / 16; + accumulator[label] = (...args) => css` + @media (max-width: ${emSize}em) { + ${css(...args)}; + } + `; + return accumulator; +}, {}); + +export function truncate(width) { + return ` + width: ${width}; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + `; +}
1683e56db2062a7cf6f0815048b91653195be5de
lib/assets/node_modules/backbone/core-model.js
lib/assets/node_modules/backbone/core-model.js
var $ = require('jquery'); var _ = require('underscore'); var Backbone = require('backbone'); /** * Base Model for all CartoDB model. * DO NOT USE Backbone.Model directly */ var Model = Backbone.Model.extend({ initialize: function (options) { _.bindAll(this, 'fetch', 'save', 'retrigger'); return Backbone.Model.prototype.initialize.call(this, options); }, /** * We are redefining fetch to be able to trigger an event when the ajax call ends, no matter if there's * a change in the data or not. Why don't backbone does this by default? ahh, my friend, who knows. * @method fetch * @param args {Object} */ fetch: function (args) { var self = this; // var date = new Date(); this.trigger('loadModelStarted'); $.when(Backbone.Model.prototype.fetch.call(this, args)).done(function (ev) { self.trigger('loadModelCompleted', ev, self); // var dateComplete = new Date() // console.log('completed in '+(dateComplete - date)); }).fail(function (ev) { self.trigger('loadModelFailed', ev, self); }); }, /** * Changes the attribute used as Id * @method setIdAttribute * @param attr {String} */ setIdAttribute: function (attr) { this.idAttribute = attr; }, /** * Listen for an event on another object and triggers on itself, with the same name or a new one * @method retrigger * @param ev {String} event who triggers the action * @param obj {Object} object where the event happens * @param obj {Object} [optional] name of the retriggered event * @todo [xabel]: This method is repeated here and in the base view definition. There's should be a way to make it unique */ retrigger: function (ev, obj, retrigEvent) { if (!retrigEvent) { retrigEvent = ev; } var self = this; obj.bind && obj.bind(ev, function () { self.trigger(retrigEvent); }, self); }, /** * We need to override backbone save method to be able to introduce new kind of triggers that * for some reason are not present in the original library. Because you know, it would be nice * to be able to differenciate "a model has been updated" of "a model is being saved". * TODO: remove jquery from here * @param {object} opt1 * @param {object} opt2 * @return {$.Deferred} */ save: function (opt1, opt2) { var self = this; if (!opt2 || !opt2.silent) this.trigger('saving'); var promise = Backbone.Model.prototype.save.apply(this, arguments); $.when(promise).done(function () { if (!opt2 || !opt2.silent) self.trigger('saved'); }).fail(function () { if (!opt2 || !opt2.silent) self.trigger('errorSaving'); }); return promise; } }); module.exports = Model;
Use CoreModel instead of cdb.core.Model
Use CoreModel instead of cdb.core.Model
JavaScript
bsd-3-clause
CartoDB/cartodb,CartoDB/cartodb,splashblot/dronedb,splashblot/dronedb,splashblot/dronedb,splashblot/dronedb,CartoDB/cartodb,CartoDB/cartodb,splashblot/dronedb,CartoDB/cartodb
--- +++ @@ -0,0 +1,81 @@ +var $ = require('jquery'); +var _ = require('underscore'); +var Backbone = require('backbone'); + +/** + * Base Model for all CartoDB model. + * DO NOT USE Backbone.Model directly + */ +var Model = Backbone.Model.extend({ + + initialize: function (options) { + _.bindAll(this, 'fetch', 'save', 'retrigger'); + return Backbone.Model.prototype.initialize.call(this, options); + }, + /** + * We are redefining fetch to be able to trigger an event when the ajax call ends, no matter if there's + * a change in the data or not. Why don't backbone does this by default? ahh, my friend, who knows. + * @method fetch + * @param args {Object} + */ + fetch: function (args) { + var self = this; + // var date = new Date(); + this.trigger('loadModelStarted'); + $.when(Backbone.Model.prototype.fetch.call(this, args)).done(function (ev) { + self.trigger('loadModelCompleted', ev, self); + // var dateComplete = new Date() + // console.log('completed in '+(dateComplete - date)); + }).fail(function (ev) { + self.trigger('loadModelFailed', ev, self); + }); + }, + /** + * Changes the attribute used as Id + * @method setIdAttribute + * @param attr {String} + */ + setIdAttribute: function (attr) { + this.idAttribute = attr; + }, + /** + * Listen for an event on another object and triggers on itself, with the same name or a new one + * @method retrigger + * @param ev {String} event who triggers the action + * @param obj {Object} object where the event happens + * @param obj {Object} [optional] name of the retriggered event + * @todo [xabel]: This method is repeated here and in the base view definition. There's should be a way to make it unique + */ + retrigger: function (ev, obj, retrigEvent) { + if (!retrigEvent) { + retrigEvent = ev; + } + var self = this; + obj.bind && obj.bind(ev, function () { + self.trigger(retrigEvent); + }, self); + }, + + /** + * We need to override backbone save method to be able to introduce new kind of triggers that + * for some reason are not present in the original library. Because you know, it would be nice + * to be able to differenciate "a model has been updated" of "a model is being saved". + * TODO: remove jquery from here + * @param {object} opt1 + * @param {object} opt2 + * @return {$.Deferred} + */ + save: function (opt1, opt2) { + var self = this; + if (!opt2 || !opt2.silent) this.trigger('saving'); + var promise = Backbone.Model.prototype.save.apply(this, arguments); + $.when(promise).done(function () { + if (!opt2 || !opt2.silent) self.trigger('saved'); + }).fail(function () { + if (!opt2 || !opt2.silent) self.trigger('errorSaving'); + }); + return promise; + } +}); + +module.exports = Model;
dd8feba17c070cd99729d86d00ca1b6a2bd2248a
js/the-blue-alliance.js
js/the-blue-alliance.js
(function($) { var API_V2_URI = "http://www.thebluealliance.com/api/v2/", tba = {}; var tbaAjax = function(url, callback) { $.ajax({ url: API_V2_URI + url, dataType: "json", type: "GET", data: { "X-TBA-App-Id": "firstwa:video-stream:1" } }).done(function(data) { // Hide the textStatus and the jqXHR from the callback callback(data); }); }; tba.team = function(teamNum, year, callback) { var teamKey = "frc" + teamNum, url = "team/" + teamKey + "/" + year; tbaAjax(url, callback); }; tba.events = function(year, callback) { var url = "events/" + year; tbaAjax(url, callback); }; tba.event = function(eventCode, year, callback) { var eventKey = year + eventCode, url = "event/" + eventKey; tbaAjax(url, callback); }; tba.event.teams = function(eventCode, year, callback) { var eventKey = year + eventCode, url = "event/" + eventKey + "/teams"; tbaAjax(url, callback); }; tba.event.matches = function(eventCode, year, callback) { var eventKey = year + eventCode, url = "event/" + eventKey + "/matches"; tbaAjax(url, callback); }; // Expose API to global space window.tba = tba; }(jQuery));
Create wrapper for The Blue Alliance's API
Create wrapper for The Blue Alliance's API
JavaScript
mit
mc10/first-look
--- +++ @@ -0,0 +1,55 @@ +(function($) { + var API_V2_URI = "http://www.thebluealliance.com/api/v2/", + tba = {}; + + var tbaAjax = function(url, callback) { + $.ajax({ + url: API_V2_URI + url, + dataType: "json", + type: "GET", + data: { + "X-TBA-App-Id": "firstwa:video-stream:1" + } + }).done(function(data) { + // Hide the textStatus and the jqXHR from the callback + callback(data); + }); + }; + + tba.team = function(teamNum, year, callback) { + var teamKey = "frc" + teamNum, + url = "team/" + teamKey + "/" + year; + + tbaAjax(url, callback); + }; + + tba.events = function(year, callback) { + var url = "events/" + year; + + tbaAjax(url, callback); + }; + + tba.event = function(eventCode, year, callback) { + var eventKey = year + eventCode, + url = "event/" + eventKey; + + tbaAjax(url, callback); + }; + + tba.event.teams = function(eventCode, year, callback) { + var eventKey = year + eventCode, + url = "event/" + eventKey + "/teams"; + + tbaAjax(url, callback); + }; + + tba.event.matches = function(eventCode, year, callback) { + var eventKey = year + eventCode, + url = "event/" + eventKey + "/matches"; + + tbaAjax(url, callback); + }; + + // Expose API to global space + window.tba = tba; +}(jQuery));
954df610468b17fcc34ad0601a190d6be7a37c6d
src/index.js
src/index.js
import * as actionCreators from './actionCreators' import * as actionTypes from './actionTypes' import * as utils from './utils' import middleware from './middleware' export { actionCreators, actionTypes, middleware, utils, }
Add exports to entry file
Add exports to entry file
JavaScript
mit
fredrikolovsson/redux-module-local-storage
--- +++ @@ -0,0 +1,11 @@ +import * as actionCreators from './actionCreators' +import * as actionTypes from './actionTypes' +import * as utils from './utils' +import middleware from './middleware' + +export { + actionCreators, + actionTypes, + middleware, + utils, +}
eb87b5c6ab51d7fa662136dfd3de9c2fcec2ea46
hooks/after_prepare/015_copy_icon_to_drawable.js
hooks/after_prepare/015_copy_icon_to_drawable.js
#!/usr/bin/env node var fs = require('fs-extra'); var path = require('path'); var klawSync = require('klaw-sync') var androidPlatformsDir = path.resolve(__dirname, '../../platforms/android/res'); var copyAllIcons = function(iconDir) { var densityDirs = klawSync(iconDir, {nofile: true}) // console.log("densityDirs = "+JSON.stringify(densityDirs)); densityDirs.forEach(function(dDir) { var files = klawSync(dDir.path, {nodir: true}); files.forEach(function(file) { var dirName = path.basename(dDir.path); var fileName = path.basename(file.path); if (dirName.startsWith("mipmap")) { var drawableName = dirName.replace("mipmap", "drawable"); var srcName = path.join(iconDir, dirName, fileName); var dstName = path.join(iconDir, drawableName, fileName); console.log("About to copy file "+srcName+" -> "+dstName); fs.copySync(srcName, dstName); } }); }); }; var copyIconsFromAllDirs = function() { copyAllIcons(androidPlatformsDir); } var platformList = process.env.CORDOVA_PLATFORMS; if (platformList == undefined) { console.log("Testing by running standalone script, invoke anyway"); copyIconsFromAllDirs(); } else { var platforms = platformList.split(","); if (platforms.indexOf('android') < 0) { console.log("Android platform not specified, skipping..."); } else { copyIconsFromAllDirs(); } }
Move the standard launcher icon from `mipmap` to `drawable`
Move the standard launcher icon from `mipmap` to `drawable` The most recent android versions store their icon under `mipmap..." (e.g. mipmap-hdpi, mipmap-xhdpi, mipmap-xxxhdpi) https://android-developers.googleblog.com/2014/10/getting-your-apps-ready-for-nexus-6-and.html But that means that if we want to have our app icon as the large icon, we need to have it in assets - only `drawables` are loaded otherwise. And if it an asset - unsure if sizing and other things will work well. So we add another hook that will copy `icon.png` from the `mipmap-*` directories to the corresponding `drawable` directories.
JavaScript
bsd-3-clause
e-mission/e-mission-phone,shankari/e-mission-phone,shankari/e-mission-phone,shankari/e-mission-phone,e-mission/e-mission-phone,shankari/e-mission-phone,e-mission/e-mission-phone,e-mission/e-mission-phone
--- +++ @@ -0,0 +1,44 @@ +#!/usr/bin/env node + +var fs = require('fs-extra'); +var path = require('path'); +var klawSync = require('klaw-sync') + +var androidPlatformsDir = path.resolve(__dirname, '../../platforms/android/res'); + +var copyAllIcons = function(iconDir) { + var densityDirs = klawSync(iconDir, {nofile: true}) + // console.log("densityDirs = "+JSON.stringify(densityDirs)); + densityDirs.forEach(function(dDir) { + var files = klawSync(dDir.path, {nodir: true}); + files.forEach(function(file) { + var dirName = path.basename(dDir.path); + var fileName = path.basename(file.path); + if (dirName.startsWith("mipmap")) { + var drawableName = dirName.replace("mipmap", "drawable"); + var srcName = path.join(iconDir, dirName, fileName); + var dstName = path.join(iconDir, drawableName, fileName); + console.log("About to copy file "+srcName+" -> "+dstName); + fs.copySync(srcName, dstName); + } + }); + }); +}; + +var copyIconsFromAllDirs = function() { + copyAllIcons(androidPlatformsDir); +} + +var platformList = process.env.CORDOVA_PLATFORMS; + +if (platformList == undefined) { + console.log("Testing by running standalone script, invoke anyway"); + copyIconsFromAllDirs(); +} else { + var platforms = platformList.split(","); + if (platforms.indexOf('android') < 0) { + console.log("Android platform not specified, skipping..."); + } else { + copyIconsFromAllDirs(); + } +}
cd9a4e7efb55c8742b496bc6beb78765d280c54d
tests/components/Sidebar-cy.js
tests/components/Sidebar-cy.js
describe('Sidebar', function () { beforeEach(function () { cy.configureCluster({ mesos: '1-task-healthy', componentHealth: false }) .visitUrl({url: '/dashboard', identify: true, fakeAnalytics: true}); }); context('Sidebar Wrapper', function () { it('is exactly the same width as the sidebar', function () { cy.get('.sidebar').then(function ($sidebar) { const sidebarWidth = $sidebar.get(0).getBoundingClientRect().width; cy.get('.sidebar-wrapper').then(function ($sidebarWrapper) { expect($sidebarWrapper.get(0).getBoundingClientRect().width) .to.equal(sidebarWidth); }); }); }); }); context('User Account Dropdown Button', function () { it('is exactly the same width as the sidebar', function () { cy.get('.sidebar').then(function ($sidebar) { const sidebarWidth = $sidebar.get(0).getBoundingClientRect().width; cy.get('.user-account-dropdown-button').then(function ($button) { expect($button.get(0).getBoundingClientRect().width) .to.equal(sidebarWidth); }); }); }); it('does not have any children wider than itself', function () { cy.get('.user-account-dropdown-button').then(function ($button) { const buttonWidth = $button.get(0).getBoundingClientRect().width; cy.get('.user-account-dropdown-button *').then(function ($children) { $children.each(function (index, child) { expect(child.getBoundingClientRect().width) .to.be.lessThan(buttonWidth); }); }); }); }); }); });
Add integration tests for sidebar width
Add integration tests for sidebar width
JavaScript
apache-2.0
dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui
--- +++ @@ -0,0 +1,53 @@ +describe('Sidebar', function () { + + beforeEach(function () { + cy.configureCluster({ + mesos: '1-task-healthy', + componentHealth: false + }) + .visitUrl({url: '/dashboard', identify: true, fakeAnalytics: true}); + }); + + context('Sidebar Wrapper', function () { + + it('is exactly the same width as the sidebar', function () { + cy.get('.sidebar').then(function ($sidebar) { + const sidebarWidth = $sidebar.get(0).getBoundingClientRect().width; + + cy.get('.sidebar-wrapper').then(function ($sidebarWrapper) { + expect($sidebarWrapper.get(0).getBoundingClientRect().width) + .to.equal(sidebarWidth); + }); + }); + }); + + }); + + context('User Account Dropdown Button', function () { + + it('is exactly the same width as the sidebar', function () { + cy.get('.sidebar').then(function ($sidebar) { + const sidebarWidth = $sidebar.get(0).getBoundingClientRect().width; + + cy.get('.user-account-dropdown-button').then(function ($button) { + expect($button.get(0).getBoundingClientRect().width) + .to.equal(sidebarWidth); + }); + }); + }); + + it('does not have any children wider than itself', function () { + cy.get('.user-account-dropdown-button').then(function ($button) { + const buttonWidth = $button.get(0).getBoundingClientRect().width; + + cy.get('.user-account-dropdown-button *').then(function ($children) { + $children.each(function (index, child) { + expect(child.getBoundingClientRect().width) + .to.be.lessThan(buttonWidth); + }); + }); + }); + }); + + }); +});
b5387595eb66d7d0063119a17c8ccd1588b59c57
migrations/20160316063014_geotags.js
migrations/20160316063014_geotags.js
export async function up(knex, Promise) { await knex.schema.createTable('geonames_admin1', function (table) { table.increments(); table.string('name'); table.string('asciiname'); table.string('code'); table.string('country_code'); table.index('code'); }); await knex.schema.table('geotags', function (table) { table.string('country_code'); table.string('admin1_code'); table.uuid('admin1_id') .references('id').inTable('geotags'); table.integer('geonames_admin1_id') .references('id').inTable('geonames_admin1'); }); } export async function down(knex, Promise) { await knex.schema.table('geotags', function (table) { table.dropColumn('country_code'); table.dropColumn('admin1_code'); table.dropColumn('admin1_id'); table.dropColumn('geonames_admin1_id'); }); await knex.schema.dropTable('geonames_admin1'); }
Add migrations for administrative divisions
Add migrations for administrative divisions
JavaScript
agpl-3.0
Lokiedu/libertysoil-site,Lokiedu/libertysoil-site
--- +++ @@ -0,0 +1,30 @@ +export async function up(knex, Promise) { + await knex.schema.createTable('geonames_admin1', function (table) { + table.increments(); + table.string('name'); + table.string('asciiname'); + table.string('code'); + table.string('country_code'); + table.index('code'); + }); + + await knex.schema.table('geotags', function (table) { + table.string('country_code'); + table.string('admin1_code'); + table.uuid('admin1_id') + .references('id').inTable('geotags'); + table.integer('geonames_admin1_id') + .references('id').inTable('geonames_admin1'); + }); +} + +export async function down(knex, Promise) { + await knex.schema.table('geotags', function (table) { + table.dropColumn('country_code'); + table.dropColumn('admin1_code'); + table.dropColumn('admin1_id'); + table.dropColumn('geonames_admin1_id'); + }); + + await knex.schema.dropTable('geonames_admin1'); +}
85abd94bc0ee46b4367da1617be0cc3a3b2d7b59
migrations/20160415120919_geotags.js
migrations/20160415120919_geotags.js
export async function up(knex, Promise) { await knex.schema.table('geotags', function (table) { table.float('lat'); table.float('lon'); table.float('land_mass'); }); } export async function down(knex, Promise) { await knex.schema.table('geotags', function (table) { table.dropColumns(['lat', 'lon', 'land_mass']); }); }
Add migration which adds lat, lon, land_mass to geotags
Add migration which adds lat, lon, land_mass to geotags
JavaScript
agpl-3.0
Lokiedu/libertysoil-site,Lokiedu/libertysoil-site
--- +++ @@ -0,0 +1,13 @@ +export async function up(knex, Promise) { + await knex.schema.table('geotags', function (table) { + table.float('lat'); + table.float('lon'); + table.float('land_mass'); + }); +} + +export async function down(knex, Promise) { + await knex.schema.table('geotags', function (table) { + table.dropColumns(['lat', 'lon', 'land_mass']); + }); +}
a9e3a386c922d55de16f27cd742b5398677d6101
variables-objects.js
variables-objects.js
// JavaScript Variables and Objects // I paired [by myself, with:] on this challenge. // __________________________________________ // Write your code below. var secretNumber = 7 var password = "just open the door" var allowedIn = false var members = ['John',"","","Mary"] // __________________________________________ // Test Code: Do not alter code below this line. function assert(test, message, test_number) { if (!test) { console.log(test_number + "false"); throw "ERROR: " + message; } console.log(test_number + "true"); return true; } assert( (typeof secretNumber === 'number'), "The value of secretNumber should be a number.", "1. " ) assert( secretNumber === 7, "The value of secretNumber should be 7.", "2. " ) assert( typeof password === 'string', "The value of password should be a string.", "3. " ) assert( password === "just open the door", "The value of password should be 'just open the door'.", "4. " ) assert( typeof allowedIn === 'boolean', "The value of allowedIn should be a boolean.", "5. " ) assert( allowedIn === false, "The value of allowedIn should be false.", "6. " ) assert( members instanceof Array, "The value of members should be an array", "7. " ) assert( members[0] === "John", "The first element in the value of members should be 'John'.", "8. " ) assert( members[3] === "Mary", "The fourth element in the value of members should be 'Mary'.", "9. " )
Add JS variables and objects
Add JS variables and objects
JavaScript
mit
ray-curran/phase-0,ray-curran/phase-0,ray-curran/phase-0
--- +++ @@ -0,0 +1,80 @@ + // JavaScript Variables and Objects + +// I paired [by myself, with:] on this challenge. + +// __________________________________________ +// Write your code below. + +var secretNumber = 7 +var password = "just open the door" +var allowedIn = false +var members = ['John',"","","Mary"] + + + +// __________________________________________ + +// Test Code: Do not alter code below this line. + +function assert(test, message, test_number) { + if (!test) { + console.log(test_number + "false"); + throw "ERROR: " + message; + } + console.log(test_number + "true"); + return true; +} + +assert( + (typeof secretNumber === 'number'), + "The value of secretNumber should be a number.", + "1. " +) + +assert( + secretNumber === 7, + "The value of secretNumber should be 7.", + "2. " +) + +assert( + typeof password === 'string', + "The value of password should be a string.", + "3. " +) + +assert( + password === "just open the door", + "The value of password should be 'just open the door'.", + "4. " +) + +assert( + typeof allowedIn === 'boolean', + "The value of allowedIn should be a boolean.", + "5. " +) + +assert( + allowedIn === false, + "The value of allowedIn should be false.", + "6. " +) + +assert( + members instanceof Array, + "The value of members should be an array", + "7. " +) + +assert( + members[0] === "John", + "The first element in the value of members should be 'John'.", + "8. " +) + +assert( + members[3] === "Mary", + "The fourth element in the value of members should be 'Mary'.", + "9. " +)
b3aded016e178167628f0827a568a56bff06fb3d
node-tests/blueprints/service-test.js
node-tests/blueprints/service-test.js
'use strict'; var blueprintHelpers = require('ember-cli-blueprint-test-helpers/helpers'); var setupTestHooks = blueprintHelpers.setupTestHooks; var emberNew = blueprintHelpers.emberNew; var emberGenerateDestroy = blueprintHelpers.emberGenerateDestroy; var expect = require('ember-cli-blueprint-test-helpers/chai').expect; describe('Acceptance: ember generate and destroy service', function() { setupTestHooks(this); it('service foo', function() { var args = ['service', 'foo']; return emberNew() .then(() => emberGenerateDestroy(args, (file) => { expect(file('app/services/foo.coffee')) .to.contain("`import Ember from 'ember'`") .to.contain('FooService = Ember.Service.extend()') .to.contain("`export default FooService`"); expect(file('tests/unit/services/foo-test.coffee')) .to.contain("`import { moduleFor, test } from 'ember-qunit'`") .to.contain("moduleFor 'service:foo', 'Unit | Service | foo', {"); })); }); it('service-test foo', function() { var args = ['service-test', 'foo']; return emberNew() .then(() => emberGenerateDestroy(args, (file) => { expect(file('tests/unit/services/foo-test.coffee')) .to.contain("`import { moduleFor, test } from 'ember-qunit'`") .to.contain("moduleFor 'service:foo', 'Unit | Service | foo', {"); })); }); });
Add inital test for service blueprint
Add inital test for service blueprint
JavaScript
mit
kimroen/ember-cli-coffeescript,kimroen/ember-cli-coffeescript,kimroen/ember-cli-coffeescript
--- +++ @@ -0,0 +1,39 @@ +'use strict'; + +var blueprintHelpers = require('ember-cli-blueprint-test-helpers/helpers'); +var setupTestHooks = blueprintHelpers.setupTestHooks; +var emberNew = blueprintHelpers.emberNew; +var emberGenerateDestroy = blueprintHelpers.emberGenerateDestroy; + +var expect = require('ember-cli-blueprint-test-helpers/chai').expect; + +describe('Acceptance: ember generate and destroy service', function() { + setupTestHooks(this); + + it('service foo', function() { + var args = ['service', 'foo']; + + return emberNew() + .then(() => emberGenerateDestroy(args, (file) => { + expect(file('app/services/foo.coffee')) + .to.contain("`import Ember from 'ember'`") + .to.contain('FooService = Ember.Service.extend()') + .to.contain("`export default FooService`"); + + expect(file('tests/unit/services/foo-test.coffee')) + .to.contain("`import { moduleFor, test } from 'ember-qunit'`") + .to.contain("moduleFor 'service:foo', 'Unit | Service | foo', {"); + })); + }); + + it('service-test foo', function() { + var args = ['service-test', 'foo']; + + return emberNew() + .then(() => emberGenerateDestroy(args, (file) => { + expect(file('tests/unit/services/foo-test.coffee')) + .to.contain("`import { moduleFor, test } from 'ember-qunit'`") + .to.contain("moduleFor 'service:foo', 'Unit | Service | foo', {"); + })); + }); +});
68a7cb66089e7e03a9be163ce588aa75f9a7e191
test/status_codes.js
test/status_codes.js
"use strict"; var assert = require('assert'); var request = require('request'); var server = require('./server'); describe('homepage', function() { it('is OK', function(done) { var baseURL = server.getBaseURL(); request(baseURL, function(error, response, body) { assert.ifError(error); assert.equal(response.statusCode, 200); done(); }); }); }); describe('reports page, all', function() { it('is OK', function(done) { var baseURL = server.getBaseURL(); request(baseURL + '/reports', function(error, response, body) { assert.ifError(error); assert.equal(response.statusCode, 200); done(); }); }); }); describe('reports page, search results', function() { it('is OK', function(done) { var baseURL = server.getBaseURL(); request(baseURL + '/reports?query=audit', function(error, response, body) { assert.ifError(error); assert.equal(response.statusCode, 200); done(); }); }); }); describe('reports ATOM feed, all', function() { it('is OK', function(done) { var baseURL = server.getBaseURL(); request(baseURL + '/reports.xml', function(error, response, body) { assert.ifError(error); assert.equal(response.statusCode, 200); done(); }); }); }); describe('reports ATOM feed, search results', function() { it('is OK', function(done) { var baseURL = server.getBaseURL(); request(baseURL + '/reports.xml?query=audit', function(error, response, body) { assert.ifError(error); assert.equal(response.statusCode, 200); done(); }); }); }); describe('inspectors page', function() { it('is OK', function(done) { var baseURL = server.getBaseURL(); request(baseURL + '/inspectors', function(error, response, body) { assert.ifError(error); assert.equal(response.statusCode, 200); done(); }); }); }); describe('inspector page', function() { it('is OK', function(done) { var baseURL = server.getBaseURL(); request(baseURL + '/inspector/denali', function(error, response, body) { assert.ifError(error); assert.equal(response.statusCode, 200); done(); }); }); }); describe('report page', function() { it('is OK', function(done) { var baseURL = server.getBaseURL(); request(baseURL + '/report/denali/DCOIG-15-013-M', function(error, response, body) { assert.ifError(error); assert.equal(response.statusCode, 200); done(); }); }); });
Add basic tests for all routes, check status codes
Add basic tests for all routes, check status codes
JavaScript
cc0-1.0
konklone/oversight.io,konklone/oversight.io,konklone/oversight.io,konklone/oversight.io
--- +++ @@ -0,0 +1,94 @@ +"use strict"; + +var assert = require('assert'); +var request = require('request'); + +var server = require('./server'); + +describe('homepage', function() { + it('is OK', function(done) { + var baseURL = server.getBaseURL(); + request(baseURL, function(error, response, body) { + assert.ifError(error); + assert.equal(response.statusCode, 200); + done(); + }); + }); +}); + +describe('reports page, all', function() { + it('is OK', function(done) { + var baseURL = server.getBaseURL(); + request(baseURL + '/reports', function(error, response, body) { + assert.ifError(error); + assert.equal(response.statusCode, 200); + done(); + }); + }); +}); + +describe('reports page, search results', function() { + it('is OK', function(done) { + var baseURL = server.getBaseURL(); + request(baseURL + '/reports?query=audit', function(error, response, body) { + assert.ifError(error); + assert.equal(response.statusCode, 200); + done(); + }); + }); +}); + +describe('reports ATOM feed, all', function() { + it('is OK', function(done) { + var baseURL = server.getBaseURL(); + request(baseURL + '/reports.xml', function(error, response, body) { + assert.ifError(error); + assert.equal(response.statusCode, 200); + done(); + }); + }); +}); + +describe('reports ATOM feed, search results', function() { + it('is OK', function(done) { + var baseURL = server.getBaseURL(); + request(baseURL + '/reports.xml?query=audit', function(error, response, body) { + assert.ifError(error); + assert.equal(response.statusCode, 200); + done(); + }); + }); +}); + +describe('inspectors page', function() { + it('is OK', function(done) { + var baseURL = server.getBaseURL(); + request(baseURL + '/inspectors', function(error, response, body) { + assert.ifError(error); + assert.equal(response.statusCode, 200); + done(); + }); + }); +}); + +describe('inspector page', function() { + it('is OK', function(done) { + var baseURL = server.getBaseURL(); + request(baseURL + '/inspector/denali', function(error, response, body) { + assert.ifError(error); + assert.equal(response.statusCode, 200); + done(); + }); + }); +}); + +describe('report page', function() { + it('is OK', function(done) { + var baseURL = server.getBaseURL(); + request(baseURL + '/report/denali/DCOIG-15-013-M', function(error, response, body) { + assert.ifError(error); + assert.equal(response.statusCode, 200); + done(); + }); + }); +});
6e1b97da4fa84a0c81c8adceb56cf8bafadf7c10
src/app/utilities/api-clients/collections.js
src/app/utilities/api-clients/collections.js
import http from '../http'; export default class collections { static create(body) { return http.post(`/zebedee/collection`, body) .then(response => { return response; }) } }
Add collection api class with create method
Add collection api class with create method
JavaScript
mit
ONSdigital/florence,ONSdigital/florence,ONSdigital/florence,ONSdigital/florence
--- +++ @@ -0,0 +1,14 @@ +import http from '../http'; + +export default class collections { + + static create(body) { + return http.post(`/zebedee/collection`, body) + .then(response => { + return response; + }) + } + + + +}
bbd96ab09308b1d05636edd1dcd674abfbf2b4d0
server/db/controllers/getSelfBasicInfoGivenFBId.js
server/db/controllers/getSelfBasicInfoGivenFBId.js
const db = require('../db.js'); module.exports = (facebookId) => { const query = `SELECT * FROM users WHERE facebook_id = '${facebookId}'`; return db.query(query) .spread((results, metadata) => results); };
Rename query function to specify input fbId not fbProfile
Rename query function to specify input fbId not fbProfile
JavaScript
mit
VictoriousResistance/iDioma,VictoriousResistance/iDioma
--- +++ @@ -0,0 +1,8 @@ +const db = require('../db.js'); + +module.exports = (facebookId) => { + const query = `SELECT * FROM users WHERE facebook_id = '${facebookId}'`; + return db.query(query) + .spread((results, metadata) => results); +}; +
2ffcffcf583d60fb5897a6b06e18ea0c6b120c9a
migrations/20160421203657_hashtags_geotags_more.js
migrations/20160421203657_hashtags_geotags_more.js
export async function up(knex, Promise) { await knex.schema.table('hashtags', function (table) { table.jsonb('more'); }); await knex.schema.table('geotags', function (table) { table.jsonb('more'); }); } export async function down(knex, Promise) { await knex.schema.table('hashtags', function (table) { table.dropColumn('more'); }); await knex.schema.table('geotags', function (table) { table.dropColumn('more'); }); }
Add migration which adds `more` to hashtags and geotags
Add migration which adds `more` to hashtags and geotags
JavaScript
agpl-3.0
Lokiedu/libertysoil-site,Lokiedu/libertysoil-site
--- +++ @@ -0,0 +1,20 @@ +export async function up(knex, Promise) { + await knex.schema.table('hashtags', function (table) { + table.jsonb('more'); + }); + + await knex.schema.table('geotags', function (table) { + table.jsonb('more'); + }); +} + +export async function down(knex, Promise) { + await knex.schema.table('hashtags', function (table) { + table.dropColumn('more'); + }); + + + await knex.schema.table('geotags', function (table) { + table.dropColumn('more'); + }); +}
f3e661870e831cd3016d11749481cf37b77f15bc
js/components/common/single-row-list-item/singleRowListItem.js
js/components/common/single-row-list-item/singleRowListItem.js
import React, { Component } from 'react'; import { Text } from 'react-native'; import { CardItem, Left, Right, Icon } from 'native-base'; export default class SingleRowListItem extends Component { static propTypes = { text: React.PropTypes.string.isRequired, icon: React.PropTypes.string, }; static defaultProps = { icon: undefined, }; render() { const { text, icon } = this.props; let iconIfProvided = []; if (icon !== undefined) { iconIfProvided = ( <Right> <Icon name={icon} /> </Right> ); } return ( <CardItem bordered button> <Left> <Text>{text}</Text> </Left> {iconIfProvided} </CardItem> ); } }
Create common single row list item component
Create common single row list item component
JavaScript
mit
justarrived/p2p-client,justarrived/p2p-client,justarrived/p2p-client,justarrived/p2p-client
--- +++ @@ -0,0 +1,37 @@ +import React, { Component } from 'react'; +import { Text } from 'react-native'; +import { CardItem, Left, Right, Icon } from 'native-base'; + +export default class SingleRowListItem extends Component { + + static propTypes = { + text: React.PropTypes.string.isRequired, + icon: React.PropTypes.string, + }; + + static defaultProps = { + icon: undefined, + }; + + render() { + const { text, icon } = this.props; + + let iconIfProvided = []; + if (icon !== undefined) { + iconIfProvided = ( + <Right> + <Icon name={icon} /> + </Right> + ); + } + + return ( + <CardItem bordered button> + <Left> + <Text>{text}</Text> + </Left> + {iconIfProvided} + </CardItem> + ); + } +}
2301aadf02a5573bafb76a7b63ef19a7926f5e9c
test/api/lambdas/:organizationName/get.js
test/api/lambdas/:organizationName/get.js
import {all, map} from "bluebird"; import {expect} from "chai"; import express from "express"; import request from "supertest-as-promised"; import {sign} from "jsonwebtoken"; import api from "api"; import * as config from "config"; import dynamodb from "services/dynamodb"; describe("GET /lambdas/:organizationName", () => { const server = express().use(api); const token = sign( {aud: config.AUTH0_CLIENT_ID, sub: "userId"}, config.AUTH0_CLIENT_SECRET ); const orgNames = ["org0", "org1", "org2"]; const lambdaNames = ["lambda0", "lambda1", "lambda2"]; beforeEach(() => { return map(orgNames, orgName => all([ dynamodb.putAsync({ TableName: config.DYNAMODB_ORGANIZATIONS, Item: { name: orgName, ownerId: "userId" } }), map(lambdaNames, lambdaName => ( dynamodb.putAsync({ TableName: config.DYNAMODB_LAMBDAS, Item: { organizationName: orgName, name: lambdaName, sourceRepository: "gh/org/repo" } }) )) ])); }); afterEach(() => { return map(orgNames, orgName => all([ dynamodb.deleteAsync({ TableName: config.DYNAMODB_ORGANIZATIONS, Key: {name: orgName} }), map(lambdaNames, lambdaName => ( dynamodb.deleteAsync({ TableName: config.DYNAMODB_LAMBDAS, Key: { organizationName: orgName, name: lambdaName } }) )) ])); }); it("404 on organization not found", () => { return request(server) .get("/lambdas/nonExistingOrganizationName") .set("Authorization", `Bearer ${token}`) .expect(404) .expect(/Organization nonExistingOrganizationName not found/); }); it("200 and returns the organization's lambdas", () => { return map(orgNames, async orgName => { const {body: lambdas} = await request(server) .get(`/lambdas/${orgName}`) .set("Authorization", `Bearer ${token}`) .expect(200); expect(lambdas).to.deep.include.members( lambdaNames.map(lambdaName => ({ organizationName: orgName, name: lambdaName, sourceRepository: "gh/org/repo" })) ); expect(lambdas).to.have.length(lambdaNames.length); }); }); });
Add tests for GET /lambdas/:organizationName
Add tests for GET /lambdas/:organizationName
JavaScript
mit
lk-architecture/lh-api
--- +++ @@ -0,0 +1,85 @@ +import {all, map} from "bluebird"; +import {expect} from "chai"; +import express from "express"; +import request from "supertest-as-promised"; +import {sign} from "jsonwebtoken"; + +import api from "api"; +import * as config from "config"; +import dynamodb from "services/dynamodb"; + +describe("GET /lambdas/:organizationName", () => { + + const server = express().use(api); + const token = sign( + {aud: config.AUTH0_CLIENT_ID, sub: "userId"}, + config.AUTH0_CLIENT_SECRET + ); + const orgNames = ["org0", "org1", "org2"]; + const lambdaNames = ["lambda0", "lambda1", "lambda2"]; + + beforeEach(() => { + return map(orgNames, orgName => all([ + dynamodb.putAsync({ + TableName: config.DYNAMODB_ORGANIZATIONS, + Item: { + name: orgName, + ownerId: "userId" + } + }), + map(lambdaNames, lambdaName => ( + dynamodb.putAsync({ + TableName: config.DYNAMODB_LAMBDAS, + Item: { + organizationName: orgName, + name: lambdaName, + sourceRepository: "gh/org/repo" + } + }) + )) + ])); + }); + afterEach(() => { + return map(orgNames, orgName => all([ + dynamodb.deleteAsync({ + TableName: config.DYNAMODB_ORGANIZATIONS, + Key: {name: orgName} + }), + map(lambdaNames, lambdaName => ( + dynamodb.deleteAsync({ + TableName: config.DYNAMODB_LAMBDAS, + Key: { + organizationName: orgName, + name: lambdaName + } + }) + )) + ])); + }); + + it("404 on organization not found", () => { + return request(server) + .get("/lambdas/nonExistingOrganizationName") + .set("Authorization", `Bearer ${token}`) + .expect(404) + .expect(/Organization nonExistingOrganizationName not found/); + }); + + it("200 and returns the organization's lambdas", () => { + return map(orgNames, async orgName => { + const {body: lambdas} = await request(server) + .get(`/lambdas/${orgName}`) + .set("Authorization", `Bearer ${token}`) + .expect(200); + expect(lambdas).to.deep.include.members( + lambdaNames.map(lambdaName => ({ + organizationName: orgName, + name: lambdaName, + sourceRepository: "gh/org/repo" + })) + ); + expect(lambdas).to.have.length(lambdaNames.length); + }); + }); + +});
607f3dfaf814022d79458d3fcf6cbef45df2cbbc
test/feature/persist/InsertOrUpdate.spec.js
test/feature/persist/InsertOrUpdate.spec.js
import { createStore, createState } from 'test/support/Helpers' import Model from 'app/model/Model' describe('Features – Persist – Insert Or Update', () => { class User extends Model { static entity = 'users' static fields () { return { id: this.attr(null), name: this.attr(''), posts: this.hasMany(Post, 'user_id') } } } class Post extends Model { static entity = 'posts' static fields () { return { id: this.attr(null), user_id: this.attr(null), title: this.attr('') } } } function getStore () { return createStore([{ model: User }, { model: Post }]) } it('can insert new data and update existing data', async () => { const store = getStore() await store.dispatch('entities/users/create', { data: { id: 1, name: 'John Doe' } }) await store.dispatch('entities/posts/create', { data: { id: 1, user_id: 1, title: 'title 01' } }) await store.dispatch('entities/users/insertOrUpdate', { data: [ { id: 1, name: 'Jane Doe', posts: [{ id: 1, user_id: 1, title: 'title 02' }] }, { id: 2, name: 'Johnny Doe', posts: [{ id: 2, user_id: 2, title: 'title 03' }] } ] }) const expected = createState('entities', { users: { '1': { $id: 1, id: 1, name: 'Jane Doe', posts: [1] }, '2': { $id: 2, id: 2, name: 'Johnny Doe', posts: [2] } }, posts: { '1': { $id: 1, id: 1, user_id: 1, title: 'title 02' }, '2': { $id: 2, id: 2, user_id: 2, title: 'title 03' } } }) expect(store.state.entities).toEqual(expected) }) })
Add insert or update feature test
Add insert or update feature test
JavaScript
mit
revolver-app/vuex-orm,revolver-app/vuex-orm
--- +++ @@ -0,0 +1,72 @@ +import { createStore, createState } from 'test/support/Helpers' +import Model from 'app/model/Model' + +describe('Features – Persist – Insert Or Update', () => { + class User extends Model { + static entity = 'users' + + static fields () { + return { + id: this.attr(null), + name: this.attr(''), + posts: this.hasMany(Post, 'user_id') + } + } + } + + class Post extends Model { + static entity = 'posts' + + static fields () { + return { + id: this.attr(null), + user_id: this.attr(null), + title: this.attr('') + } + } + } + + function getStore () { + return createStore([{ model: User }, { model: Post }]) + } + + it('can insert new data and update existing data', async () => { + const store = getStore() + + await store.dispatch('entities/users/create', { + data: { id: 1, name: 'John Doe' } + }) + + await store.dispatch('entities/posts/create', { + data: { id: 1, user_id: 1, title: 'title 01' } + }) + + await store.dispatch('entities/users/insertOrUpdate', { + data: [ + { + id: 1, + name: 'Jane Doe', + posts: [{ id: 1, user_id: 1, title: 'title 02' }] + }, + { + id: 2, + name: 'Johnny Doe', + posts: [{ id: 2, user_id: 2, title: 'title 03' }] + } + ] + }) + + const expected = createState('entities', { + users: { + '1': { $id: 1, id: 1, name: 'Jane Doe', posts: [1] }, + '2': { $id: 2, id: 2, name: 'Johnny Doe', posts: [2] } + }, + posts: { + '1': { $id: 1, id: 1, user_id: 1, title: 'title 02' }, + '2': { $id: 2, id: 2, user_id: 2, title: 'title 03' } + } + }) + + expect(store.state.entities).toEqual(expected) + }) +})
46b5f29d2fcfa706ac288298bf25d1db28785b12
src/components/RepoLinks.js
src/components/RepoLinks.js
import React from 'react' import { Link } from 'react-router' import { REPOS } from '../config' const makeIssueLinks = () => { return Object.keys(REPOS).map((repoName, i) => { const repo = REPOS[repoName] return ( <li key={`repo$-${repo.name}-${i}`}> <Link to={`/issues/${repoName}`} activeClassName='route--active' > {repo.name} </Link> </li> ) }) } export default () => { return ( <ul> {makeIssueLinks()} </ul> ) }
Add repolinks in as a global component to use on homepage as well as when a route isnt hit
Add repolinks in as a global component to use on homepage as well as when a route isnt hit
JavaScript
mit
aburd/issues-tracker,aburd/issues-tracker
--- +++ @@ -0,0 +1,27 @@ +import React from 'react' +import { Link } from 'react-router' +import { REPOS } from '../config' + +const makeIssueLinks = () => { + return Object.keys(REPOS).map((repoName, i) => { + const repo = REPOS[repoName] + return ( + <li key={`repo$-${repo.name}-${i}`}> + <Link + to={`/issues/${repoName}`} + activeClassName='route--active' + > + {repo.name} + </Link> + </li> + ) + }) +} + +export default () => { + return ( + <ul> + {makeIssueLinks()} + </ul> + ) +}
6ff0dfe41e2303a991a93f67fb98fdfc8e476529
src/blueprints/options/index.js
src/blueprints/options/index.js
/** * Exports object that contains names of options as a key and their configuration objects as a value * * @example * export default { * optionName: { * desc: 'Description for the option', * alias: 'Short name for the option', * type: Boolean || String || Number, * defaults: 'Default value', * hide: false * } * }; */ export default { 'use-default': { desc: 'Use default Sails blueprints', type: Boolean, defaults: false, hide: false } };
/** * Exports object that contains names of options as a key and their configuration objects as a value * * @example * export default { * optionName: { * desc: 'Description for the option', * alias: 'Short name for the option', * type: Boolean || String || Number, * defaults: 'Default value', * hide: false * } * }; */ export default { 'use-default': { desc: 'Scaffolds default Sails blueprints', type: Boolean, defaults: false, hide: false } };
Update description for --use-default option
Update description for --use-default option
JavaScript
mit
ghaiklor/generator-sails-rest-api,italoag/generator-sails-rest-api,IncoCode/generator-sails-rest-api,jaumard/generator-trails,tnunes/generator-trails,italoag/generator-sails-rest-api,konstantinzolotarev/generator-trails,ghaiklor/generator-sails-rest-api
--- +++ @@ -15,7 +15,7 @@ export default { 'use-default': { - desc: 'Use default Sails blueprints', + desc: 'Scaffolds default Sails blueprints', type: Boolean, defaults: false, hide: false
8b9e7302ea5ab24c718d788d5d5ae13c2871c8ff
addons/actions/src/containers/ActionLogger/index.js
addons/actions/src/containers/ActionLogger/index.js
import React from 'react'; import deepEqual from 'deep-equal'; import ActionLoggerComponent from '../../components/ActionLogger/'; import { EVENT_ID } from '../../'; export default class ActionLogger extends React.Component { constructor(props, ...args) { super(props, ...args); this.state = { actions: [] }; this._actionListener = action => this.addAction(action); } addAction(action) { action.data.args = action.data.args.map(arg => JSON.parse(arg)); const actions = [...this.state.actions]; const previous = actions.length && actions[0]; if (previous && deepEqual(previous.data, action.data)) { previous.count++; } else { action.count = 1; actions.unshift(action); } this.setState({ actions }); } clearActions() { this.setState({ actions: [] }); } componentDidMount() { this.props.channel.on(EVENT_ID, this._actionListener); } componentWillUnmount() { this.props.channel.removeListener(EVENT_ID, this._actionListener); } render() { const props = { actions: this.state.actions, onClear: () => this.clearActions(), }; return <ActionLoggerComponent {...props} />; } }
import React from 'react'; import deepEqual from 'deep-equal'; import ActionLoggerComponent from '../../components/ActionLogger/'; import { EVENT_ID } from '../../'; export default class ActionLogger extends React.Component { constructor(props, ...args) { super(props, ...args); this.state = { actions: [] }; this._actionListener = action => this.addAction(action); } addAction(action) { action.data.args = action.data.args.map(arg => JSON.parse(arg)); const actions = [...this.state.actions]; const previous = actions.length && actions[0]; if (previous && deepEqual(previous.data, action.data, { strict: true })) { previous.count++; } else { action.count = 1; actions.unshift(action); } this.setState({ actions }); } clearActions() { this.setState({ actions: [] }); } componentDidMount() { this.props.channel.on(EVENT_ID, this._actionListener); } componentWillUnmount() { this.props.channel.removeListener(EVENT_ID, this._actionListener); } render() { const props = { actions: this.state.actions, onClear: () => this.clearActions(), }; return <ActionLoggerComponent {...props} />; } }
Use strict equality to distinguish 0 from an empty string
Use strict equality to distinguish 0 from an empty string
JavaScript
mit
rhalff/storybook,storybooks/storybook,kadirahq/react-storybook,enjoylife/storybook,rhalff/storybook,nfl/react-storybook,enjoylife/storybook,jribeiro/storybook,storybooks/react-storybook,storybooks/storybook,nfl/react-storybook,rhalff/storybook,kadirahq/react-storybook,jribeiro/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,enjoylife/storybook,nfl/react-storybook,rhalff/storybook,rhalff/storybook,storybooks/storybook,rhalff/storybook,storybooks/react-storybook,enjoylife/storybook,storybooks/react-storybook,jribeiro/storybook,nfl/react-storybook,storybooks/storybook,storybooks/react-storybook,jribeiro/storybook
--- +++ @@ -14,7 +14,7 @@ action.data.args = action.data.args.map(arg => JSON.parse(arg)); const actions = [...this.state.actions]; const previous = actions.length && actions[0]; - if (previous && deepEqual(previous.data, action.data)) { + if (previous && deepEqual(previous.data, action.data, { strict: true })) { previous.count++; } else { action.count = 1;
fb65038c97a8ded28d34f7ea2bc32387395293d7
test/mocha/stop_word_filter_test.js
test/mocha/stop_word_filter_test.js
suite('lunr.stopWordFilter', function () { test('filters stop words', function () { var stopWords = ['the', 'and', 'but', 'than', 'when'] stopWords.forEach(function (word) { assert.isUndefined(lunr.stopWordFilter(word)) }) }) test('ignores non stop words', function () { var nonStopWords = ['interesting', 'words', 'pass', 'through'] nonStopWords.forEach(function (word) { assert.equal(word, lunr.stopWordFilter(word)) }) }) test('ignores properties of Object.prototype', function () { var nonStopWords = ['constructor', 'hasOwnProperty', 'toString', 'valueOf'] nonStopWords.forEach(function (word) { assert.equal(word, lunr.stopWordFilter(word)) }) }) test('is a registered pipeline function', function () { assert.equal('stopWordFilter', lunr.stopWordFilter.label) assert.equal(lunr.stopWordFilter, lunr.Pipeline.registeredFunctions['stopWordFilter']) }) })
Convert stopword filter test to mocha/chai.
Convert stopword filter test to mocha/chai.
JavaScript
mit
olivernn/lunr.js,olivernn/lunr.js,olivernn/lunr.js
--- +++ @@ -0,0 +1,30 @@ +suite('lunr.stopWordFilter', function () { + test('filters stop words', function () { + var stopWords = ['the', 'and', 'but', 'than', 'when'] + + stopWords.forEach(function (word) { + assert.isUndefined(lunr.stopWordFilter(word)) + }) + }) + + test('ignores non stop words', function () { + var nonStopWords = ['interesting', 'words', 'pass', 'through'] + + nonStopWords.forEach(function (word) { + assert.equal(word, lunr.stopWordFilter(word)) + }) + }) + + test('ignores properties of Object.prototype', function () { + var nonStopWords = ['constructor', 'hasOwnProperty', 'toString', 'valueOf'] + + nonStopWords.forEach(function (word) { + assert.equal(word, lunr.stopWordFilter(word)) + }) + }) + + test('is a registered pipeline function', function () { + assert.equal('stopWordFilter', lunr.stopWordFilter.label) + assert.equal(lunr.stopWordFilter, lunr.Pipeline.registeredFunctions['stopWordFilter']) + }) +})
13023ccb5275e50a6553bf60d8da51f5b745ca4f
tools/scripts/api-docs/pkg_order.js
tools/scripts/api-docs/pkg_order.js
#!/usr/bin/env node /** * @license Apache-2.0 * * Copyright (c) 2021 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var join = require( 'path' ).join; var writeFile = require( '@stdlib/fs/write-file' ).sync; var readJSON = require( '@stdlib/fs/read-json' ).sync; var objectInverse = require( '@stdlib/utils/object-inverse' ); var documentationPath = require( './docs_path.js' ); // VARIABLES // var OUTPUT = 'package_order.json'; // MAIN // /** * Main execution sequence. * * @private * @throws {Error} unexpected error */ function main() { var dpath; var opts; var pkgs; var out; // Resolve the API documentation path: dpath = documentationPath(); // Load the list of packages... opts = { 'encoding': 'utf8' }; pkgs = readJSON( join( dpath, 'package_list.json' ), opts ); if ( pkgs instanceof Error ) { throw pkgs; } // Generate a hash for looking up a package's order in the package list: out = objectInverse( pkgs ); // Write the database to file: writeFile( join( dpath, OUTPUT ), JSON.stringify( out ) ); } main();
Add script to generate a package order hash
Add script to generate a package order hash
JavaScript
apache-2.0
stdlib-js/www,stdlib-js/www,stdlib-js/www
--- +++ @@ -0,0 +1,69 @@ +#!/usr/bin/env node + +/** +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var join = require( 'path' ).join; +var writeFile = require( '@stdlib/fs/write-file' ).sync; +var readJSON = require( '@stdlib/fs/read-json' ).sync; +var objectInverse = require( '@stdlib/utils/object-inverse' ); +var documentationPath = require( './docs_path.js' ); + + +// VARIABLES // + +var OUTPUT = 'package_order.json'; + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +* @throws {Error} unexpected error +*/ +function main() { + var dpath; + var opts; + var pkgs; + var out; + + // Resolve the API documentation path: + dpath = documentationPath(); + + // Load the list of packages... + opts = { + 'encoding': 'utf8' + }; + pkgs = readJSON( join( dpath, 'package_list.json' ), opts ); + if ( pkgs instanceof Error ) { + throw pkgs; + } + // Generate a hash for looking up a package's order in the package list: + out = objectInverse( pkgs ); + + // Write the database to file: + writeFile( join( dpath, OUTPUT ), JSON.stringify( out ) ); +} + +main();
644fcd3cf81db274a4464c0e0a9220a553977d1b
app/pages/prescription/prescriptionFormStyles.js
app/pages/prescription/prescriptionFormStyles.js
import { default as baseTheme } from '../../themes/baseTheme'; export const formWrapperStyles = { width: [1, 0.75, 0.5, 0.33], mt: 5, mb: 6, mx: 'auto', }; export const inputStyles = { width: '100%', themeProps: { mb: 3, }, }; export const checkboxStyles = { width: '100%', themeProps: { fontSize: 1, }, }; export const checkboxGroupStyles = { variant: 'inputs.checkboxGroup.verticalBordered', theme: baseTheme, mb: 3, };
Move common prescription form styles to own file
[WEB-819] Move common prescription form styles to own file
JavaScript
bsd-2-clause
tidepool-org/blip,tidepool-org/blip,tidepool-org/blip
--- +++ @@ -0,0 +1,28 @@ +import { default as baseTheme } from '../../themes/baseTheme'; + +export const formWrapperStyles = { + width: [1, 0.75, 0.5, 0.33], + mt: 5, + mb: 6, + mx: 'auto', +}; + +export const inputStyles = { + width: '100%', + themeProps: { + mb: 3, + }, +}; + +export const checkboxStyles = { + width: '100%', + themeProps: { + fontSize: 1, + }, +}; + +export const checkboxGroupStyles = { + variant: 'inputs.checkboxGroup.verticalBordered', + theme: baseTheme, + mb: 3, +};
cb3d5a46e23f1946334007f29bc31a2c65d211ae
src/adapters/jasmine-2.x-blanket.js
src/adapters/jasmine-2.x-blanket.js
(function() { if (! jasmine) { throw new Exception("jasmine library does not exist in global namespace!"); } function elapsed(startTime, endTime) { return (endTime - startTime)/1000; } function ISODateString(d) { function pad(n) { return n < 10 ? '0'+n : n; } return d.getFullYear() + '-' + pad(d.getMonth()+1) + '-' + pad(d.getDate()) + 'T' + pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds()); } function trim(str) { return str.replace(/^\s+/, "" ).replace(/\s+$/, "" ); } function escapeInvalidXmlChars(str) { return str.replace(/\&/g, "&amp;") .replace(/</g, "&lt;") .replace(/\>/g, "&gt;") .replace(/\"/g, "&quot;") .replace(/\'/g, "&apos;"); } /** * based on https://raw.github.com/larrymyers/jasmine-reporters/master/src/jasmine.junit_reporter.js */ var BlanketReporter = function(savePath, consolidate, useDotNotation) { blanket.setupCoverage(); }; BlanketReporter.finished_at = null; // will be updated after all files have been written BlanketReporter.prototype = { specStarted: function(spec) { blanket.onTestStart(); }, specDone: function(result) { var passed = result.status === "passed" ? 1 : 0; blanket.onTestDone(1,passed); }, jasmineDone: function() { blanket.onTestsDone(); }, log: function(str) { var console = jasmine.getGlobal().console; if (console && console.log) { console.log(str); } } }; // export public jasmine.BlanketReporter = BlanketReporter; //override existing jasmine execute var originalJasmineExecute = jasmine.getEnv().execute; jasmine.getEnv().execute = function(){ console.log("waiting for blanket..."); }; blanket.beforeStartTestRunner({ checkRequirejs:true, callback:function(){ jasmine.getEnv().addReporter(new jasmine.BlanketReporter()); jasmine.getEnv().execute = originalJasmineExecute; jasmine.getEnv().execute(); } }); })();
Add adapter for Jasmine 2.x
Add adapter for Jasmine 2.x
JavaScript
mit
ssnau/blanket,reggi/blanket,agray/blanket,listepo/blanket,kidaa/blanket,listepo/blanket,kidaa/blanket,Jeff-Lewis/blanket,jlturner/blanket,ssnau/blanket,ahamid/blanket,Jeff-Lewis/blanket,Jbarget/blanket,Jbarget/blanket,agray/blanket,ahamid/blanket,reggi/blanket,agray/blanket,jlturner/blanket
--- +++ @@ -0,0 +1,82 @@ +(function() { + + if (! jasmine) { + throw new Exception("jasmine library does not exist in global namespace!"); + } + + function elapsed(startTime, endTime) { + return (endTime - startTime)/1000; + } + + function ISODateString(d) { + function pad(n) { return n < 10 ? '0'+n : n; } + + return d.getFullYear() + '-' + + pad(d.getMonth()+1) + '-' + + pad(d.getDate()) + 'T' + + pad(d.getHours()) + ':' + + pad(d.getMinutes()) + ':' + + pad(d.getSeconds()); + } + + function trim(str) { + return str.replace(/^\s+/, "" ).replace(/\s+$/, "" ); + } + + function escapeInvalidXmlChars(str) { + return str.replace(/\&/g, "&amp;") + .replace(/</g, "&lt;") + .replace(/\>/g, "&gt;") + .replace(/\"/g, "&quot;") + .replace(/\'/g, "&apos;"); + } + + /** + * based on https://raw.github.com/larrymyers/jasmine-reporters/master/src/jasmine.junit_reporter.js + */ + var BlanketReporter = function(savePath, consolidate, useDotNotation) { + + blanket.setupCoverage(); + }; + BlanketReporter.finished_at = null; // will be updated after all files have been written + + BlanketReporter.prototype = { + specStarted: function(spec) { + blanket.onTestStart(); + }, + + specDone: function(result) { + var passed = result.status === "passed" ? 1 : 0; + blanket.onTestDone(1,passed); + }, + + jasmineDone: function() { + blanket.onTestsDone(); + }, + + log: function(str) { + var console = jasmine.getGlobal().console; + + if (console && console.log) { + console.log(str); + } + } + }; + + // export public + jasmine.BlanketReporter = BlanketReporter; + + //override existing jasmine execute + var originalJasmineExecute = jasmine.getEnv().execute; + jasmine.getEnv().execute = function(){ console.log("waiting for blanket..."); }; + + + blanket.beforeStartTestRunner({ + checkRequirejs:true, + callback:function(){ + jasmine.getEnv().addReporter(new jasmine.BlanketReporter()); + jasmine.getEnv().execute = originalJasmineExecute; + jasmine.getEnv().execute(); + } + }); +})();
9a469783f03ec07166e4dd9715d13a763d9af37e
test-support/ember-cli-i18n-test.js
test-support/ember-cli-i18n-test.js
/* globals requirejs, require */ import Ember from 'ember'; import config from '../config/environment'; var keys = Ember.keys; var locales, defaultLocale; module('ember-cli-i18n', { setup: function() { var localRegExp = new RegExp(config.modulePrefix + '/locales/(.+)'); var match, moduleName; locales = {}; for (moduleName in requirejs.entries) { if (match = moduleName.match(localRegExp)) { locales[match[1]] = require(moduleName)['default']; } } defaultLocale = locales[config.APP.defaultLocale]; } }); test('locales all contain the same keys', function() { var knownLocales = keys(locales); for (var i = 0, l = knownLocales.length; i < l; i++) { var currentLocale = locales[knownLocales[i]]; if (currentLocale === defaultLocale) { continue; } for (var translationKey in defaultLocale) { ok(currentLocale[translationKey], '`' + translationKey + '` should exist in the `' + knownLocales[i] + '` locale.'); } } });
Add test confirming all locales have all keys.
Add test confirming all locales have all keys. Something that has bit our team a few times: we add a new key to the default locale file, but forget to add it to the others. This adds an test that runs in the consuming app, that confirms all locale files contain the keys from the `defaultLocale`.
JavaScript
mit
ember-furnace/ember-cli-furnace-i18n,DavyJonesLocker/ember-cli-i18n,ember-furnace/ember-cli-furnace-i18n,dockyard/ember-cli-i18n,dockyard/ember-cli-i18n,DavyJonesLocker/ember-cli-i18n
--- +++ @@ -0,0 +1,40 @@ +/* globals requirejs, require */ + +import Ember from 'ember'; +import config from '../config/environment'; + +var keys = Ember.keys; + +var locales, defaultLocale; +module('ember-cli-i18n', { + setup: function() { + var localRegExp = new RegExp(config.modulePrefix + '/locales/(.+)'); + var match, moduleName; + + locales = {}; + + for (moduleName in requirejs.entries) { + if (match = moduleName.match(localRegExp)) { + locales[match[1]] = require(moduleName)['default']; + } + } + + defaultLocale = locales[config.APP.defaultLocale]; + } +}); + +test('locales all contain the same keys', function() { + var knownLocales = keys(locales); + + for (var i = 0, l = knownLocales.length; i < l; i++) { + var currentLocale = locales[knownLocales[i]]; + + if (currentLocale === defaultLocale) { + continue; + } + + for (var translationKey in defaultLocale) { + ok(currentLocale[translationKey], '`' + translationKey + '` should exist in the `' + knownLocales[i] + '` locale.'); + } + } +});
b240a49434236c708eacf9be7a60a99052ed2bb0
server/src/scripts/add-leave-thread-permissions.js
server/src/scripts/add-leave-thread-permissions.js
// @flow import { threadPermissions, threadTypes } from 'lib/types/thread-types'; import { dbQuery, SQL } from '../database/database'; import { endScript } from './utils'; import { recalculateAllThreadPermissions } from '../updaters/thread-permission-updaters'; async function main() { try { await addLeaveThreadPermissions(); await recalculateAllThreadPermissions(); } catch (e) { console.warn(e); } finally { endScript(); } } async function addLeaveThreadPermissions() { const leaveThreadString = `$.${threadPermissions.LEAVE_THREAD}`; const updateAllRoles = SQL` UPDATE roles r LEFT JOIN threads t ON t.id = r.thread SET r.permissions = JSON_SET(permissions, ${leaveThreadString}, TRUE) WHERE t.type != ${threadTypes.PERSONAL} `; await dbQuery(updateAllRoles); } main();
Create script to add LEAVE_THREAD permission
[server] Create script to add LEAVE_THREAD permission Test Plan: Tested on a single row to check if results are matching expectacions. Inspected `membership` table to check if `leave_thread` permission is added. Inspected `roles` table to check if permission is added. Ran a query after the script, and made sure only personal threads are in the result: `SELECT * FROM roles WHERE JSON_EXTRACT(permissions, "$.leave_thread") IS NULL` Checked if leave thread button is displayed and after pressing there are no errors and user leaves thread Reviewers: ashoat, palys-swm Reviewed By: ashoat Subscribers: zrebcu411, Adrian Differential Revision: https://phabricator.ashoat.com/D466
JavaScript
bsd-3-clause
Ashoat/squadcal,Ashoat/squadcal,Ashoat/squadcal,Ashoat/squadcal,Ashoat/squadcal,Ashoat/squadcal,Ashoat/squadcal
--- +++ @@ -0,0 +1,31 @@ +// @flow + +import { threadPermissions, threadTypes } from 'lib/types/thread-types'; + +import { dbQuery, SQL } from '../database/database'; +import { endScript } from './utils'; +import { recalculateAllThreadPermissions } from '../updaters/thread-permission-updaters'; + +async function main() { + try { + await addLeaveThreadPermissions(); + await recalculateAllThreadPermissions(); + } catch (e) { + console.warn(e); + } finally { + endScript(); + } +} + +async function addLeaveThreadPermissions() { + const leaveThreadString = `$.${threadPermissions.LEAVE_THREAD}`; + const updateAllRoles = SQL` + UPDATE roles r + LEFT JOIN threads t ON t.id = r.thread + SET r.permissions = JSON_SET(permissions, ${leaveThreadString}, TRUE) + WHERE t.type != ${threadTypes.PERSONAL} + `; + await dbQuery(updateAllRoles); +} + +main();
19d06d29b6f909334f0ef8860f3f8e96b37d7917
test/refraction-test.js
test/refraction-test.js
var expect = require('./spec-helper').expect; var minim = require('../lib/minim'); var refract = require('../lib/refraction').refract; describe('refract', function() { it('returns any given element without refracting', function() { var element = new minim.StringElement('hello'); var refracted = refract(element); expect(refracted).to.equal(element); }); it('can refract a string into a string element', function() { var element = refract('Hello'); expect(element).to.be.instanceof(minim.StringElement); expect(element.content).to.equal('Hello'); }); it('can refract a number into a number element', function() { var element = refract(1); expect(element).to.be.instanceof(minim.NumberElement); expect(element.content).to.equal(1); }); it('can refract a boolean into a boolean element', function() { var element = refract(true); expect(element).to.be.instanceof(minim.BooleanElement); expect(element.content).to.equal(true); }); it('can refract a null value into a null element', function() { var element = refract(null); expect(element).to.be.instanceof(minim.NullElement); expect(element.content).to.equal(null); }); it('can refract an array of values into an array element', function() { var element = refract(['Hi', 1]); expect(element).to.be.instanceof(minim.ArrayElement); expect(element.length).to.be.equal(2); expect(element.get(0)).to.be.instanceof(minim.StringElement); expect(element.get(0).content).to.equal('Hi'); expect(element.get(1)).to.be.instanceof(minim.NumberElement); expect(element.get(1).content).to.equal(1); }); it('can refract an object into an object element', function() { var element = refract({'name': 'Doe'}); expect(element).to.be.instanceof(minim.ObjectElement); expect(element.length).to.equal(1); var member = element.content[0]; expect(member).to.be.instanceof(minim.MemberElement); expect(member.key).to.be.instanceof(minim.StringElement); expect(member.key.content).to.equal('name'); expect(member.value).to.be.instanceof(minim.StringElement); expect(member.value.content).to.equal('Doe'); }); });
Add unit tests for refraction
fix: Add unit tests for refraction
JavaScript
mit
refractproject/minim
--- +++ @@ -0,0 +1,65 @@ +var expect = require('./spec-helper').expect; +var minim = require('../lib/minim'); +var refract = require('../lib/refraction').refract; + +describe('refract', function() { + it('returns any given element without refracting', function() { + var element = new minim.StringElement('hello'); + var refracted = refract(element); + + expect(refracted).to.equal(element); + }); + + it('can refract a string into a string element', function() { + var element = refract('Hello'); + + expect(element).to.be.instanceof(minim.StringElement); + expect(element.content).to.equal('Hello'); + }); + + it('can refract a number into a number element', function() { + var element = refract(1); + + expect(element).to.be.instanceof(minim.NumberElement); + expect(element.content).to.equal(1); + }); + + it('can refract a boolean into a boolean element', function() { + var element = refract(true); + + expect(element).to.be.instanceof(minim.BooleanElement); + expect(element.content).to.equal(true); + }); + + it('can refract a null value into a null element', function() { + var element = refract(null); + + expect(element).to.be.instanceof(minim.NullElement); + expect(element.content).to.equal(null); + }); + + it('can refract an array of values into an array element', function() { + var element = refract(['Hi', 1]); + + expect(element).to.be.instanceof(minim.ArrayElement); + expect(element.length).to.be.equal(2); + expect(element.get(0)).to.be.instanceof(minim.StringElement); + expect(element.get(0).content).to.equal('Hi'); + expect(element.get(1)).to.be.instanceof(minim.NumberElement); + expect(element.get(1).content).to.equal(1); + }); + + it('can refract an object into an object element', function() { + var element = refract({'name': 'Doe'}); + + expect(element).to.be.instanceof(minim.ObjectElement); + expect(element.length).to.equal(1); + + var member = element.content[0]; + expect(member).to.be.instanceof(minim.MemberElement); + expect(member.key).to.be.instanceof(minim.StringElement); + expect(member.key.content).to.equal('name'); + expect(member.value).to.be.instanceof(minim.StringElement); + expect(member.value.content).to.equal('Doe'); + }); +});
36c06d58bd84e4909fe11f2da7ca20b9968a1aa9
test/unit_test/compiler/notfoundindcacheerror.spec.js
test/unit_test/compiler/notfoundindcacheerror.spec.js
'use strict'; /** * @ignore * @suppress {dupicate} */ var NotFoundInCacheError = /** @type {function(new:NotFoundInCacheError, string, string, string): undefined} */ (require('../../../src/compiler/NotFoundInCacheError.js')); fdescribe('Class NotFoundInCacheError', function () { describe('can be instantiated', function () { it('with correct parameters', function () { var err; expect(function () { err = new NotFoundInCacheError('unit1', 'unit1#hash', '/cache/folder/location'); }).not.toThrow(); expect(err).toBeDefined(); expect(err).not.toBeNull(); expect(err).toEqual(jasmine.any(NotFoundInCacheError)); }); it('with incorrect parameters', function () { var err; expect(function () { err = new NotFoundInCacheError(123, {}, ['some string value']); }).not.toThrow(); expect(err).toBeDefined(); expect(err).not.toBeNull(); expect(err).toEqual(jasmine.any(NotFoundInCacheError)); }); it('without parameters', function () { var err; expect(function () { err = new NotFoundInCacheError(); }).not.toThrow(); expect(err).toBeDefined(); expect(err).not.toBeNull(); expect(err).toEqual(jasmine.any(NotFoundInCacheError)); }); }); it('inherits from Error', function () { expect(new NotFoundInCacheError()).toEqual(jasmine.any(Error)); }); describe('the method', function () { var err; var unitName = 'unit1'; var unitHash = 'unit1#hash'; var cacheFolder = '/cache/folder/location'; beforeEach(function () { err = new NotFoundInCacheError(unitName, unitHash, cacheFolder); }); it('.getCompilationUnitName() returns the name of the compilation unit for the error context', function () { expect(err.getCompilationUnitName()).toBe(unitName); }); it('.getCompilationUnitHash() returns the hash of the compilation unit for the error context', function () { expect(err.getCompilationUnitHash()).toBe(unitHash); }); it('.getCacheFolderLocation() returns the name of the cache location for the error context', function () { expect(err.getCacheFolderLocation()).toBe(cacheFolder); }); }); });
Add unit tests for NotFoundInCacheError
tests: Add unit tests for NotFoundInCacheError
JavaScript
mit
lgeorgieff/nbuild,lgeorgieff/ccbuild
--- +++ @@ -0,0 +1,68 @@ +'use strict'; + +/** + * @ignore + * @suppress {dupicate} + */ +var NotFoundInCacheError = /** @type {function(new:NotFoundInCacheError, string, string, string): undefined} */ + (require('../../../src/compiler/NotFoundInCacheError.js')); + +fdescribe('Class NotFoundInCacheError', function () { + describe('can be instantiated', function () { + it('with correct parameters', function () { + var err; + expect(function () { + err = new NotFoundInCacheError('unit1', 'unit1#hash', '/cache/folder/location'); + }).not.toThrow(); + expect(err).toBeDefined(); + expect(err).not.toBeNull(); + expect(err).toEqual(jasmine.any(NotFoundInCacheError)); + }); + + it('with incorrect parameters', function () { + var err; + expect(function () { + err = new NotFoundInCacheError(123, {}, ['some string value']); + }).not.toThrow(); + expect(err).toBeDefined(); + expect(err).not.toBeNull(); + expect(err).toEqual(jasmine.any(NotFoundInCacheError)); + }); + + it('without parameters', function () { + var err; + expect(function () { + err = new NotFoundInCacheError(); + }).not.toThrow(); + expect(err).toBeDefined(); + expect(err).not.toBeNull(); + expect(err).toEqual(jasmine.any(NotFoundInCacheError)); + }); + }); + + it('inherits from Error', function () { + expect(new NotFoundInCacheError()).toEqual(jasmine.any(Error)); + }); + + describe('the method', function () { + var err; + var unitName = 'unit1'; + var unitHash = 'unit1#hash'; + var cacheFolder = '/cache/folder/location'; + beforeEach(function () { + err = new NotFoundInCacheError(unitName, unitHash, cacheFolder); + }); + + it('.getCompilationUnitName() returns the name of the compilation unit for the error context', function () { + expect(err.getCompilationUnitName()).toBe(unitName); + }); + + it('.getCompilationUnitHash() returns the hash of the compilation unit for the error context', function () { + expect(err.getCompilationUnitHash()).toBe(unitHash); + }); + + it('.getCacheFolderLocation() returns the name of the cache location for the error context', function () { + expect(err.getCacheFolderLocation()).toBe(cacheFolder); + }); + }); +});
83832098b8db0e17cec5cf5fc555ecfa3f5cbc81
lib/repositories/httpAPI.js
lib/repositories/httpAPI.js
require('isomorphic-fetch'); require('es6-promise').polyfill(); var fetch = window.fetch; var _ = require('underscore'); var CONTENT_TYPE = 'Content-Type'; var JSON_CONTENT_TYPE = 'application/json'; function HttpAPIRepository(mixinOptions) { var defaultBaseUrl = ''; var methods = ['get', 'put', 'post', 'delete']; var mixin = { request: function (options) { if (!options.headers) { options.headers = {}; } if (contentType() === JSON_CONTENT_TYPE && _.isObject(options.body)) { options.body = JSON.stringify(options.body); options.headers[CONTENT_TYPE] = JSON_CONTENT_TYPE; } return fetch(options.url, options).then(function (res) { if (isJson(res)) { res.body = JSON.parse(res._body); } return res; }); function isJson(res) { var contentTypes = getHeader(res, CONTENT_TYPE); _.isArray(contentTypes) || (contentTypes = [contentTypes]); return _.any(contentTypes, function (contentType) { return contentType.indexOf(JSON_CONTENT_TYPE) !== -1; }); } function getHeader(res, name) { return _.find(res.headers.map, function (value, key) { return key.toLowerCase() === name.toLowerCase(); }); } function contentType() { return options.headers[CONTENT_TYPE] || JSON_CONTENT_TYPE; } } }; //Sugar methods for common HTTP methods _.each(methods, function (method) { mixin[method] = function (options) { return this.request(requestOptions(method.toUpperCase(), mixinOptions.baseUrl || defaultBaseUrl, options)); }; }); return mixin; } function requestOptions(method, baseUrl, options) { if (_.isString(options)) { options = _.extend({ url: options }); } options.method = method.toLowerCase(); if (baseUrl) { var separator = ''; var firstCharOfUrl = options.url[0]; var lastCharOfBaseUrl = baseUrl[baseUrl.length - 1]; // Do some text wrangling to make sure concatenation of base url // stupid people (i.e. me) if (lastCharOfBaseUrl !== '/' && firstCharOfUrl !== '/') { separator = '/'; } else if (lastCharOfBaseUrl === '/' && firstCharOfUrl === '/') { options.url = options.url.substring(1); } options.url = baseUrl + separator + options.url; } return options; } module.exports = HttpAPIRepository;
Refactor HTTP API into repository structure
Refactor HTTP API into repository structure
JavaScript
mit
martyjs/marty,martyjs/marty-lib,kwangkim/marty,oliverwoodings/marty,goldensunliu/marty-lib,oliverwoodings/marty,thredup/marty-lib,martyjs/marty,bigardone/marty,Driftt/marty,KeKs0r/marty-lib,kwangkim/marty,CumpsD/marty-lib,thredup/marty,thredup/marty,bigardone/marty,kwangkim/marty,Driftt/marty,bigardone/marty,gmccrackin/marty-lib
--- +++ @@ -0,0 +1,94 @@ +require('isomorphic-fetch'); +require('es6-promise').polyfill(); + +var fetch = window.fetch; +var _ = require('underscore'); +var CONTENT_TYPE = 'Content-Type'; +var JSON_CONTENT_TYPE = 'application/json'; + +function HttpAPIRepository(mixinOptions) { + + var defaultBaseUrl = ''; + var methods = ['get', 'put', 'post', 'delete']; + + var mixin = { + request: function (options) { + if (!options.headers) { + options.headers = {}; + } + + if (contentType() === JSON_CONTENT_TYPE && _.isObject(options.body)) { + options.body = JSON.stringify(options.body); + options.headers[CONTENT_TYPE] = JSON_CONTENT_TYPE; + } + + return fetch(options.url, options).then(function (res) { + if (isJson(res)) { + res.body = JSON.parse(res._body); + } + + return res; + }); + + function isJson(res) { + var contentTypes = getHeader(res, CONTENT_TYPE); + + _.isArray(contentTypes) || (contentTypes = [contentTypes]); + + return _.any(contentTypes, function (contentType) { + return contentType.indexOf(JSON_CONTENT_TYPE) !== -1; + }); + } + + function getHeader(res, name) { + return _.find(res.headers.map, function (value, key) { + return key.toLowerCase() === name.toLowerCase(); + }); + } + + function contentType() { + return options.headers[CONTENT_TYPE] || JSON_CONTENT_TYPE; + } + } + }; + + //Sugar methods for common HTTP methods + _.each(methods, function (method) { + mixin[method] = function (options) { + return this.request(requestOptions(method.toUpperCase(), mixinOptions.baseUrl || defaultBaseUrl, options)); + }; + }); + + return mixin; + +} + +function requestOptions(method, baseUrl, options) { + if (_.isString(options)) { + options = _.extend({ + url: options + }); + } + + options.method = method.toLowerCase(); + + if (baseUrl) { + var separator = ''; + var firstCharOfUrl = options.url[0]; + var lastCharOfBaseUrl = baseUrl[baseUrl.length - 1]; + + // Do some text wrangling to make sure concatenation of base url + // stupid people (i.e. me) + if (lastCharOfBaseUrl !== '/' && firstCharOfUrl !== '/') { + separator = '/'; + } else if (lastCharOfBaseUrl === '/' && firstCharOfUrl === '/') { + options.url = options.url.substring(1); + } + + options.url = baseUrl + separator + options.url; + } + + return options; +} + +module.exports = HttpAPIRepository;
61f1331004e1604e3856e89504e4e469cbd4904a
webpack.config.js
webpack.config.js
var path = require('path'); var process = require('process'); var fs = require('fs'); module.exports = { context: path.join(process.env.PWD, 'frontend'), entry: "./index.js", target: 'node', output: { path: path.join(__dirname, 'dist'), filename: 'webpack.bundle.js' }, module: { loaders: [ { test: /\.js$/, loader: 'babel' } ] } };
var path = require('path'); var process = require('process'); var fs = require('fs'); var webpack = require('webpack'); module.exports = { context: path.join(process.env.PWD, 'frontend'), entry: "./index.js", target: 'node', output: { path: path.join(__dirname, 'dist'), filename: 'webpack.bundle.js' }, plugins: [ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify(process.env.NODE_ENV) } }) ], module: { loaders: [ { test: /\.js$/, loader: 'babel' } ] } };
Fix ` ReferenceError: process is not defined` on ReactPref
Fix ` ReferenceError: process is not defined` on ReactPref * ReactPref call `process`, but does not defined. so webpack.DefinePlugin give process object.
JavaScript
mit
mgi166/usi-front,mgi166/usi-front
--- +++ @@ -1,6 +1,7 @@ var path = require('path'); var process = require('process'); var fs = require('fs'); +var webpack = require('webpack'); module.exports = { context: path.join(process.env.PWD, 'frontend'), @@ -10,6 +11,13 @@ path: path.join(__dirname, 'dist'), filename: 'webpack.bundle.js' }, + plugins: [ + new webpack.DefinePlugin({ + 'process.env': { + NODE_ENV: JSON.stringify(process.env.NODE_ENV) + } + }) + ], module: { loaders: [ { test: /\.js$/, loader: 'babel' }
1a2b1508b4ab94f5e550550ebe9748288bf43f89
webpack.config.js
webpack.config.js
const path = require('path') const webpack = require('webpack') const ENV = process.env.NODE_ENV || 'development' const appendIf = (cond, ...items) => cond ? items : [] const plugins = [ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify(ENV) } }), ...appendIf(ENV === 'production', new webpack.optimize.UglifyJsPlugin()), ...appendIf(ENV !== 'production', new webpack.HotModuleReplacementPlugin()) ] module.exports = { entry: [ 'react-hot-loader/patch', './src/index.js' ], output: { path: path.resolve(__dirname, 'static'), filename: 'bundle.js' }, resolve: { extensions: ['.js', '.jsx'] }, plugins: plugins, module: { rules: [{ test: /\.jsx?$/, exclude: /node_modules/, loaders: ['react-hot-loader/webpack', 'babel-loader'], }] }, devServer: { hot: true, contentBase: path.join(__dirname, 'static'), publicPath: '/' } }
const path = require('path') const webpack = require('webpack') const ENV = process.env.NODE_ENV || 'development' const appendIf = (cond, ...items) => cond ? items : [] const plugins = [ ...appendIf(ENV !== 'production', new webpack.HotModuleReplacementPlugin()) ] module.exports = { entry: [ 'react-hot-loader/patch', './src/index.js' ], output: { path: path.resolve(__dirname, 'static'), filename: 'bundle.js' }, resolve: { extensions: ['.js', '.jsx'] }, plugins: plugins, module: { rules: [{ test: /\.jsx?$/, exclude: /node_modules/, loaders: [ 'react-hot-loader/webpack', 'babel-loader' ], }] }, devServer: { hot: true, contentBase: path.join(__dirname, 'static'), publicPath: '/' } }
Remove manual env injection and uglify plugin. webpacks `-p` argument handles this.
Remove manual env injection and uglify plugin. webpacks `-p` argument handles this.
JavaScript
mit
dan-lee/react-minimal-starter-kit,dan-lee/react-minimal-starter-kit
--- +++ @@ -4,10 +4,6 @@ const appendIf = (cond, ...items) => cond ? items : [] const plugins = [ - new webpack.DefinePlugin({ - 'process.env': { NODE_ENV: JSON.stringify(ENV) } - }), - ...appendIf(ENV === 'production', new webpack.optimize.UglifyJsPlugin()), ...appendIf(ENV !== 'production', new webpack.HotModuleReplacementPlugin()) ] @@ -28,7 +24,10 @@ rules: [{ test: /\.jsx?$/, exclude: /node_modules/, - loaders: ['react-hot-loader/webpack', 'babel-loader'], + loaders: [ + 'react-hot-loader/webpack', + 'babel-loader' + ], }] }, devServer: {
04de99947d1ace467850b9ce26999042e199f8c8
src/components/search_bar.js
src/components/search_bar.js
import React, { Component } from 'react'; class SearchBar extends Component { render() { return <input onChange={this.onInputChange} />; } onInputChange(event) { console.log(event.target.value); } } export default SearchBar;
import React, { Component } from 'react'; class SearchBar extends Component { render() { return <input onChange={event => console.log(event.target.value)} />; } // onInputChange(event) { // console.log(event.target.value); // } } export default SearchBar;
Comment out other function and place function inline to reduce code.
Comment out other function and place function inline to reduce code.
JavaScript
mit
JosephLeon/redux-simple-starter-tutorial,JosephLeon/redux-simple-starter-tutorial
--- +++ @@ -2,12 +2,12 @@ class SearchBar extends Component { render() { - return <input onChange={this.onInputChange} />; + return <input onChange={event => console.log(event.target.value)} />; } - onInputChange(event) { - console.log(event.target.value); - } + // onInputChange(event) { + // console.log(event.target.value); + // } } export default SearchBar;
3610be5301f01c0110d704a6c681c0b6c42d3ce8
src/configure/karma/index.js
src/configure/karma/index.js
export default function configureKarma (config) { const { projectPath, watch, webpackConfig, karmaConfig: userKarmaConfig } = config const defaultKarmaConfig = { basePath: projectPath, frameworks: ['jasmine', 'phantomjs-shim', 'sinon'], browsers: ['PhantomJS'], files: [ 'src/**/*.spec.*', { pattern: 'src/**/*', watched: true, included: false } ], preprocessors: { // add webpack as preprocessor 'src/**/*.spec.*': ['webpack'] }, webpack: webpackConfig, webpackServer: { noInfo: true }, singleRun: !watch, autoWatch: watch } const karmaConfig = { ...defaultKarmaConfig, ...userKarmaConfig } return { ...config, karmaConfig } }
export default function configureKarma (config) { const { projectPath, watch, webpackConfig, karmaConfig: userKarmaConfig } = config const defaultKarmaConfig = { basePath: projectPath, frameworks: ['jasmine', 'phantomjs-shim', 'sinon'], browsers: ['PhantomJS'], reporters: ['mocha'], files: [ 'src/**/*.spec.*', { pattern: 'src/**/*', watched: true, included: false } ], preprocessors: { // add webpack as preprocessor 'src/**/*.spec.*': ['webpack'] }, webpack: webpackConfig, webpackServer: { noInfo: true }, singleRun: !watch, autoWatch: watch } const karmaConfig = { ...defaultKarmaConfig, ...userKarmaConfig } return { ...config, karmaConfig } }
Add mocha reporter to karma configuration
Add mocha reporter to karma configuration
JavaScript
mit
saguijs/sagui,saguijs/sagui
--- +++ @@ -6,6 +6,7 @@ frameworks: ['jasmine', 'phantomjs-shim', 'sinon'], browsers: ['PhantomJS'], + reporters: ['mocha'], files: [ 'src/**/*.spec.*',
f57b1660ee8fb3196bcc61ef059c51b56bb73aa0
karma.conf.js
karma.conf.js
module.exports = function(config) { config.set({ frameworks: ['jquery-3.2.1', 'jasmine-jquery', 'jasmine'], browsers: ['ChromeHeadless'], files: [ 'spec/helpers/tampermonkeyStubs.js', 'public/fateOfAllFools.js', 'spec/helpers/!(tampermonkeyStubs).js', {pattern: 'spec/javascripts/fixtures/*.html', included: false}, 'spec/javascripts/*.spec.js' ] }) };
module.exports = function(config) { config.set({ frameworks: ['jquery-3.2.1', 'jasmine-jquery', 'jasmine'], browsers: ['ChromeHeadless'], files: [ 'spec/helpers/tampermonkeyStubs.js', 'docs/fateOfAllFools.js', 'spec/helpers/!(tampermonkeyStubs).js', {pattern: 'spec/javascripts/fixtures/*.html', included: false}, 'spec/javascripts/*.spec.js' ] }) };
Update path for script source
Update path for script source
JavaScript
mit
rslifka/fate_of_all_fools,rslifka/fate_of_all_fools
--- +++ @@ -4,7 +4,7 @@ browsers: ['ChromeHeadless'], files: [ 'spec/helpers/tampermonkeyStubs.js', - 'public/fateOfAllFools.js', + 'docs/fateOfAllFools.js', 'spec/helpers/!(tampermonkeyStubs).js', {pattern: 'spec/javascripts/fixtures/*.html', included: false}, 'spec/javascripts/*.spec.js'
eb9d6eccaac33ec59d0a2fc92e96af5f7eb3956f
lib/editor.js
lib/editor.js
'use babel' /* @flow */ import {CompositeDisposable} from 'atom' import type {Disposable, TextEditor, TextBuffer, TextEditorGutter} from 'atom' export class Editor { gutter: ?TextEditorGutter; textEditor: TextEditor; subscriptions: CompositeDisposable; constructor(textEditor: TextEditor) { this.textEditor = textEditor this.subscriptions = new CompositeDisposable() const visibility = atom.config.get('linter-ui-default.highlightIssues') if (visibility) { const position = atom.config.get('linter-ui-default.gutterPosition') this.gutter = this.textEditor.addGutter({ name: 'linter-ui-default', priority: position === 'Left' ? -100 : 100 }) } else this.gutter = null } getPath(): string { return this.textEditor.getPath() } getBuffer(): TextBuffer { return this.textEditor.getBuffer() } onDidDestroy(callback: Function): Disposable { const subscription = this.textEditor.onDidDestroy(callback) this.subscriptions.add(subscription) return subscription } dispose() { this.subscriptions.dispose() if (this.gutter) { this.gutter.destroy() } } }
'use babel' /* @flow */ import { CompositeDisposable, Emitter } from 'atom' import type { Disposable, TextEditor, TextBuffer, TextEditorGutter } from 'atom' export class Editor { gutter: ?TextEditorGutter; emitter: Emitter; textEditor: TextEditor; subscriptions: CompositeDisposable; constructor(textEditor: TextEditor) { this.emitter = new Emitter() this.textEditor = textEditor this.subscriptions = new CompositeDisposable() const visibility = atom.config.get('linter-ui-default.highlightIssues') if (visibility) { const position = atom.config.get('linter-ui-default.gutterPosition') this.gutter = this.textEditor.addGutter({ name: 'linter-ui-default', priority: position === 'Left' ? -100 : 100 }) } else this.gutter = null this.subscriptions.add(this.emitter) this.subscriptions.add(textEditor.onDidDestroy(() => { this.dispose() })) } onDidDestroy(callback: Function): Disposable { return this.emitter.on('did-destroy') } dispose() { this.emitter.emit('did-destroy') this.subscriptions.dispose() if (this.gutter) { this.gutter.destroy() } } }
Add an emitter to Editor class
:new: Add an emitter to Editor class
JavaScript
mit
AtomLinter/linter-ui-default,steelbrain/linter-ui-default,steelbrain/linter-ui-default
--- +++ @@ -2,17 +2,20 @@ /* @flow */ -import {CompositeDisposable} from 'atom' -import type {Disposable, TextEditor, TextBuffer, TextEditorGutter} from 'atom' +import { CompositeDisposable, Emitter } from 'atom' +import type { Disposable, TextEditor, TextBuffer, TextEditorGutter } from 'atom' export class Editor { gutter: ?TextEditorGutter; + emitter: Emitter; textEditor: TextEditor; subscriptions: CompositeDisposable; constructor(textEditor: TextEditor) { + this.emitter = new Emitter() this.textEditor = textEditor this.subscriptions = new CompositeDisposable() + const visibility = atom.config.get('linter-ui-default.highlightIssues') if (visibility) { const position = atom.config.get('linter-ui-default.gutterPosition') @@ -22,19 +25,16 @@ }) } else this.gutter = null - } - getPath(): string { - return this.textEditor.getPath() - } - getBuffer(): TextBuffer { - return this.textEditor.getBuffer() + this.subscriptions.add(this.emitter) + this.subscriptions.add(textEditor.onDidDestroy(() => { + this.dispose() + })) } onDidDestroy(callback: Function): Disposable { - const subscription = this.textEditor.onDidDestroy(callback) - this.subscriptions.add(subscription) - return subscription + return this.emitter.on('did-destroy') } dispose() { + this.emitter.emit('did-destroy') this.subscriptions.dispose() if (this.gutter) { this.gutter.destroy()
2d60bf6de2b5f455e5688e0dbfd48239d7342226
test8/testLambda.js
test8/testLambda.js
var java = require("../testHelpers").java; var nodeunit = require("nodeunit"); var util = require("util"); exports['Java8'] = nodeunit.testCase({ "call methods of a class that uses lambda expressions": function(test) { try { var TestLambda = java.import('TestLambda'); var lambda = new TestLambda(); var sum = lambda.testLambdaAdditionSync(23, 42); test.equal(sum, 65); var diff = lambda.testLambdaSubtractionSync(23, 42); test.equal(diff, -19); } catch (err) { var unsupportedVersion = err.toString().match(/Unsupported major.minor version 52.0/) test.ok(unsupportedVersion); if (unsupportedVersion) console.log('JRE 1.8 not available'); else console.error('Java8 test failed with unknown error:', err); } test.done(); } });
var java = require("../testHelpers").java; var nodeunit = require("nodeunit"); var util = require("util"); exports['Java8'] = nodeunit.testCase({ "call methods of a class that uses lambda expressions": function(test) { try { var TestLambda = java.import('TestLambda'); var lambda = new TestLambda(); var sum = lambda.testLambdaAdditionSync(23, 42); test.equal(sum, 65); var diff = lambda.testLambdaSubtractionSync(23, 42); test.equal(diff, -19); } catch (err) { var unsupportedVersion = java.instanceOf(err.cause, 'java.lang.UnsupportedClassVersionError'); test.ok(unsupportedVersion); if (unsupportedVersion) console.log('JRE 1.8 not available'); else console.error('Java8 test failed with unknown error:', err); } test.done(); } });
Use better test for UnsupportedClassVersionError.
Use better test for UnsupportedClassVersionError. The previous test worked correctly with the Oracle JVM but failed with other JVMs. This new test should work correctly on all JVMs.
JavaScript
mit
lantanagroup/node-java,lantanagroup/node-java,sebgod/node-java,sebgod/node-java,RedSeal-co/node-java,joeferner/node-java,joeferner/node-java,lantanagroup/node-java,RedSeal-co/node-java,RedSeal-co/node-java,RedSeal-co/node-java,sebgod/node-java,joeferner/node-java,sebgod/node-java,RedSeal-co/node-java,sebgod/node-java,lantanagroup/node-java,lantanagroup/node-java,joeferner/node-java,joeferner/node-java,RedSeal-co/node-java,sebgod/node-java,joeferner/node-java,lantanagroup/node-java
--- +++ @@ -14,7 +14,7 @@ test.equal(diff, -19); } catch (err) { - var unsupportedVersion = err.toString().match(/Unsupported major.minor version 52.0/) + var unsupportedVersion = java.instanceOf(err.cause, 'java.lang.UnsupportedClassVersionError'); test.ok(unsupportedVersion); if (unsupportedVersion) console.log('JRE 1.8 not available');
f9e17fda75a2c1e2d3f74d9f93b1f40d1fb4c6e6
src/App.js
src/App.js
import React, { Component } from 'react'; import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; import ContentContainer from './patterns/containers/Content'; import ExperimentsHome from './experiments/Index'; import Home from './home/Index'; import HomeHeader from './home/Header'; import TopNav from './patterns/navigation/TopNav'; import './App.css'; class App extends Component { render() { return ( <Router> <div className="App"> <header className="App-header"> <ContentContainer> <Switch> <Route exact path="/" component={HomeHeader} /> <Route component={TopNav} /> </Switch> </ContentContainer> </header> <section className="App-body"> <ContentContainer> <Switch> <Route exact path="/" component={Home} /> <Route path="/experiments/" component={ExperimentsHome} /> </Switch> </ContentContainer> </section> </div> </Router> ); } } export default App;
import React, { Component } from 'react'; import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; import ContentContainer from './patterns/containers/Content'; import ExperimentsHome from './experiments/Index'; import Home from './home/Index'; import HomeHeader from './home/Header'; import NotFound from './NotFound'; import OrganizationHome from './organization/Index'; import TopNav from './patterns/navigation/TopNav'; import './App.css'; class App extends Component { render() { return ( <Router> <div className="App"> <header className="App-header"> <ContentContainer> <Switch> <Route exact path="/" component={HomeHeader} /> <Route component={TopNav} /> </Switch> </ContentContainer> </header> <section className="App-body"> <ContentContainer> <Switch> <Route exact path="/" component={Home} /> <Route path="/experiments/" component={ExperimentsHome} /> <Route path="/organization/" component={OrganizationHome} /> <Route component={NotFound} /> </Switch> </ContentContainer> </section> </div> </Router> ); } } export default App;
Add organization + 404 pages
Add organization + 404 pages
JavaScript
mit
drainpip/shaneis.me,drainpip/shaneis.me
--- +++ @@ -9,6 +9,8 @@ import ExperimentsHome from './experiments/Index'; import Home from './home/Index'; import HomeHeader from './home/Header'; +import NotFound from './NotFound'; +import OrganizationHome from './organization/Index'; import TopNav from './patterns/navigation/TopNav'; import './App.css'; @@ -30,6 +32,8 @@ <Switch> <Route exact path="/" component={Home} /> <Route path="/experiments/" component={ExperimentsHome} /> + <Route path="/organization/" component={OrganizationHome} /> + <Route component={NotFound} /> </Switch> </ContentContainer> </section>