<commit_before>/*!
 * socket.io-node
 * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
 * MIT Licensed
 */

/**
 * Test dependencies.
 */

var builder = require('../../bin/builder')
  , common = require('./builder.common')
  , should = require('should');

/**
 * Tests.
 */

module.exports = {

  'version number': function () {
    builder.version.should().match(/([0-9]+)\.([0-9]+)\.([0-9]+)/);
    builder.version.should().equal(require('../../lib/io').version);
  },

  'production build LOC': function () {
    builder(function (err, result) {
      should.strictEqual(err, null)

      var lines = result.split('\n');
      lines.length.should().be.below(5);
      lines[0].should().match(/production/gi);
      Buffer.byteLength(result).should().be.below(42000);
    });
  },

  'development build LOC': function () {
    builder({ minify: false }, function (err, result) {
      should.strictEqual(err, null)

      var lines = result.split('\n');
      lines.length.should().be.above(5);
      lines[0].should().match(/development/gi);
      Buffer.byteLength(result).should().be.above(35000);
    });
  },

  'default builds': function () {
    builder(function (err, result) {
      should.strictEqual(err, null);

      var io = common.execute(result).io
        , transports = Object.keys(io.Transport)
        , defaults = Object.keys(builder.transports);

      /* XHR transport is private, but still available */
      transports.length.should().be.equal(defaults.length + 1);

      defaults.forEach(function (transport) {
        transports.indexOf(transport).should().be.above(-1);
      })
    });
  },

  'custom build': function () {
    builder(['websocket'], function (err, result) {
      should.strictEqual(err, null);

      var io = common.execute(result).io
        , transports = Object.keys(io.Transport);

      transports.should().have.length(1);
      transports[0].should().eql('websocket');
    });
  },

  'custom code': function () {
    var custom = 'var hello = "world";';
    builder({ custom: [custom], minify: false }, function (err, result) {
      should.strictEqual(err, null);

      result.should().include.string(custom);
    });
  },

  'node if': function () {
    var custom = '// if node \nvar hello = "world";\n'
      + '// end node\nvar pew = "pew";';

    builder({ custom: [custom], minify: false }, function (err, result) {
      should.strictEqual(err, null);

      result.should().not.include.string(custom);
      result.should().not.include.string('// if node');
      result.should().not.include.string('// end node');
      result.should().not.include.string('"world"');

      result.should().include.string('var pew = "pew"');
    });
  },

  'preserve the encoding during minification': function () {
    builder(function (err, result) {
      should.strictEqual(err, null);

      result.should().match(/(\\ufffd)/g);
    })
  },

  'globals': function () {
    builder(function (err, result) {
      should.strictEqual(err, null);

      var io = common.execute(result)
        , env = common.env()
        , allowed = ['io', 'swfobject', 'WEB_SOCKET_DISABLE_AUTO_INITIALIZATION'];

      Array.prototype.push.apply(allowed, Object.keys(env));

      Object.keys(io).forEach(function (global) {
        var index = allowed.indexOf(global);

        // the global is not allowed!
        if (!~index) {
          throw new Error('Global leak: ' + global);
        }
      });
    })
  }

};
<commit_msg>Fixed builder test<commit_after>/*!
 * socket.io-node
 * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
 * MIT Licensed
 */

/**
 * Test dependencies.
 */

var builder = require('../../bin/builder')
  , common = require('./builder.common')
  , should = require('should');

/**
 * Tests.
 */

module.exports = {

  'version number': function () {
    builder.version.should().match(/([0-9]+)\.([0-9]+)\.([0-9]+)/);
    builder.version.should().equal(require('../../lib/io').version);
  },

  'production build LOC': function () {
    builder(function (err, result) {
      should.strictEqual(err, null)

      var lines = result.split('\n');
      lines.length.should().be.below(5);
      lines[0].should().match(/production/gi);
      Buffer.byteLength(result).should().be.below(43000);
    });
  },

  'development build LOC': function () {
    builder({ minify: false }, function (err, result) {
      should.strictEqual(err, null)

      var lines = result.split('\n');
      lines.length.should().be.above(5);
      lines[0].should().match(/development/gi);
      Buffer.byteLength(result).should().be.above(35000);
    });
  },

  'default builds': function () {
    builder(function (err, result) {
      should.strictEqual(err, null);

      var io = common.execute(result).io
        , transports = Object.keys(io.Transport)
        , defaults = Object.keys(builder.transports);

      /* XHR transport is private, but still available */
      transports.length.should().be.equal(defaults.length + 1);

      defaults.forEach(function (transport) {
        transports.indexOf(transport).should().be.above(-1);
      })
    });
  },

  'custom build': function () {
    builder(['websocket'], function (err, result) {
      should.strictEqual(err, null);

      var io = common.execute(result).io
        , transports = Object.keys(io.Transport);

      transports.should().have.length(1);
      transports[0].should().eql('websocket');
    });
  },

  'custom code': function () {
    var custom = 'var hello = "world";';
    builder({ custom: [custom], minify: false }, function (err, result) {
      should.strictEqual(err, null);

      result.should().include.string(custom);
    });
  },

  'node if': function () {
    var custom = '// if node \nvar hello = "world";\n'
      + '// end node\nvar pew = "pew";';

    builder({ custom: [custom], minify: false }, function (err, result) {
      should.strictEqual(err, null);

      result.should().not.include.string(custom);
      result.should().not.include.string('// if node');
      result.should().not.include.string('// end node');
      result.should().not.include.string('"world"');

      result.should().include.string('var pew = "pew"');
    });
  },

  'preserve the encoding during minification': function () {
    builder(function (err, result) {
      should.strictEqual(err, null);

      result.should().match(/(\\ufffd)/g);
    })
  },

  'globals': function () {
    builder(function (err, result) {
      should.strictEqual(err, null);

      var io = common.execute(result)
        , env = common.env()
        , allowed = ['io', 'swfobject', 'WEB_SOCKET_DISABLE_AUTO_INITIALIZATION'];

      Array.prototype.push.apply(allowed, Object.keys(env));

      Object.keys(io).forEach(function (global) {
        var index = allowed.indexOf(global);

        // the global is not allowed!
        if (!~index) {
          throw new Error('Global leak: ' + global);
        }
      });
    })
  }

};
<|endoftext|>


<commit_before>/**
 *
 *  Web Starter Kit
 *  Copyright 2014 Google Inc. All rights reserved.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License
 *
 */

'use strict';

// Include Gulp & Tools We'll Use
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var del = require('del');
var runSequence = require('run-sequence');
var browserSync = require('browser-sync');
var pagespeed = require('psi');
var reload = browserSync.reload;

// Lint JavaScript
gulp.task('jshint', function () {
  return gulp.src('app/scripts/**/*.js')
    .pipe(reload({stream: true, once: true}))
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.if(!browserSync.active, $.jshint.reporter('fail')));
});

// Optimize Images
gulp.task('images', function () {
  return gulp.src('app/images/**/*')
    .pipe($.cache($.imagemin({
      progressive: true,
      interlaced: true
    })))
    .pipe(gulp.dest('dist/images'))
    .pipe($.size({title: 'images'}));
});

// Copy All Files At The Root Level (app)
gulp.task('copy', function() {
  return gulp.src(['app/*', '!app/*.html'])
    .pipe(gulp.dest('dist'))
    .pipe($.size({title: 'copy'}));
});

// Automatically Prefix CSS
gulp.task('styles:css', function () {
  return gulp.src('app/styles/**/*.css')
    .pipe($.changed('app/styles'))
    .pipe($.autoprefixer('last 1 version'))
    .pipe(gulp.dest('app/styles'))
    .pipe($.size({title: 'styles:css'}));
});

// Compile Sass For Style Guide Components (app/styles/components)
gulp.task('styles:components', function () {
  return gulp.src('app/styles/components/components.scss')
    .pipe($.rubySass({
      style: 'expanded',
      precision: 10,
      loadPath: ['app/styles/components']
    }))
    .pipe($.autoprefixer('last 1 version'))
    .pipe(gulp.dest('app/styles/components'))
    .pipe($.size({title: 'styles:components'}));
});

// Compile Any Other Sass Files You Added (app/styles)
gulp.task('styles:scss', function () {
  return gulp.src(['app/styles/**/*.scss', '!app/styles/components/components.scss'])
    .pipe($.rubySass({
      style: 'expanded',
      precision: 10,
      loadPath: ['app/styles']
    }))
    .pipe($.autoprefixer('last 1 version'))
    .pipe(gulp.dest('.tmp/styles'))
    .pipe($.size({title: 'styles:scss'}));
});

// Output Final CSS Styles
gulp.task('styles', ['styles:components', 'styles:scss', 'styles:css']);

// Scan Your HTML For Assets & Optimize Them
gulp.task('html', function () {
  return gulp.src('app/**/*.html')
    .pipe($.useref.assets({searchPath: '{.tmp,app}'}))
    // Concatenate And Minify JavaScript
    .pipe($.if('*.js', $.uglify({preserveComments: 'some'})))
    // Concatenate And Minify Styles
    .pipe($.if('*.css', $.csso()))
    // Remove Any Unused CSS
    // Note: If not using the Style Guide, you can delete it from
    // the next line to only include styles your project uses.
    .pipe($.if('*.css', $.uncss({ html: ['app/index.html','app/styleguide/index.html'] })))
    .pipe($.useref.restore())
    .pipe($.useref())
    // Update Production Style Guide Paths
    .pipe($.replace('components/components.css', 'components/main.min.css'))
    // Minify Any HTML
    .pipe($.minifyHtml())
    // Output Files
    .pipe(gulp.dest('dist'))
    .pipe($.size({title: 'html'}));
});

// Clean Output Directory
gulp.task('clean', del.bind(null, ['.tmp', 'dist']));

// Watch Files For Changes & Reload
gulp.task('serve', function () {
  browserSync({
    notify: false,
    server: {
      baseDir: ['.tmp', 'app']
    }
  });

  gulp.watch(['app/**/*.html'], reload);
  gulp.watch(['app/styles/**/*.scss'], ['styles:components', 'styles:scss']);
  gulp.watch(['{.tmp,app}/styles/**/*.css'], ['styles:css', reload]);
  gulp.watch(['app/scripts/**/*.js'], ['jshint']);
  gulp.watch(['app/images/**/*'], reload);
});

// Build Production Files, the Default Task
gulp.task('default', ['clean'], function (cb) {
  runSequence('styles', ['jshint', 'html', 'images', 'copy'], cb);
});

// Run PageSpeed Insights
// Update `url` below to the public URL for your site
gulp.task('pagespeed', pagespeed.bind(null, {
  // By default, we use the PageSpeed Insights
  // free (no API key) tier. You can use a Google
  // Developer API key if you have one. See
  // http://goo.gl/RkN0vE for info key: 'YOUR_API_KEY'
  url: 'https://example.com',
  strategy: 'mobile'
}));

// Load custom tasks from the `tasks` directory
try { require('require-dir')('tasks'); } catch (err) {}
<commit_msg>Adding ignore filters to uncss<commit_after>/**
 *
 *  Web Starter Kit
 *  Copyright 2014 Google Inc. All rights reserved.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License
 *
 */

'use strict';

// Include Gulp & Tools We'll Use
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var del = require('del');
var runSequence = require('run-sequence');
var browserSync = require('browser-sync');
var pagespeed = require('psi');
var reload = browserSync.reload;

// Lint JavaScript
gulp.task('jshint', function () {
  return gulp.src('app/scripts/**/*.js')
    .pipe(reload({stream: true, once: true}))
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.if(!browserSync.active, $.jshint.reporter('fail')));
});

// Optimize Images
gulp.task('images', function () {
  return gulp.src('app/images/**/*')
    .pipe($.cache($.imagemin({
      progressive: true,
      interlaced: true
    })))
    .pipe(gulp.dest('dist/images'))
    .pipe($.size({title: 'images'}));
});

// Copy All Files At The Root Level (app)
gulp.task('copy', function() {
  return gulp.src(['app/*', '!app/*.html'])
    .pipe(gulp.dest('dist'))
    .pipe($.size({title: 'copy'}));
});

// Automatically Prefix CSS
gulp.task('styles:css', function () {
  return gulp.src('app/styles/**/*.css')
    .pipe($.changed('app/styles'))
    .pipe($.autoprefixer('last 1 version'))
    .pipe(gulp.dest('app/styles'))
    .pipe($.size({title: 'styles:css'}));
});

// Compile Sass For Style Guide Components (app/styles/components)
gulp.task('styles:components', function () {
  return gulp.src('app/styles/components/components.scss')
    .pipe($.rubySass({
      style: 'expanded',
      precision: 10,
      loadPath: ['app/styles/components']
    }))
    .pipe($.autoprefixer('last 1 version'))
    .pipe(gulp.dest('app/styles/components'))
    .pipe($.size({title: 'styles:components'}));
});

// Compile Any Other Sass Files You Added (app/styles)
gulp.task('styles:scss', function () {
  return gulp.src(['app/styles/**/*.scss', '!app/styles/components/components.scss'])
    .pipe($.rubySass({
      style: 'expanded',
      precision: 10,
      loadPath: ['app/styles']
    }))
    .pipe($.autoprefixer('last 1 version'))
    .pipe(gulp.dest('.tmp/styles'))
    .pipe($.size({title: 'styles:scss'}));
});

// Output Final CSS Styles
gulp.task('styles', ['styles:components', 'styles:scss', 'styles:css']);

// Scan Your HTML For Assets & Optimize Them
gulp.task('html', function () {

  // CSS Selectors for UnCSS to ignore
  var ignore_css_selectors = [".navdrawer-container.open", /.app-bar.open/];

  return gulp.src('app/**/*.html')
    .pipe($.useref.assets({searchPath: '{.tmp,app}'}))
    // Concatenate And Minify JavaScript
    .pipe($.if('*.js', $.uglify({preserveComments: 'some'})))
    // Concatenate And Minify Styles
    .pipe($.if('*.css', $.csso()))
    // Remove Any Unused CSS
    // Note: If not using the Style Guide, you can delete it from
    // the next line to only include styles your project uses.
    .pipe($.if('*.css', $.uncss({ html: ['app/index.html','app/styleguide/index.html'], ignore: ignore_css_selectors })))
    .pipe($.useref.restore())
    .pipe($.useref())
    // Update Production Style Guide Paths
    .pipe($.replace('components/components.css', 'components/main.min.css'))
    // Minify Any HTML
    .pipe($.minifyHtml())
    // Output Files
    .pipe(gulp.dest('dist'))
    .pipe($.size({title: 'html'}));
});

// Clean Output Directory
gulp.task('clean', del.bind(null, ['.tmp', 'dist']));

// Watch Files For Changes & Reload
gulp.task('serve', function () {
  browserSync({
    notify: false,
    server: {
      baseDir: ['.tmp', 'app']
    }
  });

  gulp.watch(['app/**/*.html'], reload);
  gulp.watch(['app/styles/**/*.scss'], ['styles:components', 'styles:scss']);
  gulp.watch(['{.tmp,app}/styles/**/*.css'], ['styles:css', reload]);
  gulp.watch(['app/scripts/**/*.js'], ['jshint']);
  gulp.watch(['app/images/**/*'], reload);
});

// Build Production Files, the Default Task
gulp.task('default', ['clean'], function (cb) {
  runSequence('styles', ['jshint', 'html', 'images', 'copy'], cb);
});

// Run PageSpeed Insights
// Update `url` below to the public URL for your site
gulp.task('pagespeed', pagespeed.bind(null, {
  // By default, we use the PageSpeed Insights
  // free (no API key) tier. You can use a Google
  // Developer API key if you have one. See
  // http://goo.gl/RkN0vE for info key: 'YOUR_API_KEY'
  url: 'https://example.com',
  strategy: 'mobile'
}));

// Load custom tasks from the `tasks` directory
try { require('require-dir')('tasks'); } catch (err) {}
<|endoftext|>


<commit_before>'use strict';

define(['./module', 'darkwallet', 'util/scanner'], function (controllers, DarkWallet, Scanner) {

  // Controller
  controllers.controller('ScanningCtrl', ['$scope', 'notify', '$wallet', '_Filter', 'modals', function($scope, notify, $wallet, _, modals) {

  $scope.scanning = false;
  $scope.scanStatus = "";
  $scope.scanParams = {addresses: 10, pockets: 5, scanMaster: false, scanOld: false};

  // Initialize the master pocket address for pockets
  var createMasterAddresses = function(results) {
      var identity = DarkWallet.getIdentity();
      // Set the identity to manage pocket addresses from now on
      identity.settings.scanPocketMaster = true;
      results.forEach(function(seq) {
          if (seq.length === 1) {
              var walletAddress = identity.wallet.getAddress(seq);
              if (walletAddress) {
                  $wallet.initAddress(walletAddress);
              }
          }
      });

  };

  // Create addresses for the given results
  var createAddresses = function(results, pocketAddressesUsed, password) {
      var keyStore, rootKey, mpks, oldStyle=true;
      var identity = DarkWallet.getIdentity();
      var version = identity.store.get('version');
      if (version > 4 && !$scope.scanParams.scanOld) {
          keyStore = identity.store.getPrivateData(password);
          rootKey = Bitcoin.HDNode.fromBase58(keyStore.privKey);
          mpks = identity.store.get('mpks');
          oldStyle = false;
      }
      var pockets = identity.wallet.pockets;
      var maxIndex = {};

      // Initialize pockets and check last index for each pocket
      results.forEach(function(seq) {
          // get indexes depending on new or old style scanning
          var pocketIndex =  oldStyle ? Math.floor(seq[0]/2) : seq[0];
          var branchId = oldStyle ? seq[0] : (seq[0]*2)+seq[1];
          var addrIndex = oldStyle ? seq[1] : seq[2];

          // Set the maximum index used for the pocket
          if (!maxIndex.hasOwnProperty(branchId)) {
              maxIndex[branchId] = addrIndex||0;
          } else {
              maxIndex[branchId] = Math.max(addrIndex||0, maxIndex[branchId]);
          }
          // Initialize the pocket if it doesn't exist
          if (!pockets.hdPockets[pocketIndex]) {
              // Manual initialization of specific pocket
              pockets.hdPockets[pocketIndex] = {name: "Pocket " + pocketIndex};
              if (!oldStyle) {
                  // Set pocket mpk for new pockets
                  if (!mpks[pocketIndex]) {
                      mpks[pocketIndex] = rootKey.deriveHardened(pocketIndex).toBase58(false);
                  }
                  pockets.hdPockets[pocketIndex].mpk = mpks[pocketIndex];
              }
              // Create the pocket
              pockets.initPocketWallet(pocketIndex, 'hd', pockets.hdPockets[pocketIndex]);
          }
      });

      // Generate master addresses
      if (pocketAddressesUsed) {
          createMasterAddresses(results);
      }

      // Now generate addresses
      Object.keys(maxIndex).forEach(function(branchId) {
          var pocketIndex = Math.floor(branchId/2);
          for(var i=0; i<=maxIndex[branchId]; i++) {
              var seq = oldStyle ? [branchId, i] : [pocketIndex, branchId%2, i];
              if (!identity.wallet.pubKeys[seq]) {
                  $wallet.generateAddress(pocketIndex, i, branchId%2);
              } else {
                  console.log("Already exists!");
              }
          }
      });
      pockets.store.save();
  };

  // Update every time we get results for an address
  var onScanUpdate = function(scanned, max) {
      $scope.scanProgress = (scanned / max)*100;
      $scope.scanned = {max: max, scanned: scanned};
      if (!$scope.$$phase) {
          $scope.$apply();
      }
  };

  // Scan finished callback
  var onScanFinish = function(err, results, pocketAddressesUsed, password) {
      if (err) {
          notify.error(_('Scanning'), err.message || ""+err);
      } else {
          $scope.scanning = false;
          $scope.scanStatus = $scope.scanner.status;
          $scope.scanner = undefined;
          createAddresses(results, pocketAddressesUsed, password);

          notify.success(_('Scanning'), _('Finished. Found {0} addresses', results.length));
      }
  };

  var runScanner = function(client, identity, password) {
      var scanMaster = false, masterKey = null;
      if (identity.store.get('version') > 4 && !$scope.scanParams.scanOld) {
           // new style
           // we never scanMaster here
           masterKey = identity.store.getPrivateData(password).privKey;
      } else {
           // old style
           scanMaster = $scope.scanParams.scanMaster;
      }
      var scanner = new Scanner(client, identity, masterKey,
                                function (par1, par2, par3) { onScanFinish(par1, par2, par3, password); },
                                onScanUpdate, scanMaster);

      scanner.setMargins(parseInt($scope.scanParams.pockets||5),
                             parseInt($scope.scanParams.addresses||10));
      $scope.scanner = scanner;

      // Start scanner
      scanner.scan();
  };

  // Scan all addresses from seed
  $scope.scanSeed = function() {
      $scope.scanning = true;
      notify.note(_('Start Scanning'));
      $scope.scanned = {max: 100, scanned: 0};
      $scope.scanStatus = _('Scanning...');
      $scope.scanProgress = 0;
      var client = DarkWallet.getClient();
      if (client) {
          var identity = DarkWallet.getIdentity();
          if (identity.store.get('version') > 4 && !$scope.scanParams.scanOld) {
              modals.password(_('Write your password for scanning'), function(password) {
                  runScanner(client, identity, password);
              });
          } else {
              runScanner(client, identity);
          }
      }
  };

}]);
});
<commit_msg>Allow the scanner to generate old master keys if needed.<commit_after>'use strict';

define(['./module', 'darkwallet', 'util/scanner'], function (controllers, DarkWallet, Scanner) {

  // Controller
  controllers.controller('ScanningCtrl', ['$scope', 'notify', '$wallet', '_Filter', 'modals', function($scope, notify, $wallet, _, modals) {

  $scope.scanning = false;
  $scope.scanStatus = "";
  $scope.scanParams = {addresses: 10, pockets: 5, scanMaster: false, scanOld: false};

  // Initialize the master pocket address for pockets
  var createMasterAddresses = function(results) {
      var identity = DarkWallet.getIdentity();
      // Set the identity to manage pocket addresses from now on
      identity.settings.scanPocketMaster = true;
      results.forEach(function(seq) {
          if (seq.length === 1) {
              var walletAddress = identity.wallet.getAddress(seq);
              if (walletAddress) {
                  $wallet.initAddress(walletAddress);
              }
          }
      });

  };

  // Create addresses for the given results
  var createAddresses = function(results, pocketAddressesUsed, password) {
      var keyStore, rootKey, mpks, oldStyle=true;
      var identity = DarkWallet.getIdentity();
      var version = identity.store.get('version');
      if (version > 4 && !$scope.scanParams.scanOld) {
          keyStore = identity.store.getPrivateData(password);
          rootKey = Bitcoin.HDNode.fromBase58(keyStore.privKey);
          mpks = identity.store.get('mpks');
          oldStyle = false;
      }
      var pockets = identity.wallet.pockets;
      var maxIndex = {};

      // Initialize pockets and check last index for each pocket
      results.forEach(function(seq) {
          // get indexes depending on new or old style scanning
          var pocketIndex =  oldStyle ? Math.floor(seq[0]/2) : seq[0];
          var branchId = oldStyle ? seq[0] : (seq[0]*2)+seq[1];
          var addrIndex = oldStyle ? seq[1] : seq[2];

          // Set the maximum index used for the pocket
          if (!maxIndex.hasOwnProperty(branchId)) {
              maxIndex[branchId] = addrIndex||0;
          } else {
              maxIndex[branchId] = Math.max(addrIndex||0, maxIndex[branchId]);
          }
          // Initialize the pocket if it doesn't exist
          if (!pockets.hdPockets[pocketIndex]) {
              // Manual initialization of specific pocket
              pockets.hdPockets[pocketIndex] = {name: "Pocket " + pocketIndex};
              if (!oldStyle) {
                  // Set pocket mpk for new pockets
                  if (!mpks[pocketIndex]) {
                      mpks[pocketIndex] = rootKey.deriveHardened(pocketIndex).toBase58(false);
                  }
                  pockets.hdPockets[pocketIndex].mpk = mpks[pocketIndex];
              }
              // Create the pocket
              pockets.initPocketWallet(pocketIndex, 'hd', pockets.hdPockets[pocketIndex]);
          }
      });

      // Generate master addresses
      if (pocketAddressesUsed) {
          createMasterAddresses(results);
      }

      // Now generate addresses
      Object.keys(maxIndex).forEach(function(branchId) {
          var pocketIndex = Math.floor(branchId/2);
          for(var i=0; i<=maxIndex[branchId]; i++) {
              var seq = oldStyle ? [branchId, i] : [pocketIndex, branchId%2, i];
              if (!identity.wallet.pubKeys[seq]) {
                  $wallet.generateAddress(pocketIndex, i, branchId%2);
              } else {
                  console.log("Already exists!");
              }
          }
      });
      pockets.store.save();
  };

  // Update every time we get results for an address
  var onScanUpdate = function(scanned, max) {
      $scope.scanProgress = (scanned / max)*100;
      $scope.scanned = {max: max, scanned: scanned};
      if (!$scope.$$phase) {
          $scope.$apply();
      }
  };

  // Scan finished callback
  var onScanFinish = function(err, results, pocketAddressesUsed, password) {
      if (err) {
          notify.error(_('Scanning'), err.message || ""+err);
      } else {
          $scope.scanning = false;
          $scope.scanStatus = $scope.scanner.status;
          $scope.scanner = undefined;
          createAddresses(results, pocketAddressesUsed, password);

          notify.success(_('Scanning'), _('Finished. Found {0} addresses', results.length));
      }
  };

  var generateOldKeys = function(identity, password) {
      // generate old dw style keyring mpk and privkey
      var keyStore = identity.store.getPrivateData(password);
      var seed = keyStore.seed;
      var mKey = Bitcoin.HDNode.fromSeedHex(seed, Bitcoin.networks[identity.wallet.network]);
      var rootKey = rootKey.deriveHardened(0);

      var pubKey = rootKey.toBase58(false);
      var privKey = rootKey.toBase58(true);

      // Initialize the scan public key here for now...
      var scanKey = rootKey.deriveHardened(0);
      var scanPubKey = scanKey.toBase58(false);
      var scanPrivKey = scanKey.toBase58(true);

      // save the old private master on the keyring
      keyStore.oldPrivKey = privKey;
      identity.store.setPrivateData(keyStore, password);

      // set old mpk and scankeys on identity
      identity.wallet.oldMpk = pubKey;
      identity.wallet.oldScanKeys = [{pub: scanPubKey, priv: scanPrivKey}];

      // set on store
      this.store.set('old-scankeys', identity.wallet.oldScanKeys);
      this.store.set('old-mpk', identity.wallet.oldMpk);
  };

  var runScanner = function(client, identity, password) {
      // if scanning for old keys on a bip44 keyring need to generate the oldMpk
      if (identity.store.get('version') > 4 && $scope.scanParams.scanOld && !identity.wallet.oldMpk) {
          generateOldKeys(identity, password);
      }
      // Now setup the scanner
      var scanMaster = false, masterKey = null;
      if (identity.store.get('version') > 4 && !$scope.scanParams.scanOld) {
           // new style
           // we never scanMaster here
           masterKey = identity.store.getPrivateData(password).privKey;
      } else {
           // old style
           scanMaster = $scope.scanParams.scanMaster;
      }
      var scanner = new Scanner(client, identity, masterKey,
                                function (par1, par2, par3) { onScanFinish(par1, par2, par3, password); },
                                onScanUpdate, scanMaster);

      scanner.setMargins(parseInt($scope.scanParams.pockets||5),
                             parseInt($scope.scanParams.addresses||10));
      $scope.scanner = scanner;

      // Start scanner
      scanner.scan();
  };

  // Scan all addresses from seed
  $scope.scanSeed = function() {
      $scope.scanning = true;
      notify.note(_('Start Scanning'));
      $scope.scanned = {max: 100, scanned: 0};
      $scope.scanStatus = _('Scanning...');
      $scope.scanProgress = 0;
      var client = DarkWallet.getClient();
      if (client) {
          var identity = DarkWallet.getIdentity();
          // we need to ask for password if scanning bip44 keyring, or first time scanning for
          // old addresses if we don't have the old mpk available
          if ((identity.store.get('version') > 4 && !$scope.scanParams.scanOld) || (identity.store.get('version') > 4 && $scope.scanParams.scanOld && !identity.wallet.oldMpk)) {
              modals.password(_('Write your password for scanning'), function(password) {
                  runScanner(client, identity, password);
              });
          } else {
              runScanner(client, identity);
          }
      }
  };

}]);
});
<|endoftext|>


<commit_before>var request = require('request');
var FeedParser = require('feedparser');
var moment = require('moment');
var cheerio = require('cheerio');

var expirationInMilliseconds =  1 * 60 * 60 * 1000; // 1 hour

var lastData = null;
var lastDataTime = null;
exports.index = function(req, res){
    if (lastData && (Date.now() - lastDataTime) < expirationInMilliseconds) {
        return res.render('index', lastData);
    }

    var data = { title: 'Morning Brew Mobile', articles: [] };
    request('http://blog.cwa.me.uk/feed/')
        .pipe(new FeedParser())
        .on('error', function(error) {
            console.log('error', error);
        })
        .on('meta', function(meta) {
            data.date = meta.date;
        })
        .on('article', function(article) {
            var art = {};
            art.title = article.title;
            art.date = moment(article.date).format('MMMM Do YYYY');
            art.link = article.origlink;
            art.commentLink = article.comments;

            // Add text links for each linked article/site
            // If there is more than one link in an element, number them to disambiguate
            var $ = cheerio.load(article.description);
            $('p, li').each(function() {
                var $parent = $(this);
                var $as = $parent.find('a');
                var count = $as.length;
                var textLinks = [];
                $as.each(function(i, el) {
                    var $a = $(el);
                    $a.addClass('normal-link');
                    var url = $a.attr('href');
                    textLinks.push('text ' + (count > 1 ? (i + 1) : '') + '');
                    if (count > 1) {
                        $a.after('' + (i + 1) + ' 0) {
                    $parent.prepend('
' + textLinks.join('') + '
');
                }
            });

            art.html = $.html();

            data.articles.push(art);
        })
        .on('end', function() {
            data.articles = data.articles.slice(0, 5);
            lastData = data;
            lastDataTime = Date.now();
            res.render('index', data);
        });
};<commit_msg>Fix text button urls.<commit_after>var request = require('request');
var FeedParser = require('feedparser');
var moment = require('moment');
var cheerio = require('cheerio');

var expirationInMilliseconds =  1 * 60 * 60 * 1000; // 1 hour

var lastData = null;
var lastDataTime = null;
exports.index = function(req, res){
    if (lastData && (Date.now() - lastDataTime) < expirationInMilliseconds) {
        return res.render('index', lastData);
    }

    var data = { title: 'Morning Brew Mobile', articles: [] };
    request('http://blog.cwa.me.uk/feed/')
        .pipe(new FeedParser())
        .on('error', function(error) {
            console.log('error', error);
        })
        .on('meta', function(meta) {
            data.date = meta.date;
        })
        .on('article', function(article) {
            var art = {};
            art.title = article.title;
            art.date = moment(article.date).format('MMMM Do YYYY');
            art.link = article.origlink;
            art.commentLink = article.comments;

            // Add text links for each linked article/site
            // If there is more than one link in an element, number them to disambiguate
            var $ = cheerio.load(article.description);
            $('p, li').each(function() {
                var $parent = $(this);
                var $as = $parent.find('a');
                var count = $as.length;
                var textLinks = [];
                $as.each(function(i, el) {
                    var $a = $(el);
                    $a.addClass('normal-link');
                    var url = $a.attr('href');
                    textLinks.push('text ' + (count > 1 ? (i + 1) : '') + '');
                    if (count > 1) {
                        $a.after('' + (i + 1) + ' 0) {
                    $parent.prepend('
' + textLinks.join('') + '
');
                }
            });

            art.html = $.html();

            data.articles.push(art);
        })
        .on('end', function() {
            data.articles = data.articles.slice(0, 5);
            lastData = data;
            lastDataTime = Date.now();
            res.render('index', data);
        });
};<|endoftext|>


<commit_before>var previewWidth = 482,
    previewHeight = 110;

$(document).ready(function() {

    /* Removed as this is now (hopefully) unnecessary */
    //$("#Panel").stickyPanel({
    //    topPadding: 1,
    //    afterDetachCSSClass: "floated-panel",
    //    savePanelSpace: true
    //});

    //this statement tells the browser to fade out any success message after 5 seconds
    setTimeout(function(){$(".success").fadeOut("slow", function(){$(this).empty()});}, 5000);
});

/*
 * i18n_months and i18n_days_short are used in jquery datepickers
 * which we use in multiple places
 */
var i18n_months = [
    $.i18n._("January"),
    $.i18n._("February"),
    $.i18n._("March"),
    $.i18n._("April"),
    $.i18n._("May"),
    $.i18n._("June"),
    $.i18n._("July"),
    $.i18n._("August"),
    $.i18n._("September"),
    $.i18n._("October"),
    $.i18n._("November"),
    $.i18n._("December")
];

var i18n_months_short = [
    $.i18n._("Jan"),
    $.i18n._("Feb"),
    $.i18n._("Mar"),
    $.i18n._("Apr"),
    $.i18n._("May"),
    $.i18n._("Jun"),
    $.i18n._("Jul"),
    $.i18n._("Aug"),
    $.i18n._("Sep"),
    $.i18n._("Oct"),
    $.i18n._("Nov"),
    $.i18n._("Dec")
];

var i18n_days_short = [
    $.i18n._("Su"),
    $.i18n._("Mo"),
    $.i18n._("Tu"),
    $.i18n._("We"),
    $.i18n._("Th"),
    $.i18n._("Fr"),
    $.i18n._("Sa")
];

function adjustDateToServerDate(date, serverTimezoneOffset){
    //date object stores time in the browser's localtime. We need to artificially shift
    //it to
    var timezoneOffset = date.getTimezoneOffset()*60*1000;

    date.setTime(date.getTime() + timezoneOffset + serverTimezoneOffset*1000);

    /* date object has been shifted to artificial UTC time. Now let's
     * shift it to the server's timezone */
    return date;
}

/**
 *handle to the jplayer window
 */
var _preview_window = null;

/**
 *Gets the info from the view when menu action play choosen and opens the jplayer window.
 */
function openAudioPreview(p_event) {
    p_event.stopPropagation();

    var audioFileID = $(this).attr('audioFile');
    var objId = $('#obj_id:first').attr('value');
    var objType = $('#obj_type:first').attr('value');
    var playIndex = $(this).parent().parent().attr('id');
    playIndex = playIndex.substring(4); //remove the spl_

    if (objType == "playlist") {
        open_playlist_preview(objId, playIndex);
    } else if (objType == "block") {
        open_block_preview(objId, playIndex);
    }
}

function open_audio_preview(type, id) {
    // The reason that we need to encode artist and title string is that
    // sometime they contain '/' or '\' and apache reject %2f or %5f
    // so the work around is to encode it twice.
    openPreviewWindow(baseUrl+'audiopreview/audio-preview/audioFileID/'+id+'/type/'+type, previewWidth, previewHeight);
    _preview_window.focus();
}

/**
 *Opens a jPlayer window for the specified info, for either an audio file or playlist.
 *If audioFile, audioFileTitle, audioFileArtist is supplied the jplayer opens for one file
 *Otherwise the playlistID and playlistIndex was supplied and a playlist is played starting with the
 *given index.
 */
function open_playlist_preview(p_playlistID, p_playlistIndex) {
    if (p_playlistIndex == undefined) //Use a resonable default.
        p_playlistIndex = 0;

    if (_preview_window != null && !_preview_window.closed)
        _preview_window.playAllPlaylist(p_playlistID, p_playlistIndex);
    else
        openPreviewWindow(baseUrl+'audiopreview/playlist-preview/playlistIndex/'+p_playlistIndex+'/playlistID/'+p_playlistID, previewWidth, previewHeight);
    _preview_window.focus();
}

function open_block_preview(p_blockId, p_blockIndex) {
    if (p_blockIndex == undefined) //Use a resonable default.
        p_blockIndex = 0;

    if (_preview_window != null && !_preview_window.closed)
        _preview_window.playBlock(p_blockId, p_blockIndex);
    else
        openPreviewWindow(baseUrl+'audiopreview/block-preview/blockIndex/'+p_blockIndex+'/blockId/'+p_blockId, previewWidth, previewHeight);
    _preview_window.focus();
}

/**
 *Opens a jPlayer window for the specified info, for either an audio file or playlist.
 *If audioFile, audioFileTitle, audioFileArtist is supplied the jplayer opens for one file
 *Otherwise the playlistID and playlistIndex was supplied and a playlist is played starting with the
 *given index.
 */
function open_show_preview(p_showID, p_showIndex) {
    if (_preview_window != null && !_preview_window.closed)
        _preview_window.playAllShow(p_showID, p_showIndex);
    else
        openPreviewWindow(baseUrl+'audiopreview/show-preview/showID/'+p_showID+'/showIndex/'+p_showIndex, previewWidth, previewHeight);
    _preview_window.focus();
}

function openPreviewWindow(url, w, h) {
    var dim = (w && h) ? 'width=' + w + ',height=' + h + ',' : '';
    // Hardcoding this here is kinda gross, but the alternatives aren't much better...
    _preview_window = window.open(url, $.i18n._('Audio Player'), dim + 'scrollbars=yes');
    return false;
}

function pad(number, length) {
    return sprintf("%'0"+length+"d", number);
}

function removeSuccessMsg() {
    var $status = $('.success');

    $status.fadeOut("slow", function(){$status.empty()});
}

function getUsabilityHint() {
    var pathname = window.location.pathname;
    $.getJSON("/api/get-usability-hint", {"format": "json", "userPath": pathname}, function(json) {
        var $hint_div = $('.usability_hint');
        var current_hint = $hint_div.html();
        if (json === "") {
            // there are no more hints to display to the user
            $hint_div.hide();
        } else if (current_hint !== json) {
            // we only change the message if it is new
            if ($hint_div.is(":hidden")) {
                $hint_div.show();
            }
            $hint_div.slideUp("slow");
            $hint_div.html(json);
            $hint_div.slideDown("slow");
        } else {
            // hint is the same before we hid it so we just need to show it
            if ($hint_div.is(":hidden")) {
                $hint_div.show();
            }
        }
    });
}
<commit_msg>SAAS-940: Provide usability hints to user<commit_after>var previewWidth = 482,
    previewHeight = 110;

$(document).ready(function() {

    /* Removed as this is now (hopefully) unnecessary */
    //$("#Panel").stickyPanel({
    //    topPadding: 1,
    //    afterDetachCSSClass: "floated-panel",
    //    savePanelSpace: true
    //});

    //this statement tells the browser to fade out any success message after 5 seconds
    setTimeout(function(){$(".success").fadeOut("slow", function(){$(this).empty()});}, 5000);
});

/*
 * i18n_months and i18n_days_short are used in jquery datepickers
 * which we use in multiple places
 */
var i18n_months = [
    $.i18n._("January"),
    $.i18n._("February"),
    $.i18n._("March"),
    $.i18n._("April"),
    $.i18n._("May"),
    $.i18n._("June"),
    $.i18n._("July"),
    $.i18n._("August"),
    $.i18n._("September"),
    $.i18n._("October"),
    $.i18n._("November"),
    $.i18n._("December")
];

var i18n_months_short = [
    $.i18n._("Jan"),
    $.i18n._("Feb"),
    $.i18n._("Mar"),
    $.i18n._("Apr"),
    $.i18n._("May"),
    $.i18n._("Jun"),
    $.i18n._("Jul"),
    $.i18n._("Aug"),
    $.i18n._("Sep"),
    $.i18n._("Oct"),
    $.i18n._("Nov"),
    $.i18n._("Dec")
];

var i18n_days_short = [
    $.i18n._("Su"),
    $.i18n._("Mo"),
    $.i18n._("Tu"),
    $.i18n._("We"),
    $.i18n._("Th"),
    $.i18n._("Fr"),
    $.i18n._("Sa")
];

function adjustDateToServerDate(date, serverTimezoneOffset){
    //date object stores time in the browser's localtime. We need to artificially shift
    //it to
    var timezoneOffset = date.getTimezoneOffset()*60*1000;

    date.setTime(date.getTime() + timezoneOffset + serverTimezoneOffset*1000);

    /* date object has been shifted to artificial UTC time. Now let's
     * shift it to the server's timezone */
    return date;
}

/**
 *handle to the jplayer window
 */
var _preview_window = null;

/**
 *Gets the info from the view when menu action play choosen and opens the jplayer window.
 */
function openAudioPreview(p_event) {
    p_event.stopPropagation();

    var audioFileID = $(this).attr('audioFile');
    var objId = $('#obj_id:first').attr('value');
    var objType = $('#obj_type:first').attr('value');
    var playIndex = $(this).parent().parent().attr('id');
    playIndex = playIndex.substring(4); //remove the spl_

    if (objType == "playlist") {
        open_playlist_preview(objId, playIndex);
    } else if (objType == "block") {
        open_block_preview(objId, playIndex);
    }
}

function open_audio_preview(type, id) {
    // The reason that we need to encode artist and title string is that
    // sometime they contain '/' or '\' and apache reject %2f or %5f
    // so the work around is to encode it twice.
    openPreviewWindow(baseUrl+'audiopreview/audio-preview/audioFileID/'+id+'/type/'+type, previewWidth, previewHeight);
    _preview_window.focus();
}

/**
 *Opens a jPlayer window for the specified info, for either an audio file or playlist.
 *If audioFile, audioFileTitle, audioFileArtist is supplied the jplayer opens for one file
 *Otherwise the playlistID and playlistIndex was supplied and a playlist is played starting with the
 *given index.
 */
function open_playlist_preview(p_playlistID, p_playlistIndex) {
    if (p_playlistIndex == undefined) //Use a resonable default.
        p_playlistIndex = 0;

    if (_preview_window != null && !_preview_window.closed)
        _preview_window.playAllPlaylist(p_playlistID, p_playlistIndex);
    else
        openPreviewWindow(baseUrl+'audiopreview/playlist-preview/playlistIndex/'+p_playlistIndex+'/playlistID/'+p_playlistID, previewWidth, previewHeight);
    _preview_window.focus();
}

function open_block_preview(p_blockId, p_blockIndex) {
    if (p_blockIndex == undefined) //Use a resonable default.
        p_blockIndex = 0;

    if (_preview_window != null && !_preview_window.closed)
        _preview_window.playBlock(p_blockId, p_blockIndex);
    else
        openPreviewWindow(baseUrl+'audiopreview/block-preview/blockIndex/'+p_blockIndex+'/blockId/'+p_blockId, previewWidth, previewHeight);
    _preview_window.focus();
}

/**
 *Opens a jPlayer window for the specified info, for either an audio file or playlist.
 *If audioFile, audioFileTitle, audioFileArtist is supplied the jplayer opens for one file
 *Otherwise the playlistID and playlistIndex was supplied and a playlist is played starting with the
 *given index.
 */
function open_show_preview(p_showID, p_showIndex) {
    if (_preview_window != null && !_preview_window.closed)
        _preview_window.playAllShow(p_showID, p_showIndex);
    else
        openPreviewWindow(baseUrl+'audiopreview/show-preview/showID/'+p_showID+'/showIndex/'+p_showIndex, previewWidth, previewHeight);
    _preview_window.focus();
}

function openPreviewWindow(url, w, h) {
    var dim = (w && h) ? 'width=' + w + ',height=' + h + ',' : '';
    // Hardcoding this here is kinda gross, but the alternatives aren't much better...
    _preview_window = window.open(url, $.i18n._('Audio Player'), dim + 'scrollbars=yes');
    return false;
}

function pad(number, length) {
    return sprintf("%'0"+length+"d", number);
}

function removeSuccessMsg() {
    var $status = $('.success');

    $status.fadeOut("slow", function(){$status.empty()});
}

function getUsabilityHint() {
    var pathname = window.location.pathname;
    $.getJSON("/api/get-usability-hint", {"format": "json", "userPath": pathname}, function(json) {
        var $hint_div = $('.usability_hint');
        var current_hint = $hint_div.html();
        if (json === "") {
            // there are no more hints to display to the user
            $hint_div.hide();
        } else if (current_hint !== json) {
            // we only change the message if it is new
            if ($hint_div.is(":visible")) {
                $hint_div.hide();
            }
            $hint_div.html(json);
            $hint_div.show("slow");

        } else {
            // hint is the same before we hid it so we just need to show it
            if ($hint_div.is(":hidden")) {
                $hint_div.show();
            }
        }
    });
}
<|endoftext|>


<commit_before>CodeMirror.defineMode("elm", function() {

	function switchState(source, setState, f)
	{
		setState(f);
		return f(source, setState);
	}

	// These should all be Unicode extended, as per the Haskell 2010 report
	var smallRE = /[a-z_]/;
	var largeRE = /[A-Z]/;
	var digitRE = /[0-9]/;
	var hexitRE = /[0-9A-Fa-f]/;
	var octitRE = /[0-7]/;
	var idRE = /[a-z_A-Z0-9\']/;
	var symbolRE = /[-!#$%&*+.\/<=>?@\\^|~:\u03BB\u2192]/;
	var specialRE = /[(),;[\]`{}]/;
	var whiteCharRE = /[ \t\v\f]/; // newlines are handled in tokenizer

	function normal(interpolate)
	{
		return function (source, setState)
		{
			if (source.eatWhile(whiteCharRE))
			{
				return null;
			}

			var ch = source.next();
			if (specialRE.test(ch))
			{
				if (ch == '{' && source.eat('-'))
				{
					var t = "comment";
					if (source.eat('#'))
					{
						t = "meta";
					}
					return switchState(source, setState, ncomment(t, 1));
				}
				return null;
			}

			if (ch == '\'')
			{
				if (source.eat('\\'))
				{
					source.next();  // should handle other escapes here
				}
				else {
					source.next();
				}
				if (source.eat('\''))
				{
					return "string";
				}
				return "error";
			}

			if (ch == '"')
			{
				return switchState(source, setState, stringLiteral);
			}

			if (largeRE.test(ch))
			{
				source.eatWhile(idRE);
				return "variable-2";
			}

			if (smallRE.test(ch))
			{
				var isDef = source.pos === 1;
				source.eatWhile(idRE);
				return isDef ? "variable-3" : "variable";
			}

			if (digitRE.test(ch))
			{
				if (ch == '0')
				{
					if (source.eat(/[xX]/))
					{
						source.eatWhile(hexitRE); // should require at least 1
						return "integer";
					}
					if (source.eat(/[oO]/))
					{
						source.eatWhile(octitRE); // should require at least 1
						return "number";
					}
				}
				source.eatWhile(digitRE);
				var t = "number";
				if (source.eat('.'))
				{
					t = "number";
					source.eatWhile(digitRE); // should require at least 1
				}
				if (source.eat(/[eE]/))
				{
					t = "number";
					source.eat(/[-+]/);
					source.eatWhile(digitRE); // should require at least 1
				}
				return t;
			}

			if (symbolRE.test(ch))
			{
				if (ch == '-' && source.eat(/-/))
				{
					source.eatWhile(/-/);
					if (!source.eat(symbolRE))
					{
						source.skipToEnd();
						return "comment";
					}
				}
				source.eatWhile(symbolRE);
				return "builtin";
			}

			return "error";
		}
	}

	function ncomment(type, nest)
	{
		if (nest == 0)
		{
			return normal(false);
		}
		return function(source, setState) {
			var currNest = nest;
			while (!source.eol())
			{
				var ch = source.next();
				if (ch == '{' && source.eat('-'))
				{
					++currNest;
				}
				else if (ch == '-' && source.eat('}'))
				{
					--currNest;
					if (currNest == 0)
					{
						setState(normal(false));
						return type;
					}
				}
			}
			setState(ncomment(type, currNest));
			return type;
		}
	}

	function stringLiteral(source, setState)
	{
		while (!source.eol())
		{
			var ch = source.next();
			if (ch == '"')
			{
				setState(normal(false));
				return "string";
			}
			if (ch == '\\')
			{
				if (source.eol() || source.eat(whiteCharRE))
				{
					setState(stringGap);
					return "string";
				}
				if (source.eat('&'))
				{
				}
				else
				{
					source.next(); // should handle other escapes here
				}
			}
		}
		setState(normal(false));
		return "error";
	}

	function stringGap(source, setState)
	{
		if (source.eat('\\'))
		{
			return switchState(source, setState, stringLiteral);
		}
		source.next();
		setState(normal(false));
		return "error";
	}

	var wellKnownWords = (function() {
		var wkw = {};

		var keywords = [
			"case", "of", "as",
			"if", "then", "else",
			"let", "in",
			"infix", "infixl", "infixr",
			"type", "alias",
			"input", "output", "foreign", "loopback",
			"module", "where", "import", "exposing",
			"_", "..", "|", ":", "=", "\\", "\"", "->", "<-"
		];

		for (var i = keywords.length; i--;)
		{
			wkw[keywords[i]] = "keyword";
		}

		return wkw;
	})();

	return {
		startState: function ()  { return { f: normal(false) }; },
		copyState:  function (s) { return { f: s.f }; },

		token: function(stream, state) {
			var t = state.f(stream, function(s) { state.f = s; });
			var w = stream.current();
			return (wellKnownWords.hasOwnProperty(w)) ? wellKnownWords[w] : t;
		}
	};

});
<commit_msg>update keywords for latest draft<commit_after>CodeMirror.defineMode("elm", function() {

	function switchState(source, setState, f)
	{
		setState(f);
		return f(source, setState);
	}

	// These should all be Unicode extended, as per the Haskell 2010 report
	var smallRE = /[a-z_]/;
	var largeRE = /[A-Z]/;
	var digitRE = /[0-9]/;
	var hexitRE = /[0-9A-Fa-f]/;
	var octitRE = /[0-7]/;
	var idRE = /[a-z_A-Z0-9\']/;
	var symbolRE = /[-!#$%&*+.\/<=>?@\\^|~:\u03BB\u2192]/;
	var specialRE = /[(),;[\]`{}]/;
	var whiteCharRE = /[ \t\v\f]/; // newlines are handled in tokenizer

	function normal(interpolate)
	{
		return function (source, setState)
		{
			if (source.eatWhile(whiteCharRE))
			{
				return null;
			}

			var ch = source.next();
			if (specialRE.test(ch))
			{
				if (ch == '{' && source.eat('-'))
				{
					var t = "comment";
					if (source.eat('#'))
					{
						t = "meta";
					}
					return switchState(source, setState, ncomment(t, 1));
				}
				return null;
			}

			if (ch == '\'')
			{
				if (source.eat('\\'))
				{
					source.next();  // should handle other escapes here
				}
				else {
					source.next();
				}
				if (source.eat('\''))
				{
					return "string";
				}
				return "error";
			}

			if (ch == '"')
			{
				return switchState(source, setState, stringLiteral);
			}

			if (largeRE.test(ch))
			{
				source.eatWhile(idRE);
				return "variable-2";
			}

			if (smallRE.test(ch))
			{
				var isDef = source.pos === 1;
				source.eatWhile(idRE);
				return isDef ? "variable-3" : "variable";
			}

			if (digitRE.test(ch))
			{
				if (ch == '0')
				{
					if (source.eat(/[xX]/))
					{
						source.eatWhile(hexitRE); // should require at least 1
						return "integer";
					}
					if (source.eat(/[oO]/))
					{
						source.eatWhile(octitRE); // should require at least 1
						return "number";
					}
				}
				source.eatWhile(digitRE);
				var t = "number";
				if (source.eat('.'))
				{
					t = "number";
					source.eatWhile(digitRE); // should require at least 1
				}
				if (source.eat(/[eE]/))
				{
					t = "number";
					source.eat(/[-+]/);
					source.eatWhile(digitRE); // should require at least 1
				}
				return t;
			}

			if (symbolRE.test(ch))
			{
				if (ch == '-' && source.eat(/-/))
				{
					source.eatWhile(/-/);
					if (!source.eat(symbolRE))
					{
						source.skipToEnd();
						return "comment";
					}
				}
				source.eatWhile(symbolRE);
				return "builtin";
			}

			return "error";
		}
	}

	function ncomment(type, nest)
	{
		if (nest == 0)
		{
			return normal(false);
		}
		return function(source, setState) {
			var currNest = nest;
			while (!source.eol())
			{
				var ch = source.next();
				if (ch == '{' && source.eat('-'))
				{
					++currNest;
				}
				else if (ch == '-' && source.eat('}'))
				{
					--currNest;
					if (currNest == 0)
					{
						setState(normal(false));
						return type;
					}
				}
			}
			setState(ncomment(type, currNest));
			return type;
		}
	}

	function stringLiteral(source, setState)
	{
		while (!source.eol())
		{
			var ch = source.next();
			if (ch == '"')
			{
				setState(normal(false));
				return "string";
			}
			if (ch == '\\')
			{
				if (source.eol() || source.eat(whiteCharRE))
				{
					setState(stringGap);
					return "string";
				}
				if (source.eat('&'))
				{
				}
				else
				{
					source.next(); // should handle other escapes here
				}
			}
		}
		setState(normal(false));
		return "error";
	}

	function stringGap(source, setState)
	{
		if (source.eat('\\'))
		{
			return switchState(source, setState, stringLiteral);
		}
		source.next();
		setState(normal(false));
		return "error";
	}

	var wellKnownWords = (function() {
		var wkw = {};

		var keywords = [
			"case", "of", "as",
			"if", "then", "else",
			"let", "in",
			"infix", "infixl", "infixr",
			"type", "alias",
			"port", "perform",
			"module", "where", "import", "exposing",
			"_", "..", "|", ":", "=", "\\", "\"", "->", "<-"
		];

		for (var i = keywords.length; i--;)
		{
			wkw[keywords[i]] = "keyword";
		}

		return wkw;
	})();

	return {
		startState: function ()  { return { f: normal(false) }; },
		copyState:  function (s) { return { f: s.f }; },

		token: function(stream, state) {
			var t = state.f(stream, function(s) { state.f = s; });
			var w = stream.current();
			return (wellKnownWords.hasOwnProperty(w)) ? wellKnownWords[w] : t;
		}
	};

});
<|endoftext|>


<commit_before>"use strict";

L.Control.OpenDAP = L.Control.extend( {

  options: {},

  initialize: function ( options ) {
    L.setOptions( this, options );
  },

  onAdd: function ( map ) {
    //var name = 'leaflet-control-opendap',
    //  container = L.DomUtil.create( 'div', name + ' leaflet-bar' );

    this._map = map;
    this._svg = this._createSvg( 'inspect', this.options.chart );

    map.on( 'mousemove', _.debounce( this._mouseMove.bind( this ), 200 ), this );

    //return container;
  },

  onRemove: function ( map ) {
  },

  _mouseMove: function ( event ) {
    this.options.getData( event.latlng, function ( err, data ) {

      var d = data;

      var width = this.width;
      var height = this.height;

      var x = d3.time.scale()
        .range( [0, width] );

      var y = d3.scale.linear()
        .range( [height, 0] );

      var xAxis = d3.svg.axis()
        .scale( x )
        .orient( "bottom" );

      var yAxis = d3.svg.axis()
        .scale( y )
        .orient( "left" );

      var line = d3.svg.line()
        .x( function ( d ) {
              return x( d.date );
            } )
        .y( function ( d ) {
              return y( d.value );
            } );

      x.domain( d3.extent( d, function ( d ) {
        return d.date;
      } ) );
      y.domain( d3.extent( d, function ( d ) {
        return d.value;
      } ) );

      var svg = this._svg;

      svg.selectAll( "g" ).remove();
      svg.append( "g" )
        .attr( "class", "x axis" )
        .attr( "transform", "translate(0," + height + ")" )
        .call( xAxis );

      svg.append( "g" )
        .attr( "class", "y axis" )
        .call( yAxis )
        .append( "text" )
        .attr( "transform", "rotate(-90)" )
        .attr( "y", 6 )
        .attr( "dy", ".71em" )
        .style( "text-anchor", "end" );

      svg.append( "g" )
        .attr( "class", "data" )
        .append( "path" )
        .datum( d )
        .attr( "class", "line" )
        .attr( "d", line );

    }.bind( this ) );
  },

  _createSvg: function ( className, container ) {

    var inspect = L.DomUtil.create( 'div', className, container );

    var margin = this.margin =
                 this.options.margin ||
                 {top: 20, right: 20, bottom: 30, left: 50},
      width = this.width =
              ( this.options.width || 600 ) - margin.left - margin.right,
      height = this.height =
               ( this.options.height || 300 ) - margin.top - margin.bottom;

    var svg = this._svg = d3.select( inspect ).append( "svg" )
      .attr( "width", width + margin.left + margin.right )
      .attr( "height", height + margin.top + margin.bottom )
      .append( "g" )
      .attr( "transform", "translate(" + margin.left + "," + margin.top + ")" );

    return svg;
  }
} );

L.Map.mergeOptions( {
  opendapControl: false
} );

L.Map.addInitHook( function () {
  if ( this.options.opendapControl ) {
    this.opendapControl = new L.Control.OpenDAP();
    this.addControl( this.opendapControl );
  }
} );

L.control.opendap = function ( options ) {
  return new L.Control.OpenDAP( options );
};

Polymer( 'leaflet-opendap-control', {

  url : "", variable : "", position : "bottomright", height : 300, width : 500,

  request : function ( url, callback ) {
    var options = {
      url : url, responseType : 'arraybuffer', callback : function ( buffer ) {
        callback( undefined, jsdap( buffer ) );
      }
    };
    this.$.xhr.request( options );
  },

  created : function () {
  },

  ready : function () {
    this.request( this.url + '.dods?time,latitude,longitude', function ( err, data ) {
      this.dapvar = data;
    }.bind( this ) )
  },

  findData : function ( data, name ) {
    return _.find( data, function ( i ) {
      return i.var.name == name
    } ).data;
  },

  process_data : function ( data ) {
    var dim_data = this.findData( data[1], this.variable );
    var values = _.flatten( this.findData( dim_data, this.variable ) );
    var dates = _.map( this.findData( dim_data, 'time' ), function ( val ) {
      return moment( val * 1000 ).toDate();
    } );
    return _.filter( _.map( _.zip( dates, values ), function ( arr ) {
      return {date : arr[0], value : arr[1]}
    } ), function ( a ) {
      return parseInt( a.value ) > -32760;
    } );
  },

  request_data : function ( latlng, callback ) {
    if ( this.dapvar ) {
      var t1 = 0;
      var t2 = this.findData( this.dapvar[1], 'time' ).data.length - 1;
      var x1 = _.findLastIndex( this.findData( this.dapvar[1], 'latitude' ).data, function ( i ) {
        return i < latlng.lat
      } );
      var x2 = x1;
      var y1 = _.findLastIndex( this.findData( this.dapvar[1], 'longitude' ).data, function ( i ) {
        return i < latlng.lng
      } );
      var y2 = y1;
      var url = this.url + ".dods?" + this.variable + "[" + t1 + ":1:" + t2 + "][" + y1 + ":1:" + y2 + "][" + x1 + ":1:" + x2 + "]";
      this.request( url, function ( err, data ) { callback( err, this.process_data( data ) ); }.bind( this ) );
    }
  },

  containerChanged : function () {
    if ( this.container ) {
      var config = {
        chart  : this.$.chart,
        height : this.height,
        width  : this.width,
        getData: this.request_data.bind( this )
      };
      var control = L.control.opendap( config );
      this.control = control;
      this.container.addControl( this.control );
    }
  },

  detached : function () {
    if ( this.container && this.control ) {
      this.container.removeControl( this.control );
    }
  }
} );
<commit_msg>bring back the container, as leaflet complained<commit_after>"use strict";

L.Control.OpenDAP = L.Control.extend( {

  options: {},

  initialize: function ( options ) {
    L.setOptions( this, options );
  },

  onAdd: function ( map ) {
    var name = 'leaflet-control-opendap',
      container = L.DomUtil.create( 'div', name + ' leaflet-bar' );

    this._map = map;
    this._svg = this._createSvg( 'inspect', this.options.chart );

    map.on( 'mousemove', _.debounce( this._mouseMove.bind( this ), 200 ), this );

    return container;
  },

  onRemove: function ( map ) {
  },

  _mouseMove: function ( event ) {
    this.options.getData( event.latlng, function ( err, data ) {

      var d = data;

      var width = this.width;
      var height = this.height;

      var x = d3.time.scale()
        .range( [0, width] );

      var y = d3.scale.linear()
        .range( [height, 0] );

      var xAxis = d3.svg.axis()
        .scale( x )
        .orient( "bottom" );

      var yAxis = d3.svg.axis()
        .scale( y )
        .orient( "left" );

      var line = d3.svg.line()
        .x( function ( d ) {
              return x( d.date );
            } )
        .y( function ( d ) {
              return y( d.value );
            } );

      x.domain( d3.extent( d, function ( d ) {
        return d.date;
      } ) );
      y.domain( d3.extent( d, function ( d ) {
        return d.value;
      } ) );

      var svg = this._svg;

      svg.selectAll( "g" ).remove();
      svg.append( "g" )
        .attr( "class", "x axis" )
        .attr( "transform", "translate(0," + height + ")" )
        .call( xAxis );

      svg.append( "g" )
        .attr( "class", "y axis" )
        .call( yAxis )
        .append( "text" )
        .attr( "transform", "rotate(-90)" )
        .attr( "y", 6 )
        .attr( "dy", ".71em" )
        .style( "text-anchor", "end" );

      svg.append( "g" )
        .attr( "class", "data" )
        .append( "path" )
        .datum( d )
        .attr( "class", "line" )
        .attr( "d", line );

    }.bind( this ) );
  },

  _createSvg: function ( className, container ) {

    var inspect = L.DomUtil.create( 'div', className, container );

    var margin = this.margin =
                 this.options.margin ||
                 {top: 20, right: 20, bottom: 30, left: 50},
      width = this.width =
              ( this.options.width || 600 ) - margin.left - margin.right,
      height = this.height =
               ( this.options.height || 300 ) - margin.top - margin.bottom;

    var svg = this._svg = d3.select( inspect ).append( "svg" )
      .attr( "width", width + margin.left + margin.right )
      .attr( "height", height + margin.top + margin.bottom )
      .append( "g" )
      .attr( "transform", "translate(" + margin.left + "," + margin.top + ")" );

    return svg;
  }
} );

L.Map.mergeOptions( {
  opendapControl: false
} );

L.Map.addInitHook( function () {
  if ( this.options.opendapControl ) {
    this.opendapControl = new L.Control.OpenDAP();
    this.addControl( this.opendapControl );
  }
} );

L.control.opendap = function ( options ) {
  return new L.Control.OpenDAP( options );
};

Polymer( 'leaflet-opendap-control', {

  url : "", variable : "", position : "bottomright", height : 300, width : 500,

  request : function ( url, callback ) {
    var options = {
      url : url, responseType : 'arraybuffer', callback : function ( buffer ) {
        callback( undefined, jsdap( buffer ) );
      }
    };
    this.$.xhr.request( options );
  },

  created : function () {
  },

  ready : function () {
    this.request( this.url + '.dods?time,latitude,longitude', function ( err, data ) {
      this.dapvar = data;
    }.bind( this ) )
  },

  findData : function ( data, name ) {
    return _.find( data, function ( i ) {
      return i.var.name == name
    } ).data;
  },

  process_data : function ( data ) {
    var dim_data = this.findData( data[1], this.variable );
    var values = _.flatten( this.findData( dim_data, this.variable ) );
    var dates = _.map( this.findData( dim_data, 'time' ), function ( val ) {
      return moment( val * 1000 ).toDate();
    } );
    return _.filter( _.map( _.zip( dates, values ), function ( arr ) {
      return {date : arr[0], value : arr[1]}
    } ), function ( a ) {
      return parseInt( a.value ) > -32760;
    } );
  },

  request_data : function ( latlng, callback ) {
    if ( this.dapvar ) {
      var t1 = 0;
      var t2 = this.findData( this.dapvar[1], 'time' ).data.length - 1;
      var y1 = _.findLastIndex( this.findData( this.dapvar[1], 'latitude' ).data, function ( i ) {
        return i < latlng.lat
      } );
      var y2 = y1;
      var x1 = _.findLastIndex( this.findData( this.dapvar[1], 'longitude' ).data, function ( i ) {
        return i < latlng.lng
      } );
      var x2 = x1;
      var url = this.url + ".dods?" + this.variable + "[" + t1 + ":1:" + t2 + "][" + y1 + ":1:" + y2 + "][" + x1 + ":1:" + x2 + "]";
      this.request( url, function ( err, data ) { callback( err, this.process_data( data ) ); }.bind( this ) );
    }
  },

  containerChanged : function () {
    if ( this.container ) {
      var config = {
        chart  : this.$.chart,
        height : this.height,
        width  : this.width,
        getData: this.request_data.bind( this )
      };
      var control = L.control.opendap( config );
      this.control = control;
      this.container.addControl( this.control );
    }
  },

  detached : function () {
    if ( this.container && this.control ) {
      this.container.removeControl( this.control );
    }
  }
} );
<|endoftext|>


<commit_before>const gulp = require('gulp'),
    $ = require('gulp-load-plugins')(),
    del = require('del'),
    open = require('open'),
    path = require('path'),
    proxy = require('http-proxy-middleware'),
    webpack = require('webpack'),
    runSequence = require('run-sequence'),
    paths = {
        src: {
            root: './src',
            style: './src/styles/**/*',
            js: './src/scripts/**/*.js',
            view: './src/views/**/*',
            img: './src/images/**/*',
            data: './src/datas/**/*',
            font: './src/fonts/**/*',
            vendor: './src/vendors/**/*',
            entry: {
                'vendor.common': './src/scripts/vendor.common',
                app: './src/scripts/app'
            }
        },
        dest: {
            root: './dist',
            style: './dist/styles',
            js: './dist/scripts',
            view: './dist/views',
            img: './dist/images',
            data: './dist/datas',
            font: './dist/fonts',
            vendor: './dist/vendors'
        },
        concat: {
            css: ['./dist/styles/cyan.common.min.css', './dist/vendors/bootstrap/dist/css/bootstrap.min.css', './dist/vendors/font-awesome/css/font-awesome.min.css', './dist/styles/common.min.css', './src/scripts/mods/zSlide/zslide.css']
        }
    };
let status = '';
gulp.task('clean', () => {
    if (status === 'dev') {
        return del([paths.dest.root + '/**/*', '!' + paths.dest.vendor + '/**']);
    } else {
        return del([paths.dest.root + '/**/*']);
    }
});
gulp.task('style', () => {
    let scss = $.filter('**/*.scss', {
        restore: true
    });
    return gulp.src(paths.src.style)
        .pipe($.changed(paths.dest.style, {
            extension: '.min.css'
        }))
        .on('data', (file) => {
            $.util.log(file.path);
        })
        .pipe(scss)
        .pipe($.sass(
            {
                outputStyle: 'expanded'
            })
            .on('error', (err) => {
                $.util.log(err.message);
                this.emit('end');
            }))
        .pipe(scss.restore)
        .pipe($.csso())
        .pipe($.autoprefixer('last 2 version', 'safari5', 'ie8', 'ie9', 'opera 12.1', 'ios 6', 'android 4'))
        .on('error', (err) => {
            $.util.log(err.message);
            this.emit('end');
        })
        .pipe($.rename({
            suffix: '.min'
        }))
        .pipe(gulp.dest(paths.dest.style));
});
gulp.task('styleConcat', ['style'], () => {
    return gulp.src(paths.concat.css)
        .pipe($.concat('vendor.common.min.css'))
        .pipe(gulp.dest(paths.dest.style));
});
gulp.task('js', () => {
    return gulp.src(paths.src.js)
        .pipe($.changed(paths.dest.js, {
            extension: '.min.js'
        }))
        .on('data', (file) => {
            $.util.log(file.path);
        })
        // .pipe($.sourcemaps.init())
        .pipe($.babel({
            presets: ['es2015'],
            compact: true,
            comments: false
        }))
        .on('error', (err) => {
            $.util.log(err.fileName, err.lineNumber, err.message);
            this.emit('end');
        })
        .pipe($.rename({
            suffix: '.min'
        }))
        // .pipe($.sourcemaps.write('./', {
        //     includeContent: false,
        //     sourceRoot: '/src/scripts'
        // }))
        .pipe(gulp.dest(paths.dest.js));
});
gulp.task('webpack', (callback) => {
    const CommonsChunkPlugin = require('webpack/lib/optimize/CommonsChunkPlugin');
    const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
    let filename = '';
    let chunkFilename = '';
    if (status === 'dev') {
        filename = '[name].bundle.min.js';
        chunkFilename = '[name].chunk.min.js';
    } else if (status === 'prod') {
        filename = '[name].bundle.[hash].min.js';
        chunkFilename = '[name].chunk.min.js';
    }
    webpack({
        entry: paths.src.entry,
        output: {
            path: path.join(__dirname, paths.dest.js),
            filename: filename,
            chunkFilename: chunkFilename
        },
        plugins: [
            new UglifyJSPlugin({
                compress: {
                    warnings: false
                }
            })
        ],
        module: {
            rules: [{
                test: path.join(__dirname, 'src/scripts'),
                use: [{
                    loader: 'babel-loader',
                    options: {
                        presets: ['env'],
                        plugins: ['transform-runtime']
                    }
                }]
            }]
        },
        resolve: {},
        externals: {}
    }, (err, stats) => {
        if (err) {
            throw new $.util.PluginError('webpack', err);
        }
        $.util.log('[webpack]', stats.toString({
            // output options
        }));
        callback();
    });
});
gulp.task('rootFile', () => {
    return gulp.src(paths.src.root + '/*.*')
        .pipe(gulp.dest(paths.dest.root));
});
gulp.task('view', () => {
    return gulp.src(paths.src.view)
        .pipe(gulp.dest(paths.dest.view));
});
gulp.task('img', () => {
    return gulp.src(paths.src.img)
        .pipe(gulp.dest(paths.dest.img));
});
gulp.task('data', () => {
    return gulp.src(paths.src.data)
        .pipe(gulp.dest(paths.dest.data));
});
gulp.task('font', () => {
    return gulp.src(paths.src.font)
        .pipe(gulp.dest(paths.dest.font));
});
gulp.task('bower', () => {
    if (status === 'dev') {
        return true;
    } else if (status === 'prod') {
        return $.bower();
    }
});
gulp.task('watch', () => {
    gulp.watch(paths.src.style, ['styleConcat']);
    gulp.watch(paths.src.root + '/*.*', ['rootFile']);
    gulp.watch(paths.src.view, ['view']);
    gulp.watch(paths.src.img, ['img']);
    gulp.watch(paths.src.data, ['data']);
    gulp.watch(paths.src.vendor, ['vendor']);
    gulp.watch(paths.src.js, ['webpack']);
});
gulp.task('connect', () => {
    $.connect.server({
        debug: true,
        root: ['dist'],
        index: 'app.htm',
        port: 80,
        middleware: () => {
            return [
                proxy(['/api/admin', '/api/web'], {
                    target: 'http://127.0.0.1:9090',
                    changeOrigin: false
                }),
                proxy(['/api/cho'], {
                    target: 'http://dig.chouti.com',
                    changeOrigin: true,
                    pathRewrite: {
                        '^/api/cho': ''
                    },
                    logLevel: 'info'
                }),
                proxy(['/api/sho'], {
                    target: 'http://route.showapi.com',
                    changeOrigin: true,
                    pathRewrite: {
                        '^/api/sho': ''
                    },
                    logLevel: 'info'
                }),
                proxy(['/project', '/sso', '/authManage', '/indexController', '/globalPermissionManage', '/systemDDL', '/treeController'], {
                    target: 'http://192.168.32.33:9080',
                    changeOrigin: false
                })
            ];
        }
    });
    open('http://127.0.0.1');
});
gulp.task('shell', () => {
    return gulp.src('*.js', {
            read: false
        })
        .pipe($.shell(['node ./node_modules/justreq-cli/bin/justreq start -c']));
});
gulp.task('run', () => {
    runSequence('clean', 'bower', ['rootFile', 'view', 'img', 'data', 'font', 'styleConcat'], 'webpack', 'watch', 'connect', 'shell');
});
gulp.task('default', () => {
    status = 'dev';
    gulp.start('run');
});
gulp.task('prod', () => {
    status = 'prod';
    gulp.start('run');
});<commit_msg>设置web默认首页<commit_after>const gulp = require('gulp'),
    $ = require('gulp-load-plugins')(),
    del = require('del'),
    open = require('open'),
    path = require('path'),
    proxy = require('http-proxy-middleware'),
    webpack = require('webpack'),
    runSequence = require('run-sequence'),
    paths = {
        src: {
            root: './src',
            style: './src/styles/**/*',
            js: './src/scripts/**/*.js',
            view: './src/views/**/*',
            img: './src/images/**/*',
            data: './src/datas/**/*',
            font: './src/fonts/**/*',
            vendor: './src/vendors/**/*',
            entry: {
                'vendor.common': './src/scripts/vendor.common',
                app: './src/scripts/app'
            }
        },
        dest: {
            root: './dist',
            style: './dist/styles',
            js: './dist/scripts',
            view: './dist/views',
            img: './dist/images',
            data: './dist/datas',
            font: './dist/fonts',
            vendor: './dist/vendors'
        },
        concat: {
            css: ['./dist/styles/cyan.common.min.css', './dist/vendors/bootstrap/dist/css/bootstrap.min.css', './dist/vendors/font-awesome/css/font-awesome.min.css', './dist/styles/common.min.css', './src/scripts/mods/zSlide/zslide.css']
        }
    };
let status = '';
gulp.task('clean', () => {
    if (status === 'dev') {
        return del([paths.dest.root + '/**/*', '!' + paths.dest.vendor + '/**']);
    } else {
        return del([paths.dest.root + '/**/*']);
    }
});
gulp.task('style', () => {
    let scss = $.filter('**/*.scss', {
        restore: true
    });
    return gulp.src(paths.src.style)
        .pipe($.changed(paths.dest.style, {
            extension: '.min.css'
        }))
        .on('data', (file) => {
            $.util.log(file.path);
        })
        .pipe(scss)
        .pipe($.sass(
            {
                outputStyle: 'expanded'
            })
            .on('error', (err) => {
                $.util.log(err.message);
                this.emit('end');
            }))
        .pipe(scss.restore)
        .pipe($.csso())
        .pipe($.autoprefixer('last 2 version', 'safari5', 'ie8', 'ie9', 'opera 12.1', 'ios 6', 'android 4'))
        .on('error', (err) => {
            $.util.log(err.message);
            this.emit('end');
        })
        .pipe($.rename({
            suffix: '.min'
        }))
        .pipe(gulp.dest(paths.dest.style));
});
gulp.task('styleConcat', ['style'], () => {
    return gulp.src(paths.concat.css)
        .pipe($.concat('vendor.common.min.css'))
        .pipe(gulp.dest(paths.dest.style));
});
gulp.task('js', () => {
    return gulp.src(paths.src.js)
        .pipe($.changed(paths.dest.js, {
            extension: '.min.js'
        }))
        .on('data', (file) => {
            $.util.log(file.path);
        })
        // .pipe($.sourcemaps.init())
        .pipe($.babel({
            presets: ['es2015'],
            compact: true,
            comments: false
        }))
        .on('error', (err) => {
            $.util.log(err.fileName, err.lineNumber, err.message);
            this.emit('end');
        })
        .pipe($.rename({
            suffix: '.min'
        }))
        // .pipe($.sourcemaps.write('./', {
        //     includeContent: false,
        //     sourceRoot: '/src/scripts'
        // }))
        .pipe(gulp.dest(paths.dest.js));
});
gulp.task('webpack', (callback) => {
    const CommonsChunkPlugin = require('webpack/lib/optimize/CommonsChunkPlugin');
    const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
    let filename = '';
    let chunkFilename = '';
    if (status === 'dev') {
        filename = '[name].bundle.min.js';
        chunkFilename = '[name].chunk.min.js';
    } else if (status === 'prod') {
        filename = '[name].bundle.[hash].min.js';
        chunkFilename = '[name].chunk.min.js';
    }
    webpack({
        entry: paths.src.entry,
        output: {
            path: path.join(__dirname, paths.dest.js),
            filename: filename,
            chunkFilename: chunkFilename
        },
        plugins: [
            new UglifyJSPlugin({
                compress: {
                    warnings: false
                }
            })
        ],
        module: {
            rules: [{
                test: path.join(__dirname, 'src/scripts'),
                use: [{
                    loader: 'babel-loader',
                    options: {
                        presets: ['env'],
                        plugins: ['transform-runtime']
                    }
                }]
            }]
        },
        resolve: {},
        externals: {}
    }, (err, stats) => {
        if (err) {
            throw new $.util.PluginError('webpack', err);
        }
        $.util.log('[webpack]', stats.toString({
            // output options
        }));
        callback();
    });
});
gulp.task('rootFile', () => {
    return gulp.src(paths.src.root + '/*.*')
        .pipe(gulp.dest(paths.dest.root));
});
gulp.task('view', () => {
    return gulp.src(paths.src.view)
        .pipe(gulp.dest(paths.dest.view));
});
gulp.task('img', () => {
    return gulp.src(paths.src.img)
        .pipe(gulp.dest(paths.dest.img));
});
gulp.task('data', () => {
    return gulp.src(paths.src.data)
        .pipe(gulp.dest(paths.dest.data));
});
gulp.task('font', () => {
    return gulp.src(paths.src.font)
        .pipe(gulp.dest(paths.dest.font));
});
gulp.task('bower', () => {
    if (status === 'dev') {
        return true;
    } else if (status === 'prod') {
        return $.bower();
    }
});
gulp.task('watch', () => {
    gulp.watch(paths.src.style, ['styleConcat']);
    gulp.watch(paths.src.root + '/*.*', ['rootFile']);
    gulp.watch(paths.src.view, ['view']);
    gulp.watch(paths.src.img, ['img']);
    gulp.watch(paths.src.data, ['data']);
    gulp.watch(paths.src.vendor, ['vendor']);
    gulp.watch(paths.src.js, ['webpack']);
});
gulp.task('connect', () => {
    $.connect.server({
        debug: true,
        root: ['dist'],
        index: false,
        port: 80,
        fallback: 'dist/app.htm',
        middleware: () => {
            return [
                proxy(['/api/admin', '/api/web'], {
                    target: 'http://127.0.0.1:9090',
                    changeOrigin: false
                }),
                proxy(['/api/cho'], {
                    target: 'http://dig.chouti.com',
                    changeOrigin: true,
                    pathRewrite: {
                        '^/api/cho': ''
                    },
                    logLevel: 'info'
                }),
                proxy(['/api/sho'], {
                    target: 'http://route.showapi.com',
                    changeOrigin: true,
                    pathRewrite: {
                        '^/api/sho': ''
                    },
                    logLevel: 'info'
                }),
                proxy(['/project', '/sso', '/authManage', '/indexController', '/globalPermissionManage', '/systemDDL', '/treeController'], {
                    target: 'http://192.168.32.33:9080',
                    changeOrigin: false
                })
            ];
        }
    });
    open('http://127.0.0.1');
});
gulp.task('shell', () => {
    return gulp.src('*.js', {
            read: false
        })
        .pipe($.shell(['node ./node_modules/justreq-cli/bin/justreq start -c']));
});
gulp.task('run', () => {
    runSequence('clean', 'bower', ['rootFile', 'view', 'img', 'data', 'font', 'styleConcat'], 'webpack', 'watch', 'connect', 'shell');
});
gulp.task('default', () => {
    status = 'dev';
    gulp.start('run');
});
gulp.task('prod', () => {
    status = 'prod';
    gulp.start('run');
});<|endoftext|>