<commit_before>function ItemMenu() {
  return new Menu({
    getState : function() {
      var itemIds = game.getIntArray(game.INVENTORY_ITEM_IDS());
      var itemQtys = game.getIntArray(game.INVENTORY_QTYS());
      var itemUsabilities = [];

      var choiceLines = [];
      var items = project.data().enums().items();
      for (var i = 0; i < itemIds.length && i < itemQtys.length; ++i) {
        var itemId = itemIds[i];
        var itemQty = itemQtys[i];
        if (itemId < 0 || itemQty <= 0) {
          choiceLines.push("");
        } else {
          var item = items[itemId];
          var usable = item.usableInMenu();
          itemUsabilities.push(usable);

          var lineParts = [];
          if (!usable)
            lineParts.push("\\c[1]");
          lineParts.push(rightPad(item.name(), 32));
          lineParts.push(" : " + itemQty.toString());
          if (!usable)
            lineParts.push("\\c[0]");

          choiceLines.push(lineParts.join(""));
        }
      }

      return {
        lines : choiceLines,
        itemIds : itemIds,
        itemQtys : itemQtys,
        itemUsabilities : itemUsabilities
      }
    },
    layout : layout.southwest(sizer.prop(1.0, 0.87)),
    windowDetails : {
      displayedItems : 10,
      allowCancel : true
    }
  });
}

function enterItemsWindow(itemsTopWin, itemsMenu) {
  itemsMenu.window.takeFocus();
  itemsMenu.loopChoice(function(choiceId) {
    if (itemsMenu.state.itemIds.length == 0) {
      return true;
    }

    var itemId = itemsMenu.state.itemIds[choiceId];
    var usable = itemsMenu.state.itemUsabilities[choiceId];
    var itemsLeft = itemsMenu.state.itemQtys[choiceId];

    if (!usable || itemsLeft == 0) {
      return true;
    }

    var statusMenu = new StatusMenu();
    statusMenu.loopCharacterChoice(function onSelect(characterId) {
      if (itemsLeft > 0) {
        game.useItemInMenu(itemId, characterId);
      }

      --itemsLeft;

      // Don't return until after the user has had a chance to see the effect
      // of using the last item.
      return itemsLeft >= -1;
    });
    statusMenu.close();
  });

  itemsTopWin.window.takeFocus();
}

function itemsMenu() {
  var itemsMenu = new ItemMenu();
  var itemsTopWin = new Menu({
    getState : function() {
      return {
        lines : [ "Use", "Organize" ]
      };
    },
    layout : layout.northwest(sizer.prop(1.0, 0.13)),
    windowDetails : {
      justification : game.CENTER(),
      columns : 2,
      allowCancel : true
    }
  });

  itemsTopWin.loopChoice(function(choiceId) {
    if (choiceId == 0)
      enterItemsWindow(itemsTopWin, itemsMenu);
    return true;
  });

  itemsMenu.close();
  itemsTopWin.close();
}

function menu() {
  var statusMenu = new StatusMenu();
  var rootMenuWin = new Menu({
    getState : function() {
      return {
        lines : [ "Item", "Skills", "Equip", "Status", "Save" ],
      };
    },
    layout : layout.northeast(sizer.prop(0.2, 0.8)),
    windowDetails : {
      justification : game.CENTER(),
      allowCancel : true
    }
  });

  rootMenuWin.loopChoice(function(choiceId) {
    switch (choiceId) {
    case 0:
      itemsMenu();
      break;
    case 4:
      var saveMenu = new SaveAndLoadMenu();
      saveMenu.loopChoice(function(choiceId) {
        game.saveToSaveSlot(choiceId);
        return true;
      });
      saveMenu.close();
      break;
    }

    statusMenu.update();
    return true;
  });

  rootMenuWin.close();
  statusMenu.close();
}<commit_msg>reorganize items menu code a bit<commit_after>function ItemMenu() {
  var menu = new Menu({
    getState : function() {
      var itemIds = game.getIntArray(game.INVENTORY_ITEM_IDS());
      var itemQtys = game.getIntArray(game.INVENTORY_QTYS());
      var itemUsabilities = [];

      var choiceLines = [];
      var items = project.data().enums().items();
      for (var i = 0; i < itemIds.length && i < itemQtys.length; ++i) {
        var itemId = itemIds[i];
        var itemQty = itemQtys[i];
        if (itemId < 0 || itemQty <= 0) {
          choiceLines.push("");
        } else {
          var item = items[itemId];
          var usable = item.usableInMenu();
          itemUsabilities.push(usable);

          var lineParts = [];
          if (!usable)
            lineParts.push("\\c[1]");
          lineParts.push(rightPad(item.name(), 32));
          lineParts.push(" : " + itemQty.toString());
          if (!usable)
            lineParts.push("\\c[0]");

          choiceLines.push(lineParts.join(""));
        }
      }

      return {
        lines : choiceLines,
        itemIds : itemIds,
        itemQtys : itemQtys,
        itemUsabilities : itemUsabilities
      }
    },
    layout : layout.southwest(sizer.prop(1.0, 0.87)),
    windowDetails : {
      displayedItems : 10,
      allowCancel : true
    }
  });

  return menu;
}

function itemsMenu() {
  function enterItemsWindow(itemsTopWin, itemsMenu) {
    itemsMenu.window.takeFocus();
    itemsMenu.loopChoice(function(choiceId) {
      if (itemsMenu.state.itemIds.length == 0) {
        return true;
      }

      var itemId = itemsMenu.state.itemIds[choiceId];
      var usable = itemsMenu.state.itemUsabilities[choiceId];
      var itemsLeft = itemsMenu.state.itemQtys[choiceId];

      if (!usable || itemsLeft == 0) {
        return true;
      }

      var statusMenu = new StatusMenu();
      statusMenu.loopCharacterChoice(function onSelect(characterId) {
        if (itemsLeft > 0) {
          game.useItemInMenu(itemId, characterId);
        }

        --itemsLeft;

        // Don't return until after the user has had a chance to see the effect
        // of using the last item.
        return itemsLeft >= -1;
      });
      statusMenu.close();
    });

    itemsTopWin.window.takeFocus();
  }

  var itemsMenu = new ItemMenu();
  var itemsTopWin = new Menu({
    getState : function() {
      return {
        lines : [ "Use", "Organize" ]
      };
    },
    layout : layout.northwest(sizer.prop(1.0, 0.13)),
    windowDetails : {
      justification : game.CENTER(),
      columns : 2,
      allowCancel : true
    }
  });

  itemsTopWin.loopChoice(function(choiceId) {
    if (choiceId == 0)
      enterItemsWindow(itemsTopWin, itemsMenu);
    return true;
  });

  itemsMenu.close();
  itemsTopWin.close();
}

function menu() {
  var statusMenu = new StatusMenu();
  var rootMenuWin = new Menu({
    getState : function() {
      return {
        lines : [ "Item", "Skills", "Equip", "Status", "Save" ],
      };
    },
    layout : layout.northeast(sizer.prop(0.2, 0.8)),
    windowDetails : {
      justification : game.CENTER(),
      allowCancel : true
    }
  });

  rootMenuWin.loopChoice(function(choiceId) {
    switch (choiceId) {
    case 0:
      itemsMenu();
      break;
    case 4:
      var saveMenu = new SaveAndLoadMenu();
      saveMenu.loopChoice(function(choiceId) {
        game.saveToSaveSlot(choiceId);
        return true;
      });
      saveMenu.close();
      break;
    }

    statusMenu.update();
    return true;
  });

  rootMenuWin.close();
  statusMenu.close();
}<|endoftext|>


<commit_before>'use strict';

var _            = require('lodash');
var Promise      = require('./promise');

// The "Runner" constructor takes a "builder" (query, schema, or raw)
// and runs through each of the query statements, calling any additional
// "output" method provided alongside the query and bindings.
function Runner(builder) {
  this.builder = builder;
  this.queries = [];

  // The "connection" object is set on the runner when
  // "run" is called.
  this.connection = void 0;
}

Runner.prototype._beginTransaction = 'begin;';
Runner.prototype._commitTransaction = 'commit;';
Runner.prototype._rollbackTransaction = 'rollback;';

// "Run" the target, calling "toSQL" on the builder, returning
// an object or array of queries to run, each of which are run on
// a single connection.
Runner.prototype.run = Promise.method(function() {
  if (this.builder._transacting) {
    return this.transactionQuery();
  }
  return Promise.bind(this)
    .then(this.ensureConnection)
    .then(function(connection) {
      this.connection = connection;

      // Emit a "start" event on both the builder and the client,
      // allowing us to listen in on any events. We fire on the "client"
      // before building the SQL, and on the builder after building the SQL
      // in case we want to determine at how long it actually
      // took to build the query.
      this.client.emit('start', this.builder);
      var sql = this.builder.toSQL();
      this.builder.emit('start', this.builder);

      if (_.isArray(sql)) {
        return this.queryArray(sql);
      }
      return this.query(sql);
    })

    // If there are any "error" listeners, we fire an error event
    // and then re-throw the error to be eventually handled by
    // the promise chain. Useful if you're wrapping in a custom `Promise`.
    .catch(function(err) {
      if (this.builder._events && this.builder._events.error) {
        this.builder.emit('error', err);
      }
      throw err;
    })

    // Fire a single "end" event on the builder when
    // all queries have successfully completed.
    .tap(function() {
      this.builder.emit('end');
    })
    .finally(this.cleanupConnection);
});

// Stream the result set, by passing through to the dialect's streaming
// capabilities. If the options are
var PassThrough;
Runner.prototype.stream = function(options, handler) {
  // If we specify stream(handler).then(...
  if (arguments.length === 1) {
    if (_.isFunction(options)) {
      handler = options;
      options = {};
    }
  }

  // Determines whether we emit an error or throw here.
  var hasHandler = _.isFunction(handler);

  // Lazy-load the "PassThrough" dependency.
  PassThrough = PassThrough || require('readable-stream').PassThrough;
  var stream  = new PassThrough({objectMode: true});
  var promise = Promise.bind(this)
    .then(this.ensureConnection)
    .then(function(connection) {
      this.connection = connection;
      var sql = this.builder.toSQL();
      var err = new Error('The stream may only be used with a single query statement.');
      if (_.isArray(sql)) {
        if (hasHandler) throw err;
        stream.emit('error', err);
      }
      return sql;
    }).then(function(sql) {
      return this._stream(sql, stream, options);
    }).finally(this.cleanupConnection);

  // If a function is passed to handle the stream, send the stream
  // there and return the promise, otherwise just return the stream
  // and the promise will take care of itsself.
  if (hasHandler) {
    handler(stream);
    return promise;
  }
  return stream;
};

// Allow you to pipe the stream to a writable stream.
Runner.prototype.pipe = function(writable) {
  return this.stream().pipe(writable);
};

// "Runs" a query, returning a promise. All queries specified by the builder are guaranteed
// to run in sequence, and on the same connection, especially helpful when schema building
// and dealing with foreign key constraints, etc.
Runner.prototype.query = Promise.method(function(obj) {
  obj.__cid = this.connection.__cid;
  this.builder.emit('query', obj);
  this.client.emit('query', obj);
  return this._query(obj).bind(this).then(this.processResponse);
});

// In the case of the "schema builder" we call `queryArray`, which runs each
// of the queries in sequence.
Runner.prototype.queryArray = Promise.method(function(queries) {
  return queries.length === 1 ? this.query(queries[0]) : Promise.bind(this)
    .thenReturn(queries)
    .reduce(function(memo, query) {
      return this.query(query).then(function(resp) {
        memo.push(resp);
        return memo;
      });
    }, []);
});

// Check whether there's a transaction flag, and that it has a connection.
Runner.prototype.ensureConnection = Promise.method(function() {
  if (this.builder._connection) {
    return this.builder._connection;
  }
  return this.client.acquireConnection();
});

// "Debug" the query being run.
Runner.prototype.debug = function(obj) {
  console.dir(_.extend({__cid: this.connection.__cid}, obj));
};

// Check whether we're "debugging", based on either calling `debug` on the query.
Runner.prototype.isDebugging = function() {
  return (this.client.isDebugging === true || this.builder._debug === true);
};

// Transaction Methods:
// -------

// Run the transaction on the correct "runner" instance.
Runner.prototype.transactionQuery = Promise.method(function() {
  var runner = this.builder._transacting._runner;
  if (!(runner instanceof Runner)) {
    throw new Error('Invalid transaction object provided.');
  }
  var sql = this.builder.toSQL();
  if (_.isArray(sql)) {
    return runner.queryArray(sql);
  }
  return runner.query(sql);
});

// Begins a transaction statement on the instance,
// resolving with the connection of the current transaction.
Runner.prototype.startTransaction = Promise.method(function() {
  return Promise.bind(this)
    .then(this.ensureConnection)
    .then(function(connection) {
      this.connection  = connection;
      this.transaction = true;
      return (this._beginTransaction && this.query({sql: this._beginTransaction}));
    }).thenReturn(this);
});

// Finishes the transaction statement and handles disposing of the connection,
// resolving / rejecting the transaction's promise, and ensuring the transaction object's
// `_runner` property is `null`'ed out so it cannot continue to be used.
Runner.prototype.finishTransaction = Promise.method(function(action, containerObject, msg) {
  var query, dfd = containerObject.__dfd__;

  // Run the query to commit / rollback the transaction.
  switch (action) {
    case 0:
      query = this.commitTransaction();
      break;
    case 1:
      query = this.rollbackTransaction();
      break;
  }

  return query.then(function(resp) {
    msg = (msg === void 0) ? resp : msg;
    switch (action) {
      case 0:
        dfd.fulfill(msg);
        break;
      case 1:
        dfd.reject(msg);
        break;
    }

  // If there was a problem committing the transaction,
  // reject the transaction block (to reject the entire transaction block),
  // then re-throw the error for any promises chained off the commit.
  }).catch(function(e) {
    dfd.reject(e);
    throw e;
  }).bind(this).finally(function() {

    // Kill the "_runner" object on the containerObject,
    // so it's not possible to continue using the transaction object.
    containerObject._runner = void 0;

    return this.cleanupConnection();
  });
});

Runner.prototype.commitTransaction = function() {
  return this._commitTransaction   && this.query({sql: this._commitTransaction});
};
Runner.prototype.rollbackTransaction = function() {
  return this._rollbackTransaction && this.query({sql: this._rollbackTransaction});
};

// Cleanup the connection as necessary, if the `_connection` was
// explicitly set on the query we don't need to do anything here,
// otherwise we
Runner.prototype.cleanupConnection = Promise.method(function() {
  if (!this.builder._connection && typeof this.connection !== "undefined") {
    return this.client.releaseConnection(this.connection);
  }
});

module.exports = Runner;<commit_msg>Prevent executing a query when no connection exists<commit_after>'use strict';

var _            = require('lodash');
var Promise      = require('./promise');

// The "Runner" constructor takes a "builder" (query, schema, or raw)
// and runs through each of the query statements, calling any additional
// "output" method provided alongside the query and bindings.
function Runner(builder) {
  this.builder = builder;
  this.queries = [];

  // The "connection" object is set on the runner when
  // "run" is called.
  this.connection = void 0;
}

Runner.prototype._beginTransaction = 'begin;';
Runner.prototype._commitTransaction = 'commit;';
Runner.prototype._rollbackTransaction = 'rollback;';

// "Run" the target, calling "toSQL" on the builder, returning
// an object or array of queries to run, each of which are run on
// a single connection.
Runner.prototype.run = Promise.method(function() {
  if (this.builder._transacting) {
    return this.transactionQuery();
  }
  return Promise.bind(this)
    .then(this.ensureConnection)
    .then(function(connection) {
      this.connection = connection;

      // Emit a "start" event on both the builder and the client,
      // allowing us to listen in on any events. We fire on the "client"
      // before building the SQL, and on the builder after building the SQL
      // in case we want to determine at how long it actually
      // took to build the query.
      this.client.emit('start', this.builder);
      var sql = this.builder.toSQL();
      this.builder.emit('start', this.builder);

      if (_.isArray(sql)) {
        return this.queryArray(sql);
      }
      return this.query(sql);
    })

    // If there are any "error" listeners, we fire an error event
    // and then re-throw the error to be eventually handled by
    // the promise chain. Useful if you're wrapping in a custom `Promise`.
    .catch(function(err) {
      if (this.builder._events && this.builder._events.error) {
        this.builder.emit('error', err);
      }
      throw err;
    })

    // Fire a single "end" event on the builder when
    // all queries have successfully completed.
    .tap(function() {
      this.builder.emit('end');
    })
    .finally(this.cleanupConnection);
});

// Stream the result set, by passing through to the dialect's streaming
// capabilities. If the options are
var PassThrough;
Runner.prototype.stream = function(options, handler) {
  // If we specify stream(handler).then(...
  if (arguments.length === 1) {
    if (_.isFunction(options)) {
      handler = options;
      options = {};
    }
  }

  // Determines whether we emit an error or throw here.
  var hasHandler = _.isFunction(handler);

  // Lazy-load the "PassThrough" dependency.
  PassThrough = PassThrough || require('readable-stream').PassThrough;
  var stream  = new PassThrough({objectMode: true});
  var promise = Promise.bind(this)
    .then(this.ensureConnection)
    .then(function(connection) {
      this.connection = connection;
      var sql = this.builder.toSQL();
      var err = new Error('The stream may only be used with a single query statement.');
      if (_.isArray(sql)) {
        if (hasHandler) throw err;
        stream.emit('error', err);
      }
      return sql;
    }).then(function(sql) {
      return this._stream(sql, stream, options);
    }).finally(this.cleanupConnection);

  // If a function is passed to handle the stream, send the stream
  // there and return the promise, otherwise just return the stream
  // and the promise will take care of itsself.
  if (hasHandler) {
    handler(stream);
    return promise;
  }
  return stream;
};

// Allow you to pipe the stream to a writable stream.
Runner.prototype.pipe = function(writable) {
  return this.stream().pipe(writable);
};

// "Runs" a query, returning a promise. All queries specified by the builder are guaranteed
// to run in sequence, and on the same connection, especially helpful when schema building
// and dealing with foreign key constraints, etc.
Runner.prototype.query = Promise.method(function(obj) {
  if (!this.connection) {
    throw new Error('There is an error with the database connection. Please check your config.');
  }
  obj.__cid = this.connection.__cid;
  this.builder.emit('query', obj);
  this.client.emit('query', obj);
  return this._query(obj).bind(this).then(this.processResponse);
});

// In the case of the "schema builder" we call `queryArray`, which runs each
// of the queries in sequence.
Runner.prototype.queryArray = Promise.method(function(queries) {
  return queries.length === 1 ? this.query(queries[0]) : Promise.bind(this)
    .thenReturn(queries)
    .reduce(function(memo, query) {
      return this.query(query).then(function(resp) {
        memo.push(resp);
        return memo;
      });
    }, []);
});

// Check whether there's a transaction flag, and that it has a connection.
Runner.prototype.ensureConnection = Promise.method(function() {
  if (this.builder._connection) {
    return this.builder._connection;
  }
  return this.client.acquireConnection();
});

// "Debug" the query being run.
Runner.prototype.debug = function(obj) {
  console.dir(_.extend({__cid: this.connection.__cid}, obj));
};

// Check whether we're "debugging", based on either calling `debug` on the query.
Runner.prototype.isDebugging = function() {
  return (this.client.isDebugging === true || this.builder._debug === true);
};

// Transaction Methods:
// -------

// Run the transaction on the correct "runner" instance.
Runner.prototype.transactionQuery = Promise.method(function() {
  var runner = this.builder._transacting._runner;
  if (!(runner instanceof Runner)) {
    throw new Error('Invalid transaction object provided.');
  }
  var sql = this.builder.toSQL();
  if (_.isArray(sql)) {
    return runner.queryArray(sql);
  }
  return runner.query(sql);
});

// Begins a transaction statement on the instance,
// resolving with the connection of the current transaction.
Runner.prototype.startTransaction = Promise.method(function() {
  return Promise.bind(this)
    .then(this.ensureConnection)
    .then(function(connection) {
      this.connection  = connection;
      this.transaction = true;
      return (this._beginTransaction && this.query({sql: this._beginTransaction}));
    }).thenReturn(this);
});

// Finishes the transaction statement and handles disposing of the connection,
// resolving / rejecting the transaction's promise, and ensuring the transaction object's
// `_runner` property is `null`'ed out so it cannot continue to be used.
Runner.prototype.finishTransaction = Promise.method(function(action, containerObject, msg) {
  var query, dfd = containerObject.__dfd__;

  // Run the query to commit / rollback the transaction.
  switch (action) {
    case 0:
      query = this.commitTransaction();
      break;
    case 1:
      query = this.rollbackTransaction();
      break;
  }

  return query.then(function(resp) {
    msg = (msg === void 0) ? resp : msg;
    switch (action) {
      case 0:
        dfd.fulfill(msg);
        break;
      case 1:
        dfd.reject(msg);
        break;
    }

  // If there was a problem committing the transaction,
  // reject the transaction block (to reject the entire transaction block),
  // then re-throw the error for any promises chained off the commit.
  }).catch(function(e) {
    dfd.reject(e);
    throw e;
  }).bind(this).finally(function() {

    // Kill the "_runner" object on the containerObject,
    // so it's not possible to continue using the transaction object.
    containerObject._runner = void 0;

    return this.cleanupConnection();
  });
});

Runner.prototype.commitTransaction = function() {
  return this._commitTransaction   && this.query({sql: this._commitTransaction});
};
Runner.prototype.rollbackTransaction = function() {
  return this._rollbackTransaction && this.query({sql: this._rollbackTransaction});
};

// Cleanup the connection as necessary, if the `_connection` was
// explicitly set on the query we don't need to do anything here,
// otherwise we
Runner.prototype.cleanupConnection = Promise.method(function() {
  if (!this.builder._connection && typeof this.connection !== "undefined") {
    return this.client.releaseConnection(this.connection);
  }
});

module.exports = Runner;
<|endoftext|>


<commit_before><commit_msg>fix per semester cgpa calculation<commit_after><|endoftext|>


<commit_before>// These gulp tasks can be ran using the command: gulp.
// The gulp command will create a build folder, which you'll
// point your server to.
// The build folder will not be minified, but will contain
// things like validated HTML, compiled SASS, vendor-prefixed CSS etc...

// Autobuild on file saves with: gulp watch
// Watch tasks are used to update file changes,
// and will be ran automatically.
// use `ctrl+c` to quit the watch task.

// To build the dist folder use the command: gulp dist
// This will run minification processes and render the code
// unreadalbe.

// Include gulp
var gulp = require('gulp');

// Include Plugins
// Include Gulp
var gulp = require('gulp');

// Include plugins
var plugins = require("gulp-load-plugins")({
	pattern: ['gulp-*', 'gulp.*', 'main-bower-files'],
	replaceString: /\bgulp[\-.]/
});

// Minifies JS Files
gulp.task('compress-js', function() {
  gulp.src('src/js/*.js')
    .pipe(plugins.minify({
        ext:{
            src:'.js',
            min:'.min.js'
        }
    }))
    .pipe(gulp.dest('dist'))
});

// Put CSS libs in build
gulp.task('build-vendor-css', function() {
    return gulp.src('src/vendor/**/*.css')
    .pipe(gulp.dest('build/vendor'))
})

// Put CSS libs in dist
gulp.task('dist-vendor-css', function() {
    return gulp.src('build/vendor/**/*.css')
    .pipe(gulp.dest('dist/vendor'))
})

// Put JS libs in build
gulp.task('build-vendor-js', function() {
    return gulp.src('src/vendor/**/*.js')
    .pipe(gulp.dest('build/vendor'))
})

// Put JS libs in dist
gulp.task('dist-vendor-js', function() {
    return gulp.src('build/vendor/**/*.js')
    .pipe(gulp.dest('dist/vendor'))
})

// Minify CSS
gulp.task('minify-css', function() {
   return gulp.src('build/css/*.css')
    //.pipe(strip({ignore: /url\([\w\s:\/=\-\+;,]*\)/g}))
    .pipe(plugins.cleanCss({compatibility: 'ie8'}))
    .pipe(gulp.dest('dist/css'));
});

// Minify HTML
gulp.task('minify-html', function () {
  return gulp.src('build/*.html')
    .pipe(plugins.stripComments())
    .pipe(plugins.htmlmin({collapseWhitespace: true}))
    .pipe(gulp.dest('dist'));
});

// Compress Images
gulp.task('images', function() {
    return gulp.src('src/images/**/*')
        .pipe(plugins.imagemin())
        .pipe(gulp.dest('build/images'));
});

// Add images to dist
gulp.task('dist-images', function() {
    return gulp.src('build/images/**/*')
        .pipe(plugins.imagemin())
        .pipe(gulp.dest('dist/images'));
});

// Validate HTML
gulp.task('html', function() {
  return gulp.src('src/*.html')
  .pipe(plugins.html())
  .pipe(gulp.dest('build/'));
});

// Compile Sass
gulp.task('sass', function() {
    return gulp.src('src/scss/*.scss')
        .pipe(plugins.sass())
        .pipe(plugins.autoprefixer())
        .pipe(gulp.dest('build/css/'));
});

// Watch Files For Changes
gulp.task('watch', function() {
    gulp.watch('scss/*.scss', ['sass', 'html']);
});

// Build Distrobution Folder
gulp.task('dist', [
        'minify-html',
        'minify-css',
        'dist-images',
        'dist-vendor-css',
        'dist-vendor-js'
    ]);

// Default Task
gulp.task('default', [
        'sass',
        'html',
        'images',
        'build-vendor-css',
        'build-vendor-js'
    ]);
<commit_msg>Set up js minify: gulpfile.js<commit_after>// These gulp tasks can be ran using the command: gulp.
// The gulp command will create a build folder, which you'll
// point your server to.
// The build folder will not be minified, but will contain
// things like validated HTML, compiled SASS, vendor-prefixed CSS etc...

// Autobuild on file saves with: gulp watch
// Watch tasks are used to update file changes,
// and will be ran automatically.
// use `ctrl+c` to quit the watch task.

// To build the dist folder use the command: gulp dist
// This will run minification processes and render the code
// unreadalbe.

// Include gulp
var gulp = require('gulp');

// Include Plugins
// Include Gulp
var gulp = require('gulp');

// Include plugins
var plugins = require("gulp-load-plugins")({
	pattern: ['gulp-*', 'gulp.*', 'main-bower-files'],
	replaceString: /\bgulp[\-.]/
});

// Minifies JS Files
gulp.task('compress-js', function() {
  gulp.src('build/js/**/*.js')
    .pipe(plugins.minify({
        ext:{
            src:'.js',
            min:'.min.js'
        }
    }))
    .pipe(gulp.dest('dist/js'))
});

// Put CSS libs in build
gulp.task('build-vendor-css', function() {
    return gulp.src('src/vendor/**/*.css')
    .pipe(gulp.dest('build/vendor'))
})

// Put CSS libs in dist
gulp.task('dist-vendor-css', function() {
    return gulp.src('build/vendor/**/*.css')
    .pipe(gulp.dest('dist/vendor'))
})

// Put JS in build
gulp.task('build-js', function() {
    return gulp.src('src/js/**/*.js')
    .pipe(gulp.dest('build/js'))
})

// Put JS libs in build
gulp.task('build-vendor-js', function() {
    return gulp.src('src/vendor/**/*.js')
    .pipe(gulp.dest('build/vendor'))
})

// Put JS libs in dist
gulp.task('dist-vendor-js', function() {
    return gulp.src('build/vendor/**/*.js')
    .pipe(gulp.dest('dist/vendor'))
})

// Minify CSS
gulp.task('minify-css', function() {
   return gulp.src('build/css/*.css')
    //.pipe(strip({ignore: /url\([\w\s:\/=\-\+;,]*\)/g}))
    .pipe(plugins.cleanCss({compatibility: 'ie8'}))
    .pipe(gulp.dest('dist/css'));
});

// Minify HTML
gulp.task('minify-html', function () {
  return gulp.src('build/*.html')
    .pipe(plugins.stripComments())
    .pipe(plugins.htmlmin({collapseWhitespace: true}))
    .pipe(gulp.dest('dist'));
});

// Compress Images
gulp.task('images', function() {
    return gulp.src('src/images/**/*')
        .pipe(plugins.imagemin())
        .pipe(gulp.dest('build/images'));
});

// Add images to dist
gulp.task('dist-images', function() {
    return gulp.src('build/images/**/*')
        .pipe(plugins.imagemin())
        .pipe(gulp.dest('dist/images'));
});

// Validate HTML
gulp.task('html', function() {
  return gulp.src('src/*.html')
  .pipe(plugins.html())
  .pipe(gulp.dest('build/'));
});

// Compile Sass
gulp.task('sass', function() {
    return gulp.src('src/scss/*.scss')
        .pipe(plugins.sass())
        .pipe(plugins.autoprefixer())
        .pipe(gulp.dest('build/css/'));
});

// Watch Files For Changes
gulp.task('watch', function() {
    gulp.watch('scss/*.scss', ['sass', 'html']);
});

// Build Distrobution Folder
gulp.task('dist', [
        'minify-html',
        'minify-css',
        'dist-images',
        'dist-vendor-css',
        'dist-vendor-js',
        'compress-js'
    ]);

// Default Task
gulp.task('default', [
        'sass',
        'html',
        'images',
        'build-vendor-css',
        'build-vendor-js',
        'build-js'
    ]);
<|endoftext|>


<commit_before>const Observable = require('@sanity/observable')
const createCache = require('./utils/createCache')
const canonicalize = require('./utils/canonicalize')
const omit = require('lodash/omit')
const {BufferedDocument, Mutation} = require('@sanity/mutator')

function TODO(msg = 'TODO') {
  return function todo() {
    throw new Error(msg)
  }
}
const NOOP = () => {}

function createBufferedDocument(documentId, server) {

  const serverEvents$ = Observable.from(server.byId(documentId)).share()

  const bufferedDocs$ = serverEvents$
    .filter(event => event.type === 'snapshot')
    .map(event => event.document)
    .map(snapshot => {
      const bufferedDocument = new BufferedDocument(snapshot)

      bufferedDocument.commitHandler = function commitHandler(opts) {
        const payload = opts.mutation.params

        // TODO:
        // right now the BufferedDocument just commits fire-and-forget-ish
        // We should be able to handle failures and retry here

        server.mutate(omit(payload, 'resultRev'))
          .subscribe({
            next: opts.success,
            error: opts.failure
          })
      }

      const rebase$ = new Observable(rebaseObserver => {
        bufferedDocument.onRebase = edge => {
          rebaseObserver.next({type: 'rebase', document: edge})
        }
        return () => {
          bufferedDocument.onRebase = NOOP
        }
      }).share()

      const mutation$ = new Observable(mutationObserver => {
        bufferedDocument.onMutation = ({mutation, remote}) => {
          mutationObserver.next({
            type: 'mutation',
            document: bufferedDocument.LOCAL,
            mutations: mutation.mutations,
            origin: remote ? 'remote' : 'local'
          })
        }

        const serverMutations = serverEvents$
          .filter(event => event.type === 'mutation')
          // .do(event => {
          //   console.log('server event arrived', event)
          // })
          .subscribe(event => bufferedDocument.arrive(new Mutation(event)))

        return () => {
          serverMutations.unsubscribe()
          bufferedDocument.onMutation = NOOP
        }
      }).share()

      return {
        events: new Observable(observer => {
          observer.next({type: 'snapshot', document: bufferedDocument.LOCAL})
          return mutation$
            .merge(rebase$)
            .subscribe(observer)
        }),
        patch(patches) {
          const mutations = patches
            .map(patch => Object.assign({}, patch, {id: documentId}))
            .map(patch => ({patch: patch}))

          bufferedDocument.add(new Mutation({mutations: mutations}))
        },
        create(document) {
          const mutation = {
            create: Object.assign({id: documentId}, document)
          }
          bufferedDocument.add(new Mutation({mutations: [mutation]}))
        },
        delete() {
          bufferedDocument.add(new Mutation({mutations: [{delete: {id: documentId}}]}))
        },
        commit() {
          return new Observable(observer => {
            // todo: connect observable with request from bufferedDocument.commit somehow
            bufferedDocument.commit()
            observer.next()
            observer.complete()
          })
        }
      }
    })
    .share()

  let currentBuffered
  const cachedBuffered = new Observable(observer => {
    if (currentBuffered) {
      observer.next(currentBuffered)
      observer.complete()
    }
    return bufferedDocs$.do(doc => {
      currentBuffered = doc
    })
      .subscribe(observer)
  })

  return {
    events: cachedBuffered.switchMap(bufferedDoc => bufferedDoc.events),
    patch(patches) {
      cachedBuffered.subscribe(bufferedDoc => bufferedDoc.patch(patches))
    },
    create(document) {
      return cachedBuffered.switchMap(bufferedDoc => bufferedDoc.create(document))
    },
    delete() {
      return cachedBuffered.subscribe(bufferedDoc => bufferedDoc.delete())
    },
    commit() {
      return cachedBuffered.switchMap(bufferedDoc => bufferedDoc.commit())
    }
  }
}

const identity = val => val

module.exports = function createDocumentStore({serverConnection}) {

  const RECORDS_CACHE = createCache()

  const server = {
    byId: canonicalize(identity, serverConnection.byId),
    query: canonicalize(identity, serverConnection.query),
    mutate: serverConnection.mutate,
    delete: serverConnection.delete,
  }

  return {
    byId,
    byIds,
    query,
    create,
    checkout,
    patch: patchDoc,
    delete: deleteDoc,
    createOrReplace: TODO('Not implemented yet'),
    createIfNotExists: TODO('Not implemented yet'),
  }

  function patchDoc(documentId, patches) {
    return checkout(documentId)
      .patch(patches)
      .commit()
  }

  function deleteDoc(documentId) {
    return checkout(documentId)
      .delete()
      .commit()
  }

  function byId(documentId) {
    return checkout(documentId).events
  }

  function checkout(documentId) {
    return RECORDS_CACHE.fetch(documentId, () => createBufferedDocument(documentId, server))
  }

  function byIds(documentIds) {
    return new Observable(observer => {
      const documentSubscriptions = documentIds
        .map(id => byId(id).subscribe(observer))

      return () => {
        documentSubscriptions.map(subscription => subscription.unsubscribe())
      }
    })
  }

  function query(_query, params) {
    return Observable.from(serverConnection.query(_query, params))
  }

  function create(document) {
    return Observable.from(serverConnection.create(document))
  }
}
<commit_msg>[document-store] Make create/delete side-effecty<commit_after>const Observable = require('@sanity/observable')
const createCache = require('./utils/createCache')
const canonicalize = require('./utils/canonicalize')
const omit = require('lodash/omit')
const {BufferedDocument, Mutation} = require('@sanity/mutator')

function TODO(msg = 'TODO') {
  return function todo() {
    throw new Error(msg)
  }
}
const NOOP = () => {}

function createBufferedDocument(documentId, server) {

  const serverEvents$ = Observable.from(server.byId(documentId)).share()

  const bufferedDocs$ = serverEvents$
    .filter(event => event.type === 'snapshot')
    .map(event => event.document)
    .map(snapshot => {
      const bufferedDocument = new BufferedDocument(snapshot)

      bufferedDocument.commitHandler = function commitHandler(opts) {
        const payload = opts.mutation.params

        // TODO:
        // right now the BufferedDocument just commits fire-and-forget-ish
        // We should be able to handle failures and retry here

        server.mutate(omit(payload, 'resultRev'))
          .subscribe({
            next: opts.success,
            error: opts.failure
          })
      }

      const rebase$ = new Observable(rebaseObserver => {
        bufferedDocument.onRebase = edge => {
          rebaseObserver.next({type: 'rebase', document: edge})
        }
        return () => {
          bufferedDocument.onRebase = NOOP
        }
      }).share()

      const mutation$ = new Observable(mutationObserver => {
        bufferedDocument.onMutation = ({mutation, remote}) => {
          mutationObserver.next({
            type: 'mutation',
            document: bufferedDocument.LOCAL,
            mutations: mutation.mutations,
            origin: remote ? 'remote' : 'local'
          })
        }

        const serverMutations = serverEvents$
          .filter(event => event.type === 'mutation')
          // .do(event => {
          //   console.log('server event arrived', event)
          // })
          .subscribe(event => bufferedDocument.arrive(new Mutation(event)))

        return () => {
          serverMutations.unsubscribe()
          bufferedDocument.onMutation = NOOP
        }
      }).share()

      return {
        events: new Observable(observer => {
          observer.next({type: 'snapshot', document: bufferedDocument.LOCAL})
          return mutation$
            .merge(rebase$)
            .subscribe(observer)
        }),
        patch(patches) {
          const mutations = patches
            .map(patch => Object.assign({}, patch, {id: documentId}))
            .map(patch => ({patch: patch}))

          bufferedDocument.add(new Mutation({mutations: mutations}))
        },
        create(document) {
          const mutation = {
            create: Object.assign({id: documentId}, document)
          }
          bufferedDocument.add(new Mutation({mutations: [mutation]}))
        },
        delete() {
          bufferedDocument.add(new Mutation({mutations: [{delete: {id: documentId}}]}))
        },
        commit() {
          return new Observable(observer => {
            // todo: connect observable with request from bufferedDocument.commit somehow
            bufferedDocument.commit()
            observer.next()
            observer.complete()
          })
        }
      }
    })
    .share()

  let currentBuffered
  const cachedBuffered = new Observable(observer => {
    if (currentBuffered) {
      observer.next(currentBuffered)
      observer.complete()
    }
    return bufferedDocs$.do(doc => {
      currentBuffered = doc
    })
      .subscribe(observer)
  })

  return {
    events: cachedBuffered.switchMap(bufferedDoc => bufferedDoc.events),
    patch(patches) {
      cachedBuffered.subscribe(bufferedDoc => bufferedDoc.patch(patches))
    },
    create(document) {
      cachedBuffered.subscribe(bufferedDoc => bufferedDoc.create(document))
    },
    delete() {
      cachedBuffered.subscribe(bufferedDoc => bufferedDoc.delete())
    },
    commit() {
      return cachedBuffered.switchMap(bufferedDoc => bufferedDoc.commit())
    }
  }
}

const identity = val => val

module.exports = function createDocumentStore({serverConnection}) {

  const RECORDS_CACHE = createCache()

  const server = {
    byId: canonicalize(identity, serverConnection.byId),
    query: canonicalize(identity, serverConnection.query),
    mutate: serverConnection.mutate,
    delete: serverConnection.delete,
  }

  return {
    byId,
    byIds,
    query,
    create,
    checkout,
    patch: patchDoc,
    delete: deleteDoc,
    createOrReplace: TODO('Not implemented yet'),
    createIfNotExists: TODO('Not implemented yet'),
  }

  function patchDoc(documentId, patches) {
    return checkout(documentId)
      .patch(patches)
      .commit()
  }

  function deleteDoc(documentId) {
    return checkout(documentId)
      .delete()
      .commit()
  }

  function byId(documentId) {
    return checkout(documentId).events
  }

  function checkout(documentId) {
    return RECORDS_CACHE.fetch(documentId, () => createBufferedDocument(documentId, server))
  }

  function byIds(documentIds) {
    return new Observable(observer => {
      const documentSubscriptions = documentIds
        .map(id => byId(id).subscribe(observer))

      return () => {
        documentSubscriptions.map(subscription => subscription.unsubscribe())
      }
    })
  }

  function query(_query, params) {
    return Observable.from(serverConnection.query(_query, params))
  }

  function create(document) {
    return Observable.from(serverConnection.create(document))
  }
}
<|endoftext|>


<commit_before>// Returns fragment that emits direct data for specified object
// Optional filtering of some records is possible via `options.filter`

'use strict';

var ensureCallable = require('es5-ext/object/valid-callable')
  , ensureString   = require('es5-ext/object/validate-stringifiable-value')
  , escape         = require('es5-ext/reg-exp/escape')
  , memoize        = require('memoizee')
  , Fragment       = require('data-fragment')

  , driver = require('mano').dbDriver;

var getKeyPathFilter = function (keyPath) {
	var matches = RegExp.prototype.test.bind(new RegExp('^[a-z0-9][a-z0-9A-Z]*/' +
		escape(keyPath) + '(?:/.+|$)'));
	return function (data) { return matches(data.id); };
};

module.exports = memoize(function (dbName) {
	dbName = ensureString(dbName);
	return memoize(function (ownerId/*, options*/) {
		var fragment, options = Object(arguments[2]), filter, index, customFilter, keyPathFilter;

		ownerId = ensureString(ownerId);
		if (options.filter != null) customFilter = ensureCallable(options.filter);
		index = ownerId.indexOf('/');
		if (index !== -1) {
			keyPathFilter = getKeyPathFilter(ownerId.slice(index + 1));
			ownerId = ownerId.slice(0, index);
		}
		if (keyPathFilter) {
			if (customFilter) {
				filter = function (id, data) { return keyPathFilter(id, data) && customFilter(id, data); };
			} else {
				filter = keyPathFilter;
			}
		} else if (customFilter) {
			filter = customFilter;
		}
		fragment = new Fragment();
		fragment.promise = driver.getDirectObject(ownerId)(function (data) {
			data.forEach(function (data) {
				if (!filter || filter(data)) fragment.update(data.id, data.data);
			});
		});
		driver.on('object:' + ownerId, function (event) {
			if (event.type !== 'direct') return;
			if (!filter || filter(event)) fragment.update(event.id, event.data);
		});
		return fragment;
	}, { primitive: true });
}, { primitive: true });
<commit_msg>Fix argument retrieval<commit_after>// Returns fragment that emits direct data for specified object
// Optional filtering of some records is possible via `options.filter`

'use strict';

var ensureCallable = require('es5-ext/object/valid-callable')
  , ensureString   = require('es5-ext/object/validate-stringifiable-value')
  , escape         = require('es5-ext/reg-exp/escape')
  , memoize        = require('memoizee')
  , Fragment       = require('data-fragment')

  , driver = require('mano').dbDriver;

var getKeyPathFilter = function (keyPath) {
	var matches = RegExp.prototype.test.bind(new RegExp('^[a-z0-9][a-z0-9A-Z]*/' +
		escape(keyPath) + '(?:/.+|$)'));
	return function (data) { return matches(data.id); };
};

module.exports = memoize(function (dbName) {
	dbName = ensureString(dbName);
	return memoize(function (ownerId/*, options*/) {
		var fragment, options = Object(arguments[1]), filter, index, customFilter, keyPathFilter;

		ownerId = ensureString(ownerId);
		if (options.filter != null) customFilter = ensureCallable(options.filter);
		index = ownerId.indexOf('/');
		if (index !== -1) {
			keyPathFilter = getKeyPathFilter(ownerId.slice(index + 1));
			ownerId = ownerId.slice(0, index);
		}
		if (keyPathFilter) {
			if (customFilter) {
				filter = function (id, data) { return keyPathFilter(id, data) && customFilter(id, data); };
			} else {
				filter = keyPathFilter;
			}
		} else if (customFilter) {
			filter = customFilter;
		}
		fragment = new Fragment();
		fragment.promise = driver.getDirectObject(ownerId)(function (data) {
			data.forEach(function (data) {
				if (!filter || filter(data)) fragment.update(data.id, data.data);
			});
		});
		driver.on('object:' + ownerId, function (event) {
			if (event.type !== 'direct') return;
			if (!filter || filter(event)) fragment.update(event.id, event.data);
		});
		return fragment;
	}, { primitive: true });
}, { primitive: true });
<|endoftext|>


<commit_before>import { conferenceWillLeave } from '../conference';
import JitsiMeetJS from '../lib-jitsi-meet';

import {
    CONNECTION_DISCONNECTED,
    CONNECTION_ESTABLISHED,
    CONNECTION_FAILED,
    SET_DOMAIN
} from './actionTypes';
import './reducer';

const JitsiConnectionEvents = JitsiMeetJS.events.connection;

/**
 * Opens new connection.
 *
 * @returns {Promise<JitsiConnection>}
 */
export function connect() {
    return (dispatch, getState) => {
        const state = getState();
        const connectionOptions
            = state['features/base/connection'].connectionOptions;
        const room = state['features/base/conference'].room;
        const connection
            = new JitsiMeetJS.JitsiConnection(
                connectionOptions.appId,
                connectionOptions.token,
                {
                    ...connectionOptions,
                    bosh: connectionOptions.bosh + (room ? `?room=${room}` : '')
                });

        connection.addEventListener(
                JitsiConnectionEvents.CONNECTION_DISCONNECTED,
                connectionDisconnected);
        connection.addEventListener(
                JitsiConnectionEvents.CONNECTION_ESTABLISHED,
                connectionEstablished);
        connection.addEventListener(
                JitsiConnectionEvents.CONNECTION_FAILED,
                connectionFailed);

        connection.connect();

        /**
         * Dispatches CONNECTION_DISCONNECTED action when connection is
         * disconnected.
         *
         * @param {string} message - Disconnect reason.
         * @returns {void}
         */
        function connectionDisconnected(message) {
            connection.removeEventListener(
                    JitsiConnectionEvents.CONNECTION_DISCONNECTED,
                    connectionDisconnected);

            dispatch(_connectionDisconnected(connection, message));
        }

        /**
         * Resolves external promise when connection is established.
         *
         * @returns {void}
         */
        function connectionEstablished() {
            unsubscribe();
            dispatch(_connectionEstablished(connection));
        }

        /**
         * Rejects external promise when connection fails.
         *
         * @param {JitsiConnectionErrors} err - Connection error.
         * @returns {void}
         */
        function connectionFailed(err) {
            unsubscribe();
            console.error('CONNECTION FAILED:', err);
            dispatch(_connectionFailed(connection, err));
        }

        /**
         * Unsubscribes connection instance from CONNECTION_ESTABLISHED
         * and CONNECTION_FAILED events.
         *
         * @returns {void}
         */
        function unsubscribe() {
            connection.removeEventListener(
                    JitsiConnectionEvents.CONNECTION_ESTABLISHED,
                    connectionEstablished);
            connection.removeEventListener(
                    JitsiConnectionEvents.CONNECTION_FAILED,
                    connectionFailed);
        }
    };
}

/**
 * Closes connection.
 *
 * @returns {Function}
 */
export function disconnect() {
    return (dispatch, getState) => {
        const state = getState();
        const conference = state['features/base/conference'].conference;
        const connection = state['features/base/connection'].connection;

        let promise;

        // Leave the conference.
        if (conference) {
            // In a fashion similar to JitsiConference's CONFERENCE_LEFT event
            // (and the respective Redux action) which is fired after the
            // conference has been left, notify the application about the
            // intention to leave the conference.
            dispatch(conferenceWillLeave(conference));

            promise = conference.leave();
        } else {
            promise = Promise.resolve();
        }

        // Disconnect the connection.
        if (connection) {
            promise = promise.then(() => connection.disconnect());
        }

        return promise;
    };
}

/**
 * Sets connection domain.
 *
 * @param {string} domain - Domain name.
 * @returns {{
 *      type: SET_DOMAIN,
 *      domain: string
 *  }}
 */
export function setDomain(domain) {
    return {
        type: SET_DOMAIN,
        domain
    };
}

/**
 * Create an action for when the signaling connection has been lost.
 *
 * @param {JitsiConnection} connection - The JitsiConnection which disconnected.
 * @param {string} message - Error message.
 * @private
 * @returns {{
 *     type: CONNECTION_DISCONNECTED,
 *     connection: JitsiConnection,
 *     message: string
 * }}
 */
function _connectionDisconnected(connection, message) {
    return {
        type: CONNECTION_DISCONNECTED,
        connection,
        message
    };
}

/**
 * Create an action for when the signaling connection has been established.
 *
 * @param {JitsiConnection} connection - The JitsiConnection which was
 * established.
 * @private
 * @returns {{
 *     type: CONNECTION_ESTABLISHED,
 *     connection: JitsiConnection
 * }}
 */
function _connectionEstablished(connection) {
    return {
        type: CONNECTION_ESTABLISHED,
        connection
    };
}

/**
 * Create an action for when the signaling connection could not be created.
 *
 * @param {JitsiConnection} connection - The JitsiConnection which failed.
 * @param {string} error - Error message.
 * @private
 * @returns {{
 *     type: CONNECTION_FAILED,
 *     connection: JitsiConnection,
 *     error: string
 * }}
 */
function _connectionFailed(connection, error) {
    return {
        type: CONNECTION_FAILED,
        connection,
        error
    };
}
<commit_msg>[RN] Fix room name case sensitivity<commit_after>import { conferenceWillLeave } from '../conference';
import JitsiMeetJS from '../lib-jitsi-meet';

import {
    CONNECTION_DISCONNECTED,
    CONNECTION_ESTABLISHED,
    CONNECTION_FAILED,
    SET_DOMAIN
} from './actionTypes';
import './reducer';

const JitsiConnectionEvents = JitsiMeetJS.events.connection;

/**
 * Opens new connection.
 *
 * @returns {Promise<JitsiConnection>}
 */
export function connect() {
    return (dispatch, getState) => {
        const state = getState();
        const connectionOptions
            = state['features/base/connection'].connectionOptions;
        const room = state['features/base/conference'].room;
        const connection
            = new JitsiMeetJS.JitsiConnection(
                connectionOptions.appId,
                connectionOptions.token,
                {
                    ...connectionOptions,
                    bosh:
                        connectionOptions.bosh

                            // XXX The Jitsi Meet deployments require the room
                            // argument to be in lower case at the time of this
                            // writing but, unfortunately, they do not ignore
                            // case themselves.
                            + (room ? `?room=${room.toLowerCase()}` : '')
                });

        connection.addEventListener(
                JitsiConnectionEvents.CONNECTION_DISCONNECTED,
                connectionDisconnected);
        connection.addEventListener(
                JitsiConnectionEvents.CONNECTION_ESTABLISHED,
                connectionEstablished);
        connection.addEventListener(
                JitsiConnectionEvents.CONNECTION_FAILED,
                connectionFailed);

        connection.connect();

        /**
         * Dispatches CONNECTION_DISCONNECTED action when connection is
         * disconnected.
         *
         * @param {string} message - Disconnect reason.
         * @returns {void}
         */
        function connectionDisconnected(message) {
            connection.removeEventListener(
                    JitsiConnectionEvents.CONNECTION_DISCONNECTED,
                    connectionDisconnected);

            dispatch(_connectionDisconnected(connection, message));
        }

        /**
         * Resolves external promise when connection is established.
         *
         * @returns {void}
         */
        function connectionEstablished() {
            unsubscribe();
            dispatch(_connectionEstablished(connection));
        }

        /**
         * Rejects external promise when connection fails.
         *
         * @param {JitsiConnectionErrors} err - Connection error.
         * @returns {void}
         */
        function connectionFailed(err) {
            unsubscribe();
            console.error('CONNECTION FAILED:', err);
            dispatch(_connectionFailed(connection, err));
        }

        /**
         * Unsubscribes connection instance from CONNECTION_ESTABLISHED
         * and CONNECTION_FAILED events.
         *
         * @returns {void}
         */
        function unsubscribe() {
            connection.removeEventListener(
                    JitsiConnectionEvents.CONNECTION_ESTABLISHED,
                    connectionEstablished);
            connection.removeEventListener(
                    JitsiConnectionEvents.CONNECTION_FAILED,
                    connectionFailed);
        }
    };
}

/**
 * Closes connection.
 *
 * @returns {Function}
 */
export function disconnect() {
    return (dispatch, getState) => {
        const state = getState();
        const conference = state['features/base/conference'].conference;
        const connection = state['features/base/connection'].connection;

        let promise;

        // Leave the conference.
        if (conference) {
            // In a fashion similar to JitsiConference's CONFERENCE_LEFT event
            // (and the respective Redux action) which is fired after the
            // conference has been left, notify the application about the
            // intention to leave the conference.
            dispatch(conferenceWillLeave(conference));

            promise = conference.leave();
        } else {
            promise = Promise.resolve();
        }

        // Disconnect the connection.
        if (connection) {
            promise = promise.then(() => connection.disconnect());
        }

        return promise;
    };
}

/**
 * Sets connection domain.
 *
 * @param {string} domain - Domain name.
 * @returns {{
 *      type: SET_DOMAIN,
 *      domain: string
 *  }}
 */
export function setDomain(domain) {
    return {
        type: SET_DOMAIN,
        domain
    };
}

/**
 * Create an action for when the signaling connection has been lost.
 *
 * @param {JitsiConnection} connection - The JitsiConnection which disconnected.
 * @param {string} message - Error message.
 * @private
 * @returns {{
 *     type: CONNECTION_DISCONNECTED,
 *     connection: JitsiConnection,
 *     message: string
 * }}
 */
function _connectionDisconnected(connection, message) {
    return {
        type: CONNECTION_DISCONNECTED,
        connection,
        message
    };
}

/**
 * Create an action for when the signaling connection has been established.
 *
 * @param {JitsiConnection} connection - The JitsiConnection which was
 * established.
 * @private
 * @returns {{
 *     type: CONNECTION_ESTABLISHED,
 *     connection: JitsiConnection
 * }}
 */
function _connectionEstablished(connection) {
    return {
        type: CONNECTION_ESTABLISHED,
        connection
    };
}

/**
 * Create an action for when the signaling connection could not be created.
 *
 * @param {JitsiConnection} connection - The JitsiConnection which failed.
 * @param {string} error - Error message.
 * @private
 * @returns {{
 *     type: CONNECTION_FAILED,
 *     connection: JitsiConnection,
 *     error: string
 * }}
 */
function _connectionFailed(connection, error) {
    return {
        type: CONNECTION_FAILED,
        connection,
        error
    };
}
<|endoftext|>


<commit_before>'use strict';

module.exports = function () {
    this.World = require('../support/world.js').World;

    this.Given(/^я нахожусь на экране "([^"]*)"$/, function (viewName) {
        var that = this;
        return this.driver.findElement(this.by.xpath(this.selectors.XPATH.View.self(viewName))).then(function (element) {
            that.currentView = element;
        });
    });

    this.Then(/^система отобразит экран "([^"]*)"$/, function (viewName) {
        var that = this;
        return this.driver.findElement(this.by.xpath(this.selectors.XPATH.View.self(viewName))).then(function (element) {
            that.currentView = element;
        });
    });

    this.Then(/^система отобразит модальное окно "([^"]*)"$/, function (viewName) {
        var that = this;
        return this.driver.findElement(this.by.xpath(this.selectors.XPATH.ModalView.header(viewName))).then(function (element) {
            that.currentView = element;
        });
    });

    this.When(/^я закрою текущее модальное окно$/, function () {
        var selector = this.selectors.XPATH.ModalView.closeButton();
        var xpath = this.by.xpath(selector);
        var that = this;

        return this.driver.findElements(xpath)
            .then(function (elements) {
                var lastModalViewCloseButton = that._.last(elements);
                return lastModalViewCloseButton.click();
            });
    });

    this.Then(/^система отобразит окно-сообщение "([^"]*)"$/, function (message) {
        var selector = this.selectors.XPATH.ModalView.message();
        var xpath = this.by.xpath(selector);
        var that = this;

        message = message.replace(/''/g, '"');

        // TODO: Выполнять без setTimeout
        return this.driver.findElement(xpath).then(function (messageBox) {
            return new Promise(function (resolve, reject) {
                setTimeout(function () {
                    messageBox.getText().then(function (text) {
                        text = that.helpers.ignoreNumbers(text.trim(), message);
                        try {
                            that.assert.equal(text, message);
                            resolve();
                        } catch (err) {
                            reject(err);
                        }
                    });
                }, 500);
            });
        });
    });

    this.When(/^я нажму в окне-сообщении на кнопку "([^"]*)"$/, function (buttonText) {
        var selector = this.selectors.XPATH.ModalView.messageBoxButton(buttonText);
        var xpath = this.by.xpath(selector);

        return this.driver.findElement(xpath)
            .then(function (button) {
                button.click();
                return new Promise(function (resolve) {
                    setTimeout(resolve, 1000);
                });
            });
    });
};<commit_msg>Release 1.0.21<commit_after>'use strict';

module.exports = function () {
    this.World = require('../support/world.js').World;

    this.Given(/^я нахожусь на экране "([^"]*)"$/, function (viewName) {
        var that = this;
        return this.driver.findElement(this.by.xpath(this.selectors.XPATH.View.self(viewName))).then(function (element) {
            that.currentView = element;
        });
    });

    this.Then(/^система отобразит экран "([^"]*)"$/, function (viewName) {
        var that = this;
        return this.driver.findElement(this.by.xpath(this.selectors.XPATH.View.self(viewName))).then(function (element) {
            that.currentView = element;
        });
    });

    this.Then(/^система отобразит модальное окно "([^"]*)"$/, function (viewName) {
        var that = this;
        return this.driver.findElement(this.by.xpath(this.selectors.XPATH.ModalView.header(viewName))).then(function (element) {
            that.currentView = element;
        });
    });

    this.When(/^я закрою текущее модальное окно$/, function () {
        var selector = this.selectors.XPATH.ModalView.closeButton();
        var xpath = this.by.xpath(selector);
        var that = this;

        return this.driver.findElements(xpath)
            .then(function (elements) {
                var lastModalViewCloseButton = that._.last(elements);
                return lastModalViewCloseButton.click();
            });
    });

    this.Then(/^система отобразит окно-сообщение "([^"]*)"$/, function (message) {
        var selector = this.selectors.XPATH.ModalView.message();
        var xpath = this.by.xpath(selector);
        var that = this;

        message = message.replace(/''/g, '"');

        // TODO: Выполнять без setTimeout
        return this.driver.findElement(xpath).then(function (messageBox) {
            return new Promise(function (resolve, reject) {
                setTimeout(function () {
                    messageBox.getText().then(function (text) {
                        message = that.helpers.ignoreNumbers(text.trim(), message);
                        try {
                            that.assert.equal(text, message);
                            resolve();
                        } catch (err) {
                            reject(err);
                        }
                    });
                }, 500);
            });
        });
    });

    this.When(/^я нажму в окне-сообщении на кнопку "([^"]*)"$/, function (buttonText) {
        var selector = this.selectors.XPATH.ModalView.messageBoxButton(buttonText);
        var xpath = this.by.xpath(selector);

        return this.driver.findElement(xpath)
            .then(function (button) {
                button.click();
                return new Promise(function (resolve) {
                    setTimeout(resolve, 1000);
                });
            });
    });
};<|endoftext|>


<commit_before>'use strict';
require('dotenv').config();

const port = process.env.PORT || 5000;
const path = require('path');
const express = require('express');
const fs = require('fs');
const fetch = require('node-fetch');
const template = require('lodash/template');
const templateSettings = require('lodash/templateSettings');

const router = express.Router();

const mapPath = path.join(process.cwd(), 'map', 'build');
const storiesPath = path.join(process.cwd(), 'stories', 'build');
const app = express();

app.use(express.static(storiesPath));
app.use(express.static(mapPath));

app.get('/map', (req, res) => {
  res.sendFile(path.join(mapPath, 'map/index.html'));
});

const token = process.env.REACT_APP_CONTENTFUL_TOKEN;
const space = process.env.REACT_APP_SPACE_ID;

function parseContentfulImg(url) {
  return 'http:' + url + '?q=50&w=800&h=800'
}
function getStoryDetails(slug) {
  const url = `https://cdn.contentful.com/spaces/${space}/entries?content_type=story&query=${slug.split('-').join(' ')}&access_token=${token}`
  return fetch(url)
  .then(res => res.json())
  .then(body => {
    if (!body.items || !body.items.length) return null;
    const item = body.items[0].fields;
    const img = body.includes.Asset[0].fields.file;
    const seoStory = {};
    if (item.title) seoStory.title = `Care story - ${item.title}`;
    if (item.summary) seoStory.description = item.summary;
    if (img && img.url) {
      seoStory.image = parseContentfulImg(img.url);
    }
    return seoStory;
  });
}
function getOgTags() {
  const url = `https://cdn.contentful.com/spaces/${space}/entries?content_type=ogTags&access_token=${token}`
  return fetch(url)
  .then(res => res.json())
  .then(body => {
    if (!body.items || !body.items.length) return {};
    const field = body.items[0].fields;
    const image = body.includes.Asset[0].fields.file;
    const seo = {}
    if (field.ogTitle) seo.title = field.ogTitle;
    if (field.ogDescription) seo.description = field.ogDescription;
    if (image && image.url) seo.image = parseContentfulImg(image.url);
    return seo;
  });
}

const storiesHtml = path.join(storiesPath, 'index.html');
const storiesContent = fs.readFileSync(storiesHtml);

const seoParams = {
  title: 'CARE\'s World of Impact',
  description: 'Since 1946 CARE has turned donor gifts into life-changing programs around the world. In one map and in many stories, see how gifts to CARE deliver lasting change.',
  image: 'http://images.contentful.com/nlip0spjj3b7/6nGcJ78WYwMQeIeWsKKUou/1eabaf9ae44cfa1a7c8e5eb9979278da/ETH-2015-MT-002.JPG?q=50&w=800&h=800',
  url: ''
}
templateSettings.interpolate = /{{([\s\S]+?)}}/g;

const storiesRouter = router
  .get('/:slug', function(req, res, next) {
    getStoryDetails(req.params.slug)
      .then(({ item, img }) => {
        const seoStory = Object.assign(seoParams, tags);
        seoStory.url = req.hostname + req.baseUrl

        res.set('Content-Type', 'text/html');
        res.send(template(storiesContent)(seoStory))
      });
  })
  .get('/', (req, res) => {
    getOgTags()
      .then(function(tags) {
        const seoIndex = Object.assign(seoParams, tags);
        seoIndex.url = req.hostname + req.baseUrl

        res.set('Content-Type', 'text/html');
        res.send(template(storiesContent)(seoIndex))
      })
  });

app.use('/stories', storiesRouter);

app.listen(port, '0.0.0.0', (err) => {
  if (err) {
    console.log(err);
  }
  console.info('==> 🌎 Listening on http://0.0.0.0:%s/', port);
});
<commit_msg>Handle errors<commit_after>'use strict';
require('dotenv').config();

const port = process.env.PORT || 5000;
const path = require('path');
const express = require('express');
const fs = require('fs');
const fetch = require('node-fetch');
const template = require('lodash/template');
const templateSettings = require('lodash/templateSettings');

const router = express.Router();

const mapPath = path.join(process.cwd(), 'map', 'build');
const storiesPath = path.join(process.cwd(), 'stories', 'build');
const app = express();

app.use(express.static(storiesPath));
app.use(express.static(mapPath));

app.get('/map', (req, res) => {
  res.sendFile(path.join(mapPath, 'map/index.html'));
});

const token = process.env.REACT_APP_CONTENTFUL_TOKEN;
const space = process.env.REACT_APP_SPACE_ID;

function parseContentfulImg(url) {
  return 'http:' + url + '?q=50&w=800&h=800'
}
function getStoryDetails(slug) {
  const url = `https://cdn.contentful.com/spaces/${space}/entries?content_type=story&query=${slug.split('-').join(' ')}&access_token=${token}`
  return fetch(url)
  .then(res => res.json())
  .then(body => {
    if (!body.items || !body.items.length) return null;
    const item = body.items[0].fields;
    const img = body.includes.Asset[0].fields.file;
    const seoStory = {};
    if (item.title) seoStory.title = `Care story - ${item.title}`;
    if (item.summary) seoStory.description = item.summary;
    if (img && img.url) {
      seoStory.image = parseContentfulImg(img.url);
    }
    return seoStory;
  });
}
function getOgTags() {
  const url = `https://cdn.contentful.com/spaces/${space}/entries?content_type=ogTags&access_token=${token}`
  return fetch(url)
  .then(res => res.json())
  .then(body => {
    if (!body.items || !body.items.length) return {};
    const field = body.items[0].fields;
    const image = body.includes.Asset[0].fields.file;
    const seo = {}
    if (field.ogTitle) seo.title = field.ogTitle;
    if (field.ogDescription) seo.description = field.ogDescription;
    if (image && image.url) seo.image = parseContentfulImg(image.url);
    return seo;
  });
}

const storiesHtml = path.join(storiesPath, 'index.html');
const storiesContent = fs.readFileSync(storiesHtml);

const seoParams = {
  title: 'CARE\'s World of Impact',
  description: 'Since 1946 CARE has turned donor gifts into life-changing programs around the world. In one map and in many stories, see how gifts to CARE deliver lasting change.',
  image: 'http://images.contentful.com/nlip0spjj3b7/6nGcJ78WYwMQeIeWsKKUou/1eabaf9ae44cfa1a7c8e5eb9979278da/ETH-2015-MT-002.JPG?q=50&w=800&h=800',
  url: ''
}
templateSettings.interpolate = /{{([\s\S]+?)}}/g;

const storiesRouter = router
  .get('/:slug', function(req, res, next) {
    getStoryDetails(req.params.slug)
      .then(tags => {
        const seoStory = Object.assign(seoParams, tags);
        seoStory.url = req.hostname + req.baseUrl

        res.set('Content-Type', 'text/html');
        res.send(template(storiesContent)(seoStory))
      })
      .catch(function(e) {
        res.set('Content-Type', 'text/html');
        res.send(template(storiesContent)(seoParams))
      })
  })
  .get('/', (req, res) => {
    getOgTags()
      .then(function(tags) {
        const seoIndex = Object.assign(seoParams, tags);
        seoIndex.url = req.hostname + req.baseUrl

        res.set('Content-Type', 'text/html');
        res.send(template(storiesContent)(seoIndex))
      })
      .catch(function(e) {
        res.set('Content-Type', 'text/html');
        res.send(template(storiesContent)(seoParams))
      })
  });

app.use('/stories', storiesRouter);

app.listen(port, '0.0.0.0', (err) => {
  if (err) {
    console.log(err);
  }
  console.info('==> 🌎 Listening on http://0.0.0.0:%s/', port);
});
<|endoftext|>


<commit_before>var system  = require('system');
var webpage = require('webpage');

var input   = system.stdin.read();
var page    = webpage.create();
var errd    = false;
var signal  = '[E_PHANTOMIC] ';

page.onConsoleMessage = function (msg) {
  if (msg.indexOf(signal) === 0) {
    errd = true;
    msg = msg.substring(signal.length);
  }
  console.log(msg);
};

page.onError = function (msg, trace) {
  errd = true;
  console.error(msg);
  trace.forEach(function (t) {
    if (t.function) {
      console.error('    at ' + t.function + ' #' + t.line);
    }
  });
};

var server = require('webserver').create();
var port   = 42000;

var service = server.listen(port, function(req, res) {
  if (req.url === '/') {
    res.statusCode = 200;
    res.write('');
    res.write('');
    res.write('');
  } else if (req.url === '/js') {
    res.statusCode = 200;
    res.write('(function () {');
    res.write('  console.error = function (msg) {');
    res.write('    console.log("' + signal + '" + msg);');
    res.write('  };');
    res.write('}());');
    res.write(input);
  } else {
    res.statusCode = 404;
  }
  res.close();
});
if (service) {
  page.open('http://localhost:' + port, function () {
    setTimeout(function () {
      phantom.exit(errd ? 1 : 0);
    }, 50);
  });
} else {
  console.error('Could not start web server');
  phantom.exit(1);
}
<commit_msg>Set charset to utf-8<commit_after>var system  = require('system');
var webpage = require('webpage');

var input   = system.stdin.read();
var page    = webpage.create();
var errd    = false;
var signal  = '[E_PHANTOMIC] ';

page.onConsoleMessage = function (msg) {
  if (msg.indexOf(signal) === 0) {
    errd = true;
    msg = msg.substring(signal.length);
  }
  console.log(msg);
};

page.onError = function (msg, trace) {
  errd = true;
  console.error(msg);
  trace.forEach(function (t) {
    if (t.function) {
      console.error('    at ' + t.function + ' #' + t.line);
    }
  });
};

var server = require('webserver').create();
var port   = 42000;

var service = server.listen(port, function(req, res) {
  if (req.url === '/') {
    res.statusCode = 200;
    res.write('<meta charset="utf-8">');
    res.write('');
    res.write('');
  } else if (req.url === '/js') {
    res.statusCode = 200;
    res.write('(function () {');
    res.write('  console.error = function (msg) {');
    res.write('    console.log("' + signal + '" + msg);');
    res.write('  };');
    res.write('}());');
    res.write(input);
  } else {
    res.statusCode = 404;
  }
  res.close();
});
if (service) {
  page.open('http://localhost:' + port, function () {
    setTimeout(function () {
      phantom.exit(errd ? 1 : 0);
    }, 50);
  });
} else {
  console.error('Could not start web server');
  phantom.exit(1);
}
<|endoftext|>


<commit_before>var gulp = require('gulp'),
    gutil = require('gulp-util'),
    bump = require('gulp-bump'),
    git = require('gulp-git'),
    mocha = require('gulp-spawn-mocha'),
    mochaPhantomJS = require('gulp-mocha-phantomjs'),
    connect = require('gulp-connect'),
    clean = require('gulp-clean'),
    espower = require('gulp-espower'),
    runSequence = require('run-sequence'),
    source = require('vinyl-source-stream'),
    browserify = require('browserify'),
    merge = require('lodash.merge'),
    bumpTarget = ['./bower.json', './package.json'],
    bundleDir = 'build',
    bundleName = 'power-assert.js',
    destDir = 'espowered_tests';

function runMocha(pattern, extraOptions) {
    extraOptions = extraOptions || {};
    return gulp
        .src(pattern, {read: false})
        .pipe(mocha(merge({
            R: 'dot',
            c: true
        }, extraOptions)))
        .on('error', gutil.log);
}

function runMochaWithEspowerLoader() {
    return runMocha('test/**/*_test.js', {r: './enable_power_assert'});
}

function bumpVersion(options) {
    return gulp
        .src(bumpTarget)
        .pipe(bump(options))
        .pipe(gulp.dest('./'));
}

gulp.task('git_add', function(){
    return gulp
        .src(bumpTarget)
        .pipe(git.add());
});

gulp.task('git_commit', function(){
    var pkg = require('./package.json');
    return gulp
        .src(bumpTarget)
        .pipe(git.commit(pkg.version));
});

gulp.task('git_tag', function(done) {
    var pkg = require('./package.json');
    git.tag('v' + pkg.version, pkg.version, null, done);
});

['patch', 'minor', 'major'].forEach(function (v) {
    gulp.task('bump_' + v, function(){
        return bumpVersion({type: v});
    });
    gulp.task('release_' + v, function(){
        runSequence(
            'bump_' + v,
            'git_add',
            'git_commit',
            'git_tag'
        );
    });
});

gulp.task('connect', function() {
    connect.server({
        root: [__dirname],
        port: 9001,
        keepalive: true
    });
});

gulp.task('watch', function () {
    gulp.watch('{lib,test}/**/*.js', runMochaWithEspowerLoader);
    runMochaWithEspowerLoader();
});

gulp.task('clean_bundle', function () {
    return gulp
        .src(bundleDir, {read: false})
        .pipe(clean());
});

gulp.task('bundle', function() {
    var bundleStream = browserify('./lib/power-assert.js').bundle({standalone: 'assert'});
    return bundleStream
        .pipe(source(bundleName))
        .pipe(gulp.dest(bundleDir));
})

gulp.task('clean_espower', function () {
    return gulp
        .src(destDir, {read: false})
        .pipe(clean());
});

gulp.task('copy_others', function(){
    return gulp
        .src('test/not_tobe_instrumented/**/*.js', {base: './test/'})
        .pipe(gulp.dest(destDir));
});

gulp.task('espower', function() {
    return gulp
        .src('test/tobe_instrumented/**/*.js', {base: './test/'})
        .pipe(espower())
        .pipe(gulp.dest(destDir));
});

gulp.task('unit', function () {
    return runMochaWithEspowerLoader();
});

gulp.task('test_espowered', function () {
    return runMocha(destDir + '/**/*_test.js');
});

gulp.task('test_amd', function () {
    return gulp
        .src('test/test-amd.html')
        .pipe(mochaPhantomJS({reporter: 'dot'}));
});

gulp.task('test_browser', function () {
    return gulp
        .src('test/test-browser.html')
        .pipe(mochaPhantomJS({reporter: 'dot'}));
});

gulp.task('test', function() {
    runSequence(
        ['clean_espower', 'clean_bundle'],
        ['espower', 'copy_others', 'bundle'],
        ['unit','test_espowered','test_browser','test_amd']
    );
});
<commit_msg>Restructuring gulpfile. Extract paths object out.<commit_after>var gulp = require('gulp'),
    gutil = require('gulp-util'),
    bump = require('gulp-bump'),
    git = require('gulp-git'),
    mocha = require('gulp-spawn-mocha'),
    mochaPhantomJS = require('gulp-mocha-phantomjs'),
    connect = require('gulp-connect'),
    clean = require('gulp-clean'),
    espower = require('gulp-espower'),
    runSequence = require('run-sequence'),
    source = require('vinyl-source-stream'),
    browserify = require('browserify'),
    merge = require('lodash.merge'),
    paths = {
        bump: {
            target: ['./bower.json', './package.json']
        },
        bundle: {
            srcFile: './lib/power-assert.js',
            destDir: './build',
            destName: 'power-assert.js'
        },
        test: {
            base: './test/',
            pattern: '**/*_test.js',
            poweredDir: './espowered_tests/',
            toBeInstrumented: function () {
                return this.base + 'tobe_instrumented/' + this.pattern;
            },
            notToBeInstrumented: function () {
                return this.base + 'not_tobe_instrumented/' + this.pattern;
            },
            amd: 'test/test-amd.html',
            browser: 'test/test-browser.html'
        }
    };

function runMocha(pattern, extraOptions) {
    extraOptions = extraOptions || {};
    return gulp
        .src(pattern, {read: false})
        .pipe(mocha(merge({
            R: 'dot',
            c: true
        }, extraOptions)))
        .on('error', gutil.log);
}

function runMochaWithEspowerLoader() {
    return runMocha(paths.test.base + paths.test.pattern, {r: './enable_power_assert'});
}

function bumpVersion(options) {
    return gulp
        .src(paths.bump.target)
        .pipe(bump(options))
        .pipe(gulp.dest('./'));
}

gulp.task('git_add', function(){
    return gulp
        .src(paths.bump.target)
        .pipe(git.add());
});

gulp.task('git_commit', function(){
    var pkg = require('./package.json');
    return gulp
        .src(paths.bump.target)
        .pipe(git.commit(pkg.version));
});

gulp.task('git_tag', function(done) {
    var pkg = require('./package.json');
    git.tag('v' + pkg.version, pkg.version, null, done);
});

['patch', 'minor', 'major'].forEach(function (v) {
    gulp.task('bump_' + v, function(){
        return bumpVersion({type: v});
    });
    gulp.task('release_' + v, function(){
        runSequence(
            'bump_' + v,
            'git_add',
            'git_commit',
            'git_tag'
        );
    });
});

gulp.task('connect', function() {
    connect.server({
        root: [__dirname],
        port: 9001,
        keepalive: true
    });
});

gulp.task('watch', function () {
    gulp.watch('{lib,test}/**/*.js', runMochaWithEspowerLoader);
    runMochaWithEspowerLoader();
});

gulp.task('clean_bundle', function () {
    return gulp
        .src(paths.bundle.destDir, {read: false})
        .pipe(clean());
});

gulp.task('bundle', function() {
    var bundleStream = browserify(paths.bundle.srcFile).bundle({standalone: 'assert'});
    return bundleStream
        .pipe(source(paths.bundle.destName))
        .pipe(gulp.dest(paths.bundle.destDir));
})

gulp.task('clean_espower', function () {
    return gulp
        .src(paths.test.poweredDir, {read: false})
        .pipe(clean());
});

gulp.task('copy_others', function(){
    return gulp
        .src(paths.test.notToBeInstrumented(), {base: paths.test.base})
        .pipe(gulp.dest(paths.test.poweredDir));
});

gulp.task('espower', function() {
    return gulp
        .src(paths.test.toBeInstrumented(), {base: paths.test.base})
        .pipe(espower())
        .pipe(gulp.dest(paths.test.poweredDir));
});

gulp.task('unit', function () {
    return runMochaWithEspowerLoader();
});

gulp.task('test_espowered', function () {
    return runMocha(paths.test.poweredDir + paths.test.pattern);
});

gulp.task('test_amd', function () {
    return gulp
        .src(paths.test.amd)
        .pipe(mochaPhantomJS({reporter: 'dot'}));
});

gulp.task('test_browser', function () {
    return gulp
        .src(paths.test.browser)
        .pipe(mochaPhantomJS({reporter: 'dot'}));
});

gulp.task('test', function() {
    runSequence(
        ['clean_espower', 'clean_bundle'],
        ['espower', 'copy_others', 'bundle'],
        ['unit','test_espowered','test_browser','test_amd']
    );
});
<|endoftext|>


<commit_before>define(
        "sb/base/observable/ko/newObservableArray",
        [
                "ko",
                "sb/base/observable/newObservableArray",
                "sb/base/binding/Binding"
        ],
        function(ko, observable, binding) {

                /**
                 * Create a wraper for ko.observableArray.
                 * @param {sb.base.binding.Observer} observer observer of this observable object
                 * @param {ko.observableArray} koObservableArray observableArray object of KnockoutJS
                 * @return {sb.base.observable.ko.ObservableArray} A wraper for ko.observableArray.
                 */
                function newKoObservableArray(observer, koObservableArray) {

                        /**
                         * A wraper for ko.observableArray.
                         * @typedef {sb.base.observable.ko.ObservableArray}
                         * @implements {sb.base.observable.ObservableObject}
                         */
                        var observableArray = observable.newObservableArray(observer, koObservableArray());

                        /**
                         * handling changing of ko.observable value.
                         * @type {ko.computed}
                         */
                        var koComputed = ko.computed(function() {
                                var v = koObservable();
                                if (v !== observable()) {
                                        observable(v);
                                }
                                return v;
                        });

                        /**
                         * handling chaing of observable value.
                         * @type {sb.base.binding.Binding}
                         */
                        var b = new binding.Binding(
                                observer,
                                {observable: observable}, // inputs
                                {},                       // outputs
                                function() {              // computed
                                        var v = observable();
                                        if (v !== koObservable()) {
                                                koObservable(v);
                                        }
                                        return {};
                                }
                        );
                        b.bind();

                        return observable;
                }

                return newKoObservableArray;
        }
);

<commit_msg>pass lint<commit_after>define(
        "sb/base/observable/ko/newObservableArray",
        [
                "ko",
                "sb/base/observable/newObservableArray",
                "sb/base/binding/Binding"
        ],
        function(ko, observable, binding) {

                /**
                 * Create a wraper for ko.observableArray.
                 * @method sb.base.observable.ko.newKoObservableArray
                 * @public
                 * @static
                 * @param {sb.base.binding.Observer} observer observer of this observable object
                 * @param {ko.observableArray} koObservableArray observableArray object of KnockoutJS
                 * @return {sb.base.observable.ko.ObservableArray} A wraper for ko.observableArray.
                 */
                function newKoObservableArray(observer, koObservableArray) {

                        /**
                         * A wraper for ko.observableArray.
                         * @class ObservableArray
                         * @namespace sb.base.observable.ko
                         * @type sb.base.observable.ko.ObservableArray
                         * @extends sb.base.observable.ObservableObject
                         */
                        var observableArray = observable.newObservableArray(observer, koObservableArray());

                        /**
                         * Handling changing of ko.observable value.
                         * @property koComputed
                         * @private
                         * @type {ko.computed}
                         */
                        var koComputed = ko.computed(function() {
                                var arry = koObservableArray();
                                var length = observableArray.length();
                                var args = [0, length].concat(arry);

                                observableArray.splice.apply(observableArray, args);

                                return arry;
                        });

                        /**
                         * Handling chaing of observable value.
                         * @property b
                         * @private
                         * @type {sb.base.binding.Binding}
                         */
                        var b = new binding.Binding(
                                observer,
                                {observable: observableArray}, // inputs
                                {},                       // outputs
                                function() {              // computed
                                        var arry = observableArray();
                                        var length = koObservableArray().length;
                                        var args = [0, length].concat(arry);
                                        koObservableArray.splice.apply(args);
                                        return {};
                                }
                        );
                        b.bind();

                        return observableArray;
                }

                return newKoObservableArray;
        }
);

<|endoftext|>


<commit_before>// Required modules
var mongoose = require('mongoose');

// Required data schema
var Sensor = require('../../data/measurement');

/**
 * @api {get} /things/:thingId/measurements GET - Request all Thing's measurements
 * @apiName ListThingMeasurements
 * @apiGroup Thing
 * @apiVersion 1.0.0
 *
 * @apiParam {String} thingId	Thing's unique ID.
 *
 * @apiSuccess {Array} Measurements	Array of Measurements.
 *
 * @apiSuccessExample Success-Response:
 *     HTTP/1.1 200 OK
 *     [
 *       {
 *         "_id": "<< generated MongoDB ID >>",
 *         "sensorId": "<< generated MongoDB ID >>",
 *         "date": "2016-04-24T16:56:45.000Z",
 *         "value": 7,
 *         "__v": 0
 *       },
 *       {
 *         "_id": "<< generated MongoDB ID >>",
 *         "sensorId": "<< generated MongoDB ID >>",
 *         "date": "2016-04-24T16:59:45.000Z",
 *         "value": 8,
 *         "__v": 0
 *       }
 *     ]
 *
 * @apiUse ThingNotFoundError
 * @apiUse ServerError
 */
exports.request = function(req, res) {
	var id = req.params.thingId;

	Measurement.find({ thingId: id }, function(err, measurements) {
		if (err) {
			res.send(err);
		} else {
			res.json(measurements);
		}
	});
}<commit_msg>Temporary fix of things.listMeasurements API request<commit_after>// Required modules
var mongoose = require('mongoose');

// Required data schema
var Sensor = require('../../data/sensor');
var Measurement = require('../../data/measurement');
var Thing = require('../../data/thing');

/**
 * @api {get} /things/:thingId/measurements GET - Request all Thing's measurements
 * @apiName ListThingMeasurements
 * @apiGroup Thing
 * @apiVersion 1.0.0
 *
 * @apiParam {String} thingId	Thing's unique ID.
 *
 * @apiSuccess {Array} Measurements	Array of Measurements.
 *
 * @apiSuccessExample Success-Response:
 *     HTTP/1.1 200 OK
 *     [
 *       {
 *         "_id": "<< generated MongoDB ID >>",
 *         "sensorId": "<< generated MongoDB ID >>",
 *         "date": "2016-04-24T16:56:45.000Z",
 *         "value": 7,
 *         "__v": 0
 *       },
 *       {
 *         "_id": "<< generated MongoDB ID >>",
 *         "sensorId": "<< generated MongoDB ID >>",
 *         "date": "2016-04-24T16:59:45.000Z",
 *         "value": 8,
 *         "__v": 0
 *       }
 *     ]
 *
 * @apiUse ThingNotFoundError
 * @apiUse ServerError
 */
exports.request = function(req, res) {
	var id = req.params.thingId;

	Sensor.find({ thingId: id }, function(err, sensors) {
		if (err) {
			res.send(err);
		} else {
			console.log(sensors.length);
			//var result = [];
			result = aggregateMeasurements(sensors, 0, [], res);
		}
	});
}

function aggregateMeasurements(sensors, pos, result, res){
	if(pos == sensors.length){
		console.log(result);
		res.json(result);
		return result;
	}

	Measurement.find({sensorId: sensors[pos].id}, function(err, measurements){
		if(err){
			res.send(err);
			return;
		} else{
			aggregateMeasurements(sensors, pos+1, result.concat(measurements), res);
		}
	});
}<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { View, StyleSheet, TouchableOpacity, ScrollView, Alert } from 'react-native';
import { Container, Content, Text, Left, Right, ListItem, Spinner, Button } from 'native-base';
import Icon from 'react-native-vector-icons/FontAwesome';
import { getPlatformValue } from '../utils';
import * as firebase from 'firebase';
import { Actions } from 'react-native-router-flux';

export default class AccountDelete extends Component {

    /*Delete data
    The simplest way to delete data is to call remove() on a reference to the location of that data.
    You can also delete by specifying null as the value for another write operation such as set() or update().
    You can use this technique with update() to delete multiple children in a single API call.*/
    //TODO implement account deletion async function

  async deleteAccount() {

      var user = firebase.auth().currentUser;

      try {
          const user = firebase.auth().currentUser;
          user.delete().then(actions.login())
      } catch (e) {

      }
  }

  render() {
    return (
      <Container style={{ backgroundColor: 'black' }}>
        <View style={styles.header}>
          <TouchableOpacity>
            <Icon
              name="bars"
              size={30}
              color="white"
              onPress={this.props.sideMenu}
            />
          </TouchableOpacity>
          <Text style={{color: 'white', fontSize:25, textAlign:'center', width:250, fontWeight:'300', marginBottom:5}}>Delete Account</Text>
          <Icon name="diamond" size={20} color="gold" />
        </View>
        <ScrollView horizontal={false} showsHorizontalScrollIndicator={false} contentContainerStyle={{}}>
            <Content>
                <Text style={{color:'white', textAlign: 'center', padding: 2, marginBottom: 50, marginTop: 10}}>
                    Warning: Deleting your account will remove all traces of it from the database. You will have to recreate an
                    account if you wish to use Scale again.
                </Text>
                <Button full danger onPress={this.deleteAccount.bind(this)}>
                    <Text>Delete Account</Text>
                </Button>
            </Content>
        </ScrollView>
      </Container>
    );
  }
}

const styles = StyleSheet.create({
  totalPoints: {
    color: 'blue',
    fontWeight: 'bold',
    fontSize: 60,
  },
  red: {
    color: 'red',
  },
  headline: {
    fontWeight: 'bold',
    fontSize: 18,
    marginTop: 0,
    width: 200,
    textAlign: 'center',
    backgroundColor: 'yellow',
  },
  header: {
    paddingTop: getPlatformValue('android', 25, 20),
    flex: 0,
    flexDirection: 'row',
    height: 60,
    backgroundColor: 'black',
    justifyContent: 'space-around',
    alignItems: 'center',
    borderBottomWidth: 1,
    borderColor: '#424242',
  },
  title: {
    fontSize: 25,
    textAlign: 'center',
    width: 250,
    color: 'white',
    fontWeight: '300',
    marginBottom: 5,
  },
  selectionText: {
    color: 'white'
  }
});
<commit_msg>removed //TODO<commit_after>import React, { Component } from 'react';
import { View, StyleSheet, TouchableOpacity, ScrollView } from 'react-native';
import { Container, Content, Text, Button } from 'native-base';
import Icon from 'react-native-vector-icons/FontAwesome';
import { getPlatformValue } from '../utils';
import * as firebase from 'firebase';
import { Actions } from 'react-native-router-flux';

export default class AccountDelete extends Component {

  async deleteAccount() {

      try {
          const user = firebase.auth().currentUser;
          user.delete().then(Actions.login())
      } catch (e) {
      }
  }

  render() {
    return (
      <Container style={{ backgroundColor: 'black' }}>
        <View style={styles.header}>
          <TouchableOpacity>
            <Icon
              name="bars"
              size={30}
              color="white"
              onPress={this.props.sideMenu}
            />
          </TouchableOpacity>
          <Text style={{color: 'white', fontSize:25, textAlign:'center', width:250, fontWeight:'300', marginBottom:5}}>Delete Account</Text>
          <Icon name="diamond" size={20} color="gold" />
        </View>
        <ScrollView horizontal={false} showsHorizontalScrollIndicator={false} contentContainerStyle={{}}>
            <Content>
                <Text style={{color:'white', textAlign: 'center', padding: 2, marginBottom: 50, marginTop: 10}}>
                    Warning: Deleting your account will remove all traces of it from the database. You will have to recreate an
                    account if you wish to use Scale again.
                </Text>
                <Button full danger onPress={this.deleteAccount.bind(this)}>
                    <Text>Delete Account</Text>
                </Button>
            </Content>
        </ScrollView>
      </Container>
    );
  }
}

const styles = StyleSheet.create({
  totalPoints: {
    color: 'blue',
    fontWeight: 'bold',
    fontSize: 60,
  },
  red: {
    color: 'red',
  },
  headline: {
    fontWeight: 'bold',
    fontSize: 18,
    marginTop: 0,
    width: 200,
    textAlign: 'center',
    backgroundColor: 'yellow',
  },
  header: {
    paddingTop: getPlatformValue('android', 25, 20),
    flex: 0,
    flexDirection: 'row',
    height: 60,
    backgroundColor: 'black',
    justifyContent: 'space-around',
    alignItems: 'center',
    borderBottomWidth: 1,
    borderColor: '#424242',
  },
  title: {
    fontSize: 25,
    textAlign: 'center',
    width: 250,
    color: 'white',
    fontWeight: '300',
    marginBottom: 5,
  },
  selectionText: {
    color: 'white'
  }
});
<|endoftext|>