<commit_before>import prompt from 'prompt'
import chalk from 'chalk'
import path from 'path'
import fs from 'fs'
import _ from 'lodash'
import util from '../util'

const MODULE_NAME_CONVENTION_BEGINS = 'skin-'

const introductionText = 'you are now creating a new module for your bot.'
const nextStepText = 'your module is now setup and ready to be develop.'

const getTemplate = (template) => {
  const templatePath = path.join(__dirname, 'templates/create' , template)
  const templateContent = fs.readFileSync(templatePath)
  return _.template(templateContent)
}

const generateTemplate = (directory, filename, variables = {}) => {
  const template = getTemplate(filename)
  const compiled = template(variables)
  fs.writeFileSync(path.join(directory, filename), compiled)
}

const prefixDirectoryNameWithSkin = (directory) => {
  util.print('warn','the name of your module needs to begin by skin-')
  util.print('warn','we renamed your module to '+ chalk.bold(MODULE_NAME_CONVENTION_BEGINS + directory))
  return MODULE_NAME_CONVENTION_BEGINS + directory
}

module.exports = function() {

  util.print(introductionText)

  var schema = {
    properties: {
      name: {
        description: chalk.white('name:'),
        pattern: /^[a-z0-9][a-z0-9-_\.]+$/,
        message: 'name must be only lowercase letters, ' +
          'digits, dashes, underscores and dots.',
        required: true
      },
      description: {
        required: false,
        description: chalk.white('description:')
      },
      author: {
        required: false,
        description: chalk.white('author:')
      },
      version: {
        required: false,
        description: chalk.white('version:'),
        default: '1.0.0'
      }
    }
  }

  prompt.message = ''
  prompt.delimiter = ''

  prompt.start();

  prompt.get(schema, function (err, result) {
    var moduleDirectory = result.name

    if(moduleDirectory.substring(5) !== MODULE_NAME_CONVENTION_BEGINS){
      moduleDirectory = prefixDirectoryNameWithSkin(moduleDirectory)
    }

    if(fs.existsSync(moduleDirectory)) {
      util.print('error','directory name already exists in the current folder.')
      process.exit(1)
    } else {
      fs.mkdirSync(moduleDirectory)

      generateTemplate(moduleDirectory, 'package.json', result)
      generateTemplate(moduleDirectory, 'LICENSE')
      generateTemplate(moduleDirectory, 'index.js')

      fs.mkdirSync(moduleDirectory + '/views')
      generateTemplate(moduleDirectory, '/views/index.jsx')
      generateTemplate(moduleDirectory, '/views/test.scss')

      util.print('success',nextStepText)
    }
  })
}
<commit_msg>fix on name module<commit_after>import prompt from 'prompt'
import chalk from 'chalk'
import path from 'path'
import fs from 'fs'
import _ from 'lodash'
import util from '../util'

const MODULE_NAME_CONVENTION_BEGINS = 'skin-'

const introductionText = 'you are now creating a new module for your bot.'
const nextStepText = 'your module is now setup and ready to be develop.'

const getTemplate = (template) => {
  const templatePath = path.join(__dirname, 'templates/create' , template)
  const templateContent = fs.readFileSync(templatePath)
  return _.template(templateContent)
}

const generateTemplate = (directory, filename, variables = {}) => {
  const template = getTemplate(filename)
  const compiled = template(variables)
  fs.writeFileSync(path.join(directory, filename), compiled)
}

const prefixDirectoryNameWithSkin = (directory) => {
  util.print('warn','the name of your module needs to begin by skin-')
  util.print('warn','we renamed your module to '+ chalk.bold(MODULE_NAME_CONVENTION_BEGINS + directory))
  return MODULE_NAME_CONVENTION_BEGINS + directory
}

module.exports = function() {

  util.print(introductionText)

  var schema = {
    properties: {
      name: {
        description: chalk.white('name:'),
        pattern: /^[a-z0-9][a-z0-9-_\.]+$/,
        message: 'name must be only lowercase letters, ' +
          'digits, dashes, underscores and dots.',
        required: true
      },
      description: {
        required: false,
        description: chalk.white('description:')
      },
      author: {
        required: false,
        description: chalk.white('author:')
      },
      version: {
        required: false,
        description: chalk.white('version:'),
        default: '1.0.0'
      }
    }
  }

  prompt.message = ''
  prompt.delimiter = ''

  prompt.start();

  prompt.get(schema, function (err, result) {
    var moduleDirectory = result.name

    if(moduleDirectory.substring(5) !== MODULE_NAME_CONVENTION_BEGINS){
      result.name = moduleDirectory = prefixDirectoryNameWithSkin(moduleDirectory)
    }

    if(fs.existsSync(moduleDirectory)) {
      util.print('error','directory name already exists in the current folder.')
      process.exit(1)
    } else {
      fs.mkdirSync(moduleDirectory)

      generateTemplate(moduleDirectory, 'package.json', result)
      generateTemplate(moduleDirectory, 'LICENSE')
      generateTemplate(moduleDirectory, 'index.js')

      fs.mkdirSync(moduleDirectory + '/views')
      generateTemplate(moduleDirectory, '/views/index.jsx')
      generateTemplate(moduleDirectory, '/views/test.scss')

      util.print('success',nextStepText)
    }
  })
}
<|endoftext|>


<commit_before>/*
 The MIT License

 Copyright (c) 2014 Gareth Clay

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 */

(function () {
  'use strict';
  angular.module('cblite', ['ngResource', 'ab-base64'])
    .factory('cblite', function cbliteFactory($resource, $log, $q, base64, $filter) {

      var deferredCordova = $q.defer(),
        deferredCBLiteUrl = $q.defer(),
        cbliteUrlPromise = deferredCordova.promise.then(function () { return deferredCBLiteUrl.promise; }),
        cblite;

      function deviceReady() {
        function ParsedUrl(url) {
          // Trim off the leading 'http://'
          var http = "http://",
            credentials = url.slice(http.length, url.indexOf('@')),
            basicAuthToken = base64.encode(credentials);

          $log.debug("Couchbase Lite auth token: " + basicAuthToken);

          return {
            credentials: credentials,
            basicAuthToken: basicAuthToken,
            url: url,
            urlNoCredentials: http + url.slice(http.length + credentials.length + 1) // '@' symbol
          };
        }

        function getUrl() {
          // Grab the Couchbase Lite URL via the native bridge
          if (window.cblite) {
            window.cblite.getURL(function (err, url) {
              if (err) {
                deferredCBLiteUrl.reject(err);
              } else {
                deferredCBLiteUrl.notify("Couchbase Lite is running at " + url);
                cblite = new ParsedUrl(url);
                deferredCBLiteUrl.resolve(cblite);
              }
            });
          } else {
            throw ("Couchbase Lite plugin not found.");
          }
        }

        deferredCordova.notify("Notified that Cordova is ready");
        deferredCordova.resolve();
        getUrl();
      }

      function openResource(path, paramDefaults) {
        return cbliteUrlPromise.then(
          function (parsedUrl) {
            var headers = {Authorization: 'Basic ' + parsedUrl.basicAuthToken},
              actions = {
                'get':    {method: 'GET',  headers: headers},
                'list':   {method: 'GET',  headers: headers, isArray: true},
                'put':    {method: 'PUT',  headers: headers},
                'post':   {method: 'POST', headers: headers}
              };

            return $resource(parsedUrl.urlNoCredentials + path, paramDefaults, actions);
          },
          null,
          function (notification) {
            var message = "Angular Couchbase Lite: " + notification;
            $log.debug(message);
          }
        );
      }

      document.addEventListener('deviceready', deviceReady, false);

      return {
        // Couchbase Lite Server
        info: function () {
          $log.debug("Asking Couchbase Lite for server info");
          return openResource('').then(function (server) {
            return server.get().$promise;
          });
        },

        activeTasks: function () {
//          $log.debug("Asking Couchbase Lite for a list of active tasks");
          return openResource('_active_tasks').then(function (server) {
            return server.list().$promise;
          });
        },

        allDatabases: function () {
          var that = this;
//          $log.debug("Asking Couchbase Lite for list of all databases");
          return openResource('_all_dbs').then(function (allDatabases) {
            return allDatabases.list().$promise.then(function (databaseNames) {
              return databaseNames.map(function (name) {
                return that.database(name);
              });
            });
          });
        },

        userDatabases: function () {
          $log.debug("Asking Couchbase Lite for list of user databases");
          return this.allDatabases().then(function (databases) {
            return $filter('filter')(databases, function (db) { return db.slice(0, 1) !== '_'; });
          });
        },

        // Databases
        database: function (databaseName) {
          var openDatabase = openResource(':db', {db: databaseName}),
            openReplication = openResource('_replicate');

          function validateDocument(content) {
            var type = typeof content;
            switch (type) {
            case "string":
              if (typeof JSON.parse(content) !== "object") {
                throw "You can only save valid JSON strings";
              }
              break;

            case "object":
              if (content === null) {
                throw "You can't save a null document";
              }
              break;

            default:
              throw "You can't save this type: " + type;
            }
          }

          function toReplicationSpec(spec) {
            if (typeof spec === 'string') {
              spec = {
                url: spec,
                continuous: false
              };
            }
            return spec;
          }

          return {
            name: function () { return databaseName; },

            info: function () {
//              $log.debug("Asking Couchbase Lite for info about database [" + databaseName + "]");
              return openDatabase.then(function (db) {
                return db.get().$promise;
              });
            },

            checkIfExists: function () {
              $log.debug("Asking Couchbase Lite if database [" + databaseName + "] exists");
              return this.info().then(
                function () {
                  $log.debug("Couchbase Lite database '" + databaseName + "' exists");
                  return true;
                },
                function () {
                  $log.debug("Couchbase Lite database '" + databaseName + "' does not exist");
                  return false;
                }
              );
            },

            create: function () {
              $log.debug("Asking Couchbase Lite to create database [" + databaseName + "]");
              return openDatabase.then(function (db) {
                return db.put({}, null).$promise;
              });
            },

            createIfMissing: function () {
              var that = this;
              return this.info().then(
                function (info) { return info; },
                function (error) {
                  if (error.status === 404) {
                    return that.create();
                  }
                  throw "Unable to create database: " + JSON.stringify(error.data);
                }
              );
            },

            changes: function (spec) {
              $log.debug("Asking Couchbase Lite for list of changes to database [" + databaseName + "]");
              spec = angular.extend({}, spec, {db: databaseName});
              return openResource(':db/_changes', spec).then(function (db) {
                return db.get().$promise;
              });
            },

            all: function (spec, records) {
              spec = angular.extend({}, spec, {db: databaseName});
              var resourceString = ':db/_all_docs';
              $log.debug("Asking Couchbase Lite to get all documents in database [" + databaseName + "]");
              if (angular.isArray(records)) {
                $log.debug(JSON.stringify(records));
                return openResource(resourceString, spec).then(function (docs) {
                  return docs.post({ keys: records }).$promise;
                });
              } else {
                return openResource(resourceString, spec).then(function (docs) {
                  return docs.get().$promise;
                });
              }
            },

            // Design Doc
            design: function (designId) {
              function cleanFunction(func) {
                var type = typeof func;
                switch (type) {
                case "function":
                  // stringify and scrub
                  return String(func).replace(/\s+/g, " ");

                case "string":
                  return func;

                default:
                  throw "Invalid function definition";
                }
              }

              function toDesignDoc(content) {

                validateDocument(content);
                if (typeof content == "string") {
                  content = JSON.parse(content);
                }
                if (typeof content.views != "object") {
                  throw "Design Doc is missing valid view structure";
                }
                angular.forEach(content.views, function(value, key) {
                  value.map = cleanFunction(value.map);

                  if (typeof value.reduce != "undefined") {
                    value.reduce = cleanFunction(value.reduce);
                  }

                  this[key] = value;

                }, content.views);

                if (typeof content.language == "undefined") {
                  content.language = "javascript";
                }
                return content;
              }

              var designString = ':db/_design/:designId';

              return {
                save: function (spec) {
                  spec = toDesignDoc(spec);
                  $log.debug("Asking Couchbase Lite to save design document with id [" + designId + "] in database [" + databaseName + "]");
                  $log.debug(JSON.stringify(spec));
                  return openResource(designString, {db: databaseName, designId: designId}).then(function (document) {
                    return document.put(spec).$promise;
                  });
                },
                load: function () {
                  $log.debug("Asking Couchbase Lite to load design document with id [" + designId + "] in database [" + databaseName + "]");
                  return openResource(designString, {db: databaseName, designId: designId}).then(function (document) {
                    return document.get().$promise;
                  });
                },
                view: function (id, spec, records) {
                  spec = angular.extend({}, spec, {db: databaseName, designId: designId, id: id});
                  var viewString = designString + '/:id';
                  $log.debug("Asking Couchbase Lite to query view with id [" + designId + "/" + id + "] in database [" + databaseName + "]");
                  if (angular.isArray(records)) {
                    $log.debug(JSON.stringify(records));
                    return openResource(viewString, spec).then(function (docs) {
                      return docs.post({ keys: records }).$promise;
                    });
                  } else {
                    return openResource(viewString, spec).then(function (docs) {
                      return docs.get().$promise;
                    });
                  }
                }
              };
            },

            // Documents
            document: function (id) {
              var resourceString = ':db/:doc';

              return {
                load: function (spec) {
                  spec = angular.extend({}, spec, {db: databaseName, doc: id});
                  $log.debug("Asking Couchbase Lite for document with id [" + id + "] in database [" + databaseName + "]");
                  return openResource(resourceString, spec).then(function (document) {
                    return document.get().$promise;
                  }, function (error) {
                    $log.error("Failed to load document '" + id + "': " + JSON.stringify(error));
                    throw error;
                  });
                },

                save: function (content, revision) {
                  validateDocument(content);

                  if (revision != null && angular.isDefined(revision)) {
                    content._rev = revision
                  }

                  if (/*!isLocalDocument && */!angular.isDefined(id)) {
                    // If no id has been provided, then see if we can pull one from the document
                    id = content._id;
                    if (id === null || !angular.isDefined(id)) {
                      $log.debug("Asking Couchbase Lite to save document with a database-generated id in database [" + databaseName + "]");
                      return openResource(':db', {db: databaseName}).then(function (database) {
                        var promise = database.post(content).$promise;
                        return promise.then(function (response) {
                          // Update our cached id with the one returned in the response
                          id = response.id;
                          return promise;
                        });
                      });
                    }
                  }

                  $log.debug("Asking Couchbase Lite to save document with id [" + id + "] in database [" + databaseName + "]");
                  $log.debug(JSON.stringify(content));
                  return openResource(resourceString, {db: databaseName, doc: id}).then(function (document) {
                    return document.put(content).$promise;
                  });
                }
              };
            },

            // Replication and sync
            replicateTo: function (spec) {
              spec = toReplicationSpec(spec);
              return openReplication.then(function (replication) {
                var request = {
                  source: databaseName,
                  target: spec.url,
                  continuous: spec.continuous,
                  headers: spec.headers
                };
                $log.debug('Couchbase Lite requesting replication: ' + JSON.stringify(request));
                return replication.post(request).$promise;
              });
            },

            replicateFrom: function (spec) {
              spec = toReplicationSpec(spec);
              return openReplication.then(function (replication) {
                var request = {
                  source: spec.url,
                  target: databaseName,
                  continuous: spec.continuous,
                  headers: spec.headers
                };
                $log.debug('Couchbase Lite requesting replication: ' + JSON.stringify(request));
                return replication.post(request).$promise;
              });
            },

            syncWith: function (spec) {
              var that = this,
                sync = $q.defer(),
                combinedResponse = {};

              that.replicateTo(spec).then(
                function (localToRemoteResponse) {
                  combinedResponse.localToRemote = localToRemoteResponse;

                  return that.replicateFrom(spec).then(
                    function (remoteToLocalResponse) {
                      $log.error('Couchbase Lite replication request failed: ' + JSON.stringify(remoteToLocalResponse));
                      combinedResponse.remoteToLocal = remoteToLocalResponse;
                      sync.resolve(combinedResponse);
                    },
                    function (remoteToLocalError) {
                      combinedResponse.remoteToLocal = remoteToLocalError;
                      sync.reject(combinedResponse);
                    }
                  );
                },
                function (localToRemoteError) {
                  $log.error('Couchbase Lite replication request failed: ' + JSON.stringify(localToRemoteError));
                  combinedResponse.localToRemote = localToRemoteError;
                  sync.reject(combinedResponse);
                }
              );

              return sync.promise;
            }
          };
        }
      };
    });
}());
<commit_msg>Fixed view query url.<commit_after>/*
 The MIT License

 Copyright (c) 2014 Gareth Clay

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 */

(function () {
  'use strict';
  angular.module('cblite', ['ngResource', 'ab-base64'])
    .factory('cblite', function cbliteFactory($resource, $log, $q, base64, $filter) {

      var deferredCordova = $q.defer(),
        deferredCBLiteUrl = $q.defer(),
        cbliteUrlPromise = deferredCordova.promise.then(function () { return deferredCBLiteUrl.promise; }),
        cblite;

      function deviceReady() {
        function ParsedUrl(url) {
          // Trim off the leading 'http://'
          var http = "http://",
            credentials = url.slice(http.length, url.indexOf('@')),
            basicAuthToken = base64.encode(credentials);

          $log.debug("Couchbase Lite auth token: " + basicAuthToken);

          return {
            credentials: credentials,
            basicAuthToken: basicAuthToken,
            url: url,
            urlNoCredentials: http + url.slice(http.length + credentials.length + 1) // '@' symbol
          };
        }

        function getUrl() {
          // Grab the Couchbase Lite URL via the native bridge
          if (window.cblite) {
            window.cblite.getURL(function (err, url) {
              if (err) {
                deferredCBLiteUrl.reject(err);
              } else {
                deferredCBLiteUrl.notify("Couchbase Lite is running at " + url);
                cblite = new ParsedUrl(url);
                deferredCBLiteUrl.resolve(cblite);
              }
            });
          } else {
            throw ("Couchbase Lite plugin not found.");
          }
        }

        deferredCordova.notify("Notified that Cordova is ready");
        deferredCordova.resolve();
        getUrl();
      }

      function openResource(path, paramDefaults) {
        return cbliteUrlPromise.then(
          function (parsedUrl) {
            var headers = {Authorization: 'Basic ' + parsedUrl.basicAuthToken},
              actions = {
                'get':    {method: 'GET',  headers: headers},
                'list':   {method: 'GET',  headers: headers, isArray: true},
                'put':    {method: 'PUT',  headers: headers},
                'post':   {method: 'POST', headers: headers}
              };

            return $resource(parsedUrl.urlNoCredentials + path, paramDefaults, actions);
          },
          null,
          function (notification) {
            var message = "Angular Couchbase Lite: " + notification;
            $log.debug(message);
          }
        );
      }

      document.addEventListener('deviceready', deviceReady, false);

      return {
        // Couchbase Lite Server
        info: function () {
          $log.debug("Asking Couchbase Lite for server info");
          return openResource('').then(function (server) {
            return server.get().$promise;
          });
        },

        activeTasks: function () {
//          $log.debug("Asking Couchbase Lite for a list of active tasks");
          return openResource('_active_tasks').then(function (server) {
            return server.list().$promise;
          });
        },

        allDatabases: function () {
          var that = this;
//          $log.debug("Asking Couchbase Lite for list of all databases");
          return openResource('_all_dbs').then(function (allDatabases) {
            return allDatabases.list().$promise.then(function (databaseNames) {
              return databaseNames.map(function (name) {
                return that.database(name);
              });
            });
          });
        },

        userDatabases: function () {
          $log.debug("Asking Couchbase Lite for list of user databases");
          return this.allDatabases().then(function (databases) {
            return $filter('filter')(databases, function (db) { return db.slice(0, 1) !== '_'; });
          });
        },

        // Databases
        database: function (databaseName) {
          var openDatabase = openResource(':db', {db: databaseName}),
            openReplication = openResource('_replicate');

          function validateDocument(content) {
            var type = typeof content;
            switch (type) {
            case "string":
              if (typeof JSON.parse(content) !== "object") {
                throw "You can only save valid JSON strings";
              }
              break;

            case "object":
              if (content === null) {
                throw "You can't save a null document";
              }
              break;

            default:
              throw "You can't save this type: " + type;
            }
          }

          function toReplicationSpec(spec) {
            if (typeof spec === 'string') {
              spec = {
                url: spec,
                continuous: false
              };
            }
            return spec;
          }

          return {
            name: function () { return databaseName; },

            info: function () {
//              $log.debug("Asking Couchbase Lite for info about database [" + databaseName + "]");
              return openDatabase.then(function (db) {
                return db.get().$promise;
              });
            },

            checkIfExists: function () {
              $log.debug("Asking Couchbase Lite if database [" + databaseName + "] exists");
              return this.info().then(
                function () {
                  $log.debug("Couchbase Lite database '" + databaseName + "' exists");
                  return true;
                },
                function () {
                  $log.debug("Couchbase Lite database '" + databaseName + "' does not exist");
                  return false;
                }
              );
            },

            create: function () {
              $log.debug("Asking Couchbase Lite to create database [" + databaseName + "]");
              return openDatabase.then(function (db) {
                return db.put({}, null).$promise;
              });
            },

            createIfMissing: function () {
              var that = this;
              return this.info().then(
                function (info) { return info; },
                function (error) {
                  if (error.status === 404) {
                    return that.create();
                  }
                  throw "Unable to create database: " + JSON.stringify(error.data);
                }
              );
            },

            changes: function (spec) {
              $log.debug("Asking Couchbase Lite for list of changes to database [" + databaseName + "]");
              spec = angular.extend({}, spec, {db: databaseName});
              return openResource(':db/_changes', spec).then(function (db) {
                return db.get().$promise;
              });
            },

            all: function (spec, records) {
              spec = angular.extend({}, spec, {db: databaseName});
              var resourceString = ':db/_all_docs';
              $log.debug("Asking Couchbase Lite to get all documents in database [" + databaseName + "]");
              if (angular.isArray(records)) {
                $log.debug(JSON.stringify(records));
                return openResource(resourceString, spec).then(function (docs) {
                  return docs.post({ keys: records }).$promise;
                });
              } else {
                return openResource(resourceString, spec).then(function (docs) {
                  return docs.get().$promise;
                });
              }
            },

            // Design Doc
            design: function (designId) {
              function cleanFunction(func) {
                var type = typeof func;
                switch (type) {
                case "function":
                  // stringify and scrub
                  return String(func).replace(/\s+/g, " ");

                case "string":
                  return func;

                default:
                  throw "Invalid function definition";
                }
              }

              function toDesignDoc(content) {

                validateDocument(content);
                if (typeof content == "string") {
                  content = JSON.parse(content);
                }
                if (typeof content.views != "object") {
                  throw "Design Doc is missing valid view structure";
                }
                angular.forEach(content.views, function(value, key) {
                  value.map = cleanFunction(value.map);

                  if (typeof value.reduce != "undefined") {
                    value.reduce = cleanFunction(value.reduce);
                  }

                  this[key] = value;

                }, content.views);

                if (typeof content.language == "undefined") {
                  content.language = "javascript";
                }
                return content;
              }

              var designString = ':db/_design/:designId';

              return {
                save: function (spec) {
                  spec = toDesignDoc(spec);
                  $log.debug("Asking Couchbase Lite to save design document with id [" + designId + "] in database [" + databaseName + "]");
                  $log.debug(JSON.stringify(spec));
                  return openResource(designString, {db: databaseName, designId: designId}).then(function (document) {
                    return document.put(spec).$promise;
                  });
                },
                load: function () {
                  $log.debug("Asking Couchbase Lite to load design document with id [" + designId + "] in database [" + databaseName + "]");
                  return openResource(designString, {db: databaseName, designId: designId}).then(function (document) {
                    return document.get().$promise;
                  });
                },
                view: function (id, spec, records) {
                  spec = angular.extend({}, spec, {db: databaseName, designId: designId, id: id});
                  var viewString = designString + '/_view/:id';
                  $log.debug("Asking Couchbase Lite to query view with id [" + designId + "/" + id + "] in database [" + databaseName + "]");
                  if (angular.isArray(records)) {
                    $log.debug(JSON.stringify(records));
                    return openResource(viewString, spec).then(function (docs) {
                      return docs.post({ keys: records }).$promise;
                    });
                  } else {
                    return openResource(viewString, spec).then(function (docs) {
                      return docs.get().$promise;
                    });
                  }
                }
              };
            },

            // Documents
            document: function (id) {
              var resourceString = ':db/:doc';

              return {
                load: function (spec) {
                  spec = angular.extend({}, spec, {db: databaseName, doc: id});
                  $log.debug("Asking Couchbase Lite for document with id [" + id + "] in database [" + databaseName + "]");
                  return openResource(resourceString, spec).then(function (document) {
                    return document.get().$promise;
                  }, function (error) {
                    $log.error("Failed to load document '" + id + "': " + JSON.stringify(error));
                    throw error;
                  });
                },

                save: function (content, revision) {
                  validateDocument(content);

                  if (revision != null && angular.isDefined(revision)) {
                    content._rev = revision
                  }

                  if (/*!isLocalDocument && */!angular.isDefined(id)) {
                    // If no id has been provided, then see if we can pull one from the document
                    id = content._id;
                    if (id === null || !angular.isDefined(id)) {
                      $log.debug("Asking Couchbase Lite to save document with a database-generated id in database [" + databaseName + "]");
                      return openResource(':db', {db: databaseName}).then(function (database) {
                        var promise = database.post(content).$promise;
                        return promise.then(function (response) {
                          // Update our cached id with the one returned in the response
                          id = response.id;
                          return promise;
                        });
                      });
                    }
                  }

                  $log.debug("Asking Couchbase Lite to save document with id [" + id + "] in database [" + databaseName + "]");
                  $log.debug(JSON.stringify(content));
                  return openResource(resourceString, {db: databaseName, doc: id}).then(function (document) {
                    return document.put(content).$promise;
                  });
                }
              };
            },

            // Replication and sync
            replicateTo: function (spec) {
              spec = toReplicationSpec(spec);
              return openReplication.then(function (replication) {
                var request = {
                  source: databaseName,
                  target: spec.url,
                  continuous: spec.continuous,
                  headers: spec.headers
                };
                $log.debug('Couchbase Lite requesting replication: ' + JSON.stringify(request));
                return replication.post(request).$promise;
              });
            },

            replicateFrom: function (spec) {
              spec = toReplicationSpec(spec);
              return openReplication.then(function (replication) {
                var request = {
                  source: spec.url,
                  target: databaseName,
                  continuous: spec.continuous,
                  headers: spec.headers
                };
                $log.debug('Couchbase Lite requesting replication: ' + JSON.stringify(request));
                return replication.post(request).$promise;
              });
            },

            syncWith: function (spec) {
              var that = this,
                sync = $q.defer(),
                combinedResponse = {};

              that.replicateTo(spec).then(
                function (localToRemoteResponse) {
                  combinedResponse.localToRemote = localToRemoteResponse;

                  return that.replicateFrom(spec).then(
                    function (remoteToLocalResponse) {
                      $log.error('Couchbase Lite replication request failed: ' + JSON.stringify(remoteToLocalResponse));
                      combinedResponse.remoteToLocal = remoteToLocalResponse;
                      sync.resolve(combinedResponse);
                    },
                    function (remoteToLocalError) {
                      combinedResponse.remoteToLocal = remoteToLocalError;
                      sync.reject(combinedResponse);
                    }
                  );
                },
                function (localToRemoteError) {
                  $log.error('Couchbase Lite replication request failed: ' + JSON.stringify(localToRemoteError));
                  combinedResponse.localToRemote = localToRemoteError;
                  sync.reject(combinedResponse);
                }
              );

              return sync.promise;
            }
          };
        }
      };
    });
}());
<|endoftext|>


<commit_before>CT.admin.db = {
	"init": function() {
		CT.log("acquiring db schema");
		CT.admin.core.init("db", function(schema) {
			var skeys = Object.keys(schema);
			CT.log("got schema with " + skeys.length + " tables");
			CT.admin.db.schema = schema;
			CT.panel.simple(skeys, "db");
			for (var i = 0; i < skeys.length; i++)
				CT.dom.id("dbcontent" + skeys[i],
					true).appendChild(CT.panel.pager(CT.admin.db._build(skeys[i]),
					CT.admin.db._refill(skeys[i]), 10, "rcol", "data"));
		});
	},
	"get": function(modelName, cb, limit, offset) {
		limit = limit || 20;
		offset  = offset || 0;
		CT.admin.core.q("db", cb, ["failed to get", modelName,
			"- limit", limit, "offset", offset].join(" "), {
			"modelName": modelName,
			"limit": limit,
			"offset": offset
		});
	},
	"_refill": function(modelName) {
		var f = function(obj, cb) {
			CT.admin.db.get(modelName, cb, obj.limit, obj.offset);
		};
		return f;
	},
	"_build": function(modelName) {
		var f = function(obj) {
			return (new CT.admin.db.Editor(modelName, obj)).node;
		};
		return f;
	}
};

CT.admin.db.Editor = CT.Class({
	"_submit": function() {
		this.log("_submit");
	},
	"_input": function(f, ptype) {
		return function() {
			if (ptype == "boolean")
				return f.checked;
			if (ptype == "integer")
				return parseInt(f.value) || null;
			if (ptype == "float")
				return parseFloat(f.value) || null;
			return f.value; // string
		};
	},
	"_modal": function(key) {
		this.log("_modal", key);
		(new CT.modal.Modal({
			"node": CT.dom.node(JSON.stringify(CT.data.get(key)))
		})).show();
	},
	"_entity": function(key) {
		if (!key) return CT.dom.node("null");
		var that = this, n = CT.dom.node(),
			vdata = CT.data.get(key);
		this.log("_entity", key, vdata);
		var fill = function(d) {
			n.appendChild(CT.dom.link((d.label || d.key),
				function() { that._modal(key); }));
		};
		if (vdata)
			fill(vdata);
		else
			CT.admin.core.q("db", function(d) {
				CT.data.add(d);
				fill(d);
			}, "failed to get " + key, { "key": key });
		return n;
	},
	"_row": function(k) {
		var val = this.data[k], valcell, ptype,
			rownode = CT.dom.node("", "div", "lister");
		rownode.appendChild(CT.dom.node(k + ":", "div", "keycell"));
		ptype = rownode.ptype = this.schema[k];
		if (ptype == "key")
			valcell = this._entity(val);
		else if (ptype) {
			if (ptype == "string")
				valcell = CT.dom.field(null, val);
			else if (ptype == "boolean")
				valcell = CT.dom.checkbox(null, val);
			else if (ptype == "float")
				valcell = CT.parse.numOnly(CT.dom.field(null, val), true);
			else if (ptype == "integer")
				valcell = CT.parse.numOnly(CT.dom.field(null, val));
			valcell.getValue = this._input(valcell, ptype);
		} else
			valcell = CT.dom.node(val, "span");
		rownode.appendChild(valcell);
		return rownode;
	},
	"_table": function() {
		var k, r, n = this.node = CT.dom.node(); // TODO: list, maybe zipcode
		["string", "integer", "float", "bool", "key"].forEach(function(t) {
			n[t] = CT.dom.node();
			n.appendChild(n[t]);
		});
		for (k in this.data) {
			r = this._row(k);
			(n[r.ptype] || n).appendChild(r);
		}
		n.appendChild(CT.dom.button("Submit", this._submit));
	},
	"init": function(model, data) {
		this.log = CT.log.getLogger("Editor(" + model + ")");
		this.schema = CT.admin.db.schema[model];
		this.data = data;
		this._table();
	}
});<commit_msg>admin db editor, take 1<commit_after>CT.admin.db = {
	"init": function() {
		CT.log("acquiring db schema");
		CT.admin.core.init("db", function(schema) {
			var skeys = Object.keys(schema);
			CT.log("got schema with " + skeys.length + " tables");
			CT.admin.db.schema = schema;
			CT.panel.simple(skeys, "db");
			for (var i = 0; i < skeys.length; i++)
				CT.dom.id("dbcontent" + skeys[i],
					true).appendChild(CT.panel.pager(CT.admin.db._build(skeys[i]),
					CT.admin.db._refill(skeys[i]), 10, "rcol", "data"));
		});
	},
	"get": function(modelName, cb, limit, offset) {
		limit = limit || 20;
		offset  = offset || 0;
		CT.admin.core.q("db", cb, ["failed to get", modelName,
			"- limit", limit, "offset", offset].join(" "), {
			"modelName": modelName,
			"limit": limit,
			"offset": offset
		});
	},
	"_refill": function(modelName) {
		var f = function(obj, cb) {
			CT.admin.db.get(modelName, cb, obj.limit, obj.offset);
		};
		return f;
	},
	"_build": function(modelName) {
		var f = function(obj) {
			return (new CT.admin.db.Editor(modelName, obj)).node;
		};
		return f;
	}
};

CT.admin.db.Editor = CT.Class({
	"_submit": function() {
		this.log("_submit");
		var changes = {}, params = {
			"key": "edit",
			"data": changes
		};
		if (this.data.key)
			changes.key = this.data.key;
		else
			changes.modelName = this.modelName;
		this.inputs.forEach(function(ip) {
			var val = ip.getValue();
			if (val != this.data[ip.rowKey])
				changes[ip.rowKey] = val;
		});
		CT.admin.core.q("db", function() {
			alert("you did it");
		}, "edit failed", params);
	},
	"_input": function(f, ptype) {
		return function() {
			if (ptype == "boolean")
				return f.checked;
			if (ptype == "integer")
				return parseInt(f.value) || null;
			if (ptype == "float")
				return parseFloat(f.value) || null;
			return f.value; // string
		};
	},
	"_modal": function(key) {
		this.log("_modal", key);
		(new CT.modal.Modal({
			"node": CT.dom.node(JSON.stringify(CT.data.get(key)))
		})).show();
	},
	"_entity": function(key) {
		if (!key) return CT.dom.node("null");
		var that = this, n = CT.dom.node(),
			vdata = CT.data.get(key);
		this.log("_entity", key, vdata);
		var fill = function(d) {
			n.appendChild(CT.dom.link((d.label || d.key),
				function() { that._modal(key); }));
		};
		if (vdata)
			fill(vdata);
		else
			CT.admin.core.q("db", function(d) {
				CT.data.add(d);
				fill(d);
			}, "failed to get " + key, { "key": key });
		return n;
	},
	"_row": function(k) {
		var val = this.data[k], valcell, ptype,
			rownode = CT.dom.node("", "div", "lister");
		rownode.appendChild(CT.dom.node(k + ":", "div", "keycell"));
		ptype = rownode.ptype = this.schema[k];
		if (ptype == "key")
			valcell = this._entity(val);
		else if (ptype) {
			if (ptype == "string")
				valcell = CT.dom.field(null, val);
			else if (ptype == "boolean")
				valcell = CT.dom.checkbox(null, val);
			else if (ptype == "float")
				valcell = CT.parse.numOnly(CT.dom.field(null, val), true);
			else if (ptype == "integer")
				valcell = CT.parse.numOnly(CT.dom.field(null, val));
			valcell.getValue = this._input(valcell, ptype);
			valcell.rowKey = k;
			this.inputs.push(valcell);
		} else
			valcell = CT.dom.node(val, "span");
		rownode.appendChild(valcell);
		return rownode;
	},
	"_table": function() {
		var k, r, n = this.node = CT.dom.node(); // TODO: list, maybe zipcode
		["string", "integer", "float", "bool", "key"].forEach(function(t) {
			n[t] = CT.dom.node();
			n.appendChild(n[t]);
		});
		for (k in this.data) {
			r = this._row(k);
			(n[r.ptype] || n).appendChild(r);
		}
		n.appendChild(CT.dom.button("Submit", this._submit));
	},
	"init": function(model, data) {
		this.log = CT.log.getLogger("Editor(" + model + ")");
		this.modelName = model;
		this.schema = CT.admin.db.schema[model];
		this.data = data;
		this.inputs = [];
		this._table();
	}
});<|endoftext|>


<commit_before>// Eloquent JavaScript

// Run this file in your terminal using `node my_solution.js`. Make sure it works before moving on!

// Program Structure
// Write your own variable and do something to it.
var hi = "hello";
  console.log(hi);

prompt("What is your favorite food?");
alert("Hey! That is my favorite too!");

// Complete one of the exercises: Looping a Triangle, FizzBuzz, or Chess Board

var fizzbuzz = function(x) {
if (x % 3 == 0) && (x % 5 == 0)
   console.log("FizzBuzz");
elsif (x % 3 == 0)
   console.log("Fizz");
elsif (x % 5 == 0)
  console.log("Buzz");
else (x)
  console.log(x);
}

// Functions

// Complete the `minimum` exercise.

function min(x, y) {
  console.log(Math.min(x, y));
}

// Data Structures: Objects and Arrays
// Create an object called "me" that stores your name, age, 3 favorite foods, and a quirk below.
//Status API Training Shop Blog About Pricing
<commit_msg>Update eloquent.js<commit_after>// Eloquent JavaScript

// Run this file in your terminal using `node my_solution.js`. Make sure it works before moving on!

// Program Structure
// Write your own variable and do something to it.
var hi = "hello";
  console.log(hi);

prompt("What is your favorite food?");
alert("Hey! That is my favorite too!");

// Complete one of the exercises: Looping a Triangle, FizzBuzz, or Chess Board
var array = [1,2,3,..,100]

var fizzbuzz = function(array) {

  for(var x = 0;x<array.length;x++) {

    if(x % 3 == 0) && (x % 5 == 0) {
       console.log("FizzBuzz");
     }
    else if(x % 3 == 0) {
      console.log("Fizz");
      }
    else if(x % 5 == 0) {
       console.log("Buzz");
      };
    else{
      console.log(x);
      };
    };
};

// Functions

// Complete the `minimum` exercise.
var array2 = [x, y];

function min(array2) {
  console.log(array2.min(x, y));
};

// Data Structures: Objects and Arrays
// Create an object called "me" that stores your name, age, 3 favorite foods, and a quirk below.

var me = {
  name: 'Sanderfer',
  age: 32,
  favoriteFoods1: 'pizza',
  favoriteFoods2: 'pasta',
  favoriteFoods3: 'burger',
  quick: 'enjoys long walks',
};

//Status API Training Shop Blog About Pricing
<|endoftext|>


<commit_before>'use strict';

/*
 * Module dependencies.
 */
var _ = require('lodash'),
	mongoose = require('mongoose'),
	Schema = mongoose.Schema,
	serverJSON = require('../../../../local_files/ui/server.ui.json'),
	Helper = require('../../../../custom_objects/Helper'),
	async = require('async'),
	ValidationError = require('mongoose/lib/error/validation'),
	ValidatorError =  require('mongoose/lib/error/validator');

var validateNameProperty = function(property)
{
	var regEx = new RegExp(/^[\d\w\-\s]{5,30}$/);
	console.log('property: ' + property);
	return regEx.test(property);
};

/**
 * Event Schema
 */
var EventSchema = new Schema({
	name: {
		type: String,
		required: 'name.empty',
		//match: [new RegExp(serverJSON.api.events.name.invalid.regex), 'name.invalid'],
		//validate: [validateNameProperty, serverJSON.api.events.errors._2],
		trim: true
	},
	created: {
		type: Date,
		default: Date.now
	},
	location:{
		//type: Object,
		//required: 'Please fill location name',
		name: {
			type: String,
			default: '',
			trim: true
		},
		address: {
			type: String,
			required: 'location.address.empty',
			//match: [new RegExp(serverJSON.api.events.location.address.invalid.regex), 'location.address.invalid'],
			trim: true
		},
		lat: {
			type: Number,
			//required: serverJSON.api.events.errors._3,
			default: -1
		},
		lng: {
			type: Number,
			//required: serverJSON.api.events.errors._4,
			default: -1
		}
	},
	date:{
		type: Date,
		required: 'date.empty',
		//match: [new RegExp(serverJSON.api.events.date.invalid.regex), 'date.invalid'],
	},
	time:{
		type: Date,
		required: 'time.empty',
		//match: [new RegExp(serverJSON.api.events.time.invalid.regex), 'time.invalid'],
	},
	voteEnabled:{
		type:Boolean,
		default:true
	},
	minimumVotes:{
		type:Number,
		required: 'minimumVotes.empty'
	},
	votes: {
		yes:
		{
			type: [Schema.ObjectId],
			ref: 'User',
			validate:
			[
				{
					validator: Helper.isValidObjectIDs,
					msg: 'votes.yes.invalid'
				},
				{
					validator: Helper.isUniqueArray,
					msg: 'votes.yes.duplicate'
				}
			]
		},
		no:
		{
			type: [Schema.ObjectId],
			ref: 'User',
			validate:
			[
				{
					validator: Helper.isValidObjectIDs,
					msg: 'votes.no.invalid'
				},
				{
					validator: Helper.isUniqueArray,
					msg: 'votes.no.duplicate'
				}
			]
		},
	},

	message:{
		type: String,
		required: 'message.empty'
	},
	group: {
		type: Schema.ObjectId,
		ref: 'Group',
		//required: serverJSON.api.events.group.empty,
		validate:
		[
			{
				validator: Helper.isValidObjectID,
				msg: 'group.invalid'
			}
		]
	},
	user: {
		type: Schema.ObjectId,
		ref: 'User'
	},
	cron:
	[
		{
			key: String,
			settings: {

			}
		}
	]
});

EventSchema.statics.functionsArray = [

];

EventSchema.statics.objectIDAtts = [
	{
		name: 'user',
		model: 'User'
	},
	{
		name: 'group',
		model: 'Group'
	},
	{
		name: 'votes.yes',
		model: 'User'
	},
	{
		name: 'votes.no',
		model: 'User'
	}
];

EventSchema.statics.title = serverJSON.constants.events;
EventSchema.statics.errPath = 'api.events';
EventSchema.statics.attsToShow = ['_id', 'name', 'location', 'date', 'time', 'voteEnabled', 'minimumVotes', 'votes', 'message', 'group'];

/*********** Validate Functions **************/
EventSchema.path('group').validate(function (id,respond) {

	var Group = mongoose.model('Group');
	var query = {
		_id : id
	};

	console.log('validate group: ' + id);

	Helper.find(Group,query,function(err,mod) {

		if(err || !mod)
			respond(false);
		else
			respond(true);
	});

},'group.exist');

EventSchema.path('votes.yes').validate(function (ids,respond) {

	if(ids.length === 0)
		respond(true);

	var User = mongoose.model('User');
	var query = {
    	_id:
    	{
    		$in: ids
    	}
    };

	console.log('validate votes "yes"' + ids);

	Helper.find(User,query,function(err,mods) {

		if(err || !mods || ids.length !== mods.length)
			respond(false);
		else
			respond(true);
	});

},'votes.yes.exist');

EventSchema.path('votes.no').validate(function (ids,respond) {

	if(ids.length === 0)
		respond(true);

	var User = mongoose.model('User');
	var query = {
    	_id:
    	{
    		$in: ids
    	}
    };

	console.log('validate votes "no"' + ids);

	Helper.find(User,query,function(err,mods) {

		if(err || !mods || ids.length !== mods.length)
			respond(false);
		else
			respond(true);
	});

},'votes.no.exist');

/*********** END Validate Functions **************/

/*********** PRE Functions ***********/
EventSchema.pre('save', function (next) {

	console.log('event pre save: ' + this);

	var yesArr = [];
	var noArr = [];
	var i = null;

	for(i = 0; i < this.votes.yes.length; ++i)
		yesArr.push(this.votes.yes[i].toString());

	for(i = 0; i < this.votes.no.length; ++i)
		noArr.push(this.votes.no[i].toString());

	console.log('yesArr: ' + yesArr);
	console.log('noArr: ' + noArr);

	var intersection = _.intersection(yesArr,noArr);

	console.log('intersection: ' + intersection);
	if(intersection.length) {

		var err = new ValidationError(this);
		err.errors.votes = new ValidatorError('votes.yes', 'votes.yes.duplicate', 'notunique', '');

	  	console.log(err);

	  	next(err);
	 }
	 else
	 	next();
});

/*********** END PRE Functions ***********/

mongoose.model('Event', EventSchema);
<commit_msg>remove required values for location address and event message #75<commit_after>'use strict';

/*
 * Module dependencies.
 */
var _ = require('lodash'),
	mongoose = require('mongoose'),
	Schema = mongoose.Schema,
	serverJSON = require('../../../../local_files/ui/server.ui.json'),
	Helper = require('../../../../custom_objects/Helper'),
	async = require('async'),
	ValidationError = require('mongoose/lib/error/validation'),
	ValidatorError =  require('mongoose/lib/error/validator');

var validateNameProperty = function(property)
{
	var regEx = new RegExp(/^[\d\w\-\s]{5,30}$/);
	console.log('property: ' + property);
	return regEx.test(property);
};

/**
 * Event Schema
 */
var EventSchema = new Schema({
	name: {
		type: String,
		required: 'name.empty',
		//match: [new RegExp(serverJSON.api.events.name.invalid.regex), 'name.invalid'],
		//validate: [validateNameProperty, serverJSON.api.events.errors._2],
		trim: true
	},
	created: {
		type: Date,
		default: Date.now
	},
	location:{
		//type: Object,
		//required: 'Please fill location name',
		name: {
			type: String,
			default: '',
			trim: true
		},
		address: {
			type: String,
			//match: [new RegExp(serverJSON.api.events.location.address.invalid.regex), 'location.address.invalid'],
			trim: true
		},
		lat: {
			type: Number,
			//required: serverJSON.api.events.errors._3,
			default: -1
		},
		lng: {
			type: Number,
			//required: serverJSON.api.events.errors._4,
			default: -1
		}
	},
	date:{
		type: Date,
		required: 'date.empty',
		//match: [new RegExp(serverJSON.api.events.date.invalid.regex), 'date.invalid'],
	},
	time:{
		type: Date,
		required: 'time.empty',
		//match: [new RegExp(serverJSON.api.events.time.invalid.regex), 'time.invalid'],
	},
	voteEnabled:{
		type:Boolean,
		default:true
	},
	minimumVotes:{
		type:Number,
		required: 'minimumVotes.empty'
	},
	votes: {
		yes:
		{
			type: [Schema.ObjectId],
			ref: 'User',
			validate:
			[
				{
					validator: Helper.isValidObjectIDs,
					msg: 'votes.yes.invalid'
				},
				{
					validator: Helper.isUniqueArray,
					msg: 'votes.yes.duplicate'
				}
			]
		},
		no:
		{
			type: [Schema.ObjectId],
			ref: 'User',
			validate:
			[
				{
					validator: Helper.isValidObjectIDs,
					msg: 'votes.no.invalid'
				},
				{
					validator: Helper.isUniqueArray,
					msg: 'votes.no.duplicate'
				}
			]
		},
	},

	message:{
		type: String
	},
	group: {
		type: Schema.ObjectId,
		ref: 'Group',
		//required: serverJSON.api.events.group.empty,
		validate:
		[
			{
				validator: Helper.isValidObjectID,
				msg: 'group.invalid'
			}
		]
	},
	user: {
		type: Schema.ObjectId,
		ref: 'User'
	},
	cron:
	[
		{
			key: String,
			settings: {

			}
		}
	]
});

EventSchema.statics.functionsArray = [

];

EventSchema.statics.objectIDAtts = [
	{
		name: 'user',
		model: 'User'
	},
	{
		name: 'group',
		model: 'Group'
	},
	{
		name: 'votes.yes',
		model: 'User'
	},
	{
		name: 'votes.no',
		model: 'User'
	}
];

EventSchema.statics.title = serverJSON.constants.events;
EventSchema.statics.errPath = 'api.events';
EventSchema.statics.attsToShow = ['_id', 'name', 'location', 'date', 'time', 'voteEnabled', 'minimumVotes', 'votes', 'message', 'group'];

/*********** Validate Functions **************/
EventSchema.path('group').validate(function (id,respond) {

	var Group = mongoose.model('Group');
	var query = {
		_id : id
	};

	console.log('validate group: ' + id);

	Helper.find(Group,query,function(err,mod) {

		if(err || !mod)
			respond(false);
		else
			respond(true);
	});

},'group.exist');

EventSchema.path('votes.yes').validate(function (ids,respond) {

	if(ids.length === 0)
		respond(true);

	var User = mongoose.model('User');
	var query = {
    	_id:
    	{
    		$in: ids
    	}
    };

	console.log('validate votes "yes"' + ids);

	Helper.find(User,query,function(err,mods) {

		if(err || !mods || ids.length !== mods.length)
			respond(false);
		else
			respond(true);
	});

},'votes.yes.exist');

EventSchema.path('votes.no').validate(function (ids,respond) {

	if(ids.length === 0)
		respond(true);

	var User = mongoose.model('User');
	var query = {
    	_id:
    	{
    		$in: ids
    	}
    };

	console.log('validate votes "no"' + ids);

	Helper.find(User,query,function(err,mods) {

		if(err || !mods || ids.length !== mods.length)
			respond(false);
		else
			respond(true);
	});

},'votes.no.exist');

/*********** END Validate Functions **************/

/*********** PRE Functions ***********/
EventSchema.pre('save', function (next) {

	console.log('event pre save: ' + this);

	var yesArr = [];
	var noArr = [];
	var i = null;

	for(i = 0; i < this.votes.yes.length; ++i)
		yesArr.push(this.votes.yes[i].toString());

	for(i = 0; i < this.votes.no.length; ++i)
		noArr.push(this.votes.no[i].toString());

	console.log('yesArr: ' + yesArr);
	console.log('noArr: ' + noArr);

	var intersection = _.intersection(yesArr,noArr);

	console.log('intersection: ' + intersection);
	if(intersection.length) {

		var err = new ValidationError(this);
		err.errors.votes = new ValidatorError('votes.yes', 'votes.yes.duplicate', 'notunique', '');

	  	console.log(err);

	  	next(err);
	 }
	 else
	 	next();
});

/*********** END PRE Functions ***********/

mongoose.model('Event', EventSchema);
<|endoftext|>


<commit_before>'use strict';
import _ from 'lodash';
import Promise from 'native-promise-only';
import { checkCondition } from '../../../utils/utils';
import Component from '../component/Component';
import Components from '../../Components';

export default class NestedComponent extends Component {
  static schema(...extend) {
    return Component.schema({
      tree: true
    }, ...extend);
  }

  constructor(component, options, data) {
    super(component, options, data);
    this.type = 'components';
    this._collapsed = !!this.component.collapsed;
    this.components = [];
  }

  get defaultSchema() {
    return NestedComponent.schema();
  }

  get schema() {
    const schema = super.schema;
    schema.components = [];
    this.eachComponent((component) => schema.components.push(component.schema));
    return schema;
  }

  get collapsed() {
    return this._collapsed;
  }

  set collapsed(value) {
    this._collapsed = value;
    this.redraw();
  }

  set visible(value) {
    super.visible = value;
    const isVisible = this.visible;
    const forceShow = this.options.show && this.options.show[this.component.key];
    const forceHide = this.options.hide && this.options.hide[this.component.key];
    this.components.forEach(component => {
      if (forceShow) {
        component.visible = true;
      }
      else if (forceHide || (isVisible && !component.conditionallyVisible())) {
        component.visible = false;
      }
      component.parentVisible = isVisible;
    });
  }

  get visible() {
    return super.visible;
  }

  set parentVisible(value) {
    super.parentVisible = value;
    this.components.forEach(component => {
      component.parentVisible = this.visible;
    });
  }

  get parentVisible() {
    return super.parentVisible;
  }

  getComponents() {
    return this.components || [];
  }

  getAllComponents() {
    return this.getComponents().reduce((components, component) => {
      let result = component;

      if (component.getAllComponents) {
        result = component.getAllComponents();
      }

      return components.concat(result);
    }, []);
  }

  /**
   * Perform a deep iteration over every component, including those
   * within other container based components.
   *
   * @param {function} fn - Called for every component.
   */
  everyComponent(fn) {
    const components = this.getComponents();
    _.each(components, (component, index) => {
      if (fn(component, components, index) === false) {
        return false;
      }

      if (typeof component.everyComponent === 'function') {
        if (component.everyComponent(fn) === false) {
          return false;
        }
      }
    });
  }

  /**
   * Perform an iteration over each component within this container component.
   *
   * @param {function} fn - Called for each component
   */
  eachComponent(fn) {
    _.each(this.getComponents(), (component, index) => {
      if (fn(component, index) === false) {
        return false;
      }
    });
  }

  /**
   * Returns a component provided a key. This performs a deep search within the
   * component tree.
   *
   * @param {string} key - The key of the component to retrieve.
   * @param {function} fn - Called with the component once found.
   * @return {Object} - The component that is located.
   */
  getComponent(key, fn) {
    let comp = null;
    this.everyComponent((component, components) => {
      if (component.component.key === key) {
        comp = component;
        if (fn) {
          fn(component, components);
        }
        return false;
      }
    });
    return comp;
  }

  /**
   * Return a component provided the Id of the component.
   *
   * @param {string} id - The Id of the component.
   * @param {function} fn - Called with the component once it is retrieved.
   * @return {Object} - The component retrieved.
   */
  getComponentById(id, fn) {
    let comp = null;
    this.everyComponent((component, components) => {
      if (component.id === id) {
        comp = component;
        if (fn) {
          fn(component, components);
        }
        return false;
      }
    });
    return comp;
  }

  /**
   * Create a new component and add it to the components array.
   *
   * @param component
   * @param data
   */
  createComponent(component, options, data, before) {
    options = options || this.options;
    data = data || this.data;
    const comp = Components.create(component, options, data, true);
    comp.parent = this;
    comp.root = this.root || this;
    comp.parentVisible = this.visible;
    comp.isBuilt = true;
    if (component.internal) {
      return comp;
    }

    if (before) {
      const index = _.findIndex(this.components, { id: before.id });
      if (index !== -1) {
        this.components.splice(index, 0, comp);
      }
      else {
        this.components.push(comp);
      }
    }
    else {
      this.components.push(comp);
    }
    return comp;
  }

  getContainer() {
    return this.element;
  }

  get componentComponents() {
    return this.component.components || [];
  }

  get nestedKey() {
    return `nested-${this.key}`;
  }

  get templateName() {
    return 'container';
  }

  init() {
    this.components = this.components || [];
    this.addComponents();
  }

  /**
   *
   * @param element
   * @param data
   */
  addComponents(data) {
    data = data || this.data;
    this.componentComponents.forEach((component) => this.addComponent(component, data));
  }

  /**
   * Add a new component to the components array.
   *
   * @param {Object} component - The component JSON schema to add.
   * @param {Object} data - The submission data object to house the data for this component.
   * @param {HTMLElement} before - A DOM element to insert this element before.
   * @return {Component} - The created component instance.
   */
  addComponent(component, data, before, noAdd) {
    data = data || this.data;
    const comp = this.createComponent(component, this.options, data, before ? before.component : null);
    if (noAdd) {
      return comp;
    }
    return comp;
  }

  render(children) {
    // If already rendering, don't re-render.
    return super.render(children || this.renderTemplate(this.templateName, {
      children: this.renderComponents(),
      nestedKey: this.nestedKey,
      collapsed: this.collapsed,
    }));
  }

  renderComponents(components) {
    components = components || this.components;
    const children = components.map(component => component.render());
    return this.renderTemplate('components', {
      children,
      components,
    });
  }

  attach(element) {
    this.loadRefs(element, {
      header: 'single',
      collapsed: this.collapsed,
      [this.nestedKey]: 'single',
    });

    if (this.refs[this.nestedKey]) {
      this.attachComponents(this.refs[this.nestedKey]);
    }

    if (this.component.collapsible && this.refs.header) {
      this.addEventListener(this.refs.header, 'click', () => {
        this.collapsed = !this.collapsed;
      });
    }

    super.attach(element);
  }

  attachComponents(element, components, container) {
    components = components || this.components;
    container = container || this.component.components;

    element = this.hook('attachComponents', element, components, container, this);
    if (!element) {
      return;
    }

    let index = 0;
    Array.prototype.slice.call(element.children).forEach(child => {
      if (!child.getAttribute('data-noattach') && components[index]) {
        components[index].attach(child);
        index++;
      }
    });
  }

  /**
   * Remove a component from the components array.
   *
   * @param {Component} component - The component to remove from the components.
   * @param {Array<Component>} components - An array of components to remove this component from.
   */
  removeComponent(component, components) {
    component.destroy();
    _.remove(components, { id: component.id });
  }

  /**
   * Removes a component provided the API key of that component.
   *
   * @param {string} key - The API key of the component to remove.
   * @param {function} fn - Called once the component is removed.
   * @return {null}
   */
  removeComponentByKey(key, fn) {
    const comp = this.getComponent(key, (component, components) => {
      this.removeComponent(component, components);
      if (fn) {
        fn(component, components);
      }
    });
    if (!comp) {
      if (fn) {
        fn(null);
      }
      return null;
    }
  }

  /**
   * Removes a component provided the Id of the component.
   *
   * @param {string} id - The Id of the component to remove.
   * @param {function} fn - Called when the component is removed.
   * @return {null}
   */
  removeComponentById(id, fn) {
    const comp = this.getComponentById(id, (component, components) => {
      this.removeComponent(component, components);
      if (fn) {
        fn(component, components);
      }
    });
    if (!comp) {
      if (fn) {
        fn(null);
      }
      return null;
    }
  }

  updateValue(flags) {
    let changed = false;
    _.each(this.components, (comp) => {
      changed |= comp.updateValue(flags);
    });
    return changed;
  }

  hasChanged() {
    return false;
  }

  /**
   * A more performant way to check the conditions, calculations, and validity of
   * a submission once it has been changed.
   *
   * @param data
   * @param flags
   */
  checkData(data, flags) {
    flags = flags || {};
    let valid = true;
    if (flags.noCheck) {
      return;
    }

    // Update the value.
    let changed = this.updateValue({
      noUpdateEvent: true
    });

    // Iterate through all components and check conditions, and calculate values.
    _.each(this.getComponents(), (comp) => {
      changed |= comp.calculateValue(data, {
        noUpdateEvent: true
      });
      comp.checkConditions(data);
      if (!flags.noValidate) {
        valid &= comp.checkValidity(data);
      }
    });

    // Trigger the change if the values changed.
    if (changed) {
      this.triggerChange(flags);
    }

    // Return if the value is valid.
    return valid;
  }

  checkConditions(data) {
    this.getComponents().forEach(comp => comp.checkConditions(data));
    return super.checkConditions(data);
  }

  clearOnHide(show) {
    super.clearOnHide(show);
    this.getComponents().forEach(component => component.clearOnHide(show));
  }

  /**
   * Allow components to hook into the next page trigger to perform their own logic.
   *
   * @return {*}
   */
  beforeNext() {
    const ops = [];
    _.each(this.getComponents(), (comp) => ops.push(comp.beforeNext()));
    return Promise.all(ops);
  }

  /**
   * Allow components to hook into the submission to provide their own async data.
   *
   * @return {*}
   */
  beforeSubmit() {
    const ops = [];
    _.each(this.getComponents(), (comp) => ops.push(comp.beforeSubmit()));
    return Promise.all(ops);
  }

  calculateValue(data, flags) {
    let changed = super.calculateValue(data, flags);
    _.each(this.getComponents(), (comp) => {
      changed |= comp.calculateValue(data, flags);
    });
    return changed;
  }

  isValid(data, dirty) {
    let valid = super.isValid(data, dirty);
    _.each(this.getComponents(), (comp) => {
      valid &= comp.isValid(data, dirty);
    });
    return valid;
  }

  checkValidity(data, dirty) {
    if (!checkCondition(this.component, data, this.data, this.root ? this.root._form : {}, this)) {
      this.setCustomValidity('');
      return true;
    }

    let check = super.checkValidity(data, dirty);
    _.each(this.getComponents(), (comp) => {
      check &= comp.checkValidity(data, dirty);
    });
    return check;
  }

  setPristine(pristine) {
    super.setPristine(pristine);
    _.each(this.getComponents(), (comp) => (comp.setPristine(pristine)));
  }

  detach() {
    this.components.forEach(component => {
      component.detach();
    });
    super.detach();
  }

  destroy() {
    this.destroyComponents();
    super.destroy();
  }

  destroyComponents() {
    const components = _.clone(this.components);
    _.each(components, (comp) => this.removeComponent(comp, this.components));
    this.components = [];
  }

  setCustomValidity(message, dirty) {
    super.setCustomValidity(message, dirty);
    _.each(this.getComponents(), (comp) => comp.setCustomValidity(message, dirty));
  }

  set disabled(disabled) {
    _.each(this.components, (component) => (component.disabled = disabled));
  }

  get errors() {
    let errors = [];
    _.each(this.getAllComponents(), (comp) => {
      const compErrors = comp.errors;
      if (compErrors.length) {
        errors = errors.concat(compErrors);
      }
    });
    return errors;
  }

  get value() {
    return this.data;
  }

  getValue() {
    return this.data;
  }

  resetValue() {
    _.each(this.getComponents(), (comp) => (comp.resetValue()));
    _.unset(this.data, this.key);
    this.setPristine(true);
  }

  setValue(value, flags) {
    if (!value) {
      return false;
    }
    flags = this.getFlags.apply(this, arguments);
    let changed = false;
    this.getComponents().forEach(component => {
      if (component.type === 'button') {
        return;
      }

      if (component.type === 'components') {
        changed |= component.setValue(value, flags);
      }
      else if (value && component.hasValue(value)) {
        changed |= component.setValue(_.get(value, component.key), flags);
      }
      else {
        flags.noValidate = true;
        changed |= component.setValue(component.defaultValue, flags);
      }
    });
    return changed;
  }
}
<commit_msg>Fixed the clear on hide for hidden fields.<commit_after>'use strict';
import _ from 'lodash';
import Promise from 'native-promise-only';
import { checkCondition } from '../../../utils/utils';
import Component from '../component/Component';
import Components from '../../Components';

export default class NestedComponent extends Component {
  static schema(...extend) {
    return Component.schema({
      tree: true
    }, ...extend);
  }

  constructor(component, options, data) {
    super(component, options, data);
    this.type = 'components';
    this._collapsed = !!this.component.collapsed;
    this.components = [];
  }

  get defaultSchema() {
    return NestedComponent.schema();
  }

  get schema() {
    const schema = super.schema;
    schema.components = [];
    this.eachComponent((component) => schema.components.push(component.schema));
    return schema;
  }

  get collapsed() {
    return this._collapsed;
  }

  set collapsed(value) {
    this._collapsed = value;
    this.redraw();
  }

  set visible(value) {
    super.visible = value;
    const isVisible = this.visible;
    const forceShow = this.options.show && this.options.show[this.component.key];
    const forceHide = this.options.hide && this.options.hide[this.component.key];
    this.components.forEach(component => {
      let conditionallyVisible = component.conditionallyVisible();
      if (forceShow || (!isVisible && conditionallyVisible)) {
        component.visible = true;
      }
      else if (forceHide || (isVisible && !conditionallyVisible)) {
        component.visible = false;
      }
      component.parentVisible = isVisible;
    });
  }

  get visible() {
    return super.visible;
  }

  set parentVisible(value) {
    super.parentVisible = value;
    this.components.forEach(component => {
      component.parentVisible = this.visible;
    });
  }

  get parentVisible() {
    return super.parentVisible;
  }

  getComponents() {
    return this.components || [];
  }

  getAllComponents() {
    return this.getComponents().reduce((components, component) => {
      let result = component;

      if (component.getAllComponents) {
        result = component.getAllComponents();
      }

      return components.concat(result);
    }, []);
  }

  /**
   * Perform a deep iteration over every component, including those
   * within other container based components.
   *
   * @param {function} fn - Called for every component.
   */
  everyComponent(fn) {
    const components = this.getComponents();
    _.each(components, (component, index) => {
      if (fn(component, components, index) === false) {
        return false;
      }

      if (typeof component.everyComponent === 'function') {
        if (component.everyComponent(fn) === false) {
          return false;
        }
      }
    });
  }

  /**
   * Perform an iteration over each component within this container component.
   *
   * @param {function} fn - Called for each component
   */
  eachComponent(fn) {
    _.each(this.getComponents(), (component, index) => {
      if (fn(component, index) === false) {
        return false;
      }
    });
  }

  /**
   * Returns a component provided a key. This performs a deep search within the
   * component tree.
   *
   * @param {string} key - The key of the component to retrieve.
   * @param {function} fn - Called with the component once found.
   * @return {Object} - The component that is located.
   */
  getComponent(key, fn) {
    let comp = null;
    this.everyComponent((component, components) => {
      if (component.component.key === key) {
        comp = component;
        if (fn) {
          fn(component, components);
        }
        return false;
      }
    });
    return comp;
  }

  /**
   * Return a component provided the Id of the component.
   *
   * @param {string} id - The Id of the component.
   * @param {function} fn - Called with the component once it is retrieved.
   * @return {Object} - The component retrieved.
   */
  getComponentById(id, fn) {
    let comp = null;
    this.everyComponent((component, components) => {
      if (component.id === id) {
        comp = component;
        if (fn) {
          fn(component, components);
        }
        return false;
      }
    });
    return comp;
  }

  /**
   * Create a new component and add it to the components array.
   *
   * @param component
   * @param data
   */
  createComponent(component, options, data, before) {
    options = options || this.options;
    data = data || this.data;
    const comp = Components.create(component, options, data, true);
    comp.parent = this;
    comp.root = this.root || this;
    comp.parentVisible = this.visible;
    comp.isBuilt = true;
    if (component.internal) {
      return comp;
    }

    if (before) {
      const index = _.findIndex(this.components, { id: before.id });
      if (index !== -1) {
        this.components.splice(index, 0, comp);
      }
      else {
        this.components.push(comp);
      }
    }
    else {
      this.components.push(comp);
    }
    return comp;
  }

  getContainer() {
    return this.element;
  }

  get componentComponents() {
    return this.component.components || [];
  }

  get nestedKey() {
    return `nested-${this.key}`;
  }

  get templateName() {
    return 'container';
  }

  init() {
    this.components = this.components || [];
    this.addComponents();
  }

  /**
   *
   * @param element
   * @param data
   */
  addComponents(data) {
    data = data || this.data;
    this.componentComponents.forEach((component) => this.addComponent(component, data));
  }

  /**
   * Add a new component to the components array.
   *
   * @param {Object} component - The component JSON schema to add.
   * @param {Object} data - The submission data object to house the data for this component.
   * @param {HTMLElement} before - A DOM element to insert this element before.
   * @return {Component} - The created component instance.
   */
  addComponent(component, data, before, noAdd) {
    data = data || this.data;
    const comp = this.createComponent(component, this.options, data, before ? before.component : null);
    if (noAdd) {
      return comp;
    }
    return comp;
  }

  render(children) {
    // If already rendering, don't re-render.
    return super.render(children || this.renderTemplate(this.templateName, {
      children: this.renderComponents(),
      nestedKey: this.nestedKey,
      collapsed: this.collapsed,
    }));
  }

  renderComponents(components) {
    components = components || this.components;
    const children = components.map(component => component.render());
    return this.renderTemplate('components', {
      children,
      components,
    });
  }

  attach(element) {
    this.loadRefs(element, {
      header: 'single',
      collapsed: this.collapsed,
      [this.nestedKey]: 'single',
    });

    if (this.refs[this.nestedKey]) {
      this.attachComponents(this.refs[this.nestedKey]);
    }

    if (this.component.collapsible && this.refs.header) {
      this.addEventListener(this.refs.header, 'click', () => {
        this.collapsed = !this.collapsed;
      });
    }

    super.attach(element);
  }

  attachComponents(element, components, container) {
    components = components || this.components;
    container = container || this.component.components;

    element = this.hook('attachComponents', element, components, container, this);
    if (!element) {
      return;
    }

    let index = 0;
    Array.prototype.slice.call(element.children).forEach(child => {
      if (!child.getAttribute('data-noattach') && components[index]) {
        components[index].attach(child);
        index++;
      }
    });
  }

  /**
   * Remove a component from the components array.
   *
   * @param {Component} component - The component to remove from the components.
   * @param {Array<Component>} components - An array of components to remove this component from.
   */
  removeComponent(component, components) {
    component.destroy();
    _.remove(components, { id: component.id });
  }

  /**
   * Removes a component provided the API key of that component.
   *
   * @param {string} key - The API key of the component to remove.
   * @param {function} fn - Called once the component is removed.
   * @return {null}
   */
  removeComponentByKey(key, fn) {
    const comp = this.getComponent(key, (component, components) => {
      this.removeComponent(component, components);
      if (fn) {
        fn(component, components);
      }
    });
    if (!comp) {
      if (fn) {
        fn(null);
      }
      return null;
    }
  }

  /**
   * Removes a component provided the Id of the component.
   *
   * @param {string} id - The Id of the component to remove.
   * @param {function} fn - Called when the component is removed.
   * @return {null}
   */
  removeComponentById(id, fn) {
    const comp = this.getComponentById(id, (component, components) => {
      this.removeComponent(component, components);
      if (fn) {
        fn(component, components);
      }
    });
    if (!comp) {
      if (fn) {
        fn(null);
      }
      return null;
    }
  }

  updateValue(flags) {
    let changed = false;
    _.each(this.components, (comp) => {
      changed |= comp.updateValue(flags);
    });
    return changed;
  }

  hasChanged() {
    return false;
  }

  /**
   * A more performant way to check the conditions, calculations, and validity of
   * a submission once it has been changed.
   *
   * @param data
   * @param flags
   */
  checkData(data, flags) {
    flags = flags || {};
    let valid = true;
    if (flags.noCheck) {
      return;
    }

    // Update the value.
    let changed = this.updateValue({
      noUpdateEvent: true
    });

    // Iterate through all components and check conditions, and calculate values.
    _.each(this.getComponents(), (comp) => {
      changed |= comp.calculateValue(data, {
        noUpdateEvent: true
      });
      comp.checkConditions(data);
      if (!flags.noValidate) {
        valid &= comp.checkValidity(data);
      }
    });

    // Trigger the change if the values changed.
    if (changed) {
      this.triggerChange(flags);
    }

    // Return if the value is valid.
    return valid;
  }

  checkConditions(data) {
    this.getComponents().forEach(comp => comp.checkConditions(data));
    return super.checkConditions(data);
  }

  clearOnHide(show) {
    super.clearOnHide(show);
    this.getComponents().forEach(component => component.clearOnHide(show));
  }

  /**
   * Allow components to hook into the next page trigger to perform their own logic.
   *
   * @return {*}
   */
  beforeNext() {
    const ops = [];
    _.each(this.getComponents(), (comp) => ops.push(comp.beforeNext()));
    return Promise.all(ops);
  }

  /**
   * Allow components to hook into the submission to provide their own async data.
   *
   * @return {*}
   */
  beforeSubmit() {
    const ops = [];
    _.each(this.getComponents(), (comp) => ops.push(comp.beforeSubmit()));
    return Promise.all(ops);
  }

  calculateValue(data, flags) {
    let changed = super.calculateValue(data, flags);
    _.each(this.getComponents(), (comp) => {
      changed |= comp.calculateValue(data, flags);
    });
    return changed;
  }

  isValid(data, dirty) {
    let valid = super.isValid(data, dirty);
    _.each(this.getComponents(), (comp) => {
      valid &= comp.isValid(data, dirty);
    });
    return valid;
  }

  checkValidity(data, dirty) {
    if (!checkCondition(this.component, data, this.data, this.root ? this.root._form : {}, this)) {
      this.setCustomValidity('');
      return true;
    }

    let check = super.checkValidity(data, dirty);
    _.each(this.getComponents(), (comp) => {
      check &= comp.checkValidity(data, dirty);
    });
    return check;
  }

  setPristine(pristine) {
    super.setPristine(pristine);
    _.each(this.getComponents(), (comp) => (comp.setPristine(pristine)));
  }

  detach() {
    this.components.forEach(component => {
      component.detach();
    });
    super.detach();
  }

  destroy() {
    this.destroyComponents();
    super.destroy();
  }

  destroyComponents() {
    const components = _.clone(this.components);
    _.each(components, (comp) => this.removeComponent(comp, this.components));
    this.components = [];
  }

  setCustomValidity(message, dirty) {
    super.setCustomValidity(message, dirty);
    _.each(this.getComponents(), (comp) => comp.setCustomValidity(message, dirty));
  }

  set disabled(disabled) {
    _.each(this.components, (component) => (component.disabled = disabled));
  }

  get errors() {
    let errors = [];
    _.each(this.getAllComponents(), (comp) => {
      const compErrors = comp.errors;
      if (compErrors.length) {
        errors = errors.concat(compErrors);
      }
    });
    return errors;
  }

  get value() {
    return this.data;
  }

  getValue() {
    return this.data;
  }

  resetValue() {
    _.each(this.getComponents(), (comp) => (comp.resetValue()));
    _.unset(this.data, this.key);
    this.setPristine(true);
  }

  setValue(value, flags) {
    if (!value) {
      return false;
    }
    flags = this.getFlags.apply(this, arguments);
    let changed = false;
    this.getComponents().forEach(component => {
      if (component.type === 'button') {
        return;
      }

      if (component.type === 'components') {
        changed |= component.setValue(value, flags);
      }
      else if (value && component.hasValue(value)) {
        changed |= component.setValue(_.get(value, component.key), flags);
      }
      else {
        flags.noValidate = true;
        changed |= component.setValue(component.defaultValue, flags);
      }
    });
    return changed;
  }
}
<|endoftext|>


<commit_before>'use strict';

var Promise = require('ember-cli/lib/ext/promise');
var _       = require('lodash-node');

var chalk = require('chalk');
var blue  = chalk.blue;
var red   = chalk.red;
var grey  = chalk.grey;

function Pipeline(hookNames, options) {
  hookNames = hookNames || [];
  options = options || {};

  this._ui = options.ui;

  this._pipelineHooks = hookNames.reduce(function(pipelineHooks, hookName) {
    pipelineHooks[hookName] = [];

    return pipelineHooks;
  }, {});
}

Pipeline.prototype.register = function(hookName, fn) {
  var ui            = this._ui;
  var pipelineHooks = this._pipelineHooks;

  if (typeof fn === 'function') {
    fn = {
      name: 'anonymous function',
      fn: fn
    };
  }

  ui.write(blue('Registering hook -> ' + hookName + '[' + fn.name + ']\n'));

  if (pipelineHooks[hookName]) {
    pipelineHooks[hookName].push(fn);
  }
};

Pipeline.prototype.execute = function(context) {
  context = context || { };

  var ui            = this._ui;
  var pipelineHooks = this._pipelineHooks;
  var hookNames     = Object.keys(pipelineHooks);

  ui.write(blue('Executing pipeline\n'));

  return hookNames.reduce(function(promise, hookName) {
    return promise
      .then(function(context) {
        ui.write(blue('|\n'));
        ui.write(blue('+- ' + hookName + '\n'));

        return context;
      })
      .then(this._executeHook.bind(this, hookName));
  }.bind(this), Promise.resolve(context))
    .then(function() {
      ui.write(blue('|\n'));
      ui.write(blue('Pipeline complete\n'));
    })
    .catch(function(error) {
      ui.write(blue('|\n'));
      ui.write(red('Pipeline aborted\n'));
      return Promise.reject();
    });
};

Pipeline.prototype._executeHook = function(hookName, context) {
  var ui            = this._ui;
  var hookFunctions = this._pipelineHooks[hookName];

  return hookFunctions.reduce(function(promise, fnObject) {
    return promise
      .then(function(context) {
        ui.write(blue('|  |\n'));
        ui.write(blue('|  +- ' + fnObject.name + '\n'));
        return fnObject.fn(context);
      })
      .then(function(result) {
        return _.merge(context, result);
      })
  }, Promise.resolve(context));
}

module.exports = Pipeline;
<commit_msg>Fixed bug where merging was overwriting the array elements of distFiles<commit_after>'use strict';

var Promise = require('ember-cli/lib/ext/promise');
var _       = require('lodash-node');

var chalk = require('chalk');
var blue  = chalk.blue;
var red   = chalk.red;
var grey  = chalk.grey;

function Pipeline(hookNames, options) {
  hookNames = hookNames || [];
  options = options || {};

  this._ui = options.ui;

  this._pipelineHooks = hookNames.reduce(function(pipelineHooks, hookName) {
    pipelineHooks[hookName] = [];

    return pipelineHooks;
  }, {});
}

Pipeline.prototype.register = function(hookName, fn) {
  var ui            = this._ui;
  var pipelineHooks = this._pipelineHooks;

  if (typeof fn === 'function') {
    fn = {
      name: 'anonymous function',
      fn: fn
    };
  }

  ui.write(blue('Registering hook -> ' + hookName + '[' + fn.name + ']\n'));

  if (pipelineHooks[hookName]) {
    pipelineHooks[hookName].push(fn);
  }
};

Pipeline.prototype.execute = function(context) {
  context = context || { };

  var ui            = this._ui;
  var pipelineHooks = this._pipelineHooks;
  var hookNames     = Object.keys(pipelineHooks);

  ui.write(blue('Executing pipeline\n'));

  return hookNames.reduce(function(promise, hookName) {
    return promise
      .then(function(context) {
        ui.write(blue('|\n'));
        ui.write(blue('+- ' + hookName + '\n'));

        return context;
      })
      .then(this._executeHook.bind(this, hookName));
  }.bind(this), Promise.resolve(context))
    .then(function() {
      ui.write(blue('|\n'));
      ui.write(blue('Pipeline complete\n'));
    })
    .catch(function(error) {
      ui.write(blue('|\n'));
      ui.write(red('Pipeline aborted\n'));
      return Promise.reject();
    });
};

Pipeline.prototype._executeHook = function(hookName, context) {
  var ui            = this._ui;
  var hookFunctions = this._pipelineHooks[hookName];

  return hookFunctions.reduce(function(promise, fnObject) {
    return promise
      .then(function(context) {
        ui.write(blue('|  |\n'));
        ui.write(blue('|  +- ' + fnObject.name + '\n'));
        return fnObject.fn(context);
      })
      .then(function(result) {
        return _.merge(context, result, function(a, b) {
          if (_.isArray(a)) {
            return a.concat(b);
          }
        });
      })
  }, Promise.resolve(context));
}

module.exports = Pipeline;
<|endoftext|>


<commit_before>const Promise = require('bluebird');

const server = require('./../../server.js');

const service = {
  addAddresses: (addresses, timestamp, latitude, longitude) => {
    const DEFAULT_ID = {
      name: '00:00:00:00:00:00',
      timestamp: '2017-01-01T00:00:00.000Z',
      latitude: 33.9698,
      longitude: -118.4169,
    };
    return Promise.map(addresses, (client) => {
      const data = DEFAULT_ID;
      data.name = client || data.name;
      data.timestamp = timestamp || data.timestamp;
      data.latitude = latitude || data.latitude;
      data.longitude = longitude || data.longitude;

      return server.sequelize.models.Identifier.create(data);
    });
  },
};

module.exports = service;
<commit_msg>Added Address counting in range<commit_after>const Promise = require('bluebird');
const Moment = require('moment');

const server = require('./../../server.js');

const Models = server.sequelize.models;
const SIdentifier = Models.Identifier;

const service = {
  addAddresses: (addresses, timestamp, latitude, longitude) => {
    const DEFAULT_ID = {
      name: '00:00:00:00:00:00',
      timestamp: '2017-01-01T00:00:00.000Z',
      latitude: 33.9698,
      longitude: -118.4169,
    };
    return Promise.map(addresses, (client) => {
      const data = DEFAULT_ID;
      data.name = client || data.name;
      data.timestamp = timestamp || data.timestamp;
      data.latitude = latitude || data.latitude;
      data.longitude = longitude || data.longitude;

      return SIdentifier.create(data);
    });
  },
  getAddressesWithinRange: (options) => {
    const DEFAULT_OPTIONS = {
      latitudeMin: 33.9668,
      latitudeMax: 33.9728,
      longitudeMin: -118.4199,
      longitudeMax: -118.4139,
    };

    // Make sure to look at R-Tree indexing for optimization
    const findValue = (optimal, partial1, partial2, last) => {
      if (optimal) {
        return optimal;
      } else if (partial1 && partial2) {
        return partial1 + partial2;
      }
      return last;
    };
    const latitudeMin = findValue(options.latitudeMin,
      options.latitude,
      0 - options.radius,
      DEFAULT_OPTIONS.latitudeMin);
    const latitudeMax = findValue(options.latitudeMax,
      options.latitude,
      options.radius,
      DEFAULT_OPTIONS.latitudeMax);
    const longitudeMin = findValue(options.longitudeMin,
      options.longitude,
      0 - options.radius,
      DEFAULT_OPTIONS.longitudeMin);
    const longitudeMax = findValue(options.longitudeMax,
      options.longitude,
      options.radius,
      DEFAULT_OPTIONS.longitudeMax);
    const start = options.start || Moment().subtract(1, 'hours').toISOString();
    const end = options.end || Moment().toISOString();

    return SIdentifier.aggregate('name', 'count', {
      distinct: true,
      where: {
        latitude: {
          $gte: latitudeMin,
          $lte: latitudeMax,
        },
        longitude: {
          $gte: longitudeMin,
          $lte: longitudeMax,
        },
        timestamp: {
          $gte: start,
          $lte: end,
        },
      },
    });
  },
};

module.exports = service;
<|endoftext|>


<commit_before>var remote = {
  host: 'localhost:1234'
};

module('attachments', {
  setup : function () {
    this.name = 'idb://test_suite_db';
    this.remote = 'http://' + remote.host + '/test_suite_db/';
    //this.name = this.remote;
  }
});

var binAttDoc = {
  _id: "bin_doc",
  _attachments:{
    "foo.txt": {
      content_type:"text/plain",
      data: "VGhpcyBpcyBhIGJhc2U2NCBlbmNvZGVkIHRleHQ="
    }
  }
};

// empty attachment
var binAttDoc2 = {
  _id: "bin_doc2",
  _attachments:{
    "foo.txt": {
      content_type:"text/plain",
      data: ""
    }
  }
}

asyncTest("Test some attachments", function() {
  var db;
  initTestDB(this.name, function(err, _db) {
    db = _db;
    db.put(binAttDoc, function(err, write) {
      ok(!err, 'saved doc with attachment');
      db.get('bin_doc/foo.txt', function(err, res) {
        ok(res === 'This is a base64 encoded text', 'Correct data returned');
        db.put(binAttDoc2, function(err, rev) {
          db.get('bin_doc2/foo.txt', function(err, res, xhr) {
            ok(res === '', 'Correct data returned');
            moreTests(rev.rev);
           });
        });
      });
    });
  });

  function moreTests(rev) {
    var ndoc = 'This is no base64 encoded text';
    db.putAttachment('bin_doc2/foo2.txt', rev, ndoc, "text/plain", function() {
      db.get('bin_doc2/foo2.txt', function(err, res, xhr) {
        ok(res === 'This is no base64 encoded text', 'Correct data returned');
        start();
      });
    });
  };

});
<commit_msg>Test attachments over both idb + http adapters<commit_after>['idb-1', 'http-1'].map(function(adapter) {

  module('attachments: ' + adapter, {
    setup : function () {
      this.name = generateAdapterUrl(adapter);
    }
  });

  var binAttDoc = {
    _id: "bin_doc",
    _attachments:{
      "foo.txt": {
        content_type:"text/plain",
        data: "VGhpcyBpcyBhIGJhc2U2NCBlbmNvZGVkIHRleHQ="
      }
    }
  };

  // empty attachment
  var binAttDoc2 = {
    _id: "bin_doc2",
    _attachments:{
      "foo.txt": {
        content_type:"text/plain",
        data: ""
      }
    }
  }

  asyncTest("Test some attachments", function() {
    var db;
    initTestDB(this.name, function(err, _db) {
      db = _db;
      db.put(binAttDoc, function(err, write) {
        ok(!err, 'saved doc with attachment');
        db.get('bin_doc/foo.txt', function(err, res) {
          console.log(arguments);
          ok(res === 'This is a base64 encoded text', 'Correct data returned');
          db.put(binAttDoc2, function(err, rev) {
            db.get('bin_doc2/foo.txt', function(err, res, xhr) {
              ok(res === '', 'Correct data returned');
              moreTests(rev.rev);
            });
          });
        });
      });
    });

    function moreTests(rev) {
      var ndoc = 'This is no base64 encoded text';
      db.putAttachment('bin_doc2/foo2.txt', rev, ndoc, "text/plain", function() {
        db.get('bin_doc2/foo2.txt', function(err, res, xhr) {
          ok(res === 'This is no base64 encoded text', 'Correct data returned');
          start();
        });
      });
    };

  });

});<|endoftext|>