<commit_before>/*
 * Copyright 2014 Albert P. Tobey <atobey@datastax.com> @AlTobey
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// one-time setup, creating elements, etc.
$(function() {
  // there are two timers, one fires XHRs to update data stored in DATA
  // the other updates content on the page using data in DATA
  // These will be out of sync a little but it should be no big deal
  // since the code below is written to keep them independent.
  // This should probably be replaced by some kind of library that
  // hooks up to websockets nicely, but for now this is good enough.
  var DATA = {};
  DATA.update = function () {
      d3.json("/counts", function (data) { DATA.counts = data; split_counts(data); });
      d3.json("/top_games/human_topN", function (data) { DATA.human_topn = data; });
      d3.json("/top_games/ai_topN", function (data) { DATA.ai_topn = data; });
      d3.json("/recent", function (data) { DATA.recent_games = data; });
      d3.json("/avg_score_by_turn", function (data) { DATA.avg_score_by_turn = data; });
  };
  DATA.update();

  // place all widgets here that should auto update
  var WIDGETS = {};

  // find all keys with a dash_update() method then call it
  WIDGETS.update = function () {
    d3.keys(WIDGETS).forEach(function (key) {
      if (typeof WIDGETS[key].dash_update === 'function') {
        WIDGETS[key].dash_update(WIDGETS[key]);
      }
    });
  };

  // use jquery.timer.js to update every second
  // TODO: add play/pause buttons?
  // these will run a litle out of sync and that's OK for now
  DATA.timer = $.timer(DATA.update, 1000, true);
  WIDGETS.timer = $.timer(WIDGETS.update, 200, true);

  var get_avg_score = function (turn) {
    return DATA.avg_score_by_turn.filter(function (v) {
      if (v.name === "human" && turn_id === turn) {
        return true;
      }
      return false;
    })[0];
  };

  var move = function (game, dir) {
    var changed = game.move(dir);
    if (!changed) {
      return;
    }

    var new_tile_idx = game.insert();
    $.ajax({
      url: "/grid",
      type: "PUT",
      dataType: "json",
      data: game.serialize(),
      success: function () { console.log("XHR Succeeded."); }
    });

    d3.select(game.target + "-score").text(game.score);
    d3.select(game.target + "-turn-id").text(game.sequence);
    d3.select(game.target + "-avg-score").text(get_avg_score(game.sequence));

    game.last_turn = performance.now();
  };

  var gradient = [
    "#3EFF09", "#0BFD11", "#0CFC4B", "#0EFA84", "#0FF9BC", "#10F7F2", "#11C5F6", "#138EF5", "#1459F3", "#1525F2",
    "#3B16F0", "#6F18EF", "#A119ED", "#D31AEC", "#EB1BD2", "#E91CA0", "#E81D6F", "#E61E40", "#E52D1F", "#E45C21"
  ];

  // color the whole game div background by pressure with a gradient
  var colorize = function (game, bb) {
    var gx = 355 - Math.floor(355 * ((bb.lf_pcnt + bb.lr_pcnt)/100));
    var gy = 355 - Math.floor(355 * ((bb.lf_pcnt + bb.rf_pcnt)/100));
    d3.select(game.target + " .f7u12-grid").style("background", "radial-gradient(ellipse farthest-corner at " + gx + "px " + gy + "px , #ff3e00 5%, #ffff4b 50%, #3eff09 95%)");
    ff3e00
  };

  var game1 = new F7U12(4);
  game1.name = "00:24:44:dc:0b:25"; // Al's balance board
  game1.uuid = UUIDjs.create(1).toString();
  game1.init(2);
  game1.target = "#game1";
  game1.render(game1.target);

  var game2 = new F7U12(4);
  game2.name = "00:24:44:EE:56:A2"; // Patrick's balance board
  game2.uuid = UUIDjs.create(1).toString();
  game2.init(2);
  game2.target = "#game2";
  game2.render(game2.target);

  game3 = new F7U12(4);
  game3.name = "AI";
  game3.uuid = UUIDjs.create(1).toString();
  game3.init(2);
  game3.target = "#game3";
  game3.render(game3.target);
  game3.dash_update = function () {
    try {
      var id = DATA.recent_games.filter(function (d) { return d.player == "AI"; })[0];
      d3.json("/game/" + (id.game_id || "id-missing"), function (data) {
        game3.cells = data[data.length - 1].state;
        game3.update();
      });
    }
    catch (e) { console.log("Exception: ", e); }
  };
  WIDGETS.game3 = game3;

  var stream_bboard = function (game) {
    var sock = new WebSocket("ws://" + window.location.host + "/balance_board/" + game.name);
    sock.onerror = function (e) { console.log("socket error", e); };
    sock.onopen = function (e) {
      sock.onmessage = function(msg) {
        var bb = JSON.parse(msg.data);
        // direction may be 'none', unsupported by f7u12
        if (bb.direction == "up" || bb.direction == "down" || bb.direction == "left" || bb.direction == "right") {
          move(game, bb.direction);
        }
        colorize(game, bb);
      };
    };
  };

  // take input from balance board via a somewhat convoluted path
  stream_bboard(game1);
  stream_bboard(game2);

  d3.json("/top_games/human_topN", function (data) {
    DATA.human_topn = data;
    WIDGETS.human_leaderboard = new F7U12.Leaderboard("#human_topN_leaderboard", "Human Top 10");
    WIDGETS.human_leaderboard.render(DATA.human_topn);
    WIDGETS.human_leaderboard.dash_update = function () {
      WIDGETS.human_leaderboard.update(DATA.human_topn);
    };
  });

  d3.json("/top_games/ai_topN", function (data) {
    DATA.ai_topn = data;
    WIDGETS.ai_leaderboard = new F7U12.Leaderboard("#ai_topN_leaderboard", "AI Top 10");
    WIDGETS.ai_leaderboard.render(data);
    WIDGETS.ai_leaderboard.dash_update = function () {
      WIDGETS.ai_leaderboard.update(DATA.ai_topn);
    };
  });

  var svg1 = dimple.newSvg("#graph1", 600, 200);
  var svg2 = dimple.newSvg("#graph2", 600, 200);

  var split_counts = function (data) {
    var re = /^(ai|human)_(up|down|left|right)/;
    var ai_re = /^ai_(up|down|left|right)/;
    var human_re = /^human_(up|down|left|right)/;

    DATA.ai_moves = data.filter(function (d) { return ai_re.test(d.name); })
      .map(function (d) { return { name: d.name.replace(re, "$2"), value: d.value }; });

    DATA.human_moves = data.filter(function (d) { return human_re.test(d.name); })
      .map(function (d) { return { name: d.name.replace(re, "$2"), value: d.value }; });
  };

  d3.json("/counts", function (data) {
    split_counts(data);

    WIDGETS.ai_move_chart = new dimple.chart(svg2, DATA.ai_moves);
    WIDGETS.ai_move_chart.setBounds(60, 30, 440, 130);
    WIDGETS.ai_move_chart.addCategoryAxis("x", "name");
    WIDGETS.ai_move_chart.addMeasureAxis("y", "value");
    WIDGETS.ai_move_chart.addSeries("value", dimple.plot.bar);
    WIDGETS.ai_move_chart.draw();
    // TODO: actually wire up data in the update
    WIDGETS.ai_move_chart.dash_update = function () {
      WIDGETS.ai_move_chart.data = DATA.ai_moves;
      WIDGETS.ai_move_chart.draw();
    };

    WIDGETS.human_move_chart = new dimple.chart(svg1, DATA.human_moves);
    WIDGETS.human_move_chart.setBounds(60, 30, 440, 130);
    WIDGETS.human_move_chart.addCategoryAxis("x", "name");
    WIDGETS.human_move_chart.addMeasureAxis("y", "value");
    WIDGETS.human_move_chart.addSeries("value", dimple.plot.bar);
    WIDGETS.human_move_chart.draw();
    // TODO: actually wire up data in the update
    WIDGETS.human_move_chart.dash_update = function () {
      WIDGETS.human_move_chart.data = DATA.human_moves;
      WIDGETS.human_move_chart.draw();
    };

    // update both from here to save a little code
    WIDGETS.bignums = {};
    WIDGETS.bignums.dash_update = function () {
      ["human_games", "human_moves", "ai_games", "ai_moves"].forEach(function (name) {
        d3.select("#" + name)
          .data(DATA.counts.filter(function (d) { return d.name === name; }))
          .text(function (d) { return d.value; });
      });
    };
    WIDGETS.bignums.dash_update();
  });
});
// vim: et ts=2 sw=2 ai smarttab
<commit_msg>remove dead code<commit_after>/*
 * Copyright 2014 Albert P. Tobey <atobey@datastax.com> @AlTobey
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// one-time setup, creating elements, etc.
$(function() {
  // there are two timers, one fires XHRs to update data stored in DATA
  // the other updates content on the page using data in DATA
  // These will be out of sync a little but it should be no big deal
  // since the code below is written to keep them independent.
  // This should probably be replaced by some kind of library that
  // hooks up to websockets nicely, but for now this is good enough.
  var DATA = {};
  DATA.update = function () {
      d3.json("/counts", function (data) { DATA.counts = data; split_counts(data); });
      d3.json("/top_games/human_topN", function (data) { DATA.human_topn = data; });
      d3.json("/top_games/ai_topN", function (data) { DATA.ai_topn = data; });
      d3.json("/recent", function (data) { DATA.recent_games = data; });
      d3.json("/avg_score_by_turn", function (data) { DATA.avg_score_by_turn = data; });
  };
  DATA.update();

  // place all widgets here that should auto update
  var WIDGETS = {};

  // find all keys with a dash_update() method then call it
  WIDGETS.update = function () {
    d3.keys(WIDGETS).forEach(function (key) {
      if (typeof WIDGETS[key].dash_update === 'function') {
        WIDGETS[key].dash_update(WIDGETS[key]);
      }
    });
  };

  // use jquery.timer.js to update every second
  // TODO: add play/pause buttons?
  // these will run a litle out of sync and that's OK for now
  DATA.timer = $.timer(DATA.update, 1000, true);
  WIDGETS.timer = $.timer(WIDGETS.update, 200, true);

  var get_avg_score = function (turn) {
    return DATA.avg_score_by_turn.filter(function (v) {
      if (v.name === "human" && turn_id === turn) {
        return true;
      }
      return false;
    })[0];
  };

  var move = function (game, dir) {
    var changed = game.move(dir);
    if (!changed) {
      return;
    }

    var new_tile_idx = game.insert();
    $.ajax({
      url: "/grid",
      type: "PUT",
      dataType: "json",
      data: game.serialize(),
      success: function () { console.log("XHR Succeeded."); }
    });

    d3.select(game.target + "-score").text(game.score);
    d3.select(game.target + "-turn-id").text(game.sequence);
    d3.select(game.target + "-avg-score").text(get_avg_score(game.sequence));

    game.last_turn = performance.now();
  };

  // color the whole game div background by pressure with a gradient
  var colorize = function (game, bb) {
    var gx = 355 - Math.floor(355 * ((bb.lf_pcnt + bb.lr_pcnt)/100));
    var gy = 355 - Math.floor(355 * ((bb.lf_pcnt + bb.rf_pcnt)/100));
    d3.select(game.target + " .f7u12-grid").style("background", "radial-gradient(ellipse farthest-corner at " + gx + "px " + gy + "px , #ff3e00 5%, #ffff4b 50%, #3eff09 95%)");
  };

  var game1 = new F7U12(4);
  game1.name = "00:24:44:dc:0b:25"; // Al's balance board
  game1.uuid = UUIDjs.create(1).toString();
  game1.init(2);
  game1.target = "#game1";
  game1.render(game1.target);

  var game2 = new F7U12(4);
  game2.name = "00:24:44:EE:56:A2"; // Patrick's balance board
  game2.uuid = UUIDjs.create(1).toString();
  game2.init(2);
  game2.target = "#game2";
  game2.render(game2.target);

  game3 = new F7U12(4);
  game3.name = "AI";
  game3.uuid = UUIDjs.create(1).toString();
  game3.init(2);
  game3.target = "#game3";
  game3.render(game3.target);
  game3.dash_update = function () {
    try {
      var id = DATA.recent_games.filter(function (d) { return d.player == "AI"; })[0];
      d3.json("/game/" + (id.game_id || "id-missing"), function (data) {
        game3.cells = data[data.length - 1].state;
        game3.update();
      });
    }
    catch (e) { console.log("Exception: ", e); }
  };
  WIDGETS.game3 = game3;

  var stream_bboard = function (game) {
    var sock = new WebSocket("ws://" + window.location.host + "/balance_board/" + game.name);
    sock.onerror = function (e) { console.log("socket error", e); };
    sock.onopen = function (e) {
      sock.onmessage = function(msg) {
        var bb = JSON.parse(msg.data);
        // direction may be 'none', unsupported by f7u12
        if (bb.direction == "up" || bb.direction == "down" || bb.direction == "left" || bb.direction == "right") {
          move(game, bb.direction);
        }
        colorize(game, bb);
      };
    };
  };

  // take input from balance board via a somewhat convoluted path
  stream_bboard(game1);
  stream_bboard(game2);

  d3.json("/top_games/human_topN", function (data) {
    DATA.human_topn = data;
    WIDGETS.human_leaderboard = new F7U12.Leaderboard("#human_topN_leaderboard", "Human Top 10");
    WIDGETS.human_leaderboard.render(DATA.human_topn);
    WIDGETS.human_leaderboard.dash_update = function () {
      WIDGETS.human_leaderboard.update(DATA.human_topn);
    };
  });

  d3.json("/top_games/ai_topN", function (data) {
    DATA.ai_topn = data;
    WIDGETS.ai_leaderboard = new F7U12.Leaderboard("#ai_topN_leaderboard", "AI Top 10");
    WIDGETS.ai_leaderboard.render(data);
    WIDGETS.ai_leaderboard.dash_update = function () {
      WIDGETS.ai_leaderboard.update(DATA.ai_topn);
    };
  });

  var svg1 = dimple.newSvg("#graph1", 600, 200);
  var svg2 = dimple.newSvg("#graph2", 600, 200);

  var split_counts = function (data) {
    var re = /^(ai|human)_(up|down|left|right)/;
    var ai_re = /^ai_(up|down|left|right)/;
    var human_re = /^human_(up|down|left|right)/;

    DATA.ai_moves = data.filter(function (d) { return ai_re.test(d.name); })
      .map(function (d) { return { name: d.name.replace(re, "$2"), value: d.value }; });

    DATA.human_moves = data.filter(function (d) { return human_re.test(d.name); })
      .map(function (d) { return { name: d.name.replace(re, "$2"), value: d.value }; });
  };

  d3.json("/counts", function (data) {
    split_counts(data);

    WIDGETS.ai_move_chart = new dimple.chart(svg2, DATA.ai_moves);
    WIDGETS.ai_move_chart.setBounds(60, 30, 440, 130);
    WIDGETS.ai_move_chart.addCategoryAxis("x", "name");
    WIDGETS.ai_move_chart.addMeasureAxis("y", "value");
    WIDGETS.ai_move_chart.addSeries("value", dimple.plot.bar);
    WIDGETS.ai_move_chart.draw();
    // TODO: actually wire up data in the update
    WIDGETS.ai_move_chart.dash_update = function () {
      WIDGETS.ai_move_chart.data = DATA.ai_moves;
      WIDGETS.ai_move_chart.draw();
    };

    WIDGETS.human_move_chart = new dimple.chart(svg1, DATA.human_moves);
    WIDGETS.human_move_chart.setBounds(60, 30, 440, 130);
    WIDGETS.human_move_chart.addCategoryAxis("x", "name");
    WIDGETS.human_move_chart.addMeasureAxis("y", "value");
    WIDGETS.human_move_chart.addSeries("value", dimple.plot.bar);
    WIDGETS.human_move_chart.draw();
    // TODO: actually wire up data in the update
    WIDGETS.human_move_chart.dash_update = function () {
      WIDGETS.human_move_chart.data = DATA.human_moves;
      WIDGETS.human_move_chart.draw();
    };

    // update both from here to save a little code
    WIDGETS.bignums = {};
    WIDGETS.bignums.dash_update = function () {
      ["human_games", "human_moves", "ai_games", "ai_moves"].forEach(function (name) {
        d3.select("#" + name)
          .data(DATA.counts.filter(function (d) { return d.name === name; }))
          .text(function (d) { return d.value; });
      });
    };
    WIDGETS.bignums.dash_update();
  });
});
// vim: et ts=2 sw=2 ai smarttab
<|endoftext|>


<commit_before>/* global angular, console, BASE_URL */
angular.module('i-like-solar').controller('fbCtrl',
  function ($scope, $location, $timeout, $modal, $window, fb, salsa) {
    'use strict';

    $scope.alerts    = [];
    $scope.signedUp  = false;
    //looks for company in the query string
    $scope.company   = $location.search().company;
    //looks for source in the query string
    $scope.source    = $location.search().source;
    $scope.swFriends = true;

    $scope.signUpClass = 'medium-box';
    $scope.profileSolarized = false;
    $scope.coverSolarized   = false;

    $scope.companies = ['Clean Power Finance', 'Enphase', 'SolarCity', 'Sungevity', 'SunPower', 'Sunrun', 'Vivint Solar', 'Other'];
    if ($scope.companies.indexOf($scope.company) === -1) {
      $scope.company = null;
    }
    $scope.showDrop  = $scope.company === null ? true : false;
    $scope.loggedIn  = false;
    $scope.loading   = true;

    $scope.milestones = [{
      img: 'ms1.png',
      text: 'Sign in with Facebook',
      target: ''
    },{
      img: 'ms2.png',
      text: 'Solarize your profile',
      target: '#step-2'
    },{
      img: 'ms3.png',
      text: 'Share your solar story',
      target: '#step-3'
    }];

    $scope.largeMilestones = ['large2.png', 'large3.png'];

    $scope.profileUrl = BASE_URL + '/img/profile.jpg';
    $scope.coverUrl   = BASE_URL + '/img/example-cover.png';

    var id, token;

    fb.getLoginStatus(function (res) {
      $scope.loading = false;
      if (res.status === 'connected') {
        id = res.authResponse.userID;
        token = res.authResponse.accessToken;
        loadApp();
      }
    });

    $scope.scrollToTop = function() {
      $window.scrollTo($window.scrollX, 0);
    };

    $scope.login = function () {
      $scope.joining = true;
      fb.login(function (res) {
        $scope.joining = true;
        if (res.authResponse) {
          id = res.authResponse.userID;
          token = res.authResponse.accessToken;
          $scope.loggedIn = true;
          loadApp();
          createAlert('success', 'Congrats! Thanks for joining!');
        } else {
          $scope.joining = false;
          // createAlert('error', 'Oops, Something went wrong. Try again!');
        }
//      }, 'publish_actions');
      });
    };

	$scope.postFeed = function(){
    if (!$scope.signedUp) return createAlert('error', 'You haven\'t signed up yet!');

    var sunUrl = BASE_URL;
    if (sunUrl.indexOf(':4000') !== -1)
      sunUrl = 'https:' + sunUrl;
    else
      sunUrl = 'http:' + sunUrl;

		var publish = {
     method: 'feed',
		 name: 'I LIKE SOLAR',
		 link: 'https://apps.facebook.com/i_like_solar/',
		 picture: sunUrl,
		 caption: 'Share your story',
		 description: 'Solar is getting smarter! Did you know your friends could get solar 3x faster if they know you have solar? Share your solar story to help multiply solar power in your community. via I LIKE SOLAR.',
		};

		fb.ui(publish,  function(res){
			if (res && res.post_id) {
          createAlert('success', 'Your post was successful');
          $scope.milestones[2].img = 'ms3-filled.png';
          $scope.largeMilestones[1] = 'large3-filled.png';
          $scope.$apply();
      } else {
				//createAlert('error', 'Oops, Something went wrong. Try again!');
			}
		});
	};

	$scope.requestFriends = function(){
    if (!$scope.signedUp) return createAlert('error', 'You haven\'t signed up yet!');
		var publish = {
		  method: 'apprequests',
		  message: 'Do your solar panels make a difference? Please join I LIKE SOLAR to share the benefits of your solar with your friends.',
		  title: 'Invite your friends with solar to I LIKE SOLAR'
		};
		fb.ui(publish,  function(res){
			 if (res.request && res.to) {
				var numFriends = res.to.length;
				var f = numFriends >= 2 ? ' friends' : ' friend';
				createAlert('success', 'Your request was sent to '+numFriends+f+'.');
			  } else {
				createAlert('error', 'Oops, Something went wrong. Try again!');
			  }
		});
	};

    $scope.verify = function (company, company2) {
      return company === 'Other' ? !company2 : !company;
    };

    $scope.saveOptions = function (company, company2, swFriends, swFoF, source) {
      $scope.saving = true;
      var obj = {
        id:      id,
        token:   token,
        company: company !== 'Other' ? company : company2,
        source:  source,
        privacy: {
          friends: swFriends,
          friendsOfFriends: swFoF
        }
      };

      salsa.saveOptions(obj, function (err) {
        $scope.saving = false;
        if (err) {
          createAlert('error', 'Oops, something went wrong.');
          return console.error(err);
        }
        $scope.permissionModal.close();
        createAlert('success', 'Your info has been saved!');
      });
    };

    function solarizeProfilePhoto() {
      fb.getProfileUrl(function (res) {
        var profileUrl = res.data.url;
        fb.createProfilePhoto(profileUrl, $scope.userId, function (data) {
          var picUrl = BASE_URL + data.url;
          $scope.profileUrl = picUrl;
        });
      });
    }

    function solarizeCoverPhoto() {
      fb.getCoverUrl(function (res) {
        var coverUrl = res.cover.source;
		var offset = res.cover.offset_y;
        fb.createCoverPhoto(coverUrl, offset, $scope.userId, function (data) {
          var picUrl = BASE_URL + data.url;
          $scope.coverUrl = picUrl;
        });
      });
    }

    $scope.uploadToFacebook = function(picture) {
      if (!$scope.signedUp) return createAlert('error', 'You haven\'t signed up yet!');
      $scope[picture + 'Uploading'] = true;
      var img = picture === 'profile' ? $scope.profileUrl : $scope.coverUrl;
      fb.uploadPhoto(img, function (resp) {
        if (resp.error) return createAlert('error', resp.error.message);
        $scope[picture + 'Solarized'] = true;
        $scope.uploading = false;
        if (picture == 'profile') {
           $scope.solarized_url = 'https://www.facebook.com/photo.php?fbid=' + resp.id;
		} else {
           $scope.solarized_cover_url = 'https://www.facebook.com/photo.php?fbid=' + resp.id;
		}
        $scope.milestones[1].img = 'ms2-filled.png';
        $scope.largeMilestones[0] = 'large2-filled.png';
        createAlert('success', 'Profile photo successfully uploaded!');
        $scope.$apply();
      });
    };

    function loadApp() {
      var gotName = false;
      var gotOptions = false;

      $scope.loggedIn = true;
      // $scope.loading = false;
      fb.getUser(function (res) {
        $scope.userId = res.id || null;
        $scope.name = res.first_name || res.name;
        gotName = true;
        $scope.signedUp = true;
        $scope.signUpClass = 'small-box';
        $scope.milestones[0].img = 'ms1-filled.png';
        solarizeProfilePhoto();
        solarizeCoverPhoto();
        if (gotOptions) $scope.loading = false;
      });

      salsa.getOptions({ id: id, token: token }, function (err, data) {
        gotOptions = true;
        if (!gotName) $scope.loading = false;
        if (err) return showModal();
        $scope.company = data.company;

        $scope.swFriends = data.privacy.friends;
        $scope.swFoF = data.privacy.friendsOfFriends;
        console.log($scope.swFriends, $scope.swFoF);
      });
    }

    function showModal() {
      $scope.permissionModal = $modal.open({
        templateUrl: 'permissions.html',
        scope: $scope
      });
    }

    $scope.unsubscribe = function() {
      fb.revokelogin(function (res) {
		  createAlert('success', 'You have removed I Like Solar.');
	  });
	  salsa.deleteUser($scope.userId, function(err) {
        if (err) return createAlert('error', 'User does not exist or was not removed.');
        createAlert('success', 'You have successfully unsubscribed.');
      });
    };

    function createAlert(type, msg) {
      var alert = {
        type: type,
        msg: msg
      };

      $scope.alerts.push(alert);
      $timeout(function () {
        var index = $scope.alerts.indexOf(alert);
        $scope.alerts.splice(index, 1);
      }, 2000);
    }
  }
);
<commit_msg>Reload after unsubscribe<commit_after>/* global angular, console, BASE_URL */
angular.module('i-like-solar').controller('fbCtrl',
  function ($scope, $location, $timeout, $modal, $window, fb, salsa) {
    'use strict';

    $scope.alerts    = [];
    $scope.signedUp  = false;
    //looks for company in the query string
    $scope.company   = $location.search().company;
    //looks for source in the query string
    $scope.source    = $location.search().source;
    $scope.swFriends = true;

    $scope.signUpClass = 'medium-box';
    $scope.profileSolarized = false;
    $scope.coverSolarized   = false;

    $scope.companies = ['Clean Power Finance', 'Enphase', 'SolarCity', 'Sungevity', 'SunPower', 'Sunrun', 'Vivint Solar', 'Other'];
    if ($scope.companies.indexOf($scope.company) === -1) {
      $scope.company = null;
    }
    $scope.showDrop  = $scope.company === null ? true : false;
    $scope.loggedIn  = false;
    $scope.loading   = true;

    $scope.milestones = [{
      img: 'ms1.png',
      text: 'Sign in with Facebook',
      target: ''
    },{
      img: 'ms2.png',
      text: 'Solarize your profile',
      target: '#step-2'
    },{
      img: 'ms3.png',
      text: 'Share your solar story',
      target: '#step-3'
    }];

    $scope.largeMilestones = ['large2.png', 'large3.png'];

    $scope.profileUrl = BASE_URL + '/img/profile.jpg';
    $scope.coverUrl   = BASE_URL + '/img/example-cover.png';

    var id, token;

    fb.getLoginStatus(function (res) {
      $scope.loading = false;
      if (res.status === 'connected') {
        id = res.authResponse.userID;
        token = res.authResponse.accessToken;
        loadApp();
      }
    });

    $scope.scrollToTop = function() {
      $window.scrollTo($window.scrollX, 0);
    };

    $scope.login = function () {
      $scope.joining = true;
      fb.login(function (res) {
        $scope.joining = true;
        if (res.authResponse) {
          id = res.authResponse.userID;
          token = res.authResponse.accessToken;
          $scope.loggedIn = true;
          loadApp();
          createAlert('success', 'Congrats! Thanks for joining!');
        } else {
          $scope.joining = false;
          // createAlert('error', 'Oops, Something went wrong. Try again!');
        }
//      }, 'publish_actions');
      });
    };

	$scope.postFeed = function(){
    if (!$scope.signedUp) return createAlert('error', 'You haven\'t signed up yet!');

    var sunUrl = BASE_URL;
    if (sunUrl.indexOf(':4000') !== -1)
      sunUrl = 'https:' + sunUrl;
    else
      sunUrl = 'http:' + sunUrl;

		var publish = {
     method: 'feed',
		 name: 'I LIKE SOLAR',
		 link: 'https://apps.facebook.com/i_like_solar/',
		 picture: sunUrl,
		 caption: 'Share your story',
		 description: 'Solar is getting smarter! Did you know your friends could get solar 3x faster if they know you have solar? Share your solar story to help multiply solar power in your community. via I LIKE SOLAR.',
		};

		fb.ui(publish,  function(res){
			if (res && res.post_id) {
          createAlert('success', 'Your post was successful');
          $scope.milestones[2].img = 'ms3-filled.png';
          $scope.largeMilestones[1] = 'large3-filled.png';
          $scope.$apply();
      } else {
				//createAlert('error', 'Oops, Something went wrong. Try again!');
			}
		});
	};

	$scope.requestFriends = function(){
    if (!$scope.signedUp) return createAlert('error', 'You haven\'t signed up yet!');
		var publish = {
		  method: 'apprequests',
		  message: 'Do your solar panels make a difference? Please join I LIKE SOLAR to share the benefits of your solar with your friends.',
		  title: 'Invite your friends with solar to I LIKE SOLAR'
		};
		fb.ui(publish,  function(res){
			 if (res.request && res.to) {
				var numFriends = res.to.length;
				var f = numFriends >= 2 ? ' friends' : ' friend';
				createAlert('success', 'Your request was sent to '+numFriends+f+'.');
			  } else {
				createAlert('error', 'Oops, Something went wrong. Try again!');
			  }
		});
	};

    $scope.verify = function (company, company2) {
      return company === 'Other' ? !company2 : !company;
    };

    $scope.saveOptions = function (company, company2, swFriends, swFoF, source) {
      $scope.saving = true;
      var obj = {
        id:      id,
        token:   token,
        company: company !== 'Other' ? company : company2,
        source:  source,
        privacy: {
          friends: swFriends,
          friendsOfFriends: swFoF
        }
      };

      salsa.saveOptions(obj, function (err) {
        $scope.saving = false;
        if (err) {
          createAlert('error', 'Oops, something went wrong.');
          return console.error(err);
        }
        $scope.permissionModal.close();
        createAlert('success', 'Your info has been saved!');
      });
    };

    function solarizeProfilePhoto() {
      fb.getProfileUrl(function (res) {
        var profileUrl = res.data.url;
        fb.createProfilePhoto(profileUrl, $scope.userId, function (data) {
          var picUrl = BASE_URL + data.url;
          $scope.profileUrl = picUrl;
        });
      });
    }

    function solarizeCoverPhoto() {
      fb.getCoverUrl(function (res) {
        var coverUrl = res.cover.source;
		var offset = res.cover.offset_y;
        fb.createCoverPhoto(coverUrl, offset, $scope.userId, function (data) {
          var picUrl = BASE_URL + data.url;
          $scope.coverUrl = picUrl;
        });
      });
    }

    $scope.uploadToFacebook = function(picture) {
      if (!$scope.signedUp) return createAlert('error', 'You haven\'t signed up yet!');
      $scope[picture + 'Uploading'] = true;
      var img = picture === 'profile' ? $scope.profileUrl : $scope.coverUrl;
      fb.uploadPhoto(img, function (resp) {
        if (resp.error) return createAlert('error', resp.error.message);
        $scope[picture + 'Solarized'] = true;
        $scope.uploading = false;
        if (picture == 'profile') {
           $scope.solarized_url = 'https://www.facebook.com/photo.php?fbid=' + resp.id;
		} else {
           $scope.solarized_cover_url = 'https://www.facebook.com/photo.php?fbid=' + resp.id;
		}
        $scope.milestones[1].img = 'ms2-filled.png';
        $scope.largeMilestones[0] = 'large2-filled.png';
        createAlert('success', 'Profile photo successfully uploaded!');
        $scope.$apply();
      });
    };

    function loadApp() {
      var gotName = false;
      var gotOptions = false;

      $scope.loggedIn = true;
      // $scope.loading = false;
      fb.getUser(function (res) {
        $scope.userId = res.id || null;
        $scope.name = res.first_name || res.name;
        gotName = true;
        $scope.signedUp = true;
        $scope.signUpClass = 'small-box';
        $scope.milestones[0].img = 'ms1-filled.png';
        solarizeProfilePhoto();
        solarizeCoverPhoto();
        if (gotOptions) $scope.loading = false;
      });

      salsa.getOptions({ id: id, token: token }, function (err, data) {
        gotOptions = true;
        if (!gotName) $scope.loading = false;
        if (err) return showModal();
        $scope.company = data.company;

        $scope.swFriends = data.privacy.friends;
        $scope.swFoF = data.privacy.friendsOfFriends;
        console.log($scope.swFriends, $scope.swFoF);
      });
    }

    function showModal() {
      $scope.permissionModal = $modal.open({
        templateUrl: 'permissions.html',
        scope: $scope
      });
    }

    $scope.unsubscribe = function() {
      fb.revokelogin(function (res) {
		  createAlert('success', 'You have removed I Like Solar.');
	  });
	  salsa.deleteUser($scope.userId, function(err) {
        if (err) return createAlert('error', 'User does not exist or was not removed.');
        createAlert('success', 'You have successfully unsubscribed.');
		setTimeout(function () {location.reload(true);}, 3000);
      });
    };

    function createAlert(type, msg) {
      var alert = {
        type: type,
        msg: msg
      };

      $scope.alerts.push(alert);
      $timeout(function () {
        var index = $scope.alerts.indexOf(alert);
        $scope.alerts.splice(index, 1);
      }, 2000);
    }
  }
);
<|endoftext|>


<commit_before>
/**
 * Navigation
 */

/* Auto close navbar on click (mobile menu) */

$(".navbar-nav > li > a").click(function() {
    $(".navbar-collapse").collapse('hide');
});

/* Change navbar class on scroll */

$(".wrapper").waypoint(function() {
    $(".navbar").toggleClass("js-navbar-top");
    $(".navbar.js-toggleClass").toggleClass("navbar-default navbar-inverse");
    return false;
}, { offset: "-20px" });

/* Change navbar class on collapse/uncollapse in its top position */

$('.wrapper .navbar-collapse').on('show.bs.collapse', function () {
    $(".navbar.js-navbar-top").toggleClass("navbar-default navbar-inverse");
    $(".navbar").toggleClass("js-toggleClass js-noToggleClass");
});

$('.wrapper .navbar-collapse').on('hide.bs.collapse', function () {
    $(".navbar.js-navbar-top").toggleClass("navbar-default navbar-inverse");
    $(".navbar").toggleClass("js-toggleClass js-noToggleClass");
});

/* Sidebar */

$(".js-toggle-sidebar").on('click', function() {
    $(".wrapper").toggleClass("js-wrapper-aside");
    $(".navbar").toggleClass("js-navbar-aside");
    $(".sidebar").toggleClass("js-sidebar-aside");
    return false;
});

/**
 * Smooth scroll to anchor
 */

$(function() {
    $('a[href*=#]:not([href=#])').click(function() {
        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
            var target = $(this.hash);
            target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
            if (target.length) {
                $('html,body').animate({
                    scrollTop: (target.offset().top - 70) // 70px offset for navbar menu
                }, 1000);
                return false;
            }
        }
    });
});

// Bootstrap Custom JS
$(document).ready(function() {

  // Tooltip opt-in
  $('[data-toggle="tooltip"]').tooltip()

  // Carousel controls
  $('.carousel-control.left').click(function() {
    $('#myCarousel').carousel('prev');
  });

  $('.carousel-control.right').click(function() {
    $('#myCarousel').carousel('next');
  });

  // About Us Show full Bio
  $('#jmbutton').click(function () {
    $('#jmbio').collapse('toggle');
  });
  $('#kmbutton').click(function () {
    $('#kmbio').collapse('toggle');
  });
  $('#dpbutton').click(function () {
    $('#dpbio').collapse('toggle');
  });
  $('#dgbutton').click(function () {
    $('#dgbio').collapse('toggle');
  });

  // Hide full Bio details
  $('body').click(function() {
    $('.collapse').collapse('hide');
  });

});

/**
 * Own carousel :: Sponsors
 */

// $(document).ready(function() {
//   var owl = $('.owl-carousel');
//   owl.owlCarousel({
//       items:4,
//       loop:true,
//       margin:5,
//       responsiveBaseElement:".owl-wrapper",
//       autoplay:true,
//       autoplayTimeout:1000,
//       autoplayHoverPause:true
//   });
// });
/**
 * Doughnut charts :: Skills
 */

/* Base donut styles */

// $.fn.peity.defaults.donut = {
//     delimiter: null,
//     fill: ["#F67280", "#eee"],
//     height: null,
//     innerRadius: 68,
//     radius: 70,
//     width: null
// };

/* Animating donuts */

// $(document).ready(function() {
//     $(".js-skills__item_first").waypoint(function() {
//
//         setTimeout(function () {
//             $('.skills__item').css("visibility", "visible");
//         }, 11);
//
//         $('.skills-item__donut').each(function () {
//             var $this = $(this);
//
//             var updateChart = $this.peity('donut');
//             var text = "";
//             var i = 0;
//             var str = $this.html();
//             var arr = str.split("/");
//             var value = arr[0];
//             var maxValue = arr[1];
//             var step = value/100;
//
//             function myLoop() {
//                 setTimeout(function () {
//
//                     text = i + "/" + maxValue;
//
//                     updateChart.text(text)
//                         .change()
//
//                     i = i + step;
//
//                     if (i <= value) myLoop();
//
//                 }, 10)
//             }
//             myLoop();
//         });
//
//         this.destroy();
//
//     }, { offset: 'bottom-in-view' });
// });

// Wow Plugins

$(".wow").each(function() {
    var wowHeight = $(this).height();
    $(this).attr("data-wow-offset", wowHeight);
});

new WOW().init();

// E-mail submittal to Formspree
$(document).ready(function() {

  $( "#form" ).submit(function( event ) {
    $.ajax({
      url: "//formspree.io/darrenjack79@yahoo.com",
      method: "POST",
      data: $(this).serialize(),
      dataType: 'json',
    });
  });

});
<commit_msg>changed back to original formspree e-mail<commit_after>
/**
 * Navigation
 */

/* Auto close navbar on click (mobile menu) */

$(".navbar-nav > li > a").click(function() {
    $(".navbar-collapse").collapse('hide');
});

/* Change navbar class on scroll */

$(".wrapper").waypoint(function() {
    $(".navbar").toggleClass("js-navbar-top");
    $(".navbar.js-toggleClass").toggleClass("navbar-default navbar-inverse");
    return false;
}, { offset: "-20px" });

/* Change navbar class on collapse/uncollapse in its top position */

$('.wrapper .navbar-collapse').on('show.bs.collapse', function () {
    $(".navbar.js-navbar-top").toggleClass("navbar-default navbar-inverse");
    $(".navbar").toggleClass("js-toggleClass js-noToggleClass");
});

$('.wrapper .navbar-collapse').on('hide.bs.collapse', function () {
    $(".navbar.js-navbar-top").toggleClass("navbar-default navbar-inverse");
    $(".navbar").toggleClass("js-toggleClass js-noToggleClass");
});

/* Sidebar */

$(".js-toggle-sidebar").on('click', function() {
    $(".wrapper").toggleClass("js-wrapper-aside");
    $(".navbar").toggleClass("js-navbar-aside");
    $(".sidebar").toggleClass("js-sidebar-aside");
    return false;
});

/**
 * Smooth scroll to anchor
 */

$(function() {
    $('a[href*=#]:not([href=#])').click(function() {
        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
            var target = $(this.hash);
            target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
            if (target.length) {
                $('html,body').animate({
                    scrollTop: (target.offset().top - 70) // 70px offset for navbar menu
                }, 1000);
                return false;
            }
        }
    });
});

// Bootstrap Custom JS
$(document).ready(function() {

  // Tooltip opt-in
  $('[data-toggle="tooltip"]').tooltip()

  // Carousel controls
  $('.carousel-control.left').click(function() {
    $('#myCarousel').carousel('prev');
  });

  $('.carousel-control.right').click(function() {
    $('#myCarousel').carousel('next');
  });

  // About Us Show full Bio
  $('#jmbutton').click(function () {
    $('#jmbio').collapse('toggle');
  });
  $('#kmbutton').click(function () {
    $('#kmbio').collapse('toggle');
  });
  $('#dpbutton').click(function () {
    $('#dpbio').collapse('toggle');
  });
  $('#dgbutton').click(function () {
    $('#dgbio').collapse('toggle');
  });

  // Hide full Bio details
  $('body').click(function() {
    $('.collapse').collapse('hide');
  });

});

/**
 * Own carousel :: Sponsors
 */

// $(document).ready(function() {
//   var owl = $('.owl-carousel');
//   owl.owlCarousel({
//       items:4,
//       loop:true,
//       margin:5,
//       responsiveBaseElement:".owl-wrapper",
//       autoplay:true,
//       autoplayTimeout:1000,
//       autoplayHoverPause:true
//   });
// });
/**
 * Doughnut charts :: Skills
 */

/* Base donut styles */

// $.fn.peity.defaults.donut = {
//     delimiter: null,
//     fill: ["#F67280", "#eee"],
//     height: null,
//     innerRadius: 68,
//     radius: 70,
//     width: null
// };

/* Animating donuts */

// $(document).ready(function() {
//     $(".js-skills__item_first").waypoint(function() {
//
//         setTimeout(function () {
//             $('.skills__item').css("visibility", "visible");
//         }, 11);
//
//         $('.skills-item__donut').each(function () {
//             var $this = $(this);
//
//             var updateChart = $this.peity('donut');
//             var text = "";
//             var i = 0;
//             var str = $this.html();
//             var arr = str.split("/");
//             var value = arr[0];
//             var maxValue = arr[1];
//             var step = value/100;
//
//             function myLoop() {
//                 setTimeout(function () {
//
//                     text = i + "/" + maxValue;
//
//                     updateChart.text(text)
//                         .change()
//
//                     i = i + step;
//
//                     if (i <= value) myLoop();
//
//                 }, 10)
//             }
//             myLoop();
//         });
//
//         this.destroy();
//
//     }, { offset: 'bottom-in-view' });
// });

// Wow Plugins

$(".wow").each(function() {
    var wowHeight = $(this).height();
    $(this).attr("data-wow-offset", wowHeight);
});

new WOW().init();

// E-mail submittal to Formspree
$(document).ready(function() {

  $( "#form" ).submit(function( event ) {
    $.ajax({
      url: "//formspree.io/jmatthews@thegreatacademy.org",
      method: "POST",
      data: $(this).serialize(),
      dataType: 'json',
    });
  });

});
<|endoftext|>


<commit_before>;jQuery(document).ready(function($) {
  $("#voice-text").val("");
  magic.loadCanvas('playground')
  magic.loadBg()
  $('#image4doodle').change(magic.loadImageFile)
  //$('#addAnimation').click(magic.addAnimation)
  $('#_addAnimation').click(function() {
    $('#_addLeftAnimation').addClass("disabled")
    $('#_addRightAnimation').addClass("disabled")
    $('#_addBottomTopAnimation').addClass("disabled")
  	magic.startRecordInWorker()
  })
  $('#_addLeftAnimation').click(function() {
    $('#_addAnimation').addClass("disabled")
    $('#_addRightAnimation').addClass("disabled")
    $('#_addBottomTopAnimation').addClass("disabled")
    magic.startRecordInWorker("", "fan")})
  $('#_addRightAnimation').click(function() {
    $('#_addAnimation').addClass("disabled")
    $('#_addLeftAnimation').addClass("disabled")
    $('#_addBottomTopAnimation').addClass("disabled")
    magic.startRecordInWorker("", "train")})
  $('#_addBottomTopAnimation').click(function() {
    $('#_addAnimation').addClass("disabled")
    $('#_addLeftAnimation').addClass("disabled")
    $('#_addRightAnimation').addClass("disabled")
    magic.startRecordInWorker("", "shuttle")})

  //$('#startRecord').click(magic.startStopRecord)
  $('#preview').click(magic.preview)
  $('#view_text').click(magic.drawText)
  // Init for text magic
  textMagic.init({canvasId: 'playground',
                finished: function() { console.log('Done')},
                background: 'public/images/doodle.gif',
                text: 'Google'
  })
  $("#addTextMagic").click(textMagic.startTransform)

  $("#voice-icon").click(function(e){
    $(e.target).hide();
    $("#voice-icon-disabled").show();
    $("#voice-text").val("");
    $("#voice-text").focus();
  });
  $("#voice-text").change(function(e){
    alert(e.target.value);
    var animations = [{ id: "train", hashtags: ["one","ten", "train", "dan", "man", "xe lửa", "tàu hoả"], image_url: "public/images/train.png", method: "magic.addTrain();" },
                      { id: "fan", hashtags: ["happy", "fan", "gió", "cối xay gió", "windmill"], image_url: "public/images/train.png", method: "magic.addFan();"},
                      { id: "shuttle", hashtags: ["shuttle", "tên lửa", "hoả tiển"], image_url: "public/images/train.png", method: "magic.addShuttle();"},
                      { id: "dove", hashtags: ["bồ câu", "chim bồ câu", "chim", "bird", "dove"], image_url: "public/images/train.png", method: "magic.addDove();"}];
    var current_animations = _.filter(animations, function(a){return a["hashtags"].indexOf(e.target.value.toLowerCase()) >= 0 });
    if (current_animations.length == 0){
      var hashtags = _.flatten(_.map(animations, function(a){return a["hashtags"]})).join(", ");
      alert("We only support the keywords: " + _.map(animations, function(a){return hashtags}));
      $("#voice-icon").show();
      $("#voice-icon-disabled").hide();
    }
    else{
      eval(current_animations[0]["method"]);
    }
  });

});
$(window).resize( magic.respondCanvas );
<commit_msg>update for image<commit_after>;jQuery(document).ready(function($) {
  $("#voice-text").val("");
  magic.loadCanvas('playground')
  magic.loadBg()
  $('#image4doodle').change(magic.loadImageFile)
  //$('#addAnimation').click(magic.addAnimation)
  $('#_addAnimation').click(function() {
    $('#_addLeftAnimation').addClass("disabled")
    $('#_addRightAnimation').addClass("disabled")
    $('#_addBottomTopAnimation').addClass("disabled")
  	magic.startRecordInWorker()
  })
  $('#_addLeftAnimation').click(function() {
    $('#_addAnimation').addClass("disabled")
    $('#_addRightAnimation').addClass("disabled")
    $('#_addBottomTopAnimation').addClass("disabled")
    magic.startRecordInWorker("", "fan")})
  $('#_addRightAnimation').click(function() {
    $('#_addAnimation').addClass("disabled")
    $('#_addLeftAnimation').addClass("disabled")
    $('#_addBottomTopAnimation').addClass("disabled")
    magic.startRecordInWorker("", "train")})
  $('#_addBottomTopAnimation').click(function() {
    $('#_addAnimation').addClass("disabled")
    $('#_addLeftAnimation').addClass("disabled")
    $('#_addRightAnimation').addClass("disabled")
    magic.startRecordInWorker("", "shuttle")})

  //$('#startRecord').click(magic.startStopRecord)
  $('#preview').click(magic.preview)
  $('#view_text').click(magic.drawText)
  // Init for text magic
  textMagic.init({canvasId: 'playground',
                finished: function() { console.log('Done')},
                background: 'public/images/magic/sample_doodle.png',
                text: 'Google'
  })
  $("#addTextMagic").click(textMagic.startTransform)

  $("#voice-icon").click(function(e){
    $(e.target).hide();
    $("#voice-icon-disabled").show();
    $("#voice-text").val("");
    $("#voice-text").focus();
  });
  $("#voice-text").change(function(e){
    alert(e.target.value);
    var animations = [{ id: "train", hashtags: ["one","ten", "train", "dan", "man", "xe lửa", "tàu hoả"], image_url: "public/images/train.png", method: "magic.addTrain();" },
                      { id: "fan", hashtags: ["happy", "fan", "gió", "cối xay gió", "windmill"], image_url: "public/images/train.png", method: "magic.addFan();"},
                      { id: "shuttle", hashtags: ["shuttle", "tên lửa", "hoả tiển"], image_url: "public/images/train.png", method: "magic.addShuttle();"},
                      { id: "dove", hashtags: ["bồ câu", "chim bồ câu", "chim", "bird", "dove"], image_url: "public/images/train.png", method: "magic.addDove();"}];
    var current_animations = _.filter(animations, function(a){return a["hashtags"].indexOf(e.target.value.toLowerCase()) >= 0 });
    if (current_animations.length == 0){
      var hashtags = _.flatten(_.map(animations, function(a){return a["hashtags"]})).join(", ");
      alert("We only support the keywords: " + _.map(animations, function(a){return hashtags}));
      $("#voice-icon").show();
      $("#voice-icon-disabled").hide();
    }
    else{
      eval(current_animations[0]["method"]);
    }
  });

});
$(window).resize( magic.respondCanvas );
<|endoftext|>


<commit_before>var Pathfinder = {
  moveTowards: function(friendlyLocation, currentPosition, speed){
    var deltaY = friendlyLocation.y - currentPosition.y;
    var deltaX = friendlyLocation.x - currentPosition.x;
    var length = distanceTo(friendlyLocation);
    if (speed > 0 && length < speed){
      return friendlyLocation
    } else {
      return {'x': (currentPosition.x + (deltaX / length * speed)),'y': (currentPosition.y + (deltaY / length * speed))}
    }
  },
  movePerpendicularTo: function(friendlyLocation, currentPosition, speed){
    var deltaY = location.y - currentPosition.y;
    var deltaX = location.x - currentPosition.x;
    var length = distanceTo(friendlyLocation);
    if (speed > 0 && length < speed){
      return friendlyLocation
    } else {
      return {'x': (currentPosition.x + (deltaX / length * speed)),'y': (currentPosition.y - (deltaY / length * speed))}
    }
  },

  moveAwayFrom: function(currentPosition, hostileLocation, speed){
    Pathfinder.moveTowards(currentPosition, hostileLocation, -speed);
  },

  distanceTo: function(targetLocation, currentPosition){
    var deltaY = targetLocation.y - currentPosition.y;
    var deltaX = targetLocation.x - currentPosition.x;
    return Math.pow(deltaY,2) + Math.pow(deltaX,2)
  },

  moveRandomly: function(currentPosition, speed){
    angle = Math.random() * 2 * Math.PI;
      return {'x': (currentPosition.x + Math.cos(angle) * speed),'y': (currentPosition.y + Math.sin(angle) * speed)}
  },
}<commit_msg>update pathfinder.js to friendlyLocation<commit_after>var Pathfinder = {
  moveTowards: function(friendlyLocation, currentPosition, speed){
    var deltaY = friendlyLocation.y - currentPosition.y;
    var deltaX = friendlyLocation.x - currentPosition.x;
    var length = distanceTo(friendlyLocation);
    if (speed > 0 && length < speed){
      return friendlyLocation
    } else {
      return {'x': (currentPosition.x + (deltaX / length * speed)),'y': (currentPosition.y + (deltaY / length * speed))}
    }
  },
  movePerpendicularTo: function(friendlyLocation, currentPosition, speed){
    var deltaY = friendlyLocation.y - currentPosition.y;
    var deltaX = friendlyLocation.x - currentPosition.x;
    var length = distanceTo(friendlyLocation);
    if (speed > 0 && length < speed){
      return friendlyLocation
    } else {
      return {'x': (currentPosition.x + (deltaX / length * speed)),'y': (currentPosition.y - (deltaY / length * speed))}
    }
  },

  moveAwayFrom: function(currentPosition, hostileLocation, speed){
    Pathfinder.moveTowards(currentPosition, hostileLocation, -speed);
  },

  distanceTo: function(targetLocation, currentPosition){
    var deltaY = targetLocation.y - currentPosition.y;
    var deltaX = targetLocation.x - currentPosition.x;
    return Math.pow(deltaY,2) + Math.pow(deltaX,2)
  },

  moveRandomly: function(currentPosition, speed){
    angle = Math.random() * 2 * Math.PI;
      return {'x': (currentPosition.x + Math.cos(angle) * speed),'y': (currentPosition.y + Math.sin(angle) * speed)}
  },
}<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import { propTypes } from '../react-props-decorators.js';

import styles from './RowView.scss';

import assign from 'lodash/object/assign';
import ResizeSensor from 'css-element-queries/src/ResizeSensor';
import { calculateRowLength } from './Utils';

import RowItem from './RowItem.js';

@propTypes({
    sequenceData: PropTypes.object.isRequired,
    columnWidth: PropTypes.number
})
export default class RowView extends React.Component {

    constructor(props) {
        super(props);

        this.state = {};
    }

    _populateRows() {
        var {
            sequenceData,
            columnWidth
        } = this.props;

        var {
            fontMeasure,
            rowMeasure
        } = this.refs;

        var charWidth = fontMeasure.getBoundingClientRect().width;
        var viewWidth = rowMeasure.sequenceContainerWidth();

        var rowLength = calculateRowLength(charWidth, viewWidth, columnWidth);

        var rowItems = [];

        for (let i = 0; i < sequenceData.size; i += rowLength) {
            var rowData = assign({}, sequenceData);
            rowData.sequence = rowData.sequence.substr(i, rowLength);
            rowItems.push((
                <RowItem sequenceData={rowData} columnWidth={columnWidth} />
            ));
        }

        this.setState({ rowItems: rowItems });
    }

    componentDidMount() {
        new ResizeSensor(this.refs.rowView, this._populateRows.bind(this));
        this._populateRows();
    }

    render() {
        var {
            rowItems
        } = this.state;

        return (

m

                <RowItem ref={'rowMeasure'} sequenceData={{ sequence: '' }} className={styles.rowMeasure} />
                {rowItems}

        );
    }

}
<commit_msg>move all JSX into render()<commit_after>import React, { PropTypes } from 'react';
import { propTypes } from '../react-props-decorators.js';

import styles from './RowView.scss';

import assign from 'lodash/object/assign';
import ResizeSensor from 'css-element-queries/src/ResizeSensor';
import { calculateRowLength } from './Utils';

import RowItem from './RowItem.js';

@propTypes({
    sequenceData: PropTypes.object.isRequired,
    columnWidth: PropTypes.number
})
export default class RowView extends React.Component {

    constructor(props) {
        super(props);

        this.state = {
            rowData: []
        };
    }

    _populateRows() {
        var {
            sequenceData,
            columnWidth
        } = this.props;

        var {
            fontMeasure,
            rowMeasure
        } = this.refs;

        var charWidth = fontMeasure.getBoundingClientRect().width;
        var viewWidth = rowMeasure.sequenceContainerWidth();

        var rowLength = calculateRowLength(charWidth, viewWidth, columnWidth);

        var rowData = [];

        for (let i = 0; i < sequenceData.size; i += rowLength) {
            let data = {};
            data.sequence = sequenceData.sequence.substr(i, rowLength);
            data = assign({}, sequenceData, data);
            rowData.push(data);
        }

        this.setState({ rowData: rowData });
    }

    componentDidMount() {
        new ResizeSensor(this.refs.rowView, this._populateRows.bind(this));
        this._populateRows();
    }

    render() {
        var {
            columnWidth
        } = this.props;

        var {
            rowData
        } = this.state;

        return (

m

                <RowItem ref={'rowMeasure'} sequenceData={{ sequence: '' }} className={styles.rowMeasure} />
                {
                    rowData.map(datum => <RowItem sequenceData={datum} columnWidth={columnWidth} />)
                }

        );
    }

}
<|endoftext|>


<commit_before>// um flackern zu unterbinden
document.write('<style type="text/css"> div.vpsSwitchDisplay div.switchContent { display: none; } </style>');

Vps.onContentReady(function() {
    var els = Ext.query('div.vpsSwitchDisplay');
    els.forEach(function(el) {
        if (!el.switchDisplayObject) {
            el = Ext.get(el);
            el.switchDisplayObject = new Vps.Switch.Display(el);
        }
    });
});

Vps.Switch.Display = function(el) {
    this.addEvents({
        'beforeOpen': true,
        'beforeClose': true,
        'opened': true,
        'closed': true
    });
    this._lockAnimation = false;

    this.el = el;
    this.switchLink = Ext.get(Ext.query('.switchLink', this.el.dom)[0]);
    this.switchContent = Ext.get(Ext.query('.switchContent', this.el.dom)[0]);
    this.vpsSwitchCloseLink = Ext.query('.switchCloseLink', this.el.dom);
    if (this.vpsSwitchCloseLink.length) {
        this.vpsSwitchCloseLink = Ext.get(this.vpsSwitchCloseLink[0]);
    } else {
        this.vpsSwitchCloseLink = false;
    }

    // durch unterbinden von flackern (ganz oben) muss das auf block
    // gesetzt werden, damit die hoehe gemessen werden kann
    this.switchContent.setStyle('display', 'block');
    this.switchContent.scaleHeight = this.switchContent.getHeight();
    this.switchContent.setHeight(0);
    // und schnell wieder auf 'none' bevors wer merkt :)
    this.switchContent.setStyle('display', 'none');

    // if it is important, show on startup
    if (this.switchContent.child('.vpsImportant')) {
        this.switchContent.setStyle('display', 'block');
        this.switchContent.setStyle('height', 'auto');
        this.switchLink.addClass('switchLinkOpened');
        if (Ext.isIE6) {
            this.switchContent.setWidth(this.switchContent.getWidth());
        }
    }

    if (this.switchLink && this.switchContent) {
        Ext.EventManager.addListener(this.switchLink, 'click', function(e) {
            if (this.switchLink.hasClass('switchLinkOpened')) {
                this.doClose();
            } else {
                this.doOpen();
            }
        }, this, { stopEvent: true });
    }

    if (this.vpsSwitchCloseLink) {
        Ext.EventManager.addListener(this.vpsSwitchCloseLink, 'click', function(e) {
            this.doClose();
        }, this, { stopEvent: true });
    }
};

Ext.extend(Vps.Switch.Display, Ext.util.Observable, {
    doClose: function() {
        if (this._lockAnimation) return;
        this._lockAnimation = true;

        this.fireEvent('beforeClose', this);
        this.switchContent.scaleHeight = this.switchContent.getHeight();
        this.switchContent.scale(undefined, 0,
            { easing: 'easeOut', duration: .5, afterStyle: "display:none;",
                callback: function() {
                    this.fireEvent('closed', this);
                    this._lockAnimation = false;
                },
                scope: this
            }
        );
        this.switchLink.removeClass('switchLinkOpened');
    },

    doOpen: function() {
        if (this._lockAnimation) return;
        this._lockAnimation = true;

        this.fireEvent('beforeOpen', this);
        this.switchContent.setStyle('display', 'block');
        this.switchContent.scale(undefined, this.switchContent.scaleHeight,
            { easing: 'easeOut', duration: .5, afterStyle: "display:block;height:auto;",
                callback: function() {
                    this.fireEvent('opened', this);
                    if (Ext.isIE6) {
                        this.switchContent.setWidth(this.switchContent.getWidth());
                    }
                    this._lockAnimation = false;
                },
                scope: this
            }
        );
        this.switchLink.addClass('switchLinkOpened');
    }
});<commit_msg>Switch/Display kann auch bei hover aufgehn<commit_after>// um flackern zu unterbinden
document.write('<style type="text/css"> div.vpsSwitchDisplay div.switchContent { display: none; } </style>');

Vps.onContentReady(function() {
    var els = Ext.query('div.vpsSwitchDisplay');
    els.forEach(function(el) {
        if (!el.switchDisplayObject) {
            el = Ext.get(el);
            el.switchDisplayObject = new Vps.Switch.Display(el);
        }
    });
});

Vps.Switch.Display = function(el) {
    this.addEvents({
        'beforeOpen': true,
        'beforeClose': true,
        'opened': true,
        'closed': true
    });
    this._lockAnimation = false;

    this.el = el;
    this.switchLink = Ext.get(Ext.query('.switchLink', this.el.dom)[0]);
    if (!this.switchLink) this.switchLink = Ext.get(Ext.query('.switchLinkHover', this.el.dom)[0]);
    this.switchContent = Ext.get(Ext.query('.switchContent', this.el.dom)[0]);
    this.vpsSwitchCloseLink = Ext.query('.switchCloseLink', this.el.dom);
    if (this.vpsSwitchCloseLink.length) {
        this.vpsSwitchCloseLink = Ext.get(this.vpsSwitchCloseLink[0]);
    } else {
        this.vpsSwitchCloseLink = false;
    }

    // durch unterbinden von flackern (ganz oben) muss das auf block
    // gesetzt werden, damit die hoehe gemessen werden kann
    this.switchContent.setStyle('display', 'block');
    this.switchContent.scaleHeight = this.switchContent.getHeight();
    this.switchContent.setHeight(0);
    // und schnell wieder auf 'none' bevors wer merkt :)
    this.switchContent.setStyle('display', 'none');

    // if it is important, show on startup
    if (this.switchContent.child('.vpsImportant')) {
        this.switchContent.setStyle('display', 'block');
        this.switchContent.setStyle('height', 'auto');
        this.switchLink.addClass('switchLinkOpened');
        if (Ext.isIE6) {
            this.switchContent.setWidth(this.switchContent.getWidth());
        }
    }

    if (this.switchLink && this.switchContent) {
        if (this.switchLink.hasClass('switchLinkHover')) {
            Vps.Event.on(this.el.dom, 'mouseEnter', function() {
                this.doOpen();
            }, this);
            Vps.Event.on(this.el.dom, 'mouseLeave', function() {
                this.doClose();
            }, this);
        } else {
            Ext.EventManager.addListener(this.switchLink, 'click', function(e) {
                if (this.switchLink.hasClass('switchLinkOpened')) {
                    this.doClose();
                } else {
                    this.doOpen();
                }
            }, this, { stopEvent: true });
        }
    }

    if (this.vpsSwitchCloseLink) {
        Ext.EventManager.addListener(this.vpsSwitchCloseLink, 'click', function(e) {
            this.doClose();
        }, this, { stopEvent: true });
    }
};

Ext.extend(Vps.Switch.Display, Ext.util.Observable, {
    doClose: function() {
        if (this._lockAnimation) return;
        this._lockAnimation = true;

        this.fireEvent('beforeClose', this);
        this.switchContent.scaleHeight = this.switchContent.getHeight();
        this.switchContent.scale(undefined, 0,
            { easing: 'easeOut', duration: .5, afterStyle: "display:none;",
                callback: function() {
                    this.fireEvent('closed', this);
                    this._lockAnimation = false;
                },
                scope: this
            }
        );
        this.switchLink.removeClass('switchLinkOpened');
    },

    doOpen: function() {
        if (this._lockAnimation) return;
        this._lockAnimation = true;

        this.fireEvent('beforeOpen', this);
        this.switchContent.setStyle('display', 'block');
        this.switchContent.scale(undefined, this.switchContent.scaleHeight,
            { easing: 'easeOut', duration: .5, afterStyle: "display:block;height:auto;",
                callback: function() {
                    this.fireEvent('opened', this);
                    if (Ext.isIE6) {
                        this.switchContent.setWidth(this.switchContent.getWidth());
                    }
                    this._lockAnimation = false;
                },
                scope: this
            }
        );
        this.switchLink.addClass('switchLinkOpened');
    }
});<|endoftext|>


<commit_before>
// function getLocation() {

// 	navigator.geolocation.getCurrentPosition(function (loc) {

// 		var now = new Date()

// 		var msg = now.toString()

// 		msg += ' accuracy: ' + loc.coords.accuracy
// 		msg += ' longitude: ' + loc.coords.longitude
// 		msg += ' latitude: ' + loc.coords.latitude

// 		postMessage(msg)

// 		setTimeout(getLocation, 1000)

// 	})

// }

// getLocation()

this.onmessage(function (e) {
	console.log('myworker message received')
	console.log(e.data)
})<commit_msg>[Sun Apr 24 13:15:47 EDT 2016]<commit_after>
// function getLocation() {

// 	navigator.geolocation.getCurrentPosition(function (loc) {

// 		var now = new Date()

// 		var msg = now.toString()

// 		msg += ' accuracy: ' + loc.coords.accuracy
// 		msg += ' longitude: ' + loc.coords.longitude
// 		msg += ' latitude: ' + loc.coords.latitude

// 		postMessage(msg)

// 		setTimeout(getLocation, 1000)

// 	})

// }

// getLocation()

self.onmessage(function (e) {
	console.log('myworker message received')
	console.log(e.data)
})<|endoftext|>


<commit_before>#!/usr/bin/env node

'use strict';

var fs = require('fs');
var path = require('path');
var program = require('commander');
var htmlify = require('../index');
var logSymbols = require('log-symbols');
var stdin = require('get-stdin');
process.title = 'angular-html5';

function collect(val, memo) {
    memo.push(val);
    return memo;
}

program
    .description('Change your ng-attributes to data-ng-attributes for html5 validation')
    .version(require(path.join(__dirname, '../package.json')).version)
    .usage('[options] <file>')
    .option('-c, --custom-prefix [prefixes]', 'Optionally add custom prefixes to the list of converted directives.', collect, [])
    .on('--help', function () {
        console.log('  Examples:');
        console.log('');
        console.log('    $ angular-html5 index.js');
        console.log('    $ angular-html5 --custom-prefix ui --custom-prefix gijo index.js > ./dist/index.js');
        console.log('    $ cat index.js | angular-html5 > ./dist/index.js');
        console.log('');
    })
    .parse(process.argv);

function run(contents, params) {
    params = params || {};
    var customPrefixes = program.customPrefix;
    var app = htmlify({
        customPrefixes: customPrefixes
    });
    if (!app.test(contents)) {
        console.log(logSymbols.success, 'No ng-directives found');
    } else {
        var output = app.replace(contents);
        // use stdout.write to maintain to not add an ending newline
        process.stdout.write(output);
    }
    process.exit(0);
}

function readFiles(files) {
    //TOOD: handle multiple files
    var file = files[0];
    var _contents = fs.readFileSync(path.resolve(process.cwd(), file), 'utf8');
    run(_contents, {
        file: file
    });
}

if (!process.stdin.isTTY) {
    stdin(run);
    return;
}
if (!program.args.length) {
    program.help();
    return;
}
readFiles(program.args);
<commit_msg>Remove todo<commit_after>#!/usr/bin/env node

'use strict';

var fs = require('fs');
var path = require('path');
var program = require('commander');
var htmlify = require('../index');
var logSymbols = require('log-symbols');
var stdin = require('get-stdin');
process.title = 'angular-html5';

function collect(val, memo) {
    memo.push(val);
    return memo;
}

program
    .description('Change your ng-attributes to data-ng-attributes for html5 validation')
    .version(require(path.join(__dirname, '../package.json')).version)
    .usage('[options] <file>')
    .option('-c, --custom-prefix [prefixes]', 'Optionally add custom prefixes to the list of converted directives.', collect, [])
    .on('--help', function () {
        console.log('  Examples:');
        console.log('');
        console.log('    $ angular-html5 index.js');
        console.log('    $ angular-html5 --custom-prefix ui --custom-prefix gijo index.js > ./dist/index.js');
        console.log('    $ cat index.js | angular-html5 > ./dist/index.js');
        console.log('');
    })
    .parse(process.argv);

function run(contents, params) {
    params = params || {};
    var customPrefixes = program.customPrefix;
    var app = htmlify({
        customPrefixes: customPrefixes
    });
    if (!app.test(contents)) {
        console.log(logSymbols.success, 'No ng-directives found');
    } else {
        var output = app.replace(contents);
        // use stdout.write to maintain to not add an ending newline
        process.stdout.write(output);
    }
    process.exit(0);
}

function readFiles(files) {
    var file = files[0];
    var _contents = fs.readFileSync(path.resolve(process.cwd(), file), 'utf8');
    run(_contents, {
        file: file
    });
}

if (!process.stdin.isTTY) {
    stdin(run);
    return;
}
if (!program.args.length) {
    program.help();
    return;
}
readFiles(program.args);
<|endoftext|>


<commit_before>var argv = require('minimist')(process.argv.slice(2)),
    home = require('./../lib/homepath'),
    config = require(home.path() + '/.eliq2graphite/config.json'),
    eliq = require('eliq-promise')(config),
    logger = require('log4js-extras')(config).getLogger(__filename),
    graphite = require('./../lib/graphite')(config);

var usage = '\
Usage: \n\
eliq2graphite [--age number-of-hours] [--resolution hour|6min]\n\
\n\
Options: \n\
-a, --age=number of hours (default 2 hours)\n\
-r, --resolution=6min|hour|day (default 6min) \n\
-h, --help (show this)\
\n';

if (argv.h || argv.help) {
    console.log(usage);
} else {
    eliq.getFrom(24 || argv.a || argv.age || 2, 'hour' || argv.r || argv.resolution || '6min').then(function (value) {
        graphite.log(value)
    }, function (value) {
        logger.error(value);
    });
}
<commit_msg>Revert changes<commit_after>var argv = require('minimist')(process.argv.slice(2)),
    home = require('./../lib/homepath'),
    config = require(home.path() + '/.eliq2graphite/config.json'),
    eliq = require('eliq-promise')(config),
    logger = require('log4js-extras')(config).getLogger(__filename),
    graphite = require('./../lib/graphite')(config);

var usage = '\
Usage: \n\
eliq2graphite [--age number-of-hours] [--resolution hour|6min]\n\
\n\
Options: \n\
-a, --age=number of hours (default 2 hours)\n\
-r, --resolution=6min|hour|day (default 6min) \n\
-h, --help (show this)\
\n';

if (argv.h || argv.help) {
    console.log(usage);
} else {
    eliq.getFrom(24 || argv.a || argv.age || 2, 'hour' || argv.r || argv.resolution || '6min').then(graphite.log).catch(logger.error);
}
<|endoftext|>


<commit_before>/**
 * Copyright 2015 IBM Corp.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/

RED.deploy = (function() {

    var deploymentTypes = {
        "save":{img:"images/deploy-full-o.png"},
        "full":{img:"images/deploy-full-o.png"},
        "nodes":{img:"images/deploy-nodes-o.png"},
        "flows":{img:"images/deploy-flows-o.png"}
    }

    var deploymentType = "full";
    var deploy=false;

    function changeDeploymentType(type) {
        deploymentType = type;
        $("#btn-deploy img").attr("src",deploymentTypes[type].img);
    }

    function init() {

        var saveButton = $('
'+
        ' Save
').prependTo(".header-toolbar");

        var deployButton = $('
'+
          ' Deploy'+
          ''+
          '
').prependTo(".header-toolbar");

        $('#btn-deploy').click(function() { deploy = true ;save(undefined,true); });
        $('#btn-save').click(function() {  deploy = false ;save(undefined,false); });

        $( "#node-dialog-confirm-deploy" ).dialog({
                title: "Confirm deploy",
                modal: true,
                autoOpen: false,
                width: 530,
                height: 230,
                buttons: [
                    {
                        text: "Confirm deploy",
                        click: function() {
                            save(true);
                            $( this ).dialog( "close" );
                        }
                    },
                    {
                        text: "Cancel",
                        click: function() {
                            $( this ).dialog( "close" );
                        }
                    }
                ]
        });

        RED.menu.init({id:"btn-deploy-options",
            options: [
                {id:"btn-deploy-full",toggle:"deploy-type",icon:"images/deploy-full.png",label:"Full",sublabel:"Deploys everything in the workspace",onselect:function(s) { if(s){changeDeploymentType("full")}}},
                {id:"btn-deploy-flow",toggle:"deploy-type",icon:"images/deploy-flows.png",label:"Modified Flows",sublabel:"Only deploys flows that contain changed nodes", onselect:function(s) {if(s){changeDeploymentType("flows")}}},
                {id:"btn-deploy-node",toggle:"deploy-type",icon:"images/deploy-nodes.png",label:"Modified Nodes",sublabel:"Only deploys nodes that have changed",onselect:function(s) { if(s){changeDeploymentType("nodes")}}}
            ]
        });

        RED.nodes.on('change',function(state) {
            if (state.dirty) {
                window.onbeforeunload = function() {
                    return "You have undeployed or unsaved changes.\n\nLeaving this page will lose these changes.";
                }
                $("#btn-deploy").removeClass("disabled");
                $("#btn-save").removeClass("disabled");
            } else {
                window.onbeforeunload = null;
                if(deploy){
                    $("#btn-deploy").addClass("disabled");
                }else{
                    $("#btn-save").addClass("disabled");
                }
            }
        });
    }

    function save(force,deploy) {
        if (RED.nodes.dirty()) {
            //$("#debug-tab-clear").click();  // uncomment this to auto clear debug on deploy

            if (!force) {
                var invalid = false;
                var unknownNodes = [];
                RED.nodes.eachNode(function(node) {
                    invalid = invalid || !node.valid;
                    if (node.type === "unknown") {
                        if (unknownNodes.indexOf(node.name) == -1) {
                            unknownNodes.push(node.name);
                        }
                        invalid = true;
                    }
                });
                if (invalid) {
                    if (unknownNodes.length > 0) {
                        $( "#node-dialog-confirm-deploy-config" ).hide();
                        $( "#node-dialog-confirm-deploy-unknown" ).show();
                        var list = "
"+unknownNodes.join("

")+"
";
                        $( "#node-dialog-confirm-deploy-unknown-list" ).html(list);
                    } else {
                        $( "#node-dialog-confirm-deploy-config" ).show();
                        $( "#node-dialog-confirm-deploy-unknown" ).hide();
                    }
                    $( "#node-dialog-confirm-deploy" ).dialog( "open" );
                    return;
                }
            }
            var nns = RED.nodes.createCompleteNodeSet();

            if(deploy){
                $("#btn-icn-deploy").removeClass('fa-download');
                $("#btn-icn-deploy").addClass('spinner');
            }

            $("#btn-icn-save").removeClass('fa-download');
            $("#btn-icn-save").addClass('spinner');

            RED.nodes.dirty(false);

            $.ajax({
                url:"flows",
                type: "POST",
                data: JSON.stringify(nns),
                contentType: "application/json; charset=utf-8",
                headers: {
                    "Node-RED-Deployment-Type":deploymentType,
                    "Node-RED-Deploy-Save":deploy?"deploy":"save"
                }
            }).done(function(data,textStatus,xhr) {
                if(deploy){
                    RED.notify("Successfully deployed","success");
                }else{
                    RED.notify("Successfully saved","success");
                }
                RED.nodes.eachNode(function(node) {
                    if (node.changed) {
                        node.dirty = true;
                        node.changed = false;
                    }
                    if(node.credentials) {
                        delete node.credentials;
                    }
                });
                RED.nodes.eachConfig(function (confNode) {
                    if (confNode.credentials) {
                        delete confNode.credentials;
                    }
                });
                // Once deployed, cannot undo back to a clean state
                RED.history.markAllDirty();
                RED.view.redraw();
            }).fail(function(xhr,textStatus,err) {
                RED.nodes.dirty(true);
                if (xhr.responseText) {
                    RED.notify("Error: "+xhr.responseText,"error");
                } else {
                    RED.notify("Error: no response from server","error");
                }
            }).always(function() {
                if(deploy){
                    $("#btn-icn-deploy").removeClass('fa-download');
                    $("#btn-icn-deploy").addClass('spinner');
                }

                $("#btn-icn-save").removeClass('fa-download');
                $("#btn-icn-save").addClass('spinner');
            });
        }
    }

    return {
        init: init
    }
})();
<commit_msg>save work every time whatever node.dirty value<commit_after>/**
 * Copyright 2015 IBM Corp.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/

RED.deploy = (function() {

    var deploymentTypes = {
        "save":{img:"images/deploy-full-o.png"},
        "full":{img:"images/deploy-full-o.png"},
        "nodes":{img:"images/deploy-nodes-o.png"},
        "flows":{img:"images/deploy-flows-o.png"}
    }

    var deploymentType = "full";
    var deploy=false;

    function changeDeploymentType(type) {
        deploymentType = type;
        $("#btn-deploy img").attr("src",deploymentTypes[type].img);
    }

    function init() {

        var saveButton = $('
'+
        ' Save
').prependTo(".header-toolbar");

        var deployButton = $('
'+
          ' Deploy'+
          ''+
          '
').prependTo(".header-toolbar");

        $('#btn-deploy').click(function() { deploy = true ;save(undefined,true); });
        $('#btn-save').click(function() {  deploy = false ;save(undefined,false); });

        $( "#node-dialog-confirm-deploy" ).dialog({
                title: "Confirm deploy",
                modal: true,
                autoOpen: false,
                width: 530,
                height: 230,
                buttons: [
                    {
                        text: "Confirm deploy",
                        click: function() {
                            save(true);
                            $( this ).dialog( "close" );
                        }
                    },
                    {
                        text: "Cancel",
                        click: function() {
                            $( this ).dialog( "close" );
                        }
                    }
                ]
        });

        RED.menu.init({id:"btn-deploy-options",
            options: [
                {id:"btn-deploy-full",toggle:"deploy-type",icon:"images/deploy-full.png",label:"Full",sublabel:"Deploys everything in the workspace",onselect:function(s) { if(s){changeDeploymentType("full")}}},
                {id:"btn-deploy-flow",toggle:"deploy-type",icon:"images/deploy-flows.png",label:"Modified Flows",sublabel:"Only deploys flows that contain changed nodes", onselect:function(s) {if(s){changeDeploymentType("flows")}}},
                {id:"btn-deploy-node",toggle:"deploy-type",icon:"images/deploy-nodes.png",label:"Modified Nodes",sublabel:"Only deploys nodes that have changed",onselect:function(s) { if(s){changeDeploymentType("nodes")}}}
            ]
        });

        RED.nodes.on('change',function(state) {
            if (state.dirty) {
                window.onbeforeunload = function() {
                    return "You have undeployed or unsaved changes.\n\nLeaving this page will lose these changes.";
                }
                $("#btn-deploy").removeClass("disabled");
                $("#btn-save").removeClass("disabled");
            } else {
                window.onbeforeunload = null;
                if(deploy){
                    $("#btn-deploy").addClass("disabled");
                }else{
                    $("#btn-save").addClass("disabled");
                }
            }
        });
    }

    function save(force,deploy) {
        if (RED.nodes.dirty() || true) {
            //$("#debug-tab-clear").click();  // uncomment this to auto clear debug on deploy

            if (!force) {
                var invalid = false;
                var unknownNodes = [];
                RED.nodes.eachNode(function(node) {
                    invalid = invalid || !node.valid;
                    if (node.type === "unknown") {
                        if (unknownNodes.indexOf(node.name) == -1) {
                            unknownNodes.push(node.name);
                        }
                        invalid = true;
                    }
                });
                if (invalid) {
                    if (unknownNodes.length > 0) {
                        $( "#node-dialog-confirm-deploy-config" ).hide();
                        $( "#node-dialog-confirm-deploy-unknown" ).show();
                        var list = "
"+unknownNodes.join("

")+"
";
                        $( "#node-dialog-confirm-deploy-unknown-list" ).html(list);
                    } else {
                        $( "#node-dialog-confirm-deploy-config" ).show();
                        $( "#node-dialog-confirm-deploy-unknown" ).hide();
                    }
                    $( "#node-dialog-confirm-deploy" ).dialog( "open" );
                    return;
                }
            }
            var nns = RED.nodes.createCompleteNodeSet();

            if(deploy){
                $("#btn-icn-deploy").removeClass('fa-download');
                $("#btn-icn-deploy").addClass('spinner');
            }

            $("#btn-icn-save").removeClass('fa-download');
            $("#btn-icn-save").addClass('spinner');

            RED.nodes.dirty(false);

            $.ajax({
                url:"flows",
                type: "POST",
                data: JSON.stringify(nns),
                contentType: "application/json; charset=utf-8",
                headers: {
                    "Node-RED-Deployment-Type":deploymentType,
                    "Node-RED-Deploy-Save":deploy?"deploy":"save"
                }
            }).done(function(data,textStatus,xhr) {
                if(deploy){
                    RED.notify("Successfully deployed","success");
                }else{
                    RED.notify("Successfully saved","success");
                }
                RED.nodes.eachNode(function(node) {
                    if (node.changed) {
                        node.dirty = true;
                        node.changed = false;
                    }
                    if(node.credentials) {
                        delete node.credentials;
                    }
                });
                RED.nodes.eachConfig(function (confNode) {
                    if (confNode.credentials) {
                        delete confNode.credentials;
                    }
                });
                // Once deployed, cannot undo back to a clean state
                RED.history.markAllDirty();
                RED.view.redraw();
            }).fail(function(xhr,textStatus,err) {
                RED.nodes.dirty(true);
                if (xhr.responseText) {
                    RED.notify("Error: "+xhr.responseText,"error");
                } else {
                    RED.notify("Error: no response from server","error");
                }
            }).always(function() {
                if(deploy){
                    $("#btn-icn-deploy").removeClass('fa-download');
                    $("#btn-icn-deploy").addClass('spinner');
                }

                $("#btn-icn-save").removeClass('fa-download');
                $("#btn-icn-save").addClass('spinner');
            });
        }
    }

    return {
        init: init
    }
})();
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';

var shell = require('shelljs');
var argv = require('minimist')(process.argv.slice(2));
var fs = require('fs');
var path = require('path');
var tmpl = require('blueimp-tmpl').tmpl;
var projectName = require('project-name');

var BASE_DIR = path.resolve(__dirname, '..');
var DIST_DIR = path.join(BASE_DIR, 'dist');
var TEMPLATES_DIR = path.join(BASE_DIR, 'src', 'templates');
var VALID_PACKAGES = ['react-web'];
var BASE_ESLINT_PATH = './' + path.join('node_modules', projectName(BASE_DIR), 'dist', 'base-eslintrc');

var packages = [];
var packagesList = argv.install || argv.i || '';

function npmInstall(pkgs) {
  pkgs.forEach(function(pkg) {
    shell.exec('npm install --save ' + pkg);
  });
}

function devNpmInstall(pkgs) {
  pkgs.forEach(function(pkg) {
    shell.exec('npm install --save-dev ' + pkg);
  });
}

function copyDistConfig(sourceFilename, destFilename) {
  var sourcePath = path.join(DIST_DIR, sourceFilename);
  shell.cp('-f', sourcePath, destFilename);
}

function buildTemplateFromFile(templatePath, data) {
  var template = fs.readFileSync(path.join(TEMPLATES_DIR, templatePath), 'utf8');
  return tmpl(template, data);
}

function generateTemplate(templatePath, data, destination) {
  var template = buildTemplateFromFile(templatePath, data);
  template.to(destination);
}

if (argv.help) {
  shell.echo('Usage:');
  shell.echo('  react-boilerplate-gen <args>');
  shell.echo('');
  shell.echo('Args:');
  shell.echo('');
  shell.echo('  --install, -i: install predefined package list, options: [' + VALID_PACKAGES.join(',') + ']');
  shell.echo('  --skip-install: override to skip installing of packages');
  shell.echo('  --force, -f: overwrite existing configs, does not run install');
  shell.echo('  --eslintrc: create eslintrc, will override existing project eslintrc');
  shell.echo('  --babelrc: create babelrc, will override existing project babelrc');
}

if (!argv['skip-install'] && argv.install || !argv['skip-install'] && argv.i) {
  switch (packagesList.toLowerCase()) {
    case 'react-web':
      packages = require('../src/packages/react-web');
      break;
    default:
      shell.echo('Requires packages list name (--install or -i), valid options: ' + VALID_PACKAGES.join(','));
      shell.exit(1);
  }

  shell.echo('----> Installing packages...');
  npmInstall(packages.depends);

  shell.echo('----> Installing dev packages...');
  devNpmInstall(packages.dev);
}

if (argv.force || argv.babelrc || !shell.test('-f', '.babelrc')) {
  shell.echo('----> Generating .babelrc...');
  copyDistConfig('babelrc.json', '.babelrc');
}

if (argv.force || argv.eslintrc || !shell.test('-f', '.eslintrc')) {
  shell.echo('----> Generating project .eslintrc...');
  generateTemplate('project-eslintrc.json.tmpl', BASE_ESLINT_PATH, '.eslintrc');
}
<commit_msg>bin command creates test folders<commit_after>#!/usr/bin/env node
'use strict';

var shell = require('shelljs');
var argv = require('minimist')(process.argv.slice(2));
var fs = require('fs');
var path = require('path');
var tmpl = require('blueimp-tmpl').tmpl;
var projectName = require('project-name');

var BASE_DIR = path.resolve(__dirname, '..');
var DIST_DIR = path.join(BASE_DIR, 'dist');
var TEMPLATES_DIR = path.join(BASE_DIR, 'src', 'templates');
var VALID_PACKAGES = ['react-web'];
var BASE_ESLINT_PATH = './' + path.join('node_modules', projectName(BASE_DIR), 'dist', 'base-eslintrc');

var packages = [];
var packagesList = argv.install || argv.i || '';

function npmInstall(pkgs) {
  pkgs.forEach(function(pkg) {
    shell.exec('npm install --save ' + pkg);
  });
}

function devNpmInstall(pkgs) {
  pkgs.forEach(function(pkg) {
    shell.exec('npm install --save-dev ' + pkg);
  });
}

function copyDistConfig(sourceFilename, destFilename) {
  var sourcePath = path.join(DIST_DIR, sourceFilename);
  shell.cp('-f', sourcePath, destFilename);
}

function buildTemplateFromFile(templatePath, data) {
  var template = fs.readFileSync(path.join(TEMPLATES_DIR, templatePath), 'utf8');
  return tmpl(template, data);
}

function generateTemplate(templatePath, data, destination) {
  var template = buildTemplateFromFile(templatePath, data);
  template.to(destination);
}

if (argv.help) {
  shell.echo('Usage:');
  shell.echo('  react-boilerplate-gen <args>');
  shell.echo('');
  shell.echo('Args:');
  shell.echo('');
  shell.echo('  --install, -i: install predefined package list, options: [' + VALID_PACKAGES.join(',') + ']');
  shell.echo('  --skip-install: override to skip installing of packages');
  shell.echo('  --skip-tests: override to skip setup for tests');
  shell.echo('  --force, -f: overwrite existing configs, does not run install');
  shell.echo('  --eslintrc: create eslintrc, will override existing project eslintrc');
  shell.echo('  --babelrc: create babelrc, will override existing project babelrc');
}

if (!argv['skip-install'] && argv.install || !argv['skip-install'] && argv.i) {
  switch (packagesList.toLowerCase()) {
    case 'react-web':
      packages = require('../src/packages/react-web');
      break;
    default:
      shell.echo('Requires packages list name (--install or -i), valid options: ' + VALID_PACKAGES.join(','));
      shell.exit(1);
  }

  shell.echo('----> Installing packages...');
  npmInstall(packages.depends);

  shell.echo('----> Installing dev packages...');
  devNpmInstall(packages.dev);
}

if (argv.force || argv.babelrc || !shell.test('-f', '.babelrc')) {
  shell.echo('----> Generating .babelrc...');
  copyDistConfig('babelrc.json', '.babelrc');
}

if (argv.force || argv.eslintrc || !shell.test('-f', '.eslintrc')) {
  shell.echo('----> Generating project .eslintrc...');
  generateTemplate('project-eslintrc.json.tmpl', BASE_ESLINT_PATH, '.eslintrc');
}

if (!argv['skip-tests']) {
  shell.mkdir('-p', 'tests/browser');
  shell.mkdir('-p', 'tests/unit');
}
<|endoftext|>


<commit_before>/**
 * The main application class. An instance of this class is created by app.js when it calls
 * Ext.application(). This is the ideal place to handle application launch and initialization
 * details.
 */
Ext.define('PostgrestTest.Application', {
    extend: 'Ext.app.Application',

    requires: [
        'PostgrestTest.model.Jurisdiction',
        'PostgrestTest.store.Jurisdictions',
        'Jarvus.proxy.Postgrest',
        'Jarvus.reader.Postgrest'
    ],

    name: 'PostgrestTest',

    stores: [
        'PostgrestTest.store.Jurisdictions'
    ],

    launch: function () {
        Ext.getStore('PostgrestTest.store.Jurisdictions').load({callback: function loaded() {
            debugger;

            var store = Ext.getStore('PostgrestTest.store.Jurisdictions');

            store.filter([{
                property: 'title',
                operator: 'in',
                value:    ['Pennsylvania', 'New Jersey', 'Delaware']
            }]);
        }});
    }
});
<commit_msg>use raw HTTP calls to demo API<commit_after>/**
 * The main application class. An instance of this class is created by app.js when it calls
 * Ext.application(). This is the ideal place to handle application launch and initialization
 * details.
 */
Ext.define('PostgrestTest.Application', {
    extend: 'Ext.app.Application',

    requires: [
        'PostgrestTest.model.Jurisdiction',
        'PostgrestTest.store.Jurisdictions',
        'Jarvus.connection.Postgrest',
        'Jarvus.proxy.Postgrest',
        'Jarvus.reader.Postgrest'
    ],

    name: 'PostgrestTest',

    stores: [
        'PostgrestTest.store.Jurisdictions'
    ],

    launch: function () {
        // Ext.getStore('PostgrestTest.store.Jurisdictions').load({callback: function loaded() {
        //     debugger;

        //     var store = Ext.getStore('PostgrestTest.store.Jurisdictions');

        //     store.filter([{
        //         property: 'title',
        //         operator: 'in',
        //         value:    ['Pennsylvania', 'New Jersey', 'Delaware']
        //     }]);
        // }});

        // demo call: get a list of tables
        Jarvus.connection.Postgrest.request({
            url: '/',
            success: function(response) {
                var r = Ext.decode(response.responseText);

                console.log('Loaded list of schemas');
                console.table(r);
            }
        });

        // load all jurisdictions
        Jarvus.connection.Postgrest.request({
            url: '/jurisdictions',
            success: function(response) {
                var r = Ext.decode(response.responseText);

                console.log('Loaded list of jurisdictions');
                console.table(r);
            }
        });

        // load one jurisdiction
        Jarvus.connection.Postgrest.request({
            url: '/jurisdictions',
            urlParams: {
                id: 'eq.3'
            },
            success: function(response) {
                var r = Ext.decode(response.responseText);

                console.log('Loaded one jurisdiction:', r[0]);
            }
        });
    }
});
<|endoftext|>


<commit_before>$(document).ready(function(){
  getLeagues(); // ajax call in league_ajax.js
}); //end of document.ready

function resetLeagueList() {
  $("#notDrafted").empty();
  $("#drafted").empty();
}

function clearFormData() {
  $("#createLeague")[0].reset();
}

function createLeagueList(leagueList){
  //
  for (var league in leagueList) {
    if (leagueList[league].draftcomplete) {
      addLeagueToView(leagueList[league].league_name, true, leagueList[league].id);
    } else {
      addLeagueToView(leagueList[league].league_name, false, leagueList[league].id);
    }
  }
}

function addLeagueToView(name, draftComplete, leagueid) {
  //
  $league = $("<div>", {id: name, class: "leagueName"});
  $league.text(name);
  $leagueContainer = $("<div>", {class: "league_container"})
  $button_detail = $("<input>", {type: "submit", name: "detail", value: "VIEW / SIMULATE", class: "button-primary buttonLeague detail"});
  $button_draft = $("<input>", {type: "submit", name: "draft", value: "DRAFT NOW!", id: "button", class: "button-primary buttonLeague draft"});
  $hiddenid = $("<input>", {type: "hidden", value: name, name: "league_name"});
  $form_draft = $("<form>", {class: "form", method: "GET", action: "/draft"});
  $form_detail = $("<form>", {class: "form", method: "GET", action: "/myleagues/:" + name + ""});
  //
  if (draftComplete) {
    $form_detail.append($hiddenid);
    $form_detail.append($button_detail);
    $leagueContainer.append($league);
    $leagueContainer.append($form_detail);
    $("#drafted").append($leagueContainer);
  } else {
    $form_draft.append($hiddenid);
    $form_draft.append($button_draft);
    $leagueContainer.append($league);
    $leagueContainer.append($form_draft);
    $("#notDrafted").append($leagueContainer);
  }

}
<commit_msg>updated view/sim button<commit_after>$(document).ready(function(){
  getLeagues(); // ajax call in league_ajax.js
}); //end of document.ready

function resetLeagueList() {
  $("#notDrafted").empty();
  $("#drafted").empty();
}

function clearFormData() {
  $("#createLeague")[0].reset();
}

function createLeagueList(leagueList){
  //
  for (var league in leagueList) {
    if (leagueList[league].draftcomplete) {
      addLeagueToView(leagueList[league].league_name, true, leagueList[league].id);
    } else {
      addLeagueToView(leagueList[league].league_name, false, leagueList[league].id);
    }
  }
}

function addLeagueToView(name, draftComplete, leagueid) {
  //
  $league = $("<div>", {id: name, class: "leagueName"});
  $league.text(name);
  $leagueContainer = $("<div>", {class: "league_container"})
  $button_detail = $("<input>", {type: "submit", name: "detail", value: "VIEW / SIMULATE", class: "button-primary buttonLeague detail"});
  $button_draft = $("<input>", {type: "submit", name: "draft", value: "DRAFT NOW!", id: "button", class: "button-primary buttonLeague draft"});
  $hiddenid = $("<input>", {type: "hidden", value: name, name: "league_name"});
  $form_draft = $("<form>", {class: "form", method: "GET", action: "/draft"});
  $form_detail = $("<form>", {class: "form", method: "GET", action: "/league/myleagues/" + name + ""});
  //
  if (draftComplete) {
    $form_detail.append($hiddenid);
    $form_detail.append($button_detail);
    $leagueContainer.append($league);
    $leagueContainer.append($form_detail);
    $("#drafted").append($leagueContainer);
  } else {
    $form_draft.append($hiddenid);
    $form_draft.append($button_draft);
    $leagueContainer.append($league);
    $leagueContainer.append($form_draft);
    $("#notDrafted").append($leagueContainer);
  }

}
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';

var log      = require('npmlog')
  , minimist = require('minimist')
  , xtend    = require('xtend')
  , path     = require('path')
  , fs       = require('fs')
  ;

function usage() {
  var usageFile = path.join(__dirname, 'nad-configure-usage.txt');
  fs.createReadStream(usageFile).pipe(process.stdout);
  return;
}

var argv = minimist(process.argv.slice(2)
  , { boolean: [ 'h', 'help' ]
    , string: [ 'cc', 'cxx', 'link', 'nodedir', 'target' ]
  });

if (argv.h || argv.help) return usage();

var opts = xtend({
    cc     : 'clang'
  , cxx    : 'clang++'
  , link   : 'clang++'
  , target : process.versions.node
}, argv)

opts.nodedir = argv.nodedir
  ? path.relative(process.cwd(),  argv.nodedir)
  : path.relative(process.cwd(), 'node-' + opts.target)

var config =
  '# Generated by "nad configure", you may edit this or just rerun "nad configure"\n\n' +
  [ 'cc', 'cxx', 'link', 'target', 'nodedir' ]
    .map(function (k) {
      return k.toUpperCase() + '?=' + opts[k]
    }).join('\n')

var nadconfig_mk = path.join(process.cwd(), '.nadconfig.mk');
fs.writeFileSync(nadconfig_mk, config);

log.info('nad', 'Current config:')
fs.createReadStream(nadconfig_mk).pipe(process.stdout)
<commit_msg>fixing versions starting with 'v' during nad configure<commit_after>#!/usr/bin/env node
'use strict';

var log      = require('npmlog')
  , minimist = require('minimist')
  , xtend    = require('xtend')
  , path     = require('path')
  , fs       = require('fs')
  ;

function usage() {
  var usageFile = path.join(__dirname, 'nad-configure-usage.txt');
  fs.createReadStream(usageFile).pipe(process.stdout);
  return;
}

var argv = minimist(process.argv.slice(2)
  , { boolean: [ 'h', 'help' ]
    , string: [ 'cc', 'cxx', 'link', 'nodedir', 'target' ]
  });

if (argv.h || argv.help) return usage();

var opts = xtend({
    cc     : 'clang'
  , cxx    : 'clang++'
  , link   : 'clang++'
  , target : process.versions.node
}, argv)

// Ensure version doesn't include 'v', i.e. turn 'v0.10.31' into '0.10.31'
if (opts.target[0] === 'v') opts.target = opts.target.slice(1);

opts.nodedir = argv.nodedir
  ? path.relative(process.cwd(),  argv.nodedir)
  : path.relative(process.cwd(), 'node-' + opts.target)

var config =
  '# Generated by "nad configure", you may edit this or just rerun "nad configure"\n\n' +
  [ 'cc', 'cxx', 'link', 'target', 'nodedir' ]
    .map(function (k) {
      return k.toUpperCase() + '?=' + opts[k]
    }).join('\n')

var nadconfig_mk = path.join(process.cwd(), '.nadconfig.mk');
fs.writeFileSync(nadconfig_mk, config);

log.info('nad', 'Current config:')
fs.createReadStream(nadconfig_mk).pipe(process.stdout)
<|endoftext|>