<commit_before>
'use strict';

const _ = require('lodash');
const Script = require('smooch-bot').Script;

const scriptRules = require('./script.json');

var myDate = new Date();
var groet = '';

/* hour is before noon */
if ( myDate.getHours() < 8 )
{
  groet = "Goeiemorgen 🌝.  Bedankt voor je bezoek maar op dit moment is Independer echter gesloten. 🕘 Uiteraard kun je met onze IndyBot verder praten maar er is helaas niemand die jouw vraag specifiek kan beantwoorden. Je kan je vraag ook doormailen 📩 naar info@independer. Dan komt het altijd goed.";
}
else
if ( myDate.getHours() >8 )
{
  groet = "Goeiemorgen 🌝 ";
}
else  /* Hour is from noon to 5pm (actually to 5:59 pm) */
if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 )
{
groet = "Goedendag 🌞";
}
else  /* the hour is after 5pm, so it is between 6pm and midnight */
if ( myDate.getHours() > 17&& myDate.getHours() <= 20 )
{
groet = "Goedenavond 🌙";
}
else
if (myDate.getHours() > 20  || myDate.getHours() <= 24 )
{
  groet = "Goedenavond 🌙  Bedankt voor je bezoek maar op dit moment is Independer echter gesloten. 🕘 Uiteraard kun je met onze IndyBot verder praten maar er is helaas niemand die jouw vraag specifiek kan beantwoorden. Je kan je vraag ook doormailen 📩 naar info@independer. Dan komt het altijd goed.";
}
else  /* the hour is not between 0 and 24, so something is wrong */
{
groet = "Welkom. ";
}

function wait(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}

module.exports = new Script({

 processing: {
prompt: (bot) => bot.say('![](http://www.bieg.nl/beeld/speechbubble.gif)'),
 receive: () => 'processing'
 },

start: {
    receive: (bot,message) => {
        const opening = message.text.trim().toUpperCase();
        return bot.say(`${groet}... Wat voor soort hypotheek zoek je? `)
        .then(() => bot.say(`![](http://www.bieg.nl/beeld/woningen.jpg)`))
        .then(() => bot.say(`%[Starters Hypotheek](postback:hypotheektype_starter)`))
        .then(() => bot.say (`%[Nieuwe hypotheek](postback:hypotheektype_nieuw) `))
        .then(() => bot.say (`%[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`))
        .then(() => 'selecteerHypotheek');
    }
},

selecteerHypotheek: {
    receive: (bot, message) => {
      switch(message.text) {
      case 'Hoi':
            return bot.say(`${groet} waar ben je naar op zoek? %[Starters hypotheek](postback:hypotheektype_starter) %[Nieuwe hypotheek](postback:hypotheektype_nieuw) %[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`)
            .then(() => 'askName')
          break;
      case 'Starters Hypotheek':
          return bot.say(`Wat voor type woning zoek je? `)
          .then(() => bot.say(`%[🏬 Appartement](postback:hypotheekkeuze_appartement) %[🏠 Huis](postback:hypotheekkeuze_huis) %[📭 Vakantiewoning](postback:hypotheekkeuze_vakantiewoning)`))
          .then(() => 'woningType')
              break;
        case 'Nieuwe hypotheek':
          return bot.say(`😞 Helaas biedt Independer momenteel alleen Starters een hypotheek aan.`)
          .then(() => bot.say(`Via onderstaande link kun je de beste hypotheekadviseur voor jou vinden. %[💼 Zoek Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/jelocatie.aspx)`))
            .then(() => 'finish')
          break;
        case 'Hypotheek oversluiten':
          return bot.say(`😟 Het spijt me maar op dit moment biedt Independer alleen  Starters een hypotheek.`)
          .then(()=> bot.say(`Als het allemaal wel zo ver is, wil je dan een update ontvangen? %[Ja, dat wil ik wel](postback:update_ja) %[Nee, dat hoeft niet](postback:update_nee)`))
            .then(() => 'updateOntvangen')
          break;
        default:
          return bot.say(`![](http://www.bieg.nl/beeld/speechbubble.gif)`)
            .then(() => 'processing')
          break;
      }
    }
},

updateOntvangen: {
    receive: (bot, message) => {
      switch(message.text) {
        case 'Ja, dat wil ik wel':
            return bot.say(`👍 Leuk, dan houd ik  je op de hoogte zodra er weer nieuws is.`)
            .then(() => 'update_ja');
          break;
          case 'Nee, dat hoeft niet':
              receive: () => 'bye'
              break;
          default:
            receive => 'processing'
            break;
}
}
},

update_ja: {
  prompt: (bot) => bot.say('Wat is je email adres?'),
      receive: (bot, message) => {
          const emailer=message.text;
          return bot.setProp('emailer', emailer)
              .then(()  => bot.say(`Ok - ✉  dan hou ik je via ${emailer} op de hoogte.`))
              .then(()  =>'lastCheck')
    }
},
update_nee: {
  receive: () => 'bye'
},

hypotheekStarter: {
    receive: () => 'askName'
},
hypotheektype_nieuw: {
    prompt: (bot) => bot.say('Independer biedt momenteel alleen voor Starters een hypotheek. Onderstaande link bied je meer informatie %[Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/intro.aspx)'),
    receive: () => 'processing'
},

woningType: {
  receive: (bot, message) => {
    switch(message.text) {
        case '🏬 Appartement':
          return bot.say(`Nice!`)
          .then(() => 'vervolgVragen')
          break;
      case '🏠 Huis':
          return bot.say(`Leuk`)
          .then(() => 'vervolgVragen')
          break;
    case '📭 Vakantiewoning':
          return bot.say(`Gezellig`)
          .then(() => 'vervolgVragen')
          break;
      default:
        receive => 'processing'
        break;
        }
    }
},

vervolgVragen: {
  prompt: (bot) => bot.say('Hoe heet je eigelijk? 😋'),
          receive: (bot, message) => {
              const Name = message.text.trim().toUpperCase();
              return bot.setProp('Name', Name)
                  .then(() => bot.say('Hoi ${Name}. 📋 Ik heb nog wat vragen voor je om verder te kunnen.'))
                  .then(() => bot.say('komt ie'));
            }
},

lastCheck: {
    prompt: (bot) => bot.say(' Is er nog iets waar ik  je bij kan helpen?  🔶  %[Ik zoek meer informatie](postback:meerInfo) %[Nee hoor](postback:bye)'),
          receive: (bot, message) => {
            switch(message.text) {
              case 'Nee hoor':
                  receive: ()  => 'bye'
                  break;
             case 'Ik zoek meer informatie':
                  receive: () => 'speak'
                  break;
            case 'Nee':
                  receive: () => 'bye'
                  break;
            default:
              return bot.say('![](http://www.bieg.nl/beeld/speechbubble.gif)')
                .then(() => 'processing')
              break;
            }
        }
},

meerInfo: {
  prompt: (bot) => bot.say('![](http://www.bieg.nl/beeld/info.pdf)'),
   receive: () => 'processing'
},

bye: {
    prompt: (bot) => bot.say('Fijn je gesproken te hebben. Bedankt voor je tijd ⏲'),
    receive: ()  => 'finish'
},

// error: {
// prompt: (bot) => bot.say('Sorry - kun je dat nog eens zeggen?  Er ging iets mis...'),
// receive: () => ''
// },

finish: {
receive: () => 'finish'
},

  speak: {
          receive: (bot, message) => {

              let upperText = message.text.trim().toUpperCase();

              function updateSilent() {
                  switch (upperText) {
                      case "CONNECT ME":
                          return bot.setProp("silent", true);
                      case "DISCONNECT":
                          return bot.setProp("silent", false);
                      default:
                          return Promise.resolve();
                  }
              }

              function getSilent() {
                  return bot.getProp("silent");
              }

              function processMessage(isSilent) {
                  if (isSilent) {
                      return Promise.resolve("speak");
                  }

                  if (!_.has(scriptRules, upperText)) {
                      return bot.say(`So, I'm good at structured conversations but stickers, emoji and sentences still confuse me. Say 'more' to chat about something else.`).then(() => 'speak');
                  }

                  var response = scriptRules[upperText];
                  var lines = response.split('\n');

                  var p = Promise.resolve();
                  _.each(lines, function(line) {
                      line = line.trim();
                      p = p.then(function() {
                          console.log(line);
                          return wait(50).then(function() {
                              return bot.say(line);
                          });
                      });
                  });

                  return p.then(() => 'speak');
              }

              return updateSilent()
                  .then(getSilent)
                  .then(processMessage);
          }
      }
});
<commit_msg>efq<commit_after>
'use strict';

const _ = require('lodash');
const Script = require('smooch-bot').Script;

const scriptRules = require('./script.json');

var myDate = new Date();
var groet = '';

/* hour is before noon */
if ( myDate.getHours() < 8 )
{
  groet = "Goeiemorgen 🌝.  Bedankt voor je bezoek maar op dit moment is Independer echter gesloten. 🕘 Uiteraard kun je met onze IndyBot verder praten maar er is helaas niemand die jouw vraag specifiek kan beantwoorden. Je kan je vraag ook doormailen 📩 naar info@independer. Dan komt het altijd goed.";
}
else
if ( myDate.getHours() >8 )
{
  groet = "Goeiemorgen 🌝 ";
}
else  /* Hour is from noon to 5pm (actually to 5:59 pm) */
if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 )
{
groet = "Goedendag 🌞";
}
else  /* the hour is after 5pm, so it is between 6pm and midnight */
if ( myDate.getHours() > 17&& myDate.getHours() <= 20 )
{
groet = "Goedenavond 🌙";
}
else
if (myDate.getHours() > 20  || myDate.getHours() <= 24 )
{
  groet = "Goedenavond 🌙  Bedankt voor je bezoek maar op dit moment is Independer echter gesloten. 🕘 Uiteraard kun je met onze IndyBot verder praten maar er is helaas niemand die jouw vraag specifiek kan beantwoorden. Je kan je vraag ook doormailen 📩 naar info@independer. Dan komt het altijd goed.";
}
else  /* the hour is not between 0 and 24, so something is wrong */
{
groet = "Welkom. ";
}

function wait(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}

module.exports = new Script({

 processing: {
prompt: (bot) => bot.say('![](http://www.bieg.nl/beeld/speechbubble.gif)'),
 receive: () => 'processing'
 },

start: {
    receive: (bot,message) => {
        const opening = message.text.trim().toUpperCase();
        return bot.say(`${groet}... Wat voor soort hypotheek zoek je? `)
        .then(() => bot.say(`![](http://www.bieg.nl/beeld/woningen.jpg)`))
        .then(() => bot.say(`%[Starters Hypotheek](postback:hypotheektype_starter)`))
        .then(() => bot.say (`%[Nieuwe hypotheek](postback:hypotheektype_nieuw) `))
        .then(() => bot.say (`%[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`))
        .then(() => 'selecteerHypotheek');
    }
},

selecteerHypotheek: {
    receive: (bot, message) => {
      switch(message.text) {
      case 'Hoi':
            return bot.say(`${groet} waar ben je naar op zoek? %[Starters hypotheek](postback:hypotheektype_starter) %[Nieuwe hypotheek](postback:hypotheektype_nieuw) %[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`)
            .then(() => 'askName')
          break;
      case 'Starters Hypotheek':
          return bot.say(`Wat voor type woning zoek je? `)
          .then(() => bot.say(`%[🏬 Appartement](postback:hypotheekkeuze_appartement) %[🏠 Huis](postback:hypotheekkeuze_huis) %[📭 Vakantiewoning](postback:hypotheekkeuze_vakantiewoning)`))
          .then(() => 'woningType')
              break;
        case 'Nieuwe hypotheek':
          return bot.say(`😞 Helaas biedt Independer momenteel alleen Starters een hypotheek aan.`)
          .then(() => bot.say(`Via onderstaande link kun je de beste hypotheekadviseur voor jou vinden. %[💼 Zoek Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/jelocatie.aspx)`))
            .then(() => 'finish')
          break;
        case 'Hypotheek oversluiten':
          return bot.say(`😟 Het spijt me maar op dit moment biedt Independer alleen  Starters een hypotheek.`)
          .then(()=> bot.say(`Als het allemaal wel zo ver is, wil je dan een update ontvangen? %[Ja, dat wil ik wel](postback:update_ja) %[Nee, dat hoeft niet](postback:update_nee)`))
            .then(() => 'updateOntvangen')
          break;
        default:
          return bot.say(`![](http://www.bieg.nl/beeld/speechbubble.gif)`)
            .then(() => 'processing')
          break;
      }
    }
},

updateOntvangen: {
    receive: (bot, message) => {
      switch(message.text) {
        case 'Ja, dat wil ik wel':
            return bot.say(`👍 Leuk, dan houd ik  je op de hoogte zodra er weer nieuws is.`)
            .then(() => 'update_ja');
          break;
          case 'Nee, dat hoeft niet':
              receive: () => 'bye'
              break;
          default:
            receive => 'processing'
            break;
}
}
},

update_ja: {
  prompt: (bot) => bot.say('Wat is je email adres?'),
      receive: (bot, message) => {
          const emailer=message.text;
          return bot.setProp('emailer', emailer)
              .then(()  => bot.say(`Ok - ✉  dan hou ik je via ${emailer} op de hoogte.`))
              .then(()  =>'lastCheck')
    }
},
update_nee: {
  receive: () => 'bye'
},

hypotheekStarter: {
    receive: () => 'askName'
},
hypotheektype_nieuw: {
    prompt: (bot) => bot.say('Independer biedt momenteel alleen voor Starters een hypotheek. Onderstaande link bied je meer informatie %[Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/intro.aspx)'),
    receive: () => 'processing'
},

woningType: {
  receive: (bot, message) => {
    switch(message.text) {
        case '🏬 Appartement':
          return bot.say(`Nice!`)
          .then(() => 'vervolgVragen')
          break;
      case '🏠 Huis':
          return bot.say(`Leuk`)
          .then(() => 'vervolgVragen')
          break;
    case '📭 Vakantiewoning':
          return bot.say(`Gezellig`)
          .then(() => 'vervolgVragen')
          break;
      default:
        receive => 'processing'
        break;
        }
    }
},

vervolgVragen: {
  prompt: (bot) => bot.say('Hoe heet je eigelijk? 😋'),
          receive: (bot, message) => {
              const Name = message.text.trim().toUpperCase();
              return bot.setProp('Name', Name)
                  .then(() => bot.say('Hoi ${Name}. 📋 Ik heb nog wat vragen voor je om verder te kunnen.'))
                  .then(() => 'processing')
            }
},

lastCheck: {
    prompt: (bot) => bot.say(' Is er nog iets waar ik  je bij kan helpen?  🔶  %[Ik zoek meer informatie](postback:meerInfo) %[Nee hoor](postback:bye)'),
          receive: (bot, message) => {
            switch(message.text) {
              case 'Nee hoor':
                  receive: ()  => 'bye'
                  break;
             case 'Ik zoek meer informatie':
                  receive: () => 'speak'
                  break;
            case 'Nee':
                  receive: () => 'bye'
                  break;
            default:
              return bot.say('![](http://www.bieg.nl/beeld/speechbubble.gif)')
                .then(() => 'processing')
              break;
            }
        }
},

meerInfo: {
  prompt: (bot) => bot.say('![](http://www.bieg.nl/beeld/info.pdf)'),
   receive: () => 'processing'
},

bye: {
    prompt: (bot) => bot.say('Fijn je gesproken te hebben. Bedankt voor je tijd ⏲'),
    receive: ()  => 'finish'
},

// error: {
// prompt: (bot) => bot.say('Sorry - kun je dat nog eens zeggen?  Er ging iets mis...'),
// receive: () => ''
// },

finish: {
receive: () => 'finish'
},

  speak: {
          receive: (bot, message) => {

              let upperText = message.text.trim().toUpperCase();

              function updateSilent() {
                  switch (upperText) {
                      case "CONNECT ME":
                          return bot.setProp("silent", true);
                      case "DISCONNECT":
                          return bot.setProp("silent", false);
                      default:
                          return Promise.resolve();
                  }
              }

              function getSilent() {
                  return bot.getProp("silent");
              }

              function processMessage(isSilent) {
                  if (isSilent) {
                      return Promise.resolve("speak");
                  }

                  if (!_.has(scriptRules, upperText)) {
                      return bot.say(`So, I'm good at structured conversations but stickers, emoji and sentences still confuse me. Say 'more' to chat about something else.`).then(() => 'speak');
                  }

                  var response = scriptRules[upperText];
                  var lines = response.split('\n');

                  var p = Promise.resolve();
                  _.each(lines, function(line) {
                      line = line.trim();
                      p = p.then(function() {
                          console.log(line);
                          return wait(50).then(function() {
                              return bot.say(line);
                          });
                      });
                  });

                  return p.then(() => 'speak');
              }

              return updateSilent()
                  .then(getSilent)
                  .then(processMessage);
          }
      }
});
<|endoftext|>


<commit_before>'use strict';

const Script = require('smooch-bot').Script;

module.exports = new Script({
    processing: {
        prompt: (bot) => bot.say('Beep boop...'),
        receive: () => 'processing'
    },

    start: {
        receive: (bot) => {
            return bot.say('Hallo! ich bin Andreas Sefzigs Bot.')
                .then(() => bot.say('Wenn Andreas online ist, sieht er unsere Unterhaltung. Darf ich Sie zunächst ankündigen?'))
                .then(() => 'askName');
        }
    },

    askName: {
        prompt: (bot) => bot.say('Wie sollen wir Sie nennen?'),
        receive: (bot, message) => {
            const name = message.text;
            return bot.setProp('name', name)
                .then(() => bot.say(`Prima, wir nennen Sie ${name}.`))
                .then(() => 'register');
        }
    },

    register: {
        prompt: (bot) => bot.say('Wollen Sie --Person oder --Kompetenzen?'),
        receive: (bot, message) => {

            const wollen = message.text.replace("--", "");

            if (wollen == "HALLO") { bot.say('Begrüßung und alles.'); }

            return bot.setProp('wollen', wollen)
                .then(() => 'finish');
        }
    },

    finish: {
        receive: (bot, message) => {
            return bot.getProp('name')
                .then(() => 'finish');
        }
    }
});
<commit_msg>Tests<commit_after>'use strict';

const Script = require('smooch-bot').Script;

module.exports = new Script({
    processing: {
        prompt: (bot) => bot.say('Beep boop...'),
        receive: () => 'processing'
    },

    start: {
        receive: (bot) => {
            return bot.say('Hallo! ich bin Andreas Sefzigs Bot.')
                .then(() => bot.say('Wenn Andreas online ist, sieht er diese Unterhaltung.'))
                .then(() => 'askName');
        }
    },

    askName: {
        prompt: (bot) => bot.say('Wie sollen wir Sie nennen?'),
        receive: (bot, message) => {
            const name = message.text;
            return bot.setProp('name', name)
                .then(() => bot.say(`Prima, wir nennen Sie ${name}.`)),
                .then(() => bot.say('Wollen Sie --Person oder --Kompetenzen?'))
                .then(() => 'register');
        }
    },

    register: {
        receive: (bot, message) => {

            const wollen = message.text;
            var befehl = wollen;
            befehl = befehl.replace("--", "");
            befehl = befehl.trim();
            befehl = befehl.toUpperCase();

            if (befehl == "HALLO")     { bot.say('Begrüßung und alles.'); }
            if (befehl == "ABBRECHEN") { bot.say('Text zum Abbruch.'); }

            return bot.setProp('wollen', wollen)
                .then(() => 'register');
        }
    },

    finish: {
        receive: (bot, message) => {
            return bot.getProp('name')
                .then(() => 'finish');
        }
    }
});
<|endoftext|>


<commit_before>//  The calculator pseudoClass represents a four-function calculator.
//  The following both defines and constructs the singleton calculator object.

//  This file is part of Abacus For The Rest Of Us
//  Copyright (C) 2013 Max Galloway-Carson
//
//  Abacus For The Rest Of Us is free software: you can redistribute it and/or modify
//  it under the terms of the GNU Affero General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//  GNU Affero General Public License for more details.
//
//  You should have received a copy of the GNU Affero General Public License
//  along with this program. If not, see <http://www.gnu.org/licenses/>.
//
//  email me at: maxvgc@gmail.com

var calculator = (function () {

    'use strict';

    var model,
        view,
        controller;

//  model pseudoclass is an internal representation of
//  the calculator's state.

    model = {

        tally : 0, // running total since last clear

        operator : '+', // last operator pressed

        temp : '', // number, as it entered by user

        isClear : true, // flag indicates whether there has been output

//      The evaluate function performs a computation.
//      First, it performs the stored operation on temp and tally.
//      Then it stores the given operation for the next evaluation.
//
//      Returns the state to show to user.

        evaluate : function (operate) {

//      Special condition if there has not been output yet.

            var tempN = parseFloat(this.temp);

            if (this.isClear) {

                this.tally = tempN;
                this.isClear = false;

            } else {

//              Perform the stored operation on tally and temp

                switch (this.operator) {

                case '+':
                    this.tally += tempN;
                    break;

                case '-':
                    this.tally -= tempN;
                    break;

                case 'x':
                    this.tally *= tempN;
                    break;

                case '/':
                    this.tally /= tempN;
                    break;

                }
            }

//          In either case, update the display, and prepare for
//          next input

            this.temp = '0'; // reset temp
            this.operator = operate; // get ready to perform
            // the given operation

            if (isNaN(this.tally)) {
                this.reset();
            }

            return this.tally; // user sees result of computation
        },

//      The update function will take string representing a single
//      digit, and
//      append it to what the user has entered so far, both on the
//      screen and internally.
//      Returns the state to show to user.

        update : function (lastDigit) {

//          wipe out display to prevent leading zero
            if (this.temp === '0') {
                this.temp = '';
            }

//          concat display with new input
            this.temp += lastDigit;

            return this.temp; // user sees number entered thus far
        },

//      The reset function clears the calculator's instance
//      variables, and wipes the screen.

        reset : function () {
            this.tally = 0;
            this.operator = '+';
            this.temp = '0';
            this.isClear = true;
            return 0;
        }

    }; // end model

//  view is the representation of the screen.

    view = {

//      the object holding the output.

        display : {
            innerHTML : "0"
        },

//      method to set display to given number

        output : function (val) {

            this.display.innerHTML = val;

        },

//      Sets sets given object to be the new display.
//      Copies the old output into new display.

        setDisplay : function (newScreen) { // function

            if (typeof newScreen === 'object') {

                newScreen.innerHTML = this.display.innerHTML;

                this.display = newScreen;
            }
        }
    }; // end view

//  These are the calculator's publicly facing methods.
//  They should be consided the controller.

//  Enter number is called when a user presses a digit, and takes that
//  digit as a param. If possible, enterNumber will pass that digit
//  to the inner calculator's update method.

    controller = {
        enterNumber : function (num) {

            if (typeof model.update === 'function') {

//              Pass response from model's update method to
//              the view
                view.output(model.update(num));
            }
        },

//      Enter operator is called when a user presses an operator,
//      and takes that operator as a param. If possible, enterOperator
//      will pass that operator to the inner calculator's
//      evaluate method.

        enterOperator : function (opp) {

            if (typeof model.evaluate === 'function') {

//              Pass response from model's evaluate method to
//              the view
                view.output(model.evaluate(opp));
            }
        },

//      Clear is called when a user presses the clear button, and
//      takes no params. If possible, clear will call the inner
//      calculator's reset method.

        clear : function () {

            if (typeof model.reset === 'function') {

//              Pass response from model's reset method to
//              the view
                view.output(model.reset());
            }
        },

//      Set Display takes an object, and set it to be the
//      Calculator's new output field.

        setDisplay : function (obj) {

            view.setDisplay(obj);
        }
    };

    return controller;

}()); // end calculator definition

// This is where the setup for the calculator happens. It's all
// inside an anonymous function, so the vars and the functions
// will go away at the end.

(function () {

    'use strict';

    var numbers,
        operators,
        i,
        k,
        request;

//  First, create click handlers for the buttons

//  function takes a number button dom element, and
//  attaches calc's enterNumber method to its click event
    function bindNum(obj) {
        obj.onclick = function () {
            calculator.enterNumber(this.value); // 'this' is obj (a num btn)
        };
    }

//  function takes a function button dom element, and
//  attaches calc's enterOperator method to its click event
    function bindOpp(obj) {
        obj.onclick = function () {
            calculator.enterOperator(this.value); // 'this' is obj (a fn btn)
        };
    }

//  Second, run setup routine, in which page elements are bound to
//  calculator methods.

//  Start by calling the calcuator's init method, passing
//  in an output element to be the display.

    /*jslint browser:true*/

    calculator.setDisplay(document.getElementById('out'));

//  Move onto binding the numbers' click
//  event to the calculator's update method.

    numbers = document.getElementsByClassName('number');

    for (i = 0; i < numbers.length; i += 1) {

//      clicking a number will update the display and
//      the temp variable

        bindNum(numbers[i]);
    }

    operators = document.getElementsByClassName('operator');

    for (k = 0; k < operators.length; k += 1) {

//      clicking an operator will make the calculator
//      perform an operation.

        bindOpp(operators[k]);

    }

//  lastly, bind the clear function to the clear buttons' click event

    document.getElementById('clear').onclick = function () {
        calculator.clear();
    };

//  Try to install app in firefox os if it is not already installed
//  I have no error handlers, and only handle the first success,
//  because there is nothing to be done in other cases.

    request = navigator.mozApps.getSelf();

    request.onsuccess = function () {
        if (!request.result) { // not installed yet, try to

            navigator.mozApps.install(location.protocol + '//' + location.host + '/manifest.webapp');

        } // otherwise the app is already installed, so do nothing
    };

}()); // end the anonymous init function, and invoke it
<commit_msg>working on yuidoc documentation.<commit_after>/**
 * The calculator pseudoClass represents a four-function calculator. The
 * following both defines and constructs the singleton calculator object.
 *
 * @author Max Galloway-Carson
 * @version 1.0
 *
 * Note that I will be using yuidoc throughout
 * http://yui.github.com/yuidoc/syntax/index.html
 *
 * This file is part of Abacus For The Rest Of Us Copyright (C) 2013 Max
 * Galloway-Carson
 *
 * Abacus For The Rest Of Us is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http:*www.gnu.org/licenses/>.
 *
 * email me at: maxvgc@gmail.com
 */

var calculator = (function() {

    'use strict';

    var model, view, controller;

    /**
     * model pseudoclass is an internal representation of the calculator's
     * state.
     */
    model = {

        /**
         * running total since last clear
         *
         * @property tally
         * @type Number
         * @default 0
         */
        tally : 0,

        /**
         * last operator pressed
         *
         * @property operator
         * @type String
         * @default '+"
         */
        operator : '+',

        /**
         * number, as it entered by user
         *
         * @property temp
         * @type String
         * @default ''
         */
        temp : '',

        /**
         * flag indicates whether there has been output
         *
         * @property isClear
         * @type Boolean
         * @default true
         */
        isClear : true,

        /**
         * The evaluate function performs a computation. First, it performs the
         * stored operation on temp and tally. Then it stores the given
         * operation for the next evaluation.
         *
         * @method evaluate
         * @param {String}
         *            operate the operator that was pressed
         * @return {String} Returns the state to show to user.
         */
        evaluate : function(operate) {

            // Special condition if there has not been output yet.

            var tempN = parseFloat(this.temp);

            if (this.isClear) {

                this.tally = tempN;
                this.isClear = false;

            } else {

                // Perform the stored operation on tally and temp

                switch (this.operator) {

                case '+':
                    this.tally += tempN;
                    break;

                case '-':
                    this.tally -= tempN;
                    break;

                case 'x':
                    this.tally *= tempN;
                    break;

                case '/':
                    this.tally /= tempN;
                    break;

                }
            }

            // In either case, update the display, and prepare for
            // next input

            this.temp = '0'; // reset temp
            this.operator = operate; // get ready to perform
            // the given operation

            if (isNaN(this.tally)) {
                this.reset();
            }

            return this.tally; // user sees result of computation
        },

        /**
         * The update function will take string representing a single digit, and
         * append it to what the user has entered so far, both on the screen and
         * internally.
         *
         * @method update
         * @param {String} lastDigit: the value of the button being pressed
         * @return {String} Returns the state to show to user.
         */

        update : function(lastDigit) {

            // wipe out display to prevent leading zero
            if (this.temp === '0') {
                this.temp = '';
            }

            // concat display with new input
            this.temp += lastDigit;

            return this.temp; // user sees number entered thus far
        },

        /**
         * The reset function clears the calculator's instance variables, and
         * wipes the screen.
         *
         * @method reset
         * @return {Number} zero: the blank screen
         */
        reset : function() {
            this.tally = 0;
            this.operator = '+';
            this.temp = '0';
            this.isClear = true;
            return 0;
        }

    }; // end model

    /**
     * view is the representation of the screen.
     */
    view = {

        /**
         * the object holding the output.
         *
         * @property display
         * @type String
         * @default '0
         */
        display : {
            innerHTML : '0'
        },

        /**
         * set display to given number
         *
         * @method output
         * @param {any}
         * @return {null}
         */
        output : function(val) {

            this.display.innerHTML = val;
            return;
        },
        /**
         * Sets sets given object to be the new display. Copies the old output
         * into new display.
         *
         * @method setDisplay
         * @param {Object} node that will be new display
         * @return {null}
         */
        setDisplay : function(newScreen) { // function

            if (typeof newScreen === 'object') {

                newScreen.innerHTML = this.display.innerHTML;

                this.display = newScreen;
            }

            return;
        }
    }; // end view

    // These are the calculator's publicly facing methods.
    // They should be consided the controller.

    // Enter number is called when a user presses a digit, and takes that
    // digit as a param. If possible, enterNumber will pass that digit
    // to the inner calculator's update method.

    controller = {
        enterNumber : function(num) {

            if (typeof model.update === 'function') {

                // Pass response from model's update method to
                // the view
                view.output(model.update(num));
            }
        },

        // Enter operator is called when a user presses an operator,
        // and takes that operator as a param. If possible, enterOperator
        // will pass that operator to the inner calculator's
        // evaluate method.

        enterOperator : function(opp) {

            if (typeof model.evaluate === 'function') {

                // Pass response from model's evaluate method to
                // the view
                view.output(model.evaluate(opp));
            }
        },

        // Clear is called when a user presses the clear button, and
        // takes no params. If possible, clear will call the inner
        // calculator's reset method.

        clear : function() {

            if (typeof model.reset === 'function') {

                // Pass response from model's reset method to
                // the view
                view.output(model.reset());
            }
        },

        // Set Display takes an object, and set it to be the
        // Calculator's new output field.

        setDisplay : function(obj) {

            view.setDisplay(obj);
        }
    };

    return controller;

}()); // end calculator definition

// This is where the setup for the calculator happens. It's all
// inside an anonymous function, so the vars and the functions
// will go away at the end.

(function() {

    'use strict';

    var numbers, operators, i, k, request;

    // First, create click handlers for the buttons

    // function takes a number button dom element, and
    // attaches calc's enterNumber method to its click event
    function bindNum(obj) {
        obj.onclick = function() {
            calculator.enterNumber(this.value); // 'this' is obj (a num btn)
        };
    }

    // function takes a function button dom element, and
    // attaches calc's enterOperator method to its click event
    function bindOpp(obj) {
        obj.onclick = function() {
            calculator.enterOperator(this.value); // 'this' is obj (a fn btn)
        };
    }

    // Second, run setup routine, in which page elements are bound to
    // calculator methods.

    // Start by calling the calcuator's init method, passing
    // in an output element to be the display.

    /* jslint browser:true */

    calculator.setDisplay(document.getElementById('out'));

    // Move onto binding the numbers' click
    // event to the calculator's update method.

    numbers = document.getElementsByClassName('number');

    for (i = 0; i < numbers.length; i += 1) {

        // clicking a number will update the display and
        // the temp variable

        bindNum(numbers[i]);
    }

    operators = document.getElementsByClassName('operator');

    for (k = 0; k < operators.length; k += 1) {

        // clicking an operator will make the calculator
        // perform an operation.

        bindOpp(operators[k]);

    }

    // lastly, bind the clear function to the clear buttons' click event

    document.getElementById('clear').onclick = function() {
        calculator.clear();
    };

    // Try to install app in firefox os if it is not already installed
    // I have no error handlers, and only handle the first success,
    // because there is nothing to be done in other cases.

    request = navigator.mozApps.getSelf();

    request.onsuccess = function() {
        if (!request.result) { // not installed yet, try to

            navigator.mozApps.install(location.protocol + '//' + location.host
                    + '/manifest.webapp');

        } // otherwise the app is already installed, so do nothing
    };

}()); // end the anonymous init function, and invoke it
<|endoftext|>


<commit_before>$(document).ready(function(){

    var debug = true;

    var words;

    var vowels = ["a", "e", "ə", "i", "ı",  "ö", "o", "ü", "u"];

    function getSyllables(word) {

        var syllables = new Array();

        var c = word.length; // length of the word
        var i = c-1; // cursor
        var l = 1; // last syllable length
        var vowelFound = false;

        while (i > -1) {

            var _i = '', _i_1 = '', _s = '', _c = '', _c_1 = '', _l = l;

            var push = false;

            if ( i == 0) { // latest letter: push
                push = true;

            } else {

                var currentIsVowel = _.contains(vowels, word[i].toLowerCase());
                var previousIsVowel = _.contains(vowels, word[i-1].toLowerCase());

                _i = currentIsVowel;
                _i_1 = previousIsVowel;

                if ( currentIsVowel ) vowelFound = true;

                if ( currentIsVowel && previousIsVowel) {
                    push = true;
                }

                if ( (!currentIsVowel) && previousIsVowel && l > 1 && vowelFound) {
                    push = true;
                }

                if ( (!currentIsVowel) && (!previousIsVowel) && l > 1 && vowelFound) {
                    push = true;
                }

            }

            if (push) {

                var s = word.substr(i, l);
                syllables.unshift(s);

                l = 0;
                vowelFound = false;

                _s = s;

            }

            if (debug)
                alert('i=' + i + ' (' + previousIsVowel + ', ' + currentIsVowel + '), (' + _c_1 + ', ' + _c  +'), l=' + _l + ', s: ' + _s )

            l++; // syllable is goind on
            i--; // move cursor
        }

        return syllables;

    }

    $.getJSON( "words.json", function( data ) {
        words = data;
    });

    $("#search").click(function(){

        var query = $("#query").val();
        var syllables = getSyllables(query);
        var result = _.filter(words, function(word){ return word.match( _.last(syllables) + "$" ); });

        $("#results").text("");
        $.each(result, function(num, word) {
            $("#results").append('' + word + " ");
        });

    });

});<commit_msg>Debug disabled<commit_after>$(document).ready(function(){

    var debug = false;

    var words;

    var vowels = ["a", "e", "ə", "i", "ı",  "ö", "o", "ü", "u"];

    function getSyllables(word) {

        var syllables = new Array();

        var c = word.length; // length of the word
        var i = c-1; // cursor
        var l = 1; // last syllable length
        var vowelFound = false;

        while (i > -1) {

            var _i = '', _i_1 = '', _s = '', _c = '', _c_1 = '', _l = l;

            var push = false;

            if ( i == 0) { // latest letter: push
                push = true;

            } else {

                var currentIsVowel = _.contains(vowels, word[i].toLowerCase());
                var previousIsVowel = _.contains(vowels, word[i-1].toLowerCase());

                _i = currentIsVowel;
                _i_1 = previousIsVowel;

                if ( currentIsVowel ) vowelFound = true;

                if ( currentIsVowel && previousIsVowel) {
                    push = true;
                }

                if ( (!currentIsVowel) && previousIsVowel && l > 1 && vowelFound) {
                    push = true;
                }

                if ( (!currentIsVowel) && (!previousIsVowel) && l > 1 && vowelFound) {
                    push = true;
                }

            }

            if (push) {

                var s = word.substr(i, l);
                syllables.unshift(s);

                l = 0;
                vowelFound = false;

                _s = s;

            }

            if (debug)
                alert('i=' + i + ' (' + previousIsVowel + ', ' + currentIsVowel + '), (' + _c_1 + ', ' + _c  +'), l=' + _l + ', s: ' + _s )

            l++; // syllable is goind on
            i--; // move cursor
        }

        return syllables;

    }

    $.getJSON( "words.json", function( data ) {
        words = data;
    });

    $("#search").click(function(){

        var query = $("#query").val();
        var syllables = getSyllables(query);
        var result = _.filter(words, function(word){ return word.match( _.last(syllables) + "$" ); });

        $("#results").text("");
        $.each(result, function(num, word) {
            $("#results").append('' + word + " ");
        });

    });

});<|endoftext|>


<commit_before>'use strict';

const _ = require('lodash');
const Script = require('smooch-bot').Script;
var pg = require('pg');
var Q = require("q");
var request = require("request");
var newUser = require("./db");
var logConversation = require("./conversation");
var nlp = require("./nlp");
var pushConv = require("./push");
var newBot_msg = require("./newBot");

var sched = require("./sched");  //delete later

const scriptRules = require('./script.json');

var msgLog = {
    smoochId: '',
    received: '',
    usermessage: '',
    role: '',
    message_id: '',
    sourcetype: '',
    receivedtime: '',
    responsemessage: '',
    responsetype: '',
    responsetime: ''
  };

function wait(ms) {
    return new Promise((resolve) => {
        setTimeout(resolve, ms);
    });
}

module.exports = new Script({
    processing: {
        //prompt: (bot) => bot.say('Beep boop...'),
        receive: () => 'processing'
    },

    start: {
        receive: (bot) => {
            return bot.say('Hello!  I\'m A16, the Agile2016 EventBot Concierge.  To find out what I can help you with type MENU for options or KEY for Keywords.')
                .then(() => 'speak');
        }
    },

    speakers: {
      prompt: (bot) => bot.say('What speaker are you searching for?'),
      receive: (bot, message) => {
        const name = message.text;
        return bot.setProp('name', name)
          .then(() => bot.say(`I will search for ${name} is that OK? %[Yes]() %[No](postback:hello)`))
          .then(() => 'speak');
      }
    },

    finish: {
      receive: (bot, message) => {
        return bot.getProp('name')
          .then((name) => bot.say('That is all!'))
          .then(() => 'speak');
      }
    },

    speak: {
        receive: (bot, message) => {
            console.log("===bot user ");
            let upperText = message.text.trim().toUpperCase();

            if (upperText == 'SPEAKERS') {
              return bot.getProp('name')
              .then(() => 'speakers');
            }

            msgLog.smoochId = bot.userId;
            msgLog.received = message.received;
            msgLog.usermessage = message.text;
            msgLog.role = message.role;
            msgLog.message_id = message.message_id;
            msgLog.sourcetype = message.source.type;
            msgLog.receivedtime = new Date();

////here
            //sched.schedSessions('SessionList');

            //This is the control list of smoochId that can send broadcast messages
            var authUsers = ['a30fa820d0a0f0216fa26070'];

            newUser(bot)

            //For ad hoc messages - scheduled messages are done differently in checkItems
            if (authUsers.indexOf(bot.userId) !== -1) {
              if (upperText.substr(0,4) == '/SK ') {
                upperText = upperText.substr(0,3);
                newBot_msg(message.text.substr(4));
                console.log("****after push msg:  ",message.text," authUser:  ",authUsers);
              }
            }

            function updateSilent() {
                switch (upperText) {
                    case "CONNECT ME":
                        return bot.setProp("silent", true);
                    case "/SUPPORT":
                        return bot.setProp("silent", true);
                    case "DISCONNECT":
                        return bot.setProp("silent", false);
                    case "/A16":
                        console.log("*** ",upperText," ***");
                        processMessage(false);
                        return bot.setProp("silent", false);
                    default:
                        return Promise.resolve();
                }
            }

            function getSilent() {
                return bot.getProp("silent");
            }

            function processMessage(isSilent) {
                if (isSilent) {
                    return Promise.resolve("speak");
                }

                var promises = [];
                var source;
                var fulfillmentSpeech;
                var simplified;
                promises.push(nlp(upperText, bot.userId));

                Q.all(promises).then(function(responses) {
                    // response is the JSON from API.ai
                    responses.forEach(function(response) {
                        //console.log("===in Q.all");
                        console.log("===received result from API.ai",response);
                        source = response.result.source;
                        if (source && source !== 'agent')
                        {
                            fulfillmentSpeech = response.result.fulfillment.speech;
                            simplified = response.result.parameters.simplified;
                        }
//                        console.log("source: ", source);
//                        console.log("fulfillmentSpeech: ", fulfillmentSpeech);
//                        console.log("simplified: ", simplified);

                        respondMessage(source, fulfillmentSpeech, simplified);
                    });
                }, function(error) {
                    console.log("===Q all error ", error);
                });
            }

            function respondMessage(source, fulfillmentSpeech, simplified)
            {
//                console.log("source: ", source);
//                console.log("fulfillmentSpeech: ", fulfillmentSpeech);
//                console.log("simplified: ", simplified);
//                console.log("===receive step 3",upperText);

              if (source != 'agent')
                {
//                    console.log("===source is ", source);
                    if (fulfillmentSpeech)
                    {
                      switch (simplified) {
                        case "hello":
//                          console.log("===in hello");
                          upperText = simplified.trim().toUpperCase();
                          break;
                        case "what do you know":
//                          console.log("===in what do you know");
                          upperText = simplified.trim().toUpperCase();
                          break;
                        case "can you talk":
//                          console.log("===can you talk");
                          upperText = simplified.trim().toUpperCase();
                          break;
                        default:
//                          console.log("===in switch default");
                          msgLog.responsemessage = fulfillmentSpeech;
                          msgLog.responsetime = new Date;
                          msgLog.responsetype = 'API.AI';
                          return bot.say(fulfillmentSpeech).then(() => 'speak');
                      }
                    }
                    else if (simplified)
                    {
//                        console.log("simplified is: ", simplified);
                        upperText = simplified.toUpperCase();
                    }
                }
                if (!_.has(scriptRules, upperText)) {
//                    console.log("===no rule", upperText);
                    return bot.say(`I'm sorry that is not something I know.  Type MENU or KEY for a list of things I can help you with.`).then(() => 'speak');
                }

                var response = scriptRules[upperText];
                var lines = response.split('\n');

                var p = Promise.resolve();
                _.each(lines, function(line) {
                    line = line.trim();
                    p = p.then(function() {
                        console.log("=== p line",line);
                        return wait(5).then(function() {
                            msgLog.responsemessage = line;
                            msgLog.responsetime = new Date;
                            msgLog.responsetype = 'JSON';
                            console.log("=== msgLog  obj",msgLog);
                            logConversation(msgLog);
                            return bot.say(line);
                        });
                    });
                });
                return p.then(() => 'speak');
            }

            return updateSilent()
                .then(getSilent)
                .then(processMessage);
        }
    }
});
<commit_msg>fix to msgLog was not capturing _id<commit_after>'use strict';

const _ = require('lodash');
const Script = require('smooch-bot').Script;
var pg = require('pg');
var Q = require("q");
var request = require("request");
var newUser = require("./db");
var logConversation = require("./conversation");
var nlp = require("./nlp");
var pushConv = require("./push");
var newBot_msg = require("./newBot");

var sched = require("./sched");  //delete later

const scriptRules = require('./script.json');

var msgLog = {
    smoochId: '',
    received: '',
    usermessage: '',
    role: '',
    message_id: '',
    sourcetype: '',
    receivedtime: '',
    responsemessage: '',
    responsetype: '',
    responsetime: ''
  };

function wait(ms) {
    return new Promise((resolve) => {
        setTimeout(resolve, ms);
    });
}

module.exports = new Script({
    processing: {
        //prompt: (bot) => bot.say('Beep boop...'),
        receive: () => 'processing'
    },

    start: {
        receive: (bot) => {
            return bot.say('Hello!  I\'m A16, the Agile2016 EventBot Concierge.  To find out what I can help you with type MENU for options or KEY for Keywords.')
                .then(() => 'speak');
        }
    },

    speakers: {
      prompt: (bot) => bot.say('What speaker are you searching for?'),
      receive: (bot, message) => {
        const name = message.text;
        return bot.setProp('name', name)
          .then(() => bot.say(`I will search for ${name} is that OK? %[Yes]() %[No](postback:hello)`))
          .then(() => 'speak');
      }
    },

    finish: {
      receive: (bot, message) => {
        return bot.getProp('name')
          .then((name) => bot.say('That is all!'))
          .then(() => 'speak');
      }
    },

    speak: {
        receive: (bot, message) => {
            console.log("===bot user ");
            let upperText = message.text.trim().toUpperCase();

            if (upperText == 'SPEAKERS') {
              return bot.getProp('name')
              .then(() => 'speakers');
            }

            msgLog.smoochId = bot.userId;
            msgLog.received = message.received;
            msgLog.usermessage = message.text;
            msgLog.role = message.role;
            msgLog.message_id = message._id;
            msgLog.sourcetype = message.source.type;
            msgLog.receivedtime = new Date();

////here
            //sched.schedSessions('SessionList');

            //This is the control list of smoochId that can send broadcast messages
            var authUsers = ['a30fa820d0a0f0216fa26070'];

            newUser(bot)

            //For ad hoc messages - scheduled messages are done differently in checkItems
            if (authUsers.indexOf(bot.userId) !== -1) {
              if (upperText.substr(0,4) == '/SK ') {
                upperText = upperText.substr(0,3);
                newBot_msg(message.text.substr(4));
                console.log("****after push msg:  ",message.text," authUser:  ",authUsers);
              }
            }

            function updateSilent() {
                switch (upperText) {
                    case "CONNECT ME":
                        return bot.setProp("silent", true);
                    case "/SUPPORT":
                        return bot.setProp("silent", true);
                    case "DISCONNECT":
                        return bot.setProp("silent", false);
                    case "/A16":
                        console.log("*** ",upperText," ***");
                        processMessage(false);
                        return bot.setProp("silent", false);
                    default:
                        return Promise.resolve();
                }
            }

            function getSilent() {
                return bot.getProp("silent");
            }

            function processMessage(isSilent) {
                if (isSilent) {
                    return Promise.resolve("speak");
                }

                var promises = [];
                var source;
                var fulfillmentSpeech;
                var simplified;
                promises.push(nlp(upperText, bot.userId));

                Q.all(promises).then(function(responses) {
                    // response is the JSON from API.ai
                    responses.forEach(function(response) {
                        //console.log("===in Q.all");
                        console.log("===received result from API.ai",response);
                        source = response.result.source;
                        if (source && source !== 'agent')
                        {
                            fulfillmentSpeech = response.result.fulfillment.speech;
                            simplified = response.result.parameters.simplified;
                        }
//                        console.log("source: ", source);
//                        console.log("fulfillmentSpeech: ", fulfillmentSpeech);
//                        console.log("simplified: ", simplified);

                        respondMessage(source, fulfillmentSpeech, simplified);
                    });
                }, function(error) {
                    console.log("===Q all error ", error);
                });
            }

            function respondMessage(source, fulfillmentSpeech, simplified)
            {
//                console.log("source: ", source);
//                console.log("fulfillmentSpeech: ", fulfillmentSpeech);
//                console.log("simplified: ", simplified);
//                console.log("===receive step 3",upperText);

              if (source != 'agent')
                {
//                    console.log("===source is ", source);
                    if (fulfillmentSpeech)
                    {
                      switch (simplified) {
                        case "hello":
//                          console.log("===in hello");
                          upperText = simplified.trim().toUpperCase();
                          break;
                        case "what do you know":
//                          console.log("===in what do you know");
                          upperText = simplified.trim().toUpperCase();
                          break;
                        case "can you talk":
//                          console.log("===can you talk");
                          upperText = simplified.trim().toUpperCase();
                          break;
                        default:
//                          console.log("===in switch default");
                          msgLog.responsemessage = fulfillmentSpeech;
                          msgLog.responsetime = new Date;
                          msgLog.responsetype = 'API.AI';
                          return bot.say(fulfillmentSpeech).then(() => 'speak');
                      }
                    }
                    else if (simplified)
                    {
//                        console.log("simplified is: ", simplified);
                        upperText = simplified.toUpperCase();
                    }
                }
                if (!_.has(scriptRules, upperText)) {
//                    console.log("===no rule", upperText);
                    return bot.say(`I'm sorry that is not something I know.  Type MENU or KEY for a list of things I can help you with.`).then(() => 'speak');
                }

                var response = scriptRules[upperText];
                var lines = response.split('\n');

                var p = Promise.resolve();
                _.each(lines, function(line) {
                    line = line.trim();
                    p = p.then(function() {
                        console.log("=== p line",line);
                        return wait(5).then(function() {
                            msgLog.responsemessage = line;
                            msgLog.responsetime = new Date;
                            msgLog.responsetype = 'JSON';
                            console.log("=== msgLog  obj",msgLog);
                            logConversation(msgLog);
                            return bot.say(line);
                        });
                    });
                });
                return p.then(() => 'speak');
            }

            return updateSilent()
                .then(getSilent)
                .then(processMessage);
        }
    }
});
<|endoftext|>


<commit_before>jQuery(function($) {
    // Variables
    var errorMessage = $('#message .error');

    // Adjust the error message as to prevent confusion
    errorMessage.html('You need to enable video streaming');

    // Gather the user's media
    navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;

    // Supported?
    if (navigator.getUserMedia)
        navigator.getUserMedia({video:true}, gotStream, error);
    else
        errorMessage.html('Your browser is not supported');

    // We've got the user's media stream
    function gotStream(localStream) {
        $('body').addClass('js');

        // Variables
        var video = $('video#local');

        window.stream = localStream;
        video.attr('src', window.URL.createObjectURL(localStream));
    }

    // Error gathering the user's media stream
    function error(error) {
        console.log("navigator.getUserMedia error: ", error);
    }
});<commit_msg>Improved error message<commit_after>jQuery(function($) {
    // Variables
    var errorMessage = $('#message .error');

    // Adjust the error message as to prevent confusion
    errorMessage.html('You need to enable video streaming');

    // Gather the user's media
    navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;

    // Supported?
    if (navigator.getUserMedia)
        navigator.getUserMedia({video:true}, gotStream, error);
    else
        errorMessage.html('Your browser is not supported');

    // We've got the user's media stream
    function gotStream(localStream) {
        $('body').addClass('js');

        // Variables
        var video = $('video#local');

        window.stream = localStream;
        video.attr('src', window.URL.createObjectURL(localStream));
    }

    // Error gathering the user's media stream
    function error(error) {
        console.log('Error gathering the user\'s media stream: ', error);
    }
});<|endoftext|>


<commit_before>;(function(window, document){

  var requestAnimationFrame = (function(){
    return window.requestAnimationFrame
        || window.webkitRequestAnimationFrame
        || window.mozRequestAnimationFrame
        || window.oRequestAnimationFrame
        || window.msRequestAnimationFrame
        || function(callback){ window.setTimeout(callback, 1000/60)}
  })()
  , yOffset = "pageYOffset" in window

  function absoluteOffset(el){
    var value = el.offsetTop
    while(el && (el = el.offsetParent)) value += el.offsetTop
    return value
  }

  function scroll(to, duration) {
    var origin = yOffset ? window.pageYOffset : document.documentElement.scrollTop
      , start = +new Date()
      , end = start + (duration || 500)
      , direction

    if(typeof to == "object" && "nodeName" in to) to = absoluteOffset(to)
    to = document.height < (to + window.innerHeight) ? document.height - window.innerHeight : to

    direction = to - origin < 0 ? true : false

    function handler(){
      var now = +new Date()
      if (now <= end) {
        if(direction) scrollTo(0, origin - (now - start) / (end - start) * origin + to)
        else scrollTo(0, origin + (now - start) / (end - start) * (to - origin))
        requestAnimationFrame(handler)
      } else {
        scrollTo(0, to)
      }
    }

    requestAnimationFrame(handler)
  }

  document.scrollTo = scroll

})(this, this.document)<commit_msg>changed requestAnimationFrame emulation<commit_after>;(function(window, document){

  var requestAnimationFrame = (function(){
    return window.requestAnimationFrame
        || window.webkitRequestAnimationFrame
        || window.mozRequestAnimationFrame
        || window.oRequestAnimationFrame
        || window.msRequestAnimationFrame
        || function(callback){
            window.setTimeout(function(){
              callback(+new Date())
            }, 1000/60)
          }
  })()
  , yOffset = "pageYOffset" in window

  function absoluteOffset(el){
    var value = el.offsetTop
    while(el && (el = el.offsetParent)) value += el.offsetTop
    return value
  }

  function scroll(to, duration) {
    var origin = yOffset ? window.pageYOffset : document.documentElement.scrollTop
      , start = +new Date()
      , end = start + (duration || 500)
      , direction

    if(typeof to == "object" && "nodeName" in to) to = absoluteOffset(to)
    to = document.height < (to + window.innerHeight) ? document.height - window.innerHeight : to

    direction = to - origin < 0 ? true : false

    function handler(now){
      if (now <= end) {
        if(direction) scrollTo(0, origin - (now - start) / (end - start) * origin + to)
        else scrollTo(0, origin + (now - start) / (end - start) * (to - origin))
        requestAnimationFrame(handler)
      } else {
        scrollTo(0, to)
      }
    }

    requestAnimationFrame(handler)
  }

  document.scrollTo = scroll

})(this, this.document)<|endoftext|>


<commit_before>/*

    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
      This file is part of the Smart Developer Hub Project:
        http://www.smartdeveloperhub.org/
      Center for Open Middleware
            http://www.centeropenmiddleware.com/
    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
      Copyright (C) 2015 Center for Open Middleware.
    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
      Licensed under the Apache License, Version 2.0 (the "License");
      you may not use this file except in compliance with the License.
      You may obtain a copy of the License at
                http://www.apache.org/licenses/LICENSE-2.0
      Unless required by applicable law or agreed to in writing, software
      distributed under the License is distributed on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      See the License for the specific language governing permissions and
     limitations under the License.
    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
*/
'use strict';

    var loadStartDate = new Date();
    try {
        // global buyan
        var bunyan = require('bunyan');
        var PrettyStream = require('bunyan-prettystream');
    } catch (err) {
        console.error("Bot Error. bunyan logs problem: " + err);
    }
    try {
        // Set Config params
        require('./config');
    } catch (err) {
        console.error("Fatal BOT Error with config: " + err);
        setTimeout(function() {
            process.exit(0);
        }, 1000);
    }

    // Shut down function
    var gracefullyShuttinDown = function gracefullyShuttinDown() {
        log.warn('Shut down signal Received ');
        log.warn(" ! Shutting Down SDH-API manually.");
        setTimeout(function () {
            process.exit(0);
        }, 500);
    };

    // Set security handlers
    process.on('SIGINT', gracefullyShuttinDown);
    process.on('SIGTERM', gracefullyShuttinDown);

    var init = function init(botID, callback) {
        exports.id = botID;
        GLOBAL.botId = botID;
        GLOBAL.sdhProjectsByID = {};
        GLOBAL.sdhProjectsByName = {};
        GLOBAL.sdhReposByID = {};
        GLOBAL.sdhReposByName = {};
        GLOBAL.sdhReposByName = {};
        GLOBAL.sdhProductsByID = {};
        GLOBAL.sdhProductsByName = {};
        GLOBAL.sdhUsersByID = {};
        GLOBAL.sdhOrganizationsByID = {};
        /* File Log */
        var prettyStdOut = new PrettyStream();
        prettyStdOut.pipe(process.stdout);
        GLOBAL.log = null;
        GLOBAL.mkdirp = require("mkdirp");
        var ready = false;
        var getDirName = require("path").dirname;
        mkdirp(getDirName(FILE_LOG_PATH), function (err) {
            if (err) {
                console.error("! Log file disabled");
                console.error("Error creating log file " +  FILE_LOG_PATH);
                console.error(err);
            } else {
                log = bunyan.createLogger({
                        name: 'SDH-BOT',
                        streams: [{
                            level: CONSOLE_LOG_LEVEL,
                            stream: prettyStdOut
                        },
                        {
                            level: FILE_LOG_LEVEL,
                            type: 'rotating-file',
                            path: FILE_LOG_PATH,
                            period: FILE_LOG_PERIOD + 'h',
                            count: FILE_LOG_NFILES
                        }]
                });
                log.info("... Loading SDH BOT CORE ...");
                try {
                    GLOBAL.moment = require("moment");
                    GLOBAL.request = require('request');
                } catch (err) {
                    log.error(" ! Error loading dependencies: " + err);
                    log.info('Exiting...');
                    setTimeout(function () {
                        process.exit(0);
                    }, 500);
                }
                log.info('...starting...');
                //var oldBots = require('./brain/botinterfaces.js');
                log.info('...OK...');
                // take SDHMembers
                preloadEntityIds(callback);
            }
        });
    };

    var preloadEntityIds = function preloadEntityIds(cb) {
        var rcounter = 0;
        var endLoad = function endLoad() {
            rcounter++;
            if (rcounter == 5) {
                cb();
            } else if(rcounter > 5) {
                log.debug('Concurr error sdhbot.preloadEntityIds');
            }
        };
        //Members
        internalSDHtools.getSDHMembers(function (members) {
            for (var i = 0; i < members.length; i++) {
                sdhUsersByID[members[i].userid] = members[i];
            }
            endLoad()
        });
        //Repositories
        internalSDHtools.getSDHRepositories(function (rep) {
            for (var i = 0; i < rep.length; i++) {
                sdhReposByID[rep[i].repositoryid] = rep[i];
                sdhReposByName[rep[i].name] = rep[i];
            }
            endLoad()
        });
        //Products
        internalSDHtools.getSDHProducts(function (prod) {
            for (var i = 0; i < prod.length; i++) {
                sdhProductsByID[prod[i].productid] = prod[i];
            }
            endLoad()
        });
        //Projects
        internalSDHtools.getSDHProjects(function (proj) {
            for (var i = 0; i < proj.length; i++) {
                sdhProjectsByID[proj[i].projectid] = proj[i];
            }
            endLoad()
        });
        //Organizations
        internalSDHtools.getSDHOrganizations(function (org) {
            for (var i = 0; i < org.length; i++) {
                // By the moment there are no organizationid in the unique Organization info in SDH
                //sdhOrganizationsByID[org[i].organizationid] = org[i];
                sdhOrganizationsByID[org[i].title] = org[i];
            }
            endLoad()
        });
    };

    GLOBAL.internalSDHtools = require('./brain/sdhBasic.js');
    GLOBAL.sdhPatternHandlers = require('./brain/sdhPatternHandlers.js');
    exports.knownPatterns = sdhPatternHandlers.phInfo;
    // Export SDH Functions
    for (var meth in internalSDHtools) {
        exports[meth] = internalSDHtools[meth];
    }

    // Export init
    exports.init = init;

    // Config
    var validUrl = require('valid-url');
    exports.setSdhApiUrl = function setSdhApiUrl(uri) {
        SDH_API_URL = uri;
        if (!validUrl.isUri(SDH_API_URL)){
            log.error("Not valid SDH_API_URL: " + SDH_API_URL);
            process.exit(0);
        }
    };
    exports.setSdhDashboardUrl = function setSdhDashboardUrl(uri) {
        SDH_DASHBOARD_URL = uri;
        if (!validUrl.isUri(SDH_DASHBOARD_URL)){
            log.error("Not valid SDH_DASHBOARD_URL: " + SDH_API_URL);
            process.exit(0);
        }
    };
    GLOBAL.clientUserInfo = {};
    exports.setMembersIdRel = function setMembersIdRel(matchingObj) {
        clientUserInfo = matchingObj;
    };<commit_msg>New method for Elastic Search integration<commit_after>/*

    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
      This file is part of the Smart Developer Hub Project:
        http://www.smartdeveloperhub.org/
      Center for Open Middleware
            http://www.centeropenmiddleware.com/
    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
      Copyright (C) 2015 Center for Open Middleware.
    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
      Licensed under the Apache License, Version 2.0 (the "License");
      you may not use this file except in compliance with the License.
      You may obtain a copy of the License at
                http://www.apache.org/licenses/LICENSE-2.0
      Unless required by applicable law or agreed to in writing, software
      distributed under the License is distributed on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      See the License for the specific language governing permissions and
     limitations under the License.
    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
*/
'use strict';

    var loadStartDate = new Date();
    try {
        // global buyan
        var bunyan = require('bunyan');
        var PrettyStream = require('bunyan-prettystream');
    } catch (err) {
        console.error("Bot Error. bunyan logs problem: " + err);
    }
    try {
        // Set Config params
        require('./config');
    } catch (err) {
        console.error("Fatal BOT Error with config: " + err);
        setTimeout(function() {
            process.exit(0);
        }, 1000);
    }

    // Shut down function
    var gracefullyShuttinDown = function gracefullyShuttinDown() {
        log.warn('Shut down signal Received ');
        log.warn(" ! Shutting Down SDH-API manually.");
        setTimeout(function () {
            process.exit(0);
        }, 500);
    };

    // Set security handlers
    process.on('SIGINT', gracefullyShuttinDown);
    process.on('SIGTERM', gracefullyShuttinDown);

    var init = function init(botID, callback) {
        exports.id = botID;
        GLOBAL.botId = botID;
        GLOBAL.sdhProjectsByID = {};
        GLOBAL.sdhProjectsByName = {};
        GLOBAL.sdhReposByID = {};
        GLOBAL.sdhReposByName = {};
        GLOBAL.sdhReposByName = {};
        GLOBAL.sdhProductsByID = {};
        GLOBAL.sdhProductsByName = {};
        GLOBAL.sdhUsersByID = {};
        GLOBAL.sdhOrganizationsByID = {};
        /* File Log */
        var prettyStdOut = new PrettyStream();
        prettyStdOut.pipe(process.stdout);
        GLOBAL.log = null;
        GLOBAL.mkdirp = require("mkdirp");
        var ready = false;
        var getDirName = require("path").dirname;
        mkdirp(getDirName(FILE_LOG_PATH), function (err) {
            if (err) {
                console.error("! Log file disabled");
                console.error("Error creating log file " +  FILE_LOG_PATH);
                console.error(err);
            } else {
                log = bunyan.createLogger({
                        name: 'SDH-BOT',
                        streams: [{
                            level: CONSOLE_LOG_LEVEL,
                            stream: prettyStdOut
                        },
                        {
                            level: FILE_LOG_LEVEL,
                            type: 'rotating-file',
                            path: FILE_LOG_PATH,
                            period: FILE_LOG_PERIOD + 'h',
                            count: FILE_LOG_NFILES
                        }]
                });
                log.info("... Loading SDH BOT CORE ...");
                try {
                    GLOBAL.moment = require("moment");
                    GLOBAL.request = require('request');
                } catch (err) {
                    log.error(" ! Error loading dependencies: " + err);
                    log.info('Exiting...');
                    setTimeout(function () {
                        process.exit(0);
                    }, 500);
                }
                log.info('...starting...');
                //var oldBots = require('./brain/botinterfaces.js');
                log.info('...OK...');
                // take SDHMembers
                preloadEntityIds(callback);
            }
        });
    };

    var preloadEntityIds = function preloadEntityIds(cb) {
        var rcounter = 0;
        var endLoad = function endLoad() {
            rcounter++;
            if (rcounter == 5) {
                cb();
            } else if(rcounter > 5) {
                log.debug('Concurr error sdhbot.preloadEntityIds');
            }
        };
        //Members
        internalSDHtools.getSDHMembers(function (members) {
            for (var i = 0; i < members.length; i++) {
                sdhUsersByID[members[i].userid] = members[i];
            }
            endLoad()
        });
        //Repositories
        internalSDHtools.getSDHRepositories(function (rep) {
            for (var i = 0; i < rep.length; i++) {
                sdhReposByID[rep[i].repositoryid] = rep[i];
                sdhReposByName[rep[i].name] = rep[i];
            }
            endLoad()
        });
        //Products
        internalSDHtools.getSDHProducts(function (prod) {
            for (var i = 0; i < prod.length; i++) {
                sdhProductsByID[prod[i].productid] = prod[i];
            }
            endLoad()
        });
        //Projects
        internalSDHtools.getSDHProjects(function (proj) {
            for (var i = 0; i < proj.length; i++) {
                sdhProjectsByID[proj[i].projectid] = proj[i];
            }
            endLoad()
        });
        //Organizations
        internalSDHtools.getSDHOrganizations(function (org) {
            for (var i = 0; i < org.length; i++) {
                // By the moment there are no organizationid in the unique Organization info in SDH
                //sdhOrganizationsByID[org[i].organizationid] = org[i];
                sdhOrganizationsByID[org[i].title] = org[i];
            }
            endLoad()
        });
    };

    var startESindex = function startESindex() {
        //TODO
        var sdhUsersByID_ = {};
        var cleanIndex = [
            elastic.indexExists("users").then(function (exists) {
                if (exists) {
                    return elastic.deleteIndex("users");
                }
            }).then(function () {
                return elastic.initIndex("users").then(function() {
                        return elastic.initMapping("users");
                    })
            }),
            elastic.indexExists("products").then(function (exists) {
                if (exists) {
                    return elastic.deleteIndex("products");
                }
            }).then(function () {
                return elastic.initIndex("products").then(function() {
                    return elastic.initMapping("products");
                })
            }),
            elastic.indexExists("projects").then(function (exists) {
                if (exists) {
                    return elastic.deleteIndex("projects");
                }
            }).then(function () {
                return elastic.initIndex("projects").then(function() {
                    return elastic.initMapping("projects");
                })
            }),
            elastic.indexExists("repositories").then(function (exists) {
                if (exists) {
                    return elastic.deleteIndex("repositories");
                }
            }).then(function () {
                return elastic.initIndex("repositories").then(function () {
                    return elastic.initMapping("repositories");
                })
            })
        ];
        var getEntities = [
            //Members
            internalSDHtools.getSDHMembers(function (members) {
                members.map(function (dat) {
                    sdhUsersByID_[dat.userid] = dat;
                    return elastic.addDocument(dat, indexName);
                });
                for (var i = 0; i < members.length; i++) {
                    sdhUsersByID[members[i].userid] = members[i];
                }
                log.info(sdhUsersByID)
                return members.all(members);
            }),
            //Repositories
            internalSDHtools.getSDHRepositories(function (rep) {
                for (var i = 0; i < rep.length; i++) {
                    sdhReposByID[rep[i].repositoryid] = rep[i];
                    sdhReposByName[rep[i].name] = rep[i];
                }
            }),
            //Products
            internalSDHtools.getSDHProducts(function (prod) {
                for (var i = 0; i < prod.length; i++) {
                    sdhProductsByID[prod[i].productid] = prod[i];
                }
            }),
            //Projects
            internalSDHtools.getSDHProjects(function (proj) {
                for (var i = 0; i < proj.length; i++) {
                    sdhProjectsByID[proj[i].projectid] = proj[i];
                }
            }),
            //Organizations
            internalSDHtools.getSDHOrganizations(function (org) {
                for (var i = 0; i < org.length; i++) {
                    // By the moment there are no organizationid in the unique Organization info in SDH
                    //sdhOrganizationsByID[org[i].organizationid] = org[i];
                    sdhOrganizationsByID[org[i].title] = org[i];
                }
            })
        ];

        Promise.all(cleanIndex).all(getEntities).then(function () {
                log.info("elasticTools enable");
            }
        ).catch(function(err) {
            log.info("error loading data into Elastic Search");
            log.error(err);
        });
    };

    GLOBAL.internalSDHtools = require('./brain/sdhBasic.js');
    GLOBAL.sdhPatternHandlers = require('./brain/sdhPatternHandlers.js');
    exports.knownPatterns = sdhPatternHandlers.phInfo;
    // Export SDH Functions
    for (var meth in internalSDHtools) {
        exports[meth] = internalSDHtools[meth];
    }

    // Export init
    exports.init = init;

    // Config
    var validUrl = require('valid-url');
    exports.setSdhApiUrl = function setSdhApiUrl(uri) {
        SDH_API_URL = uri;
        if (!validUrl.isUri(SDH_API_URL)){
            log.error("Not valid SDH_API_URL: " + SDH_API_URL);
            process.exit(0);
        }
    };
    exports.setSdhDashboardUrl = function setSdhDashboardUrl(uri) {
        SDH_DASHBOARD_URL = uri;
        if (!validUrl.isUri(SDH_DASHBOARD_URL)){
            log.error("Not valid SDH_DASHBOARD_URL: " + SDH_API_URL);
            process.exit(0);
        }
    };
    GLOBAL.clientUserInfo = {};
    exports.setMembersIdRel = function setMembersIdRel(matchingObj) {
        clientUserInfo = matchingObj;
    };<|endoftext|>