<commit_before>var jsbinInitializer = (function(){
  function setup(){
    var storedSettings = store.localStorage.getItem('settings');
    if (storedSettings === "undefined") {
      // yes, equals the *string* "undefined", then something went wrong
      storedSettings = null;
    }

    // In all cases localStorage takes precedence over user settings so users can
    // configure it from the console and overwrite the server delivered settings
    jsbin.settings = $.extend({}, jsbin.settings, JSON.parse(storedSettings || '{}'));

    if (jsbin.user) {
      jsbin.settings = $.extend({}, jsbin.user.settings, jsbin.settings);
    }

    // if the above code isn't dodgy, this for hellz bells is:
    jsbin.mobile = /WebKit.*Mobile.*|Android/.test(navigator.userAgent);
    jsbin.tablet = /iPad/i.test(navigator.userAgent); // sue me.
    // IE detect - sadly uglify is compressing the \v1 trick to death :(
    // via @padolsey & @jdalton - https://gist.github.com/527683
    jsbin.ie = (function(){
      var undef,
          v = 3,
          div = document.createElement('div'),
          all = div.getElementsByTagName('i');
      while (
        div.innerHTML = '',
        all[0]
      );
      return v > 4 ? v : undef;
    }());

    if (!storedSettings && (location.origin + location.pathname) === jsbin.root + '/') {
      // first timer - let's welcome them shall we, Dave?
      store.localStorage.setItem('settings', '{}');
    }

    if (!jsbin.settings.editor) {
      // backward compat with jsbin-v2
      jsbin.settings.editor = {};
    }

    if (jsbin.settings.codemirror) {
      $.extend(jsbin.settings.editor, jsbin.settings.codemirror);
    }

    if (jsbin.settings.editor.theme) {
      $(document.documentElement).addClass('cm-s-' + jsbin.settings.editor.theme.split(' ')[0]);
    }

    // Add a pre-filter to all ajax requests to add a CSRF header to prevent
    // malicious form submissions from other domains.
    jQuery.ajaxPrefilter(function (options, original, xhr) {
      var skip = {head: 1, get: 1};
      if (!skip[options.type.toLowerCase()] &&
          !options.url.match(/^https:\/\/api.github.com/)) {
        xhr.setRequestHeader('X-CSRF-Token', jsbin.state.token);
      }
    });

    jsbin.owner = function () {
      return jsbin.user && jsbin.user.name && jsbin.state.metadata && jsbin.state.metadata.name === jsbin.user.name;
    };

    jsbin.getURL = function (options) {
      if (!options) { options = {}; }

      var withoutRoot = options.withoutRoot;
      var url = withoutRoot ? '' : jsbin.root;
      var state = jsbin.state;

      if (state.code) {
        url += '/' + state.code;

        if (!state.latest || options.withRevision) { //} && state.revision !== 1) {
          if (options.withRevision !== false) {
            url += '/' + (state.revision || 1);
          }
        }
      }
      return url;
    };

    jsbin.state.updateSettings = throttle(function updateBinSettingsInner(update, method) {
      if (!method) {
        method = 'POST';
      }

      if (jsbin.state.code) {
        $.ajax({
          type: method, // consistency ftw :-\
          url: jsbin.getURL({ withRevision: true }) + '/settings',
          data: update
        });
      }
    }, 500);

    $window.unload(unload);

    // window.addEventListener('storage', function (e) {
    //   if (e.storageArea === localStorage && e.key === 'settings') {
    //     console.log('updating from storage');
    //     console.log(JSON.parse(store.localStorage.settings));
    //     jsbin.settings = JSON.parse(store.localStorage.settings);
    //   }
    // });

    // hack for Opera because the unload event isn't firing to capture the settings, so we put it on a timer
    if ($.browser.opera) {
      setInterval(unload, 500);
    }

    if (location.search.indexOf('api=') !== -1) {
      (function () {
        var urlParts = location.search.substring(1).split(','),
            newUrlParts = [],
            i = urlParts.length,
            apiurl = '';

        while (i--) {
          if (urlParts[i].indexOf('api=') !== -1) {
            apiurl = urlParts[i].replace(/&?api=/, '');
          } else {
            newUrlParts.push(urlParts[i]);
          }
        }

        $.getScript(jsbin.root + '/js/chrome/sandbox.js', function () {
          var sandbox = new Sandbox(apiurl);
          sandbox.get('settings', function (data) {
            $.extend(jsbin.settings, data);
            unload();
            window.location = location.pathname + (newUrlParts.length ? '?' + newUrlParts.join(',') : '');
          });
        });

      }());
    }

    $document.one('jsbinReady', function () {
      exposeSettings();
      $bin.removeAttr('style');
      $body.addClass('ready');
    });

    if (navigator.userAgent.indexOf(' Mac ') !== -1) (function () {
      var el = $('#keyboardHelp')[0];
      el.innerHTML = el.innerHTML.replace(/ctrl/g, 'cmd').replace(/Ctrl/g, 'ctrl');
    })();

    if (jsbin.embed) {
      $window.on('focus', function () {
        return false;
      });
    }
  }

  setup();
})();
<commit_msg>Refine jsbin_initializer<commit_after>var JsbinInitializer = (function(){
  function setup(){
    var storedSettings = store.localStorage.getItem('settings');
    if (storedSettings === "undefined") {
      // yes, equals the *string* "undefined", then something went wrong
      storedSettings = null;
    }

    // In all cases localStorage takes precedence over user settings so users can
    // configure it from the console and overwrite the server delivered settings
    jsbin.settings = $.extend({}, jsbin.settings, JSON.parse(storedSettings || '{}'));

    if (jsbin.user) {
      jsbin.settings = $.extend({}, jsbin.user.settings, jsbin.settings);
    }

    // if the above code isn't dodgy, this for hellz bells is:
    jsbin.mobile = /WebKit.*Mobile.*|Android/.test(navigator.userAgent);
    jsbin.tablet = /iPad/i.test(navigator.userAgent); // sue me.
    // IE detect - sadly uglify is compressing the \v1 trick to death :(
    // via @padolsey & @jdalton - https://gist.github.com/527683
    jsbin.ie = (function(){
      var undef,
          v = 3,
          div = document.createElement('div'),
          all = div.getElementsByTagName('i');
      while (
        div.innerHTML = '',
        all[0]
      );
      return v > 4 ? v : undef;
    }());

    if (!storedSettings && (location.origin + location.pathname) === jsbin.root + '/') {
      // first timer - let's welcome them shall we, Dave?
      store.localStorage.setItem('settings', '{}');
    }

    if (!jsbin.settings.editor) {
      // backward compat with jsbin-v2
      jsbin.settings.editor = {};
    }

    if (jsbin.settings.codemirror) {
      $.extend(jsbin.settings.editor, jsbin.settings.codemirror);
    }

    if (jsbin.settings.editor.theme) {
      $(document.documentElement).addClass('cm-s-' + jsbin.settings.editor.theme.split(' ')[0]);
    }

    // Add a pre-filter to all ajax requests to add a CSRF header to prevent
    // malicious form submissions from other domains.
    jQuery.ajaxPrefilter(function (options, original, xhr) {
      var skip = {head: 1, get: 1};
      if (!skip[options.type.toLowerCase()] &&
          !options.url.match(/^https:\/\/api.github.com/)) {
        xhr.setRequestHeader('X-CSRF-Token', jsbin.state.token);
      }
    });

    jsbin.owner = function () {
      return jsbin.user && jsbin.user.name && jsbin.state.metadata && jsbin.state.metadata.name === jsbin.user.name;
    };

    jsbin.getURL = function (options) {
      if (!options) { options = {}; }

      var withoutRoot = options.withoutRoot;
      var url = withoutRoot ? '' : jsbin.root;
      var state = jsbin.state;

      if (state.code) {
        url += '/' + state.code;

        if (!state.latest || options.withRevision) { //} && state.revision !== 1) {
          if (options.withRevision !== false) {
            url += '/' + (state.revision || 1);
          }
        }
      }
      return url;
    };

    jsbin.state.updateSettings = throttle(function updateBinSettingsInner(update, method) {
      if (!method) {
        method = 'POST';
      }

      if (jsbin.state.code) {
        $.ajax({
          type: method, // consistency ftw :-\
          url: jsbin.getURL({ withRevision: true }) + '/settings',
          data: update
        });
      }
    }, 500);

    $window.unload(unload);

    // window.addEventListener('storage', function (e) {
    //   if (e.storageArea === localStorage && e.key === 'settings') {
    //     console.log('updating from storage');
    //     console.log(JSON.parse(store.localStorage.settings));
    //     jsbin.settings = JSON.parse(store.localStorage.settings);
    //   }
    // });

    // hack for Opera because the unload event isn't firing to capture the settings, so we put it on a timer
    if ($.browser.opera) {
      setInterval(unload, 500);
    }

    if (location.search.indexOf('api=') !== -1) {
      (function () {
        var urlParts = location.search.substring(1).split(','),
            newUrlParts = [],
            i = urlParts.length,
            apiurl = '';

        while (i--) {
          if (urlParts[i].indexOf('api=') !== -1) {
            apiurl = urlParts[i].replace(/&?api=/, '');
          } else {
            newUrlParts.push(urlParts[i]);
          }
        }

        $.getScript(jsbin.root + '/js/chrome/sandbox.js', function () {
          var sandbox = new Sandbox(apiurl);
          sandbox.get('settings', function (data) {
            $.extend(jsbin.settings, data);
            unload();
            window.location = location.pathname + (newUrlParts.length ? '?' + newUrlParts.join(',') : '');
          });
        });

      }());
    }

    $document.one('jsbinReady', function () {
      exposeSettings();
      $bin.removeAttr('style');
      $body.addClass('ready');
    });

    if (navigator.userAgent.indexOf(' Mac ') !== -1) (function () {
      var el = $('#keyboardHelp')[0];
      el.innerHTML = el.innerHTML.replace(/ctrl/g, 'cmd').replace(/Ctrl/g, 'ctrl');
    })();

    if (jsbin.embed) {
      $window.on('focus', function () {
        return false;
      });
    }
  }

  return {
    setup: setup
  }
})();

JsbinInitializer.setup();
<|endoftext|>


<commit_before>'use strict';

/**
 *  @ngdoc filter
 *  @name zeus.utils:prettyNumber
 *
 *  @description
 *  Converts large numbers to human readable strings
 *
 *  @param { number } num The large number
 *  @param { number=} precision The numeric precision
 *
 *  @returns { string } Human readable format of the large number
 *
 *  @example
 <example module="zeus.utils">
    <file name="index.html">

 {{ 1407919200 | prettyNumber }}

 {{ 158291 | prettyNumber }}

 {{ 1397828100000 | prettyNumber }}

 {{ 14079192 | prettyNumber }}

    </file>
 </example>
 **/
angular.module( 'zeus.utils' )
    .filter( 'prettyNumber', function () {

        var units = [ '', 'K', 'M', 'B', 'T' ],
            prettyNumber;

        prettyNumber = function ( num, precision ) {

            var temp = num,
                i, decimals, result;

            precision = precision || 1;

            for ( i = 0; i < units.length; i++ ) {
                if ( temp >= 1000 ) {
                    decimals = temp % 1000;
                    temp = temp / 1000;
                } else {
                    break;
                }
            }

            if ( decimals > 0 ) {
                decimals = +( decimals / 1000 ).toFixed( precision );
                result = ( Math.floor( temp ) + decimals ) +
                    '' + units[ i ];
            } else {
                result = Math.round( temp ) + '' + units[ i ];
            }

            return result;

        };

        return prettyNumber;
    }
);
<commit_msg>Fix docs for prettyNumber<commit_after>'use strict';

/**
 *  @ngdoc filter
 *  @name zeus.utils.filter:prettyNumber
 *
 *  @description
 *  Converts large numbers to human readable strings
 *
 *  @param { number } num The large number
 *  @param { number=} precision The numeric precision
 *
 *  @returns { string } Human readable format of the large number
 *
 *  @example
 <example module="zeus.utils">
    <file name="index.html">

 {{ 1407919200 | prettyNumber }}

 {{ 158291 | prettyNumber }}

 {{ 1397828100000 | prettyNumber }}

 {{ 14079192 | prettyNumber }}

    </file>
 </example>
 **/
angular.module( 'zeus.utils' )
    .filter( 'prettyNumber', function () {

        var units = [ '', 'K', 'M', 'B', 'T' ],
            prettyNumber;

        prettyNumber = function ( num, precision ) {

            var temp = num,
                i, decimals, result;

            precision = precision || 1;

            for ( i = 0; i < units.length; i++ ) {
                if ( temp >= 1000 ) {
                    decimals = temp % 1000;
                    temp = temp / 1000;
                } else {
                    break;
                }
            }

            if ( decimals > 0 ) {
                decimals = +( decimals / 1000 ).toFixed( precision );
                result = ( Math.floor( temp ) + decimals ) +
                    '' + units[ i ];
            } else {
                result = Math.round( temp ) + '' + units[ i ];
            }

            return result;

        };

        return prettyNumber;
    }
);
<|endoftext|>


<commit_before>(function(e){var t=["Moz","Webkit","Khtml","O","ms"],n=["TransitionProperty","TransitionTiming","TransitionDelay","TransitionDuration","TransitionEnd"],r=["rotate","scale","skew","translate","translatex","translatey","matrix"],i=function(e){return e.charAt(0).toUpperCase()+e.substr(1)},s=document.createElement("div"),o=function(e){var n;if(e in s.style){return e}for(var r=0;r<t.length;r+=1){n=t[r]+i(e);if(n in s.style){return n}}return e},u=function(){var e=document.body||document.documentElement,n=e.style,r="transition";if(typeof n[r]=="string"){return true}r=r.charAt(0).toUpperCase()+r.substr(1);for(var i=0;i<t.length;i++){if(typeof n[t[i]+r]=="string"){return true}}return false},a=function(e){var t=0,n;e+="";e=e.toLowerCase();if(e.indexOf("ms")!==-1){n=e.split("ms");t=Number(n[0])}else if(e.indexOf("s")!==-1){n=e.split("s");t=Number(n[0])*1e3}else{t=Number(e)}return Math.round(t)},f=function(e,t){for(var n in t){if(t.hasOwnProperty(n)){e.style[o(n)]=t[n]}}},l=function(e){var t={TransitionTiming:"ease",TransitionDuration:"0.5s",TransitionProperty:"all"},s,u,a,f,l;for(s in e){if(e.hasOwnProperty(s)){a="Transition"+i(s);f=s.toLowerCase();l=false;for(u=0;u<n.length;u+=1){if(a==n[u]){t[n[u]]=e[s];l=true;break}}for(u=0;u<r.length;u+=1){if(f==r[u]){t[o("transform")]=t[o("transform")]||"";t[o("transform")]+=" "+s+"("+e[s]+")";l=true;break}}if(!l){t[s]=e[s]}}}return t},c=function(e){for(var t in e){if(e.hasOwnProperty(t)){return false}}return true},h=u();e.animateVDOM=function(t,n){var r=t.config;t.config=function(i,s,o){e.animateElement(i,n);if(r){r.apply(t,arguments)}}};e.animate=function(e,t){e.style=e.style||{};var r=l(t),i={},s=a(r.TransitionDuration)||0;n.map(function(t,n){var r=e.style[t];if(r){i[t]=r}});if(e.style["transform"]){i["transform"]=e.style["transform"]}clearTimeout(e.propTimer);e.propTimer=setTimeout(function(){n.map(function(t){var n={};n[t]="";f(e,n)});if(!c(i)){f(e,i)}},s);if(h){f(e,r)}else{if(typeof $!=="undefined"&&$.fn&&$.fn.animate){$(e).animate(r,a(r.TransitionDuration))}}}})(window.m||{})<commit_msg>No need to remove properties<commit_after>(function(e){var t=["Moz","Webkit","Khtml","O","ms"],n=["TransitionProperty","TransitionTiming","TransitionDelay","TransitionDuration","TransitionEnd"],r=["rotate","scale","skew","translate","translatex","translatey","matrix"],i=function(e){return e.charAt(0).toUpperCase()+e.substr(1)},s=document.createElement("div"),o=function(e){var n;if(e in s.style){return e}for(var r=0;r<t.length;r+=1){n=t[r]+i(e);if(n in s.style){return n}}return e},u=function(){var e=document.body||document.documentElement,n=e.style,r="transition";if(typeof n[r]=="string"){return true}r=r.charAt(0).toUpperCase()+r.substr(1);for(var i=0;i<t.length;i++){if(typeof n[t[i]+r]=="string"){return true}}return false},a=function(e){var t=0,n;e+="";e=e.toLowerCase();if(e.indexOf("ms")!==-1){n=e.split("ms");t=Number(n[0])}else if(e.indexOf("s")!==-1){n=e.split("s");t=Number(n[0])*1e3}else{t=Number(e)}return Math.round(t)},f=function(e,t){for(var n in t){if(t.hasOwnProperty(n)){e.style[o(n)]=t[n]}}},l=function(e){var t={TransitionTiming:"ease",TransitionDuration:"0.5s",TransitionProperty:"all"},s,u,a,f,l;for(s in e){if(e.hasOwnProperty(s)){a="Transition"+i(s);f=s.toLowerCase();l=false;for(u=0;u<n.length;u+=1){if(a==n[u]){t[n[u]]=e[s];l=true;break}}for(u=0;u<r.length;u+=1){if(f==r[u]){t[o("transform")]=t[o("transform")]||"";t[o("transform")]+=" "+s+"("+e[s]+")";l=true;break}}if(!l){t[s]=e[s]}}}return t},c=function(e){for(var t in e){if(e.hasOwnProperty(t)){return false}}return true},h=u();e.animateVDOM=function(t,n){var r=t.config;t.config=function(i,s,o){e.animateElement(i,n);if(r){r.apply(t,arguments)}}};e.animate=function(e,t){e.style=e.style||{};var n=l(t);if(h){f(e,n)}else{if(typeof $!=="undefined"&&$.fn&&$.fn.animate){$(e).animate(n,a(n.TransitionDuration)||0)}}}})(window.m||{})<|endoftext|>


<commit_before>var gulp = require('gulp'); // needed
var concat = require('gulp-concat'); // needed for build task
var connect = require('gulp-connect'); // needed for server task
var insert = require('gulp-insert'); // needed for build task
var replace = require('gulp-replace'); // needed for build task
var streamify = require('gulp-streamify'); // needed for build task
var uglify = require('gulp-uglify'); // needed for build task
var browserify = require('browserify'); // needed for build task
var source = require('vinyl-source-stream'); // needed for build task
var merge = require('merge-stream'); // needed for build task
var collapse = require('bundle-collapser/plugin'); // needed for build task
var packageJSON = require('./package.json');

var srcDir = './src/';
var outDir = './public/';

var header = "/*!\n" +
  " * Chart.js\n" +
  " * http://chartjs.org/\n" +
  " * Version: {{ version }}\n" +
  " *\n" +
  " * Copyright 2016 Nick Downie\n" +
  " * Released under the MIT license\n" +
  " * https://github.com/chartjs/Chart.js/blob/master/LICENSE.md\n" +
  " */\n";

gulp.task('build', buildTask);
gulp.task('watch', watchTask);
gulp.task('server', serverTask);
gulp.task('dev', ['server', 'default']);
gulp.task('default', ['build', 'watch']);

/**
 * Generates the bower.json manifest file which will be pushed along release tags.
 * Specs: https://github.com/bower/spec/blob/master/json.md
 */

function buildTask() {

  var nonBundled = browserify('./src/chart.js', { standalone: 'Chart' })
    .plugin(collapse)
    .bundle()
    .pipe(source('Chart.js'))
    .pipe(streamify(uglify()))
    .pipe(insert.prepend(header))
    .pipe(streamify(replace('{{ version }}', packageJSON.version)))
    .pipe(streamify(concat('Chart.min.js')))
    .pipe(gulp.dest(outDir));

  return merge(nonBundled);

}

function watchTask() {
  return gulp.watch('./src/**', ['build']);
}

function serverTask() {
  connect.server({
    port: 8000
  });
}
<commit_msg>removed some unneeded lines<commit_after>var gulp = require('gulp'); // needed
var concat = require('gulp-concat'); // needed for build task
var connect = require('gulp-connect'); // needed for server task
var insert = require('gulp-insert'); // needed for build task
var replace = require('gulp-replace'); // needed for build task
var streamify = require('gulp-streamify'); // needed for build task
var uglify = require('gulp-uglify'); // needed for build task
var browserify = require('browserify'); // needed for build task
var source = require('vinyl-source-stream'); // needed for build task
var merge = require('merge-stream'); // needed for build task
var collapse = require('bundle-collapser/plugin'); // needed for build task
var packageJSON = require('./package.json');

var srcDir = './src/';
var outDir = './public/';

var header = "/*!\n" +
  " * Chart.js\n" +
  " * http://chartjs.org/\n" +
  " * Version: 2.3.0\n" +
  " *\n" +
  " * Copyright 2016 Nick Downie\n" +
  " * Released under the MIT license\n" +
  " * https://github.com/chartjs/Chart.js/blob/master/LICENSE.md\n" +
  " */\n";

gulp.task('build', buildTask);
gulp.task('watch', watchTask);
gulp.task('server', serverTask);
gulp.task('dev', ['server', 'default']);
gulp.task('default', ['build', 'watch']);

function buildTask() {

  var nonBundled = browserify('./src/chart.js', { standalone: 'Chart' })
    .plugin(collapse)
    .bundle()
    .pipe(source('Chart.js'))
    .pipe(streamify(uglify()))
    .pipe(insert.prepend(header))
    .pipe(streamify(concat('Chart.min.js')))
    .pipe(gulp.dest(outDir));

  return merge(nonBundled);

}

function watchTask() {
  return gulp.watch('./src/**', ['build']);
}

function serverTask() {
  connect.server({
    port: 8000
  });
}
<|endoftext|>


<commit_before>var utils = require('../utils'),
    packages = require('../packages'),
    logger = require('../logger'),
    couchdb = require('../couchdb'),
    kansorc = require('../kansorc'),
    argParse = require('../args').parse,
    exec = require('child_process').exec,
    path = require('path'),
    fs = require('fs'),
    pathExists = fs.exists || path.exists,
    url = require('url'),
    urlParse = url.parse,
    urlFormat = url.format;

exports.summary = 'Load a project and push to a CouchDB database';

exports.usage = '' +
'kanso push [PATH] [DB]\n' +
'\n' +
'Parameters:\n' +
'  PATH    Path to project directory to push (defaults to ".")\n' +
'  DB      The CouchDB database to upload the app to, will use "default"\n' +
'          env set in .kansorc if none provided and .kansorc exists\n' +
'\n' +
'Options:\n' +
'  --minify    Compress CommonJS modules attachment using UglifyJS\n' +
'  --open      Open the app URL in the browser after pushing\n' +
'  --baseURL   Add a custom baseURL property to the kanso.json values\n' +
'  --id        Specify a custom document id for the generated app,\n' +
'              defaults to "_design/<name>" where <name> is from kanso.json';

/**
 * Main command called when typing "kanso push ..." on the command line
 */

exports.run = function (settings, args) {
    var a = argParse(args, {
        'minify': {match: '--minify'},
        'open': {match: '--open'},
        'baseURL': {match: '--baseURL', value: true},
        'id': {match: '--id', value: true}
    });
    var url;
    var dir = a.positional[0] || '.';
    pathExists(dir, function (exists) {
        if (!exists) {
            dir = process.cwd();
            url = a.positional[0];
        }
        dir = utils.abspath(dir);
        kansorc.extend(settings, dir + '/.kansorc', function (err, settings) {
            if (err) {
                return logger.error(err);
            }
            if (a.positional.length > 1) {
                url = a.positional[1];
            }
            else if (a.positional.length && !exists) {
                url = a.positional[0];
            }

            var env = utils.argToEnv(settings, url);
            url = env.db;
            if (env.baseURL) {
                a.options.baseURL = env.baseURL;
            }
            if (env.minify) {
                a.options.minify = env.minify;
            }
            if (env.id) {
                a.options.id = env.id;
            }

            // these options will override values in kanso.json
            // the 'id' and 'open' options are not relevant to that data
            var opt = env.overrides || {};
            opt.minify = a.options.minify;
            opt.baseURL = a.options.baseURL;

            exports.loadApp(dir, url, opt, settings,
                function (err, url, cfg, doc) {
                    if (err) {
                        return logger.error(err);
                    }
                    var app_url = exports.getAppURL(url, cfg, doc);
                    var noauth_url = utils.noAuthURL(app_url);

                    if (a.options.open) {
                        exports.openInBrowser(app_url, function (err) {
                            if (err) {
                                return logger.error(err);
                            }
                            logger.end(noauth_url);
                        });
                    }
                    else {
                        logger.end(noauth_url);
                    }
                }
            );
        });
    });
};

/**
 * Builds the app prior to pushing
 */

exports.loadApp = function (dir, url, options, settings, callback) {
    var paths = settings.package_paths || [];
    var parent_dir = path.dirname(dir);
    if (path.basename(parent_dir) === 'packages') {
        paths.push(parent_dir);
    }
    var build_start = new Date().getTime();
    packages.load(dir, paths, null, options, function (err, doc, cfg) {
        if (err) {
            if (callback) {
                return callback(err);
            }
            else {
                return logger.error(err);
            }
        }
        var build_end = new Date().getTime();
        console.log('Build complete: ' + (build_end - build_start) + 'ms');
        utils.completeAuth(url, false, function (err, url) {
            if (err) {
                return callback(err);
            }
            utils.catchAuthError(
                exports.push, url, [dir, options, cfg, doc], callback
            );
        });
    });
};

/**
 * Upload the app to the DB, catch auth errors and prompt for password
 */

exports.push = function (url, dir, options, cfg, doc, callback) {
    var db = couchdb(url);
    var root = couchdb(url);
    root.instance.pathname = '';
    root.session(function (err, info, resp) {
        if (err) {
            return callback(err);
        }
        var server_time = utils.ISODateString(new Date(resp.headers.date));
        if (!doc.kanso) {
            doc.kanso = {};
        }
        doc.kanso.push_time = server_time;
        doc.kanso.pushed_by = info.userCtx.name;

        db.ensureDB(function (err) {
            if (err) {
                return callback(err);
            }
            var id = options.id || '_design/' + cfg.name;
            logger.info('Uploading...');

            db.save(id, doc, {force: true}, function (err) {
                callback(err, url, cfg, doc);
            });
        });
    });
};

/**
 * Tries to determine the right URL to report on the command-line after a
 * successful push
 *
 * OK: <url>
 */

exports.getAppURL = function (url, cfg, doc) {
    var newurl= urlParse(url);
    delete newurl.auth;
    delete newurl.host;
    var ddoc_url = urlFormat(newurl) + '/' + doc._id;

    if (!/^_design\//.test(doc._id)) {
        // not pushed as a design doc, report doc url instead of app url
        return ddoc_url;
    }

    var app_url = ddoc_url;
    if (cfg.index) {
        // if there's an index property in kanso.json
        app_url = ddoc_url + cfg.index;
    }
    if (cfg.baseURL !== undefined) {
        // if there is a custom baseURL defined
        newurl.pathname = cfg.baseURL + '/';
        app_url = urlFormat(newurl);
    }
    else if (doc.rewrites && doc.rewrites.length) {
        app_url = ddoc_url + '/_rewrite/';
    }
    else if (doc._attachments && doc._attachments['index.html']) {
        app_url = ddoc_url + '/index.html';
    }
    else if (doc._attachments && doc._attachments['index.htm']) {
        app_url = ddoc_url + '/index.htm';
    }
    return app_url;
};

/**
 * Opens the app URL in the browser when the --open option is used
 */

exports.openInBrowser = function (url, callback) {
    if (process.platform === 'linux') {
        cmd = 'xdg-open';
    }
    else {
        // OSX
        cmd = 'open';
    }
    console.log('Opening URL in browser...');
    exec(cmd + ' ' + url, callback);
};
<commit_msg>Make the push url available on the options so modules can use<commit_after>var utils = require('../utils'),
    packages = require('../packages'),
    logger = require('../logger'),
    couchdb = require('../couchdb'),
    kansorc = require('../kansorc'),
    argParse = require('../args').parse,
    exec = require('child_process').exec,
    path = require('path'),
    fs = require('fs'),
    pathExists = fs.exists || path.exists,
    url = require('url'),
    urlParse = url.parse,
    urlFormat = url.format;

exports.summary = 'Load a project and push to a CouchDB database';

exports.usage = '' +
'kanso push [PATH] [DB]\n' +
'\n' +
'Parameters:\n' +
'  PATH    Path to project directory to push (defaults to ".")\n' +
'  DB      The CouchDB database to upload the app to, will use "default"\n' +
'          env set in .kansorc if none provided and .kansorc exists\n' +
'\n' +
'Options:\n' +
'  --minify    Compress CommonJS modules attachment using UglifyJS\n' +
'  --open      Open the app URL in the browser after pushing\n' +
'  --baseURL   Add a custom baseURL property to the kanso.json values\n' +
'  --id        Specify a custom document id for the generated app,\n' +
'              defaults to "_design/<name>" where <name> is from kanso.json';

/**
 * Main command called when typing "kanso push ..." on the command line
 */

exports.run = function (settings, args) {
    var a = argParse(args, {
        'minify': {match: '--minify'},
        'open': {match: '--open'},
        'baseURL': {match: '--baseURL', value: true},
        'id': {match: '--id', value: true}
    });
    var url;
    var dir = a.positional[0] || '.';
    pathExists(dir, function (exists) {
        if (!exists) {
            dir = process.cwd();
            url = a.positional[0];
        }
        dir = utils.abspath(dir);
        kansorc.extend(settings, dir + '/.kansorc', function (err, settings) {
            if (err) {
                return logger.error(err);
            }
            if (a.positional.length > 1) {
                url = a.positional[1];
            }
            else if (a.positional.length && !exists) {
                url = a.positional[0];
            }

            var env = utils.argToEnv(settings, url);
            url = env.db;
            if (env.baseURL) {
                a.options.baseURL = env.baseURL;
            }
            if (env.minify) {
                a.options.minify = env.minify;
            }
            if (env.id) {
                a.options.id = env.id;
            }

            // these options will override values in kanso.json
            // the 'id' and 'open' options are not relevant to that data
            var opt = env.overrides || {};
            opt.minify = a.options.minify;
            opt.baseURL = a.options.baseURL;

            exports.loadApp(dir, url, opt, settings,
                function (err, url, cfg, doc) {
                    if (err) {
                        return logger.error(err);
                    }
                    var app_url = exports.getAppURL(url, cfg, doc);
                    var noauth_url = utils.noAuthURL(app_url);

                    if (a.options.open) {
                        exports.openInBrowser(app_url, function (err) {
                            if (err) {
                                return logger.error(err);
                            }
                            logger.end(noauth_url);
                        });
                    }
                    else {
                        logger.end(noauth_url);
                    }
                }
            );
        });
    });
};

/**
 * Builds the app prior to pushing
 */

exports.loadApp = function (dir, url, options, settings, callback) {
    var paths = settings.package_paths || [];
    var parent_dir = path.dirname(dir);
    if (path.basename(parent_dir) === 'packages') {
        paths.push(parent_dir);
    }
    var build_start = new Date().getTime();
    // make the url available to the modules
    options._url = url;
    packages.load(dir, paths, null, options, function (err, doc, cfg) {
        if (err) {
            if (callback) {
                return callback(err);
            }
            else {
                return logger.error(err);
            }
        }
        var build_end = new Date().getTime();
        console.log('Build complete: ' + (build_end - build_start) + 'ms');
        utils.completeAuth(url, false, function (err, url) {
            if (err) {
                return callback(err);
            }
            utils.catchAuthError(
                exports.push, url, [dir, options, cfg, doc], callback
            );
        });
    });
};

/**
 * Upload the app to the DB, catch auth errors and prompt for password
 */

exports.push = function (url, dir, options, cfg, doc, callback) {
    var db = couchdb(url);
    var root = couchdb(url);
    root.instance.pathname = '';
    root.session(function (err, info, resp) {
        if (err) {
            return callback(err);
        }
        var server_time = utils.ISODateString(new Date(resp.headers.date));
        if (!doc.kanso) {
            doc.kanso = {};
        }
        doc.kanso.push_time = server_time;
        doc.kanso.pushed_by = info.userCtx.name;

        db.ensureDB(function (err) {
            if (err) {
                return callback(err);
            }
            var id = options.id || '_design/' + cfg.name;
            logger.info('Uploading...');

            db.save(id, doc, {force: true}, function (err) {
                callback(err, url, cfg, doc);
            });
        });
    });
};

/**
 * Tries to determine the right URL to report on the command-line after a
 * successful push
 *
 * OK: <url>
 */

exports.getAppURL = function (url, cfg, doc) {
    var newurl= urlParse(url);
    delete newurl.auth;
    delete newurl.host;
    var ddoc_url = urlFormat(newurl) + '/' + doc._id;

    if (!/^_design\//.test(doc._id)) {
        // not pushed as a design doc, report doc url instead of app url
        return ddoc_url;
    }

    var app_url = ddoc_url;
    if (cfg.index) {
        // if there's an index property in kanso.json
        app_url = ddoc_url + cfg.index;
    }
    if (cfg.baseURL !== undefined) {
        // if there is a custom baseURL defined
        newurl.pathname = cfg.baseURL + '/';
        app_url = urlFormat(newurl);
    }
    else if (doc.rewrites && doc.rewrites.length) {
        app_url = ddoc_url + '/_rewrite/';
    }
    else if (doc._attachments && doc._attachments['index.html']) {
        app_url = ddoc_url + '/index.html';
    }
    else if (doc._attachments && doc._attachments['index.htm']) {
        app_url = ddoc_url + '/index.htm';
    }
    return app_url;
};

/**
 * Opens the app URL in the browser when the --open option is used
 */

exports.openInBrowser = function (url, callback) {
    if (process.platform === 'linux') {
        cmd = 'xdg-open';
    }
    else {
        // OSX
        cmd = 'open';
    }
    console.log('Opening URL in browser...');
    exec(cmd + ' ' + url, callback);
};
<|endoftext|>


<commit_before>var Server = require("../server").Server;

// The ping strategy uses pings each server and records the
// elapsed time for the server so it can pick a server based on lowest
// return time for the db command {ping:true}
var PingStrategy = exports.PingStrategy = function(replicaset, secondaryAcceptableLatencyMS) {
  this.replicaset = replicaset;
  this.secondaryAcceptableLatencyMS = secondaryAcceptableLatencyMS;
  this.state = 'disconnected';
  this.pingInterval = 5000;
  // Class instance
  this.Db = require("../../db").Db;
}

// Starts any needed code
PingStrategy.prototype.start = function(callback) {
  // already running?
  if ('connected' == this.state) return;

  this.state = 'connected';

  // Start ping server
  this._pingServer(callback);
}

// Stops and kills any processes running
PingStrategy.prototype.stop = function(callback) {
  // Stop the ping process
  this.state = 'disconnected';
  // Call the callback
  callback(null, null);
}

PingStrategy.prototype.checkoutSecondary = function(tags, secondaryCandidates) {
  // Servers are picked based on the lowest ping time and then servers that lower than that + secondaryAcceptableLatencyMS
  // Create a list of candidat servers, containing the primary if available
  var candidateServers = [];

  // If we have not provided a list of candidate servers use the default setup
  if(!Array.isArray(secondaryCandidates)) {
    candidateServers = this.replicaset._state.master != null ? [this.replicaset._state.master] : [];
    // Add all the secondaries
    var keys = Object.keys(this.replicaset._state.secondaries);
    for(var i = 0; i < keys.length; i++) {
      candidateServers.push(this.replicaset._state.secondaries[keys[i]])
    }
  } else {
    candidateServers = secondaryCandidates;
  }

  // Final list of eligable server
  var finalCandidates = [];

  // If we have tags filter by tags
  if(tags != null && typeof tags == 'object') {
    // If we have an array or single tag selection
    var tagObjects = Array.isArray(tags) ? tags : [tags];
    // Iterate over all tags until we find a candidate server
    for(var _i = 0; _i < tagObjects.length; _i++) {
      // Grab a tag object
      var tagObject = tagObjects[_i];
      // Matching keys
      var matchingKeys = Object.keys(tagObject);
      // Remove any that are not tagged correctly
      for(var i = 0; i < candidateServers.length; i++) {
        var server = candidateServers[i];
        // If we have tags match
        if(server.tags != null) {
          var matching = true;

          // Ensure we have all the values
          for(var j = 0; j < matchingKeys.length; j++) {
            if(server.tags[matchingKeys[j]] != tagObject[matchingKeys[j]]) {
              matching = false;
              break;
            }
          }

          // If we have a match add it to the list of matching servers
          if(matching) {
            finalCandidates.push(server);
          }
        }
      }
    }
  } else {
    // Final array candidates
    var finalCandidates = candidateServers;
  }

  // Sort by ping time
  finalCandidates.sort(function(a, b) {
    return a.runtimeStats['pingMs'] > b.runtimeStats['pingMs'];
  });

  if(0 === finalCandidates.length)
    return new Error("No replica set members available for query");

  // handle undefined pingMs
  var lowestPing = finalCandidates[0].runtimeStats['pingMs'] | 0;

  // determine acceptable latency
  var acceptable = lowestPing + this.secondaryAcceptableLatencyMS;

  // remove any server responding slower than acceptable
  var len = finalCandidates.length;
  while(len--) {
    if(finalCandidates[len].runtimeStats['pingMs'] > acceptable) {
      finalCandidates.splice(len, 1);
    }
  }

  // If no candidates available return an error
  if(finalCandidates.length == 0)
    return new Error("No replica set members available for query");

  // Pick a random acceptable server
  return finalCandidates[Math.round(Math.random(1000000) * (finalCandidates.length - 1))].checkoutReader();
}

PingStrategy.prototype._pingServer = function(callback) {
  var self = this;

  // Ping server function
  var pingFunction = function() {
    if(self.state == 'disconnected') return;

    var addresses = self.replicaset._state.addresses;

    // Grab all servers
    var serverKeys = Object.keys(addresses);

    // Number of server entries
    var numberOfEntries = serverKeys.length;

    // We got keys
    for(var i = 0; i < serverKeys.length; i++) {

      // We got a server instance
      var server = addresses[serverKeys[i]];

      // Create a new server object, avoid using internal connections as they might
      // be in an illegal state
      new function(serverInstance) {
        var options = { poolSize: 1, timeout: 500, auto_reconnect: false };
        var server = new Server(serverInstance.host, serverInstance.port, options);
        var db = new self.Db(self.replicaset.db.databaseName, server);

        db.on("error", done);

        // Open the db instance
        db.open(function(err) {
          if (err) return done();

          // Startup time of the command
          var startTime = Date.now();

          // Execute ping on this connection
          db.executeDbCommand({ping:1}, function() {
            if(null != serverInstance.runtimeStats && serverInstance.isConnected()) {
              serverInstance.runtimeStats['pingMs'] = Date.now() - startTime;
            }
            done();
          })
        })

        function done () {
          // Close connection
          db.close();

          // Adjust the number of checks
          numberOfEntries--;

          // If we are done with all results coming back trigger ping again
          if(0 === numberOfEntries && 'connected' == self.state) {
            setTimeout(pingFunction, self.pingInterval);
          }
        }
      }(server);
    }
  }

  // Start pingFunction
  setTimeout(pingFunction, 1000);

  callback && callback(null);
}
<commit_msg>consistant api, callback to start/stop are optional<commit_after>var Server = require("../server").Server;

// The ping strategy uses pings each server and records the
// elapsed time for the server so it can pick a server based on lowest
// return time for the db command {ping:true}
var PingStrategy = exports.PingStrategy = function(replicaset, secondaryAcceptableLatencyMS) {
  this.replicaset = replicaset;
  this.secondaryAcceptableLatencyMS = secondaryAcceptableLatencyMS;
  this.state = 'disconnected';
  this.pingInterval = 5000;
  // Class instance
  this.Db = require("../../db").Db;
}

// Starts any needed code
PingStrategy.prototype.start = function(callback) {
  // already running?
  if ('connected' == this.state) return;

  this.state = 'connected';

  // Start ping server
  this._pingServer(callback);
}

// Stops and kills any processes running
PingStrategy.prototype.stop = function(callback) {
  // Stop the ping process
  this.state = 'disconnected';

  // optional callback
  callback && callback(null, null);
}

PingStrategy.prototype.checkoutSecondary = function(tags, secondaryCandidates) {
  // Servers are picked based on the lowest ping time and then servers that lower than that + secondaryAcceptableLatencyMS
  // Create a list of candidat servers, containing the primary if available
  var candidateServers = [];

  // If we have not provided a list of candidate servers use the default setup
  if(!Array.isArray(secondaryCandidates)) {
    candidateServers = this.replicaset._state.master != null ? [this.replicaset._state.master] : [];
    // Add all the secondaries
    var keys = Object.keys(this.replicaset._state.secondaries);
    for(var i = 0; i < keys.length; i++) {
      candidateServers.push(this.replicaset._state.secondaries[keys[i]])
    }
  } else {
    candidateServers = secondaryCandidates;
  }

  // Final list of eligable server
  var finalCandidates = [];

  // If we have tags filter by tags
  if(tags != null && typeof tags == 'object') {
    // If we have an array or single tag selection
    var tagObjects = Array.isArray(tags) ? tags : [tags];
    // Iterate over all tags until we find a candidate server
    for(var _i = 0; _i < tagObjects.length; _i++) {
      // Grab a tag object
      var tagObject = tagObjects[_i];
      // Matching keys
      var matchingKeys = Object.keys(tagObject);
      // Remove any that are not tagged correctly
      for(var i = 0; i < candidateServers.length; i++) {
        var server = candidateServers[i];
        // If we have tags match
        if(server.tags != null) {
          var matching = true;

          // Ensure we have all the values
          for(var j = 0; j < matchingKeys.length; j++) {
            if(server.tags[matchingKeys[j]] != tagObject[matchingKeys[j]]) {
              matching = false;
              break;
            }
          }

          // If we have a match add it to the list of matching servers
          if(matching) {
            finalCandidates.push(server);
          }
        }
      }
    }
  } else {
    // Final array candidates
    var finalCandidates = candidateServers;
  }

  // Sort by ping time
  finalCandidates.sort(function(a, b) {
    return a.runtimeStats['pingMs'] > b.runtimeStats['pingMs'];
  });

  if(0 === finalCandidates.length)
    return new Error("No replica set members available for query");

  // handle undefined pingMs
  var lowestPing = finalCandidates[0].runtimeStats['pingMs'] | 0;

  // determine acceptable latency
  var acceptable = lowestPing + this.secondaryAcceptableLatencyMS;

  // remove any server responding slower than acceptable
  var len = finalCandidates.length;
  while(len--) {
    if(finalCandidates[len].runtimeStats['pingMs'] > acceptable) {
      finalCandidates.splice(len, 1);
    }
  }

  // If no candidates available return an error
  if(finalCandidates.length == 0)
    return new Error("No replica set members available for query");

  // Pick a random acceptable server
  return finalCandidates[Math.round(Math.random(1000000) * (finalCandidates.length - 1))].checkoutReader();
}

PingStrategy.prototype._pingServer = function(callback) {
  var self = this;

  // Ping server function
  var pingFunction = function() {
    if(self.state == 'disconnected') return;

    var addresses = self.replicaset._state.addresses;

    // Grab all servers
    var serverKeys = Object.keys(addresses);

    // Number of server entries
    var numberOfEntries = serverKeys.length;

    // We got keys
    for(var i = 0; i < serverKeys.length; i++) {

      // We got a server instance
      var server = addresses[serverKeys[i]];

      // Create a new server object, avoid using internal connections as they might
      // be in an illegal state
      new function(serverInstance) {
        var options = { poolSize: 1, timeout: 500, auto_reconnect: false };
        var server = new Server(serverInstance.host, serverInstance.port, options);
        var db = new self.Db(self.replicaset.db.databaseName, server);

        db.on("error", done);

        // Open the db instance
        db.open(function(err) {
          if (err) return done();

          // Startup time of the command
          var startTime = Date.now();

          // Execute ping on this connection
          db.executeDbCommand({ping:1}, function() {
            if(null != serverInstance.runtimeStats && serverInstance.isConnected()) {
              serverInstance.runtimeStats['pingMs'] = Date.now() - startTime;
            }
            done();
          })
        })

        function done () {
          // Close connection
          db.close();

          // Adjust the number of checks
          numberOfEntries--;

          // If we are done with all results coming back trigger ping again
          if(0 === numberOfEntries && 'connected' == self.state) {
            setTimeout(pingFunction, self.pingInterval);
          }
        }
      }(server);
    }
  }

  // Start pingFunction
  setTimeout(pingFunction, 1000);

  callback && callback(null);
}
<|endoftext|>


<commit_before>'use strict'

const CONFIG = require('config')['shorte.st']
CONFIG.token = process.env[CONFIG.token]

const shortestAPI = require('shortest-api')
const shortest = shortestAPI(CONFIG)

const cleanTitle = require('./clean-title')
const serializer = require('./serializer')
const { asyncify } = require('async')
const osom = require('osom')

const validate = osom({
  /* common */
  title: {
    required: true,
    type: String,
    transform: [cleanTitle]
  },
  category: {
    required: true,
    type: Array
  },
  seller: {
    required: true,
    type: String
  },
  provider: {
    required: true,
    type: String
  },
  path: {
    type: String
  },
  url: {
    required: true,
    type: String
  },
  createdAt: {
    type: Number
  },
  updatedAt: {
    required: true,
    type: Number
  },

  /** identify:common **/
  brand: String,
  model: String,
  price: {
    required: true,
    type: Number
  },
  year: Number,

  'mast.size': Number,

  'sail.size': Number,

  'board.size': Number,

  'boom.size': String,
  'boom.type': String,

  'fin.size': Number,
  'fin.type': String,

  'mast.carbon': Number,
  'mast.type': String
})

const validateAsync = asyncify(validate)

function validator (schema, cb) {
  schema = serializer(schema)

  validateAsync(schema, function (err, instance) {
    if (err) return cb(err, instance)
    shortest(instance.url, function (err, shortenUrl) {
      if (err) return cb(err)
      instance.shortenUrl = shortenUrl
      return cb(null, instance)
    })
  })
}

module.exports = validator
<commit_msg>Add price validation<commit_after>'use strict'

const CONFIG = require('config')['shorte.st']
CONFIG.token = process.env[CONFIG.token]

const shortestAPI = require('shortest-api')
const shortest = shortestAPI(CONFIG)

const cleanTitle = require('./clean-title')
const serializer = require('./serializer')
const { asyncify } = require('async')
const osom = require('osom')

const validate = osom({
  /* common */
  title: {
    required: true,
    type: String,
    transform: [cleanTitle]
  },
  category: {
    required: true,
    type: Array
  },
  seller: {
    required: true,
    type: String
  },
  provider: {
    required: true,
    type: String
  },
  path: {
    type: String
  },
  url: {
    required: true,
    type: String
  },
  createdAt: {
    type: Number
  },
  updatedAt: {
    required: true,
    type: Number
  },

  /** identify:common **/
  brand: String,
  model: String,
  price: {
    required: true,
    type: Number,
    validate: price => price > 1
  },
  year: Number,

  'mast.size': Number,

  'sail.size': Number,

  'board.size': Number,

  'boom.size': String,
  'boom.type': String,

  'fin.size': Number,
  'fin.type': String,

  'mast.carbon': Number,
  'mast.type': String
})

const validateAsync = asyncify(validate)

function validator (schema, cb) {
  schema = serializer(schema)

  validateAsync(schema, function (err, instance) {
    if (err) return cb(err, instance)
    shortest(instance.url, function (err, shortenUrl) {
      if (err) return cb(err)
      instance.shortenUrl = shortenUrl
      return cb(null, instance)
    })
  })
}

module.exports = validator
<|endoftext|>


<commit_before>'use strict';

function guess(){
    var guessvalue = parseInt(
      document.getElementById('guess-input').value,
      10
    );

    // Only allow guesses if the guess button is not disabled.
    if(document.getElementById('guess-button').disabled){
        return;
    }

    var guess_max = parseInt(
      document.getElementById('guess-max').value,
      10
    );
    var guess_min = parseInt(
      document.getElementById('guess-min').value,
      10
    );

    // If the guess is not a number or not in guessing range.
    if(isNaN(guessvalue)
      || guessvalue.length < 1
      || guessvalue < guess_min
      || guessvalue > guess_max){
        document.getElementById('info').innerHTML =
          'You must enter an integer between ' + guess_min + ' and ' + guess_max + ', inclusive.';
        return;
    }

    document.getElementById('guess-input').value = guessvalue;

    // Check if valid guess is lower than value.
    if(guessvalue > value){
        document.getElementById('info').innerHTML = 'LOWER';

    // Check if valid guess is higher than value.
    }else if(guessvalue < value){
        document.getElementById('info').innerHTML = 'HIGHER';

    // Only option left is guess is correct.
    }else{
        // Disable guess button to prevent further guesses.
        document.getElementById('guess-button').disabled = true;

        // Update info with victory message.
        document.getElementById('info').innerHTML = 'CORRECT! YOU WIN!';
    }

    document.getElementById('guesses').innerHTML = parseInt(
      document.getElementById('guesses').innerHTML,
      10
    ) + 1;
}

function new_game(skip){
    if(!skip
      && !window.confirm('Start new game?')){
        return;
    }

    // Clear guess input.
    document.getElementById('guess-input').value = '';
    document.getElementById('info').innerHTML = '';

    // Reset number of guesses.
    document.getElementById('guesses').innerHTML = 0;

    // Enable guess button to allow more gueses.
    document.getElementById('guess-button').disabled = false;

    // Generate new value to guess.
    var min_value = parseInt(
      document.getElementById('guess-min').value,
      10
    );
    value = Math.floor(
      Math.random()
        * (parseInt(document.getElementById('guess-max').value, 10) - min_value)
    ) + min_value;
}

function set_value(type){
    // Set a new maximum guess value.
    var temp = window.prompt(
      'Enter ' + type + ' value:',
      document.getElementById('guess-' + type).value
    );
    if(temp == null){
        return;
    }

    document.getElementById('guess-' + type).value = isNaN(temp) || temp.length < 1
      ? (type === 'min'
        ? 1
        : 1000000)
      : temp;

    new_game(true);
}

var value = 0;

window.onkeyup = function(e){
    var key = e.keyCode || e.which;

    // ENTER: guess.
    if(key === 13){
        guess();

    // N: new game.
    }else if(key === 78){
        new_game(false);
    }
};

window.onload = function(e){
    new_game(true);
};
<commit_msg>replaced guess-button disabling with boolean<commit_after>'use strict';

function guess(){
    if(!guessing){
        return;
    }

    var guessvalue = parseInt(
      document.getElementById('guess-input').value,
      10
    );

    var guess_max = parseInt(
      document.getElementById('guess-max').value,
      10
    );
    var guess_min = parseInt(
      document.getElementById('guess-min').value,
      10
    );

    // If the guess is not a number or not in guessing range.
    if(isNaN(guessvalue)
      || guessvalue.length < 1
      || guessvalue < guess_min
      || guessvalue > guess_max){
        document.getElementById('info').innerHTML =
          'You must enter an integer between ' + guess_min + ' and ' + guess_max + ', inclusive.';
        return;
    }

    document.getElementById('guess-input').value = guessvalue;

    // Check if valid guess is lower than value.
    if(guessvalue > value){
        document.getElementById('info').innerHTML = 'LOWER';

    // Check if valid guess is higher than value.
    }else if(guessvalue < value){
        document.getElementById('info').innerHTML = 'HIGHER';

    // Only option left is guess is correct.
    }else{
        guessing = false;

        // Update info with victory message.
        document.getElementById('info').innerHTML = 'CORRECT! YOU WIN!';
    }

    document.getElementById('guesses').innerHTML = parseInt(
      document.getElementById('guesses').innerHTML,
      10
    ) + 1;
}

function new_game(skip){
    if(!skip
      && !window.confirm('Start new game?')){
        return;
    }

    guessing = true;

    // Clear guess input.
    document.getElementById('guess-input').value = '';
    document.getElementById('info').innerHTML = '';

    // Reset number of guesses.
    document.getElementById('guesses').innerHTML = 0;

    // Generate new value to guess.
    var min_value = parseInt(
      document.getElementById('guess-min').value,
      10
    );
    value = Math.floor(
      Math.random()
        * (parseInt(document.getElementById('guess-max').value, 10) - min_value)
    ) + min_value;
}

function set_value(type){
    // Set a new maximum guess value.
    var temp = window.prompt(
      'Enter ' + type + ' value:',
      document.getElementById('guess-' + type).value
    );
    if(temp == null){
        return;
    }

    document.getElementById('guess-' + type).value = isNaN(temp) || temp.length < 1
      ? (type === 'min'
        ? 1
        : 1000000)
      : temp;

    new_game(true);
}

var guessing = true;
var value = 0;

window.onkeyup = function(e){
    var key = e.keyCode || e.which;

    // ENTER: guess.
    if(key === 13){
        guess();

    // N: new game.
    }else if(key === 78){
        new_game(false);
    }
};

window.onload = function(e){
    new_game(true);
};
<|endoftext|>


<commit_before>var
    esPhinx,
    window;

(function ($module) {
    "use strict";

    const
        CSS_CLASS = "esphinx ui",
        CSS_CLASS_QUERY = "." + CSS_CLASS.replace(/ +/g, ".");

    $module.extend({

        selectors: {

            Select: {

                new: function (select, options) {
                    var
                        $ = esPhinx,
                        ConstructionClass = $module.selectors.Select,
                        wrapper = $("

"),
                        caption = $("

"),
                        optionsPanel = $("

"),
                        searchTextBox = $("<input></input>"),
                        abstractSelect = $("

"),
                        abstractOptions = [],
                        captionText = $("

"),
                        selectElement = $(select),
                        optionElements = selectElement.find("option"),

                        Option = {
                            new: function(data) {
                                var
                                    option,
                                    abstractOption,
                                    ConstructionClass = Option,
                                    select = $(data.select),

                                    buildAbstractOption = function (li,
                                                                    option) {

                                        li = $(li);
                                        option = $(option);
                                        li.text(option.text());
                                        li.attribute("data-value", option
                                                     .attribute("value"));
                                    };

                                if (!(this instanceof ConstructionClass.new)) {
                                    return new ConstructionClass.new(data);
                                }

                                this.append = function() {
                                    if (abstractOption.tagName() != "option") {
                                        data.abstractSelect
                                            .append(abstractOption);
                                    }
                                };

                                this.select = function() {
                                    $(data.captionText).text($(abstractOption)
                                                             .textContent());
                                    select.find("option:checked")
                                        .unselect();
                                    option.select();
                                    $(data.optionsPanel).hide();
                                    toggleCaptionClass(data.caption);
                                };

                                this.element = function() {
                                    return abstractOption;
                                };

                                if ($(data.option).tagName() == "option") {
                                    option = $(data.option);
                                    abstractOption = $("

");
                                    buildAbstractOption(abstractOption, option);
                                    this.append();
                                } else {
                                    abstractOption = $(data.option);
                                    option = select
                                        .find("option[value='" +
                                              abstractOption.data("value") +
                                              "']");
                                }
                            }
                        },

                        selected = function(select) {
                            return $(select).find("option:checked");
                        },

                        toggleCaptionClass = function (caption) {
                            caption.toggleClass("arrow-expanded",
                                "arrow-retracted");
                        },

                        decorate = function() {
                            selectElement.hide();

                            wrapper.insertAfter(selectElement);
                            captionText.text(selected(selectElement).text());
                            caption.append(captionText);
                            wrapper.prepend(caption);
                            wrapper.append(optionsPanel);
                            optionsPanel.append(abstractSelect);

                            var
                                bindFoundListEventListener = function(
                                    abstractOptions) {
                                    abstractOptions
                                        .forEach(function(abstractOption) {
                                        $(abstractOption.element()).on("click",
                                            function() {
                                            abstractOption.select();
                                        });
                                    });
                                },

                                decorateOptions = function(optionElements) {
                                    optionElements.each(function(option) {
                                        option = Option.new({
                                            option: option,
                                            select: selectElement,
                                            caption: caption,
                                            captionText: captionText,
                                            optionsPanel: optionsPanel,
                                            abstractSelect: abstractSelect
                                        });

                                        abstractOptions.push(option);
                                    });

                                    bindFoundListEventListener(abstractOptions);
                                    abstractOptions = [];
                                },

                                decorateSearchTextBox = function() {
                                    searchTextBox.attribute("type", "text");
                                    optionsPanel.prepend(searchTextBox);

                                    $.ui.panels.autocomplete
                                        .new(searchTextBox, abstractSelect, {
                                        order: options.order
                                    }, function (found) {
                                        decorateOptions(found);
                                    });

                                };

                            $(window.document).on("click", function (e) {
                                var
                                    wrapper = $(CSS_CLASS_QUERY + ".select"),
                                    optionsPanels = wrapper
                                        .find(".options-panel"),
                                    captions = wrapper.find(".caption");

                                if (!$(e.target).parent(CSS_CLASS_QUERY +
                                                        ".select").some()) {
                                    if (optionsPanels.visible()) {
                                        optionsPanels.hide();
                                        captions.removeClass("arrow-expanded");
                                        captions.addClass("arrow-retracted");
                                    }

                                }
                            });

                            wrapper.addClass(CSS_CLASS + " select");
                            caption.addClass("caption arrow-retracted");
                            optionsPanel.addClass("options-panel");
                            captionText.addClass("text");

                            // toggle on click on caption
                            caption.on("click", function () {
                                optionsPanel.toggle();
                                toggleCaptionClass($(this));
                            });

                            if (typeof options.searchTextBox == "boolean" &&
                                options.searchTextBox) {
                                decorateSearchTextBox();
                            }

                            decorateOptions(optionElements);
                        };

                    if (!(this instanceof ConstructionClass.new)) {
                        return new ConstructionClass
                            .new($(select), options);
                    }

                    decorate();

                    return this;
                }

            }

        }

    });

}(esPhinx.ui));
<commit_msg>final code with refactor<commit_after>var
    esPhinx,
    window;

(function ($module) {
    "use strict";

    const
        CSS_CLASS = "esphinx ui",
        CSS_CLASS_QUERY = "." + CSS_CLASS.replace(/ +/g, ".");

    $module.extend({

        selectors: {

            Select: {

                new: function (select, options) {
                    var
                        $ = esPhinx,
                        ConstructionClass = $module.selectors.Select,
                        wrapper = $("

"),
                        caption = $("

"),
                        optionsPanel = $("

"),
                        searchTextBox = $("<input></input>"),
                        abstractSelect = $("

"),
                        abstractOptions = [],
                        captionText = $("

"),
                        selectElement = $(select),
                        optionElements = selectElement.find("option"),

                        Option = {
                            new: function(data) {
                                var
                                    option,
                                    abstractOption,
                                    ConstructionClass = Option,
                                    select = $(data.select),

                                    buildAbstractOption = function (li,
                                                                    option) {

                                        li = $(li);
                                        option = $(option);
                                        li.text(option.text());
                                        li.attribute("data-value", option
                                                     .attribute("value"));
                                    };

                                if (!(this instanceof ConstructionClass.new)) {
                                    return new ConstructionClass.new(data);
                                }

                                this.append = function() {
                                    if (abstractOption.tagName() != "option") {
                                        data.abstractSelect
                                            .append(abstractOption);
                                    }
                                };

                                this.select = function() {
                                    $(data.captionText).text($(abstractOption)
                                                             .textContent());
                                    select.find("option:checked")
                                        .unselect();
                                    option.select();
                                    $(data.optionsPanel).hide();
                                    toggleCaptionClass(data.caption);
                                };

                                this.element = function() {
                                    return abstractOption;
                                };

                                if ($(data.option).tagName() == "option") {
                                    option = $(data.option);
                                    abstractOption = $("

");
                                    buildAbstractOption(abstractOption, option);
                                    this.append();
                                } else {
                                    abstractOption = $(data.option);
                                    option = select
                                        .find("option[value='" +
                                              abstractOption.data("value") +
                                              "']");
                                }
                            }
                        },

                        selected = function(select) {
                            return $(select).find("option:checked");
                        },

                        toggleCaptionClass = function (caption) {
                            caption.toggleClass("arrow-expanded",
                                "arrow-retracted");
                        },

                        decorate = function() {
                            selectElement.hide();

                            wrapper.insertAfter(selectElement);
                            captionText.text(selected(selectElement).text());
                            caption.append(captionText);
                            wrapper.prepend(caption);
                            wrapper.append(optionsPanel);
                            optionsPanel.append(abstractSelect);

                            var
                                bindFoundListEventListener = function(
                                    abstractOptions) {
                                    abstractOptions
                                        .forEach(function(abstractOption) {
                                        $(abstractOption.element()).on("click",
                                            function() {
                                            abstractOption.select();
                                        });
                                    });
                                },

                                decorateOptions = function(optionElements) {
                                    optionElements.each(function(option) {
                                        option = Option.new({
                                            option: option,
                                            select: selectElement,
                                            caption: caption,
                                            captionText: captionText,
                                            optionsPanel: optionsPanel,
                                            abstractSelect: abstractSelect
                                        });

                                        abstractOptions.push(option);
                                    });

                                    bindFoundListEventListener(abstractOptions);
                                    abstractOptions = [];
                                },

                                decorateSearchTextBox = function() {
                                    searchTextBox.attribute("type", "text");
                                    optionsPanel.prepend(searchTextBox);

                                    $.ui.panels.autocomplete
                                        .new(searchTextBox, abstractSelect, {
                                        order: options.order
                                    }, function (found) {
                                        decorateOptions(found);
                                    });

                                };

                            wrapper.addClass(CSS_CLASS + " select");
                            caption.addClass("caption arrow-retracted");
                            optionsPanel.addClass("options-panel");
                            captionText.addClass("text");

                            // toggle on click on caption
                            caption.on("click", function () {
                                optionsPanel.toggle();
                                toggleCaptionClass($(this));
                            });

                            if (typeof options.searchTextBox == "boolean" &&
                                options.searchTextBox) {
                                decorateSearchTextBox();
                            }

                            decorateOptions(optionElements);
                        };

                    if (!(this instanceof ConstructionClass.new)) {
                        return new ConstructionClass
                            .new($(select), options);
                    }

                    decorate();

                    $(window.document).on("click", function (e) {
                        var
                            wrapper = $(CSS_CLASS_QUERY + ".select"),
                            optionsPanels = wrapper
                                .find(".options-panel"),
                            captions = wrapper.find(".caption");

                        if (!$(e.target).parent(CSS_CLASS_QUERY +
                                                ".select").some()) {
                            if (optionsPanels.visible()) {
                                optionsPanels.hide();
                                captions.removeClass("arrow-expanded");
                                captions.addClass("arrow-retracted");
                            }

                        }
                    });

                    return this;
                }

            }

        }

    });

}(esPhinx.ui));
<|endoftext|>


<commit_before>var fs=require("fs");

/*
  check if exists
  check if is directory
    if is directory
      check if default filename exists
        if exists respond
        else next
    else is file
      respond
*/

/* Static route */
module.exports=function(statpath,def){
  def=def||"/index.html";
  return function(req,res,next){
    var path=statpath+decodeURIComponent(req.url);
//    console.log(JSON.stringify({      url:req.url      ,path:path    }));
    var bin;

    var response=function(path){
      var ext;
      path.replace(/\.[^.]*$/,function(e){
        ext=e;
      });
      var type;
      console.log("extension: "+ext)
      switch (ext){
        case '.ttf':
          type='application/x-font-ttf';
          bin=true;
          break;
        case '.woff':
          type='application/x-font-woff';
          bin=true;
          break;
        case '.svg':
          type='image/svg+xml';
          break;
        case '.css':
          type='text/css';
          break;
        case '.json':
          type='application/json';
          break;
        case '.js':
          type='text/javascript';
          break;
        case '.ico':
          bin=true;
          type='image/x-icon';
          break;
        case '.gif':
          bin=true;
          type='image/gif';
          break;
        case '.png':
          bin=true;
          type='image/png'
          break;
        case '.jpeg':
        case '.jpg':
          bin=true;
          type='image/jpeg';
          break;
        case '.pdf':
          bin=true;
          type='application/pdf';
          break;
        case '.exe':
          bin=true;
          type='application/x-msdownload';
          break;
        case '.htm':
        case '.html':
          type='text/html';
          break;
        default:
          type='text/plain;charset=utf8';
          break;
      }
      fs.readFile(path,(!bin)?"utf8":null,function(err,data){
 //       console.log(path);
        if(err)
          console.log(err)||
          next(req,res);
        else{
          res.statusCode=200;
          res.setHeader("Content-Type",type);
          res.end(data);
        }
      });
    };

    // check if there is something there
    fs.exists(path,function(e){
      if(e){ // there is! what is it?
        fs.stat(path,function(err,stats){
          if(err) // problem?
            console.log(err)||next(req,res);

          // is it a directory?
          if(stats.isDirectory()){
            fs.exists(path+def,function(e){
              if(e){ // it exists!
                response(path+def);
              }else{ // it does not
                next(req,res);
              }
            });
          }else if (stats.isFile()){
            response(path);
          }else{
            next(req,res)
          }
        });
      }else
        next(req,res);
    });
  };
};
<commit_msg>added otf support<commit_after>var fs=require("fs");

/*
  check if exists
  check if is directory
    if is directory
      check if default filename exists
        if exists respond
        else next
    else is file
      respond
*/

/* Static route */
module.exports=function(statpath,def){
  def=def||"/index.html";
  return function(req,res,next){
    var path=statpath+decodeURIComponent(req.url);
//    console.log(JSON.stringify({      url:req.url      ,path:path    }));
    var bin;

    var response=function(path){
      var ext;
      path.replace(/\.[^.]*$/,function(e){
        ext=e;
      });
      var type;
      console.log("extension: "+ext)
      switch (ext){
        case '.otf':
          type='application/x-font-otf';
          bin=true;
          break;
        case '.ttf':
          type='application/x-font-ttf';
          bin=true;
          break;
        case '.woff':
          type='application/x-font-woff';
          bin=true;
          break;
        case '.svg':
          type='image/svg+xml';
          break;
        case '.css':
          type='text/css';
          break;
        case '.json':
          type='application/json';
          break;
        case '.js':
          type='text/javascript';
          break;
        case '.ico':
          bin=true;
          type='image/x-icon';
          break;
        case '.gif':
          bin=true;
          type='image/gif';
          break;
        case '.png':
          bin=true;
          type='image/png'
          break;
        case '.jpeg':
        case '.jpg':
          bin=true;
          type='image/jpeg';
          break;
        case '.pdf':
          bin=true;
          type='application/pdf';
          break;
        case '.exe':
          bin=true;
          type='application/x-msdownload';
          break;
        case '.htm':
        case '.html':
          type='text/html';
          break;
        default:
          type='text/plain;charset=utf8';
          break;
      }
      fs.readFile(path,(!bin)?"utf8":null,function(err,data){
 //       console.log(path);
        if(err)
          console.log(err)||
          next(req,res);
        else{
          res.statusCode=200;
          res.setHeader("Content-Type",type);
          res.end(data);
        }
      });
    };

    // check if there is something there
    fs.exists(path,function(e){
      if(e){ // there is! what is it?
        fs.stat(path,function(err,stats){
          if(err) // problem?
            console.log(err)||next(req,res);

          // is it a directory?
          if(stats.isDirectory()){
            fs.exists(path+def,function(e){
              if(e){ // it exists!
                response(path+def);
              }else{ // it does not
                next(req,res);
              }
            });
          }else if (stats.isFile()){
            response(path);
          }else{
            next(req,res)
          }
        });
      }else
        next(req,res);
    });
  };
};
<|endoftext|>


<commit_before>define('app/views/backend_add', [
    'app/models/backend',
    'text!app/templates/backend_add.html',
    'ember'],
    /**
     *
     * Add Backend Dialog
     *
     * @returns Class
     */
    function(Backend, backend_add_html) {

        return Ember.View.extend({

            template: Ember.Handlebars.compile(backend_add_html),

            init: function() {
                this._super();
            },

            selectBackend: function(event){
                if (event.target.title.indexOf("rackspace") !== -1 || event.target.title.indexOf("linode") !== -1)  {
                    $('#textApiKey').text('2. Username:');
                    $('#textApiSecret').text('3. API Key:');
                } else {
                    $('#textApiKey').text('2. API Key:');
                    $('#textApiSecret').text('3. API Secret:');
                }
                $('.select-backend-collapsible').collapsible('option','collapsedIcon','check');
                $('.select-backend-collapsible span.ui-btn-text').text(event.target.text);
                Mist.backendAddController.set('newBackendProvider',
                    {provider: $(event.target).attr('title'),
                     title: event.target.text
                    }
                );
                $('.select-backend-collapsible').trigger('collapse');

                Mist.backendsController.some(function(backend){
                    if (event.target.title.split('_')[0] == 'ec2' && backend.provider.split('_')[0] == 'ec2') {
                        //Autocomplete
                        $('input[id=create-backend-key]').val(backend.apikey);
                        $('input[id=create-backend-secret]').val('getsecretfromdb');
                        $('#create-backend-ok').button('enable');
                        return true;
                    } else if (event.target.title.substr(0,9) == 'rackspace' &&
 backend.provider.substr(0,9) == 'rackspace') {
                        $('input[id=create-backend-key]').val(backend.apikey);
                        $('input[id=create-backend-secret]').val('getsecretfromdb');
                        $('#create-backend-ok').button('enable');
                        return true;
                    } else if (event.target.title == 'linode' && backend.provider == 'linode') {
                        return true;
                    }
                });
            },

            addBackend: function() {
                $('.select-listmenu li').on('click', this.selectBackend);
                $('#add-backend').panel('open');
                // resize dismiss div TODO: reset on window resize
                $('.ui-panel-dismiss-position-right').css('left',(0-$('.ui-panel-position-right.ui-panel-open').width()));
            },

            backClicked: function() {
                Mist.backendAddController.newBackendClear();
                $('.select-listmenu li').off('click', this.selectBackend);
                $("#add-backend").panel("close");
            },

            addButtonClick: function(){
                var that = this;
                var payload = {
                    "title": '', // TODO
                    "provider": Mist.backendAddController.newBackendProvider,
                    "apikey" : $('#create-backend-key').val(),
                    "apisecret": $('#create-backend-secret').val()
                };

                $.ajax({
                    url: '/backends',
                    type: "POST",
                    contentType: "application/json",
                    dataType: "json",
                    headers: { "cache-control": "no-cache" },
                    data: JSON.stringify(payload),
                    success: function(result) {
                        Mist.backendsController.pushObject(Backend.create(result));
                        info('added backend ' + result.id);
                        Mist.backendAddController.newBackendClear();
                        $("#add-backend").panel("close");
                        $('.select-listmenu li').off('click', this.selectBackend);
                    }
                });
            },

            providerList: function() {
                return SUPPORTED_PROVIDERS;
            }.property('providerList')
        });
    }
);
<commit_msg>delete autocompleted backend credentials when selecting non-ec2 backend<commit_after>define('app/views/backend_add', [
    'app/models/backend',
    'text!app/templates/backend_add.html',
    'ember'],
    /**
     *
     * Add Backend Dialog
     *
     * @returns Class
     */
    function(Backend, backend_add_html) {

        return Ember.View.extend({

            template: Ember.Handlebars.compile(backend_add_html),

            init: function() {
                this._super();
            },

            selectBackend: function(event){
                if (event.target.title.indexOf("rackspace") !== -1 || event.target.title.indexOf("linode") !== -1)  {
                    $('#textApiKey').text('2. Username:');
                    $('#textApiSecret').text('3. API Key:');
                } else {
                    $('#textApiKey').text('2. API Key:');
                    $('#textApiSecret').text('3. API Secret:');
                }
                $('.select-backend-collapsible').collapsible('option','collapsedIcon','check');
                $('.select-backend-collapsible span.ui-btn-text').text(event.target.text);
                Mist.backendAddController.set('newBackendProvider',
                    {provider: $(event.target).attr('title'),
                     title: event.target.text
                    }
                );
                $('.select-backend-collapsible').trigger('collapse');

                Mist.backendsController.some(function(backend){
                    $('input[id=create-backend-key]').val('');
                    $('input[id=create-backend-secret]').val('');
                    if (event.target.title.split('_')[0] == 'ec2' && backend.provider.split('_')[0] == 'ec2') {
                        //Autocomplete
                        $('input[id=create-backend-key]').val(backend.apikey);
                        $('input[id=create-backend-secret]').val('getsecretfromdb');
                        $('#create-backend-ok').button('enable');
                        return true;
                    } else if (event.target.title.substr(0,9) == 'rackspace' && backend.provider.substr(0,9) == 'rackspace') {
                        $('input[id=create-backend-key]').val(backend.apikey);
                        $('input[id=create-backend-secret]').val('getsecretfromdb');
                        $('#create-backend-ok').button('enable');
                        return true;
                    }
                    return true;
                });
            },

            addBackend: function() {
                $('.select-listmenu li').on('click', this.selectBackend);
                $('#add-backend').panel('open');
                // resize dismiss div TODO: reset on window resize
                $('.ui-panel-dismiss-position-right').css('left',(0-$('.ui-panel-position-right.ui-panel-open').width()));
            },

            backClicked: function() {
                Mist.backendAddController.newBackendClear();
                $('.select-listmenu li').off('click', this.selectBackend);
                $("#add-backend").panel("close");
            },

            addButtonClick: function(){
                var that = this;
                var payload = {
                    "title": '', // TODO
                    "provider": Mist.backendAddController.newBackendProvider,
                    "apikey" : $('#create-backend-key').val(),
                    "apisecret": $('#create-backend-secret').val()
                };

                $.ajax({
                    url: '/backends',
                    type: "POST",
                    contentType: "application/json",
                    dataType: "json",
                    headers: { "cache-control": "no-cache" },
                    data: JSON.stringify(payload),
                    success: function(result) {
                        Mist.backendsController.pushObject(Backend.create(result));
                        info('added backend ' + result.id);
                        Mist.backendAddController.newBackendClear();
                        $("#add-backend").panel("close");
                        $('.select-listmenu li').off('click', this.selectBackend);
                    }
                });
            },

            providerList: function() {
                return SUPPORTED_PROVIDERS;
            }.property('providerList')
        });
    }
);
<|endoftext|>


<commit_before>import React from 'react';
import {getMajorVersion} from '../lib/utils.js';

/**
 * Get the list of modified properties
 * @param  {Element} entity        Entity where the component belongs
 * @param  {string} componentName Component name
 * @return {object}               List of modified properties with their value
 */
function getModifiedProperties (entity, componentName) {
  var data = entity.components[componentName].data;
  var defaultData = entity.components[componentName].schema;
  var diff = {};
  for (var key in data) {
    var defaultValue = defaultData[key].default;
    var currentValue = data[key];

    // Some parameters could be null and '' like mergeTo
    if (!(isEmpty(currentValue) && isEmpty(defaultValue)) &&
      currentValue !== defaultValue) {
      diff[key] = data[key];
    }
  }
  return diff;
}

/**
 * [getClipboardRepresentation description]
 * @param  {[type]} entity        [description]
 * @param  {[type]} componentName [description]
 * @return {[type]}               [description]
 */
export function getClipboardRepresentation (entity, componentName) {
  var diff = getModifiedProperties(entity, componentName);
  var attributes = AFRAME.utils.styleParser.stringify(diff).replace(/;|:/g, '$& ');
  return `${componentName}="${attributes}"`;
}

/**
 * Get the component docs link
 * @param  {string} componentName Component's name
 * @return {string}               URL to the documentation
 */
export function getComponentDocsUrl (componentName) {
  if (AFRAME.components[componentName]) {
    // Returns link from the core components
    return 'https://aframe.io/docs/' + getMajorVersion(AFRAME.version) + '/components/' +
      (componentName === 'camera' ? '' : componentName.toLowerCase() + '.html');
  }
}

/**
 * Get component documentation html link
 * @param  {string} componentName Component's name
 * @return {string}               Html icon link to the documentation
 */
export function getComponentDocsHtmlLink (componentName) {
  let url = getComponentDocsUrl(componentName);
  if (url) {
    return  event.stopPropagation()}
      href={url}>;
  }
  return '';
}

function isEmpty (string) {
  return string === null || string === '';
}
<commit_msg>Prevent copy to clipboard invalid attributes<commit_after>import React from 'react';
import {getMajorVersion} from '../lib/utils.js';

/**
 * Get the list of modified properties
 * @param  {Element} entity        Entity where the component belongs
 * @param  {string} componentName Component name
 * @return {object}               List of modified properties with their value
 */
function getModifiedProperties (entity, componentName) {
  var data = entity.components[componentName].data;
  var defaultData = entity.components[componentName].schema;
  var diff = {};
  for (var key in data) {
    // Prevent adding unknown attributes
    if (!defaultData[key]) { continue; }

    var defaultValue = defaultData[key].default;
    var currentValue = data[key];

    // Some parameters could be null and '' like mergeTo
    if (!(isEmpty(currentValue) && isEmpty(defaultValue)) &&
      currentValue !== defaultValue) {
      diff[key] = data[key];
    }
  }
  return diff;
}

/**
 * [getClipboardRepresentation description]
 * @param  {[type]} entity        [description]
 * @param  {[type]} componentName [description]
 * @return {[type]}               [description]
 */
export function getClipboardRepresentation (entity, componentName) {
  var diff = getModifiedProperties(entity, componentName);
  var attributes = AFRAME.utils.styleParser.stringify(diff).replace(/;|:/g, '$& ');
  return `${componentName}="${attributes}"`;
}

/**
 * Get the component docs link
 * @param  {string} componentName Component's name
 * @return {string}               URL to the documentation
 */
export function getComponentDocsUrl (componentName) {
  if (AFRAME.components[componentName]) {
    // Returns link from the core components
    return 'https://aframe.io/docs/' + getMajorVersion(AFRAME.version) + '/components/' +
      (componentName === 'camera' ? '' : componentName.toLowerCase() + '.html');
  }
}

/**
 * Get component documentation html link
 * @param  {string} componentName Component's name
 * @return {string}               Html icon link to the documentation
 */
export function getComponentDocsHtmlLink (componentName) {
  let url = getComponentDocsUrl(componentName);
  if (url) {
    return  event.stopPropagation()}
      href={url}>;
  }
  return '';
}

function isEmpty (string) {
  return string === null || string === '';
}
<|endoftext|>