commit
stringlengths
40
40
subject
stringlengths
1
3.25k
old_file
stringlengths
4
311
new_file
stringlengths
4
311
old_contents
stringlengths
0
26.3k
lang
stringclasses
3 values
proba
float64
0
1
diff
stringlengths
0
7.82k
93aadcedf6abaaeea65e0bdddcfedabd4f0bcf5a
Add callback for building metadata
index.js
index.js
var crypto = require('crypto') var stream = require('stream') var fileType = require('file-type') function staticValue (value) { return function (req, file, cb) { cb(null, value) } } function defaultKey (req, file, cb) { crypto.randomBytes(16, function (err, raw) { cb(err, err ? undefined : raw.toString('hex')) }) } function defaultAcl (req, file, cb) { setImmediate(cb, null, 'private') } function defaultContentType (req, file, cb) { setImmediate(cb, null, 'application/octet-stream') } function autoContentType (req, file, cb) { file.stream.once('data', function (firstChunk) { var type = fileType(firstChunk) var mime = (type === null ? 'application/octet-stream' : type.mime) var outStream = new stream.PassThrough() outStream.write(firstChunk) file.stream.pipe(outStream) cb(null, mime, outStream) }) } function collect (storage, req, file, cb) { storage.getBucket(req, file, function (err, bucket) { if (err) return cb(err) storage.getKey(req, file, function (err, key) { if (err) return cb(err) storage.getAcl(req, file, function (err, acl) { if (err) return cb(err) storage.getContentType(req, file, function (err, contentType, replacementStream) { if (err) return cb(err) cb.call(storage, null, { bucket: bucket, key: key, acl: acl, contentType: contentType, replacementStream: replacementStream }) }) }) }) }) } function S3Storage (opts) { switch (typeof opts.s3) { case 'object': this.s3 = opts.s3; break default: throw new TypeError('Expected opts.s3 to be object') } switch (typeof opts.bucket) { case 'function': this.getBucket = opts.bucket; break case 'string': this.getBucket = staticValue(opts.bucket); break case 'undefined': throw new Error('bucket is required') default: throw new TypeError('Expected opts.bucket to be undefined, string or function') } switch (typeof opts.key) { case 'function': this.getKey = opts.key; break case 'undefined': this.getKey = defaultKey; break default: throw new TypeError('Expected opts.key to be undefined or function') } switch (typeof opts.acl) { case 'function': this.getAcl = opts.acl; break case 'string': this.getAcl = staticValue(opts.acl); break case 'undefined': this.getAcl = defaultAcl; break default: throw new TypeError('Expected opts.acl to be undefined, string or function') } switch (typeof opts.contentType) { case 'function': this.getContentType = opts.contentType; break case 'undefined': this.getContentType = defaultContentType; break default: throw new TypeError('Expected opts.contentType to be undefined or function') } } S3Storage.prototype._handleFile = function (req, file, cb) { collect(this, req, file, function (err, opts) { if (err) return cb(err) var currentSize = 0 var upload = this.s3.upload({ Bucket: opts.bucket, Key: opts.key, ACL: opts.acl, ContentType: opts.contentType, Body: (opts.replacementStream || file.stream) }) upload.on('httpUploadProgress', function (ev) { if (ev.total) currentSize = ev.total }) upload.send(function (err, result) { if (err) return cb(err) cb(null, { size: currentSize, bucket: opts.bucket, key: opts.key, acl: opts.acl, contentType: opts.contentType, location: result.Location, etag: result.ETag }) }) }) } S3Storage.prototype._removeFile = function (req, file, cb) { this.s3.deleteObject({ Bucket: file.bucket, Key: file.key }, cb) } module.exports = function (opts) { return new S3Storage(opts) } module.exports.AUTO_CONTENT_TYPE = autoContentType module.exports.DEFAULT_CONTENT_TYPE = defaultContentType
JavaScript
0.000001
@@ -505,24 +505,101 @@ stream')%0A%7D%0A%0A +function defaultMetadata (req, file, cb) %7B%0A setImmediate(cb, null, null)%0A%7D%0A%0A function aut @@ -1228,32 +1228,135 @@ return cb(err)%0A%0A + storage.getMetadata(req, file, function (err, metadata) %7B%0A if (err) return cb(err)%0A%0A storage. @@ -1432,32 +1432,34 @@ am) %7B%0A + + if (err) return @@ -1459,32 +1459,34 @@ return cb(err)%0A%0A + cb.cal @@ -1508,32 +1508,34 @@ , %7B%0A + bucket: bucket,%0A @@ -1542,24 +1542,26 @@ + + key: key,%0A @@ -1554,24 +1554,26 @@ key: key,%0A + @@ -1578,24 +1578,60 @@ acl: acl,%0A + metadata: metadata,%0A @@ -1648,32 +1648,34 @@ e: contentType,%0A + repl @@ -1707,16 +1707,31 @@ tStream%0A + %7D)%0A @@ -3031,24 +3031,275 @@ nction')%0A %7D +%0A%0A switch (typeof opts.metadata) %7B%0A case 'function': this.getMetadata = opts.metadata; break%0A case 'undefined': this.getMetadata = defaultMetadata; break%0A default: throw new TypeError('Expected opts.metadata to be undefined or function')%0A %7D %0A%7D%0A%0AS3Storag @@ -3590,24 +3590,55 @@ ontentType,%0A + Metadata: opts.metadata,%0A Body: @@ -4010,32 +4010,65 @@ ts.contentType,%0A + metadata: opts.metadata,%0A location
016ab1e17dc850be50057443be02a0863c3beb2f
minor prettification
index.js
index.js
var postcss = require('postcss'); var reduceFunctionCall = require('reduce-function-call'); var d3 = require('d3-color'); function justFloat(n) { return parseFloat(n); } function objectToArray(o) { return Object.keys(o).map(function (key) { return o[key]; }); } function colorValuesDefined(hcl) { return !objectToArray(hcl).some(isNaN); } function transformDecl(decl) { var value = decl.value; function reduceHcl(body) { var hclValues = body.split(',').map(justFloat); var hclColor = d3.hcl.apply(null, hclValues); if (!colorValuesDefined(hclColor)) throw decl.error('Unable to parse color: "' + value + '"'); if (!hclColor.displayable()) throw decl.error('HCL color out of range: "' + value + '"'); var hex = hclColor.toString(); if (hclValues.length == 4) { var α = hclValues[3]; var rgb = d3.rgb(hex); return ['rgba(', rgb.r, ', ', rgb.g, ', ', rgb.b, ', ', α, ')'].join(''); } return hex; } decl.value = reduceFunctionCall(value, 'hcl', reduceHcl); } function colorHcl(css) { css.eachDecl(transformDecl); } module.exports = postcss.plugin('postcss-color-hcl', function colorHclPlugin() { return colorHcl; });
JavaScript
0.999999
@@ -85,17 +85,16 @@ call');%0A -%0A var d3 = @@ -603,17 +603,19 @@ lColor)) + %7B %0A - @@ -670,32 +670,42 @@ + value + '%22');%0A + %7D%0A if (!hcl @@ -724,16 +724,18 @@ yable()) + %7B %0A @@ -792,32 +792,43 @@ + value + '%22');%0A + %7D%0A%0A var hex @@ -1044,33 +1044,32 @@ ('');%0A %7D%0A -%0A return h
3011ee97d94c6b98dde64b29abd3d819c1854b71
simplify index.js
index.js
index.js
var electron = require('electron') var path = require('path') var app = electron.app // report crashes to the Electron project require('crash-reporter').start({ // TODO: collect crash reports // productName: 'WebTorrent', // companyName: 'WebTorrent', // submitURL: 'https://webtorrent.io/crash-report', // autoSubmit: true }) // adds debug features like hotkeys for triggering dev tools and reload require('electron-debug')() // prevent window being garbage collected var mainWindow function onClosed () { // dereference the window // for multiple windows store them in an array mainWindow = null } function createMainWindow () { const win = new electron.BrowserWindow({ width: 600, height: 400 }) win.loadURL('file://' + path.join(__dirname, 'index.html')) win.on('closed', onClosed) return win } app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit() } }) app.on('activate', () => { if (!mainWindow) { mainWindow = createMainWindow() } }) app.on('ready', () => { mainWindow = createMainWindow() })
JavaScript
0.999946
@@ -101,33 +101,12 @@ shes - to the Electron project%0A +%0A// requ @@ -139,45 +139,12 @@ t(%7B%0A - // -TODO: collect crash reports%0A // + pro @@ -167,20 +167,20 @@ rrent',%0A - // + company @@ -199,20 +199,20 @@ rrent',%0A - // + submitU @@ -253,20 +253,20 @@ eport',%0A - // + autoSub @@ -275,16 +275,19 @@ t: true%0A +// %7D)%0A%0A// a @@ -445,129 +445,256 @@ ow%0A%0A -function onClosed () %7B%0A // dereference the window%0A // for multiple windows store them in an array%0A mainWindow = null +app.on('ready', function () %7B%0A mainWindow = createMainWindow()%0A%7D)%0A%0Aapp.on('activate', function () %7B%0A if (!mainWindow) mainWindow = createMainWindow()%0A%7D)%0A%0Aapp.on('window-all-closed', function () %7B%0A if (process.platform !== 'darwin') app.quit() %0A%7D +) %0A%0Afu @@ -802,17 +802,16 @@ 00%0A %7D)%0A -%0A win.lo @@ -876,188 +876,31 @@ n.on -('closed', onClosed)%0A%0A return win%0A%7D%0A%0Aapp.on('window-all-closed', () =%3E %7B%0A if (process.platform !== 'darwin') %7B%0A app.quit()%0A %7D%0A%7D)%0A%0Aapp.on('activate', () =%3E %7B%0A if (!mainWindow +ce('closed', function ( ) %7B%0A @@ -920,92 +920,29 @@ w = -createMainWindow() +null %0A -%7D%0A %7D)%0A -%0Aapp.on('ready', () =%3E %7B%0A mainWindow = createMainWindow() + return win %0A%7D -) %0A
95f6c9f9e7ad81a55dc05bd23796764437f1d18e
Fix options mapping for array values
index.js
index.js
'use strict'; var _ = require('lodash'), child_process = require('child_process'), gutil = require('gulp-util'), PluginError = gutil.PluginError, es = require('event-stream'), path = require('path'), fs = require('fs'), PLUGIN_NAME = 'gulp-mspec-runner', MSPEC_CONSOLE = 'mspec-clr4.exe', MSPEC_X86_CONSOLE = 'mspec-x86-clr4.exe', runner; // Main entry point runner = function gulpMSpecRunner(opts) { var stream, files; opts = opts || {}; files = []; stream = es.through(function write(file) { if (_.isUndefined(file)) { fail(this, 'File may not be null.'); } files.push(file); this.emit('data', file); }, function end() { run(this, files, opts); }); return stream; }; runner.getExecutable = function (options) { var executable, consoleRunner; consoleRunner = options.platform === 'x86' ? MSPEC_X86_CONSOLE : MSPEC_CONSOLE; if (!options.executable) { return consoleRunner; } // trim any existing surrounding quotes and then wrap in "" executable = trim(options.executable, '\\s', '"', "'"); return !path.extname(options.executable) ? path.join(executable, consoleRunner) : executable; }; runner.getArguments = function (options, assemblies) { var args = []; if (options.options) { args = args.concat(parseSwitches(options.options)); } args = args.concat(assemblies); return args; }; function parseSwitches(options) { var filtered, switches, switchChar = '--'; switches = _.map(options, function (val, key) { var qualifier; if (typeof val === 'boolean') { if (val) { return (switchChar + key); } return undefined; } if (typeof val === 'string') { qualifier = val.trim().indexOf(' ') > -1 ? '"' : ''; return (switchChar + key + ':' + qualifier + val + qualifier); } if (val instanceof Array) { return (switchChar + key + ':' + val.join(',')); } }); filtered = _.filter(switches, function (val) { return !_.isUndefined(val); }); return filtered; } function fail(stream, msg) { stream.emit('error', new gutil.PluginError(PLUGIN_NAME, msg)); } function end(stream) { stream.emit('end'); } function run(stream, files, options) { var child, args, exe, opts, assemblies, cleanupTempFiles; options.options = options.options || {}; assemblies = files.map(function (file) { return file.path; }); if (assemblies.length === 0) { return fail(stream, 'Some assemblies required.'); } opts = { stdio: [process.stdin, process.stdout, process.stderr, 'pipe'] }; exe = runner.getExecutable(options); args = runner.getArguments(options, assemblies); child = child_process.spawn(exe, args, opts); child.on('error', function (e) { fail(stream, e.code === 'ENOENT' ? 'Unable to find \'' + exe + '\'.' : e.message); }); child.on('close', function (code) { if (cleanupTempFiles) { cleanupTempFiles(); } if (code !== 0) { gutil.log(gutil.colors.red('Machine Specification tests failed.')); fail(stream, 'Machine Specification tests failed.'); } else { gutil.log(gutil.colors.cyan('Machine Specification tests passed')); } return end(stream); }); } function trim() { var args = Array.prototype.slice.call(arguments), source = args[0], replacements = args.slice(1).join(','), regex = new RegExp("^[" + replacements + "]+|[" + replacements + "]+$", "g"); return source.replace(regex, ''); } module.exports = runner;
JavaScript
0.999999
@@ -1843,32 +1843,33 @@ y) %7B%0A%09%09%09%09return +%5B (switchChar + ke @@ -1869,24 +1869,18 @@ ar + key - + ':' + +), val.joi @@ -1885,17 +1885,17 @@ oin(',') -) +%5D ;%0A%09%09%09%7D%0A%09 @@ -1996,24 +1996,34 @@ %09return +_.flatten( filtered ;%0A%09%7D%0A%0Afu @@ -2014,16 +2014,17 @@ filtered +) ;%0A%09%7D%0A%0Afu
eaab25b309d3ebd178e67d5a267428d5f8bdd402
fix java executable name
index.js
index.js
var count = 0; var spawn = require('child_process').spawn; var fs = require('fs'); function parseUml(page) { uml = page.content.match(/^```uml((.*\n)+?)?```$/igm); if (uml) { fs.writeFileSync("./plantuml.uml", uml); return true; } return false; } function execFile(command, args, callback) { var prc = spawn(command, args); prc.on('error', function (err) { console.log('cannot spawn java'); }); prc.stdout.on('data', function(data) { console.log(data.toString()); }); prc.stderr.on('data', function(data) { console.log(data.toString()); }); prc.on('close', function(code) { if ("function" === typeof callback) callback(!!code); }); }; module.exports = { book: { assets: "./book", js: [ "test.js" ], css: [ "test.css" ], html: { "html:start": function() { return "<!-- Start book " + this.options.title + " -->" }, "html:end": function() { return "<!-- End of book " + this.options.title + " -->" }, "head:start": "<!-- head:start -->", "head:end": "<!-- head:end -->", "body:start": "<!-- body:start -->", "body:end": "<!-- body:end -->" } }, hooks: { // For all the hooks, this represent the current generator // This is called before the book is generated "init": function() { console.log("init gitbook-plugin-plantuml!"); }, // This is called after the book generation "finish": function() { console.log("finish gitbook-plugin-plantuml!"); }, // The following hooks are called for each page of the book // and can be used to change page content (html, data or markdown) // Before parsing markdown "page:before": function(page) { // page.path is the path to the file // page.content is a string with the file markdown content var hasUml = parseUml(page); if (!hasUml) { return page; } console.log('processing uml... %j', page.path); var chapterPath = page.path.split('/')[0] var lines = fs.readFileSync('plantuml.uml', 'utf8').split('```,'); //UML debugger; try { execFile('javaa', ['-jar', 'plantuml.jar', '-tsvg', 'plantuml.uml', '-o', chapterPath ]); } catch (e) {}; for (var i = 0; i < lines.length; i++) { if (i == 0) { page.content = page.content.replace(lines[i], '![](plantuml.svg)'); continue; } if (i < 10) { page.content = page.content.replace(lines[i], '![](plantuml_00' + i + '.svg)'); continue; } if (i >= 10 && i < 100) { page.content = page.content.replace(lines[i], '![](plantuml_0' + i + '.svg)'); continue; } if (i >= 100) { page.content = page.content.replace(lines[i], '![](plantuml_' + i + '.svg)'); continue; } }; page.content = page.content.replace(/```/g, ''); // Example: //page.content = "# Title\n" + page.content; return page; }, // Before html generation "page": function(page) { // page.path is the path to the file // page.sections is a list of parsed sections // Example: //page.sections.unshift({type: "normal", content: "<h1>Title</h1>"}) return page; }, // After html generation "page:after": function(page) { // page.path is the path to the file // page.content is a string with the html output // Example: //page.content = "<h1>Title</h1>\n" + page.content; // -> This title will be added before the html tag so not visible in the browser return page; } } };
JavaScript
0.999828
@@ -2458,17 +2458,16 @@ le('java -a ', %5B'-ja
c4d3e056f36ce7cd89607d6c6699ff8a19fe9cd4
Remove redundant console.log.
index.js
index.js
"use strict"; // A Quick var assign = Object.assign || require('./src/utils/object.assign.polyfill'); var commandLineArgumentsResolver = require('./src/resolvers/CommandLineArgumentsResolver'); var environmentVariablesResolver = require('./src/resolvers/EnvironmentVariablesResolver'); var jsonResolver = require('./src/resolvers/JSONResolver'); module.exports.CommandLineArgumentsResolver = commandLineArgumentsResolver; module.exports.EnvironmentVariablesResolver = environmentVariablesResolver; module.exports.JSONResolver = jsonResolver; module.exports.resolve = function() { var args = [].slice.call(arguments); if (args.length === 0) { args = [environmentVariablesResolver, commandLineArgumentsResolver]; } var objects = args.map(function(resolver) { return resolver.call(); }); return assign.apply(null, objects); }; console.log(module.exports.resolve());
JavaScript
0.000002
@@ -852,44 +852,4 @@ ;%0A%7D; -%0A%0Aconsole.log(module.exports.resolve());
737acdbf451d057a2e3bc00e80aaf2e81a0f4f4d
index machinetypeindicator
index.js
index.js
module.exports = { auth: { Account: require('./src/auth/account'), Profile: require('./src/auth/profile'), Role: require('./src/auth/role'), ApiEndpoint: require('./src/auth/api-endpoint') }, master: { Product: require('./src/master/product'), Buyer: require('./src/master/buyer'), Supplier: require('./src/master/supplier'), Uom: require('./src/master/uom'), Division: require('./src/master/division'), Unit: require('./src/master/unit'), Category: require('./src/master/category'), Currency: require('./src/master/currency'), Vat: require('./src/master/vat'), Budget: require('./src/master/budget'), ThreadSpecification: require('./src/master/thread-specification'), Machine:require('./src/master/machine'), LotMachine:require('./src/master/lot-machine'), YarnEquivalentConversion:require('./src/master/yarn-equivalent-conversion'), Uster:require('./src/master/uster'), UsterClassification:require('./src/master/uster-classification'), LampStandard:require('./src/master/lamp-standard'), AccountBank:require('./src/master/account-bank'), Instruction:require('./src/master/instruction'), MachineType:require('./src/master/machine-type'), MachineTypeIndicator:require('./src/master/machine-type-Indicator'), OrderType:require('./src/master/order-type'), ProcessType:require('./src/master/process-type'), ColorType:require('./src/master/color-type'), Step:require('./src/master/step') }, purchasing: { PurchaseOrderItem: require('./src/purchasing/purchase-order-item'), PurchaseOrder: require('./src/purchasing/purchase-order'), PurchaseOrderExternal: require('./src/purchasing/purchase-order-external'), QualityStandard: require('./src/purchasing/quality-standard'), DeliveryOrder: require('./src/purchasing/delivery-order'), DeliveryOrderItem: require('./src/purchasing/delivery-order-item'), DeliveryOrderItemFulfillment: require('./src/purchasing/delivery-order-item-fulfillment'), UnitReceiptNote: require('./src/purchasing/unit-receipt-note'), UnitReceiptNoteItem: require('./src/purchasing/unit-receipt-note-item'), PurchaseRequestItem: require('./src/purchasing/purchase-request-item'), PurchaseRequest: require('./src/purchasing/purchase-request'), UnitPaymentCorrectionNote: require('./src/purchasing/unit-payment-correction-note'), UnitPaymentCorrectionNoteItem: require('./src/purchasing/unit-payment-correction-note-item'), UnitPaymentOrder: require('./src/purchasing/unit-payment-order'), UnitPaymentOrderItem: require('./src/purchasing/unit-payment-order-item'), enum: { PurchaseRequestStatus: require('./src/purchasing/enum/purchase-request-status-enum'), PurchaseOrderStatus: require('./src/purchasing/enum/purchase-order-status-enum') } }, production:{ spinning:{ winding:{ WindingQualitySampling: require('./src/production/spinning/winding/winding-quality-sampling'), WindingProductionOutput: require('./src/production/spinning/winding/winding-production-output') }, DailySpinningProductionReport: require('./src/production/spinning/daily-spinning-production-report') }, finishingPrinting : { ProductionOrder: require('./src/production/finishing-printing/production-order'), ProductionOrderDetail: require('./src/production/finishing-printing/production-order-detail'), SalesContract: require("./src/production/finishing-printing/sales-contract"), DailyOperation: require("./src/production/finishing-printing/daily-operation"), Partition: require("./src/production/finishing-printing/partition"), Kanban: require("./src/production/finishing-printing/kanban") } }, sales:{ SalesContract: require('./src/sales/sales-contract'), SalesContractItem: require('./src/sales/sales-contract-item'), SalesContractSubItem: require('./src/sales/sales-contract-sub-item') }, map: require('./src/map'), validator: require('./src/validator') }
JavaScript
0.000002
@@ -1402,17 +1402,17 @@ ne-type- -I +i ndicator
39e7b05060d0e764ca32d0bed602d145b7d7706a
Use new readable event from midiplex to start pipe
index.js
index.js
var Midiplex = require('midiplex') var midi = require('midi') var through = require('through') var net = require('net') var mp = new Midiplex() function controlServer(controlNum) { return net.createServer(function(stream) { mp.addControllerStream(stream, {maxVal: 127, controller: controlNum}) }) } var serverX = controlServer(1) var serverY = controlServer(2) serverX.listen(9001) serverY.listen(9002) var output = new midi.output() console.log(output.getPortName(0)) output.openPort(0) var midiStream = midi.createWriteStream(output) mp.getReadableStream().pipe(midiStream)
JavaScript
0
@@ -542,16 +542,49 @@ output)%0A +%0Amp.on('readable', function()%7B%0A mp.getRe @@ -615,8 +615,11 @@ Stream)%0A +%7D)%0A
32054b4d31d050df3471d6e4b9afe10105dfad9d
Add "up and running" message to root of app.
index.js
index.js
var express = require('express'); var Fulcrum = require('fulcrum-app'); var models = require('fulcrum-models'); var fulcrumMiddleware = require('connect-fulcrum-webhook'); var Forecast = require('forecast.io'); var app = express(); var form; // Change the variables below to match your app and api keys var formId = '3f45825d-f123-46d0-927c-925db4a63618'; var forecastApiKey = process.env.FORECAST_API_KEY; var fulcrumApiKey = process.env.FULCRUM_API_KEY; var fulcrumWeatherFields = { summary : 'wx_summary', temperature : 'wx_air_temperature', humidity : 'wx_relative_humidity', pressure : 'wx_barometric_pressure' }; var forecast = new Forecast({ APIKey: forecastApiKey }); var fulcrum = new Fulcrum({ api_key: fulcrumApiKey }); fulcrum.forms.find(formId, function (error, response) { if (error) { return console.log('Error fetching form: ', error); } form = new models.Form(response.form); }); function payloadProcessor (payload, done) { if (payload.data.form_id !== formId) { return done(); } var record = new models.Record(payload.data); record.setForm(form); var latitude = record.get('latitude'); var longitude = record.get('longitude'); var clientCreatedAt = record.get('client_created_at'); var date = new Date(clientCreatedAt); var unixTimestamp = date.getTime() / 1000; var forecastOptions = { exclude : 'minutely,hourly,daily,alerts,flags', units : 'si' }; if (!(latitude && longitude)) { console.log('Skipping record because latitude and/or longitude is missing.'); return done(); } forecast.getAtTime(latitude, longitude, unixTimestamp, forecastOptions, function (error, res, data) { if (error) { return done(error); } // The "currently" value represents weather metrics at the time when the // record was created. var currentWeather = data.currently; // Loop through each of the weather fields in our app. If the current reading // from forecast.io contains this metric, update the record with this info. Object.keys(fulcrumWeatherFields).forEach(function (metric) { if (currentWeather[metric]) { record.updateFieldByDataName(fulcrumWeatherFields[metric], currentWeather[metric].toString()); } }); // Update the record to include our freshly populated fields. fulcrum.records.update(record.get('id'), record.toJSON(), function (error, resp) { if (error) { return done(error); } done(); }); }); } var fulcrumConfig = { actions : ['record.create'], processor : payloadProcessor }; app.use('/fulcrum', fulcrumMiddleware(fulcrumConfig)); var port = (process.env.PORT || 5000); app.listen(port, function () { console.log('Listening on port ' + port); });
JavaScript
0
@@ -2711,24 +2711,123 @@ mConfig));%0A%0A +app.get('/', function (req, resp) %7B%0A resp.send('fulcrum-record-weather is up and running!');%0A%7D);%0A%0A var port = (
947a5276bdbcf4eb6ea98e16d89baea282cd0645
fix the merge conflict again whatever
index.js
index.js
var through = require('through'); var browserify = require('browserify'); var chokidar = require('chokidar'); module.exports = watchify; watchify.browserify = browserify; function watchify(opts) { if (!opts) opts = {}; var b = typeof opts.bundle === 'function' ? opts : browserify(opts); var cache = {}; var pkgcache = {}; var watching = {}; var pending = false; var queuedCloses = {}; var queuedDeps = {}; <<<<<<< HEAD var changingDeps = {}; var first = true; ======= var first = true; >>>>>>> accept cache and pkgcache as options if (opts.cache) { cache = opts.cache; delete opts.cache; first = false; } <<<<<<< HEAD ======= >>>>>>> accept cache and pkgcache as options if (opts.pkgcache) { pkgcache = opts.pkgcache; delete opts.pkgcache; } <<<<<<< HEAD ======= >>>>>>> accept cache and pkgcache as options b.on('package', function (file, pkg) { pkgcache[file] = pkg; }); b.on('dep', function(dep) { queuedDeps[dep.id] = dep; }); function addDep (dep) { if (watching[dep.id]) return; watching[dep.id] = true; cache[dep.id] = dep; var watcher = chokidar.watch(dep.id, { persistent: true, ignoreInitial: true, }); watcher.on('error', function(err) { b.emit('error', err); }); watcher.on('change', function(path) { delete cache[dep.id]; queuedCloses[dep.id] = watcher; changingDeps[dep.id] = true // wait for the disk/editor to quiet down first: if (!pending) setTimeout(function () { pending = false; b.emit('update', Object.keys(changingDeps)); changingDeps = {}; }, opts.delay || 300); pending = true; }); } var bundle = b.bundle.bind(b); b.bundle = function (opts_, cb) { if (b._pending) return bundle(opts_, cb); if (typeof opts_ === 'function') { cb = opts_; opts_ = {}; } if (!opts_) opts_ = {}; if (!first) opts_.cache = cache; opts_.includePackage = true; opts_.packageCache = pkgcache; first = false; // we only want to mess with the listeners if the bundle was created // successfully, e.g. on the 'close' event. var outStream = bundle(opts_, cb); outStream.on('close', function() { var depId; for (depId in queuedCloses) { queuedCloses[depId].close(); watching[depId] = false; } queuedCloses = {}; for (depId in queuedDeps) { addDep(queuedDeps[depId]); } queuedDeps = {}; }); return outStream; }; return b; }
JavaScript
0.000001
@@ -434,29 +434,16 @@ s = %7B%7D;%0A -%3C%3C%3C%3C%3C%3C%3C HEAD%0A var @@ -492,84 +492,8 @@ %0A -=======%0A var first = true;%0A%0A%3E%3E%3E%3E%3E%3E%3E accept cache and pkgcache as options%0A @@ -598,79 +598,12 @@ %7D%0A -%3C%3C%3C%3C%3C%3C%3C HEAD%0A %0A=======%0A%0A%3E%3E%3E%3E%3E%3E%3E accept cache and pkgcache as options + %0A @@ -698,79 +698,12 @@ %7D%0A -%3C%3C%3C%3C%3C%3C%3C HEAD%0A %0A=======%0A%0A%3E%3E%3E%3E%3E%3E%3E accept cache and pkgcache as options + %0A
d3529aab61b169e5dda205489113664b8acda057
Fix path
index.js
index.js
'use strict'; const app = require('app'), BW = require('browser-window'), path = require('path'); // Various tasks to do before the app is ready. require('crash-reporter').start(); app.commandLine.appendSwitch('enable-transparent-visuals'); let main = null; app.on('ready', function(){ const screen = require('screen'); let size = screen.getPrimaryDisplay().workAreaSize; main = new BW({ 'width': size.width - 200, 'height': size.height - 200, 'frame': false, 'transparent': true, 'center': true }); main.setTitle('Pheo'); //main.openDevTools(); main.loadUrl('file://' + path.join(__dirname, 'views', 'index.html')); });
JavaScript
0.000018
@@ -643,17 +643,8 @@ ame, - 'views', 'in
02c50eb26ff44dbd4c70507f12f9488758e6210a
save bytes
index.js
index.js
'use strict' module.exports = pixie pixie.compile = compile pixie.render = render function pixie (source, open, close) { open = open || '{{' close = close || '}}' var openLength = open.length var closeLength = close.length var fragments = [] var expressions = [] var first var last for (var i = 0; (first = source.indexOf(open, last)) > -1;) { fragments[i] = source.slice(last, first) last = source.indexOf(close, first += openLength) expressions[i++] = source.slice(first, last) last += closeLength } fragments[i] = source.slice(last) return [fragments, expressions] } function compile (template, data) { var source = '' var fragments = template[0] var expressions = template[1] for (var i = 0, length = expressions.length; i < length; i++) { source += fragments[i] var value = data[expressions[i]] if (value) { source += value } } return source + fragments[i] } function render (source, data, open, close) { return compile(pixie(source, open, close), data) }
JavaScript
0.000002
@@ -867,27 +867,18 @@ -if ( value -) %7B%0A + && ( sour @@ -892,14 +892,9 @@ alue -%0A %7D +) %0A %7D
2dcb00a2be18d2247dc52810b7888a8810eafc31
Add https client support
index.js
index.js
//////////////////////////////////////////////// // // Web Request Handler // //////////////////////////////////////////////// // Add 'startsWith' function to String objects // Reference: http://stackoverflow.com/questions/646628/how-to-check-if-a-string-startswith-another-string if (typeof String.prototype.startsWith != 'function') { String.prototype.startsWith = function (str){ return this.slice(0, str.length) == str; }; } var http = require('http'); var urlParser = require('url'); var qs = require('querystring'); var mainHTML = 'Gotcha!'; var converters = { 'test': function(data, headers) { var url = headers['x-target-url'] || 'http://requestb.in/1msdb5t1'; return { url: url, format: 'json', data: data }; }, 'sns2slack': function(data, headers) { return { url: 'https://hooks.slack.com/services/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', format: 'json', data: { 'text': '' + data['Subject'] + '\n\n' + data['Message'] } }; } }; var formatters = { 'form': { contentType: 'application/x-www-form-urlencoded', stringify: qs.stringify, parse: qs.parse }, 'json': { contentType: 'application/json', stringify: JSON.stringify, parse: JSON.parse } }; var defaultFormatter = { contentType: 'text/plain', stringify: function(data) { return data; }, parse: function(data) { return data; } }; function parseData(text, contentType) { for (var k in formatters) { if (contentType.startsWith(formatters[k].contentType)) { return formatters[k].parse(text); } } return defaultFormatter.parse(text); } function handleQueryRequest(request, response) { if (request.location.pathname == '/') { response.writeHead(200); response.end(mainHTML); }else { response.writeHead(404); response.end(); } } function handleWebhookRequest(request, response) { var converterType = request.location.pathname.substr(1); console.log('CONVERTER_TYPE: ' + converterType); var convert = converters[converterType]; if (!convert) { response.writeHead(404); return response.end(); } var requestBody = ''; request.on('data', function(chunk) { requestBody += chunk; }); request.on('end', function() { console.log('REQUEST_BODY: ' + requestBody); var contentType = request.headers['content-type']; var requestData = parseData(requestBody, contentType); var upstream = convert(requestData, request.headers); if (!upstream) { response.writeHead(400); return response.end(); } console.log('UPSTREAM OPTIONS: ' + JSON.stringify(upstream)); var upstreamRequestOptions = urlParser.parse(upstream.url); upstreamRequestOptions.method = upstream.method || 'POST'; upstreamRequestOptions.headers = upstream.headers || {}; var formatter = formatters[upstream.format] || defaultFormatter; var upstreamRequestBody = formatter.stringify(upstream.data); upstreamRequestOptions.headers['Content-Type'] = formatter.contentType; upstreamRequestOptions.headers['Content-Length'] = (upstreamRequestBody||'').length; var upstreamRequest = http.request(upstreamRequestOptions, function(upstreamResponse) { var upstreamResponseStatusCode = upstreamResponse.statusCode; var upstreamResponseBody = ''; upstreamResponse.setEncoding('utf8'); upstreamResponse.on('data', function(chunk) { upstreamResponseBody += chunk; }); upstreamResponse.on('end', function() { console.log('RESPONSE: [' + upstreamResponseStatusCode + '] ' + upstreamResponseBody); response.writeHead(upstreamResponseStatusCode, { 'Content-Type': upstreamResponse.headers['content-type'] }); response.write(upstreamResponseBody); response.end(); }); }); upstreamRequest.on('error', function handleError(error) { console.log('RESPONSE_ERROR: ' + error.message); response.writeHead(500); response.write(error.message); response.end(); }); upstreamRequest.write(upstreamRequestBody); upstreamRequest.end(); }); } function handleRequest(request, response) { request.location = urlParser.parse(request.url); if (request.method == 'GET') { return handleQueryRequest(request, response); }else if (request.method == 'POST') { return handleWebhookRequest(request, response); }else { response.writeHead(405); response.end(); } } var port = process.env.PORT || 18080; http.createServer(handleRequest).listen(port); console.log('Server running at port ' + port);
JavaScript
0
@@ -457,24 +457,54 @@ re('http');%0A +var https = require('https');%0A var urlParse @@ -3431,32 +3431,41 @@ th;%0A%0A var + client = upstreamRequest @@ -3468,15 +3468,89 @@ uest - +Options.protocol = = +' http +s:' ? https : http;%0A var upstreamRequest = client .req
6a15e08b7618f298ae19b873c9e2eb7d9d9fce9d
update basic package-file testing
test/testPackageFiles.js
test/testPackageFiles.js
/* jshint -W097 */// jshint strict:false /*jslint node: true */ var expect = require('chai').expect; var fs = require('fs'); describe('Test package.json and io-package.json', function() { it('Test package files', function (done) { var fileContentIOPackage = fs.readFileSync(__dirname + '/../io-package.json'); var ioPackage = JSON.parse(fileContentIOPackage); var fileContentNPMPackage = fs.readFileSync(__dirname + '/../package.json'); var npmPackage = JSON.parse(fileContentNPMPackage); expect(ioPackage).to.be.an('object'); expect(npmPackage).to.be.an('object'); expect(ioPackage.common.version).to.exist; expect(npmPackage.version).to.exist; if (!expect(ioPackage.common.version).to.be.equal(npmPackage.version)) { console.log('ERROR: Version numbers in package.json and io-package.json differ!!'); } if (!ioPackage.common.news || !ioPackage.common.news[ioPackage.common.version]) { console.log('WARNING: No news entry for current version exists in io-package.json, no rollback in Admin possible!'); } done(); }); });
JavaScript
0
@@ -11,18 +11,19 @@ -W097 */ -// +%0A/* jshint @@ -34,19 +34,23 @@ ct:false + */ %0A/* + jslint n @@ -62,16 +62,40 @@ true */%0A +/* jshint expr: true */%0A var expe @@ -1158,32 +1158,738 @@ !');%0A %7D%0A%0A + expect(ioPackage.common.authors).to.exist;%0A if (ioPackage.common.name.indexOf('template') !== 0) %7B%0A if (Array.isArray(ioPackage.common.authors)) %7B%0A expect(ioPackage.common.authors.length).to.not.be.equal(0);%0A if (ioPackage.common.authors.length === 1) %7B%0A expect(ioPackage.common.authors%5B0%5D).to.not.be.equal('my Name %3Cmy@email.com%3E');%0A %7D%0A %7D%0A else %7B%0A expect(ioPackage.common.authors).to.not.be.equal('my Name %3Cmy@email.com%3E');%0A %7D%0A %7D%0A else %7B%0A console.log('Testing for set authors field in io-package skipped because template adapter');%0A %7D%0A done();%0A
0e67be76485d7e836b3d7ccfa61f9a3f02dc36a6
support node_modules/.bin
index.js
index.js
var hackfile = require('hackfile') var fs = require('fs') module.exports = function(src) { var tree = hackfile(src.toString().replace(/(\s+)run (.+)\n/g, '$1run\n$1 $2\n').replace(/#[^\n]+/g, '')) // haxx var tick = 1 var backgrounds = [] var fns = [] var visit = function(line) { var cmd = line[0] var params = line[1] switch (cmd) { case 'map': var cmds = [] for (var i = 0; i < params.length; i++) { var p = params[i] cmds.push(i && i < params.length-1 ? 'tee >('+p+' >&2)' : p+(i ? ' >&2' : '')) } return '('+cmds.join(' | ')+') 2>&1' case 'reduce': return params.join('\n')+'\n' case 'run': return params.join('\n')+'\n' case 'pipe': return params.join(' | ')+'\n' case 'background': var str = '' var pids = [] for (var i = 0; i < params.length; i++) { var p = params[i] var pid = 'DATSCRIPT_PID'+(tick++) pids.push(pid) str += p+' &\n'+pid+'=$!\n' } for (var i = 0; i < pids.length; i++) { backgrounds.push('kill $'+pids[i]+'\nwait $'+pids[i]+'\n') } return str case 'fork': var str = '' var pids = [] for (var i = 0; i < params.length; i++) { var p = params[i] var pid = 'DATSCRIPT_PID'+(tick++) pids.push(pid) str += p+' &\n'+pid+'=$!\n' } for (var i = 0; i < pids.length; i++) { str += 'wait $'+pids[i]+'\n' } return str } fns.push(cmd+'() {\n'+params.map(visit).join('')+'}\n') return '' } var output = tree.map(visit).join('') return '#!/bin/bash\n'+fns.join('')+'\n'+output+'\n'+backgrounds.join('') }
JavaScript
0.000001
@@ -1663,16 +1663,51 @@ n/bash%5Cn +export PATH=node_modules/.bin:$PATH '+fns.jo
493c7762f5b3922a1cb90813933831ae8fd5e7a3
update basic package-file testing
test/testPackageFiles.js
test/testPackageFiles.js
/* jshint -W097 */ /* jshint strict:false */ /* jslint node: true */ /* jshint expr: true */ var expect = require('chai').expect; var fs = require('fs'); describe('Test package.json and io-package.json', function() { it('Test package files', function (done) { console.log(); var fileContentIOPackage = fs.readFileSync(__dirname + '/../io-package.json', 'utf8'); var ioPackage = JSON.parse(fileContentIOPackage); var fileContentNPMPackage = fs.readFileSync(__dirname + '/../package.json', 'utf8'); var npmPackage = JSON.parse(fileContentNPMPackage); expect(ioPackage).to.be.an('object'); expect(npmPackage).to.be.an('object'); expect(ioPackage.common.version, 'ERROR: Version number in io-package.json needs to exist').to.exist; expect(npmPackage.version, 'ERROR: Version number in package.json needs to exist').to.exist; expect(ioPackage.common.version, 'ERROR: Version numbers in package.json and io-package.json needs to match').to.be.equal(npmPackage.version); if (!ioPackage.common.news || !ioPackage.common.news[ioPackage.common.version]) { console.log('WARNING: No news entry for current version exists in io-package.json, no rollback in Admin possible!'); console.log(); } expect(npmPackage.author, 'ERROR: Author in package.json needs to exist').to.exist; expect(ioPackage.common.authors, 'ERROR: Authors in io-package.json needs to exist').to.exist; if (ioPackage.common.name.indexOf('template') !== 0) { if (Array.isArray(ioPackage.common.authors)) { expect(ioPackage.common.authors.length, 'ERROR: Author in io-package.json needs to be set').to.not.be.equal(0); if (ioPackage.common.authors.length === 1) { expect(ioPackage.common.authors[0], 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <my@email.com>'); } } else { expect(ioPackage.common.authors, 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <my@email.com>'); } } else { console.log('WARNING: Testing for set authors field in io-package skipped because template adapter'); console.log(); } expect(fs.existsSync(__dirname + '/../README.md'), 'ERROR: README.md needs to exist! Please create one with description, detail information and changelog. English is mandatory.').to.be.true; expect(fs.existsSync(__dirname + '/../LICENSE'), 'ERROR: LICENSE needs to exist! Please create one.').to.be.true; if (!ioPackage.common.titleLang || typeof ioPackage.common.titleLang !== 'object') { console.log('WARNING: titleLang is not existing in io-package.json. Please add'); console.log(); } if ( ioPackage.common.title.indexOf('iobroker') !== -1 || ioPackage.common.title.indexOf('ioBroker') !== -1 || ioPackage.common.title.indexOf('adapter') !== -1 || ioPackage.common.title.indexOf('Adapter') !== -1 ) { console.log('WARNING: title contains Adapter or ioBroker. It is clear anyway, that it is adapter for ioBroker.'); console.log(); } if (ioPackage.common.name.indexOf('vis-') !== 0) { if (!ioPackage.common.materialize || !fs.existsSync(__dirname + '/../admin/index_m.html') || !fs.existsSync(__dirname + '/../gulpfile.js')) { console.log('WARNING: Admin3 support is missing! Please add it'); console.log(); } if (ioPackage.common.materialize) { expect(fs.existsSync(__dirname + '/../admin/index_m.html'), 'Admin3 support is enabled in io-package.json, but index_m.html is missing!').to.be.true; } } var licenseFileExists = fs.existsSync(__dirname + '/../LICENSE'); var fileContentReadme = fs.readFileSync(__dirname + '/../README.md', 'utf8'); if (fileContentReadme.indexOf('## Changelog') === -1) { console.log('Warning: The README.md should have a section ## Changelog'); console.log(); } expect((licenseFileExists || fileContentReadme.indexOf('## License') !== -1), 'A LICENSE must exist as LICENSE file or as part of the README.md').to.be.true; if (!licenseFileExists) { console.log('Warning: The License should also exist as LICENSE file'); console.log(); } if (fileContentReadme.indexOf('## License') === -1) { console.log('Warning: The README.md should also have a section ## License to be shown in Admin3'); console.log(); } done(); }); });
JavaScript
0
@@ -2574,130 +2574,8 @@ ue;%0A - expect(fs.existsSync(__dirname + '/../LICENSE'), 'ERROR: LICENSE needs to exist! Please create one.').to.be.true;%0A
c302d96b9c4027b15bf769d05c3f6e7c226082c2
Refactor the transform into smaller pieces
index.js
index.js
var transformTools = require('browserify-transform-tools'); var sourceMap = require('convert-source-map'); var extend = require('underscore').extend; var defaults = { sourceMap: false, readableNames: true, modules: [], }; var useMacros = /"use macros"|'use macros'/; var options = { includeExtensions: [".js", ".sjs"] }; module.exports = transformTools.makeStringTransform( "sweetjsify", options, function (content, transformOptions, done) { var filename = transformOptions.file; var config = transformOptions.config || {}; var modules = config.modules || []; var sweet = require('sweet.js'); if(!useMacros.test(content)) { return done(null, content); } try { modules.forEach(function(mod) { sweet.loadMacro(mod); }); } catch(e) { return done('Error while loading modules:' + filename + '\n' + e); } var opts = extend({filename: filename}, defaults, config); var result; delete opts.modules; try { result = sweet.compile(content, opts); } catch(e) { return done('Error in file: ' + filename + '\n' + e); } if(config.sourceMap) { var map = sourceMap.fromJSON(result.sourceMap); map.sourcemap.sourcesContent = [buffer]; done(null, result.code + '\n' + map.toComment()); } else { done(null, result.code); } } );
JavaScript
0.998569
@@ -104,22 +104,17 @@ ');%0Avar -extend +_ = requi @@ -133,15 +133,8 @@ re') -.extend ;%0A%0Av @@ -166,12 +166,11 @@ ap: -fals +tru e,%0A @@ -260,446 +260,162 @@ /;%0A%0A -var options = %7B%0A includeExtensions: %5B%22.js%22, %22.sjs%22%5D%0A%7D;%0A%0Amodule.exports = transformTools.makeStringTransform(%0A %22sweetjsify%22,%0A options,%0A function (content, transformOptions, done) %7B%0A var filename = transformOptions.file;%0A var config = transformOptions.config %7C%7C %7B%7D;%0A var modules = config.modules %7C%7C %5B%5D;%0A var sweet = require('sweet.js');%0A%0A if(!useMacros.test(content)) %7B%0A return done(null, content);%0A %7D%0A%0A +function fileUsesMacros(content) %7B%0A return useMacros.test(content);%0A%7D%0A%0Afunction loadModules(modules, done) %7B%0A var sweet = require('sweet.js');%0A%0A try %7B%0A @@ -406,26 +406,24 @@ );%0A%0A try %7B%0A - modules. @@ -452,18 +452,16 @@ %7B%0A - sweet.lo @@ -478,18 +478,16 @@ d);%0A - %7D);%0A @@ -482,18 +482,16 @@ %7D);%0A - %7D catc @@ -497,33 +497,24 @@ ch(e) %7B%0A - return done('Error @@ -539,149 +539,136 @@ les: -' + filename + '%5Cn' + e);%0A %7D%0A%0A var opts = extend(%7Bfilename: filename%7D, defaults, config);%0A var result;%0A delete opts. +%5Cn' + e);%0A return;%0A %7D%0A%0A return sweet;%0A%7D%0A%0Afunction compile(sweet, config, done) %7B%0A var opts = _.omit(config, ' modules +') ;%0A - try @@ -677,18 +677,14 @@ - result = +return swe @@ -694,16 +694,23 @@ compile( +config. content, @@ -717,18 +717,16 @@ opts);%0A - %7D catc @@ -736,25 +736,16 @@ ) %7B%0A - return done('Er @@ -761,16 +761,23 @@ le: ' + +config. filename @@ -792,23 +792,67 @@ + e);%0A - %7D%0A%0A +%7D%0A%7D%0A%0Afunction addSourceMap(result, config, done) %7B%0A if(con @@ -864,26 +864,24 @@ ourceMap) %7B%0A - var map @@ -924,18 +924,16 @@ p);%0A - map.sour @@ -960,19 +960,25 @@ = %5B -buffer +config.content %5D;%0A - @@ -1033,59 +1033,650 @@ ;%0A - %7D else %7B%0A done(null, result.code);%0A +%7D else %7B%0A done(null, result.code);%0A %7D%0A%7D%0A%0Afunction sweetjsify(content, transformOptions, done) %7B%0A var opts = _.extend(%7Bfilename: transformOptions.file, content: content%7D,%0A defaults,%0A transformOptions.config);%0A%0A if(!fileUsesMacros(content)) %7B%0A return done(null, content);%0A %7D%0A%0A var sweet = loadModules(opts.modules, done);%0A if(!sweet) %7B return; %7D%0A%0A var result = compile(sweet, opts, done);%0A if(!result) %7B return; %7D%0A +%0A -%7D%0A +addSourceMap(result, opts, done);%0A%7D%0A%0Avar options = %7B includeExtensions: %5B%22.js%22, %22.sjs%22%5D %7D;%0Amodule.exports = transformTools.makeStringTransform(%22sweetjsify%22, options, sweetjsify );%0A
45337604f15086a04c2007715d41231747accc2d
Add "@" to start of single line .cmd files
index.js
index.js
// On windows, create a .cmd file. // Read the #! in the file to see what it uses. The vast majority // of the time, this will be either: // "#!/usr/bin/env <prog> <args...>" // or: // "#!<prog> <args...>" // // Write a binroot/pkg.bin + ".cmd" file that has this line in it: // @<prog> <args...> %~dp0<target> %* module.exports = cmdShim cmdShim.ifExists = cmdShimIfExists var fs = require("graceful-fs") var mkdir = require("mkdirp") , path = require("path") , shebangExpr = /^#\!\s*(?:\/usr\/bin\/env)?\s*([^ \t]+)(.*)$/ function cmdShimIfExists (from, to, cb) { fs.stat(from, function (er) { if (er) return cb() cmdShim(from, to, cb) }) } // Try to unlink, but ignore errors. // Any problems will surface later. function rm (path, cb) { fs.unlink(path, function(er) { cb() }) } function cmdShim (from, to, cb) { fs.stat(from, function (er, stat) { if (er) return cb(er) cmdShim_(from, to, cb) }) } function cmdShim_ (from, to, cb) { var then = times(2, next, cb) rm(to, then) rm(to + ".cmd", then) function next(er) { writeShim(from, to, cb) } } function writeShim (from, to, cb) { // make a cmd file and a sh script // First, check if the bin is a #! of some sort. // If not, then assume it's something that'll be compiled, or some other // sort of script, and just call it directly. mkdir(path.dirname(to), function (er) { if (er) return cb(er) fs.readFile(from, "utf8", function (er, data) { if (er) return writeShim_(from, to, null, null, cb) var firstLine = data.trim().split(/\r*\n/)[0] , shebang = firstLine.match(shebangExpr) if (!shebang) return writeShim_(from, to, null, null, cb) var prog = shebang[1] , args = shebang[2] || "" return writeShim_(from, to, prog, args, cb) }) }) } function writeShim_ (from, to, prog, args, cb) { var shTarget = path.relative(path.dirname(to), from) , target = shTarget.split("/").join("\\") , longProg , shProg = prog && prog.split("\\").join("/") , shLongProg shTarget = shTarget.split("\\").join("/") args = args || "" if (!prog) { prog = "\"%~dp0\\" + target + "\"" shProg = "\"$basedir/" + shTarget + "\"" args = "" target = "" shTarget = "" } else { longProg = "\"%~dp0\\" + prog + ".exe\"" shLongProg = "\"$basedir/" + prog + "\"" target = "\"%~dp0\\" + target + "\"" shTarget = "\"$basedir/" + shTarget + "\"" } // @IF EXIST "%~dp0\node.exe" ( // "%~dp0\node.exe" "%~dp0\.\node_modules\npm\bin\npm-cli.js" %* // ) ELSE ( // SETLOCAL // SET PATHEXT=%PATHEXT:;.JS;=;% // node "%~dp0\.\node_modules\npm\bin\npm-cli.js" %* // ) var cmd if (longProg) { cmd = "@IF EXIST " + longProg + " (\r\n" + " " + longProg + " " + args + " " + target + " %*\r\n" + ") ELSE (\r\n" + " @SETLOCAL\r\n" + " @SET PATHEXT=%PATHEXT:;.JS;=;%\r\n" + " " + prog + " " + args + " " + target + " %*\r\n" + ")" } else { cmd = prog + " " + args + " " + target + " %*\r\n" } // #!/bin/sh // basedir=`dirname "$0"` // // case `uname` in // *CYGWIN*) basedir=`cygpath -w "$basedir"`;; // esac // // if [ -x "$basedir/node.exe" ]; then // "$basedir/node.exe" "$basedir/node_modules/npm/bin/npm-cli.js" "$@" // ret=$? // else // node "$basedir/node_modules/npm/bin/npm-cli.js" "$@" // ret=$? // fi // exit $ret var sh = "#!/bin/sh\n" if (shLongProg) { sh = sh + "basedir=`dirname \"$0\"`\n" + "\n" + "case `uname` in\n" + " *CYGWIN*) basedir=`cygpath -w \"$basedir\"`;;\n" + "esac\n" + "\n" sh = sh + "if [ -x "+shLongProg+" ]; then\n" + " " + shLongProg + " " + args + " " + shTarget + " \"$@\"\n" + " ret=$?\n" + "else \n" + " " + shProg + " " + args + " " + shTarget + " \"$@\"\n" + " ret=$?\n" + "fi\n" + "exit $ret\n" } else { sh = shProg + " " + args + " " + shTarget + " \"$@\"\n" + "exit $?\n" } var then = times(2, next, cb) fs.writeFile(to + ".cmd", cmd, "utf8", then) fs.writeFile(to, sh, "utf8", then) function next () { chmodShim(to, cb) } } function chmodShim (to, cb) { var then = times(2, cb, cb) fs.chmod(to, 0755, then) fs.chmod(to + ".cmd", 0755, then) } function times(n, ok, cb) { var errState = null return function(er) { if (!errState) { if (er) cb(errState = er) else if (--n === 0) ok() } } }
JavaScript
0
@@ -3041,16 +3041,22 @@ cmd = + %22@%22 + prog +
e02a479f4d8e6e511d9b67238a00571acdf2838a
remove psvr
index.js
index.js
"use strict"; const PORT = 4422; const path = require('path'); //to control iRobot create2 const SerialPort = require("serialport"); const fs = require("fs"); const Repl = require("repl"); const Devices = require("./src/detect"); const express = require('express'); const app = express(); const http = require('http').Server(app); const io = require('socket.io')(http); const Roomba = require("./src/roombaController.js"); Devices.getArduinoComName() .then( port => { board = new five.Board({ "repl": false, port }); board.on("ready", boardHandler); board.on("fail", event => { console.error(event); }); }); app.get('/', (req, res) => { res.sendFile(path.join(__dirname, 'client/index.html')); }); app.use("/", express.static(path.join(__dirname, 'client'))); app.use("/assets", express.static(path.join(__dirname, 'client/assets'))); http.listen(PORT, function(){ console.log('Listen on ',PORT); }); let pixel = require("node-pixel"); let five = require("johnny-five"); var strip = null; var numPixels = 12; var fps = 30; // how many frames per second do you want to try? //Connect to PSVR var PSVR = require("psvr"); var device = new PSVR(); let yaw = 90; let servo_yaw = 90; function boardHandler() { servo_yaw = new five.Servo({ pin : 6, range: [30, 150], startAt: 90 }); console.log("Board ready, lets add light"); strip = new pixel.Strip({ board: this, controller: "FIRMATA", strips: [ {pin: 3, length: 12}, {pin: 7, length: 8},] }); strip.on("ready", function() { console.log("Strip ready"); var colors = ["red", "green", "blue"]; var current_colors = [0,1,2]; var pixel_list = [0,1,2]; var blinker = setInterval(function() { strip.color("#000"); // blanks it out for (var i=0; i< pixel_list.length; i++) { if (++pixel_list[i] >= strip.stripLength()) { pixel_list[i] = 0; if (++current_colors[i] >= colors.length) current_colors[i] = 0; } strip.pixel(pixel_list[i]).color(colors[current_colors[i]]); } strip.show(); }, 1000/fps); }); strip.on("error", function(err) { console.log(err); process.exit(); }); device.on("data", function(data) { yaw = Math.floor(data.yaw * 0.00002) + 90; if( yaw < 0 ) { yaw = 10; } else if ( yaw > 180) { yaw = 170; } console.log(yaw); servo_yaw.to(yaw); }); }; Devices.getRoombaComName() .then( port => { const roomba = new Roomba(port); io.of('/irobotCommand').on('connection', roomba.handler.bind(roomba)); }); io.sockets.on('connection', function(socket) { console.log("hello socket"); socket.on('servo', function(deg) { if (deg[0] !== null && deg[0] !== undefined) servo_yaw.to(180 - deg[0]); }) });
JavaScript
0.000014
@@ -1144,61 +1144,8 @@ SVR%0A -var PSVR = require(%22psvr%22);%0Avar device = new PSVR();%0A let @@ -2165,232 +2165,8 @@ );%0A%0A - device.on(%22data%22, function(data) %7B%0A yaw = Math.floor(data.yaw * 0.00002) + 90;%0A%0A if( yaw %3C 0 ) %7B%0A yaw = 10;%0A %7D else if ( yaw %3E 180) %7B%0A yaw = 170;%0A %7D%0A console.log(yaw);%0A servo_yaw.to(yaw);%0A %7D);%0A %7D;%0A%0A
e3c51b51d660d9988b913c595ab7343dcf568b5b
fix gpio paths
index.js
index.js
"use strict" const fs = require("fs"); const path = require("path"); const base = "/sys/class/gpio/" exports.activate = (gpio) => { fs.createWriteStream(base + 'export').end(gpio.toString()) }; exports.deactivate= (gpio) => { fs.createWriteStream(base + 'unexport').end(gpio.toString()) }; exports.read = (gpio) => { return fs.createReadStream(path.resolve(base + gpio)); }; exports.write = (gpio) => { return fs.createWriteStream(path.resolve(base + gpio)); };
JavaScript
0.000004
@@ -93,16 +93,20 @@ ss/gpio/ +gpio %22%0A%0Aexpor @@ -378,24 +378,35 @@ (base + gpio + + %22/value%22 ));%0A%7D;%0A%0Aexpo @@ -485,15 +485,26 @@ e + gpio + + %22/value%22 ));%0A%7D;%0A
72660cc82266f9c39eee9a885865035a17273bfe
use _.extend on options in toc.add() method
index.js
index.js
/** * marked-toc <https://github.com/jonschlinkert/marked-toc> * * Copyright (c) 2014 Jon Schlinkert, contributors. * Licensed under the MIT license. */ 'use strict'; var file = require('fs-utils'); var marked = require('marked'); var chalk = require('chalk'); var matter = require('gray-matter'); var template = require('template'); var slugify = require('uslug'); var _ = require('lodash'); // Local libs var utils = require('./lib/utils'); // Default template to use for TOC var defaultTemplate = '<%= depth %><%= bullet %>[<%= heading %>](#<%= url %>)\n'; var generate = function(str, options) { var opts = _.extend({ firsth1: false, blacklist: true, omit: [], maxDepth: 3 }, options); var toc = ''; var tokens = marked.lexer(str); var tocArray = []; // Remove the very first h1, true by default if(opts.firsth1 === false) { tokens.shift(); } // Do any h1's still exist? var h1 = _.any(tokens, {depth: 1}); tokens.filter(function (token) { // Filter out everything but headings if (token.type !== 'heading' || token.type === 'code') { return false; } // Since we removed the first h1, we'll check to see if other h1's // exist. If none exist, then we unindent the rest of the TOC if(!h1) { token.depth = token.depth - 1; } // Store original text and create an id for linking token.heading = opts.clean ? utils.clean(token.text, opts) : token.text; // Create a "slugified" id for linking token.id = slugify(token.text, {allowedChars: '-'} || opts); // Omit headings with these strings var omissions = ['Table of Contents', 'TOC', 'TABLE OF CONTENTS']; var omit = _.union([], opts.omit, omissions); if (utils.isMatch(omit, token.heading)) { return; } return true; }).forEach(function (h) { if(h.depth > opts.maxDepth) { return; } var data = _.extend({}, opts.data, { depth : new Array((h.depth - 1) * 2 + 1).join(' '), bullet : opts.bullet ? opts.bullet : '* ', heading: h.heading, url : h.id }); tocArray.push(data); var tmpl = opts.template || defaultTemplate; toc += template(tmpl, data); }); return { data: tocArray, toc: opts.clean ? utils.clean(toc, opts) : toc }; }; /** * toc */ var toc = module.exports = function(str, options) { return generate(str, options).toc; }; toc.raw = function(str, options) { return generate(str, options); }; toc.insert = function(str, options) { var start = '<!-- toc -->\n'; var stop = '\n<!-- toc stop -->'; var strip = /<!-- toc -->[\s\S]+<!-- toc stop -->/; var content = matter(str).content; var front = matter.extend(str); // Remove the existing TOC content = content.replace(strip, start); // Generate the new TOC var table = start + toc(content, options) + stop; return front + content.replace(start, table); }; // Read a file and add a TOC, dest is optional. toc.add = function(src, dest, options) { var content = file.readFileSync(src); if (utils.isDest(dest)) {options = dest; dest = src;} file.writeFileSync(dest, toc.insert(content, {clean: ['docs']})); console.log(chalk.green('>> Success:'), dest); };
JavaScript
0.000003
@@ -3031,24 +3031,74 @@ options) %7B%0A + var opts = _.extend(%7Bclean: %5B'docs'%5D%7D, options)%0A var conten @@ -3228,33 +3228,20 @@ ontent, -%7Bclean: %5B'docs'%5D%7D +opts ));%0A co @@ -3283,12 +3283,13 @@ ), dest);%0A%7D; +%0A
2e3c812965e7f8f95cb8e4738b52c80b8dbc80b2
fix #623
index.js
index.js
import Swiper from './src/' module.exports = Swiper
JavaScript
0
@@ -25,28 +25,255 @@ c/'%0A -module.exports = Swiper +/**%0A * Resolve ES6 and CommonJS compatibility issues%0A * 1. CommonJS code%0A * const Swiper = require('react-native-swiper');%0A * 2. ES6 code%0A * import Swiper from 'react-native-swiper';%0A */%0Amodule.exports = Swiper;%0Amodule.exports.default = Swiper; %0A
7ca8e8b82b453fb3e071d108551f6da2a6469890
support opt.maxListeners
index.js
index.js
var CachedEmitter = require("cached-events") , slice = Array.prototype.slice module.exports = CachedOperation function CachedOperation(f, getKey) { var keys = {} , emitter = CachedEmitter() getKey = getKey || defaultGetKey return operation function operation() { var args = slice.call(arguments) , cb = args.pop() , key = getKey(args) args.push(intercept) if (!keys[key]) { keys[key] = true f.apply(null, args) } emitter.on(key, cb) function intercept() { var results = slice.call(arguments) results.unshift(key) emitter.emit.apply(emitter, results) } } } function defaultGetKey(args) { return args[0] }
JavaScript
0
@@ -137,22 +137,20 @@ tion(f, -getKey +opts ) %7B%0A @@ -204,16 +204,43 @@ ()%0A%0A +opts = opts %7C%7C %7B%7D%0A%0A var getKey = @@ -236,24 +236,29 @@ ar getKey = +opts. getKey %7C%7C de @@ -270,16 +270,103 @@ GetKey%0A%0A + if (opts.maxListeners) %7B%0A emitter.setMaxListeners(opts.maxListeners)%0A %7D%0A%0A retu
d5fd035b30fbebd7c30348250264e05f150617f0
Add tokenizeMethod as default
index.js
index.js
var _ = require( "lodash" ); var WORDS = "a, about, above, across, after, again, against, all, almost, alone, along, already, also, although, always, among, an, and, another, any, anybody, anyone, anything, anywhere, are, area, areas, around, as, ask, asked, asking, asks, at, away, b, back, backed, backing, backs, be, became, because, become, becomes, been, before, began, behind, being, beings, best, better, between, big, both, but, by, c, came, can, cannot, case, cases, certain, certainly, clear, clearly, come, could, d, did, differ, different, differently, do, does, done, down, down, downed, downing, downs, during, e, each, early, either, end, ended, ending, ends, enough, even, evenly, ever, every, everybody, everyone, everything, everywhere, f, face, faces, fact, facts, far, felt, few, find, finds, first, for, four, from, full, fully, further, furthered, furthering, furthers, g, gave, general, generally, get, gets, give, given, gives, go, going, good, goods, got, great, greater, greatest, group, grouped, grouping, groups, h, had, has, have, having, he, her, here, herself, high, high, high, higher, highest, him, himself, his, how, however, i, if, important, in, interest, interested, interesting, interests, into, is, it, its, itself, j, just, k, keep, keeps, kind, knew, know, known, knows, l, large, largely, last, later, latest, least, less, let, lets, like, likely, long, longer, longest, m, made, make, making, man, many, may, me, member, members, men, might, more, most, mostly, mr, mrs, much, must, my, myself, n, necessary, need, needed, needing, needs, never, new, new, newer, newest, next, no, nobody, non, noone, not, nothing, now, nowhere, number, numbers, o, of, off, often, old, older, oldest, on, once, one, only, open, opened, opening, opens, or, order, ordered, ordering, orders, other, others, our, out, over, p, part, parted, parting, parts, per, perhaps, place, places, point, pointed, pointing, points, possible, present, presented, presenting, presents, problem, problems, put, puts, q, quite, r, rather, really, right, right, room, rooms, s, said, same, saw, say, says, second, seconds, see, seem, seemed, seeming, seems, sees, several, shall, she, should, show, showed, showing, shows, side, sides, since, small, smaller, smallest, so, some, somebody, someone, something, somewhere, state, states, still, still, such, sure, t, take, taken, than, that, the, their, them, then, there, therefore, these, they, thing, things, think, thinks, this, those, though, thought, thoughts, three, through, thus, to, today, together, too, took, toward, turn, turned, turning, turns, two, u, under, until, up, upon, us, use, used, uses, v, very, w, want, wanted, wanting, wants, was, way, ways, we, well, wells, went, were, what, when, where, whether, which, while, who, whole, whose, why, will, with, within, without, work, worked, working, works, would, x, y, year, years, yet, you, young, younger, youngest, your, yours, z" var stopWords = WORDS.split( ", " ); function ScuttleZanetti( options ) { this.options = _.defaults( options, { tokenizePattern: /\W+/, stopWords: stopWords } ); } ScuttleZanetti.prototype.removeStopWords = function( s ) { var tokens = this.tokenize( s.toLowerCase( ) ); return _.filter( tokens, function( w ) { return !~this.options.stopWords.indexOf( w ); }.bind( this ) ).join( " " ); }; ScuttleZanetti.prototype.tokenize = function( s ) { var results = s.split(this.options.tokenizePattern); return _.without(results,'',' '); }; exports.api = ScuttleZanetti; exports.stopWords = stopWords;
JavaScript
0.000001
@@ -3091,13 +3091,114 @@ rn: -/%5CW+/ +undefined, %0A tokenizeMethod: function( s ) %7B%0A return s.replace(/%5B%5E%5Cw%5Cs-%5D/, %22%22).split( %22 %22 );%0A %7D ,%0A @@ -3540,49 +3540,155 @@ ults - = s.split(this.options.tokenizePattern); +;%0A if( this.options.tokenizePattern )%0A results = s.split(this.options.tokenizePattern);%0A else%0A results = this.options.tokenizeMethod( s );%0A %0A r
c6f4f200b60fb288f210610bc137577816369dfc
Use correct port for HTTPS
index.js
index.js
var http = module.exports; var EventEmitter = require('events').EventEmitter; var Request = require('./lib/request'); http.request = function (params, cb) { if (!params) params = {}; if (!params.host && !params.port) { params.port = parseInt(window.location.port, 10); } if (!params.host) params.host = window.location.hostname; if (!params.port) params.port = 80; if (!params.scheme) params.scheme = window.location.protocol.split(':')[0]; var req = new Request(new xhrHttp, params); if (cb) req.on('response', cb); return req; }; http.get = function (params, cb) { params.method = 'GET'; var req = http.request(params, cb); req.end(); return req; }; http.Agent = function () {}; http.Agent.defaultMaxSockets = 4; var xhrHttp = (function () { if (typeof window === 'undefined') { throw new Error('no window object present'); } else if (window.XMLHttpRequest) { return window.XMLHttpRequest; } else if (window.ActiveXObject) { var axs = [ 'Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP' ]; for (var i = 0; i < axs.length; i++) { try { var ax = new(window.ActiveXObject)(axs[i]); return function () { if (ax) { var ax_ = ax; ax = null; return ax_; } else { return new(window.ActiveXObject)(axs[i]); } }; } catch (e) {} } throw new Error('ajax not supported in this browser') } else { throw new Error('ajax not supported in this browser'); } })();
JavaScript
0.000088
@@ -382,16 +382,49 @@ s.port = + params.scheme == 'https' ? 443 : 80;%0A
e4c78f1a4f338a52f4154aade95e3814746dbc7d
add module_folder to exports
index.js
index.js
/* * index.js * * David Janes * IOTDB.org * 2015-06-22 * * Copyright [2013-2015] [David P. Janes] * * 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"; var mdns = require('mdns'); var iotdb = require('iotdb'); var _ = iotdb._; var ad_http; var ad_api; var advertise_http = function(locals) { var td = {}; var client_id = _.d.get(locals.homestar.settings, "/keys/homestar/key"); if (client_id) { td.runner = client_id; } ad_http = mdns.createAdvertisement( mdns.tcp('http'), locals.homestar.settings.webserver.port, { // host: locals.homestar.settings.webserver.host, name: "Home☆Star: " + locals.homestar.settings.name, txtRecord: td }); ad_http.start(); }; var advertise_api = function(locals) { var td = { api: "/api" }; var client_id = _.d.get(locals.homestar.settings, "/keys/homestar/key"); if (client_id) { td.runner = client_id; } ad_api = mdns.createAdvertisement( mdns.tcp('iotdb'), locals.homestar.settings.webserver.port, { // host: locals.homestar.settings.webserver.host, name: locals.homestar.settings.name, txtRecord: td }); ad_api.start(); }; exports.homestar = { setup_app: function(locals, app) { advertise_http(locals); advertise_api(locals); } };
JavaScript
0.000001
@@ -1944,12 +1944,48 @@ );%0A %7D%0A%7D;%0A +%0Aexports.module_folder = __dirname;%0A
0f582c22b792b578cf9500a057a486b45dbe98bc
make sure we're working with string in the string stringifier
index.js
index.js
'use strict'; function isObject(x) { return typeof x === 'object' && x !== null; } module.exports = function (val, opts, pad) { var seen = []; return (function stringify(val, opts, pad) { opts = opts || {}; opts.indent = opts.indent || '\t'; pad = pad || ''; if (typeof val === 'number' || typeof val === 'boolean' || val === null || val === undefined) { return val; } if (val instanceof Date) { return 'new Date(\'' + val.toISOString() + '\')'; } if (Array.isArray(val)) { if (val.length === 0) { return '[]'; } return '[\n' + val.map(function (el, i) { var eol = val.length - 1 === i ? '\n' : ',\n'; return pad + opts.indent + stringify(el, opts, pad + opts.indent) + eol; }).join('') + pad + ']'; } if (isObject(val)) { if (seen.indexOf(val) !== -1) { return '"[Circular]"'; } var objKeys = Object.keys(val); if (objKeys.length === 0) { return '{}'; } seen.push(val); var ret = '{\n' + objKeys.map(function (el, i) { if (opts.filter && !opts.filter(val, el)) { return ''; } var eol = objKeys.length - 1 === i ? '\n' : ',\n'; var key = /^[a-z$_][a-z$_0-9]*$/i.test(el) ? el : stringify(el, opts); return pad + opts.indent + key + ': ' + stringify(val[el], opts, pad + opts.indent) + eol; }).join('') + pad + '}'; seen.pop(val); return ret; } if (opts.singleQuotes === false) { return '"' + val.replace(/"/g, '\\\"') + '"'; } return '\'' + val.replace(/'/g, '\\\'') + '\''; })(val, opts, pad); };
JavaScript
0.000204
@@ -1429,27 +1429,35 @@ eturn '%22' + +String( val +) .replace(/%22/ @@ -1495,19 +1495,27 @@ '%5C'' + +String( val +) .replace
96fcb7b050504c3b83854794e83cb4c9c797578b
move constructor methods to top level
index.js
index.js
module.exports = { Parser = require('./lib/parser.js'), Evaluator = require('./lib/evaluator.js'), types = require('./types') };
JavaScript
0
@@ -22,18 +22,70 @@ Parser - = +: require('./lib/parser.js').Parser,%0A createParser: require @@ -99,24 +99,37 @@ /parser.js') +.createParser ,%0A Evalua @@ -131,18 +131,79 @@ valuator - = +: require('./lib/evaluator.js').Evaluator,%0A createEvaluator: require @@ -224,16 +224,32 @@ tor.js') +.createEvaluator ,%0A ty @@ -251,18 +251,17 @@ types - = +: require
a801611772d73f564260b6690a156f047a1757f5
Change sendFile error
index.js
index.js
const fs = require('fs'); const config = require('./config.json'); const restify = require('restify'); const Router = require('./Router'); const router = new Router(); const server = restify.createServer({ name: 'SmallCDN', }); server.use(restify.gzipResponse()); server.use((req, res, next) => { res.sendFile = (v, library, version, file) => { // eslint-disable-line fs.readFile(`assets/v${v}/${library}/${version}/${file}`, 'utf8', (err, data) => { if (err) return res.send(500, { code: 500, message: err.message }); return res.end(data); }); }; return next(); }); server.get('/', (req, res, next) => { res.redirect(301, 'https://smallcdn.rocks', next); }); router.use('/v2', require('./routes/v2')); router.use('/', require('./routes/v1')); router.applyRoutes(server); server.listen(config.port);
JavaScript
0.000001
@@ -500,19 +500,17 @@ %7B code: -500 +6 , messag @@ -516,19 +516,46 @@ ge: -err.message +%22there was an error reading from disk%22 %7D);
e3b1656e91606c8c19aea649a40fb277398df43b
Update some doc comments.
index.js
index.js
export {Transform} from "./transform" export {Step, StepResult} from "./step" export {canLift, canWrap} from "./ancestor" export {joinPoint, joinableBlocks} from "./join" export {PosMap, MapResult, Remapping} from "./map" import "./mark" import "./split" import "./replace" // !! This module defines a way to transform documents. Transforming // happens in `Step`s, which are atomic, well-defined modifications to // a document. [Applying](`Step.apply`) a step produces a new document // and a [position map](#PosMap) that maps positions in the old // document to position in the new document. Steps can be // [inverted](#Step.invert) to create a step that undoes their effect, // and chained together in a convenience object called a `Transform`. // // This module does not depend on the browser API being available // (i.e. you can load it into any JavaScript environment). // // These are the types of steps defined:
JavaScript
0
@@ -869,24 +869,110 @@ onment).%0A//%0A +// You can read more about transformations in %5Bthis%0A// guide%5D(guide/transform.md).%0A//%0A // These are
e004df50879299306ecc3cf0310c98eb53f2b9be
Remove extraneous statements, use new class name
index.js
index.js
// jscs:disable requireMultipleVarDecl 'use strict'; var Promise = require('bluebird'), StorageBase = require('ghost-storage-base'), imgur = require('imgur'); class ImgurStore extends StorageBase { constructor() { super(); } save(image) { // TODO: save delete url return new Promise(function(resolve, reject) { imgur.uploadFile(image.path) .then(function(json) { if(!json || !json.data || !json.data.link) return reject(); resolve(json.data.link); }) .catch(reject); }); } exists(fileName, targetDir) { // TODO: check file status return new Promise(function(resolve) { resolve(true); }); } serve() { return function customServe(req, res, next) { next(); } } delete() { return Promise.reject('not implemented'); } read(options) { } } module.exports = ImgurStore;
JavaScript
0.0003
@@ -87,27 +87,27 @@ '),%0A +Base Storage -Base = requi @@ -178,16 +178,18 @@ mgurStor +ag e extend @@ -194,19 +194,19 @@ nds +Base Storage -Base %7B%0A @@ -314,56 +314,8 @@ urn -new Promise(function(resolve, reject) %7B%0A imgu @@ -339,18 +339,16 @@ e.path)%0A - @@ -384,76 +384,37 @@ - if(!json %7C%7C !json.data %7C%7C !json.data.link) return reject() +return json.data.link ;%0A @@ -413,78 +413,92 @@ + %7D)%0A -resolve(json.data.link);%0A %7D)%0A .catch(reject + .catch(function(err) %7B%0A return Promise.reject(err.message );%0A + @@ -594,48 +594,16 @@ urn -new Promise -(function(resolve) %7B%0A +. reso @@ -613,26 +613,16 @@ (true);%0A - %7D);%0A %7D%0A%0A @@ -659,20 +659,8 @@ tion - customServe (req @@ -697,16 +697,17 @@ %0A %7D +; %0A %7D%0A%0A @@ -835,7 +835,8 @@ Stor +ag e; -%0A
20de9a903fb14a38eef2321438309ed1dfbe807d
Fix movements 3.
index.js
index.js
// Load dependencies const express = require('express'); var app = express(); const path = require('path'), server = require('http').createServer(app), port = process.env.PORT || 5223; io = require('socket.io')(server); // Server global acc, vel, dist variables var aX = 0, aY = 0, aZ = 0, vX = 0, vY = 0, vZ = 0, sX = 0, sY = 0, sZ = 0; // Fix OS paths app.use(express.static(path.join(__dirname, 'public'))); // Setup socket communication io.on('connection', function ( socket ) { socket.on('joined', function() { console.log("Joined"); socket.broadcast.emit('joined', { message: "Joined" }); }); // Data socket.on('phone-data', function ( data ) { // Check array size - same lengths // if (aX.length >= 100) chopArrays(100); // Store acc data aX = data.accelerometer.x; aY = data.accelerometer.y; aZ = data.accelerometer.z; // Update vel, disp var steps = Math.round(1/data.interval); displacement3D(0.0167, 60); // Broadcast new data socket.broadcast.emit('phone-data', { accelerometer: { x: data.accelerometer.x, y: data.accelerometer.y, z: data.accelerometer.z }, velocity: { vX: vX, vY: vY, vZ: vZ }, displacement: { sX: sX, sY: sY, sZ: sZ }, rotationRate: data.rotationRate, interval: data.interval }); }); socket.on('disconnect', function() { console.log("Client disconnected."); socket.broadcast.emit('disconnet', {}); }); }); server.listen(port, function() { console.log('Server listening on port %d', port); }); // Utils function displacement3D(dt, steps) { for (var i = 0; i < steps; i++) { vX = vX + dt*aX; vY = vY + dt*aY; vZ = vZ + dt*aZ; sX = sX + dt*vX; sY = sY + dt*vY; sZ = sZ + dt*vZ; console.log(sX + '\t' + sY + '\t' + sZ); } }
JavaScript
0
@@ -1003,10 +1003,9 @@ 67, -60 +1 );%0A
37b9d0b60166a80f5fe5d0597ffa01fc67a0afe5
Remove flow file annotation rule
index.js
index.js
const restrictedGlobals = require("eslint-restricted-globals"); module.exports = { root: true, parser: "babel-eslint", extends: [ "airbnb", "plugin:flowtype/recommended", "prettier", "prettier/flowtype", "prettier/react" ], plugins: ["flowtype"], globals: { _LTracker: false, __insp: false, mixpanel: false }, env: { browser: true, jest: true }, rules: { // Airbnb Rule Overrides camelcase: "off", "func-names": "error", "no-param-reassign": "off", "no-plusplus": ["error", { allowForLoopAfterthoughts: true }], "no-prototype-builtins": "off", "no-restricted-globals": ["error", "isFinite", "isNaN"] .concat(restrictedGlobals) .filter(g => !["location", "history"].includes(g)), "no-restricted-syntax": [ "error", { selector: "ForInStatement", message: "for..in loops iterate over the entire prototype chain, which is virtually never what you want. Use Object.{keys,values,entries}, and iterate over the resulting array." }, { selector: "LabeledStatement", message: "Labels are a form of GOTO; using them makes code confusing and hard to maintain and understand." }, { selector: "WithStatement", message: "`with` is disallowed in strict mode because it makes code impossible to predict and optimize." } ], "no-underscore-dangle": "off", "no-unused-expressions": "off", "prefer-destructuring": "off", "jsx-a11y/anchor-is-valid": [ "error", { components: ["Link"], specialLink: ["to"], aspects: ["noHref", "invalidHref", "preferButton"] } ], // Import overrides "import/no-extraneous-dependencies": [ "error", { devDependencies: [ "**/__tests__/**", "**/*.test.js", "**/*.test.jsx", "**/webpack.config.js", "**/webpack.config.*.js" ], packageDir: ["./", "../"], optionalDependencies: false } ], "import/prefer-default-export": "off", // Flowtype Rules "flowtype/no-dupe-keys": "error", "flowtype/no-primitive-constructor-types": "error", "flowtype/no-weak-types": "warn", "flowtype/require-parameter-type": [ "warn", { excludeArrowFunctions: true } ], "flowtype/require-return-type": [ "warn", "always", { excludeArrowFunctions: true } ], "flowtype/require-valid-file-annotation": [ "warn", "always", { annotationStyle: "line" } ], "flowtype/sort-keys": [ "off", "asc", { caseSensitive: false, natural: true } ], "flowtype/type-id-match": ["warn", "^([A-Z][a-z0-9]*)+T$"], // React Overrides for Flow // These can probably be removed at some point when bugs are worked out "react/no-unused-prop-types": "off", "react/sort-comp": [ "error", { order: [ "type-annotations", "instance-variables", "static-methods", "lifecycle", "/^on.+$/", "getters", "setters", "/^(get|set)(?!(InitialState$|DefaultProps$|ChildContext$)).+$/", "instance-methods", "everything-else", "/^render.+$/", "render" ] } ] }, settings: { flowtype: { onlyFilesWithFlowAnnotation: true } } };
JavaScript
0
@@ -2512,127 +2512,8 @@ %5D,%0A - %22flowtype/require-valid-file-annotation%22: %5B%0A %22warn%22,%0A %22always%22,%0A %7B annotationStyle: %22line%22 %7D%0A %5D,%0A
d7b72e48aaf6eda79c2f874439b4866838f7808c
Revert "Testing"
index.js
index.js
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ______ ______ ______ __ __ __ ______ /\ == \ /\ __ \ /\__ _\ /\ \/ / /\ \ /\__ _\ \ \ __< \ \ \/\ \ \/_/\ \/ \ \ _"-. \ \ \ \/_/\ \/ \ \_____\ \ \_____\ \ \_\ \ \_\ \_\ \ \_\ \ \_\ \/_____/ \/_____/ \/_/ \/_/\/_/ \/_/ \/_/ This is a sample Slack Button application that provides a custom Slash command. This bot demonstrates many of the core features of Botkit: * * Authenticate users with Slack using OAuth * Receive messages using the slash_command event * Reply to Slash command both publicly and privately # RUN THE BOT: Create a Slack app. Make sure to configure at least one Slash command! -> https://api.slack.com/applications/new Run your bot from the command line: clientId=<my client id> clientSecret=<my client secret> PORT=3000 node bot.js Note: you can test your oauth authentication locally, but to use Slash commands in Slack, the app must be hosted at a publicly reachable IP or host. # EXTEND THE BOT: Botkit is has many features for building cool and useful bots! Read all about it here: -> http://howdy.ai/botkit ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ /* Uses the slack button feature to offer a real time bot to multiple teams */ var Botkit = require('botkit'); if (!process.env.CLIENT_ID || !process.env.CLIENT_SECRET || !process.env.PORT || !process.env.VERIFICATION_TOKEN) { console.log('Error: Specify CLIENT_ID, CLIENT_SECRET, VERIFICATION_TOKEN and PORT in environment'); process.exit(1); } var config = {} if (process.env.MONGOLAB_URI) { var BotkitStorage = require('botkit-storage-mongo'); config = { storage: BotkitStorage({mongoUri: process.env.MONGOLAB_URI}), }; } else { config = { json_file_store: './db_slackbutton_slash_command/' }; } var controller = Botkit.slackbot(config).configureSlackApp( { clientId: process.env.CLIENT_ID, clientSecret: process.env.CLIENT_SECRET, scopes: ['commands'] } ); controller.setupWebserver(process.env.PORT, function (err, webserver) { controller.createWebhookEndpoints(controller.webserver); controller.createOauthEndpoints(controller.webserver, function (err, req, res) { if (err) { res.status(500).send('ERROR: ' + err); } else { res.send('Success!'); } }); }); // // BEGIN EDITING HERE! // controller.on('slash_command', function (slashCommand, message) { console.log(message); switch (message.command) { case "/echo": //handle the `/echo` slash command. We might have others assigned to this app too! // The rules are simple: If there is no text following the command, treat it as though they had requested "help" // Otherwise just echo back to them what they sent us. // but first, let's make sure the token matches! if (message.token !== process.env.VERIFICATION_TOKEN) return; //just ignore it. // if no text was supplied, treat it as a help command if (message.text === "" || message.text === "help") { slashCommand.replyPrivate(message, "I echo back what you tell me. " + "Try typing `/echo hello` to see."); return; } // If we made it here, just echo what the user typed back at them //TODO You do it! slashCommand.replyPublic(message, "1", function() { slashCommand.replyPublicDelayed(message, "2").then(slashCommand.replyPublicDelayed(message, "3")); }); break; case '/work': if (message.text === 'start') { // test slashCommand.replyPublic(message, 'Started working time: tuesday, **6.5.2017** at **7:45**. <br /><br />Time to get work done, we need to make some money.'); } break; default: slashCommand.replyPublic(message, "I'm afraid I don't know how to " + message.command + " yet."); } }) ;
JavaScript
0
@@ -3808,16 +3808,8 @@ ') %7B - // test %0A
56678965684e2604a30b423ea83cc4a47f5ad97b
Edit comments.
index.js
index.js
/* Copyright (c) 2015 Jesse McCarthy <http://jessemccarthy.net/> */ var rs = require('readable-stream'), util = require('util'); // A full pragma looks like // `({"compiler": "browserify", "version": "1.23.456"});` module.exports = BrowserifyPragma; function BrowserifyPragma (opts) { if (!(this instanceof BrowserifyPragma)) return new BrowserifyPragma(opts); var self = this; opts = opts || {}; Object.keys(opts).forEach(function (prop) { self[prop] = opts[prop]; }); // Store content from start of file. self.src = []; self.src.byteLength = 0; self.detected = false; self.present = false; } // BrowserifyPragma /** * Generate browserify pragma. */ BrowserifyPragma.generate = function (opts) { opts = opts || {}; // Manually construct this as a string (instead of using JSON.stringify()) to // ensure property order. return BrowserifyPragma.prototype.template.replace( 'VERSION', opts.version ); }; // generate /** * Test for browserify pragma. * @param string src * @return boolean */ BrowserifyPragma.detect = function (src) { return this.prototype.re.test(src); }; // detect var Pragma = BrowserifyPragma.prototype; Pragma.encoding = 'utf-8'; // Placeholder version value to represent the max length. Pragma.version = '123.456.789'; // Max bytes that may precede pragma. 3 = max BOM length. Pragma.preMaxBytes = 3; Pragma.template = '({"compiler": "browserify", "version": "VERSION"});'; Pragma.sample = Pragma.template.replace('VERSION', Pragma.version); Pragma.re = new RegExp( "^" + // BOM "\\uFEFF?" + Pragma.template .replace(/[(){}]/g, '\\$&') .replace( 'VERSION', '[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}' ) ); // Minimum number of bytes needed to detect pragma. Pragma.minBytes = Pragma.preMaxBytes + Buffer.byteLength(Pragma.sample, Pragma.encoding); function Detector () { rs.Transform.apply(this, arguments); } // Detector util.inherits(Detector, rs.Transform); Detector.prototype._transform = function _transform (chunk, enc, cb) { var pragma = this.pragma; if (!pragma.detected) { pragma.src.push(chunk); pragma.src.byteLength += chunk.length; if (pragma.src.byteLength >= pragma.minBytes) { pragma.present = BrowserifyPragma.detect( Buffer.concat(pragma.src).toString(Pragma.encoding) ); pragma.detected = true; pragma.done(pragma); } } this.push(chunk); cb(); } // _transform Detector.prototype._flush = function _flush (cb) { // Source didn't contain enough bytes to test for pragma. if (!this.pragma.detected) this.pragma.done(this.pragma); this.pragma.src = []; cb(); } // _flush // Setup a stream to pipe source through first to check for the pragma // before piping to other streams. Pragma.detector = function () { if (!this._detector) { var stream = this._detector = new Detector; stream.pragma = this; } return this._detector; }; // detector
JavaScript
0
@@ -132,38 +132,353 @@ );%0A%0A -// A full pragma looks like%0A// +module.exports = BrowserifyPragma;%0A%0A/**%0A * Implement browserify pragma handling logic. A pragma is a fragment that can%0A * be prepended to bundles and subsequently detected by browserify during%0A * bundling to apply appropriate handling to the module, e.g. omitting parsing%0A * for %60require()%60 calls. A pragma looks like (backticks not literal):%0A * %60(%7B @@ -533,44 +533,11 @@ );%60%0A -%0Amodule.exports = BrowserifyPragma;%0A + */ %0Afun
3dd57320b5f5596bab0a475cc7547def7fb5f141
Fix grid generation bugs
app/scripts/hexmap.js
app/scripts/hexmap.js
'use strict'; /** * @ngdoc function * @name learningAngularJsApp.controller:HexmapCtrl * @description * # HexmapCtrl * Controller of the learningAngularJsApp */ // Hex math defined here: http://blog.ruslans.com/2011/02/hexagonal-grid-math.html function HexagonGrid(canvasId, radius) { this.radius = radius; this.canvas = document.getElementById(canvasId); this.context = this.canvas.getContext('2d'); // All the hexagons, indexed by hexagonal coordinates [u,v] this.hexagons = {}; // All the labels, indexed by hexagonal coordinates [u,v] this.labels = {}; this.canvasOriginX = 0; this.canvasOriginY = 0; this.stage = new createjs.Stage(canvasId); this.stage.enableMouseOver(20); } // Add or update a text label to the given coordinates HexagonGrid.prototype.addLabel = function (u, v, label) { // Check if the label already exists, so it doesn't get recreated if(!([u,v] in this.labels)){ var pixel = this.hexToPixel(u,v); var text = new createjs.Text(label, '60px Arial', '#ffffff'); text.x = pixel[0] - 15; text.y = pixel[1] + 15; text.textBaseline = 'alphabetic'; // Add the text label to dictionary this.labels[[u,v]] = text; // Add the text label to the stage this.stage.addChild(text); } else { this.labels[[u,v]].text = label; } // Update the stage this.stage.update(); }; // Add a sprite HexagonGrid.prototype.addSprite = function (u, v, image){ var pixel = this.hexToPixel(u,v); var bitmap = new createjs.Bitmap(image); bitmap.x = pixel[0] - 40; bitmap.y = pixel[1] - 40; bitmap.scaleX = 0.4; bitmap.scaleY = 0.4; this.stage.addChild(bitmap); this.stage.update(event); }; HexagonGrid.prototype.drawHexGrid = function (radius, originX, originY) { this.canvasOriginX = originX; this.canvasOriginY = originY; this.selectedCoord = {u:0, v:0}; for (var u = -radius; u < radius; u++){ for (var v = -radius; v < radius; v++){ var a = {u: u, v: v}; var b = {u: 0, v: 0}; if (this.Distance(a,b) > 3){ continue; } this.addHex(u, v); } } }; HexagonGrid.prototype.setHexColor = function(u,v, color){ if (typeof u !== 'undefined' && typeof v !== 'undefined'){ if ([u,v] in this.hexagons){ this.hexagons[[u,v]].graphics._fill.style = color; this.stage.update(); } } }; HexagonGrid.prototype.hexToPixel = function(u,v){ var y = this.radius * Math.sqrt(3) * (u + v/2); var x = this.radius * 3/2 * v; x += this.canvasOriginX; y += this.canvasOriginY; return [x, y]; }; HexagonGrid.prototype.pixelToHex = function(x, y){ x -= this.canvasOriginX; y -= this.canvasOriginY; var r = Math.round(x * 2/3 / this.radius); var q = Math.round((-x / 3 + Math.sqrt(3)/3 * y) / this.radius); return [q, r]; }; HexagonGrid.prototype.addHex = function(u, v) { var hexagonGrid = this; var pixel = this.hexToPixel(u,v); var hexagon = new createjs.Shape(); hexagon.hexcoord = {u:u, v:v}; var fillCommand = hexagon.graphics.beginFill('Grey').command; hexagon.graphics.beginStroke('black'); hexagon.graphics.drawPolyStar(pixel[0], pixel[1], this.radius, 6, 0 , 0); // Add mouse event hexagon.on('click', function(e){ console.log('clicked on', e.target.hexcoord); hexagonGrid.selectedCoord = e.target.hexcoord; }); var originalColor; hexagon.on('mouseover', function(e){ originalColor = fillCommand.style; fillCommand.style = 'blue'; hexagonGrid.stage.update(e); }); hexagon.on('mouseout', function(e){ fillCommand.style = originalColor; this.stage.update(e); }); this.stage.addChild(hexagon); this.stage.update(); this.hexagons[[u,v]] = hexagon; return hexagon.graphics; }; HexagonGrid.prototype.Distance = function(a, b){ return (Math.abs(a.u - b.u) + Math.abs(a.u + a.v - b.u - b.v) + Math.abs(a.v - b.v)) / 2; };
JavaScript
0
@@ -1984,16 +1984,17 @@ ius; u %3C += radius; @@ -2032,16 +2032,17 @@ ius; v %3C += radius; @@ -2145,17 +2145,22 @@ (a,b) %3E -3 +radius )%7B%0A
0ad05f23c5e4fc1c4eec99c75aa69de235bcb86c
Simplify API and add a method for getting global options.
index.js
index.js
'use strict'; var assign = require('object-assign'); var argv = require('minimist')(process.argv.slice(2)); var path = require('path'); var loaded = []; function loadTask (task, opts) { var func; var funcLoadError; // Don't trace tasks if they've already been loaded. if (loaded.indexOf(task) > -1) { return; } // Find the first matching module. opts.base.some(function (base) { try { return func = require(path.join(base, task)); } catch (e) { funcLoadError = e; return false; } }); if (!func && funcLoadError) { throw new Error ('could not load task "' + task + '" because it could not be found in ' + JSON.stringify(opts.base) + ' because: ' + funcLoadError); } // Flag so we can check for circular deps. loaded.push(task); // Tasks can be: module.exports = ['dependencies'] if (Array.isArray(func)) { var deps = func; func = function (opts, done) { return done(); }; func.dependencies = deps; } // Don't register private tasks. if (func.private) { return; } (func.dependencies || []).forEach(function (dep) { try { loadTask(dep, opts); } catch (e) { throw new Error('could not load task dependency "' + dep + '" for "' + task + '" because: ' + e); } }); opts.gulp.task(task, func.bind(argv)); } module.exports = function (opts) { opts = assign({ base: process.cwd(), gulp: require('gulp') }, opts); if (typeof opts.base === 'string') { opts.base = [opts.base]; } opts.base = opts.base.map(function (base) { return path.isAbsolute(base) ? base : path.join(process.cwd(), base); }); argv._.forEach(function (task) { loadTask(task, opts); }); };
JavaScript
0
@@ -102,16 +102,40 @@ ce(2));%0A +var fs = require('fs');%0A var path @@ -150,24 +150,25 @@ re('path');%0A +%0A var loaded = @@ -168,18 +168,18 @@ oaded = -%5B%5D +%7B%7D ;%0A%0Afunct @@ -186,28 +186,114 @@ ion -loadTask (task, opts +resolvePath (p) %7B%0A return path.isAbsolute(p) ? p : path.join(process.cwd(), p);%0A%7D%0A%0Afunction loadOptions ( ) %7B%0A @@ -302,20 +302,20 @@ var -func +opts ;%0A var func @@ -314,125 +314,452 @@ var -funcLoadError;%0A%0A // Don't trace tasks if they've already been loaded.%0A if (loaded.indexOf(task) %3E -1) %7B%0A +rcFile = path.join(process.cwd(), '.gulprc');%0A%0A if (fs.existsSync(rcFile)) %7B%0A try %7B%0A opts = JSON.parse(fs.readFileSync(rcFile));%0A %7D catch (e) %7B%0A throw new Error('cannot parse config %22' + rcFile + '%22 because: ' + e);%0A %7D%0A %7D%0A%0A return assign(%7B%0A base: '.',%0A gulp: 'node_modules/gulp'%0A %7D, opts, argv);%0A%7D%0A%0Afunction loadTask (task, opts) %7B%0A var func;%0A var funcLoadError;%0A%0A // Don't recurse.%0A if (loaded%5Btask%5D) %7B return; %0A %7D @@ -750,28 +750,49 @@ %5D) %7B return; + %7D %0A -%7D +loaded%5Btask%5D = task; %0A%0A // Find @@ -987,24 +987,63 @@ %7D%0A %7D);%0A%0A + // Try and give helpful load errors.%0A if (!func @@ -1123,40 +1123,12 @@ '%22 -because it could not be found in +from ' + @@ -1201,730 +1201,259 @@ // -Flag so we can check for circular deps.%0A loaded.push(task);%0A%0A // Tasks can be: module.exports = %5B'dependencies'%5D%0A if (Array.isArray(func)) %7B%0A var deps = +Simple register.%0A opts.gulp.task(task, func +) ;%0A - func = function (opts, done) %7B%0A return done();%0A %7D;%0A func.dependencies = deps;%0A %7D%0A%0A // Don't register private tasks.%0A if (func.private) %7B%0A return;%0A %7D%0A%0A (func.dependencies %7C%7C %5B%5D).forEach(function (dep) %7B%0A try %7B%0A loadTask(dep, opts);%0A %7D catch (e) %7B%0A throw new Error('could not load task dependency %22' + dep + '%22 for %22' + task + '%22 because: ' + e);%0A %7D%0A %7D);%0A%0A opts.gulp.task(task, func.bind(argv));%0A%7D%0A%0Amodule.exports = function (opts) %7B%0A opts = assign(%7B%0A b +%7D%0A%0Afunction loadTasks () %7B%0A var opts = loadOptions();%0A%0A // Can specify the path to the Gulp module.%0A opts.gulp = require(resolvePath(opts.gulp));%0A%0A // B ase -: p -rocess.cwd(),%0A gulp: require('gulp')%0A %7D, opts);%0A +ath can be a string or array of base paths. %0A i @@ -1528,199 +1528,306 @@ %0A%0A -opts.base = opts.base.map(function (base) %7B%0A return path.isAbsolute(base) ? base : path.join(process.cwd(), base);%0A %7D);%0A%0A argv._.forEach(function (task) %7B%0A loadTask(task, opts);%0A %7D); +// Ensure all paths are normalised.%0A opts.base = opts.base.map(resolvePath);%0A%0A // Load all specified tasks.%0A argv._.forEach(function (task) %7B%0A loadTask(task, opts);%0A %7D);%0A%0A // Export the options so they can be used.%0A return opts;%0A%7D%0A%0Amodule.exports = %7B%0A load: loadTasks,%0A opts: loadOptions %0A%7D;%0A
fe907951ffd0033a2752649c4d380d3de93ca35c
change codestyle
index.js
index.js
const isSeparator = (input) => input === '-' || (Array.isArray(input) && input[0] === '-') const isClickHandler = (fn) => typeof fn === 'function' const isRole = (role) => [ 'undo', 'redo', 'cut', 'copy', 'paste', 'pasteandmatchstyle', 'selectall', 'delete', 'minimize', 'close', 'quit', 'togglefullscreen', 'about', 'hide', 'hideothers', 'unhide', 'front', 'zoom', 'window', 'help', 'services' ].includes(role) function convert (menuDesc) { if (!Array.isArray(menuDesc)) { if (isSeparator(menuDesc)) return { type: 'separator' } return menuDesc } if (menuDesc.length === 0) return menuDesc menuDesc = menuDesc.slice(0) // shallow clone array if (isSeparator(menuDesc[0])) return { type: 'separator' } // is it a menu-item or a submenu? if (typeof menuDesc[0] === 'string') { // convention dictates the first being the label let menuDescObj = { label: menuDesc[0] } menuDesc.shift() // already processed label, so get rid of it menuDesc.forEach(menuItem => { if (isClickHandler(menuItem)) return Object.assign(menuDescObj, { click: menuItem }) if (isRole(menuItem)) return Object.assign(menuDescObj, { role: menuItem }) // by this point, we've already checked if the string was a label or role, now it must be an accelerator if (typeof menuItem === 'string') return Object.assign(menuDescObj, { accelerator: menuItem }) if (Array.isArray(menuItem)) return Object.assign(menuDescObj, { submenu: convert(menuItem) }) }) return menuDescObj } else { // assume sub-menu return menuDesc.map(convert) } } module.exports = convert
JavaScript
0.000028
@@ -560,16 +560,17 @@ esc%0A %7D%0A +%0A if (me @@ -601,71 +601,10 @@ urn -menuDesc%0A menuDesc = menuDesc.slice(0) // shallow clone array%0A +%5B%5D %0A i @@ -664,46 +664,8 @@ r' %7D -%0A%0A // is it a menu-item or a submenu? %0A i @@ -682,25 +682,25 @@ menuDesc%5B0%5D -= +! == 'string') @@ -700,20 +700,65 @@ tring') -%7B%0A +return menuDesc.map(convert) // assume sub-menu%0A%0A // con @@ -806,147 +806,57 @@ l%0A - let menuDescObj = %7B label: menuDesc%5B0%5D %7D%0A menuDesc.shift() // already processed label, so get rid of it%0A%0A menuDesc.forEach( +return menuDesc.slice(1).reduce((result, menuItem =%3E @@ -855,16 +855,15 @@ Item +) =%3E %7B%0A - @@ -909,35 +909,30 @@ ject.assign( -menuDescObj +result , %7B click: m @@ -942,26 +942,24 @@ Item %7D)%0A - - if (isRole(m @@ -985,35 +985,30 @@ ject.assign( -menuDescObj +result , %7B role: me @@ -1013,26 +1013,24 @@ menuItem %7D)%0A - // by th @@ -1126,26 +1126,24 @@ lerator%0A - if (typeof m @@ -1181,35 +1181,30 @@ ject.assign( -menuDescObj +result , %7B accelera @@ -1220,18 +1220,16 @@ Item %7D)%0A - if ( @@ -1274,27 +1274,22 @@ .assign( -menuDescObj +result , %7B subm @@ -1320,103 +1320,34 @@ )%0A - %7D)%0A%0A return menuDescObj%0A %7D else %7B // assume sub-menu%0A return menuDesc.map(convert)%0A +%7D, %7B label: menuDesc%5B0%5D %7D +) %0A%7D%0A%0A
f18c4103c7e29e17a8a185821fed4a11f625275f
remove unused modules
index.js
index.js
'use strict'; function hasLocalConfig() { try { require.resolve('./localConfig'); return true; } catch (e) { return false; } } if (hasLocalConfig()) Object.assign(process.env, require('./localConfig')); const path = require('path'); const co = require('co'); const koa = require('koa'); const route = require('koa-route'); const gh = require('./lib/github'); const app = koa(); if (!process.env.KOA_KEYS) throw new Error('KOA_KEYS not set'); app.keys = process.env.KOA_KEYS.split(/\s+/); app.proxy = !!process.env.KOA_PROXY; app.use(require('koa-logger')()); app.use(require('./controller/error')()); if (process.env.KOA_REQUIRE_HTTPS) { app.use(require('koa-sslify')({ trustProtoHeader: !!process.env.KOA_PROXY, })); } app.use(require('./controller/purecss')('/purecss')); app.use(require('koa-session')(app)); require('koa-ejs')(app, { root: path.join(__dirname, 'view'), layout: 'template', cache: true, viewExt: '.html', debug: false, }); app.use(require('./controller/auth')('/auth')); app.use(require('./controller/pull')('')); app.listen(process.env.PORT || 5000);
JavaScript
0.000002
@@ -6,16 +6,74 @@ strict'; +%0Aconst path = require('path');%0Aconst koa = require('koa'); %0A%0Afuncti @@ -280,164 +280,8 @@ );%0A%0A -%0Aconst path = require('path');%0Aconst co = require('co');%0Aconst koa = require('koa');%0Aconst route = require('koa-route');%0Aconst gh = require('./lib/github'); %0A%0Aco
32ca55b674243e19e3dbc40830860208a5f14c0a
handle `unhandledRejection`s, tweaks
index.js
index.js
/*! * always-done <https://github.com/tunnckoCore/always-done> * * Copyright (c) 2015 Charlike Mike Reagent <@tunnckoCore> (http://www.tunnckocore.tk) * Released under the MIT license. */ 'use strict' var sliced = require('sliced') var onetime = require('onetime') var dezalgo = require('dezalgo') var Bluebird = require('bluebird') var isError = require('is-typeof-error') var isAsyncFn = require('is-async-function') var isNodeStream = require('is-node-stream') var isChildProcess = require('is-child-process') var streamExhaust = require('stream-exhaust') var onStreamEnd = require('on-stream-end') module.exports = function alwaysDone (fn) { var self = this var argz = sliced(arguments) var args = sliced(argz, 1, -1) var callback = argz[argz.length - 1] if (typeof fn !== 'function') { throw new TypeError('always-done: expect `fn` to be function') } if (typeof callback !== 'function') { throw new TypeError('always-done: expect `callback` to be function') } var done = onetime(dezalgo(function (err) { if (err instanceof Error) { callback.call(self, err) return } callback.apply(self, [null].concat(sliced(arguments, 1))) })) process.once('uncaughtException', done) process.on('newListener', function (name) { this.removeAllListeners(name) }) if (isAsyncFn(fn)) args = args.concat(done) return Bluebird.resolve() .then(function () { return fn.apply(self, args) }) .then(function (ret) { if (isNodeStream(ret) || isChildProcess(ret)) { onStreamEnd(streamExhaust(ret), done) return } if (ret && typeof ret.subscribe === 'function') { if (ret.value) return done(null, ret.value) ret.subscribe(function noop () {}, done, done) return } if (isError(ret)) { done(ret) return } done.call(self, null, ret) }, done) }
JavaScript
0
@@ -1231,16 +1231,59 @@ , done)%0A + process.once('unhandledRejection', done)%0A proces @@ -1807,20 +1807,104 @@ , done, -done +function () %7B%0A callback.apply(self, %5Bnull%5D.concat(sliced(arguments)))%0A %7D )%0A @@ -2016,24 +2016,41 @@ null, ret)%0A + return ret%0A %7D, done)
236e521dd312f0140edf6d7ce390e54b5718da1e
Use repl
index.js
index.js
/* Licensed under the MIT License. See the accompanying LICENSE file for terms. */ var readline = require('readline'), async = require('async'), serialport = require('serialport'), SerialPort = serialport.SerialPort, connected = false, candidates = [], input, esp; function readPorts(err, ports) { ports.forEach(eachPort); attempt(); } function eachPort(port) { candidates.push(function candidate(cb) { analyze(port, cb); }); } function attempt() { async.series(candidates, function done(err) { if (!connected) { var msg = candidates.length ? 'Espruino not found!' : 'No connected devices found!'; console.log(msg + 'Make sure Espruino is plugged in.'); } }); } function close() { input.close(); onLine('reset()'); esp.close(); } function autoComplete(line) { var completions = '.help .exit .quit .q'.split(' '), hits = completions.filter(function(c) { return c.indexOf(line) == 0 }); return [hits.length ? hits : completions, line] } function onLine(line) { switch (line) { case '.help': process.stdout.write('Help text!\n'); break; case '.q': case '.quit': case '.exit': close(); break; default: esp.write(line + '\r'); break; } } function onCtrlC() { process.stdout.write('(^C again to quit)'); close(); } function startUi() { // start readline ui input = readline.createInterface({ input: process.stdin, output: process.stdout, completer: autoComplete }); input.on('line', onLine); input.on('SIGINT', onCtrlC); } function onData(data) { process.stdout.write(data.toString()); } function connect(dev) { // connect to espruino esp = new SerialPort(dev, {}); esp.on('data', onData); connected = true; } function analyze(port, cb) { if (!connected) { var dev = port.comName, id = port.pnpId; console.log('Analyzing ' + dev + ' (' + id + ')'); if (id.match('Espruino') || id.match('STM32')) { console.log('Found compatible Espruino device! --^'); console.log('Connecting...'); startUi(); connect(dev); } else { console.log('No Espruino found, continuing. --^'); } } cb(null); } console.log('Searching for Espruino compatible device...'); serialport.list(readPorts);
JavaScript
0.000001
@@ -87,34 +87,136 @@ r re -adline = require('readline +pl = require('repl'), // https://github.com/joyent/node/blob/master/lib/repl.js%0A util = require('util'),%0A vm = require('vm '),%0A @@ -325,16 +325,59 @@ alPort,%0A + espruinoStub = require('./data/stub'),%0A conn @@ -412,16 +412,29 @@ s = %5B%5D,%0A + context,%0A inpu @@ -931,321 +931,554 @@ ion -close() %7B%0A input.close();%0A onLine('reset()') +write(code, context, file, cb) %7B%0A var err,%0A result ;%0A +%0A -esp.close();%0A%7D%0A%0Afunction autoComplete(line) %7B%0A +// strip repl's wrapping bs%0A code = code.replace(/%5E%5C(%7C%5Cn%5C)$/g, '');%0A%0A // first, create the Script object to check the syntax%0A try %7B%0A + var -completions = '.help .exit .quit .q'.split(' '),%0A hits = completions.filter(function(c) %7B return c.indexOf(line) == 0 %7D);%0A return %5Bhits.length ? hits : completions, line%5D%0A%7D%0A%0Afunction onLine(lin +script = vm.createScript(code, %7B%0A filename: file,%0A displayErrors: false%0A %7D);%0A %7D catch (e) %7B%0A // pass through unexpected end of input to handle multiline%0A if (e.name === 'SyntaxError' && /%5EUnexpected end of input/.test(e.message)) %7B%0A err = e;%0A %7D%0A %7D%0A%0A if (cod e) %7B @@ -1486,227 +1486,271 @@ + -switch (line) %7B%0A case '.help':%0A process.stdout.write('Help text!%5Cn');%0A break;%0A case '.q':%0A case '.quit':%0A case '.exit':%0A close();%0A break;%0A default:%0A + if (!err) %7B%0A try %7B%0A result = script.runInContext(context, %7BdisplayErrors: false%7D);%0A %7D catch (e) %7B%0A %7D%0A%0A // let autocomplete pass thru%0A result = context%5Bcode%5D;%0A if (!result) %7B%0A @@ -1771,18 +1771,18 @@ ite( -lin +cod e + '%5C -r +n ');%0A @@ -1793,325 +1793,271 @@ -break;%0A %7D%0A%7D%0A%0Afunction onCtrlC() %7B%0A process.stdout.write('(%5EC again to quit)');%0A close();%0A%7D%0A%0Afunction startUi() %7B%0A // start readline ui%0A input = readline.createInterface(%7B%0A input: process.stdin,%0A output: process.stdout,%0A completer: autoComplete%0A %7D);%0A input.on('line', onLine); + %7D%0A %7D%0A %7D%0A%0A cb(err, result);%0A%7D%0A%0Afunction startUi() %7B%0A // start readline ui%0A input = repl.start(%7Bprompt: %22%3E%22, useGlobal: true, useColors: true, ignoreUndefined: true, eval: write%7D);%0A%0A // replace context to get closer to espruino environment %0A @@ -2067,28 +2067,47 @@ put. +c on -('SIGINT', onCtrlC +text = vm.createContext(espruinoStub );%0A%7D @@ -2666,24 +2666,27 @@ -startUi( +connect(dev );%0A @@ -2688,35 +2688,32 @@ -connect(dev +startUi( );%0A %7D
94566feb4d0d66c97091282bd687e1589e6f4033
Corrige nome de uma variável.
index.js
index.js
'use strict'; function um(num) { var numeros = [ 'zero', 'um', 'dois', 'três', 'quatro', 'cinco', 'seis', 'sete', 'oito', 'nove' ]; return numeros[num]; } function dez(num) { if (num < 10) { return um(num); } var numeros = [ 'dez', 'onze', 'doze', 'treze', 'quatorze', 'quinze', 'dezesseis', 'dezessete', 'dezoito', 'dezenove', 'vinte', 'trinta', 'quarenta', 'cinquenta', 'sessenta', 'setenta', 'oitenta', 'noventa' ]; if (num < 20) { return numeros[num - 10]; } else { var n1 = numeros[(num - num % 10) / 10 + 8], n2 = num % 10; if (num % 10 === 0) { return n1; } else { return n1 + ' e ' + um(n2); } } } function cem(num) { if (num < 100) { return dez(num); } else if (num === 100) { return 'cem'; } else { var numeros = [ 'cento', 'duzentos', 'trezentos', 'quatrocentos', 'quinhentos', 'seissentos', 'setecentos', 'oitocentos', 'novecentos' ]; var n1 = numeros[(num - num % 100) / 100 - 1], n2 = num % 100; if (num % 100 === 0) { return n1; } else { return n1 + ' e ' + dez(n2); } } } function f(numero, sigular, plural, fun) { return function (num) { if (num === 1e3) { return 'mil'; } var n = (num - num % numero) / numero, n2; if (num < numero) { return fun(num); } else if (n === 1) { if (num === numero) { return 'um ' + sigular; } n2 = num % numero; if (num < 1e6) { if (n2 % 100 === 0 || n2 < 100) { return sigular + ' e ' + fun(n2); } else { return sigular + ' ' + fun(n2); } } else { if (n2 % 100 === 0 || n2 < 100) { return 'um ' + sigular + ' e ' + fun(n2); } else { return 'um ' + sigular + ' ' + fun(n2); } } } else { if (num % numero === 0) { return fun(n) + ' ' + plural; } else { var n1 = n; n2 = num % numero; if (n2 % 100 === 0 || n2 < 100) { return fun(n1) + ' ' + plural + ' e ' + fun(n2); } else { return fun(n1) + ' ' + plural + ' ' + fun(n2); } } } }; } var mil = f(1e+3, 'mil', 'mil', cem), milhao = f(1e+6, 'milhão', 'milhões', mil), bilhao = f(1e+9, 'bilhão', 'bilhões', milhao), trilhao = f(1e+12, 'trilhão', 'trilhões', bilhao), quadrilhao = f(1e+15, 'quadrilhão', 'quadrilhões', trilhao), quintilhao = f(1e+18, 'quintilhão', 'quintilhões', quadrilhao), sextilhao = f(1e+21, 'sextilhão', 'sextilhões', quintilhao), septilhao = f(1e+24, 'septilhão', 'septilhões', sextilhao), octilhao = f(1e+27, 'octilhão', 'octilhões', septilhao), nonilhao = f(1e+30, 'nonilhão', 'nonilhões', octilhao), decilhao = f(1e+33, 'decilhão', 'decilhões', nonilhao); module.exports = function (num) { if (typeof num === 'number' && !(num % 1) && num >= 0 && num < 1e+36) { return nonilhao(num); } else if (num) { return new Error('Número inválido.'); } else { return undefined; } };
JavaScript
0
@@ -1584,16 +1584,17 @@ mero, si +n gular, p @@ -1901,24 +1901,25 @@ n 'um ' + si +n gular;%0A @@ -2060,32 +2060,33 @@ return si +n gular + ' e ' + @@ -2148,16 +2148,17 @@ eturn si +n gular + @@ -2290,32 +2290,33 @@ eturn 'um ' + si +n gular + ' e ' + @@ -2386,16 +2386,17 @@ m ' + si +n gular +
4b6e393288853a1cf21bb92de29f9c18f7e7e02a
add load test
index.js
index.js
/** *@file index.js *@description 合并ajax请求 请求格式eg: *@author xtx1130 *@example: $.ajax({ url:'http://127.0.0.1:8086', type:'post', data:{ 0:{ url:'http://url', type:'get', data:'qipuId=1' }, 1:{ url:'http://url', type:'get', data:'qipuId=1' } }, success:function(data){ console.log(JSON.parse(data)) } }) *@tips:后台必须restful接口规则,规则相应修改见app/deps/httpRequest line 34 **/ 'use strict'; const koa = require('koa'); //const env = require('./config/index.js'); //middleware const midentryLog = require('./app/middleware/entryLog'); const res = require('./app/controller/res.js'); const combine = require('./app/middleware/interCombine'); const apis = require('./app/routes/apis'); const otherRouter = require('./app/routes/useless'); const rootRouter = require('./app/routes/rootRouter'); //const v8Router = require('./app/routes/v8test'); const helmet = require('koa-helmet'); const testing = require('testing'); const pHttp = require('./app/deps/promiseHttp'); const app = new koa(); let args = process.argv.slice(2); let port = (args[0] && /^\d+$/.test(args[0])) ? parseInt(args[0]) : 8031; //app.use(helmet()); //错误日志 let middleWare = [midentryLog,res,apis.routes(),combine,rootRouter.routes(),otherRouter.routes()]; let regester = (arg) => { arg.forEach(fn=>app.use(fn)) } regester(middleWare) // app.use(midentryLog); // //res 500 404 200 option 以及跨域头 // app.use(res); // //app.use(v8Router.routes(), v8Router.allowedMethods()); // app.use(apis.routes()); // app.use(apis.allowedMethods()) // app.use(combine); // app.use(rootRouter.routes()); // app.use(rootRouter.allowedMethods()); // app.use(otherRouter.routes()); // app.use(otherRouter.allowedMethods()) let mainApp = app.listen(port); //testing let testStartServer = async callback =>{ let options = { port: 10531, }; regester(middleWare) let server = app.listen(options.port); let reqGetSuccess = await pHttp({port:'10531',path:'/apis',method:'get',timeout:500}); let reqGetReject = await pHttp({port:'10531',path:'/',method:'get',timeout:500}); let reqPostSuccess = await pHttp({port:'10531',path:'/apis',method:'post',timeout:500}); let reqPostReject = await pHttp({port:'10531',path:'/',method:'post',timeout:500}); try{ let reqErr = await pHttp({port:'10530',path:'/',method:'post',timeout:500}); }catch(e){ testing.verify(e, 'this must throw error', callback); } testing.verify(reqGetSuccess.httpStatusCode==200,reqGetSuccess.httpStatusCode+'not 200',callback); testing.verify(reqGetReject.httpStatusCode==404,reqGetReject.httpStatusCode+'not 404',callback); testing.verify(reqPostSuccess.httpStatusCode==200,reqPostSuccess.httpStatusCode+'not 200',callback); testing.verify(reqPostReject.httpStatusCode==404,reqPostReject.httpStatusCode+'not 404',callback); server.close(function(error){ testing.check(error, 'Could not stop server', callback); testing.success(callback); }); mainApp.close(); } module.exports.test = testStartServer; console.log(`Server up and running! On port ${port}!`);
JavaScript
0.000001
@@ -1,11 +1,12 @@ /** +1 %0A *@file
b97e0dc7a97b9ed76bd9e376b8c2e2fe28c929c8
Add options for exact or g regex
index.js
index.js
'use strict'; module.exports = function() { return new RegExp('^\\s*(?:\\+?(\\d{1,3}))?[-. (]*(\\d{3})[-. )]*(\\d{3})[-. ]*(\\d{4})(?: *x(\\d+))?\\s*$'); }
JavaScript
0.000001
@@ -38,34 +38,65 @@ ion( -) %7B%0A return new RegExp('%5E +options) %7B%0A options = options %7C%7C %7B%7D;%0A var regexBase = ' %5C%5Cs* @@ -180,9 +180,122 @@ %5C%5Cs* -$ +';%0A%0A return options.exact ? new RegExp('%5E' + regexBase + '$') :%0A new RegExp(regexBase, 'g ');%0A
ee03843f84a84ce36b26c32ff89b4c5d7dad13f0
remove extra space
index.js
index.js
var app = require('./src'); var port = process.env.PORT || 5000; app.listen(port); console.log("Linx API server listening on port ", port); module.exports = app;
JavaScript
0.002319
@@ -125,17 +125,16 @@ on port - %22, port)
698a66400593281a6c97a3f69643d7f6ddaa3301
remove unneeded Promise.all()
index.js
index.js
/* jslint node: true, esnext: true */ "use strict"; const AdpaterInboundFileFactory = require('./lib/adapter-inbound-file'); exports.adpaterInboundFile = AdpaterInboundFileFactory; exports.registerWithManager = manager => Promise.all([ manager.registerStep(AdpaterInboundFileFactory) ]);
JavaScript
0.000001
@@ -31,17 +31,17 @@ true */%0A -%22 +' use stri @@ -46,9 +46,9 @@ rict -%22 +' ;%0A%0Ac @@ -222,23 +222,8 @@ =%3E -Promise.all(%5B%0A%09 mana @@ -269,9 +269,6 @@ ory) -%0A%5D) ;%0A
a304e6d5d0706d03fc664634a058325cfab099d0
delete console.log
app/static/js/edit.js
app/static/js/edit.js
$(document).ready(function() { playground({ 'codeEl': '#code', 'outputEl': '#output', 'runEl': '#run', 'fmtEl': '#fmt', 'fmtImportEl': '#imports', 'shareEl': '#share', 'shareURLEl': '#shareURL', 'enableHistory': true }); playgroundEmbed({ 'codeEl': '#code', 'shareEl': '#share', 'embedEl': '#embed', 'embedLabelEl': '#embedLabel', 'embedHTMLEl': '#shareURL' }); $('#code').linedtextarea(); // login $('#loginButton').click(function() { $.ajax({ url: "/save", type: "POST", data: $("#code").val() }) .done(function(data, textStatus, jqXHR) { location.href = data; }); }); // open post gist modal $("#postGistModalButton").click(function() { if (typeof Cookies.get("access_token") === "undefined") { $("#loginAlertModal").modal("show"); } else { $("#postGistModal").modal("show"); } }); // create gist $("#postGistButton").click(function() { $.ajax({ url: "/gist", type: "POST", data: JSON.stringify({ description: $("#description").val(), public: $("#public").prop("checked"), file_name: $("#fileName").val(), code: $("#code").val() }) }) .done(function(data, textStatus, jqXHR) { $("#postGistModal").modal("hide"); $("#postGistDoneModal a#gistLink").attr("href", data); $("#postGistDoneModal a#gistLink").text(data); $("#postGistDoneModal").modal("show"); console.log(data); console.log(textStatus); console.log(jqXHR); }) .fail(function(jqXHR, textStatus, errorThrown) { $("#postGistFailModal").modal("show"); console.log(jqXHR); console.log(textStatus); console.log(errorThrown); }); }); // Avoid line wrapping. $('#code').attr('wrap', 'off'); var about = $('#about'); about.click(function(e) { if ($(e.target).is('a')) { return; } about.hide(); }); $('#aboutButton').click(function() { if (about.is(':visible')) { about.hide(); return; } about.show(); }); // Preserve "Imports" checkbox value between sessions. if (readCookie('playgroundImports') == 'true') $('#imports').attr('checked','checked'); $('#imports').change(function() { createCookie('playgroundImports', $(this).is(':checked') ? 'true' : ''); }); // Fire Google Analytics events for Run/Share button clicks. if (window.trackEvent) { $('#run').click(function() { window.trackEvent('playground', 'click', 'run-button'); }); $('#share').click(function() { window.trackEvent('playground', 'click', 'share-button'); }); } }); function createCookie(name, value) { document.cookie = name+"="+value+"; path=/"; } function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; }
JavaScript
0.000007
@@ -1430,84 +1430,8 @@ %22);%0A -%09%09%09%09console.log(data);%0A%09%09%09%09console.log(textStatus);%0A%09%09%09%09console.log(jqXHR);%0A %09%09%09%7D @@ -1531,91 +1531,8 @@ %22);%0A -%09%09%09%09console.log(jqXHR);%0A%09%09%09%09console.log(textStatus);%0A%09%09%09%09console.log(errorThrown);%0A %09%09%09%7D
50443f9afce31d8a7bfe4e663e42e04702820441
Use full gain on the sine/cosine waves
index.js
index.js
'use strict' var debug = require('debug')('monster-drift') delete process.env.DEBUG // hackrf doesn't like this flag var devices = require('hackrf')() var ook = require('./lib/ook') var commands = require('./lib/commands') module.exports = MonsterDrift function MonsterDrift (opts) { if (!(this instanceof MonsterDrift)) return new MonsterDrift() if (!opts) opts = {} this._freq = opts.freq || 27143550 // probably channel 19: 27.145 (yellow) this._index = 0 this._stream = null this._speed = opts.speed || 1 this._inversed = opts.swaplr || false this._stopIn = opts.stop || null this._stopTimer = null var encode = ook({ freq: this._freq, gain: 32, symbolPeriod: 0.4638 }) var self = this this._signal = {} Object.keys(commands).forEach(function (key) { var cmd = commands[key] self._signal[key] = encode(Array(100).join(cmd[0])) self._signal[key].name = cmd[1] }) this._device = devices.open(opts.id || 0) this._device.setTxGain(opts.gain || 30) // TX VGA (IF) gain, 0-47 dB in 1 dB steps this._device.setFrequency(this._freq) } MonsterDrift.prototype.turn180 = function (cb) { this.batch([ [this.forward, 1000], [this.right, 125], [this.reverseLeft, 100], [this.reverse, 1000] ], cb) } MonsterDrift.prototype._start = function () { var self = this debug('starting') this._device.startTx(function (buf, cb) { var i if (self._stream) { for (i = 0; i < buf.length; i++) { buf[i] = self._stream[self._index++] if (self._index === self._stream.length) self._index = 0 } } else { for (i = 0; i < buf.length; i++) buf[i] = 0 } cb() }) } MonsterDrift.prototype.stop = function (cb) { if (!this._stream) return cb ? cb() : null debug('stopping') this._stream = null this._device.stopTx(function () { debug('stopped!') if (cb) cb() }) } MonsterDrift.prototype.close = function (cb) { var self = this this.stop(function () { self._device.close(cb) }) } MonsterDrift.prototype.forward = function (speed) { switch (speed || this._speed) { case 3: return this._drive(this._signal.fff) case 2: return this._drive(this._signal.ff) default: this._drive(this._signal.f) } } MonsterDrift.prototype.forwardLeft = function () { this._drive(this._inversed ? this._signal.fr : this._signal.fl) } MonsterDrift.prototype.forwardRight = function () { this._drive(this._inversed ? this._signal.fl : this._signal.fr) } MonsterDrift.prototype.reverse = function () { this._drive(this._signal.r) } MonsterDrift.prototype.reverseLeft = function () { this._drive(this._inversed ? this._signal.rr : this._signal.rl) } MonsterDrift.prototype.reverseRight = function () { this._drive(this._inversed ? this._signal.rl : this._signal.rr) } MonsterDrift.prototype.right = function () { this._drive(this._inversed ? this._signal.wl : this._signal.wr) } MonsterDrift.prototype.left = function () { this._drive(this._inversed ? this._signal.wr : this._signal.wl) } MonsterDrift.prototype.batch = function (commands, cb) { var self = this next() function next (i) { var command = commands[i || 0] if (!command) return self.stop(cb) var fn = commands[0] var ms = commands[1] fn.call(self) if (ms) { setTimeout(function () { next(++i) }, ms) } else if (cb) { cb() } } } MonsterDrift.prototype._drive = function (s) { debug(s.name) if (this._stopTimer) clearTimeout(this._stopTimer) if (this._stream === s) return else if (!this._stream) this._start() debug('new direction') this._index = 0 this._stream = s if (this._stopIn) { var self = this this._stopTimer = setTimeout(function () { self.stop() }, this._stopIn) } }
JavaScript
0.000001
@@ -677,10 +677,11 @@ in: -32 +127 ,%0A
0b232e0f71c1f08a73d6942c97377c603a8e97d7
Fix SafeBuffer.from() to throw when passed a number
index.js
index.js
var buffer = require('buffer') if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { module.exports = buffer } else { // Copy properties from require('buffer') Object.keys(buffer).forEach(function (prop) { exports[prop] = buffer[prop] }) exports.Buffer = SafeBuffer } function SafeBuffer (arg, encodingOrOffset, length) { return Buffer(arg, encodingOrOffset, length) } // Copy static methods from Buffer Object.keys(Buffer).forEach(function (prop) { SafeBuffer[prop] = Buffer[prop] }) SafeBuffer.from = function (arg, encodingOrOffset, length) { if (typeof value === 'number') { throw new TypeError('Argument must not be a number') } return Buffer(arg, encodingOrOffset, length) } SafeBuffer.alloc = function (size, fill, encoding) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } var buf = Buffer(size) if (fill !== undefined) { if (typeof encoding === 'string') { buf.fill(fill, encoding) } else { buf.fill(fill) } } else { buf.fill(0) } return buf } SafeBuffer.allocUnsafe = function (size) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } return Buffer(size) } SafeBuffer.allocUnsafeSlow = function (size) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } return buffer.SlowBuffer(size) }
JavaScript
0.000001
@@ -607,13 +607,11 @@ eof -value +arg ===
ea615f1e0c4ff0200f28a681971f6d883c9163d2
Use strictEqual in test.js
app/templates/test.js
app/templates/test.js
'use strict'; var assert = require('assert'); var <%=camelize(props.project)%> = require('./index.js'); it('should do something', function () { assert.equals(true, false); });
JavaScript
0.000002
@@ -150,14 +150,19 @@ ert. -e +strictE qual -s (tru
c78d3dd455311f0bef1f29b8ea4c35b70158cb1e
Update signal check on child process exit
index.js
index.js
'use strict'; var Promise = require('bluebird'); var PriorityQueue = require('js-priority-queue'); var cp = require('child_process'); var uuid = require('uuid'); var _ = require('lodash'); var Tadpole = (function () { //Private Variables var _initialized = false, _options, _addsPending = 0, _toRemove = 0, _addResolver; /* numChildren: In a single core environment, we'll still use one thread and let the OS manage resources. In a multicore environment, we'll leave one core for Node and use the rest for child threads. */ var _defaultOptions = { numChildren: require('os').cpus().length -1 || 1, priority: true, addTimout: 30000, env: process.ENV, respawn: true }; var _functionDefaults = { priority: 100, }; /* A container for our child threads. */ var _children = {}; /* This object is mainly for holding the resolver functions, but also keeps a record of each payload. */ var _inProcess = {}; var _functions = {}; var _queue = new PriorityQueue({comparator: function(a,b){ return a.priority - b.priority;}}); return { spawn: function(userOptions){ if (_initialized) throw new Error('Cannot re-initialize Tadpole.'); userOptions = userOptions || {}; _.defaults(userOptions, _defaultOptions); _options = userOptions; for (var i = 0; i < userOptions.numChildren; i++){ addChild(); } _initialized = true; }, addFunction: function(functionObject) { if (_addsPending > 0) throw new Error('Cannot add another function until previous add has completed.'); if (_functions[functionObject.name]) throw new Error('Already added a function with that name.'); if (functionObject.priority < 1) throw new Error('Priority less than 1 reserved for module use.'); if (!functionObject.func || !functionObject.name) throw new Error('Function object must contain both function and name.'); _.defaults(functionObject, _functionDefaults); functionObject.func = stringifyFunction(functionObject.func); //dehydrate the function functionObject.action = 'ADDFUNC'; _functions[functionObject.name] = functionObject; _.each(_children, function(child){ injectFunction(functionObject, child); }); return new Promise(function(resolve, reject){ _addResolver = resolve; //TODO: reject if timeout elapses }); }, run: function(name, args){ return new Promise(function(resolve, reject){ request({action: name, priority: _functions[name].priority, args: args, resolver: resolve, rejecter: reject }); }); }, remove: function(num){ if (num < 1) throw new Error('Must provide value greater than 0 to remove.'); num = num || 1; if (num > this.size()) num = this.size(); while(num){ _toRemove++; if(!_queue.length) killChild(); num--; } }, add: function(num){ num = num || 1; while(num){ injectAllFunctions(addChild()); num--; } }, size: function(){ return Object.keys(_children).length; }, killAll: function(){ if (_initialized){ this.remove(this.size()); _functions = {}; _initialized = false; } } }; //Private functions. function stringifyFunction (func) { return '(' + func + ')'; } /* This function is used by the module methods to process the result of each child thread action, and then get the next action from the queue. */ function next (childId, payload) { //use the IDs to retrieve the payload from our storage in this thread var sentPayload = _inProcess[payload.id]; if (payload.error){ sentPayload.rejecter(payload.error); return; } if (sentPayload.action === 'ADDFUNC') { _addsPending--; if (_addsPending === 0) _addResolver(true); } else { sentPayload.resolver(payload.result); //resolve those promises! } delete _inProcess[payload.id]; //no memory leaks please //take this child out of service if we want to decrement running processes if (_toRemove) { killChild(childId); return; } try{ var nextPayload = _queue.dequeue(); _inProcess[nextPayload.id] = nextPayload; _children[childId].child.send(nextPayload); } catch(err){ //empty queue throws error _children[childId].active = false; //if the queue is empty, this child can rest } } function setId(payload){ payload.id = uuid.v4(); } function request (payload){ setId(payload); if (_queue.length){ // if the queue is full, just enqueue the payload _queue.queue(payload); } else { //otherwise, let's find this payload a home! var slotted = false; _.each(_children, function(child, key){ if (!child.active){ _inProcess[payload.id] = payload; child.active = true; child.thread.send(payload); slotted = true; return false; //if we've found a home, we stop the each loop } }); if (!slotted) _queue.queue(payload); //in case the queue was empty, but all the threads were working } } function addChild(id){ id = id || uuid.v4(); var child = cp.fork(__dirname + '/child.js', {env: _options.env, execArgv: []}); child.on('error', function(error){ console.error('Error in child process: ' + error); }); //when we get the result of reach transaction, this function is called to get the next operation in the queue child.on('message', function(payload){ next(id, payload); }); if (_options.respawn) { child.on('exit', function(code, signal){ if (!signal === 'SIGTERM'){ addChild(id); injectAllFunctions(child); } }); } var container = {thread: child, id: id, active: false}; _children[id] = container; return id; } function injectFunction(functionObject, child){ _addsPending++; setId(functionObject); new Promise(function(resolve, reject) { functionObject.resolver = resolve; functionObject.rejecter = reject; _inProcess[functionObject.id] = functionObject; child.thread.send(functionObject); }); } function injectAllFunctions(child){ if (!_addsPending){ _.each(_functions, function(functionObject){ injectFunction(functionObject, child); }); } else setTimeout(function(){ injectAllFunctions(child); }, 500); } function killChild(childId){ if (childId){ _children[childId].thread.kill(); delete _children[childId]; _toRemove--; } else { _.each(_children, function(child){ if (!child.active){ killChild(child.id); return false; //we can stop once we get one } }); // we haven't killed the child, but there is still a value in _toRemove, so it should be killed when it finishes what it's working on } } })(); module.exports = Tadpole;
JavaScript
0
@@ -5878,17 +5878,16 @@ if ( -! signal -= +! == ' @@ -7209,8 +7209,9 @@ Tadpole; +%0A
341a926419f625a64f09db044e69942d81314433
Add readable stream
index.js
index.js
import request from 'request'; import cheerio from 'cheerio'; export function sendInitialQuery(query, callback) { if (!query.year) { return process.nextTick(callback, new Error('query.year is not provided')); } const j = request.jar(); const INITIAL_URL = `http://${query.ip}/alis/EK/do_searh.php?radiodate=simple&valueINP=${query.year}&tema=1&tag=6`; request({ url: INITIAL_URL, jar: j }, (err, response, body) => { if (err) { callback(err); return; } callback(null, { page: body, jar: j }); }); } export function getPage(url, jug, callback) { request({ url, jar: jug }, (err, response, body) => { if (err) { return callback(err); } callback(null, body); }); } export function getNextPageUrl($) { const pageLink = $('#Agt'); const pageUrl = (`${$(pageLink).attr('href')}`); return pageUrl; } export function getBooks($) { return $('.article').each(function () { ReadableStreamBooks.push($(this).text()); }); } export function getNumberedPageUrls(page, ip) { const $ = cheerio.load(page); const firstTenPageLinks = $('a[href^=\'do_other\']'); const firstTenPageUrls = $(firstTenPageLinks).map((i, link) => `http://${ip}/alis/EK/${$(link).attr('href')}`).toArray(); return firstTenPageUrls; } export function run(fn, q, ip, jar) { if (q.length === 0) { return ReadableStreamBooks.push(null); } fn(q[0], jar, (err, page) => { if (err) { return err; } const $ = cheerio.load(page); getBooks($); const nextPageUrl = getNextPageUrl($); if (nextPageUrl === 'undefined') { return ReadableStreamBooks.push(null); } const remainingQueue = q.slice(1); if (q.length === 1) { remainingQueue.push(`http://${ip}/alis/EK/${nextPageUrl}`); } run(fn, remainingQueue, ip, jar); }); }
JavaScript
0.000008
@@ -54,16 +54,142 @@ heerio'; +%0Aimport Stream from 'stream';%0A%0Aexport const ReadableStreamBooks = new Stream.Readable();%0AReadableStreamBooks._read = () =%3E %7B%7D; %0A%0Aexport
3b64740ef9027c174fa24ce23b39f9d6ca76309a
remove unnecessary code
index.js
index.js
'use strict'; var debug = require('debug')('prompt-list'); var Radio = require('prompt-radio'); var cyan = require('ansi-cyan'); var dim = require('ansi-dim'); /** * List prompt */ function List(question, answers, ui) { debug('initializing from <%s>', __filename); Radio.apply(this, arguments); this.listInitialized = false; this.question.type = 'list'; this.default = question.default; this._when = question.when; this.on('ask', this.onAsk.bind(this)); this.on('render', () => { if (this.contextHistory.length > 0) this.helpMessage = ''; }); } /** * Inherit Radio */ Radio.extend(List); /** * Render a choice. */ List.prototype.onAsk = function() { if (this.listInitialized) return; this.listInitialized = true; this.helpMessage = this.options.helpMessage || dim('(Use arrow keys)'); this.choices.options.checkbox = false; this.choices.options.format = this.renderChoice(this.choices); }; /** * Render a choice. */ List.prototype.renderChoice = function(choices) { return function(line) { return choices.position === choices.index ? cyan(line) : line; }; }; /** * Render final selected answer when "line" ("enter" keypress) * is emitted */ List.prototype.renderAnswer = function() { return cyan(this.getAnswer()); }; /** * Get selected list item */ List.prototype.getAnswer = function() { return this.choices.key(this.position); }; /** * overriding "when" function to avoid setting a value when there * is not a default value and the question was not asked */ List.prototype.when = function() { if (this._when && !this._when.apply(this, arguments)) { this.position = this.default === undefined ? -1 : this.default; return false; } return true; }; /** * Module exports */ module.exports = List;
JavaScript
0.00242
@@ -364,75 +364,8 @@ t';%0A -%0A this.default = question.default;%0A this._when = question.when;%0A%0A th @@ -1504,33 +1504,66 @@ %7B%0A -if (this._when && !this._ +var that = this;%0A return Promise.resolve(Radio.prototype. when @@ -1590,19 +1590,46 @@ ts)) +%0A .then(function(when) %7B%0A -this + that .pos @@ -1642,43 +1642,39 @@ = th -is.default === undefined ? -1 : thi +at.choices.getIndex(that.option s.de @@ -1678,18 +1678,21 @@ .default +) ;%0A + retu @@ -1698,32 +1698,20 @@ urn -false;%0A %7D%0A return true +when;%0A %7D) ;%0A%7D;
df46c56adfc09dc634dfe00a1f1616c0a86c3c9d
add plugin.expose to rethinkdb as documented
index.js
index.js
'use strict'; var rethink = require('rethinkdb'); exports.register = function (plugin, opts, next) { opts = opts || {}; if (!opts.url) { opts.port = opts.port || 28015; opts.host = opts.host || 'localhost'; opts.db = opts.db || 'test'; } else { var url = require('url').parse(opts.url); opts.port = parseInt(url.port) || 28015; opts.host = url.hostname || 'localhost'; opts.db = url.pathname ? url.pathname.replace(/^\//, '') : 'test'; if (url.auth) opts.authKey = url.auth.split(':')[1]; } rethink.connect(opts, function (err, conn) { if (err) { plugin.log(['hapi-rethinkdb', 'error'], err.message); console.error(err); return next(err); } plugin.expose('connection', conn); plugin.expose('library', rethink); plugin.bind({ rethinkdbConn: conn, rethinkdb: rethink }); plugin.log(['hapi-rethinkdb', 'info'], 'RethinkDB connection established'); return next(); }); }; exports.register.attributes = { pkg: require('./package.json') };
JavaScript
0
@@ -791,16 +791,57 @@ think);%0A + plugin.expose('rethinkdb', rethink);%0A plug
b99e4d691373bdbf01c2585597a1c635d8dad61e
fix index.js style
index.js
index.js
var fs = require('fs') var path = require('path') var stripComments = require('strip-json-comments') var filename = path.join(__dirname, '.eslintrc') var data = fs.readFileSync(filename, {encoding: 'utf-8'}) var dataWithoutComments = stripComments(data) var parsed = JSON.parse(dataWithoutComments) module.exports = parsed
JavaScript
0.000176
@@ -1,12 +1,27 @@ +'use strict';%0A%0A var fs = req @@ -30,16 +30,17 @@ re('fs') +; %0Avar pat @@ -58,16 +58,17 @@ ('path') +; %0Avar str @@ -110,16 +110,17 @@ mments') +; %0A%0Avar fi @@ -161,16 +161,17 @@ lintrc') +; %0Avar dat @@ -219,13 +219,13 @@ 'utf -- 8'%7D) +; %0Avar @@ -266,16 +266,17 @@ ts(data) +; %0Avar par @@ -312,16 +312,17 @@ omments) +; %0A%0Amodule @@ -338,9 +338,10 @@ = parsed +; %0A
d74c9dbf5d71d02efe6c6c5074e57b09f9e7059d
Add ALLOW_RELEASE_CANDIDATE_TAG env option
index.js
index.js
#! /usr/bin/env node require('dotenv').config({ path: `${ process.env.PWD }/.env` }) const standardChangelog = require('standard-changelog') , conventionalGithubReleaser = require('conventional-github-releaser') , bump = require('bump-regex') , inquirer = require('inquirer') , fs = require('fs') , q = require('q') , exec = require('child_process').exec , concatStream = require('concat-stream') const PACKAGE_PATH = `${ process.env.PWD }/package.json` , CHANGELOG_PATH = `${ process.env.PWD }/CHANGELOG.md` , RC_PREID = process.env.RELEASE_CANDIDATE_PREID || 'rc' const VERSION = require(PACKAGE_PATH).version function get_all_versions() { const opts = { str: fs.readFileSync(PACKAGE_PATH).toString() } return q.all([ q.nfcall(bump, Object.assign({ type: 'prerelease', preid: RC_PREID }, opts)), q.nfcall(bump, Object.assign({ type: 'patch' }, opts)), q.nfcall(bump, Object.assign({ type: 'minor' }, opts)), q.nfcall(bump, Object.assign({ type: 'major'}, opts)) ]) .spread((rc, patch, minor, major) => { return { rc, patch, minor, major } }) } function prompt(versions) { return inquirer.prompt([ { name: "version", type: "list", choices: [{ name: `release-candidate (${ versions.rc.new })`, value: versions.rc }, { name: `patch (${ versions.patch.new })`, value: versions.patch }, { name: `minor (${ versions.minor.new })`, value: versions.minor }, { name: `major (${ versions.major.new })`, value: versions.major }, { name: `cancel`, value: null }], default: versions.patch, message: "What kind of release is it?" } ]) .then(({ version }) => { if (!version) process.exit(0) return version }) } function bump_version(version) { return q.nfcall(fs.writeFile, PACKAGE_PATH, version.str) .then(() => version) } function changelog(version) { standardChangelog.createIfMissing(CHANGELOG_PATH) if (version.preid === RC_PREID && !process.env.ALLOW_RELEASE_CANDIDATE_CHANGELOG) { return version } let defer = q.defer() let file = fs.readFileSync(CHANGELOG_PATH) standardChangelog() .pipe(concatStream({ encoding: 'buffer'}, (data) => { fs.writeFileSync(CHANGELOG_PATH, Buffer.concat([data, file])) defer.resolve(version) })) return defer.promise } function git_commit(version) { let defer = q.defer() exec([ 'git add package.json CHANGELOG.md', `git commit -a -m "chore(release): v${ version.new }"` ].join(' && '), (err) => { if (err) return defer.reject(err) defer.resolve(version) }) return defer.promise } function git_push(version) { let defer = q.defer() exec('git push', (err) => { if (err) return defer.reject(err) defer.resolve(version) }) return defer.promise } function git_tag(version) { if (version.preid === RC_PREID) return version let defer = q.defer() exec([ 'git fetch --tags', `git tag ${ version.new }`, 'git push --tags' ].join(' && '), (err) => { if (err) return defer.reject(err) defer.resolve(version) }) return defer.promise } function github_release(version) { if (version.preid === RC_PREID) return version if (!process.env.GITHUB_OAUTH_TOKEN) { console.log('Cannot run conventionalGithubReleaser. You must add a .env file with a GITHUB_OAUTH_TOKEN key') return version } const GITHUB_AUTH = { type: 'oauth', token: process.env.GITHUB_OAUTH_TOKEN } return q.nfcall(conventionalGithubReleaser, GITHUB_AUTH, { preset: 'angular' }) } function notify(msg, optional) { return (version) => { if (optional && version.preid === RC_PREID) return version console.log(msg.replace('$$version', version.new)) return version } } get_all_versions() .then(prompt) .then(notify('- Update package.json with version: $$version')) .then(bump_version) .then(notify('- Update changelog', !process.env.ALLOW_RELEASE_CANDIDATE_CHANGELOG)) .then(changelog) .then(notify('- git commit')) .then(git_commit) .then(notify('- git push')) .then(git_push) .then(notify('- git tag', true)) .then(git_tag) .then(notify('- Github release', true)) .then(github_release) .catch((err) => console.log(err))
JavaScript
0.000002
@@ -3230,33 +3230,87 @@ eid === RC_PREID -) + && !process.env.ALLOW_RELEASE_CANDIDATE_TAG) %7B%0A return version%0A @@ -3305,24 +3305,30 @@ urn version%0A + %7D%0A let defe @@ -4596,20 +4596,56 @@ t tag', -true +!process.env.ALLOW_RELEASE_CANDIDATE_TAG ))%0A.then
6b7effa076c38a4843c1be98f68a34ff5b599a36
Add a start parameter to get event only from a specific date
index.js
index.js
"use strict"; var https = require("https"); var xmljs = require("libxmljs"); module.exports = { /** * Get a list of Folders/Calendars from a given url * * @param {String} url * @param {String} user * @param {String} pass * @param {function} cb */ getList: function (url, user, pass, cb) { var urlparts = /(https?)\:\/\/(.*?):?(\d*)?(\/.*\/?)/gi.exec(url); var protocol = urlparts[1]; var host = urlparts[2]; var port = urlparts[3] || (protocol === "https" ? 443 : 80); var path = urlparts[4]; var xml = '<?xml version="1.0" encoding="utf-8" ?>\n' + ' <D:propfind xmlns:D="DAV:" xmlns:C="http://calendarserver.org/ns/">\n' + ' <D:prop>\n' + ' <D:displayname />\n' + ' </D:prop>\n' + ' </D:propfind>'; var options = { rejectUnauthorized: false, hostname : host, port : port, path : path, method : 'PROPFIND', headers : { "Content-type" : "text/xml", "Content-Length": xml.length, "User-Agent" : "calDavClient", "Connection" : "close", "Depth" : "1" } }; if (user && pass) { var userpass = new Buffer(user + ":" + pass).toString('base64'); options.headers["Authorization"] = "Basic " + userpass; } var req = https.request(options, function (res) { var s = ""; res.on('data', function (chunk) { s += chunk; }); req.on('close', function () { var reslist = []; try { var xmlDoc = xmljs.parseXml(s); // console.log(xmlDoc.toString() ); var resp = xmlDoc.find("a:response", { a: 'DAV:'}); for (var i in resp) { var el = resp[i]; var href = el.get("a:href", { a: 'DAV:'}); var dspn = el.get("a:propstat/a:prop/a:displayname", { a: 'DAV:'}); if (dspn) { var resobj = {}; resobj.displayName = dspn.text(); resobj.href = href.text(); reslist.push(resobj); } } } catch (e) { console.log("Error parsing response") } cb(reslist); }); }); req.end(xml); req.on('error', function (e) { console.log('problem with request: ' + e.message); }); }, /** * Get a list of Events from a given Calendarurl * * @param {String} url * @param {String} user * @param {String} pass * @param {function} cb */ getEvents: function (url, user, pass, cb) { var urlparts = /(https?)\:\/\/(.*?):?(\d*)?(\/.*\/?)/gi.exec(url); var protocol = urlparts[1]; var host = urlparts[2]; var port = urlparts[3] || (protocol === "https" ? 443 : 80); var path = urlparts[4]; var xml = '<?xml version="1.0" encoding="utf-8" ?>\n' + '<C:calendar-query xmlns:D="DAV:" xmlns:C="urn:ietf:params:xml:ns:caldav">\n' + ' <D:prop>\n' + ' <C:calendar-data/>\n' + ' </D:prop>\n' + ' <C:filter>\n' + ' <C:comp-filter name="VCALENDAR">\n' + ' <C:comp-filter name="VEVENT">\n' + ' <C:time-range start="20140617T112033Z"/>\n' + ' </C:comp-filter>\n' + ' </C:comp-filter>\n' + ' </C:filter>\n' + '</C:calendar-query>'; var options = { rejectUnauthorized: false, hostname : host, port : port, path : path, method : 'REPORT', headers : { "Content-type" : "text/xml", "Content-Length": xml.length, "User-Agent" : "calDavClient", "Connection" : "close", "Depth" : "1" } }; if (user && pass) { var userpass = new Buffer(user + ":" + pass).toString('base64'); options.headers["Authorization"] = "Basic " + userpass; } var req = https.request(options, function (res) { var s = ""; res.on('data', function (chunk) { s += chunk; }); req.on('close', function () { var reslist = []; try { var xmlDoc = xmljs.parseXml(s); // console.log(xmlDoc.toString() ); var data = xmlDoc.find("a:response/a:propstat/a:prop/c:calendar-data", { a: 'DAV:', c: "urn:ietf:params:xml:ns:caldav" }); for (var i in data) { var ics = data[i].text(); var evs = ics.match(/BEGIN:VEVENT[\s\S]*END:VEVENT/gi); for (var x in evs) { var evobj = {}; var evstr = evs[x]; evstr = evstr.split("\n"); for (var y in evstr) { var evpropstr = evstr[y]; if (evpropstr.match(/BEGIN:|END:/gi)) { continue; } var sp = evpropstr.split(":"); var key = sp[0]; var val = sp[1]; if (key && val) { evobj[key] = val; } } reslist.push(evobj) } } cb(reslist); } catch (e) { console.log("Error parsing response") } }); }); req.end(xml); req.on('error', function (e) { console.log('problem with request: ' + e.message); }); } };
JavaScript
0
@@ -2545,32 +2545,101 @@ %7BString%7D pass%0A + * @param %7BString%7D date from which to start like 20140617T112033Z%0A * @param %7Bfu @@ -2687,32 +2687,39 @@ url, user, pass, + start, cb) %7B%0A%0A var @@ -3321,32 +3321,25 @@ start=%22 -20140617T112033Z +'+start+' %22/%3E%5Cn' + @@ -5472,8 +5472,9 @@ %0A%0A %7D%0A%7D; +%0A
f967eab11e2877d3504ccd6b36e1da45c92d4ddb
Fix jslint errors
index.js
index.js
/*jslint indent: 2 */ /*global console: true, require: true, exports */ var EventEmitter = require('events').EventEmitter; var GoogleClientLogin = require('googleclientlogin').GoogleClientLogin; var util = require('util'); var querystring = require('querystring'); const contactsUrl = '/m8/feeds/contacts/', contactGroupsUrl = '/m8/feeds/groups/', typeContacts = 'contacts', typeGroups = 'groups', projectionThin = 'thin'; var GoogleContacts = function (conf) { var contacts = this; this.conf = conf || {}; this.conf.service = 'contacts'; }; GoogleContacts.prototype = {}; util.inherits(GoogleContacts, EventEmitter); GoogleContacts.prototype.auth = function (cb) { if (!this.googleAuth) { this.googleAuth = new GoogleClientLogin(this.conf); this.googleAuth.on('login', function () { this.isLoggedIn = true; }.bind(this)); } if (!this.isLoggedIn) { this.googleAuth.on('login', function () { cb(); }.bind(this)); this.googleAuth.on('error', function () { this.emit('error', 'login failed'); }); this.googleAuth.login(); } else { cb(); } }, GoogleContacts.prototype.getContacts = function (params) { this.auth(function () { this._getContacts(params); }.bind(this)); }; GoogleContacts.prototype.getContactGroups = function (projection, limit) { this.auth(function () { this._getContactGroups(projection, limit); }.bind(this)); }; GoogleContacts.prototype._onContactsReceived = function (response, data) { this.contacts = JSON.parse(data); this.emit('contactsReceived', this.contacts); }; GoogleContacts.prototype._onContactGroupsReceived = function (response, data) { this.contactGroups = JSON.parse(data); this.emit('contactGroupsReceived', this.contactGroups); }; GoogleContacts.prototype._onResponse = function (request, response) { var data = '', finished = false; // Thats a hack, because the end event is not emitted, but close yes. // https://github.com/joyent/node/issues/728 var onFinish = function () { if (!finished) { finished = true; if (response.statusCode >= 200 && response.statusCode < 300) { if (request.path.indexOf(contactsUrl) === 0) { this._onContactsReceived(response, data); } else if (request.path.indexOf(contactGroupsUrl) === 0) { this._onContactGroupsReceived(response, data); } } else { var error = new Error('Bad response status: ' + response.statusCode); this.emit('error', error); } } }.bind(this); response.on('data', function (chunk) { data += chunk; }); response.on('error', function (e) { this.emit('error', e); }.bind(this)); response.on('close', onFinish); response.on('end', onFinish); }; GoogleContacts.prototype._buildPath = function (type, params) { var path, request; params = params || {}; params.alt = 'json'; var projection = projectionThin; if (params.projection) { projection = params.projection; delete params.projection; } path = type === typeGroups ? contactGroupsUrl : contactsUrl; path += this.conf.email + '/' + projection + '?' + querystring.stringify(params); return path; }; GoogleContacts.prototype._get = function (type, params) { var request = require('https').request( { host: 'www.google.com', port: 443, path: this._buildPath(type, params), method: 'GET', headers: { 'Authorization': 'GoogleLogin auth=' + this.googleAuth.getAuthId() } }, function (response) { this._onResponse(request, response); }.bind(this) ).on('error', function (e) { // console.log('error getting stuff', e); }); request.end(); }; GoogleContacts.prototype._getContacts = function (params) { this._get(typeContacts, params); }; GoogleContacts.prototype._getContactGroups = function (projection, params) { this._get(typeGroups, params); }; exports.GoogleContacts = GoogleContacts;
JavaScript
0.000436
@@ -11,16 +11,29 @@ ndent: 2 +, nomen: true */%0A/*gl @@ -276,13 +276,12 @@ );%0A%0A -const +var con @@ -314,20 +314,16 @@ acts/',%0A - contac @@ -356,20 +356,16 @@ oups/',%0A - typeCo @@ -385,20 +385,16 @@ tacts',%0A - typeGr @@ -410,20 +410,16 @@ roups',%0A - projec @@ -1124,17 +1124,17 @@ );%0A %7D%0A%7D -, +; %0AGoogleC @@ -1497,34 +1497,32 @@ sponse, data) %7B%0A - this.contacts @@ -1533,34 +1533,32 @@ ON.parse(data);%0A - this.emit('con @@ -1668,26 +1668,24 @@ se, data) %7B%0A - this.conta @@ -1713,18 +1713,16 @@ (data);%0A - this.e @@ -1877,16 +1877,26 @@ = false +, onFinish ;%0A // T @@ -2010,20 +2010,16 @@ s/728%0A -var onFinish @@ -2849,16 +2849,28 @@ request +, projection ;%0A para @@ -2913,20 +2913,16 @@ son';%0A -var projecti @@ -2942,16 +2942,17 @@ onThin;%0A +%0A if (pa
6c0d7af43219c275d4451e53bb08b2d91ec8022b
Fix ssdb client pool from update
index.js
index.js
var express = require('express'); var app = express(); var ssdb = require('ssdb') var debug = require('debug')('rapidchat') //ssdb promise global.Promise = require('bluebird').Promise app.get('/', function(req, res){ res.sendFile(__dirname + '/index.html') }) app.use(express.static(__dirname)) var server = app.listen(3123, function() { debug('Listening on ' + 3123) }) //@todo kick users + ip from channel var ssdb_client = ssdb.createClient().promisify() var io = require('socket.io')(server) function updateUsers(channel) { return ssdb_client.hgetall(channel) .catch(function(err) { console.error("Error hgetall channel", err) }) .then(function(data) { //hgetall returns [user.uid, socketid, user.uid, socketid] //formating to key=>value var len = data.length var i = 0 var users = {}, key for (; i < len; i++) { if(i == 0 || i%2 == 0) { key = data[i] } else { users[key] = data[i] } } return Promise.resolve(users) }) } function handleError(prefix) { return function print(error) { console.error(prefix + error.name) console.error(error.message) console.error(error.stack) } } var leaveChannel = function leaveChannel(socket) { socket.leave(socket.channel) debug('User %s left channel %s', socket.uid, socket.channel) return ssdb_client.hdel(socket.channel, socket.uid).then(function() { return updateUsers(socket.channel) }).then(function(users) { debug('user left emit users %j', users) io.to(socket.channel).emit('left', { users: users }) return new Promise.resolve() }) .catch(handleError('leaveChannel')) } var joinChannel = function joinChannel(user, socket) { debug(user.uid + " joining " + user.channel) socket.uid = user.uid socket.channel = user.channel ssdb_client.hset(socket.channel, socket.uid, socket.id) .then(function() { return updateUsers(socket.channel) }) .then(function(users) { socket.join(socket.channel) io.to(socket.channel).emit('joined', users) debug("Exchange ping from ", socket.id, "to => ", socket.channel) socket.broadcast.to(socket.channel).emit('exchange ping', socket.id, user.publicKey) }) .catch(handleError('join')) } io.on('connection', function(socket) { socket.on('join', function(user) { if(!user.channel || !user.uid) return; if(socket.channel && socket.channel !== user.channel) { return leaveChannel(socket).then(function() { return joinChannel(user, socket) }) } else { return joinChannel(user, socket) } }) socket.on('exchange pong', function(to, key) { debug("Exchange pong from ", socket.id, "to =>", to) socket.broadcast.to(to).emit('exchange pong', key) }) socket.on('message', function(from, pgpMessage, time, to) { socket.broadcast.to(to ? to : socket.channel).emit('message', from, pgpMessage, time) }) socket.on('disconnect', function() { leaveChannel(socket) }) }) process.on('uncaughtException', function (err) { if(!err instanceof Error) err = new Error(err) console.error(err.name + ' - ' + err.message) console.error(err.stack) process.exit(1) })
JavaScript
0
@@ -120,20 +120,30 @@ at')%0A%0A// -ssdb +replace native promise @@ -383,16 +383,62 @@ 23)%0A%7D)%0A%0A +var pool = ssdb.createPool(%7Bpromisify: true%7D)%0A //@todo @@ -488,37 +488,20 @@ t = -ssdb.createClient().promisify +pool.acquire ()%0Av
b95f46d0025624ccf22390b96caa43d495600e8b
remove `ask` plugin for now
index.js
index.js
/*! * update <https://github.com/jonschlinkert/update> * * Copyright (c) 2015, Jon Schlinkert. * Licensed under the MIT License. */ 'use strict'; /** * module dependencies */ var path = require('path'); var minimist = require('minimist'); var expand = require('expand-args'); var cli = require('base-cli'); var store = require('base-store'); var pipeline = require('base-pipeline'); var loader = require('assemble-loader'); var Base = require('assemble-core'); var ask = require('assemble-ask'); var config = require('./lib/config'); var locals = require('./lib/locals'); var utils = require('./lib/utils'); /** * Create an `update` application. This is the main function exported * by the update module. * * ```js * var Update = require('update'); * var update = new Update(); * ``` * @param {Object} `options` * @api public */ function Update(options) { if (!(this instanceof Update)) { return new Update(options); } Base.call(this, options); this.name = this.options.name || 'update'; this.isUpdate = true; this.initUpdate(this); } /** * Inherit assemble-core */ Base.extend(Update); /** * Initialize Updater defaults */ Update.prototype.initUpdate = function(base) { this.set('updaters', {}); // custom middleware handlers this.handler('onStream'); this.handler('preWrite'); this.handler('postWrite'); // parse command line arguments var argv = expand(minimist(process.argv.slice(2)), { alias: {v: 'verbose'} }); this.option('argv', argv); // expose `argv` on the instance this.mixin('argv', function(prop) { var args = [].slice.call(arguments); args.unshift(argv); return utils.get.apply(null, args); }); // load the package.json for the updater this.data(utils.pkg.sync(this.options.path)); config(this); this.use(utils.runtimes({ displayName: function (key) { return base.name === key ? key : (base.name + ':' + key); } })) this.use(locals('update')) .use(store()) .use(pipeline()) .use(loader()) .use(ask()) .use(cli()) .use(utils.defaults()) .use(utils.opts()) var data = utils.get(this.cache.data, 'update'); data = utils.extend({}, data, argv); this.config.process(data); this.engine(['md', 'tmpl'], require('engine-base')); this.onLoad(/\.(md|tmpl)$/, function (view, next) { utils.matter.parse(view, next); }); }; Update.prototype.cwd = function(dir) { var cwd = dir || process.cwd(); return function() { var args = [].slice.call(arguments); args.unshift(cwd); return path.resolve.apply(null, args); }; }; Update.prototype.log = function() { if (this.enabled('verbose')) { console.log.apply(console, arguments); } }; Update.prototype.flag = function(key) { return this.get('argv.' + key); }; Update.prototype.cmd = function(key) { return utils.commands(this.argv)[key] || false; }; Update.prototype.extendFile = function(file, config, opts) { var parsed = utils.tryParse(file.content); var obj = utils.extend({}, parsed, config); var res = {}; if (opts && opts.sort === true) { var keys = Object.keys(obj).sort(); var len = keys.length, i = -1; while (++i < len) { var key = keys[i]; res[key] = obj[key]; } } else { res = obj; } file.content = JSON.stringify(res, null, 2); if (opts.newline) file.content += '\n'; }; /** * Register updater `name` with the given `update` * instance. * * @param {String} `name` * @param {Object} `update` Instance of update * @return {Object} Returns the instance for chaining */ Update.prototype.updater = function(name, app) { if (arguments.length === 1 && typeof name === 'string') { return this.updaters[name]; } app.use(utils.runtimes({ displayName: function(key) { return app.name === key ? key : (app.name + ':' + key); } })); this.emit('updater', name, app); this.updaters[name] = app; return app; }; /** * Expose `Update` */ module.exports = Update; /** * Expose `utils` */ module.exports.utils = utils; /** * Expose package.json metadata */ module.exports.pkg = require('./package');
JavaScript
0
@@ -467,43 +467,8 @@ e'); -%0Avar ask = require('assemble-ask'); %0A%0Ava @@ -1998,24 +1998,8 @@ ())%0A - .use(ask())%0A
686e65c9e3bc0ecb03e3b31de17c52d469ecc860
Set a title
app/webpack.common.js
app/webpack.common.js
'use strict' const path = require('path') const HtmlWebpackPlugin = require('html-webpack-plugin') const CleanWebpackPlugin = require('clean-webpack-plugin') const webpack = require('webpack') const merge = require('webpack-merge') const devClientId = '3a723b10ac5575cc5bb9' const devClientSecret = '22c34d87789a365981ed921352a7b9a8c3f69d54' const environment = process.env.NODE_ENV || 'development' const replacements = { __OAUTH_CLIENT_ID__: JSON.stringify(process.env.DESKTOP_OAUTH_CLIENT_ID || devClientId), __OAUTH_SECRET__: JSON.stringify(process.env.DESKTOP_OAUTH_CLIENT_SECRET || devClientSecret), __DARWIN__: process.platform === 'darwin', __WIN32__: process.platform === 'win32', __DEV__: environment === 'development', __RELEASE_ENV__: JSON.stringify(environment), 'process.platform': JSON.stringify(process.platform), 'process.env.NODE_ENV': JSON.stringify(environment), 'process.env.TEST_ENV': JSON.stringify(process.env.TEST_ENV), } const outputDir = 'out' const commonConfig = { externals: [ '7zip' ], output: { filename: '[name].js', path: path.resolve(__dirname, '..', outputDir), libraryTarget: 'commonjs2' }, module: { rules: [ { test: /\.tsx?$/, include: path.resolve(__dirname, 'src'), use: [ { loader: 'awesome-typescript-loader', options: { useBabel: true, useCache: true, }, } ], exclude: /node_modules/, }, { test: /\.node$/, use: [ { loader: 'node-native-loader', options: { name: "[name].[ext]" } } ], } ], }, plugins: [ new CleanWebpackPlugin([ outputDir ], { verbose: false }), // This saves us a bunch of bytes by pruning locales (which we don't use) // from moment. new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/), new webpack.DefinePlugin(replacements), new webpack.NoEmitOnErrorsPlugin(), ], resolve: { extensions: [ '.js', '.ts', '.tsx' ], modules: [ path.resolve(__dirname, 'node_modules/') ], }, node: { __dirname: false, __filename: false }, } const mainConfig = merge({}, commonConfig, { entry: { main: path.resolve(__dirname, 'src/main-process/main') }, target: 'electron-main', }) const rendererConfig = merge({}, commonConfig, { entry: { renderer: path.resolve(__dirname, 'src/ui/index') }, target: 'electron-renderer', module: { rules: [ { test: /\.(jpe?g|png|gif|ico)$/, use: ['file?name=[path][name].[ext]'] } ] }, plugins: [ new HtmlWebpackPlugin({ 'template': path.join(__dirname, 'static', 'index.html'), 'chunks': ['renderer'] }), ], }) const sharedConfig = merge({}, commonConfig, { entry: { shared: path.resolve(__dirname, 'src/shared-process/index') }, target: 'electron-renderer', plugins: [ new HtmlWebpackPlugin({ 'template': path.join(__dirname, 'static', 'error.html'), // without this we overwrite index.html 'filename': 'error.html', // we don't need any scripts to run on this page 'excludeChunks': [ 'main', 'renderer', 'shared', 'ask-pass' ] }), new HtmlWebpackPlugin({ 'filename': 'shared.html', 'chunks': ['shared'] }), ], }) const askPassConfig = merge({}, commonConfig, { entry: { 'ask-pass': path.resolve(__dirname, 'src/ask-pass/main') }, target: 'node', }) const crashConfig = merge({}, commonConfig, { entry: { crash: path.resolve(__dirname, 'src/crash/index') }, target: 'electron-renderer', plugins: [ new HtmlWebpackPlugin({ 'filename': 'crash.html', 'chunks': ['crash'] }), ], }) module.exports = { main: mainConfig, shared: sharedConfig, renderer: rendererConfig, askPass: askPassConfig, crash: crashConfig, replacements: replacements, externals: commonConfig.externals, }
JavaScript
0.999999
@@ -3641,33 +3641,63 @@ gin(%7B%0A -' +title: 'GitHub Desktop',%0A filename ': 'crash.ht @@ -3684,17 +3684,16 @@ filename -' : 'crash @@ -3702,32 +3702,30 @@ tml',%0A -' chunks -' : %5B'crash'%5D%0A
83ce9359345cf944a2f715db8a39cf839658f472
Update splitEvery test with ES6 syntax
test/util/split-every.js
test/util/split-every.js
import {assert} from 'chai'; import splitEvery from '../../src/util/split-every.js'; describe('#splitEvery', () => { it('should split a collection into slices of the specified length', function() { assert.deepEqual(R.splitEvery(1, [1, 2, 3, 4]), [[1], [2], [3], [4]]); assert.deepEqual(R.splitEvery(2, [1, 2, 3, 4]), [[1, 2], [3, 4]]); assert.deepEqual(R.splitEvery(3, [1, 2, 3, 4]), [[1, 2, 3], [4]]); assert.deepEqual(R.splitEvery(4, [1, 2, 3, 4]), [[1, 2, 3, 4]]); assert.deepEqual(R.splitEvery(5, [1, 2, 3, 4]), [[1, 2, 3, 4]]); assert.deepEqual(R.splitEvery(3, []), []); assert.deepEqual(R.splitEvery(1, 'abcd'), ['a', 'b', 'c', 'd']); assert.deepEqual(R.splitEvery(2, 'abcd'), ['ab', 'cd']); assert.deepEqual(R.splitEvery(3, 'abcd'), ['abc', 'd']); assert.deepEqual(R.splitEvery(4, 'abcd'), ['abcd']); assert.deepEqual(R.splitEvery(5, 'abcd'), ['abcd']); assert.deepEqual(R.splitEvery(3, ''), []); }); });
JavaScript
0
@@ -185,18 +185,13 @@ h', -function() +() =%3E %7B%0A
ceb96e712da4212770713d5e77714b471b0bdc09
put built browser file into root dir for visual test
test/visual/runvisual.js
test/visual/runvisual.js
var connect = require('connect'), fs = require("fs"), path = require("path"), sys = require("sys"); build(path.resolve(__dirname, "../../package.json")); connect.createServer( connect.staticProvider({ root: path.join(__dirname, "files"), cache: true }) ).listen(3000); sys.puts("visit http://127.0.0.1:3000/vis.html"); function build(pkgFile, name, dest) { sys.puts("building..."); var pkg = JSON.parse(fs.readFileSync(pkgFile || "package.json")); name = name || pkg.name; dest = dest || name + ".js"; var code = "var " + name + " = " + getCode(pkg.main + ".js", " "); fs.writeFileSync(dest, code, "utf-8"); sys.puts("> " + dest); }; function getCode(file, indent) { sys.puts(indent + file); var code = fs.readFileSync(file, "utf-8"); // replace all the require("mod")s with their code // can't handle dep cycles var re = /require\(["'](.+?)["']\)/g; function expand(match, mod) { if(mod.indexOf(".") != 0) return "window"; // external dep, assume it will be global var dep = path.join(path.dirname(file), mod + ".js"); return getCode(dep, indent + " "); } code = code.replace(re, expand); return "(function() {\n\ var module = { exports: {}};\n\ var exports = module.exports;\n" + code + "\nreturn module.exports;\ })()"; }
JavaScript
0
@@ -106,16 +106,58 @@ sys%22);%0A%0A +var root = path.join(__dirname, %22files%22);%0A build(pa @@ -262,37 +262,12 @@ ot: -path.join(__dirname, %22files%22) +root , ca @@ -523,16 +523,32 @@ dest %7C%7C + path.join(root, name + @@ -552,18 +552,18 @@ + %22.js%22 +) ; -%0A %0A var c
a1da80b41584d9ddaacf774aabbece61e31c082f
Add test for number names
tests/validation.test.js
tests/validation.test.js
/* global describe, it */ 'use strict'; (function () { var expect = require('chai').expect; var utils = require('../src/utils'); var Command = require('../src/command'); var KWArg = require('../src/kwarg'); var Flag = require('../src/flag'); var Arg = require('../src/arg'); describe('validation', function () { describe('validateName', function () { var nodes = [Command, KWArg, Flag, Arg]; it('should error if node names are not strings', function () { var anError = /string/i; utils.each(nodes, function (node) { expect(node.bind(null, undefined)).to.throw(anError); expect(node.bind(null, null)).to.throw(anError); expect(node.bind(null, {})).to.throw(anError); expect(node.bind(null, [])).to.throw(anError); }); }); it('should error if node names are empty', function () { var anError = /empty/i; utils.each(nodes, function (node) { expect(node.bind(null, '')).to.throw(anError); }); }); it('should error if node names contain spaces', function () { var anError = /spaces/i; utils.each(nodes, function (node) { expect(node.bind(null, ' test')).to.throw(anError); expect(node.bind(null, 'test ')).to.throw(anError); expect(node.bind(null, ' te st ')).to.throw(anError); }); }); it('should error if node names begin with -', function () { var anError = /begin\swith/i; utils.each(nodes, function (node) { expect(node.bind(null, '-test')).to.throw(anError); expect(node.bind(null, 'word-word')).not.to.throw(anError); }); }); }); }); })();
JavaScript
0.000072
@@ -793,32 +793,88 @@ throw(anError);%0A + expect(node.bind(null, 1)).to.throw(anError);%0A %7D);%0A
dd541abcc57e23d79410a2f24d1472c60de3acc3
fix cross require
indexer.js
indexer.js
var request = require('request'); var async = require('async'); var _ = require('lodash'); var fs = require('fs'); var moment = require('moment'); var autocomplete = require('./autocomplete'); var EventEmitter = require('events').EventEmitter; var cross = require('cross'); //var url = "http://sis.rutgers.edu/soc/subjects.json?semester=12013&campus=NB&level=U"; var url = "http://sis.rutgers.edu/soc/subjects.json?semester=$SEMESTER&campus=$CAMPUS&level=$LEVEL"; var subj = "http://sis.rutgers.edu/soc/courses.json?subject=$SUBJ&semester=$SEMESTER&campus=$CAMPUS&level=$LEVEL"; // Number is the month they start in // winter: 0 // spring: 1 // summer: 7 // fall: 9 var campuses = ['NB', 'NK', 'CM', 'ONLINE', 'WM', 'AC', 'MC', 'J', 'RV', 'CC', 'CU']; function titleToAbbrev (title) { return title.split(' ').reduce(function (memo, item) { if (item != 'and') return memo + item[0]; else return memo; }, ""); } function capitalize (text) { return text.trim().toLowerCase().split(' ').map(function (item) { if (item == 'ii' || item == 'i' || item == 'iii' || item == 'iv') return item.toUpperCase(); // TODO: about a million other english oddities and other edge cases if (item != 'and') { if (item) return item[0].toUpperCase() + item.slice(1); else return ''; } else return item; }).join(' '); } function index (semester, campus, level, callback) { var myUrl = url .replace('$SEMESTER', semester) .replace('$CAMPUS', campus) .replace('$LEVEL', level); request(myUrl, function (err, res, body) { console.log("Retrieved:", myUrl); try { if (err) throw err; var data = JSON.parse(body); var base = {ids: {}, names: {}, abbrevs: {}, courses: {}}; async.reduce(data, base, function (memo, item, callback) { var subjUrl = subj .replace('$SEMESTER', semester) .replace('$CAMPUS', campus) .replace('$LEVEL', level) .replace('$SUBJ', item.code); request(subjUrl, function (err, res, body) { try { if (err) throw err; var data = JSON.parse(body); var subject = {id: item.code, name: capitalize(item.description)}; subject.courses = _.reduce(data, function (c, item) { var t = capitalize(item.expandedTitle || item.title); c[item.courseNumber] = t; memo.courses[t] = { subj: subject.id, course: item.courseNumber }; return c; }, {}); memo.ids[subject.id] = subject; var abbrev = titleToAbbrev(subject.name); memo.abbrevs[abbrev] = memo.abbrevs[abbrev] || []; memo.abbrevs[abbrev].push(subject.id); memo.names[subject.name] = subject.id; callback(null, memo); } catch (e) { callback(e); } }); }, function (err, result) { callback(err, result); }); } catch (e) { callback(e); } }); } // Indexes all semesters we care about, returns a hash of those. function run (callback) { var semesters = autocomplete.calcSemesters(new Date().getMonth(), new Date().getFullYear()); var dbg = new EventEmitter(); var jobs = cross.for(semesters, campuses, ['G', 'U'], function (sem, campus, level) { return function (callback) { index(sem, campus, level, function (err, data) { dbg.emit('debug', 'Done indexing ' + sem + ' ' + campus + ' ' + level); callback(err, {filename: 'indexes/' + sem + "_" + campus + "_" + level + ".json", data: data}); }); }; }); async.parallel(jobs, callback); return dbg; } module.exports = run; run.index = index; if (require.main === module) { var emitter = run(function (err, data) { if (err) console.log(err.stack); else { _.each(data, function (item) { console.log('writing to ' + item.filename); fs.writeFile(item.filename, JSON.stringify(item.data)); }); } }); emitter.on('debug', function (msg) { console.log(msg); }); }
JavaScript
0
@@ -258,16 +258,18 @@ equire(' +./ cross');
872560892c58fb1ac1f8cb32d6625ba8784e4f86
fix exec
release.config.js
release.config.js
const CHANGELOG_HEADER = `# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html), enforced with [semantic-release](https://github.com/semantic-release/semantic-release). ` module.exports = { preset: 'conventionalcommits', releaseRules: [ { breaking: true, release: 'major' }, { type: 'feat', release: 'minor' }, { type: 'fix', release: 'patch' }, ], changelogFile: 'CHANGELOG.md', changelogTitle: CHANGELOG_HEADER, tarballDir: 'pack', message: 'chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}', assets: ['CHANGELOG.md', 'pack/*.tgz'], assignees: ['hertzg'], plugins: [ '@semantic-release/commit-analyzer', '@semantic-release/release-notes-generator', '@semantic-release/changelog', [ '@semantic-release/exec', { verifyConditionsCmd: './verify.sh', prepareCmd: 'prettier --write CHANGELOG.md', }, ], '@semantic-release/npm', '@semantic-release/git', '@semantic-release/github', ], }
JavaScript
0.000001
@@ -992,52 +992,8 @@ %7B%0A - verifyConditionsCmd: './verify.sh',%0A
ffe4a0cbd3b4ad95110afc4bf88a94faf00b1478
Remove commented code
routes/newUser.js
routes/newUser.js
const UserDB = require('../db/userdb').Users exports.save = (req, res, next) => { var data = req.body.user //req.session.user = user UserDB.insert(data, (err, user) => { console.log('<newUser.js, save > callback from DB after insert user -> ', user) if (err) throw new Error(err) retriveUserDetailAndRedirect(data.phoneNumber, req, res) }) console.log('<newUser.js save > data -> ', data) } const retriveUserDetailAndRedirect = (phoneNumber, req, res) => { console.log('<newUser.js, retriveUserDetailAndRedirect > Entry') UserDB.findByPhoneNumber(phoneNumber, (err, user) => { console.log('<newUser.js, retriveUserDetailAndRedirect > callback from findByPhoneNumber user -> ', user) if (err) throw new Error(err) if (user) { req.session.user = user res.redirect('chatRelay') } else { res.writeHead(200, { 'Content-Type': 'text/html' }) res.end('Something went wrong while retriving user detail :( ') } }) }
JavaScript
0
@@ -107,36 +107,8 @@ ser%0A - //req.session.user = user%0A Us
a6eb117fd246888474b08546a969385d4f71c34c
Remove debug
routes/threads.js
routes/threads.js
module.exports = function threads(app, apiClient){ app.get('/:shortname', function(req, res){ var shortName = req.params.shortname, page = req.query.page; apiClient.getBoard(shortName, function(err, board){ var boardName; if(board && board.name){ boardName = board.name.toLowerCase(); } apiClient.getIndexThreads(boardName, page, function(err, threads){ console.log(threads); res.render('threads.html', { 'board': board, 'threads': threads }); }); }); }); app.post('/:board', function(req, res){ var board = req.params.board; apiClient.newThread(board, {}); }); }
JavaScript
0.000001
@@ -378,34 +378,8 @@ s)%7B%0A -%09%09%09%09console.log(threads);%0A %09%09%09%09
a6b2580b1ff344216b27e6ee5cf8a53fe6c8877e
comment out to debug an error
routes/webhook.js
routes/webhook.js
// for facebook verification 'use strict' const util = require('util'); const path = require('path'); const constants = require(path.join(__dirname, "../setup/constants")); const USER_DOMAIN = 'https://graph.facebook.com/v2.6/1356921494324269'; const request = require('request'), pageAccessToken = constants.PAGE_ACCESS_TOKEN, verifyToken = constants.VERIFY_TOKEN; const GOAL_OPTIONS = [ { "content_type": "text", "title": "Go to the gym", "payload": "GOAL_GYM" }, { "content_type": "text", "title": "Wake up early", "payload": "GOAL_WAKE_UP" } ]; const FREQUENCY_OPTIONS = [ { "content_type": "text", "title": "Weekdays", "payload": "FREQUENCY_WEEKDAYS" }, { "content_type": "text", "title": "Weekends", "payload": "FREQUENCY_WEEKENDS" }, { "content_type": "text", "title": "Every day", "payload": "FREQUENCY_EVERY_DAY" } ]; var webhookController = require(path.join(__dirname,'../controllers/webhookController')); var testController = require(path.join(__dirname,'../controllers/testController')); module.exports = function(app){ app.get('/webhook/', function (req, res) { if (req.query['hub.verify_token'] === verifyToken) { res.send(req.query['hub.challenge']) } res.send('Error, wrong token') }); // to post data app.post('/webhook/', function (req, res) { console.log('In POST request'); let messaging_events = req.body.entry[0].messaging //Test DB Connection testController.saveObj(req, res, app.models.Test) for (let i = 0; i < messaging_events.length; i++) { let event = req.body.entry[0].messaging[i] let sender = event.sender.id if (event.message && event.message.text) { let text = event.message.text if (text === 'Generic') { sendGenericMessage(sender) continue } if(event.message.text === 'Get started') { sendTextMessage(sender, { text: "Your life is about to be changed! What goal would you like to start tracking?", quick_replies: GOAL_OPTIONS }); request(`${USER_DOMAIN}?access_token=${pageAccessToken}`, function(error, response, body) { if (!error && response.statusCode == 200) { console.log(response); console.log(body); } }) // .get(`${USER_DOMAIN}?access_token=${pageAccessToken}`) // .on('response', function(response) { // console.log(response); // console.log(response.body); // 200 // }) // .on('error', function(err) { // console.log(err) // }) } if(event.message.quick_reply) { switch (event.message.quick_reply.payload) { case 'GOAL_WAKE_UP': case 'GOAL_GYM': { sendTextMessage(sender, { text: "Great, and how often would you like me to check in?", quick_replies: FREQUENCY_OPTIONS }); break; } case 'FREQUENCY_WEEKDAYS': case 'FREQUENCY_WEEKENDS': case 'FREQUENCY_EVERY_DAY': { sendTextMessage(sender, { text: "Thanks, your dreams are only a few taps away!" }); break; } } } } if (event.postback) { let text = JSON.stringify(event.postback) sendTextMessage(sender, "Postback received: "+text.substring(0, 200), pageAccessToken) continue } } res.sendStatus(200) }); function sendTextMessage(sender, messageData) { request({ url: 'https://graph.facebook.com/v2.6/me/messages', qs: {access_token:pageAccessToken}, method: 'POST', json: { recipient: {id:sender}, message: messageData, } }, function(error, response, body) { if (error) { console.log('Error sending messages: ', error) } else if (response.body.error) { console.log('Error: ', response.body.error) } }) }; function sendGenericMessage(sender) { let messageData = { "attachment": { "type": "template", "payload": { "template_type": "generic", "elements": [{ "title": "First card", "subtitle": "Element #1 of an hscroll", "image_url": "http://messengerdemo.parseapp.com/img/rift.png", "buttons": [{ "type": "web_url", "url": "https://www.messenger.com", "title": "web url" }, { "type": "postback", "title": "Postback", "payload": "Payload for first element in a generic bubble", }], }, { "title": "Second card", "subtitle": "Element #2 of an hscroll", "image_url": "http://messengerdemo.parseapp.com/img/gearvr.png", "buttons": [{ "type": "postback", "title": "Postback", "payload": "Payload for second element in a generic bubble", }], }] } } } request({ url: 'https://graph.facebook.com/v2.6/me/messages', qs: {access_token:pageAccessToken}, method: 'POST', json: { recipient: {id:sender}, message: messageData, } }, function(error, response, body) { if (error) { console.log('Error sending messages: ', error) } else if (response.body.error) { console.log('Error: ', response.body.error) } }) }; }
JavaScript
0
@@ -2080,16 +2080,18 @@ ction%0A%09%09 +// testCont
bbe7be31955150f734a1a652a1fa575274af96dc
update if exists by author/name
app-database.js
app-database.js
var Bacon = require("baconjs") var randomstring = require("randomstring") var MongoClient = require('mongodb').MongoClient function AppDatabase(mongoUrl, app) { MongoClient.connect(mongoUrl, function(err, conn) { if (err) { console.log("ERROR: cannot connect to mongo at ", mongoUrl, err) } else { AppDatabaseWithConnection(conn, app) } }) } function AppDatabaseWithConnection(conn, app) { var apps = conn.collection("apps") app.get("/apps", function(req, res) { sendResult(mongoFind({}), res) }) app.get("/apps/:author", function(req, res) { sendResult(mongoFind({"content.author": req.params.author}), res) }) app.get("/apps/:id", function(req, res) { sendResult(mongoFind({"id": req.params.id}).map(".0"), res) }) app.get("/apps/:author/:name", function(req, res) { sendResult(mongoFind({"content.author": req.params.author, "content.description": req.params.name}).map(".0"), res) }) app.post("/apps", function(req, res) { var data = { id: randomstring.generate(10), content: JSON.stringify(req.body), date: new Date() } sendResult(mongoPost(data).map(data), res) }) function mongoPost(data) { return Bacon.fromNodeCallback(apps, "insert", [data]) } function mongoFind(query) { return Bacon.fromNodeCallback(apps.find(query).sort({date: -1}), "toArray") } function sendResult(resultE, res) { resultE.onError(res, "send") resultE.onValue(function(value) { if (value) { res.json(value) } else { res.status(404).send("Not found") } }) } } module.exports = AppDatabase
JavaScript
0.000001
@@ -844,32 +844,24 @@ mongoFind(%7B%22 -content. author%22: req @@ -881,27 +881,12 @@ r, %22 -content.description +name %22: r @@ -972,56 +972,153 @@ -var data = %7B%0A id: randomstring.generate(10) +sendResult(mongoPost(req.body), res)%0A %7D)%0A function mongoPost(content) %7B%0A var data = %7B%0A author: content.author,%0A name: content.name ,%0A @@ -1145,24 +1145,23 @@ ringify( -req.body +content ),%0A @@ -1192,141 +1192,161 @@ -sendResult(mongoPost(data).map(data), res)%0A %7D)%0A function mongoPost(data) %7B%0A return Bacon.fromNodeCallback(apps, %22insert%22, %5B +return Bacon.fromNodeCallback(apps, %0A %22update%22, %0A %7B%22author%22: data.author, %22name%22: data.name%7D, %0A data, %0A %7Bupsert: true%7D)%0A .map( data -%5D )%0A @@ -1523,19 +1523,88 @@ ror( -res, %22send%22 +function(err) %7B %0A console.log(%22Mongo error%22, err)%0A res.send(err)%0A %7D )%0A
9f718de3d22b05d70b9cbd94f0f86cbeb719d154
this.getUint16 should be this.dv.getUint16
typeServices/application/x-java-class.js
typeServices/application/x-java-class.js
define(function() { 'use strict'; function ClassView(buffer, byteOffset, byteLength) { this.dv = new DataView(buffer, byteOffset, byteLength); this.bytes = new Uint8Array(buffer, byteOffset, byteLength); } ClassView.prototype = { get signature() { return this.dv.getUint32(0, false); }, get hasValidSignature() { return this.signature === 0xCAFEBABE; }, get versionMinor() { return this.dv.getUint16(4, false); }, get versionMajor() { return this.dv.getUint16(6, false); }, get constantPools() { var c = new Array(this.dv.getUint16(8, false) - 1); var pos = 10; var bytes = this.bytes; var dv = this.dv; for (var i = 1; i < c.length; i++) { var constantType = bytes[pos++]; switch (constantType) { case 1: var length = dv.getUint16(pos, false); pos += 2; c[i] = {type:'utf8', value:new TextDecoder('utf-8').decode(bytes.subarray(pos, pos + length))}; pos += length; break; case 3: c[i] = {type:'integer', value:dv.getInt32(pos, false)}; pos += 4; break; case 4: c[i] = {type:'float', value:dv.getFloat32(pos, false)}; pos += 4; break; case 5: c[i] = {type:'long', valueHi:dv.getInt32(pos, false), valueLo:dv.getInt32(pos+4, false)}; pos += 8; break; case 6: c[i] = {type:'double', value:dv.getFloat64(pos, false)}; pos += 8; break; case 7: c[i] = {type:'class', nameIndex:dv.getUint16(pos, false)}; pos += 2; break; case 8: c[i] = {type:'string', utf8Index:dv.getUint16(pos, false)}; pos += 2; break; case 9: c[i] = {type:'fieldRef', classIndex:dv.getUint16(pos, false), nameAndTypeIndex:dv.getUint16(pos + 2, false)}; pos += 4; break; case 10: c[i] = {type:'methodRef', classIndex:dv.getUint16(pos, false), nameAndTypeIndex:dv.getUint16(pos + 2, false)}; pos += 4; break; case 11: c[i] = {type:'interfacMethodRef', classIndex:dv.getUint16(pos, false), nameAndTypeIndex:dv.getUint16(pos + 2, false)}; pos += 4; break; case 12: c[i] = {type:'nameAndType', nameIndex:dv.getUint16(pos, false), descriptorIndex:dv.getUint16(pos+2, false)}; pos += 4; break; case 15: c[i] = {type:'methodHandle', refKind:bytes[pos], refIndex:dv.getUint16(pos+1, false)}; pos += 3; break; case 16: c[i] = {type:'methodType', descriptorIndex:dv.getUint16(pos, false)}; pos += 2; break; case 18: c[i] = { type:'invokeDynamic', bootstrapMethodAttrIndex:dv.getUint16(pos, false), nameAndTypeIndex:dv.getUint16(pos+2, false), }; pos += 4; break; default: throw new Error('unknown constant type code: ' + constantType); } } c.afterPos = pos; Object.defineProperty(this, 'constantPools', {value:c}); return c; }, get accessFlags() { return this.dv.getUint16(this.constantPools.afterPos, false); }, get isPublic() { return !!(this.accessFlags & 0x0001); }, get isFinal() { return !!(this.accessFlags & 0x0010); }, get isSuper() { return !!(this.accessFlags & 0x0020); }, get isInterface() { return !!(this.accessFlags & 0x0200); }, get isAbstract() { return !!(this.accessFlags & 0x0400); }, get isSynthetic() { return !!(this.accessFlags & 0x1000); }, get isAnnotation() { return !!(this.accessFlags & 0x2000); }, get isEnum() { return !!(this.accessFlags & 0x4000); }, get thisClass() { return this.constantPools[this.getUint16(this.constantPools.afterPos + 2, false)]; }, get superClass() { return this.constantPools[this.getUint16(this.constantPools.afterPos + 4, false)]; }, }; return { getStructView: function() { return ClassView; }, }; });
JavaScript
0.999993
@@ -4104,32 +4104,35 @@ stantPools%5Bthis. +dv. getUint16(this.c @@ -4234,16 +4234,19 @@ ls%5Bthis. +dv. getUint1
0127c0947ced28baddc096e0e73065308ed111c3
Test game on mobile with js movements
app/game/car.js
app/game/car.js
var carIDList = []; var printed = false; function newCarID(){ var newID = "car" + carIDList.length; carIDList.push(newID); return newID; } Car.prototype.id = "" //String: ID of DOM representation Car.prototype.name = "" //String Car.prototype.color = "" //Color as String Car.prototype.position = 0 //Double Car.prototype.appearanceOptions = 36; //Body Type as Integer Car.prototype.appearance = 1; //Body Type as Integer function Car(name, color, position){ this.id = newCarID(); this.name = name || "Car"; this.color = color || "red"; this.position = position || 0; this.appearance = Math.round((Math.random() * (this.appearanceOptions - 1)) + 1); } Car.prototype.update = function(boardSize, roadSize, increment){ //console.log("updated car: " + this.name); this.position += increment; if(this.position > (boardSize + roadSize)){ console.log("out of road bounds"); this.position = -2.5 * roadSize; if(printed){ document.getElementById(this.id).style.display = "none"; } } else{ if(printed){ document.getElementById(this.id).style.display = "block"; } } if(printed){ document.getElementById(this.id).style.marginLeft = this.position + "px"; } } Car.prototype.toHTML = function(){ var html = ''; html += '<div id="' + this.id + '" class="car" style="margin-left:'; html += this.position + 'px;background-image:'; html += 'url(style/cars/path' + (2192 + this.appearance) * 2 + '.png);">'; html += '</div>'; return html; }
JavaScript
0
@@ -289,28 +289,95 @@ ype. -position = 0 //Doubl +boardSize = 100; //Double%0ACar.prototype.position = 0 //Double as percentage of boardSiz e%0ACa @@ -607,16 +607,39 @@ %22red%22;%0A +%09this.boardSize = 100;%0A %09this.po @@ -813,16 +813,16 @@ ement)%7B%0A - %09//conso @@ -858,16 +858,45 @@ .name);%0A +%09this.boardSize = boardSize;%0A %09this.po
92e02d8a322678aed62e451ad53043928397d416
Rename interface.
app/gateways.js
app/gateways.js
exports = module.exports = function(IoC, dfault) { var Factory = require('fluidfactory'); var factory = new Factory(); return Promise.resolve(factory) .then(function(factory) { var detectorPlugIns = IoC.components('http://i.bixbyjs.org/platform/http/gatewayDetector'); return Promise.all(detectorPlugIns.map(function(plugin) { return plugin.create(); } )) .then(function(plugins) { plugins.forEach(function(plugin, i) { logger.info('Loaded HTTP gateway detector: ' + detectorPlugIns[i].a['@name']); factory.use(plugin); }); factory.use(dfault); }) .then(function() { return factory; }); }) .then(function(factory) { return function() { var ifaces = factory.create(); if (typeof ifaces == 'string') { return [ ifaces ]; } return ifaces; } }); }; exports['@require'] = [ '!container', './gateways/default' ];
JavaScript
0
@@ -268,17 +268,17 @@ rm/http/ -g +G atewayDe
ee46763a7aa8468a2c2e04dfa829ca4d97267e9d
Make sure midnight gets converted properly. Fixes feedbin/support#349.
vendor/assets/javascripts/format_date.js
vendor/assets/javascripts/format_date.js
(function () { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; var re = new RegExp(/%(a|A|b|B|c|C|d|D|e|F|h|H|I|j|k|l|L|m|M|n|p|P|r|R|s|S|t|T|u|U|v|V|W|w|x|X|y|Y|z)/g); var abbreviatedWeekdays = ["Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat"]; var fullWeekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; var abbreviatedMonths = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; var fullMonths = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; function padNumber(num, count, padCharacter) { if (typeof padCharacter == "undefined") { padCharacter = "0"; } var lenDiff = count - String(num).length; var padding = ""; if (lenDiff > 0) while (lenDiff--) padding += padCharacter; return padding + num; } function dayOfYear(d) { var oneJan = new Date(d.getFullYear(), 0, 1); return Math.ceil((d - oneJan) / 86400000); } function weekOfYear(d) { var oneJan = new Date(d.getFullYear(), 0, 1); return Math.ceil((((d - oneJan) / 86400000) + oneJan.getDay() + 1) / 7); } function isoWeekOfYear(d) { var target = new Date(d.valueOf()); var dayNr = (d.getDay() + 6) % 7; target.setDate(target.getDate() - dayNr + 3); var jan4 = new Date(target.getFullYear(), 0, 4); var dayDiff = (target - jan4) / 86400000; return 1 + Math.ceil(dayDiff / 7); } function tweleveHour(d) { return d.getHours() > 12 ? d.getHours() - 12 : d.getHours(); } function timeZoneOffset(d) { var hoursDiff = (-d.getTimezoneOffset() / 60); var result = padNumber(Math.abs(hoursDiff), 4); return (hoursDiff > 0 ? "+" : "-") + result; } Date.prototype.format = function (formatString) { return formatString.replace(re, __bind(function (m, p) { switch (p) { case "a": return abbreviatedWeekdays[this.getDay()]; case "A": return fullWeekdays[this.getDay()]; case "b": return abbreviatedMonths[this.getMonth()]; case "B": return fullMonths[this.getMonth()]; case "c": return this.toLocaleString(); case "C": return Math.round(this.getFullYear() / 100); case "d": return padNumber(this.getDate(), 2); case "D": return this.format("%m/%d/%y"); case "e": return padNumber(this.getDate(), 2, " "); case "F": return this.format("%Y-%m-%d"); case "h": return this.format("%b"); case "H": return padNumber(this.getHours(), 2); case "I": return padNumber(tweleveHour(this), 2); case "j": return padNumber(dayOfYear(this), 3); case "k": return padNumber(this.getHours(), 2, " "); case "l": return padNumber(tweleveHour(this), 2, " "); case "L": return padNumber(this.getMilliseconds(), 3); case "m": return padNumber(this.getMonth() + 1, 2); case "M": return padNumber(this.getMinutes(), 2); case "n": return "\n"; case "p": return this.getHours() > 11 ? "PM" : "AM"; case "P": return this.format("%p").toLowerCase(); case "r": return this.format("%I:%M:%S %p"); case "R": return this.format("%H:%M"); case "s": return this.getTime() / 1000; case "S": return padNumber(this.getSeconds(), 2); case "t": return "\t"; case "T": return this.format("%H:%M:%S"); case "u": return this.getDay() == 0 ? 7 : this.getDay(); case "U": return padNumber(weekOfYear(this), 2); //either this or W is wrong (or both) case "v": return this.format("%e-%b-%Y"); case "V": return padNumber(isoWeekOfYear(this), 2); case "W": return padNumber(weekOfYear(this), 2); //either this or U is wrong (or both) case "w": return padNumber(this.getDay(), 2); case "x": return this.toLocaleDateString(); case "X": return this.toLocaleTimeString(); case "y": return String(this.getFullYear()).substring(2); case "Y": return this.getFullYear(); case "z": return timeZoneOffset(this); default: return match; } }, this)); }; }).call(this);
JavaScript
0
@@ -1603,24 +1603,89 @@ veHour(d) %7B%0A + if (d.getHours() == 0) %7B%0A return 12;%0A %7D%0A else %7B%0A return d @@ -1737,16 +1737,22 @@ ours();%0A + %7D%0A %7D%0A %0A
c3eb73c926839ba188c9ad2dc14a2be1cbd532be
add SLACK_APP_CLIENT_ID from Heroku config to bundle
tasks/loadHerokuEnv.js
tasks/loadHerokuEnv.js
import { herokuConfig } from './util' import { extend, pick } from 'lodash' const keys = [ 'ASSET_HOST', 'ASSET_PATH', 'AWS_ACCESS_KEY_ID', 'AWS_S3_BUCKET', 'AWS_S3_HOST', 'AWS_SECRET_ACCESS_KEY', 'FACEBOOK_APP_ID', 'FILEPICKER_API_KEY', 'GOOGLE_BROWSER_KEY', 'GOOGLE_CLIENT_ID', 'LOG_LEVEL', 'NODE_ENV', 'SEGMENT_KEY', 'UPSTREAM_HOST' ] export default function (done) { herokuConfig().info((err, vars) => { if (err) done(err) extend(process.env, pick(vars, keys)) done() }) }
JavaScript
0
@@ -340,16 +340,41 @@ T_KEY',%0A + 'SLACK_APP_CLIENT_ID',%0A 'UPSTR
8f7dc33e6b0751b1a1c6fb451d42409759f52aa5
change admin.js
app/js/admin.js
app/js/admin.js
var admin_ready = function() { $('#admin_page_controller').hide(); var eventName = getURLParameter("q"); $('#text_event_name').text("Event name: " + eventName); if(eventName == null || eventName.trim() == "") { $('#text_event_name').text("Error: Invalid event name "); } } $(document).ready(admin_ready); angular.module('teamform-admin-app', ['firebase']) .controller('AdminCtrl', ['$scope', '$firebaseObject', '$firebaseArray', function($scope, $firebaseObject, $firebaseArray) { // TODO: implementation of AdminCtrl // Initialize $scope.param as an empty JSON object $scope.param = {}; // Call Firebase initialization code defined in site.js initalizeFirebase(); var refPath, ref, eventName; eventName = getURLParameter("q"); refPath = eventName + "/admin/param"; ref = firebase.database().ref(refPath); // Link and sync a firebase object $scope.param = $firebaseObject(ref); $scope.paramMess=""; $scope.paramLdMess=function(){ // $scope.param.$loaded() // .then(function(data) { // Fill in some initial values when the DB entry doesn't exist if(typeof $scope.param.maxTeamSize == "undefined"){ $scope.param.maxTeamSize = 10; $scope.paramMess+="NoMax " } if(typeof $scope.param.minTeamSize == "undefined"){ $scope.param.minTeamSize = 1; $scope.paramMess+="NoMin " } // Enable the UI when the data is successfully loaded and synchornized $('#admin_page_controller').show(); }; $scope.param.$loaded().then($scope.paramLdMess); // }) // .catch(function(error) { // Database connection error handling... //console.error("Error:", error); // }); refPath = "users"; $scope.users = []; $scope.users = $firebaseArray(firebase.database().ref(refPath)); console.log($scope.users); refPath = eventName + "/team"; $scope.team = []; $scope.team = $firebaseArray(firebase.database().ref(refPath)); refPath = eventName + "/member"; $scope.member = []; $scope.member = $firebaseArray(firebase.database().ref(refPath)); $scope.changeMinTeamSize = function(delta) { var newVal = $scope.param.minTeamSize + delta; if (newVal >=1 && newVal <= $scope.param.maxTeamSize ) { $scope.param.minTeamSize = newVal; } $scope.param.$save(); } $scope.changeMaxTeamSize = function(delta) { var newVal = $scope.param.maxTeamSize + delta; if (newVal >=1 && newVal >= $scope.param.minTeamSize ) { $scope.param.maxTeamSize = newVal; } $scope.param.$save(); } $scope.saveFunc = function() { $scope.param.$save(); // Finally, go back to the front-end window.location.href= "main.html"; } }]);
JavaScript
0.000001
@@ -2656,12 +2656,13 @@ f= %22 -ma in +dex .htm
92bd419428e1b21b191a4032ed55a656b35ea254
Reset timer just before starting them
app/js/index.js
app/js/index.js
'use strict'; // get the duration for all timer from configuration var configuration = require('../configuration.js'); var timerDurations = configuration.readSettings('TimerDuration'); var pomodoroTimer = timerDurations[0]; var shortBreakTimer = timerDurations[1]; var longBreakTimer = timerDurations[2]; // create the timer with the pomodoro duration var nodeTimers = require('node-timers'); var timer_pomodoro = nodeTimers.countdown({pollInterval: 1000, startTime: pomodoroTimer}); var timer_shortBreak = nodeTimers.countdown({pollInterval: 1000, startTime: shortBreakTimer}); var timer_longBreak = nodeTimers.countdown({pollInterval: 1000, startTime: longBreakTimer}); // display the pomodoro duration document.getElementById("timer").innerHTML = displayMs(pomodoroTimer); const {ipcRenderer} = require('electron'); // variable to know at which step we currently are (from 0 to 7) // even step => pomodor // odd => brek (7 => long break) var step = 0; // let close the window with the close button var closeEl = document.querySelector('.close'); closeEl.addEventListener('click', function () { ipcRenderer.send('close-main-window'); }); // the settings button open the settings window var settingsEl = document.querySelector('.settings'); settingsEl.addEventListener('click', function () { ipcRenderer.send('open-settings-window'); }); // set all action button var actionButtons = document.querySelectorAll('.button-action'); for (var i = 0; i < actionButtons.length; i++) { var actionButton = actionButtons[i]; var actionName = actionButton.attributes['data-action'].value; prepareButton(actionButton, actionName); } // prepare each button function prepareButton(buttonEl, actionName) { buttonEl.querySelector('span').style.backgroundImage = 'url("img/icons/' + actionName + '.png")'; switch(actionName) { case 'start': buttonEl.addEventListener('click', function () { console.log('start'); if (step % 2 == 0){ timer_pomodoro.start(); } else{ if (step === 7){ timer_longBreak.start(); } else{ timer_shortBreak.start(); } } }); break; case 'stop': buttonEl.addEventListener('click', function () { timer_pomodoro.stop(); timer_pomodoro.reset(); document.getElementById("timer").innerHTML = displayMs(timer_pomodoro.time()); }); break; default: console.log('what?'); } } // at each poll from the timer we display the remaining time timer_pomodoro.on("poll", function (time) { document.getElementById("timer").innerHTML = displayMs(timer_pomodoro.time()); }); timer_pomodoro.on("done", function(time){ step = (step + 1)%8; timer_pomodoro.stop(); timer_pomodoro.reset(); document.getElementById("timer").innerHTML = displayMs(shortBreakTimer); document.getElementById("step").innerHTML = step+"/8"; }); // at each poll from the timer we display the remaining time timer_shortBreak.on("poll", function (time) { document.getElementById("timer").innerHTML = displayMs(timer_shortBreak.time()); }); timer_shortBreak.on("done", function(time){ step = (step + 1)%8; timer_shortBreak.stop(); timer_shortBreak.reset(); document.getElementById("timer").innerHTML = displayMs(timer_pomodoro.time()); document.getElementById("step").innerHTML = step+"/8"; }); // at each poll from the timer we display the remaining time timer_longBreak.on("poll", function (time) { document.getElementById("timer").innerHTML = displayMs(timer_longBreak.time()); }); timer_longBreak.on("done", function(time){ step = (step + 1)%8; timer_shortBreak.stop(); timer_shortBreak.reset(); document.getElementById("timer").innerHTML = displayMs(timer_pomodoro.time()); document.getElementById("step").innerHTML = step+"/8"; }); // display the ms timer in a human readable format "min:sec" function displayMs(time){ var m = Math.floor((time/60000)); var s = ((time % 60000)/1000).toFixed(0); if (s === 60){ s = 0 } return m + ":" + (s < 10 ? '0' : '') + s; }
JavaScript
0
@@ -1912,57 +1912,61 @@ -console.log('start');%0A if (step %25 2 == 0)%7B +if (step %25 2 == 0)%7B%0A timer_pomodoro.reset(); %0A @@ -2047,16 +2047,53 @@ === 7)%7B%0A + timer_longBreak.reset();%0A @@ -2141,32 +2141,70 @@ else%7B%0A + timer_shortBreak.reset();%0A time @@ -2334,32 +2334,62 @@ , function () %7B%0A + if (step %25 2 == 0)%7B%0A timer_po @@ -2403,32 +2403,34 @@ stop();%0A + timer_pomodoro.r @@ -2429,32 +2429,34 @@ modoro.reset();%0A + document @@ -2526,16 +2526,450 @@ ime());%0A + %7D%0A else%7B%0A if (step === 7)%7B%0A timer_longBreak.stop();%0A timer_longBreak.reset();%0A document.getElementById(%22timer%22).innerHTML = displayMs(timer_longBreak.time());%0A %7D%0A else%7B%0A timer_shortBreak.stop();%0A timer_shortBreak.reset();%0A document.getElementById(%22timer%22).innerHTML = displayMs(timer_shortBreak.time());%0A %7D%0A %7D%0A %7D) @@ -3256,32 +3256,55 @@ function(time)%7B%0A + console.log('done');%0A step = (step + @@ -3339,34 +3339,8 @@ ();%0A - timer_pomodoro.reset();%0A do @@ -3765,36 +3765,8 @@ ();%0A - timer_shortBreak.reset();%0A do @@ -4155,32 +4155,32 @@ = (step + 1)%258;%0A + timer_shortBre @@ -4194,36 +4194,8 @@ ();%0A - timer_shortBreak.reset();%0A do
f0567847372c1d9807861a4f0e61403e68ca3bbf
fix bug - report check in wrong place
tasks/utils/printer.js
tasks/utils/printer.js
var fs = require('fs'); var emitter = require('./emitter'); var toArray = require('./toArray'); var CONSOLE = 'console'; var NEWLINE = '\n'; var TAB = '\t'; var printStr = ''; var grunt, options = {report: false}; var PRINT_VERBOSE = 'print::verbose'; var PRINT_REPORT = 'print::report'; var PRINT_FILE = 'print::file'; var PRINT_LINE = 'print::line'; var PRINT_IGNORED = 'print:ignored'; var PRINT_FINALIZE = 'print::finalize'; var log = function () { if (!options.report) { return; } var args = Array.prototype.slice.call(arguments); if (options.log === CONSOLE) { grunt.log.writeln.apply(grunt.log, args); } else { for (var i = 0; i < args.length; i++) { printStr += grunt.log.uncolor(args[i]) + " "; } printStr += NEWLINE; } }; emitter.on(PRINT_REPORT, function (evt, strings) { if (options.report) { log.apply(null, toArray(strings)); } }); emitter.on(PRINT_VERBOSE, function (evt, strings) { if (options.report === 'verbose') { log.apply(null, toArray(strings)); } }); emitter.on(PRINT_FILE, function (evt, fileInfo, options) { fileInfo.from = fileInfo.from || 'Gruntfile.js'; var str = fileInfo.src[options.color]; var str2 = ' - ' + fileInfo.from; if (fileInfo.type === 'file') { str2 += ':' + fileInfo.line; } else { str2 += ':' + fileInfo.type + ' ' + fileInfo.value; } log.apply(null, toArray(TAB + str + str2.grey)); }); emitter.on(PRINT_LINE, function (evt, strings) { log.apply(null, toArray(strings)); }); emitter.on(PRINT_IGNORED, function (evt, ignored) { var i; if (ignored) { for (i in ignored) { if (ignored[i].ignoreCount) { emitter.fire(PRINT_FILE, ignored[i], {color: 'grey'}); } } } }); emitter.on(PRINT_FINALIZE, function (evt, data) { function getSize(path) { if (grunt.file.exists(path)) { var stat = fs.statSync(path); return (stat.size / 1024).toFixed(2); } } if (options.log === CONSOLE) { emitter.fire(PRINT_LINE, NEWLINE + "Files generated:"); emitter.fire(PRINT_LINE, TAB + data.path.blue, (getSize(data.path) + 'k').green); if (options.minify && data.pathMin) { emitter.fire(PRINT_LINE, TAB + data.pathMin.blue, (getSize(data.pathMin) + 'k').green); } } else { var output = "Files generated:" + NEWLINE + TAB + data.path + " " + getSize(data.path) + 'k' + NEWLINE; if (options.minify && data.pathMin) { output += TAB + data.pathMin + " " + getSize(data.pathMin) + 'k' + NEWLINE; } printStr = '------' + new Date().toLocaleString() + "------" + NEWLINE + NEWLINE + output + printStr; grunt.file.write(options.log, printStr); } }); exports.setGrunt = function(val) { grunt = val; }; exports.setOptions = function(val) { options = val; };
JavaScript
0
@@ -453,57 +453,8 @@ ) %7B%0A - if (!options.report) %7B%0A return;%0A %7D%0A @@ -2363,32 +2363,52 @@ %7D%0A %7D else + if (options.report) %7B%0A var o @@ -2841,32 +2841,33 @@ Grunt = function + (val) %7B%0A grun @@ -2908,16 +2908,17 @@ function + (val) %7B%0A
902414f0b159fdfb6c4b2ddd681143b61ebe2df7
Fix error from merge conflict.
app/js/index.js
app/js/index.js
import React from 'react' import 'babel-polyfill' import 'inert-polyfill' import '../styles/bootstrap.min.css' import '../styles/fonts.css' import '../styles/font-awesome.css' import '../styles/app.css' import { render } from 'react-dom' import { Provider } from 'react-redux' import routes from './routes' import { ThemeProvider } from 'styled-components' import theme from '@styled/theme' import log4js from 'log4js' import { authorizationHeaderValue } from './utils/api-utils' import { configureLogging } from './utils/logging-utils' import store from './store' const state = store.getState() const coreAPIPassword = state.settings.api.coreAPIPassword const logServerPort = state.settings.api.logServerPort configureLogging( log4js, logServerPort, authorizationHeaderValue(coreAPIPassword), process.env.NODE_ENV ) window.addEventListener('error', event => { // eslint-disable-next-line const logger = log4js.getLogger("window.addWindowListener('error')") logger.error(event) }) window.onerror = (messageOrEvent, source, lineno, colno, error) => { const logger = log4js.getLogger('window.onerror') logger.error(messageOrEvent, error) } const logger = log4js.getLogger('index.js') configureLogging( log4js, logServerPort, authorizationHeaderValue(coreAPIPassword), process.env.NODE_ENV ) if (process.env.NODE_ENV === 'production') { if ('serviceWorker' in navigator) { window.addEventListener('load', () => { navigator.serviceWorker .register('/sw.js') .then(registration => { console.log('SW registered: ', registration) }) .catch(registrationError => { console.log('SW registration failed: ', registrationError) }) }) } } window.addEventListener('error', event => { // eslint-disable-next-line const logger = log4js.getLogger("window.addWindowListener('error')") logger.error(event) }) window.onerror = (messageOrEvent, source, lineno, colno, error) => { const logger = log4js.getLogger('window.onerror') logger.error(messageOrEvent, error) } const logger = log4js.getLogger('index.js') if (process.env.NODE_ENV !== 'production') { logger.trace('NODE_ENV is not production') logger.debug('Enabling React devtools') window.React = React } render( <Provider store={store}> <ThemeProvider theme={theme}>{routes}</ThemeProvider> </Provider>, document.getElementById('app') ) }) if (module.hot) { module.hot.accept() }
JavaScript
0
@@ -1204,18 +1204,16 @@ x.js')%0A%0A - configur @@ -1222,18 +1222,16 @@ ogging(%0A - log4js @@ -1234,18 +1234,16 @@ g4js,%0A - - logServe @@ -1249,18 +1249,16 @@ erPort,%0A - author @@ -1296,18 +1296,16 @@ ord),%0A - - process. @@ -1321,15 +1321,11 @@ ENV%0A - )%0A%0A - if ( @@ -1365,18 +1365,16 @@ ion') %7B%0A - if ('s @@ -1407,18 +1407,16 @@ ) %7B%0A - - window.a @@ -1453,18 +1453,16 @@ %7B%0A - navigato @@ -1485,18 +1485,16 @@ - - .registe @@ -1505,18 +1505,16 @@ sw.js')%0A - @@ -1539,34 +1539,32 @@ =%3E %7B%0A - - console.log('SW @@ -1592,34 +1592,32 @@ ration)%0A - %7D)%0A .ca @@ -1611,18 +1611,16 @@ - - .catch(r @@ -1637,26 +1637,24 @@ nError =%3E %7B%0A - co @@ -1714,31 +1714,27 @@ or)%0A - - %7D)%0A - %7D)%0A %7D @@ -1734,19 +1734,13 @@ )%0A - - %7D%0A - %7D%0A%0A - wind @@ -1779,18 +1779,16 @@ nt =%3E %7B%0A - // esl @@ -1811,18 +1811,16 @@ -line%0A - - const lo @@ -1880,18 +1880,16 @@ ror')%22)%0A - logger @@ -1906,16 +1906,12 @@ nt)%0A - %7D)%0A%0A - wind @@ -1977,18 +1977,16 @@ =%3E %7B%0A - - const lo @@ -2027,18 +2027,16 @@ error')%0A - logger @@ -2069,62 +2069,11 @@ or)%0A - %7D%0A%0A - const logger = log4js.getLogger('index.js')%0A%0A if ( @@ -2113,18 +2113,16 @@ ion') %7B%0A - logger @@ -2158,18 +2158,16 @@ ction')%0A - logger @@ -2200,18 +2200,16 @@ tools')%0A - window @@ -2227,22 +2227,18 @@ act%0A - %7D%0A +%7D%0A render(%0A @@ -2233,18 +2233,16 @@ render(%0A - %3CProvi @@ -2260,18 +2260,16 @@ store%7D%3E%0A - %3CThe @@ -2318,18 +2318,16 @@ ovider%3E%0A - %3C/Prov @@ -2333,18 +2333,16 @@ vider%3E,%0A - docume @@ -2370,14 +2370,10 @@ p')%0A - )%0A%7D ) +%0A %0A%0Aif
338f8270b9c1743bc8f396cbf0cbb3d312f42d1e
add actual usage vs just billable usage
teksavvy-data-watch.js
teksavvy-data-watch.js
var CONFIG = require("./config"), nodemailer = require("nodemailer"), API_URL = "https://api.teksavvy.com/web/Usage/UsageRecords?$skip=40", urllib = require('urllib'), onPeakDownloadTotal = 0, onPeakUploadTotal = 0, offPeakDownloadTotal = 0, offPeakUploadTotal = 0; function downloadData (url) { urllib.request(url, { headers: { "TekSavvy-APIKey": CONFIG.API_KEY } }, function (err, rawData, res) { var functionStop = false, subject = "", message = ""; transporter = nodemailer.createTransport({ service: CONFIG.EMAIL_PROVIDER, auth: { user: CONFIG.EMAIL_USER, pass: CONFIG.EMAIL_PASSWORD } }); if (err) { throw err; } JSON.parse(rawData.toString()).value.reverse().forEach (function (currentDataElement, index, array) { var year = currentDataElement.Date.split("T")[0].split("-")[0], month = currentDataElement.Date.split("T")[0].split("-")[1], day = currentDataElement.Date.split("T")[0].split("-")[2], previousMonth = index >= 1 ? array[ index - 1 ].Date.split("T")[0].split("-")[1] : null; if (index > 1 && month != previousMonth) { functionStop = true; } if (!functionStop) { onPeakDownloadTotal += currentDataElement.OnPeakDownload, onPeakUploadTotal += currentDataElement.OnPeakUpload, offPeakDownloadTotal += currentDataElement.OffPeakDownload, offPeakUploadTotal += currentDataElement.OffPeakUpload; } }); var dataOverage = onPeakDownloadTotal - CONFIG.DATA_CAP, percentUsedOfDataCap = Math.round ((onPeakDownloadTotal / CONFIG.DATA_CAP) * 100); console.log (" OnPeak/OffPeak (GB)\n " + "D: " + onPeakDownloadTotal.toFixed(2) + "/" + offPeakDownloadTotal.toFixed(2) + "\n " + "U: " + onPeakUploadTotal.toFixed(2) + "/" + offPeakUploadTotal.toFixed(2)); if (onPeakDownloadTotal > CONFIG.DATA_CAP) { subject = "!!! ALERT !!!", message = "Data limit exceded by " + dataOverage.toFixed(2) + "GB"; } else if (onPeakDownloadTotal >= CONFIG.DATA_CAP * 0.80) { subject = "*** Warning ***", message = "You are at 80% of your data limit " + dataOverage.toFixed(2) + "GB"; } else if (onPeakDownloadTotal >= CONFIG.DATA_CAP * 0.50) { subject = "Data usage notice", message = "You are at 50% of your data limit " + dataOverage.toFixed(2) + "GB"; } console.log ("Used " + onPeakDownloadTotal + "GB of " + CONFIG.DATA_CAP + "GB or " + percentUsedOfDataCap + "%"); var mailOptions = { from: "TekSavvy Data Watch <usage@data.teksavvy>", to: "stevenharradine@gmail.com", subject: subject, text: message, html: message }; // if lowest threshold for sending mail if (onPeakDownloadTotal >= CONFIG.DATA_CAP * 0.50) { // send mail with defined transport object transporter.sendMail(mailOptions, function(error, info){ if (error){ console.log(error); } else { console.log("Message sent: " + info.response); } }); } }); } downloadData (API_URL);
JavaScript
0
@@ -2549,16 +2549,17 @@ al + %22GB +* of %22 + @@ -2615,16 +2615,194 @@ + %22%25%22); +%0A%09%09console.log (%22%22);%0A%09%09console.log (%22* Billable usage, actual usage %22 + (onPeakDownloadTotal + offPeakDownloadTotal + onPeakUploadTotal + offPeakUploadTotal).toFixed(2) + %22GB%22 ); %0A%0A%09%09var
c1722979ee7258dda36ec425c3c641db778c1beb
call notify if notifyBlocking is not defined
lib/Bugsnag.js
lib/Bugsnag.js
import { NativeModules } from 'react-native'; const NativeClient = NativeModules.BugsnagReactNative; /** * A Bugsnag monitoring and reporting client */ export class Client { /** * Creates a new Bugsnag client */ constructor(apiKeyOrConfig) { if (apiKeyOrConfig.constructor === String) { this.config = new Configuration(apiKeyOrConfig); } else if (apiKeyOrConfig instanceof Configuration) { this.config = apiKeyOrConfig; } else { throw new Error('Bugsnag: A client must be constructed with an API key or Configuration'); } if (NativeClient) { NativeClient.startWithOptions(this.config.toJSON()); this.handleUncaughtErrors(); if (this.config.handlePromiseRejections) this.handlePromiseRejections(); } else { throw new Error('Bugsnag: No native client found. Is BugsnagReactNative installed in your native code project?'); } } /** * Registers a global error handler which sends any uncaught error to * Bugsnag before invoking the previous handler, if any. */ handleUncaughtErrors = () => { if (ErrorUtils) { const previousHandler = ErrorUtils.getGlobalHandler(); ErrorUtils.setGlobalHandler((error, isFatal) => { if (this.config.autoNotify) { this.notify(error, report => {report.severity = 'error'}, true, () => { if (previousHandler) { previousHandler(error, isFatal); } }); } else if (previousHandler) { previousHandler(error, isFatal); } }); } } handlePromiseRejections = () => { const tracking = require('promise/setimmediate/rejection-tracking'), client = this; tracking.enable({ allRejections: true, onUnhandled: function(id, error) { client.notify(error); }, onHandled: function() {} }); } /** * Sends an error report to Bugsnag * @param error The error instance to report * @param beforeSendCallback A callback invoked before the report is sent * so additional information can be added * @param blocking When true, blocks the native thread execution * until complete. If unspecified, sends the * request asynchronously * @param postSendCallback Callback invoked after request is queued */ notify = async (error, beforeSendCallback, blocking, postSendCallback) => { if (!(error instanceof Error)) { console.warn('Bugsnag could not notify: error must be of type Error'); return; } if (!this.config.shouldNotify()) { return; } const report = new Report(this.config.apiKey, error); for (callback of this.config.beforeSendCallbacks) { if (callback(report) === false) { return; } } if (beforeSendCallback) { beforeSendCallback(report); } NativeClient.notifyBlocking(report.toJSON(), blocking || false, postSendCallback); } setUser = (id, name, email) => { NativeClient.setUser({id, name, email}); } /** * Clear custom user data and reset to the default device identifier */ clearUser = () => { NativeClient.clearUser(); } /** * Leaves a 'breadcrumb' log message. The most recent breadcrumbs * are attached to subsequent error reports. */ leaveBreadcrumb = (name, metadata) => { if (name.constructor !== String) { console.warn('Breadcrumb name must be a String'); return; } if (metadata == undefined) { metadata = {}; } if (metadata.constructor === String) { metadata = {'message': metadata }; } if (!metadata instanceof Object) { console.warn('Breadcrumb metadata is not an Object or String, discarding'); metadata = {}; } let type = metadata['type'] || 'manual'; delete metadata['type']; NativeClient.leaveBreadcrumb({ name, type, metadata: typedMap(metadata) }); } } /** * Configuration options for a Bugsnag client */ export class Configuration { constructor(apiKey) { const metadata = require('../package.json') this.version = metadata['version']; this.apiKey = apiKey; this.delivery = new StandardDelivery() this.beforeSendCallbacks = []; this.notifyReleaseStages = undefined; this.releaseStage = undefined; this.appVersion = undefined; this.autoNotify = true; this.handlePromiseRejections = !__DEV__; // prefer banner in dev mode } /** * Whether reports should be sent to Bugsnag, based on the release stage * configuration */ shouldNotify = () => { return !this.releaseStage || !this.notifyReleaseStages || this.notifyReleaseStages.includes(this.releaseStage); } /** * Adds a function which is invoked after an error is reported but before * it is sent to Bugsnag. The function takes a single parameter which is * an instance of Report. */ registerBeforeSendCallback = (callback) => { this.beforeSendCallbacks.push(callback) } /** * Remove a callback from the before-send pipeline */ unregisterBeforeSendCallback = (callback) => { const index = this.beforeSendCallbacks.indexOf(callback); if (index != -1) { this.beforeSendCallbacks.splice(index, 1); } } /** * Remove all callbacks invoked before reports are sent to Bugsnag */ clearBeforeSendCallbacks = () => { this.beforeSendCallbacks = [] } toJSON = () => { return { apiKey: this.apiKey, releaseStage: this.releaseStage, notifyReleaseStages: this.notifyReleaseStages, endpoint: this.delivery.endpoint, appVersion: this.appVersion, version: this.version }; } } export class StandardDelivery { constructor(endpoint) { this.endpoint = endpoint || 'https://notify.bugsnag.com'; } } /** * A report generated from an error */ export class Report { constructor(apiKey, error) { this.apiKey = apiKey; this.errorClass = error.constructor.name; this.errorMessage = error.message; this.context = undefined; this.groupingHash = undefined; this.metadata = {}; this.severity = 'warning'; this.stacktrace = error.stack; this.user = {}; } /** * Attach additional diagnostic data to the report. The key/value pairs * are grouped into sections. */ addMetadata = (section, key, value) => { if (!this.metadata[section]) { this.metadata[section] = {}; } this.metadata[section][key] = value; } toJSON = () => { return { apiKey: this.apiKey, context: this.context, errorClass: this.errorClass, errorMessage: this.errorMessage, groupingHash: this.groupingHash, metadata: typedMap(this.metadata), severity: this.severity, stacktrace: this.stacktrace, user: this.user } } } const allowedMapObjectTypes = ['string', 'number', 'boolean']; /** * Convert an object into a structure with types suitable for serializing * across to native code. */ const typedMap = function(map) { const output = {}; for (const key in map) { const value = map[key]; if (value instanceof Object) { output[key] = {type: 'map', value: typedMap(value)}; } else { const type = typeof value; if (allowedMapObjectTypes.includes(type)) { output[key] = {type: type, value: value}; } } } return output; }
JavaScript
0
@@ -2928,24 +2928,65 @@ rt);%0A %7D%0A%0A + if (NativeClient.notifyBlocking) %7B%0A NativeCl @@ -3025,110 +3025,109 @@ N(), -%0A blocking %7C%7C false,%0A postSendCallback); + blocking %7C%7C false, postSendCallback);%0A %7D else %7B%0A NativeClient.notify(report.toJSON());%0A %7D %0A %7D
58d997d00fdb819066c84fb97ed12c969e13d3af
remove console.log
lib/Channel.js
lib/Channel.js
var Model = require('./Model'); var Note = require('./Note'); var Collection = require('./Collection'); var volumeParams = require('./mixins/volumeParams'); // var debounce = require('lodash.debounce'); var expressions = require('dilla-expressions'); var NotesCollection = Collection.extend({ model: Note }); var Channel = Model.extend(volumeParams, { type: 'channel', props: { transform: 'function' }, collections: { rawNotes: NotesCollection, expandedNotes: NotesCollection }, initialize: function () { Model.prototype.initialize.apply(this, arguments); this._cache = {}; this.listenTo(this.rawNotes, 'start', this._start); this.listenTo(this.rawNotes, 'stop', this._stop); this.listenTo(this.rawNotes, 'add', this._onAddRawNote); this.listenTo(this.rawNotes, 'remove', this._onRemoveRawNote); this.listenTo(this.rawNotes, 'change:position', this._onChangeRawNote); this.listenTo(this.expandedNotes, 'add', this._onAddExpandedNote); this.listenTo(this.expandedNotes, 'remove', this._onRemoveExpandedNote); }, add: function () { var notes = [].slice.call(arguments).map(function (raw) { return raw instanceof Note ? raw : Note.fromRaw(raw); }); this.rawNotes.add(notes); }, notes: function (bar, beat, tick) { if (!bar) return this.expandedNotes.models.slice(); var cache = this._cache; var beats = cache[bar]; if (!beat) return beats['*'].slice(); var ticks = beats[beat]; if (!tick) return ticks['*'].slice(); return ticks[tick].slice(); }, _onAddExpandedNote: function (note) { var cache = this._cache; cache[note.bar] = cache[note.bar] || {}; cache[note.bar]['*'] = cache[note.bar]['*'] || []; cache[note.bar]['*'].push(note); cache[note.bar][note.beat] = cache[note.bar][note.beat] || {}; cache[note.bar][note.beat]['*'] = cache[note.bar][note.beat]['*'] || []; cache[note.bar][note.beat]['*'].push(note); cache[note.bar][note.beat][note.tick] = cache[note.bar][note.beat][note.tick] || []; cache[note.bar][note.beat][note.tick].push(note); }, _onRemoveExpandedNote: function (note) { var cache = this._cache; var barIndex = cache[note.bar]['*'].indexOf(note); cache[note.bar]['*'].splice(barIndex, 1); var beatIndex = cache[note.bar][note.beat]['*'].indexOf(note); cache[note.bar][note.beat]['*'].splice(beatIndex, 1); var tickIndex = cache[note.bar][note.beat][note.tick].indexOf(note); cache[note.bar][note.beat][note.tick].splice(tickIndex, 1); }, _onAddRawNote: function (note) { var pattern = this.collection && this.collection.parent; var options = { barsPerLoop: pattern && pattern.bars || 1, beatsPerBar: pattern && pattern.beatsPerBar || 4 }; expressions([[note.position]], options).forEach(function (position) { var ghost = note.ghost({ position: position[0] }); this.expandedNotes.add(ghost); }.bind(this)); }, _onRemoveRawNote: function (note) { this.expandedNotes.models.slice().forEach(function (ghost) { console.log('?', ghost.position, ghost.key, !!ghost.original, note === ghost.original) if (note === ghost.original) { this.expandedNotes.remove(ghost); note.detachGhost(ghost); } }.bind(this)); }, _onChangeRawNote: function (note) { this._onRemoveRawNote(note); this._onAddRawNote(note); }, _start: function (time, note) { if (!this.mute) { this.trigger('start', time, note, this); } }, _stop: function (time, note) { this.trigger('stop', time, note, this); } }); module.exports = Channel;
JavaScript
0.000006
@@ -3080,101 +3080,8 @@ ) %7B%0A - console.log('?', ghost.position, ghost.key, !!ghost.original, note === ghost.original)%0A
19e03b9f4305be90f22b15cc964c91daac4db198
serilize regex to string
Utility/build_syntax.js
Utility/build_syntax.js
#!/usr/bin/env node var fs = require("fs"); var output_dir = ""; var input_dir = ""; function report_error(msg) { console.error(msg); process.exit(-1); } function parse_args(args) { args = args.slice(2); if (args.length == 0) report_error("should run with parameters"); for (i = 0; i < args.length; i++){ if (args[i] == "-i") { input_dir = args[++i]; } else if (args[i] == "-o"){ output_dir = args[++i]; } else { report_error("unknown option"); } } } function list_language(input_dir) { var filepath = []; var files = fs.readdirSync(input_dir); for (var i in files) { if (/.*\.js$/.test(files[i])) { filepath.push(files[i].substring(0, files[i].length-3)); } } return filepath; } has_cyclic_ref = false; function find_ref(obj, path) { has_cyclic_ref = true; var ref = ["ref"]; var i = 0; var found = false; for (i = 0; i < path.length; i++) { ref.push(path[i].key); //push path element name if (path[i].obj == obj) { found = true; break; } } if (!found) { report_error("there declared to be a cyclic reference in the path " + path + " but we cannot found it"); } return ref.join(":"); } function shadow_copy(obj) { var result = {}; if (obj.constructor == Array) result = []; for (var key in obj) { result[key] = obj[key]; } return result; } function remove_cyclic_ref(obj, path){ if(typeof obj != "object") return obj; var new_obj = shadow_copy(obj); // we do not modify this object directly, because this may be a **shared object** that are referenced in other place obj.visited = true; for(var key in new_obj){ if (obj[key] == null) continue; if (obj[key].visited){ new_obj[key] = find_ref(obj[key], path); } else { var child = remove_cyclic_ref(obj[key], path.concat({"key":key, "obj":obj[key]})); new_obj[key] = child; } } delete obj.visited; return new_obj; } var hljs = require("./tmp/build/lib/index.js"); function get_defs() { var lang_defs = []; var lang_names = hljs.listLanguages(); for (var i = 0; i < lang_names.length; i++){ var lang_hash = hljs.getLanguage(lang_names[i]); try{ has_cyclic_ref = false; lang_hash = remove_cyclic_ref(lang_hash, []); lang_hash["name"] = lang_names[i]; if (has_cyclic_ref) console.error("WARNING: language " + lang_names[i] + " contains cyclic reference"); var json = JSON.stringify(lang_hash, null, " "); lang_defs.push(json); } catch(e){ console.error(e.stack); report_error(e); console.log("Language: " + lang_names[i]); } } return lang_defs; } function get_names() { return hljs.listLanguages(); } function write_syntax(names, defs) { for (var i = 0; i < names.length; i++) { var file = output_dir + "/" + names[i] + ".json"; fs.writeFileSync(file, defs[i]); } } parse_args(process.argv); var lang_defs = get_defs(); var lang_names = get_names(); write_syntax(lang_names, lang_defs);
JavaScript
0.999982
@@ -1360,30 +1360,60 @@ %09if( -typ +! (obj instanc eof -obj != %22object%22 +Object) %7C%7C (obj instanceof RegExp) ) re @@ -1941,16 +1941,121 @@ ex.js%22); +%0Afunction replacer(key, value) %7B%0A%09if (value instanceof RegExp) return value.source;%0A%09else return value;%0A%7D %0A%0Afuncti @@ -2498,20 +2498,24 @@ g_hash, -null +replacer , %22 %22);
4b2ad6ca95196a7b44a37a46cf79a11091e140fc
Fix crash on monitor component launch
lib/Monitor.js
lib/Monitor.js
var EventEmitter = require('eventemitter2').EventEmitter2, util = require('util'), Discovery = require('./Discovery'), axon = require('axon'), portfinder = require('portfinder'), _ = require('lodash'), charm = require('charm')(); var Monitor = function(advertisement, discoveryOptions) { discoveryOptions = discoveryOptions || {}; _.defaults(discoveryOptions, { monitor: true, log: false }); advertisement.type = 'monitor'; advertisement.key = Monitor.environment + (advertisement.key || ''); var that = this, d = this.discovery = Discovery(advertisement, discoveryOptions), host = discoveryOptions && discoveryOptions.address || '0.0.0.0', interval = discoveryOptions.interval || 5000; portfinder.getPort({host: host, port: advertisement.port}, onPort); function onPort(err, port) { if (err) process.exit(err); advertisement.port = +port; var sub = new axon.SubEmitterSocket(port); sub.bind(port); sub.server.on('error', function(err) { if (err.code != 'EADDRINUSE') throw err; portfinder.getPort({host: host, port: advertisement.port}, onPort); }); sub.on('bind', function() { sub.on('status', function(status) { that.emit('status', status); }); }); } if (discoveryOptions.disableScreen) return; charm.pipe(process.stdout); charm.reset().erase('screen').position(0, 0). write(' '); (function draw() { charm.erase('screen'); var index = 3; charm.position(0, 2); charm.foreground('green'). write('Name').move(16). write('id').move(33). write('Address').move(11). write('Port'); charm.erase('down'); d.eachNode(function(node) { var port = node.advertisement.port || '----'; port += ''; charm.position(0, index).foreground('cyan'). write(node.advertisement.name.slice(0, 20)).move(20 - node.advertisement.name.length, 0). foreground('magenta').write(node.id).move(3, 0). foreground('yellow').write(node.address).move(3, 0). foreground('red').write(port); index++; }); charm.position(0, 1); setTimeout(draw, interval); })(); }; util.inherits(Monitor, EventEmitter); Monitor.environment = ''; Monitor.setEnvironment = function(environment) { Monitor.environment = environment + ':'; }; module.exports = Monitor;
JavaScript
0.000001
@@ -1047,13 +1047,11 @@ ub.s -erver +ock .on(
7768f52f92054ac8cd0b2cbd78047c10c746b4aa
Fix vue-kitchen-sink config
examples/vue-kitchen-sink/.storybook/main.js
examples/vue-kitchen-sink/.storybook/main.js
module.exports = { stories: ['../src/stories/**/*.stories.(js|mdx)'], addons: [ '@storybook/addon-docs/preset', '@storybook/addon-storysource', '@storybook/addon-actions', '@storybook/addon-links', '@storybook/addon-notes', '@storybook/addon-knobs', '@storybook/addon-viewport', '@storybook/addon-options', '@storybook/addon-backgrounds', '@storybook/addon-a11y', '@storybook/addon-contexts', '@storybook/addon-docs', ], };
JavaScript
0.000066
@@ -107,15 +107,8 @@ docs -/preset ',%0A @@ -431,37 +431,8 @@ s',%0A - '@storybook/addon-docs',%0A %5D,
9f5d81c3239c502591c731593ca37a42edbd43d3
Add code format
keyframes-tool.js
keyframes-tool.js
/*! Keyframes-Tool | The MIT License (MIT) | Copyright (c) 2017 GibboK */ const css = require('css'); const R = require('ramda'); const fs = require('fs'); const path = require('path'); let fileIn, fileOut; /** * Check software requirements. */ let checkPrerequisites = () => { return new Promise((fulfill, reject) => { try { // check node version let getNodeVersion = strVersion => { let numberPattern = /\d+/g; return numVersion = Number(strVersion.match(numberPattern).join('')) }, requiredVersion = getNodeVersion('v6.9.1'), currentVersion = getNodeVersion(process.version); if (currentVersion >= requiredVersion) { fulfill(); } else { throw ('you current version of node.js is not supported, please update to the latest version of node.js'); } } catch (err) { reject(err); } }); }; /** * Get arguments passed by Node.js from terminal. */ let getNodeArguments = () => { return new Promise((fulfill, reject) => { try { // check paths in arguments let hasFileInOutArgs = process.argv.length === 4; if (!hasFileInOutArgs) { throw ('arguments for file-in and file-out must be provided'); } // normalize paths fileIn = path.resolve(path.normalize(process.argv[2])).toString(); fileOut = path.resolve(path.normalize(process.argv[3])).toString(); // check paths for extensions let isFileInCss = fileIn.endsWith('.css'), isFileOutJson = fileOut.endsWith('.json'); if (!isFileInCss) { throw ('argument file-in must have extension .css'); } if (!isFileOutJson) { throw ('argument file-out must have extension .json'); } fulfill(); } catch (err) { reject(err); } }); }; /** * Read CSS input file. */ let readInputFile = () => { // read css file return new Promise((fulfill, reject) => { fs.readFile(fileIn, (err, data) => { if (err) { reject(err); } else { fulfill(data); } }); }); } /** * Parse content of CSS input file and create an AST tree. */ let parse = data => { return new Promise((fulfill, reject) => { try { let parsedData = css.parse(data.toString(), { silent: false }); fulfill(parsedData); } catch (err) { reject(err); } }); }; /** * Validate AST tree content. */ let validate = data => { return new Promise((fulfill, reject) => { try { let isStylesheet = data.type === 'stylesheet', hasNoParsingErrors = 'stylesheet' in data && data.stylesheet.parsingErrors.length === 0, hasKeyframes = R.any((rule) => rule.type === 'keyframes', data.stylesheet.rules); if (!isStylesheet || !hasNoParsingErrors || !hasKeyframes) { if (!isStylesheet) { throw 'ast is not of type stylesheet'; } if (!hasNoParsingErrors) { R.map(err => console.log(new Error(`error: ${err}`)), data.stylesheet.parsingErrors); throw 'file has parse error'; } if (!hasKeyframes) { throw 'no keyframes rules found'; } } fulfill(data); } catch (err) { reject(err); } }); }; /** * Process AST tree content and a new data structure valid for Web Animation API KeyframeEffect. * The following code uses Ramda.js for traversing a complex AST tree, * an alternative and simplified version is visible at http://codepen.io/gibbok/pen/PbRrxp */ let processAST = data => { return new Promise((fulfill, reject) => { try { let processKeyframe = (vals, declarations) => [ // map each value R.map(R.cond([ [R.equals('from'), R.always("0")], [R.equals('to'), R.always("1")], [R.T, R.pipe( // covert `offset` to a string representing a decimal point parseFloat, R.divide(R.__, 100), R.toString() )] ]), vals), // collect all property value pairs and merge in one object R.reduce(R.merge, {}, R.map(R.converge(R.objOf, [ R.prop('property'), R.prop('value') ]), declarations)) ]; let processAnimation = (offsets, transf) => // process offset property R.map(R.pipe( R.objOf('offset'), R.merge(transf)), offsets); let getContentOfKeyframes = R.map(R.pipe( // process keyframes R.converge(processKeyframe, [ R.prop('values'), R.prop('declarations') ]), // process animations R.converge(processAnimation, [ R.nth(0), R.nth(1) ]))); let transformAST = R.pipe( // get `stylesheet.rules` property R.path(['stylesheet', 'rules']), // get only object whose `type` property is `keyframes` R.filter(R.propEq('type', 'keyframes')), // map each item in `keyframes` collection // to an object `{name: keyframe.name, content: [contentOfkeyframes] }` R.map((keyframe) => ({ name: keyframe.name, content: getContentOfKeyframes(keyframe.keyframes) })), // make a new object using animation `name` as keys // and using a flatten content as values R.converge(R.zipObj, [ R.map(R.prop('name')), R.map(R.pipe(R.prop('content'), R.flatten)) ]) ); // order by property `offset` ascending let orderByOffset = R.map(R.pipe(R.sortBy(R.prop('offset')))); // convert hyphenated properties to camelCase let convertToCamelCase = data => { let mapKeys = R.curry((fn, obj) => R.fromPairs(R.map(R.adjust(fn, 0), R.toPairs(obj))) ), camelCase = (str) => str.replace(/[-_]([a-z])/g, (m) => m[1].toUpperCase()) return R.map(R.map(mapKeys(camelCase)), data) }; // convert `animationTimingFunction` to `easing` for compatibility with web animations api // and assign `easing` default value to `ease` when `animation-timing-function` from css file is not provided let convertToEasing = data => { const convert = data => { const ease = R.prop('animationTimingFunction', data) || 'ease'; return R.dissoc('animationTimingFunction', R.assoc('easing', ease, data)); }; let result = R.map(R.map(convert))(data); return result; }; // process let process = R.pipe( transformAST, orderByOffset, convertToCamelCase, convertToEasing ); let result = process(data); fulfill(result); } catch (err) { reject(err); } }); }; /** * Write JSON output file. */ let writeOutputFile = data => { return new Promise((fulfill, reject) => { data = JSON.stringify(data); fs.writeFile(fileOut, data, (err) => { if (err) { reject(err); } else { fulfill(data); } }); }); }; /** * Initiate conversion process. */ let init = () => { checkPrerequisites().then(() => { return getNodeArguments(); }).then(() => { return readInputFile(); }).then(data => { return parse(data); }).then(data => { return validate(data); }).then(data => { return processAST(data); }).then(data => { return writeOutputFile(data); }).then(data => { console.log('success: file created at: ' + fileOut); }).catch(err => { console.log('error: ' + err); }); }; init();
JavaScript
0.000035
@@ -7536,27 +7536,16 @@ %7D;%0A - %0A
bfa431493680c980eb8c3243d02df1616450d0a5
Update main.js
Server/main.js
Server/main.js
"use strict"; var express = require("express"), logger = require("morgan"), cookieParser = require("cookie-parser"), bodyParser = require("body-parser"), methodOverride = require("method-override"), session = require("express-session"), mongojs = require("mongojs"), compression = require('compression'); const MongoStore = require("connect-mongo")(session); let app = express(); let config = { db: process.env.DBURL }; // Integrate Middleware app.use(logger("dev")); app.use(methodOverride("_method")); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(session({ secret: "keyboard cat", store: new MongoStore({ url: config.db }) })); app.use((req, res, next) => { // MONGOJS - See GH for Docs req.db = mongojs(config.db); next(); }); app.get("/dynamic", (req, res) => { res.send("Hello, world"); }); app.use(compression()); app.use(express.static("Build/Client")); // require("./routes/test.js")(app); var server = app.listen(process.env.PORT || 3000, () => { var {address: host, port} = server.address(); console.log(`Listening on http://${host}:${port}/`); }); var io = require("socket.io")(server) // usernames which are currently connected to the chat var usernames = {}; var numUsers = 0; //new stuff, in addition to chat parts above var users = {}; var teams = {}; io.on('connection', function (socket) { socket.on("register", function(data){ //eventually add auth here socket.username = data.username; users[data.username] = {socket: socket}; socket.emit("loggedin", data.username); }); socket.on("checkusername", function(username){ if(false){ //add auth check here socket.emit("usernamecheckresponse", "not available"); } }); socket.on("checkteamname", function(teamname){ console.log(teamname); console.log(teams); console.log(teamname in teams); if(teamname in teams){ if(teams[teamname].users.length == 5){ socket.emit("teamcheckresponse", "full"); } else{ socket.emit("teamcheckresponse", "exists"); } } else{ socket.emit("teamcheckresponse", "new"); } }); socket.on("jointeam", function(teamname){ if(!(teamname in teams)){ teams[teamname] = { name: teamname, users: [] }; } teams[teamname].users.push(socket.username); console.log(teams); users[socket.username].teamname = teamname; socket.emit("joinedteam"); teams[teamname].users.forEach(function(user){ socket.emit("newmember", user); if(user !== socket.username){ console.log("users"); console.log(users); users[user].socket.emit("newmember", socket.username); } }); if(teams[teamname].users.length == 5){ teams[teamname].users.forEach(function(user){ users[user].socket.emit("readytoselect"); }); } console.log("Teams: " + JSON.stringify(teams)); for (let i in users) { console.log("" + i + ": " + users[i]); } //debugger; }); socket.on("requestgamestart", function () { console.log("Recieved a request to start the game"); let teamname = users[socket.username].teamname; let team = teams[teamname]; for (let username of team.users) { users[username].socket.emit("startgame"); console.log("Telling user to start: " + username); } }); socket.on("position-update-user", function(data){ //console.log("" + socket.username + "sent position update " + JSON.stringify(data)); let teamname = users[socket.username].teamname; let team = teams[teamname]; for (let username of team.users) { if (username !== socket.username) { let user = users[username]; data.user = socket.username; user.socket.emit("position-update-others", data); } } }); });
JavaScript
0.000001
@@ -984,18 +984,32 @@ nt%22));%0A%0A -// +app.use(%22/api/%22, require @@ -1023,21 +1023,16 @@ tes/ -test +api .js%22) -(app );%0A%0A
4ed1f73aaa922e8b71300d0fbc1ae0b2dc5a8f48
Update Updater.js
lib/Updater.js
lib/Updater.js
"use strict"; var chalk = require('chalk'); var readline = require('readline'); var rl = readline.createInterface(process.stdin, process.stdout); var sys = require('sys'); var exec = require('child_process').exec; var fs = require('fs'); var request = require('request'); var tempWrite = require('temp-write'); function checkForUpdate() { console.log(chalk.magenta("[UPDATER] Checking for updates...")); fs.readFile('./package.json', 'utf-8', function(err, data) { if (err) { console.error(err); process.exit(); } request('https://raw.githubusercontent.com/LifeMushroom/Modular-Node.js-IRC-Bot/master/package.json', function(error, response, body) { if (!error && response.statusCode == 200) { if (JSON.parse(body).version > JSON.parse(data).version) { console.log(chalk.magenta("[UPDATER]" + " Update Found!")); rl.question(chalk.magenta("Update? [yes]/no: "), function(answer) { if (answer == 'yes') { fs.readFile('./config.js', 'utf-8', function (err, data) { if (err) { console.error(err); process.exit(); } var tempconfig = tempWrite.sync(data); exec("git pull"); fs.writeFile('./old_config.js', fs.readFileSync(tempconfig, 'utf-8'), function (err) { if (err) { console.error(err); process.exit(); } console.log(chalk.magenta("[UPDATER] Successfully updated! Your new configuration's name is \"config_old.js\".")); console.log(chalk.magenta("[UPDATER] Please check your \"config.js\" to add the new features to your \"config_old.js\" and then rename your \"config_old.js\" to \"config.js\"")); console.log(chalk.magenta("[UPDATER] Please re-run your bot when you are ready!")); process.exit(); }); }); } else { console.log(chalk.magenta("[UPDATER] Update Aborted")); } }); } else { console.log(chalk.magenta("[UPDATER] No updates found... Booted up!")); } } else { console.error(err); } }); }); } checkForUpdate();
JavaScript
0.000001
@@ -588,20 +588,21 @@ com/ -LifeMushroom +PranavMahesh1 /Mod
ea20e28f5c60420a7ad5bc3fb2fa2dcb0cc353cc
Remove Register() binding; it's been deprecated
lib/account.js
lib/account.js
module.exports = function(exports) { // ************************ // Contacts Methods // ************************ var https = require('https') , qs = require('querystring') , vars = exports.vars ; /** * Retrieves the basic account information for the Dwolla account associated with the account identifier. * https://www.dwolla.com/developers/endpoints/users/basicinformation * * @param {String} id * @param {Function} fn **/ exports.basicAccountInfo = function(id, fn) { if (typeof fn !== 'function') { throw new Error('Missing callback'); } if (!vars._client_id) { throw new Error('Missing arg client_id'); } if (!vars._client_secret) { throw new Error('Missing arg client_secret'); } if (!id) { throw new Error('Missing arg id'); } var path = '/users/' + id; var params = {}; params.client_id = vars._client_id; params.client_secret = vars._client_secret; exports._request(path, params, fn); }; /** * Retrieves the account information for the user assoicated with the authorized access token. * https://www.dwolla.com/developers/endpoints/users/accountinformation * * @param {Function} fn **/ exports.fullAccountInfo = function(fn) { if (typeof fn !== 'function') { throw new Error('Missing callback'); } if (!vars._token) { throw new Error('Missing arg oauth_token'); } var params = { oauth_token: vars._token }; exports._request('/users/', params, fn); }; /** * Retrieves the account balance for the user for the authorized access token. * https://www.dwolla.com/developers/endpoints/balance/account * * @param {Function} fn * */ exports.balance = function(fn) { if (typeof fn !== 'function') { throw new Error('Missing callback'); } if (!vars._token) { throw new Error('Missing arg oauth_token'); } var params = { oauth_token: vars._token }; exports._request('/balance/', params, fn); }; /** * Register a new Dwolla user account. * https://www.dwolla.com/developers/endpoints/register/user * * @param {Object} userInfo * @param {Function} fn */ exports.register = function(userInfo, fn) { if (typeof fn !== 'function') { throw new Error('Missing callback'); } if (!vars._client_id) { throw new Error('Missing arg client_id'); } if (!vars._client_secret) { throw new Error('Missing arg client_secret'); } if (!userInfo) { throw new Error('Missing arg userInfo'); } var params = {}; params.client_id = vars._client_id; params.client_secret = vars._client_secret; exports._post('/register/?' + qs.stringify(params), userInfo, fn); }; }
JavaScript
0
@@ -2092,748 +2092,5 @@ %0A - %0A /**%0A * Register a new Dwolla user account.%0A * https://www.dwolla.com/developers/endpoints/register/user%0A *%0A * @param %7BObject%7D userInfo%0A * @param %7BFunction%7D fn%0A */%0A exports.register = function(userInfo, fn) %7B%0A if (typeof fn !== 'function') %7B throw new Error('Missing callback'); %7D%0A if (!vars._client_id) %7B throw new Error('Missing arg client_id'); %7D%0A if (!vars._client_secret) %7B throw new Error('Missing arg client_secret'); %7D%0A if (!userInfo) %7B throw new Error('Missing arg userInfo'); %7D%0A %0A var params = %7B%7D;%0A params.client_id = vars._client_id;%0A params.client_secret = vars._client_secret;%0A exports._post('/register/?' + qs.stringify(params), userInfo, fn);%0A %7D;%0A %7D
2ec0985f70d44782da08f4566ef721636408e904
update file /lib/account.js
lib/account.js
lib/account.js
var mbaasApi = require('fh-mbaas-api'); var q = require('q'); var request = require('request'); var Account = function () { this.login = oAuthPostLogin; /** * This function consumes the sessionToken, and the authResponse * * @param {String} sessionToken session token returned by the OAuth mbaas * @param {Object} authResponse authResponse returned by Google * @param {Callback} callback a node callback * @returns nothing, but returns the session on the callback */ function oAuthPostLogin(req, res) { console.log(req.body); var sessionToken = req.body.sessionToken; var authResponse = req.body.authResponse; var callback = function(error, data) { if (error){ res.statusCode = 500; console.log('login error', error); return res.end(error); } else { res.json(data); } } mbaasApi.session.get(sessionToken, function (err, session) { if (!session) { initSession(sessionToken, authResponse, callback); } else { callback(null, session); } }); } /** * Validate the user's session info with Google, and create a session object. * This will also create a account object if necessary. * * @param {String} sessionToken session token returned by the OAuth mbaas * @param {Object} authResponse authResponse returned by Google * @param {Callback} nodeCallback a node callback */ function initSession(sessionToken, authResponse, nodeCallback) { //validate with google var options = { url: 'https://www.googleapis.com/oauth2/v2/userinfo', method: 'GET', headers: {'Authorization': 'Bearer ' + authResponse.authToken} }; request.request(request, handleGoogleResponse(sessionToken, authResponse, nodeCallback)).end(); } /** * * This callback consumes Google's response, and performs the appropriate * actions on the session. (Set session optionally creating the account). * * @param {type} sessionToken * @param {type} authResponse * @param {type} nodeCallback * @returns session Data on callback if successful, error on callback otherwise */ function handleGoogleResponse(sessionToken, authResponse, nodeCallback) { return function (response) { var body = ''; //another chunk of data has been recieved, so append it to `str` response.on('data', function (chunk) { body += chunk; }); //the whole response has been recieved, so we just print it out here response.on('end', function () { var resObject = JSON.parse(body); if (authResponse.id === resObject.id) { //load from storage checkAccountAndCreateSession(resObject.id, sessionToken, authResponse, nodeCallback); } else { nodeCallback('Id for client does not match id for token.'); } }); response.on('error', function (e) { nodeCallback(e); }); }; } /** * Loads a users data onto the session or creates a user and loads * authResponse onto the session * * @param {Sting} googleUserId * @param {Sting} sessionToken * @param {Object} authResponse * @param {NodeCallback} nodeCallback * @returns session Data on callback if successful, error on callback otherwise */ function checkAccountAndCreateSession(googleUserId, sessionToken, authResponse, nodeCallback) { var handleResults = function (error, responseData) { if (error) { return nodeCallback(error, null); } else { if (!responseData || responseData.count === 0) { //no account, must create. createAccountAndSetSession(sessionToken, authResponse, nodeCallback); } else { //account exists, set session and return it. setSession(sessionToken, responseData.list[0].fields, nodeCallback); } } }; mbaasApi.db({ "act": "list", "type": 'account', "eq": {"id": googleUserId}, }, handleResults); } /** * Creates an account and sets the session to that account. * @param {Sting} sessionToken * @param {Object} authResponse * @param {NodeCallback} nodeCallback * @returns session Data on callback if successful, error on callback otherwise */ function createAccountAndSetSession(sessionToken, authResponse, nodeCallback) { mbaasApi.db({ "act": "create", "type": 'account', "fields": [authResponse] }, function (error, data) { if (error) { return nodeCallback(error); } else { setSession(sessionToken, authResponse, nodeCallback); } }); } /** * * Sets the session. * * @param {Sting} sessionToken * @param {Object} sessionData * @param {NodeCallback} nodeCallback * @returns session Data on callback if successful, error on callback otherwise */ function setSession(sessionToken, sessionData, nodeCallback) { mbaasApi.session.set(sessionToken, sessionData, function (error, ignore) { if (error) return nodeCallback(error); else return nodeCallback(null, sessionData); }); } }; module.exports = new Account();
JavaScript
0.000002
@@ -1931,24 +1931,16 @@ uest -.request(request +(options , ha
fbefb8675b26320b295f481b4872ce99f0180807
Disable progress bar
lib/adduser.js
lib/adduser.js
module.exports = adduser var log = require('npmlog') var npm = require('./npm.js') var read = require('read') var userValidate = require('npm-user-validate') var output = require('./utils/output') var usage = require('./utils/usage') var chain = require('slide').chain var crypto try { crypto = require('crypto') } catch (ex) {} adduser.usage = usage( 'adduser', 'npm adduser [--registry=url] [--scope=@orgname] [--always-auth]' ) function adduser (args, cb) { if (!crypto) { return cb(new Error( 'You must compile node with ssl support to use the adduser feature' )) } var creds = npm.config.getCredentialsByURI(npm.config.get('registry')) var c = { u: creds.username || '', p: creds.password || '', e: creds.email || '' } var u = {} chain([ [readUsername, c, u], [readPassword, c, u], [readEmail, c, u], [save, c, u] ], cb) } function readUsername (c, u, cb) { var v = userValidate.username read({prompt: 'Username: ', default: c.u || ''}, function (er, un) { if (er) { return cb(er.message === 'cancelled' ? er.message : er) } // make sure it's valid. we have to do this here, because // couchdb will only ever say "bad password" with a 401 when // you try to PUT a _users record that the validate_doc_update // rejects for *any* reason. if (!un) { return readUsername(c, u, cb) } var error = v(un) if (error) { log.warn(error.message) return readUsername(c, u, cb) } c.changed = c.u !== un u.u = un cb(er) }) } function readPassword (c, u, cb) { var v = userValidate.pw var prompt if (c.p && !c.changed) { prompt = 'Password: (or leave unchanged) ' } else { prompt = 'Password: ' } read({prompt: prompt, silent: true}, function (er, pw) { if (er) { return cb(er.message === 'cancelled' ? er.message : er) } if (!c.changed && pw === '') { // when the username was not changed, // empty response means "use the old value" pw = c.p } if (!pw) { return readPassword(c, u, cb) } var error = v(pw) if (error) { log.warn(error.message) return readPassword(c, u, cb) } c.changed = c.changed || c.p !== pw u.p = pw cb(er) }) } function readEmail (c, u, cb) { var v = userValidate.email var r = { prompt: 'Email: (this IS public) ', default: c.e || '' } read(r, function (er, em) { if (er) { return cb(er.message === 'cancelled' ? er.message : er) } if (!em) { return readEmail(c, u, cb) } var error = v(em) if (error) { log.warn(error.message) return readEmail(c, u, cb) } u.e = em cb(er) }) } function save (c, u, cb) { // save existing configs, but yank off for this PUT var uri = npm.config.get('registry') var scope = npm.config.get('scope') // there may be a saved scope and no --registry (for login) if (scope) { if (scope.charAt(0) !== '@') scope = '@' + scope var scopedRegistry = npm.config.get(scope + ':registry') var cliRegistry = npm.config.get('registry', 'cli') if (scopedRegistry && !cliRegistry) uri = scopedRegistry } var params = { auth: { username: u.u, password: u.p, email: u.e } } npm.registry.adduser(uri, params, function (er, doc) { if (er) return cb(er) // don't want this polluting the configuration npm.config.del('_token', 'user') if (scope) npm.config.set(scope + ':registry', uri, 'user') if (doc && doc.token) { npm.config.setCredentialsByURI(uri, { token: doc.token }) } else { npm.config.setCredentialsByURI(uri, { username: u.u, password: u.p, email: u.e, alwaysAuth: npm.config.get('always-auth') }) } log.info('adduser', 'Authorized user %s', u.u) var scopeMessage = scope ? ' to scope ' + scope : '' output('Logged in as %s%s on %s.', u.u, scopeMessage, uri) npm.config.save('user', cb) }) }
JavaScript
0.000083
@@ -776,16 +776,40 @@ u = %7B%7D%0A%0A + log.disableProgress()%0A chain(
6ef7292a987643fd9cbea9ef97360a51b2c3b2ac
Remove some old code
lib/apphost.js
lib/apphost.js
module.exports = exports = createAppHost; function createAppHost() { } exports.virtualAppLoader = require('./middleware/app-loader'); exports.devSandbox = require('./middleware/dev-sandbox'); exports.htmlPage = require('./middleware/html-page'); exports.trafficControl = require('./middleware/traffic-control'); exports.logout = require('./middleware/logout'); exports.virtualRouter = require('./middleware/virtual-router'); exports.errorFallback = require('./middleware/error-fallback'); exports.authenticated = require('./middleware/authenticated');
JavaScript
0.001477
@@ -1,78 +1,4 @@ -module.exports = exports = createAppHost;%0A%0Afunction createAppHost() %7B%0A%0A%7D%0A%0A expo
4fadd0aa113deebece4c73d79083849ef5d00c6c
Mark apiLoader.services as private
lib/browser.js
lib/browser.js
var AWS = require('./core'); // Load browser API loader AWS.apiLoader = function(svc, version) { return AWS.apiLoader.services[svc][version]; }; AWS.apiLoader.services = {}; // Load the DOMParser XML parser AWS.XML.Parser = require('./xml/browser_parser'); // Load the XHR HttpClient require('./http/xhr'); if (typeof window !== 'undefined') window.AWS = AWS; if (typeof module !== 'undefined') module.exports = AWS;
JavaScript
0
@@ -140,16 +140,41 @@ ion%5D;%0A%7D; +%0A%0A/**%0A * @api private%0A */ %0AAWS.api
9ebe3ab2df3e82e9ea79b4ccc56542f7c97cc2fa
Refresh after upload
routes/git.js
routes/git.js
var Repo = require('../models/repo.js'); var nodegit = require('nodegit'); var promisify = require("promisify-node"); var validator = require('validator'); var fse = promisify(require("fs-extra")); var fs = require('fs'); var path = require('path'); var EasyZip = require('easy-zip').EasyZip; var AdmZip = require('adm-zip'); var multer = require('multer'); var done = false; exports.addRoutes = function(app) { app.get('/app', function(req, res) { res.render('index', { body: 'This is LetsGit' }); }); app.post('/clone', function(req, res) { var repoURL = req.body.url; var repoName = path.basename(repoURL, '.git'); var pathName = "./repos/" + req.user._id + "/" + repoName + "/"; console.log(repoURL); console.log(repoName); console.log(pathName); fse.remove(pathName).then(function() { var entry; //TODO: Add error handling //TODO: Add url validation nodegit.Clone.clone(repoURL, pathName, {ignoreCertErrors: 1}) .done(function() { var testRepo = new Repo({ name: repoName, path: pathName, createdAt: new Date().toJSON(), updatedAt: new Date().toJSON(), userId: req.user._id }); testRepo.save(); res.json({code: 0}); }); }); }); app.post('/createrepo', function(req, res) { }); app.post('/uploadrepo/:repoName', function(req, res) { var file = req.files.file; var repoName = req.params.repoName; console.log(file); var filePath = path.resolve(__dirname + "/../" + file.path); console.log("FILE PATH:" + filePath); var outputPath = path.resolve(__dirname + "/../repos/" + req.user._id + "/" + repoName); console.log("SAVE PATH:" + outputPath); fse.remove(outputPath).then(function() { var zip = new AdmZip(filePath); zip.extractAllTo(outputPath, true); }); }); app.get('/download/:repoName', function(req, res) { var repoName = req.params.repoName; var projectDirectory = __dirname + "/../repos/" + req.user._id + "/" + repoName; var destinationURL = __dirname + "/../downloads/" + req.user._id + "-" + repoName + ".zip" var zip = new EasyZip(); zip.zipFolder(projectDirectory, function() { zip.writeToFile(destinationURL); }); res.sendfile(path.resolve(destinationURL)); }); };
JavaScript
0
@@ -1804,16 +1804,91 @@ true);%0A +%09%09%09res.redirect(req.get('referer'));%09//Semi-hackish way of refreshing page%0A %09%09%7D);%0A%09%7D @@ -2007,16 +2007,29 @@ ctory = +path.resolve( __dirnam @@ -2068,32 +2068,33 @@ + %22/%22 + repoName +) ;%0A%09%09var destinat @@ -2102,16 +2102,29 @@ onURL = +path.resolve( __dirnam @@ -2184,18 +2184,160 @@ + %22.zip%22 -%0A%0A +);%0A%09%09console.log(%22project%22 + projectDirectory);%0A%09%09console.log(%22destination%22 + destinationURL);%0A%0A%09%09fse.remove(destinationURL).then(function() %7B%0A%09 %09%09var zi @@ -2344,20 +2344,19 @@ p = new -Easy +Adm Zip();%0A%09 @@ -2360,18 +2360,21 @@ ;%0A%09%09 -%0A%09 %09zip. -zip +addLocal Fold @@ -2396,27 +2396,12 @@ tory -, function() %7B%0A +);%0A%09 %09%09zi @@ -2411,14 +2411,11 @@ rite -ToFile +Zip (des @@ -2432,15 +2432,10 @@ L);%0A +%0A %09 -%09%7D);%0A%0A %09%09re @@ -2445,29 +2445,16 @@ endfile( -path.resolve( destinat @@ -2460,16 +2460,21 @@ tionURL) +;%0A%09%09%7D );%0A%0A%09%7D);
1e12579e4d8d6efceb21979a75d32473cc82da39
Move days and month outside of function
lib/convert.js
lib/convert.js
var relative = require('./relative'); module.exports = function(dateTime, pattern, options) { if(this.constructor == module.exports) { // Called as constructor var _dateTime; var _pattern; var _options = options; // If first argument is pattern assigning it to _pattern if(typeof dateTime === 'string') { _pattern = dateTime; } else { _dateTime = dateTime; _pattern = pattern; } return function(dateOrPattern, pattrn) { if(pattrn) { validate.all(dateOrPattern, pattrn, _options); return convert(dateOrPattern, pattrn); } if(dateOrPattern) { if(dateOrPattern instanceof Date) { return convert(dateOrPattern, _pattern); } else if(typeof dateOrPattern === 'string') { return convert(_dateTime, dateOrPattern); } else { throw new TypeError('Unknow type of first argument, expected Date or String but recieved <' + typeof dateOrPattern + '>'); } } else { validate.all(_dateTime, _pattern, options); return convert(_dateTime, _pattern); } } } else { // Called as function validate.all(dateTime, pattern, options); return convert(dateTime, pattern); } } /** * Add 0 if number less than 10 to display proper date/time format * @param {Number} number * @returns {String/Number} Value with 0 on start if number less than 10, else return given number */ function validateForOneDigit(number) { if(number < 10) { return '0' + number; } else { return number; } } // Becareful this fuction don't validate arguments! function convert(dateTime, pattern) { // If no pattern provided setting default one var defaultPattern = pattern || '%hh%:%mm% %DD%/%MM%/%YYYY%'; var result; const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; const filters = [ { pattern: /%hh%/g, replacment: validateForOneDigit(dateTime.getHours()) }, { pattern: /%mm%/g, replacment: validateForOneDigit(dateTime.getMinutes()) }, { pattern: /%ss%/g, replacment: validateForOneDigit(dateTime.getSeconds()) }, { pattern: /%DD%/g, replacment: validateForOneDigit(dateTime.getDate()) }, { pattern: /%MM%/g, replacment: validateForOneDigit(dateTime.getMonth()) }, { pattern: /%YYYY%/g, replacment: validateForOneDigit(dateTime.getFullYear()) }, { pattern: /%YY%/g, //TODO replacment: validateForOneDigit(dateTime.getFullYear().toString().slice(2)) }, { pattern: /%h%/g, replacment: dateTime.getHours() }, { pattern: /%m%/g, replacment: dateTime.getMinutes() }, { pattern: /%s%/g, replacment: dateTime.getSeconds() }, { pattern: /%D%/g, replacment: dateTime.getDate() }, { pattern: /%M%/g, replacment: dateTime.getMonth() }, { pattern: /%day%/g, replacment: days[dateTime.getDay()] }, { pattern: /%month%/g, replacment: months[dateTime.getMonth()] }, { pattern: /%relative%/g, replacment: relative(dateTime) } ]; filters.forEach(function(f) { defaultPattern = defaultPattern.replace(f.pattern, f.replacment); }); return defaultPattern; } /* * Validating arguments */ var validate = { date: function(date) { if(date instanceof Date === false) { throw new TypeError('Provided argument is not instance of Date'); } else { return true; } }, pattern: function(pattern) { if(pattern && typeof pattern !== 'string') { throw new TypeError('Pattern must be string'); } else { return true; } }, options: function(options) { if(options && typeof options !== 'object') { throw new TypeError('Options must be object'); } else { return true; } }, all: function(date, pattern, options) { this.date(date); this.pattern(pattern); this.options(options); } }
JavaScript
0.000002
@@ -32,16 +32,249 @@ ive');%0A%0A +const days = %5B'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'%5D;%0Aconst months = %5B'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'%5D;%0A%0A module.e @@ -344,16 +344,17 @@ uctor == += module. @@ -1791,17 +1791,16 @@ tern) %7B%0A -%0A %09// If n @@ -1906,254 +1906,8 @@ ';%0A%09 -var result;%0A%0A%09const days = %5B'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'%5D;%0A%09const months = %5B'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'%5D; %0A%09co @@ -3104,16 +3104,17 @@ %09%09%7D%0A%09%5D;%0A +%09 %0A%09filter
8991fe1903598bca46387b7aefa0d668929a181e
add case
lib/fengine.js
lib/fengine.js
/*! * fengine * Version: 0.0.1 * Date: 2016/8/2 * https://github.com/Nuintun/fengine * * This is licensed under the MIT License (MIT). * For details, see: https://github.com/Nuintun/fengine/blob/master/LICENSE */ 'use strict'; var os = require('os'); var fs = require('fs'); var url = require('url'); var path = require('path'); var http = require('http'); var util = require('./util'); var colors = require('colors'); var cluster = require('cluster'); var FileSend = require('file-send'); var Transform = require('./transform'); // variable declaration var CWD = process.cwd(); var NUMCPUS = os.cpus().length; var LOGLEVELS = { INFO: 'info', WARN: 'warn', ERROR: 'error' }; var FAVICON = path.join(__dirname, '../favicon.ico'); var FAVICONSIZE = fs.lstatSync(FAVICON).size; /** * is out bound * @param path * @param root * @returns {boolean} */ function isOutBound(path, root){ if (process.platform === 'win32') { path = path.toLowerCase(); root = root.toLowerCase(); } if (path.length < root.length) { return true; } return path.indexOf(root) !== 0; } /** * decode uri * @param uri * @returns {*} */ function decodeURI(uri){ try { return decodeURIComponent(uri); } catch (err) { return -1; } } /** * Fengine * @param options * @constructor */ function Fengine(options){ this.options = options; this.run(); } /** * * @type {{ * dir: Fengine.dir, * error: Fengine.error, * log: Fengine.log, * run: Fengine.run * }} */ Fengine.prototype = { dir: function (files, dir){ var html = '<!DOCTYPE html>' + '<html>' + ' <head>' + ' <meta name="renderer" content="webkit"/>' + ' <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>' + ' <meta content="text/html; charset=utf-8" http-equiv="content-type"/>' + ' <title>' + dir + '</title>' + ' <style>' + ' html, body, hr { margin: 0; padding: 0; }' + ' h1 { margin: 6px 0; }' + ' hr { font-size: 0; line-height: 0; height: 1px; }' + ' a { display: block; }' + ' .ui-dir { text-indent: 10px; }' + ' .ui-file { padding: 3px 30px; }' + ' </style>' + ' </head>' + ' <body>' + ' <a class="ui-dir" href="' + dir + '" title="' + dir + '"><h1>' + dir + '</h1></a><hr/>'; files.forEach(function (file){ var href = dir + file; html += '<a class="ui-file" href="' + href + '" title="' + href + '">' + file + '</a>'; }); html += ' </body>' + '</html>'; return html; }, error: function (response, statusCode){ response.statusCode = statusCode; response.setHeader('Content-Type', 'text/html; charset=UTF-8'); response.end(http.STATUS_CODES[statusCode]); }, log: function (data){ var message = data.message; switch (data.type) { case LOGLEVELS.INFO: message = colors.cyan.bold(message); break; case LOGLEVELS.WARN: message = colors.yellow.bold(message); break; case LOGLEVELS.ERROR: message = colors.red.bold(message); break; } console.log(message); }, run: function (){ var context = this; var options = context.options; if (cluster.isMaster) { // worker var worker; // create thread for (var i = 0; i < NUMCPUS; i++) { // fork worker = cluster.fork(); // listen event worker.on('message', context.log); } } else { // create server var server = http.createServer(function (requset, response){ var parsed = requset.url; if (parsed === -1 || ~parsed.indexOf('\0')) { return context.error(response, 400); } parsed = url.parse(decodeURI(requset.url)); var pathname = parsed.pathname; var extname = path.extname(pathname).toLowerCase(); switch (extname) { case '.htm': case '.html': pathname = path.join(options.root, pathname); if (isOutBound(pathname, CWD)) { return context.error(response, 403); } if (!/^[.]+[/\\]/.test(path.relative(options.base, pathname))) { fs.readFile(pathname, function (error, source){ if (error) { return context.error(response, 404); } response.statusCode = 200; response.setHeader('Content-Type', 'text/html'); var transform = new Transform(pathname, source.toString(), { root: options.base, data: options.data, layout: options.layout, delimiter: options.delimiter }); transform.on('data', function (data){ response.write(data); }); transform.on('end', function (){ response.end(); }); }); } else { new FileSend(requset, { root: options.root }).pipe(response); } break; default: if (pathname.toLowerCase() === '/favicon.ico') { pathname = path.join(options.root, pathname); fs.lstat(pathname, function (error){ response.statusCode = 200; response.setHeader('Content-Type', 'image/x-icon'); if (error) { response.setHeader('Content-Length', FAVICONSIZE); return fs.createReadStream(FAVICON).pipe(response); } else { new FileSend(requset, { root: options.root }).pipe(response); } }); } else { var send = new FileSend(requset, { root: options.root }).on('dir', function (realpath, stats, next){ // set Content-Type send.setHeader('Content-Type', 'text/html; charset=UTF-8'); // read dir fs.readdir(realpath, function (error, files){ if (error) { send.statError(response, error); } else { // response next(context.dir(files, pathname)); } }); }).pipe(response); } break; } }); // start listening server.on('listening', function (){ // message process.send({ type: 'info', message: 'Server thread ' + cluster.worker.id + ' runing at: ' + options.hostname + ':' + options.port }); }); // error server.on('error', function (error){ // message process.send({ type: 'error', message: 'Server thread ' + cluster.worker.id + ' failed to start: ' + error.message }); // exit process.exit(); }); // close server.on('close', function (){ // message process.send({ type: 'info', message: 'Server thread ' + cluster.worker.id + ' closed' }); // exit process.exit(); }); // listen server.listen(options.port, options.hostname || '127.0.0.1'); // return return server; } } }; module.exports = Fengine;
JavaScript
0.999999
@@ -4583,19 +4583,8 @@ urce -.toString() , %7B%0A
bde8dacc2ca3f035f68462051ad10baf6db32811
Use the new config
lib/filters.js
lib/filters.js
var bodyParser = require('body-parser') , crypto = require('crypto'); module.exports = function(app) { // Payload parser app.use(bodyParser.json()); // Validates secret token sent by Github with POST app.use(function(req, res, next) { if (req.method !== 'POST') return next(); var secret = app.get('secret_token') , headers = req.headers , payload = JSON.stringify(req.body) , signatureSent = headers['x-hub-signature'] , hmac = crypto.createHmac('sha1', secret) , signature = 'sha1='; signature += crypto .createHmac('sha1', secret) .update(payload) .digest('hex'); if (!signatureSent || signature !== signatureSent) { return res .status(401) .send('Unauthorized'); } return next(); }); // Checks if event and action is supported app.use(function(req, res, next) { if (req.method !== 'POST') return next(); var event = req.headers['x-github-event'] , payload = req.body , supported = app.get('github_events'); if (!event || !supported[event]) { return res .status(400) .send('Event ' + event + ' is not supported'); } if (!!~supported[event].indexOf(payload.action) === false) { return res .status(400) .send('Action ' + payload.action + ' is not supported'); } return next(); }); };
JavaScript
0.000002
@@ -63,16 +63,46 @@ crypto') +%0A , cfg = require('./config') ;%0A%0Amodul @@ -133,28 +133,8 @@ ) %7B%0A - // Payload parser%0A ap @@ -318,31 +318,21 @@ t = -app.get('secret_token') +cfg.api.TOKEN %0A @@ -1020,33 +1020,25 @@ d = -app.get('github_events'); +cfg.github.EVENTS %0A%0A
498b0d591f57be266ef19023297ba8a7885bc483
Fix a bug with autocompleting namespaced objects
lib/helpers.js
lib/helpers.js
/* @flow */ import stringScore from 'sb-string_score' import type { TextEditor, Point } from 'atom' const REGEX_LABEL = /(\w+)/ const REGEX_PREFIX = /((:\w[\w:-]+)|(\$\w*)|::(\w+)|(\w+))$/ export function getTransformedText(textEditor: TextEditor, bufferPosition: Point): string { const textBuffer = textEditor.getBuffer() const text = textBuffer.getText() const index = textBuffer.characterIndexForPosition(bufferPosition) return text.substr(0, index) + 'AUTO332' + text.substr(index) } export function parseSuggestions(suggestions: string, prefix: string): Array<Object> { const toReturn = [] const chunks = suggestions.split('\n') for (let i = 0, length = chunks.length; i < length; ++i) { const chunk = chunks[i].trim() const firstSpace = chunk.indexOf(' ') let type = 'property' const replacement = chunk.substr(0, firstSpace) const description = chunk.substr(firstSpace + 1) || '_' const label = REGEX_LABEL.exec(description)[0] let snippet if (description === 'class') { type = 'class' } else if (replacement.substr(0, 1) === '$') { type = 'variable' } else if (label === 'function') { type = 'function' let match let number = 0 const regex = /(\$\w+)/g snippet = [] while ((match = regex.exec(description)) !== null) { // eslint-disable-line snippet.push(`\${${++ number}:${match[0]}}`) } snippet = `${replacement}(${snippet.join(', ')}\${${++number}})` } const score = stringScore(chunk, prefix) if (prefix !== '' && score === 0) { continue } toReturn.push({ type, leftLabel: label, description, text: !snippet && replacement, snippet, replacementPrefix: prefix, score: stringScore(chunk, prefix), }) } return toReturn } export function getPrefix(editor: TextEditor, bufferPosition: Point): string { const lineText = editor.getTextInBufferRange([bufferPosition, [bufferPosition.row, 0]]) const matches = REGEX_PREFIX.exec(lineText) || [] return matches[2] || matches[3] || matches[4] || matches[5] || '' }
JavaScript
0
@@ -176,18 +176,22 @@ :(%5Cw+)%7C( +%5B %5Cw +%5C%5C%5D +))$/%0A%0Ae
450b0ca4e1a34356713c721dd41fdd418ca90f7c
Implement getPrototypeOf in firstImplementer correctly
lib/helpers.js
lib/helpers.js
import fs from 'fs-extra'; import {ncp} from 'ncp'; /** * Takes an array of targets and returns a proxy. The proxy intercepts property accessor calls and * returns the value of that property on the first object in `targets` where the target implements that property. */ export function firstImplementer(...targets) { return new Proxy({__implementations: targets}, { get(target, name) { if (Reflect.has(target, name)) { return target[name]; } const firstValidTarget = targets.find(t => Reflect.has(t, name)); if (firstValidTarget) { return firstValidTarget[name]; } else if (Reflect.has(target, name)) { return target[name]; } else { return undefined; } }, set(target, name, value) { const firstValidTarget = targets.find(t => Reflect.has(t, name)); if (firstValidTarget) { // eslint-disable-next-line no-return-assign return firstValidTarget[name] = value; } else { // eslint-disable-next-line no-return-assign return target[name] = value; } }, // Used by sinon getOwnPropertyDescriptor(target, name) { const firstValidTarget = targets.find(t => Reflect.getOwnPropertyDescriptor(t, name)); const compositeOwnPropertyDescriptor = Reflect.getOwnPropertyDescriptor(target, name); if (firstValidTarget) { return Reflect.getOwnPropertyDescriptor(firstValidTarget, name); } else if (compositeOwnPropertyDescriptor) { return compositeOwnPropertyDescriptor; } else { return undefined; } }, // Used by sinon getPrototypeOf(target) { return targets.reduce((acc, t) => { return Object.create(Reflect.getPrototypeOf(t), acc); }, {}); }, }); } export function readFile(absoluteFilePath, encoding = 'utf8') { return new Promise((resolve, reject) => { fs.readFile(absoluteFilePath, encoding, (err, contents) => { if (err) { reject(err); } else { resolve(contents); } }); }); } export function writeFile(absoluteFilePath, contents) { return new Promise((resolve, reject) => { fs.writeFile(absoluteFilePath, contents, err => { if (err) { return reject(err); } else { return resolve(); } }); }); } export function deleteFileOrFolder(path) { return new Promise((resolve, reject) => { fs.remove(path, err => { if (err) { return reject(err); } else { return resolve(); } }); }); } export function copyFile(source, target) { return new Promise((resolve, reject) => { ncp(source, target, err => { if (err) { return reject(err); } else { return resolve(target); } }); }); } export function getTempDir(prefix) { return new Promise((resolve, reject) => { fs.mkdtemp(prefix, (err, folder) => { if (err) { return reject(err); } else { return resolve(folder); } }); }); } export function fsStat(absoluteFilePath) { return new Promise((resolve, reject) => { fs.stat(absoluteFilePath, (err, stats) => { if (err) { reject(err); } else { resolve(stats); } }); }); } export function shortenSha(sha) { return sha.slice(0, 8); } export const classNameForStatus = { added: 'added', deleted: 'removed', modified: 'modified', equivalent: 'ignored', };
JavaScript
0
@@ -46,16 +46,246 @@ 'ncp';%0A%0A +%0Afunction descriptorsFromProto(proto) %7B%0A return Object.getOwnPropertyNames(proto).reduce((acc, name) =%3E %7B%0A Object.assign(acc, %7B%0A %5Bname%5D: Reflect.getOwnPropertyDescriptor(proto, name),%0A %7D);%0A return acc;%0A %7D, %7B%7D);%0A%7D%0A%0A /**%0A * T @@ -841,83 +841,8 @@ e%5D;%0A - %7D else if (Reflect.has(target, name)) %7B%0A return target%5Bname%5D;%0A @@ -1810,30 +1810,33 @@ et) %7B%0A -return +const v = targets.red @@ -1882,20 +1882,45 @@ .create( -Refl +acc, descriptorsFromProto(Obj ect.getP @@ -1936,13 +1936,9 @@ f(t) -, acc +) );%0A @@ -1945,19 +1945,49 @@ %7D, -%7B%7D) +Object.prototype);%0A return v ;%0A %7D,
42d1872ce9173de74bb348b5aada8eaa75855c63
change to use const and let
lib/hydrate.js
lib/hydrate.js
/** value should have the following format { body: { responseType: '', responseText: value, status: '', statusText: '' }, headers: '' } */ // borrow from superagent function trim (s = '') { return ''.trim ? s.trim(s) : s.replace(/(^\s*|\s*$)/g, '') } // borrow from superagent function parseHeaders (str = '') { var lines = str.split(/\r?\n/) var fields = {} var index var line var field var val lines.pop() // trailing CRLF for (let i = 0, len = lines.length; i < len; i += 1) { line = lines[i] index = line.indexOf(':') field = line.slice(0, index).toLowerCase() val = trim(line.slice(index + 1)) fields[field] = val } return fields } export default function hydrate (value) { const xhr = value.body || {} const headers = parseHeaders(value.headers) xhr.getAllResponseHeaders = function () { return value.headers } xhr.getResponseHeader = function (header) { return headers[header] } return xhr }
JavaScript
0
@@ -333,19 +333,21 @@ '') %7B%0A -var +const lines = @@ -368,19 +368,19 @@ ?%5Cn/)%0A -var +let fields @@ -386,19 +386,19 @@ = %7B%7D%0A -var +let index%0A @@ -402,19 +402,19 @@ x%0A -var +let line%0A var @@ -409,19 +409,19 @@ line%0A -var +let field%0A @@ -425,11 +425,11 @@ d%0A -var +let val