<commit_before>/*
Copyright 2015 Google Inc.

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.

*/

(function() {

	function retryIt(fn, initialDelay, maxTries) {
	  var one = function(fn, delay, triesLeft) {
	    --triesLeft;
	    if (fn() || triesLeft <= 0) {
	      return;
	    }
	    window.setTimeout(function() {
	      one(fn, delay*2, triesLeft);
	    }, delay*2);
	  };
	  window.setTimeout(function() {
	    one(fn, initialDelay*2, maxTries-1);
	  }, initialDelay);
	}

	var hashRe = /#.*\/[a-f0-9]+$/;
	var issueRe = /^https:\/\/github.com\/([A-Za-z0-9-]+\/[A-Za-z0-9-]+\/issues\/[0-9]+)/
	var pullRe = /^https:\/\/github.com\/([A-Za-z0-9-]+\/[A-Za-z0-9-]+\/pull\/[0-9]+)/

	function addBadge() {
		var hash = window.location.hash;
		if (!hashRe.exec(hash)) return;

		var ps = document.getElementsByTagName("p");
		for (var i = 0; i < ps.length; i++) {
			var as = ps[i].getElementsByTagName("a");
			for (var j = 0; j < as.length; j++) {
				var m = issueRe.exec(as[j].href);
				if (!m) {
					m = pullRe.exec(as[j].href);
				}
				if (!m) continue;

				// If a comment mentions another issue by number,
				// GitHub will make a link to that other issue.
				// We don't want those; we only want the one at the
				// bottom that says "view it on GitHub".
				if (as[j].textContent != "view it on GitHub") continue;

				console.log("match:", m[0]);

				var magic = "azg";

				var img = document.createElement("img");
				img.src = "https://github-shields.com/github/"+m[1]+".svg";
				var a = document.createElement("a");
				a.href = m[0];
				a.appendChild(img);
				var div = document.createElement("div");
				div.className = magic;
				div.appendChild(a);

				retryIt(function() {
					var ms = document.getElementsByClassName(magic);
					if (ms.length != 1) return false;
					ms[0].parentElement.insertBefore(div, ms[0]);
					return true;
				}, 500, 5);

				return; // Stop at first one.
			}
		}
	}

	window.addEventListener("hashchange", addBadge, false);
})();
<commit_msg>GitHub repository names can contain underscores<commit_after>/*
Copyright 2015 Google Inc.

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.

*/

(function() {

	function retryIt(fn, initialDelay, maxTries) {
	  var one = function(fn, delay, triesLeft) {
	    --triesLeft;
	    if (fn() || triesLeft <= 0) {
	      return;
	    }
	    window.setTimeout(function() {
	      one(fn, delay*2, triesLeft);
	    }, delay*2);
	  };
	  window.setTimeout(function() {
	    one(fn, initialDelay*2, maxTries-1);
	  }, initialDelay);
	}

	var hashRe = /#.*\/[a-f0-9]+$/;
	var issueRe = /^https:\/\/github.com\/([A-Za-z0-9-]+\/[\w-]+\/issues\/[0-9]+)/;
	var pullRe = /^https:\/\/github.com\/([A-Za-z0-9-]+\/[\w-]+\/pull\/[0-9]+)/;

	function addBadge() {
		var hash = window.location.hash;
		if (!hashRe.exec(hash)) return;

		var ps = document.getElementsByTagName("p");
		for (var i = 0; i < ps.length; i++) {
			var as = ps[i].getElementsByTagName("a");
			for (var j = 0; j < as.length; j++) {
				var m = issueRe.exec(as[j].href);
				if (!m) {
					m = pullRe.exec(as[j].href);
				}
				if (!m) continue;

				// If a comment mentions another issue by number,
				// GitHub will make a link to that other issue.
				// We don't want those; we only want the one at the
				// bottom that says "view it on GitHub".
				if (as[j].textContent != "view it on GitHub") continue;

				console.log("match:", m[0]);

				var magic = "azg";

				var img = document.createElement("img");
				img.src = "https://github-shields.com/github/"+m[1]+".svg";
				var a = document.createElement("a");
				a.href = m[0];
				a.appendChild(img);
				var div = document.createElement("div");
				div.className = magic;
				div.appendChild(a);

				retryIt(function() {
					var ms = document.getElementsByClassName(magic);
					if (ms.length != 1) return false;
					ms[0].parentElement.insertBefore(div, ms[0]);
					return true;
				}, 500, 5);

				return; // Stop at first one.
			}
		}
	}

	window.addEventListener("hashchange", addBadge, false);
})();
<|endoftext|>


<commit_before>'use strict';

import assert from 'assert';
import {Server} from 'hapi';
import hapiMysqlRoutes from '../hapi-mysql-routes-plugin';

describe('hapi-mysql-routes-plugin', () => {
  describe('validation', () => {

    it('should not error if all the required options are set', (done) => {
      let server = new Server();
      server.connection();
      server.register({
        register: hapiMysqlRoutes,
        options: {
          mysqlConfig: 'mysql',
          primaryKey: 'primaryKey',
          tableName: 'tableName'
        }
      }, (err) => {
        assert.ifError(err);
        done();
      });
    });
  });
});
<commit_msg>SEN-1612<commit_after>'use strict';

import assert from 'assert';
import {Server} from 'hapi';
import hapiMysqlRoutes from '../hapi-mysql-routes-plugin';

describe.skip('hapi-mysql-routes-plugin', () => {
  describe('validation', () => {

    it('should not error if all the required options are set', (done) => {
      let server = new Server();
      server.connection();
      server.register({
        register: hapiMysqlRoutes,
        options: {
          mysqlConfig: 'mysql',
          primaryKey: 'primaryKey',
          tableName: 'tableName'
        }
      }, (err) => {
        assert.ifError(err);
        done();
      });
    });
  });
});
<|endoftext|>


<commit_before>window.c.project.Show = (function(m, c, _, models){
  return {
    controller: function(args) {
      var vm = m.postgrest.filtersVM({project_id: 'eq'}),
          projectDetails = m.prop([]);

      vm.project_id(args.root.getAttribute('data-id'));

      models.projectDetail.getRowWithToken(vm.parameters()).then(projectDetails);

      return {
        vm: vm,
        projectDetails: projectDetails
      };
    },

    view: function(ctrl) {
      return _.map(ctrl.projectDetails(), function(project){
        return m('.project-show', [
          m.component(c.ProjectHeader, {project: project}),
          m.component(c.ProjectTabs, {project: project}),
          m.component(c.ProjectMain, {project: project}),
          (project.is_owner_or_admin ? m.component(c.ProjectNav, {project: project}) : '')
        ]);
      });
    }
  };
}(window.m, window.c, window._, window.c.models));
<commit_msg>project show should request userDetails and rewardDetails before load components<commit_after>window.c.project.Show = (function(m, c, _, models, h){
  return {
    controller: function(args) {
      var vm = m.postgrest.filtersVM({project_id: 'eq'}),
          idVM = h.idVM,
          projectDetails = m.prop([]),
          userDetails = m.prop([]),
          rewardDetails = m.prop([]);

      vm.project_id(args.root.getAttribute('data-id'));

      models.projectDetail.getRowWithToken(vm.parameters()).then(function(data) {
        var project = data[0];
        projectDetails(data);

        idVM.id(project.user_id);
        models.userDetail.getRowWithToken(idVM.parameters()).then(userDetails);
      });

      models.rewardDetail.getPage(vm.parameters()).then(rewardDetails);

      return {
        vm: vm,
        projectDetails: projectDetails,
        userDetails: userDetails,
        rewardDetails: rewardDetails
      };
    },

    view: function(ctrl) {
      return _.map(ctrl.projectDetails(), function(project){
        return m('.project-show', [
          m.component(c.ProjectHeader, {project: project, userDetails: ctrl.userDetails}),
          m.component(c.ProjectTabs, {project: project}),
          m.component(c.ProjectMain, {project: project, rewardDetails: ctrl.rewardDetails}),
          (project.is_owner_or_admin ? m.component(c.ProjectNav, {project: project}) : '')
        ]);
      });
    }
  };
}(window.m, window.c, window._, window.c.models, window.c.h));
<|endoftext|>


<commit_before>// ==UserScript==
// @name        hvTrainer
// @name:zh-CN  【HV】训练
// @author      Dodying
// @namespace   https://github.com/dodying/Dodying-UserJs
// @supportURL  https://github.com/dodying/Dodying-UserJs/issues
// @icon        https://raw.githubusercontent.com/dodying/UserJs/master/Logo.png
// @include     http*://hentaiverse.org/*
// @include     http*://alt.hentaiverse.org/*
// @version     1.01b
// @grant       none
// @run-at      document-end
// ==/UserScript==
(function () {
  var dateObj = new Date();
  var countdownBox = document.createElement('div');
  countdownBox.className = 'trainCountdown';
  countdownBox.style.cssText = 'font-weight:bold;font-size:large;';
  $('div.clb').appendChild(countdownBox);
  if (!$('#progress_counter_1')) { //不位于训练界面或训练完成
    var timeEnd = localStorage.timeEnd || '';
    if (timeEnd === '' || timeEnd <= dateObj.getTime()) { //训练完成
      $('.trainCountdown').innerHTML = 'Train Completed';
      document.title = 'Train Completed';
    } else { //不位于训练界面
      var timeLast = parseInt((timeEnd - dateObj.getTime()) / 1000);
      $('.trainCountdown').innerHTML = timeLast;
      var timeDecrease = 0;
      var timeUpdateIntarval = setInterval(timeUpdate, 1000);
    }
  } else { //位于训练界面且训练中
    var nowTraining = $('#mainpane>div>table>tbody>tr>td>strong').innerText;
    var nowTrainingProcess = $('#progress_counter_1').innerText;
    var traningItems = document.querySelectorAll('#trainform tr>td:nth-child(1) .fd4>div');
    for (var i = 0; i < traningItems.length; i++) {
      if (traningItems[i].innerText === nowTraining) break;
    }
    var timeAll = parseInt($('#trainform tbody>tr:nth-child(' + (i + 2) + ')>td:nth-child(4) .fd4>div').innerText);
    var timeLast = parseInt(timeAll * (1 - 0.01 * nowTrainingProcess) * 60 * 60);
    localStorage.timeEnd = dateObj.getTime() + timeLast * 1000;
    $('.trainCountdown').innerHTML = timeLast;
    var timeDecrease = 0;
    var timeUpdateIntarval = setInterval(timeUpdate, 1000);
  }
  function timeUpdate() {
    timeDecrease++;
    if (timeLast <= timeDecrease) {
      $('.trainCountdown').innerHTML = 'Train Completed';
      document.title = 'Train Completed';
      clearInterval(timeUpdateIntarval);
    } else {
      var timeCountdownNow = timeLast - timeDecrease;
      var second = Math.floor(timeCountdownNow % 60);
      if (second < 10) second = '0' + second.toString();
      var minite = Math.floor((timeCountdownNow / 60) % 60);
      if (minite < 10) minite = '0' + minite.toString();
      var hour = Math.floor((timeCountdownNow / 3600) % 24);
      if (hour < 10) hour = '0' + hour.toString();
      $('.trainCountdown').innerText = hour + ':' + minite + ':' + second;
    }
  }
  function $(e) {
    return document.querySelector(e);
  }
}) ();
<commit_msg>Update hvTrainer.user.js<commit_after>// ==UserScript==
// @name        hvTrainer
// @name:zh-CN  【HV】训练
// @author      Dodying
// @namespace   https://github.com/dodying/Dodying-UserJs
// @supportURL  https://github.com/dodying/Dodying-UserJs/issues
// @icon        https://raw.githubusercontent.com/dodying/UserJs/master/Logo.png
// @include     http*://hentaiverse.org/*
// @include     http*://alt.hentaiverse.org/*
// @version     1.01b
// @grant       none
// @run-at      document-end
// ==/UserScript==
(function () {
  var dateObj = new Date();
  var countdownBox = document.createElement('div');
  countdownBox.className = 'trainCountdown';
  countdownBox.style.cssText = 'font-weight:bold;font-size:large;';
  $('div.clb').appendChild(countdownBox);
  if (!$('#progress_counter_1')) { //不位于训练界面或训练完成
    var trainTimeEnd = localStorage.trainTimeEnd || '';
    if (trainTimeEnd === '' || trainTimeEnd <= dateObj.getTime()) { //训练完成
      $('.trainCountdown').innerHTML = 'Train Completed';
      document.title = 'Train Completed';
    } else { //不位于训练界面
      var timeLast = parseInt((trainTimeEnd - dateObj.getTime()) / 1000);
      $('.trainCountdown').innerHTML = timeLast;
      var timeDecrease = 0;
      var timeUpdateIntarval = setInterval(timeUpdate, 1000);
    }
  } else { //位于训练界面且训练中
    var nowTraining = $('#mainpane>div>table>tbody>tr>td>strong').innerText;
    var nowTrainingProcess = $('#progress_counter_1').innerText;
    var traningItems = document.querySelectorAll('#trainform tr>td:nth-child(1) .fd4>div');
    for (var i = 0; i < traningItems.length; i++) {
      if (traningItems[i].innerText === nowTraining) break;
    }
    var timeAll = parseInt($('#trainform tbody>tr:nth-child(' + (i + 2) + ')>td:nth-child(4) .fd4>div').innerText);
    var timeLast = parseInt(timeAll * (1 - 0.01 * nowTrainingProcess) * 60 * 60);
    localStorage.trainTimeEnd = dateObj.getTime() + timeLast * 1000;
    $('.trainCountdown').innerHTML = timeLast;
    var timeDecrease = 0;
    var timeUpdateIntarval = setInterval(timeUpdate, 1000);
  }
  function timeUpdate() {
    timeDecrease++;
    if (timeLast <= timeDecrease) {
      $('.trainCountdown').innerHTML = 'Train Completed';
      document.title = 'Train Completed';
      clearInterval(timeUpdateIntarval);
    } else {
      var timeCountdownNow = timeLast - timeDecrease;
      var second = Math.floor(timeCountdownNow % 60);
      if (second < 10) second = '0' + second.toString();
      var minite = Math.floor((timeCountdownNow / 60) % 60);
      if (minite < 10) minite = '0' + minite.toString();
      var hour = Math.floor((timeCountdownNow / 3600) % 24);
      if (hour < 10) hour = '0' + hour.toString();
      $('.trainCountdown').innerText = hour + ':' + minite + ':' + second;
    }
  }
  function $(e) {
    return document.querySelector(e);
  }
}) ();
<|endoftext|>


<commit_before>var dataRef = new Firebase("https://sudarshan.firebaseio.com/");
var chatRef = new Firebase("https://sudarshan.firebaseio.com/**chats**");
var id = Math.random().toString(16).slice(2);

filepicker.setKey("AzauR2MBSBeslVoQIcZ8gz");

var ytplayer = null;
var mp4player = null;

var roomName = null;
var tokboxSession = null;
var tokboxToken = null;

var disableUntil;

var last_in = null;

var first_run;

var creating;

function makeRoom (name) {
  creating = true;
  $.getJSON("http://www.smuralidhar.com/pennapps2014s/generate.php", function(res){
      dataRef = dataRef.root();
      dataRef = dataRef.child(name);
      dataRef.on('value', incoming);
      dataRef.update(
      {
        type: null,
        video: null,
        seek: 0,
        timestamp: now(),
        playing: false,
        sessionId: res.sessionId,
        token: res.token,
        owner: id
      }
    );
    chatRef = chatRef.child(name);
    chatRef.on('child_added', chatIn);
    first_run = true;
    roomName = name;
  });
}

function joinRoom (name) {
  dataRef = dataRef.root();
  dataRef = dataRef.child(name);
  dataRef.on('value', incoming);
  chatRef = chatRef.child(name);
  chatRef.on('child_added', chatIn)
  first_run = true;
  roomName = name;
}

function chatIn (fb) {
  var data = fb.val();
  var date = new Date(data.timestamp).toLocaleTimeString()
  var me = data.id == id ? " class='self'" : "";
  var html = "
" +
                "" + data.name + " " +
                "" +
                date.substring(0, date.length - 6) + " " +
                "" + data.message + "" +
            "
";
  $("#chat ul").append(html);
}

function chatOut (msg) {
  var nickname = $("#nickname")[0].value;
  chatRef.push({
    id: id,
    name: (nickname ? nickname : id),
    message: msg,
    timestamp: new Date().getTime()
  })
}

function incoming (fb) {
  var data = fb.val();
  console.log("inc");
  console.log(data);

  if (!creating && data == null){
    alert("This room does not exist! Creating a new room.");
    makeRoom(roomName);
    return;
  }
  creating = false;

  if (last_in && (data.video != last_in.video || data.type != last_in.type)){
    $("#container").html("

");
    ytplayer = null;
    mp4player = null;
  }

  last_in = data;

  if (first_run){
    tokboxSession = data.sessionId;
    tokboxToken = data.token;
    showWelcomeMessage();
    $("#chat").prepend("
"+roomName+"
");
    $("#chat").show();
    runWebcam(tokboxSession, tokboxToken);
    first_run = false;
  }

  if (data.type == "YT") {
    if (ytplayer == null)
      makeYtPlayer(data.video);
    else
      handleYtInc(data);
  }
  else if (data.type == "mp4"){
    if (mp4player == null)
      makeMp4Player(data);
    else
      handleMp4Inc(data);
  }
}

function outgoing (playing, seek) {
  console.log("out");
  console.log({playing:playing, seek:seek});
  dataRef.update(
    {playing: playing, seek: seek, timestamp: now(), owner: id}
  );
}

function showWelcomeMessage () {
  $("#inputs").html("
	" +
    "<input id='vid' type='text' placeholder='Choose a video (Youtube or MP4)'></input>	" +
    "<button id='choose'>Load</button><button id='upload'>Upload</button>
");
  $("#choose").click(function(){
    var vid = $("#vid")[0].value + "#";
    if (vid.indexOf("youtube.com")>-1){
      var key = vid.substring(vid.indexOf("v=")+2, vid.indexOf("#"));
      var type = "YT";
      dataRef.update({type: type, video: key});
    }
    else if (vid.indexOf(".mp4") > -1){
      dataRef.update({type:"mp4", video: $("#vid")[0].value});
    }
    else
      alert ("Link not recognized");
  });
  $("#upload").click(function(){
    filepicker.pickAndStore(
      {extension: '.mp4', multiple:false},
      {location: 'S3'},
      function(InkBlobs){
        console.log(InkBlobs);
        var key = InkBlobs[0].key;
        var url = "http://s3-us-west-2.amazonaws.com/vidsync/" + key;
        dataRef.update({type: "mp4", video: url});
        $(".cover").hide();
      },
      function(FEError){
        $(".cover").hide();
      });
    coverUp();
  });
}

function makeYtPlayer(vid) {
  disableUntil = -1;
  var params = { allowScriptAccess: "always" };
  var atts = { id: "myytplayer" };
  swfobject.embedSWF("http://www.youtube.com/v/" + vid + "?version=3&controls=1&enablejsapi=1&playerapiid=ytplayer&allowfullscreen=1",
    "ytapiplayer", "100%", "100%", "8", null, null, params, atts);
}
function makeMp4Player(data) {
  disableUntil = false;
  jwplayer("ytapiplayer").setup({file: data.video, width: "80%", height: "90%"});
  mp4player = jwplayer();
  mp4player.onReady(function() {
    console.log('setup');

    mp4player.onSeek(mp4SeekListener);
    mp4player.onPlay(function() {mp4PlayPauseListener(true)});
    mp4player.onPause(function() {mp4PlayPauseListener(false)});

    handleMp4Inc(data);

    setInterval(function(){
      dataRef.once('value', function(data){
        var pres = now();
        var curr = mp4player.getPosition();
        data = data.val();
        if (data.playing)
          loc = data.seek + pres - data.timestamp;
        else
          loc = data.seek;
        var playing = mp4player.getState() == "PLAYING";

        console.log(curr - loc);
        if (Math.abs (curr - loc) > 2 ||
            data.playing != playing){
          if (data.owner == id)
            outgoing(playing, mp4player.getPosition());
          else
            handleMp4Inc(data);
      }
      })
    }, 2000);
  })
}

function onYouTubePlayerReady(playerId) {
  ytplayer = $("#myytplayer")[0];
  ytplayer.addEventListener("onStateChange", "ytListener");

  handleYtInc(last_in);

  setInterval(function(){
    dataRef.once('value', function(data){
      var pres = now();
      var curr = ytplayer.getCurrentTime();
      data = data.val();
      if (data.playing)
        loc = data.seek + pres - data.timestamp;
      else
        loc = data.seek;
      var playing = ytplayer.getPlayerState() == 1;

      //console.log(curr - loc);
      if (Math.abs (curr - loc) > 0.5 ||
          data.playing != playing)
        handleYtInc(data);
    })
  }, 2000);
}

function handleYtInc(data) {
  // disable the listener until state is correct
  if (data.playing)
    disableUntil = 1;
  else
    disableUntil = 2;

  if (data.playing)
    data.seek += now() - data.timestamp;

  ytplayer.seekTo(data.seek);

  if (data.playing)
    ytplayer.playVideo();
  else
    ytplayer.pauseVideo();
}

function handleMp4Inc(data) {
  if(data.owner == id){
    console.log("ignoring own")
    return;
  }
  if (data.playing)
    data.seek += now() - data.timestamp;

  // ignore 2 events (assume it take under .05 seconds)
  disableUntil = true;
  console.log("disabling handlers");
  setTimeout(function(){
    disableUntil = false;
    console.log("TIME UP!")
  }, 50)
  mp4player.seek(data.seek);
  mp4player.play(data.playing);

  console.log('done handle');
}

function ytListener (value){
  if (disableUntil > -1){
    console.log("ignoring- " + value);
    if (disableUntil == value)
      disableUntil = -1;
    return;
  }
  switch (value) {
    case -1:
      console.log("unstarted");
      disableUntil = 2;
      ytplayer.seekTo(0);
      ytplayer.pauseVideo();
      break;
    case 0:
      console.log("ended");
      break;
    case 1:
      console.log("playing");
      disableUntil = 1;
      ytplayer.pauseVideo();
      outgoing (true, ytplayer.getCurrentTime());
      break;
    case 2:
      console.log("paused");
      disableUntil = 2;
      ytplayer.playVideo();
      outgoing (false, ytplayer.getCurrentTime());
      break;
    case 3:
      console.log("buffering");
      break;
    case 5:
      console.log("cued");
      break;
  }
}

function mp4PlayPauseListener (play){
  if (disableUntil){
    console.log("ignoring " + play);
    return;
  }

  console.log(play);

  //mp4player.pause(play);
  outgoing (play, mp4player.getPosition());
}
function mp4SeekListener () {
  if (disableUntil){
    console.log("ignoring seek");
    return;
  }
  console.log("seek");
  outgoing (false, mp4player.getPosition(), function(){
    mp4player.pause();
  });
}

function now () {
  return new Date().getTime() / 1000;
}

$(document).ready (function() {

  // get facebook api
  $.getScript('//connect.facebook.net/en_UK/all.js', function(){
    FB.init({
      appId: '1534846250073976',
    });
    $('#loginbutton,#feedbutton').removeAttr('disabled');
    FB.getLoginStatus(updateStatusCallback);
  });

  $("#create").click(function() {
    makeRoom($("#room")[0].value)
  });
  $("#join").click(function() {
    joinRoom($("#room")[0].value)
  });

  $("#message").keyup(function(e){
    e.preventDefault();
    var key = window.event ? e.keyCode : e.which;
    if (key == '13') {
        chatOut($("#message")[0].value);
	$("#message")[0].value = null;
    }
  })
})

function coverUp() {
  var iframe = $("#filepicker_dialog")
  var x = iframe.offset().left;
  var y = iframe.offset().top;
  var cover = $("<div class='cover' style=\"z-index: 99999999999999; position:absolute;background:white; width:200px; height:75px;top:"+y+";left:"+x+"\"
").appendTo("body")

}
<commit_msg>facebook<commit_after>var dataRef = new Firebase("https://sudarshan.firebaseio.com/");
var chatRef = new Firebase("https://sudarshan.firebaseio.com/**chats**");
var id = Math.random().toString(16).slice(2);

filepicker.setKey("AzauR2MBSBeslVoQIcZ8gz");

var ytplayer = null;
var mp4player = null;

var roomName = null;
var tokboxSession = null;
var tokboxToken = null;

var disableUntil;

var last_in = null;

var first_run;

var creating;

function makeRoom (name) {
  creating = true;
  $.getJSON("http://www.smuralidhar.com/pennapps2014s/generate.php", function(res){
      dataRef = dataRef.root();
      dataRef = dataRef.child(name);
      dataRef.on('value', incoming);
      dataRef.update(
      {
        type: null,
        video: null,
        seek: 0,
        timestamp: now(),
        playing: false,
        sessionId: res.sessionId,
        token: res.token,
        owner: id
      }
    );
    chatRef = chatRef.child(name);
    chatRef.on('child_added', chatIn);
    first_run = true;
    roomName = name;
  });
}

function joinRoom (name) {
  dataRef = dataRef.root();
  dataRef = dataRef.child(name);
  dataRef.on('value', incoming);
  chatRef = chatRef.child(name);
  chatRef.on('child_added', chatIn)
  first_run = true;
  roomName = name;
}

function chatIn (fb) {
  var data = fb.val();
  var date = new Date(data.timestamp).toLocaleTimeString()
  var me = data.id == id ? " class='self'" : "";
  var html = "
" +
                "" + data.name + " " +
                "" +
                date.substring(0, date.length - 6) + " " +
                "" + data.message + "" +
            "
";
  $("#chat ul").append(html);
}

function chatOut (msg) {
  var nickname = $("#nickname")[0].value;
  chatRef.push({
    id: id,
    name: (nickname ? nickname : id),
    message: msg,
    timestamp: new Date().getTime()
  })
}

function incoming (fb) {
  var data = fb.val();
  console.log("inc");
  console.log(data);

  if (!creating && data == null){
    alert("This room does not exist! Creating a new room.");
    makeRoom(roomName);
    return;
  }
  creating = false;

  if (last_in && (data.video != last_in.video || data.type != last_in.type)){
    $("#container").html("

");
    ytplayer = null;
    mp4player = null;
  }

  last_in = data;

  if (first_run){
    tokboxSession = data.sessionId;
    tokboxToken = data.token;
    showWelcomeMessage();
    $("#chat").prepend("
"+roomName+"
");
    $("#chat").show();
    runWebcam(tokboxSession, tokboxToken);
    first_run = false;
  }

  if (data.type == "YT") {
    if (ytplayer == null)
      makeYtPlayer(data.video);
    else
      handleYtInc(data);
  }
  else if (data.type == "mp4"){
    if (mp4player == null)
      makeMp4Player(data);
    else
      handleMp4Inc(data);
  }
}

function outgoing (playing, seek) {
  console.log("out");
  console.log({playing:playing, seek:seek});
  dataRef.update(
    {playing: playing, seek: seek, timestamp: now(), owner: id}
  );
}

function showWelcomeMessage () {
  $("#inputs").html("
	" +
    "<input id='vid' type='text' placeholder='Choose a video (Youtube or MP4)'></input>	" +
    "<button id='choose'>Load</button><button id='upload'>Upload</button>
");
  $("#choose").click(function(){
    var vid = $("#vid")[0].value + "#";
    if (vid.indexOf("youtube.com")>-1){
      var key = vid.substring(vid.indexOf("v=")+2, vid.indexOf("#"));
      var type = "YT";
      dataRef.update({type: type, video: key});
    }
    else if (vid.indexOf(".mp4") > -1){
      dataRef.update({type:"mp4", video: $("#vid")[0].value});
    }
    else
      alert ("Link not recognized");
  });
  $("#upload").click(function(){
    filepicker.pickAndStore(
      {extension: '.mp4', multiple:false},
      {location: 'S3'},
      function(InkBlobs){
        console.log(InkBlobs);
        var key = InkBlobs[0].key;
        var url = "http://s3-us-west-2.amazonaws.com/vidsync/" + key;
        dataRef.update({type: "mp4", video: url});
        $(".cover").hide();
      },
      function(FEError){
        $(".cover").hide();
      });
    coverUp();
  });
}

function makeYtPlayer(vid) {
  disableUntil = -1;
  var params = { allowScriptAccess: "always" };
  var atts = { id: "myytplayer" };
  swfobject.embedSWF("http://www.youtube.com/v/" + vid + "?version=3&controls=1&enablejsapi=1&playerapiid=ytplayer&allowfullscreen=1",
    "ytapiplayer", "100%", "100%", "8", null, null, params, atts);
}
function makeMp4Player(data) {
  disableUntil = false;
  jwplayer("ytapiplayer").setup({file: data.video, width: "80%", height: "90%"});
  mp4player = jwplayer();
  mp4player.onReady(function() {
    console.log('setup');

    mp4player.onSeek(mp4SeekListener);
    mp4player.onPlay(function() {mp4PlayPauseListener(true)});
    mp4player.onPause(function() {mp4PlayPauseListener(false)});

    handleMp4Inc(data);

    setInterval(function(){
      dataRef.once('value', function(data){
        var pres = now();
        var curr = mp4player.getPosition();
        data = data.val();
        if (data.playing)
          loc = data.seek + pres - data.timestamp;
        else
          loc = data.seek;
        var playing = mp4player.getState() == "PLAYING";

        console.log(curr - loc);
        if (Math.abs (curr - loc) > 2 ||
            data.playing != playing){
          if (data.owner == id)
            outgoing(playing, mp4player.getPosition());
          else
            handleMp4Inc(data);
      }
      })
    }, 2000);
  })
}

function onYouTubePlayerReady(playerId) {
  ytplayer = $("#myytplayer")[0];
  ytplayer.addEventListener("onStateChange", "ytListener");

  handleYtInc(last_in);

  setInterval(function(){
    dataRef.once('value', function(data){
      var pres = now();
      var curr = ytplayer.getCurrentTime();
      data = data.val();
      if (data.playing)
        loc = data.seek + pres - data.timestamp;
      else
        loc = data.seek;
      var playing = ytplayer.getPlayerState() == 1;

      //console.log(curr - loc);
      if (Math.abs (curr - loc) > 0.5 ||
          data.playing != playing)
        handleYtInc(data);
    })
  }, 2000);
}

function handleYtInc(data) {
  // disable the listener until state is correct
  if (data.playing)
    disableUntil = 1;
  else
    disableUntil = 2;

  if (data.playing)
    data.seek += now() - data.timestamp;

  ytplayer.seekTo(data.seek);

  if (data.playing)
    ytplayer.playVideo();
  else
    ytplayer.pauseVideo();
}

function handleMp4Inc(data) {
  if(data.owner == id){
    console.log("ignoring own")
    return;
  }
  if (data.playing)
    data.seek += now() - data.timestamp;

  // ignore 2 events (assume it take under .05 seconds)
  disableUntil = true;
  console.log("disabling handlers");
  setTimeout(function(){
    disableUntil = false;
    console.log("TIME UP!")
  }, 50)
  mp4player.seek(data.seek);
  mp4player.play(data.playing);

  console.log('done handle');
}

function ytListener (value){
  if (disableUntil > -1){
    console.log("ignoring- " + value);
    if (disableUntil == value)
      disableUntil = -1;
    return;
  }
  switch (value) {
    case -1:
      console.log("unstarted");
      disableUntil = 2;
      ytplayer.seekTo(0);
      ytplayer.pauseVideo();
      break;
    case 0:
      console.log("ended");
      break;
    case 1:
      console.log("playing");
      disableUntil = 1;
      ytplayer.pauseVideo();
      outgoing (true, ytplayer.getCurrentTime());
      break;
    case 2:
      console.log("paused");
      disableUntil = 2;
      ytplayer.playVideo();
      outgoing (false, ytplayer.getCurrentTime());
      break;
    case 3:
      console.log("buffering");
      break;
    case 5:
      console.log("cued");
      break;
  }
}

function mp4PlayPauseListener (play){
  if (disableUntil){
    console.log("ignoring " + play);
    return;
  }

  console.log(play);

  //mp4player.pause(play);
  outgoing (play, mp4player.getPosition());
}
function mp4SeekListener () {
  if (disableUntil){
    console.log("ignoring seek");
    return;
  }
  console.log("seek");
  outgoing (false, mp4player.getPosition(), function(){
    mp4player.pause();
  });
}

function now () {
  return new Date().getTime() / 1000;
}

$(document).ready (function() {

  // get facebook api
  $.getScript('//connect.facebook.net/en_UK/all.js', function(){
    FB.init({
      appId: '1534846250073976',
    });
    $('#loginbutton,#feedbutton').removeAttr('disabled');
    FB.getLoginStatus(updateStatusCallback);

    $("#invite").click(function(){
      FB.ui({
        method: 'send',
        link: 'http://www.smuralidhar.com/vidsync',
      });
    });
  });

  $("#create").click(function() {
    makeRoom($("#room")[0].value)
  });
  $("#join").click(function() {
    joinRoom($("#room")[0].value)
  });

  $("#message").keyup(function(e){
    e.preventDefault();
    var key = window.event ? e.keyCode : e.which;
    if (key == '13') {
        chatOut($("#message")[0].value);
	$("#message")[0].value = null;
    }
  })
})

function coverUp() {
  var iframe = $("#filepicker_dialog")
  var x = iframe.offset().left;
  var y = iframe.offset().top;
  var cover = $("<div class='cover' style=\"z-index: 99999999999999; position:absolute;background:white; width:200px; height:75px;top:"+y+";left:"+x+"\"
").appendTo("body")

}
<|endoftext|>


<commit_before>/*jslint browser:true, plusplus:true, vars:true */
/*jshint browser:true, jquery:true */

(function ($) {
    'use strict';

    var options = $.lazyLoadXT;

    options.forceEvent += ' lazycomplete';
    options.autoLoad = options.autoLoad || 50;

    $(document).ready(function () {
        setTimeout(function () {
            $(window).trigger('lazycomplete');
        }, options.autoLoad);
    });

})(window.jQuery || window.Zepto);
<commit_msg>fix autoload addon<commit_after>/*jslint browser:true, plusplus:true, vars:true */
/*jshint browser:true, jquery:true */

(function ($) {
    'use strict';

    var options = $.lazyLoadXT;

    options.forceEvent += ' lazyautoload';
    options.autoLoadTime = options.autoLoadTime || 50;

    $(document).ready(function () {
        setTimeout(function () {
            $(window).trigger('lazyautoload');
        }, options.autoLoadTime);
    });

})(window.jQuery || window.Zepto);
<|endoftext|>


<commit_before>javascript: {
  var ap = window.ap;
  var aurl = (function(t) {
    function o(t) {
      if (~t.indexOf("audio_api_unavailable")) {
        var e = t.split("?extra=")[1].split("#"),
          o = "" === e[1] ? "" : a(e[1]);
        if (e = a(e[0]), "string" != typeof o || !e) return t;
        o = o ? o.split(String.fromCharCode(9)) : [];
        for (var s, r, n = o.length; n--;) {
          if (r = o[n].split(String.fromCharCode(11)), s = r.splice(0, 1, e)[0], !l[s]) return t;
          e = l[s].apply(null, r)
        }
        if (e && "http" === e.substr(0, 4)) return e
      }
      return t
    }

    function a(t) {
      if (!t || t.length % 4 == 1) return !1;
      for (var e, i, o = 0, a = 0, s = ""; i = t.charAt(a++);) i = r.indexOf(i), ~i && (e = o % 4 ? 64 * e + i : i, o++ % 4) && (s += String.fromCharCode(255 & e >> (-2 * o & 6)));
      return s
    }

    function s(t, e) {
      var i = t.length,
        o = [];
      if (i) {
        var a = i;
        for (e = Math.abs(e); a--;) e = (i * (a + 1) ^ e + a) % i, o[a] = e
      }
      return o
    };
    var r = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMN0PQRSTUVWXYZO123456789+/=",
      l = {
        v: function(t) {
          return t.split("").reverse().join("")
        },
        r: function(t, e) {
          t = t.split("");
          for (var i, o = r + r, a = t.length; a--;) i = o.indexOf(t[a]), ~i && (t[a] = o.substr(i - e, 1));
          return t.join("")
        },
        s: function(t, e) {
          var i = t.length;
          if (i) {
            var o = s(t, e),
              a = 0;
            for (t = t.split(""); ++a < i;) t[a] = t.splice(o[i - 1 - a], 1, t[a])[0];
            t = t.join("")
          }
          return t
        },
        i: function(t, e) {
          return l.s(t, e ^ vk.id)
        },
        x: function(t, e) {
          var i = [];
          return e = e.charCodeAt(0), each(t.split(""), function(t, o) {
            i.push(String.fromCharCode(o.charCodeAt(0) ^ e))
          }), i.join("")
        }
      };
    return o(t);
  })(ap._currentAudio[2]);

  var aname = ap._currentAudio[4] + ' - ' + ap._currentAudio[3] + '.ts';
  console.log('URL: ' + aurl);
  console.log('Title: ' + aname);
  acmd = "\"C:\\Program Files (x86)\\Streamlink\\bin\\streamlink.exe\" --hls-segment-threads 10 -f -o \"C:\\Downloads\\Music\\"+aname.replace(/&|[&*\\\/]/g, "_")+"\" "+aurl+" best";
  console.log('cmd: ' + acmd);
  alert("Copy and run this:\n"+acmd);
}<commit_msg>save to mp3<commit_after>javascript: {
  var ap = window.ap;
  var aurl = (function(t) {
    function o(t) {
      if (~t.indexOf("audio_api_unavailable")) {
        var e = t.split("?extra=")[1].split("#"),
          o = "" === e[1] ? "" : a(e[1]);
        if (e = a(e[0]), "string" != typeof o || !e) return t;
        o = o ? o.split(String.fromCharCode(9)) : [];
        for (var s, r, n = o.length; n--;) {
          if (r = o[n].split(String.fromCharCode(11)), s = r.splice(0, 1, e)[0], !l[s]) return t;
          e = l[s].apply(null, r)
        }
        if (e && "http" === e.substr(0, 4)) return e
      }
      return t
    }

    function a(t) {
      if (!t || t.length % 4 == 1) return !1;
      for (var e, i, o = 0, a = 0, s = ""; i = t.charAt(a++);) i = r.indexOf(i), ~i && (e = o % 4 ? 64 * e + i : i, o++ % 4) && (s += String.fromCharCode(255 & e >> (-2 * o & 6)));
      return s
    }

    function s(t, e) {
      var i = t.length,
        o = [];
      if (i) {
        var a = i;
        for (e = Math.abs(e); a--;) e = (i * (a + 1) ^ e + a) % i, o[a] = e
      }
      return o
    };
    var r = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMN0PQRSTUVWXYZO123456789+/=",
      l = {
        v: function(t) {
          return t.split("").reverse().join("")
        },
        r: function(t, e) {
          t = t.split("");
          for (var i, o = r + r, a = t.length; a--;) i = o.indexOf(t[a]), ~i && (t[a] = o.substr(i - e, 1));
          return t.join("")
        },
        s: function(t, e) {
          var i = t.length;
          if (i) {
            var o = s(t, e),
              a = 0;
            for (t = t.split(""); ++a < i;) t[a] = t.splice(o[i - 1 - a], 1, t[a])[0];
            t = t.join("")
          }
          return t
        },
        i: function(t, e) {
          return l.s(t, e ^ vk.id)
        },
        x: function(t, e) {
          var i = [];
          return e = e.charCodeAt(0), each(t.split(""), function(t, o) {
            i.push(String.fromCharCode(o.charCodeAt(0) ^ e))
          }), i.join("")
        }
      };
    return o(t);
  })(ap._currentAudio[2]);

  var aname = ap._currentAudio[4] + ' - ' + ap._currentAudio[3] + '.mp3';
  console.log('URL: ' + aurl);
  console.log('Title: ' + aname);
  acmd = "\"C:\\Program Files (x86)\\Streamlink\\bin\\streamlink.exe\" -l warning --hls-segment-threads 10 -f -O "+aurl+" best | \"C:\\Program Files (x86)\\Streamlink\\ffmpeg\\ffmpeg.exe\" -loglevel warning -y -i pipe:0 -c copy \"C:\\Downloads\\Music\\"+aname.replace(/&|[&*\\\/]/g, "_")+"\"";
  console.log('cmd: ' + acmd);
  alert("Copy and run this:\n"+acmd);
}
<|endoftext|>


<commit_before>/*
 *  Sizing v2.0 - jQuery Type Char Animation
 *
 *  Copyright (c) 2012, 2014 Deux Huit Huit (http://www.deuxhuithuit.com/)
 *  Licensed under the MIT (https://github.com/DeuxHuitHuit/jQuery-type-char-animation/blob/master/LICENSE.txt)
 */

(function ($, undefined) {

	'use strict';

	var getCharTime = function (char, tPos) {
		return ((Math.random() * 10000) % 30) + 50;
	};

	var getSpaceTime = function (tPos) {
		return 150;
	};

	var typeCharAnimation = function(options) {
		var

		t = $(this),

		// ensure options
		o = $.extend({}, $.typeCharAnimation.defaults, options);

		if (t.length != 1) {
			if (!!window.console) {
				console.error('[type-char] can only be called on single elements');
			}
		} else {
			// start animation
			startTypeChar(t, o);
		}
	};

	var startTypeChar = function (t, options) {

		var

		txtBox = $(t),

		dT = options.text.split(''),

		tPos = 0,

		valueFx = txtBox[txtBox.is('input, textarea') ? 'val' : 'text'],

		typeChar = function () {
			var char = dT[tPos];

			// add a new char
			valueFx.call(txtBox, valueFx.call(txtBox) + char);

			// increment pointer
			tPos++;

			// focus the element
			txtBox.focus();

			if (tPos < dT.length) {
				setTimeout(typeChar, char == ' ' ? options.spaceTime(tPos) : options.charTime(char, tPos));
				if ($.isFunction(options.step)) {
					options.step.call(t, char, tPos);
				}

			} else {
				if ($.isFunction(options.complete)) {
					options.complete.call(t);
				}
			}
		};

		// set initial text
		if (!!options.initialText) {
			valueFx.call(txtBox, options.initialText);
		}

		// focus
		txtBox.focus();

		// type first char
		typeChar();
	};

	// ACTUAL PLUGIN
	$.fn.extend({
		typeCharAnimation: typeCharAnimation
	});

	// defaults
	$.typeCharAnimation = {
		defaults: {
			initialText: null, // string
			text: null, // string
			step: null, // function (char, tPos)
			complete: null, // function ()
			blockUserInput: false,
			charTime: getCharTime, // function (char, tPos)
			spaceTime: getSpaceTime // function (tPos)
		}
	};

})(jQuery);<commit_msg>code format (bis)<commit_after>/*
 *  Sizing v2.0 - jQuery Type Char Animation
 *
 *  Copyright (c) 2012, 2014 Deux Huit Huit (http://www.deuxhuithuit.com/)
 *  Licensed under the MIT (https://github.com/DeuxHuitHuit/jQuery-type-char-animation/blob/master/LICENSE.txt)
 */

(function ($, undefined) {

	'use strict';

	var getCharTime = function (char, tPos) {
		return ((Math.random() * 10000) % 30) + 50;
	};

	var getSpaceTime = function (tPos) {
		return 150;
	};

	var typeCharAnimation = function(options) {
		var t = $(this);

		// ensure options
		var o = $.extend({}, $.typeCharAnimation.defaults, options);

		if (t.length != 1) {
			if (!!window.console) {
				console.error('[type-char] can only be called on single elements');
			}
		} else {
			// start animation
			startTypeChar(t, o);
		}
	};

	var startTypeChar = function (t, options) {
		var txtBox = $(t);

		var dT = options.text.split('');

		var tPos = 0;

		var valueFx = txtBox[txtBox.is('input, textarea') ? 'val' : 'text'];

		var typeChar = function () {
			var char = dT[tPos];

			// add a new char
			valueFx.call(txtBox, valueFx.call(txtBox) + char);

			// increment pointer
			tPos++;

			// focus the element
			txtBox.focus();

			if (tPos < dT.length) {
				setTimeout(typeChar, char == ' ' ? options.spaceTime(tPos) : options.charTime(char, tPos));
				if ($.isFunction(options.step)) {
					options.step.call(t, char, tPos);
				}

			} else {
				if ($.isFunction(options.complete)) {
					options.complete.call(t);
				}
			}
		};

		// set initial text
		if (!!options.initialText) {
			valueFx.call(txtBox, options.initialText);
		}

		// focus
		txtBox.focus();

		// type first char
		typeChar();
	};

	// ACTUAL PLUGIN
	$.fn.extend({
		typeCharAnimation: typeCharAnimation
	});

	// defaults
	$.typeCharAnimation = {
		defaults: {
			initialText: null, // string
			text: null, // string
			step: null, // function (char, tPos)
			complete: null, // function ()
			blockUserInput: false,
			charTime: getCharTime, // function (char, tPos)
			spaceTime: getSpaceTime // function (tPos)
		}
	};

})(jQuery);<|endoftext|>


<commit_before>$( document ).ready(function() {
	var $output = $('#articles');
	var $outputElement = $('
');
	var $form = $("form#wiki");
	var $search = $form.find("input[type=search]");
	var $progress = $('#progress');
	var $scrollTopLink = $('#scrollTop');
	var pageids = [];
	var add_level;

	/* Setup button handler */
	$form.submit(function( event ) {
		event.preventDefault();
		$('#submit-btn').prop('disabled', true);
		var start_article = $search.val();
		add_level = $(this).find("input[type=range]").val()
		console.log('Start: %c' + start_article, 'color: green');
		console.log("ADD level", add_level)
		setProgress(start_article);
		// Reset
		pageids = [];
		$output.empty();
		$scrollTopLink.hide();
		// Start
		minifyUI();
		getWikiSentence(start_article);
	});

	handleParams();

	// Enable click handler to work for elements that are created dynamically
	// Equivalent of deprecated .live()
	$output.on("click", "a.internal", function(event) {
		event.preventDefault();
		var query = $(this).attr('href').split('#')[1];
		handleParams(query);
	});
	$('#by').on("click", "a.internal", function(event) {
		event.preventDefault();
		handleParams($(this).attr('href'));
	});

	function minifyUI() {
		$('#header-container').animate({
			marginLeft: "20px",
			marginTop: "20px"
		});
		$('#header-container').addClass('minified');
		$('#logo-container').animate({
			width: "3em",
			marginLeft: "120px",
			marginTop: "10px"
		});
		$('#logo-container').addClass('minified');
		$('#settings-div').animate({
			marginTop: '-100px',
			paddingBottom: '20px'
		});
	}

	function handleParams(param) {
		var query = param || window.location.hash.substr(1);
		console.log('query: ', query);
		if (!query) { return }
		$search.val(query.replace(/_/g,' '));
		$form.submit();
	}

	/* Returns the query URL for the Wikipedia API of a given page */
	function wikiApiFirstSectionUrl(page) {
		var wiki_api_base = "https://en.wikipedia.org/w/api.php?"
		params = {
			action: "parse",
			format: "json",
			// Prevent double encode, page is already urlencoded
			page: decodeURI(page),
			redirects: 1,
			prop: "text",
			section: 0,
			disableeditsection: 1,
			disabletoc: 1,
			noimages: 1
		}
		/* "callback=?" makes jquery pick a custom name for the callback.
		JQuery then knows to set the datatype to JSONP.
		The server wraps the requested JSON in a function call with the callback's name.*/
		return wiki_api_base + $.param(params) + "&callback=?";
	}

	//TODO deduplicate
	/* Returns the query URL for the Wikipedia API of a given page's categories */
	function wikiApiCategoriesUrl(page) {
		var wiki_api_base = "https://en.wikipedia.org/w/api.php?"
		params = {
			action: "parse",
			format: "json",
			// Prevent double encode, page is already urlencoded
			page: decodeURI(page),
			redirects: 1,
			prop: "categories",
			//disablelimitreport: 1, //increases response times drastically
			disableeditsection: 1,
			disabletoc: 1,
			noimages: 1
		}
		/* "callback=?" makes jquery pick a custom name for the callback.
		JQuery then knows to set the datatype to JSONP.
		The server wraps the requested JSON in a function call with the callback's name.*/
		return wiki_api_base + $.param(params) + "&callback=?";
	}

	/* Returns a parsed structure queryable with JQuery from an HTML string */
	function parseToDOM(html_string) {
		// http://stackoverflow.com/questions/15403600
		return $($.parseHTML('
' + html_string + '
'));
	}

	/* Return HTML without elements that should not be rendered */
	function cleanWikiHTML(html_string) {
		temp_dom = parseToDOM(html_string);
		//TODO this breaks on "Magic"
		//temp_dom = temp_dom.children('p, ul, ol').first().nextUntil('h2', 'p, ul, ol');
		// The response comes wrapped in a 'mw-parser-output' div...
		temp_dom = temp_dom.children('div.mw-parser-output').children('p, ul, ol:not(.references)');

		var html = '';
		temp_dom.each(function() { html += $(this).prop('outerHTML'); });
		console.log('Cleaned HTMl length:', html.length);
		return html
	}

	/* Returns a text up to a sentence that ends with an  tag */
	function parseForSentence(html_string) {
		if (add_level == 1){
			var dividers = ['.', ').', ';', ');', '!', ')!', '?', ')?', '
']; // wont this ignore instances of ";" or "!" even if they come before the first "."???
			// Old fashioned iteration. [].forEach does not support breaking
			// out of the loop, see
			// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
			for(var i = 0; i < dividers.length; i++) {
				var divider = '' + dividers[i];
				var split = html_string.split(divider);
				if ( split.length > 1 ) {
					//TODO make "ADD-level" configurable, e.g. use last possible link
					// true: Continue, sentence has a link at the end
					return [split[0] + divider, true]
				}
			}
		}
		else if (add_level == 3){
			var divider = ''
			var split = html_string.split(divider);
			if ( split.length > 1 ) {
				return [split[0] + divider + '—', true]
			}
		}
		else if (add_level == 2){
			var first_divider = '';
			var i = html_string.indexOf(first_divider) + first_divider.length;
			var constant_part = html_string.substring(0, i);
			var split_part = html_string.substring(i, html_string.length);
			console.log(split_part);
			var divider = ''
			var split = split_part.split(divider);
			if ( split.length > 1 ) {
				return [constant_part + split[0] + divider + '—', true]
			}

		}
		console.log('No next wiki page');
		// false: No link could be found. No next wiki page available
		return [html_string, false]
	}

	/* Return the name of the page linked to from the last  tag */
	function getNextEntryName(sentence_dom) {
		//TODO use first link and cut of the sentence to make it properly ADD.
		var last_a = sentence_dom.find('a:last');
		var next_entry = last_a.attr('href').split('/wiki/')[1];
		var title = last_a.attr('title');
		console.log('Next: %c' + title, 'color: green');
		setProgress(title);
		return next_entry
	}

	/* Append text to the page */
	function appendSentences(dom, include_markup) {
		dom = dom.clone();
		dom.find('a').each(function() {
			// Don't link to Wikipedia help pages
			if ( $(this).attr('href').startsWith('/wiki/Help:') ) {
				$(this).replaceWith($(this).text());
			} else {
				$(this).attr('href', this.href.replace('/wiki/', '#'));
				$(this).addClass('internal');
			}
		});
		if ( include_markup ) {
			sentence = dom.html();
		} else {
			sentence = dom.text();
		}
		$output.append($outputElement.clone().html(sentence));
		// Scroll to new bottom of page
		$("html, body").animate({ scrollTop: $(document).height() }, 1);
	}

	function setProgress(title) {
		$progress.text('Looking up \'' + title + '\'...');
	}

	/* Return whether the id was already queried, also stores passed ids */
	function isRepetition(page_id) {
		if ( pageids.indexOf(page_id) > -1 ) {
			console.log('Repetition detected.');
			return true
		}
		pageids.push(page_id);
		return false
	}

	function getFirstHref(html_string) {
		var dom = parseToDOM(cleanWikiHTML(html_string));
		var first_a = dom.find('a:first');
		var next_entry = first_a.attr('href').split('/wiki/')[1];
		console.log('Next: ', first_a.attr('title'));
		return next_entry
	}

	// Cleanup after one query is finished
	function done(reason) {
		$('#submit-btn').prop('disabled', false);
		var word_count = $output.text().trim().split(/\s+/).length;
		console.log(word_count);
		$progress.text('Done. ' + reason + '. ' + word_count + ' words written.');
		$scrollTopLink.show();
	}

	function getWikiSentence(page_title){
		var cat_query_url = wikiApiCategoriesUrl(page_title);
		var cat_query = $.getCachedJSON( cat_query_url, 250 );
		cat_query.fail(function() { console.error("Error: ", cat_query_url); });
		var text_query_url = wikiApiFirstSectionUrl(page_title);
		var text_query = $.getCachedJSON( text_query_url, 250 );
		text_query.fail(function() { console.error("Error: ", text_query_url); });

		$.when( cat_query, text_query ).done( function(cat_resp, text_resp){
			//var [cat_data, cat_status, cat_jqXHR] = cat_resp;
			var cat_data = cat_resp[0];
			//var [text_data, text_status, text_jqXHR] = text_resp;
			var text_data = text_resp[0];
			var pageid = cat_data.parse.pageid;
			var section_text = text_data.parse.text["*"];
			console.assert(pageid == text_data.parse.pageid, pageid, text_data.parse.pageid);
			if ( isRepetition(pageid) ) {
				done('Repetition detected for article: "' + page_title.replace(/_/g, ' ') + '"');
				return
			}
			var categories = cat_data.parse.categories;
			var isDis = categories.some(function(e){
				return e["*"].toLowerCase().indexOf('disambiguation') > -1
			});
			if ( isDis ) {
				console.log('Disambiguation page found: ', cat_data.parse.title);
				getWikiSentence(getFirstHref(section_text));
			} else {
				var html = cleanWikiHTML(section_text);
				//TODO Do not return next_entry_available here, make getNextEntryName check
				var [sentence, next_entry_available] = parseForSentence(html);
				var sentence_dom = parseToDOM(sentence);
				// TODO checkbox for include_markup
				appendSentences(sentence_dom, true);
				if ( !next_entry_available ) { done('No next Wiki page was found'); return }
				var next_page = getNextEntryName(sentence_dom);
				getWikiSentence(next_page);
			}
		}); //done
	} //getWikiSentence
}); //document.ready
<commit_msg>Remove text in brackets. It always just sent you to IPA page.<commit_after>$( document ).ready(function() {
	var $output = $('#articles');
	var $outputElement = $('
');
	var $form = $("form#wiki");
	var $search = $form.find("input[type=search]");
	var $progress = $('#progress');
	var $scrollTopLink = $('#scrollTop');
	var pageids = [];
	var add_level;

	/* Setup button handler */
	$form.submit(function( event ) {
		event.preventDefault();
		$('#submit-btn').prop('disabled', true);
		var start_article = $search.val();
		add_level = $(this).find("input[type=range]").val()
		console.log('Start: %c' + start_article, 'color: green');
		console.log("ADD level", add_level)
		setProgress(start_article);
		// Reset
		pageids = [];
		$output.empty();
		$scrollTopLink.hide();
		// Start
		minifyUI();
		getWikiSentence(start_article);
	});

	handleParams();

	// Enable click handler to work for elements that are created dynamically
	// Equivalent of deprecated .live()
	$output.on("click", "a.internal", function(event) {
		event.preventDefault();
		var query = $(this).attr('href').split('#')[1];
		handleParams(query);
	});
	$('#by').on("click", "a.internal", function(event) {
		event.preventDefault();
		handleParams($(this).attr('href'));
	});

	function minifyUI() {
		$('#header-container').animate({
			marginLeft: "20px",
			marginTop: "20px"
		});
		$('#header-container').addClass('minified');
		$('#logo-container').animate({
			width: "3em",
			marginLeft: "120px",
			marginTop: "10px"
		});
		$('#logo-container').addClass('minified');
		$('#settings-div').animate({
			marginTop: '-100px',
			paddingBottom: '20px'
		});
	}

	function handleParams(param) {
		var query = param || window.location.hash.substr(1);
		console.log('query: ', query);
		if (!query) { return }
		$search.val(query.replace(/_/g,' '));
		$form.submit();
	}

	/* Returns the query URL for the Wikipedia API of a given page */
	function wikiApiFirstSectionUrl(page) {
		var wiki_api_base = "https://en.wikipedia.org/w/api.php?"
		params = {
			action: "parse",
			format: "json",
			// Prevent double encode, page is already urlencoded
			page: decodeURI(page),
			redirects: 1,
			prop: "text",
			section: 0,
			disableeditsection: 1,
			disabletoc: 1,
			noimages: 1
		}
		/* "callback=?" makes jquery pick a custom name for the callback.
		JQuery then knows to set the datatype to JSONP.
		The server wraps the requested JSON in a function call with the callback's name.*/
		return wiki_api_base + $.param(params) + "&callback=?";
	}

	//TODO deduplicate
	/* Returns the query URL for the Wikipedia API of a given page's categories */
	function wikiApiCategoriesUrl(page) {
		var wiki_api_base = "https://en.wikipedia.org/w/api.php?"
		params = {
			action: "parse",
			format: "json",
			// Prevent double encode, page is already urlencoded
			page: decodeURI(page),
			redirects: 1,
			prop: "categories",
			//disablelimitreport: 1, //increases response times drastically
			disableeditsection: 1,
			disabletoc: 1,
			noimages: 1
		}
		/* "callback=?" makes jquery pick a custom name for the callback.
		JQuery then knows to set the datatype to JSONP.
		The server wraps the requested JSON in a function call with the callback's name.*/
		return wiki_api_base + $.param(params) + "&callback=?";
	}

	/* Returns a parsed structure queryable with JQuery from an HTML string */
	function parseToDOM(html_string) {
		// http://stackoverflow.com/questions/15403600
		return $($.parseHTML('
' + html_string + '
'));
	}

	/* Return HTML without elements that should not be rendered */
	function cleanWikiHTML(html_string) {
		temp_dom = parseToDOM(html_string);
		//TODO this breaks on "Magic"
		//temp_dom = temp_dom.children('p, ul, ol').first().nextUntil('h2', 'p, ul, ol');
		// The response comes wrapped in a 'mw-parser-output' div...
		console.log(temp_dom)
		temp_dom = temp_dom.children('div.mw-parser-output').children('p, ul, ol:not(.references)');

		temp_dom.find('sup').remove();
        // Remove citations
        temp_dom.children('.references').remove();
        // I am trying to get rid of references that did not get removed in the children -> references.
        // Sometimes the wiki is badly formatted like "Eastern Mediterranean"
        // temp_dom.find('.references').remove();
        temp_dom.find('span.reference-text').remove();
        //Removes little listen buttons
        temp_dom.children('.metadata').remove();
        // The box showing coordinates is part of the main html
        temp_dom.find('span#coordinates').remove();
        // Remove links to pronunciation audio
        temp_dom.find('span.noexcerpt').remove();
        // Remove cite error that API returns
        temp_dom.find('span.mw-ext-cite-error').remove();

		var html = '';
		temp_dom.each(function() { html += $(this).prop('outerHTML'); });
		console.log('Cleaned HTMl length:', html.length);
		return html
	}

	/* Returns a text up to a sentence that ends with an  tag */
	function parseForSentence(html_string) {
		if (add_level == 1){
			var dividers = ['.', ').', ';', ');', '!', ')!', '?', ')?', '
']; // wont this ignore instances of ";" or "!" even if they come before the first "."???
			// Old fashioned iteration. [].forEach does not support breaking
			// out of the loop, see
			// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
			for(var i = 0; i < dividers.length; i++) {
				var divider = '' + dividers[i];
				var split = html_string.split(divider);
				if ( split.length > 1 ) {
					//TODO make "ADD-level" configurable, e.g. use last possible link
					// true: Continue, sentence has a link at the end
					return [split[0] + divider, true]
				}
			}
		}
		else if (add_level == 3){
			var divider = ''
			var split = html_string.split(divider);
			if ( split.length > 1 ) {
				return [split[0] + divider + '—', true]
			}
		}
		else if (add_level == 2){
			var first_divider = '';
			var i = html_string.indexOf(first_divider) + first_divider.length;
			var constant_part = html_string.substring(0, i);
			var split_part = html_string.substring(i, html_string.length);
			// console.log(split_part);

			var divider = ''
			var split = split_part.split(divider);
			if ( split.length > 1 ) {
				return [constant_part + split[0] + divider + '—', true]
			}

		}
		console.log('No next wiki page');
		// false: No link could be found. No next wiki page available
		return [html_string, false]
	}

	function removeFirstBracket(text) {
        // how close to the beginning does it have to be be deleted? Remember all the html markup is in there as well
        var chars_from_start = 250;
        if (text.substring(0, chars_from_start).indexOf('(') != -1) {
            console.log('Removing brackets');
            open_bracket_index = null;
            close_bracket_index = null;
            counter = 0;
            acounter = 0;
            for (i = 0; i < text.length; i++) {
                if (text[i] == '<' & text[i + 1] == 'a') {
                    acounter = acounter + 1
                } else if (text[i] == '/' & text[i + 1] == 'a' & text[i + 2] == '>') {
                    acounter = acounter - 1
                }

                if (acounter == 0) {
                    if (text[i] == '(') {
                        counter = counter + 1;
                        if (open_bracket_index == null) {
                            open_bracket_index = i;
                        }
                    } //if
                    else if (text[i] == ')') {
                        counter = counter - 1;
                        if (counter == 0) {
                            close_bracket_index = i + 2; //+1 is the bracket itself, +1 again for the space after it
                            return text.slice(0, open_bracket_index) + text.slice(close_bracket_index);
                        }
                    } //else if
                } //if
            } //for
        } // if
        return text
    } //function

	/* Return the name of the page linked to from the last  tag */
	function getNextEntryName(sentence_dom) {
		//TODO use first link and cut of the sentence to make it properly ADD.
		var last_a = sentence_dom.find('a:last');
		var next_entry = last_a.attr('href').split('/wiki/')[1];
		var title = last_a.attr('title');
		console.log('Next: %c' + title, 'color: green');
		setProgress(title);
		return next_entry
	}

	/* Append text to the page */
	function appendSentences(dom, include_markup) {
		dom = dom.clone();
		dom.find('a').each(function() {
			// Don't link to Wikipedia help pages
			if ( $(this).attr('href').startsWith('/wiki/Help:') ) {
				$(this).replaceWith($(this).text());
			} else {
				$(this).attr('href', this.href.replace('/wiki/', '#'));
				$(this).addClass('internal');
			}
		});
		if ( include_markup ) {
			sentence = dom.html();
		} else {
			sentence = dom.text();
		}
		$output.append($outputElement.clone().html(sentence));
		// Scroll to new bottom of page
		$("html, body").animate({ scrollTop: $(document).height() }, 1);
	}

	function setProgress(title) {
		$progress.text('Looking up \'' + title + '\'...');
	}

	/* Return whether the id was already queried, also stores passed ids */
	function isRepetition(page_id) {
		if ( pageids.indexOf(page_id) > -1 ) {
			console.log('Repetition detected.');
			return true
		}
		pageids.push(page_id);
		return false
	}

	function getFirstHref(html_string) {
		var dom = parseToDOM(cleanWikiHTML(html_string));
		var first_a = dom.find('a:first');
		var next_entry = first_a.attr('href').split('/wiki/')[1];
		console.log('Next: ', first_a.attr('title'));
		return next_entry
	}

	// Cleanup after one query is finished
	function done(reason) {
		$('#submit-btn').prop('disabled', false);
		var word_count = $output.text().trim().split(/\s+/).length;
		console.log(word_count);
		$progress.text('Done. ' + reason + '. ' + word_count + ' words written.');
		$scrollTopLink.show();
	}

	function getWikiSentence(page_title){
		var cat_query_url = wikiApiCategoriesUrl(page_title);
		var cat_query = $.getCachedJSON( cat_query_url, 250 );
		cat_query.fail(function() { console.error("Error: ", cat_query_url); });
		var text_query_url = wikiApiFirstSectionUrl(page_title);
		var text_query = $.getCachedJSON( text_query_url, 250 );
		text_query.fail(function() { console.error("Error: ", text_query_url); });

		$.when( cat_query, text_query ).done( function(cat_resp, text_resp){
			//var [cat_data, cat_status, cat_jqXHR] = cat_resp;
			var cat_data = cat_resp[0];
			//var [text_data, text_status, text_jqXHR] = text_resp;
			var text_data = text_resp[0];
			var pageid = cat_data.parse.pageid;
			var section_text = text_data.parse.text["*"];
			console.assert(pageid == text_data.parse.pageid, pageid, text_data.parse.pageid);
			if ( isRepetition(pageid) ) {
				done('Repetition detected for article: "' + page_title.replace(/_/g, ' ') + '"');
				return
			}
			var categories = cat_data.parse.categories;
			var isDis = categories.some(function(e){
				return e["*"].toLowerCase().indexOf('disambiguation') > -1
			});
			if ( isDis ) {
				console.log('Disambiguation page found: ', cat_data.parse.title);
				getWikiSentence(getFirstHref(section_text));
			} else {
				var html = cleanWikiHTML(section_text);
				html = removeFirstBracket(html)
				console.log("1 brack")
				console.log(html)
				//TODO Do not return next_entry_available here, make getNextEntryName check
				var [sentence, next_entry_available] = parseForSentence(html);
				var sentence_dom = parseToDOM(sentence);
				// TODO checkbox for include_markup
				appendSentences(sentence_dom, true);
				if ( !next_entry_available ) { done('No next Wiki page was found'); return }
				var next_page = getNextEntryName(sentence_dom);
				getWikiSentence(next_page);
			}
		}); //done
	} //getWikiSentence
}); //document.ready
<|endoftext|>


<commit_before>angular.module('copayApp.controllers').controller('paperWalletController',
  function($scope, $timeout, $log, $ionicModal, $ionicHistory, feeService, popupService, gettextCatalog, platformInfo, configService, profileService, $state, bitcore, ongoingProcess, txFormatService, $stateParams, walletService) {

    function _scanFunds(cb) {
      function getPrivateKey(scannedKey, isPkEncrypted, passphrase, cb) {
        if (!isPkEncrypted) return cb(null, scannedKey);
        $scope.wallet.decryptBIP38PrivateKey(scannedKey, passphrase, null, cb);
      };

      function getBalance(privateKey, cb) {
        $scope.wallet.getBalanceFromPrivateKey(privateKey, cb);
      };

      function checkPrivateKey(privateKey) {
        try {
          new bitcore.PrivateKey(privateKey, 'livenet');
        } catch (err) {
          return false;
        }
        return true;
      };

      getPrivateKey($scope.scannedKey, $scope.isPkEncrypted, $scope.passphrase, function(err, privateKey) {
        if (err) return cb(err);
        if (!checkPrivateKey(privateKey)) return cb(new Error('Invalid private key'));

        getBalance(privateKey, function(err, balance) {
          if (err) return cb(err);
          return cb(null, privateKey, balance);
        });
      });
    };

    $scope.scanFunds = function() {
      ongoingProcess.set('scanning', true);
      $timeout(function() {
        _scanFunds(function(err, privateKey, balance) {
          ongoingProcess.set('scanning', false);
          if (err) {
            $log.error(err);
            popupService.showAlert(gettextCatalog.getString('Error scanning funds:'), err || err.toString());
            $state.go('tabs.home');
          } else {
            $scope.privateKey = privateKey;
            $scope.balanceSat = balance;
            if ($scope.balanceSat <= 0)
              popupService.showAlert(gettextCatalog.getString('Error'), gettextCatalog.getString('Not funds found'));
            var config = configService.getSync().wallet.settings;
            $scope.balance = txFormatService.formatAmount(balance) + ' ' + config.unitName;
          }
          $scope.$apply();
        });
      }, 100);
    };

    function _sweepWallet(cb) {
      walletService.getAddress($scope.wallet, true, function(err, destinationAddress) {
        if (err) return cb(err);

        $scope.wallet.buildTxFromPrivateKey($scope.privateKey, destinationAddress, null, function(err, testTx) {
          if (err) return cb(err);
          var rawTxLength = testTx.serialize().length;
          feeService.getCurrentFeeRate('livenet', null, function(err, feePerKB) {
            var opts = {};
            opts.fee = Math.round((feePerKB * rawTxLength) / 2000);
            $scope.wallet.buildTxFromPrivateKey($scope.privateKey, destinationAddress, opts, function(err, tx) {
              if (err) return cb(err);
              $scope.wallet.broadcastRawTx({
                rawTx: tx.serialize(),
                network: 'livenet'
              }, function(err, txid) {
                if (err) return cb(err);
                return cb(null, destinationAddress, txid);
              });
            });
          });
        });
      });
    };

    $scope.sweepWallet = function() {
      ongoingProcess.set('sweepingWallet', true);
      $scope.sending = true;

      $timeout(function() {
        _sweepWallet(function(err, destinationAddress, txid) {
          ongoingProcess.set('sweepingWallet', false);
          $scope.sending = false;
          if (err) {
            $log.error(err);
            popupService.showAlert(gettextCatalog.getString('Error sweeping wallet:'), err || err.toString());
          } else {
            $scope.sendStatus = 'success';
          }
          $scope.$apply();
        });
      }, 100);
    };

    $scope.onSuccessConfirm = function() {
      $state.go('tabs.home');
    };

    $scope.onWalletSelect = function(wallet) {
      $scope.wallet = wallet;
    };

    $scope.showWalletSelector = function() {
      if ($scope.singleWallet) return;
      $scope.walletSelectorTitle = gettextCatalog.getString('Transfer to');
      $scope.showWallets = true;
    };

    $scope.$on("$ionicView.beforeEnter", function(event, data) {
      $scope.scannedKey = (data.stateParams && data.stateParams.privateKey) ? data.stateParams.privateKey : null;
      $scope.isPkEncrypted = $scope.scannedKey ? ($scope.scannedKey.substring(0, 2) == '6P') : null;
      $scope.sendStatus = null;
      $scope.error = false;

      $scope.wallets = profileService.getWallets({
        onlyComplete: true,
        network: 'livenet',
      });
      $scope.singleWallet = $scope.wallets.length == 1;

      if (!$scope.wallets || !$scope.wallets.length) {
        $scope.noMatchingWallet = true;
        return;
      }
    });

    $scope.$on("$ionicView.enter", function(event, data) {
      $scope.wallet = $scope.wallets[0];
      if (!$scope.wallet) return;
      if (!$scope.isPkEncrypted) $scope.scanFunds();
      else {
        var message = gettextCatalog.getString('Private key encrypted. Enter password');
        popupService.showPrompt(null, message, null, function(res) {
          $scope.passphrase = res;
          $scope.scanFunds();
        });
      }
    });

  });
<commit_msg>fix sweep paper wallet<commit_after>angular.module('copayApp.controllers').controller('paperWalletController',
  function($scope, $timeout, $log, $ionicModal, $ionicHistory, feeService, popupService, gettextCatalog, platformInfo, configService, profileService, $state, bitcore, ongoingProcess, txFormatService, $stateParams, walletService) {

    function _scanFunds(cb) {
      function getPrivateKey(scannedKey, isPkEncrypted, passphrase, cb) {
        if (!isPkEncrypted) return cb(null, scannedKey);
        $scope.wallet.decryptBIP38PrivateKey(scannedKey, passphrase, null, cb);
      };

      function getBalance(privateKey, cb) {
        $scope.wallet.getBalanceFromPrivateKey(privateKey, cb);
      };

      function checkPrivateKey(privateKey) {
        try {
          new bitcore.PrivateKey(privateKey, 'livenet');
        } catch (err) {
          return false;
        }
        return true;
      };

      getPrivateKey($scope.scannedKey, $scope.isPkEncrypted, $scope.passphrase, function(err, privateKey) {
        if (err) return cb(err);
        if (!checkPrivateKey(privateKey)) return cb(new Error('Invalid private key'));

        getBalance(privateKey, function(err, balance) {
          if (err) return cb(err);
          return cb(null, privateKey, balance);
        });
      });
    };

    $scope.scanFunds = function() {
      ongoingProcess.set('scanning', true);
      $timeout(function() {
        _scanFunds(function(err, privateKey, balance) {
          ongoingProcess.set('scanning', false);
          if (err) {
            $log.error(err);
            popupService.showAlert(gettextCatalog.getString('Error scanning funds:'), err || err.toString());
            $state.go('tabs.home');
          } else {
            $scope.privateKey = privateKey;
            $scope.balanceSat = balance;
            if ($scope.balanceSat <= 0)
              popupService.showAlert(gettextCatalog.getString('Error'), gettextCatalog.getString('Not funds found'));
            var config = configService.getSync().wallet.settings;
            $scope.balance = txFormatService.formatAmount(balance) + ' ' + config.unitName;
          }
          $scope.$apply();
        });
      }, 100);
    };

    function _sweepWallet(cb) {
      walletService.getAddress($scope.wallet, true, function(err, destinationAddress) {
        if (err) return cb(err);

        $scope.wallet.buildTxFromPrivateKey($scope.privateKey, destinationAddress, null, function(err, testTx) {
          if (err) return cb(err);
          var rawTxLength = testTx.serialize().length;
          feeService.getCurrentFeeRate('livenet', function(err, feePerKB) {
            var opts = {};
            opts.fee = Math.round((feePerKB * rawTxLength) / 2000);
            $scope.wallet.buildTxFromPrivateKey($scope.privateKey, destinationAddress, opts, function(err, tx) {
              if (err) return cb(err);
              $scope.wallet.broadcastRawTx({
                rawTx: tx.serialize(),
                network: 'livenet'
              }, function(err, txid) {
                if (err) return cb(err);
                return cb(null, destinationAddress, txid);
              });
            });
          });
        });
      });
    };

    $scope.sweepWallet = function() {
      ongoingProcess.set('sweepingWallet', true);
      $scope.sending = true;

      $timeout(function() {
        _sweepWallet(function(err, destinationAddress, txid) {
          ongoingProcess.set('sweepingWallet', false);
          $scope.sending = false;
          if (err) {
            $log.error(err);
            popupService.showAlert(gettextCatalog.getString('Error sweeping wallet:'), err || err.toString());
          } else {
            $scope.sendStatus = 'success';
          }
          $scope.$apply();
        });
      }, 100);
    };

    $scope.onSuccessConfirm = function() {
      $state.go('tabs.home');
    };

    $scope.onWalletSelect = function(wallet) {
      $scope.wallet = wallet;
    };

    $scope.showWalletSelector = function() {
      if ($scope.singleWallet) return;
      $scope.walletSelectorTitle = gettextCatalog.getString('Transfer to');
      $scope.showWallets = true;
    };

    $scope.$on("$ionicView.beforeEnter", function(event, data) {
      $scope.scannedKey = (data.stateParams && data.stateParams.privateKey) ? data.stateParams.privateKey : null;
      $scope.isPkEncrypted = $scope.scannedKey ? ($scope.scannedKey.substring(0, 2) == '6P') : null;
      $scope.sendStatus = null;
      $scope.error = false;

      $scope.wallets = profileService.getWallets({
        onlyComplete: true,
        network: 'livenet',
      });
      $scope.singleWallet = $scope.wallets.length == 1;

      if (!$scope.wallets || !$scope.wallets.length) {
        $scope.noMatchingWallet = true;
        return;
      }
    });

    $scope.$on("$ionicView.enter", function(event, data) {
      $scope.wallet = $scope.wallets[0];
      if (!$scope.wallet) return;
      if (!$scope.isPkEncrypted) $scope.scanFunds();
      else {
        var message = gettextCatalog.getString('Private key encrypted. Enter password');
        popupService.showPrompt(null, message, null, function(res) {
          $scope.passphrase = res;
          $scope.scanFunds();
        });
      }
    });

  });
<|endoftext|>


<commit_before>var NODE_ENV = require("./index")

module.exports = envScript

function envScript() {
    return ";(function () {\n" +
        "    window.NODE_ENV = '" + JSON.stringify(NODE_ENV) + "'\n" +
        "}());\n"
}
<commit_msg>remove new lines otherwise source maps are off by 3<commit_after>var NODE_ENV = require("./index")

module.exports = envScript

function envScript() {
    return ";(function () {" +
        "    window.NODE_ENV = '" + JSON.stringify(NODE_ENV) + "'" +
        "}());"
}
<|endoftext|>


<commit_before>
'use strict';

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

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

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

/* hour is before noon */
if ( myDate.getHours() < 12 )
{
groet = "Goeiemorgen";
}
else  /* Hour is from noon to 5pm (actually to 5:59 pm) */
if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 )
{
groet = "Goedendag";
}
else  /* the hour is after 5pm, so it is between 6pm and midnight */
if ( myDate.getHours() > 17 && myDate.getHours() <= 24 )
{
groet = "Goedenavond";
}
else  /* the hour is not between 0 and 24, so something is wrong */
{
groet = "Welkom";
}

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

module.exports = new Script({

 processing: {
//prompt: (bot) => bot.say('...'),
 receive: () => 'processing'
 },

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

selecteerHypotheek: {
    receive: (bot, message) => {
      switch(message.text) {
      case 'Hoi':
            return bot.say(`${groet} waar ben je naar op zoek? %[Starters hypotheek](postback:hypotheektype_starter) %[Nieuwe hypotheek](postback:hypotheektype_nieuw) %[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`)
            .then(() => 'askName')
          break;
      case 'Starters hypotheek':
      //  prompt: (bot) => bot.say(`![](http:www.bieg.nl/beeld/appartement.jpg)`)
          return bot.say(`Wat voor type woning zoek je? `)
          .then(() => bot.say(`%[Appartement](postback:hypotheekkeuze_appartement) %[Huis](postback:hypotheekkeuze_huis) %[Vakantiewoning](postback:hypotheekkeuze_vakantiewoning)`))
          .then(() => 'hypotheektype_starter')
              break;
        case 'Nieuwe hypotheek':
          return bot.say('Helaas biedt Independer momenteel alleen Starters een hypotheek aan.')
          .then(() => bot.say(`Via onderstaande link kun je de beste hypotheekadviseur voor jou vinden.`))
          .then(() => bot.say(` %[Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/intro.aspx)`))
          .then(() => 'processing')
          break;
        case 'Hypotheek oversluiten':
          return bot.say('Het spijt me maar op dit moment biedt Independer alleen  Starters een hypotheek.')
          .then(() => bot.say('Als het allemaal wel zo ver is, wil je dan een update ontvangen? '))
          .then(() => bot.say( ' %[Ja - graag](postback:updateJa) %[Nee, bedankt](postback:updateNee)'))
          .then(() => 'updateOntvangen')
          break;
        default:
          return bot.say(`...`)
            .then(() => 'processing')
          break;
      }
    }
},

updateOntvangen: {
    receive: (bot, message) => {
      switch(message.text) {
        case 'Ja - graag':
            return bot.say('Laat je dan even je email achter? Dan houden we je op de hoogte...')
            .then(() => 'updateJa')
          break;
          case 'Nee, bedankt':
              receive: () => 'bye')
              break;
          default:
            return bot.say('...')
              .then(() => 'processing')
            break;
}
}
},

updateJa: {
    // receive: (bot, message) => {
    //   const emailVisitor : message.text;
    //   return bot.setProp('emailVisitor', emailVisitor)
    //   .then(()  => bot.say(`Ok - dan hou ik je via ${emailVisitor} op de hoogte.`))
    //   .then(() => 'bye');
    // }
    receive: () => 'processing'
},

updateNee: {
    receive: () => 'processing'
},

hypotheekkeuze_appartement: {
receive: (bot,message)  => {
    //  prompt: (bot) => bot.say(`![](http:www.bieg.nl/beeld/appartement.jpg)`)
    receive: () => 'askName'
}
},
hypotheekkeuze_huis: {
//    prompt: (bot) => bot.say(`![](http:www.bieg.nl/beeld/appartement.jpg)`)
  receive: () => 'askName'
},
hypotheekkeuze_vakantiewoning: {
//    prompt: (bot) => bot.say(`![](http:www.bieg.nl/beeld/appartement.jpg)`)
    receive: () => 'askName'
},
hypotheektype_starter: {
    prompt: (bot) => bot.say('Pleasure meeting you - starter'),
    receive: () => 'processing'
},
hypotheektype_nieuw: {
    prompt: (bot) => bot.say('Independer biedt momenteel alleen voor Starters een hypotheek. ')
    .then(() => bot.say('Onderstaande link bied je meer informatie'))
    .then(() =>bot.say('%[Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/intro.aspx)')),
    receive: () => 'processing'
},

askName: {
  // receive: (bot, message) => {
  //   switch(message.text) {
  //       case 'Appartement':
  //         return bot.say('Nice! Hoe heet je eigelijk? Dat maakt het praten een stuk makkelijker...')
  //         .then(() => 'vervolgVragen')
  //         break;
  //     case 'Huis':
  //         return bot.say('Leuk! Hoe heet je eigelijk? Dat maakt het praten een stuk makkelijker...')
  //         .then(() => 'vervolgVragen')
  //         break;
  //     default:
  //       return bot.say('...')
  //         .then(() => 'processing')
  //       break;
  //   }
  //   }
},

vervolgVragen: {
  // receive: (bot, message) => {
  //       const name = message.text;
  //       return bot.setProp('name', name)
  //           .then(() => bot.say('Hoi ${name}. Ik heb nog wat vragen voor je om verder te kunnen.'))
  //           .then(() => 'lastCheck');
  //   }
},

lastCheck: {
    // prompt: (bot) => bot.say('Is er nog iets waar ik  je bij kan helpen? %[JA](postback:nogietsanders) %[NEE](postback:bye) '),
    // .then(()  => 'processing');
},

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

/* hour is before noon */
if ( myDate.getHours() < 12 )
{
groet = "Goeiemorgen";
}
else  /* Hour is from noon to 5pm (actually to 5:59 pm) */
if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 )
{
groet = "Goedendag";
}
else  /* the hour is after 5pm, so it is between 6pm and midnight */
if ( myDate.getHours() > 17 && myDate.getHours() <= 24 )
{
groet = "Goedenavond";
}
else  /* the hour is not between 0 and 24, so something is wrong */
{
groet = "Welkom";
}

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

module.exports = new Script({

 processing: {
//prompt: (bot) => bot.say('...'),
 receive: () => 'processing'
 },

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

selecteerHypotheek: {
    receive: (bot, message) => {
      switch(message.text) {
      case 'Hoi':
            return bot.say(`${groet} waar ben je naar op zoek? %[Starters hypotheek](postback:hypotheektype_starter) %[Nieuwe hypotheek](postback:hypotheektype_nieuw) %[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`)
            .then(() => 'askName')
          break;
      case 'Starters hypotheek':
      //  prompt: (bot) => bot.say(`![](http:www.bieg.nl/beeld/appartement.jpg)`)
          return bot.say(`Wat voor type woning zoek je? `)
          .then(() => bot.say(`%[Appartement](postback:hypotheekkeuze_appartement) %[Huis](postback:hypotheekkeuze_huis) %[Vakantiewoning](postback:hypotheekkeuze_vakantiewoning)`))
          .then(() => 'hypotheektype_starter')
              break;
        case 'Nieuwe hypotheek':
          return bot.say('Helaas biedt Independer momenteel alleen Starters een hypotheek aan.')
          .then(() => bot.say(`Via onderstaande link kun je de beste hypotheekadviseur voor jou vinden.`))
          .then(() => bot.say(` %[Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/intro.aspx)`))
          .then(() => 'processing')
          break;
        case 'Hypotheek oversluiten':
          return bot.say('Het spijt me maar op dit moment biedt Independer alleen  Starters een hypotheek.')
          .then(() => bot.say('Als het allemaal wel zo ver is, wil je dan een update ontvangen? '))
          .then(() => bot.say( ' %[Ja - graag](postback:updateJa) %[Nee, bedankt](postback:updateNee)'))
          .then(() => 'updateOntvangen')
          break;
        default:
          return bot.say(`...`)
            .then(() => 'processing')
          break;
      }
    }
},

updateOntvangen: {
//     receive: (bot, message) => {
//       switch(message.text) {
//         case 'Ja - graag':
//             return bot.say('Laat je dan even je email achter? Dan houden we je op de hoogte...')
//             .then(() => 'updateJa')
//           break;
//           case 'Nee, bedankt':
//               receive: () => 'bye')
//               break;
//           default:
//             return bot.say('...')
//               .then(() => 'processing')
//             break;
// }
// }
},

updateJa: {
    // receive: (bot, message) => {
    //   const emailVisitor : message.text;
    //   return bot.setProp('emailVisitor', emailVisitor)
    //   .then(()  => bot.say(`Ok - dan hou ik je via ${emailVisitor} op de hoogte.`))
    //   .then(() => 'bye');
    // }
//    receive: () => 'processing'
},

updateNee: {
    receive: () => 'processing'
},

hypotheekkeuze_appartement: {
  receive: (bot,message)  => {
    //  prompt: (bot) => bot.say(`![](http:www.bieg.nl/beeld/appartement.jpg)`)
    receive: () => 'askName'
    }
},

hypotheekkeuze_huis: {
//    prompt: (bot) => bot.say(`![](http:www.bieg.nl/beeld/appartement.jpg)`)
  receive: () => 'askName'
},
hypotheekkeuze_vakantiewoning: {
//    prompt: (bot) => bot.say(`![](http:www.bieg.nl/beeld/appartement.jpg)`)
    receive: () => 'askName'
},
hypotheektype_starter: {
    //prompt: (bot) => bot.say('Pleasure meeting you - starter'),
    receive: () => 'processing'
},
hypotheektype_nieuw: {
    // prompt: (bot) => bot.say('Independer biedt momenteel alleen voor Starters een hypotheek. ')
    // .then(() => bot.say('Onderstaande link bied je meer informatie'))
    // .then(() =>bot.say('%[Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/intro.aspx)')),
    // receive: () => 'processing'
},

askName: {
  // receive: (bot, message) => {
  //   switch(message.text) {
  //       case 'Appartement':
  //         return bot.say('Nice! Hoe heet je eigelijk? Dat maakt het praten een stuk makkelijker...')
  //         .then(() => 'vervolgVragen')
  //         break;
  //     case 'Huis':
  //         return bot.say('Leuk! Hoe heet je eigelijk? Dat maakt het praten een stuk makkelijker...')
  //         .then(() => 'vervolgVragen')
  //         break;
  //     default:
  //       return bot.say('...')
  //         .then(() => 'processing')
  //       break;
  //   }
  //   }
},

vervolgVragen: {
  // receive: (bot, message) => {
  //       const name = message.text;
  //       return bot.setProp('name', name)
  //           .then(() => bot.say('Hoi ${name}. Ik heb nog wat vragen voor je om verder te kunnen.'))
  //           .then(() => 'lastCheck');
  //   }
},

lastCheck: {
    // prompt: (bot) => bot.say('Is er nog iets waar ik  je bij kan helpen? %[JA](postback:nogietsanders) %[NEE](postback:bye) '),
    // .then(()  => 'processing');
},

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

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

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

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

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

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

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

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

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

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

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

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

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