<commit_before>/**
 * @overview ccm component for commenting
 * @author Tea Kless <tea.kless@web.de>, 2017
 * @license The MIT License (MIT)
 */

( function () {

  var component = {

    name: 'comment',
    version: '1.0.0',

    ccm: {
      url: 'https://akless.github.io/ccm/version/ccm-10.0.0.min.js',
      integrity: 'sha384-bCcBv9yCHVcXtsHxkfPcFeT+j77G112ZADZ1DkxcYdxjflPG4lTiiFiB3Jp+c2NG',
      crossorigin: 'anonymous'
    },

    config: {
      templates: {
        "main": {
          "class": "container",
          "inner": [
            {
              "id": "comment-list",
              "class": "row"
            },
            {
              "tag": "form",
              "class": "row",
              "inner": [
                {
                  "id": "new-comment",
                  "inner": [
                    {
                      "tag": "button",
                      "type": "button",
                      "class": "btn btn-default btn-xs",
                      "onclick": "%render_editor%",
                      "inner": [
                        {
                          "tag": "span",
                          "class": "glyphicon glyphicon-plus-sign",
                          "aria-hidden": "true"
                        },
                        " add comment"
                      ]
                    }
                  ]
                }
              ]
            }
          ]
        },
        "editor":{
          "inner": [
            {
              "class": "row form-group",
              "inner":
                {
                  "class": "container-fluid",
                  "id": "editor"
                }
            },
            {
              "class": "row",
              "id": "add-comment",
              "inner": [
                {
                  "tag": "button",
                  "type": "button",
                  "class": "btn btn-default btn-xs",
                  "onclick": "%add_comment%",
                  "inner": " add comment"
                }
              ]
            }
          ]
        },
        "voting_overview": {
          "class": "voting_overview row",
          "inner": [
            {
              "class": "col-md-12",
              "inner": "%get_voting%"
            },
            {
              "class": "col-md-12",
              "inner": "votes"
            }
          ]
        },
        "simple_comment": {
          "inner": [
            {
              "class": "row comment-item",
              "inner": [
                {
                  "class": "col-md-1 col-xs-1 voting-area"
                },
                {
                  "class": "col-md-11 col-xs-11 comment-overview",
                  "inner": [
                    "%comment_content% - ",
                    {
                      "tag": "span",
                      "class": "sub-text",
                      "inner": [
                        {
                          "tag": "span",
                          "class": "glyphicon glyphicon-user",
                          "aria-hidden": "true"
                        },
                        " %user% ",
                        {
                          "tag": "span",
                          "class": "glyphicon glyphicon-time",
                          "aria-hidden": "true"
                        },
                        " %date% "
                      ]
                    }
                  ]
                }

              ]
            },
            {
              "tag": "hr",
              "class": "row"
            }
          ]
        },
        "expand_comment": {}
      },

      sorting_by_voting: true,
      comment_template: 'simple', // or expand
      data: {
        store: [ 'ccm.store', '../comment/comment_datastore.js' ],
        key: 'demo'
      },
      user:  [ 'ccm.instance', 'https://akless.github.io/ccm-components/user/ccm.user.min.js' ], //{ logged_in: true, 'guest.user': 'tmeskh2s' } ],
      editor: [ 'ccm.component', '../editor/ccm.editor.js',
        { 'settings.modules.toolbar': false },
        { 'settings.placeholder': 'Write your comment here ...' }

      ],
      voting: [ "ccm.component", "../voting/ccm.voting.js", {
        icon_likes: 'fa fa-lg fa-chevron-up',
        icon_dislikes: 'fa fa-lg fa-chevron-down',
        data: {
          store: [ 'ccm.store', '../voting/voting_datastore.js' ]
        }
      } ],

      libs: [ 'ccm.load', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css',
        '../comment/style.css',
        'https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js',
        { context: 'head', url: 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css' } ]
    },

    Instance: function () {
      var self = this;
      var editor;
      var dataset;

      this.init = function ( callback ) {

        // listen to change event of ccm realtime datastore => (re)render own content
        self.data.store.onChange = function ( question ) {
          dataset = question;
          self.start();
        };

        callback();
      };

      this.start = function ( callback ) {

        self.ccm.helper.dataset( self.data.store, self.data.key, function ( dataset ) {
          if ( !dataset.comments ) dataset.comments = [];

          var main_elem = self.ccm.helper.html( self.templates.main, {
            render_editor: function () {
              self.element.querySelector( '#new-comment' ).classList.add( 'fade-comment' );
              renderEditor();
            }
          } );

          renderComments();

          function renderComments() {
            var unsorted_comments = [];

            main_elem.querySelector( '#comment-list').innerHTML = '';

            var counter = 1;
            //asynchronous problem
            dataset.comments.map( renderComment );
            check();

            // waiting: all comments and their voting ist put in on-the-fly object
            function check() {
              counter--;
              if( counter > 0 ) return;

              if ( self.sorting_by_voting )
                unsorted_comments.sort( compare );

              unsorted_comments.map( function ( entry ) {
                // prepend element to DOM
                self.ccm.helper.prepend( main_elem.querySelector( '#comment-list' ), entry.comment );
              });

              self.ccm.helper.setContent( self.element, main_elem );
              if ( callback ) callback();

              function compare( a, b ) {
                if ( a.voting < b.voting )
                  return -1;
                if ( a.voting > b.voting )
                  return 1;
                return a.date.localeCompare( b.date );
              }

            }

            function renderComment( comment ) {
              var comment_elem;

              if( self.comment_template === 'simple' ) {
                // generate on-the-fly element
                comment_elem = self.ccm.helper.html( self.templates.simple_comment, {
                  comment_content: comment.content,
                  user: comment.user,
                  date: moment( comment.date ).fromNow()
                });
              }

              //if voting is set then render voting-component
              if ( self.voting )
                renderVoting( comment.voting );

              function renderVoting( voting ) {

                counter++;

                if ( self.user.isLoggedIn() && (comment.user === self.user.data().user) )
                  voting.user = '';

                self.voting.start( voting, function ( voting_inst ) {
                  // fill array for sorting
                  unsorted_comments.push( { "voting": voting_inst.getVoting(), "comment": comment_elem, "date": comment.date } );
                  comment_elem.querySelector( '.voting-area' ).appendChild( voting_inst.root );
                  check();
                } );
              }
            }
          }

          function renderEditor() {
            if ( !self.user ) return;

            self.element.querySelector( '#new-comment' ).innerHTML = '';

            var editor_elem = self.ccm.helper.html( self.templates.editor, {
              add_comment: function () { newComment() }
            } );

            self.user.login( function () {
              self.editor.start( function (instance) {
                editor_elem.querySelector( '#editor' ).appendChild( instance.root );
                editor = instance
              } );
            });

            self.element.querySelector( '#new-comment' ).appendChild( editor_elem );
          }

          function newComment() {

            dataset.comments.push(
              {
                "user": self.user.data().user,
                "date": moment().format(),
                "content": editor.get().getText(),
                "voting": { 'data.key': dataset.key + '-' + dataset.comments.length + 1 }
              } );

            // update dataset for rendering => (re)render accepted answer
            self.data.store.set( dataset, function () { self.start() } );
          }

        } );
      };
    }
  };

  function p(){window.ccm[v].component(component)}var f="ccm."+component.name+(component.version?"-"+component.version.join("."):"")+".js";if(window.ccm&&null===window.ccm.files[f])window.ccm.files[f]=component;else{var n=window.ccm&&window.ccm.components[component.name];n&&n.ccm&&(component.ccm=n.ccm),"string"==typeof component.ccm&&(component.ccm={url:component.ccm});var v=component.ccm.url.split("/").pop().split("-");if(v.length>1?(v=v[1].split("."),v.pop(),"min"===v[v.length-1]&&v.pop(),v=v.join(".")):v="latest",window.ccm&&window.ccm[v])p();else{var e=document.createElement("script");document.head.appendChild(e),component.ccm.integrity&&e.setAttribute("integrity",component.ccm.integrity),component.ccm.crossorigin&&e.setAttribute("crossorigin",component.ccm.crossorigin),e.onload=function(){p(),document.head.removeChild(e)},e.src=component.ccm.url}}
}() );<commit_msg>update comment component<commit_after>/**
 * @overview ccm component for commenting
 * @author Tea Kless <tea.kless@web.de>, 2017
 * @license The MIT License (MIT)
 */

( function () {

  var component = {

    name: 'comment',
    version: [ 1,0,0 ],

    ccm: {
      url: 'https://akless.github.io/ccm/version/ccm-10.0.0.min.js',
      integrity: 'sha384-bCcBv9yCHVcXtsHxkfPcFeT+j77G112ZADZ1DkxcYdxjflPG4lTiiFiB3Jp+c2NG',
      crossorigin: 'anonymous'
    },

    config: {
      templates: {
        "main": {
          "class": "container",
          "inner": [
            {
              "id": "comment-list",
              "class": "row"
            },
            {
              "tag": "form",
              "class": "row",
              "inner": [
                {
                  "id": "new-comment",
                  "inner": [
                    {
                      "tag": "button",
                      "type": "button",
                      "class": "btn btn-default btn-xs",
                      "onclick": "%render_editor%",
                      "inner": [
                        {
                          "tag": "span",
                          "class": "glyphicon glyphicon-plus-sign",
                          "aria-hidden": "true"
                        },
                        " add comment"
                      ]
                    }
                  ]
                }
              ]
            }
          ]
        },
        "editor":{
          "inner": [
            {
              "class": "row form-group",
              "inner":
                {
                  "class": "container-fluid",
                  "id": "editor"
                }
            },
            {
              "class": "row",
              "id": "add-comment",
              "inner": [
                {
                  "tag": "button",
                  "type": "button",
                  "class": "btn btn-default btn-xs",
                  "onclick": "%add_comment%",
                  "inner": " add comment"
                }
              ]
            }
          ]
        },
        "voting_overview": {
          "class": "voting_overview row",
          "inner": [
            {
              "class": "col-md-12",
              "inner": "%get_voting%"
            },
            {
              "class": "col-md-12",
              "inner": "votes"
            }
          ]
        },
        "simple_comment": {
          "inner": [
            {
              "class": "row comment-item",
              "inner": [
                {
                  "class": "col-md-1 col-xs-1 voting-area"
                },
                {
                  "class": "col-md-11 col-xs-11 comment-overview",
                  "inner": [
                    "%comment_content% - ",
                    {
                      "tag": "span",
                      "class": "sub-text",
                      "inner": [
                        {
                          "tag": "span",
                          "class": "glyphicon glyphicon-user",
                          "aria-hidden": "true"
                        },
                        " %user% ",
                        {
                          "tag": "span",
                          "class": "glyphicon glyphicon-time",
                          "aria-hidden": "true"
                        },
                        " %date% "
                      ]
                    }
                  ]
                }

              ]
            },
            {
              "tag": "hr",
              "class": "row"
            }
          ]
        },
        "expand_comment": {}
      },

      sorting_by_voting: true,
      comment_template: 'simple', // or expand
      data: {
        store: [ 'ccm.store', '../comment/comment_datastore.js' ],
        key: 'demo'
      },
      user:  [ 'ccm.instance', 'https://akless.github.io/ccm-components/user/ccm.user.min.js' ], //{ logged_in: true, 'guest.user': 'tmeskh2s' } ],
      editor: [ 'ccm.component', '../editor/ccm.editor.js',
        { 'settings.modules.toolbar': false },
        { 'settings.placeholder': 'Write your comment here ...' }

      ],
      voting: [ "ccm.component", "../voting/ccm.voting.js", {
        icon_likes: 'fa fa-lg fa-chevron-up',
        icon_dislikes: 'fa fa-lg fa-chevron-down',
        data: {
          store: [ 'ccm.store', '../voting/voting_datastore.js' ]
        }
      } ],

      libs: [ 'ccm.load', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css',
        '../comment/style.css',
        'https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js',
        { context: 'head', url: 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css' } ]
    },

    Instance: function () {
      var self = this;
      var editor;
      var dataset;

      this.init = function ( callback ) {

        // listen to change event of ccm realtime datastore => (re)render own content
        self.data.store.onChange = function ( question ) {
          dataset = question;
          self.start();
        };

        callback();
      };

      this.start = function ( callback ) {

        self.ccm.helper.dataset( self.data.store, self.data.key, function ( dataset ) {
          if ( !dataset.comments ) dataset.comments = [];

          var main_elem = self.ccm.helper.html( self.templates.main, {
            render_editor: function () {
              self.element.querySelector( '#new-comment' ).classList.add( 'fade-comment' );
              renderEditor();
            }
          } );

          renderComments();

          function renderComments() {
            var unsorted_comments = [];

            main_elem.querySelector( '#comment-list').innerHTML = '';

            var counter = 1;
            //asynchronous problem
            dataset.comments.map( renderComment );
            check();

            // waiting: all comments and their voting ist put in on-the-fly object
            function check() {
              counter--;
              if( counter > 0 ) return;

              if ( self.sorting_by_voting )
                unsorted_comments.sort( compare );

              unsorted_comments.map( function ( entry ) {
                // prepend element to DOM
                self.ccm.helper.prepend( main_elem.querySelector( '#comment-list' ), entry.comment );
              });

              self.ccm.helper.setContent( self.element, main_elem );
              if ( callback ) callback();

              function compare( a, b ) {
                if ( a.voting < b.voting )
                  return -1;
                if ( a.voting > b.voting )
                  return 1;
                return a.date.localeCompare( b.date );
              }

            }

            function renderComment( comment ) {
              var comment_elem;

              if( self.comment_template === 'simple' ) {
                // generate on-the-fly element
                comment_elem = self.ccm.helper.html( self.templates.simple_comment, {
                  comment_content: comment.content,
                  user: comment.user,
                  date: moment( comment.date ).fromNow()
                });
              }

              //if voting is set then render voting-component
              if ( self.voting )
                renderVoting( comment.voting );

              function renderVoting( voting ) {

                counter++;

                if ( self.user.isLoggedIn() && (comment.user === self.user.data().user) )
                  voting.user = '';

                self.voting.start( voting, function ( voting_inst ) {
                  // fill array for sorting
                  unsorted_comments.push( { "voting": voting_inst.getVoting(), "comment": comment_elem, "date": comment.date } );
                  comment_elem.querySelector( '.voting-area' ).appendChild( voting_inst.root );
                  check();
                } );
              }
            }
          }

          function renderEditor() {
            if ( !self.user ) return;

            self.element.querySelector( '#new-comment' ).innerHTML = '';

            var editor_elem = self.ccm.helper.html( self.templates.editor, {
              add_comment: function () { newComment() }
            } );

            self.user.login( function () {
              self.editor.start( function (instance) {
                editor_elem.querySelector( '#editor' ).appendChild( instance.root );
                editor = instance
              } );
            });

            self.element.querySelector( '#new-comment' ).appendChild( editor_elem );
          }

          function newComment() {

            dataset.comments.push(
              {
                "user": self.user.data().user,
                "date": moment().format(),
                "content": editor.get().getText(),
                "voting": { 'data.key': dataset.key + '-' + dataset.comments.length + 1 }
              } );

            // update dataset for rendering => (re)render accepted answer
            self.data.store.set( dataset, function () { self.start() } );
          }

        } );
      };
    }
  };

  function p(){window.ccm[v].component(component)}var f="ccm."+component.name+(component.version?"-"+component.version.join("."):"")+".js";if(window.ccm&&null===window.ccm.files[f])window.ccm.files[f]=component;else{var n=window.ccm&&window.ccm.components[component.name];n&&n.ccm&&(component.ccm=n.ccm),"string"==typeof component.ccm&&(component.ccm={url:component.ccm});var v=component.ccm.url.split("/").pop().split("-");if(v.length>1?(v=v[1].split("."),v.pop(),"min"===v[v.length-1]&&v.pop(),v=v.join(".")):v="latest",window.ccm&&window.ccm[v])p();else{var e=document.createElement("script");document.head.appendChild(e),component.ccm.integrity&&e.setAttribute("integrity",component.ccm.integrity),component.ccm.crossorigin&&e.setAttribute("crossorigin",component.ccm.crossorigin),e.onload=function(){p(),document.head.removeChild(e)},e.src=component.ccm.url}}
}() );<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var path = require('path')
var bodyParser = require('body-parser')
var root = path.join(__dirname, '../');
var _ = require('underscore');
var option = require('./option');

console.log(option);
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/myapp', option);
var db = mongoose.connection;

var Guest = require('./model/guest').Guest;

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
  Guest.find({}, function(err, docs) {
      if (!err){
          console.log('found docs', docs);
      } else {throw err;}
  });
});

app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
}));

//serve up home page
app.get('/', function (req, res) {
  res.sendfile(path.join(root, 'app/index.html'));
});

//serve up static contents
app.use(express.static(path.join(root, 'app')));

app.post('/rsvp/email', function(req, res){
  var email = req.body.email;

  //given email, create a new guest, need to change to create only if not found

  Guest.findOne({email:email}, function(err, guest){
    console.log('error is', err);
    console.log('guest', guest);
    if(!guest){
      var newGuest = new Guest({email:email});
      newGuest.save(function(err, guest){
        res.end(email);
      })
    } else {
      res.end(email);
    }
  })
});

app.post('/rsvp/information', function(req, res){
  var info = req.body.info;

  Guest.findOne({email:info.email}, function(err, guest){
    if(err){
      console.log('error finding email', err);
    } else {
      _.extend(guest, info);
      guest.save(function(err, guest){
        console.log('guest saved');
        res.end('');
      })
    }
  })
})

app.post('/rsvp/additionalguest', function(req, res){
  var email = req.body.email;
  var guestInfo = req.body.guestInfo;

  Guest.findOne({email:email}, function(err, guest){
    guest.guestInfo = guestInfo;
    guest.save(function(err, guest){
      console.log('Info saved, ', guest);
      res.end('')
    })
  })
})

var server = app.listen(8000, function () {
  // var host = server.address().address;
  // var port = server.address().port;
});<commit_msg>change port<commit_after>var express = require('express');
var app = express();
var path = require('path')
var bodyParser = require('body-parser')
var root = path.join(__dirname, '../');
var _ = require('underscore');
var option = require('./option').option;

console.log(option);
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/myapp', option);
var db = mongoose.connection;

var Guest = require('./model/guest').Guest;

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
  Guest.find({}, function(err, docs) {
      if (!err){
          console.log('found docs', docs);
      } else {throw err;}
  });
});

app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
}));

//serve up home page
app.get('/', function (req, res) {
  res.sendfile(path.join(root, 'app/index.html'));
});

//serve up static contents
app.use(express.static(path.join(root, 'app')));

app.post('/rsvp/email', function(req, res){
  var email = req.body.email;

  //given email, create a new guest, need to change to create only if not found

  Guest.findOne({email:email}, function(err, guest){
    console.log('error is', err);
    console.log('guest', guest);
    if(!guest){
      var newGuest = new Guest({email:email});
      newGuest.save(function(err, guest){
        res.end(email);
      })
    } else {
      res.end(email);
    }
  })
});

app.post('/rsvp/information', function(req, res){
  var info = req.body.info;

  Guest.findOne({email:info.email}, function(err, guest){
    if(err){
      console.log('error finding email', err);
    } else {
      _.extend(guest, info);
      guest.save(function(err, guest){
        console.log('guest saved');
        res.end('');
      })
    }
  })
})

app.post('/rsvp/additionalguest', function(req, res){
  var email = req.body.email;
  var guestInfo = req.body.guestInfo;

  Guest.findOne({email:email}, function(err, guest){
    guest.guestInfo = guestInfo;
    guest.save(function(err, guest){
      console.log('Info saved, ', guest);
      res.end('')
    })
  })
})

var server = app.listen(9000, function () {
  // var host = server.address().address;
  // var port = server.address().port;
});<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc service
 * @name atacamaApp.elasticsearchService
 * @description
 * # elasticsearchService
 * Service in the atacamaApp.
 */
angular.module('atacamaApp')
    .service('elasticsearchService', function($rootScope, $resource, es) {
        // AngularJS will instantiate a singleton by calling "new" on this function
        console.log('elasticsearchService has been created');

        var url = 'http://localhost:48002';

        // TODO 1. return from resource to passed-in variable $scope.data[0].values does not work
        // TODO 2. cannot access $scope.data[0].values from websocket callback in here

        // var ticks = Restangular.one('tick').one(symbol).one(sod);

        // ticks.get().then(function (response) {
        //   $scope.data[0].values = response.ticks;
        // });

        var template = function(symbol, date) {
          return {
            size: 5000,
            query: {
              bool: {
                must: [
                  {query_string: {
                    query: symbol,
                    fields: ['symbol'],
                    default_operator: 'and'
                  }
                },{
                  range: {
                    date: {
                      from: date,
                      to: null,
                      include_lower: true,
                      include_upper: true
                    }
                  }
                }]
              }
            }
          }
        }

        this.ping = function() {
          es.ping({
            requestTimeout: 3000,
          // undocumented params are appended to the query string
            hello: "elasticsearch"
          }, function (error) {
            if (error) {
              console.error('elasticsearch cluster is down!');
            } else {
              console.log('elasticsearch cluster returned ping');
            }
          });
        }

        this.getTicksAfter = function(symbol, date) {
          //  [2015-09-21 08:09:30,744][INFO ][index.search.slowlog.query] [Fault Zone] [test-tick][4] took[14.8ms], took_millis[14], types[tick], stats[], search_type[DFS_QUERY_THEN_FETCH], total_shards[5], source[{"from":0,"size":17,"query":{"bool":{"must":[{"query_string":{"query":"ABC","fields":["symbol"],"default_operator":"and"}},{"range":{"date":{"from":1442790000000,"to":null,"include_lower":true,"include_upper":true}}}]}}}], extra_source[],
          return es.search({
            index: 'turbine-ticks',
            type: 'turbine-tick',
            body: template(symbol, date)
          });
        }

        this.getStocksAfter = function(symbol, date) {
          return es.search({
            index: 'turbine-stocks',
            type: 'turbine-stocks', //TODO TYPO!!!
            body: template(symbol, date)
          });
        }

        this.parseResults = function(response) {
          return _.sortBy(_.map(response.hits.hits, '_source'), 'date');
        }
        //this.getTicksAfter = function(symbol, date, reply) {
        //    var call = GetTicksAfter.get({
        //            symbol: symbol,
        //            date: date
        //        }
        //        ,function(response) {
        //            reply = response.ticks;
        //        }
        //    )
        //};

        //this.getTicksAfter(symbol, date) {
        //    $http.get(url + '/' + symbol + '/' + date).
        //      success(function(data, status, headers, config) {
        //      })
        //}

        // this.add = function(tick) {
        //    ticks.push(tick);
        //};

    });
<commit_msg>corrected elasticsearch stock type name<commit_after>'use strict';

/**
 * @ngdoc service
 * @name atacamaApp.elasticsearchService
 * @description
 * # elasticsearchService
 * Service in the atacamaApp.
 */
angular.module('atacamaApp')
    .service('elasticsearchService', function($rootScope, $resource, es) {
        // AngularJS will instantiate a singleton by calling "new" on this function
        console.log('elasticsearchService has been created');

        var url = 'http://localhost:48002';

        // TODO 1. return from resource to passed-in variable $scope.data[0].values does not work
        // TODO 2. cannot access $scope.data[0].values from websocket callback in here

        // var ticks = Restangular.one('tick').one(symbol).one(sod);

        // ticks.get().then(function (response) {
        //   $scope.data[0].values = response.ticks;
        // });

        var template = function(symbol, date) {
          return {
            size: 5000,
            query: {
              bool: {
                must: [
                  {query_string: {
                    query: symbol,
                    fields: ['symbol'],
                    default_operator: 'and'
                  }
                },{
                  range: {
                    date: {
                      from: date,
                      to: null,
                      include_lower: true,
                      include_upper: true
                    }
                  }
                }]
              }
            }
          }
        }

        this.ping = function() {
          es.ping({
            requestTimeout: 3000,
          // undocumented params are appended to the query string
            hello: "elasticsearch"
          }, function (error) {
            if (error) {
              console.error('elasticsearch cluster is down!');
            } else {
              console.log('elasticsearch cluster returned ping');
            }
          });
        }

        this.getTicksAfter = function(symbol, date) {
          //  [2015-09-21 08:09:30,744][INFO ][index.search.slowlog.query] [Fault Zone] [test-tick][4] took[14.8ms], took_millis[14], types[tick], stats[], search_type[DFS_QUERY_THEN_FETCH], total_shards[5], source[{"from":0,"size":17,"query":{"bool":{"must":[{"query_string":{"query":"ABC","fields":["symbol"],"default_operator":"and"}},{"range":{"date":{"from":1442790000000,"to":null,"include_lower":true,"include_upper":true}}}]}}}], extra_source[],
          return es.search({
            index: 'turbine-ticks',
            type: 'turbine-tick',
            body: template(symbol, date)
          });
        }

        this.getStocksAfter = function(symbol, date) {
          return es.search({
            index: 'turbine-stocks',
            type: 'turbine-stock', //TODO TYPO!!!
            body: template(symbol, date)
          });
        }

        this.parseResults = function(response) {
          return _.sortBy(_.map(response.hits.hits, '_source'), 'date');
        }
        //this.getTicksAfter = function(symbol, date, reply) {
        //    var call = GetTicksAfter.get({
        //            symbol: symbol,
        //            date: date
        //        }
        //        ,function(response) {
        //            reply = response.ticks;
        //        }
        //    )
        //};

        //this.getTicksAfter(symbol, date) {
        //    $http.get(url + '/' + symbol + '/' + date).
        //      success(function(data, status, headers, config) {
        //      })
        //}

        // this.add = function(tick) {
        //    ticks.push(tick);
        //};

    });
<|endoftext|>


<commit_before>'use strict';

describe('searchResults controllers', function() {

	var searchServiceDeferred;

	beforeEach(module('searchResults'));

	//beforeEach(angular.mock.inject(function () {
	//	searchServiceDeferred = q.defer();
	//	spyOn(searchService, "getOnWardFlightResults").and.returnValue(searchServiceDeferred.promise);
	//}));

	var ctrl
		, $scope
		, Service = { // mock the Service service
			getOnWardFlightResults: function () {},
		},
		searchQuery = {
			from: 'BAN',
			to: 'CHE',
			departDate: "Fri Jun 03 2016 00:00:00 GMT+0530 (IST)"
		};

	beforeEach(inject(function ($controller, $rootScope) {
		$scope = $rootScope.$new(); // create a new clean scope
		$controller('SearchResultsCtrl as results', {
			Service: Service,
			$scope: $scope
		});

	}));

	it('should have false value for flightList and true after function call', function() {
		expect($scope.results.flightList).toBeFalsy();
		$scope.results.searchFlights(searchQuery);
		expect($scope.results.flightList).toBeFalsy();
	});

});
<commit_msg>Prabhu - passing test<commit_after>'use strict';

describe('searchResults controllers', function() {

	var searchServiceDeferred;

	beforeEach(module('searchResults'));

	//beforeEach(angular.mock.inject(function () {
	//	searchServiceDeferred = q.defer();
	//	spyOn(searchService, "getOnWardFlightResults").and.returnValue(searchServiceDeferred.promise);
	//}));

	var ctrl
		, $scope
		, Service = { // mock the Service service
			getOnWardFlightResults: function () {},
		},
		searchQuery = {
			from: 'BAN',
			to: 'CHE',
			departDate: "Fri Jun 03 2016 00:00:00 GMT+0530 (IST)"
		};

	beforeEach(inject(function ($controller, $rootScope) {
		$scope = $rootScope.$new(); // create a new clean scope
		$controller('SearchResultsCtrl as results', {
			Service: Service,
			$scope: $scope
		});

	}));

	it('should have false value for flightList and true after function call', function() {
		expect($scope.results.flightList).toBeFalsy();
		$scope.results.searchFlights(searchQuery);
		expect($scope.results.flightList).toBeTruthy();
	});

});
<|endoftext|>


<commit_before>import DS from "ember-data";
import Ember from "ember";
import config from '../config/environment';

export default DS.Model.extend( {
    first_name: DS.attr("string"),
    last_name: DS.attr("string"),
    nick_name: DS.attr("string"),
    full_name: Ember.computed("first_name", "nick_name", "last_name", function() {
        //console.log(this.get("nick_name"));
        if(!this.get("nick_name") || this.get("nick_name").length === 0) {
            return this.get("first_name") + ' ' + this.get("last_name");
        }
        return this.get("first_name") + ' "' + this.get("nick_name") + '" ' + this.get("last_name");
    }),
    profile_picture: DS.attr("string"),
    profile_picture_r: Ember.computed("profile_picture", function() {
        var p = this.get("profile_picture");
        if(p) {
            return config.API_LOC + p;
        }
        return "/img/avatar-default.svg";
    }),
    short_info: DS.attr("string"),
    gender: DS.attr("string"),

    // Relevant only when user
    score: DS.attr("number"),
    tasks_num: DS.attr("number"),
    achievements: DS.hasMany("achievement", {async: true}),
    school_name: DS.attr("string"),
    addr_country: DS.attr("string"),
    seasons: DS.attr("number"),

    role: DS.attr("string", {defaultValue: "participant"}),
    admin: Ember.computed("role", function(){
        return this.get("role") === "admin";
    }),

    organisator: Ember.computed("role", function(){
        return (this.get("role") === "org") || (this.get("role") === "admin");
    }),

    participant: Ember.computed("role", function(){
        return this.get("role") === "participant";
    }),

    tester: Ember.computed("role", function(){
        return this.get("role") === "tester";
    }),

    score_inverted: Ember.computed("score", function(){
        return -this.get("score");
    }),

    // this property must be here, see ./profile.js
    show_solved: Ember.computed("role", function(){
        return this.get("role") === "participant";
    }),

    // Relevant only when organisator
    tasks: DS.hasMany("task", {async: true}),
    email: DS.attr("string"),

    role_str: Ember.computed("gender", "role", function() {
        var ret = "";
        if ((this.get("role") === "org") || (this.get("role") === "admin")) {
            ret = "organizátor";
        }
        if (this.get("role") === "participant") {
            ret = "řešitel";
        }
        if (this.get("role") === "tester") {
            ret = "tester";
        }
        if (this.get("gender") === "female") {
            ret = ret + "ka";
        }
        return ret;
    }),

});
<commit_msg>Default avatars based on gender.<commit_after>import DS from "ember-data";
import Ember from "ember";
import config from '../config/environment';

export default DS.Model.extend( {
    first_name: DS.attr("string"),
    last_name: DS.attr("string"),
    nick_name: DS.attr("string"),
    full_name: Ember.computed("first_name", "nick_name", "last_name", function() {
        //console.log(this.get("nick_name"));
        if(!this.get("nick_name") || this.get("nick_name").length === 0) {
            return this.get("first_name") + ' ' + this.get("last_name");
        }
        return this.get("first_name") + ' "' + this.get("nick_name") + '" ' + this.get("last_name");
    }),
    profile_picture: DS.attr("string"),
    profile_picture_r: Ember.computed("profile_picture", "gender", function() {
        var p = this.get("profile_picture");
        if (p) { return config.API_LOC + p; }
        if (this.get("gender") == "female") {
            return "/img/avatar-default-woman.svg";
        } else {
            return "/img/avatar-default.svg";
        }
    }),
    short_info: DS.attr("string"),
    gender: DS.attr("string"),

    // Relevant only when user
    score: DS.attr("number"),
    tasks_num: DS.attr("number"),
    achievements: DS.hasMany("achievement", {async: true}),
    school_name: DS.attr("string"),
    addr_country: DS.attr("string"),
    seasons: DS.attr("number"),

    role: DS.attr("string", {defaultValue: "participant"}),
    admin: Ember.computed("role", function(){
        return this.get("role") === "admin";
    }),

    organisator: Ember.computed("role", function(){
        return (this.get("role") === "org") || (this.get("role") === "admin");
    }),

    participant: Ember.computed("role", function(){
        return this.get("role") === "participant";
    }),

    tester: Ember.computed("role", function(){
        return this.get("role") === "tester";
    }),

    score_inverted: Ember.computed("score", function(){
        return -this.get("score");
    }),

    // this property must be here, see ./profile.js
    show_solved: Ember.computed("role", function(){
        return this.get("role") === "participant";
    }),

    // Relevant only when organisator
    tasks: DS.hasMany("task", {async: true}),
    email: DS.attr("string"),

    role_str: Ember.computed("gender", "role", function() {
        var ret = "";
        if ((this.get("role") === "org") || (this.get("role") === "admin")) {
            ret = "organizátor";
        }
        if (this.get("role") === "participant") {
            ret = "řešitel";
        }
        if (this.get("role") === "tester") {
            ret = "tester";
        }
        if (this.get("gender") === "female") {
            ret = ret + "ka";
        }
        return ret;
    }),

});
<|endoftext|>


<commit_before>/**
 * WordPress dependencies
 */
import { activatePlugin, createURL, visitAdminPage } from '@wordpress/e2e-test-utils';

/**
 * Internal dependencies
 */
import {
	deactivateUtilityPlugins,
	resetSiteKit,
	setSearchConsoleProperty,
	wpApiFetch,
	useRequestInterception,
} from '../../../utils';

async function proceedToSetUpAnalytics() {
	await Promise.all( [
		expect( page ).toClick( '.googlesitekit-cta-link', { text: /set up analytics/i } ),
		page.waitForSelector( '.googlesitekit-setup-module__inputs' ),
		page.waitForRequest( ( req ) => req.url().match( 'analytics/data' ) ),
	] );
}

const setReferenceURL = async () => {
	return wpApiFetch( {
		path: 'google-site-kit/v1/e2e/reference-url',
		method: 'post',
		data: {
			url: 'http://non-matching-url.test',
		},
	} );
};

describe( 'setting up the Analytics module with an existing account and no existing tag', () => {
	beforeAll( async () => {
		await page.setRequestInterception( true );

		useRequestInterception( ( request ) => {
			if ( request.url().startsWith( 'https://accounts.google.com/o/oauth2/auth' ) ) {
				request.respond( {
					status: 302,
					headers: {
						location: createURL( '/', [
							'oauth2callback=1',
							'code=valid-test-code',
							'e2e-site-verification=1',
							'scope=TEST_ALL_SCOPES',
						].join( '&' ) ),
					},
				} );
			} else if ( request.url().match( '/wp-json/google-site-kit/v1/data/' ) ) {
				request.respond( {
					status: 200,
				} );
			} else {
				request.continue();
			}
		} );
	} );

	beforeEach( async () => {
		await activatePlugin( 'e2e-tests-auth-plugin' );
		await activatePlugin( 'e2e-tests-site-verification-plugin' );
		await activatePlugin( 'e2e-tests-oauth-callback-plugin' );
		await activatePlugin( 'e2e-tests-module-setup-analytics-api-mock' );
		await setSearchConsoleProperty();

		await visitAdminPage( 'admin.php', 'page=googlesitekit-settings' );
		await page.waitForSelector( '.mdc-tab-bar' );
		await expect( page ).toClick( '.mdc-tab', { text: /connect more services/i } );
		await page.waitForSelector( '.googlesitekit-settings-connect-module--analytics' );
	} );

	afterEach( async () => {
		await deactivateUtilityPlugins();
		await resetSiteKit();
	} );

	it( 'pre-selects account and property if the tag matches one belonging to the user', async () => {
		await proceedToSetUpAnalytics();

		await expect( page ).toMatchElement( '.mdc-select__selected-text', { text: /test account a/i } );
		await expect( page ).toMatchElement( '.mdc-select__selected-text', { text: /test property x/i } );
		await expect( page ).toMatchElement( '.mdc-select__selected-text', { text: /test profile x/i } );

		// Select Test Account B
		await expect( page ).toClick( '.mdc-select', { text: /test account a/i } );
		await Promise.all( [
			expect( page ).toClick( '.mdc-menu-surface--open .mdc-list-item', { text: /test account b/i } ),
			page.waitForResponse( ( res ) => res.url().match( 'modules/analytics/data' ) ),
		] );

		// Selects reload with properties and profiles for Test Account B
		await expect( page ).toMatchElement( '.mdc-select__selected-text', { text: /test account b/i } );
		await expect( page ).toMatchElement( '.mdc-select__selected-text', { text: /test property y/i } );
		await expect( page ).toMatchElement( '.mdc-select__selected-text', { text: /test profile y/i } );

		// Select Property Z
		await expect( page ).toClick( '.mdc-select', { text: /test property y/i } );
		await Promise.all( [
			expect( page ).toClick( '.mdc-menu-surface--open .mdc-list-item', { text: /test property z/i } ),
			page.waitForResponse( ( res ) => res.url().match( 'modules/analytics/data' ) ),
		] );

		// Selects reload with properties and profiles for Test Profile Z
		await expect( page ).toMatchElement( '.mdc-select__selected-text', { text: /test account b/i } );
		await expect( page ).toMatchElement( '.mdc-select__selected-text', { text: /test property z/i } );
		await expect( page ).toMatchElement( '.mdc-select__selected-text', { text: /test profile z/i } );

		await page.waitFor( 500 );
		await expect( page ).toClick( 'button', { text: /configure analytics/i } );

		await page.waitForSelector( '.googlesitekit-publisher-win--win-success' );
		await expect( page ).toMatchElement( '.googlesitekit-publisher-win__title', { text: /Congrats on completing the setup for Analytics!/i } );
	} );

	it( 'prompts for account and property if the site URL does not match a property belonging to the user', async () => {
		await setReferenceURL();

		await proceedToSetUpAnalytics();

		await expect( page ).toMatchElement( '.googlesitekit-analytics__select-account .mdc-select__selected-text', { text: '' } );
		await expect( page ).toMatchElement( '.googlesitekit-analytics__select-property .mdc-select__selected-text', { text: '' } );
		await expect( page ).toMatchElement( '.googlesitekit-analytics__select-profile .mdc-select__selected-text', { text: '' } );
		await expect( page ).toMatchElement( 'button[disabled]', { text: /configure analytics/i } );

		// Select Test Account A
		await expect( page ).toClick( '.googlesitekit-analytics__select-account .mdc-select__selected-text' );
		await expect( page ).toClick( '.mdc-menu-surface--open .mdc-list-item', { text: /test account a/i } );

		// See the selects populate
		await expect( page ).toMatchElement( '.mdc-select__selected-text', { text: /test account a/i } );
		await expect( page ).toMatchElement( '.mdc-select__selected-text', { text: /test property x/i } );
		await expect( page ).toMatchElement( '.mdc-select__selected-text', { text: /test profile x/i } );

		await expect( page ).toClick( '.mdc-select', { text: /test property x/i } );
		await expect( page ).toClick( '.mdc-menu-surface--open .mdc-list-item', { text: /set up a new property/i } );

		await expect( page ).toMatchElement( '.mdc-select__selected-text', { text: /set up a new property/i } );
		await expect( page ).toMatchElement( '.mdc-select__selected-text', { text: /set up a new profile/i } );

		// Intentionally does not submit to trigger property & profile creation requests.
	} );

	it( 'includes an option to setup a new account', async () => {
		await proceedToSetUpAnalytics();

		await expect( page ).toMatchElement( '.mdc-select__selected-text', { text: /test account a/i } );
		await expect( page ).toMatchElement( '.mdc-select__selected-text', { text: /test property x/i } );
		await expect( page ).toMatchElement( '.mdc-select__selected-text', { text: /test profile x/i } );

		await expect( page ).toClick( '.googlesitekit-analytics__select-account .mdc-select__selected-text' );
		await expect( page ).toClick( '.mdc-menu-surface--open .mdc-list-item', { text: /set up a new account/i } );

		// Ensure dropdowns are now hidden.
		await expect( page ).not.toMatchElement( '.googlesitekit-setup-module--analytics select' );
		await expect( page ).toMatchElement( 'button', { text: /create an account/i } );
		await expect( page ).toMatchElement( 'button', { text: /re-fetch my account/i } );

		await Promise.all( [
			page.waitForResponse( ( res ) => res.url().match( 'modules/analytics/data' ) ),
			expect( page ).toClick( 'button', { text: /re-fetch my account/i } ),
		] );

		// Dropdowns are revealed and reset on refetch.
		await expect( page ).toMatchElement( '.googlesitekit-analytics__select-account .mdc-select__selected-text', { text: '' } );
		await expect( page ).toMatchElement( '.googlesitekit-analytics__select-property .mdc-select__selected-text', { text: '' } );
		await expect( page ).toMatchElement( '.googlesitekit-analytics__select-profile .mdc-select__selected-text', { text: '' } );
	} );
} );
<commit_msg>Test AMP validation after setting up Analytics.<commit_after>/**
 * WordPress dependencies
 */
import { activatePlugin, deactivatePlugin, createURL, visitAdminPage } from '@wordpress/e2e-test-utils';

/**
 * Internal dependencies
 */
import {
	activateAmpAndSetMode,
	deactivateUtilityPlugins,
	resetSiteKit,
	setSearchConsoleProperty,
	setupAnalytics,
	wpApiFetch,
	useRequestInterception,
} from '../../../utils';

async function proceedToSetUpAnalytics() {
	await Promise.all( [
		expect( page ).toClick( '.googlesitekit-cta-link', { text: /set up analytics/i } ),
		page.waitForSelector( '.googlesitekit-setup-module__inputs' ),
		page.waitForRequest( ( req ) => req.url().match( 'analytics/data' ) ),
	] );
}

const setReferenceURL = async () => {
	return wpApiFetch( {
		path: 'google-site-kit/v1/e2e/reference-url',
		method: 'post',
		data: {
			url: 'http://non-matching-url.test',
		},
	} );
};

describe( 'setting up the Analytics module with an existing account and no existing tag', () => {
	beforeAll( async () => {
		await page.setRequestInterception( true );

		useRequestInterception( ( request ) => {
			if ( request.url().startsWith( 'https://accounts.google.com/o/oauth2/auth' ) ) {
				request.respond( {
					status: 302,
					headers: {
						location: createURL( '/', [
							'oauth2callback=1',
							'code=valid-test-code',
							'e2e-site-verification=1',
							'scope=TEST_ALL_SCOPES',
						].join( '&' ) ),
					},
				} );
			} else if ( request.url().match( '/wp-json/google-site-kit/v1/data/' ) ) {
				request.respond( {
					status: 200,
				} );
			} else {
				request.continue();
			}
		} );
	} );

	beforeEach( async () => {
		await activatePlugin( 'e2e-tests-auth-plugin' );
		await activatePlugin( 'e2e-tests-site-verification-plugin' );
		await activatePlugin( 'e2e-tests-oauth-callback-plugin' );
		await activatePlugin( 'e2e-tests-module-setup-analytics-api-mock' );
		await setSearchConsoleProperty();

		await visitAdminPage( 'admin.php', 'page=googlesitekit-settings' );
		await page.waitForSelector( '.mdc-tab-bar' );
		await expect( page ).toClick( '.mdc-tab', { text: /connect more services/i } );
		await page.waitForSelector( '.googlesitekit-settings-connect-module--analytics' );
	} );

	afterEach( async () => {
		await deactivatePlugin( 'amp' );
		await deactivateUtilityPlugins();
		await resetSiteKit();
	} );

	it( 'pre-selects account and property if the tag matches one belonging to the user', async () => {
		await proceedToSetUpAnalytics();

		await expect( page ).toMatchElement( '.mdc-select__selected-text', { text: /test account a/i } );
		await expect( page ).toMatchElement( '.mdc-select__selected-text', { text: /test property x/i } );
		await expect( page ).toMatchElement( '.mdc-select__selected-text', { text: /test profile x/i } );

		// Select Test Account B
		await expect( page ).toClick( '.mdc-select', { text: /test account a/i } );
		await Promise.all( [
			expect( page ).toClick( '.mdc-menu-surface--open .mdc-list-item', { text: /test account b/i } ),
			page.waitForResponse( ( res ) => res.url().match( 'modules/analytics/data' ) ),
		] );

		// Selects reload with properties and profiles for Test Account B
		await expect( page ).toMatchElement( '.mdc-select__selected-text', { text: /test account b/i } );
		await expect( page ).toMatchElement( '.mdc-select__selected-text', { text: /test property y/i } );
		await expect( page ).toMatchElement( '.mdc-select__selected-text', { text: /test profile y/i } );

		// Select Property Z
		await expect( page ).toClick( '.mdc-select', { text: /test property y/i } );
		await Promise.all( [
			expect( page ).toClick( '.mdc-menu-surface--open .mdc-list-item', { text: /test property z/i } ),
			page.waitForResponse( ( res ) => res.url().match( 'modules/analytics/data' ) ),
		] );

		// Selects reload with properties and profiles for Test Profile Z
		await expect( page ).toMatchElement( '.mdc-select__selected-text', { text: /test account b/i } );
		await expect( page ).toMatchElement( '.mdc-select__selected-text', { text: /test property z/i } );
		await expect( page ).toMatchElement( '.mdc-select__selected-text', { text: /test profile z/i } );

		await page.waitFor( 500 );
		await expect( page ).toClick( 'button', { text: /configure analytics/i } );

		await page.waitForSelector( '.googlesitekit-publisher-win--win-success' );
		await expect( page ).toMatchElement( '.googlesitekit-publisher-win__title', { text: /Congrats on completing the setup for Analytics!/i } );
	} );

	it( 'prompts for account and property if the site URL does not match a property belonging to the user', async () => {
		await setReferenceURL();

		await proceedToSetUpAnalytics();

		await expect( page ).toMatchElement( '.googlesitekit-analytics__select-account .mdc-select__selected-text', { text: '' } );
		await expect( page ).toMatchElement( '.googlesitekit-analytics__select-property .mdc-select__selected-text', { text: '' } );
		await expect( page ).toMatchElement( '.googlesitekit-analytics__select-profile .mdc-select__selected-text', { text: '' } );
		await expect( page ).toMatchElement( 'button[disabled]', { text: /configure analytics/i } );

		// Select Test Account A
		await expect( page ).toClick( '.googlesitekit-analytics__select-account .mdc-select__selected-text' );
		await expect( page ).toClick( '.mdc-menu-surface--open .mdc-list-item', { text: /test account a/i } );

		// See the selects populate
		await expect( page ).toMatchElement( '.mdc-select__selected-text', { text: /test account a/i } );
		await expect( page ).toMatchElement( '.mdc-select__selected-text', { text: /test property x/i } );
		await expect( page ).toMatchElement( '.mdc-select__selected-text', { text: /test profile x/i } );

		await expect( page ).toClick( '.mdc-select', { text: /test property x/i } );
		await expect( page ).toClick( '.mdc-menu-surface--open .mdc-list-item', { text: /set up a new property/i } );

		await expect( page ).toMatchElement( '.mdc-select__selected-text', { text: /set up a new property/i } );
		await expect( page ).toMatchElement( '.mdc-select__selected-text', { text: /set up a new profile/i } );

		// Intentionally does not submit to trigger property & profile creation requests.
	} );

	it( 'includes an option to setup a new account', async () => {
		await proceedToSetUpAnalytics();

		await expect( page ).toMatchElement( '.mdc-select__selected-text', { text: /test account a/i } );
		await expect( page ).toMatchElement( '.mdc-select__selected-text', { text: /test property x/i } );
		await expect( page ).toMatchElement( '.mdc-select__selected-text', { text: /test profile x/i } );

		await expect( page ).toClick( '.googlesitekit-analytics__select-account .mdc-select__selected-text' );
		await expect( page ).toClick( '.mdc-menu-surface--open .mdc-list-item', { text: /set up a new account/i } );

		// Ensure dropdowns are now hidden.
		await expect( page ).not.toMatchElement( '.googlesitekit-setup-module--analytics select' );
		await expect( page ).toMatchElement( 'button', { text: /create an account/i } );
		await expect( page ).toMatchElement( 'button', { text: /re-fetch my account/i } );

		await Promise.all( [
			page.waitForResponse( ( res ) => res.url().match( 'modules/analytics/data' ) ),
			expect( page ).toClick( 'button', { text: /re-fetch my account/i } ),
		] );

		// Dropdowns are revealed and reset on refetch.
		await expect( page ).toMatchElement( '.googlesitekit-analytics__select-account .mdc-select__selected-text', { text: '' } );
		await expect( page ).toMatchElement( '.googlesitekit-analytics__select-property .mdc-select__selected-text', { text: '' } );
		await expect( page ).toMatchElement( '.googlesitekit-analytics__select-profile .mdc-select__selected-text', { text: '' } );
	} );

	describe( 'Homepage AMP', () => {
		it( 'validates for logged-in users', async () => {
			await setupAnalytics();
			await activateAmpAndSetMode( 'standard' );
			await Promise.all( [
				page.goto( createURL( '/' ), { waitUntil: 'load' } ),
				page.waitForSelector( '#amp-admin-bar-item-status-icon' ),
			] );
			await expect( page ).toMatchElement( '#amp-admin-bar-item-status-icon', { text: '✅' } );
		} );
		it( 'validates for non-logged-in users', async () => {
			await setupAnalytics();
			await activateAmpAndSetMode( 'standard' );
			await expect( '/' ).toHaveValidAMP();
		} );
	} );
} );
<|endoftext|>


<commit_before>'use strict'

const cluster = require('cluster')
const os = require('os')

const co = require('co')
const exists = require('101/exists')
const first = require('first-event')
const times = require('times-loop')
const values = require('object-values')
const retry = require('promise-retry')

const debug = require('./utils/debug.js')()
const getEnv = require('./utils/get-env.js')

class QueueWorkerCounter {
  constructor () {
    this.reset()
  }
  inc (queueName) {
    const countsByQueue = this.countsByQueue

    countsByQueue[queueName] = countsByQueue[queueName] || 0
    countsByQueue[queueName]++

    return countsByQueue[queueName]
  }
  reset () {
    this.countsByQueue = {}
  }
}
// Singleton queue worker counter helper
const queueWorkerCounter = new QueueWorkerCounter()

// Cluster Manager Class

module.exports = class ClusterManager {
  constructor (app) {
    this.app = app
  }
  /**
   * fork process and create a worker
   * @param  {String} queueName name of queue which worker will consume
   * @param  {Number} queueWorkerNum
   * @return {Promise} worker promise
   */
  static fork (queueName) {
    const queueWorkerNum = queueWorkerCounter.inc(queueName)

    return co(function * () {
      // fork process
      debug(`worker create "${queueName}:${queueWorkerNum}"`)
      const worker = cluster.fork({
        COWORKERS_QUEUE: queueName,
        COWORKERS_QUEUE_WORKER_NUM: queueWorkerNum
      })
      // handle worker messages
      worker.on('message', ClusterManager.messageHandler)
      // set custom properties
      worker.__queueName = queueName
      worker.__queueWorkerNum = queueWorkerNum
      // worker created
      debug(`worker created pid=${worker.process.pid} "${queueName}:${queueWorkerNum}"`)
      // wait for successful connection to rabbit, or error
      //   note: waiting for connect will call close if it fails.
      //     if close fails process will exit -> coworkers:close:error
      const events = yield [
        first(worker, [ 'error', 'online' ]).then(function () {
          debug(`worker online "${queueName}:${queueWorkerNum}"`)
        }),
        first(worker, [ 'exit', 'coworkers:close', 'coworkers:close:error', 'coworkers:connect' ])
      ]
      const onlineEvent = events[1]
      const event = onlineEvent.event
      // check if worker exited before connecting (to rabbitmq)
      if (event === 'exit') {
        debug(`worker process exited before connect "${queueName}:${queueWorkerNum}"`)
        throw new Error(`worker process exited before connect "${queueName}:${queueWorkerNum}"`)
      }
      // check if worker failed to connect (connection closed instead of connected)
      if (event.indexOf('coworkers:close') === 0) {
        debug(`worker connect errored "${queueName}:${queueWorkerNum}"`)
        debug(`worker connect errored -> kill worker "${queueName}:${queueWorkerNum}"`)
        // kill the disconnected worker and throw the error
        yield ClusterManager.killWorker(worker)
        throw new Error(`worker connect errored "${queueName}:${queueWorkerNum}"`)
      }
      // worker successfully connected to rabbitmq
      debug(`worker connect success "${queueName}:${queueWorkerNum}"`)
      // respawn worker if it exists
      worker.once('exit', ClusterManager.respawnWorker)
      return worker
    }).catch(function (err) {
      // log err and rethrow
      debug(`worker create error "${queueName}:${queueWorkerNum}"`, err)
      throw err
    })
  }
  /**
   * worker exit handler
   * @param  {Number} code   exit code of worker process
   * @param  {String} signal signal that caused worker process exit
   */
  static respawnWorker (code, signal) {
    const worker = this
    const queueName = worker.__queueName
    const queueWorkerNum = worker.__queueWorkerNum
    const COWORKERS_RESPAWN_RETRY_ATTEMPTS = process.env.COWORKERS_RESPAWN_RETRY_ATTEMPTS
    const COWORKERS_RESPAWN_RETRY_MIN_TIMEOUT = process.env.COWORKERS_RESPAWN_RETRY_MIN_TIMEOUT
    const COWORKERS_RESPAWN_RETRY_FACTOR = process.env.COWORKERS_RESPAWN_RETRY_FACTOR
    const opts = {
      retries: exists(COWORKERS_RESPAWN_RETRY_ATTEMPTS) ? COWORKERS_RESPAWN_RETRY_ATTEMPTS : 20,
      minTimeout: exists(COWORKERS_RESPAWN_RETRY_MIN_TIMEOUT) ? COWORKERS_RESPAWN_RETRY_MIN_TIMEOUT : 10,
      factor: exists(COWORKERS_RESPAWN_RETRY_FACTOR) ? COWORKERS_RESPAWN_RETRY_FACTOR : 1
    }
    debug(`worker exited with code=${code} signal=${signal} "${queueName}:${queueWorkerNum}"`)
    return retry(opts, function (retry, attempt) {
      return co(function * () {
        // if signal is SIGINT, do not respawn
        if (signal === 'SIGINT') {
          debug(`no respawn. process exited w/ SIGINT "${queueName}:${queueWorkerNum}"`)
          return
        }
        // respawn worker
        const attemptMsg = attempt > 1 ? ` attempt=${attempt}` : ''
        debug(`respawn worker${attemptMsg} "${queueName}:${queueWorkerNum}"`)
        yield ClusterManager.fork(queueName)
      }).catch(function (err) {
        debug(`respawn failed for "${queueName}:${queueWorkerNum}"`, err)
        retry(err)
      })
    }).catch(function (err) {
      debug(`all ${opts.retries} respawn worker attempts failed "${queueName}:${queueWorkerNum}"`, err)
      process.nextTick(function () {
        throw err
      })
    })
  }
  /**
   * stop a worker
   * @param  {Worker} worker cluster worker to stop
   * @return {Promise} stop promise
   */
  static killWorker (worker) {
    const queueName = worker.__queueName
    const queueWorkerNum = worker.__queueWorkerNum
    const COWORKERS_KILL_RETRY_ATTEMPTS = process.env.COWORKERS_KILL_RETRY_ATTEMPTS
    const COWORKERS_KILL_RETRY_MIN_TIMEOUT = process.env.COWORKERS_KILL_RETRY_MIN_TIMEOUT
    const COWORKERS_KILL_RETRY_FACTOR = process.env.COWORKERS_KILL_RETRY_FACTOR
    const opts = {
      retries: exists(COWORKERS_KILL_RETRY_ATTEMPTS) ? COWORKERS_KILL_RETRY_ATTEMPTS : 20,
      minTimeout: exists(COWORKERS_KILL_RETRY_MIN_TIMEOUT) ? COWORKERS_KILL_RETRY_MIN_TIMEOUT : 10,
      factor: exists(COWORKERS_KILL_RETRY_FACTOR) ? COWORKERS_KILL_RETRY_FACTOR : 1
    }

    return retry(opts, function (retry, attempt) {
      return co(function * () {
        const attemptMsg = attempt > 1 ? ` attempt=${attempt}` : ''
        debug(`kill worker${attemptMsg} "${queueName}:${queueWorkerNum}"`)
        // check if worker is already killed
        if (worker.process.killed) {
          debug(`worker already killed "${queueName}:${queueWorkerNum}"`)
          return
        }
        // kill worker
        worker.kill('SIGINT') // handled in application.js
        // wait until worker is exits
        yield first(worker, [ 'error', 'exit' ])
      }).then(function () {
        debug(`worker exit success "${queueName}:${queueWorkerNum}"`)
      }).catch(function (err) {
        debug(`worker exit errorer "${queueName}:${queueWorkerNum}"`, err)
        retry(err)
      })
    }).catch(function (err) {
      debug(`all ${opts.retries} kill worker attempts failed "${queueName}:${queueWorkerNum}"`, err)
      throw err
    })
  }
  /**
   * handler messages and look for coworker events
   * if a coworker event message is recieved emit the event on the worker
   * @param {Object} message object
   */
  static messageHandler (msg) {
    const queueName = this.__queueName
    const queueWorkerNum = this.__queueWorkerNum
    debug(`worker got a message "${queueName}:${queueWorkerNum}"`)
    if (msg.coworkersEvent) {
      debug(`worker got a coworkers message ${msg.coworkersEvent} "${queueName}:${queueWorkerNum}"`)
      this.emit(msg.coworkersEvent)
    }
  }
  /**
   * start cluster manager and create worker processes
   * @return {Promise} start promise
   */
  start () {
    debug(`master pid=${process.pid}`)
    debug('master start')
    const self = this

    if (this.startingPromise) {
      return this.startingPromise
    }

    if (cluster.workers.length) {
      debug('workers exist, stop them before start')
      // not completely stopped, cleanup first
      this.startingPromise = self.stop()
        .catch(function (err) {
          debug('cluster-manager stop (before start) errored', err)
          const startErr = new Error('Start cancelled because pending stop failed (.stopErr)')
          startErr.stopErr = err
          // delete connecting promise, connect cancelled
          delete self.startingPromise
          throw startErr
        })
        .then(function () {
          debug('cluster-manager stop (before start) success')
          delete self.startingPromise
          return self.start()
        })

      return self.startingPromise
    }

    this.startingPromise = co(function * () {
      const COWORKERS_WORKERS_PER_QUEUE = getEnv().COWORKERS_WORKERS_PER_QUEUE
      const numQueues = self.app.queueNames.length
      const numCpus = os.cpus().length
      let queueNames

      debug('num cpus %s', numCpus)
      debug('num queues %s', numQueues)
      debug('queue names %o', self.app.queueNames)

      if (exists(COWORKERS_WORKERS_PER_QUEUE) || numCpus > numQueues) {
        // The number of cpus is greater than the number of consumers (processes).
        // To optimize cpu-usage, the number of processes should be greater.
        // Create "n" clones of each consumer, so that n * queues >= cpus.
        let workersPerQueue = exists(COWORKERS_WORKERS_PER_QUEUE)
          ? COWORKERS_WORKERS_PER_QUEUE
          : Math.ceil(numCpus / numQueues)
        debug('workers / queue %s', workersPerQueue)

        queueNames = []
        times(workersPerQueue, function () {
          queueNames = queueNames.concat(self.app.queueNames)
        })
      } else {
        debug('workers / queue %s', 1)
        // numCpus < numQueues, so create one consumer per queue
        queueNames = self.app.queueNames
      }
      // wait for all forks to complete even if an error occurs
      const forkErrs = []
      debug('queueNames %o', queueNames)
      yield queueNames.map(function (queueName) {
        return ClusterManager.fork(queueName).catch(function (err) {
          forkErrs.push(err)
        })
      })
      // check if any worker forks failed
      if (forkErrs.length) {
        const err = new Error('Some worker forks failed (.errors)')
        err.errors = forkErrs
        throw err
      }
    }).then(function () {
      delete self.startingPromise
      debug('cluster-manager start success')
    }).catch(function (err) {
      delete self.startingPromise
      debug('cluster-manager start errored', err)
      throw err
    })

    return this.startingPromise
  }
  /**
   * stop cluster manager, exit all worker processes, and allow master process to stop
   * @param  {String} signal signal to cause
   * @return {Promise} stop promise
   */
  stop (signal) {
    debug('master stop')
    return co(function * () {
      // wait for all kills to complete even if an error occurs
      const killErrs = []
      yield values(cluster.workers).map(function (worker) {
        return ClusterManager.killWorker(worker).catch(function (err) {
          killErrs.push(err)
        })
      })
      // check if any worker kills failed
      if (killErrs.length) {
        const err = new Error('Some worker kills failed (.errors)')
        err.errors = killErrs
        throw err
      }
      debug('cluster-manager stop success')
    }).catch(function (err) {
      debug('cluster-manager stop errored', err)
      throw err
    })
  }
}
<commit_msg>propagate env to workers<commit_after>'use strict'

const cluster = require('cluster')
const os = require('os')

const co = require('co')
const exists = require('101/exists')
const put = require('101/put')
const first = require('first-event')
const times = require('times-loop')
const values = require('object-values')
const retry = require('promise-retry')

const debug = require('./utils/debug.js')()
const getEnv = require('./utils/get-env.js')

class QueueWorkerCounter {
  constructor () {
    this.reset()
  }
  inc (queueName) {
    const countsByQueue = this.countsByQueue

    countsByQueue[queueName] = countsByQueue[queueName] || 0
    countsByQueue[queueName]++

    return countsByQueue[queueName]
  }
  reset () {
    this.countsByQueue = {}
  }
}
// Singleton queue worker counter helper
const queueWorkerCounter = new QueueWorkerCounter()

// Cluster Manager Class

module.exports = class ClusterManager {
  constructor (app) {
    this.app = app
  }
  /**
   * fork process and create a worker
   * @param  {String} queueName name of queue which worker will consume
   * @param  {Number} queueWorkerNum
   * @return {Promise} worker promise
   */
  static fork (queueName) {
    const queueWorkerNum = queueWorkerCounter.inc(queueName)

    return co(function * () {
      // fork process
      debug(`worker create "${queueName}:${queueWorkerNum}"`)
      const env = put(process.env, {
        COWORKERS_QUEUE: queueName,
        COWORKERS_QUEUE_WORKER_NUM: queueWorkerNum
      })
      const worker = cluster.fork(env)
      // handle worker messages
      worker.on('message', ClusterManager.messageHandler)
      // set custom properties
      worker.__queueName = queueName
      worker.__queueWorkerNum = queueWorkerNum
      // worker created
      debug(`worker created pid=${worker.process.pid} "${queueName}:${queueWorkerNum}"`)
      // wait for successful connection to rabbit, or error
      //   note: waiting for connect will call close if it fails.
      //     if close fails process will exit -> coworkers:close:error
      const events = yield [
        first(worker, [ 'error', 'online' ]).then(function () {
          debug(`worker online "${queueName}:${queueWorkerNum}"`)
        }),
        first(worker, [ 'exit', 'coworkers:close', 'coworkers:close:error', 'coworkers:connect' ])
      ]
      const onlineEvent = events[1]
      const event = onlineEvent.event
      // check if worker exited before connecting (to rabbitmq)
      if (event === 'exit') {
        debug(`worker process exited before connect "${queueName}:${queueWorkerNum}"`)
        throw new Error(`worker process exited before connect "${queueName}:${queueWorkerNum}"`)
      }
      // check if worker failed to connect (connection closed instead of connected)
      if (event.indexOf('coworkers:close') === 0) {
        debug(`worker connect errored "${queueName}:${queueWorkerNum}"`)
        debug(`worker connect errored -> kill worker "${queueName}:${queueWorkerNum}"`)
        // kill the disconnected worker and throw the error
        yield ClusterManager.killWorker(worker)
        throw new Error(`worker connect errored "${queueName}:${queueWorkerNum}"`)
      }
      // worker successfully connected to rabbitmq
      debug(`worker connect success "${queueName}:${queueWorkerNum}"`)
      // respawn worker if it exists
      worker.once('exit', ClusterManager.respawnWorker)
      return worker
    }).catch(function (err) {
      // log err and rethrow
      debug(`worker create error "${queueName}:${queueWorkerNum}"`, err)
      throw err
    })
  }
  /**
   * worker exit handler
   * @param  {Number} code   exit code of worker process
   * @param  {String} signal signal that caused worker process exit
   */
  static respawnWorker (code, signal) {
    const worker = this
    const queueName = worker.__queueName
    const queueWorkerNum = worker.__queueWorkerNum
    const COWORKERS_RESPAWN_RETRY_ATTEMPTS = process.env.COWORKERS_RESPAWN_RETRY_ATTEMPTS
    const COWORKERS_RESPAWN_RETRY_MIN_TIMEOUT = process.env.COWORKERS_RESPAWN_RETRY_MIN_TIMEOUT
    const COWORKERS_RESPAWN_RETRY_FACTOR = process.env.COWORKERS_RESPAWN_RETRY_FACTOR
    const opts = {
      retries: exists(COWORKERS_RESPAWN_RETRY_ATTEMPTS) ? COWORKERS_RESPAWN_RETRY_ATTEMPTS : 20,
      minTimeout: exists(COWORKERS_RESPAWN_RETRY_MIN_TIMEOUT) ? COWORKERS_RESPAWN_RETRY_MIN_TIMEOUT : 10,
      factor: exists(COWORKERS_RESPAWN_RETRY_FACTOR) ? COWORKERS_RESPAWN_RETRY_FACTOR : 1
    }
    debug(`worker exited with code=${code} signal=${signal} "${queueName}:${queueWorkerNum}"`)
    return retry(opts, function (retry, attempt) {
      return co(function * () {
        // if signal is SIGINT, do not respawn
        if (signal === 'SIGINT') {
          debug(`no respawn. process exited w/ SIGINT "${queueName}:${queueWorkerNum}"`)
          return
        }
        // respawn worker
        const attemptMsg = attempt > 1 ? ` attempt=${attempt}` : ''
        debug(`respawn worker${attemptMsg} "${queueName}:${queueWorkerNum}"`)
        yield ClusterManager.fork(queueName)
      }).catch(function (err) {
        debug(`respawn failed for "${queueName}:${queueWorkerNum}"`, err)
        retry(err)
      })
    }).catch(function (err) {
      debug(`all ${opts.retries} respawn worker attempts failed "${queueName}:${queueWorkerNum}"`, err)
      process.nextTick(function () {
        throw err
      })
    })
  }
  /**
   * stop a worker
   * @param  {Worker} worker cluster worker to stop
   * @return {Promise} stop promise
   */
  static killWorker (worker) {
    const queueName = worker.__queueName
    const queueWorkerNum = worker.__queueWorkerNum
    const COWORKERS_KILL_RETRY_ATTEMPTS = process.env.COWORKERS_KILL_RETRY_ATTEMPTS
    const COWORKERS_KILL_RETRY_MIN_TIMEOUT = process.env.COWORKERS_KILL_RETRY_MIN_TIMEOUT
    const COWORKERS_KILL_RETRY_FACTOR = process.env.COWORKERS_KILL_RETRY_FACTOR
    const opts = {
      retries: exists(COWORKERS_KILL_RETRY_ATTEMPTS) ? COWORKERS_KILL_RETRY_ATTEMPTS : 20,
      minTimeout: exists(COWORKERS_KILL_RETRY_MIN_TIMEOUT) ? COWORKERS_KILL_RETRY_MIN_TIMEOUT : 10,
      factor: exists(COWORKERS_KILL_RETRY_FACTOR) ? COWORKERS_KILL_RETRY_FACTOR : 1
    }

    return retry(opts, function (retry, attempt) {
      return co(function * () {
        const attemptMsg = attempt > 1 ? ` attempt=${attempt}` : ''
        debug(`kill worker${attemptMsg} "${queueName}:${queueWorkerNum}"`)
        // check if worker is already killed
        if (worker.process.killed) {
          debug(`worker already killed "${queueName}:${queueWorkerNum}"`)
          return
        }
        // kill worker
        worker.kill('SIGINT') // handled in application.js
        // wait until worker is exits
        yield first(worker, [ 'error', 'exit' ])
      }).then(function () {
        debug(`worker exit success "${queueName}:${queueWorkerNum}"`)
      }).catch(function (err) {
        debug(`worker exit errorer "${queueName}:${queueWorkerNum}"`, err)
        retry(err)
      })
    }).catch(function (err) {
      debug(`all ${opts.retries} kill worker attempts failed "${queueName}:${queueWorkerNum}"`, err)
      throw err
    })
  }
  /**
   * handler messages and look for coworker events
   * if a coworker event message is recieved emit the event on the worker
   * @param {Object} message object
   */
  static messageHandler (msg) {
    const queueName = this.__queueName
    const queueWorkerNum = this.__queueWorkerNum
    debug(`worker got a message "${queueName}:${queueWorkerNum}"`)
    if (msg.coworkersEvent) {
      debug(`worker got a coworkers message ${msg.coworkersEvent} "${queueName}:${queueWorkerNum}"`)
      this.emit(msg.coworkersEvent)
    }
  }
  /**
   * start cluster manager and create worker processes
   * @return {Promise} start promise
   */
  start () {
    debug(`master pid=${process.pid}`)
    debug('master start')
    const self = this

    if (this.startingPromise) {
      return this.startingPromise
    }

    if (cluster.workers.length) {
      debug('workers exist, stop them before start')
      // not completely stopped, cleanup first
      this.startingPromise = self.stop()
        .catch(function (err) {
          debug('cluster-manager stop (before start) errored', err)
          const startErr = new Error('Start cancelled because pending stop failed (.stopErr)')
          startErr.stopErr = err
          // delete connecting promise, connect cancelled
          delete self.startingPromise
          throw startErr
        })
        .then(function () {
          debug('cluster-manager stop (before start) success')
          delete self.startingPromise
          return self.start()
        })

      return self.startingPromise
    }

    this.startingPromise = co(function * () {
      const COWORKERS_WORKERS_PER_QUEUE = getEnv().COWORKERS_WORKERS_PER_QUEUE
      const numQueues = self.app.queueNames.length
      const numCpus = os.cpus().length
      let queueNames

      debug('num cpus %s', numCpus)
      debug('num queues %s', numQueues)
      debug('queue names %o', self.app.queueNames)

      if (exists(COWORKERS_WORKERS_PER_QUEUE) || numCpus > numQueues) {
        // The number of cpus is greater than the number of consumers (processes).
        // To optimize cpu-usage, the number of processes should be greater.
        // Create "n" clones of each consumer, so that n * queues >= cpus.
        let workersPerQueue = exists(COWORKERS_WORKERS_PER_QUEUE)
          ? COWORKERS_WORKERS_PER_QUEUE
          : Math.ceil(numCpus / numQueues)
        debug('workers / queue %s', workersPerQueue)

        queueNames = []
        times(workersPerQueue, function () {
          queueNames = queueNames.concat(self.app.queueNames)
        })
      } else {
        debug('workers / queue %s', 1)
        // numCpus < numQueues, so create one consumer per queue
        queueNames = self.app.queueNames
      }
      // wait for all forks to complete even if an error occurs
      const forkErrs = []
      debug('queueNames %o', queueNames)
      yield queueNames.map(function (queueName) {
        return ClusterManager.fork(queueName).catch(function (err) {
          forkErrs.push(err)
        })
      })
      // check if any worker forks failed
      if (forkErrs.length) {
        const err = new Error('Some worker forks failed (.errors)')
        err.errors = forkErrs
        throw err
      }
    }).then(function () {
      delete self.startingPromise
      debug('cluster-manager start success')
    }).catch(function (err) {
      delete self.startingPromise
      debug('cluster-manager start errored', err)
      throw err
    })

    return this.startingPromise
  }
  /**
   * stop cluster manager, exit all worker processes, and allow master process to stop
   * @param  {String} signal signal to cause
   * @return {Promise} stop promise
   */
  stop (signal) {
    debug('master stop')
    return co(function * () {
      // wait for all kills to complete even if an error occurs
      const killErrs = []
      yield values(cluster.workers).map(function (worker) {
        return ClusterManager.killWorker(worker).catch(function (err) {
          killErrs.push(err)
        })
      })
      // check if any worker kills failed
      if (killErrs.length) {
        const err = new Error('Some worker kills failed (.errors)')
        err.errors = killErrs
        throw err
      }
      debug('cluster-manager stop success')
    }).catch(function (err) {
      debug('cluster-manager stop errored', err)
      throw err
    })
  }
}
<|endoftext|>


<commit_before>var restify = require('restify');
var server4socket = require("http").createServer().listen(8080);
var io = require("socket.io").listen(server4socket);

// API server with restify 8081------------------------------------------------
function hello(req, res, next) {
  res.send('hello ' + req.params.name + ' ' + req.params.add);
}

function move(req, res, next) {
  res.send('move ' + req.params.x + ' ' + req.params.y + ' ' + req.params.z);
}

function emergency(req, res, next) {
  res.send('emergency');
}

var server4api = restify.createServer();
server4api.use(restify.queryParser());

server4api.get('/hello', hello);
server4api.get('/move', move);
server4api.get('/emergency', emergency);

server4api.listen(8081, function() {
  console.log('%s listening at %s', server4api.name, server4api.url);
});
//-----------------------------------------------------------------------------

// socket wit socket.io 8080---------------------------------------------------
io.sockets.on("connection", function (socket) {
  // ジャイロを受け取る
  socket.on("gyro", function (data) {
    //io.sockets.emit("publish", {value:data.value});
    var obj = JSON.parse(data);
    var x = obj.dir_x;
    var y = obj.dir_y;
    //var z = data.dir_z;
    console.log(x + ' '+ y);
    //console.log(data);
  });
});
//------------------------------------------------------------------------------
<commit_msg>Add data pipe<commit_after>var restify = require('restify');
var server4socket = require("http").createServer().listen(8080);
var io = require("socket.io").listen(server4socket);

var sumo = require('jumping-night-drone');
var drone = sumo.createClient();

drone.connect(function() {
  //console.log("connect!");

  var video = drone.getVideoStream();
  video.on("data", function(data) {
    process.stdout.write(data);
  });

  // socket wit socket.io 8080---------------------------------------------------
  io.sockets.on("connection", function (socket) {
    // ジャイロを受け取る
    socket.on("gyro", function (data) {
      var obj = JSON.parse(data);
      var x = obj.dir_x;
      var y = obj.dir_y;
      //console.log(x + ' '+ y);

      if(y < 0){
        drone.stop();
        return;
      }

      if(x < 0){
        drone.curveForwardRight(30, -x*0.3);
      }else{
        drone.curveForwardLeft(30, x*0.3);
      }
    });
  });
  //------------------------------------------------------------------------------

});

// API server with restify 8081------------------------------------------------
function hello(req, res, next) {
  res.send('hello ' + req.params.name + ' ' + req.params.add);
}

function move(req, res, next) {
  res.send('move ' + req.params.x + ' ' + req.params.y + ' ' + req.params.z);
}

function emergency(req, res, next) {
  res.send('emergency');

  var server4socket2Client = require("http").createServer().listen(8082);
  var io2C = require("socket.io").listen(server4socket2Client);

}

var server4api = restify.createServer();
server4api.use(restify.queryParser());

server4api.get('/hello', hello);
server4api.get('/move', move);
server4api.get('/emergency', emergency);

server4api.listen(8081, function() {
  //console.log('%s listening at %s', server4api.name, server4api.url);
});
//-----------------------------------------------------------------------------
<|endoftext|>


<commit_before>(function(window, angular){
	'use strict';

	// DESCRIPTION:
	// vsRepeat directive stands for Virtual Scroll Repeat. It turns a standard ngRepeated set of elements in a scrollable container
	// into a component, where the user thinks he has all the elements rendered and all he needs to do is scroll (without any kind of
	// pagination - which most users loath) and at the same time the browser isn't overloaded by that many elements/angular bindings etc.
	// The directive renders only so many elements that can fit into current container's clientHeight.

	// LIMITATIONS:
	// - current version works only for vertically stacked elements
	// - current version only supports an Array as a right-hand-side object for ngRepeat
	// - all rendered elements must have the same predefined height

	// USAGE:
	// In order to use the vsRepeat directive you need to measure the single element's height (including all paddings and margins).
	// You can use any kind of developer tools you like. Let's say that that height is 50px.
	// example:
	//

	//

	//
	//

	//

	//
	// - the vsRepeat directive must be applied to a direct parent of an element with ngRepeat
	// - the value of vsRepeat attribute is the single element's height measured in pixels

	// OPTIONAL PARAMETERS (attributes):
	// vs-scroll-parent="selector" - selector to the scrollable container. The directive will look for a closest parent matching
	// 								 the given selector (defaults to the current element)
	// vs-top-offset="value" - top offset in pixels (defaults to 0)
	// vs-excess="value" - an integer number representing the number of elements to be rendered outside of the current container's viewport
	// 					   (defaults to 2)

	// EVENTS:
	// - 'vsRepeatTrigger' - an event the directive listens for to manually trigger reinitialization
	// - 'vsRepeatReinitialized' - an event the directive emits upon reinitialization done

	var isMacOS = navigator.appVersion.indexOf('Mac') != -1,
		wheelEventName = typeof window.onwheel !== 'undefined' ? 'wheel' : typeof window.onmousewheel !== 'undefined' ? 'mousewheel' : 'DOMMouseScroll';
	angular.module('vs-repeat', []).directive('vsRepeat', ['$compile', function($compile){
		return {
			restrict: 'A',
			scope: true,
			compile: function($element, $attrs){
				var childClone = $element.children().eq(0).clone(),
					ngRepeatExpression = childClone.attr('ng-repeat'),
					expressionMatches = /^\s*(\S+)\s+in\s+(\S+)\s*(track\s+by\s+\S+)?/.exec(ngRepeatExpression),
					lhs = expressionMatches[1],
					rhs = expressionMatches[2],
					rhsSuffix = expressionMatches[3],
					collectionName = '$vs_collection',
					originalCollection = [],
					originalLength,
					$wheelHelper,
					$fillElement;

				$element.empty();
				if(!window.getComputedStyle || window.getComputedStyle($element[0]).position !== 'absolute')
					$element.css('position', 'relative');
				return {
					pre: function($scope, $element, $attrs){
						$scope.elementHeight = parseInt($attrs.vsRepeat, 10);
						var $scrollParent = $attrs.vsScrollParent ? $element.closest($attrs.vsScrollParent) : $element;
						$scope.topOffset = $attrs.vsTopOffset ? parseInt($attrs.vsTopOffset, 10) : 0;
						$scope.excess = $attrs.vsExcess ? parseInt($attrs.vsExcess, 10) : 2;

						$scope.$watchCollection(rhs, function(coll){
							originalCollection = coll || [];
							if(!originalCollection || originalCollection.length < 1){
								$scope[collectionName] = [];
								originalLength = 0;
								$fillElement.css({'height': 0});
								return;
							}
							else{
								originalLength = originalCollection.length;
							}
							reinitialize();
						});

						childClone.attr('ng-repeat', lhs + ' in ' + collectionName + (rhsSuffix ? ' ' + rhsSuffix : ''))
								.attr('ng-style', '{top: ($index + startIndex) * elementHeight + topOffset}')
								.attr('style', 'position: absolute;');
						$compile(childClone)($scope);
						$element.append(childClone);

						$fillElement = $('

')
							.prependTo($element)
							.css({'position':'relative'});

						var _prevMouse = {};
						if(isMacOS){
							$wheelHelper = $('

')
								.appendTo($fillElement)
								.on(wheelEventName, function(e){
									e.preventDefault();
									e.stopPropagation();
									$scrollParent[0].scrollTop += (e.originalEvent.deltaY || -e.originalEvent.wheelDeltaY);
								}).on('mousemove', function(e){
									if(_prevMouse.x !== e.clientX || _prevMouse.y !== e.clientY)
										$(this).hide();
									_prevMouse = {
										x: e.clientX,
										y: e.clientY
									};
								}).hide();
						}

						$scope.startIndex = 0;
						$scope.endIndex = 0;

						$scrollParent.on('scroll.vs-repeat', function scrollHandler(e){
							if(updateInnerCollection())
								$scope.$apply();
						});

						if(isMacOS){
							$scrollParent.on(wheelEventName + '.vs-repeat', wheelHandler);
						}
						function wheelHandler(e){
							e.preventDefault();
							$wheelHelper.show();
						}

						function onWindowResize(){
							if(updateInnerCollection())
								$scope.$apply();
						}

						$(window).on('resize', onWindowResize);

						$scope.$on('$destroy', function(){
							$(window).off('resize', onWindowResize);
						});

						$scope.$on('vsRepeatTrigger', reinitialize);
						var _prevStartIndex,
							_prevEndIndex;
						function reinitialize(){
							_prevStartIndex = void 0;
							_prevEndIndex = void 0;
							updateInnerCollection();
							$fillElement.css({'height': $scope.elementHeight*originalLength});
							$scope.$emit('vsRepeatReinitialized');
						}

						var _prevClientHeight;
						function reinitOnClientHeightChange(){
							var ch = $scrollParent[0].clientHeight;
							if(ch !== _prevClientHeight){
								reinitialize();
								if(!$scope.$root.$$phase)
									$scope.$digest();
							}
							_prevClientHeight = ch;
						}

						$scope.$watch(function(){
							if(typeof window.requestAnimationFrame === "function")
								window.requestAnimationFrame(reinitOnClientHeightChange);
							else
								reinitOnClientHeightChange();
						});

						function updateInnerCollection(){
							$scope.startIndex = Math.max(
								Math.floor(
									($scrollParent[0].scrollTop) / $scope.elementHeight + $scope.excess/2
								) - $scope.excess,
								0
							);
							$scope.endIndex = Math.min(
								$scope.startIndex + Math.ceil(
									$scrollParent[0].clientHeight / $scope.elementHeight
								) + $scope.excess,
								originalLength
							);

							var digestRequired = $scope.startIndex !== _prevStartIndex || $scope.endIndex !== _prevEndIndex;

							if(digestRequired)
								$scope[collectionName] = originalCollection.slice($scope.startIndex, $scope.endIndex);

							_prevStartIndex = $scope.startIndex;
							_prevEndIndex = $scope.endIndex;

							return digestRequired;
						}
					}
				};
			}
		};
	}]);

	$('head').append([
		''
	].join(''));
})(window, window.angular);<commit_msg>fixed a bug when vsRepeat was nested inside another ngRepeat<commit_after>(function(window, angular){
	'use strict';

	// DESCRIPTION:
	// vsRepeat directive stands for Virtual Scroll Repeat. It turns a standard ngRepeated set of elements in a scrollable container
	// into a component, where the user thinks he has all the elements rendered and all he needs to do is scroll (without any kind of
	// pagination - which most users loath) and at the same time the browser isn't overloaded by that many elements/angular bindings etc.
	// The directive renders only so many elements that can fit into current container's clientHeight.

	// LIMITATIONS:
	// - current version works only for vertically stacked elements
	// - current version only supports an Array as a right-hand-side object for ngRepeat
	// - all rendered elements must have the same predefined height

	// USAGE:
	// In order to use the vsRepeat directive you need to measure the single element's height (including all paddings and margins).
	// You can use any kind of developer tools you like. Let's say that that height is 50px.
	// example:
	//

	//

	//
	//

	//

	//
	// - the vsRepeat directive must be applied to a direct parent of an element with ngRepeat
	// - the value of vsRepeat attribute is the single element's height measured in pixels

	// OPTIONAL PARAMETERS (attributes):
	// vs-scroll-parent="selector" - selector to the scrollable container. The directive will look for a closest parent matching
	// 								 the given selector (defaults to the current element)
	// vs-top-offset="value" - top offset in pixels (defaults to 0)
	// vs-excess="value" - an integer number representing the number of elements to be rendered outside of the current container's viewport
	// 					   (defaults to 2)

	// EVENTS:
	// - 'vsRepeatTrigger' - an event the directive listens for to manually trigger reinitialization
	// - 'vsRepeatReinitialized' - an event the directive emits upon reinitialization done

	var isMacOS = navigator.appVersion.indexOf('Mac') != -1,
		wheelEventName = typeof window.onwheel !== 'undefined' ? 'wheel' : typeof window.onmousewheel !== 'undefined' ? 'mousewheel' : 'DOMMouseScroll';
	angular.module('vs-repeat', []).directive('vsRepeat', ['$compile', function($compile){
		return {
			restrict: 'A',
			scope: true,
			compile: function($element, $attrs){
				var ngRepeatChild = $element.children().eq(0),
					ngRepeatExpression = ngRepeatChild.attr('ng-repeat'),
					childCloneHtml = ngRepeatChild[0].outerHTML,
					expressionMatches = /^\s*(\S+)\s+in\s+(\S+)\s*(track\s+by\s+\S+)?/.exec(ngRepeatExpression),
					lhs = expressionMatches[1],
					rhs = expressionMatches[2],
					rhsSuffix = expressionMatches[3],
					collectionName = '$vs_collection';

				$element.empty();
				if(!window.getComputedStyle || window.getComputedStyle($element[0]).position !== 'absolute')
					$element.css('position', 'relative');
				return {
					pre: function($scope, $element, $attrs){
						var childClone = angular.element(childCloneHtml),
							originalCollection = [],
							originalLength,
							$wheelHelper,
							$fillElement;

						$scope.elementHeight = parseInt($attrs.vsRepeat, 10);
						var $scrollParent = $attrs.vsScrollParent ? $element.closest($attrs.vsScrollParent) : $element;
						$scope.topOffset = $attrs.vsTopOffset ? parseInt($attrs.vsTopOffset, 10) : 0;
						$scope.excess = $attrs.vsExcess ? parseInt($attrs.vsExcess, 10) : 2;

						$scope.$watchCollection(rhs, function(coll){
							originalCollection = coll || [];
							if(!originalCollection || originalCollection.length < 1){
								$scope[collectionName] = [];
								originalLength = 0;
								$fillElement.css({'height': 0});
								return;
							}
							else{
								originalLength = originalCollection.length;
							}
							reinitialize();
						});

						childClone.attr('ng-repeat', lhs + ' in ' + collectionName + (rhsSuffix ? ' ' + rhsSuffix : ''))
								.attr('ng-style', '{top: ($index + startIndex) * elementHeight + topOffset}')
								.attr('style', 'position: absolute;');
						$compile(childClone)($scope);
						$element.append(childClone);

						$fillElement = angular.element('

')
							.css({'position':'relative'});
						$element.prepend($fillElement);

						var _prevMouse = {};
						if(isMacOS){
							$wheelHelper = angular.element('

')
								.on(wheelEventName, function(e){
									e.preventDefault();
									e.stopPropagation();
									$scrollParent[0].scrollTop += (e.originalEvent.deltaY || -e.originalEvent.wheelDeltaY);
								}).on('mousemove', function(e){
									if(_prevMouse.x !== e.clientX || _prevMouse.y !== e.clientY)
										angular.element(this).css('display', 'none');
									_prevMouse = {
										x: e.clientX,
										y: e.clientY
									};
								}).css('display', 'none');
							$fillElement.append($wheelHelper);
						}

						$scope.startIndex = 0;
						$scope.endIndex = 0;

						$scrollParent.on('scroll.vs-repeat', function scrollHandler(e){
							if(updateInnerCollection())
								$scope.$apply();
						});

						if(isMacOS){
							$scrollParent.on(wheelEventName + '.vs-repeat', wheelHandler);
						}
						function wheelHandler(e){
							e.preventDefault();
							$wheelHelper.css('display', 'block');
						}

						function onWindowResize(){
							if(updateInnerCollection())
								$scope.$apply();
						}

						angular.element(window).on('resize', onWindowResize);

						$scope.$on('$destroy', function(){
							angular.element(window).off('resize', onWindowResize);
						});

						$scope.$on('vsRepeatTrigger', reinitialize);
						var _prevStartIndex,
							_prevEndIndex;
						function reinitialize(){
							_prevStartIndex = void 0;
							_prevEndIndex = void 0;
							updateInnerCollection();
							$fillElement.css({'height': $scope.elementHeight*originalLength});
							$scope.$emit('vsRepeatReinitialized');
						}

						var _prevClientHeight;
						function reinitOnClientHeightChange(){
							var ch = $scrollParent[0].clientHeight;
							if(ch !== _prevClientHeight){
								reinitialize();
								if(!$scope.$root.$$phase)
									$scope.$digest();
							}
							_prevClientHeight = ch;
						}

						$scope.$watch(function(){
							if(typeof window.requestAnimationFrame === "function")
								window.requestAnimationFrame(reinitOnClientHeightChange);
							else
								reinitOnClientHeightChange();
						});

						function updateInnerCollection(){
							$scope.startIndex = Math.max(
								Math.floor(
									($scrollParent[0].scrollTop) / $scope.elementHeight + $scope.excess/2
								) - $scope.excess,
								0
							);
							$scope.endIndex = Math.min(
								$scope.startIndex + Math.ceil(
									$scrollParent[0].clientHeight / $scope.elementHeight
								) + $scope.excess,
								originalLength
							);

							var digestRequired = $scope.startIndex !== _prevStartIndex || $scope.endIndex !== _prevEndIndex;

							if(digestRequired)
								$scope[collectionName] = originalCollection.slice($scope.startIndex, $scope.endIndex);

							_prevStartIndex = $scope.startIndex;
							_prevEndIndex = $scope.endIndex;

							return digestRequired;
						}
					}
				};
			}
		};
	}]);

	angular.element(document.head).append([
		''
	].join(''));
})(window, window.angular);<|endoftext|>