<commit_before>/**
 * Created by Robert on 02/05/2014.
 */

var ProgressBar = require('progress');
var cheerio = require('cheerio');
var async = require('async');
var fs = require('fs');
var albumProgressBar;
var albumHtml;
var request;
var config;

module.exports = {
  login : function login(configIn, callback) {
    config = configIn;
    request = require('request');
    var cookie = 'pbx_' + config.baseDomain.replace(/\./g, '_') + '=' + config.authCookieValue;
    var j = request.jar();
    j.setCookie(cookie, 'http://' + config.baseDomain);

    request = request.defaults({jar : j});
    request('http://' + config.baseDomain + '/my/albums', function (err, response, body) {
      if (!err && response.statusCode == 200) {
        var $ = cheerio.load(body);
        if ($('#pbx_signout').length !== 0) {
          albumHtml = body;
          callback(null, true);
        } else {
          callback('Was unable to login with given cookie value!');
        }
      } else {
        callback(err);
      }
    });
  },

  getAlbumList : function getAlbumList() {
    var $ = cheerio.load(albumHtml);
    var albumObjects = [];
    var albums = $('.pbx_myphotobox_thumbnail');

    albums.each(function () {

      albumObjects.push({
        name  : $(this).find('.pbx_object_name').text(),
        link  : $(this).find('.pbx_object_title').attr('href'),
        count : parseInt($($(this).find('span')[1]).text().replace(/\D/g, ""), 10)
      });
    });

    return albumObjects;
  },

  getPhotos : function getPhotos(html) {

    var $ = cheerio.load(html);
    var photos = [];

    $('.pbx_thumb_container').each(function () {
      photos.push({
        link : $(this).find('img').attr('onclick').split("'")[1],
        id   : $(this).find('img').attr('onclick').split("'")[1].split('photo_id=')[1]
      });
    });

    return photos;

  },

  downloadPhoto : function downloadPhotos(options, callback) {

    var buildName = function (name) {
      var counter = 1;
      var originalName = name;
      // copy with duplicate file names
      while(fs.existsSync(options.outputDir + '/' + name + '.jpg')) {
        name = originalName + '_' + counter;
        counter++;
      }
      return name  + '.jpg';
    };

    request('http://' + config.baseDomain + '/my/photo/full?photo_id=' + options.id,
      function (err, response, body) {
        if (!err && response.statusCode == 200) {
          var $ = cheerio.load(body);
          var name = buildName($('img').attr('alt'));
          // Save photo
          request($('img').attr('src'), callback).pipe(fs.createWriteStream(options.outputDir + '/' + name));
        } else {
          callback(err);
        }
      }
    );
  },

  downloadPagePhotos : function (options, callback) {
    var self = this;
    var photos = this.getPhotos(options.body);
    var outputDir = options.outputDir + '/' + options.album.name;

    if (!fs.existsSync(outputDir)) {
      fs.mkdirSync(outputDir);
    }

    async.each(photos, function (photo, callbackFn) {
      self.downloadPhoto({id : photo.id, outputDir : outputDir }, function (err) {
        if (err) {
          callback(err);
        } else {
          if (options.showProgress) {
            albumProgressBar.tick();
          }
          callbackFn(null, true);
        }
      });

    }, function (err) {

      if (err) {
        // One of the iterations produced an error.
        // All processing will now stop.
        console.log('A file failed to process');
      } else {
        callback(null, true)
      }
    });
  },

  // Get all the albumHtml of all the pages of a album (for later processing)
  getAlbumPages : function (album, callback) {

    var pageRequests = [];
    request('http://' + config.baseDomain + album.link, function (err, response, body) {
      if (!err && response.statusCode == 200) {

        pageRequests.push(body);
        var $ = cheerio.load(body);
        var pageLink = $('.pbx_paginator_count a').attr('href');
        var pageLinks = [];
        var thumbsPerPage = $('.pbx_thumb_container').length;

        if (album.count > 100) {
          pageLinks.push(pageLink);
          var pageCount = Math.ceil(album.count/thumbsPerPage);
          for (var i=3;i<=pageCount;i++) {
            var link = pageLink.replace('&page=2&', '&page=' + i + '&');
            pageLinks.push(link);
          }
        }

        if (pageLinks.length !== 0) {
          async.each(
            pageLinks,
            function (link, callbackFn) {
              request('http://' + config.baseDomain + '/my/album' + link, function (err, response, body) {
                if (!err && response.statusCode == 200) {
                  pageRequests.push(body);
                  callbackFn(null)
                } else {
                  callback(err);
                }
              });
            },
            function (err) {
              if (err) {
                callback(err);
              } else {
                callback(null, pageRequests); // pass back all html pages
              }
            }
          );
        } else {
          callback(null, pageRequests); // only one page
        }
      } else {
        callback(err);
      }
    });
  },

  downloadAlbum : function downloadAlbum(options, callback) {

    var self = this;
    if (options.showProgress) {
      console.log('Processing album:', options.album.name);

      if (options.album.count === 0) {
        console.log('  [Album empty]');
        return callback(null);
      } else {
        albumProgressBar = new ProgressBar('  [:bar] Downloading :current of :total (:percent)', {
          total      : options.album.count,
          complete   : '*',
          incomplete : ' ',
          width      : 40
        });
      }
    }

    // To download album, first get the content of every page in the album,
    // Then download the photos from each page
    this.getAlbumPages(options.album, function (err, getAlbumPages) {
      if (err) {
        callback(err);
      } else {
        async.each(
          getAlbumPages,
          function (body, callbackFn) {
            options.body = body;
            self.downloadPagePhotos(
              options,
              function (err) {
                if (err) {
                  callback(err);
                } else {
                  callbackFn();
                }
              });
          },
          function (err) {
            if (err) {
              callback(err);
            } else {
              callback(null, true, options.album)
            }
          }
        );
      }
    });
  },

  downloadAll : function downloadAll(options, callback) {

    var self = this;
    var albums = this.getAlbumList();

    async.eachSeries(
      albums,
      function iterator(album, callbackFn) {
        options.album = album;
        self.downloadAlbum({
          album        : album,
          showProgress : options.showProgress,
          outputDir    : options.outputDir
        }, function (err) {
          if (err) {
            callback(err);
          } else {
            callbackFn(null, true, options.album);
          }
        })
      },
      function finalCallback(err) {
        if (err) {
          callback(err);
        } else {
          callback(null, true, options.album)
        }
      }
    );
  }
};<commit_msg>Fixing minor issue where if your view preference was not default some images would not be downloaded (reported by user tomdbarker)<commit_after>/**
 * Created by Robert on 02/05/2014.
 */

var ProgressBar = require('progress');
var cheerio = require('cheerio');
var async = require('async');
var fs = require('fs');
var albumProgressBar;
var albumHtml;
var request;
var config;

module.exports = {
  login : function login(configIn, callback) {
    config = configIn;
    request = require('request');
    var cookie = 'pbx_' + config.baseDomain.replace(/\./g, '_') + '=' + config.authCookieValue;
    var j = request.jar();
    j.setCookie(cookie, 'http://' + config.baseDomain);

    request = request.defaults({jar : j});
    request('http://' + config.baseDomain + '/my/albums', function (err, response, body) {
      if (!err && response.statusCode == 200) {
        var $ = cheerio.load(body);
        if ($('#pbx_signout').length !== 0) {
          albumHtml = body;
          callback(null, true);
        } else {
          callback('Was unable to login with given cookie value!');
        }
      } else {
        callback(err);
      }
    });
  },

  getAlbumList : function getAlbumList() {
    var $ = cheerio.load(albumHtml);
    var albumObjects = [];
    var albums = $('.pbx_myphotobox_thumbnail');

    albums.each(function () {

      albumObjects.push({
        name  : $(this).find('.pbx_object_name').text(),
        link  : $(this).find('.pbx_object_title').attr('href'),
        count : parseInt($($(this).find('span')[1]).text().replace(/\D/g, ""), 10)
      });
    });

    return albumObjects;
  },

  getPhotos : function getPhotos(html) {

    var $ = cheerio.load(html);
    var photos = [];

    $('.pbx_thumb_container').each(function () {
      photos.push({
        link : $(this).find('img').attr('onclick').split("'")[1],
        id   : $(this).find('img').attr('onclick').split("'")[1].split('photo_id=')[1]
      });
    });

    return photos;

  },

  downloadPhoto : function downloadPhotos(options, callback) {

    var buildName = function (name) {
      var counter = 1;
      var originalName = name;
      // copy with duplicate file names
      while(fs.existsSync(options.outputDir + '/' + name + '.jpg')) {
        name = originalName + '_' + counter;
        counter++;
      }
      return name  + '.jpg';
    };

    request('http://' + config.baseDomain + '/my/photo/full?photo_id=' + options.id,
      function (err, response, body) {
        if (!err && response.statusCode == 200) {
          var $ = cheerio.load(body);
          var name = buildName($('img').attr('alt'));
          // Save photo
          request($('img').attr('src'), callback).pipe(fs.createWriteStream(options.outputDir + '/' + name));
        } else {
          callback(err);
        }
      }
    );
  },

  downloadPagePhotos : function (options, callback) {
    var self = this;
    var photos = this.getPhotos(options.body);
    var outputDir = options.outputDir + '/' + options.album.name;

    if (!fs.existsSync(outputDir)) {
      fs.mkdirSync(outputDir);
    }

    async.each(photos, function (photo, callbackFn) {
      self.downloadPhoto({id : photo.id, outputDir : outputDir }, function (err) {
        if (err) {
          callback(err);
        } else {
          if (options.showProgress) {
            albumProgressBar.tick();
          }
          callbackFn(null, true);
        }
      });

    }, function (err) {

      if (err) {
        // One of the iterations produced an error.
        // All processing will now stop.
        console.log('A file failed to process');
      } else {
        callback(null, true)
      }
    });
  },

  // Get all the albumHtml of all the pages of a album (for later processing)
  getAlbumPages : function (album, callback) {

    var pageRequests = [];
    request('http://' + config.baseDomain + album.link, function (err, response, body) {
      if (!err && response.statusCode == 200) {

        pageRequests.push(body);
        var $ = cheerio.load(body);
        var pageLink = $('.pbx_paginator_count a').attr('href');
        var pageLinks = [];
        var thumbsPerPage = $('.pbx_thumb_container').length;

        if (album.count > thumbsPerPage) {
          pageLinks.push(pageLink);
          var pageCount = Math.ceil(album.count/thumbsPerPage);
          for (var i=3;i<=pageCount;i++) {
            var link = pageLink.replace('&page=2&', '&page=' + i + '&');
            pageLinks.push(link);
          }
        }

        if (pageLinks.length !== 0) {
          async.each(
            pageLinks,
            function (link, callbackFn) {
              request('http://' + config.baseDomain + '/my/album' + link, function (err, response, body) {
                if (!err && response.statusCode == 200) {
                  pageRequests.push(body);
                  callbackFn(null)
                } else {
                  callback(err);
                }
              });
            },
            function (err) {
              if (err) {
                callback(err);
              } else {
                callback(null, pageRequests); // pass back all html pages
              }
            }
          );
        } else {
          callback(null, pageRequests); // only one page
        }
      } else {
        callback(err);
      }
    });
  },

  downloadAlbum : function downloadAlbum(options, callback) {

    var self = this;
    if (options.showProgress) {
      console.log('Processing album:', options.album.name);

      if (options.album.count === 0) {
        console.log('  [Album empty]');
        return callback(null);
      } else {
        albumProgressBar = new ProgressBar('  [:bar] Downloading :current of :total (:percent)', {
          total      : options.album.count,
          complete   : '*',
          incomplete : ' ',
          width      : 40
        });
      }
    }

    // To download album, first get the content of every page in the album,
    // Then download the photos from each page
    this.getAlbumPages(options.album, function (err, getAlbumPages) {
      if (err) {
        callback(err);
      } else {
        async.each(
          getAlbumPages,
          function (body, callbackFn) {
            options.body = body;
            self.downloadPagePhotos(
              options,
              function (err) {
                if (err) {
                  callback(err);
                } else {
                  callbackFn();
                }
              });
          },
          function (err) {
            if (err) {
              callback(err);
            } else {
              callback(null, true, options.album)
            }
          }
        );
      }
    });
  },

  downloadAll : function downloadAll(options, callback) {

    var self = this;
    var albums = this.getAlbumList();

    async.eachSeries(
      albums,
      function iterator(album, callbackFn) {
        options.album = album;
        self.downloadAlbum({
          album        : album,
          showProgress : options.showProgress,
          outputDir    : options.outputDir
        }, function (err) {
          if (err) {
            callback(err);
          } else {
            callbackFn(null, true, options.album);
          }
        })
      },
      function finalCallback(err) {
        if (err) {
          callback(err);
        } else {
          callback(null, true, options.album)
        }
      }
    );
  }
};<|endoftext|>


<commit_before>var path = require('path');
var routes = require('./server/routes/index');
var recipes = require('./server/routes/recipes');
var bodyParser = require('body-parser');
var connect = require('connect');
var mongoConnect = require('./server/mongoConnect.js');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var mongoose = require('mongoose');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;

/*var routes = require('./server/routes/index');*/

var uri = 'mongodb://localhost:27017/recipals';
var db = require('mongoose').connect(uri);
/*var db;
mongoConnect.connect().then(function() {
    //maybe some additional logic if need by when mongo connects
    db = mongoConnect.db;
});*/

var express = require('express'),
    port = 8005,
    app = express();

app.options("*", function (req, res) {
    console.log("OPTIONS");
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Methods", "*");
    res.setHeader("Access-Control-Allow-Headers", "format, Accept, X-Requested-With, Origin, Content-Type ");
    res.end();
});

// view engine setup
app.set('views', path.join(__dirname, 'views'));

//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('express-session')({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', express.static(path.join(__dirname, '/')));

app.use('/', routes);
//app.use('/newRecipe', );
app.use('/login', routes);
app.use('/recipes', recipes);
app.use('/newRecipes', recipes);

// passport config
var Account = require('./server/models/account.js');
passport.use(new LocalStrategy(
  function(username, password, done) {
    Account.findOne({ username: username }, function (err, user) {
        console.log(user);
      if (err) { return done(err); }
      if (!user) { return done(null, false); }
      if (user.password != password) { return done(null, false); }
      return done(null, user);
    });
  }
));
passport.serializeUser(Account.serializeUser());
passport.deserializeUser(Account.deserializeUser());

//mongoose.connect('mongodb://localhost:27017/Recipals');

// catch 404 and forward to error handler
/*app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});*/

app.listen(port);
console.log('Server running on port ' + port + '.');<commit_msg>Fixed registration. Utilizes salt and hash, doesnt store or compare psaswords<commit_after>var path = require('path');
var routes = require('./server/routes/index');
var recipes = require('./server/routes/recipes');
var bodyParser = require('body-parser');
var connect = require('connect');
var mongoConnect = require('./server/mongoConnect.js');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var mongoose = require('mongoose');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;

/*var routes = require('./server/routes/index');*/

var uri = 'mongodb://localhost:27017/recipals';
var db = require('mongoose').connect(uri);
/*var db;
mongoConnect.connect().then(function() {
    //maybe some additional logic if need by when mongo connects
    db = mongoConnect.db;
});*/

var express = require('express'),
    port = 8005,
    app = express();

app.options("*", function (req, res) {
    console.log("OPTIONS");
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Methods", "*");
    res.setHeader("Access-Control-Allow-Headers", "format, Accept, X-Requested-With, Origin, Content-Type ");
    res.end();
});

// view engine setup
app.set('views', path.join(__dirname, 'views'));

//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('express-session')({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', express.static(path.join(__dirname, '/')));

app.use('/', routes);
//app.use('/newRecipe', );
app.use('/login', routes);
app.use('/recipes', recipes);
app.use('/newRecipes', recipes);

// passport config
var Account = require('./server/models/account.js');
/*passport.use(new LocalStrategy(
  function(username, password, done) {
    Account.findOne({ username: username }, function (err, user) {
        console.log(user);
      if (err) { return done(err); }
      if (!user) { return done(null, false); }
      if (user.password != password) { return done(null, false); }
      return done(null, user);
    });
  }
));*/
passport.use(new LocalStrategy(Account.authenticate()));
passport.serializeUser(Account.serializeUser());
passport.deserializeUser(Account.deserializeUser());

//mongoose.connect('mongodb://localhost:27017/Recipals');

// catch 404 and forward to error handler
/*app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});*/

app.listen(port);
console.log('Server running on port ' + port + '.');<|endoftext|>


<commit_before>var path = require("path");
var webpack = require("webpack");
var webpackConfig = require("./webpack.config.js");
var base_config = require("./chore/chore.config");

webpackConfig.entry = {};

// Karma configuration
// Generated on Fri Jan 16 2015 01:40:34 GMT+0200 (EET)
module.exports = function (config) {
    var cfg = {
        basePath: ".",
        frameworks: ["jasmine"],
        port: 9876,
        logLevel: config.LOG_INFO,
        colors: true,
        autoWatch: true,
        browsers: ["Chrome"],

        customLaunchers: {
            Chrome_Travis_CI: {
                base: 'Chrome',
                flags: ['--no-sandbox']
            }
        },

        files: [
            "./node_modules/angular/angular.js"
            , "./node_modules/angular-mocks/angular-mocks.js"
            , "./dist/index.js"
            , "./src/star-rating.controller.jasmine.ts"
        ],

        // Karma plugins loaded
        plugins: [
            "karma-webpack"
            , "karma-jasmine"
            , "karma-coverage"
            , "karma-chrome-launcher"
        ],

        // Coverage reporter generates the coverage
        reporters: ["progress", "dots", "coverage"],

        // Source files that you wanna generate coverage for.
        // Do not include tests or libraries (these files will be instrumented by Istanbul)
        preprocessors: {
            "src/*!(*.jasmine*|*.protractor|*.mock|*.bundle).ts": ["webpack", "coverage"]
            //, "src/**/*.ts": ["webpack"]
            //, "src/*!(*.jasmine*|*.protractor*|*.mock*|*.bundle*).ts": ["webpack", "coverage"]
            //, "./src/star-rating.controller.ts": ["webpack", "coverage"]
            //, "./src/star-rating.component.ts": ["webpack", "coverage"]
            , "./dist/*.js*": ["coverage"]
        },

        webpack: webpackConfig,

        coverageReporter: {
            reporters: [
                {dir: "coverage/"},
                {type: "lcov"}
            ]
        },

        singleRun: true
    };

    if (process.env.TRAVIS) {
        cfg.browsers = ['Chrome_Travis_CI'];
    }

    config.set(cfg);
};<commit_msg>chore(travis-ci): test testing<commit_after>var path = require("path");
var webpack = require("webpack");
var webpackConfig = require("./webpack.config.js");
var base_config = require("./chore/chore.config");

webpackConfig.entry = {};

// Karma configuration
// Generated on Fri Jan 16 2015 01:40:34 GMT+0200 (EET)
module.exports = function (config) {
    var cfg = {
        basePath: ".",
        frameworks: ["jasmine"],
        port: 9876,
        logLevel: config.LOG_INFO,
        colors: true,
        autoWatch: true,
        browsers: ["PhantomJS"],

        /*customLaunchers: {
            Chrome_Travis_CI: {
                base: 'Chrome',
                flags: ['--no-sandbox']
            }
        },*/

        files: [
            "./node_modules/angular/angular.js"
            , "./node_modules/angular-mocks/angular-mocks.js"
            , "./dist/index.js"
            , "./src/star-rating.controller.jasmine.ts"
        ],

        // Karma plugins loaded
        plugins: [
            "karma-webpack"
            , "karma-jasmine"
            , "karma-coverage"
            , "karma-chrome-launcher"
        ],

        // Coverage reporter generates the coverage
        reporters: ["progress", "dots", "coverage"],

        // Source files that you wanna generate coverage for.
        // Do not include tests or libraries (these files will be instrumented by Istanbul)
        preprocessors: {
            "src/*!(*.jasmine*|*.protractor|*.mock|*.bundle).ts": ["webpack", "coverage"]
            //, "src/**/*.ts": ["webpack"]
            //, "src/*!(*.jasmine*|*.protractor*|*.mock*|*.bundle*).ts": ["webpack", "coverage"]
            //, "./src/star-rating.controller.ts": ["webpack", "coverage"]
            //, "./src/star-rating.component.ts": ["webpack", "coverage"]
            , "./dist/*.js*": ["coverage"]
        },

        webpack: webpackConfig,

        coverageReporter: {
            reporters: [
                {dir: "coverage/"},
                {type: "lcov"}
            ]
        },

        singleRun: true
    };

    if (process.env.TRAVIS) {
        //cfg.browsers = ['Chrome_Travis_CI'];
    }

    config.set(cfg);
};<|endoftext|>


<commit_before>// Traditional Chinese

jQuery.extend( jQuery.fn.pickadate.defaults, {
    monthsFull: [ '一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月' ],
    monthsShort: [ '一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二' ],
    weekdaysFull: [ '星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六' ],
    weekdaysShort: [ '日', '一', '二', '三', '四', '五', '六' ],
    today: '今天',
    clear: '清除',
    close: '关闭',
    firstDay: 1,
    format: 'yyyy 年 mm 月 dd 日',
    formatSubmit: 'yyyy/mm/dd'
});

jQuery.extend( jQuery.fn.pickatime.defaults, {
    clear: '清除'
});
<commit_msg>Fixed the translation "close" to traditional chinese<commit_after>// Traditional Chinese

jQuery.extend( jQuery.fn.pickadate.defaults, {
    monthsFull: [ '一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月' ],
    monthsShort: [ '一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二' ],
    weekdaysFull: [ '星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六' ],
    weekdaysShort: [ '日', '一', '二', '三', '四', '五', '六' ],
    today: '今天',
    clear: '清除',
    close: '關閉',
    firstDay: 1,
    format: 'yyyy 年 mm 月 dd 日',
    formatSubmit: 'yyyy/mm/dd'
});

jQuery.extend( jQuery.fn.pickatime.defaults, {
    clear: '清除'
});
<|endoftext|>


<commit_before>module.exports = function(config) {
  config.set({
    basePath: './',
    frameworks: ['systemjs', 'jasmine'],
    systemjs: {
      configFile: 'app/config.js',
      config: {
        paths: {
          "*": "*",
          "src/*": "app/src/*",
          "github:*": "app/jspm_packages/github/*",
          "npm:*": "app/jspm_packages/npm/*",
          "typescript": "node_modules/typescript/lib/typescript.js",
          "systemjs": "node_modules/systemjs/dist/system.js",
          'system-polyfills': 'node_modules/systemjs/dist/system-polyfills.js',
          'es6-module-loader': 'node_modules/es6-module-loader/dist/es6-module-loader.js',
        },
        packages: {
          'app/test/unit': {
            defaultExtension: 'ts'
          },
          'app/src': {
            defaultExtension: 'ts'
          }
        },
        transpiler: 'typescript',
        typescriptOptions : {
          "module": "amd",
          "emitDecoratorMetadata": true,
          "experimentalDecorators": true
        }
      },
      serveFiles: [
        'app/src/**/*.*',
        'app/jspm_packages/**/*'
      ]
    },
    files: [
      'app/test/unit/setup.ts',
      'app/test/unit/*.ts'
    ],
    exclude: [],
    preprocessors: { },
    reporters: ['progress'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false,
    customLaunchers: {
      Chrome_travis_ci: {
        base: 'Chrome',
        flags: ['--no-sandbox']
      }
    },
  });

  if (process.env.TRAVIS) {
    configuration.browsers = ['Chrome_travis_ci', 'Firefox'];
  }
};<commit_msg>chore(karma): fixed karma error<commit_after>module.exports = function(config) {

  var configuration = {
    basePath: './',
    frameworks: ['systemjs', 'jasmine'],
    systemjs: {
      configFile: 'app/config.js',
      config: {
        paths: {
          "*": "*",
          "src/*": "app/src/*",
          "github:*": "app/jspm_packages/github/*",
          "npm:*": "app/jspm_packages/npm/*",
          "typescript": "node_modules/typescript/lib/typescript.js",
          "systemjs": "node_modules/systemjs/dist/system.js",
          'system-polyfills': 'node_modules/systemjs/dist/system-polyfills.js',
          'es6-module-loader': 'node_modules/es6-module-loader/dist/es6-module-loader.js',
        },
        packages: {
          'app/test/unit': {
            defaultExtension: 'ts'
          },
          'app/src': {
            defaultExtension: 'ts'
          }
        },
        transpiler: 'typescript',
        typescriptOptions : {
          "module": "amd",
          "emitDecoratorMetadata": true,
          "experimentalDecorators": true
        }
      },
      serveFiles: [
        'app/src/**/*.*',
        'app/jspm_packages/**/*'
      ]
    },
    files: [
      'app/test/unit/setup.ts',
      'app/test/unit/*.ts'
    ],
    exclude: [],
    preprocessors: { },
    reporters: ['progress'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false,
    customLaunchers: {
      Chrome_travis_ci: {
        base: 'Chrome',
        flags: ['--no-sandbox']
      }
    },
  };

  if (process.env.TRAVIS) {
    configuration.browsers = ['Chrome_travis_ci', 'Firefox'];
  }

  config.set(configuration);
};<|endoftext|>


<commit_before>module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['mocha'],
    files: [
      { pattern: 'https://cdn.polyfill.io/v2/polyfill.js?flags=gated&features=default,NodeList.prototype.@@iterator,IntersectionObserver', watched: false, served: false, included: true },
      { pattern: 'node_modules/power-assert/build/power-assert.js', watched: true, served: true, included: true },
      { pattern: 'dist/*.js', watched: true, served: true, included: true },
      { pattern: 'test/integration/usecase/**/*.{html,css,js}', watched: true, served: true, included: true },
      { pattern: 'test/unit/fixture/**/*', watched: true, served: true, included: false }
    ],
    exclude: [
    ],
    espowerPreprocessor: {
      options: {
        emitActualCode: false,
        ignoreUpstreamSourceMap: true
      }
    },
    reporters: ['dots'],
    coverageReporter: {
      dir: 'coverage',
      subdir: function (browser, platform) {
        return browser.toLowerCase().split(' ')[0];
      },
			includeAllSources: true,
      instrumenters: {
        isparta: require('isparta')
      },
      instrumenter: {
        '**/*.js': 'isparta'
      },
      reporters: [
        { type: 'lcov' },
        { type: 'text-summary', subdir: '.', file: 'summary.txt' },
      ]
    },
    autoWatch: true,
    autoWatchBatchDelay: 500,
    browsers: ['Chrome'],
  });
};
<commit_msg>chore(config): refactoring<commit_after>module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['mocha'],
    files: [
      { pattern: 'https://cdn.polyfill.io/v2/polyfill.js?flags=gated&features=default,NodeList.prototype.@@iterator,IntersectionObserver', watched: false, served: false, included: true },
      { pattern: 'node_modules/power-assert/build/power-assert.js', watched: true, served: true, included: true },
      { pattern: 'dist/*.js', watched: true, served: true, included: true },
      { pattern: 'test/integration/usecase/**/*.{html,css,js}', watched: true, served: true, included: true },
      { pattern: 'test/unit/fixture/**/*', watched: true, served: true, included: false }
    ],
    exclude: [
    ],
    espowerPreprocessor: {
      options: {
        emitActualCode: false,
        ignoreUpstreamSourceMap: true
      }
    },
    reporters: ['dots'],
    coverageReporter: {
      dir: 'coverage',
      subdir: function (browser, platform) {
        return browser.toLowerCase().split(' ')[0];
      },
      includeAllSources: true,
      instrumenters: {
        isparta: require('isparta')
      },
      instrumenter: {
        '**/*.js': 'isparta'
      },
      reporters: [
        { type: 'lcov' },
        { type: 'text-summary', subdir: '.', file: 'summary.txt' },
      ]
    },
    autoWatch: true,
    autoWatchBatchDelay: 500,
    browsers: ['Chrome'],
  });
};
<|endoftext|>


<commit_before>var http = require('http');
var express = require('express');
var app = express.createServer();

//Lets define a port we want to listen to
const PORT=8080;

//We need a function which handles requests and send response
function handleRequest(request, response){
    request.render('about.html');
    response.end('It Works!! Path Hit: ' + request.url);
}

//Create a server
var server = http.createServer(handleRequest);

//Lets start our server
server.listen(PORT, function(){
    //Callback triggered when server is successfully listening. Hurray!
    console.log("Server listening on: http://localhost:%s", PORT);
});<commit_msg>Change server.js bootup method<commit_after>var http = require('http');

var express = require("express");
var app = express();

// //Lets define a port we want to listen to
// const PORT=8080;

// //We need a function which handles requests and send response
// function handleRequest(request, response){
//     request.render('about.html');
//     response.end('It Works!! Path Hit: ' + request.url);
// }

// //Create a server
// var server = http.createServer(handleRequest);

// //Lets start our server
// server.listen(PORT, function(){
//     //Callback triggered when server is successfully listening. Hurray!
//     console.log("Server listening on: http://localhost:%s", PORT);
// });

   app.use(express.static(__dirname + '/public'));

app.get('/', function(req, res) {
    res.render(index);
});
console.log('Booting..');
console.log('Here we go..');
console.log('Server is Started');

app.listen(8080, '127.0.0.1')<|endoftext|>


<commit_before>// Karma configuration
// Generated on Thu Aug 06 2015 09:43:45 GMT+0200 (W. Europe Daylight Time)
var fs = require("fs")

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    // frameworks: ['mocha', 'requirejs', 'chai'],
    // frameworks: [],
    // 'requirejs' ... !!!! THIS BREAKS Lively Modules
    frameworks: ['mocha','chai'],

    // frameworks: [],

    // list of files / patterns to load in the browser
    files: [
      'src/external/system.src.js',
      'src/external/babel-browser.js',
      'vendor/regenerator-runtime.js',

      // #Jens, cannot load lively.modules here, because we configure System.js later
      // ALT: 'src/external/lively.modules-with-lively.vm.js',
      // 'node_modules/systemjs/dist/system.src.js',
      // 'node_modules/lively.modules/dist/lively.modules-with-lively.vm.js',

      // {pattern: 'node_modules/**/*.js', included: false},
      // {pattern: 'node_modules/**/*.json', included: false},
      {pattern: 'node_modules/chai/chai.js', included: false},
      {pattern: 'node_modules/mocha/mocha.js', included: false},
      {pattern: 'src/**/*.js*', included: false},
      {pattern: 'src/**/*.css*', included: false},
      {pattern: 'swx-*.js', included: false},

      {pattern: 'test/**/*.js', included: false},

      {pattern: 'vendor/**/*.js', included: false},
      {pattern: 'templates/**/*', included: false},
      {pattern: 'test-main.js', included: false},
      {pattern: 'package.json', included: false},

      {pattern: 'src/external/focalStorage.js', included: false},
      'test-loader.js'
    ],

    proxies: {
      '/node_modules/': '/base/node_modules/',
      '/node_modules/chai/chai.js': '/base/node_modules/chai/chai.js',
      '/node_modules/mocha/mocha.js': '/base/node_modules/mocha/mocha.js',
      '/src/': '/base/src/',
      '/test/': '/base/test/',
      '/templates/': '/base/templates/',
      '/vendor/': '/base/vendor/',
      '/package.json': '/base/package.json',
      '/swx-loader.js': '/base/swx-loader.js',
    },

    // list of files to exclude
    // TODO: call github api from travis ci
    exclude: ['src/external/**/*-test.js'].concat(process.env.TRAVIS ? ['test/github-api-test.js'] : []),

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress', 'mocha'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome'],

    customLaunchers: {
      Chrome_Travis_CI: {
        base: 'Chrome',
        flags: ['--no-sandbox']
      },
      ChromeCanary_Travis_CI: {
        base: 'ChromeCanary',
        flags: ['--no-sandbox']
      },
    },

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    browserNoActivityTimeout: 60000
  });

  // Not needed at the moment
  // if (!process.env.GithubToken) {
  //   console.log("\033[7m\033[31m****************************************************************************\033[0m");
  //   console.log("\033[7m\033[31m* You need to provide the \"GithubToken\" environment variable to run tests. *\033[0m");
  //   console.log("\033[7m\033[31m****************************************************************************\033[0m");
  //   process.exit(-1);
  // }

  // insert the github token
  fs.writeSync(
    fs.openSync("test-main.js", "w"),
    "// AUTOGENERATED, please do not edit!!! \n" +fs.readFileSync("test-main.template.js", "utf8").replace("INSERTGITHUBTOKEN", process.env.GithubToken)
  );

  config.browsers = ['Chrome_Travis_CI'];
};
<commit_msg>fix karma this time<commit_after>// Karma configuration
// Generated on Thu Aug 06 2015 09:43:45 GMT+0200 (W. Europe Daylight Time)
var fs = require("fs")

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    // frameworks: ['mocha', 'requirejs', 'chai'],
    // frameworks: [],
    // 'requirejs' ... !!!! THIS BREAKS Lively Modules
    frameworks: ['mocha','chai'],

    // frameworks: [],

    // list of files / patterns to load in the browser
    files: [
      'src/external/system.src.js',
      'src/external/babel-browser.js',
      'vendor/regenerator-runtime.js',

      // #Jens, cannot load lively.modules here, because we configure System.js later
      // ALT: 'src/external/lively.modules-with-lively.vm.js',
      // 'node_modules/systemjs/dist/system.src.js',
      // 'node_modules/lively.modules/dist/lively.modules-with-lively.vm.js',

      // {pattern: 'node_modules/**/*.js', included: false},
      // {pattern: 'node_modules/**/*.json', included: false},
      {pattern: 'node_modules/chai/chai.js', included: false},
      {pattern: 'node_modules/mocha/mocha.js', included: false},
      {pattern: 'src/**/*.js*', included: false},
      {pattern: 'src/**/*.css*', included: false},
      {pattern: 'swx-*.js', included: false},

      {pattern: 'test/**/*.js', included: false},

      {pattern: 'vendor/**/*.js', included: false},
      {pattern: 'templates/**/*', included: false},
      {pattern: 'test-main.js', included: false},
      {pattern: 'package.json', included: false},

      {pattern: 'src/external/focalStorage.js', included: false},
      'test-loader.js'
    ],

    proxies: {
      '/node_modules/': '/base/node_modules/',
      '/node_modules/chai/chai.js': '/base/node_modules/chai/chai.js',
      '/node_modules/mocha/mocha.js': '/base/node_modules/mocha/mocha.js',
      '/src/': '/base/src/',
      '/test/': '/base/test/',
      '/templates/': '/base/templates/',
      '/vendor/': '/base/vendor/',
      '/package.json': '/base/package.json',
      '/swx-boot.js': '/base/swx-boot.js',
      '/swx-kernel.js': '/base/swx-kernel.js',
      '/swx-loader.js': '/base/swx-loader.js',
      '/swx-post.js': '/base/swx-post.js',
      '/swx-pre.js': '/base/swx-pre.js',
    },

    // list of files to exclude
    // TODO: call github api from travis ci
    exclude: ['src/external/**/*-test.js'].concat(process.env.TRAVIS ? ['test/github-api-test.js'] : []),

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress', 'mocha'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome'],

    customLaunchers: {
      Chrome_Travis_CI: {
        base: 'Chrome',
        flags: ['--no-sandbox']
      },
      ChromeCanary_Travis_CI: {
        base: 'ChromeCanary',
        flags: ['--no-sandbox']
      },
    },

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    browserNoActivityTimeout: 60000
  });

  // Not needed at the moment
  // if (!process.env.GithubToken) {
  //   console.log("\033[7m\033[31m****************************************************************************\033[0m");
  //   console.log("\033[7m\033[31m* You need to provide the \"GithubToken\" environment variable to run tests. *\033[0m");
  //   console.log("\033[7m\033[31m****************************************************************************\033[0m");
  //   process.exit(-1);
  // }

  // insert the github token
  fs.writeSync(
    fs.openSync("test-main.js", "w"),
    "// AUTOGENERATED, please do not edit!!! \n" +fs.readFileSync("test-main.template.js", "utf8").replace("INSERTGITHUBTOKEN", process.env.GithubToken)
  );

  config.browsers = ['Chrome_Travis_CI'];
};
<|endoftext|>


<commit_before>/*
 * Slinky
 * A light-weight, responsive, mobile-like navigation menu plugin for jQuery
 * Built by Ali Zahid <ali.zahid@live.com>
 * Published under the MIT license
 */

;(function($) {
	var lastClick;

	$.fn.slinky = function(options) {
		// Setup plugin defaults

		var settings = $.extend({
			label: 'Back',
			title: false,
			speed: 300,
			resize: true
		}, options);

		// Convenience method for navigation animation

		var move = function(menu, next, callback) {
			var left = Math.round(parseInt(menu.get(0).style.left)) || 0;

			// Use multiples of 100% for responsive animation

			menu.css('left', -Math.abs(next ? left - 100 : left + 100) + '%');

			// Callback after animation is finished

			if (typeof callback === 'function') {
				setTimeout(callback, settings.speed);
			}
		};

		// Convenience method for resizing menu

		var resize = function(menu, content) {
			menu.height(content.outerHeight());
		};

		return this.each(function() {
			// The root node is where animation happens

			var menu = $(this),
				root = menu.children().first();

			// Set CSS animation duration

			menu.css('transition-duration', settings.speed + 'ms');
			root.css('transition-duration', settings.speed + 'ms');

			// Add .next class to links with sub menus

			$('a + ul', menu).prev().addClass('next');

			// Add header for back button and title

			$('li > ul', menu).prepend('
');

			// Add title

			if (settings.title === true) {
				// Create a label with title from the parent

				$('li > ul', menu).each(function() {
					var label = $(this).parent().find('a').first().text(),
						title = $('
').text(label);

					$('> .header', this).append(title);
				});
			}

			// Add back links with appropriate labels

			if (!settings.title && settings.label === true) {
				// Create a link with label from parent

				$('li > ul', menu).each(function() {
					var label = $(this).parent().find('a').first().text(),
						backLink = $('').text(label).prop('href', '#').addClass('back');

					$('> .header', this).append(backLink);
				});
			} else {
				// Create a link with the label from settings

				var backLink = $('').text(settings.label).prop('href', '#').addClass('back');

				$('.header', menu).append(backLink);
			}

			// Setup navigation

			$('a', menu).on('click', function(e) {
				if ((lastClick + settings.speed) > Date.now()) {
					return;
				}

				lastClick = Date.now();

				var a = $(this);

				// Disable navigation if link has hash
				// else proceed to URL

				if (/#/.test(this.href)) {
					e.preventDefault();
				}

				// Animate forward or backward
				// Resize menu height to match content, if required

				if (a.hasClass('next')) {
					a.next().show();

					move(root, true);

					if (settings.resize) {
						resize(menu, a.next());
					}
				} else if (a.hasClass('back')) {
					move(root, false, function() {
						a.parent().parent().hide();
					});

					if (settings.resize) {
						resize(menu, a.parent().parent().parents('ul'));
					}
				}
			});
		});

		return this;
	};
}(jQuery));
<commit_msg>Too hardcore for comments<commit_after>/*
 * Slinky
 * A light-weight, responsive, mobile-like navigation menu plugin for jQuery
 * Built by Ali Zahid <ali.zahid@live.com>
 * Published under the MIT license
 */

;(function($) {
	var lastClick;

	$.fn.slinky = function(options) {
		var settings = $.extend({
			label: 'Back',
			title: false,
			speed: 300,
			resize: true
		}, options);

		var move = function(menu, next, callback) {
			var left = Math.round(parseInt(menu.get(0).style.left)) || 0;

			menu.css('left', -Math.abs(next ? left - 100 : left + 100) + '%');

			if (typeof callback === 'function') {
				setTimeout(callback, settings.speed);
			}
		};

		var resize = function(menu, content) {
			menu.height(content.outerHeight());
		};

		return this.each(function() {
			var menu = $(this),
				root = menu.children().first();

			menu.css('transition-duration', settings.speed + 'ms');
			root.css('transition-duration', settings.speed + 'ms');

			$('a + ul', menu).prev().addClass('next');

			$('li > ul', menu).prepend('
');

			if (settings.title === true) {
				$('li > ul', menu).each(function() {
					var label = $(this).parent().find('a').first().text(),
						title = $('
').text(label);

					$('> .header', this).append(title);
				});
			}

			if (!settings.title && settings.label === true) {
				$('li > ul', menu).each(function() {
					var label = $(this).parent().find('a').first().text(),
						backLink = $('').text(label).prop('href', '#').addClass('back');

					$('> .header', this).append(backLink);
				});
			} else {
				var backLink = $('').text(settings.label).prop('href', '#').addClass('back');

				$('.header', menu).append(backLink);
			}

			$('a', menu).on('click', function(e) {
				if ((lastClick + settings.speed) > Date.now()) {
					return;
				}

				lastClick = Date.now();

				var a = $(this);

				if (/#/.test(this.href)) {
					e.preventDefault();
				}

				if (a.hasClass('next')) {
					a.next().show();

					move(root, true);

					if (settings.resize) {
						resize(menu, a.next());
					}
				} else if (a.hasClass('back')) {
					move(root, false, function() {
						a.parent().parent().hide();
					});

					if (settings.resize) {
						resize(menu, a.parent().parent().parents('ul'));
					}
				}
			});
		});

		return this;
	};
}(jQuery));
<|endoftext|>


<commit_before>const webpackConfig = require("./webpack.config");
const path = require('path');

delete webpackConfig.entry;

module.exports = function (config) {
    if (process.env.TRAVIS && !process.env.TRAVIS_PULL_REQUEST) {
        if (!process.env.BROWSER_STACK_USERNAME || !process.env.BROWSER_STACK_ACCESS_KEY) {
            console.log('Make sure the BROWSER_STACK_* environment variables are set.');
            process.exit(1);
        }
    }

    const customLaunchers = {
        sl_chrome_42: {
            base: 'BrowserStack',
            browser: 'chrome',
            os: 'Windows',
            os_version: '10',
            browser_version: '42'
        },
        sl_chrome_latest: {
            base: 'BrowserStack',
            browser: 'chrome',
            platform: 'Windows 7',
            os: 'Windows',
            os_version: '10'
        },
        sl_firefox_39: {
            base: 'BrowserStack',
            browser: 'firefox',
            browser_version: '39.0',
            os: 'Windows',
            os_version: '8.1'
        },
        sl_firefox_latest: {
            base: 'BrowserStack',
            browser: 'firefox',
            os: 'Windows',
            os_version: '8.1'
        },
        sl_safari_9: {
            base: 'BrowserStack',
            browser: 'safari',
            browser_version: '9.1',
            os: 'OS X',
            os_version: 'El Capitan'
        },
        sl_safari_8: {
            base: 'BrowserStack',
            browser: 'safari',
            os: 'OS X',
            os_version: 'Yosemite',
            browser_version: '8.0'
        },
        sl_safari_10: {
            base: 'BrowserStack',
            browser: 'safari',
            os: 'OS X',
            os_version: 'Sierra',
            browser_version: '10.1'
        },
        sl_safari_latest: {
            base: 'BrowserStack',
            browser: 'safari',
            os: 'OS X',
            os_version: 'High Sierra'
        },
        sl_ie_11: {
            base: 'BrowserStack',
            browser: 'IE',
            os: 'Windows',
            os_version: '8.1',
            browser_version: '11.0'
        },
        sl_edge_14: {
            base: 'BrowserStack',
            browser: 'Edge',
            os: 'Windows',
            os_version: '10',
            browser_version: '14.0'
        },
        sl_edge_15: {
            base: 'BrowserStack',
            browser: 'Edge',
            os: 'Windows',
            os_version: '10',
            browser_version: '15.0'
        },
        sl_edge_latest: {
            base: 'BrowserStack',
            browser: 'Edge',
            os: 'Windows',
            os_version: '10'
        }
    };

    config.set({

        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: '',

        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ['jasmine'],

        // list of files / patterns to load in the browser
        files: [
            'tests/**/*-spec.ts'
        ],

        // list of files to exclude
        exclude: [],

        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {
            "tests/**/*.ts": ["webpack", "sourcemap"],
            "src/**/*.ts": ["webpack", "sourcemap" ]
        },

        mime: { 'text/x-typescript': ['ts'] },

        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: process.env.TRAVIS
            ? process.env.TRAVIS_PULL_REQUEST
                ? ['dots', 'summary', 'coverage-istanbul']
                : ['dots', 'summary', 'BrowserStack', 'coverage-istanbul']
            : ['progress', 'coverage-istanbul'],

        coverageIstanbulReporter: {
            reports: [ 'html', 'lcovonly', 'text-summary' ],
            dir: path.join(__dirname, 'coverage'),
            combineBrowserReports: true,
            fixWebpackSourcePaths: true,
            'report-config': {
                html: { outdir: 'html' }
            }
        },

        // web server port
        port: 9876,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: false,

        // define browsers
        customLaunchers: customLaunchers,

        browsers: process.env.TRAVIS && !process.env.TRAVIS_PULL_REQUEST
            ? ['sl_chrome_latest', 'sl_safari_latest', 'sl_firefox_latest', 'sl_edge_latest']
            : ['ChromeHeadless'],

        singleRun: true,

        concurrency: process.env.TRAVIS ? 1 : 2,

        webpack: webpackConfig,

        // to avoid DISCONNECTED messages when connecting to BrowserStack
        browserDisconnectTimeout : 10000, // default 2000
        browserDisconnectTolerance : 1, // default 0
        browserNoActivityTimeout : 4*60*1000, //default 10000
        captureTimeout : 4*60*1000, //default 60000

        hostname: 'bs-local.com',
        browserStack: {
            project: 'Alcaeus',
            startTunnel: true
        }
    });
};
<commit_msg>disable browser stack based on env variables<commit_after>const webpackConfig = require("./webpack.config");
const path = require('path');

delete webpackConfig.entry;

const noBrowserStack = !process.env.BROWSER_STACK_USERNAME || !process.env.BROWSER_STACK_ACCESS_KEY

module.exports = function (config) {
    if (process.env.TRAVIS && noBrowserStack) {
        console.warn('BROWSER_STACK_* environment variables are not available.');
    }

    const customLaunchers = {
        sl_chrome_42: {
            base: 'BrowserStack',
            browser: 'chrome',
            os: 'Windows',
            os_version: '10',
            browser_version: '42'
        },
        sl_chrome_latest: {
            base: 'BrowserStack',
            browser: 'chrome',
            platform: 'Windows 7',
            os: 'Windows',
            os_version: '10'
        },
        sl_firefox_39: {
            base: 'BrowserStack',
            browser: 'firefox',
            browser_version: '39.0',
            os: 'Windows',
            os_version: '8.1'
        },
        sl_firefox_latest: {
            base: 'BrowserStack',
            browser: 'firefox',
            os: 'Windows',
            os_version: '8.1'
        },
        sl_safari_9: {
            base: 'BrowserStack',
            browser: 'safari',
            browser_version: '9.1',
            os: 'OS X',
            os_version: 'El Capitan'
        },
        sl_safari_8: {
            base: 'BrowserStack',
            browser: 'safari',
            os: 'OS X',
            os_version: 'Yosemite',
            browser_version: '8.0'
        },
        sl_safari_10: {
            base: 'BrowserStack',
            browser: 'safari',
            os: 'OS X',
            os_version: 'Sierra',
            browser_version: '10.1'
        },
        sl_safari_latest: {
            base: 'BrowserStack',
            browser: 'safari',
            os: 'OS X',
            os_version: 'High Sierra'
        },
        sl_ie_11: {
            base: 'BrowserStack',
            browser: 'IE',
            os: 'Windows',
            os_version: '8.1',
            browser_version: '11.0'
        },
        sl_edge_14: {
            base: 'BrowserStack',
            browser: 'Edge',
            os: 'Windows',
            os_version: '10',
            browser_version: '14.0'
        },
        sl_edge_15: {
            base: 'BrowserStack',
            browser: 'Edge',
            os: 'Windows',
            os_version: '10',
            browser_version: '15.0'
        },
        sl_edge_latest: {
            base: 'BrowserStack',
            browser: 'Edge',
            os: 'Windows',
            os_version: '10'
        }
    };

    config.set({

        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: '',

        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ['jasmine'],

        // list of files / patterns to load in the browser
        files: [
            'tests/**/*-spec.ts'
        ],

        // list of files to exclude
        exclude: [],

        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {
            "tests/**/*.ts": ["webpack", "sourcemap"],
            "src/**/*.ts": ["webpack", "sourcemap" ]
        },

        mime: { 'text/x-typescript': ['ts'] },

        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: process.env.TRAVIS
            ? noBrowserStack
                ? ['dots', 'summary', 'coverage-istanbul']
                : ['dots', 'summary', 'BrowserStack', 'coverage-istanbul']
            : ['progress', 'coverage-istanbul'],

        coverageIstanbulReporter: {
            reports: [ 'html', 'lcovonly', 'text-summary' ],
            dir: path.join(__dirname, 'coverage'),
            combineBrowserReports: true,
            fixWebpackSourcePaths: true,
            'report-config': {
                html: { outdir: 'html' }
            }
        },

        // web server port
        port: 9876,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: false,

        // define browsers
        customLaunchers: customLaunchers,

        browsers: process.env.TRAVIS && !noBrowserStack
            ? ['sl_chrome_latest', 'sl_safari_latest', 'sl_firefox_latest', 'sl_edge_latest']
            : ['ChromeHeadless'],

        singleRun: true,

        concurrency: process.env.TRAVIS ? 1 : 2,

        webpack: webpackConfig,

        // to avoid DISCONNECTED messages when connecting to BrowserStack
        browserDisconnectTimeout : 10000, // default 2000
        browserDisconnectTolerance : 1, // default 0
        browserNoActivityTimeout : 4*60*1000, //default 10000
        captureTimeout : 4*60*1000, //default 60000

        hostname: 'bs-local.com',
        browserStack: {
            project: 'Alcaeus',
            startTunnel: true
        }
    });
};
<|endoftext|>


<commit_before>module.exports = function(sails) {

	/**
	 * Module dependencies.
	 */

	var util = require('../../util'),
		async = require('async'),
		FatalError = require('../../errors/fatal')(sails),
		loadAppModelsAndAdapters = require('./loadUserModules')(sails),
		Waterline = require('waterline'),
		fs = require('fs');

	/**
	 * Expose Hook definition
	 */

	return {

		initialize: function(cb) {
			var self = this;

			////////////////////////////////////////////////////////////////////////////
			// NOTE: If a user hook needs to add or modify model definitions,
			// the hook should wait until `hook:orm:loaded`, then reload the original
			// model modules `orm/loadUserModules`. Finally, the ORM should be flushed using
			// `restart()` below.
			////////////////////////////////////////////////////////////////////////////

			// Load model and adapter definitions defined in the project
			async.auto({

				_loadModules: loadAppModelsAndAdapters,

				// Normalize model definitions and merge in defaults from `sails.config.model`
				modelDefs: ['_loadModules', function normalizeModelDefs (cb) {
					util.each(sails.models, self.normalizeModelDef);
					cb(null, sails.models);
				}],

				// Once all user model definitions are loaded into sails.models,
				// go ahead and start the ORM, instantiate the models
				instantiatedCollections: ['modelDefs', this.startORM],

				_exposeModels: ['instantiatedCollections', this.exposeModels]

			}, cb);
		},

		/**
		 * Merge defaults and normalize options in this model definition
		 */
		normalizeModelDef: function (modelDef, modelID) {

			// TODO	: (after plane when there's internet)
			//		: Is there a recursive version of _.defaults()?
			//		: Otherwise, we have to do:
			//		: `modelDef = util.merge({}, sails.config.model, modelDef);`

			// Implicit framework defaults
			var implicitDefaults = {
				identity: modelID,
				tableName: modelID
			};

			// App defaults from `sails.config.model`
			var appDefaults = sails.config.model;

			// Rebuild model definition using the defaults
			modelDef = util.merge(implicitDefaults, appDefaults, modelDef);

			// Backwards compatibilty for `Model.adapter`
			if (modelDef.adapter) {
				// sails.log.warn(
				// 	'Deprecation warning :: ' +
				// 	'Replacing `' + modelDef.globalId + '.adapter` ' +
				// 	'with `' + modelDef.globalId + '.connections`....');
				modelDef.connections = modelDef.adapter;
				delete modelDef.adapter;
			}

			// Ensure that Model.connections is an array
			if ( ! util.isArray(modelDef.connections) ) {
				modelDef.connections = [modelDef.connections];
			}

			// Iterate through each of this models' connections
			// -> If `connection` is not an object yet, try to look-up connection by name
			// -> Otherwise `connection` defined inline in model-- just need to normalize it
			// -> If invalid connection found, throw fatal error.
			modelDef.connections = util.map( modelDef.connections, function (connection) {
				if ( util.isString(connection) ) {
					connection = _lookupConnection(connection, modelID);
					connection = _normalizeConnection(connection, modelID);
					return connection;
				}
				if ( util.isObject(connection) ) {
					return _normalizeConnection(connection, modelID);
				}
				return FatalError.__InvalidConnection__ (connection, modelDef.identity);
			});

			// If it isn't set directly, set the model's `schema` property
			// based on the first adapter in its connections (left -> right)
			if ( typeof modelDef.schema === 'undefined') {
				var connection, schema;
				for (var i in modelDef.connections) {
					connection = modelDef.connections[i];
					// console.log('checking connection: ', connection);
					if (typeof connection.schema !== 'undefined') {
						schema = connection.schema;
						break;
					}
				}
				// console.log('trying to determine preference for schema setting..', modelDef.schema, typeof modelDef.schema, typeof modelDef.schema !== 'undefined', schema);
				if (typeof schema !== 'undefined') {
					modelDef.schema = schema;
				}
			}

			// Save modified model definition back to sails.models
			sails.models[modelID] = modelDef;
		},

		/**
		 * Instantiate Waterline Collection for each Sails Model,
		 * then start the ORM.
		 *
		 * @param {Function}	cb
		 *						  -> err	// Error, if one occurred, or null
		 *
		 * @param {Object}		stack
		 *						stack.modelDefs {}
		 *
		 * @global {Object}		sails
		 *						sails.models {}
		 */
		startORM: function(cb, stack) {
			var modelDefs = stack.modelDefs;

			// -> Build adHoc adapters (this will add `adapter` key to models)
			//		(necessary for loading the right adapter config w/i Waterline)
			var adHocAdapters = _buildAdHocAdapterSet(modelDefs);
			sails.adHocAdapters = adHocAdapters;

			// -> Instantiate ORM in memory.
			// -> Iterate through each model definition:
			//		-> Create a proper Waterline Collection for each model
			//		-> then register it w/ the ORM.
			sails.log.verbose('Starting ORM...');
			var instantiatedCollections = {};

			async.each( Object.keys(modelDefs), function instantiateCollection (modelID, next) {
				var modelDef = modelDefs[modelID];

				sails.log.verbose(
					'Registering model `' + modelID + '` in Waterline (ORM) with definition ::','\n',
					modelDef,'\n');

				var Model = Waterline.Collection.extend(modelDef);
				new Model({
					adapters: adHocAdapters,
					tableName: modelDef.tableName
				}, function (err, instantiatedCollection) {
					if (err) return next(err);
					instantiatedCollections[modelID] = instantiatedCollection;
					return next();
				});
			}, function allCollectionsInstantiated (err) {
				if (err) return cb(err);
				// console.log('***** ',instantiatedCollections);
				return cb(null, instantiatedCollections);
			});
		},

		/**
		 * exposeModels
		 *
		 * @param {Function}	cb
		 *						  -> err	// Error, if one occurred, or null
		 *
		 * @param {Object}		stack
		 *						stack.instantiatedCollections {}
		 */
		exposeModels: function (cb, stack) {
			var collections = stack.instantiatedCollections;

			Object.keys(collections).forEach(function eachInstantiatedCollection (modelID) {

				// Set `sails.models.*` reference to instantiated Collection
				// Exposed as `sails.models[modelID]`
				sails.models[modelID] = collections[modelID];

				// Create global variable for this model
				// (if enabled in `sails.config.globals`)
				// Exposed as `[globalId]`
				if (sails.config.globals.models) {
					var globalName = sails.models[modelID].globalId || sails.models[modelID].identity;
					global[globalName] = collections[modelID];
				}
			});

			cb();
		}
	};

	/**
	 * Lookup a connection (e.g., `{ adapter: 'sails-disk' }`)
	 * by name (e.g., 'devDB')
	 *
	 * @param {String}	connectionName
	 *
	 * @param {String}	modelID
	 *					// Optional, improves quality of error messages
	 *
	 * @global	sails
	 *			sails.config
	 *			sails.config.connections {}
	 *
	 * @throws {FatalError}	__UnknownConnection__
	 * @api private
	 */
	function _lookupConnection (connectionName, modelID) {
		var connection = sails.config.connections[connectionName];

		if (connection) return connection;

		// If this is not a known connection, we should throw a fatal error.
		// Try loading it as an adapter though, just in case
		// (also backwards compat w/ <= v0.9.4)
		// sails.log.warn('Deprecated: No such connection "' + connectionName + '" exists...');
		// sails.log.warn('Trying to load it as an adapter instead-- using module ' +
		// 	'`sails-' + connectionName + '` with its default settings...'
		// );
		_ensureAdapter( connectionName );
		return { adapter: 'sails-' + connectionName };

		// TODO: consider removing the above tolerance in 0.10.x
		// return FatalError.__UnknownConnection__ (connectionName, modelID);
	}

	/**
	 * Normalize properties of a connection
	 * (handles deprecation warnings / validation errors and making types consistent)
	 *
	 * @param {Object}	connection
	 *					connection.adapter	// Name of adapter module used by this connection
	 *					connection.module	// Deprecated- equivalent to `connection.adapter`
	 *
	 * @param {String}	modelID
	 *					// Optional, improves quality of error messages
	 *					// Identity of the model this connection came from
	 *
	 * @throws {FatalError}		__UnknownConnection__
	 * @throws {FatalError}		__InvalidConnection__
	 * @throws {FatalError}		__InvalidAdapter__
	 * @api private
	 */
	function _normalizeConnection (connection, modelID) {
		// Connection is not formatted properly, throw a fatal error.
		if ( !util.isObject(connection) ) {
			return FatalError.__InvalidConnection__ (connection, modelID);
		}

		// Backwards compatibilty for `connection.module`
		if ( connection.module ) {
			// sails.log.warn(
			// 	'Deprecation warning :: In model `' + modelID + '`\'s `connections` config, ' +
			// 	'replacing `module` with `adapter`....');
			connection.adapter = connection.module;
			delete connection.module;
		}

		// Adapter is required for a connection
		if ( !connection.adapter ) {
			// Invalid connection found, throw fatal error.
			return FatalError.__InvalidConnection__ (connection, modelID);
		}

		// Verify that referenced adapter has been loaded
		// If it doesn't, try and load it as a dependency from `node_modules`
		_ensureAdapter(connection.adapter);

		// Defaults connection object to its adapter's defaults
		var desAdapters = sails.adapters[connection.adapter];
		connection = util.merge({}, desAdapters.defaults, connection);

		// Success- connection normalized and validated
		// (any missing adapters were either acquired, or the loading process was stopped w/ a fatal error)
		return connection;
	}

	/**
	 * Make sure the specified adapter is loaded
	 * If not, try to require() it.
	 */
	function _ensureAdapter ( moduleName ) {

		// Verify that referenced adapter has been loaded
		// If it doesn't, try and load it as a dependency from `node_modules`
		if (!sails.adapters[moduleName]) {

			// (Format adapter name to make sure we make the best attempt we can)
			if ( ! moduleName.match(/^(sails-|waterline-)/) ) {
				moduleName = 'sails-' + moduleName;
			}

			// Since it is unknown so far, try and load the adapter from `node_modules`
			// sails.log.warn('Loading adapter (', moduleName, ') for ' + modelID, ' from `node_modules` directory...');
			var modulePath = sails.config.appPath + '/node_modules/' + moduleName;
			if ( !fs.existsSync (modulePath) ) {
				// If adapter doesn't exist, log an error and exit
				return FatalError.__UnknownAdapter__ (moduleName, modelID);
			}

			// Since the module seems to exist, try to require it (execute the code)
			try {
				sails.adapters[moduleName] = require(modulePath);
			}
			catch (err) {
				return FatalError.__InvalidAdapter__ (moduleName, err);
			}
		}
	}

	/**
	 * buildAdHocAdapterSet
	 *
	 * The `ad hoc adapter set` consists of the working adapters Waterline uses internally
	 * to talk to various resources.  In this function, ad hoc adapters are built from the connection configuration
	 * in the provided models.  For each unique connection, a new ad-hoc adapter is built, and `registerCollection()`
	 * will be run.
	 *
	 * Note	: `Model.connections` must already be cross-referenced against `sails.config.connections` at this point,
	 *		: since we assume that in every case, `Model.connections` is an array of objects with an `adapter` property.
	 *
	 * @sideEffect modifies `modelDefinitions` (adds `adapter` key)
	 *
	 * @param {Object} modelDefinitions
	 *
	 * TODO :	Perhaps instead of creating clones (ad-hoc adapters), extend Waterline to figure out connection objects
	 *			internally, so then they can just be passed in.
	 *			e.g., `modelDef.adapter = util.cloneDeep(modelDef.connections);`
	 */
	function _buildAdHocAdapterSet (modelDefinitions) {

		// Build set of customized/cloned adapters
		var adHocAdapters = {};
		var i = 0;

		util.each(modelDefinitions, function eachModelDef (modelDef) {

			// Keep track of generated unique connection IDs
			var connectionIDs = [];

			util.each(modelDef.connections, function eachConnection (connection) {

				// Track unique, process-wide identifiers for each connection
				var connectionID = 'adhoc_adapter_' + i;
				connectionIDs.push(connectionID);
				i++;

				// Create and save new ad-hoc adapter
				adHocAdapters[connectionID] = _cloneAdapter({
					adapterID: connection.adapter,
					adapterDefs: sails.adapters,
					connection: connection
				});
			});

			// Populate the `adapter` property in the model definition
			// with an array of the uniquely generated connection ID strings for this model.
			// TODO: in Waterline core, use `connectionNames` instead (or something like that)
			sails.log.verbose('Setting Model.adapter with ad-hoc clone ids => ', connectionIDs);
			modelDef.adapter = connectionIDs;

			// Old way (replaced w/ generated connection names- since uniquness guarantee was hard to achieve)
			// ::::::::::::::::::::::::::::::::::::
			// Then pluck out the adapter ids from the model's connections
			// and plug them as a list of strings into `Model.adapter`
			// modelDef.adapter = util.pluck(modelDef.connections, 'adapter');
		});

		return adHocAdapters;
	}

	/**
	 * _cloneAdapter
	 *
	 * Given the definitions of all relevant adapters,
	 * @returns a configured, ad-hoc adapter clone
	 *
	 * @param {Object} opts
	 * @api private
	 */
	function _cloneAdapter (opts) {
		with (opts) {
			var clonedAdapter = util.cloneDeep(adapterDefs[adapterID]);
			var clonedConnection = util.cloneDeep(connection);
			clonedAdapter.config = util.merge(clonedAdapter.defaults || {}, clonedConnection);
			sails.log.verbose(
				'Cloned new ad-hoc adapter','\n',
				'\t:: source adapter ::',adapterID, '\n',
				'\t:: source connection ::',connection, '\n',
				'\t:: config ::',clonedAdapter.config,'\n'
			);
			return clonedAdapter;
		}
	}

};<commit_msg>Allow both sails-* or * (backwards compat).<commit_after>module.exports = function(sails) {

	/**
	 * Module dependencies.
	 */

	var util = require('../../util'),
		async = require('async'),
		FatalError = require('../../errors/fatal')(sails),
		loadAppModelsAndAdapters = require('./loadUserModules')(sails),
		Waterline = require('waterline'),
		fs = require('fs');

	/**
	 * Expose Hook definition
	 */

	return {

		initialize: function(cb) {
			var self = this;

			////////////////////////////////////////////////////////////////////////////
			// NOTE: If a user hook needs to add or modify model definitions,
			// the hook should wait until `hook:orm:loaded`, then reload the original
			// model modules `orm/loadUserModules`. Finally, the ORM should be flushed using
			// `restart()` below.
			////////////////////////////////////////////////////////////////////////////

			// Load model and adapter definitions defined in the project
			async.auto({

				_loadModules: loadAppModelsAndAdapters,

				// Normalize model definitions and merge in defaults from `sails.config.model`
				modelDefs: ['_loadModules', function normalizeModelDefs (cb) {
					util.each(sails.models, self.normalizeModelDef);
					cb(null, sails.models);
				}],

				// Once all user model definitions are loaded into sails.models,
				// go ahead and start the ORM, instantiate the models
				instantiatedCollections: ['modelDefs', this.startORM],

				_exposeModels: ['instantiatedCollections', this.exposeModels]

			}, cb);
		},

		/**
		 * Merge defaults and normalize options in this model definition
		 */
		normalizeModelDef: function (modelDef, modelID) {

			// TODO	: (after plane when there's internet)
			//		: Is there a recursive version of _.defaults()?
			//		: Otherwise, we have to do:
			//		: `modelDef = util.merge({}, sails.config.model, modelDef);`

			// Implicit framework defaults
			var implicitDefaults = {
				identity: modelID,
				tableName: modelID
			};

			// App defaults from `sails.config.model`
			var appDefaults = sails.config.model;

			// Rebuild model definition using the defaults
			modelDef = util.merge(implicitDefaults, appDefaults, modelDef);

			// Backwards compatibilty for `Model.adapter`
			if (modelDef.adapter) {
				// sails.log.warn(
				// 	'Deprecation warning :: ' +
				// 	'Replacing `' + modelDef.globalId + '.adapter` ' +
				// 	'with `' + modelDef.globalId + '.connections`....');
				modelDef.connections = modelDef.adapter;
				delete modelDef.adapter;
			}

			// Ensure that Model.connections is an array
			if ( ! util.isArray(modelDef.connections) ) {
				modelDef.connections = [modelDef.connections];
			}

			// Iterate through each of this models' connections
			// -> If `connection` is not an object yet, try to look-up connection by name
			// -> Otherwise `connection` defined inline in model-- just need to normalize it
			// -> If invalid connection found, throw fatal error.
			modelDef.connections = util.map( modelDef.connections, function (connection) {
				if ( util.isString(connection) ) {
					connection = _lookupConnection(connection, modelID);
					connection = _normalizeConnection(connection, modelID);
					return connection;
				}
				if ( util.isObject(connection) ) {
					return _normalizeConnection(connection, modelID);
				}
				return FatalError.__InvalidConnection__ (connection, modelDef.identity);
			});

			// If it isn't set directly, set the model's `schema` property
			// based on the first adapter in its connections (left -> right)
			if ( typeof modelDef.schema === 'undefined') {
				var connection, schema;
				for (var i in modelDef.connections) {
					connection = modelDef.connections[i];
					// console.log('checking connection: ', connection);
					if (typeof connection.schema !== 'undefined') {
						schema = connection.schema;
						break;
					}
				}
				// console.log('trying to determine preference for schema setting..', modelDef.schema, typeof modelDef.schema, typeof modelDef.schema !== 'undefined', schema);
				if (typeof schema !== 'undefined') {
					modelDef.schema = schema;
				}
			}

			// Save modified model definition back to sails.models
			sails.models[modelID] = modelDef;
		},

		/**
		 * Instantiate Waterline Collection for each Sails Model,
		 * then start the ORM.
		 *
		 * @param {Function}	cb
		 *						  -> err	// Error, if one occurred, or null
		 *
		 * @param {Object}		stack
		 *						stack.modelDefs {}
		 *
		 * @global {Object}		sails
		 *						sails.models {}
		 */
		startORM: function(cb, stack) {
			var modelDefs = stack.modelDefs;

			// -> Build adHoc adapters (this will add `adapter` key to models)
			//		(necessary for loading the right adapter config w/i Waterline)
			var adHocAdapters = _buildAdHocAdapterSet(modelDefs);
			sails.adHocAdapters = adHocAdapters;

			// -> Instantiate ORM in memory.
			// -> Iterate through each model definition:
			//		-> Create a proper Waterline Collection for each model
			//		-> then register it w/ the ORM.
			sails.log.verbose('Starting ORM...');
			var instantiatedCollections = {};

			async.each( Object.keys(modelDefs), function instantiateCollection (modelID, next) {
				var modelDef = modelDefs[modelID];

				sails.log.verbose(
					'Registering model `' + modelID + '` in Waterline (ORM) with definition ::','\n',
					modelDef,'\n');

				var Model = Waterline.Collection.extend(modelDef);
				new Model({
					adapters: adHocAdapters,
					tableName: modelDef.tableName
				}, function (err, instantiatedCollection) {
					if (err) return next(err);
					instantiatedCollections[modelID] = instantiatedCollection;
					return next();
				});
			}, function allCollectionsInstantiated (err) {
				if (err) return cb(err);
				// console.log('***** ',instantiatedCollections);
				return cb(null, instantiatedCollections);
			});
		},

		/**
		 * exposeModels
		 *
		 * @param {Function}	cb
		 *						  -> err	// Error, if one occurred, or null
		 *
		 * @param {Object}		stack
		 *						stack.instantiatedCollections {}
		 */
		exposeModels: function (cb, stack) {
			var collections = stack.instantiatedCollections;

			Object.keys(collections).forEach(function eachInstantiatedCollection (modelID) {

				// Set `sails.models.*` reference to instantiated Collection
				// Exposed as `sails.models[modelID]`
				sails.models[modelID] = collections[modelID];

				// Create global variable for this model
				// (if enabled in `sails.config.globals`)
				// Exposed as `[globalId]`
				if (sails.config.globals.models) {
					var globalName = sails.models[modelID].globalId || sails.models[modelID].identity;
					global[globalName] = collections[modelID];
				}
			});

			cb();
		}
	};

	/**
	 * Lookup a connection (e.g., `{ adapter: 'sails-disk' }`)
	 * by name (e.g., 'devDB')
	 *
	 * @param {String}	connectionName
	 *
	 * @param {String}	modelID
	 *					// Optional, improves quality of error messages
	 *
	 * @global	sails
	 *			sails.config
	 *			sails.config.connections {}
	 *
	 * @throws {FatalError}	__UnknownConnection__
	 * @api private
	 */
	function _lookupConnection (connectionName, modelID) {
		var connection = sails.config.connections[connectionName];

		if (connection) return connection;

		// If this is not a known connection, we should throw a fatal error.
		// Try loading it as an adapter though, just in case
		// (also backwards compat w/ <= v0.9.4)
		// sails.log.warn('Deprecated: No such connection "' + connectionName + '" exists...');
		// sails.log.warn('Trying to load it as an adapter instead-- using module ' +
		// 	'`sails-' + connectionName + '` with its default settings...'
		// );
		var loadedModuleName = _ensureAdapter( connectionName );
		return { adapter: loadedModuleName };

		// TODO: consider removing the above tolerance in 0.10.x
		// return FatalError.__UnknownConnection__ (connectionName, modelID);
	}

	/**
	 * Normalize properties of a connection
	 * (handles deprecation warnings / validation errors and making types consistent)
	 *
	 * @param {Object}	connection
	 *					connection.adapter	// Name of adapter module used by this connection
	 *					connection.module	// Deprecated- equivalent to `connection.adapter`
	 *
	 * @param {String}	modelID
	 *					// Optional, improves quality of error messages
	 *					// Identity of the model this connection came from
	 *
	 * @throws {FatalError}		__UnknownConnection__
	 * @throws {FatalError}		__InvalidConnection__
	 * @throws {FatalError}		__InvalidAdapter__
	 * @api private
	 */
	function _normalizeConnection (connection, modelID) {
		// Connection is not formatted properly, throw a fatal error.
		if ( !util.isObject(connection) ) {
			return FatalError.__InvalidConnection__ (connection, modelID);
		}

		// Backwards compatibilty for `connection.module`
		if ( connection.module ) {
			// sails.log.warn(
			// 	'Deprecation warning :: In model `' + modelID + '`\'s `connections` config, ' +
			// 	'replacing `module` with `adapter`....');
			connection.adapter = connection.module;
			delete connection.module;
		}

		// Adapter is required for a connection
		if ( !connection.adapter ) {
			// Invalid connection found, throw fatal error.
			return FatalError.__InvalidConnection__ (connection, modelID);
		}

		// Verify that referenced adapter has been loaded
		// If it doesn't, try and load it as a dependency from `node_modules`
		_ensureAdapter(connection.adapter);

		// Defaults connection object to its adapter's defaults
		var desAdapters = sails.adapters[connection.adapter];
		connection = util.merge({}, desAdapters.defaults, connection);

		// Success- connection normalized and validated
		// (any missing adapters were either acquired, or the loading process was stopped w/ a fatal error)
		return connection;
	}

	/**
	 * Make sure the specified adapter is loaded
	 * If not, try to require() it.
	 *
	 * @returns name of the module that Sails was able to load, otherwise, fatal error
	 */
	function _ensureAdapter ( moduleName ) {

		// Verify that referenced adapter has been loaded
		// If it doesn't, try and load it as a dependency from `node_modules`
		if (!sails.adapters[moduleName]) {

			// (Format adapter name to make sure we make the best attempt we can)
			if ( ! moduleName.match(/^(sails-|waterline-)/) ) {
				moduleName = 'sails-' + moduleName;
			}

			// Since it is unknown so far, try and load the adapter from `node_modules`
			// sails.log.warn('Loading adapter (', moduleName, ') for ' + modelID, ' from `node_modules` directory...');
			var modulePath = sails.config.appPath + '/node_modules/' + moduleName;
			if ( !fs.existsSync (modulePath) ) {
				// If adapter doesn't exist, log an error and exit
				return FatalError.__UnknownAdapter__ (moduleName);
			}

			// Since the module seems to exist, try to require it (execute the code)
			try {
				sails.adapters[moduleName] = require(modulePath);
			}
			catch (err) {
				return FatalError.__InvalidAdapter__ (moduleName, err);
			}
		}

		// Return `sails-*` module name
		return moduleName;
	}

	/**
	 * buildAdHocAdapterSet
	 *
	 * The `ad hoc adapter set` consists of the working adapters Waterline uses internally
	 * to talk to various resources.  In this function, ad hoc adapters are built from the connection configuration
	 * in the provided models.  For each unique connection, a new ad-hoc adapter is built, and `registerCollection()`
	 * will be run.
	 *
	 * Note	: `Model.connections` must already be cross-referenced against `sails.config.connections` at this point,
	 *		: since we assume that in every case, `Model.connections` is an array of objects with an `adapter` property.
	 *
	 * @sideEffect modifies `modelDefinitions` (adds `adapter` key)
	 *
	 * @param {Object} modelDefinitions
	 *
	 * TODO :	Perhaps instead of creating clones (ad-hoc adapters), extend Waterline to figure out connection objects
	 *			internally, so then they can just be passed in.
	 *			e.g., `modelDef.adapter = util.cloneDeep(modelDef.connections);`
	 */
	function _buildAdHocAdapterSet (modelDefinitions) {

		// Build set of customized/cloned adapters
		var adHocAdapters = {};
		var i = 0;

		util.each(modelDefinitions, function eachModelDef (modelDef) {

			// Keep track of generated unique connection IDs
			var connectionIDs = [];

			util.each(modelDef.connections, function eachConnection (connection) {

				// Track unique, process-wide identifiers for each connection
				var connectionID = 'adhoc_adapter_' + i;
				connectionIDs.push(connectionID);
				i++;

				// Create and save new ad-hoc adapter
				adHocAdapters[connectionID] = _cloneAdapter({
					adapterID: connection.adapter,
					adapterDefs: sails.adapters,
					connection: connection
				});
			});

			// Populate the `adapter` property in the model definition
			// with an array of the uniquely generated connection ID strings for this model.
			// TODO: in Waterline core, use `connectionNames` instead (or something like that)
			sails.log.verbose('Setting Model.adapter with ad-hoc clone ids => ', connectionIDs);
			modelDef.adapter = connectionIDs;

			// Old way (replaced w/ generated connection names- since uniquness guarantee was hard to achieve)
			// ::::::::::::::::::::::::::::::::::::
			// Then pluck out the adapter ids from the model's connections
			// and plug them as a list of strings into `Model.adapter`
			// modelDef.adapter = util.pluck(modelDef.connections, 'adapter');
		});

		return adHocAdapters;
	}

	/**
	 * _cloneAdapter
	 *
	 * Given the definitions of all relevant adapters,
	 * @returns a configured, ad-hoc adapter clone
	 *
	 * @param {Object} opts
	 * @api private
	 */
	function _cloneAdapter (opts) {
		with (opts) {
			var clonedAdapter = util.cloneDeep(adapterDefs[adapterID]);
			var clonedConnection = util.cloneDeep(connection);
			clonedAdapter.config = util.merge(clonedAdapter.defaults || {}, clonedConnection);
			sails.log.verbose(
				'Cloned new ad-hoc adapter','\n',
				'\t:: source adapter ::',adapterID, '\n',
				'\t:: source connection ::',connection, '\n',
				'\t:: config ::',clonedAdapter.config,'\n'
			);
			return clonedAdapter;
		}
	}

};<|endoftext|>


<commit_before>process.env.TEST = true;
process.env.NODE_ENV = 'test';

const webpack = require("webpack");
const path = require("path");
const webpackConfig = require('./webpack.config.js');

delete webpackConfig.entry;

module.exports = function(config) {

  var configuration = {
    basePath: "",
    frameworks: [
      "mocha",
      "chai",
      "sinon",
      "es6-shim"
    ],
    files: [
      "./test/entry.test.ts",
      "./test/**/**/**.test.ts",
      {
        pattern: '**/*.map',
        served: true,
        included: false,
        watched: true
      }
    ],
    preprocessors: {
      "./**/**/**/**.ts": ["sourcemap"],
      "./test/**/**/**.test.ts": ["webpack"]
    },
    webpack: webpackConfig,
    webpackMiddleware: {
      noInfo: true
    },
    plugins: [
      "karma-webpack",
      "karma-sourcemap-writer",
      "karma-sourcemap-loader",
      "karma-remap-istanbul",
      "karma-mocha-reporter",
      "karma-mocha",
      "karma-chai",
      "karma-sinon",
      "karma-es6-shim",
      "karma-coverage"
    ],
    reporters: (config.singleRun
      ? ["dots", "mocha", "coverage"]
      : ["dots", "mocha"]),
    coverageReporter: {
      dir: "coverage",
      reporters: [
        { type: 'html', subdir: 'report-html' },
        { type: 'lcov', subdir: 'report-lcov' }
      ],
      instrumenterOptions: {
        istanbul: { noCompact: true }
      }
    },
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome']
  };

  if (process.env.TRAVIS) {
    configuration.browsers = ['PhantomJS'];
    configuration.plugins.push("karma-phantomjs-launcher");
  } else {
    configuration.plugins.push("karma-chrome-launcher");
    configuration.browsers = ['Chrome'];
  }

  config.set(configuration);
};
<commit_msg>Change Karma to use PhantomJS<commit_after>process.env.TEST = true;
process.env.NODE_ENV = 'test';

const webpack = require("webpack");
const path = require("path");
const webpackConfig = require('./webpack.config.js');

delete webpackConfig.entry;

module.exports = function(config) {

  var configuration = {
    basePath: "",
    frameworks: [
      "mocha",
      "chai",
      "sinon",
      "es6-shim"
    ],
    files: [
      "./test/entry.test.ts",
      "./test/**/**/**.test.ts",
      {
        pattern: '**/*.map',
        served: true,
        included: false,
        watched: true
      }
    ],
    preprocessors: {
      "./**/**/**/**.ts": ["sourcemap"],
      "./test/**/**/**.test.ts": ["webpack"]
    },
    webpack: webpackConfig,
    webpackMiddleware: {
      noInfo: true
    },
    plugins: [
      "karma-webpack",
      "karma-sourcemap-writer",
      "karma-sourcemap-loader",
      "karma-remap-istanbul",
      "karma-mocha-reporter",
      "karma-mocha",
      "karma-chai",
      "karma-sinon",
      "karma-es6-shim",
      "karma-coverage"
    ],
    reporters: (config.singleRun
      ? ["dots", "mocha", "coverage"]
      : ["dots", "mocha"]),
    coverageReporter: {
      dir: "coverage",
      reporters: [
        { type: 'html', subdir: 'report-html' },
        { type: 'lcov', subdir: 'report-lcov' }
      ],
      instrumenterOptions: {
        istanbul: { noCompact: true }
      }
    },
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome']
  };

  if (process.env.TRAVIS) {
    configuration.browsers = ['PhantomJS'];
    configuration.plugins.push("karma-phantomjs-launcher");
  } else {
    configuration.plugins.push("karma-phantomjs-launcher");
    configuration.browsers = ['PhantomJS'];
  }

  config.set(configuration);
};
<|endoftext|>


<commit_before>define (['jquery', 'aggregate'], function ($, aggregate) {

    var stats = {};

    function build (statsParam) {
        stats = statsParam;
    }

    function getAgeText () {

        var part1 = $('#result-age-1').val();
        var part2 = $('#result-age-2').val();
        var age = 40;

        $('#age_result').text(part1 + age + part2);

    }

    function getEpochText () {

        var part1 = $('#result-epoch-1').val();
        var part2 = $('#result-epoch-2').val();
        var part3 = $('#result-epoch-2').val();

        var year = 1992;
        var artist = "Nirvana";
        var album = "Nevermind";

        $('#epoch_result').text(part1 + year + part2 + artist + part3 + album);

    }

    function getStyleText () {
        $('#style_result').text("Escuchas la misma música que una persona de 40 años.");

    }

    function getSimilarText () {
        $('#similar_result').text("Escuchas la misma música que una persona de 40 años.");

    }

    return {
        build: build,
        getAgeText: getAgeText,
        getEpochText: getEpochText,
        getStyleText: getStyleText,
        getSimilarText: getSimilarText
    };
});<commit_msg>fix epoch text<commit_after>define (['jquery', 'aggregate'], function ($, aggregate) {

    var stats = {};

    function build (statsParam) {
        stats = statsParam;
    }

    function getAgeText () {

        var part1 = $('#result-age-1').val();
        var part2 = $('#result-age-2').val();
        var age = 40;

        $('#age_result').text(part1 + age + part2);

    }

    function getEpochText () {

        var part1 = $('#result-epoch-1').val();
        var part2 = $('#result-epoch-2').val();
        var part3 = $('#result-epoch-3').val();

        var year = 1992;
        var artist = "Nirvana";
        var album = "Nevermind";

        $('#epoch_result').text(part1 + year + part2 + artist + part3 + album);

    }

    function getStyleText () {
        $('#style_result').text("Escuchas la misma música que una persona de 40 años.");

    }

    function getSimilarText () {
        $('#similar_result').text("Escuchas la misma música que una persona de 40 años.");

    }

    return {
        build: build,
        getAgeText: getAgeText,
        getEpochText: getEpochText,
        getStyleText: getStyleText,
        getSimilarText: getSimilarText
    };
});<|endoftext|>