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
7326b1a4430f7b2a3fe8329e04c3b5bf28af24c9
Fix JS style.
power/power_api.js
power/power_api.js
// Copyright (c) 2013 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // FIXME: A lot of these methods should throw NOT_SUPPORTED_ERR on desktop. // There is no easy way to do verify which methods are supported yet. var screenState = undefined; var defaultScreenBrightness = undefined; var resources = { 'SCREEN': { type: 0, states: { 'SCREEN_OFF': 0, 'SCREEN_DIM': 1, 'SCREEN_NORMAL': 2, 'SCREEN_BRIGHT': 3 // Deprecated. } }, 'CPU': { type: 1, states: { 'CPU_AWAKE': 4 } } }; var listeners = []; function callListeners(oldState, newState) { var previousState = Object.keys(resources['SCREEN'].states)[oldState]; var changedState = Object.keys(resources['SCREEN'].states)[newState]; listeners.forEach(function(listener) { listener(previousState, changedState); }); } var postMessage = function(msg) { extension.postMessage(JSON.stringify(msg)); }; var sendSyncMessage = function(msg) { return extension.internal.sendSyncMessage(JSON.stringify(msg)); }; function getScreenState() { var msg = { 'cmd': 'PowerGetScreenState' }; var r = JSON.parse(sendSyncMessage(msg)); screenState = r.state; } extension.setMessageListener(function(msg) { var m = JSON.parse(msg); if (m.cmd == 'ScreenStateChanged') { var newState = m.state; if (screenState == undefined) getScreenState(); if (screenState !== newState) { callListeners(screenState, newState); screenState = newState; } } }); exports.request = function(resource, state) { // Validate permission to 'power'. // throw new WebAPIException(SECURITY_ERR); if (typeof resource !== 'string' || typeof state !== 'string') { throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR); } if (!resources.hasOwnProperty(resource)) { throw new tizen.WebAPIException(tizen.WebAPIException.INVALID_VALUES_ERR); } if (!resources[resource].states.hasOwnProperty(state)) { throw new tizen.WebAPIException(tizen.WebAPIException.INVALID_VALUES_ERR); } // Exception check: SCREEN_OFF is a state cannot be requested if (resource === 'SCREEN' && state === 'SCREEN_OFF') { throw new tizen.WebAPIException(tizen.WebAPIException.INVALID_VALUES_ERR); } postMessage({ 'cmd': 'PowerRequest', 'resource': resources[resource].type, 'state': resources[resource].states[state] }); }; exports.release = function(resource) { // Validate permission to 'power'. Do not throw, just bail out. if (typeof resource !== 'string') throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR); if (!resources.hasOwnProperty(resource)) throw new tizen.WebAPIException(tizen.WebAPIException.INVALID_VALUES_ERR); postMessage({ 'cmd': 'PowerRelease', 'resource': resources[resource].type }); }; exports.setScreenStateChangeListener = function(listener) { // No permission validation. if (typeof listener !== 'function') throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR); // FIXME: According to docs, it should throw INVALID_VALUES_ERR if input // parameters contain an invalid value. Verify the Tizen 2.x impl. listeners.push(listener); }; exports.unsetScreenStateChangeListener = function() { // No permission validation. listeners = []; }; exports.getScreenBrightness = function() { var brightness = parseFloat(sendSyncMessage({ 'cmd': 'PowerGetScreenBrightness' })); return brightness; }; defaultScreenBrightness = exports.getScreenBrightness(); exports.setScreenBrightness = function(brightness) { // Validate permission to 'power'. // throw new WebAPIException(SECURITY_ERR); if (typeof brightness !== 'number' || !isFinite(brightness)) throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR); if (brightness < 0 || brightness > 1) throw new tizen.WebAPIException(tizen.WebAPIException.INVALID_VALUES_ERR); postMessage({ 'cmd': 'PowerSetScreenBrightness', 'value': brightness }); }; exports.isScreenOn = function() { getScreenState(); if (typeof screenState !== 'number') throw new tizen.WebAPIException(tizen.WebAPIException.UNKNOWN_ERR); return screenState !== resources['SCREEN'].states['SCREEN_OFF']; }; exports.restoreScreenBrightness = function() { // Validate permission to 'power'. // throw new WebAPIException(SECURITY_ERR); if (defaultScreenBrightness < 0 || defaultScreenBrightness > 1) throw new tizen.WebAPIException(tizen.WebAPIException.UNKNOWN_ERR); postMessage({ 'cmd': 'PowerSetScreenBrightness', 'value': defaultScreenBrightness }); }; exports.turnScreenOff = function() { // Validate permission to 'power'. // throw new WebAPIException(SECURITY_ERR); // FIXME: throw UNKNOWN_ERR during failure to set the new value. postMessage({ 'cmd': 'PowerSetScreenEnabled', 'value': false }); }; exports.turnScreenOn = function() { // Validate permission to 'power'. // throw new WebAPIException(SECURITY_ERR); // FIXME: throw UNKNOWN_ERR during failure to set the new value. postMessage({ 'cmd': 'PowerSetScreenEnabled', 'value': true }); };
JavaScript
0
@@ -1152,26 +1152,24 @@ enState() %7B%0A - var msg = @@ -1170,18 +1170,16 @@ msg = %7B%0A - 'cmd @@ -1209,15 +1209,11 @@ '%0A - - %7D;%0A - va @@ -1252,18 +1252,16 @@ (msg));%0A - screen
c5c681673d7abe3a50162982cd15a31407c78444
Use dedicated html id generator
view/dbjs/form-section-base-get-resolvent.js
view/dbjs/form-section-base-get-resolvent.js
/** * @param options {object} * @returns {object} of the form: * { * affectedSectionId: id || undefined, * legacyScript: radioMatch || selectMatch || undefined, * formResolvent: field || undefined * } */ 'use strict'; var generateId = require('time-uuid') , resolvePropertyPath = require('dbjs/_setup/utils/resolve-property-path') , isObject = require('dbjs/is-dbjs-object') , d = require('d') , db = require('mano').db , ns = require('mano').domjs.ns; module.exports = Object.defineProperty(db.FormSectionBase.prototype, 'getFormResolvent', d(function (/*options*/) { var result, match, options = Object(arguments[0]) , master = options.master || this.master, dbjsInput; result = {}; match = {}; if (this.resolventProperty) { result.affectedSectionId = generateId(); if (typeof this.resolventValue === 'boolean') { match[Number(this.resolventValue)] = result.affectedSectionId; } else if (isObject(this.resolventValue)) { match[this.resolventValue.__id__] = result.affectedSectionId; } else { match[this.resolventValue] = result.affectedSectionId; } result.formResolvent = ns.field({ dbjs: resolvePropertyPath(master, this.resolventProperty ).observable }); dbjsInput = result.formResolvent._dbjsInput; if (dbjsInput instanceof db.Base.DOMSelect) { dbjsInput.control.id = 'select-' + generateId(); result.legacyScript = ns.legacy('selectMatch', dbjsInput.control.id, match); } else { if (!(dbjsInput.observable.descriptor.inputOptions && (dbjsInput.observable.descriptor.inputOptions.multiline === false))) { dbjsInput.dom.classList.add('multiline'); } result.legacyScript = ns.legacy('radioMatch', options.formId || this.domId, master.__id__ + '/' + this.resolventProperty, match); } } return result; }));
JavaScript
0
@@ -262,15 +262,39 @@ re(' -time-uu +dom-ext/html-document/generate- id')
bd8a046c839c4ee827b4662c7f5bb3b70c8f78e8
Update server.js
examples/server.js
examples/server.js
const webpack = require('webpack'); const WebpackDevServer = require('webpack-dev-server'); const config = require('./webpack.config'); const port = process.env.PORT || 3000; config.entry.app.push( 'webpack-dev-server/client?http://0.0.0.0:' + port, 'webpack/hot/only-dev-server' ); new WebpackDevServer(webpack(config), { publicPath: config.output.publicPath, disableHostCheck: true, hot: true, stats: { colors: true, }, }).listen(port, function(err) { if (err) { console.log(err); } console.log('Listening at localhost:' + port); });
JavaScript
0.000001
@@ -362,16 +362,44 @@ icPath,%0A + historyApiFallback: true,%0A disabl
0840a069ed41d2d81783e1a0d87bba5fceda427f
remove console.log
examples/server.js
examples/server.js
var http = require('http') var app = require('../index')() var send = require('../send') var error = require('../error') var log = app.log app.on('/', function (req, res, ctx) { if (req.method === 'POST') { console.log(ctx.body) return send(200, ctx.body).pipe(res) } else if (req.method === 'GET') { return send(200, { message: 'oh hey friends' }).pipe(res) } return error(400, 'Method not allowed').pipe(res) }) http.createServer(app).listen(3000, function () { log.info('server started at http://127.0.0.1:3000') })
JavaScript
0.000006
@@ -207,34 +207,8 @@ ) %7B%0A - console.log(ctx.body)%0A
ed1707eca68aec633786d20cfeacdb04a02f6952
add attribution to relay
src/networkLayer.js
src/networkLayer.js
// ensure env has promise support import { polyfill } from 'es6-promise'; polyfill(); import fetch from 'isomorphic-fetch'; import { isString, isArray, } from 'lodash'; class NetworkLayer { constructor(uri, opts = {}) { if (!uri) { throw new Error('A remote enpdoint is required for a newtork layer'); } if (!isString(uri)) { throw new Error('Uri must be a string'); } this._uri = uri; this._opts = { ...opts }; } query(requests) { let clonedRequests = []; if (!isArray(requests)) { clonedRequests = [requests]; } else { clonedRequests = [...requests]; } return Promise.all(clonedRequests.map(request => ( this._query(request).then( result => result.json() ).then(payload => { if (payload.hasOwnProperty('errors')) { const error = new Error( `Server request for query '${request.getDebugName()}' failed for the following reasons:\n\n ${formatRequestErrors(request, payload.errors)}` ); error.source = payload; throw error; } else if (!payload.hasOwnProperty('data')) { throw new Error( `Server response was missing for query '${request.getDebugName()}'.` ); } else { return payload; } }) ))); } _query(request) { return fetch(this._uri, { ...this._opts, body: JSON.stringify({ query: request.getQueryString(), variables: request.getVariables(), }), headers: { ...this._opts.headers, Accept: '*/*', 'Content-Type': 'application/json', }, method: 'POST', }); } } function formatRequestErrors(request, errors) { const CONTEXT_BEFORE = 20; const CONTEXT_LENGTH = 60; const queryLines = request.getQueryString().split('\n'); return errors.map(({ locations, message }, ii) => { const prefix = `${(ii + 1)}. `; const indent = ' '.repeat(prefix.length); // custom errors thrown in graphql-server may not have locations const locationMessage = locations ? (`\n${locations.map(({ column, line }) => { const queryLine = queryLines[line - 1]; const offset = Math.min(column - 1, CONTEXT_BEFORE); return [ queryLine.substr(column - 1 - offset, CONTEXT_LENGTH), `${' '.repeat(offset)}^^^`, ].map(messageLine => indent + messageLine).join('\n'); }).join('\n')}`) : ''; return prefix + message + locationMessage; }).join('\n'); } export default NetworkLayer;
JavaScript
0
@@ -1714,16 +1714,185 @@ %7D%0A%0A%7D%0A%0A +/*%0A%0A An easy way to breakdown the errors of a query%0A from https://github.com/facebook/relay/blob/master/src/network-layer/default/RelayDefaultNetworkLayer.js#L174%0A%0A*/%0A function
64fd9b9f784a419545f6f0a94337552c20d1dbcd
add constraint
src/objects/Room.js
src/objects/Room.js
import { SpriteWidth, SpriteHeight, SpriteRatioX, SpriteRatioY } from "../Constants.js"; import { Wall } from "../SpriteConstants"; class Room extends Phaser.Group { constructor(game, parent, name) { super(game, parent, name, false, false, Phaser.Physics.ARCADE); } createRandomLine(x1, y1, x2, y2, division = 1, varX = 0, varY = 0) { const middleX = (x1 + x2) / 2 + (varX * SpriteWidth); const middleY = (y1 + y2) / 2 + (varY * SpriteHeight); const middleXBefore = middleX - (middleX % SpriteWidth); const middleXAfter = middleX + (middleX % SpriteWidth); const middleYBefore = middleY - (middleY % SpriteHeight); const middleYAfter = middleY + (middleY % SpriteHeight); if(division > 1) { this.createRandomLine(x1, y1, middleXBefore, middleYBefore, division - 1, varX, varY); this.createRandomLine(middleXAfter, middleYAfter, x2, y2, division - 1, varX, varY); } else { this.createLine(x1,y1, middleXBefore, middleYBefore); this.createLine(middleXAfter, middleYAfter, x2, y2); } } createLineByTile(x1, y1, nbTilesX, nbTilesY, division, varX = 0, varY = 0) { if(nbTilesX < 0 ) { throw `createLineByTile ${nbTilesX} is negative`; } if(nbTilesY < 0 ) { throw `createLineByTile ${nbTilesY} is negative`; } this.createRandomLine(x1, y1, (nbTilesX-1) * SpriteWidth + x1 , (nbTilesY-1) * SpriteHeight + y1, division, varX, varY); } // //Brasenhem algorithm createLine(x1,y1, x2, y2) { const dx = Math.abs(x2 - x1); const sx = x1 < x2 ? SpriteWidth : -SpriteWidth; const dy = Math.abs(y2 - y1); const sy = y1 < y2 ? SpriteHeight : -SpriteHeight; var err = (dx > dy ? dx : -dy) / 2; let x = x1; let y = y1; while (true) { this.createSprite(x,y); debugger if (x >= x2 && y >= y2) break; let e2 = err; if (e2 > - dx) { err -= dy; x += sx; } if (e2 < dy) { err += dx; y += sy; } } } createSprite(x,y) { let sprite = this.create(x, y, Wall); sprite.scale.setTo(SpriteRatioX, SpriteRatioY); } //// // #### // # # // # # // # # // (x,y) #### // /// createSquare(x, y, nbTilesBySide) { this.createRandomSquare(x, y, nbTilesBySide, 1, 0, 0); } // const division = 3; // const varX = -1; // const varY = 1; createRandomSquare(x, y, nbTilesBySide, division, varX, varY) { this.createLineByTile(x, y, nbTilesBySide, 1, division, varX, varY); this.createLineByTile(x, y + (nbTilesBySide-1) * SpriteHeight, nbTilesBySide, 1, division, varX, varY); //nbtiles - 2 because corner was drawn by vertical line this.createLineByTile(x, y + SpriteHeight, 1, nbTilesBySide - 2, division, varX, varY); this.createLineByTile(x + (nbTilesBySide-1) * SpriteWidth, y + SpriteHeight, 1, nbTilesBySide - 2, division, varX, varY); } } export default Room;
JavaScript
0.000177
@@ -55,16 +55,24 @@ teRatioY +, Bounds %7D from @@ -1749,17 +1749,16 @@ y = y1;%0A -%0A whil @@ -1802,23 +1802,8 @@ y);%0A - debugger%0A @@ -1835,16 +1835,76 @@ break;%0A + if(x %3C 0 %7C%7C y %3C 0 %7C%7C x %3E Bounds %7C%7C y %3E Bounds) break;%0A le
a0984bf05b9855cf554f7eacc80e463730e4db4d
Fix wording
site/website/pages/en/download.js
site/website/pages/en/download.js
/** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const React = require('react'); const CompLibrary = require('../../core/CompLibrary'); const Container = CompLibrary.Container; const CWD = process.cwd(); const versions = require(`${CWD}/all-versions.json`); const MarkdownBlock = CompLibrary.MarkdownBlock; function Downloads(props) { const {config: siteConfig} = props; const latest = versions[0]; const repoUrl = `https://github.com/${siteConfig.organizationName}/${siteConfig.projectName}`; return ( <div className="docMainWrapper wrapper"> <Container className="mainContainer versionsContainer"> <div> <header> <h1>{siteConfig.title} Downloads</h1> </header> <MarkdownBlock> The Hazelcast Jet download package includes Hazelcast Jet server and several additional modules. It requires a JDK to run, which can be obtained from [AdoptOpenJDK](https://adoptopenjdk.net) (minimum version is 8 - recommended is 11 or later). For details about what's included, and minimim requirements please see the [installation page](/docs/operations/installation). </MarkdownBlock> <h3 id="latest">Current version (Stable)</h3> <table className="versions"> <tbody> <tr> <th>{latest.version}</th> <td> <a href={`${repoUrl}/releases/download/v${latest.version}/hazelcast-jet-${latest.version}.tar.gz`}> hazelcast-jet-{latest.version}.tar.gz </a> </td> <td>{latest.size}MB</td> <td> <a href={ latest.releaseNotes ? `${latest.releaseNotes}` : `${repoUrl}/releases/tag/v${latest.version}`}> Release Notes </a> </td> <td> <a href={`/javadoc/${latest.version}`} target="_blank" rel="noreferrer noopener"> Javadoc </a> </td> </tr> </tbody> </table> <p>Hazelcast Jet artifacts can also be retrieved using the following Maven coordinates:</p> <pre><code className="language-groovy css hljs"> groupId: <span className="hljs-string">com.hazelcast.jet</span><br/> artifactId: <span className="hljs-string">hazelcast-jet</span><br/> version: <span className="hljs-string">{latest.version}</span> </code></pre> <p>For the full list of modules, please see <a href="https://search.maven.org/search?q=g:com.hazelcast.jet">Maven Central</a>.</p> <h3 id="management-center">Management Center</h3> <p>Jet Management Center can be used for monitoring the cluster and running jobs. For instructions on how to download and run it, see the <a href="/docs/enterprise/management-center">installation page</a>.</p> {/* <p> You can download Hazelcast Jet Management Center <a href={`https://download.hazelcast.com/hazelcast-jet-management-center/hazelcast-jet-management-center-${latest.version}.tar.gz`}>here</a>. </p> <p> You can run the Management Center without a license key, but it will only work with a single node cluster. Get a 30-day trial license from <a href="https://hazelcast.com/download">the Hazelcast website</a>. </p> <p> For details about what's included, and minimim requirements please see the <a href="/docs/enterprise/management-center">installation page</a>. </p> */} <h3 id="archive">Past Versions</h3> <p>Here you can find previous versions of Hazelcast Jet.</p> <table className="versions"> <tbody> {versions.map( current => current.version !== latest.version && ( <tr key={current.version}> <th>{current.version}</th> <td> <a href={`${repoUrl}/releases/download/v${current.version}/hazelcast-jet-${current.version}.tar.gz`}> hazelcast-jet-{current.version}.tar.gz </a> </td> <td> {current.size} MB </td> <td> <a href={ current.releaseNotes ? `${current.releaseNotes}` : `${repoUrl}/releases/tag/v${current.version}`}> Release Notes </a> </td> <td> <a href={`/javadoc/${current.version}`} target="_blank" rel="noreferrer noopener"> Javadoc </a> </td> </tr> ), )} </tbody> </table> </div> </Container> </div> ); } module.exports = Downloads;
JavaScript
0.000977
@@ -3028,25 +3028,8 @@ ster - and running jobs . Fo
2cbd28138d5781aebc39381a50a7ee8815987e48
Remove a startup test from dev env
src/config/env/development.js
src/config/env/development.js
/** @module Env Dev */ 'use strict'; var logger = require(process.env.LOGGER)('Env Dev'); // EXPORTED OBJECT ============================================================ /** * [exports description] * * @type {Object} */ module.exports = { app: { title: 'Accounting app - Development environment' }, server: { port: process.env.PORT || 8081 }, db : { url: 'mongodb://localhost/accounting_app-dev' // TODO extract url to a private file } }; // PRIVATE FUNCTIONS ========================================================== /** * Setup the database for testing */ function setupDB() { logger.debug('Setting up the Dev DB'); // General ledger --------------------------------------------------------- var GeneralLedger = require('../../app/models/generalLedger.model'); logger.debug('removing all existing general ledger'); GeneralLedger.remove(null).exec(); var testingGeneralLedger = require('./dev/testingGeneralLedgersList'); GeneralLedger.create(testingGeneralLedger, function(err) { if (err){ logger.error('Error while creating the testing general ledgers'); logger.error(err); }else { logger.debug('All testing general ledgers have been created'); // Accounts ------------------------------------------------------- var Account = require('../../app/models/account.model'); logger.debug('removing all existing accounts'); Account.remove(null).exec(); var testingAccounts = require('./dev/testingAccountsList'); Account.create(testingAccounts, function(err) { if (err){ logger.error('Error while creating the testing accounts'); logger.error(err); }else { logger.debug('All testing accounts have been created'); GeneralLedger.findOne(function(err, generalLedger) { if (!err && generalLedger){ logger.debug('The net worth of the general ledger is ' + generalLedger.netWorth); } else { logger.error('There was an error while finding the general ledgers'); } }); } }); } }); } // EXPORTED FUNCTIONS ========================================================= /** * [initEnv description] */ module.exports.initEnv = function() { logger.debug('Configuration initialization of dev environment'); }; /** * [initEnvPostDBConnection description] */ module.exports.initEnvPostDBConnection = function() { logger.debug('Post-DB connection configuration initialization of dev environment'); setupDB(); };
JavaScript
0.000001
@@ -86,16 +86,17 @@ ev');%0A%0A%0A +%0A // EXPOR @@ -1023,16 +1023,17 @@ (err) %7B%0A +%0A %09%09if (er @@ -1036,16 +1036,17 @@ (err)%7B%0A +%0A %09%09%09logge @@ -1128,16 +1128,17 @@ r(err);%0A +%0A %09%09%7Delse @@ -1139,16 +1139,17 @@ %7Delse %7B%0A +%0A %09%09%09logge @@ -1207,17 +1207,16 @@ ted');%0A%0A -%0A %09%09%09// Ac @@ -1539,16 +1539,17 @@ (err) %7B%0A +%0A %09%09%09%09if ( @@ -1550,24 +1550,25 @@ %09%09if (err)%7B%0A +%0A %09%09%09%09%09logger. @@ -1643,16 +1643,17 @@ r(err);%0A +%0A %09%09%09%09%7Dels @@ -1652,24 +1652,25 @@ %09%09%09%09%7Delse %7B%0A +%0A %09%09%09%09%09logger. @@ -1723,315 +1723,23 @@ );%0A%0A -%09%09%09%09%09GeneralLedger.findOne(function(err, generalLedger) %7B%0A%0A%09%09%09%09%09%09if (!err && generalLedger)%7B%0A%09%09%09%09%09%09%09logger.debug('The net worth of the general ledger is ' + generalLedger.netWorth);%0A%09%09%09%09%09%09%7D else %7B%0A%09%09%09%09%09%09%09logger.error('There was an error while finding the general ledgers');%0A%09%09%09%09%09%09%7D%0A%0A%09%09%09%09%09%7D);%0A%0A %09%09%09%09%7D%0A +%0A %09%09%09%7D);%0A%0A %0A%0A%09%09 @@ -1738,25 +1738,19 @@ );%0A%0A -%0A%0A%09%09%09%0A %09%09%7D%0A +%0A %09%7D);%0A%0A -%0A %7D%0A%0A%0A
230800a962b270e6f3e84e339be4c1bea80c085d
fix up (tunnel-client dep added to mojito-client)
tests/unit/lib/app/autoload/test-mojito-client.client.js
tests/unit/lib/app/autoload/test-mojito-client.client.js
/* * Copyright (c) 2011-2012, Yahoo! Inc. All rights reserved. * Copyrights licensed under the New BSD License. * See the accompanying LICENSE file for terms. */ /*jslint anon:true, sloppy:true, nomen:true, node:true*/ /*global YUI*/ /* * Test suite for the mojito-client.client.js file functionality. */ YUI({useBrowserConsole: true}).use( 'mojito-client', 'test', function(Y) { var suite = new Y.Test.Suite("mojito-client.client tests"), A = Y.Assert; suite.add(new Y.Test.Case({ setUp: function() { this.mojitoClient = new Y.mojito.Client(); }, "test constructor": function() { var client = this.mojitoClient; A.isObject(client); } })); Y.Test.Runner.add(suite); } );
JavaScript
0
@@ -235,16 +235,71 @@ YUI*/%0A%0A +YUI.add('mojito-tunnel-client', function(Y, NAME) %7B%7D);%0A %0A/*%0A * T
01a95a69a537c3a5432f41dfa7fc81c36f2ce535
fix comment parsing in Foxx controllers
js/common/modules/org/arangodb/foxx/preprocessor.js
js/common/modules/org/arangodb/foxx/preprocessor.js
/*global require, exports */ //////////////////////////////////////////////////////////////////////////////// /// @brief Foxx Preprocessor /// /// @file /// /// DISCLAIMER /// /// Copyright 2013 triagens GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is triAGENS GmbH, Cologne, Germany /// /// @author Lucas Dohmen /// @author Copyright 2013, triAGENS GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// var Preprocessor, preprocess, ArrayIterator, extend = require("underscore").extend, coffeeScript = require("coffee-script"); ArrayIterator = function (arr) { 'use strict'; this.array = arr; this.currentLineNumber = -1; }; extend(ArrayIterator.prototype, { next: function () { 'use strict'; this.currentLineNumber += 1; return this.array[this.currentLineNumber]; }, current: function () { 'use strict'; return this.array[this.currentLineNumber]; }, hasNext: function () { 'use strict'; return this.currentLineNumber < (this.array.length - 1); }, replaceWith: function (newLine) { 'use strict'; this.array[this.currentLineNumber] = newLine; }, entireString: function () { 'use strict'; return this.array.join("\n"); }, getCurrentLineNumber: function () { 'use strict'; if (this.hasNext()) { return this.currentLineNumber; } } }); Preprocessor = function (input, type) { 'use strict'; if (type === 'coffee') { input = coffeeScript.compile(input, {bare: true}); } this.iterator = new ArrayIterator(input.replace('\r', '').split("\n")); this.inJSDoc = false; }; extend(Preprocessor.prototype, { result: function () { 'use strict'; return this.iterator.entireString(); }, convert: function () { 'use strict'; while (this.searchNext()) { this.convertLine(); } return this; }, searchNext: function () { 'use strict'; while (this.iterator.hasNext()) { if (this.isJSDoc(this.iterator.next())) { return true; } } }, convertLine: function () { 'use strict'; this.iterator.replaceWith( "applicationContext.comment(\"" + this.stripComment(this.iterator.current()) + "\");" ); }, getCurrentLineNumber: function () { 'use strict'; return this.iterator.getCurrentLineNumber(); }, // helper stripComment: function (str) { 'use strict'; return str.match(/^\s*\/?\*\*?\/?\s*(.*)$/)[1]; }, isJSDoc: function (str) { 'use strict'; var matched; if (this.inJSDoc && str.match(/^\s*\*/)) { matched = true; if (str.match(/^\s*\*\//)) { this.inJSDoc = false; } } else if ((!this.inJSDoc) && str.match(/^\s*\/\*\*/)) { matched = true; this.inJSDoc = true; } return matched; } }); preprocess = function (input, type) { 'use strict'; var processer = new Preprocessor(input, type); return processer.convert().result(); }; // Only Exported for Tests, please use `process` exports.Preprocessor = Preprocessor; // process(str) returns the processed String exports.preprocess = preprocess; // ----------------------------------------------------------------------------- // --SECTION-- END-OF-FILE // ----------------------------------------------------------------------------- /// Local Variables: /// mode: outline-minor /// outline-regexp: "/// @brief\\|/// @addtogroup\\|/// @page\\|// --SECTION--\\|/// @\\}\\|/\\*jslint" /// End:
JavaScript
0.000006
@@ -3002,29 +3002,31 @@ urn str. -match +replace (/%5E%5Cs*%5C/ ?%5C*%5C*?%5C/ @@ -3021,31 +3021,311 @@ s*%5C/ -? %5C*%5C* -?%5C/?%5Cs*(.*)$/)%5B1%5D; +/, ''). // start of JSDoc comment%0A replace(/%5E%5Cs*%5C*/, ''). // continuation of JSDoc comment%0A replace(/%5E.*?%5C*%5C//, ''). // end of JSDoc comment%0A replace(/%5C%5C/g, '%5C%5C%5C%5C'). // replace backslashes%0A replace(/%22/g, '%5C%5C%22'); // replace quotes %0A %7D @@ -3411,20 +3411,30 @@ .inJSDoc - && +) %7B%0A if ( str.matc @@ -3436,22 +3436,20 @@ .match(/ -%5E%5Cs*%5C* +%5C*%5C/ /)) %7B%0A @@ -3456,86 +3456,98 @@ -matched = true;%0A if (str.match(/%5E%5Cs*%5C*%5C//)) %7B%0A this.inJSDoc = fals + this.inJSDoc = false;%0A matched = true;%0A %7D%0A else %7B%0A matched = tru e;%0A
c8ba54d0a3f43c440866d4ac8595eb87e1447335
use grunt.util.linefeed instead of hard-coding '\n'
tasks/usebanner.js
tasks/usebanner.js
/* * grunt-banner * https://github.com/mattstyles/grunt-banner * * Copyright (c) 2013 Matt Styles * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { // Please see the Grunt documentation for more information regarding task // creation: http://gruntjs.com/creating-tasks grunt.registerMultiTask('usebanner', 'Adds a banner or a footer to a file', function() { // Set up defaults for the options hash var options = this.options({ position: 'top', banner: '' }); if ( options.position !== 'top' && options.position !== 'bottom' ) { options.position = 'top'; } // Iterate over the list of files and add the banner or footer this.files.forEach( function( file ) { file.src.forEach( function( src ) { if ( grunt.file.isFile( src ) ) { grunt.file.write( src, options.position === 'top' ? options.banner + '\n' + grunt.file.read( src ) : grunt.file.read( src ) + '\n' + options.banner ); grunt.log.writeln( 'Banner added to file ' + src.cyan ); } }); }); grunt.log.writeln( '✔'.magenta + ' grunt-banner completed successfully' ); }); };
JavaScript
0.000439
@@ -1015,20 +1015,35 @@ anner + -'%5Cn' +grunt.util.linefeed + grunt @@ -1091,12 +1091,27 @@ ) + -'%5Cn' +grunt.util.linefeed + o @@ -1167,27 +1167,31 @@ %09grunt. -log +verbose .writeln( 'B
34719be9318a0a98dd006dcfa6f26f672bdce5d2
Correct 'abort' message.
tasks/wp_deploy.js
tasks/wp_deploy.js
/* * grunt-wp-deploy * https://github.com/stephenharris/wp-deploy * * Copyright (c) 2013 Stephen Harris * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { var exec = require('child_process').exec; var inquirer = require('inquirer'); // Please see the Grunt documentation for more information regarding task // creation: http://gruntjs.com/creating-tasks grunt.registerMultiTask('wp_deploy', 'Deploys a git Repo to the WordPress SVN repo', function() { var done = this.async(); var cmd; var options = this.options({ svn_url: "http://plugins.svn.wordpress.org/{plugin-slug}", svn_user: false, plugin_slug: false, build_dir: false, }); var pkg = grunt.file.readJSON('package.json'); var questions = []; if( !options.plugin_slug ){ grunt.fail.fatal( "Plug-in slug not provided" ); } if( !options.build_dir ){ grunt.fail.fatal( "Build directory not provided" ); } if( !options.svn_user ){ questions.push({ type: "input", name: "svn_username", message: "What's your SVN username?" }); } inquirer.prompt( questions, function( answers ) { //Set up slug, main file, readme file and paths. var slug = options.plugin_slug; var svnpath = "/tmp/" + slug; var build_dir = options.build_dir.replace(/\/?$/, '/'); //trailing slash var plugin_file = build_dir + slug+".php"; var readme_file = build_dir + "readme.txt"; //SVN user/url var svnuser = options.svn_user || answers.svn_username; var svnurl = options.svn_url.replace( '{plugin-slug}', slug ); //Try to find readme if ( !grunt.file.exists(readme_file) ) { grunt.fail.warn('readme.txt file not not found.'); } //Try to find plug-in file if ( !grunt.file.exists(plugin_file) ) { grunt.fail.warn( plugin_file+' file not not found.'); } //Get versions: var readme = grunt.file.read(readme_file); var readmeVersion = readme.match( new RegExp("^Stable tag:\\s*(\\S+)","im") ); var plugin = grunt.file.read(plugin_file); var pluginVersion = plugin.match( new RegExp("^Version:\\s*(\\S+)","im") ); //Check versions if( projectVersionCompare( pluginVersion[1], readmeVersion[1] ) !== 0 ){ grunt.log.warn( 'Versions do not match:'); grunt.log.warn( "(readme.txt) " + readmeVersion[1] + " != " + pluginVersion[1] + " ("+plugin_file+")" ); } //Set some varaibles var new_version = pluginVersion[1]; var commitmsg = "Tagging "+new_version; //Clean up temp dir cmd = exec( 'rm -fr '+svnpath ); //Check out SVN repo grunt.log.writeln( 'Checking out '+ svnurl ); var cmd = exec( 'svn co '+svnurl+ ' ' + svnpath, {}, function(){ if( !grunt.file.exists( svnpath ) ){ grunt.fail.fatal( 'Checkout of "'+svnurl+'"unsuccessful'); } grunt.log.writeln( 'Check out complete.'); if( grunt.file.exists( svnpath+"/tags/"+new_version) ){ grunt.fail.warn( 'Tag ' + new_version + ' already exists'); } //Clearing trunk grunt.log.writeln( 'Clearing trunk.'); exec( 'rm -fr '+svnpath+"/trunk/*" ); //grunt.log.writeln( 'Ignoring github specific files and deployment script.'); exec( 'svn propset svn:ignore "deploy.sh readme.md .git .gitignore" "'+svnpath+'/trunk/"' ); //Copying build to temporary directory grunt.log.writeln( 'Copying ' + build_dir + ' to ' + svnpath+'/trunk/'); exec( 'cp -ar '+ build_dir + '. ' + svnpath+'/trunk/' ); //Lets ask for confirmation before commit stuff inquirer.prompt( [ { type: "confirm", name: "are_you_sure", message: 'Are you sure you want to commit "'+ new_version+'"?' }], function( answers ) { if( !answers.are_you_sure ){ grunt.log.writeln( 'Removing temporary directory ' + svnpath ); return; } //Add all new files that are not set to be ignored cmd = "cd "+svnpath+"/trunk; pwd;"; cmd += "svn status | grep -v '^.[ \t]*\\..*' | grep '^?' | awk '{print $2}' | xargs svn add;"; //Add new files cmd += "svn status | grep -v '^.[ \t]*\\..*' | grep '^!' | awk '{print $2}' | xargs svn delete;"; //Remove missing files exec(cmd,{}, function( a, b, c ){ //Commit to trunk grunt.log.writeln( 'Committing to trunk'); var cmd = exec( 'cd '+svnpath+'/trunk\n svn commit --username="'+svnuser+'" -m "'+commitmsg+'"',{}, function( a, b, c ){ //Copy to tag grunt.log.writeln( 'Copying to tag'); var cmd = exec( "cd "+svnpath+"\n svn copy trunk/ tags/"+new_version, {}, function( a, b,c ){ //Commit tag grunt.log.writeln( 'Committing tag'); var cmd = exec( 'cd '+svnpath+'/tags/'+new_version+'\n svn commit --username="'+svnuser+'" -m "'+commitmsg+'"', {}, function( a,b,c){ done(); }); }); } ); }); });//Confirmation }); }); //Initial questions }); //Compares version numbers var projectVersionCompare = function(left, right) { if (typeof left + typeof right !== 'stringstring'){ return false; } var a = left.split('.'), b = right.split('.'), i = 0, len = Math.max(a.length, b.length); for (; i < len; i++) { if ((a[i] && !b[i] && parseInt(a[i], 10) > 0) || (parseInt(a[i], 10) > parseInt(b[i], 10))) { return 1; } else if ((b[i] && !a[i] && parseInt(b[i], 10) > 0) || (parseInt(a[i], 10) < parseInt(b[i], 10))) { return -1; } } return 0; }; };
JavaScript
0.003823
@@ -3675,48 +3675,20 @@ n( ' -Removing temporary directory ' + svnpath +Aborting...' );%0A
930b8bc91f7c963a4510c21db5785931f41fa0c6
set type to directory on directories
fs.js
fs.js
var fs = require('fs') var pump = require('pump') var mkdirp = require('mkdirp') var through = require('through2') var path = require('path') var walker = require('folder-walker') var each = require('stream-each') module.exports.listEach = function (opts, onEach, cb) { var stream = walker(opts.dir, {filter: opts.filter || function (filename) { var basename = path.basename(filename) if (basename[0] === '.') return false // ignore hidden files and folders return true }}) each(stream, function (data, next) { var item = { name: data.relname, mode: data.stat.mode, uid: data.stat.uid, gid: data.stat.gid, mtime: data.stat.mtime.getTime(), ctime: data.stat.ctime.getTime() } var isFile = data.stat.isFile() if (isFile) { item.createReadStream = function () { return fs.createReadStream(data.filepath) } } onEach(item, next) }, cb) } module.exports.createDownloadStream = function (drive, dir) { return through.obj(function (entry, enc, next) { var entryPath = path.join(dir, entry.value.name) mkdirp.sync(path.dirname(entryPath)) var content = drive.get(entry) var writeStream = fs.createWriteStream(entryPath, {mode: entry.value.mode}) pump(content.createStream(), writeStream, function (err) { next(err) }) }) }
JavaScript
0.000003
@@ -888,25 +888,129 @@ %7D%0A -%7D + item.type = 'file'%0A %7D%0A var isDir = data.stat.isDirectory()%0A if (isDir) item.type = 'directory' %0A onEach(
830a354447f2e622845ef46db0ff0e6695b0846f
Fix socialTrack
ga.js
ga.js
/** * @class GA * @author Flavio De Stefano <[email protected]> * Proxy module for Google Analitycs * * Require 'analitycs.google' * */ /** * * **ua**: UA of Google Analitycs. Default: `null` * @type {Object} */ var config = _.extend({ ua: null }, Alloy.CFG.T.ga); exports.config = config; var $ = require('analytics.google'); var $TRACKER = null; /** * Track an event * * @param {String} cat Category **or object passed to native proxy** * @param {String} act The action * @param {String} [lbl] Label * @param {String} [val] Value */ function trackEvent(cat, act, lbl, val){ if (!$TRACKER) return; var obj = {}; if (_.isObject(cat)) { obj = cat; } else { obj.category = cat; obj.action = act; obj.label = lbl ? lbl : ''; obj.value = val ? +val : 0; } $TRACKER.trackEvent(obj); Ti.API.debug("GA: EVENT - "+JSON.stringify(obj)); } exports.trackEvent = trackEvent; /** * @method event * @inheritDoc #trackEvent * Alias for {@link #trackEvent} */ exports.event = trackEvent; /** * Track a screen * * @param {String} name The screen name */ function trackScreen(name){ if (!$TRACKER) return; $TRACKER.trackScreen(name); Ti.API.debug("GA: SCREEN - "+name); } exports.trackScreen = trackScreen; /** * @method screen * @inheritDoc #trackScreen * Alias for {@link #trackScreen} */ exports.screen = trackScreen; /** * Track a social action * * @param {String} net The social network name **or object passed to native proxy** * @param {String} [act] The action (Default `share`) * @param {String} [tar] Target */ function trackSocial(net, act, tar){ if (!$TRACKER) return; var obj = {}; if (_.isObject(net)) { obj = net; } else { obj.network = net; obj.action = act || 'share'; obj.target = tar || ''; } $TRACKER.trackSocial(net); Ti.API.debug("GA: SOCIAL - "+JSON.stringify(obj)); } exports.trackSocial = trackSocial; /** * @method social * @inheritDoc #trackSocial * Alias for {@link #trackSocial} */ exports.social = trackSocial; /** * Track timing * * @param {String} cat Category **or object passed to native proxy** * @param {String} time Time expressed in ms * @param {String} [name] Name * @param {String} [lbl] Label */ function trackTiming(cat, time, name, lbl){ if (!$TRACKER) return; var obj = {}; if (_.isObject(cat)) { obj = cat; } else { obj.category = cat; obj.time = time; obj.name = name || ''; obj.label = lbl || ''; } $TRACKER.trackTiming(obj); Ti.API.debug("GA: TIME - "+JSON.stringify(obj)); } exports.trackTiming = trackTiming; /** * @method time * @inheritDoc #trackTiming * Alias for {@link #trackTiming} */ exports.time = trackTiming; /** * Set the tracker UA. * @param {String} ua */ function setTrackerUA(ua) { $TRACKER = $.getTracker(ua); } exports.setTrackerUA = setTrackerUA; (function init(){ $.trackUncaughtExceptions = true; $.debug = false; if (config.ua) { setTrackerUA(config.ua); } })();
JavaScript
0
@@ -1828,19 +1828,19 @@ kSocial( -net +obj );%0A%09Ti.A
2061c800ee1572f7bf83b5c3541b03490a98cbc2
Add id#ivars() helper to get a wrapped id's instance variables.
id.js
id.js
/** * The 'id' function is essentially the "base class" for all Objective-C * objects that get passed around JS-land. */ var proto = exports.proto = Object.create(Function.prototype) , core = require('./core') , types = require('./types') , SEL = require('./sel') , exception = require('./exception') /** * Wraps up a pointer that is expected to be a compatible Objective-C * object that can recieve messages. */ exports.wrap = function wrap (pointer) { // This 'id' function is syntax sugar around the msgSend function attached to // it. 'msgSend' is expecting the selector first, an Array of args second, so // this function just massages it into place and returns the result. function id () { var args = [] , sel if (arguments.length === 1) { var arg = arguments[0] if (arg.constructor.name == 'String') { sel = arg } else { sel = [] Object.keys(arg).forEach(function (s) { sel.push(s) args.push(arg[s]) }) sel.push('') sel = sel.join(':') } } else { sel = [] var len = arguments.length for (var i=0; i<len; i+=2) { sel.push(arguments[i]) args.push(arguments[i+1]) } sel.push('') sel = sel.join(':') } return id.msgSend(sel, args) } // Save a reference to the pointer for use by the prototype functions id.pointer = pointer; // Morph into a MUTANT FUNCTION FREAK!!1! id.__proto__ = proto; return id; } // Avoid a circular dep. core._idwrap = exports.wrap; /** * A very important function that *does the message sending* between * Objective-C objects. When you do `array('addObject', anObject)`, this * `msgSend` function is the one that finally gets called to do the dirty work. * * This function accepts a String selector as the first argument, and an Array * of (wrapped) values that get passed to the the message. This function takes * care of unwrapping the passing in arguments an wrapping up the result value, * if necessary. * * If you wanted to monkey-patch *every* message that got sent out from an * object though NodObjC, this is the place to do it. */ proto.msgSend = function msgSend (sel, args) { var types = this._getTypes(sel) , argTypes = types[1] , msgSendFunc = core.get_objc_msgSend(types) , unwrappedArgs = core.unwrapValues([this, sel].concat(args), argTypes) , rtn try { rtn = msgSendFunc.apply(null, unwrappedArgs) } catch (e) { throw exception.wrap(e) } // Process the return value into a wrapped value if needed return core.wrapValue(rtn, types[0]) } /** * Accepts a SEL and queries the current object for the return type and * argument types for the given selector. If current object does not implment * that selector, then check the superclass, and repeat recursively until * a subclass that responds to the selector is found, or until the base class * is found (in which case the current obj does not respond to 'sel' and we * should throw an Error). */ proto._getTypes = function getTypes (sel) { var c = this.getClass() , t = c._getTypesClass(sel, this.isClass) if (!t) throw new Error('Object does not respond to selector: '+sel); return t; } /** * Retrieves the wrapped Class instance for this object. */ proto.getClass = function getClass () { return exports._wrapClass(this._getClassPointer()); } /** * Returns the node-ffi pointer for the class of this object. */ proto._getClassPointer = function getClassPointer () { return core.object_getClass(this.pointer) } /** * Calls 'object_getClassName()' on this object. */ proto.getClassName = function getClassName () { return core.object_getClassName(this.pointer); } /** * Dynamically changes the object's Class. */ proto.setClass = function setClass (newClass) { return exports._wrapClass(core.object_setClass(this.pointer, newClass.pointer)); } /** * Walks up the inheritance chain and returns an Array of Strings of * superclasses. */ proto.ancestors = function ancestors () { var rtn = [] , c = this.getClass() while (c) { rtn.push(c.getName()) c = c.getSuperclass() } return rtn } /** * Returns an Array of Strings of the names of methods that the current object * will respond to. This function can iterate through the object's superclasses * recursively, if you specify a 'maxDepth' number argument. */ proto.methods = function methods (maxDepth, sort) { var rtn = [] , c = this.getClass() , md = maxDepth || 1 , depth = 0 while (c && depth++ < md) { var ms = c.getInstanceMethods() , i = ms.length while (i--) { if (!~rtn.indexOf(ms[i])) rtn.push(ms[i]); } c = c.getSuperclass() } return sort === false ? rtn : rtn.sort() } /** * The id wrap's overidden toString() function proxies up to the id's * description method: [[id description] UTF8String] */ proto.toString = function toString () { return this('description')('UTF8String'); } proto.inspect = function inspect () { return this.toString() }
JavaScript
0
@@ -4186,24 +4186,392 @@ turn rtn%0A%7D%0A%0A +proto.ivars = function ivars (maxDepth, sort) %7B%0A var rtn = %5B%5D%0A , c = this.getClass()%0A , md = maxDepth %7C%7C 1%0A , depth = 0%0A while (c && depth++ %3C md) %7B%0A var is = c.getInstanceVariables()%0A , i = is.length%0A while (i--) %7B%0A if (!~rtn.indexOf(is%5Bi%5D)) rtn.push(is%5Bi%5D)%0A %7D%0A c = c.getSuperclass()%0A %7D%0A return sort === false ? rtn : rtn.sort()%0A%7D%0A%0A /**%0A * Retur
02cf2c342bcf678c6442eb7db85fefd1900882ff
Clear the closeWithTimeout timer before unmounting
lib/components/ModalPortal.js
lib/components/ModalPortal.js
var React = require('react'); var div = React.DOM.div; var focusManager = require('../helpers/focusManager'); var scopeTab = require('../helpers/scopeTab'); var cx = require('classnames'); // so that our CSS is statically analyzable var CLASS_NAMES = { overlay: { base: 'ReactModal__Overlay', afterOpen: 'ReactModal__Overlay--after-open', beforeClose: 'ReactModal__Overlay--before-close' }, content: { base: 'ReactModal__Content', afterOpen: 'ReactModal__Content--after-open', beforeClose: 'ReactModal__Content--before-close' } }; var OVERLAY_STYLES = { position: 'fixed', left: 0, right: 0, top: 0, bottom: 0 }; function stopPropagation(event) { event.stopPropagation(); } var ModalPortal = module.exports = React.createClass({ displayName: 'ModalPortal', getInitialState: function() { return { afterOpen: false, beforeClose: false }; }, componentDidMount: function() { // Focus needs to be set when mounting and already open if (this.props.isOpen) { this.setFocusAfterRender(true); this.open(); } }, componentWillReceiveProps: function(newProps) { // Focus only needs to be set once when the modal is being opened if (!this.props.isOpen && newProps.isOpen) { this.setFocusAfterRender(true); this.open(); } else if (this.props.isOpen && !newProps.isOpen) { this.close(); } }, componentDidUpdate: function () { if (this.focusAfterRender) { this.focusContent(); this.setFocusAfterRender(false); } }, setFocusAfterRender: function (focus) { this.focusAfterRender = focus; }, open: function() { focusManager.setupScopedFocus(this.getDOMNode()); focusManager.markForFocusLater(); this.setState({isOpen: true}, function() { this.setState({afterOpen: true}); }.bind(this)); }, close: function() { if (!this.ownerHandlesClose()) return; if (this.props.closeTimeoutMS > 0) this.closeWithTimeout(); else this.closeWithoutTimeout(); }, focusContent: function() { this.refs.content.getDOMNode().focus(); }, closeWithTimeout: function() { this.setState({beforeClose: true}, function() { setTimeout(this.closeWithoutTimeout, this.props.closeTimeoutMS); }.bind(this)); }, closeWithoutTimeout: function() { this.setState({ afterOpen: false, beforeClose: false }, this.afterClose); }, afterClose: function() { focusManager.returnFocus(); focusManager.teardownScopedFocus(); }, handleKeyDown: function(event) { if (event.keyCode == 9 /*tab*/) scopeTab(this.refs.content.getDOMNode(), event); if (event.keyCode == 27 /*esc*/) this.requestClose(); }, handleOverlayClick: function() { if (this.ownerHandlesClose()) this.requestClose(); else this.focusContent(); }, requestClose: function() { if (this.ownerHandlesClose()) this.props.onRequestClose(); }, ownerHandlesClose: function() { return this.props.onRequestClose; }, shouldBeClosed: function() { return !this.props.isOpen && !this.state.beforeClose; }, buildClassName: function(which) { var className = CLASS_NAMES[which].base; if (this.state.afterOpen) className += ' '+CLASS_NAMES[which].afterOpen; if (this.state.beforeClose) className += ' '+CLASS_NAMES[which].beforeClose; return className; }, render: function() { return this.shouldBeClosed() ? div() : ( div({ ref: "overlay", className: cx(this.buildClassName('overlay'), this.props.overlayClassName), style: OVERLAY_STYLES, onClick: this.handleOverlayClick }, div({ ref: "content", style: this.props.style, className: cx(this.buildClassName('content'), this.props.className), tabIndex: "-1", onClick: stopPropagation, onKeyDown: this.handleKeyDown }, this.props.children ) ) ); } });
JavaScript
0
@@ -1083,32 +1083,110 @@ ();%0A %7D%0A %7D,%0A%0A + componentWillUnmount: function() %7B%0A clearTimeout(this.closeTimer);%0A %7D,%0A%0A componentWillR @@ -2297,16 +2297,34 @@ %7B%0A + this.closeTimer = setTime
2a9a78f7fc4212a48670db9c814c5d8a141fd5ce
Update src/models/Thread.js
src/models/Thread.js
src/models/Thread.js
import { FirestoreModel } from 'myfirebase' class Thread extends FirestoreModel { /** * Create new Thread.js Instance. * * @param {object} ref */ constructor (ref) { super(ref) } /** * Define required properties. * * @return array */ required () { return [] } /** * Set User id. * * @param {int} uid * @return void */ setUserId (uid) { this.uid = uid } /** * Set Photo url. * * @param {string} photoURL * @return void */ setPhotoUrl (photoURL) { this.photoURL = photoURL } /** * Set Username. * * @param {string} username * @return void */ setUsername (username) { this.username = username } /** * Set created_at. * * @param {*} timestamp * @return void */ setCreatedAt (timestamp) { this.created_at = timestamp } /** * Check if the message is empty. * * @return {Boolean} */ isEmpty () { return !this.message } } export default Thread;
JavaScript
0.000001
@@ -1124,16 +1124,139 @@ ge%0A %7D +%0A%0A /**%0A * Clear message.%0A * %0A * @return %7Bvoid%7D%0A */%0A clearMessage () %7B%0A this.message = ''%0A %7D %0A%7D%0A%0Aexpo
e04ca0b17eebd49abc295da27ee78f616e4c32b5
Update src/models/Thread.js
src/models/Thread.js
src/models/Thread.js
import { FirestoreModel } from 'myfirebase' class Thread extends FirestoreModel { /** * Create new Thread.js Instance. * * @param {object} ref */ constructor (ref) { super(ref) } /** * Define required properties. * * @return array */ required () { return [] } /** * Set User id. * * @param {int} uid * @return void */ setUserId (uid) { this.uid = uid } /** * Set Photo url. * * @param {string} photoURL * @return void */ setPhotoUrl (photoURL) { this.photoURL = photoURL } /** * Set Username. * * @param {string} username * @return void */ setUsername (username) { this.username = username } /** * Set created_at. * * @param {*} timestamp * @return void */ setCreatedAt (timestamp) { this.created_at = timestamp } /** * Check if the message is empty. * * @return {Boolean} */ isEmpty () { return !this.message } /** * Clear message. * * @return {void} */ clearMessage () { this.message = '' } } export default Thread;
JavaScript
0.000001
@@ -1247,16 +1247,161 @@ ''%0A %7D +%0A%0A /**%0A * Set thread message.%0A * %0A * @param %7Bvoid%7D message%0A */%0A setMessage (message) %7B%0A this.message = message%0A %7D %0A%7D%0A%0Aexpo
3294cfc76f403723dcb7b0198365cbffa20b455b
add nav-extended, close #406
src/navbar/navbar.js
src/navbar/navbar.js
import { bindable, customElement } from 'aurelia-templating'; import { bindingMode } from 'aurelia-binding'; import { inject } from 'aurelia-dependency-injection'; import { getBooleanFromAttributeValue } from '../common/attributes'; import { AttributeManager } from '../common/attributeManager'; @customElement('md-navbar') @inject(Element) export class MdNavbar { @bindable({ defaultBindingMode: bindingMode.oneTime }) mdFixed; @bindable({ defaultBindingMode: bindingMode.oneTime }) mdAutoHeight; fixedAttributeManager; constructor(element) { this.element = element; } attached() { this.fixedAttributeManager = new AttributeManager(this.fixedAnchor); this.navAttributeManager = new AttributeManager(this.nav); if (getBooleanFromAttributeValue(this.mdFixed)) { this.fixedAttributeManager.addClasses('navbar-fixed'); } if (getBooleanFromAttributeValue(this.mdAutoHeight)) { this.navAttributeManager.addClasses('md-auto-height'); } } detached() { if (getBooleanFromAttributeValue(this.mdFixed)) { this.fixedAttributeManager.removeClasses('navbar-fixed'); } if (getBooleanFromAttributeValue(this.mdAutoHeight)) { this.navAttributeManager.addClasses('md-auto-height'); } } }
JavaScript
0
@@ -413,24 +413,99 @@ ode.oneTime%0A + %7D) mdExtended;%0A @bindable(%7B%0A defaultBindingMode: bindingMode.oneTime%0A %7D) mdFixed @@ -502,24 +502,24 @@ %7D) mdFixed;%0A - @bindable( @@ -1061,24 +1061,146 @@ ht');%0A %7D%0A + if (getBooleanFromAttributeValue(this.mdExtended)) %7B%0A this.navAttributeManager.addClasses('nav-extended');%0A %7D%0A %7D%0A%0A detac @@ -1413,35 +1413,38 @@ ttributeManager. -add +remove Classes('md-auto @@ -1456,18 +1456,143 @@ ht');%0A %7D%0A + if (getBooleanFromAttributeValue(this.mdExtended)) %7B%0A this.navAttributeManager.removeClasses('nav-extended');%0A %7D%0A %7D%0A%7D%0A
a0520205fb3768f3d6b92cb438291af79b6ad6be
Fix DstoreAdapter range query and result total
legacy/DstoreAdapter.js
legacy/DstoreAdapter.js
define([ 'dojo/_base/declare', 'dojo/_base/array', 'dojo/store/util/QueryResults' /*=====, "dstore/api/Store" =====*/ ], function (declare, arrayUtil, QueryResults /*=====, Store =====*/) { // module: // An adapter mixin that makes a dstore store object look like a legacy Dojo object store. // No base class, but for purposes of documentation, the base class is dstore/api/Store var base = null; /*===== base = Store; =====*/ var adapterPrototype = { // store: // The dstore store that is wrapped as a Dojo object store store: null, constructor: function (kwArgs) { declare.safeMixin(this, kwArgs); }, query: function (query, options) { // summary: // Queries the store for objects. This does not alter the store, but returns a // set of data from the store. // query: String|Object|Function // The query to use for retrieving objects from the store. // options: dstore/api/Store.QueryOptions // The optional arguments to apply to the resultset. // returns: dstore/api/Store.QueryResults // The results of the query, extended with iterative methods. // // example: // Given the following store: // // ...find all items where "prime" is true: // // | store.query({ prime: true }).forEach(function(object){ // | // handle each object // | }); var results = this.store.filter(query); if (options) { // Apply sorting var sort = options.sort; if (sort) { if (Object.prototype.toString.call(sort) === '[object Array]') { var sortOptions; while ((sortOptions = sort.pop())) { results = results.sort(sortOptions.attribute, sortOptions.descending); } } else { results = results.sort(sort); } } // Apply a range var start = options.start; var end = start != null && options.count && (start + options.count); results = results.range(start, end); } return new QueryResults(results.map(function (object) { return object; })); } }; var delegatedMethods = [ 'get', 'put', 'add', 'remove', 'getIdentity' ]; arrayUtil.forEach(delegatedMethods, function (methodName) { adapterPrototype[methodName] = function () { var store = this.store; return store[methodName].apply(store, arguments); }; }); return declare(base, adapterPrototype); });
JavaScript
0.000001
@@ -1768,27 +1768,30 @@ %09%09%09%09 -var +if (' start - = +' in options .sta @@ -1790,89 +1790,50 @@ ions -.start; +) %7B %0A%09%09%09%09 +%09 var - end = start -! = -null && options.count && (start + options.count) +options.start %7C%7C 0 ;%0A +%09 %09%09%09%09 @@ -1860,35 +1860,119 @@ nge( -start, end);%0A%09%09%09%7D%0A%09%09%09return +%0A%09%09%09%09%09%09start,%0A%09%09%09%09%09%09options.count ? (start + options.count) : Infinity%0A%09%09%09%09%09);%0A%09%09%09%09%7D%0A%09%09%09%7D%0A%09%09%09var queryResults = new @@ -2044,16 +2044,79 @@ %09%09%09%7D));%0A +%09%09%09queryResults.total = results.total;%0A%09%09%09return queryResults;%0A %09%09%7D%0A%09%7D;%0A
cdcd46cea88e1d7cf35e74e14f819f3b04c8653b
Fix angular module creation.
src/observability.js
src/observability.js
(function() { "use strict"; var observableMethods = { registerObserver: function (fn) { if (typeof fn !== "function") { throw new TypeError("registerObserver must be called with a function"); } setupObservers(this); this._observers.push(fn); }, notifyObservers: function () { var notifyArgs = arguments; this._observers.forEach(function(fn) { fn.apply(null, notifyArgs); }); } }; function setupObservers(obj) { if (obj._observers) { return; } Object.defineProperty(obj, "_observers", { enumerable: false, // Hide property from for..in, JSON.stringify, etc. writable: false, // Prevent overwriting configurable: false, // Prevent redefinition value: [] }); } function mixinObservability (obj) { if (obj.hasOwnProperty('_observers')) { throw new Error("the '_observers' property is already in use"); } obj.registerObserver = observableMethods.registerObserver; obj.notifyObservers = observableMethods.notifyObservers; return obj; } window.mixinObservability = mixinObservability; if (window.angular) { angular.module("observability.js").value("mixinObservability", mixinObservability); } })();
JavaScript
0
@@ -1404,16 +1404,20 @@ lity.js%22 +, %5B%5D ).value(
98a8c58eb12a3d51b3173237010ba4e383c2c111
Fix for click in submit button's children. Also fixes that button's value not being posted. Can't test until jsdom gets fixed, see https://github.com/tmpvar/jsdom/pull/1523 [#1523]
src/parsley/form.js
src/parsley/form.js
import $ from 'jquery'; import ParsleyAbstract from './abstract'; import ParsleyUtils from './utils'; var ParsleyForm = function (element, domOptions, options) { this.__class__ = 'ParsleyForm'; this.$element = $(element); this.domOptions = domOptions; this.options = options; this.parent = window.Parsley; this.fields = []; this.validationResult = null; }; var statusMapping = {pending: null, resolved: true, rejected: false}; ParsleyForm.prototype = { onSubmitValidate: function (event) { // This is a Parsley generated submit event, do not validate, do not prevent, simply exit and keep normal behavior if (true === event.parsley) return; // If we didn't come here through a submit button, use the first one in the form var $submitSource = this._$submitSource || this.$element.find('input[type="submit"], button[type="submit"]').first(); this._$submitSource = null; this.$element.find('.parsley-synthetic-submit-button').prop('disabled', true); if ($submitSource.is('[formnovalidate]')) return; var promise = this.whenValidate({event}); if ('resolved' === promise.state() && false !== this._trigger('submit')) { // All good, let event go through. We make this distinction because browsers // differ in their handling of `submit` being called from inside a submit event [#1047] } else { // Rejected or pending: cancel this submit event.stopImmediatePropagation(); event.preventDefault(); if ('pending' === promise.state()) promise.done(() => { this._submit($submitSource); }); } }, onSubmitButton: function(event) { this._$submitSource = $(event.target); }, // internal // _submit submits the form, this time without going through the validations. // Care must be taken to "fake" the actual submit button being clicked. _submit: function ($submitSource) { if (false === this._trigger('submit')) return; // Add submit button's data if ($submitSource) { var $synthetic = this.$element.find('.parsley-synthetic-submit-button').prop('disabled', false); if (0 === $synthetic.length) $synthetic = $('<input class="parsley-synthetic-submit-button" type="hidden">').appendTo(this.$element); $synthetic.attr({ name: $submitSource.attr('name'), value: $submitSource.attr('value') }); } this.$element.trigger($.extend($.Event('submit'), {parsley: true})); }, // Performs validation on fields while triggering events. // @returns `true` if all validations succeeds, `false` // if a failure is immediately detected, or `null` // if dependant on a promise. // Consider using `whenValidate` instead. validate: function (options) { if (arguments.length >= 1 && !$.isPlainObject(options)) { ParsleyUtils.warnOnce('Calling validate on a parsley form without passing arguments as an object is deprecated.'); var [group, force, event] = arguments; options = {group, force, event}; } return statusMapping[ this.whenValidate(options).state() ]; }, whenValidate: function ({group, force, event} = {}) { this.submitEvent = event; if (event) { this.submitEvent = $.extend({}, event, {preventDefault: () => { ParsleyUtils.warnOnce("Using `this.submitEvent.preventDefault()` is deprecated; instead, call `this.validationResult = false`"); this.validationResult = false; }}); } this.validationResult = true; // fire validate event to eventually modify things before very validation this._trigger('validate'); // Refresh form DOM options and form's fields that could have changed this._refreshFields(); var promises = this._withoutReactualizingFormOptions(() => { return $.map(this.fields, field => field.whenValidate({force, group})); }); return ParsleyUtils.all(promises) .done( () => { this._trigger('success'); }) .fail( () => { this.validationResult = false; this.focus(); this._trigger('error'); }) .always(() => { this._trigger('validated'); }) .pipe(...this._pipeAccordingToValidationResult()); }, // Iterate over refreshed fields, and stop on first failure. // Returns `true` if all fields are valid, `false` if a failure is detected // or `null` if the result depends on an unresolved promise. // Prefer using `whenValid` instead. isValid: function (options) { if (arguments.length >= 1 && !$.isPlainObject(options)) { ParsleyUtils.warnOnce('Calling isValid on a parsley form without passing arguments as an object is deprecated.'); var [group, force] = arguments; options = {group, force}; } return statusMapping[ this.whenValid(options).state() ]; }, // Iterate over refreshed fields and validate them. // Returns a promise. // A validation that immediately fails will interrupt the validations. whenValid: function ({group, force} = {}) { this._refreshFields(); var promises = this._withoutReactualizingFormOptions(() => { return $.map(this.fields, field => field.whenValid({group, force})); }); return ParsleyUtils.all(promises); }, _refreshFields: function () { return this.actualizeOptions()._bindFields(); }, _bindFields: function () { var oldFields = this.fields; this.fields = []; this.fieldsMappedById = {}; this._withoutReactualizingFormOptions(() => { this.$element .find(this.options.inputs) .not(this.options.excluded) .each((_, element) => { var fieldInstance = new window.Parsley.Factory(element, {}, this); // Only add valid and not excluded `ParsleyField` and `ParsleyFieldMultiple` children if (('ParsleyField' === fieldInstance.__class__ || 'ParsleyFieldMultiple' === fieldInstance.__class__) && (true !== fieldInstance.options.excluded)) if ('undefined' === typeof this.fieldsMappedById[fieldInstance.__class__ + '-' + fieldInstance.__id__]) { this.fieldsMappedById[fieldInstance.__class__ + '-' + fieldInstance.__id__] = fieldInstance; this.fields.push(fieldInstance); } }); $.each(ParsleyUtils.difference(oldFields, this.fields), (_, field) => { field._trigger('reset'); }); }); return this; }, // Internal only. // Looping on a form's fields to do validation or similar // will trigger reactualizing options on all of them, which // in turn will reactualize the form's options. // To avoid calling actualizeOptions so many times on the form // for nothing, _withoutReactualizingFormOptions temporarily disables // the method actualizeOptions on this form while `fn` is called. _withoutReactualizingFormOptions: function (fn) { var oldActualizeOptions = this.actualizeOptions; this.actualizeOptions = function () { return this; }; var result = fn(); this.actualizeOptions = oldActualizeOptions; return result; }, // Internal only. // Shortcut to trigger an event // Returns true iff event is not interrupted and default not prevented. _trigger: function (eventName) { return this.trigger('form:' + eventName); } }; export default ParsleyForm;
JavaScript
0
@@ -1673,17 +1673,24 @@ $(event. -t +currentT arget);%0A
73b503d5ce23504daa99c492eaaba33f07969ee4
Fix linter error in Kick
src/plugins/Kick.js
src/plugins/Kick.js
import Plugin from "./../Plugin"; import Auth from "../helpers/Auth"; export default class Kick extends Plugin { static get plugin() { return { name: "Kick", description: "Kicks users", help: "Reply with /kick or ban, or send /[kick|ban] ID.", needs: { database: true } }; } onCommand({message, command, args}, reply) { let target; if (args.length === 1) target = Number(args[0]); else if (message.reply_to_message) { if (message.reply_to_message.new_chat_participant) target = message.reply_to_message.new_chat_participant.id; else if (message.reply_to_message.left_chat_participant) target = message.reply_to_message.left_chat_participant.id; else target = message.reply_to_message.from.id; } else target = null; const banned = this.db[message.chat.id]; switch (command) { case "list": return reply({ type: "text", text: JSON.stringify(this.db["chat" + message.chat.id]) }); case "banlist": if (!this.db[message.chat.id]) return reply({ type: "text", text: "Empty." }); return reply({ type: "text", text: JSON.stringify(this.db[message.chat.id]) }); case "kick": if (!Auth.isMod(message.from.id)) return; if (!target) return reply({ type: "text", text: "Reply to a message sent by the kickee with /kick or /ban to remove him. Alternatively, use /kick or /ban followed by the user ID (eg. /kick 1234), which you can get from /list." }); if (Auth.isMod(target)) return reply({ type: "text", text: "Can't kick mods or admins." }); this.bot.kickChatMember(message.chat.id, target).catch((/* err */) => reply({ type: "text", text: "An error occurred while kicking the user." })); return; case "ban": if (!Auth.isMod(message.from.id)) return; if (!target) return reply({ type: "text", text: "Reply to a message sent by the kickee with /kick or /ban to remove him. Alternatively, use /kick or /ban followed by the user ID (eg. /kick 1234), which you can get from /list." }); if (Auth.isMod(target)) return reply({ type: "text", text: "Can't ban mods or admins." }); if (!banned) this.db[message.chat.id] = []; this.db[message.chat.id].push(target); this.bot.kickChatMember(message.chat.id, target).catch((/* err */) => reply({ type: "text", text: "An error occurred while kicking the user." })); return; case "pardon": if (!Auth.isMod(message.from.id)) return; if (!target) return reply({ type: "text", text: "Reply to a message sent by the kickee with /kick or /ban to remove him. Alternatively, use /kick or /ban followed by the user ID (eg. /kick 1234), which you can get from /list." }); if (!banned) return; this.db[message.chat.id] = banned.filter(id => id !== target); reply({ type: "text", text: "Pardoned." }); return; default: return; } } onNewChatParticipant(message, reply) { // If there is no database, nobody was ever banned so far. Return early. if (!this.db[message.chat.id]) return; const target = message.new_chat_participant.id; if (this.db[message.chat.id].indexOf(target) === -1) return; if (Auth.isMod(target)) return; this.bot.kickChatMember(message.chat.id, target).catch((/* err */) => reply({ type: "text", text: "An error occurred while kicking the user." })); } }
JavaScript
0.000001
@@ -910,24 +910,16 @@ %7D -%0A else%0A
7fa04c7f763c76177a0c39c0151822fa19136960
Fix mix of tabs and spaces for indentation
src/proj4leaflet.js
src/proj4leaflet.js
L.CRS.proj4js = (function () { var createProjection = function (code, def, /*L.Transformation*/ transformation) { if (typeof(def) !== 'undefined') { Proj4js.defs[code] = def; } var proj = new Proj4js.Proj(code); return { project: function (latlng) { var point = new L.Point(latlng.lng, latlng.lat); return Proj4js.transform(Proj4js.WGS84, proj, point); }, unproject: function (point, unbounded) { var point2 = Proj4js.transform(proj, Proj4js.WGS84, point.clone()); return new L.LatLng(point2.y, point2.x, unbounded); } }; }; return function (code, def, transformation) { return L.Util.extend({}, L.CRS, { code: code, transformation: transformation ? transformation: new L.Transformation(1, 0, -1, 0), projection: createProjection(code, def) }); }; }());
JavaScript
0.000001
@@ -673,22 +673,19 @@ CRS, %7B%0D%0A - +%09%09%09 code: co @@ -689,22 +689,19 @@ code,%0D%0A - +%09%09%09 transfor @@ -781,14 +781,11 @@ ),%0D%0A - +%09%09%09 proj
d4a4f562b97571f727285fc5c60244b2bcdd082f
Add 'define' statement
chromatography.js
chromatography.js
(function() { var Color; chromato = function(x, y, z, m) { return new Color(x, y, z, m); }; if ((typeof module !== "undefined" && module !== null) && (module.exports != null)) { module.exports = chroma; } chromato.color = function(x, y, z, m) { return new Color(x, y, z, m); }; chromato.color = function(x, y, z, m) { return new Color(x, y, z, m); }; chromato.rgb = function(r, g, b, a) { return new Color(r, g, b, a, 'rgb'); }; chromato.hex = function(x) { return new Color(x); }; chromato.interpolate = function(a, b, f, m) { if ((a == null) || (b == null)) { return '#000'; } if (type(a) === 'string') { a = new Color(a); } if (type(b) === 'string') { b = new Color(b); } return a.interpolate(f, b, m); }; chromato.mix = chromato.interpolate; }).call(this);
JavaScript
0.999999
@@ -215,33 +215,41 @@ %7D%0A%0A -chromato.color + if (typeof define == = +' function (x, @@ -248,57 +248,204 @@ tion -(x, y, z, m) +' && define.amd) %7B%0A define(%5B%5D, function() %7B%0A return chroma;%0A %7D);%0A %7D else %7B%0A + -return new Color(x, y, z, m);%0A%7D; + root = typeof exports !== %22undefined%22 && exports !== null ? exports : this;%0A root.chroma = chroma;%0A %7D %0A%0A
540b635d1bb30deadfa39794bd9bb0a94dcd6fea
Change badge names for magnified badge group
src/constants/badge-groups.js
src/constants/badge-groups.js
import { pluralize } from 'helpers/text'; export const badgeGroups = { MULTI: [ { count: 1, expeditions: 5, name: 'Novice Collection\'s Explorer', badge: 'multi/multi_1x5.png', }, { count: 25, expeditions: 5, name: 'Intermediate Collection\'s Explorer', badge: 'multi/multi_25x5.png', }, ], CROSS: [ { count: 10, name: 'Pioneer', badge: 'cross/10_each.png' }, { count: 30, name: 'Pro', badge: 'cross/NfNProBadge.png' }, ], plant: [ { count: 1, name: 'Seed', badge: 'plants/seed.png' }, { count: 10, name: 'Seedling', badge: 'plants/seedling.png' }, { count: 25, name: 'Sprout', badge: 'plants/sapling.png' }, { count: 75, name: 'Tree', badge: 'plants/tree.png' }, { count: 250, name: 'Oak', badge: 'plants/oak.png' }, { count: 1000, name: 'Mature Tree', badge: 'plants/mature-tree.png' }, ], insect: [ { count: 1, name: 'Egg', badge: 'bugs/egg.png' }, { count: 25, name: 'Caterpillar', badge: 'bugs/caterpillar.png' }, { count: 100, name: 'Butterfly', badge: 'bugs/butterfly.png' }, { count: 500, name: 'Butterflies', badge: 'bugs/butterflies.png' }, ], bird: [ { count: 1, name: 'Nest', badge: 'birds/nest.png' }, { count: 25, name: 'Fledgling', badge: 'birds/fledgling.png' }, { count: 200, name: 'Adult Bird', badge: 'birds/adult.png' }, ], fungus: [ { count: 1, name: 'Spore', badge: 'macrofungi/spore.png' }, { count: 25, name: 'Mycelium', badge: 'macrofungi/mycelium.png' }, { count: 100, name: 'Mushroom', badge: 'macrofungi/mushroom.png' }, ], crab: [ { count: 1, name: 'Egg', badge: 'crabs/egg.png' }, { count: 25, name: 'Zoea', badge: 'crabs/zoea.png' }, { count: 50, name: 'Megalops', badge: 'crabs/megalops.png' }, { count: 100, name: 'Rock Crab', badge: 'crabs/rock-crab.png' }, ], magnified: [ { count: 5, name: '5x', badge: 'magnified/NfN_Parasitoid-02.png' }, { count: 50, name: '50x', badge: 'magnified/NfN_Parasitoid-03.png' }, { count: 150, name: '150x', badge: 'magnified/NfN_Parasitoid-04.png' }, ], }; Object.keys(badgeGroups).forEach(g => badgeGroups[g].forEach(b => { b.group = g; // eslint-disable-line no-param-reassign let description = ''; switch (g) { case 'MULTI': description = `for ${b.count} ${pluralize('records', b.count)} in ${b.expeditions} expeditions`; break; case 'CROSS': description = `for transcribing ${b.count} ${pluralize('records', b.count)} in old and new Notes from Nature`; break; default: description = `for transcribing ${b.count} ${b.group} ${pluralize('records', b.count)}`; } b.description = description; // eslint-disable-line no-param-reassign }));
JavaScript
0
@@ -1909,16 +1909,21 @@ ame: '5x + Zoom ', badge @@ -1988,16 +1988,21 @@ me: '50x + Zoom ', badge @@ -2069,16 +2069,21 @@ e: '150x + Zoom ', badge
166f9079512682774ee29a7bc57c9c660be945d0
add empty select tag
src/containers/QueryFilter.js
src/containers/QueryFilter.js
import { Component } from 'react'; import { connect } from 'react-redux'; import { push } from 'react-router-redux'; export default class TagFilter extends Component { initQueryFilter() { const { loadCategories, loadTags } = this.props; loadCategories(); loadTags(); } getFilteredPosts(categoryInput, tagInput, searchInput) { const { dispatch, loadPosts } = this.props; let fullUrl = ''; let params = {}; // if there is no input, then show all posts again, if not, then show posts filtered by queries if (searchInput.value !== '' || tagInput.value !== '' || categoryInput.value !== '') { if (categoryInput.value !== '') { fullUrl += `/category/${categoryInput.value}`; params.category = categoryInput.value; } if (tagInput.value !== '') { fullUrl += `/tag/${tagInput.value}`; params.tag = tagInput.value; } if (searchInput.value !== '') { fullUrl += `/search/${searchInput.value}`; params.search = searchInput.value; } dispatch(push(fullUrl)); loadPosts(fullUrl, params, false); } else { dispatch(push('/')) loadPosts('/', params, false); } // clear inputs categoryInput.value = ''; tagInput.value = ''; searchInput.value = ''; } componentDidMount() { this.initQueryFilter(); } render() { let categoryInput; let tagInput; let searchInput; return ( <div> <form onSubmit={e => { e.preventDefault(); this.getFilteredPosts(categoryInput, tagInput, searchInput); }}> <select ref={node => { categoryInput = node}}> {Object.keys(this.props.categories).length ? Object.values(this.props.categories).map(category => <option key={category.slug} value={category.slug}>{category.slug}</option>) : <option value="">Loading...</option> } </select> <select ref={node => { tagInput = node}}> {Object.keys(this.props.tags).length ? Object.values(this.props.tags).map(tag => <option key={tag.slug} value={tag.slug}>{tag.slug}</option>) : <option value="">Loading...</option> } </select> <input type="text" placeholder="search" ref={node => { searchInput = node; }}/> <button type="submit">Filter Posts</button> </form> </div> ) } } export default connect()(TagFilter);
JavaScript
0.000001
@@ -1693,32 +1693,71 @@ Input = node%7D%7D%3E%0A + %3Coption value=%22%22%3E%3C/option%3E%0A %7BObj @@ -2072,32 +2072,71 @@ Input = node%7D%7D%3E%0A + %3Coption value=%22%22%3E%3C/option%3E%0A %7BObj @@ -2374,26 +2374,16 @@ select%3E%0A - %0A
e51dfcebb50c2640da8d157bdc4b504fae8998af
remove hide on preview analytics
src/scripts/view.js
src/scripts/view.js
Polymer({ is: 'figme-item-view', properties: { item: Object, isShown: { type: Boolean, value: false } }, show: function() { this.isShown = true; ga('send', 'event', 'Preview', 'show', this.item.id); }, hide: function() { this.isShown = false; ga('send', 'event', 'Preview', 'hide', this.item.id); }, download: function() { var link = document.createElement('a'); link.download = null; link.href = this.item.images.original.url; link.click(); ga('send', 'event', 'Copy', 'Download', this.item.id); }, copy: function() { this.querySelector('#content-copy').click(); } });
JavaScript
0
@@ -336,70 +336,8 @@ se;%0A - ga('send', 'event', 'Preview', 'hide', this.item.id);%0A
9b0eddd2d7cadd0f81fc6f2e5efb774adbee7f42
Fix HTML rendering on server
src/server/index.js
src/server/index.js
import path from 'path'; import express from 'express'; import React from 'react'; import { renderToString } from 'react-dom/server'; import { match, RouterContext } from 'react-router'; import Helmet from 'react-helmet'; import routes from '../shared/routes'; const app = express(); const PORT = process.env.PORT || 8080; app.use(express.static(path.join(__dirname, '/../../dist/public'))); function renderPage(appHtml, head) { return ` <!DOCTYPE html> <html lang="en"> <head ${head.htmlAttributes.toString()}> ${head.meta.toString()} ${head.title.toString()} ${head.link.toString()} </head> <body> <div id="root">${appHtml}</div> <script src="/bundle.js"></script> </body> </html> `; } app.get('*', (req, res) => { match({ routes: routes, location: req.url }, (err, redirect, props) => { if (err) { res.status(500).send(err.message); } else if (redirect) { res.redirect(redirect.pathname + redirect.search); } else if (props) { const appHtml = renderToString(<RouterContext {...props} />); let head = Helmet.rewind(); res.send(renderPage(appHtml, head)); } else { res.status(404).send('Not Found'); } }); }); app.listen(PORT, () => { console.log(`Listening on port ${PORT}`); });
JavaScript
0.000002
@@ -470,31 +470,8 @@ tml -lang=%22en%22%3E%0A %3Chead $%7Bhe @@ -501,16 +501,62 @@ ing()%7D%3E%0A + %3Chead%3E%0A %3Cmeta charset=%22utf-8%22 /%3E%0A @@ -562,20 +562,21 @@ $%7Bhead. -meta +title .toStrin @@ -587,37 +587,36 @@ %0A $%7Bhead. -title +meta .toString()%7D%0A
c75652929c4ecbf09aa60013a53b1bff7c717583
Replace default build reporter for better experience
src/server/index.js
src/server/index.js
/** * Copyright 2017-present, Callstack. * All rights reserved. */ const Express = require("express"); const http = require("http"); /** * Custom made middlewares */ const webpackDevMiddleware = require("webpack-dev-middleware"); const devToolsMiddleware = require("./middleware/devToolsMiddleware"); const liveReloadMiddleware = require("./middleware/liveReloadMiddleware"); const statusPageMiddleware = require("./middleware/statusPageMiddleware"); /** * Temporarily loaded from React Native to get debugger running. Soon to be replaced. */ const WebSocketProxy = require("./util/webSocketProxy.js"); /** * Packager-like Server running on top of Webpack */ class Server { constructor(compiler) { const appHandler = new Express(); const webpackMiddleware = webpackDevMiddleware(compiler, { lazy: false, noInfo: true, watchOptions: { aggregateTimeout: 300, poll: 1000 } }); this.httpServer = http.createServer(appHandler); const debuggerProxy = new WebSocketProxy( this.httpServer, "/debugger-proxy" ); // Middlewares appHandler .use(devToolsMiddleware(debuggerProxy)) .use(liveReloadMiddleware(compiler)) .use(statusPageMiddleware) .use(webpackMiddleware); } /** * Starts listening to incoming requests */ listen(...args) { return this.httpServer.listen(...args); } } module.exports = Server;
JavaScript
0
@@ -55,24 +55,37 @@ s reserved.%0A + * %0A * @flow%0A */%0A%0Aconst E @@ -616,24 +616,568 @@ roxy.js%22);%0A%0A +/**%0A * Better build reporter for Webpack builds%0A */%0Aconst buildReporter = (reporterOptions) =%3E %7B%0A const %7B state, stats, options %7D = reporterOptions;%0A %0A if (!state) %7B%0A console.log('Compiling...');%0A %7D%0A%0A if (!stats.hasErrors() && !stats.hasWarnings()) %7B%0A const time = stats.endTime - stats.startTime;%0A console.log(%60Compiled in $%7Btime%7Dms%60);%0A return;%0A %7D%0A %0A if (stats.hasWarnings()) %7B%0A console.log('Compiled with warnings');%0A return;%0A %7D%0A%0A if (stats.hasErrors()) %7B%0A console.log('Failed to compile');%0A return;%0A %7D%0A%7D%0A%0A /**%0A * Packa @@ -1226,35 +1226,28 @@ */%0A -class Server %7B%0A constructo +function createServe r(co @@ -1252,22 +1252,25 @@ compiler +: any ) %7B%0A - const @@ -1399,16 +1399,47 @@ : true,%0A + reporter: buildReporter,%0A wa @@ -1519,29 +1519,30 @@ %7D);%0A%0A -this. +const httpServer = @@ -1626,21 +1626,16 @@ (%0A -this. httpServ @@ -1863,85 +1863,10 @@ ;%0A -%7D%0A%0A /**%0A * Starts listening to incoming requests%0A */%0A listen(...args) %7B + %0A @@ -1877,13 +1877,8 @@ urn -this. http @@ -1887,29 +1887,9 @@ rver -.listen(...args);%0A %7D +; %0A%7D%0A%0A @@ -1905,16 +1905,22 @@ ports = +create Server;%0A
b1895a87993725b2e0bf8ea7a0858719eddfe89c
Remove comments
lib/activities/Activity.js
lib/activities/Activity.js
'use strict'; const debug = require('debug'); const EventEmitter = require('events').EventEmitter; const internals = {}; module.exports = internals.Activity = function(activity, parentContext) { this.parentContext = parentContext; this.id = activity.id; this.type = activity.$type; this.name = activity.name; this._debug = debug(`bpmn-engine:${this.type.toLowerCase()}`); this.activity = activity; this.inbound = parentContext.getInboundSequenceFlows(activity.id); this.outbound = parentContext.getOutboundSequenceFlows(activity.id); this.io = parentContext.getActivityIO(activity.id); this.multipleInbound = this.inbound.length > 1; this.isStart = this.inbound.length === 0; this.isEnd = this.outbound.length === 0; this.entered = false; this._debug(`<${this.id}>`, 'init'); }; internals.Activity.prototype = Object.create(EventEmitter.prototype); internals.Activity.prototype.activate = function() { this.setupInboundListeners(); }; internals.Activity.prototype.deactivate = function() { this.teardownInboundListeners(); }; internals.Activity.prototype.run = function() { this.canceled = false; this.enter(); }; internals.Activity.prototype.resume = function(state) { if (!state.entered) return; this._debug(`<${this.id}>`, 'resume'); this.run(); }; internals.Activity.prototype.signal = function() { }; internals.Activity.prototype.enter = function(flow) { this._debug(`<${this.id}>`, 'enter'); if (this.entered) { throw new Error(`Already entered <${this.id}>`); } this.entered = true; this.emit('enter', this, flow); }; internals.Activity.prototype.leave = function() { this._debug(`<${this.id}>`, 'leave'); if (!this.entered) { throw new Error(`Already left <${this.id}>`); } this.pendingDiscard = false; this.entered = false; // this.emit('leave', this); setImmediate(() => { this.emit('leave', this); }); }; internals.Activity.prototype.cancel = function() { this.canceled = true; this._debug(`<${this.id}>`, 'cancel'); this.emit('cancel', this); this.takeAllOutbound(); }; internals.Activity.prototype.onInbound = function(flow) { if (flow.discarded) { return discardedInbound.apply(this, arguments); } const message = this.getInput(); return this.run(message); }; internals.Activity.prototype.onLoopedInbound = function() { if (this.entered) this.leave(); }; internals.Activity.prototype.discard = function(flow, rootFlow) { if (!this.entered) this.enter(flow); return this.discardAllOutbound(rootFlow); }; function discardedInbound(flow, rootFlow) { if (!this.multipleInbound) { return this.discard(flow, rootFlow); } if (!this.pendingDiscard) { this._debug(`<${this.id}>`, `pending inbound from discarded <${flow.id}>`); this.pendingDiscard = true; // Remove one since one inbound flow must have been taken this.pendingLength = this.inbound.length - 1; // Emit leave because we are not waiting for discarded flow this.emit('leave', this); return; } this.pendingLength--; this._debug(`<${this.id}>`, `inbound from discarded <${flow.id}> - pending ${this.pendingLength}`); if (this.pendingLength === 0) { this.discard(flow, rootFlow); } } internals.Activity.prototype.takeAllOutbound = function(message) { if (!this.isEnd) { this._debug(`<${this.id}>`, `take all outbound (${this.outbound.length})`); this.outbound.forEach((flow) => flow.take(message)); } this.leave(); }; internals.Activity.prototype.discardAllOutbound = function(rootFlow) { if (!this.isEnd) { this._debug(`<${this.id}>`, `discard all outbound (${this.outbound.length})`); this.outbound.forEach((flow) => { flow.discard(rootFlow); }); } this.leave(rootFlow); }; internals.Activity.prototype.setupInboundListeners = function() { if (!this.inbound.length) return; if (this._onInbound) return; this._onInbound = this.onInbound.bind(this); this._onLoopedInbound = this.onLoopedInbound.bind(this); this.inbound.forEach((flow) => { flow.on('taken', this._onInbound); flow.on('discarded', this._onInbound); flow.on('looped', this._onLoopedInbound); }); }; internals.Activity.prototype.teardownInboundListeners = function() { if (!this._onInbound) return; this.inbound.forEach((flow) => { flow.removeListener('taken', this._onInbound); flow.removeListener('discarded', this._onInbound); flow.removeListener('looped', this._onLoopedInbound); }); delete this._onInbound; }; internals.Activity.prototype.getOutput = function(message) { if (!this.io) return message; return this.io.getOutput(message); }; internals.Activity.prototype.getInput = function(message) { if (!this.io) return message; return this.io.getInput(message); }; internals.Activity.prototype.getState = function() { return { id: this.id, type: this.type, entered: this.entered }; };
JavaScript
0
@@ -1815,39 +1815,8 @@ se;%0A - // this.emit('leave', this);%0A se
91018f94b1885f75020ca3bccc145af58d4c7950
Make find blueprint use JsonApiService
lib/api/blueprints/find.js
lib/api/blueprints/find.js
/** * Module dependencies */ var util = require( 'util' ), actionUtil = require( './_util/actionUtil' ), pluralize = require('pluralize'); /** * Find Records * * get /:modelIdentity * * An API call to find and return model instances from the data adapter * using the specified criteria. * */ module.exports = function findRecords(req, res) { // Look up the model var Model = actionUtil.parseModel(req); // Lookup for records that match the specified criteria var query = Model.find(); query.exec((err, matchingRecords) => { if (err) return res.serverError(err); var data = { data: [] }; matchingRecords.forEach((record) => { var id = record.id; delete record.id data.data.push({ id: id.toString(), type: pluralize(req.options.model || req.options.controller), attributes: record }); }) return res.ok(data); }); };
JavaScript
0.000001
@@ -641,159 +641,18 @@ -matchingRecords.forEach((record) =%3E %7B%0A var id = record.id;%0A delete record.id%0A%0A data.data.push(%7B%0A id: id.toString(),%0A +var type -: + = plu @@ -706,77 +706,76 @@ ler) -,%0A attributes: record%0A %7D);%0A %7D)%0A%0A return res.ok(data +;%0A%0A return res.ok(JsonApiService.serialize(type, matchingRecords) );%0A
5ac6e72f6957ea82279f0e786f6ce890aa637d40
fix some errors on Windows
lib/atom-markdown-katex.js
lib/atom-markdown-katex.js
'use strict' /** * atom-markdown-katex plugin for atom editor * By Yiyi Wang (shd101wyy) * */ let startMDPreview = require('./md-preview.js').startMDPreview, MarkdownPreviewEditor = require('./md-preview-editor') // open new window to show rendered markdown html function beginMarkdownKatexPreview() { // get current selected active editor let activeEditor = atom.workspace.getActiveTextEditor() startMDPreview(activeEditor) } // customize markdown preview css function customizeCSS() { atom.workspace .open("atom://.atom/stylesheet") .then(function(editor) { let customCssTemplate = `\n /* * atom-markdown-katex custom style */ .markdown-katex-preview-custom { // please write your custom style here // eg: // color: blue; // change font color // font-size: 14px; // change font size // // custom pdf output style @media print { } } // please don't modify the .markdown-katex-preview section below .markdown-katex-preview { .markdown-katex-preview-custom() !important; } ` let text = editor.getText() if (text.indexOf('.markdown-katex-preview-custom {') < 0 || text.indexOf('.markdown-katex-preview {') < 0) { editor.setText(text + customCssTemplate) } }) } function createTOC() { let editor = atom.workspace.getActiveTextEditor() if (editor && startMDPreview(editor)) { editor.insertText(`\n<!-- toc -->\n`) } } function toggleScrollSync() { let flag = atom.config.get('atom-markdown-katex.scrollSync') atom.config.set('atom-markdown-katex.scrollSync', !flag) if (!flag) { atom.notifications.addInfo('Scroll Sync enabled') } else { atom.notifications.addInfo('Scroll Sync disabled') } } function activateFn(state) { atom.commands.add('atom-workspace', 'markdown-katex-preview:customize-css', customizeCSS) atom.commands.add('atom-workspace', 'markdown-katex-preview:toc-create', createTOC) atom.commands.add('atom-workspace', 'markdown-katex-preview:toggle', beginMarkdownKatexPreview) atom.commands.add('atom-workspace', 'markdown-katex-preview:toggle-scroll-sync', toggleScrollSync) // close all atom-markdown-katex: uri pane let paneItems = atom.workspace.getPaneItems() for (let i = 0; i < paneItems.length; i++) { let uri = paneItems[i].getURI() paneItems[i].destroy() } } // set opener atom.workspace.addOpener((uri)=> { if (uri.startsWith('atom-markdown-katex://') && uri.endsWith(' preview')) { return new MarkdownPreviewEditor(uri) } }) atom.workspace.onDidOpen(function(event) { if (atom.config.get('atom-markdown-katex.openPreviewPaneAutomatically')) { if (event.uri && event.item && (event.uri.endsWith('.md') || event.uri.endsWith('.markdown'))) { let editor = event.item let previewUrl = 'atom-markdown-katex://' + editor.getPath() + ' preview' let previewPane = atom.workspace.paneForURI(previewUrl) if (!previewPane) { startMDPreview(editor) } } } }) } module.exports = { activate: activateFn }
JavaScript
0.000038
@@ -2333,16 +2333,102 @@ etURI()%0A + if (uri && uri.startsWith('atom-markdown-katex:/') && uri.endsWith(' preview')) %7B%0A pa
ab1ce92b2ccdd20e767ad6c210066b3a5db18db0
Fix getter method references
lib/_relation/getter.js
lib/_relation/getter.js
'use strict'; var arrRemove = require('es5-ext/lib/Array/prototype/remove') , d = require('es5-ext/lib/Object/descriptor') , relation = require('./') , defineProperty = Object.defineProperty , activateTriggers, deactivateTriggers; activateTriggers = function (baseRel) { var ontriggeradd, ontriggerdelete, onadd, onremove, onnsadd, onnsremove , add, remove, name, obj, objects, subGetter; obj = baseRel.obj; name = '_' + baseRel.name; onadd = function (event) { add(event.obj); }; onremove = function (nu, old) { remove((nu || old).obj); }; onnsadd = function (event) { add(event.obj.prototype); }; onnsremove = function (nu, old) { remove((nu || old).obj.prototype); }; add = function (obj) { var rel; rel = obj[name]; if (rel.hasOwnProperty('_value')) return; defineProperty(rel, '_getter_', d(subGetter)); objects.push(obj); obj.on('add', onadd); obj.on('remove', onremove); if (obj._type_ === 'prototype') { obj.ns.on('add', onnsadd); obj.ns.on('remove', onnsremove); } baseRel.triggers.forEach(function (triggerName) { obj.get(triggerName).on('change', rel._update_); }); rel._update_(); if (obj.hasOwnProperty('_children_')) obj._children_.forEach(onadd); }; remove = function (obj) { var rel; rel = obj[name]; if (!rel.hasOwnProperty('_getter_')) return; delete rel._getter_; arrRemove.call(objects, obj); obj.off('add', onadd); obj.off('remove', onremove); if (obj._type_ === 'prototype') { obj.ns.off('add', onnsadd); obj.ns.off('remove', onnsremove); } baseRel.triggers.forEach(function (triggerName) { obj['_' + triggerName].off('change', rel._update_); }); if (obj.hasOwnProperty('_children_')) obj._children_.forEach(onremove); }; // Whenever new trigger is added, set it up and refresh values baseRel.triggers.on('add', ontriggeradd = function (triggerName) { objects.forEach(function self(obj) { var rel = obj[name]; obj.get(triggerName).on('change', rel._update_); rel._update_(); }); }); // Whenever trigger is removed, deactivate it baseRel.triggers.on('delete', ontriggerdelete = function (triggerName) { triggerName = '_' + triggerName; objects.forEach(function self(obj) { obj[triggerName].off('change', obj[name]._update_); }); }); objects = [obj]; // Main relation getter configuaration defineProperty(baseRel, '_getter_', d({ ontriggeradd: ontriggeradd, ontriggerdelete: ontriggerdelete, add: add, remove: remove, objects: objects })); obj.on('add', onadd); obj.on('remove', onremove); if (obj._type_ === 'prototype') { obj.ns.on('add', onnsadd); obj.ns.on('remove', onnsremove); } // Extended relations getter configuration subGetter = { add: add, remove: remove }; baseRel.triggers.forEach(function (triggerName) { // Make sure property is globally defined obj.get(triggerName).on('change', baseRel._update_); }); baseRel._update_(); // Activate triggers for relation extensions if (obj.hasOwnProperty('_children_')) obj._children_.forEach(onadd); }; deactivateTriggers = function (rel) { var getter = rel._getter_, obj = rel.obj; if (getter.once) { rel.triggers.off('add', getter.once); delete rel._getter_; return; } if (getter.ontriggeradd) rel.triggers.off('add', getter.ontriggeradd); if (getter.ontriggerdelete) { rel.triggers.off('delete', getter.ontriggerdelete); } getter.remove(obj); }; Object.defineProperties(relation, { _setGetter_: d(function () { var name, getter; if (this.hasOwnProperty('_value')) { if (this.hasOwnProperty('_getter_')) { // Some getter is already setup if (this._getter_.objects) { // Function has changed, refresh values name = '_' + this.name; this._getter_.objects.forEach(function (child) { child[name]._update_(); }); return; } else if (this._getter_.once) { this._update_(); return; } // Upper relation getter // Deactivate it deactivateTriggers(this); } if (this.triggers.count) { // Setup getter activateTriggers(this); } else { // No triggers, do not setup getter // but we wait until first trigger is added defineProperty(this, '_getter_', d(getter = {})); this.triggers.once('add', getter.once = function () { delete this._getter_; activateTriggers(this); }.bind(this)); this._update_(); } } else { if (this.hasOwnProperty('_getter_')) { // Deactivate old base getter deactivateTriggers(this); } if (this._getter_.add) { this._getter_.add(this.obj); } else { this._update_(); } } }), _deleteGetter_: d(function () { if (this.hasOwnProperty('_getter_')) deactivateTriggers(this); }) });
JavaScript
0.000001
@@ -1210,26 +1210,24 @@ en_.forEach( -on add);%0A%09%7D;%0A%09r @@ -1723,18 +1723,16 @@ forEach( -on remove); @@ -3020,18 +3020,16 @@ forEach( -on add);%0A%7D;
9e1ccc41097b2215a02375c2dc7325d08ee0a9e0
read wifiName property from config object
lib/accessories/wifi.js
lib/accessories/wifi.js
/** * FritzWifiAccessory * * @url https://github.com/andig/homebridge-fritz * @author Andreas Götz <[email protected]> * @license MIT */ /* jslint node: true, laxcomma: true, esversion: 6 */ "use strict"; var Service, Characteristic, FritzPlatform; module.exports = function(homebridge) { Service = homebridge.hap.Service; Characteristic = homebridge.hap.Characteristic; FritzPlatform = require('../platform')(homebridge); return FritzWifiAccessory; }; function FritzWifiAccessory(platform) { this.platform = platform; this.name = this.platform.options.wifiName || "Guest WLAN"; this.services = { AccessoryInformation: new Service.AccessoryInformation(), Switch: new Service.Switch(this.name) }; this.services.AccessoryInformation .setCharacteristic(Characteristic.Manufacturer, "AVM"); this.services.AccessoryInformation .setCharacteristic(Characteristic.Model, "Fritz!Box"); this.platform.fritz('getOSVersion').then(function(version) { this.services.AccessoryInformation .setCharacteristic(Characteristic.FirmwareRevision, version); }.bind(this)); this.services.Switch.getCharacteristic(Characteristic.On) .on('get', this.getOn.bind(this)) .on('set', this.setOn.bind(this)) ; setInterval(this.update.bind(this), this.platform.interval); } FritzWifiAccessory.prototype.getServices = function() { return [this.services.AccessoryInformation, this.services.Switch]; }; FritzWifiAccessory.prototype.getOn = function(callback) { this.platform.log("Getting guest WLAN state"); var service = this.services.Switch; callback(null, service.fritzState); this.platform.fritz('getGuestWlan').then(function(res) { service.fritzState = res.activate_guest_access; service.getCharacteristic(Characteristic.On).setValue(res.activate_guest_access, undefined, FritzPlatform.Context); }); }; FritzWifiAccessory.prototype.setOn = function(on, callback, context) { if (context == FritzPlatform.Context) { callback(null, on); return; } this.platform.log("Switching guest WLAN to " + on); this.platform.fritz('setGuestWlan', on ? true : false).then(function(res) { callback(null, res.activate_guest_access); }); }; FritzWifiAccessory.prototype.update = function() { this.platform.log("Updating guest WLAN"); var self = this; this.getOn(function(foo, state) { self.services.Switch.getCharacteristic(Characteristic.On).setValue(state, undefined, FritzPlatform.Context); }); };
JavaScript
0.000001
@@ -575,15 +575,14 @@ orm. -options +config .wif
122c290b6313cad385ad0b961585e7620b54f558
Fix mode list.
lib/ace/ext/modelist.js
lib/ace/ext/modelist.js
define(function(require, exports, module) { "use strict"; var modes = []; /** * Suggests a mode based on the file extension present in the given path * @param {string} path The path to the file * @returns {object} Returns an object containing information about the * suggested mode. */ function getModeForPath(path) { var mode = modesByName.text; var fileName = path.split(/[\/\\]/).pop(); for (var i = 0; i < modes.length; i++) { if (modes[i].supportsFile(fileName)) { mode = modes[i]; break; } } return mode; } var Mode = function(name, caption, extensions) { this.name = name; this.caption = caption; this.mode = "ace/mode/" + name; this.extensions = extensions; if (/\^/.test(extensions)) { var re = extensions.replace(/\|(\^)?/g, function(a, b){ return "$|" + (b ? "^" : "^.*\\."); }) + "$"; } else { var re = "^.*\\.(" + extensions + ")$"; } this.extRe = new RegExp(re, "gi"); }; Mode.prototype.supportsFile = function(filename) { return filename.match(this.extRe); }; // todo firstlinematch var supportedModes = { ABAP: ["abap"], ABC: ["abc"], ActionScript:["as"], ADA: ["ada|adb"], Apache_Conf: ["^htaccess|^htgroups|^htpasswd|^conf|htaccess|htgroups|htpasswd"], AsciiDoc: ["asciidoc|adoc"], Assembly_x86:["asm"], AutoHotKey: ["ahk"], BatchFile: ["bat|cmd"], <<<<<<< HEAD BXL ["bxl"], C9Search: ["c9search_results"], ======= >>>>>>> upstream/master C_Cpp: ["cpp|c|cc|cxx|h|hh|hpp"], C9Search: ["c9search_results"], Cirru: ["cirru|cr"], Clojure: ["clj|cljs"], Cobol: ["CBL|COB"], coffee: ["coffee|cf|cson|^Cakefile"], ColdFusion: ["cfm"], CSharp: ["cs"], CSS: ["css"], Curly: ["curly"], D: ["d|di"], Dart: ["dart"], Diff: ["diff|patch"], Dockerfile: ["^Dockerfile"], Dot: ["dot"], Dummy: ["dummy"], DummySyntax: ["dummy"], Eiffel: ["e"], EJS: ["ejs"], Elixir: ["ex|exs"], Elm: ["elm"], Erlang: ["erl|hrl"], Forth: ["frt|fs|ldr"], FTL: ["ftl"], Gcode: ["gcode"], Gherkin: ["feature"], Gitignore: ["^.gitignore"], Glsl: ["glsl|frag|vert"], golang: ["go"], Groovy: ["groovy"], HAML: ["haml"], Handlebars: ["hbs|handlebars|tpl|mustache"], Haskell: ["hs"], haXe: ["hx"], HTML: ["html|htm|xhtml"], HTML_Ruby: ["erb|rhtml|html.erb"], INI: ["ini|conf|cfg|prefs"], Io: ["io"], Jack: ["jack"], Jade: ["jade"], Java: ["java"], JavaScript: ["js|jsm"], JSON: ["json"], JSONiq: ["jq"], JSP: ["jsp"], JSX: ["jsx"], Julia: ["jl"], LaTeX: ["tex|latex|ltx|bib"], Lean: ["lean|hlean"], LESS: ["less"], Liquid: ["liquid"], Lisp: ["lisp"], LiveScript: ["ls"], LogiQL: ["logic|lql"], LSL: ["lsl"], Lua: ["lua"], LuaPage: ["lp"], Lucene: ["lucene"], Makefile: ["^Makefile|^GNUmakefile|^makefile|^OCamlMakefile|make"], Markdown: ["md|markdown"], Mask: ["mask"], MATLAB: ["matlab"], Maze: ["mz"], MEL: ["mel"], MUSHCode: ["mc|mush"], MySQL: ["mysql"], Nix: ["nix"], ObjectiveC: ["m|mm"], OCaml: ["ml|mli"], Pascal: ["pas|p"], Perl: ["pl|pm"], pgSQL: ["pgsql"], PHP: ["php|phtml|shtml|php3|php4|php5|phps|phpt|aw|ctp"], Powershell: ["ps1"], Praat: ["praat|praatscript|psc|proc"], Prolog: ["plg|prolog"], Properties: ["properties"], Protobuf: ["proto"], Python: ["py"], R: ["r"], RDoc: ["Rd"], RHTML: ["Rhtml"], Ruby: ["rb|ru|gemspec|rake|^Guardfile|^Rakefile|^Gemfile"], Rust: ["rs"], SASS: ["sass"], SCAD: ["scad"], Scala: ["scala"], Scheme: ["scm|rkt"], SCSS: ["scss"], SH: ["sh|bash|^.bashrc"], SJS: ["sjs"], Smarty: ["smarty|tpl"], snippets: ["snippets"], Soy_Template:["soy"], Space: ["space"], SQL: ["sql"], SQLServer: ["sqlserver"], Stylus: ["styl|stylus"], SVG: ["svg"], Tcl: ["tcl"], Tex: ["tex"], Text: ["txt"], Textile: ["textile"], Toml: ["toml"], Twig: ["twig"], Typescript: ["ts|typescript|str"], Vala: ["vala"], VBScript: ["vbs|vb"], Velocity: ["vm"], Verilog: ["v|vh|sv|svh"], VHDL: ["vhd|vhdl"], XML: ["xml|rdf|rss|wsdl|xslt|atom|mathml|mml|xul|xbl|xaml"], XQuery: ["xq"], YAML: ["yaml|yml"], // Add the missing mode "Django" to ext-modelist Django: ["html"] }; var nameOverrides = { ObjectiveC: "Objective-C", CSharp: "C#", golang: "Go", C_Cpp: "C and C++", coffee: "CoffeeScript", HTML_Ruby: "HTML (Ruby)", FTL: "FreeMarker" }; var modesByName = {}; for (var name in supportedModes) { var data = supportedModes[name]; var displayName = (nameOverrides[name] || name).replace(/_/g, " "); var filename = name.toLowerCase(); var mode = new Mode(filename, displayName, data[0]); modesByName[filename] = mode; modes.push(mode); } module.exports = { getModeForPath: getModeForPath, modes: modes, modesByName: modesByName }; });
JavaScript
0
@@ -1472,21 +1472,8 @@ %22%5D,%0A -%3C%3C%3C%3C%3C%3C%3C HEAD%0A @@ -1537,40 +1537,8 @@ %22%5D,%0A -=======%0A%3E%3E%3E%3E%3E%3E%3E upstream/master%0A
bc843c8d76c3b00c297dd83fc4d1ff3d63c9a5aa
add done callback function to be used for tests
lib/actions/generate.js
lib/actions/generate.js
'use strict'; const createPipeline = require('./../pipeline'); const initPipelineFns = require('./../pipeline_fns'); const initProcessorRegister = require('../register_functions/content_asset_decorator_processor'); const initFileProcessorRegister = require('../register_functions/file_processor'); const initTemplateProcessorRegister = require('../register_functions/template_processor'); const initHelperRegister = require('../register_functions/helper'); const genericFileProcessor = require('../generic_processors/file_processor'); const genericTemplateProcessor = require('../generic_processors/template_processor'); const genericContentProcessor = require('../generic_processors/content_processor'); const loadTemplates = require('../load_templates'); const DB = require('../db'); const loadConfigs = require('../load_configs'); const loadPlugins = require('../load_plugins'); const internalPluginPaths = require('../internal_plugins'); function generate(basePath, isProd) { const db = new DB(); const { generatorConfig, globalConfig, externalPluginPaths } = loadConfigs(basePath, isProd); const templatesPath = `${basePath}/${generatorConfig.template.path}`; // Initialize processors const fileProcessors = new Map(); const registerFileProcessor = initFileProcessorRegister({ fileProcessors }); const helpers = {}; const registerHelper = initHelperRegister({ helpers }); const templateProcessors = new Map(); const registerTemplateProcessor = initTemplateProcessorRegister({ templateProcessors }); const processors = new Map(); const initialPipelineData = {}; const callOrder = []; const registerProcessor = initProcessorRegister({ generatorConfig, globalConfig, initialPipelineData, processors, callOrder, basePath, }); function registerPlugin(type, ...args) { if (type === 'file') { registerFileProcessor(...args); } else if (type === 'helper') { registerHelper(...args); } else if (type === 'template') { registerTemplateProcessor(...args); } else { registerProcessor(type, ...args); } } loadPlugins(basePath, internalPluginPaths, externalPluginPaths).forEach((plugin) => { plugin(registerPlugin); }); const templates = new Map(); loadTemplates(templatesPath, templates, helpers.readers); const processFile = genericFileProcessor(fileProcessors, generatorConfig.file, helpers); const processTemplate = genericTemplateProcessor( templateProcessors, templates, generatorConfig.template, helpers ); const helperFunctions = Object.assign({}, { processFile, renderTemplate: processTemplate, processContent: genericContentProcessor, }, helpers); const pipeline = createPipeline(); const pipelineFns = initPipelineFns(processors, callOrder, db, helperFunctions); pipeline.use(pipelineFns.processReaders); pipeline.use(pipelineFns.processPreprocessors); pipeline.use(pipelineFns.processTemplateVariables); pipeline.use(pipelineFns.processProcessors); pipeline.use(pipelineFns.processPostprocessors); pipeline.use(pipelineFns.processWriters); pipeline.execute(initialPipelineData); } module.exports = generate;
JavaScript
0
@@ -947,42 +947,142 @@ );%0A%0A -function generate(basePath, isProd +// doneFn is the last pipeline function. It's used for E2E tests%0Afunction generate(basePath, isProd = false, doneFn = (_, n) =%3E %7Bn();%7D ) %7B%0A @@ -3222,24 +3222,48 @@ essWriters); +%0A pipeline.use(doneFn); %0A%0A pipeline
c402470d6d5ed30f3c92f58894001c56ab1d5d70
Add comments
src/string-class.js
src/string-class.js
// Disable eslint do not modify native methods /* eslint-disable no-extend-native */ String.prototype.hasVowels = function hasVowels() { // Is there any vowel in the input string? const vowels = new RegExp('[aeiou]', 'i'); return vowels.test(this); }; String.prototype.toUpper = function toUpper() { /* Replace all lowercase letters in the input string with their uppercase * analogs by converting each letter's ASCII value to decimal then back to * ASCII */ const upper = new RegExp('[a-z]', 'g'); return this.replace(upper, function transform(letter) { return String.fromCharCode(letter.charCodeAt(0) - 32); }); }; String.prototype.toLower = function toLower() { const lower = new RegExp('[A-Z]', 'g'); return this.replace(lower, function transform(letter) { return String.fromCharCode(letter.charCodeAt(0) + 32); }); }; String.prototype.ucFirst = function ucFirst() { /* Convert the fist character of the input string to uppercase then concatenate * the rest of the string with the uppercase character */ return this[0].toUpper() + this.slice(1); }; String.prototype.isQuestion = function isQuestion() { // Is the last letter of the input string a question mark? const quest = new RegExp(/\?$/); return quest.test(this); }; String.prototype.words = function words() { /* Split the input string at any of the provided special characters * and return an array of words */ const splitter = new RegExp('[:," ";|?!().]'); return this.split(splitter); }; String.prototype.wordCount = function wordCount() { return this.words().length; }; String.prototype.toCurrency = function toCurrency() { /* (/d) -> Maches digits from 0-9 and remembers the particular digit match * (/d)(?=(\d{3})+\.) -> Only matches a digit if it is followed by * three other digits and if the entire string is a float */ const curr = new RegExp(/(\d)(?=(\d{3})+\.)/g); return (parseFloat(this).toFixed(2).replace(curr, '$1,')) .toString(); }; String.prototype.fromCurrency = function fromCurrency() { return Number(this.replace(/,/, '')); };
JavaScript
0
@@ -1665,16 +1665,17 @@ d) -%3E Ma +t ches dig
52be08b80141ad46a56ab8cdb76f93971762b99b
Fix for potentially misleading logging
lib/cli/commands/deploy.js
lib/cli/commands/deploy.js
// > The deploy command tars up a directory and streams it to the server // // > Copyright © 2013 Matt Styles // > Licensed under the MIT license 'use strict'; // Includes. var icarus = require( './../../icarus' ), fs = require( 'fs' ), path = require( 'path' ), util = require( 'util' ), exec = require( 'child_process').exec, request = require( 'superagent' ), Progress = require( 'progress' ), tar = require( 'tar' ), fstream = require( 'fstream' ), zlib = require( 'zlib' ); // Expose the deployment route. module.exports = (function() { // // Members // ------- // Set the path data -- hardcode for now.<br> // @todo grab this from the config. var route = { host: 'http://localhost', port: '8080', path: 'deploy' } // Store this here for now.<br> // @todo sort out encapsulation properly. var dirSize = 0; var progressBar = null; // Store the local tmp folder.<br> // @todo should be in the config. var tmpFolder = '.icarus/tmp/'; // // Methods // ------- // Handle returning an invalid folder. // An invalid folder is one that does not contain a `package.json`. var onInvalidFolder = function( dir ) { icarus.log.info( 'An error occurred finding the project root' ); icarus.log.error( process.cwd() + ' is not a valid folder' ); }; // Handle finding a valid project folder. var onProjectFolder = function( dir ) { // Read the package and pass to the main create tar function fs.readFile( path.join( dir, 'package.json' ), function( err, res ) { if ( err ) { // Handle this error. // For now just log an error but we should probably exit. icarus.log.warn( 'No package.json found at root -- using default log file' ); process.exit(); } icarus.log.debug( 'Found package.json for the project'.info ); icarus.out( 'Valid project directory - '.info + 'package.json '.em + 'found'.info ); // Parse the package, we'll need stuff from it var pkg = JSON.parse( res ); // Create the tarball and send it to the server createTar( dir, pkg, sendToRemote ); }); }; // This function serves two purposes - // it reads the directory and stores its size and, // it creates an archive of the directory. var createTar = function( dir, pkg, cb ) { var timestamp = new Date(); // Create archive name var archiveName = pkg.name + '-v' + pkg.version + '-' + timestamp.toJSON() + '.tar.gz'; icarus.out( 'Creating tarball'.verbose, 'deploying' ); // Reads the directory and stores the number of files. // Gzip the archive. // The number of files are used as a reference to to measure the progress of the deployment. var fileReader = fstream.Reader( { path: dir, type: 'Directory' } ) .on( 'error', function( err ) { icarus.log.error( 'Error reading directory : ' + err ); }) .pipe( tar.Pack() ) .on( 'error', function( err ) { icarus.log.error( 'Error packing the directory into the archive tarball : ' + err ); }) .pipe( zlib.createGzip() ) .on( 'error', function() { icarus.log.error( 'Error gzipping the directory : ' + err ); }) .pipe( fstream.Writer( path.join( icarus.utils.getHome(), tmpFolder, archiveName ) ) ) .on ('error', function( err ) { icarus.log.error( 'Error storing tmp tar : ' + err ); }) .on( 'close', function() { icarus.out( 'Finished packing tarball'.verbose, 'deploying' ); // Finished reading the directory so hit the callback. cb( path.join( icarus.utils.getHome(), tmpFolder, archiveName ), pkg ); }); }; // Tar up the folder var sendToRemote = function( tmpPath, pkg ) { var bar = null, size = 0; // Create request object var req = request .post( route.host + ':' + route.port + '/' + route.path ) .type("binary") .query( { pkgName: icarus.utils.parsePkgName( pkg.name ) || 'not specified', tmpName: tmpPath || 'not specified' } ) .on( 'error', function( err ) { icarus.log.error( 'There was an error streaming the deploy : ' + err ); }) .on( 'response', function( res ) { icarus.out( res.body.status.em, 'deploy status' ); }); // Output starting deploy icarus.out( 'Starting deployment of tarball'.verbose, 'deploying' ); // Read the directory, tar it up and send through the request object fs.stat( tmpPath, function( err, stat ) { // Handle an error - most likely a file not found error if ( err ) { icarus.log.error( 'Error statting the temp deploy artifact : ' + err ); } fstream.Reader( { path: tmpPath, type: 'File' } ) .on( 'error', function( err ) { icarus.log.error( 'Error reading tmp file' ); }) .on( 'open', function() { // Create the progress bar size = stat.size; bar = new Progress( 'uploading [:bar] :percent', { complete : '=', incomplete : '-', width : 30, total : stat.size }); }) .on( 'data', function( chunk ) { // Update the progress bar if ( bar ) { bar.tick( chunk.length > size ? size : chunk.length ); } }) .on( 'end', function() { icarus.out( 'Finished sending tarball'.verbose, 'deploying' ); }) // Should this be piped into a stream to convert to base64? .pipe( req ) .on( 'error', function( err ) { icarus.log.error( 'Error piping to the request' ); }); }); }; // Return the route function return function( opts ) { // Find the project root and deploy that folder icarus.out( 'Attempting to deploy from '.info + process.cwd().em ); icarus.utils.findProjectRoot( onInvalidFolder, onProjectFolder ); }; })();
JavaScript
0.000001
@@ -1710,82 +1710,8 @@ or.%0A - // For now just log an error but we should probably exit.%0A @@ -1773,34 +1773,8 @@ root - -- using default log file ' );
aad0a00384f118bbd4e4a614eeeafd12d01c67ed
remove comments
lib/commands/attachment.js
lib/commands/attachment.js
'use strict'; // var doc = savedDoc // <some saved couchdb document which has an attachment> // var id = doc._id // var rev = doc._rev // var idAndRevData = { // id: id, // rev: rev // } // var attachmentData = { // name: attachmentName // something like 'foo.txt' // 'Content-Type': attachmentMimeType // something like 'text/plain', 'application/pdf', etc. // body: rawAttachmentBody // something like 'foo document body text' // } // var readStream = fs.createReadStream('/path/to/file/') // var writeStream = db.saveAttachment(idData, attachmentData, callbackFunction) // readStream.pipe(writeStream) module.exports = attachment; var node_fs = require('fs'); // @param {Object} options // - tar: {string} absolute path of tarball file // - pkg: {string} package name // - rev: {string} couchdb rev of the pkg document // - name: {string} file name of couchdb attachment // { // pkg: 'neuronjs', // name: 'neuronjs-2.0.1.tgz', // rev: '10-xxxxxxxxxxxxxxxx', // tar: '/blah' // } function attachment(options, callback, logger, db) { var path = '/' + options.pkg + '/-/' + db.escape(options.name) + '/-rev/' + options.rev; var db_stream = db.put(path, callback); var file_stream = node_fs.createReadStream(options.tar); db_stream.on('error', callback); logger.debug('upload', options.tar, path); file_stream.pipe(db_stream); }
JavaScript
0
@@ -12,636 +12,8 @@ ';%0A%0A -// var doc = savedDoc // %3Csome saved couchdb document which has an attachment%3E%0A// var id = doc._id%0A// var rev = doc._rev%0A// var idAndRevData = %7B%0A// id: id,%0A// rev: rev%0A// %7D%0A// var attachmentData = %7B%0A// name: attachmentName // something like 'foo.txt'%0A// 'Content-Type': attachmentMimeType // something like 'text/plain', 'application/pdf', etc.%0A// body: rawAttachmentBody // something like 'foo document body text'%0A// %7D%0A// var readStream = fs.createReadStream('/path/to/file/')%0A// var writeStream = db.saveAttachment(idData, attachmentData, callbackFunction)%0A// readStream.pipe(writeStream)%0A%0A modu
ebaec176a77d047bd8583fa0501d70b3a485cffe
check if the passed reference is a DaoFactory
lib/dao-factory-manager.js
lib/dao-factory-manager.js
var Toposort = require('toposort-class') module.exports = (function() { var DAOFactoryManager = function(sequelize) { this.daos = [] this.sequelize = sequelize } DAOFactoryManager.prototype.addDAO = function(dao) { this.daos.push(dao) return dao } DAOFactoryManager.prototype.removeDAO = function(dao) { this.daos = this.daos.filter(function(_dao) { return _dao.name != dao.name }) } DAOFactoryManager.prototype.getDAO = function(daoName, options) { options = options || {} options.attribute = options.attribute || 'name' var dao = this.daos.filter(function(dao) { return dao[options.attribute] === daoName }) return !!dao ? dao[0] : null } DAOFactoryManager.prototype.__defineGetter__('all', function() { return this.daos }) /** * Iterate over DAOs in an order suitable for e.g. creating tables. Will * take foreign key constraints into account so that dependencies are visited * before dependents. */ DAOFactoryManager.prototype.forEachDAO = function(iterator) { var daos = {} , sorter = new Toposort() this.daos.forEach(function(dao) { daos[dao.tableName] = dao var deps = [] for(var attrName in dao.rawAttributes) { if(dao.rawAttributes.hasOwnProperty(attrName)) { if(dao.rawAttributes[attrName].references) { deps.push(dao.rawAttributes[attrName].references) } } } sorter.add(dao.tableName, deps) }) sorter.sort().reverse().forEach(function(name) { iterator(daos[name]) }) } return DAOFactoryManager })()
JavaScript
0.000001
@@ -6,16 +6,18 @@ oposort + = requir @@ -35,16 +35,58 @@ -class') +%0A , DaoFactory = require('./dao-factory') %0A%0Amodule @@ -1120,16 +1120,18 @@ ar daos + = %7B%7D%0A @@ -1194,24 +1194,45 @@ tion(dao) %7B%0A + var deps = %5B%5D%0A%0A daos%5Bd @@ -1250,36 +1250,16 @@ e%5D = dao -%0A var deps = %5B%5D %0A%0A @@ -1261,16 +1261,17 @@ for + (var att @@ -1302,32 +1302,33 @@ es) %7B%0A if + (dao.rawAttribut @@ -1372,39 +1372,144 @@ -if(dao.rawAttributes%5Battr +(function(reference) %7B%0A if (!!reference) %7B%0A deps.push((reference instanceof DaoFactory) ? reference.table Name -%5D. + : refe @@ -1513,20 +1513,17 @@ eference -s) %7B +) %0A @@ -1527,25 +1527,30 @@ -deps.push +%7D%0A %7D) (dao.raw @@ -1582,28 +1582,16 @@ rences)%0A - %7D%0A
a8e4775302b0738e40915e423d06d465403fbcd7
Add enableAndStartService utility function which enable a service, "waits" and than starts a service. Function only waits before calls start if a runit service manager is used.
lib/deployment/services.js
lib/deployment/services.js
/* * Licensed to Cloudkick, Inc ('Cloudkick') under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * Cloudkick licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var serviceManagement = require('service_management'); /** * Creates an instance of a service, building out the runit application directory. * @param {String} instanceName Name of the instance. * @param {String} instancePath The path to the version instance. * @param {Object} manifestObj The manifest object of the instance. * @param {Function} callback Callback on completion, first parameter if present is an error. */ function createService(instanceName, instancePath, manifestObj, callback) { var manager = serviceManagement.getDefaultManager().getManager(); var templateArgs = { serviceName: instanceName, instancePath: instancePath, entryFile: manifestObj['entry_file'], applicationType: manifestObj.type }; manager.getServiceTemplate(templateArgs, function(err, template) { if (err) { callback(err); return; } manager.createService(instanceName, template, function(err) { callback(err); }); }); }; exports.createService = createService;
JavaScript
0
@@ -790,16 +790,47 @@ e.%0A */%0A%0A +var async = require('async');%0A%0A var serv @@ -875,16 +875,196 @@ ement'); +%0Avar runit = require('service_management/runit');%0A%0A/**%0A * Maximum delay before runit picks up new changes (in milliseconds).%0A * @type %7BNumber%7D%0A * @const%0A */%0Avar RUNIT_DELAY = 6000; %0A%0A/**%0A * @@ -1982,41 +1982,1531 @@ );%0A%7D -;%0A%0Aexports.createService = create +%0A%0A/**%0A * A utility function which enables the service, waits RUNIT_DELAY number of%0A * milliseconds and than starts the service.%0A *%0A * Note: Function will only wait RUNIT_DELAY milliseconds before calling%0A * service.start if a runit service manager is used.%0A * In any case, callback is fired immediately after service.start has been%0A * called.%0A *%0A * @param %7BString%7D Service name.%0A * @param %7BFunction%7D callback which is fired with (err)%0A */%0Afunction enableAndStartService(serviceName, callback) %7B%0A var manager = serviceManagement.getDefaultManager().getManager();%0A var service;%0A%0A function getService(callback) %7B%0A manager.getService(serviceName, function(err, service) %7B%0A if (err) %7B%0A callback(err);%0A return;%0A %7D%0A%0A callback(null, service);%0A %7D);%0A %7D%0A%0A function enableService(service, callback) %7B%0A service.enable(function(err) %7B%0A if (err) %7B%0A callback(err);%0A return;%0A %7D%0A%0A callback(null, service);%0A %7D);%0A %7D%0A%0A function waitAndStartService(service, callback) %7B%0A // Waiting is only needed if we are using runit service manager%0A if (!manager instanceof runit.RunitServiceManager) %7B%0A service.start(callback);%0A return;%0A %7D%0A%0A callback();%0A setTimeout(function() %7B%0A service.start(function() %7B%7D);%0A %7D, RUNIT_DELAY);%0A %7D%0A%0A var ops = %5BgetService, enableService, waitAndStartService%5D;%0A%0A async.waterfall(ops, function(err) %7B%0A callback(err);%0A %7D);%0A%7D%0A%0Aexports.createService = createService;%0Aexports.enableAndStartService = enableAndStart Serv
e31ab9888d82e28c7676e5f3d4e5fb3ebb0061f7
Add documentation.
lib/exchange/redelegate.js
lib/exchange/redelegate.js
/** * Module dependencies. */ var utils = require('../utils') , TokenError = require('../errors/tokenerror'); /** * * References: * - [A Method of Bearer Token Redelegation and Chaining for OAuth 2](http://tools.ietf.org/html/draft-richer-oauth-chain-00) * - [OAuth Service Chaining](http://www.ietf.org/mail-archive/web/oauth/current/msg09859.html) * - [review: draft-richer-oauth-chain-00.txt](http://www.ietf.org/mail-archive/web/oauth/current/msg10185.html) * */ module.exports = function(options, issue) { if (typeof options == 'function') { issue = options; options = undefined; } options = options || {}; if (!issue) { throw new TypeError('oauth2orize-redelegate exchange requires an issue callback'); } var userProperty = options.userProperty || 'user'; // For maximum flexibility, multiple scope spearators can optionally be // allowed. This allows the server to accept clients that separate scope // with either space or comma (' ', ','). This violates the specification, // but achieves compatibility with existing client libraries that are already // deployed. var separators = options.scopeSeparator || ' '; if (!Array.isArray(separators)) { separators = [ separators ]; } return function redelegate(req, res, next) { if (!req.body) { return next(new Error('OAuth2orize requires body parsing. Did you forget app.use(express.bodyParser())?')); } // The 'user' property of `req` holds the authenticated user. In the case // of the token endpoint, the property will contain the OAuth 2.0 client. var client = req[userProperty] , token = req.body.token , scope = req.body.scope; if (!token) { return next(new TokenError('Missing required parameter: token', 'invalid_request')); } if (scope) { for (var i = 0, len = separators.length; i < len; i++) { var separated = scope.split(separators[i]); // only separate on the first matching separator. this allows for a sort // of separator "priority" (ie, favor spaces then fallback to commas) if (separated.length > 1) { scope = separated; break; } } if (!Array.isArray(scope)) { scope = [ scope ]; } } function issued(err, accessToken, params) { if (err) { return next(err); } if (!accessToken) { return next(new TokenError('Invalid token', 'invalid_grant')); } var tok = {}; tok.access_token = accessToken; if (params) { utils.merge(tok, params); } tok.token_type = tok.token_type || 'Bearer'; var json = JSON.stringify(tok); res.setHeader('Content-Type', 'application/json'); res.setHeader('Cache-Control', 'no-store'); res.setHeader('Pragma', 'no-cache'); res.end(json); } try { var arity = issue.length; if (arity == 4) { issue(client, token, scope, issued); } else { // arity == 3 issue(client, token, issued); } } catch (ex) { return next(ex); } }; };
JavaScript
0
@@ -113,16 +113,555 @@ ;%0A%0A%0A/**%0A + * Exchanges an access token for a derivative token.%0A *%0A * This exchange is used by a resource server to exchange an access token it has%0A * recieved from a client for a derivative token for use with another resource%0A * server. This scenario facilitiates service chaining, in which one service%0A * needs to communicate with another service in order to fulfill the original%0A * request.%0A *%0A * In order to preserve the original authorization granted, the derivitive token%0A * should be of equal or lesser scope than that of the original token.%0A *%0A * Re @@ -1011,16 +1011,107 @@ tml)%0A *%0A + * @param %7BObject%7D options%0A * @param %7BFunction%7D issue%0A * @return %7BFunction%7D%0A * @api public%0A */%0Amodu
f0ee5cc3241ecf3a0350cf56f228c9e16f26dada
update filenames with latest Android icon names
lib/favicons-middleware.js
lib/favicons-middleware.js
var fs = require('fs'); var crypto = require('crypto'); var path = require('path'); var url = require('url'); module.exports = function favicons(dir, opts) { dir = dir || process.cwd() + '/public'; opts = opts || {}; var cache = Object.create(null); var maxAge = opts.maxAge || 86400000; var filenames = [ 'favicon.ico', 'favicon.png', 'apple-touch-icon.png', 'apple-touch-icon-precomposed.png', 'apple-touch-icon-57x57.png', 'apple-touch-icon-57x57-precomposed.png', 'apple-touch-icon-72x72.png', 'apple-touch-icon-72x72-precomposed.png', 'apple-touch-icon-76x76.png', 'apple-touch-icon-76x76-precomposed.png', 'apple-touch-icon-114x114.png', 'apple-touch-icon-114x114-precomposed.png', 'apple-touch-icon-120x120.png', 'apple-touch-icon-120x120-precomposed.png', 'apple-touch-icon-144x144.png', 'apple-touch-icon-144x144-precomposed.png', 'apple-touch-icon-152x152.png', 'apple-touch-icon-152x152-precomposed.png', 'apple-touch-icon-180x180.png', 'apple-touch-icon-180x180-precomposed.png', 'touch-icon-192x192.png' ]; return function favicons(req, res, next) { var pathname = url.parse(req.url).pathname; var basename = path.basename(pathname); var index = filenames.indexOf(basename); var cached; var extname; if ( pathname.split('/').length > 2 ) { return next(); } if ( index < 0 ) { return next(); } extname = path.extname(basename); cached = cache[basename]; if (cached) { res.set(cached.headers); res.send(cached.body); return; } fs.readFile(path.join(dir, req.path), function(err, buf) { if (err) { if (err.errno && err.errno === 34) { res.statusCode = 404; } return next(err); } cached = cache[basename] = { headers: { 'Content-Type': extname === '.ico' ? 'image/x-icon' : 'image/'+extname.split('.').pop(), 'Content-Length': buf.length, 'ETag': '"' + crypto.createHash('md5').update(buf).digest("hex") + '"', 'Cache-Control': 'public, max-age=' + (maxAge / 1000) }, body: buf }; res.set(cached.headers); res.send(cached.body); }); }; };
JavaScript
0
@@ -1086,32 +1086,134 @@ -'touch-icon-192x192.png' +%22favicon-16x16.png%22,%0A %22favicon-32x32.png%22,%0A %22favicon-128x128.png%22,%0A %22mstile-150x150.png%22,%0A %22safari-pinned-tab.svg%22 %0A %5D
079691e9532c08399b50bd5c0407546543088aa4
fix body parser hanging issue
lib/helpers/body-parser.js
lib/helpers/body-parser.js
'use strict'; var qs = require('qs'); var bytes = require('bytes'); var anyBody = require('body/any'); var formBody = require('body/form'); var defaultSizeLimit = '200kb'; function queryStringParser(text, callback) { callback(null, qs.parse(text)); } function handleBodyFn(options, bodyFn) { options = options || {}; options.querystring = { parse: queryStringParser }; options.limit = bytes.parse(options.limit || defaultSizeLimit); return function (req, res, next) { bodyFn(req, res, options, function (err, parsedBody) { req.body = parsedBody || req.body || {}; next(); }); }; } module.exports = { /** * Middleware that forces a default * req.body object (null object). */ forceDefaultBody: function () { return function forceDefaultBodyMiddleware(req, res, next) { req.body = req.body || {}; next(); }; }, /** * Middleware for parsing a form (query string) * encoded request body. */ form: function formParserMiddleware(options) { return handleBodyFn(options, formBody); }, /** * Middleware for parsing either a form * (query string) or JSON encoded request body. */ formOrJson: function formOrJsonParserMiddleware(options) { return handleBodyFn(options, anyBody); } };
JavaScript
0.000001
@@ -473,24 +473,164 @@ es, next) %7B%0A + // If the body is already parsed, by e.g. body-parser, then skip parsing.%0A if (req.body !== undefined) %7B%0A return next();%0A %7D%0A%0A bodyFn(r
dd035c95d264301bc15c211db133802980b1ef3a
Remove unused
lib/bootstrapHelpers.js
lib/bootstrapHelpers.js
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /** * * Helper functions for Bootstrap components. */ function setButtonChecked(button, checked) { button.checked = checked; button.parentNode.classList.toggle("active", checked); } function toggleHidden(hidden) { let hiddenClass = "hidden"; if (typeof hidden === "boolean") { for (let i = 1; i < arguments.length; i++) { arguments[i].classList.toggle(hiddenClass, hidden); } } else if (hidden) { hidden.classList.toggle(hiddenClass); } } function toggleFade(element) { element.classList.add("fade"); setTimeout(function () { element.classList.remove("fade"); }, 2000); } function addInputValidation(input, callback) { function validateInput(e) { let pass = e.target.checkValidity(); input.parentNode.classList.toggle("has-error", !pass); callback(pass); } input.addEventListener("input", validateInput); input.addEventListener("change", validateInput); input.addEventListener("blur", validateInput); } function getSubPage(url) { let request = new Request(url, { method: "GET", headers: { "Content-Type": "text/xml" }, mode: "same-origin", cache: "force-cache" }); return fetch(request).then(response => { return response.text() }).then(text => { return document.createRange().createContextualFragment(text); }); } function changeTab(tab) { let tabInfo = tab.split("#"); let tabSelector = document.querySelector(".tab-selector[data-tab=" + tabInfo[0] + "]"); if (!tabSelector || tabSelector.classList.contains("active")) { return; } document.getElementById("tabs").querySelector(".active").classList.remove("active"); tabSelector.parentNode.classList.add("active"); document.querySelector(".tab-pane.active").classList.remove("active"); document.getElementById(tabSelector.dataset.tab + "Tab").classList.add("active"); document.title = browser.i18n.getMessage(tabSelector.dataset.tabTitle); document.getElementById("pageTitle").textContent = document.title; if (tabInfo[1]) { window.location.hash = tabInfo[1] } } function setTabFromHash() { let hash = window.location.hash; if (hash.startsWith("#tab-")) { changeTab(hash.substring(5)); } } window.addEventListener("hashchange", setTabFromHash); document.addEventListener("DOMContentLoaded", function () { setTabFromHash(); for (let close of document.querySelectorAll(".close")) { close.addEventListener("click", function () { this.parentNode.classList.remove("show") }); } });
JavaScript
0.000349
@@ -862,385 +862,8 @@ %0A%7D%0A%0A -function addInputValidation(input, callback) %7B%0A function validateInput(e) %7B%0A let pass = e.target.checkValidity();%0A input.parentNode.classList.toggle(%22has-error%22, !pass);%0A callback(pass);%0A %7D%0A%0A input.addEventListener(%22input%22, validateInput);%0A input.addEventListener(%22change%22, validateInput);%0A input.addEventListener(%22blur%22, validateInput);%0A%7D%0A%0A func
1717c45ddeacc50c058462e0ac03d8a4ca308584
Move initialization of Brackets object from appshell_extensions.js to Global.js (#13975)
src/utils/Global.js
src/utils/Global.js
/* * Copyright (c) 2012 - present Adobe Systems Incorporated. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ /** * Initializes the global "brackets" variable and it's properties. * Modules should not access the global.brackets object until either * (a) the module requires this module, i.e. require("utils/Global") or * (b) the module receives a "appReady" callback from the utils/AppReady module. */ define(function (require, exports, module) { "use strict"; var configJSON = require("text!config.json"), UrlParams = require("utils/UrlParams").UrlParams; // Define core brackets namespace if it isn't already defined // // We can't simply do 'brackets = {}' to define it in the global namespace because // we're in "use strict" mode. Most likely, 'window' will always point to the global // object when this code is running. However, in case it isn't (e.g. if we're running // inside Node for CI testing) we use this trick to get the global object. var Fn = Function, global = (new Fn("return this"))(); if (!global.brackets) { global.brackets = {}; } // Parse URL params var params = new UrlParams(); params.parse(); // Parse src/config.json try { global.brackets.metadata = JSON.parse(configJSON); global.brackets.config = global.brackets.metadata.config; } catch (err) { console.log(err); } // Uncomment the following line to force all low level file i/o routines to complete // asynchronously. This should only be done for testing/debugging. // NOTE: Make sure this line is commented out again before committing! //brackets.forceAsyncCallbacks = true; // Load native shell when brackets is run in a native shell rather than the browser // TODO: (issue #266) load conditionally global.brackets.shellAPI = require("utils/ShellAPI"); // Determine OS/platform if (global.navigator.platform === "MacIntel" || global.navigator.platform === "MacPPC") { global.brackets.platform = "mac"; } else if (global.navigator.platform.indexOf("Linux") >= 0) { global.brackets.platform = "linux"; } else { global.brackets.platform = "win"; } global.brackets.inBrowser = !global.brackets.hasOwnProperty("fs"); // Are we in a desktop shell with a native menu bar? var hasNativeMenus = params.get("hasNativeMenus"); if (hasNativeMenus) { global.brackets.nativeMenus = (hasNativeMenus === "true"); } else { global.brackets.nativeMenus = (!global.brackets.inBrowser); } // Locale-related APIs global.brackets.isLocaleDefault = function () { return !global.localStorage.getItem("locale"); }; global.brackets.getLocale = function () { // By default use the locale that was determined in brackets.js return params.get("testEnvironment") ? "en" : (global.localStorage.getItem("locale") || global.require.s.contexts._.config.locale); }; global.brackets.setLocale = function (locale) { if (locale) { global.localStorage.setItem("locale", locale); } else { global.localStorage.removeItem("locale"); } }; // Create empty app namespace if running in-browser if (!global.brackets.app) { global.brackets.app = {}; } // Loading extensions requires creating new require.js contexts, which // requires access to the global 'require' object that always gets hidden // by the 'require' in the AMD wrapper. We store this in the brackets // object here so that the ExtensionLoader doesn't have to have access to // the global object. global.brackets.libRequire = global.require; // Also store our current require.js context (the one that loads brackets // core modules) so that extensions can use it. // Note: we change the name to "getModule" because this won't do exactly // the same thing as 'require' in AMD-wrapped modules. The extension will // only be able to load modules that have already been loaded once. global.brackets.getModule = require; /* API for retrieving the global RequireJS config * For internal use only */ global.brackets._getGlobalRequireJSConfig = function () { return global.require.s.contexts._.config; }; exports.global = global; });
JavaScript
0
@@ -2134,24 +2134,523 @@ brackets) %7B%0A +%0A // Earlier brackets object was initialized at %0A // https://github.com/adobe/brackets-shell/blob/908ed1503995c1b5ae013473c4b181a9aa64fd22/appshell/appshell_extensions.js#L945.%0A // With the newer versions of CEF, the initialization was crashing the render process, citing%0A // JS eval error. So moved the brackets object initialization from appshell_extensions.js to here.%0A if (global.appshell) %7B%0A global.brackets = global.appshell;%0A %7D else %7B%0A glob @@ -2663,24 +2663,34 @@ ckets = %7B%7D;%0A + %7D%0A %7D%0A%0A /
abf20365ddc898d0c98f273f465322563a1bbba9
remove console.log(jsonAxes)
src/renderer/axes.js
src/renderer/axes.js
const processAxes = ( Graph, graph, type, axisOptions, allAxes ) => { if ( !Array.isArray( axisOptions ) ) { axisOptions = [ axisOptions ]; } axisOptions.forEach( ( options ) => { let constructorName; if ( type == 'x' ) { type = 'bottom'; } else if ( type == 'y' ) { type = 'left'; } if ( type == 'bottom' || type == 'top' ) { constructorName = 'graph.axis.x'; if ( options.type == 'category' ) { constructorName += '.bar'; } } else { constructorName = 'graph.axis.y'; } var axis = new( Graph.getConstructor( constructorName ) )( graph, type ); axis.init( graph, options ); if ( type == 'bottom' ) { graph.setBottomAxis( axis, graph.getNumAxes( 'bottom' ) ); } else if ( type == 'top' ) { graph.setTopAxis( axis, graph.getNumAxes( 'top' ) ); } else if ( type == 'left' ) { graph.setLeftAxis( axis, graph.getNumAxes( 'left' ) ); } else if ( type == 'right' ) { graph.setRightAxis( axis, graph.getNumAxes( 'right' ) ); } if ( options.type == 'category' ) { axis.categories = options.categories; } if ( options.name ) { allAxes[ name ] = axis; } } ); }; const makeAxes = ( Graph, graph, jsonAxes ) => { const allAxes = []; console.log( jsonAxes ); if ( jsonAxes.x ) { processAxes( Graph, graph, 'x', jsonAxes.x, allAxes ); } if ( jsonAxes.y ) { processAxes( Graph, graph, 'y', jsonAxes.y, allAxes ); } if ( jsonAxes.top ) { processAxes( Graph, graph, 'top', jsonAxes.top, allAxes ); } if ( jsonAxes.left ) { processAxes( Graph, graph, 'left', jsonAxes.left, allAxes ); } if ( jsonAxes.bottom ) { processAxes( Graph, graph, 'bottom', jsonAxes.bottom, allAxes ); } if ( jsonAxes.right ) { processAxes( Graph, graph, 'right', jsonAxes.right, allAxes ); } }; export default makeAxes;
JavaScript
0.000011
@@ -1293,35 +1293,8 @@ %5B%5D;%0A - console.log( jsonAxes );%0A if
ade63f614a9005f5eedd01cdb0b3ae3f3eac92d0
add default ops state
lib/dirAsyncSequence.js
lib/dirAsyncSequence.js
'use strict'; var fs = require('fs'), path = require('path'), Lazy = require('lazy.js'); /** * * @class DirectoryStreamSequence * * @param path * @param ops * @constructor */ function DirectoryStreamSequence(path, ops) { this.path = path; this.ops = ops; this.parent = this; } DirectoryStreamSequence.prototype = new Lazy.AsyncSequence(); DirectoryStreamSequence.prototype.getIterator = function() { return new DirectoryStreamSequenceIterator(this.path, this.ops); }; /** * @class DirectoryStreamSequenceIterator * @param path * @constructor */ function DirectoryStreamSequenceIterator(path, ops) { this.path = path; this.ops = ops; this.files = []; this.directories = []; var stat = this.createStat(path); if (stat.isDirectory()) { this.directories.push(stat); } this.currentFile = null; this.hasParsedRoot = false; } DirectoryStreamSequenceIterator.prototype.current = function() { return this.currentFile; }; DirectoryStreamSequenceIterator.prototype._checkFile = function(file) { var stat = fs.statSync(file); if (stat.isDirectory()) { this.directories.push(file); } }; DirectoryStreamSequenceIterator.prototype.createStat = function(root, name) { var filePath = name?path.join(root, name):root, stat = fs.statSync(filePath); stat.path = filePath; stat.root = root; stat.name = name; return stat; }; DirectoryStreamSequenceIterator.prototype.moveNext = function() { var self = this, file; if (this.files.length === 0 && (this.ops.recursive || !this.hasParsedRoot)) { this.hasParsedRoot = true; var root = this.directories.pop(); if (root) { append(self.files, fs.readdirSync(root.path) .map(function(fileName) { return self.createStat(root.path, fileName); }) ); } } if (this.files.length > 0) { file = this.files.pop(); if (file.isDirectory()) { this.directories.push(file); } } else { return false; } this.currentFile = file; return true; }; module.exports = function(path, ops) { return new DirectoryStreamSequence(path, ops) }; function append(array, source) { Array.prototype.push.apply(array, source); return array; }
JavaScript
0.000001
@@ -663,33 +663,73 @@ this.ops = ops -; + %7C%7C %7B%0A recursive: true%0A %7D;%0A %0A this.files
298b7ff039ddf155832a4ce83df99b044e015dbd
Fix name not being passed to search query
lib/google-locations.js
lib/google-locations.js
var https = require('https'), _ = require('underscore'), url = require('url'); var GoogleLocations = function(key, options) { // Set default options if (!options) options = {}; options = _.defaults(options, { format: 'json', headers: { "User-Agent": 'Google-Locations (https://www.npmjs.org/package/google-locations)' }, host: 'maps.googleapis.com', port: 443, path: '/maps/api/' }); this.config = { key: key, format: options.format, headers: options.headers, host: options.host, port: options.port, path: options.path }; return this; }; //Google place search GoogleLocations.prototype.search = function(options, cb) { options = _.defaults(options, { location: [37.42291810, -122.08542120], radius: 10, name: 'A', language: 'en', rankby: 'prominence', types: [] }); options.location = options.location.join(','); if (options.types.length > 0) { options.types = options.types.join('|'); } else { delete options.types; } if (options.rankby == 'distance') options.radius = null; this._makeRequest(this._generateUrl(options, 'place', 'nearbysearch'), cb); }; GoogleLocations.prototype.autocomplete = function(options, cb) { options = _.defaults(options, { language: "en", }); this._makeRequest(this._generateUrl(options, 'place', 'autocomplete'), cb); }; // Goolge place details GoogleLocations.prototype.details = function(options, cb) { if (!options.placeid) return cb({error: 'placeid string required'}); options = _.defaults(options, { // placeid: options.placeid, language: 'en' }); this._makeRequest(this._generateUrl(options, 'place', 'details'), cb); }; GoogleLocations.prototype.geocodeAddress = function(options, cb) { if (!options.address) return cb({error: 'Address string required'}); options = _.defaults(options, { language: 'en' }); options.address = options.address.replace(/\s/g, '+'); this._makeRequest(this._generateUrl(options, 'geocode', null), cb); }; GoogleLocations.prototype.reverseGeocode = function(options, cb) { options = _.defaults(options, { latlng: [37.42291810, -122.08542120], language: 'en' }); options.latlng = options.latlng.join(','); this._makeRequest(this._generateUrl(options, 'geocode', null), cb); }; GoogleLocations.prototype.findPlaceDetailsWithAddress = function(options, cb) { if (!options.address) return cb({error: "Address string required"}); var _self = this; var name; if (options.name) { name = options.name; delete options.name; } var maxResults = 1; if (options.maxResults) { maxResults = options.maxResults; delete options.maxResults; } _self.geocodeAddress(options, function(err, result){ if (err) return cb({message: "Error geocoding address", error: err}); var location; try { location = result.results[0].geometry.location; } catch (exp) { return cb({message: "Malformed results -- try a more specific address", error: exp}); } var query = {location: [location.lat, location.lng], rankby: "prominence", radius: 250}; if (options.name) query.name = name; _self.search(query, function(err, result){ if (err) return cb({message: "Error searching for places near geocoded location", error: err}); if (result.results.length === 0) return cb(null, {details: [], errors: []}); var details = []; var errors = []; var j = (maxResults > result.results.length) ? result.results.length : maxResults; for (var i = 0; i < j; i++) { var placeid; try { placeid = result.results[i].place_id; _self.details({placeid: placeid}, function(err, result){ if (err) { errors.push({message: "Error requesting details for placeid " + placeid, error: err}); } else { details.push(result); } if (details.length + errors.length == j) return cb(null, {details: details, errors: errors}); }); } catch (exp) { errors.push({message: "No place_id found", error: exp}); if (details.length + errors.length == j) return cb(null, {details: details, errors: errors}); } } }); }); }; // Run the request GoogleLocations.prototype._makeRequest = function(request_query, cb) { // Pass the requested URL as an object to the get request https.get(request_query, function(res) { var data = []; res .on('data', function(chunk) { data.push(chunk); }) .on('end', function() { var dataBuff = data.join('').trim(); var result; try { result = JSON.parse(dataBuff); } catch (exp) { result = {'status_code': 500, 'status_text': 'JSON Parse Failed'}; } cb(null, result); }); }) .on('error', function(e) { cb(e); }); }; GoogleLocations.prototype._generateUrl = function(query, type, method) { //https://maps.googleapis.com/maps/api/place/nearbysearch/json? //https://maps.googleapis.com/maps/api/geocode/json? _.compact(query); query.key = this.config.key; return url.parse(url.format({ protocol: 'https', hostname: this.config.host, pathname: this.config.path + type + '/' + (method ? method + '/' : '') + this.config.format, query: query })); }; module.exports = GoogleLocations;
JavaScript
0.000008
@@ -3140,32 +3140,24 @@ 0%7D;%0A if ( -options. name) query.
468ce5bc122e580fed449525d8f83ada78fb1d5e
Fix syntax
lib/helpers/hydrater.js
lib/helpers/hydrater.js
'use strict'; /** * @file Hydrate the file from scratch. * Download it from AnyFetch, save it to local storage, run the hydrater function and return the result. * * This helper is used in the server queue. */ var async = require('async'); var fork = require('child_process').fork; var request = require('supertest'); var restify = require('restify'); var url = require('url'); var rarity = require('rarity'); var util = require('util'); var lib = require('../index.js'); var HydrationError = lib.HydrationError; module.exports = function(hydraterFunction, logger, errLogger) { if(!errLogger) { errLogger = logger; } /** * Handle a hydration task: * - Download the file * - Call the user-provided `hydraterFunction` * - Patch the document to apply the changes against the AnyFetch API * - Cleanup * * @param {Object} task Task object, keys must be `file_path` (file URL) and `callback` (URL) * @param {Function} done(err) */ return function(task, done) { logger("Starting task: " + ((task.file_path) ? task.file_path : task.document.id)); async.waterfall([ function performHydration(cb) { var child = fork(__dirname + '/child-process.js', {silent: true}); var stderr = ""; var stdout = ""; var timeout; /** * Function to call, either on domain error, on hydration error or successful hydration. * Will clean the fs and dispose the domain for better performance. */ var cleaner = function(err, changes) { if(!cleaner.called) { cleaner.called = true; cb(err, changes); } if(stdout !== "") { logger(stdout); } if(stderr !== "") { errLogger(stderr); } clearTimeout(timeout); }; cleaner.called = false; child.on('error', function(exitCode) { cleaner(new HydrationError("Wild error appeared while spawning child. Exit code:" + exitCode)); }); child.stderr.on('readable', function() { var chunk; while (null !== (chunk = child.stderr.read())) { stderr += chunk; } }); child.stdout.on('readable', function() { var chunk; while (null !== (chunk = child.stdout.read())) { stdout += chunk; } }); child.on('exit', function(errCode) { if(errCode === 143) { // The child process exited normally after we sent him a SIGTERM. The output will be catch in the timeout, not here. return; } if(errCode !== 0) { cleaner(new HydrationError("Child exiting with err code: " + errCode + stdout + stderr)); } }); // Build objects to send to child var options = {}; options.urlCallback = task.callback; options.apiUrl = ''; if(task.callback) { var parsed = url.parse(task.callback); options.apiUrl = parsed.protocol + "//" + parsed.host; } child.send({ functionPath: hydraterFunction, priority: task.priority, file_path: task.file_path, document: task.document, changes: lib.defaultChanges(), options: options, }); child.on('message', function(res) { var err = res.err; // If the function replied with an "HydrationError", we'll wrap this in a nicely formatted document // and stop the error from bubbling up. if(err && err._hydrationError) { res.changes = {}; res.changes.hydration_errored = true; res.changes.hydration_error = err.message; err = null; } cleaner(err, res.changes); }); timeout = setTimeout(function() { if(!cleaner.called) { var changes = {}; changes.hydration_errored = true; changes.hydration_error = "Task took too long."; errLogger('Killing task: ' + ((task.file_path) ? task.file_path : task.document.id)); child.kill('SIGTERM'); setTimeout(function() { if(child.connected) { child.kill('SIGKILL'); } cleaner(null, changes); }, process.env.TIMEOUT / 6 || 10 * 1000); } }, process.env.TIMEOUT || 60 * 1000); }, function cleanChanges(changes, cb) { // Removing empty changes to patch only effective changes var isEmpty = function(elem) { if(util.isArray(elem)) { return (elem.length === 0); } if(elem instanceof Object) { if(util.isDate(elem)) { return false; } return (Object.getOwnPropertyNames(elem).length === 0); } return false; }; if(changes !== null) { Object.keys(changes).forEach(function(key) { if(isEmpty(changes[key])) { delete changes[key]; } }); } cb(null, changes); }, function patchDocument(changes, cb) { // Returning null means we won't complete the hdyration, and are waiting for something else. if(changes === null) { logger("Skipped task: " + ((task.file_path) ? task.file_path : task.document.id)); return cb(); } logger("End of task: " + ((task.file_path) ? task.file_path : task.document.id)); // When long_polling, it is possible we don't have a callback if(task.callback) { var apiUrl = url.parse(task.callback, false, true); request(apiUrl.protocol + "//" + apiUrl.host) .patch(apiUrl.path) .send(changes) .end(rarity.carry([changes], cb)); } else { cb(null, changes); } } ], function handleErrors(err, changes, res) { async.waterfall([ function logError(cb) { if(err) { errLogger("ERR hydrating " + ((task.file_path) ? task.file_path : task.document.id), err.toString()); } if(res && res.statusCode && res.statusCode !== 204) { errLogger("ERR hydrating: server refused data! Code:" + res.statusCode); } cb(null); }, function forwardError(cb) { if(!err) { if(task.long_poll) { task.res.send(changes); task.next(); } return cb(null); } if(task.long_poll) { task.next(new restify.InvalidContentError("ERR hydrating " + ((task.file_path) ? task.file_path : task.document.id) + err.toString())); cb(null); } else { var apiUrl = url.parse(task.callback, false, true); request(apiUrl.protocol + "//" + apiUrl.host) .patch(apiUrl.path) .send({ hydration_error: err.toString() }) .end(cb); } } ], function(internalErr) { if(internalErr) { errLogger("ERR", internalErr); } done(err || internalErr, changes); }); }); }; };
JavaScript
0.509732
@@ -6829,16 +6829,26 @@ %7D +%0A else %7B%0A @@ -7217,16 +7217,25 @@ Logger(%22 +INTERNAL ERR%22, in
a2587167edfc7e3cccfa81996cbc31cead683a26
Fix test error
lib/hexo/load_config.js
lib/hexo/load_config.js
'use strict'; const merge = require('lodash/merge'); const { sep, resolve, join, parse } = require('path'); const tildify = require('tildify'); const Theme = require('../theme'); const Source = require('./source'); const fs = require('hexo-fs'); const chalk = require('chalk'); module.exports = ctx => { if (!ctx.env.init) return; const baseDir = ctx.base_dir; let configPath = ctx.config_path; return fs.exists(configPath).then(exist => { return exist ? configPath : findConfigPath(configPath); }).then(path => { if (!path) return; configPath = path; return ctx.render.render({path}); }).then(config => { if (!config || typeof config !== 'object') return; ctx.log.debug('Config loaded: %s', chalk.magenta(tildify(configPath))); config = merge(ctx.config, config); ctx.config_path = configPath; config.root = config.root.replace(/\/*$/, '/'); config.url = config.url.replace(/\/+$/, ''); ctx.public_dir = resolve(baseDir, config.public_dir) + sep; ctx.source_dir = resolve(baseDir, config.source_dir) + sep; ctx.source = new Source(ctx); if (!config.theme) return; config.theme = config.theme.toString(); ctx.theme_dir = join(baseDir, 'themes', config.theme) + sep; ctx.theme_script_dir = join(ctx.theme_dir, 'scripts') + sep; ctx.theme = new Theme(ctx); }); }; function findConfigPath(path) { const { dir, name } = parse(path); return fs.readdir(dir).then(files => { const item = files.find(item => item.startsWith(basename)); if (item != null) return pathFn.join(dirname, item); }); }
JavaScript
0.000017
@@ -1516,20 +1516,16 @@ rtsWith( -base name));%0A @@ -1557,23 +1557,16 @@ urn -pathFn. join(dir name @@ -1561,20 +1561,16 @@ join(dir -name , item);
2b7d5ecce06fc4dc0588797f3513a95d29a6ff3b
Use underscores
lib/inputs/HTTPInput.js
lib/inputs/HTTPInput.js
let util = require('util'), BaseInput = require('./BaseInput'), EventContainer = require('../EventContainer') /** * Turns http requests into events * You must call `listen` after adding this input * * const http = require('http') * let s = http.createServer() * s.listen(9012) * addInputPlugin('http', { server: s }) * * @param {String} options.name * @param {Object} options.server A server object or anything that emits a readable stream. You must call listen. * * @extends BaseInput * @constructor */ let HTTPInput = function (options) { HTTPInput.super_.call(this, options) let self = this self.name = options.name || HTTPInput.NAME self.server = options.server self.sockets = {} self._id = 0 self.logger.debug(self.name, 'starting up') self._wireServer() self.streamStash.on('start', function () { self.state = 1 for (let socketId in self.sockets) { self.sockets[socketId].resume() } self.emit('started') }) self.streamStash.on('stopInput', function () { self.state = 0 for (let socketId in self.sockets) { self.sockets[socketId].pause() } self.emit('stoppedInput') }) self.streamStash.on('stop', function () { self.emit('stopped') }) } HTTPInput.NAME = "HTTP" HTTPInput.DESCRIPTION = "Listens to an http server and emits requests as events" util.inherits(HTTPInput, BaseInput) module.exports = HTTPInput HTTPInput.prototype._wireSocket = function (socket) { let self = this socket._id = self._id++ self.sockets[socket._id] = socket socket.on('error', function (error) { self.logger.error(self.name, 'Connection # ' + socket.socketId + ' (' + self.remoteAddress + ') had an error', { error: error.stack || error }) socket.destroy() }) socket.on('close', function () { delete self.sockets[socket._id] }) } HTTPInput.prototype._wireServer = function () { let self = this self.server.on('connection', function (socket) { if (self.state !== 1) { socket.pause() } self._wireSocket(socket) }) self.server.on('request', (req, res) => { let body = '' req.on('end', () => { self._emitEvent( req.method + ' ' + req.url + ' HTTP/' + req.httpVersion, event => { event.data.httpRequest = { url: req.url, headers: req.headers, trailers: req.trailers, body: body, version: req.httpVersion, remote: { address: req.socket.remoteAddress, family: req.socket.remoteFamily, port: req.socket.remotePort, } } event.on('complete', function () { if (event.state === EventContainer.STATE.FAILED) { self.logger.debug(self.name, 'Nacking event', { event_id: event.eventId }) res.statusCode = 500 } else { self.logger.debug(self.name, 'Acking event', { event_id: event.eventId }) res.statusCode = 200 } res.end() }) self.emit('event', event) } ) }) req.on('data', (data) => { body += data }) }) }
JavaScript
0.00001
@@ -2444,17 +2444,18 @@ ata.http -R +_r equest =
c7fba4755776d26c9080a711ff9edc640395eaf1
Add volume scales
src/scales/volume.js
src/scales/volume.js
/* * Cookie Calculator / scales/volume.js * copyright (c) 2016 Susisu */ "use strict"; import { SIUnit } from "../units.js"; let values = [ ]; export default values.map(x => ({ quantity : SIUnit.CUBIC_METRE.value(x.value), description: x.description }));
JavaScript
0.000002
@@ -139,16 +139,623 @@ ues = %5B%0A + %7B%0A value: 2.82e-45,%0A description:%0A %60Proton%60%0A %7D,%0A %7B%0A value: 7.23e-30,%0A description:%0A %60Hydrogen atom%60%0A %7D,%0A %7B%0A value: 5e-21,%0A description:%0A %60A virus%60%0A %7D,%0A %7B%0A value: 9e-17,%0A description:%0A %60Human red blood cell%60%0A %7D,%0A %7B%0A value: 2e-15,%0A description:%0A %60Ink drop of a printer%60%0A %7D,%0A %7B%0A value: 6.2e-11,%0A description:%0A %60A medium grain of sand%60%0A %7D,%0A %7B%0A value: 2e-8,%0A description:%0A %60A grain of rice%60%0A %7D%0A %5D;%0A%0Aexpo
51c2ce6c9069cb85c37f756caebc426fe265d2fb
Fix root expires token handling
lib/lumbar-long-expires.js
lib/lumbar-long-expires.js
var _ = require('underscore'), async = require('async'), exec = require('child_process').exec, jsdom = require('jsdom').jsdom, lumbar = require('lumbar'), fu = lumbar.fileUtil; module.exports = { priority: 80, generateToken: function(command, callback) { if (!command) { return callback(undefined, ''); } exec(command, {cwd: lumbar.fileUtil.lookupPath()}, function(err, stdout, stderr) { callback(err, (stdout || '').replace(/\n/g, '')); }); }, updateHtmlReferences: function(context, content, callback) { function updateResources(mode, query, create) { return function(callback) { async.forEach(_.clone(doc.querySelectorAll(query)), function(el, callback) { var module = (el.src || el.href).replace(/^module:/, ''); context.fileNamesForModule(mode, module, function(err, fileNames) { if (err) { return callback(err); } // Generate replacement elements for each of the entries var content = fileNames.map(function(fileName) { return create(context.config.loadPrefix() + fileName.fileName.path + '.' + fileName.fileName.extension); }); // Output and kill the original content.forEach(function(replace) { el.parentNode.insertBefore(replace, el); }); el.parentNode.removeChild(el); callback(); }); }, callback); } } var doc = jsdom(content, null, { features: { ProcessExternalResources: false, QuerySelector: true } }); async.parallel([ updateResources('scripts', 'script[src^="module:"]', function(href) { var script = doc.createElement('script'); script.type = 'text/javascript'; script.src = href; return script; }), updateResources('styles', 'link[href^="module:"]', function(href) { var link = doc.createElement('link'); link.rel = 'stylesheet'; link.type = 'text/css'; link.href = href; return link; }) ], function(err) { callback(err, doc.doctype + doc.innerHTML); }); }, fileName: function(context, next, complete) { // Prepend the cache buster value next(function(err, ret) { if (err) { return complete(err); } function generatePath(err, token) { if (ret && token && (context.mode !== 'static' || !context.resource['no-expires-token'] || !context.resource.root)) { // Move the expires token after the platform path if that is the start of the path if (ret.path.indexOf(context.platformPath) === 0) { ret.path = ret.path.substring(context.platformPath.length); token = context.platformPath + token; } ret.path = token + '/' + ret.path; } complete(err, ret); } if (context.configCache.longExpires) { generatePath(undefined, context.configCache.longExpires); } else { module.exports.generateToken( context.config.attributes['long-expires'], generatePath); } }); }, resource: function(context, next, complete) { var resource = context.resource; if (context.mode === 'static' && resource['update-externals']) { next(function(err, resource) { function generator(context, callback) { // Load the source data fu.loadResource(context, resource, function(err, file) { if (err) { return complete(err); } // Update the content module.exports.updateHtmlReferences(context, file.content, function(err, data) { callback(err, { data: data, inputs: file.inputs }); }); }); } // Include any attributes that may have been defined on the base entry if (!_.isString(resource)) { _.extend(generator, resource); } complete(undefined, generator); }); } else { next(complete); } } };
JavaScript
0.000001
@@ -2492,24 +2492,25 @@ static' %7C%7C ! +( context.reso @@ -2537,17 +2537,16 @@ en'%5D %7C%7C -! context. @@ -2560,16 +2560,17 @@ e.root)) +) %7B%0A
a577b3c8f0fca2aa88c994095488f577bbddb325
update default injected styles
lib/oasis/style-barrier.js
lib/oasis/style-barrier.js
import nextFrame from 'oasis/raf'; function addThrottledListener(elt, event, handler) { let pending = false; elt.addEventListener(event, () => { if (pending) { return; } pending = true; nextFrame(() => { pending = false; handler(); }); }); } function setSrcDoc(iframe, content) { if ("srcdoc" in document.createElement("iframe")) { iframe.srcdoc = content; } else { iframe.setAttribute('srcdoc', content); /* jshint -W107 */ iframe.setAttribute('src', 'javascript: window.frameElement.getAttribute("srcdoc");'); /* jshint +W107 */ } } export default function styleBarrier(content, didLoad) { let iframe = document.createElement('iframe'); iframe.style.width = '100%'; iframe.style.height = '100%'; iframe.style.border = '0'; iframe.scrolling = 'no'; iframe.style.display = 'block'; setSrcDoc(iframe, '<head><base target="_top"><style type="text/css">body { padding: 0; margin: 0; } body > * { width: 100%; }</style></head><body>' + content + '</body>'); let adaptHeight = () => { if (!iframe.attributes['data-card-external-sizing']) { let body = iframe.contentWindow.document.body; iframe.style.height = Math.min(body.getBoundingClientRect().bottom, body.scrollHeight) + 'px'; } }; let addedListener = false; iframe.onload = () => { adaptHeight(); if (!addedListener) { addedListener = true; addThrottledListener(iframe.contentWindow, 'resize', adaptHeight); } if (didLoad) { didLoad(); } }; return iframe; }
JavaScript
0.000001
@@ -949,16 +949,29 @@ rgin: 0; + height: auto %7D body
9306de9dcfd88eec32d334419cfa83726c1edc81
fix error
lib/offshore/core/cache.js
lib/offshore/core/cache.js
var fs = require('fs'); var path = require('path'); var os = require('os'); var _ = require('lodash'); var filepath = os.tmpdir(); var prefix = 'CACHE_'; var defaultCacheTime = 3600000; var HEADER_SIZE = 20; function fullpath(key) { return path.join(filepath, prefix + key); } ; var DefaultAdapter = { get: function(key, cb) { var self = this; var headerStream = fs.createReadStream(fullpath(key), {start: 0, end: HEADER_SIZE - 1}); var header = ''; headerStream.on('error', function(err) { headerStream.destroy(); if (err.code === 'ENOENT') { return cb(self.errors.NO_CACHE); } cb(err); }); headerStream.on('data', function(data) { header += data.toString(); }); headerStream.on('end', function() { var time = parseInt(header); // if cache is valid if (time >= new Date().getTime() || time === 0) { var content = ''; var contentStream = fs.createReadStream(fullpath(key), {start: HEADER_SIZE}); contentStream.on('error', function(err) { contentStream.destroy(); cb(err); }); contentStream.on('data', function(data) { content += data.toString(); }); contentStream.on('end', function() { var cache; if (content === 'UNDEFINED') { return cb(null); } try { cache = JSON.parse(content); cb(null, cache); } catch (e) { if (_.isUndefined(cache)) { cb(e); } } }); } else { cb(self.errors.NO_CACHE); } }); }, set: function(key, value, time) { var valid = 0; if (_.isUndefined(time)) { valid = new Date().getTime() + defaultCacheTime; } else if (time > 0) { valid = new Date().getTime() + (time * 1000); } var content; if (_.isUndefined(value)) { content = 'UNDEFINED'; } else { content = JSON.stringify(value); } var header = valid.toString(); var pad = HEADER_SIZE - header.length; for (var i = 0; i < pad; i ++) { header += ' '; } fs.createWriteStream(fullpath(key)).write(header + content); } }; module.exports = { initialize: function(options, cb) { var options = options || {}; var self = this; options.defaultCacheTime = options.defaultCacheTime || defaultCacheTime; // if an adapter is specified if (options.adapter && options.adapter !== 'default') { // Detects if there is a `getDatastore` in the adapter. Exit if it not exists. if (! options.adapter.getDatastore) { throw new Error('Adapter does not support Datastore interface which is required for cache'); } options.adapter.getDatastore(options, function(err, cache) { self.get = function(key, cb) { cache.get(key, function(err, value) { if (err && err.message === '404') { cb(self.errors.NO_CACHE); } else if (err) { cb(err); } else if (value.ttl >= new Date().getTime() || value.ttl === 0) { cb(null, value.data); } else { cb(self.errors.NO_CACHE); } }); }; self.set = function(key, value, time) { var valid = 0; if (_.isUndefined(time)) { valid = new Date().getTime() + defaultCacheTime; } else if (time > 0) { valid = new Date().getTime() + (time * 1000); } var data = {ttl: valid, data: value}; cache.set(key, data, function() { if (time > 0) { setTimeout(function() { //check cache cache.get(key, function(err, value) { if (err) { return; } if (value.ttl >= new Date().getTime()) { cache.remove(key); } }); }, time); } }); }; cb(); }); } else { filepath = options.path || filepath; prefix = options.prefix || prefix; defaultCacheTime = options.defaultCacheTime; this.get = DefaultAdapter.get; this.set = DefaultAdapter.set; cb(); } }, errors: { NO_CACHE: new Error("NO_CACHE") } };
JavaScript
0.000002
@@ -3944,16 +3944,31 @@ move(key +, function() %7B%7D );%0A
b9f2eb21fa23d369ad5185adb3ec33ca7001d474
Fix api docs of Processor
lib/mincer/processor.js
lib/mincer/processor.js
/*:nodoc:* internal * class Processor * * Subclass of [[Template]]. * * Used to create custom processors without need to extend [[Template]] by * simply providing a function to the processor registration methods: * * var name = 'my-pre-processor'; * var func = function (context, data, callback) { * callback(null, data.toLowerCase()); * }; * * // register custom pre-processor * environment.registerPreProcessor('text/css', name, func); * * // unregister custom pre-processor * environment.unregisterPreProcessor('text/css', name); * * * ##### See Also: * * - [[Context]] * - [[Processing]] **/ 'use strict'; // stdlib var inherits = require('util').inherits; // 3rd-party var _ = require('underscore'); // internal var Template = require('./template'); var prop = require('./common').prop; // Class constructor var Processor = module.exports = function Processor() { Template.apply(this, arguments); }; inherits(Processor, Template); // Run processor Processor.prototype.evaluate = function (context, locals, callback) { if (Processor === this.constructor) { callback(new Error("Processor can't be used directly. Use `Processor.create()`")); return; } this.constructor.__func__(context, this.data, callback); }; /*:nodoc:* * Processor.create(name, func) -> Function * * Returns new `Processor` subclass. **/ Processor.create = function (name, func) { var Klass; if (!_.isFunction(func)) { throw new Error("Processor#create() expects second argument to be a function"); } Klass = function () { Processor.apply(this, arguments); }; inherits(Klass, Processor); prop(Klass, '__name__', 'Processor:' + name); prop(Klass, '__func__', func); return Klass; };
JavaScript
0
@@ -40,41 +40,8 @@ %0A *%0A - * Subclass of %5B%5BTemplate%5D%5D.%0A *%0A * @@ -624,16 +624,64 @@ ssing%5D%5D%0A + *%0A *%0A * ##### SUBCLASS OF%0A *%0A * %5B%5BTemplate%5D%5D%0A **/%0A%0A%0A'
9949a62f1f56417ac02a8873fe49c21cc143e1c4
Fix output view closing too early Output view would close too early because of previous timeout.
lib/output-view-manager.js
lib/output-view-manager.js
'use babel'; 'use strict'; /* jshint node: true */ /* jshint esversion: 6 */ /* global localStorage, console, atom, module */ const ScrollView = require('atom-space-pen-views').ScrollView; let defaultMessage = '[Loading...]'; class OutputView extends ScrollView { constructor() { super(); this.message = ''; } addLine(line) { if (this.message == defaultMessage) { this.message = ''; } this.message += line; return this; } reset() { this.message = defaultMessage; this.find('.output').text(this.message); } finish() { let timeoutLen = atom.config.get('messageTimeout') * 1000; timeoutLen = timeoutLen ? timeoutLen : 5000; this.find('.output').text(this.message); this.show(); this.timeout = setTimeout( () => { this.toggle(); }, timeoutLen ); } toggle() { if (this.timeout) { clearTimeout(this.timeout); } ScrollView.prototype.toggle.call(this); } } OutputView.content = function() { return this.div({class: 'pb-run output-view'}, () => { this.pre({class: 'output'}, defaultMessage); }); }; module.exports.OutputView = OutputView; let activeView = null; class OutputViewManager { constructor() { this.view = null; } new() { if (activeView) { activeView.reset(); } return this.getView(); } getView() { if (!activeView) { activeView = new module.exports.OutputView(); atom.workspace.addBottomPanel({item: activeView}); // activeView.hide(); } return activeView; } } let manager = new OutputViewManager(); module.exports.OutputViewManager = manager;
JavaScript
0.007646
@@ -346,24 +346,102 @@ ine(line) %7B%0A + if (this.timeout) %7B%0A clearTimeout(this.timeout);%0A %7D%0A if ( @@ -470,24 +470,24 @@ tMessage) %7B%0A - @@ -582,24 +582,102 @@ reset() %7B%0A + if (this.timeout) %7B%0A clearTimeout(this.timeout);%0A %7D%0A this @@ -754,24 +754,24 @@ age);%0A %7D%0A - finish() @@ -769,24 +769,102 @@ finish() %7B%0A + if (this.timeout) %7B%0A clearTimeout(this.timeout);%0A %7D%0A let
fb491087b9a8771c8b45d441f5185036ee5adf6e
Fix array parser parsing blank string.
lib/parsers/as-array.js
lib/parsers/as-array.js
'use strict'; function parseQueryParamAsArray(p) { return function parseQueryParameter(q) { var query = {}; query[p] = q[p].split(','); return query; }; } module.exports = parseQueryParamAsArray;
JavaScript
0.000033
@@ -122,16 +122,30 @@ ery%5Bp%5D = + (q && q%5Bp%5D) ? q%5Bp%5D.sp @@ -152,16 +152,21 @@ lit(',') + : %5B%5D ;%0A%0A r
b9e2d28204cf196af51e184ad757c9e34619d016
Change 'Default Menu' title to 'Menu'
lib/plugin/menu/menu.js
lib/plugin/menu/menu.js
"use strict"; const Plugin = require('../plugin'); const Data = require('../settings/data'); const MenuWidget = require('./widget/menuWidget'); const Handler = require('../router/handler'); const merge = require('../../util/merge'); const Path = require('path'); const {coroutine: co} = require('bluebird'); class Menu extends Plugin { constructor(engine) { super(engine); // Declare the Default menus let Settings = engine.plugin.get('Settings'); Settings.cache.set(new Data({ id: `menu/menus.json`, filename: Path.join('menu', `menus.json`), storage: 'settings', storageCanChange: true, // TODO: Escape. description: 'Stores the list of Menus.', default: [ 'default', 'admin', 'context', 'navigation', ], })); // Declare the menu overrides. Settings.cache.set(new Data({ id: `menu/entryOverrides.json`, filename: Path.join('menu', `entryOverrides.json`), storage: 'settings', storageCanChange: true, // TODO: Escape. description: 'Stores the menu entry overrides.', default: {}, })); this.menus = {}; this.handlerQueue = []; } init() { return co(function*(self, superInit){ yield superInit.call(self); // Set up the menu widgets. let Settings = self.engine.plugin.get('Settings'); let Layout = self.engine.plugin.get('Layout'); const menus = yield Settings.cache.get('menu/menus.json').load(); // TODO: Translate. // TODO: Escape. const defaults = { default: { title: 'Default Menu', description: 'Default menu that most likely appear in the sidebar of each page.', showParentLinks: true, maxLevels: undefined, }, admin: { title: 'Admin Menu', description: 'Administration menu.', showParentLinks: true, maxLevels: undefined, }, context: { title: 'Context Sensitive Menu', description: 'Menu whose items contain dynamic paths.', showParentLinks: false, maxLevels: 1, }, navigation: { title: 'Navigation Menu', description: 'Small menu whose items are normally used for site navigation.', showParentLinks: false, maxLevels: 1, }, }; for (let menu of menus) { // TODO: Escape. Settings.cache.set(new Data({ id: `menu/menu-${menu}.json`, filename: Path.join('menu', `menu-${menu}.json`), storage: 'settings', storageCanChange: true, // TODO: Escape. description: 'Stores the settings for a menu.', default: merge({ id: `Menu.${menu}`, title: menu, description: '', showParentLinks: true, maxLevels: undefined, overrides: {}, }, (defaults[menu] ? defaults[menu] : {})), })); } // Load the menus and create a Widget for each of them. // TODO: Translate. for (let menu of menus) { let settings = yield Settings.cache.get(`menu/menu-${menu}.json`).load(); self.menus[menu] = new MenuWidget(settings, self.engine); Layout.widgets.set(self.menus[menu]); } // Load the Menu Entry overrides. self.entryOverrides = yield Settings.cache.get('menu/entryOverrides.json').load(); // Process any handlers that have been queued. self.processHandlers(); })(this, super.init); } addHandler(handler) { this.handlerQueue.push(handler); if (this.entryOverrides !== undefined) { this.processHandlers(); } return this; } processHandlers() { for (let key in this.handlerQueue) { let handler = this.handlerQueue[key]; if (handler instanceof Handler) { if (this.entryOverrides[handler.id]) { // There is an override for this handler. } else { // There is no override for this handler. if (handler.menu && handler.menu.menu && this.menus[handler.menu.menu]) { // The menu exists. // Add the handler. this.menus[handler.menu.menu].addHandler(handler); } } } else { // This is an ad-hoc menu entry. } } // Clear the queue. this.handlerQueue = []; } } module.exports = Menu;
JavaScript
0.008324
@@ -1609,24 +1609,16 @@ title: ' -Default Menu',%0A
cf492e9eba6902df7c6f3e7764fbcca08b95ff25
Disable minifyJs for ampSafe
lib/presets/ampSafe.es6
lib/presets/ampSafe.es6
import objectAssign from 'object-assign'; import safePreset from './safe'; /** * A safe preset for AMP pages (https://www.ampproject.org) */ export default objectAssign({}, safePreset, { collapseBooleanAttributes: { amphtml: true, }, });
JavaScript
0.000001
@@ -246,12 +246,33 @@ %0A %7D,%0A + minifyJs: false,%0A %7D);%0A
7838950f5aa2c97555d60dd704466d0a26d84d04
Remove redundant branches to fix Airbnb 9 issue.
lib/registration-record.js
lib/registration-record.js
'use strict'; /** * Registration record for a dependency */ class RegistrationRecord { /** * Initialize a new registration record * @param {object} details - Registration details */ constructor(details) { if (!details) { throw new Error('Cannot initialize RegistrationRecord: no details passed'); } else if (!(details.generator)) { throw new Error('Cannot initialize RegistrationRecord: no generator function'); } else if (!(details.tags)) { throw new Error('Cannot initialize RegistrationRecord: no tags'); } this.generator = details.generator; this.argList = details.argList || []; this.tags = details.tags; } } module.exports = RegistrationRecord;
JavaScript
0
@@ -337,33 +337,32 @@ %7D else if (! -( details.generato @@ -363,17 +363,16 @@ nerator) -) %7B%0A @@ -468,17 +468,16 @@ se if (! -( details. @@ -481,17 +481,16 @@ ls.tags) -) %7B%0A
0cf5fd7e04e03aeb7b3744a4fb411a1a90b948e8
Add support for private packages
lib/registry-package.js
lib/registry-package.js
var registryUrl = require('registry-url') var request = require('superagent') var url = require('url') var parsePackage = require('./parse-package') module.exports = registryPackage function registryPackage(name, opts, callback) { request .get(url.resolve(registryUrl(), name)) .end(parsePackage(opts, callback)) }
JavaScript
0
@@ -1,12 +1,36 @@ +var rc = require(%22rc%22);%0A var registry @@ -43,17 +43,17 @@ require( -' +%22 registry @@ -56,18 +56,19 @@ stry-url -') +%22); %0Avar req @@ -82,17 +82,17 @@ require( -' +%22 superage @@ -93,18 +93,19 @@ peragent -') +%22); %0Avar url @@ -119,14 +119,15 @@ ire( -'url') +%22url%22); %0Avar @@ -150,17 +150,17 @@ require( -' +%22 ./parse- @@ -170,44 +170,11 @@ kage -')%0A%0Amodule.exports = registryPackage +%22); %0A%0Afu @@ -226,20 +226,147 @@ %7B%0A +var npmConf = rc(%22npm%22, %7B%7D);%0A var npmAuthenticationToken = npmConf%5B%22//registry.npmjs.org/:_authToken%22%5D;%0A var packageInfoRequest = request -%0A .get @@ -403,13 +403,147 @@ me)) +; %0A - +if (npmAuthenticationToken) %7B%0A packageInfoRequest.set(%22Authorization%22, %60Bearer $%7BnpmAuthenticationToken%7D%60);%0A %7D%0A packageInfoRequest .end @@ -576,7 +576,43 @@ ck)) +; %0A%7D%0A +%0Amodule.exports = registryPackage;%0A
5ca17674128754c7fa05e7cb5ce6f38622f2ee22
fix error message for REST step failure
lib/rest-integration.js
lib/rest-integration.js
let Operation = require('./operation'); let Integration = require('./integration.js'); let SwaggerClient = require('./swagger-client'); const METHODS = ['get', 'put', 'post', 'patch', 'delete', 'options', 'head']; const getID = op => { return op.operationId || (op.method.toUpperCase() + ' ' + op.path); } class RESTOperation extends Operation { constructor(info, integration) { super(getID(info), integration); } call(args, cb) { return this.integration.client.request(this.info.method, this.info.path, args, cb); } } class RESTIntegration extends Integration { constructor(name, spec) { spec.operations = {}; for (let path in spec.paths) { for (let method in spec.paths[path]) { if (method === 'parameters') continue; let op = spec.paths[path][method]; op.method = method; op.path = path; let bestCode = null; for (let code in op.responses) { if (code.startsWith('2') && (!bestCode || code < bestCode)) { bestCode = code; } } if (!bestCode) { op.response = {description: 'OK'} } else { op.response = op.responses[bestCode]; } spec.operations[getID(op)] = op; } } super(name, spec); METHODS.forEach(m => { this[m] = path => { let op = this.spec.paths[path][m]; return this.makeOperation(getID(op), op); } }) this.client = new SwaggerClient({swagger: spec}); } initialize(cb) { this.client.initialize((err) => { this.spec = this.client.swagger; this.client.authorize(this.account); cb(err); }); } makeOperation(name, opSpec) { return new RESTOperation(opSpec, this) } resolveOperationId(str) { for (let opId in this.spec.operations) { let op = this.spec.operations[opId]; let fakeOpId = new RegExp('^\s*' + op.method + '\\s+' + op.path + '\s*$', 'i'); if (str === op.operationId || str.match(fakeOpId)) { return opId; } } throw new Error("Couldn't resolve operation " + str); } } RESTIntegration.RESTOperation = RESTOperation; module.exports = RESTIntegration;
JavaScript
0.000001
@@ -523,18 +523,279 @@ , args, -cb +(err, data) =%3E %7B%0A if (err) %7B%0A if (err instanceof Error) return cb(err);%0A let message = err.statusCode;%0A if (data) message += '%5Cn' + JSON.stringify(data, null, 2);%0A return cb(new Error(message));%0A %7D%0A cb(null, data);%0A %7D );%0A %7D%0A%7D
f54bfb323fceb0927292f1255647785bf34c03d3
Remove debug code
lib/server/tokenService.js
lib/server/tokenService.js
const _ = require('lodash'); const grpc = require('grpc'); const path = require('path'); const unirest = require('unirest'); const fd = grpc.load(path.join(__dirname, './proto/com/africastalking/SdkServerService.proto')).africastalking; let config = null; const sipCredentials = []; const getToken = (cxt, callback) => { let url = 'https://'; const type = cxt.request.type; switch(type) { case 'API': url += 'api.'; break; case 'Payment': url += 'payment.'; break; default: callback(new Error(`Invalid/Unknown token type: ${type}`)); return; } if (config.username === 'sandbox') { url += 'sandbox.'; } // url += 'africastalking.com/token/generate'; url = 'https://kaende-api-rs-host.africastalking.com/token/generate'; console.log(url); unirest.post(url) .headers({ 'apiKey': config.apiKey, 'Accept': 'application/json', 'Content-Type': 'application/json' }) .send({ username: config.username }) .end(function (response) { if (response.status >= 200 && response.status < 300) { const tokenResponse = response.body; callback(null, { token: tokenResponse.token, expiration: Date.now() + (tokenResponse.lifetimeInSeconds * 1000), username: config.username, environment: config.username === 'sandbox' ? 'sandbox' : 'production', }); } else { callback(new Error(response.body), null); } }); }; const getSipCredentials = (cxt, callback) => { callback(null, { credentials: sipCredentials }); }; module.exports = (params) => { config = _.cloneDeep(params); return { definition: fd.SdkServerService.service, implementation: { getToken, getSipCredentials, }, addSipCredentials: (username, password, host, port = 5060, transport = "udp") => { sipCredentials.push({ username, password, host, port, transport, }); }, }; };
JavaScript
0.000299
@@ -739,11 +739,8 @@ %0A - // url @@ -783,104 +783,8 @@ te'; -%0A url = 'https://kaende-api-rs-host.africastalking.com/token/generate';%0A console.log(url); %0A%0A
d5b5341ae7b569ae2b7e1f534711bc6441883210
remove original not a function error
lib/services/HttpClient.js
lib/services/HttpClient.js
'use strict'; var angular = require('camunda-bpm-sdk-js/vendor/angular'); var CamSDK = require('camunda-bpm-sdk-js/lib/angularjs/index'); module.exports = ['$rootScope', '$timeout' , '$q', function($rootScope, $timeout, $q) { function AngularClient(config) { this._wrapped = new CamSDK.Client.HttpClient(config); } angular.forEach(['post', 'get', 'load', 'put', 'del', 'options', 'head'], function(name) { AngularClient.prototype[name] = function(path, options) { var myTimeout = $timeout(function() {}, 100000); var original = options.done; options.done = function(err, result) { function applyResponse() { // in case the session expired if (err && err.status === 401) { // broadcast that the authentication changed $rootScope.$broadcast('authentication.changed', null); // set authentication to null $rootScope.authentication = null; // broadcast event that a login is required // proceeds a redirect to /login $rootScope.$broadcast('authentication.login.required'); return; } original(err, result); } var phase = $rootScope.$$phase; if(phase !== '$apply' && phase !== '$digest') { $rootScope.$apply(applyResponse); } else { applyResponse(); } $timeout.cancel(myTimeout); }; return $q.when( this._wrapped[name](path, options) ); }; }); angular.forEach(['on', 'once', 'off', 'trigger'], function(name) { AngularClient.prototype[name] = function() { this._wrapped[name].apply(this, arguments); }; }); return AngularClient; }];
JavaScript
0.000063
@@ -552,28 +552,78 @@ ginal = -options.done +angular.isFunction(options.done) ? options.done : angular.noop ;%0A%0A
9612eacb2dd9075aebc8c87e5882725d3742cb16
fix lookupOption to allow falsy values except undefined
lib/route_controller.js
lib/route_controller.js
/*****************************************************************************/ /* Imports */ /*****************************************************************************/ var Controller = Iron.Controller; var Url = Iron.Url; var MiddlewareStack = Iron.MiddlewareStack; /*****************************************************************************/ /* RouteController */ /*****************************************************************************/ RouteController = Controller.extend({ constructor: function (options) { RouteController.__super__.constructor.apply(this, arguments); this.options = options || {}; this._onStopCallbacks = []; this.init(options); } }); /** * Returns an option value following an "options chain" which is this path: * * this (which includes the proto chain) * this.options * this.route.options * this.router.options */ RouteController.prototype.lookupOption = function (key) { // "this" object or its proto chain if (this[key]) return this[key]; // this.options if (_.has(this.options, key)) return this.options[key]; // see if we have the CurrentOptions dynamic variable set. var opts = CurrentOptions.get(); if (opts && _.has(opts, key)) return opts[key]; // this.route.options if (this.route && this.route.options && _.has(this.route.options, key)) return this.route.options[key]; // this.router.options if (this.router && this.router.options && _.has(this.router.options, key)) return this.router.options[key]; }; /** * Returns an array of hook functions for the given hook names. Hooks are * collected in this order: * * router global hooks * route option hooks * prototype of the controller * this object for the controller * * For example, this.collectHooks('onBeforeAction', 'before') * will return an array of hook functions where the key is either onBeforeAction * or before. * * Hook values can also be strings in which case they are looked up in the * Iron.Router.hooks object. * * TODO: Add an options last argument which can specify to only collect hooks * for a particular environment (client, server or both). */ RouteController.prototype._collectHooks = function (/* hook1, alias1, ... */) { var self = this; var hookNames = _.toArray(arguments); var getHookValues = function (value) { if (!value) return []; var lookupHook = self.router.lookupHook; var hooks = _.isArray(value) ? value : [value]; return _.map(hooks, function (h) { return lookupHook(h); }); }; var collectInheritedHooks = function (ctor, hookName) { var hooks = []; if (ctor.__super__) hooks = hooks.concat(collectInheritedHooks(ctor.__super__.constructor, hookName)); return _.has(ctor.prototype, hookName) ? hooks.concat(getHookValues(ctor.prototype[hookName])) : hooks; }; var eachHook = function (cb) { for (var i = 0; i < hookNames.length; i++) { cb(hookNames[i]); } }; var routerHooks = []; eachHook(function (hook) { var name = self.route && self.route.getName(); var hooks = self.router.getHooks(hook, name); routerHooks = routerHooks.concat(hooks); }); var protoHooks = []; eachHook(function (hook) { var hooks = collectInheritedHooks(self.constructor, hook); protoHooks = protoHooks.concat(hooks); }); var thisHooks = []; eachHook(function (hook) { if (_.has(self, hook)) { var hooks = getHookValues(self[hook]); thisHooks = thisHooks.concat(hooks); } }); var routeHooks = []; if (self.route) { eachHook(function (hook) { var hooks = getHookValues(self.route.options[hook]); routeHooks = routeHooks.concat(hooks); }); } var allHooks = routerHooks .concat(routeHooks) .concat(protoHooks) .concat(thisHooks); return allHooks; }; RouteController.prototype.runHooks = function (/* hook, alias1, ...*/ ) { var hooks = this._collectHooks.apply(this, arguments); for (var i = 0, l = hooks.length; i < l; i++) { var h = hooks[i]; h.call(this); } }; Iron.RouteController = RouteController;
JavaScript
0
@@ -983,24 +983,31 @@ chain%0A if ( +typeof this%5Bkey%5D)%0A @@ -1003,16 +1003,32 @@ his%5Bkey%5D + !== 'undefined' )%0A re
d1326e6dfa94f6d49e76b7fd62b3a05e34cd6264
Use the session user to fetch org repos
lib/router/repo-info.js
lib/router/repo-info.js
/*jshint strict:true, trailing:false, unused:true, node:true */ 'use strict'; require("babel/register"); var GitHub = require('../github'); var redis = require('../redis'); var Repo = require('../repo'); module.exports = function(req, res) { var owner = req.params.owner; var name = req.params.repo; return redis.get(owner) .then( (token) => { var gh = new GitHub(token); var repo = new Repo(owner, name, gh); return repo.findDependencies() .then( (manifests) => { return Promise.all([ repo.fetchVersions(manifests), gh.get(`/repos/${owner}/${name}`) ]); }) .then( (values) => { let [manifests, _repo] = values; res.render('repo', {repo: _repo, manifests: manifests}); }); }) .catch( (err) => { console.log(err.stack); res.render('error'); }); };
JavaScript
0
@@ -324,19 +324,30 @@ dis.get( -own +req.session.us er)%0A .t @@ -784,24 +784,46 @@ (err) =%3E %7B%0A + console.log(err);%0A console.
f3adc3d330e7682bd26c5ad28f1e7dcb02632a4d
Tidy up
lib/sonaatti-scraper.js
lib/sonaatti-scraper.js
#!/usr/bin/env node var restaurants = ['aallokko', 'alvari', 'cafe-libri', 'lozzi', 'musica', 'piato', 'wilhelmiina', 'hestia', 'kvarkki', 'ylisto', 'novelli', 'normaalikoulu']; var apiPrefix = 'api'; var baseUrl = 'http://www.sonaatti.fi/'; var restify = require('restify'); var io = require('node.io'); function respond(req, res, next) { res.send(foodToday()); } var server = restify.createServer(); restaurants.forEach(function(restaurant) { server.get('/' + apiPrefix + '/' + restaurant + '/today', function(req, res) { foodToday(baseUrl + restaurant, function(data) { res.send(data); }); }) // TODO: specific days }); server.listen(8000, function() { console.log('%s listening at %s', server.name, server.url); }); function foodToday(url, done) { var job = new io.Job({ input: false, run: function() { this.getHtml(url, function(err, $) { if (err) throw err; var $p = $('.listapaikka'); var ret = []; $('.ruuat p', $p).each(function(k) { ret.push({food: k.text}); }); $('.hinnat', $p).text.split('\n').forEach(function(k, i) { ret[i].price = k; }); ret = ret.filter(function(k) { return k.food && k.price; }); this.emit(ret); }); } }); io.start( job, {}, function(err, output) { if (err) throw err; done(output); }, true ); } /* // other days $('.lista .ruuat p').each(function(k) { console.log(k.text); // TODO: split by , }); */
JavaScript
0.000027
@@ -304,24 +304,136 @@ node.io');%0A%0A +// TODO: --serve%0AfoodToday(baseUrl + 'piato', function(d) %7Bconsole.log(d);%7D);%0A// main();%0A%0Afunction main() %7B%0A function res @@ -455,24 +455,28 @@ next) %7B%0A + + res.send(foo @@ -486,19 +486,27 @@ day());%0A -%7D%0A%0A + %7D%0A%0A var serv @@ -534,16 +534,20 @@ rver();%0A + restaura @@ -585,16 +585,20 @@ ) %7B%0A + + server.g @@ -676,16 +676,20 @@ + foodToda @@ -725,24 +725,28 @@ ion(data) %7B%0A + @@ -769,24 +769,28 @@ + %7D);%0A %7D)%0A / @@ -785,15 +785,24 @@ + -%7D)%0A + %7D);%0A + // T @@ -820,21 +820,29 @@ ic days%0A + %7D);%0A%0A + server.l @@ -862,24 +862,28 @@ unction() %7B%0A + console. @@ -934,19 +934,25 @@ r.url);%0A + %7D); +%0A%7D %0A%0Afuncti
4fbbd142358bba34cabe104e6804ed5228dfea0b
check if path contains `/` at beginning
lib/util/escape-path.js
lib/util/escape-path.js
// Escape URI-sensitive chars, but leave forward slashes alone. module.exports = function escapePath(p) { return encodeURIComponent(p) .replace(/%2F/g, '/') .replace(/\)/g, '%29') .replace(/\(/g, '%28'); }
JavaScript
0.000001
@@ -105,14 +105,15 @@ %7B%0A -return +var p = enc @@ -212,10 +212,62 @@ '%2528');%0A + if (p%5B0%5D === '/') %7B p = p.slice(1); %7D%0A return p;%0A %7D%0A
1f989423cea21d3f75b7731b5b7665bc91722363
Load rabbitmq credentials from docker secret file
lib/utilities/config.js
lib/utilities/config.js
var nconf = require('nconf'); var path = require('path'); var getSecret = require('./docker-secrets').getDockerSecret; var argv = require('yargs') .option('app-config', { "alias": "a", "describe": "Configure EPP with JSON string", "string": true }).coerce('app-config', JSON.parse) .option("registries", { "alias": "r", "describe": "List of domain registries", "array": true }) .option("listen", { "alias": "l", "describe": "listen", "default": 3000, "number": true }).option("json", { "alias": "j", "describe": "JSON formatted logs", "default": false }).option('config-file', { "alias": "f", "describe": "Path to JSON config file" }).option('loglevel', { "describe": "Log level", "default": "info" }).option('rabbithost', { "describe": "RabbitMQ host" }).option('rabbitport', { "describe": "RabbitMQ port", "number": true, "default": 5672 }).option('epp_login', { "describe": "EPP login" }).option('epp_password', { "describe": "EPP password" }).option('rabbitlogin', { "describe": "Login for rabbitmq" }).option('rabbitpassword', { "describe": "Password for rabbitmq" }).option('vhost', { "describe": "vhost for rabbit", "default": "/" }).help('h').alias('h', 'help') .argv; module.exports.getConfig = function(file = "epp-config.json") { nconf.overrides(argv).env(); file = nconf.get('config-file') || file; var filePath = path.resolve(file); nconf.file(filePath); // Read secret files mounted by docker secret. let eppLoginFile = nconf.get('EPP_LOGIN_FILE'); let eppPasswordFile = nconf.get('EPP_PASSWORD_FILE'); if (eppLoginFile) { getSecret(eppLoginFile, (line) => { nconf.set('epp_login', line); }) } if (eppPasswordFile) { getSecret(eppPasswordFile, (line) => { nconf.set('epp_password', line); }) } return nconf; };
JavaScript
0
@@ -1614,16 +1614,140 @@ FILE');%0A + let rabbitmqUser = nconf.get('RABBITMQ_DEFAULT_USER_FILE');%0A let rabbitmqPass = nconf.get('RABBITMQ_DEFAULT_PASS_FILE');%0A if (ep @@ -1945,16 +1945,217 @@ %7D)%0A %7D%0A + if (rabbitmqUser) %7B%0A getSecret(rabbitmqUser, (line) =%3E %7B nconf.set('rabbitlogin', line)%7D)%0A %7D%0A if (rabbitmqPass) %7B%0A getSecret(rabbitmqPass, (line) =%3E %7B nconf.set('rabbitpassword', line)%7D)%0A %7D%0A return
b3ffd237a7993897d56ec309f6b70c3b35281b6a
Update up to changes in es5-ext
lib/utils/index-test.js
lib/utils/index-test.js
'use strict'; var fs = require('fs') , normalize = require('path').normalize , curry = require('es5-ext/lib/Function/prototype/curry') , contains = curry.call(require('es5-ext/lib/Array/prototype/contains')) , noop = require('es5-ext/lib/Function/noop') , not = require('es5-ext/lib/Function/prototype/not') , oForEach = require('es5-ext/lib/Object/for-each') , convert = require('es5-ext/lib/String/prototype/dash-to-camel-case') , a2p = require('deferred').promisify , isPromise = require('deferred/lib/is-promise') , readDir; readDir = function (dir) { var i, o = {}; if (isPromise(dir)) { return dir; } dir = normalize(dir); return a2p(fs.readdir)(dir).map(function (f) { return a2p(fs.stat)(dir + '/' + f)(function (stats) { if (stats.isFile()) { if ((f.slice(-3) !== '.js') || (f === 'index.js') || (f[0] === '_')) { return; } f = f.slice(0, -3); } else if (!stats.isDirectory()) { return; } o[convert.call(f)] = normalize(dir + '/' + f); }, noop); })(o); }; module.exports = function (dir, ignores) { return function (t, a, d) { readDir(dir)(function (o) { var keys = Object.keys(t); if (ignores) { keys = keys.filter(not.call(contains), ignores); } oForEach(o, function (path, f) { var i, fc; if ((i = keys.indexOf(f)) === -1) { fc = f.charAt(0).toUpperCase() + f.slice(1); if ((i = keys.indexOf(fc)) === -1) { a.ok(false, f + " - is present ?"); } else { a.ok(true, (f = fc) + " - is present ?"); } } else { a.ok(true, f + " - is present ?"); } if (i !== -1) { keys.splice(i, 1); a(t[f], require(path), f + " - points its module ?"); } }); a.ok(keys.length === 0, "[" + keys.toString() + "] - no extras found ?"); d(); }).end(); }; }; module.exports.readDir = readDir;
JavaScript
0
@@ -448,12 +448,14 @@ ype/ -dash +hyphen -to- @@ -463,13 +463,8 @@ amel --case ')%0A
8d06698669ae8a93893315d416b6676a01a89ff2
Rearrange ErrorView buttons
lib/views/error-view.js
lib/views/error-view.js
import React from 'react'; import PropTypes from 'prop-types'; export default class ErrorView extends React.Component { static propTypes = { title: PropTypes.string, descriptions: PropTypes.arrayOf(PropTypes.string), preformatted: PropTypes.bool, retry: PropTypes.func, logout: PropTypes.func, openDevTools: PropTypes.func, } static defaultProps = { title: 'Error', descriptions: ['An unknown error occurred'], preformatted: false, } render() { return ( <div className="github-Message"> <div className="github-Message-wrapper"> <h1 className="github-Message-title">{this.props.title}</h1> {this.props.descriptions.map(this.renderDescription)} <div className="github-Message-action"> {this.props.openDevTools && ( <button className="github-Message-button btn btn-devtools" onClick={this.props.openDevTools}> Open dev tools </button> )} {this.props.retry && ( <button className="github-Message-button btn btn-primary" onClick={this.props.retry}>Try Again</button> )} {this.props.logout && ( <button className="github-Message-button btn btn-logout" onClick={this.props.logout}>Logout</button> )} </div> </div> </div> ); } renderDescription = (description, key) => { if (this.props.preformatted) { return ( <pre key={key} className="github-Message-description"> {description} </pre> ); } else { return ( <p key={key} className="github-Message-description"> {description} </p> ); } } }
JavaScript
0.000001
@@ -770,24 +770,192 @@ ge-action%22%3E%0A + %7Bthis.props.retry && (%0A %3Cbutton className=%22github-Message-button btn btn-primary%22 onClick=%7Bthis.props.retry%7D%3ETry Again%3C/button%3E%0A )%7D%0A @@ -1164,176 +1164,8 @@ )%7D%0A - %7Bthis.props.retry && (%0A %3Cbutton className=%22github-Message-button btn btn-primary%22 onClick=%7Bthis.props.retry%7D%3ETry Again%3C/button%3E%0A )%7D%0A
394999c50829e833dbe1669aef3f274d2265dfe6
Update tests
__tests__/components/Languages-test.js
__tests__/components/Languages-test.js
jest.dontMock('../../components/Languages.js'); var React = require('react'); var TestUtils = require('react-addons-test-utils'); var languagesComponent = React.createFactory(require('../../components/Languages')); describe('Languages component test suite', function () { var component; describe('for an empty languages props', function () { beforeEach(function () { component = TestUtils.renderIntoDocument( languagesComponent() ); }); it('renders the heading', function () { var h2 = TestUtils.findRenderedDOMComponentWithTag(component, 'h2'); expect(h2.getDOMNode().textContent).toEqual('Languages'); }); it('renders NO DL element', function () { var dl = TestUtils.scryRenderedDOMComponentsWithTag(component, 'dl'); expect(dl.length).toBe(0); }); }); describe('for a list of languages props', function () { var languages = [ { language: "English", fluency: "Native speaker" }, { language: "Indonesian", fluency: "Ignorant tourist" } ]; var h2, dl, dts; beforeEach(function () { component = TestUtils.renderIntoDocument( languagesComponent({ languages: languages }) ); h2 = TestUtils.findRenderedDOMComponentWithTag(component, 'h2'); dl = TestUtils.scryRenderedDOMComponentsWithTag(component, 'dl'); dts = TestUtils.scryRenderedDOMComponentsWithTag(component, 'dt'); dds = TestUtils.scryRenderedDOMComponentsWithTag(component, 'dd'); }); it('renders the heading', function () { expect(h2.getDOMNode().textContent).toEqual('Languages'); }); it('renders 1 DL element', function () { expect(dl.length).toBe(1); }); it('renders 2 dt elements', function () { expect(dts.length).toBe(2); }); it('renders 2 dd elements', function () { expect(dds.length).toBe(2); }); it('renders "English" into the first dt', function () { expect(dts[0].getDOMNode().textContent).toEqual('English'); }); it('renders "Ignorant tourist" into the second dd', function () { expect(dds[1].getDOMNode().textContent).toEqual('Ignorant tourist'); }); }); });
JavaScript
0.000001
@@ -72,16 +72,53 @@ eact');%0A +var ReactDOM = require('react-dom');%0A var Test @@ -157,24 +157,24 @@ st-utils');%0A - %0Avar languag @@ -610,38 +610,45 @@ ;%0A%09%09%09expect( -h2.get +ReactDOM.find DOMNode( ).textConten @@ -627,32 +627,34 @@ DOM.findDOMNode( +h2 ).textContent).t @@ -1548,22 +1548,29 @@ ect( -h2.get +ReactDOM.find DOMNode( ).te @@ -1557,32 +1557,34 @@ DOM.findDOMNode( +h2 ).textContent).t @@ -1927,26 +1927,29 @@ ect( -dts%5B0%5D.get +ReactDOM.find DOMNode( ).te @@ -1936,32 +1936,38 @@ DOM.findDOMNode( +dts%5B0%5D ).textContent).t @@ -2074,26 +2074,35 @@ ect( -dds%5B1%5D.getDOMNode( +ReactDOM.findDOMNode(dds%5B1%5D ).te
a2497d0cc85505cb5c68fcd351d23369fd1e5f7c
Resolve strange kalastack_url inconsistency between installer/updater
kalabox/updater.js
kalabox/updater.js
/** * @file * Update mechanism for Kalabox's dependencies. * * Copyright 2013 Kalamuna LLC */ // Dependencies: var fs = require('fs'), exec = require('child_process').exec, request = require('request'), flow = require('nue').flow, as = require('nue').as, config = require('../config'), box = require('./box'), installUtils = require('./installer/install-utils'), logger = require('../logger'), removeDir = require('rimraf').sync; // "Constants": var UPDATE_URL = config.get('UPDATE_URL'), KALASTACK_BASE_URL = config.get('KALASTACK_BASE_URL'), KALASTACK_DIR = config.get('KALASTACK_DIR'), DEPENDENCIES = [ 'terminatur' ], KEEP_FILES = [ '.kalabox', '.vagrant', 'config.json' ]; // Variables: var configFileContents = null, configuration = {}, dependenciesUpdate = false, kalastackUpdate = false, socket; /** * Checks the canonical online source for updates. */ exports.checkForUpdates = flow('checkForUpdates')( function checkForUpdates0(callback) { this.data.callback = callback; // Download the updates file. request(UPDATE_URL, this.async(as(2))); }, function checkForUpdates1(body) { // Parse the updates and read in the current config. configFileContents = body; configuration = JSON.parse(body); var currentConfig = {}; if (fs.existsSync(KALASTACK_DIR + 'config.json')) { currentConfig = JSON.parse(fs.readFileSync(KALASTACK_DIR + 'config.json')); } // Check the dependencies and Kalastack versions against the latest ones. DEPENDENCIES.forEach(function(dependency) { if (currentConfig[dependency + '_version'] != configuration[dependency + '_version']) { dependenciesUpdate = true; return false; } }); if (currentConfig['kalastack_version'] != configuration['kalastack_version']) { kalastackUpdate = true; } this.next(dependenciesUpdate || kalastackUpdate); }, function checkForUpdatesEnd(needsUpdate) { if (this.err) { logger.warn('Updates check failed: ' + this.err.message); this.err = null; this.data.callback(false); } else { this.data.callback(needsUpdate); } this.next(); } ); /** * Updates any out of date dependencies. */ exports.update = flow('update')( function update0(callback) { this.data.callback = callback; // Connect to the UI. io.sockets.on('connection', this.async(as(0))); }, function update1(newSocket) { socket = newSocket; sendMessage('You Gone Get Updated!...'); sendIcon('fa fa-download', 'kalagreen'); sendProgress(25); // Write the new configuration file. fs.writeFileSync(KALASTACK_DIR + 'config.json', configFileContents); // Halt the box. box.stopBox(this.async()); }, function update1() { // Refresh Kalastack if there's an update. sendIcon('fa fa-cog fa-spin', 'kalablue'); sendProgress(40); if (kalastackUpdate) { refreshKalastack(this.async()); } else { this.next(); } }, function update2() { // Provision and start the box. sendProgress(77); installUtils.spinupBox(this.async()); }, function updateEnd() { if (this.err) { if (this.data.callback) { this.data.callback(this.err); } this.err = null; } else if (this.data.callback) { this.data.callback(); } sendProgress(100); socket.emit('updatesComplete'); this.next(); } ); /** * Replaces the Kalastack source code on the host with that of the latest version. */ var refreshKalastack = flow('refreshKalastack')( function refreshKalastack0(callback) { this.data.callback = callback; // @todo switch to os.tmpdir() once we upgrade Node past 0.8. this.data.temp = process.env['TMPDIR']; // Delete the old Kalastack files. files = fs.readdirSync(KALASTACK_DIR); files.forEach(function(file) { if (KEEP_FILES.indexOf(file) !== -1) { return true; } var filePath = KALASTACK_DIR + file, fileInfo = fs.statSync(filePath); if (fileInfo.isDirectory()) { removeDir(filePath); } else { fs.unlinkSync(filePath); } }); // Download the new Kalastack files. var kalastackRequest = request(KALASTACK_BASE_URL + configuration['kalastack_version']); kalastackRequest.on('end', this.async()); kalastackRequest.pipe(fs.createWriteStream(this.data.temp + 'kalastack.tar.gz')); }, function refreshKalastack1() { // Extract the new Kalastack files. var temp = this.data.temp; if (!fs.existsSync(temp + 'kalastack')) { fs.mkdirSync(temp + 'kalastack'); } exec('tar zxvf ' + temp + 'kalastack.tar.gz -C ' + temp + 'kalastack --strip-components 1', this.async()); }, function refreshKalastack2() { // Move the new files into place. var temp = this.data.temp, newFiles = fs.readdirSync(temp + 'kalastack'); newFiles.forEach(function(file) { var filePath = temp + 'kalastack/' + file; fs.renameSync(filePath, KALASTACK_DIR + file); }); this.next(); }, function refreshKalastackEnd() { if (this.err) { this.data.callback(this.err); this.err = null; } else { this.data.callback(); } this.next(); } ); /* UI Interaction Functions */ function sendMessage(message) { socket.emit('installer', { message: message }); } function sendIcon(icon, kalacolor) { socket.emit('installer', { icon: icon, kalacolor: kalacolor}); } function sendProgress(progress, install) { socket.emit('installer', { complete: progress }); }
JavaScript
0
@@ -629,24 +629,178 @@ TACK_DIR'),%0A + KALASTACK_VERSION = config.kalastack.get('kalastack_version'),%0A KALASTACK_URL = KALASTACK_BASE_URL + 'kalastack-' + KALASTACK_VERSION + '.tar.gz',%0A DEPENDEN @@ -4489,53 +4489,11 @@ ACK_ -BASE_URL + configuration%5B'kalastack_version'%5D +URL );%0A
f95c49edb3637a91b9e2c7d4b17c405c3eb5ebb6
refresh button
Resources/layouts/ipad/nav.js
Resources/layouts/ipad/nav.js
Layouts.ipad.nav = function(main_content, main_window) { var nav_view = Ti.UI.createView({ backgroundImage:"images/nav/NCR_iPad2_button_row_bg.png", top:189, height:122, left:0, right:0 }); var schedules_button = Ti.UI.createButton({ backgroundImage:"images/nav/NCR_iPad_schedule_btn_inactive.png", backgroundSelectedImage:"images/nav/NCR_iPad_schedule_btn_active.png", top:23, left:24, height:83, width:228, id: 'schedules' }); var maps_button = Ti.UI.createButton({ backgroundImage:"images/nav/NCR_iPad_events_btn_inactive.png", backgroundSelectedImage:"images/nav/NCR_iPad_events_btn_active.png", top:23, right:24, height:83, width:228, id: 'maps' }); var speakers_button = Ti.UI.createButton({ backgroundImage:"images/nav/NCR_iPad_speakers_btn_inactive.png", backgroundSelectedImage:"images/nav/NCR_iPad_speakers_btn_active.png", top:23, height:83, width:228, id: 'speakers' }); var activity = Helpers.ui.spinner(); activity.show(); var button_group = UI.ButtonGroup(speakers_button, schedules_button); schedules_button.addEventListener('click', App.swapView(main_content, "sessions#index")); speakers_button.addEventListener('click', App.swapView(main_content, "speakers#index")); maps_button.addEventListener('click', App.action.p(main_window, "maps#index")); refresh_view.add(activity); refresh_view.add(refresh_button); nav_view.add(schedules_button); nav_view.add(maps_button); nav_view.add(speakers_button); schedules_button.fireEvent('click', {}); Ti.App.addEventListener("apiUpdateStart", function(e) { refresh_button.visible = false; }); Ti.App.addEventListener("apiUpdateFinish", function(e) { refresh_button.visible = true; button_group.activeButton().fireEvent('click', e); }); return nav_view; }
JavaScript
0.000001
@@ -1546,105 +1546,8 @@ );%0A%09 -%0A%09Ti.App.addEventListener(%22apiUpdateStart%22, function(e) %7B%0A%09%09refresh_button.visible = false;%0A%09%7D);%0A %09%0A%09T @@ -1606,41 +1606,8 @@ ) %7B%0A -%09%09refresh_button.visible = true;%0A %09%09bu
d14ac4cb067e0e69e9e286b738c222ec1ce189b9
increase verbosity of persisted logs
src/server/logger.js
src/server/logger.js
import { join } from "path" import { format, inspect } from "util" import { Writable } from "stream" import bunyan from "bunyan" import { environment } from "./environment" const logPath = join(process.cwd(), "log", environment) let logger = null export default function() { if (logger === null) { logger = createLogger() } return logger } function createLogger() { let streams = createStreams() let logger = bunyan.createLogger({ name: environment, streams: streams }) process.on("uncaughtException", (err) => { logger.error({ err }, `Uncaught Exception: ${inspect(err)}`); }) return logger } function createStreams() { let streams = [{ path: logPath }] if (environment === "development") { streams.push({ type: "raw", level: "info", stream: new Writable({ objectMode: true, write: (obj, _, cb) => { process.stdout.write(`${obj.time}: ${obj.msg}\n`) cb() } }) }) } return streams }
JavaScript
0
@@ -691,16 +691,32 @@ logPath +, level: %22debug%22 %7D%5D%0A%0A i
11f80d5ba0cb82e20e17b22484dc4d9a172eff1f
Load all enum files in the Plugin class to expose for plugins
classes/Plugin.js
classes/Plugin.js
var Path = require('path'), fs = require('fs-extra'), {app} = require('electron'); module.exports = function(pluginName) { const pluginPath = Path.resolve('plugins', pluginName); return { require: (name) => { return require(Path.resolve('./', name)); }, event: { on: function(eventName, fn) { app.pluginSystem.listeners[eventName] = app.pluginSystem.listeners[eventName] || []; app.pluginSystem.listeners[eventName].push(fn); }, send: (eventName, eventData) => { if(app.Events[eventName]) { app.Events[eventName](eventName, eventData); } } }, window: { register: function(manifest) { if(typeof manifest === 'string') { manifest = fs.readJsonSync(Path.resolve(pluginPath, manifest)); } // Now we have that manifest is a JSON object manifest.path = Path.resolve(pluginPath, manifest.path); app.Events['registerWindow'](null, manifest); } }, settings: { setGlobal: function(name, data) { app.Events['setGlobalSetting'](null, { name: name, data: data }); }, setLocal: function(name, data) { app.Events['setLocalSetting'](null, { plugin: pluginName, name: name, data: data }); } } }; }
JavaScript
0
@@ -190,22 +190,28 @@ );%0A%0A -return +var plugin = %7B%0A @@ -1641,14 +1641,407 @@ %7D -%0A %7D; +,%0A enums: %7B%7D%0A %7D;%0A%0A // Load all enums in the ./enum directory and set plugin.enums%0A const enumFiles = fs.readdirSync( './enum' );%0A enumFiles.forEach((enumFile) =%3E %7B%0A const enumFileNameWithoutExt = enumFile.split('.js')%5B0%5D;%0A%0A plugin.enums%5BenumFileNameWithoutExt%5D = require(%0A Path.join(app.getAppPath(), 'enum', enumFile)%0A );%0A %7D);%0A%0A return plugin %0A%7D%0A
99a4a3666abc6183e74f4b830fd6f0ae5890e1bf
Print Button
js/OpenGraph.js
js/OpenGraph.js
// Called when the page is ready and loaded $(document).ready(function() { // ------------------------------------------- // --- OpenGraphAppPaper.js Initialization --- // ------------------------------------------- board = JXG.JSXGraph.initBoard('myBox', { boundingbox: [-10, 12, 10, -10], axis: { ticks: { drawLabels: true }, firstArrow: true, strokeColor: 'black' }, grid: { strokeWidth: 0.75 }, showCopyright: false, showNavigation: false, keepaspectratio: true, //square graph coming in zoom: { wheel: true, needshift: false }, pan: { enabled: true, // Allow panning needTwoFingers: false, // panningis done with two fingers on touch devices needshift: false // mouse panning needs pressing of the shift key } }); board.resizeContainer($(window).width(), $(window).height()); //init resize centerOrigin(); // init center board.on("move", onBoardMovement); $("#resetHome").click(function () { centerOrigin(); }); $("#resetZoom").click(function () { board.zoom100(); }); $("#zoomIn").click(function () { board.zoomIn(); }); $("#zoomOut").click(function () { board.zoomOut(); }); // Called when the zoom type / toggle zoom type button has been clicked $("#toggleZoomType").click(function () { // Variables var zt = $("#zoomType").text().trim().toLowerCase(); switch (zt) { case "xy": $("#zoomType").html("&nbsp;x"); board.attr.zoom.factorx = 1.25; board.attr.zoom.factory = 1.0; break; case "x": $("#zoomType").html("&nbsp;y"); board.attr.zoom.factorx = 1.0; board.attr.zoom.factory = 1.25; break; case "y": $("#zoomType").html("xy"); board.attr.zoom.factorx = 1.25; board.attr.zoom.factory = 1.25; break; } }); // ----------------------------------- // --- OpenGraph.js Initialization --- // ----------------------------------- // Also OpenGraph's on load function gets called first, because it was positioned before the entry one //if(location.hash!= "") //updateEntry($(".entry")[0], location.hash.substring(1)); // Page Buttons $("#dockButton").click(onCollapseCollapser); $("#header").html("<em>OpenGraphingCalculator <sub>&alpha; 0.20</sub></em>"); $("#addNewEntry").on("click", constructNewEntry); $("#deleteAll").on("click", clearAll); $("#dockRight").on("click", collapseAll); // ------------------------------------------- // --- OpenGraphAppEntry.js Initialization --- // ------------------------------------------- // 1. add event listeners to the form $(".myForm" ).on("click", ".btn-remove", onRemoveClick ).on("click", ".map", onMapClick ).on("click", ".showColor", onShowColorClick ).on("mouseover", ".grabber", makeDraggable // TODO: make touch friendly ).on("mouseout", ".grabber", makeUnDraggable // TODO: make touch friendly ).on("click", ".dashed", onDashedClick ).on("click", ".mathinput", onMathInputClick ).on("click", ".drawer1", onDrawerClick ).on("keyup", ".entry", onEntryKeyUp ).on("click", ".collapse-entry", onCollapseEntryClick ).on("click", ".thicknessPlus", onThicknessPlusClick ).on("click", ".thicknessMinus", onThicknessMinusClick ).on("click", ".tangentLine", onTangentLineClick ).on("click", ".derivative", onDerivativeClick ).on("click", ".roots", onRootsClick ).on("click", ".integral", onIntegralClick); // 2. Construct first entry in the form //set global mathquill behavior MathQuill.addAutoCommands('pi theta sqrt sum'); blankEntry = $(".entry"); // initial entry (global jquery Object constant) blankEntry.remove(); constructNewEntry(); if(location.hash!= "") updateEntry($(".entry")[0], location.hash.substring(1)); else if(location.search!= "") { // Variables var sterms= location.search.substring(1); var temp= sterms.split('&'); var k= 0; for(var i= 0; i< temp.length; i++) { if(i< temp.length-1) { constructNewEntry(); } updateEntry($(".entry")[k], temp[i].trim()); k++; } } }); // Called when the collapser has collapsed a collapsible collapser function onCollapseCollapser(e) { // Variables var parent= $($(e.target).parents(".controlContainer")[0]); var cc= parent.find(".buttons")[0]; if(cc.style.visibility== "hidden") { cc.style.visibility= "visible"; cc.style.display= "block"; $(this).find(".glyphicon").removeClass("glyphicon-menu-left").addClass("glyphicon-menu-right"); } else { cc.style.visibility= "hidden"; cc.style.display= "none"; $(this).find(".glyphicon").removeClass("glyphicon-menu-right").addClass("glyphicon-menu-left"); parent.css({right: "0px"}); } } // Writes into the given entry with the given string function updateEntry(entry, str, usesLatex) { MathQuill($(entry).find(".math-field")[0]).latex(str); // Simulates a key up to render the graph onEntryKeyUp( { target: $(entry).find(".math-field")[0], keyCode: 0 }); } // End of File
JavaScript
0.000078
@@ -2047,24 +2047,652 @@ %7D%0A %7D);%0A + $(%22#print%22).click(function () %7B%0A board.renderer.svgRoot.setAttribute(%22xmlns%22, %22http://www.w3.org/2000/svg%22);%0A var svg = board.renderer.svgRoot;%0A var svgData = new XMLSerializer().serializeToString(svg);%0A%0A // having trouble changing this to PNG%0A // need to create a canvas or something%0A // http://jsxgraph.uni-bayreuth.de/wp/2012/11/02/howto-export-jsxgraph-constructions/ %0A var w = window.open();%0A w.document.write(%22%3Ch1%3EYour Graph%3C/h1%3E%22);%0A //console.log(svgData);%0A w.document.write(svgData);%0A //w.document.write(%22%3Cimg src=%22+png+%22%3E%22);%0A%0A%0A %7D);%0A%0A%0A%0A // -----
19c007901d7b4397c9d35ae1beb2cc386bbb4438
Add warning for undefined connection file (#5223)
lib/dialects/sqlite3/index.js
lib/dialects/sqlite3/index.js
// SQLite3 // ------- const defaults = require('lodash/defaults'); const map = require('lodash/map'); const { promisify } = require('util'); const Client = require('../../client'); const Raw = require('../../raw'); const Transaction = require('./execution/sqlite-transaction'); const SqliteQueryCompiler = require('./query/sqlite-querycompiler'); const SchemaCompiler = require('./schema/sqlite-compiler'); const ColumnCompiler = require('./schema/sqlite-columncompiler'); const TableCompiler = require('./schema/sqlite-tablecompiler'); const ViewCompiler = require('./schema/sqlite-viewcompiler'); const SQLite3_DDL = require('./schema/ddl'); const Formatter = require('../../formatter'); const QueryBuilder = require('./query/sqlite-querybuilder'); class Client_SQLite3 extends Client { constructor(config) { super(config); if (config.useNullAsDefault === undefined) { this.logger.warn( 'sqlite does not support inserting default values. Set the ' + '`useNullAsDefault` flag to hide this warning. ' + '(see docs https://knexjs.org/guide/query-builder.html#insert).' ); } } _driver() { return require('sqlite3'); } schemaCompiler() { return new SchemaCompiler(this, ...arguments); } transaction() { return new Transaction(this, ...arguments); } queryCompiler(builder, formatter) { return new SqliteQueryCompiler(this, builder, formatter); } queryBuilder() { return new QueryBuilder(this); } viewCompiler(builder, formatter) { return new ViewCompiler(this, builder, formatter); } columnCompiler() { return new ColumnCompiler(this, ...arguments); } tableCompiler() { return new TableCompiler(this, ...arguments); } ddl(compiler, pragma, connection) { return new SQLite3_DDL(this, compiler, pragma, connection); } wrapIdentifierImpl(value) { return value !== '*' ? `\`${value.replace(/`/g, '``')}\`` : '*'; } // Get a raw connection from the database, returning a promise with the connection object. acquireRawConnection() { return new Promise((resolve, reject) => { // the default mode for sqlite3 let flags = this.driver.OPEN_READWRITE | this.driver.OPEN_CREATE; if (this.connectionSettings.flags) { if (!Array.isArray(this.connectionSettings.flags)) { throw new Error(`flags must be an array of strings`); } this.connectionSettings.flags.forEach((_flag) => { if (!_flag.startsWith('OPEN_') || !this.driver[_flag]) { throw new Error(`flag ${_flag} not supported by node-sqlite3`); } flags = flags | this.driver[_flag]; }); } const db = new this.driver.Database( this.connectionSettings.filename, flags, (err) => { if (err) { return reject(err); } resolve(db); } ); }); } // Used to explicitly close a connection, called internally by the pool when // a connection times out or the pool is shutdown. async destroyRawConnection(connection) { const close = promisify((cb) => connection.close(cb)); return close(); } // Runs the query on the specified connection, providing the bindings and any // other necessary prep work. _query(connection, obj) { if (!obj.sql) throw new Error('The query is empty'); const { method } = obj; let callMethod; switch (method) { case 'insert': case 'update': case 'counter': case 'del': callMethod = 'run'; break; default: callMethod = 'all'; } return new Promise(function (resolver, rejecter) { if (!connection || !connection[callMethod]) { return rejecter( new Error(`Error calling ${callMethod} on connection.`) ); } connection[callMethod](obj.sql, obj.bindings, function (err, response) { if (err) return rejecter(err); obj.response = response; // We need the context here, as it contains // the "this.lastID" or "this.changes" obj.context = this; return resolver(obj); }); }); } _stream(connection, obj, stream) { if (!obj.sql) throw new Error('The query is empty'); const client = this; return new Promise(function (resolver, rejecter) { stream.on('error', rejecter); stream.on('end', resolver); return client ._query(connection, obj) .then((obj) => obj.response) .then((rows) => rows.forEach((row) => stream.write(row))) .catch(function (err) { stream.emit('error', err); }) .then(function () { stream.end(); }); }); } // Ensures the response is returned in the same format as other clients. processResponse(obj, runner) { const ctx = obj.context; const { response, returning } = obj; if (obj.output) return obj.output.call(runner, response); switch (obj.method) { case 'select': return response; case 'first': return response[0]; case 'pluck': return map(response, obj.pluck); case 'insert': { if (returning) { if (response) { return response; } // ToDo Implement after https://github.com/microsoft/vscode-node-sqlite3/issues/15 is resolved this.logger.warn( 'node-sqlite3 does not currently support RETURNING clause' ); } return [ctx.lastID]; } case 'del': case 'update': case 'counter': return ctx.changes; default: { return response; } } } poolDefaults() { return defaults({ min: 1, max: 1 }, super.poolDefaults()); } formatter(builder) { return new Formatter(this, builder); } values(values, builder, formatter) { if (Array.isArray(values)) { if (Array.isArray(values[0])) { return `( values ${values .map( (value) => `(${this.parameterize(value, undefined, builder, formatter)})` ) .join(', ')})`; } return `(${this.parameterize(values, undefined, builder, formatter)})`; } if (values instanceof Raw) { return `(${this.parameter(values, builder, formatter)})`; } return this.parameter(values, builder, formatter); } } Object.assign(Client_SQLite3.prototype, { dialect: 'sqlite3', driverName: 'sqlite3', }); module.exports = Client_SQLite3;
JavaScript
0
@@ -828,16 +828,336 @@ onfig);%0A +%0A if (config.connection && config.connection.filename === undefined) %7B%0A this.logger.warn(%0A 'Could not find %60connection.filename%60 in config. Please specify ' +%0A 'the database path and name to avoid errors. ' +%0A '(see docs https://knexjs.org/guide/#configuration-options)'%0A );%0A %7D%0A%0A if (
076d16226a4b77449d6b5f82a2cb5b5070b4f503
change SW route
src/server/server.js
src/server/server.js
import 'babel-polyfill' import path from 'path' import { Server } from 'http' import Express from 'express' // eslint-disable-line import React from 'react' import { renderToString } from 'react-dom/server' import { match, RouterContext } from 'react-router' import { createStore } from 'redux' import { Provider } from 'react-redux' import csshook from 'css-modules-require-hook/preset' // eslint-disable-line import routes from '../shared/views/routes' import NotFoundPage from '../shared/views/PageNotFound/PageNotFound' import rootReducer from '../shared/views/rootReducer' const app = new Express() const server = new Server(app) if (process.env.SSLONLY === 'true') { app.use((req, res, next) => { if (req.header('x-forwarded-proto') !== 'https') { return res.redirect(`https://${req.get('Host')}${req.url}`) } return next() }) } app.get('/static/sw.js', (req, res) => { res.set('Service-Worker-Allowed', '/demo') return res.sendFile(path.resolve(__dirname, '/dist/static/sw.js')) }) // define the folder that will be used for static assets app.use(Express.static(path.resolve(process.cwd(), 'dist'))) // universal routing and rendering app.get('*', (req, res) => { const store = createStore(rootReducer) const initialState = store.getState() match( { routes, location: req.url }, (err, redirectLocation, renderProps) => { // in case of error display the error message if (err) { return res.status(500).send(err.message) } // in case of redirect propagate the redirect to the browser if (redirectLocation) { return res.redirect(302, redirectLocation.pathname + redirectLocation.search) } // generate the React markup for the current route let markup if (renderProps) { // get base url renderProps.location.baseUrl = req.headers.host //eslint-disable-line // console.log('render props', renderProps) // console.log('req url', req.headers.host) // if the current route matched we have renderProps markup = renderToString( <Provider store={store}> <RouterContext {...renderProps} /> </Provider>) } else { // otherwise we can render a 404 page markup = renderToString(<NotFoundPage />) res.status(404) } // render the index template with the embedded React markup return res.send(renderFullPage(markup, initialState)) } ) }) // TODO: We should use FS to read the index.html generated by webpack // and insert the html in there. function renderFullPage(html, preloadedState) { return ` <!doctype html> <html> <head> <title>Indepth Demo</title> <base href="/" /> <meta charset="utf-8"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="Expires" content="0"> <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1"/> <meta name="apple-mobile-web-app-capable" content="yes"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.css"/> <link rel="stylesheet" href="/common.css"/> <link rel="manifest" href="/static/manifest.json"> <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Open+Sans:300,400,400i,700|Roboto|Material+Icons"> <style> * { box-sizing: border-box; } html, body, #root { width: 100%; height: 100%; } html { -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; font-family: 'Open Sans', 'Roboto', Helvetica, sans-serif; color: #686868; } body, #root { position: relative; } </style> </head> <body> <script> window.__PRELOADED_STATE__ = ${JSON.stringify(preloadedState)} </script> <div id="root">${html}</div> <script src="/js/bundle.js"></script> </body> </html> ` } const port = process.env.PORT || 3000 const env = process.env.NODE_ENV || 'production' server.listen(port, err => { if (err) { return console.error(err) } return console.info(`Server running on http://localhost:${port} [${env}]`) })
JavaScript
0.000001
@@ -988,16 +988,21 @@ rname, ' +../.. /dist/st
39569c7b2a45b8a16dac596f2e9f0a65e7e503d7
Remove unused SKIP for websql
lib/dialects/websql/runner.js
lib/dialects/websql/runner.js
// Runner // ------- module.exports = function(client) { var Promise = require('../../promise'); // Require the SQLite3 Runner. require('../sqlite3/runner')(client); var Runner_SQLite3 = client.Runner; var inherits = require('inherits'); var _ = require('lodash'); // Inherit from the `Runner` constructor's prototype, // so we can add the correct `then` method. function Runner_WebSQL() { Runner_SQLite3.apply(this, arguments); } inherits(Runner_WebSQL, Runner_SQLite3); // Runs the query on the specified connection, providing the bindings and any other necessary prep work. Runner_WebSQL.prototype._query = Promise.method(function(obj) { if (this.isDebugging()) this.debug(obj); if (obj.sql === SKIP) { return Promise.resolve(obj); } var connection = this.connection; return new Promise(function(resolver, rejecter) { if (!connection) { return rejecter(new Error('No connection provided.')); } connection.executeSql(obj.sql, obj.bindings, function(trx, response) { obj.response = response; return resolver(obj); }, function(trx, err) { console.error(err); rejecter(err); }); }); }); // Null out the transaction statements so they aren't run. Runner_WebSQL.prototype._beginTransaction = null; Runner_WebSQL.prototype._commitTransaction = null; Runner_WebSQL.prototype._rollbackTransaction = null; // Ensures the response is returned in the same format as other clients. Runner_WebSQL.prototype.processResponse = function(obj) { var resp = obj.response; if (obj.output) return obj.output.call(this, resp); switch (obj.method) { case 'pluck': case 'first': case 'select': var results = []; for (var i = 0, l = resp.rows.length; i < l; i++) { results[i] = _.clone(resp.rows.item(i)); } if (obj.method === 'pluck') results = _.pluck(results, obj.pluck); return obj.method === 'first' ? results[0] : results; case 'insert': return [resp.insertId]; case 'delete': case 'update': case 'counter': return resp.rowsAffected; default: return resp; } }; // Assign the newly extended `Runner` constructor to the client object. client.Runner = Runner_WebSQL; };
JavaScript
0.000001
@@ -696,71 +696,8 @@ j);%0A - if (obj.sql === SKIP) %7B%0A return Promise.resolve(obj);%0A %7D%0A va
7cdbe4ededf2cc84f9eb1f9cedc439ba425e696c
fix buggy dispose in TimerNode, https://github.com/phetsims/scenery-phet/issues/430
js/TimerNode.js
js/TimerNode.js
// Copyright 2014-2018, University of Colorado Boulder /** * Shows a readout of the elapsed time, with play and pause buttons. By default there are no units (which could be used * if all of a simulations time units are in 'seconds'), or you can specify a selection of units to choose from. * * @author Jonathan Olson <[email protected]> * @author Sam Reid (PhET Interactive Simulations) * @author Anton Ulyanov (Mlearner) */ define( function( require ) { 'use strict'; // modules var BooleanRectangularToggleButton = require( 'SUN/buttons/BooleanRectangularToggleButton' ); var inherit = require( 'PHET_CORE/inherit' ); var Node = require( 'SCENERY/nodes/Node' ); var Path = require( 'SCENERY/nodes/Path' ); var PauseIconShape = require( 'SCENERY_PHET/PauseIconShape' ); var PlayIconShape = require( 'SCENERY_PHET/PlayIconShape' ); var RectangularPushButton = require( 'SUN/buttons/RectangularPushButton' ); var sceneryPhet = require( 'SCENERY_PHET/sceneryPhet' ); var ShadedRectangle = require( 'SCENERY_PHET/ShadedRectangle' ); var Tandem = require( 'TANDEM/Tandem' ); var TimerReadoutNode = require( 'SCENERY_PHET/TimerReadoutNode' ); var UTurnArrowShape = require( 'SCENERY_PHET/UTurnArrowShape' ); // constants var ICON_HEIGHT = 10; /** * @param {Property.<number>} timeProperty * @param {Property.<boolean>} runningProperty * @param {Object} [options] * @constructor */ function TimerNode( timeProperty, runningProperty, options ) { options = _.extend( { // See also options that pass through to TimerReadoutNode touchAreaDilation: 10, cursor: 'pointer', iconFill: 'black', iconStroke: null, iconLineWidth: 1, buttonBaseColor: '#DFE0E1', buttonSpacing: 6, // horizontal distance between the buttons buttonTopMargin: 6, // space between the bottom of the readout and the top of the buttons // Tandem is required to make sure the buttons are instrumented tandem: Tandem.required }, options ); assert && assert( options.buttonSpacing >= 0, 'Buttons cannot overlap' ); assert && assert( options.buttonTopMargin >= 0, 'Buttons cannot overlap the readout' ); Node.call( this ); // Create the TimerReadoutNode. If we need more flexibility for this part, consider inversion of control var timerReadoutNode = new TimerReadoutNode( timeProperty, options ); timerReadoutNode.centerX = 0; // Buttons ---------------------------------------------------------------------------- var resetPath = new Path( new UTurnArrowShape( ICON_HEIGHT ), { fill: options.iconFill } ); var playIconHeight = resetPath.height; var playIconWidth = 0.8 * playIconHeight; var playPath = new Path( new PlayIconShape( playIconWidth, playIconHeight ), { stroke: options.iconStroke, fill: options.iconFill } ); var pausePath = new Path( new PauseIconShape( 0.75 * playIconWidth, playIconHeight ), { stroke: options.iconStroke, fill: options.iconFill } ); var playPauseButton = new BooleanRectangularToggleButton( pausePath, playPath, runningProperty, { baseColor: options.buttonBaseColor, tandem: options.tandem.createTandem( 'playPauseButton' ) } ); var resetButton = new RectangularPushButton( { listener: function resetTimer() { runningProperty.set( false ); timeProperty.set( 0 ); }, content: resetPath, baseColor: options.buttonBaseColor, tandem: options.tandem.createTandem( 'resetButton' ) } ); // Layout ---------------------------------------------------------------------------- var contents = new Node(); contents.addChild( resetButton ); contents.addChild( playPauseButton ); contents.addChild( timerReadoutNode ); resetButton.right = -options.buttonSpacing / 2; playPauseButton.left = options.buttonSpacing / 2; resetButton.top = timerReadoutNode.bottom + options.buttonTopMargin; playPauseButton.top = timerReadoutNode.bottom + options.buttonTopMargin; var panelPad = 8; contents.left = panelPad; contents.top = panelPad; // Panel background var roundedRectangle = new ShadedRectangle( contents.bounds.dilated( panelPad ) ); roundedRectangle.touchArea = roundedRectangle.localBounds.dilated( options.touchAreaDilation ); this.addChild( roundedRectangle ); this.addChild( contents ); // @public (read-only) - Target for drag listeners this.dragTarget = roundedRectangle; var updateResetButtonEnabled = function( value ) { resetButton.enabled = value > 0; }; timeProperty.link( updateResetButtonEnabled ); // @private this.disposeTimerNode = function() { timerReadoutNode.dispose(); timeProperty.unlink( updateResetButtonEnabled ); resetButton.dispose(); playPauseButton.dispose(); }; this.mutate( options ); } sceneryPhet.register( 'TimerNode', TimerNode ); return inherit( Node, TimerNode, { /** * Release resources when no longer be used. * @public */ dispose: function() { this.disposeTimerNode(); } } ); } );
JavaScript
0
@@ -5179,24 +5179,67 @@ imerNode();%0A + Node.prototype.dispose.call( this );%0A %7D%0A %7D );
c0c17041a09f9ee1aa80368f4e8eb8d3485c48a9
fix ssh password being ignored
client/actions.js
client/actions.js
'use strict'; import { Client } from 'ssh2'; import net from 'net'; import Redis from 'ioredis'; import _ from 'lodash'; const actions = { connect(config) { return dispatch => { if (config.ssh) { dispatch({ type: 'updateConnectStatus', data: 'SSH connecting...' }); const conn = new Client(); conn .on('ready', () => { const server = net.createServer(function (sock) { conn.forwardOut(sock.remoteAddress, sock.remotePort, config.host, config.port, function (err, stream) { if (err) { return sock.end(); } sock.pipe(stream).pipe(sock); }); }).listen(0, function () { handleRedis(config, { host: '127.0.0.1', port: server.address().port }); }); }) .on('error', err => { dispatch({ type: 'disconnect' }); alert(`SSH Error: ${err.message}`); }); try { conn.connect({ host: config.sshHost, port: config.sshPort || 22, username: config.sshUser, privateKey: config.sshKey, passphrase: config.sshKeyPassphrase }); } catch (err) { dispatch({ type: 'disconnect' }); alert(`SSH Error: ${err.message}`); } } else { handleRedis(config); } function handleRedis(config, override) { dispatch({ type: 'updateConnectStatus', data: 'Redis connecting...' }); const redis = new Redis(_.assign({}, config, override, { showFriendlyErrorStack: true, retryStrategy() { return false; } })); redis.defineCommand('setKeepTTL', { numberOfKeys: 1, lua: 'local ttl = redis.call("pttl", KEYS[1]) if ttl > 0 then return redis.call("SET", KEYS[1], ARGV[1], "PX", ttl) else return redis.call("SET", KEYS[1], ARGV[1]) end' }); redis.defineCommand('lremindex', { numberOfKeys: 1, lua: 'local FLAG = "$$#__@DELETE@_REDIS_@PRO@__#$$" redis.call("lset", KEYS[1], ARGV[1], FLAG) redis.call("lrem", KEYS[1], 1, FLAG)' }); redis.defineCommand('duplicateKey', { numberOfKeys: 2, lua: 'local dump = redis.call("dump", KEYS[1]) local pttl = 0 if ARGV[1] == "TTL" then pttl = redis.call("pttl", KEYS[1]) end return redis.call("restore", KEYS[2], pttl, dump)' }); redis.once('connect', function () { redis.ping((err, res) => { if (err) { if (err.message === 'Ready check failed: NOAUTH Authentication required.') { err.message = 'Redis Error: Access denied. Please double-check your password.'; } alert(err.message); dispatch({ type: 'disconnect' }); return; } const version = redis.serverInfo.redis_version; if (version && version.length >= 5) { const versionNumber = Number(version[0] + version[2]); if (versionNumber < 28) { alert('Medis only supports Redis >= 2.8 because servers older than 2.8 don\'t support SCAN command, which means it not possible to access keys without blocking Redis.'); dispatch({ type: 'disconnect' }); return; } } dispatch({ type: 'connect', data: { redis, config } }); }) }); redis.once('end', function () { dispatch({ type: 'disconnect' }); alert('Redis Error: Connection failed'); }); } }; } }; export default function (type, data, callback) { if (actions[type]) { return actions[type](data, callback); } if (typeof data === 'function') { return { type, callback: data }; } return { type, data, callback }; }
JavaScript
0.000007
@@ -964,16 +964,49 @@ try %7B%0A + if (config.sshKey) %7B%0A @@ -1022,16 +1022,18 @@ nnect(%7B%0A + @@ -1070,16 +1070,18 @@ + port: co @@ -1112,16 +1112,18 @@ + username @@ -1152,16 +1152,18 @@ + + privateK @@ -1181,16 +1181,18 @@ sshKey,%0A + @@ -1233,36 +1233,273 @@ hrase%0A + + %7D);%0A + %7D else %7B%0A conn.connect(%7B%0A host: config.sshHost,%0A port: config.sshPort %7C%7C 22,%0A username: config.sshUser,%0A password: config.sshPassword%0A %7D);%0A %7D%0A %7D catch
9f171809e5ae91244b690fa4ca70296edbc550b6
send geojson as string not as object CDB-585
lib/assets/javascripts/cartodb/table/geom_editor.js
lib/assets/javascripts/cartodb/table/geom_editor.js
cdb.admin.GeometryEditor = cdb.core.View.extend({ className: "editing", MAX_VERTEXES: 2000, events: { 'click .done': 'finish', 'click .discard': 'discard', 'click .cancel': 'discard', 'mousedown': 'killEvent' }, initialize: function() { this.add_related_model(this.model); this.geomBeingEdited = null; this.drawer = null; }, isEditing: function() { return this.geomBeingEdited ? true: false; }, /** * finish the editing if there is some geometry being edited and save it * triggers editFinish */ finish: function(e) { this.killEvent(e); if ((this.drawer && this.drawer.canFinish()) || this.isEditing()) { var self = this; if(this.geomBeingEdited) { this.geomBeingEdited.destroy(); this.geomBeingEdited = null; } if(this.drawer) { this.row.set('the_geom', this.drawer.getGeoJSON()); this.drawer.clean(); this.drawer = null; } var isNew = this.row.isNew() this.model.notice('Saving ... ', 'load'); $.when(this.row.save(null)).done(function() { if(isNew){ self.trigger('geomCreated', self.row); } self.trigger('editFinish') self.model.notice('Saved', 'info', 5000); self.row = null; }).fail(function() { self.trigger('editFinish'); self.model.notice('Something has failed', 'error', 5000); self.row = null; }); this.hide(); } }, /** * finish the editing and undo the changes done. * triggers 'editDiscard' */ discard: function(e) { this.killEvent(e); if(this.geomBeingEdited) { this.geomBeingEdited.destroy(); this.geomBeingEdited = null; this.row.set('the_geom', this.originalGeom); this.originalGeom = null; this.row = null; this.trigger('editDiscard'); } if(this.drawer) { this.drawer.clean(); this.drawer = null; this.trigger('editDiscard'); } this.mapView.bind(null, null, this); this.hide(); }, _getGeomCount: function(geojson) { var count = 0; _.each(geojson.coordinates, function(pol1, i){ _.each(pol1, function(pol2, j) { count = count + pol2.length; }) }); return count; }, /** * edits the row geometry * the row should contain the_geom attribute. * When the edit is finish the row is saved */ editGeom: function(row) { var self = this , geojson = JSON.parse(row.get('the_geom')); if (this._getGeomCount(geojson) > this.MAX_VERTEXES) { this._showStopEdit(row); return false; } else { this._startEdition(row) } }, _startEdition: function(row) { this.trigger('editStart'); this.discard(); var geo = new cdb.geo.Geometry({ geojson: JSON.parse(row.get('the_geom')), // Supporting leaflet and gmaps styles, overrriding them style: { fillColor: "white", fillOpacity: 0.4, weight: 4, color:"#397DBA", opacity: 1, strokeColor: "#397DBA", clickable: false } }); this.row = row; this.originalGeom = row.get('the_geom'); this.geomBeingEdited = geo; // when model is edited the model changes geo.bind('change:geojson', function() { row.set({the_geom: JSON.stringify(geo.get('geojson'))}); }); this.mapView.map.addGeometry(geo); var geoView = this.mapView.geometries[geo.cid]; geoView.edit(true); this.$('.finish_editing .tooltip').hide(); this.$el.fadeIn(); }, _showStopEdit: function(row) { var self = this; var edit_confirmation = new cdb.admin.BaseDialog({ title: "This geometry is too big to edit from the web", description: "Editing this geometry could freeze or crash your browser, and you could lose your work. We encourage you to edit this feature through the API.", template_name: 'common/views/confirm_dialog', clean_on_hide: true, enter_to_confirm: true, ok_button_classes: "right button grey", ok_title: "I'll take the risk", cancel_button_classes: "underline margin15", cancel_title: "Cancel", modal_type: "confirmation", width: 500 }); // If user confirms, app removes the row edit_confirmation.ok = function() { self._startEdition(row); } edit_confirmation .appendToBody() .open(); }, /** * create geometry * @param row a row model, normally empty * @param type can be 'point', 'polygon', 'line' */ createGeom: function(row, type) { var self = this; this.discard(); this.row = row; this.geomType = type; this.trigger('editStart'); var editors = { 'point': PointDrawTool, 'polygon': PolygonDrawTool, 'line': PolylineDrawTool }; this.drawer = new editors[type]({ mapview: this.mapView }); this.drawer.start(); var c; this.mapView.bind('click', c = function() { if(self.drawer.canFinish()) { this.mapView.unbind('click', c); self.$('.finish_editing .tooltip').fadeOut(); self.$('.finish_editing .done').removeClass("disabled"); } }, this); this.render(); this.$('.finish_editing .done').addClass("disabled"); this.$('.finish_editing .tooltip').show(); this.$el.fadeIn(); }, render: function() { this.$el.html(this.getTemplate('table/views/geom_edit')({ geom_type: this.geomType})); return this; } });
JavaScript
0
@@ -869,24 +869,39 @@ 'the_geom', +JSON.stringify( this.drawer. @@ -913,16 +913,17 @@ oJSON()) +) ;%0A
798c2577b8a12220fb873fe55045067f34add6f5
Update countdown.js
js/countdown.js
js/countdown.js
function getTimeRemaining(endtime) { var t = Date.parse(endtime) - Date.parse(new Date()); var seconds = Math.floor((t / 1000) % 60); var minutes = Math.floor((t / 1000 / 60) % 60); var hours = Math.floor((t / (1000 * 60 * 60)) % 24); var days = Math.floor(t / (1000 * 60 * 60 * 24)); return { 'total': t, 'days': days, 'hours': hours + 24 * days, 'minutes': minutes, 'seconds': seconds }; } function initializeClock(id, endtime) { var clock = document.getElementById(id); var daysSpan = clock.querySelector('.days'); var hoursSpan = clock.querySelector('.hours'); var minutesSpan = clock.querySelector('.minutes'); //var secondsSpan = clock.querySelector('.seconds'); function updateClock() { var t = getTimeRemaining(endtime); daysSpan.innerHTML = t.days; hoursSpan.innerHTML = ('0' + t.hours).slice(-2); minutesSpan.innerHTML = ('0' + t.minutes).slice(-2); //secondsSpan.innerHTML = ('0' + t.seconds).slice(-2); if (t.total <= 0) { clearInterval(timeinterval); } } updateClock(); var timeinterval = setInterval(updateClock, 1000); } var deadline = new Date("May 05, 2018 24:00:00"); initializeClock('countdown', deadline);
JavaScript
0
@@ -355,20 +355,8 @@ ours - + 24 * days ,%0A
12c7fa7456c24d93db7cdd6a116b0f6fece82184
remove log
test/acceptance.js
test/acceptance.js
// use a minimal 100 line test framework. We do not want this // file to exit prematurely. both `tape` & `mocha` do process.exit() var test = require('assert-tap').test var Readable = require('readable-stream').Readable var setTimeout = require('timers').setTimeout var getRawBody = require('../') // this test is about infinite streams. If this file never terminates // then its a bug because rawBody with limit's set should not // allow a process to hang. // if any of the streams we create are left in flowing mode // then the script never ends & its a failing test. function createChunk() { var base = Math.random().toString(32) var KB_4 = 32 * 4 var KB_8 = KB_4 * 2 var KB_16 = KB_8 * 2 var KB_64 = KB_16 * 4 var rand = Math.random() if (rand < 0.25) { return repeat(base, KB_4) } else if (rand < 0.5) { return repeat(base, KB_8) } else if (rand < 0.75) { return repeat(base, KB_16) } else { return repeat(base, KB_64) } function repeat(str, num) { return new Array(num + 1).join(str) } } function createInfiniteStream() { var stream = new Readable() stream._read = function () { var rand = 2 + Math.floor(Math.random() * 10) setTimeout(function () { for (var i = 0; i < rand; i++) { stream.push(createChunk()) } }, 100) } // immediately put the stream in flowing mode stream.resume() return stream } var defaultLimit = 1024 * 1024 // assert is just the normal node assert & assert.end() is like done() in mocha test('a stream with a limit lower then length', function (assert) { var stream = createInfiniteStream() getRawBody(stream, { limit: defaultLimit, length: defaultLimit * 2 }, function (err, body) { assert.ok(err) assert.equal(err.type, 'entity.too.large') assert.equal(err.message, 'request entity too large') assert.equal(err.statusCode, 413) assert.equal(err.length, defaultLimit * 2) assert.equal(err.limit, defaultLimit) assert.equal(body, undefined) assert.end() }) }) test('a stream with an encoding', function (assert) { var stream = createInfiniteStream() stream.setEncoding('utf8') getRawBody(stream, { limit: defaultLimit }, function (err, body) { assert.ok(err) assert.equal(err.type, 'stream.encoding.set') assert.equal(err.message, 'stream encoding should not be set') assert.equal(err.statusCode, 500) assert.end() }) }) test('a stream with a limit', function (assert) { var stream = createInfiniteStream() getRawBody(stream, { limit: defaultLimit }, function (err, body) { assert.ok(err) assert.equal(err.type, 'entity.too.large') assert.equal(err.statusCode, 413) assert.ok(err.received > defaultLimit) assert.equal(err.limit, defaultLimit) assert.end() }) }) test('a stream that errored', function (assert) { var stream = createInfiniteStream() getRawBody(stream, function (err, body) { console.log('wtf :(') assert.ok(err) assert.equal(err.message, 'BOOM') assert.end() }) setTimeout(function () { stream.emit('error', new Error('BOOM')) }, 500) })
JavaScript
0.000001
@@ -2951,35 +2951,8 @@ ) %7B%0A - console.log('wtf :(')%0A%0A
8c3e702c3521a2f7c4b28994d25022e5d4487f2c
Update functions.js
js/functions.js
js/functions.js
$(document).ready(function() { setTimeout(function() { $("#preloader").css("display","none") }, 5000); }); function hoverHash(imdb) { $.get("https://www.omdbapi.com/?i="+imdb+"&plot=full&r=json&apikey=bd31da15", function (data) { movie_rating = Math.round(data.imdbRating); movie_rating_star = '<i class="fas fa-star"></i>'; movie_rating_star_empty = '<i class="far fa-star"></i>'; html_rating = movie_rating_star.repeat(movie_rating)+movie_rating_star_empty.repeat(10 - movie_rating); $("#movie-rating-star-"+imdb).html(html_rating); }); $("#movie-rating-star-"+imdb).css("visibility", "visible"); } function outHash(imdb) { $("#movie-rating-star-"+imdb).css("visibility", "hidden"); } function catalogue(hash, imdb, magnet, title, rating, poster, genre, background, api_url, provider, proxy, content_value) { var html = ""; html+='<div id="movie-box-'+'" class="movie-box movie-box-'+genre+' col-lg-2 col-md-3 col-sm-6 col-xs-12" style="position:relative;float:left;">'; html+='<div style="width: 100%; height: 330px; position: absolute;left: 0px; top: 0px; -webkit-filter: blur(3px); -moz-filter: blur(3px); -o-filter: blur(3px); -ms-filter: blur(3px); filter: blur(3px); background-image:url('+background+'); background-position: center; background-size: cover; background-repeat: no-repeat; -webkit-box-shadow: inset 0px 0px 30px 30px rgba(0, 0, 0, 1); -moz-box-shadow: inset 0px 0px 30px 30px rgba(0, 0, 0, 1); box-shadow: inset 0px 0px 30px 30px rgba(0, 0, 0, 1);"></div>'; // html+='<a href="'+magnet+'" target="_blank">'; html+='<img id="img-movie-box-'+hash+'" class="hover-luz" title="'+title+'" alt="'+title+'" src="'+poster+'" onclick="openNewWidow(1080, 720, &#39;'+magnet+'&#39;)" onmouseover="hoverHash(&#39;'+imdb+'&#39;)" onmouseout="outHash(&#39;'+imdb+'&#39;)"/>'; html+='<div id="movie-rating-star-'+imdb+'" class="movie_rating_star"></div></div>'; // html+='</a>'; $('#movies').append(html); } var getUrlParameter = function getUrlParameter(sParam) { var sPageURL = decodeURIComponent(window.location.search.substring(1)), sURLVariables = sPageURL.split('&'), sParameterName, i; for (i = 0; i < sURLVariables.length; i++) { sParameterName = sURLVariables[i].split('='); if (sParameterName[0] === sParam) { return sParameterName[1] === undefined ? true : sParameterName[1]; } } }; function openNewWidow(width, height, hash) { var top = (screen.availHeight / 2) - (height / 2); var left = (screen.availWidth / 2) - (width / 2); var features = "location=1, status=1, scrollbars=1, width=" + width + ", height=" + height + ", top=" + top + ", left=" + left; window.open(hash, "kad", features); window.close(); }
JavaScript
0.000002
@@ -2701,20 +2701,56 @@ ow.open( -hash +%22https://codepen.io/eliooses/pen/vMQpEO%22 , %22kad%22, @@ -2778,12 +2778,13 @@ w.close();%0A%7D +%0A
efe9a59f29e322e9450dd4ee62f491f3ce904b40
Update tests to cover expected result of getLicense method.
test/basic-test.js
test/basic-test.js
// Basic tests // =========== // Basic library tests. var expect = require('chai').expect, QClient = require('../qclient'), config = require('./config.js'), Q = new QClient(config.clientId, config.clientSecret, config.options); describe('QClient', function() { it('should set client ID and secret as properties during initialization', function() { expect(Q).to.have.property('clientId'); expect(Q).to.have.property('secretToken'); }); describe('#getPlanInfo', function() { it('should return a JSON response containing data for a single plan', function(done) { Q.getPlanInfo('73836AK0750003', 'AK', 'Aleutians East', function(err, planInfo) { if (err) { done(err); } var plan = JSON.parse(planInfo); expect(plan.status).to.equal('ok'); expect(plan.plan).to.have.all.keys(['coverage_type', 'state', 'county', 'metal_level', 'issuer', 'plan_id', 'plan_name', 'plan_type', 'rating_area', 'issuer_id', 'effective_date', 'expiration_date', 'tobacco_matters']); done(); }); }); }); describe('#getLicenses', function() { it('should return JSON containing licenses', function(done) { Q.getLicenses(config.npn, function(err, response) { if (err) done(err); expect(response).to.be.a('string'); var parsed = JSON.parse(response); describe('#getLicenses -> response.licenses', function() { it('should have a status of "ok"', function() { expect(parsed.status).to.equal('ok'); }); it('should be an array', function() { expect(parsed.licenses).to.be.an('array'); }); it('should contain a collection of objects', function() { parsed.licenses.forEach(function(license) { expect(license).to.be.an('object'); }); describe('response.licenses', function() { it('should have expected keys', function() { expect(parsed.licenses[0]).to.have.all.keys(['state', 'number', 'issued_date', 'expiration_date', 'resident_status', 'loa', 'loa_code', 'last_updated']); }); }); }); }); done(); }); }) }); });
JavaScript
0
@@ -240,18 +240,51 @@ options) +,%0A _ = require('lodash') ;%0A - %0Adescrib @@ -1317,97 +1317,8 @@ );%0A%0A - expect(response).to.be.a('string');%0A%0A var parsed = JSON.parse(response);%0A%0A @@ -1457,22 +1457,24 @@ expect( -par +respon se -d .status) @@ -1564,38 +1564,40 @@ expect( -par +respon se -d .licenses).to.be @@ -1705,22 +1705,24 @@ -par +respon se -d .license @@ -1848,33 +1848,32 @@ response.license -s ', function() %7B%0A @@ -1923,32 +1923,73 @@ ', function() %7B%0A + console.log('got here');%0A @@ -1999,14 +1999,16 @@ ect( -par +respon se -d .lic @@ -2153,32 +2153,822 @@ %7D); +%0A%0A it('has at least two keys that are date objects', function() %7B%0A expect(response.licenses%5B0%5D.issued_date).to.be.a('date');%0A expect(response.licenses%5B0%5D.last_updated).to.be.a('date');%0A %7D)%0A%0A describe('license.expiration_date', function() %7B%0A it('should have a value of %22PERPETUAL%22 or be a valid date object', function() %7B%0A expect(response.licenses%5B0%5D).to.satisfy(function(license) %7B%0A if (_.isString(license.expiration_date)) %7B%0A return license.expiration_date === 'PERPETUAL';%0A %7D else %7B%0A return _.isDate(license.expiration_date);%0A %7D%0A %7D);%0A %7D);%0A %7D); %0A %7D);
36355e6b9fdaa6a1b51bfb3b8b06036094791241
Add some space
judy.js
judy.js
/*! written by @travisjeffery */ +function ($) { 'use strict'; var Effect = function (element) { this.element = element this.chars = element.querySelectorAll('.js-judy-char') this.charsLength = this.chars.length if (!this.charsLength) return this.endIndex = 0 this.startIndex = 0 this.hueIndex = Math.floor(360 * Math.random()) this.colors = [] this.hasMouseover = true this.isAnimating = true this.animate() document.addEventListener('mouseover', this, false) } Effect.prototype.handleEvent = function(event) { var typeHandler = event.type + 'Handler' this[typeHandler] && this[typeHandler](event) } Effect.prototype.mouseoverHandler = function(event) { if (this.element.contains(event.target)) return this.hasMouseover = false document.removeEventListener('mouseover', this, false) } Effect.prototype.animate = function() { this.endIndex = Math.min(this.endIndex + 1, this.charsLength) var hue = 10 * this.hueIndex % 360, color = this.hasMouseover ? 'hsl(' + hue + ', 100%, 50%)' : '' this.colors.unshift(color) for (var n = this.startIndex; n < this.endIndex; n++) this.chars[n].style.color = this.colors[n] this.hasMouseover ? this.hueIndex++ : this.startIndex = Math.min(this.startIndex + 1, this.charsLength) this.isAnimating = this.startIndex !== this.charsLength this.isAnimating && requestAnimationFrame(this.animate.bind(this)) } function getTaggedElement (element, tag) { for (;Node.DOCUMENT_NODE !== element.nodeType;) { if (element.nodeName.toLowerCase() === tag) return element element = element.parentNode } return null } function prepareChars (element) { var words = element.textContent.split(' ') for (;element.firstChild;) element.removeChild(element.firstChild) var fragment = document.createDocumentFragment() for (var i = 0, l = words.length; l > i; i++) { var word = words[i] , wordElement = document.createElement('span') , chars = word.split('') wordElement.className = 'js-judy-word' for (var j = 0, m = chars.length; m > j; j++) { var charElement = document.createElement('span') charElement.className = 'js-judy-char' charElement.textContent = chars[j] wordElement.appendChild(charElement) } fragment.appendChild(wordElement) fragment.appendChild(document.createTextNode(' ')) } element.appendChild(fragment) } function onMouseover (event) { var element = getTaggedElement(event.target, 'a') element && new Effect(element) } $.fn.judy = function() { document.addEventListener('mouseover', onMouseover, false) return this.each(function () { prepareChars(this) }) } }(jQuery);
JavaScript
0.012746
@@ -268,26 +268,24 @@ return%0A - this.endInde @@ -290,24 +290,24 @@ dex = 0%0A + this.sta @@ -1107,16 +1107,17 @@ )' : ''%0A +%0A this @@ -1139,16 +1139,17 @@ (color)%0A +%0A for @@ -1241,18 +1241,17 @@ lors%5Bn%5D%0A - +%0A this @@ -1797,16 +1797,17 @@ it(' ')%0A +%0A for @@ -1869,18 +1869,17 @@ tChild)%0A - +%0A var @@ -1923,16 +1923,17 @@ gment()%0A +%0A for @@ -2086,16 +2086,17 @@ lit('')%0A +%0A wo @@ -2132,16 +2132,17 @@ y-word'%0A +%0A fo @@ -2383,16 +2383,16 @@ nt)%0A - %7D%0A @@ -2383,24 +2383,25 @@ nt)%0A %7D%0A +%0A fragme
421b548b527b40b83dd9a204e58bfc928de11e53
Add axis labels to histograms
js/histogram.js
js/histogram.js
function draw_hist(ident, vals) { // A formatter for counts. var formatCount = d3.format(",.0f"); var margin = {top: 10, right: 30, bottom: 30, left: 30}, width = 200 - margin.left - margin.right, height = 100 - margin.top - margin.bottom; var x = d3.scale.linear() .domain([-5, 5]) .range([0, width]); // Generate a histogram using twenty uniformly-spaced bins. var data = d3.layout.histogram() .bins(x.ticks(20)) (vals); var y = d3.scale.linear() .domain([0, d3.max(data, function(d) { return d.y + Math.sqrt(d.y); })]) .range([height, 0]); var xAxis = d3.svg.axis() .scale(x) .ticks(5) .tickFormat(function(d) { return '';}) .orient("bottom"); var yAxis = d3.svg.axis() .scale(y) .ticks(4) //.tickFormat(function(d) { return ''; }) .orient("left"); var svg = d3.select(ident).append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); var bar = svg.selectAll(".bar") .data(data) .enter().append("svg:circle") .attr("stroke", "black") .attr("fill", function(d, i) { return "black" }) .attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; }) .attr("r", function(d, i) { return 1 }); svg.selectAll(".bar") .data(data) .enter().append("svg:line") .attr("x1", 0) .attr("x2", 0) .attr("y1", function(d) { return y(Math.sqrt(d.y))-60; }) .attr("y2", function(d) { return -y(Math.sqrt(d.y))+60; }) .attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; }) .attr("stroke", "black") .attr("stroke-width", 1) svg.selectAll(".bar") .data(data) .enter().append("svg:line") .attr("x1", -2) .attr("x2", 2) .attr("y1", function(d) { return y(Math.sqrt(d.y))-60; }) .attr("y2", function(d) { return y(Math.sqrt(d.y))-60; }) .attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; }) .attr("stroke", "black") .attr("stroke-width", 1) svg.selectAll(".bar") .data(data) .enter().append("svg:line") .attr("x1", -2) .attr("x2", 2) .attr("y1", function(d) { return -y(Math.sqrt(d.y))+60; }) .attr("y2", function(d) { return -y(Math.sqrt(d.y))+60; }) .attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; }) .attr("stroke", "black") .attr("stroke-width", 1) bar.append("rect") .attr("x", 1) .attr("width", x(data[0].dx)) .attr("height", function(d) { return height - y(d.y); }); svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + (height ) + ")") .call(xAxis); svg.append("g") .attr("class", "y axis") .attr("transform", "translate(0, 0)") .call(yAxis); return svg; } function Histogram(ident) { // TODO: Allow for arbitrary numbers of events this.values = d3.range(1000).map(d3.random.normal(0, 1)); this.counter = 0; draw_hist(ident, []); this.add_events = function(num) { d3.select(ident).select("svg").remove(); draw_hist(ident, this.values.slice(0, this.counter+num)); this.counter += num; } this.clear = function() { d3.select(ident).select("svg").remove(); draw_hist(ident, []); this.counter = 0; } }
JavaScript
0.000004
@@ -98,11 +98,10 @@ t(%22, -.0f +0d %22);%0A @@ -157,17 +157,17 @@ , left: -3 +4 0%7D,%0A @@ -697,17 +697,17 @@ .ticks( -5 +3 )%0A @@ -3090,110 +3090,531 @@ nd(%22 -g%22)%0A .attr(%22class%22, %22y axis%22)%0A .attr(%22transform%22, %22translate(0, 0)%22)%0A .call(yAxis +text%22)%0A .attr(%22class%22, %22x label%22)%0A .attr(%22text-anchor%22, %22end%22)%0A .attr(%22x%22, width)%0A .attr(%22y%22, height + 20)%0A .text(%22m (GeV)%22);%0A%0A svg.append(%22g%22)%0A .attr(%22class%22, %22y axis%22)%0A .attr(%22transform%22, %22translate(0, 0)%22)%0A .call(yAxis);%0A%0A svg.append(%22text%22)%0A .attr(%22class%22, %22y label%22)%0A .attr(%22text-anchor%22, %22end%22)%0A .attr(%22y%22, -20)%0A .attr(%22dy%22, %22-1em%22)%0A .attr(%22dx%22, %22-0.5em%22)%0A .attr(%22transform%22, %22rotate(-90)%22)%0A .text(%22events%22 );%0A%0A
56db6587422408579fdf52e19d41ab539cd36a20
add platform flag for sample app symlink issue
lib/MMXSampleApp.js
lib/MMXSampleApp.js
var ejs = require('ejs') , fs = require('fs') , MMXManager = require('./MMXManager') , JSZip = require("jszip"); var CONFIGS = { android : { quickstart : 'quickstart-android/app/src/main/res/raw/quickstart.properties', rpsls : 'rpsls-android/app/src/main/res/raw/rpsls.properties', soapbox : 'soapbox-android/app/src/main/res/raw/soapbox.properties' }, ios : { quickstart : 'quickstart-ios/QuickStart/Configurations.plist', rpsls : 'rpsls-ios/RPSLS/Configurations.plist', soapbox : 'soapbox-ios/Soapbox/Configurations.plist' } }; var TEMPLATES = { android : fs.readFileSync('./views/file-templates/sample-android-config.ejs', 'ascii'), ios : fs.readFileSync('./views/file-templates/sample-ios-config.ejs', 'ascii') }; var MMXSampleApp = function(){}; MMXSampleApp.prototype.getSample = function(userMagnetId, mmxId, platform, sampleId, cb){ var me = this; var samplesDir = (ENV_CONFIG.App.samplesDir && ENV_CONFIG.App.samplesDir != './') ? ENV_CONFIG.App.samplesDir : ''; me.getSampleConfig(userMagnetId, mmxId, platform, function(e, tmpl){ if(e) return cb(e); fs.readFile(samplesDir+sampleId+'-'+platform+'.zip', function(e, data){ if(e) return cb('unable-to-create'); var zip = new JSZip(data); zip.file(CONFIGS[platform][sampleId], new Buffer(tmpl)); cb(null, zip.generate({ type : 'nodebuffer' })); }); }); }; MMXSampleApp.prototype.getSampleConfig = function(userMagnetId, mmxId, platform, cb){ if(!platform) return cb('invalid-platform'); MMXManager.getApp(userMagnetId, mmxId, function(e, app){ if(e) return cb(e); MMXManager.getConfigs(userMagnetId, function(e, mmxconfig){ if(e) return cb(e); cb(null, ejs.render(TEMPLATES[platform], { params : app, config : ENV_CONFIG, mmxconfig : mmxconfig })); }); }); }; module.exports = new MMXSampleApp();
JavaScript
0
@@ -1468,16 +1468,20 @@ type + : 'nodeb @@ -1486,16 +1486,61 @@ ebuffer' +,%0A platform : process.platform %0A
1a8efa78722eb174f75b6472a14e8d6f9ed4f771
Add Josh Lewis
js/locations.js
js/locations.js
var locations = [ { name: 'wayne bills', origin: 'northaven, tn', latitude: 35.26507, longitude: -90.04078 }, { name: 'brad montgomery', origin: 'lepanto, ar', latitude: 35.61046, longitude: -90.33114 }, { name: 'stephen bramlett', origin: 'memphis, tn', latitude: 35.14174, longitude: -89.97456 }, { name: 'eric terpstra', origin: 'kellogg, ia', latitude: 41.776711, longitude:-92.964886 } ];
JavaScript
0.00029
@@ -391,12 +391,109 @@ 964886 %7D +,%0A %7B name: 'josh lewis', origin: 'rogersville, mo', latitude: 37.110618, longitude: -93.053759 %7D %0A%5D;%0A
7306b74c1da3723bf42fd875f349ada496d823a6
Add Daniel Soskel to locations.
js/locations.js
js/locations.js
var locations = [ { name: 'wayne bills', origin: 'northaven, tn', latitude: 35.26507, longitude: -90.04078 }, { name: 'brad montgomery', origin: 'lepanto, ar', latitude: 35.61046, longitude: -90.33114 }, { name: 'Stephen Bramlett', origin: 'memphis, tn', latitude: 35.2243923520236, longitude: -90.00089585781097 }, { name: 'eric terpstra', origin: 'kellogg, ia', latitude: 41.776711, longitude:-92.964886 }, { name: 'josh lewis', origin: 'rogersville, mo', latitude: 37.110618, longitude: -93.053759 }, { name: 'Daniel Pritchett', origin: 'Dothan, AL', latitude: 31.2290238, longitude: -85.4766258 }, { name: 'Joe Ferguson', origin: 'memphis, tn', latitude: 35.2246054, longitude: -90.0001485 }, { name: 'David Hiltenbrand', origin: 'Pine Bluff, AR', latitude: 34.231984, longitude: -92.135550 }, { name: 'Ismael Alonso', origin: 'Valladolid, ES-VA', latitude: 41.6519094, longitude: -4.730486 }, { name: 'Collin Barrett', origin: 'Kalamazoo, MI', latitude: 42.271161, longitude: -85.660178 }, { name: 'Claudio Donndelinger', origin: 'Tucson, AZ', latitude: 32.2274179, longitude: -110.9604492 }, { name: 'Jason Myers', origin: 'Sacramento, CA', latitude: 35.143839,longitude: -89.944866 } ];
JavaScript
0
@@ -1207,12 +1207,118 @@ 944866 %7D +,%0A %7B name: 'Daniel Soskel', origin: 'Salt Lake City, UT', latitude: 40.7762692, longitude: -112.2006695 %7D %0A%5D;%0A
270088278d55af8bf7d54893e6753a1c5509d5aa
Update lunr-feed.js
js/lunr-feed.js
js/lunr-feed.js
--- --- // builds lunr var index = lunr(function () { this.field('title') this.field('content', {boost: 10}) this.field('category') this.field('tags') this.ref('id') {% assign count = 0 %} {% for post in site.posts %} this.add({ title: {{post.title | jsonify}}, category: {{post.category | jsonify}}, content: {{post.content | strip_html | jsonify}}, tags: {{post.tags | jsonify}}, id: {{count}} }); {% assign count = count | plus: 1 %} {% endfor %} }) ; console.log( jQuery.type(index) ); // builds reference data var store = [{% for post in site.posts %}{ //{% assign plink = post.url | prepend:'/blog' %} //{% assign pimage = post.image | prepend:'/blog/posts/' %} "title": {{post.title | jsonify}}, // "link": {{ plink | jsonify}}, "link": {{ post.url | jsonify}}, // "image": {{ pimage | jsonify }}, "image": {{ post.image | jsonify }}, "date": {{ post.date | date: '%B %-d, %Y' | jsonify }}, "category": {{ post.category | jsonify }}, "excerpt": {{ post.content | strip_html | truncatewords: 20 | jsonify }} }{% unless forloop.last %},{% endunless %}{% endfor %}] // builds search $(document).ready(function() { $('input#search').on('keyup', function () { var resultdiv = $('#results'); // Get query var query = $(this).val(); // Search for it var result = index.search(query); // Show results resultdiv.empty(); // Add status resultdiv.prepend('<p class="">Found '+result.length+' result(s)</p>'); // Loop through, match, and add results for (var item in result) { var ref = result[item].ref; var searchitem = '<div class="result"><img src="'+store[ref].image+'" class="result-img"><div class="result-body"><a href="'+store[ref].link+'" class="post-title">'+store[ref].title+'</a><div class="post-date small">'+store[ref].category+' &times; '+store[ref].date+'</div><p>'+store[ref].excerpt+'</p></div>'; //alt="'+store[ref].title+'" resultdiv.append(searchitem); } }); });
JavaScript
0
@@ -649,18 +649,16 @@ g' %25%7D%0A -// %7B%25 assig @@ -695,13 +695,8 @@ d:'/ -blog/ post @@ -825,18 +825,16 @@ nify%7D%7D,%0A -// %22image
d2c48cfa207b9b5b27774a9f3fa4fae4d243760e
Test code
js/menuLogic.js
js/menuLogic.js
"use strict"; var user = undefined; // Using a redirect. firebase.auth().getRedirectResult().then(function(result) { if (result.credential) { // This gives you a Google Access Token. var token = result.credential.accessToken; } user = result.user; }); if (user !== undefined) { $("#mainMenu-loginMenu").hide(); $("#controls").show(); $("#logoutBtn").show(); } var navigateLogin = function() { $("#mainMenu").hide(); $("#mainMenu-loginMenu").show(); }; var navigateRegister = function() { $("#mainMenu").hide(); $("#mainMenu-registerMenu").show(); }; var navigateFreePlay = function() { $("#mainMenu").hide(); $("#controls").show(); }; var navigateModes = function() { $("#controls").hide(); $("#modes").show(); }; var navigateGrids = function() { $("#modes").hide(); $("#mainLogo").hide(); $("#grids").show(); }; var navigateMenu = function() { $("#mainMenu").show(); $("#mainMenu-registerMenu").hide(); $("#mainMenu-loginMenu").hide(); $("#controls").hide(); }; var navigateType = function() { $("#modes").hide(); $("#controls").show(); }; var loginUser = function() { var loginEmail = document.getElementById('loginEmail'); var loginPassword = document.getElementById('loginPassword'); var loginError = document.getElementById('loginError'); firebase.auth().signInWithEmailAndPassword(loginEmail.value, loginPassword.value).then(function() { $("#mainMenu-loginMenu").hide(); $("#controls").show(); $("#logoutBtn").show(); }).catch(function(error) { loginError.innerHTML = error; }); }; var loginUserGoogle = function() { var provider = new firebase.auth.GoogleAuthProvider(); firebase.auth().signInWithRedirect(provider); }; var registerUser = function() { var registerEmail = document.getElementById('registerEmail'); var registerPassword = document.getElementById('registerPassword'); var registerError = document.getElementById('registerError'); firebase.auth().createUserWithEmailAndPassword(registerEmail.value, registerPassword.value).then(function() { $("#mainMenu-loginMenu").hide(); $("#controls").show(); $("#logoutBtn").show(); }).catch(function(error) { registerError.innerHTML = error; }); }; var loadGame = function(x, y) { var text = encodeURI('VRgame.html#gridY=' + y + '&gridX=' + x); window.location.href = text; }; var signOut = function() { firebase.auth().signOut().then(function() { location.reload(); }, function(error) { }); };
JavaScript
0.000001
@@ -268,16 +268,109 @@ lt.user; +%0A%0A $(%22#mainMenu-loginMenu%22).hide();%0A $(%22#controls%22).show();%0A $(%22#logoutBtn%22).show(); %0A%7D);%0A%0Aif
c2ec4bcfb81d7d21141710a68e3588df8f87f4c5
maintain consistent code style
lib/timelines/timelines.js
lib/timelines/timelines.js
'use strict'; var EventHandler = require('./../utilities/event-handler'); var converter = require('framework-utilities/converter'); var toSalty = converter.sweetToSalty; var piecewise = require('./../helpers/helpers').piecewise; function Timelines(timelineGroups, states) { EventHandler.apply(this); this._timelineGroups = timelineGroups || {}; this._states = states; this._currName = null; this._currTimeline = null; this._pausedTimelines = {}; this._behaviorList = this._createBehaviors(); } Timelines.prototype = Object.create(EventHandler.prototype); Timelines.prototype.constructor = Timelines; Timelines.prototype._createBehaviors = function _createBehaviors() { var behaviors = {}; for (var timelineName in this._timelineGroups) { var behaviorGroup = this._timelineGroups[timelineName]; var time = '__' + timelineName + 'Time'; var saltyTimeline = toSalty(behaviorGroup); for (var selectorBehavior in saltyTimeline) { var timeline = saltyTimeline[selectorBehavior]; var selector = selectorBehavior.split('|')[0]; var behavior = selectorBehavior.split('|')[1]; if (!behaviors[selector]) behaviors[selector] = {}; var valueFunction = 'BEST.helpers.piecewise(' + JSON.stringify(timeline) + ')'; behaviors[selector][behavior] = new Function(time, 'return ' + valueFunction + '(' + time + ')' ); } } return behaviors; } Timelines.prototype.getBehaviors = function getBehaviors() { return this._behaviorList || {}; } Timelines.prototype.get = function get(timelineName) { this._currTimeline = toSalty(this._timelineGroups[timelineName]); this._currName = timelineName; this._currStateName = '__' + timelineName + 'Time'; return this; }; Timelines.prototype.start = function start(options) { options = options || {}; var speed = options.speed || 1; var duration = options.duration || 0; var transition = {duration: duration / speed}; this._states.set(this._currStateName, 0); this._states.set(this._currStateName, duration, transition); this._setPaused(this._currName, false); return this; }; Timelines.prototype.halt = function halt() { var timeElapsed = this._states.get(this._currStateName); // duration is needed until all states are stored in Transitionables this._states.set(this._currStateName, timeElapsed, {duration: 0}); this._setPaused(this._currName, true); return this; }; Timelines.prototype.resume = function resume() { var speed = this._currSpeed; var totalTime = this._currDuration; var timeElapsed = this._states.get(this._currStateName); var timeLeft = totalTime - timeElapsed; this._states.set(this._currStateName, totalTime, {duration: timeLeft / speed}); this._setPaused(this._currName, false); return this; }; Timelines.prototype.rewind = function rewind() { var speed = this._currSpeed; var timeElapsed = this._states.get(this._currStateName); var transition = {duration: timeElapsed / speed}; this._states.set(this._currStateName, 0, transition); this._setPaused(this._currName, false); return this; }; Timelines.prototype.isPaused = function isPaused() { return this._pausedTimelines[this._currName] || false; }; Timelines.prototype._setPaused = function _setPaused(timelineName, bool) { this._pausedTimelines[timelineName] = bool; }; Timelines.mergeBehaviors = function(definitionBehaviors, timelineBehaviors) { var behaviors = definitionBehaviors; for (var selector in timelineBehaviors) { var timelineSelector = timelineBehaviors[selector]; var definitionSelector = definitionBehaviors[selector]; if (definitionSelector) { for (var behavior in timelineSelector) { var timelineBehavior = timelineSelector[behavior]; var definitionBehavior = definitionSelector[behavior]; if (definitionBehavior) { /* decide on injected timelineArgument api */ } else { behaviors[selector][behavior] = timelineBehavior; } } } } return behaviors; }; module.exports = Timelines;
JavaScript
0.00106
@@ -3894,33 +3894,32 @@ - var timelineBeha @@ -3949,25 +3949,24 @@ %5Bbehavior%5D;%0A - @@ -4037,25 +4037,24 @@ - if (definiti @@ -4115,17 +4115,16 @@ pi */ %7D%0A -
0c271db3766effc35aa26118c1620ec6f7764b4f
Fix broken log object output.
lib/utils/requestLogger.js
lib/utils/requestLogger.js
var _ = require('underscore'); exports.create = function(logger) { const PAYLOAD_PREVIEW_LENGTH = 1024; const EXPOSED_CENSOR_CHARS = 4; var logRequest = (verb, requestOptions) => { logRequestBasics('info', verb, requestOptions); logHeaders(requestOptions.headers); logPayload(requestOptions.body); //TODO: Restrict payload rendering MIME types }; var logRetryAttempt = (verb, requestOptions, error, attemptNum) => { logger.warn('Request failed, performing retry #%d\nCause: %O', attemptNum, error); logRequestBasics('warn', verb, requestOptions); }; var logRetryFailure = (verb, requestOptions, error, attemptNum) => { logger.error('Request failed after %d retries\nCause: %O', attemptNum, error); logRequestBasics('error', verb, requestOptions); }; var logSuccessfulResponse = response => { logger.info('Response: Success (HTTP %d)', response.statusCode); logHeaders(response.headers); logPayload(response.body); }; var logErrorResponse = (verb, requestOptions, error) => { logRequestBasics('error', verb, requestOptions); var {statusCode, errorCode, message, refId} = error; logger.error( 'Response: Failure (HTTP %d)\nError Code: %d - %s\nRef ID: %s', statusCode, errorCode, message, refId); logHeaders(error.headers); logPayload(error.body); //TODO: Censor token results }; var logRequestBasics = (level, verb, requestOptions) => { var url = buildLoggingUrl(requestOptions); logger.log(level, '%s %s', verb, url); }; var logHeaders = headers => { if(_.isEmpty(headers)) return; logger.silly('Headers: %O', headers); }; var logPayload = payload => { if(_.isEmpty(payload)) return; var preview = payload; if(preview.length > PAYLOAD_PREVIEW_LENGTH) { preview = payload.substring(0, PAYLOAD_PREVIEW_LENGTH) + '...'; } logger.verbose('Payload (preview): %s', preview); logger.debug('Payload (full): %s', payload); }; // Formatting Utilities var buildLoggingUrl = requestOptions => { var queryParams = ''; var qs = requestOptions.qs; if(!_.isEmpty(qs)) { qs = censorQueryParams(qs); queryParams = '?' + (_.pairs(qs) .map(([key, val]) => `${encodeURIComponent(key)}=${encodeURIComponent(val)}`) .join('&')); } return requestOptions.url + queryParams; }; const queryParamBlacklist = ['code', 'client_id', 'hash', 'refresh_token'].sort(); var censorQueryParams = buildCensor(queryParamBlacklist); var headerBlacklist = ['authorization'].sort(); var censorHeaders = buildCensor(headerBlacklist); var buildCensor = function(blacklist) { return obj => _.mapObject(obj, (val, key) => { var keyMatch = key.toLowerCase(); return (blacklist.indexOf(keyMatch) != -1) // Found in censor blacklist ? censor(val) : val; }); }; var censor = s => { if(_.isEmpty(s)) return s; var censoredSection = '*'.repeat(Math.max(s.length - EXPOSED_CENSOR_CHARS, 0)); var exposedSection = s.slice(-EXPOSED_CENSOR_CHARS); return censoredSection + exposedSection; }; // Generated object return { logRequest: logRequest, logRetryAttempt: logRetryAttempt, logRetryFailure: logRetryFailure, logSuccessfulResponse: logSuccessfulResponse, logErrorResponse: logErrorResponse }; }; const doNothing = () => {}; exports.empty = { logRequest: doNothing, logRetryAttempt: doNothing, logRetryFailure: doNothing, logSuccessfulResponse: doNothing, logErrorResponse: doNothing };
JavaScript
0.000002
@@ -488,34 +488,32 @@ try #%25d%5CnCause: -%25O ', attemptNum, e @@ -708,18 +708,16 @@ nCause: -%25O ', attem @@ -735,61 +735,8 @@ r);%0A - logRequestBasics('error', verb, requestOptions);%0A %7D; @@ -1577,10 +1577,8 @@ rs: -%25O ', h
184eb8bf0f473fa5b54c1661e9f4522d5d943eec
Check the message before parsing
lib/message/message-parser.js
lib/message/message-parser.js
// telegram-mt-node // Copyright 2014 Enrico Stara '[email protected]' // Released under the MIT License // https://github.com/enricostara/telegram-mt-node // MessageParser class // // This class provide a parser for the messages from Telegram // Import dependencies require('requirish')._(module); var logger = require('get-log')('message.MessageParser'); // The constructor function MessageParser() { } // Extend `events.EventEmitter` class require('util').inherits(MessageParser, require('events').EventEmitter); MessageParser.prototype.parse = function (message, duration) { switch (message.getTypeName()) { case 'mtproto.type.Msg_container': var msgs = message.messages.list; if (logger.isDebugEnabled()) { logger.debug('MessageContainer found with [%s] messages', msgs.length) } for (var i = 0; i < msgs.length; i++) { this.parse(msgs[i], duration); } break; case 'mtproto.type.Message': if (logger.isDebugEnabled()) { logger.debug('Message found with id [%s]', message.msg_id) } var body = message.body; body._messageId = message.msg_id; this.parse(body, duration); break; case 'mtproto.type.Msgs_ack': if (logger.isDebugEnabled()) { logger.debug('Msgs-Acknowledgement for %s ids', message.msg_ids.list) } this.emit(message.getTypeName(), message.msg_ids.list); break; default : if (logger.isDebugEnabled()) { logger.debug('%s found', message.getTypeName(), duration); } this.emit(message.getTypeName(), message, duration); } }; // Export the class module.exports = exports = MessageParser;
JavaScript
0
@@ -598,24 +598,152 @@ duration) %7B%0A + if(!message %7C%7C !message.getTypeName) %7B%0A logger.error('Message undefined or unknown', message);%0A return;%0A %7D%0A switch (