<commit_before>'use strict';

const apiai = require('apiai');
const express = require('express');
const bodyParser = require('body-parser');
const uuid = require('node-uuid');
const request = require('request');

const REST_PORT = (process.env.PORT || 5000);
const APIAI_ACCESS_TOKEN = process.env.APIAI_ACCESS_TOKEN;
const APIAI_LANG = process.env.APIAI_LANG || 'en';
const FB_VERIFY_TOKEN = process.env.FB_VERIFY_TOKEN;
const FB_PAGE_ACCESS_TOKEN = process.env.FB_PAGE_ACCESS_TOKEN;

const apiAiService = apiai(APIAI_ACCESS_TOKEN, {language: APIAI_LANG, requestSource: "fb"});
const sessionIds = new Map();

function processEvent(event) {
    var sender = event.sender.id;

    if (event.message && event.message.text) {
        var text = event.message.text;
        // Handle a text message from this sender

        if (!sessionIds.has(sender)) {
            sessionIds.set(sender, uuid.v1());
        }

        console.log("Text", text);

        let apiaiRequest = apiAiService.textRequest(text,
            {
                sessionId: sessionIds.get(sender)
            });

        apiaiRequest.on('response', (response) => {
            if (isDefined(response.result)) {
                let responseText = response.result.fulfillment.speech;
                let responseData = response.result.fulfillment.data;
                let action = response.result.action;
                let parameters = response.result.parameters;

                if (action){
                    try {
                        var action_module = require('./'+ action);
                        console.log(action_module.get(parameters));
                    } catch(e) {
                        console.error(action +" is not found");
                    }
                }else{
                    console.error("no action");
                }

                if (isDefined(responseData) && isDefined(responseData.facebook)) {
                    try {
                        console.log('Response as formatted message');
                        sendFBMessage(sender, responseData.facebook);
                    } catch (err) {
                        sendFBMessage(sender, {text: err.message });
                    }
                } else if (isDefined(responseText)) {
                    console.log('Response as text message');
                    // facebook API limit for text length is 320,
                    // so we split message if needed
                    var splittedText = splitResponse(responseText);
                    /*
                    for (var i = 0; i < splittedText.length; i++) {
                        sendFBMessage(sender, {text: splittedText[i]});
                    }
                    */
                    var num_line = parameters.num_line
                    var action_module = require('./RATP_App.js');
                    action_module.info(function(result) {
                         var returedData = result;

                         sendFBMessage(sender, returedData);
                    },num_line);

                }

            }
        });

        apiaiRequest.on('error', (error) => console.error(error));
        apiaiRequest.end();
    }
}

function splitResponse(str) {
    if (str.length <= 320)
    {
        return [str];
    }

    var result = chunkString(str, 300);

    return result;

}

function chunkString(s, len)
{
    var curr = len, prev = 0;

    var output = [];

    while(s[curr]) {
        if(s[curr++] == ' ') {
            output.push(s.substring(prev,curr));
            prev = curr;
            curr += len;
        }
        else
        {
            var currReverse = curr;
            do {
                if(s.substring(currReverse - 1, currReverse) == ' ')
                {
                    output.push(s.substring(prev,currReverse));
                    prev = currReverse;
                    curr = currReverse + len;
                    break;
                }
                currReverse--;
            } while(currReverse > prev)
        }
    }
    output.push(s.substr(prev));
    return output;
}

function sendFBMessage(sender, messageData) {
    var to_string = JSON.stringify(messageData);
    var to_size = to_string.substring(0, 300);

    request({
        url: 'https://graph.facebook.com/v2.6/me/messages',
        qs: {access_token: FB_PAGE_ACCESS_TOKEN},
        method: 'POST',
        json: {
            recipient: {id: sender},
            message: {text : to_size}
        }
    }, function (error, response, body) {
        if (error) {
            console.log('Error sending message: ', error);
        } else if (response.body.error) {
            console.log('Error: ', response.body.error);
        }
    });
}

function doSubscribeRequest() {
    request({
            method: 'POST',
            uri: "https://graph.facebook.com/v2.6/me/subscribed_apps?access_token=" + FB_PAGE_ACCESS_TOKEN
        },
        function (error, response, body) {
            if (error) {
                console.error('Error while subscription: ', error);
            } else {
                console.log('Subscription result: ', response.body);
            }
        });
}

function isDefined(obj) {
    if (typeof obj == 'undefined') {
        return false;
    }

    if (!obj) {
        return false;
    }

    return obj != null;
}

const app = express();
app.use(bodyParser.json());
app.all('*', function (req, res, next) {
    // res.header("Access-Control-Allow-Origin", '*');
    // res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, content-type, accept");
    next();
});

app.get('/webhook/', function (req, res) {
    if (req.query['hub.verify_token'] == FB_VERIFY_TOKEN) {
        res.send(req.query['hub.challenge']);

        setTimeout(function () {
            doSubscribeRequest();
        }, 3000);
    } else {
        res.send('Error, wrong validation token');
    }
});

app.post('/webhook/', function (req, res) {
    try {
        var messaging_events = req.body.entry[0].messaging;
        for (var i = 0; i < messaging_events.length; i++) {
            var event = req.body.entry[0].messaging[i];
            processEvent(event);
        }
        return res.status(200).json({
            status: "ok"
        });
    } catch (err) {
        return res.status(400).json({
            status: "error",
            error: err
        });
    }

});

app.listen(REST_PORT, function () {
    console.log('Rest service ready on port ' + REST_PORT);
});

doSubscribeRequest();
<commit_msg>Update app.js<commit_after>'use strict';

const apiai = require('apiai');
const express = require('express');
const bodyParser = require('body-parser');
const uuid = require('node-uuid');
const request = require('request');

const REST_PORT = (process.env.PORT || 5000);
const APIAI_ACCESS_TOKEN = process.env.APIAI_ACCESS_TOKEN;
const APIAI_LANG = process.env.APIAI_LANG || 'en';
const FB_VERIFY_TOKEN = process.env.FB_VERIFY_TOKEN;
const FB_PAGE_ACCESS_TOKEN = process.env.FB_PAGE_ACCESS_TOKEN;

const apiAiService = apiai(APIAI_ACCESS_TOKEN, {language: APIAI_LANG, requestSource: "fb"});
const sessionIds = new Map();

function processEvent(event) {
    var sender = event.sender.id;

    if (event.message && event.message.text) {
        var text = event.message.text;
        // Handle a text message from this sender

        if (!sessionIds.has(sender)) {
            sessionIds.set(sender, uuid.v1());
        }

        console.log("Text", text);

        let apiaiRequest = apiAiService.textRequest(text,
            {
                sessionId: sessionIds.get(sender)
            });

        apiaiRequest.on('response', (response) => {
            if (isDefined(response.result)) {
                let responseText = response.result.fulfillment.speech;
                let responseData = response.result.fulfillment.data;
                let action = response.result.action;
                let parameters = response.result.parameters;

                if (action){
                    try {
                        var action_module = require('./'+ action + '.js');
                        console.log(action_module.get(parameters));
                        action_module.get(function(result) {
                            var returedData = result;
                             sendFBMessage(sender, returedData);
                        },parameters);

                    } catch(e) {
                        console.error(action +" is not found");
                    }
                }else{
                    console.error("no action");
                }

                if (isDefined(responseData) && isDefined(responseData.facebook)) {
                    try {
                        console.log('Response as formatted message');
                        sendFBMessage(sender, responseData.facebook);
                    } catch (err) {
                        sendFBMessage(sender, {text: err.message });
                    }
                } else if (isDefined(responseText)) {
                    console.log('Response as text message');
                    // facebook API limit for text length is 320,
                    // so we split message if needed
                    var splittedText = splitResponse(responseText);
                    /*
                    for (var i = 0; i < splittedText.length; i++) {
                        sendFBMessage(sender, {text: splittedText[i]});
                    }
                    */

                }

            }
        });

        apiaiRequest.on('error', (error) => console.error(error));
        apiaiRequest.end();
    }
}

function splitResponse(str) {
    if (str.length <= 320)
    {
        return [str];
    }

    var result = chunkString(str, 300);

    return result;

}

function chunkString(s, len)
{
    var curr = len, prev = 0;

    var output = [];

    while(s[curr]) {
        if(s[curr++] == ' ') {
            output.push(s.substring(prev,curr));
            prev = curr;
            curr += len;
        }
        else
        {
            var currReverse = curr;
            do {
                if(s.substring(currReverse - 1, currReverse) == ' ')
                {
                    output.push(s.substring(prev,currReverse));
                    prev = currReverse;
                    curr = currReverse + len;
                    break;
                }
                currReverse--;
            } while(currReverse > prev)
        }
    }
    output.push(s.substr(prev));
    return output;
}

function sendFBMessage(sender, messageData) {
    var to_string = JSON.stringify(messageData);
    var to_size = to_string.substring(0, 300);

    request({
        url: 'https://graph.facebook.com/v2.6/me/messages',
        qs: {access_token: FB_PAGE_ACCESS_TOKEN},
        method: 'POST',
        json: {
            recipient: {id: sender},
            message: {text : to_size}
        }
    }, function (error, response, body) {
        if (error) {
            console.log('Error sending message: ', error);
        } else if (response.body.error) {
            console.log('Error: ', response.body.error);
        }
    });
}

function doSubscribeRequest() {
    request({
            method: 'POST',
            uri: "https://graph.facebook.com/v2.6/me/subscribed_apps?access_token=" + FB_PAGE_ACCESS_TOKEN
        },
        function (error, response, body) {
            if (error) {
                console.error('Error while subscription: ', error);
            } else {
                console.log('Subscription result: ', response.body);
            }
        });
}

function isDefined(obj) {
    if (typeof obj == 'undefined') {
        return false;
    }

    if (!obj) {
        return false;
    }

    return obj != null;
}

const app = express();
app.use(bodyParser.json());
app.all('*', function (req, res, next) {
    // res.header("Access-Control-Allow-Origin", '*');
    // res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, content-type, accept");
    next();
});

app.get('/webhook/', function (req, res) {
    if (req.query['hub.verify_token'] == FB_VERIFY_TOKEN) {
        res.send(req.query['hub.challenge']);

        setTimeout(function () {
            doSubscribeRequest();
        }, 3000);
    } else {
        res.send('Error, wrong validation token');
    }
});

app.post('/webhook/', function (req, res) {
    try {
        var messaging_events = req.body.entry[0].messaging;
        for (var i = 0; i < messaging_events.length; i++) {
            var event = req.body.entry[0].messaging[i];
            processEvent(event);
        }
        return res.status(200).json({
            status: "ok"
        });
    } catch (err) {
        return res.status(400).json({
            status: "error",
            error: err
        });
    }

});

app.listen(REST_PORT, function () {
    console.log('Rest service ready on port ' + REST_PORT);
});

doSubscribeRequest();
<|endoftext|>


<commit_before>import React             from 'react';
import Expo              from 'expo';
import {LayoutAnimation} from 'react-native';
import {launchApp}       from 'feature-u';
import {reducerAspect}   from 'feature-redux';
import {logicAspect}     from 'feature-redux-logic';
import {routeAspect}     from 'feature-router';
import SplashScreen      from './util/comp/SplashScreen';
import features          from './feature'; // the set of features that comprise this application

// define our set of "plugable" feature-u Aspects, conforming to our app's run-time stack
const aspects = [
  reducerAspect, // redux          ... extending: Feature.reducer
  logicAspect,   // redux-logic    ... extending: Feature.logic
  routeAspect,   // Feature Routes ... extending: Feature.route
];

// configure our Aspects (as needed)
// ... StateRouter fallback screen (when no routes are in effect)
routeAspect.fallbackElm = <SplashScreen msg="I'm trying to think but it hurts!"/>;
// ... StateRouter animation hook
routeAspect.componentWillUpdateHook = () => LayoutAnimation.configureNext(LayoutAnimation.Presets.spring);

// diagnostic: activate feature-u logging
// launchApp.diag.logf.enable();

// launch our app, exposing the feature-u App object (facilitating cross-feature communication)!
export default launchApp({
  aspects,
  features,
  registerRootAppElm(rootAppElm) {
    Expo.registerRootComponent(()=>rootAppElm); // convert rootAppElm to a React Component
  }
});
<commit_msg>minor doc change<commit_after>import React             from 'react';
import Expo              from 'expo';
import {LayoutAnimation} from 'react-native';
import {launchApp}       from 'feature-u';
import {reducerAspect}   from 'feature-redux';
import {logicAspect}     from 'feature-redux-logic';
import {routeAspect}     from 'feature-router';
import SplashScreen      from './util/comp/SplashScreen';
import features          from './feature'; // the set of features that comprise this application

// define our set of "plugable" feature-u Aspects, conforming to our app's run-time stack
const aspects = [
  reducerAspect, // redux          ... extending: Feature.reducer
  logicAspect,   // redux-logic    ... extending: Feature.logic
  routeAspect,   // Feature Routes ... extending: Feature.route
];

// configure our Aspects (as needed)
// ... StateRouter fallback screen (when no routes are in effect)
routeAspect.fallbackElm = <SplashScreen msg="I'm trying to think but it hurts!"/>;
// ... StateRouter animation hook
routeAspect.componentWillUpdateHook = () => LayoutAnimation.configureNext(LayoutAnimation.Presets.spring);

// diagnostic: activate feature-u logging
// launchApp.diag.logf.enable();
// launchApp.diag.logf.elm2html = (elm) => elm; // show react elms as object blobs

// launch our app, exposing the feature-u App object (facilitating cross-feature communication)!
export default launchApp({
  aspects,
  features,
  registerRootAppElm(rootAppElm) {
    Expo.registerRootComponent(()=>rootAppElm); // convert rootAppElm to a React Component
  }
});
<|endoftext|>


<commit_before>import Commando from 'discord.js-commando'
import Community from './community/community'

import path from 'path'
import sqlite from 'sqlite'
import winston from 'winston'

import config from '/data/config.json'

String.prototype.capitalizeFirstLetter = function() { return this.charAt(0).toUpperCase() + this.slice(1) }

winston.remove(winston.transports.Console)
winston.add(winston.transports.Console, { level: config.logLevel })

const client = new Commando.Client({ owner: config.owner, commandPrefix: config.prefix })

client.on('debug', winston.debug)
client.on('warn', winston.warn)
client.on('error', winston.error)

client.on('guildCreate', guild => { winston.info(`Joined Guild: ${guild.name}.`) })
client.on('guildDelete', guild => { winston.info(`Departed Guild: ${guild.name}.`) })

client.on('guildMemberRemove', guildMember => { Community.dropDepartedMember(guildMember.guild.id, guildMember.id) })

client.on('disconnect', event => { winston.warn(`Disconnected [${event.code}]: ${event.reason || 'Unknown reason'}`)} )
client.on('reconnecting', () => { winston.info('Reconnecting...')})

client.on('ready', async () => {
    await Community.init(client).catch(winston.error)
    winston.info('Client Ready.')
    winston.verbose(`Current Guilds (${client.guilds.size}): ${client.guilds.map(guild => { return guild.name }).join('; ')}.`)
    client.user.setGame('Hearthstone')
})

client.setProvider(
    sqlite.open('/data/settings.sqlite3').then(db => new Commando.SQLiteProvider(db))
).catch(winston.error)

client.registry
    .registerDefaultTypes()
    .registerGroups([
        ['card', 'Card Information'],
        ['community', 'Community']
    ])
    .registerDefaultGroups()
    .registerCommandsIn(path.join(__dirname, 'commands'))
    .registerDefaultCommands({ eval_: false, commandState: false })

client.login(config.token)
<commit_msg>Update main app file to use new sequelized data<commit_after>import Commando from 'discord.js-commando'
import CommunityManager from './community/community-manager'
import PostgreSQL from './postgresql/postgresql'
import SequelizeProvider from './postgresql/sequelize-provider'

import path from 'path'
import winston from 'winston'

import config from '/data/config.json'

String.prototype.capitalizeFirstLetter = function() { return this.charAt(0).toUpperCase() + this.slice(1) }

winston.remove(winston.transports.Console)
winston.add(winston.transports.Console, { level: config.logLevel })

const postgresql = new PostgreSQL(config.database)
postgresql.init()

const client = new Commando.Client({ owner: config.owner, commandPrefix: config.prefix })
const communityManager = new CommunityManager(client)

client
    .on('debug', winston.debug)
    .on('warn', winston.warn)
    .on('error', winston.error)
    .on('disconnect', event => { winston.warn(`Disconnected [${event.code}]: ${event.reason || 'Unknown reason'}`) })
    .on('reconnecting', () => { winston.info('Reconnecting...') })
    .on('guildCreate', guild => { winston.verbose(`Joined Guild: ${guild.name}.`) })
    .on('guildDelete', guild => {
        winston.verbose(`Departed Guild: ${guild.name}.`)
        communityManager.handleGuildDepart(guild.id)
    })
    .on('guildMemberRemove', guildMember => { communityManager.handleMemberDepart(guildMember.guild.id, guildMember.id) })
    .on('ready', async () => {
        communityManager.start()
        winston.info('Client Ready.')
        winston.verbose(`Current Guilds (${client.guilds.size}): ${client.guilds.map(guild => { return guild.name }).join('; ')}.`)
        client.user.setGame('Hearthstone')
    })

client.setProvider(new SequelizeProvider(postgresql.db)).catch(winston.error)

client.registry
    .registerDefaultTypes()
    .registerGroups([
        ['card', 'Card Information'],
        ['community', 'Community']
    ])
    .registerDefaultGroups()
    .registerCommandsIn(path.join(__dirname, 'commands'))
    .registerDefaultCommands({ eval_: false, commandState: false })

client.login(config.token)
<|endoftext|>


<commit_before>const IndexObj = new Index();

// function to readfiles
readFiles = (files) => {
  document.getElementById('errorMsg').innerHTML = "";
  const select = $('#dropdown');
  for (let i = 0; i < files.length; i++) {
    const f = files[i];

    const reader = new FileReader();
    const refinedName = f.name.replace(/\.json/g, "").replace(/\s+/g, "");
    let contents;
    reader.onload = (es) => {
      try {
        contents = Index.isValidJson(es.target.result);
        if(!contents){
          throw Error("Invalid JSON format");
        }
      } catch (e) {
        document.getElementById('myModal').style.display = "block";
        document.getElementById('myModal').style.fontWeight = "bold";
        document.getElementById('errorMsg')
        .innerHTML += `${f.name} failed to upload. Reason? ` + e.message + "
";
      }

      if (contents) {
        IndexObj.files[refinedName] = {};
        IndexObj.files[refinedName]['name'] = f.name;
        if (Array.isArray(contents) && contents.length !== 0) {
          // check if content is an array of objects
          IndexObj.files[refinedName]['books'] = contents;
        }
        else {
          // do this if content has just one object
          IndexObj.files[refinedName]['books'] = [contents];
        }
        select.append(`<option selected value='${refinedName}'>${IndexObj
          .files[refinedName]['name']}</option>`);
      }
    };
    if (!IndexObj.files[refinedName]) {
      reader.readAsText(f);
    }
  }
  if (IndexObj.files.length > 1) {
    getIndex();
  }
  else {
    $('#indexTableDiv').empty()
      .append("
Index has not been created for this file.
");
  }

};

buildTable = (books, indices, keys, documentkey, type) => {
  let frame, line;
  if (type === 'create') {
    frame = '#indexList';
    line = "table";
  }
  else {
    frame = '#searchList';
    line = "search";
  }
  refinedkey = documentkey;
  documentkey = documentkey.replace(/\.json/g, "").replace(/\s+/g, "");
  if (type === 'search') {
    documentkey += 'find';
  }
  let contents;
  let divkey = '#' + documentkey;
  $(frame)
    .append(' <button id="toggleindex" data-toggle="collapse"' +
    'data-target="#' + documentkey + '" class="btn">
'
    + refinedkey + '
</button>');
  $(frame).append('
' +
    '
');

  $(divkey).append($("
"));
  let divkey2 = '#' + documentkey + '' + line + '';
  const table = $(divkey2);
  let tableHeader = '
Words	';
  for (const index in books) {
    tableHeader += `<th>${books[index].title}</th>`;
  }
  tableHeader += "

";
  table.append(tableHeader);
  for (const index in keys) {
    let row = "
";
    row += `<td>${keys[index]}</td>`;
    for (let i = 0; i < books.length; i++) {
      let td = "";
      const whereWordsExist = indices[keys[index]];
      if (whereWordsExist.indexOf(i) >= 0) {
        td += "✔";
      } else {
        td += "✖";
      }
      td += "	";
      row += td;
    }

    row += "
";

    table.append(row);
  }
  table.append("
");
  if (!document.getElementById(documentkey + 'out')) {
    let newdiv = document.createElement('div');
    newdiv.className = "outercontain";
    newdiv.id = documentkey + "out";
    $(".table").wrap(newdiv);
  }
};

createIndex = () => {
  $('.collapse').removeClass('in');
  const documentkey = document.getElementById('dropdown').value;
  let books, indices, name;
  let select = $('#dropdown2');
  if (documentkey && !IndexObj.getIndex(documentkey)) {
    IndexObj.createIndex(documentkey, IndexObj.files[documentkey].books);
    indices = IndexObj.getIndex(documentkey);
    books = IndexObj.files[documentkey].books;
    name = IndexObj.files[documentkey].name;
    select.append(`<option value='${documentkey}'>${IndexObj
      .files[documentkey]['name']}</option>`);
    $('#dropdown').children('option[value="' + documentkey + '"]')
    .attr('disabled', true)
  }
  if ($('#dropdown2 > option').length === 2) {
    select.append("<option value='' selected >All files</option>");
  }
  const keys = Object.keys(indices);
  buildTable(books, indices, keys, name, 'create');
};

searchIndex = (terms) => {
  try {
    $('#searchList').empty();
    const documentkey = document.getElementById('dropdown2').value;
    let books = [];
    let searchResult;
    if (documentkey) {
      searchResult = IndexObj.searchIndex(terms, documentkey);
      console.log(searchResult);
      books = IndexObj.files[documentkey].books;
      name = IndexObj.files[documentkey].name;
      if (searchResult) {
        const keys = Object.keys(searchResult);
        buildTable(books, searchResult, keys, name, "search");
      }
      else{
            throw Error("Search terms must contain letters or numbers");
          }
    } else {
      let files = IndexObj.files;
      for (const documentkey in files) {
          searchResult = IndexObj.searchIndex(terms, documentkey);
          books = IndexObj.files[documentkey].books;
          name = IndexObj.files[documentkey].name;
          if (searchResult) {
            const keys = Object.keys(searchResult);
            buildTable(books, searchResult, keys, name, "search");
          } else {
            throw Error("Search terms must contain letters or numbers");
          }
      }
    }
  }
  catch (e) {
    document.getElementById('myModal').style.display = "block";
    document.getElementById('myModal').style.fontWeight = "bold";
    document.getElementById('errorMsg')
    .innerHTML = e.message;
  }
};

reset = () => {
  document.getElementById('indexList').innerHTML = "";
  document.getElementById('searchList').innerHTML = "";
  document.getElementById('query').value = "";
  document.getElementById('dropdown').innerHTML = "";
  document.getElementById('dropdown2').innerHTML = "";
  IndexObj.files = {};
};

<commit_msg>modify app.js<commit_after>const IndexObj = new Index();

// function to readfiles
readFiles = (files) => {
  document.getElementById('errorMsg').innerHTML = '';
  const select = $('#dropdown');
  for (let i = 0; i < files.length; i += 1) {
    const f = files[i];
    const refinedName = f.name.replace(/\.json/g, '').replace(/\s+/g, '');
    const reader = new FileReader();
    let contents;
    reader.onload = (es) => {
      try {
        contents = Index.isValidJson(es.target.result);
        if (!contents) {
          throw Error('Invalid JSON format');
        }
      } catch (e) {
        document.getElementById('myModal').style.display = 'block';
        document.getElementById('myModal').style.fontWeight = 'bold';
        document.getElementById('errorMsg')
          .innerHTML += `${f.name} failed to upload. Reason? ${e.message}<br>`;
      }
      IndexObj.addFiles(contents, f.name);
      select.append(`<option selected value='${refinedName}'>${IndexObj
        .files[refinedName].name}</option>`);
    };
    if (!IndexObj.files[refinedName]) {
      reader.readAsText(f);
    }
  }
  if (IndexObj.files.length > 1) {
    getIndex();
  } else {
    $('#indexTableDiv').empty()
      .append('
Index has not been created for this file.
');
  }
};

buildTable = (books, indices, keys, documentkey, type) => {
  let frame, line;
  if (type === 'create') {
    frame = '#indexList';
    line = 'table';
  } else {
    frame = '#searchList';
    line = 'search';
  }
  refinedkey = documentkey;
  documentkey = documentkey.replace(/\.json/g, '').replace(/\s+/g, '');
  if (type === 'search') {
    documentkey += 'find';
  }
  let contents;
  const divkey = `#${documentkey}`;
  $(frame)
    .append(`${' <button id="toggleindex" data-toggle="collapse"' +
    'data-target="#'}${documentkey}" class="btn">
${
     refinedkey}
</button>`);
  $(frame).append(`<div id="${documentkey}" class="collapse in">` +
    `</div>`);

  $(divkey).append($(`
`));
  const divkey2 = `#${documentkey}${line}`;
  const table = $(divkey2);
  let tableHeader = '
Words	';
  for (const index in books) {
    tableHeader += `<th>${books[index].title}</th>`;
  }
  tableHeader += '

';
  table.append(tableHeader);
  for (const index in keys) {
    let row = '
';
    row += `<td>${keys[index]}</td>`;
    for (let i = 0; i < books.length; i++) {
      let td = '';
      const whereWordsExist = indices[keys[index]];
      if (whereWordsExist.indexOf(i) >= 0) {
        td += "✔";
      } else {
        td += "✖";
      }
      td += '	';
      row += td;
    }

    row += '
';

    table.append(row);
  }
  table.append('
');
  if (!document.getElementById(`${documentkey}out`)) {
    const newdiv = document.createElement('div');
    newdiv.className = 'outercontain';
    newdiv.id = `${documentkey}out`;
    $('.table').wrap(newdiv);
  }
};

createIndex = () => {
  $('.collapse').removeClass('in');
  const documentkey = document.getElementById('dropdown').value;
  let books, indices, name;
  const select = $('#dropdown2');
  if (documentkey && !IndexObj.getIndex(documentkey)) {
    IndexObj.createIndex(documentkey, IndexObj.files[documentkey].books);
    indices = IndexObj.getIndex(documentkey);
    books = IndexObj.files[documentkey].books;
    name = IndexObj.files[documentkey].name;
    select.append(`<option value='${documentkey}'>${IndexObj
      .files[documentkey]['name']}</option>`);
    $('#dropdown').children(`option[value="${documentkey}"]`)
      .attr('disabled', true)
  }
  if ($('#dropdown2 > option').length === 2) {
    select.append("<option value='' selected >All files</option>");
  }
  const keys = Object.keys(indices);
  buildTable(books, indices, keys, name, 'create');
};

searchIndex = (terms) => {
  try {
    $('#searchList').empty();
    const documentkey = document.getElementById('dropdown2').value;
    let books = [];
    let name;
    let searchResult;
    if (documentkey) {
      searchResult = IndexObj.searchIndex(terms, documentkey);
      searchResult = searchResult[documentkey];
      books = IndexObj.files[documentkey].books;
      name = IndexObj.files[documentkey].name;
      if (searchResult) {
        const keys = Object.keys(searchResult);
        buildTable(books, searchResult, keys, name, 'search');
      } else {
        throw Error('Search terms must contain letters or numbers');
      }
    } else {
      searchResult = IndexObj.searchIndex(terms);
      for(const file in searchResult) {
        const keys = Object.keys(searchResult[file]);
        books = IndexObj.files[file].books;
        name = IndexObj.files[file].name;
        if (searchResult[file]) {
          buildTable(books, searchResult[file], keys, name, 'search');
        } else {
          throw Error('Search terms must contain letters or numbers');
        }
      }
    }
  } catch (e) {
    document.getElementById('myModal').style.display = 'block';
    document.getElementById('myModal').style.fontWeight = 'bold';
    document.getElementById('errorMsg')
      .innerHTML = e.message;
  }
};

reset = () => {
  document.getElementById('indexList').innerHTML = '';
  document.getElementById('searchList').innerHTML = '';
  document.getElementById('query').value = '';
  document.getElementById('dropdown').innerHTML = '';
  document.getElementById('dropdown2').innerHTML = '';
  IndexObj.files = {};
};

<|endoftext|>


<commit_before>import {Observable} from 'rx';
import {div, a, h2, h3, img, hr, button} from '@cycle/dom';

import projects from '../data/projects';

const PROJECTS_PER_PAGE = 10;

const INSTRUCTIONS = `
Please add new projects by making a pull request or issue against this project's repository.
`;

function renderSidebar () {
  return (
    div('.sidebar', [

      a({href: 'http://cycle.js.org', target: '_blank'}, [
        img({src: 'assets/cyclejs_logo.svg', alt: 'Cycle.js'})
      ]),

      h2('Built with Cycle.js'),

      div('.instructions', {innerHTML: INSTRUCTIONS}),

      hr(),

      div('.credit', [
        'Built by ',
        a({href: 'https://github.com/Widdershin'}, 'Widdershin'),
        ' with the help of the ',
        a({href: 'https://github.com/Widdershin/graphs/contributors'}, 'Cycle community'),
        '.'
      ])
    ])
  );
}

function renderProject (project, index, projects) {
  const lastProject = index === projects.length - 1;

  return (
    div('.project', [
      div('.project-header', [
        a('.homepage', {href: project.homepage, target: '_blank'}, [
          h3('.name', project.name)
        ]),

        a('.repo', {href: project.repository, target: '_blank'}, [
          img('.repo-img', {src: 'assets/github.svg', alt: project.name})
        ])
      ]),

      div('.description', project.description),

      a('.homepage', {href: project.homepage, target: '_blank'}, [
        img('.screenshot', {src: project.screenshot, alt: project.name})
      ]),

      lastProject ? '' : hr()
    ])
  );
}

function renderNavigationControls (projects, numberToRender) {
  if (numberToRender >= projects.length) {
    return;
  }

  return (
    div('.navigation', [
      button('.more', 'Show more')
    ])
  );
}

function renderProjects (projects, numberToRender) {
  return (
    div('.projects', projects
      .slice(0, numberToRender)
      .map(renderProject)
      .concat([renderNavigationControls(projects, numberToRender)])
    )
  );
}

export default function App ({DOM}) {
  const showMore$ = DOM
    .select('.navigation .more')
    .events('click')
    .do(ev => ev.preventDefault())
    .map(_ => +PROJECTS_PER_PAGE);

  const projectsToShowCount$ = showMore$
    .scan((current, change) => current + change, PROJECTS_PER_PAGE)
    .startWith(PROJECTS_PER_PAGE);

  return {
    DOM: projectsToShowCount$.map(numberToShow =>
      div('.built-with-cycle', [
        renderSidebar(),
        renderProjects(projects, numberToShow)
      ])
    )
  };
}
<commit_msg>Fix up sidebar links<commit_after>import {Observable} from 'rx';
import {div, a, h2, h3, img, hr, button} from '@cycle/dom';

import projects from '../data/projects';

const PROJECTS_PER_PAGE = 10;

const INSTRUCTIONS = `
Please add new projects by making a pull request or issue against this project's repository.
`;

function renderSidebar () {
  return (
    div('.sidebar', [

      a({href: 'http://cycle.js.org', target: '_blank'}, [
        img({src: 'assets/cyclejs_logo.svg', alt: 'Cycle.js'})
      ]),

      h2('Built with Cycle.js'),

      div('.instructions', {innerHTML: INSTRUCTIONS}),

      hr(),

      div('.credit', [
        'Built by ',
        a({href: 'https://github.com/Widdershin', _target: 'blank'}, 'Widdershin'),
        ' with the help of the ',
        a({href: 'https://github.com/Widdershin/built-with-cycle/graphs/contributors', _target: 'blank'}, 'Cycle community'),
        '.'
      ])
    ])
  );
}

function renderProject (project, index, projects) {
  const lastProject = index === projects.length - 1;

  return (
    div('.project', [
      div('.project-header', [
        a('.homepage', {href: project.homepage, target: '_blank'}, [
          h3('.name', project.name)
        ]),

        a('.repo', {href: project.repository, target: '_blank'}, [
          img('.repo-img', {src: 'assets/github.svg', alt: project.name})
        ])
      ]),

      div('.description', project.description),

      a('.homepage', {href: project.homepage, target: '_blank'}, [
        img('.screenshot', {src: project.screenshot, alt: project.name})
      ]),

      lastProject ? '' : hr()
    ])
  );
}

function renderNavigationControls (projects, numberToRender) {
  if (numberToRender >= projects.length) {
    return;
  }

  return (
    div('.navigation', [
      button('.more', 'Show more')
    ])
  );
}

function renderProjects (projects, numberToRender) {
  return (
    div('.projects', projects
      .slice(0, numberToRender)
      .map(renderProject)
      .concat([renderNavigationControls(projects, numberToRender)])
    )
  );
}

export default function App ({DOM}) {
  const showMore$ = DOM
    .select('.navigation .more')
    .events('click')
    .do(ev => ev.preventDefault())
    .map(_ => +PROJECTS_PER_PAGE);

  const projectsToShowCount$ = showMore$
    .scan((current, change) => current + change, PROJECTS_PER_PAGE)
    .startWith(PROJECTS_PER_PAGE);

  return {
    DOM: projectsToShowCount$.map(numberToShow =>
      div('.built-with-cycle', [
        renderSidebar(),
        renderProjects(projects, numberToShow)
      ])
    )
  };
}
<|endoftext|>


<commit_before>'use strict';

// loading config etc.
const newrelic = require('newrelic');
const config = require('../config');
const version = require('../package.json').version;

// loading libraries
const express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io');
const socket = io(server);
const path = require('path');
const logger = require('./logger');

// Loading components
import SearchServer from './components/Search/Search.server.js';

// settings up our provider
var serviceProvider = require('dbc-node-serviceprovider');
serviceProvider.init(config.services, socket);

// Port config
app.set('port', process.env.PORT || 8080); // eslint-disable-line no-process-env

// Configure templating
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// setting paths
app.use(express.static(path.join(__dirname, '../public')));
app.use(express.static(path.join(__dirname, '../static')));

// setting local vars that should be availbe to our template engine
app.locals.newrelic = newrelic;
app.locals.version = version;
app.locals.env = process.env; // eslint-disable-line no-process-env

// setting basic routes -- should be moved elsewhere in the future
app.get('/', function(req, res) {
  res.render('logo');
});

app.get('/autocomplete', function(req, res) {
  res.render('autocomplete');
});

app.get(['/querysearch', '/querysearch/*'], function(req, res) {
  const query = req.query || [];
  // @TODO Parse properties from url
  res.render('search', SearchServer({query}));
});

// starting server
server.listen(app.get('port'), function() {
  logger.info('Server listening on ' + app.get('port'));
  logger.info({message: 'Versions: ', data: process.versions});
  logger.info(version + ' is up and running');
});
<commit_msg>move route to /search/*<commit_after>'use strict';

// loading config etc.
const newrelic = require('newrelic');
const config = require('../config');
const version = require('../package.json').version;

// loading libraries
const express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io');
const socket = io(server);
const path = require('path');
const logger = require('./logger');

// Loading components
import SearchServer from './components/Search/Search.server.js';

// settings up our provider
var serviceProvider = require('dbc-node-serviceprovider');
serviceProvider.init(config.services, socket);

// Port config
app.set('port', process.env.PORT || 8080); // eslint-disable-line no-process-env

// Configure templating
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// setting paths
app.use(express.static(path.join(__dirname, '../public')));
app.use(express.static(path.join(__dirname, '../static')));

// setting local vars that should be availbe to our template engine
app.locals.newrelic = newrelic;
app.locals.version = version;
app.locals.env = process.env; // eslint-disable-line no-process-env

// setting basic routes -- should be moved elsewhere in the future
app.get('/', function(req, res) {
  res.render('logo');
});

app.get('/autocomplete', function(req, res) {
  res.render('autocomplete');
});

app.get(['/search', '/search/*'], function(req, res) {
  const query = req.query || [];
  // @TODO Parse properties from url
  res.render('search', SearchServer({query}));
});

// starting server
server.listen(app.get('port'), function() {
  logger.info('Server listening on ' + app.get('port'));
  logger.info({message: 'Versions: ', data: process.versions});
  logger.info(version + ' is up and running');
});
<|endoftext|>


<commit_before>var mqtt   = require('mqtt');
var tcp    = require('net');
var moment = require('moment-timezone');

var fritzConnection;
var mqttConnection;

var regexCall       = /^(\d{2}\.\d{2}\.\d{2} \d{2}\:\d{2}\:\d{2});CALL;(\d+);(\d+);(\d+);(\d+);/g; // datum;CALL;ConnectionID;Nebenstelle;GenutzteNummer;AngerufeneNummer;
var regexRing       = /^(\d{2}\.\d{2}\.\d{2} \d{2}\:\d{2}\:\d{2});RING;(\d+);(\d+);(\d+);(\w+);/g; // datum;RING;ConnectionID;Anrufer-Nr;Angerufene-Nummer;Gateway;
var regexConnect    = /^(\d{2}\.\d{2}\.\d{2} \d{2}\:\d{2}\:\d{2});CONNECT;(\d+);(\d+);(\d+);/g;    // datum;CONNECT;ConnectionID;Nebenstelle;Nummer;
var regexDisconnect = /^(\d{2}\.\d{2}\.\d{2} \d{2}\:\d{2}\:\d{2});DISCONNECT;(\d+);(\d+);/g;       // datum;DISCONNECT;ConnectionID;dauerInSekunden;

mqttConnection = mqtt.connect('tcp://localhost:1883', {
    protocolId: 'MQIsdp',
    protocolVersion: 3,
    will: {topic: "fritz/connect", payload: "0", qos: 1}
});

mqttConnection.on('connect', function () {

    fritzConnection = tcp.connect('1012', '192.168.178.1');

    fritzConnection.on('data', function(data) {

        var event = {};
        var ts;
        var parsed = [];

        if (parsed = regexCall.exec(data)) {
            event = {
                ts: moment.tz(parsed[1], 'DD.MM.YY HH:mm:ss', 'Europe/Berlin').get('X'),
                type: 'call',
                connectionId: parsed[2],
                extension: parsed[3],
                callingNumber: parsed[4],
                calledNumber: parsed[5]
            };
            console.log('CALL', event);
        }
        if (parsed = regexRing.exec(data)) {
            event = {
                ts: moment.tz(parsed[1], 'DD.MM.YY HH:mm:ss', 'Europe/Berlin').get('X'),
                type: 'ring',
                connectionId: parsed[2],
                callingNumber: parsed[3],
                calledNumber: parsed[4],
                gateway: parsed[5]
            };
            console.log('RING', event);
        }
        if (parsed = regexConnect.exec(data)) {
            event = {
                ts: moment.tz(parsed[1], 'DD.MM.YY HH:mm:ss', 'Europe/Berlin').get('X'),
                type: 'connect',
                connectionId: parsed[2],
                extension: parsed[3],
                callingNumber: parsed[4]
            };
            console.log('CONNECT', event);
        }
        if (parsed = regexDisconnect.exec(data)) {
            event = {
                ts: moment.tz(parsed[1], 'DD.MM.YY HH:mm:ss', 'Europe/Berlin').get('X'),
                type: 'disconnect',
                connectionId: parsed[2],
                length: parsed[3]
            };
            console.log('DISCONNECT', event);
        }

        mqttConnection.publish('fritz/callmonitor/', JSON.stringify(event));
    }).on('connect', function() {
        console.log('callmonitor connect');
        mqttConnection.publish('fritz/callmonitor/connect', '1');
    }).on('end', function() {
        mqttConnection.publish('fritz/callmonitor/connect', '0');
    });

});

mqttConnection.on('reconnect', function () {
    console.log('mqtt reconnect');
});

mqttConnection.on('close', function () {
    console.log('mqtt close');
});

mqttConnection.on('error', function (error) {
    console.log('mqtt error: ', error);
});

mqttConnection.on('message', function (topic, message) {
    console.log('mqtt message:', topic, message.toString());
});

<commit_msg>update<commit_after>var mqtt   = require('mqtt');
var tcp    = require('net');
var moment = require('moment-timezone');

var fritzConnection;
var mqttConnection;

var regexCall       = /^(\d{2}\.\d{2}\.\d{2} \d{2}\:\d{2}\:\d{2});CALL;(\d+);(\d+);(\d+);(\d+);/g; // datum;CALL;ConnectionID;Nebenstelle;GenutzteNummer;AngerufeneNummer;
var regexRing       = /^(\d{2}\.\d{2}\.\d{2} \d{2}\:\d{2}\:\d{2});RING;(\d+);(\d+);(\d+);(\w+);/g; // datum;RING;ConnectionID;Anrufer-Nr;Angerufene-Nummer;Gateway;
var regexConnect    = /^(\d{2}\.\d{2}\.\d{2} \d{2}\:\d{2}\:\d{2});CONNECT;(\d+);(\d+);(\d+);/g;    // datum;CONNECT;ConnectionID;Nebenstelle;Nummer;
var regexDisconnect = /^(\d{2}\.\d{2}\.\d{2} \d{2}\:\d{2}\:\d{2});DISCONNECT;(\d+);(\d+);/g;       // datum;DISCONNECT;ConnectionID;dauerInSekunden;

mqttConnection = mqtt.connect('tcp://localhost:1883', {
    protocolId: 'MQIsdp',
    protocolVersion: 3,
    will: {topic: "fritz/callmonitor/connect", payload: "0", qos: 1}
});

mqttConnection.on('connect', function () {

    fritzConnection = tcp.connect('1012', '192.168.178.1');

    fritzConnection.on('data', function(data) {

        var event = {};

        if (parsed = regexCall.exec(data)) {
            event = {
                ts: moment.tz(parsed[1], 'DD.MM.YY HH:mm:ss', 'Europe/Berlin').get('X'),
                type: 'call',
                connectionId: parsed[2],
                extension: parsed[3],
                callingNumber: parsed[4],
                calledNumber: parsed[5]
            };
            console.log('CALL', event);
        }
        if (parsed = regexRing.exec(data)) {
            event = {
                ts: moment.tz(parsed[1], 'DD.MM.YY HH:mm:ss', 'Europe/Berlin').get('X'),
                type: 'ring',
                connectionId: parsed[2],
                callingNumber: parsed[3],
                calledNumber: parsed[4],
                gateway: parsed[5]
            };
            console.log('RING', event);
        }
        if (parsed = regexConnect.exec(data)) {
            event = {
                ts: moment.tz(parsed[1], 'DD.MM.YY HH:mm:ss', 'Europe/Berlin').get('X'),
                type: 'connect',
                connectionId: parsed[2],
                extension: parsed[3],
                callingNumber: parsed[4]
            };
            console.log('CONNECT', event);
        }
        if (parsed = regexDisconnect.exec(data)) {
            event = {
                ts: moment.tz(parsed[1], 'DD.MM.YY HH:mm:ss', 'Europe/Berlin').get('X'),
                type: 'disconnect',
                connectionId: parsed[2],
                length: parsed[3]
            };
            console.log('DISCONNECT', event);
        }

        mqttConnection.publish('fritz/callmonitor/', JSON.stringify(event));
    }).on('connect', function() {
        console.log('callmonitor connect');
        mqttConnection.publish('fritz/callmonitor/connect', '1');
    }).on('end', function() {
        mqttConnection.publish('fritz/callmonitor/connect', '0');
    });

});

mqttConnection.on('reconnect', function () {
    console.log('mqtt reconnect');
});

mqttConnection.on('close', function () {
    console.log('mqtt close');
});

mqttConnection.on('error', function (error) {
    console.log('mqtt error: ', error);
});

mqttConnection.on('message', function (topic, message) {
    console.log('mqtt message:', topic, message.toString());
});

<|endoftext|>


<commit_before>var app;

POOLVR.ballMeshes = [];
POOLVR.ballBodies = [];
POOLVR.initialPositions = [];
POOLVR.onTable = [false,
                  true, true, true, true, true, true, true,
                  true,
                  true, true, true, true, true, true, true];
POOLVR.nextBall = 1;

POOLVR.selectNextBall = function (inc) {
    "use strict";
    inc = inc || 1;
    var next = Math.max(1, Math.min(15, POOLVR.nextBall + inc));
    while (!POOLVR.onTable[next]) {
        next = Math.max(1, Math.min(15, next + inc));
        if (next === POOLVR.nextBall) {
            break;
        }
    }
    if (POOLVR.nextBall != next) {
        POOLVR.nextBall = next;
        POOLVR.textGeomLogger.log("BALL " + POOLVR.nextBall + " SELECTED");
    }
};

POOLVR.resetTable = function () {
    "use strict";
    POOLVR.ballBodies.forEach(function (body, ballNum) {
        body.wakeUp();
        body.position.copy(POOLVR.initialPositions[ballNum]);
        body.velocity.set(0, 0, 0);
        body.angularVelocity.set(0, 0, 0);
        // body.bounces = 0;
        body.mesh.visible = true;
    });
    if (POOLVR.synthSpeaker.speaking === false) {
        POOLVR.synthSpeaker.speak("Table reset.");
    }
    POOLVR.nextBall = 1;
    POOLVR.textGeomLogger.log("TABLE RESET.");
};

POOLVR.autoPosition = ( function () {
    "use strict";
    var nextVector = new THREE.Vector3();
    var UP = new THREE.Vector3(0, 1, 0);
    function autoPosition(avatar) {
        POOLVR.textGeomLogger.log("YOU ARE BEING AUTO-POSITIONED.  NEXT BALL: " + POOLVR.nextBall);

        avatar.heading = Math.atan2(
            -(POOLVR.ballMeshes[POOLVR.nextBall].position.x - POOLVR.ballMeshes[0].position.x),
            -(POOLVR.ballMeshes[POOLVR.nextBall].position.z - POOLVR.ballMeshes[0].position.z)
        );
        avatar.quaternion.setFromAxisAngle(UP, avatar.heading);
        avatar.updateMatrixWorld();

        nextVector.copy(POOLVR.toolRoot.position);
        avatar.localToWorld(nextVector);
        nextVector.sub(POOLVR.ballMeshes[0].position);
        nextVector.y = 0;
        avatar.position.sub(nextVector);
    }
    return autoPosition;
} )();

POOLVR.startTutorial = function () {
    "use strict";
    POOLVR.synthSpeaker.speak("Hello.  Welcome. To. Pool-ver.", function () {
        POOLVR.textGeomLogger.log("HELLO.  WELCOME TO POOLVR.");
    });

    POOLVR.synthSpeaker.speak("Please wave a stick-like object in front of your Leap Motion controller.", function () {
        POOLVR.textGeomLogger.log("PLEASE WAVE A STICK-LIKE OBJECT IN FRONT OF YOUR");
        POOLVR.textGeomLogger.log("LEAP MOTION CONTROLLER.");
    });

    POOLVR.synthSpeaker.speak("Keep the stick within the interaction box when you want to make contact with.  A ball.", function () {
        POOLVR.textGeomLogger.log("KEEP THE STICK WITHIN THE INTERACTION BOX WHEN YOU WANT");
        POOLVR.textGeomLogger.log("TO MAKE CONTACT WITH A BALL...");
    });
};

var animate = function (world, keyboard, gamepad, updateTool, updateGraphics, moveToolRoot) {
    "use strict";
    var UP = new THREE.Vector3(0, 1, 0),
        walkSpeed = 0.333,
        floatSpeed = 0.1;
    var avatar = POOLVR.avatar;
    var lt = 0;

    function animate(t) {
        var dt = (t - lt) * 0.001;
        requestAnimationFrame(animate);

        updateTool(dt);

        updateGraphics();

        if (app.vrControls.enabled) {
            app.vrControls.update();
        }
        app.vrManager.render(app.scene, app.camera, t);

        //world.step(dt);
        //world.step(1/75, dt, 5);
        world.step(1/60, dt, 5);

        keyboard.update(dt);
        gamepad.update(dt);

        moveToolRoot(keyboard, gamepad, dt);

        var floatUp = keyboard.getValue("floatUp") + keyboard.getValue("floatDown");
        var drive = keyboard.getValue("driveBack") + keyboard.getValue("driveForward");
        var strafe = keyboard.getValue("strafeRight") + keyboard.getValue("strafeLeft");

        var heading = -0.8 * dt * (keyboard.getValue("turnLeft") + keyboard.getValue("turnRight"));
        if (avatar.floatMode) {
            floatUp += gamepad.getValue("float");
            strafe += gamepad.getValue("strafe");
        } else {
            drive += gamepad.getValue("drive");
            heading += 0.8 * dt * gamepad.getValue("dheading");
        }
        floatUp *= floatSpeed;
        if (strafe || drive) {
            var len = walkSpeed * Math.min(1, 1 / Math.sqrt(drive * drive +
                strafe * strafe));
            strafe *= len;
            drive *= len;
        } else {
            strafe = 0;
            drive = 0;
        }

        if (floatUp !== 0 || strafe !== 0 || heading !== 0 || drive !== 0) {
            avatar.heading += heading;
            var cosHeading = Math.cos(avatar.heading),
                sinHeading = Math.sin(avatar.heading);

            avatar.quaternion.setFromAxisAngle(UP, avatar.heading);

            avatar.position.x += dt * (strafe * cosHeading + drive * sinHeading);
            avatar.position.z += dt * (drive * cosHeading - strafe * sinHeading);
            avatar.position.y += dt * floatUp;
        }

        lt = t;
    }

    return animate;

};

/* jshint multistr: true */
function onLoad() {
    "use strict";

    POOLVR.loadConfig();
    console.log("POOLVR.config =\n" + JSON.stringify(POOLVR.config, undefined, 2));

    var avatar = new THREE.Object3D();
    avatar.position.fromArray(POOLVR.config.initialPosition);
    avatar.heading = 0;
    avatar.floatMode = false;
    avatar.toolMode = false;
    POOLVR.avatar = avatar;

    POOLVR.synthSpeaker = new SynthSpeaker({volume: POOLVR.config.synthSpeakerVolume, rate: 0.8, pitch: 0.5});

    POOLVR.textGeomLogger = {
        root: new THREE.Object3D(),
        log: function (msg) { console.log(msg); },
        clear: function () {}
    };
    if (POOLVR.config.useTextGeomLogger) {
        var fontLoader = new THREE.FontLoader();
        fontLoader.load('fonts/Anonymous Pro_Regular.js', function (font) {
            var textGeomCacher = new TextGeomUtils.TextGeomCacher(font, {size: 0.12});
            var textGeomLoggerMaterial = new THREE.MeshBasicMaterial({color: 0xff3210});
            POOLVR.textGeomLogger = new TextGeomUtils.TextGeomLogger(textGeomCacher,
                {material: textGeomLoggerMaterial, nrows: 7, lineHeight: 1.8 * 0.12});
            avatar.add(POOLVR.textGeomLogger.root);
            POOLVR.textGeomLogger.root.position.set(-2.5, 1.0, -3.5);
        });
    }

    THREE.py.parse(THREEPY_SCENE).then( function (scene) {

        if (!POOLVR.config.useBasicMaterials) {
            var centerSpotLight = new THREE.SpotLight(0xffffee, 1, 10, 90);
            centerSpotLight.position.set(0, 3, 0);
            centerSpotLight.castShadow = true;
            centerSpotLight.shadowCameraNear = 0.01;
            centerSpotLight.shadowCameraFar = 4;
            centerSpotLight.shadowCameraFov = 90;
            scene.add(centerSpotLight);
        }

        if (POOLVR.config.usePointLight) {
            var pointLight = new THREE.PointLight(0xaa8866, 0.8, 40);
            pointLight.position.set(4, 5, 2.5);
            scene.add(pointLight);
        }

        var UP = new THREE.Vector3(0, 1, 0);
        var appConfig = combineObjects(POOLVR.config, {
            onResetVRSensor: function (lastRotation, lastPosition) {
                // app.camera.updateMatrix();
                avatar.heading += lastRotation - app.camera.rotation.y;
                POOLVR.toolRoot.rotation.y -= (lastRotation - app.camera.rotation.y);
                POOLVR.toolRoot.position.sub(lastPosition);
                POOLVR.toolRoot.position.applyAxisAngle(UP, -lastRotation + app.camera.rotation.y);
                POOLVR.toolRoot.position.add(app.camera.position);
                // POOLVR.toolRoot.updateMatrix();
                avatar.updateMatrixWorld();
            }
        });

        app = new WebVRApplication(scene, appConfig);

        var world = new CANNON.World();
        world.gravity.set( 0, -POOLVR.config.gravity, 0 );
        //world.broadphase = new CANNON.SAPBroadphase( world );
        world.defaultContactMaterial.contactEquationStiffness   = 1e6;
        world.defaultContactMaterial.frictionEquationStiffness  = 1e6;
        world.defaultContactMaterial.contactEquationRelaxation  = 3;
        world.defaultContactMaterial.frictionEquationRelaxation = 3;
        world.solver.iterations = 9;

        THREE.py.CANNONize(scene, world);

        avatar.add(app.camera);
        scene.add(avatar);

        POOLVR.setupMaterials(world);
        POOLVR.setupWorld(scene, world);

        var leapTool = addTool(avatar, world, POOLVR.toolOptions);
        POOLVR.toolRoot = leapTool.toolRoot;

        requestAnimationFrame( animate(world, POOLVR.keyboard, POOLVR.gamepad, leapTool.updateTool, leapTool.updateGraphics, leapTool.moveToolRoot) );

        POOLVR.startTutorial();

    } );

}
<commit_msg>fix spotlight<commit_after>var app;

POOLVR.ballMeshes = [];
POOLVR.ballBodies = [];
POOLVR.initialPositions = [];
POOLVR.onTable = [false,
                  true, true, true, true, true, true, true,
                  true,
                  true, true, true, true, true, true, true];
POOLVR.nextBall = 1;

POOLVR.selectNextBall = function (inc) {
    "use strict";
    inc = inc || 1;
    var next = Math.max(1, Math.min(15, POOLVR.nextBall + inc));
    while (!POOLVR.onTable[next]) {
        next = Math.max(1, Math.min(15, next + inc));
        if (next === POOLVR.nextBall) {
            break;
        }
    }
    if (POOLVR.nextBall != next) {
        POOLVR.nextBall = next;
        POOLVR.textGeomLogger.log("BALL " + POOLVR.nextBall + " SELECTED");
    }
};

POOLVR.resetTable = function () {
    "use strict";
    POOLVR.ballBodies.forEach(function (body, ballNum) {
        body.wakeUp();
        body.position.copy(POOLVR.initialPositions[ballNum]);
        body.velocity.set(0, 0, 0);
        body.angularVelocity.set(0, 0, 0);
        // body.bounces = 0;
        body.mesh.visible = true;
    });
    if (POOLVR.synthSpeaker.speaking === false) {
        POOLVR.synthSpeaker.speak("Table reset.");
    }
    POOLVR.nextBall = 1;
    POOLVR.textGeomLogger.log("TABLE RESET.");
};

POOLVR.autoPosition = ( function () {
    "use strict";
    var nextVector = new THREE.Vector3();
    var UP = new THREE.Vector3(0, 1, 0);
    function autoPosition(avatar) {
        POOLVR.textGeomLogger.log("YOU ARE BEING AUTO-POSITIONED.  NEXT BALL: " + POOLVR.nextBall);

        avatar.heading = Math.atan2(
            -(POOLVR.ballMeshes[POOLVR.nextBall].position.x - POOLVR.ballMeshes[0].position.x),
            -(POOLVR.ballMeshes[POOLVR.nextBall].position.z - POOLVR.ballMeshes[0].position.z)
        );
        avatar.quaternion.setFromAxisAngle(UP, avatar.heading);
        avatar.updateMatrixWorld();

        nextVector.copy(POOLVR.toolRoot.position);
        avatar.localToWorld(nextVector);
        nextVector.sub(POOLVR.ballMeshes[0].position);
        nextVector.y = 0;
        avatar.position.sub(nextVector);
    }
    return autoPosition;
} )();

POOLVR.startTutorial = function () {
    "use strict";
    POOLVR.synthSpeaker.speak("Hello.  Welcome. To. Pool-ver.", function () {
        POOLVR.textGeomLogger.log("HELLO.  WELCOME TO POOLVR.");
    });

    POOLVR.synthSpeaker.speak("Please wave a stick-like object in front of your Leap Motion controller.", function () {
        POOLVR.textGeomLogger.log("PLEASE WAVE A STICK-LIKE OBJECT IN FRONT OF YOUR");
        POOLVR.textGeomLogger.log("LEAP MOTION CONTROLLER.");
    });

    POOLVR.synthSpeaker.speak("Keep the stick within the interaction box when you want to make contact with.  A ball.", function () {
        POOLVR.textGeomLogger.log("KEEP THE STICK WITHIN THE INTERACTION BOX WHEN YOU WANT");
        POOLVR.textGeomLogger.log("TO MAKE CONTACT WITH A BALL...");
    });
};

var animate = function (world, keyboard, gamepad, updateTool, updateGraphics, moveToolRoot) {
    "use strict";
    var UP = new THREE.Vector3(0, 1, 0),
        walkSpeed = 0.333,
        floatSpeed = 0.1;
    var avatar = POOLVR.avatar;
    var lt = 0;

    function animate(t) {
        var dt = (t - lt) * 0.001;
        requestAnimationFrame(animate);

        updateTool(dt);

        updateGraphics();

        if (app.vrControls.enabled) {
            app.vrControls.update();
        }
        app.vrManager.render(app.scene, app.camera, t);

        //world.step(dt);
        //world.step(1/75, dt, 5);
        world.step(1/60, dt, 5);

        keyboard.update(dt);
        gamepad.update(dt);

        moveToolRoot(keyboard, gamepad, dt);

        var floatUp = keyboard.getValue("floatUp") + keyboard.getValue("floatDown");
        var drive = keyboard.getValue("driveBack") + keyboard.getValue("driveForward");
        var strafe = keyboard.getValue("strafeRight") + keyboard.getValue("strafeLeft");

        var heading = -0.8 * dt * (keyboard.getValue("turnLeft") + keyboard.getValue("turnRight"));
        if (avatar.floatMode) {
            floatUp += gamepad.getValue("float");
            strafe += gamepad.getValue("strafe");
        } else {
            drive += gamepad.getValue("drive");
            heading += 0.8 * dt * gamepad.getValue("dheading");
        }
        floatUp *= floatSpeed;
        if (strafe || drive) {
            var len = walkSpeed * Math.min(1, 1 / Math.sqrt(drive * drive +
                strafe * strafe));
            strafe *= len;
            drive *= len;
        } else {
            strafe = 0;
            drive = 0;
        }

        if (floatUp !== 0 || strafe !== 0 || heading !== 0 || drive !== 0) {
            avatar.heading += heading;
            var cosHeading = Math.cos(avatar.heading),
                sinHeading = Math.sin(avatar.heading);

            avatar.quaternion.setFromAxisAngle(UP, avatar.heading);

            avatar.position.x += dt * (strafe * cosHeading + drive * sinHeading);
            avatar.position.z += dt * (drive * cosHeading - strafe * sinHeading);
            avatar.position.y += dt * floatUp;
        }

        lt = t;
    }

    return animate;

};

/* jshint multistr: true */
function onLoad() {
    "use strict";

    POOLVR.loadConfig();
    console.log("POOLVR.config =\n" + JSON.stringify(POOLVR.config, undefined, 2));

    var avatar = new THREE.Object3D();
    avatar.position.fromArray(POOLVR.config.initialPosition);
    avatar.heading = 0;
    avatar.floatMode = false;
    avatar.toolMode = false;
    POOLVR.avatar = avatar;

    POOLVR.synthSpeaker = new SynthSpeaker({volume: POOLVR.config.synthSpeakerVolume, rate: 0.8, pitch: 0.5});

    POOLVR.textGeomLogger = {
        root: new THREE.Object3D(),
        log: function (msg) { console.log(msg); },
        clear: function () {}
    };
    if (POOLVR.config.useTextGeomLogger) {
        var fontLoader = new THREE.FontLoader();
        fontLoader.load('fonts/Anonymous Pro_Regular.js', function (font) {
            var textGeomCacher = new TextGeomUtils.TextGeomCacher(font, {size: 0.12});
            var textGeomLoggerMaterial = new THREE.MeshBasicMaterial({color: 0xff3210});
            POOLVR.textGeomLogger = new TextGeomUtils.TextGeomLogger(textGeomCacher,
                {material: textGeomLoggerMaterial, nrows: 7, lineHeight: 1.8 * 0.12});
            avatar.add(POOLVR.textGeomLogger.root);
            POOLVR.textGeomLogger.root.position.set(-2.5, 1.0, -3.5);
        });
    }

    THREE.py.parse(THREEPY_SCENE).then( function (scene) {

        if (!POOLVR.config.useBasicMaterials) {
            var centerSpotLight = new THREE.SpotLight(0xffffee, 1, 8, Math.PI / 2);
            centerSpotLight.position.set(0, 3, 0);
            centerSpotLight.castShadow = true;
            centerSpotLight.shadow.camera.near = 0.01;
            centerSpotLight.shadow.camera.far = 4;
            centerSpotLight.shadow.camera.fov = 90;
            scene.add(centerSpotLight);
        }

        if (POOLVR.config.usePointLight) {
            var pointLight = new THREE.PointLight(0xaa8866, 0.8, 40);
            pointLight.position.set(4, 5, 2.5);
            scene.add(pointLight);
        }

        var UP = new THREE.Vector3(0, 1, 0);
        var appConfig = combineObjects(POOLVR.config, {
            onResetVRSensor: function (lastRotation, lastPosition) {
                // app.camera.updateMatrix();
                avatar.heading += lastRotation - app.camera.rotation.y;
                POOLVR.toolRoot.rotation.y -= (lastRotation - app.camera.rotation.y);
                POOLVR.toolRoot.position.sub(lastPosition);
                POOLVR.toolRoot.position.applyAxisAngle(UP, -lastRotation + app.camera.rotation.y);
                POOLVR.toolRoot.position.add(app.camera.position);
                // POOLVR.toolRoot.updateMatrix();
                avatar.updateMatrixWorld();
            }
        });

        app = new WebVRApplication(scene, appConfig);

        var world = new CANNON.World();
        world.gravity.set( 0, -POOLVR.config.gravity, 0 );
        //world.broadphase = new CANNON.SAPBroadphase( world );
        world.defaultContactMaterial.contactEquationStiffness   = 1e6;
        world.defaultContactMaterial.frictionEquationStiffness  = 1e6;
        world.defaultContactMaterial.contactEquationRelaxation  = 3;
        world.defaultContactMaterial.frictionEquationRelaxation = 3;
        world.solver.iterations = 9;

        THREE.py.CANNONize(scene, world);

        avatar.add(app.camera);
        scene.add(avatar);

        POOLVR.setupMaterials(world);
        POOLVR.setupWorld(scene, world);

        var leapTool = addTool(avatar, world, POOLVR.toolOptions);
        POOLVR.toolRoot = leapTool.toolRoot;

        requestAnimationFrame( animate(world, POOLVR.keyboard, POOLVR.gamepad, leapTool.updateTool, leapTool.updateGraphics, leapTool.moveToolRoot) );

        POOLVR.startTutorial();

    } );

}
<|endoftext|>


<commit_before>/* See license.txt for terms of usage */

define([
    "firebug/lib/object",
    "firebug/firebug",
    "firebug/lib/locale",
    "firebug/lib/url",
    "firebug/chrome/tabWatcher",
    "firebug/chrome/annotations",
    "firebug/chrome/firefox",
],
function(Obj, Firebug, Locale, Url, TabWatcher, Annotations, Firefox) {

// ********************************************************************************************* //
// Constants

const Cc = Components.classes;
const Ci = Components.interfaces;

// ********************************************************************************************* //

/**
 * @module Implements Firebug activation logic.
 *
 * 1) Part of the logic is based on annotation service (see components/firebug-annotations.js)
 *    in order to remember whether Firebug is activated for given site or not.
 *    If there is "firebugged.showFirebug" annotation for a given site Firebug is activated.
 *    If there is "firebugged.closed" annotation for a given site Firebug is not activated.
 *
 * 2) Other part is based on extensions.firebug.allPagesActivation option. This option
 *    can be set to the following values:
 *    none: The option isn't used (default value)
 *    on:   Firebug is activated for all URLs.
 *    off:  Firebug is never activated.
 *
 *    This logic has higher priority over the URL annotations.
 *    If "off" options is selected, all existing URL annotations are removed.
 */
Firebug.Activation = Obj.extend(Firebug.Module,
{
    dispatchName: "activation",

    // called once
    initializeUI: function()
    {
        Firebug.Module.initializeUI.apply(this, arguments);

        TabWatcher.initializeUI();
        TabWatcher.addListener(this);
    },

    shutdown: function()
    {
        Firebug.Module.shutdown.apply(this, arguments);

        TabWatcher.removeListener(this);
    },

    // true if the Places annotation the URI "firebugged"
    shouldCreateContext: function(browser, url, userCommands)
    {
        if (FBTrace.DBG_ACTIVATION)
            FBTrace.sysout("shouldCreateContext allPagesActivation " +
                Firebug.allPagesActivation);

        if (Firebug.allPagesActivation == "on")
            return true;

        // if about:blank gets through, issue 1483 fails
        // xxxHonza: The following condition is the cause of issue 5632
        // Note that removing the condition doesn't cause issue 1481 to fail anymore.
        //if (Firebug.filterSystemURLs && Url.isSystemURL(url))
        //    return false;

        if (userCommands)
            return true;

        // document.open on a firebugged page
        if (browser && browser.showFirebug && url.substr(0, 8) === "wyciwyg:")
            return true;

        try
        {
            var uri = this.convertToURIKey(url, Firebug.activateSameOrigin);
            if (!uri)
                return false;

            var hasAnnotation = Annotations.pageHasAnnotation(uri);

            if (FBTrace.DBG_ACTIVATION)
            {
                FBTrace.sysout("shouldCreateContext hasAnnotation " + hasAnnotation +
                    " for " + uri.spec + " in " +
                    (browser ? browser.contentWindow.location : "no browser") +
                    " using activateSameOrigin: " + Firebug.activateSameOrigin);
            }

            // Annotated, so return the value.
            if (hasAnnotation)
                return this.checkAnnotation(browser, uri);

            // Then Firebug.TabWatcher found a connection.
            if (browser.FirebugLink)
            {
                var dst = browser.FirebugLink.dst;
                var dstURI = this.convertToURIKey(dst.spec, Firebug.activateSameOrigin);

                if (FBTrace.DBG_ACTIVATION)
                {
                    FBTrace.sysout("shouldCreateContext found FirebugLink pointing to " +
                        dstURI.spec, browser.FirebugLink);
                }

                // And it matches us now.
                if (dstURI && dstURI.equals(uri))
                {
                    var srcURI = this.convertToURIKey(browser.FirebugLink.src.spec,
                        Firebug.activateSameOrigin);

                    if (srcURI)
                    {
                        if (FBTrace.DBG_ACTIVATION)
                        {
                            FBTrace.sysout("shouldCreateContext found FirebugLink pointing from " +
                                srcURI.spec, browser.FirebugLink);
                        }

                        // And it's on the same domain.
                        if (srcURI.schemeIs("file") || (dstURI.host == srcURI.host))
                        {
                            hasAnnotation = Annotations.pageHasAnnotation(srcURI);
                            // And the source page was annotated.
                            if (hasAnnotation)
                            {
                                var srcShow = this.checkAnnotation(browser, srcURI);
                                // And the source annotation said show it.
                                if (srcShow)
                                {
                                    // So we show dst as well.
                                    this.watchBrowser(browser);
                                }
                                return srcShow;
                            }
                        }
                    }
                }
                else
                {
                    if (FBTrace.DBG_ACTIVATION)
                        FBTrace.sysout("shouldCreateContext FirebugLink does not match " +
                            uri.spec, browser.FirebugLink);
                }
            }
            else if (browser.contentWindow.opener)
            {
                var openerContext = Firebug.TabWatcher.getContextByWindow(
                    browser.contentWindow.opener);

                if (FBTrace.DBG_ACTIVATION)
                    FBTrace.sysout("shouldCreateContext opener found, has " +
                        (openerContext ? "a " : "no ") + " context: " +
                        browser.contentWindow.opener.location);

                if (openerContext)
                {
                    // popup windows of Firebugged windows are Firebugged
                    return true;
                }
            }

            // don't createContext
            return false;
        }
        catch (exc)
        {
            if (FBTrace.DBG_ERRORS)
            {
                FBTrace.sysout("pageHasAnnotation FAILS for url: " + url + " which gave uri " +
                    (uri ? uri.spec : "null"), exc);
            }
        }
    },

    shouldShowContext: function(context)
    {
        return this.shouldCreateContext(context.browser, context.getWindowLocation().toString());
    },

    // Firebug is opened in the browser.
    watchBrowser: function(browser)
    {
        try
        {
            var annotation = "firebugged.showFirebug";
            this.setPageAnnotation(browser.currentURI.spec, annotation);
        }
        catch (e)
        {
            if (FBTrace.DBG_ERRORS)
                FBTrace.sysout("activation.watchBrowser; EXCEPTION " + e, e);
        }
    },

    // Firebug closes in the browser.
    unwatchBrowser: function(browser, userCommands)
    {
        var uri = browser.currentURI.spec;
        // Then mark to not open virally.
        if (userCommands)
        {
            this.setPageAnnotation(uri, "firebugged.closed");
        }
        else
        {
            // unmark this URI
            this.removePageAnnotation(uri);
        }
    },

    clearAnnotations: function()
    {
        Annotations.clear();
        Annotations.flush();

        Firebug.connection.dispatch("onClearAnnotations", []);
    },

    // Process the URL to canonicalize it. This needs not be reversible.
    convertToURIKey: function(url, sameOrigin)
    {
        // Remove the fragment. It shouldn't have any impact on the activation.
        url = url.replace(/#.*/, "");

        var uri = Url.makeURI(Url.normalizeURL(url));

        if (Firebug.filterSystemURLs && Url.isSystemURL(url))
            return uri;

        // avoid exceptions
        if (url == "about:blank")
            return uri;

        if (uri && sameOrigin)
        {
            try
            {
                // Returns the string before the path (such as "scheme://user:password@host:port").
                var prePath = uri.prePath;
                var shortURI = Url.makeURI(prePath);
                if (!shortURI)
                    return uri;

                // Annoying "about" URIs throw if .host is accessed
                if (shortURI.scheme === "about")
                    return shortURI;

                if (shortURI.scheme === "file")
                    return shortURI;

                return shortURI;

                // This makes a.co.uk -> co.uk, mail.cn.mozilla.com -> cn.mozilla.com and
                // blog.getfirebug.com -> getfirebug.com, which is wrong. See issue 2202.)
                /*
                var host = shortURI.host;
                if (host)
                {
                    // Slice the subdomain (if any) from the URL so that activateSameOrigin works
                    // for domains (including TLD domains). So we want:
                    // 1) www.google.com -> google.com
                    // 2) www.stuff.co.nz -> stuff.co.nz
                    // 3) getfirebug.com -> getfirebug.com
                    var levels = host.split('.');
                    if (levels.length > 2)
                        levels = levels.slice(1);
                    shortURI.host = levels.join('.');
                    return shortURI;
                }
                */
            }
            catch (exc)
            {
                if (FBTrace.DBG_ERRORS)
                    FBTrace.sysout("activation.convertToURIKey returning full URI, " +
                        "activateSameOrigin FAILS for shortURI " + shortURI + " because: " + exc,
                        exc);

                return uri;
            }
        }

        return uri;
    },

    checkAnnotation: function(browser, uri)
    {
        var annotation = Annotations.getPageAnnotation(uri);

        if (FBTrace.DBG_ACTIVATION)
            FBTrace.sysout("shouldCreateContext read back annotation " + annotation +
                " for uri " + uri.spec);

        // Then the user closed Firebug on this page last time.
        if ((Firebug.allPagesActivation != "on") && (annotation.indexOf("closed") > 0))
        {
            // annotated as 'closed', don't create
            return false;
        }
        else
        {
            // annotated, createContext
            return true;
        }
    },

    setPageAnnotation: function(currentURI, annotation)
    {
        var uri = this.convertToURIKey(currentURI, Firebug.activateSameOrigin);
        if (uri)
            Annotations.setPageAnnotation(uri, annotation);

        if (FBTrace.DBG_ACTIVATION || FBTrace.DBG_ANNOTATION)
            FBTrace.sysout("setPageAnnotation currentURI " + currentURI + " becomes URI key "+
                (uri ? uri.spec : "ERROR"));

        if (Firebug.activateSameOrigin)
        {
            uri = this.convertToURIKey(currentURI, false);
            if (uri)
                Annotations.setPageAnnotation(uri, annotation);

            if (FBTrace.DBG_ACTIVATION || FBTrace.DBG_ANNOTATION)
                FBTrace.sysout("setPageAnnotation with activeSameOrigin currentURI " +
                    currentURI.spec + " becomes URI key " + (uri ? uri.spec : "ERROR"));
        }
    },

    removePageAnnotation: function(currentURI)
    {
        var uri = this.convertToURIKey(currentURI, Firebug.activateSameOrigin);
        if (uri)
            Annotations.removePageAnnotation(uri);

        if (Firebug.activateSameOrigin)
        {
            uri = this.convertToURIKey(currentURI, false);
            if (uri)
                Annotations.removePageAnnotation(uri);
        }

        if (FBTrace.DBG_ACTIVATION)
            FBTrace.sysout("Firebug.Activation.unwatchBrowser untagged "+uri.spec);
    },

    // Stops at the first fn(uri) that returns a true value.
    iterateAnnotations: function(fn)
    {
        var annotations = Annotations.getAnnotations(this.annotationName);
        for (var uri in annotations)
        {
            var rc = fn(uri, annotations[uri]);
            if (rc)
                return rc;
        }
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Options

    /**
     * After all options (and annotations) have been reset make sure to set
     * a new annotation for the current URL.
     * The annotation will ensure Firebug to be visible after refresh.
     */
    afterResetAllOptions: function()
    {
        // Only reset the annotation if Firebug is active for the current URL.
        if (!Firebug.currentContext)
            return;

        var currentURI = Firefox.getCurrentURI();
        var annotation = "firebugged.showFirebug";

        this.setPageAnnotation(currentURI.spec, annotation);
    }
});

// ********************************************************************************************* //
// Registration

Firebug.registerModule(Firebug.Activation);

return Firebug.Activation;

// ********************************************************************************************* //
});
<commit_msg>Update comment + use strict (related to issue 5632)<commit_after>/* See license.txt for terms of usage */

define([
    "firebug/lib/object",
    "firebug/firebug",
    "firebug/lib/locale",
    "firebug/lib/url",
    "firebug/chrome/tabWatcher",
    "firebug/chrome/annotations",
    "firebug/chrome/firefox",
],
function(Obj, Firebug, Locale, Url, TabWatcher, Annotations, Firefox) {

"use strict";

// ********************************************************************************************* //
// Constants

const Cc = Components.classes;
const Ci = Components.interfaces;

// ********************************************************************************************* //

/**
 * @module Implements Firebug activation logic.
 *
 * 1) Part of the logic is based on annotation service (see components/firebug-annotations.js)
 *    in order to remember whether Firebug is activated for given site or not.
 *    If there is "firebugged.showFirebug" annotation for a given site Firebug is activated.
 *    If there is "firebugged.closed" annotation for a given site Firebug is not activated.
 *
 * 2) Other part is based on extensions.firebug.allPagesActivation option. This option
 *    can be set to the following values:
 *    none: The option isn't used (default value)
 *    on:   Firebug is activated for all URLs.
 *    off:  Firebug is never activated.
 *
 *    This logic has higher priority over the URL annotations.
 *    If "off" options is selected, all existing URL annotations are removed.
 */
Firebug.Activation = Obj.extend(Firebug.Module,
{
    dispatchName: "activation",

    // called once
    initializeUI: function()
    {
        Firebug.Module.initializeUI.apply(this, arguments);

        TabWatcher.initializeUI();
        TabWatcher.addListener(this);
    },

    shutdown: function()
    {
        Firebug.Module.shutdown.apply(this, arguments);

        TabWatcher.removeListener(this);
    },

    // true if the Places annotation the URI "firebugged"
    shouldCreateContext: function(browser, url, userCommands)
    {
        if (FBTrace.DBG_ACTIVATION)
            FBTrace.sysout("shouldCreateContext allPagesActivation " +
                Firebug.allPagesActivation);

        if (Firebug.allPagesActivation == "on")
            return true;

        // This condition has been introduced to disable Firebug for about:blank
        // which caused issue 1483 to fail. However, there are cases when users
        // want to inspect even system pages (such as about:blank) and don't want
        // Firebug UI to be automatically hidden (see issue 5632).
        // Since issue 1483 doesn't fail anymore, the condition is removed.
        //if (Firebug.filterSystemURLs && Url.isSystemURL(url))
        //    return false;

        if (userCommands)
            return true;

        // document.open on a Firebugged page
        if (browser && browser.showFirebug && url.substr(0, 8) === "wyciwyg:")
            return true;

        try
        {
            var uri = this.convertToURIKey(url, Firebug.activateSameOrigin);
            if (!uri)
                return false;

            var hasAnnotation = Annotations.pageHasAnnotation(uri);

            if (FBTrace.DBG_ACTIVATION)
            {
                FBTrace.sysout("shouldCreateContext hasAnnotation " + hasAnnotation +
                    " for " + uri.spec + " in " +
                    (browser ? browser.contentWindow.location : "no browser") +
                    " using activateSameOrigin: " + Firebug.activateSameOrigin);
            }

            // Annotated, so return the value.
            if (hasAnnotation)
                return this.checkAnnotation(browser, uri);

            // Then Firebug.TabWatcher found a connection.
            if (browser.FirebugLink)
            {
                var dst = browser.FirebugLink.dst;
                var dstURI = this.convertToURIKey(dst.spec, Firebug.activateSameOrigin);

                if (FBTrace.DBG_ACTIVATION)
                {
                    FBTrace.sysout("shouldCreateContext found FirebugLink pointing to " +
                        dstURI.spec, browser.FirebugLink);
                }

                // And it matches us now.
                if (dstURI && dstURI.equals(uri))
                {
                    var srcURI = this.convertToURIKey(browser.FirebugLink.src.spec,
                        Firebug.activateSameOrigin);

                    if (srcURI)
                    {
                        if (FBTrace.DBG_ACTIVATION)
                        {
                            FBTrace.sysout("shouldCreateContext found FirebugLink pointing from " +
                                srcURI.spec, browser.FirebugLink);
                        }

                        // And it's on the same domain.
                        if (srcURI.schemeIs("file") || (dstURI.host == srcURI.host))
                        {
                            hasAnnotation = Annotations.pageHasAnnotation(srcURI);
                            // And the source page was annotated.
                            if (hasAnnotation)
                            {
                                var srcShow = this.checkAnnotation(browser, srcURI);
                                // And the source annotation said show it.
                                if (srcShow)
                                {
                                    // So we show dst as well.
                                    this.watchBrowser(browser);
                                }
                                return srcShow;
                            }
                        }
                    }
                }
                else
                {
                    if (FBTrace.DBG_ACTIVATION)
                        FBTrace.sysout("shouldCreateContext FirebugLink does not match " +
                            uri.spec, browser.FirebugLink);
                }
            }
            else if (browser.contentWindow.opener)
            {
                var openerContext = Firebug.TabWatcher.getContextByWindow(
                    browser.contentWindow.opener);

                if (FBTrace.DBG_ACTIVATION)
                    FBTrace.sysout("shouldCreateContext opener found, has " +
                        (openerContext ? "a " : "no ") + " context: " +
                        browser.contentWindow.opener.location);

                if (openerContext)
                {
                    // popup windows of Firebugged windows are Firebugged
                    return true;
                }
            }

            // don't createContext
            return false;
        }
        catch (exc)
        {
            if (FBTrace.DBG_ERRORS)
            {
                FBTrace.sysout("pageHasAnnotation FAILS for url: " + url + " which gave uri " +
                    (uri ? uri.spec : "null"), exc);
            }
        }
    },

    shouldShowContext: function(context)
    {
        return this.shouldCreateContext(context.browser, context.getWindowLocation().toString());
    },

    // Firebug is opened in the browser.
    watchBrowser: function(browser)
    {
        try
        {
            var annotation = "firebugged.showFirebug";
            this.setPageAnnotation(browser.currentURI.spec, annotation);
        }
        catch (e)
        {
            if (FBTrace.DBG_ERRORS)
                FBTrace.sysout("activation.watchBrowser; EXCEPTION " + e, e);
        }
    },

    // Firebug closes in the browser.
    unwatchBrowser: function(browser, userCommands)
    {
        var uri = browser.currentURI.spec;
        // Then mark to not open virally.
        if (userCommands)
        {
            this.setPageAnnotation(uri, "firebugged.closed");
        }
        else
        {
            // unmark this URI
            this.removePageAnnotation(uri);
        }
    },

    clearAnnotations: function()
    {
        Annotations.clear();
        Annotations.flush();

        Firebug.connection.dispatch("onClearAnnotations", []);
    },

    // Process the URL to canonicalize it. This needs not be reversible.
    convertToURIKey: function(url, sameOrigin)
    {
        // Remove the fragment. It shouldn't have any impact on the activation.
        url = url.replace(/#.*/, "");

        var uri = Url.makeURI(Url.normalizeURL(url));

        if (Firebug.filterSystemURLs && Url.isSystemURL(url))
            return uri;

        // avoid exceptions
        if (url == "about:blank")
            return uri;

        if (uri && sameOrigin)
        {
            try
            {
                // Returns the string before the path (such as "scheme://user:password@host:port").
                var prePath = uri.prePath;
                var shortURI = Url.makeURI(prePath);
                if (!shortURI)
                    return uri;

                // Annoying "about" URIs throw if .host is accessed
                if (shortURI.scheme === "about")
                    return shortURI;

                if (shortURI.scheme === "file")
                    return shortURI;

                return shortURI;

                // This makes a.co.uk -> co.uk, mail.cn.mozilla.com -> cn.mozilla.com and
                // blog.getfirebug.com -> getfirebug.com, which is wrong. See issue 2202.)
                /*
                var host = shortURI.host;
                if (host)
                {
                    // Slice the subdomain (if any) from the URL so that activateSameOrigin works
                    // for domains (including TLD domains). So we want:
                    // 1) www.google.com -> google.com
                    // 2) www.stuff.co.nz -> stuff.co.nz
                    // 3) getfirebug.com -> getfirebug.com
                    var levels = host.split('.');
                    if (levels.length > 2)
                        levels = levels.slice(1);
                    shortURI.host = levels.join('.');
                    return shortURI;
                }
                */
            }
            catch (exc)
            {
                if (FBTrace.DBG_ERRORS)
                    FBTrace.sysout("activation.convertToURIKey returning full URI, " +
                        "activateSameOrigin FAILS for shortURI " + shortURI + " because: " + exc,
                        exc);

                return uri;
            }
        }

        return uri;
    },

    checkAnnotation: function(browser, uri)
    {
        var annotation = Annotations.getPageAnnotation(uri);

        if (FBTrace.DBG_ACTIVATION)
            FBTrace.sysout("shouldCreateContext read back annotation " + annotation +
                " for uri " + uri.spec);

        // Then the user closed Firebug on this page last time.
        if ((Firebug.allPagesActivation != "on") && (annotation.indexOf("closed") > 0))
        {
            // annotated as 'closed', don't create
            return false;
        }
        else
        {
            // annotated, createContext
            return true;
        }
    },

    setPageAnnotation: function(currentURI, annotation)
    {
        var uri = this.convertToURIKey(currentURI, Firebug.activateSameOrigin);
        if (uri)
            Annotations.setPageAnnotation(uri, annotation);

        if (FBTrace.DBG_ACTIVATION || FBTrace.DBG_ANNOTATION)
            FBTrace.sysout("setPageAnnotation currentURI " + currentURI + " becomes URI key "+
                (uri ? uri.spec : "ERROR"));

        if (Firebug.activateSameOrigin)
        {
            uri = this.convertToURIKey(currentURI, false);
            if (uri)
                Annotations.setPageAnnotation(uri, annotation);

            if (FBTrace.DBG_ACTIVATION || FBTrace.DBG_ANNOTATION)
                FBTrace.sysout("setPageAnnotation with activeSameOrigin currentURI " +
                    currentURI.spec + " becomes URI key " + (uri ? uri.spec : "ERROR"));
        }
    },

    removePageAnnotation: function(currentURI)
    {
        var uri = this.convertToURIKey(currentURI, Firebug.activateSameOrigin);
        if (uri)
            Annotations.removePageAnnotation(uri);

        if (Firebug.activateSameOrigin)
        {
            uri = this.convertToURIKey(currentURI, false);
            if (uri)
                Annotations.removePageAnnotation(uri);
        }

        if (FBTrace.DBG_ACTIVATION)
            FBTrace.sysout("Firebug.Activation.unwatchBrowser untagged "+uri.spec);
    },

    // Stops at the first fn(uri) that returns a true value.
    iterateAnnotations: function(fn)
    {
        var annotations = Annotations.getAnnotations(this.annotationName);
        for (var uri in annotations)
        {
            var rc = fn(uri, annotations[uri]);
            if (rc)
                return rc;
        }
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Options

    /**
     * After all options (and annotations) have been reset make sure to set
     * a new annotation for the current URL.
     * The annotation will ensure Firebug to be visible after refresh.
     */
    afterResetAllOptions: function()
    {
        // Only reset the annotation if Firebug is active for the current URL.
        if (!Firebug.currentContext)
            return;

        var currentURI = Firefox.getCurrentURI();
        var annotation = "firebugged.showFirebug";

        this.setPageAnnotation(currentURI.spec, annotation);
    }
});

// ********************************************************************************************* //
// Registration

Firebug.registerModule(Firebug.Activation);

return Firebug.Activation;

// ********************************************************************************************* //
});
<|endoftext|>


<commit_before>const databaseName = 'choredb';

module.exports = {
  development: {
    client: 'postgresql',
    connection: `postgres://localhost:5432/${databaseName}`,
    migrations: {
      directory: __dirname + '/src/server/db/migrations'
    },
    seeds: {
      directory: __dirname + '/src/server/db/seeds'
    }
  },
  test: {
    client: 'postgresql',
    connection: `postgres://localhost:5432/${databaseName}_test`,
    migrations: {
      directory: __dirname + '/src/server/db/migrations'
    },
    seeds: {
      directory: __dirname + '/src/server/db/seeds'
    }
  },
  production: {
    client: 'postgresql',
    connection: process.env.DATABASE_URL,
    pool: 5,
    migrations: {
      directory: __dirname + '/src/server/db/migrations'
    }
  }
};
<commit_msg>Trying to get heroku db to work.<commit_after>const databaseName = 'choredb';

module.exports = {
  development: {
    client: 'postgresql',
    connection: `postgres://localhost:5432/${databaseName}`,
    migrations: {
      directory: __dirname + '/src/server/db/migrations'
    },
    seeds: {
      directory: __dirname + '/src/server/db/seeds'
    }
  },
  test: {
    client: 'postgresql',
    connection: `postgres://localhost:5432/${databaseName}_test`,
    migrations: {
      directory: __dirname + '/src/server/db/migrations'
    },
    seeds: {
      directory: __dirname + '/src/server/db/seeds'
    }
  },
  production: {
    client: 'postgresql',
    connection: process.env.DATABASE_URL,
    pool: {
      min: 0,
      max: 7
    },
    migrations: {
      directory: __dirname + '/src/server/db/migrations'
    }
  }
};
<|endoftext|>