<commit_before>import {Microservices} from '../configs/microservices';
import rp from 'request-promise';
const log = require('../configs/log').log;

export default {
    name: 'notifications',
    // At least one of the CRUD methods is Required
    read: (req, resource, params, config, callback) => {
        req.reqId = req.reqId ? req.reqId : -1;
        log.info({Id: req.reqId, Service: __filename.split('/').pop(), Resource: resource, Operation: 'read', Method: req.method});
        let args = params.params? params.params : params;
        let uid = args.uid;
        if (uid === undefined) {
            uid = 0;
        }

        if (resource === 'notifications.list'){

            let subscriptionsString = '';
            // let mockupSubscriptions = [
            //   {id:'2', type: 'user', name: 'Nikola T.', selected: true},
            //   {id:'1', type: 'user', name: 'Dejan P.', selected: true},
            //   {id:'9', type: 'deck', name: 'Collaborative authoring of presentations', selected: true},
            //   {id:'8', type: 'slide', name: 'Introduction', selected: true}
            // ];
            // mockupSubscriptions.push({id:String(uid), type: 'owner', name: 'My decks and slides', selected: true});
            let subscriptions = [{id:String(uid), type: 'owner', name: 'My decks and slides', selected: true}];

            rp.get({uri: Microservices.notification.uri + '/notifications/' + uid + '?metaonly=false'}).then((res) => {
                let notifications = JSON.parse(res).items;
                callback(null, {notifications: notifications, subscriptions: subscriptions});
            }).catch((err) => {
                console.log(err);
                callback(null, {notifications: [], subscriptions: subscriptions});
            });
        } else if (resource === 'notifications.countnew'){
            rp.get({uri: Microservices.notification.uri + '/notifications/' + uid + '?metaonly=true'}).then((res) => {
                let count = JSON.parse(res).count;
                callback(null, {count: count});
            }).catch((err) => {
                console.log(err);
                callback(null, {count: 0});
            });
        }
    },
    delete: (req, resource, params, config, callback) => {
        req.reqId = req.reqId ? req.reqId : -1;
        log.info({Id: req.reqId, Service: __filename.split('/').pop(), Resource: resource, Operation: 'delete', Method: req.method});
        let args = params.params? params.params : params;

        if (resource === 'notifications.item'){
            /*********connect to microservices*************/
            const id = args.notificationId;
            let options = {
                method: 'DELETE',
                uri: Microservices.notification.uri + '/notification/delete',
                body:JSON.stringify({
                    id: id
                })
            };
            rp(options).then((res) => {
                callback(null, {id: id});
            }).catch((err) => {
                console.log(err);
                callback(err, params);
            });
        } else if (resource === 'notifications.all'){
            /*********connect to microservices*************/
            let uid = String(args.uid);

            let options = {
                method: 'DELETE',
                uri: Microservices.notification.uri + '/notifications/delete',
                body:JSON.stringify({
                    subscribed_user_id: uid
                })
            };
            rp(options).then((res) => {
                callback(null, params);
            }).catch((err) => {
                console.log(err);
                callback(err, params);
            });
        }
    },
    update: (req, resource, params, body, config, callback) => {
      req.reqId = req.reqId ? req.reqId : -1;
      log.info({Id: req.reqId, Service: __filename.split('/').pop(), Resource: resource, Operation: 'read', Method: req.method});
      let args = params.params? params.params : params;
      let uid = args.uid;
      if (uid === undefined) {
          uid = 0;
      }

      if (resource === 'notifications.read'){
         let id = args.id;
         rp.put({
             uri: Microservices.notification.uri + '/notification/mark/' + id,
             body: JSON.stringify({
                 read: true
             }),
             resolveWithFullResponse: true
         }).then((res) => {
             callback(null, {id: id});
         }).catch((err) => {
             console.log(err);
             callback(null, {});
         });
      } else if (resource === 'notifications.readall'){
         rp.put({
             uri: Microservices.notification.uri + '/notification/markall/' + id,
             body: JSON.stringify({
                 read: true
             }),
             resolveWithFullResponse: true
         }).then((res) => {
             callback(null, {args: args});
         }).catch((err) => {
             console.log(err);
             callback(null, {});
         });
      }
    }

    // other methods
    // create: (req, resource, params, body, config, callback) => {},
    //

};
<commit_msg>SWIK-1684 corrected some  indentation problems<commit_after>import {Microservices} from '../configs/microservices';
import rp from 'request-promise';
const log = require('../configs/log').log;

export default {
    name: 'notifications',
    // At least one of the CRUD methods is Required
    read: (req, resource, params, config, callback) => {
        req.reqId = req.reqId ? req.reqId : -1;
        log.info({Id: req.reqId, Service: __filename.split('/').pop(), Resource: resource, Operation: 'read', Method: req.method});
        let args = params.params? params.params : params;
        let uid = args.uid;
        if (uid === undefined) {
            uid = 0;
        }

        if (resource === 'notifications.list'){

            let subscriptionsString = '';
            // let mockupSubscriptions = [
            //   {id:'2', type: 'user', name: 'Nikola T.', selected: true},
            //   {id:'1', type: 'user', name: 'Dejan P.', selected: true},
            //   {id:'9', type: 'deck', name: 'Collaborative authoring of presentations', selected: true},
            //   {id:'8', type: 'slide', name: 'Introduction', selected: true}
            // ];
            // mockupSubscriptions.push({id:String(uid), type: 'owner', name: 'My decks and slides', selected: true});
            let subscriptions = [{id:String(uid), type: 'owner', name: 'My decks and slides', selected: true}];

            rp.get({uri: Microservices.notification.uri + '/notifications/' + uid + '?metaonly=false'}).then((res) => {
                let notifications = JSON.parse(res).items;
                callback(null, {notifications: notifications, subscriptions: subscriptions});
            }).catch((err) => {
                console.log(err);
                callback(null, {notifications: [], subscriptions: subscriptions});
            });
        } else if (resource === 'notifications.countnew'){
            rp.get({uri: Microservices.notification.uri + '/notifications/' + uid + '?metaonly=true'}).then((res) => {
                let count = JSON.parse(res).count;
                callback(null, {count: count});
            }).catch((err) => {
                console.log(err);
                callback(null, {count: 0});
            });
        }
    },
    delete: (req, resource, params, config, callback) => {
        req.reqId = req.reqId ? req.reqId : -1;
        log.info({Id: req.reqId, Service: __filename.split('/').pop(), Resource: resource, Operation: 'delete', Method: req.method});
        let args = params.params? params.params : params;

        if (resource === 'notifications.item'){
            /*********connect to microservices*************/
            const id = args.notificationId;
            let options = {
                method: 'DELETE',
                uri: Microservices.notification.uri + '/notification/delete',
                body:JSON.stringify({
                    id: id
                })
            };
            rp(options).then((res) => {
                callback(null, {id: id});
            }).catch((err) => {
                console.log(err);
                callback(err, params);
            });
        } else if (resource === 'notifications.all'){
            /*********connect to microservices*************/
            let uid = String(args.uid);

            let options = {
                method: 'DELETE',
                uri: Microservices.notification.uri + '/notifications/delete',
                body:JSON.stringify({
                    subscribed_user_id: uid
                })
            };
            rp(options).then((res) => {
                callback(null, params);
            }).catch((err) => {
                console.log(err);
                callback(err, params);
            });
        }
    },
    update: (req, resource, params, body, config, callback) => {
        req.reqId = req.reqId ? req.reqId : -1;
        log.info({Id: req.reqId, Service: __filename.split('/').pop(), Resource: resource, Operation: 'read', Method: req.method});
        let args = params.params? params.params : params;
        let uid = args.uid;
        if (uid === undefined) {
            uid = 0;
        }

        if (resource === 'notifications.read'){
            let id = args.id;
            rp.put({
                uri: Microservices.notification.uri + '/notification/mark/' + id,
                body: JSON.stringify({
                    read: true
                }),
                resolveWithFullResponse: true
            }).then((res) => {
                callback(null, {id: id});
            }).catch((err) => {
                console.log(err);
                callback(null, {});
            });
        } else if (resource === 'notifications.readall'){
            rp.put({
                uri: Microservices.notification.uri + '/notification/markall/' + id,
                body: JSON.stringify({
                    read: true
                }),
                resolveWithFullResponse: true
            }).then((res) => {
                callback(null, {args: args});
            }).catch((err) => {
                console.log(err);
                callback(null, {});
            });
        }
    }

    // other methods
    // create: (req, resource, params, body, config, callback) => {},
    //

};
<|endoftext|>


<commit_before>/*jslint continue: true, devel: true, evil: true, indent: 2, nomen: true, plusplus: true, regexp: true, rhino: true, sloppy: true, sub: true, unparam: true, vars: true, white: true */
/*global _, HostAdapter, hostAdapter, ejs */

var ARTIST_KEYS = ['org.dbpedia.ontology.Band', 'org.dbpedia.ontology.MusicalArtist', 'org.dbpedia.ontology.Artist'];

function findBestResult(keys, recognitionResults) {
  var currentBestResult = null;

  console.log('entering findBestResult');

  _(keys).each(function (key) {
    console.log('findBestResult: checking key ' + key);

    var rrList = recognitionResults[key];
    if (!rrList) {
      return;
    }

    _(rrList).each(function (rr) {
       if (!currentBestResult || (rr.recognitionLevel > currentBestResult.recognitionLevel)) {
          currentBestResult = rr;
       }
    });
  });

  console.log('Best result = ' + currentBestResult.wikipediaArticleName);

  return currentBestResult;
}

function articleNameToName(articleName, recognitionResults) {
  return _(recognitionResults['com.solveforall.recognition.WikipediaArticle']).find(function (rr) {
    return (rr.article === articleName);
  }).title;
}

function lowerCaseWords(s) {
  return s.split(/\s+/).map(function (w) {
    return w.toLowerCase();
  });
}

function makeResponseHandler(recognitionLevel, showIfNotFound) {
  return function (responseText, response) {
    console.log('Got response ' + responseText);

    if (response.statusCode !== 200) {
      console.error('Got bad status code ' + response.statusCode);
      return null;
    }

    var artistObj = JSON.parse(responseText);

    if ((artistObj.albums.length === 0) && (showIfNotFound !== 'true')) {
      console.log('No albums for artist found, not outputting result');
      return null;
    }

    var contentTemplateXml = <heredoc>
      <![CDATA[

          <% var underscoredArtist = artist.replace(' ', '_'); %>
          <% if (albums.length > 0) { %>

              Songs by <%= artist %>:

            <% _(albums).each(function(album) { %>

                  <%= album.album %>
                  <% if (album.year) { %>
                    (<%= album.year %>)
                  <% } %>
                  <% if (album.amazonLink) { %>

                    <a href="<%= album.amazonLink %>">

                  <% } %>

                  <% _(album.songs).each(function(song) { %>

                    <a href="http://lyrics.wikia.com/<%= underscoredArtist %>:<%= song.replace(' ', '_') %>">
                      <%= song %>

                  <% }); %>

            <% }); %>

          <% } else { %>

            Sorry, I can't find any songs by <%= artist %>.

          <% } %>

      ]]>
    </heredoc>;

    var contentTemplate = contentTemplateXml.toString();

    return [{
      content: ejs.render(contentTemplate, artistObj),
      contentType: 'text/html',
      serverSideSanitized: true,
      label: 'Songs',
      iconUrl: 'http://lyrics.wikia.com/favicon.ico',
      summaryHtml: 'Songs by ' + _(artistObj.artist).escapeHTML() + '',
      relevance: recognitionLevel
    }];
  };
}

function generateResults(recognitionResults, q, context) {
  'use strict';

  if (context.isSuggestionQuery) {
    return [];
  }

  var artistResult = findBestResult(ARTIST_KEYS, recognitionResults);

  var artist = null;
  var recognitionLevel = 0.0;
  if (artistResult) {
    artist = articleNameToName(artistResult.wikipediaArticleName, recognitionResults);
    recognitionLevel = artistResult.recognitionLevel;
  } else {
    artist = q;
  }

  var url = 'http://lyrics.wikia.com/api.php';

  var request = hostAdapter.makeWebRequest(url, {
    data: {
      artist: artist,
      fmt: 'realjson'
    }
  });

  var settings = context.settings;
  request.send('makeResponseHandler(' + recognitionLevel.toFixed(4) + ',' +
               _(settings.showIfNotFound || 'false').toBoolean() + ')');

  return HostAdapter.SUSPEND;
}
<commit_msg>Reduce relevance of Songs for an Artist<commit_after>/*jslint continue: true, devel: true, evil: true, indent: 2, nomen: true, plusplus: true, regexp: true, rhino: true, sloppy: true, sub: true, unparam: true, vars: true, white: true */
/*global _, HostAdapter, hostAdapter, ejs */

var ARTIST_KEYS = ['org.dbpedia.ontology.Band', 'org.dbpedia.ontology.MusicalArtist', 'org.dbpedia.ontology.Artist'];

function findBestResult(keys, recognitionResults) {
  var currentBestResult = null;

  console.log('entering findBestResult');

  _(keys).each(function (key) {
    console.log('findBestResult: checking key ' + key);

    var rrList = recognitionResults[key];
    if (!rrList) {
      return;
    }

    _(rrList).each(function (rr) {
       if (!currentBestResult || (rr.recognitionLevel > currentBestResult.recognitionLevel)) {
          currentBestResult = rr;
       }
    });
  });

  console.log('Best result = ' + currentBestResult.wikipediaArticleName);

  return currentBestResult;
}

function articleNameToName(articleName, recognitionResults) {
  return _(recognitionResults['com.solveforall.recognition.WikipediaArticle']).find(function (rr) {
    return (rr.article === articleName);
  }).title;
}

function lowerCaseWords(s) {
  return s.split(/\s+/).map(function (w) {
    return w.toLowerCase();
  });
}

function makeResponseHandler(recognitionLevel, showIfNotFound) {
  return function (responseText, response) {
    console.log('Got response ' + responseText);

    if (response.statusCode !== 200) {
      console.error('Got bad status code ' + response.statusCode);
      return null;
    }

    var artistObj = JSON.parse(responseText);

    if ((artistObj.albums.length === 0) && (showIfNotFound !== 'true')) {
      console.log('No albums for artist found, not outputting result');
      return null;
    }

    var contentTemplateXml = <heredoc>
      <![CDATA[

          <% var underscoredArtist = artist.replace(' ', '_'); %>
          <% if (albums.length > 0) { %>

              Songs by <%= artist %>:

            <% _(albums).each(function(album) { %>

                  <%= album.album %>
                  <% if (album.year) { %>
                    (<%= album.year %>)
                  <% } %>
                  <% if (album.amazonLink) { %>

                    <a href="<%= album.amazonLink %>">

                  <% } %>

                  <% _(album.songs).each(function(song) { %>

                    <a href="http://lyrics.wikia.com/<%= underscoredArtist %>:<%= song.replace(' ', '_') %>">
                      <%= song %>

                  <% }); %>

            <% }); %>

          <% } else { %>

            Sorry, I can't find any songs by <%= artist %>.

          <% } %>

      ]]>
    </heredoc>;

    var contentTemplate = contentTemplateXml.toString();

    return [{
      content: ejs.render(contentTemplate, artistObj),
      contentType: 'text/html',
      serverSideSanitized: true,
      label: 'Songs',
      iconUrl: 'http://lyrics.wikia.com/favicon.ico',
      summaryHtml: 'Songs by ' + _(artistObj.artist).escapeHTML() + '',
      relevance: recognitionLevel
    }];
  };
}

function generateResults(recognitionResults, q, context) {
  'use strict';

  if (context.isSuggestionQuery) {
    return [];
  }

  var artistResult = findBestResult(ARTIST_KEYS, recognitionResults);

  var artist = null;
  var recognitionLevel = 0.0;
  if (artistResult) {
    artist = articleNameToName(artistResult.wikipediaArticleName, recognitionResults);
    recognitionLevel = artistResult.recognitionLevel * 0.5;
  } else {
    artist = q;
  }

  var url = 'http://lyrics.wikia.com/api.php';

  var request = hostAdapter.makeWebRequest(url, {
    data: {
      artist: artist,
      fmt: 'realjson'
    }
  });

  var settings = context.settings;
  request.send('makeResponseHandler(' + recognitionLevel.toFixed(4) + ',' +
               _(settings.showIfNotFound || 'false').toBoolean() + ')');

  return HostAdapter.SUSPEND;
}
<|endoftext|>


<commit_before>/*jslint continue: true, devel: true, evil: true, indent: 2, nomen: true, plusplus: true, regexp: true, rhino: true, sloppy: true, sub: true, unparam: true, vars: true, white: true */
/*global _, HostAdapter, hostAdapter */
function generateResults(recognitionResults, q, context) {
  'use strict';

  // In case of explicit activation
  var stockSymbols = q;
  var relevance = 0;
  var comparisonIndicator = '';
  var rrs = recognitionResults['com.solveforall.recognition.finance.stocks.StockSymbol'];

  if (rrs) {
    var stockSymbolArray = _(rrs).map(function (rr) {
      return rr.symbol;
    });

    if (stockSymbolArray.length > 0) {
      relevance = _(rrs).chain().map(function(rr) {
        return rr.recognitionLevel;
      }).max().value();

      console.log('set relevance = ' + relevance);
    }

    if (stockSymbolArray.length > 1) {
      comparisonIndicator = ',,comparison';
    }

    stockSymbols = stockSymbolArray.join(',');
  }

  if (!stockSymbols || (stockSymbols.length === 0)) {
    return null;
  }

  var settings = context.settings;
  var chartInterval = settings.chartInterval || '5d';
  var newsCount = settings.newsCount || '5';

  var chartFragment = ';chart=' + chartInterval;

  if (chartInterval === 'None') {
    chartFragment = '';
  }

  // TODO: validate stockSymbols, chartInterval, newsCount

  var encodedStockSymbol = encodeURIComponent(stockSymbols);

  return [{
    label: 'Yahoo! Finance',
    iconUrl: 'https://finance.yahoo.com/favicon.ico',
    uri: 'http://api.finance.yahoo.com/instrument/1.0/' + encodedStockSymbol +
      '/badge' + chartFragment + comparisonIndicator + ';news=' +
      newsCount + ';quote/HTML/f.white?AppID=f0L2..pOymKhmdoad.D7vJulKkc5&sig=Ypb18cXVe63kvDF9Uz5GH5RcLBU-&t=1393739815394',
    embeddable: true,
    shouldEmbed: true,
    relevance: relevance,
    minHeight: 614,
    preferredHeight: 614,
    preferredWidth: 338
  }];
}
<commit_msg>Reduce height of Yahoo! Finance Badge<commit_after>/*jslint continue: true, devel: true, evil: true, indent: 2, nomen: true, plusplus: true, regexp: true, rhino: true, sloppy: true, sub: true, unparam: true, vars: true, white: true */
/*global _, HostAdapter, hostAdapter */
function generateResults(recognitionResults, q, context) {
  'use strict';

  // In case of explicit activation
  var stockSymbols = q;
  var relevance = 0;
  var comparisonIndicator = '';
  var rrs = recognitionResults['com.solveforall.recognition.finance.stocks.StockSymbol'];

  if (rrs) {
    var stockSymbolArray = _(rrs).map(function (rr) {
      return rr.symbol;
    });

    if (stockSymbolArray.length > 0) {
      relevance = _(rrs).chain().map(function(rr) {
        return rr.recognitionLevel;
      }).max().value();

      console.log('set relevance = ' + relevance);
    }

    if (stockSymbolArray.length > 1) {
      comparisonIndicator = ',,comparison';
    }

    stockSymbols = stockSymbolArray.join(',');
  }

  if (!stockSymbols || (stockSymbols.length === 0)) {
    return null;
  }

  var settings = context.settings;
  var chartInterval = settings.chartInterval || '5d';
  var newsCount = settings.newsCount || '5';

  var chartFragment = ';chart=' + chartInterval;

  if (chartInterval === 'None') {
    chartFragment = '';
  }

  // TODO: validate stockSymbols, chartInterval, newsCount

  var encodedStockSymbol = encodeURIComponent(stockSymbols);

  return [{
    label: 'Yahoo! Finance',
    iconUrl: 'https://finance.yahoo.com/favicon.ico',
    uri: 'http://api.finance.yahoo.com/instrument/1.0/' + encodedStockSymbol +
      '/badge' + chartFragment + comparisonIndicator + ';news=' +
      newsCount + ';quote/HTML/f.white?AppID=f0L2..pOymKhmdoad.D7vJulKkc5&sig=Ypb18cXVe63kvDF9Uz5GH5RcLBU-&t=1393739815394',
    embeddable: true,
    shouldEmbed: true,
    relevance: relevance,
    minHeight: 294,
    preferredHeight: 294,
    preferredWidth: 320
  }];
}
<|endoftext|>


<commit_before>var deBody = [MOVE, WORK, MOVE, WORK, CARRY];
var exBody = [MOVE, WORK, MOVE, WORK, MOVE, WORK, MOVE, CARRY];
var levelUp = function levelUp(room) {
//    let numExtensions = room.find(FIND_MY_STRUCTURES, {filter: (str) => str.structureType == STRUCTURE_EXTENSION}).length;
    let numContainers = room.find(FIND_MY_STRUCTURES, {filter: (str) => str.structureType == STRUCTURE_CONTAINER}).length;
    if (room.energyAvailable >= 500 && numContainers >= 3 && room.controller.level > 2) {
        return 'mature';
    } else {
        return 'boom';
    }
};
module.exports = {
    tasks: [],
    creeps: {
        harvester: {
            desired: 2,
            body: exBody
        },
        containerHarvester: {
            desired: 0,
            body: exBody
        },
        upgrader: {
            desired: 1,
            body: deBody
        },
        defender: {
            desired: 0,
            body: [MOVE, ATTACK, MOVE, ATTACK]
        },
        sherpa: {
            desired: 0,
            body: [MOVE, CARRY, MOVE, CARRY]
        },
        builder: {
            desired: 2,
            body: deBody
        }
    },
    // desiredHarvesters: 2,
    // desiredUpgraders: 1,
    // desiredBuilders: 0,
    // desiredSherpas: 1,
    // desiredDefenders: 0,
    // harvester: exBody,
    // upgrader: deBody,
    // defender: [MOVE, ATTACK, MOVE, ATTACK],
    // builder:deBody,
    // sherpa: [MOVE, CARRY, MOVE, CARRY],
    hitsWall: 2000,
    hitsRampart: 2000,
    name:'boom',
    levelUp: levelUp
};<commit_msg>split boom stage into two stages<commit_after>var deBody = [MOVE, WORK, MOVE, WORK, CARRY];
var exBody = [MOVE, WORK, MOVE, WORK, MOVE, WORK, MOVE, CARRY];
var levelUp = function levelUp(room) {
//    let numExtensions = room.find(FIND_MY_STRUCTURES, {filter: (str) => str.structureType == STRUCTURE_EXTENSION}).length;
    let numContainers = room.find(FIND_STRUCTURES, {filter: (str) => str.structureType == STRUCTURE_CONTAINER}).length;
    if (room.energyAvailable >= 500 && numContainers >= 3) {
        if (room.controller.level > 2) {
            return 'mature';
        } else {
            return 'rush';
        }
    } else if (false ) {
//
    } else {
        return 'boom';
    }
};
module.exports = {
    tasks: [],
    creeps: {
        harvester: {
            desired: 2,
            body: exBody
        },
        containerHarvester: {
            desired: 0,
            body: exBody
        },
        upgrader: {
            desired: 1,
            body: deBody
        },
        defender: {
            desired: 0,
            body: [MOVE, ATTACK, MOVE, ATTACK]
        },
        sherpa: {
            desired: 0,
            body: [MOVE, CARRY, MOVE, CARRY]
        },
        builder: {
            desired: 2,
            body: deBody
        }
    },
    // desiredHarvesters: 2,
    // desiredUpgraders: 1,
    // desiredBuilders: 0,
    // desiredSherpas: 1,
    // desiredDefenders: 0,
    // harvester: exBody,
    // upgrader: deBody,
    // defender: [MOVE, ATTACK, MOVE, ATTACK],
    // builder:deBody,
    // sherpa: [MOVE, CARRY, MOVE, CARRY],
    hitsWall: 2000,
    hitsRampart: 2000,
    name:'boom',
    levelUp: levelUp
};<|endoftext|>


<commit_before>#!/usr/bin/env node
var spawn = require('child_process').spawn;

var workingDir = process.env.WORKING_DIR || process.env.PACKAGE_DIR || './';
var args = ['test-packages', '--once', '--driver-package', 'test-in-console', '-p', 10015];

if (typeof process.env.METEOR_RELEASE !== 'undefined' &&
    process.env.METEOR_RELEASE !== '') {
    args.push('--release');
    args.push(process.env.METEOR_RELEASE);
}

if (typeof process.env.PACKAGES === 'undefined') {
  args.push('./');
}
else if (process.env.PACKAGES !== '') {
  args = args.concat(process.env.PACKAGES.split(';'));
}

var meteor = spawn((process.env.TEST_COMMAND || 'meteor'), args, {cwd: workingDir});
meteor.stdout.pipe(process.stdout);
meteor.stderr.pipe(process.stderr);
meteor.on('close', function (code) {
  console.log('meteor exited with code ' + code);
  process.exit(code);
});

meteor.stdout.on('data', function startTesting(data) {
  data = data.toString();
  if(data.match(/10015|test-in-console listening/)) {
    console.log('starting testing...');
    meteor.stdout.removeListener('data', startTesting);
    runTestSuite();
  }
});

function runTestSuite() {
  process.env.URL = "http://localhost:10015/";
  var phantomjs = spawn('phantomjs', ['./phantom_runner.js']);
  phantomjs.stdout.pipe(process.stdout);
  phantomjs.stderr.pipe(process.stderr);

  phantomjs.on('close', function(code) {
    meteor.kill('SIGQUIT');
    process.exit(code);
  });
}
<commit_msg>fixed for "non-package" tests<commit_after>#!/usr/bin/env node
var spawn = require('child_process').spawn;

var workingDir = process.env.WORKING_DIR || process.env.PACKAGE_DIR || './';
var args = ['test-packages', '--once', '--driver-package', 'test-in-console', '-p', 10015];

if (typeof process.env.METEOR_RELEASE !== 'undefined' &&
    process.env.METEOR_RELEASE !== '') {
    args.push('--release');
    args.push(process.env.METEOR_RELEASE);
}

var meteor = spawn((process.env.TEST_COMMAND || 'meteor'), args, {cwd: workingDir});
meteor.stdout.pipe(process.stdout);
meteor.stderr.pipe(process.stderr);
meteor.on('close', function (code) {
  console.log('meteor exited with code ' + code);
  process.exit(code);
});

meteor.stdout.on('data', function startTesting(data) {
  data = data.toString();
  if(data.match(/10015|test-in-console listening/)) {
    console.log('starting testing...');
    meteor.stdout.removeListener('data', startTesting);
    runTestSuite();
  }
});

function runTestSuite() {
  process.env.URL = "http://localhost:10015/";
  var phantomjs = spawn('phantomjs', ['./phantom_runner.js']);
  phantomjs.stdout.pipe(process.stdout);
  phantomjs.stderr.pipe(process.stderr);

  phantomjs.on('close', function(code) {
    meteor.kill('SIGQUIT');
    process.exit(code);
  });
}
<|endoftext|>


<commit_before>function pokemonLabel(name, disappear_time, id, disappear_time, latitude, longitude) {
    disappear_date = new Date(disappear_time)

    var pad = function pad(number) {
      return number <= 99 ? ("0" + number).slice(-2) : number;
    };

    var str = '\

\
            ' + name + '\
             - \
            \
                #' + id + '\
            \

\

\
            Disappears at ' + pad(disappear_date.getHours()) + ':' + pad(disappear_date.getMinutes()) + ':' + pad(disappear_date.getSeconds()) + '\
            (00m00s)
\

\
            Get Directions\

';

    return str;
}

var map;
var marker;
function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: center_lat, lng: center_lng},
        zoom: 16
    });
    marker = new google.maps.Marker({
        position: {lat: center_lat, lng: center_lng},
        map: map,
        animation: google.maps.Animation.DROP
    });

    $.getJSON("/pokemons", function(result){
        $.each(result, function(i, item){

            var marker = new google.maps.Marker({
                position: {lat: item.latitude, lng: item.longitude},
                map: map,
                icon: 'static/icons/'+item.pokemon_id+'.png'
            });

            marker.infoWindow = new google.maps.InfoWindow({
                content: pokemonLabel(item.pokemon_name, item.disappear_time, item.pokemon_id, item.disappear_time, item.latitude, item.longitude)
            });

            marker.addListener('click', function() {
                marker.infoWindow.open(map, marker);
            });

            console.log(item.latitude);
        });
    });
}
<commit_msg>Display markers on mouse hover (#544)<commit_after>function pokemonLabel(name, disappear_time, id, disappear_time, latitude, longitude) {
    disappear_date = new Date(disappear_time)

    var pad = function pad(number) {
      return number <= 99 ? ("0" + number).slice(-2) : number;
    };

    var str = '\

\
            ' + name + '\
             - \
            \
                #' + id + '\
            \

\

\
            Disappears at ' + pad(disappear_date.getHours()) + ':' + pad(disappear_date.getMinutes()) + ':' + pad(disappear_date.getSeconds()) + '\
            (00m00s)
\

\
            Get Directions\

';

    return str;
}

var map;
var marker;
function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: center_lat, lng: center_lng},
        zoom: 16
    });
    marker = new google.maps.Marker({
        position: {lat: center_lat, lng: center_lng},
        map: map,
        animation: google.maps.Animation.DROP
    });

    $.getJSON("/pokemons", function(result){
        $.each(result, function(i, item){

            var marker = new google.maps.Marker({
                position: {lat: item.latitude, lng: item.longitude},
                map: map,
                icon: 'static/icons/'+item.pokemon_id+'.png'
            });

            marker.infoWindow = new google.maps.InfoWindow({
                content: pokemonLabel(item.pokemon_name, item.disappear_time, item.pokemon_id, item.disappear_time, item.latitude, item.longitude)
            });

            google.maps.event.addListener(marker.infoWindow, 'closeclick', function(){
                delete marker["persist"];
                marker.infoWindow.close();
            });

            marker.addListener('click', function() {
                marker["persist"] = true;
                marker.infoWindow.open(map, marker);
            });

            marker.addListener('mouseover', function() {
                marker.infoWindow.open(map, marker);
            });

            marker.addListener('mouseout', function() {
                if (!marker["persist"]) {
                    marker.infoWindow.close();
                }
            });

            console.log(item.latitude);
        });
    });
}
<|endoftext|>


<commit_before>// Copyright: Hiroshi Ichikawa <http://gimite.net/en/>
// Lincense: New BSD Lincense
// Reference: http://dev.w3.org/html5/websockets/
// Reference: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol

if (!window.WebSocket) {

  if (!window.console) console = {log: function(){ }, error: function(){ }};

  WebSocket = function(url, protocol, proxyHost, proxyPort, headers) {
    var self = this;
    self.readyState = WebSocket.CONNECTING;
    self.bufferedAmount = 0;
    WebSocket.__addTask(function() {
      self.__flash =
        WebSocket.__flash.create(url, protocol, proxyHost || null, proxyPort || 0, headers || null);

      self.__flash.addEventListener("open", function(fe) {
        try {
          if (self.onopen) self.onopen();
        } catch (e) {
          console.error(e.toString());
        }
      });

      self.__flash.addEventListener("close", function(fe) {
        try {
          if (self.onopen) self.onclose();
        } catch (e) {
          console.error(e.toString());
        }
      });

      self.__flash.addEventListener("message", function(fe) {
        var data = decodeURIComponent(fe.getData());
        try {
          if (self.onmessage) {
            var e;
            if (window.MessageEvent) {
              e = document.createEvent("MessageEvent");
              e.initMessageEvent("message", false, false, data, null, null, window);
            } else { // IE
              e = {data: data};
            }
            self.onmessage(e);
          }
        } catch (e) {
          console.error(e.toString());
        }
      });

      self.__flash.addEventListener("stateChange", function(fe) {
        try {
          self.readyState = fe.getReadyState();
          self.bufferedAmount = fe.getBufferedAmount();
        } catch (e) {
          console.error(e.toString());
        }
      });

      //console.log("[WebSocket] Flash object is ready");
    });
  }

  WebSocket.prototype.send = function(data) {
    if (!this.__flash || this.readyState == WebSocket.CONNECTING) {
      throw "INVALID_STATE_ERR: Web Socket connection has not been established";
    }
    var result = this.__flash.send(data);
    if (result < 0) { // success
      return true;
    } else {
      this.bufferedAmount = result;
      return false;
    }
  };

  WebSocket.prototype.close = function() {
    if (!this.__flash) return;
    if (this.readyState != WebSocket.OPEN) return;
    this.__flash.close();
    // Sets/calls them manually here because Flash WebSocketConnection.close cannot fire events
    // which causes weird error:
    // > You are trying to call recursively into the Flash Player which is not allowed.
    this.readyState = WebSocket.CLOSED;
    if (this.onclose) this.onclose();
  };

  /**
   * Implementation of {@link DOM 2 EventTarget Interface}
   *
   * @param {string} type
   * @param {function} listener
   * @param {boolean} useCapture !NB Not implemented yet
   * @return void
   */
  WebSocket.prototype.addEventListener = function(type, listener, useCapture) {
    if (!('__events' in this)) {
      this.__events = {};
    }
    if (!(type in this.__events)) {
      this.__events[type] = [];
      if ('function' == typeof this['on' + type]) {
        this.__events[type].defaultHandler = this['on' + type];
        this['on' + type] = WebSocket_FireEvent(this, type);
      }
    }
    this.__events[type].push(listener);
  };

  /**
   * Implementation of {@link DOM 2 EventTarget Interface}
   *
   * @param {string} type
   * @param {function} listener
   * @param {boolean} useCapture NB! Not implemented yet
   * @return void
   */
  WebSocket.prototype.removeEventListener = function(type, listener, useCapture) {
    if (!('__events' in this)) {
      this.__events = {};
    }
    if (!(type in this.__events)) return;
    for (var i = this.__events.length; i > -1; --i) {
      if (listener === this.__events[type][i]) {
        this.__events[type].splice(i, 1);
        break;
      }
    }
  };

  /**
   * Implementation of {@link DOM 2 EventTarget Interface}
   *
   * @param {WebSocketEvent} event
   * @return void
   */
  WebSocket.prototype.dispatchEvent = function(event) {
    if (!('__events' in this)) throw 'UNSPECIFIED_EVENT_TYPE_ERR';
    if (!(event.type in this.__events)) throw 'UNSPECIFIED_EVENT_TYPE_ERR';

    for (var i = 0, l = this.__events[event.type].length; i < l; ++ i) {
      this.__events[event.type][i](event);
      if (event.cancelBubble) break;
    }

    if (false !== event.returnValue &&
        'function' == typeof this.__events[event.type].defaultHandler)
    {
      this.__events[event.type].defaultHandler(event);
    }
  };

  /**
   *
   * @param {object} object
   * @param {string} type
   */
  function WebSocket_FireEvent(object, type) {
    return function(data) {
      var event = new WebSocketEvent();
      event.initEvent(type, true, true);
      event.target = event.currentTarget = object;
      for (var key in data) {
        event[key] = data[key];
      }
      object.dispatchEvent(event, arguments);
    };
  }

  /**
   * Basic implementation of {@link DOM 2 EventInterface}
   *
   * @class
   * @constructor
   */
  function WebSocketEvent(){}

  /**
   *
   * @type boolean
   */
  WebSocketEvent.prototype.cancelable = true;

  /**
   *
   * @type boolean
   */
  WebSocketEvent.prototype.cancelBubble = false;

  /**
   *
   * @return void
   */
  WebSocketEvent.prototype.preventDefault = function() {
    if (this.cancelable) {
      this.returnValue = false;
    }
  };

  /**
   *
   * @return void
   */
  WebSocketEvent.prototype.stopPropagation = function() {
    this.cancelBubble = true;
  };

  /**
   *
   * @param {string} eventTypeArg
   * @param {boolean} canBubbleArg
   * @param {boolean} cancelableArg
   * @return void
   */
  WebSocketEvent.prototype.initEvent = function(eventTypeArg, canBubbleArg, cancelableArg) {
    this.type = eventTypeArg;
    this.cancelable = cancelableArg;
    this.timeStamp = new Date();
  };

  WebSocket.CONNECTING = 0;
  WebSocket.OPEN = 1;
  WebSocket.CLOSED = 2;

  WebSocket.__tasks = [];

  WebSocket.__initialize = function() {
    if (!WebSocket.__swfLocation) {
      console.error("[WebSocket] set WebSocket.__swfLocation to location of WebSocketMain.swf");
      return;
    }
    var container = document.createElement("div");
    container.id = "webSocketContainer";
    // Puts the Flash out of the window. Note that we cannot use display: none or visibility: hidden
    // here because it prevents Flash from loading at least in IE.
    container.style.position = "absolute";
    container.style.left = "-100px";
    container.style.top = "-100px";
    var holder = document.createElement("div");
    holder.id = "webSocketFlash";
    container.appendChild(holder);
    document.body.appendChild(container);
    swfobject.embedSWF(
      WebSocket.__swfLocation, "webSocketFlash", "10", "10", "9.0.0",
      null, {bridgeName: "webSocket"}, null, null,
      function(e) {
        if (!e.success) console.error("[WebSocket] swfobject.embedSWF failed");
      }
    );
    FABridge.addInitializationCallback("webSocket", function() {
      try {
        //console.log("[WebSocket] FABridge initializad");
        WebSocket.__flash = FABridge.webSocket.root();
        WebSocket.__flash.setCallerUrl(location.href);
        for (var i = 0; i < WebSocket.__tasks.length; ++i) {
          WebSocket.__tasks[i]();
        }
        WebSocket.__tasks = [];
      } catch (e) {
        console.error("[WebSocket] " + e.toString());
      }
    });
  };

  WebSocket.__addTask = function(task) {
    if (WebSocket.__flash) {
      task();
    } else {
      WebSocket.__tasks.push(task);
    }
  }

  // called from Flash
  function webSocketLog(message) {
    console.log(decodeURIComponent(message));
  }

  // called from Flash
  function webSocketError(message) {
    console.error(decodeURIComponent(message));
  }

  if (window.addEventListener) {
    window.addEventListener("load", WebSocket.__initialize, false);
  } else {
    window.attachEvent("onload", WebSocket.__initialize);
  }
}
<commit_msg>We keep console as a local variable to avoid writing `console` in the global scope Check for Flash presence to create WebSocket<commit_after>// Copyright: Hiroshi Ichikawa <http://gimite.net/en/>
// Lincense: New BSD Lincense
// Reference: http://dev.w3.org/html5/websockets/
// Reference: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol

(function(){
	var hasFlash = (function(){
		if ('navigator' in window && 'plugins' in navigator && 'Shockwave Flash' in navigator.plugins){
			return !! navigator.plugins['Shockwave Flash'].description;
		}

		if ('ActiveXObject' in window){
			try {
				return !! new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version');
			} catch (e){}
		}

		return false;
	})();

	if (!window.WebSocket && hasFlash) {

		var console = window.console;

	  if (!console) console = {log: function(){ }, error: function(){ }};

	  WebSocket = function(url, protocol, proxyHost, proxyPort, headers) {
	    var self = this;
	    self.readyState = WebSocket.CONNECTING;
	    self.bufferedAmount = 0;
	    WebSocket.__addTask(function() {
	      self.__flash =
	        WebSocket.__flash.create(url, protocol, proxyHost || null, proxyPort || 0, headers || null);

	      self.__flash.addEventListener("open", function(fe) {
	        try {
	          if (self.onopen) self.onopen();
	        } catch (e) {
	          console.error(e.toString());
	        }
	      });

	      self.__flash.addEventListener("close", function(fe) {
	        try {
	          if (self.onopen) self.onclose();
	        } catch (e) {
	          console.error(e.toString());
	        }
	      });

	      self.__flash.addEventListener("message", function(fe) {
	        var data = decodeURIComponent(fe.getData());
	        try {
	          if (self.onmessage) {
	            var e;
	            if (window.MessageEvent) {
	              e = document.createEvent("MessageEvent");
	              e.initMessageEvent("message", false, false, data, null, null, window);
	            } else { // IE
	              e = {data: data};
	            }
	            self.onmessage(e);
	          }
	        } catch (e) {
	          console.error(e.toString());
	        }
	      });

	      self.__flash.addEventListener("stateChange", function(fe) {
	        try {
	          self.readyState = fe.getReadyState();
	          self.bufferedAmount = fe.getBufferedAmount();
	        } catch (e) {
	          console.error(e.toString());
	        }
	      });

	      //console.log("[WebSocket] Flash object is ready");
	    });
	  }

	  WebSocket.prototype.send = function(data) {
	    if (!this.__flash || this.readyState == WebSocket.CONNECTING) {
	      throw "INVALID_STATE_ERR: Web Socket connection has not been established";
	    }
	    var result = this.__flash.send(data);
	    if (result < 0) { // success
	      return true;
	    } else {
	      this.bufferedAmount = result;
	      return false;
	    }
	  };

	  WebSocket.prototype.close = function() {
	    if (!this.__flash) return;
	    if (this.readyState != WebSocket.OPEN) return;
	    this.__flash.close();
	    // Sets/calls them manually here because Flash WebSocketConnection.close cannot fire events
	    // which causes weird error:
	    // > You are trying to call recursively into the Flash Player which is not allowed.
	    this.readyState = WebSocket.CLOSED;
	    if (this.onclose) this.onclose();
	  };

	  /**
	   * Implementation of {@link DOM 2 EventTarget Interface}
	   *
	   * @param {string} type
	   * @param {function} listener
	   * @param {boolean} useCapture !NB Not implemented yet
	   * @return void
	   */
	  WebSocket.prototype.addEventListener = function(type, listener, useCapture) {
	    if (!('__events' in this)) {
	      this.__events = {};
	    }
	    if (!(type in this.__events)) {
	      this.__events[type] = [];
	      if ('function' == typeof this['on' + type]) {
	        this.__events[type].defaultHandler = this['on' + type];
	        this['on' + type] = WebSocket_FireEvent(this, type);
	      }
	    }
	    this.__events[type].push(listener);
	  };

	  /**
	   * Implementation of {@link DOM 2 EventTarget Interface}
	   *
	   * @param {string} type
	   * @param {function} listener
	   * @param {boolean} useCapture NB! Not implemented yet
	   * @return void
	   */
	  WebSocket.prototype.removeEventListener = function(type, listener, useCapture) {
	    if (!('__events' in this)) {
	      this.__events = {};
	    }
	    if (!(type in this.__events)) return;
	    for (var i = this.__events.length; i > -1; --i) {
	      if (listener === this.__events[type][i]) {
	        this.__events[type].splice(i, 1);
	        break;
	      }
	    }
	  };

	  /**
	   * Implementation of {@link DOM 2 EventTarget Interface}
	   *
	   * @param {WebSocketEvent} event
	   * @return void
	   */
	  WebSocket.prototype.dispatchEvent = function(event) {
	    if (!('__events' in this)) throw 'UNSPECIFIED_EVENT_TYPE_ERR';
	    if (!(event.type in this.__events)) throw 'UNSPECIFIED_EVENT_TYPE_ERR';

	    for (var i = 0, l = this.__events[event.type].length; i < l; ++ i) {
	      this.__events[event.type][i](event);
	      if (event.cancelBubble) break;
	    }

	    if (false !== event.returnValue &&
	        'function' == typeof this.__events[event.type].defaultHandler)
	    {
	      this.__events[event.type].defaultHandler(event);
	    }
	  };

	  /**
	   *
	   * @param {object} object
	   * @param {string} type
	   */
	  function WebSocket_FireEvent(object, type) {
	    return function(data) {
	      var event = new WebSocketEvent();
	      event.initEvent(type, true, true);
	      event.target = event.currentTarget = object;
	      for (var key in data) {
	        event[key] = data[key];
	      }
	      object.dispatchEvent(event, arguments);
	    };
	  }

	  /**
	   * Basic implementation of {@link DOM 2 EventInterface}
	   *
	   * @class
	   * @constructor
	   */
	  function WebSocketEvent(){}

	  /**
	   *
	   * @type boolean
	   */
	  WebSocketEvent.prototype.cancelable = true;

	  /**
	   *
	   * @type boolean
	   */
	  WebSocketEvent.prototype.cancelBubble = false;

	  /**
	   *
	   * @return void
	   */
	  WebSocketEvent.prototype.preventDefault = function() {
	    if (this.cancelable) {
	      this.returnValue = false;
	    }
	  };

	  /**
	   *
	   * @return void
	   */
	  WebSocketEvent.prototype.stopPropagation = function() {
	    this.cancelBubble = true;
	  };

	  /**
	   *
	   * @param {string} eventTypeArg
	   * @param {boolean} canBubbleArg
	   * @param {boolean} cancelableArg
	   * @return void
	   */
	  WebSocketEvent.prototype.initEvent = function(eventTypeArg, canBubbleArg, cancelableArg) {
	    this.type = eventTypeArg;
	    this.cancelable = cancelableArg;
	    this.timeStamp = new Date();
	  };

	  WebSocket.CONNECTING = 0;
	  WebSocket.OPEN = 1;
	  WebSocket.CLOSED = 2;

	  WebSocket.__tasks = [];

	  WebSocket.__initialize = function() {
	    if (!WebSocket.__swfLocation) {
	      console.error("[WebSocket] set WebSocket.__swfLocation to location of WebSocketMain.swf");
	      return;
	    }
	    var container = document.createElement("div");
	    container.id = "webSocketContainer";
	    // Puts the Flash out of the window. Note that we cannot use display: none or visibility: hidden
	    // here because it prevents Flash from loading at least in IE.
	    container.style.position = "absolute";
	    container.style.left = "-100px";
	    container.style.top = "-100px";
	    var holder = document.createElement("div");
	    holder.id = "webSocketFlash";
	    container.appendChild(holder);
	    document.body.appendChild(container);
	    swfobject.embedSWF(
	      WebSocket.__swfLocation, "webSocketFlash", "10", "10", "9.0.0",
	      null, {bridgeName: "webSocket"}, null, null,
	      function(e) {
	        if (!e.success) console.error("[WebSocket] swfobject.embedSWF failed");
	      }
	    );
	    FABridge.addInitializationCallback("webSocket", function() {
	      try {
	        //console.log("[WebSocket] FABridge initializad");
	        WebSocket.__flash = FABridge.webSocket.root();
	        WebSocket.__flash.setCallerUrl(location.href);
	        for (var i = 0; i < WebSocket.__tasks.length; ++i) {
	          WebSocket.__tasks[i]();
	        }
	        WebSocket.__tasks = [];
	      } catch (e) {
	        console.error("[WebSocket] " + e.toString());
	      }
	    });
	  };

	  WebSocket.__addTask = function(task) {
	    if (WebSocket.__flash) {
	      task();
	    } else {
	      WebSocket.__tasks.push(task);
	    }
	  }

	  // called from Flash
	  function webSocketLog(message) {
	    console.log(decodeURIComponent(message));
	  }

	  // called from Flash
	  function webSocketError(message) {
	    console.error(decodeURIComponent(message));
	  }

	  if (window.addEventListener) {
	    window.addEventListener("load", WebSocket.__initialize, false);
	  } else {
	    window.attachEvent("onload", WebSocket.__initialize);
	  }
	}

})();<|endoftext|>


<commit_before>// Copyright: Hiroshi Ichikawa <http://gimite.net/en/>
// License: New BSD License
// Reference: http://dev.w3.org/html5/websockets/
// Reference: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol

(function() {

  if (window.WebSocket) return;

  var console = window.console;
  if (!console || !console.log || !console.error) {
    console = {log: function(){ }, error: function(){ }};
  }

  if (!swfobject.hasFlashPlayerVersion("10.0.0")) {
    console.error("Flash Player >= 10.0.0 is required.");
    return;
  }
  if (location.protocol == "file:") {
    console.error(
      "WARNING: web-socket-js doesn't work in file:///... URL " +
      "unless you set Flash Security Settings properly. " +
      "Open the page via Web server i.e. http://...");
  }

  /**
   * This class represents a faux web socket.
   * @param {string} url
   * @param {string} protocol
   * @param {string} proxyHost
   * @param {int} proxyPort
   * @param {string} headers
   */
  WebSocket = function(url, protocol, proxyHost, proxyPort, headers) {
    var self = this;
    self.__id = WebSocket.__nextId++;
    WebSocket.__instances[self.__id] = self;
    self.readyState = WebSocket.CONNECTING;
    self.bufferedAmount = 0;
    // Uses setTimeout() to make sure __createFlash() runs after the caller sets ws.onopen etc.
    // Otherwise, when onopen fires immediately, onopen is called before it is set.
    setTimeout(function() {
      WebSocket.__addTask(function() {
        WebSocket.__flash.create(
            self.__id, url, protocol, proxyHost || null, proxyPort || 0, headers || null);
      });
    }, 0);
  };

  /**
   * Send data to the web socket.
   * @param {string} data  The data to send to the socket.
   * @return {boolean}  True for success, false for failure.
   */
  WebSocket.prototype.send = function(data) {
    if (this.readyState == WebSocket.CONNECTING) {
      throw "INVALID_STATE_ERR: Web Socket connection has not been established";
    }
    // We use encodeURIComponent() here, because FABridge doesn't work if
    // the argument includes some characters. We don't use escape() here
    // because of this:
    // https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Functions#escape_and_unescape_Functions
    // But it looks decodeURIComponent(encodeURIComponent(s)) doesn't
    // preserve all Unicode characters either e.g. "\uffff" in Firefox.
    // Note by wtritch: Hopefully this will not be necessary using ExternalInterface.  Will require
    // additional testing.
    var result = WebSocket.__flash.send(this.__id, encodeURIComponent(data));
    if (result < 0) { // success
      return true;
    } else {
      this.bufferedAmount += result;
      return false;
    }
  };

  /**
   * Close this web socket gracefully.
   */
  WebSocket.prototype.close = function() {
    if (this.readyState == WebSocket.CLOSED || this.readyState == WebSocket.CLOSING) {
      return;
    }
    this.readyState = WebSocket.CLOSING;
    WebSocket.__flash.close(this.__id);
  };

  /**
   * Implementation of {@link DOM 2 EventTarget Interface}
   *
   * @param {string} type
   * @param {function} listener
   * @param {boolean} useCapture !NB Not implemented yet
   * @return void
   */
  WebSocket.prototype.addEventListener = function(type, listener, useCapture) {
    if (!('__events' in this)) {
      this.__events = {};
    }
    if (!(type in this.__events)) {
      this.__events[type] = [];
      if ('function' == typeof this['on' + type]) {
        this.__events[type].defaultHandler = this['on' + type];
        this['on' + type] = this.__createEventHandler(this, type);
      }
    }
    this.__events[type].push(listener);
  };

  /**
   * Implementation of {@link DOM 2 EventTarget Interface}
   *
   * @param {string} type
   * @param {function} listener
   * @param {boolean} useCapture NB! Not implemented yet
   * @return void
   */
  WebSocket.prototype.removeEventListener = function(type, listener, useCapture) {
    if (!('__events' in this)) {
      this.__events = {};
    }
    if (!(type in this.__events)) return;
    for (var i = this.__events.length; i > -1; --i) {
      if (listener === this.__events[type][i]) {
        this.__events[type].splice(i, 1);
        break;
      }
    }
  };

  /**
   * Implementation of {@link DOM 2 EventTarget Interface}
   *
   * @param {WebSocketEvent} event
   * @return void
   */
  WebSocket.prototype.dispatchEvent = function(event) {
    if (!('__events' in this)) throw 'UNSPECIFIED_EVENT_TYPE_ERR';
    if (!(event.type in this.__events)) throw 'UNSPECIFIED_EVENT_TYPE_ERR';

    for (var i = 0, l = this.__events[event.type].length; i < l; ++ i) {
      this.__events[event.type][i](event);
      if (event.cancelBubble) break;
    }

    if (false !== event.returnValue &&
      'function' == typeof this.__events[event.type].defaultHandler)
    {
      this.__events[event.type].defaultHandler(event);
    }
  };

  /**
   * Handle an event from Flash.  Do any WebSocket-specific
   * handling before passing the event off to the event handlers.
   * @param {Object} event
   */
  WebSocket.prototype.__handleEvent = function(event) {
    if ("readyState" in event) {
      this.readyState = event.readyState;
    }

    try {
      if (event.type == "open") {
        if (this.onopen) this.onopen();
      } else if (event.type == "close") {
        if (this.onclose) this.onclose();
      } else if (event.type == "error") {
        if (this.onerror) this.onerror(event);
      } else if (event.type == "message") {
        if (this.onmessage) {
          var data = decodeURIComponent(event.message);
          var e;
          if (window.MessageEvent && !window.opera) {
            e = document.createEvent("MessageEvent");
            e.initMessageEvent("message", false, false, data, null, null, window, null);
          } else {
            // IE and Opera, the latter one truncates the data parameter after any 0x00 bytes.
            e = {data: data};
          }
          this.onmessage(e);
        }
      } else {
        throw "unknown event type: " + event.type;
      }
    } catch (e) {
      console.error(e);
    }
  };

  /**
   * @param {object} object
   * @param {string} type
   */
  WebSocket.prototype.__createEventHandler = function(object, type) {
    return function(data) {
      var event = new WebSocketEvent();
      event.initEvent(type, true, true);
      event.target = event.currentTarget = object;
      for (var key in data) {
        event[key] = data[key];
      }
      object.dispatchEvent(event, arguments);
    };
  };

  /**
   * Define the WebSocket readyState enumeration.
   */
  WebSocket.CONNECTING = 0;
  WebSocket.OPEN = 1;
  WebSocket.CLOSING = 2;
  WebSocket.CLOSED = 3;

  WebSocket.__flash = null;
  WebSocket.__instances = {};
  WebSocket.__tasks = [];
  WebSocket.__nextId = 0;

  /**
   * Loads WebSocketMain.swf and creates WebSocketMain object in Flash.
   */
  WebSocket.__initialize = function() {
    if (WebSocket.__flash) return;

    if (WebSocket.__swfLocation) {
      // For backword compatibility.
      window.WEB_SOCKET_SWF_LOCATION = WebSocket.__swfLocation;
    }
    if (!window.WEB_SOCKET_SWF_LOCATION) {
      console.error("[WebSocket] set WEB_SOCKET_SWF_LOCATION to location of WebSocketMain.swf");
      return;
    }
    var container = document.createElement("div");
    container.id = "webSocketContainer";
    // Hides Flash box. We cannot use display: none or visibility: hidden because it prevents
    // Flash from loading at least in IE. So we move it out of the screen at (-100, -100).
    // But this even doesn't work with Flash Lite (e.g. in Droid Incredible). So with Flash
    // Lite, we put it at (0, 0). This shows 1x1 box visible at left-top corner but this is
    // the best we can do as far as we know now.
    container.style.position = "absolute";
    if (WebSocket.__isFlashLite()) {
      container.style.left = "0px";
      container.style.top = "0px";
    } else {
      container.style.left = "-100px";
      container.style.top = "-100px";
    }
    var holder = document.createElement("div");
    holder.id = "webSocketFlash";
    container.appendChild(holder);
    document.body.appendChild(container);
    // See this article for hasPriority:
    // http://help.adobe.com/en_US/as3/mobile/WS4bebcd66a74275c36cfb8137124318eebc6-7ffd.html
    swfobject.embedSWF(
      WEB_SOCKET_SWF_LOCATION,
      "webSocketFlash",
      "1" /* width */,
      "1" /* height */,
      "10.0.0" /* SWF version */,
      null,
      null,
      {hasPriority: true, swliveconnect : true, allowScriptAccess: "always"},
      null,
      function(e) {
        if (!e.success) {
          console.error("[WebSocket] swfobject.embedSWF failed");
        }
      });
  };

  /**
   * Load a new flash security policy file.
   * @param {string} url
   */
  WebSocket.loadFlashPolicyFile = function(url){
    WebSocket.__addTask(function() {
      WebSocket.__flash.loadManualPolicyFile(url);
    });
  };

  /**
   * Called by flash to notify js that it's fully loaded and ready
   * for communication.
   */
  WebSocket.__onFlashInitialized = function() {
    // We need to set a timeout here to avoid round-trip calls
    // to flash during the initialization process.
    setTimeout(function() {
      WebSocket.__flash = document.getElementById("webSocketFlash");
      WebSocket.__flash.setCallerUrl(location.href);
      WebSocket.__flash.setDebug(!!window.WEB_SOCKET_DEBUG);
      for (var i = 0; i < WebSocket.__tasks.length; ++i) {
        WebSocket.__tasks[i]();
      }
      WebSocket.__tasks = [];
    }, 0);
  };

  /**
   * Called by flash to dispatch an event to a web socket.
   * @param {object} eventObj  A web socket event dispatched from flash.
   */
  WebSocket.__onFlashEvent = function() {
    setTimeout(function() {
      // Gets events using receiveEvents() instead of getting it from event object
      // of Flash event. This is to make sure to keep message order.
      // It seems sometimes Flash events don't arrive in the same order as they are sent.
      var events = WebSocket.__flash.receiveEvents();
      for (var i = 0; i < events.length; ++i) {
        WebSocket.__instances[events[i].webSocketId].__handleEvent(events[i]);
      }
    }, 0);
    return true;
  };

  // called from Flash
  WebSocket.__log = function(message) {
    console.log(decodeURIComponent(message));
  };

  // called from Flash
  WebSocket.__error = function(message) {
    console.error(decodeURIComponent(message));
  };

  WebSocket.__addTask = function(task) {
    if (WebSocket.__flash) {
      task();
    } else {
      WebSocket.__tasks.push(task);
    }
  };

  /**
   * Test if the browser is running flash lite.
   * @return {boolean} True if flash lite is running, false otherwise.
   */
  WebSocket.__isFlashLite = function() {
    if (!window.navigator || !window.navigator.mimeTypes) {
      return false;
    }
    var mimeType = window.navigator.mimeTypes["application/x-shockwave-flash"];
    if (!mimeType || !mimeType.enabledPlugin || !mimeType.enabledPlugin.filename) {
      return false;
    }
    return mimeType.enabledPlugin.filename.match(/flashlite/i) ? true : false;
  };

  /**
   * Basic implementation of {@link DOM 2 EventInterface}
   *
   * @class
   * @constructor
   */
  function WebSocketEvent(){}

  /**
   *
   * @type boolean
   */
  WebSocketEvent.prototype.cancelable = true;

  /**
  *
  * @type boolean
  */
  WebSocketEvent.prototype.cancelBubble = false;

  /**
  *
  * @return void
  */
  WebSocketEvent.prototype.preventDefault = function() {
    if (this.cancelable) {
      this.returnValue = false;
    }
  };

  /**
  *
  * @return void
  */
  WebSocketEvent.prototype.stopPropagation = function() {
    this.cancelBubble = true;
  };

  /**
  *
  * @param {string} eventTypeArg
  * @param {boolean} canBubbleArg
  * @param {boolean} cancelableArg
  * @return void
  */
  WebSocketEvent.prototype.initEvent = function(eventTypeArg, canBubbleArg, cancelableArg) {
    this.type = eventTypeArg;
    this.cancelable = cancelableArg;
    this.timeStamp = new Date();
  };

  if (!window.WEB_SOCKET_DISABLE_AUTO_INITIALIZATION) {
    if (window.addEventListener) {
      window.addEventListener("load", function(){
        WebSocket.__initialize();
      }, false);
    } else {
      window.attachEvent("onload", function(){
        WebSocket.__initialize();
      });
    }
  }

})();
<commit_msg>Cleaning up event handling. Passing real event to both onXXX and handlers added by addEventHandler(). Deleting check of cancelBubble which (probably) should not affect.<commit_after>// Copyright: Hiroshi Ichikawa <http://gimite.net/en/>
// License: New BSD License
// Reference: http://dev.w3.org/html5/websockets/
// Reference: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol

(function() {

  if (window.WebSocket) return;

  var console = window.console;
  if (!console || !console.log || !console.error) {
    console = {log: function(){ }, error: function(){ }};
  }

  if (!swfobject.hasFlashPlayerVersion("10.0.0")) {
    console.error("Flash Player >= 10.0.0 is required.");
    return;
  }
  if (location.protocol == "file:") {
    console.error(
      "WARNING: web-socket-js doesn't work in file:///... URL " +
      "unless you set Flash Security Settings properly. " +
      "Open the page via Web server i.e. http://...");
  }

  /**
   * This class represents a faux web socket.
   * @param {string} url
   * @param {string} protocol
   * @param {string} proxyHost
   * @param {int} proxyPort
   * @param {string} headers
   */
  WebSocket = function(url, protocol, proxyHost, proxyPort, headers) {
    var self = this;
    self.__id = WebSocket.__nextId++;
    WebSocket.__instances[self.__id] = self;
    self.readyState = WebSocket.CONNECTING;
    self.bufferedAmount = 0;
    self.__events = {};
    // Uses setTimeout() to make sure __createFlash() runs after the caller sets ws.onopen etc.
    // Otherwise, when onopen fires immediately, onopen is called before it is set.
    setTimeout(function() {
      WebSocket.__addTask(function() {
        WebSocket.__flash.create(
            self.__id, url, protocol, proxyHost || null, proxyPort || 0, headers || null);
      });
    }, 0);
  };

  /**
   * Send data to the web socket.
   * @param {string} data  The data to send to the socket.
   * @return {boolean}  True for success, false for failure.
   */
  WebSocket.prototype.send = function(data) {
    if (this.readyState == WebSocket.CONNECTING) {
      throw "INVALID_STATE_ERR: Web Socket connection has not been established";
    }
    // We use encodeURIComponent() here, because FABridge doesn't work if
    // the argument includes some characters. We don't use escape() here
    // because of this:
    // https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Functions#escape_and_unescape_Functions
    // But it looks decodeURIComponent(encodeURIComponent(s)) doesn't
    // preserve all Unicode characters either e.g. "\uffff" in Firefox.
    // Note by wtritch: Hopefully this will not be necessary using ExternalInterface.  Will require
    // additional testing.
    var result = WebSocket.__flash.send(this.__id, encodeURIComponent(data));
    if (result < 0) { // success
      return true;
    } else {
      this.bufferedAmount += result;
      return false;
    }
  };

  /**
   * Close this web socket gracefully.
   */
  WebSocket.prototype.close = function() {
    if (this.readyState == WebSocket.CLOSED || this.readyState == WebSocket.CLOSING) {
      return;
    }
    this.readyState = WebSocket.CLOSING;
    WebSocket.__flash.close(this.__id);
  };

  /**
   * Implementation of {@link DOM 2 EventTarget Interface}
   *
   * @param {string} type
   * @param {function} listener
   * @param {boolean} useCapture
   * @return void
   */
  WebSocket.prototype.addEventListener = function(type, listener, useCapture) {
    if (!(type in this.__events)) {
      this.__events[type] = [];
    }
    this.__events[type].push(listener);
  };

  /**
   * Implementation of {@link DOM 2 EventTarget Interface}
   *
   * @param {string} type
   * @param {function} listener
   * @param {boolean} useCapture
   * @return void
   */
  WebSocket.prototype.removeEventListener = function(type, listener, useCapture) {
    if (!(type in this.__events)) return;
    var events = this.__events[type];
    for (var i = events.length - 1; i >= 0; --i) {
      if (events[i] === listener) {
        events.splice(i, 1);
        break;
      }
    }
  };

  /**
   * Implementation of {@link DOM 2 EventTarget Interface}
   *
   * @param {Event} event
   * @return void
   */
  WebSocket.prototype.dispatchEvent = function(event) {
    var events = this.__events[event.type] || [];
    for (var i = 0; i < events.length; ++i) {
      events[i](event);
    }
    var handler = this["on" + event.type];
    if (handler) handler(event);
  };

  /**
   * Handles an event from Flash.
   * @param {Object} flashEvent
   */
  WebSocket.prototype.__handleEvent = function(flashEvent) {
    if ("readyState" in flashEvent) {
      this.readyState = flashEvent.readyState;
    }

    var jsEvent;
    if (flashEvent.type == "open" || flashEvent.type == "error") {
      jsEvent = this.__createSimpleEvent(flashEvent.type);
    } else if (flashEvent.type == "close") {
      // TODO implement jsEvent.wasClean
      jsEvent = this.__createSimpleEvent("close");
    } else if (flashEvent.type == "message") {
      var data = decodeURIComponent(flashEvent.message);
      jsEvent = this.__createMessageEvent("message", data);
    } else {
      throw "unknown event type: " + flashEvent.type;
    }

    this.dispatchEvent(jsEvent);
  };

  WebSocket.prototype.__createSimpleEvent = function(type) {
    if (window.Event) {
      var event = document.createEvent("Event");
      event.initEvent(type, false, false);
      return event;
    } else {
      return {type: type, bubbles: false, cancelable: false};
    }
  };

  WebSocket.prototype.__createMessageEvent = function(type, data) {
    if (window.MessageEvent && !window.opera) {
      var event = document.createEvent("MessageEvent");
      event.initMessageEvent("message", false, false, data, null, null, window, null);
      return event;
    } else {
      // IE and Opera, the latter one truncates the data parameter after any 0x00 bytes.
      return {type: type, data: data, bubbles: false, cancelable: false};
    }
  };

  /**
   * Define the WebSocket readyState enumeration.
   */
  WebSocket.CONNECTING = 0;
  WebSocket.OPEN = 1;
  WebSocket.CLOSING = 2;
  WebSocket.CLOSED = 3;

  WebSocket.__flash = null;
  WebSocket.__instances = {};
  WebSocket.__tasks = [];
  WebSocket.__nextId = 0;

  /**
   * Load a new flash security policy file.
   * @param {string} url
   */
  WebSocket.loadFlashPolicyFile = function(url){
    WebSocket.__addTask(function() {
      WebSocket.__flash.loadManualPolicyFile(url);
    });
  };

  /**
   * Loads WebSocketMain.swf and creates WebSocketMain object in Flash.
   */
  WebSocket.__initialize = function() {
    if (WebSocket.__flash) return;

    if (WebSocket.__swfLocation) {
      // For backword compatibility.
      window.WEB_SOCKET_SWF_LOCATION = WebSocket.__swfLocation;
    }
    if (!window.WEB_SOCKET_SWF_LOCATION) {
      console.error("[WebSocket] set WEB_SOCKET_SWF_LOCATION to location of WebSocketMain.swf");
      return;
    }
    var container = document.createElement("div");
    container.id = "webSocketContainer";
    // Hides Flash box. We cannot use display: none or visibility: hidden because it prevents
    // Flash from loading at least in IE. So we move it out of the screen at (-100, -100).
    // But this even doesn't work with Flash Lite (e.g. in Droid Incredible). So with Flash
    // Lite, we put it at (0, 0). This shows 1x1 box visible at left-top corner but this is
    // the best we can do as far as we know now.
    container.style.position = "absolute";
    if (WebSocket.__isFlashLite()) {
      container.style.left = "0px";
      container.style.top = "0px";
    } else {
      container.style.left = "-100px";
      container.style.top = "-100px";
    }
    var holder = document.createElement("div");
    holder.id = "webSocketFlash";
    container.appendChild(holder);
    document.body.appendChild(container);
    // See this article for hasPriority:
    // http://help.adobe.com/en_US/as3/mobile/WS4bebcd66a74275c36cfb8137124318eebc6-7ffd.html
    swfobject.embedSWF(
      WEB_SOCKET_SWF_LOCATION,
      "webSocketFlash",
      "1" /* width */,
      "1" /* height */,
      "10.0.0" /* SWF version */,
      null,
      null,
      {hasPriority: true, swliveconnect : true, allowScriptAccess: "always"},
      null,
      function(e) {
        if (!e.success) {
          console.error("[WebSocket] swfobject.embedSWF failed");
        }
      });
  };

  /**
   * Called by Flash to notify JS that it's fully loaded and ready
   * for communication.
   */
  WebSocket.__onFlashInitialized = function() {
    // We need to set a timeout here to avoid round-trip calls
    // to flash during the initialization process.
    setTimeout(function() {
      WebSocket.__flash = document.getElementById("webSocketFlash");
      WebSocket.__flash.setCallerUrl(location.href);
      WebSocket.__flash.setDebug(!!window.WEB_SOCKET_DEBUG);
      for (var i = 0; i < WebSocket.__tasks.length; ++i) {
        WebSocket.__tasks[i]();
      }
      WebSocket.__tasks = [];
    }, 0);
  };

  /**
   * Called by Flash to notify WebSockets events are fired.
   */
  WebSocket.__onFlashEvent = function() {
    setTimeout(function() {
      try {
        // Gets events using receiveEvents() instead of getting it from event object
        // of Flash event. This is to make sure to keep message order.
        // It seems sometimes Flash events don't arrive in the same order as they are sent.
        var events = WebSocket.__flash.receiveEvents();
        for (var i = 0; i < events.length; ++i) {
          WebSocket.__instances[events[i].webSocketId].__handleEvent(events[i]);
        }
      } catch (e) {
        console.error(e);
      }
    }, 0);
    return true;
  };

  // Called by Flash.
  WebSocket.__log = function(message) {
    console.log(decodeURIComponent(message));
  };

  // Called by Flash.
  WebSocket.__error = function(message) {
    console.error(decodeURIComponent(message));
  };

  WebSocket.__addTask = function(task) {
    if (WebSocket.__flash) {
      task();
    } else {
      WebSocket.__tasks.push(task);
    }
  };

  /**
   * Test if the browser is running flash lite.
   * @return {boolean} True if flash lite is running, false otherwise.
   */
  WebSocket.__isFlashLite = function() {
    if (!window.navigator || !window.navigator.mimeTypes) {
      return false;
    }
    var mimeType = window.navigator.mimeTypes["application/x-shockwave-flash"];
    if (!mimeType || !mimeType.enabledPlugin || !mimeType.enabledPlugin.filename) {
      return false;
    }
    return mimeType.enabledPlugin.filename.match(/flashlite/i) ? true : false;
  };

  if (!window.WEB_SOCKET_DISABLE_AUTO_INITIALIZATION) {
    if (window.addEventListener) {
      window.addEventListener("load", function(){
        WebSocket.__initialize();
      }, false);
    } else {
      window.attachEvent("onload", function(){
        WebSocket.__initialize();
      });
    }
  }

})();
<|endoftext|>


<commit_before>'use strict';

// Declare app level module which depends on views, and components
angular.module('myApp', [
  'ngRoute',
  'ngWebSocket',
  'ngMaterial',
  'angularCSS',
  'dcbImgFallback',
  'myApp.main',
  'myApp.roverDrive',
  'myApp.roverObserve',
  'myApp.roverService',
  'myApp.logs',
  'myApp.settings',
  'myApp.example',
  'myApp.info',
  'myApp.version',
  'myApp.dpad'
])
.config(function ($mdThemingProvider) {
		$mdThemingProvider.theme('default')
			.primaryPalette('blue',{
				'default': '800',
				'hue-1': '200',
				'hue-2': '600',
				'hue-3': '800'
			})
			.accentPalette('green',{'default': '500'})
			.warnPalette('red');
	})
.config(['$routeProvider', function($routeProvider) {
  $routeProvider.
	when('/main', {
  	templateUrl: 'main/main.html',
  	controller: 'MainCtrl'
 	}).
  when('/drive',{
    templateUrl: 'roverDrive/roverDrive.html',
    controller: 'RoverDriveCtrl'
  }).
  when('/observe',{
    templateUrl: 'roverObserve/roverObserve.html',
    controller: 'RoverObserveCtrl'
  }).
  when('/settings',{
    templateUrl: 'settings/settings.html',
    controller: 'SettingsCtrl'
  }).
  when('/logs',{
    templateUrl: 'logs/logs.html',
    controller: 'LogsCtrl'
  }).
	when('/info',{
		templateUrl: 'info/info.html',
		controller: 'InfoCtrl'
	}).
	when('/example', {
	  templateUrl: 'example/example.html',
    controller: 'ExampleCtrl'
  }).
	otherwise({redirectTo: '/main'});

}])
.controller('SidebarCtrl', function ($scope, $timeout, $mdSidenav, $mdUtil, $log) {
  $scope.closeSidebar = function () {
     $mdSidenav('sidebar').close();
   };

  $scope.toggleSidebar = $mdUtil.debounce(function () {
     console.log('toggle sidebar');
     $mdSidenav('sidebar').toggle();
   }, 200);
})
;
<commit_msg>Changed color-scheme<commit_after>'use strict';

// Declare app level module which depends on views, and components
angular.module('myApp', [
  'ngRoute',
  'ngWebSocket',
  'ngMaterial',
  'angularCSS',
  'dcbImgFallback',
  'myApp.main',
  'myApp.roverDrive',
  'myApp.roverObserve',
  'myApp.roverService',
  'myApp.logs',
  'myApp.settings',
  'myApp.example',
  'myApp.info',
  'myApp.version',
  'myApp.dpad'
])
.config(function ($mdThemingProvider) {
		$mdThemingProvider.theme('default')
			.primaryPalette('cyan',{
				'default': '800',
				'hue-1': '400',
				'hue-2': '700',
				'hue-3': '800'
			})
			.accentPalette('blue-grey',{'default': '500'})
			.warnPalette('red', {'default': '800'});
	})
.config(['$routeProvider', function($routeProvider) {
  $routeProvider.
	when('/main', {
  	templateUrl: 'main/main.html',
  	controller: 'MainCtrl'
 	}).
  when('/drive',{
    templateUrl: 'roverDrive/roverDrive.html',
    controller: 'RoverDriveCtrl'
  }).
  when('/observe',{
    templateUrl: 'roverObserve/roverObserve.html',
    controller: 'RoverObserveCtrl'
  }).
  when('/settings',{
    templateUrl: 'settings/settings.html',
    controller: 'SettingsCtrl'
  }).
  when('/logs',{
    templateUrl: 'logs/logs.html',
    controller: 'LogsCtrl'
  }).
	when('/info',{
		templateUrl: 'info/info.html',
		controller: 'InfoCtrl'
	}).
	when('/example', {
	  templateUrl: 'example/example.html',
    controller: 'ExampleCtrl'
  }).
	otherwise({redirectTo: '/main'});

}])
.controller('SidebarCtrl', function ($scope, $timeout, $mdSidenav, $mdUtil, $log) {
  $scope.closeSidebar = function () {
     $mdSidenav('sidebar').close();
   };

  $scope.toggleSidebar = $mdUtil.debounce(function () {
     console.log('toggle sidebar');
     $mdSidenav('sidebar').toggle();
   }, 200);
})
;
<|endoftext|>


<commit_before>import React from 'react'
import PropTypes from 'prop-types'

import { msg } from '_/intl'
import { escapeHtml } from '../../../utils'
import itemStyle from '../../itemListStyle.css'
import style from './style.css'

import { Icon } from 'patternfly-react'
import { Grid, Row, Col } from '_/components/Grid'
import DeleteConfirmationModal from '../../../VmModals/DeleteConfirmationModal'
import NicEditor from './NicEditor'
import NicLinkStateIcon from './NicLinkStateIcon'
import OverlayTooltip from '_/components/OverlayTooltip'
import EllipsisValue from '_/components/EllipsisValue'
/**
 * Render a single NIC in the list of Nics on the Nics Card.
 *
 * If _edit_ then render the appropriate action buttons linked to provided
 * handler functions.
 */
const NicListItem = ({ idPrefix, nic, vmStatus, vnicProfileList, isEditing, onEdit, onDelete }) => {
  const canEdit = !!onEdit
  const canDelete = !!onDelete

  return

    {/* Status Column - content width only */}

      <NicLinkStateIcon linkState={nic.linked} idSuffix={nic.id} />

    {/* Details Column - take the rest of the space */}

        <span id={`${idPrefix}-name`}>{nic.name}
        <span className={style['vnic-info']} id={`${idPrefix}-vnic-info`}>
          { nic.vnicProfile.id
            ? `(${nic.vnicProfile.name}/${nic.vnicProfile.network})`
            : `[${msg.nicNoVnicAssigned()}]`
          }

      <Grid>
        <Row>
          <Col cols={4} wrapExpand className={style['ip4-container']} id={`${idPrefix}-ipv4`}>
            { nic.ipv4.length > 0 &&
              nic.ipv4.map((ip4, index) =>
                <EllipsisValue
                  tooltip={ip4}
                  key={`${nic.id}-${ip4}-${index}`}
                  id={`${idPrefix}-ipv4-${index}`}
                >

{msg.nicIP4()}: {ip4}

                </EllipsisValue>)
            }
          </Col>
          <Col cols={8} wrapExpand className={style['ip6-container']} id={`${idPrefix}-ipv6`}>
            { nic.ipv6.length > 0 &&
              nic.ipv6.map((ip6, index) =>
                <EllipsisValue
                  tooltip={ip6}
                  key={`${nic.id}-${ip6}-${index}`}
                  id={`${idPrefix}-ipv6-${index}`}
                >

{msg.nicIP6()}: {ip6}

                </EllipsisValue>)
            }
          </Col>
        </Row>
      </Grid>

    {/* Actions Column (if edit) - content width, no wrapping */}
    { isEditing &&
    <span className={itemStyle['item-row-actions']} id={`${idPrefix}-actions`}>
      { canEdit &&
        <NicEditor
          idPrefix={`${idPrefix}-edit`}
          nic={nic}
          vmStatus={vmStatus}
          vnicProfileList={vnicProfileList}
          onSave={onEdit}
          trigger={
            <OverlayTooltip id={`${idPrefix}-edit-tooltip`} tooltip={msg.nicEditTooltip()}>
              <a id={`${idPrefix}-edit-action`} className={itemStyle['item-action']}>
                <Icon type='pf' name='edit' />

            </OverlayTooltip>
          }
        />
      }
      { !canEdit &&
        <OverlayTooltip id={`${idPrefix}-edit-tooltip-disabled`} tooltip={msg.nicEditDisabledTooltip()}>
          <Icon
            type='pf'
            name='edit'
            id={`${idPrefix}-edit-action-disabled`}
            className={`${itemStyle['item-action']} ${itemStyle['item-action-disabled']}`}
          />
        </OverlayTooltip>
      }

      { canDelete &&
        <DeleteConfirmationModal
          id={`${idPrefix}-delete-modal`}
          onDelete={() => { onDelete(nic.id) }}
          trigger={
            <OverlayTooltip id={`${idPrefix}-delete-tooltip`} tooltip={msg.nicDeleteTooltip()}>
              <a id={`${idPrefix}-delete-action`} className={itemStyle['item-action']}>
                <Icon type='pf' name='delete' />

            </OverlayTooltip>
          }
        >
          <span
            dangerouslySetInnerHTML={{
              __html: msg.areYouSureYouWantToDeleteNic({
                nicName: `"<strong>${escapeHtml(nic.name)}</strong>"`,
              }),
            }}
          />
        </DeleteConfirmationModal>
      }
      { !canDelete &&
        <OverlayTooltip id={`${idPrefix}-delete-tooltip-disabled`} tooltip={msg.nicDeleteDisabledTooltip()}>
          <Icon
            type='pf'
            name='delete'
            id={`${idPrefix}-delete-action-disabled`}
            className={`${itemStyle['item-action']} ${itemStyle['item-action-disabled']}`}
          />
        </OverlayTooltip>
      }

    }

}
NicListItem.propTypes = {
  idPrefix: PropTypes.string.isRequired,
  nic: PropTypes.object.isRequired,
  vmStatus: PropTypes.string.isRequired,
  vnicProfileList: PropTypes.object.isRequired,
  isEditing: PropTypes.bool.isRequired,

  onEdit: PropTypes.func,
  onDelete: PropTypes.func,
}

export default NicListItem
<commit_msg>Remove div container from EllipsisValue's children<commit_after>import React from 'react'
import PropTypes from 'prop-types'

import { msg } from '_/intl'
import { escapeHtml } from '../../../utils'
import itemStyle from '../../itemListStyle.css'
import style from './style.css'

import { Icon } from 'patternfly-react'
import { Grid, Row, Col } from '_/components/Grid'
import DeleteConfirmationModal from '../../../VmModals/DeleteConfirmationModal'
import NicEditor from './NicEditor'
import NicLinkStateIcon from './NicLinkStateIcon'
import OverlayTooltip from '_/components/OverlayTooltip'
import EllipsisValue from '_/components/EllipsisValue'

/**
 * Render a single NIC in the list of Nics on the Nics Card.
 *
 * If _edit_ then render the appropriate action buttons linked to provided
 * handler functions.
 */
const NicListItem = ({ idPrefix, nic, vmStatus, vnicProfileList, isEditing, onEdit, onDelete }) => {
  const canEdit = !!onEdit
  const canDelete = !!onDelete

  return

    {/* Status Column - content width only */}

      <NicLinkStateIcon linkState={nic.linked} idSuffix={nic.id} />

    {/* Details Column - take the rest of the space */}

        <span id={`${idPrefix}-name`}>{nic.name}
        <span className={style['vnic-info']} id={`${idPrefix}-vnic-info`}>
          { nic.vnicProfile.id
            ? `(${nic.vnicProfile.name}/${nic.vnicProfile.network})`
            : `[${msg.nicNoVnicAssigned()}]`
          }

      <Grid>
        <Row>
          <Col cols={4} wrapExpand className={style['ip4-container']} id={`${idPrefix}-ipv4`}>
            { nic.ipv4.length > 0 &&
              nic.ipv4.map((ip4, index) =>
                <EllipsisValue
                  tooltip={ip4}
                  key={`${nic.id}-${ip4}-${index}`}
                  id={`${idPrefix}-ipv4-${index}`}
                >
                  {msg.nicIP4()}: {ip4}
                </EllipsisValue>)
            }
          </Col>
          <Col cols={8} wrapExpand className={style['ip6-container']} id={`${idPrefix}-ipv6`}>
            { nic.ipv6.length > 0 &&
              nic.ipv6.map((ip6, index) =>
                <EllipsisValue
                  tooltip={ip6}
                  key={`${nic.id}-${ip6}-${index}`}
                  id={`${idPrefix}-ipv6-${index}`}
                >
                  {msg.nicIP6()}: {ip6}
                </EllipsisValue>)
            }
          </Col>
        </Row>
      </Grid>

    {/* Actions Column (if edit) - content width, no wrapping */}
    { isEditing &&
    <span className={itemStyle['item-row-actions']} id={`${idPrefix}-actions`}>
      { canEdit &&
        <NicEditor
          idPrefix={`${idPrefix}-edit`}
          nic={nic}
          vmStatus={vmStatus}
          vnicProfileList={vnicProfileList}
          onSave={onEdit}
          trigger={
            <OverlayTooltip id={`${idPrefix}-edit-tooltip`} tooltip={msg.nicEditTooltip()}>
              <a id={`${idPrefix}-edit-action`} className={itemStyle['item-action']}>
                <Icon type='pf' name='edit' />

            </OverlayTooltip>
          }
        />
      }
      { !canEdit &&
        <OverlayTooltip id={`${idPrefix}-edit-tooltip-disabled`} tooltip={msg.nicEditDisabledTooltip()}>
          <Icon
            type='pf'
            name='edit'
            id={`${idPrefix}-edit-action-disabled`}
            className={`${itemStyle['item-action']} ${itemStyle['item-action-disabled']}`}
          />
        </OverlayTooltip>
      }

      { canDelete &&
        <DeleteConfirmationModal
          id={`${idPrefix}-delete-modal`}
          onDelete={() => { onDelete(nic.id) }}
          trigger={
            <OverlayTooltip id={`${idPrefix}-delete-tooltip`} tooltip={msg.nicDeleteTooltip()}>
              <a id={`${idPrefix}-delete-action`} className={itemStyle['item-action']}>
                <Icon type='pf' name='delete' />

            </OverlayTooltip>
          }
        >
          <span
            dangerouslySetInnerHTML={{
              __html: msg.areYouSureYouWantToDeleteNic({
                nicName: `"<strong>${escapeHtml(nic.name)}</strong>"`,
              }),
            }}
          />
        </DeleteConfirmationModal>
      }
      { !canDelete &&
        <OverlayTooltip id={`${idPrefix}-delete-tooltip-disabled`} tooltip={msg.nicDeleteDisabledTooltip()}>
          <Icon
            type='pf'
            name='delete'
            id={`${idPrefix}-delete-action-disabled`}
            className={`${itemStyle['item-action']} ${itemStyle['item-action-disabled']}`}
          />
        </OverlayTooltip>
      }

    }

}
NicListItem.propTypes = {
  idPrefix: PropTypes.string.isRequired,
  nic: PropTypes.object.isRequired,
  vmStatus: PropTypes.string.isRequired,
  vnicProfileList: PropTypes.object.isRequired,
  isEditing: PropTypes.bool.isRequired,

  onEdit: PropTypes.func,
  onDelete: PropTypes.func,
}

export default NicListItem
<|endoftext|>