<commit_before>/**
 * Note: Please scroll to the bottom for more details. The top has been reserved for notes and such.
 *
 *
 = return
 *

 = paragraph break
 *
 * ** If you're not familar with programming and how that relates to apostrophes, single quotes and double quotes then please use: **
 *
 * - apostrophe = '
 *
 * - left single quote = ‘
 * - right single quote = ’
 *
 * - left double quote = “
 * - right double quote = ”
 *
 * Other special characters: http://www.degraeve.com/reference/specialcharacters.php
 */

var ezMQ = {
  "ezobj":[

     {
	  'index'		: 18,
	  'title'		: '',
	  'idea_size'	: '115',
	  'idea'		: "Good days for insights had nothing to do with stunning breakthroughs or grand victories. The key turned out to be having small wins—minor innovations and troubling problems solved—on concrete steps toward a larger goal. Creative insights flowed best when people had clear goals but also freedom in how they reached them. And, most crucial, they had protected time—enough to really think freely. A creative cocoon.",
	  'quotes'		: true,
	  'select'		: 'A creative cocoon',
	  'who'			: 'Daniel Goleman',
	  'note'		: 'Focus - Chapter 4',
	  'caption'		: setupCaption
    },

     {
	  'index'		: 17,
	  'title'		: '',
	  'idea_size'	: '155',
	  'idea'		: "In the tumult of our daily distractions and to-do lists, innovation dead-ends; in open times it flourishes...

Open time lets the creative spirit flourish; tight schedules kill it.",
	  'quotes'		: true,
	  'select'		: 'Open time',
	  'who'			: 'Daniel Goleman',
	  'note'		: 'Focus - Chapter 4',
	  'caption'		: setupCaption
    },

    {
	  'index'		: 16,
	  'title'		: '',
	  'idea_size'	: '125',
	  'idea'		: "In a complex world where almost everyone has access to the same information, new value arises from the original synthesis, from putting ideas together in novel ways, and from smart questions that open up untapped potential. Creative insights entail joining elements in a useful, fresh way.",
	  'quotes'		: true,
	  'select'		: 'New value arises',
	  'who'			: 'Daniel Goleman',
	  'note'		: 'Focus - Chapter 4',
	  'caption'		: setupCaption
    },

    {
	  'index'		: 15,
	  'title'		: '',
	  'idea_size'	: '130',
	  'idea'		: "By contrast, a scientist too determined to confirm his hypothesis risks ignoring findings that don't fit his expectations—dismissing them as noise or error, not a doorway to new discoveries—and so misses what might become more fruitful theories.",
	  'quotes'		: true,
	  'select'		: 'A scientist',
	  'who'			: 'Daniel Goleman',
	  'note'		: 'Focus - Chapter 4',
	  'caption'		: setupCaption
    },

    {
	  'index'		: 14,
	  'title'		: '',
	  'idea_size'	: '125',
	  'idea'		: "So while emotions can drive our attention, with active effort we can also manage emotions top-down. Then the prefrontal areas take charge of the amygdala, tuning down its potency. An angry face, or even that cute baby, can fail to capture our attention when the circuits for top-down control of attention take over the brain's choices of what to ignore.",
	  'quotes'		: true,
	  'select'		: 'Manage emotions top-down',
	  'who'			: 'Daniel Goleman',
	  'note'		: 'Focus - Chapter 3',
	  'caption'		: setupCaption
    },

    {
	  'index'		: 13,
	  'title'		: '',
	  'idea_size'	: '165',
	  'idea'		: "We are wired to pay reflexive attention to 'super-normal stimuli,' whether for safety, nutrition, or sex—like a cat that can't help chasing a fake mouse on a string.",
	  'quotes'		: true,
	  'select'		: 'Super-normal stimuli',
	  'who'			: 'Daniel Goleman',
	  'note'		: 'Focus - Chapter 3',
	  'caption'		: setupCaption
    },

    {
	  'index'		: 12,
	  'title'		: '',
	  'idea_size'	: '115',
	  'idea'		: "Overloading attention shrinks mental control...Life immersed in digital distractions creates a near-constant cognitive overload. And that overload wears out self-control.

Forget that resolve to diet. Lost in the digital world we mindlessly reach for the Pringles.",
	  'quotes'		: true,
	  'select'		: 'The Pringles',
	  'who'			: 'Daniel Goleman',
	  'note'		: 'Focus - Chapter 3',
	  'caption'		: setupCaption
    },

    {
	  'index'		: 11,
	  'title'		: '',
	  'idea_size'	: '155',
	  'idea'		: "When the coach reviews plays from a game and only focuses on what not to do next time, it's a recipe for players to choke.",
	  'quotes'		: true,
	  'select'		: 'Recipe for players to choke',
	  'who'			: 'Daniel Goleman',
	  'note'		: 'Focus - Chapter 3',
	  'caption'		: setupCaption
    },

    {
	  'index'		: 10,
	  'title'		: '',
	  'idea_size'	: '115',
	  'idea'		: "As world-class champions attest, at the topmost levels, where your opponents have practiced about as many thousands of hours as you have, any competition becomes a mental game: your mind state determines how well you can focus, and so how well you can do. The more you can relax and trust in bottom-up moves, the more you free your mind to be nimble.",
	  'quotes'		: true,
	  'select'		: 'World-class champions',
	  'who'			: 'Daniel Goleman',
	  'note'		: 'Focus - Chapter 3',
	  'caption'		: setupCaption
    },

    {
	  'index'		: 9,
	  'title'		: '',
	  'idea_size'	: '135',
	  'idea'		: "The human brain counts among evolution's good-enough, but not perfect, designs. The brain's more ancient bottom-up systems apparently worked well for basic survival during most of human prehistory—but their design makes for some troubles today.",
	  'quotes'		: true,
	  'select'		: 'Good-enough, but not perfect',
	  'who'			: 'Daniel Goleman',
	  'note'		: 'Focus - Chapter 3',
	  'caption'		: setupCaption
    },

    {
	  'index'		: 8,
	  'title'		: '',
	  'idea_size'	: '135',
	  'idea'		: "Full focus gives us a potential doorway into flow. But when we choose to focus on one thing and ignore the rest, we surface a constant tension—usually invisible—between a great neural divide, where the top of the brain tussles with the bottom.",
	  'quotes'		: true,
	  'select'		: 'Doorway into flow',
	  'who'			: 'Daniel Goleman',
	  'note'		: 'Focus - Chapter 2',
	  'caption'		: setupCaption
    },

    {
	  'index'		: 7,
	  'title'		: '',
	  'idea_size'	: '150',
	  'idea'		: "Deep thinking demands sustaining a focused mind. The more distracted we are, the more shallow our reflections; likewise, the shorter our reflections, the more trivial they are likely to be.",
	  'quotes'		: true,
	  'select'		: 'Deep thinking demands',
	  'who'			: 'Daniel Goleman',
	  'note'		: 'Focus - Chapter 2',
	  'caption'		: setupCaption
    },

    {
	  'index'		: 6,
	  'title'		: '',
	  'idea_size'	: '120',
	  'idea'		: "The ability to stay steady on one target and ignore everything else operates in the brain's prefrontal regions...That means those who focus best are relatively immune to emotional turbulence...The power to disengage our attention from one thing and move it to another is essential for well-being.",
	  'quotes'		: true,
	  'select'		: 'Emotional turbulence',
	  'who'			: 'Daniel Goleman',
	  'note'		: 'Focus - Chapter 2',
	  'caption'		: setupCaption
    },

    {
	  'index'		: 5,
	  'title'		: '',
	  'idea_size'	: '135',
	  'idea'		: "The more our focus gets disrupted, the worse we do. For instance, a test of how much college athletes are prone to having their concentration disrupted by anxiety correlates significantly with how well or poorly they will perform in the upcoming season.",
	  'quotes'		: true,
	  'select'		: 'The worse we do',
	  'who'			: 'Daniel Goleman',
	  'note'		: 'Focus - Chapter 2',
	  'caption'		: setupCaption
    },

    {
	  'index'		: 4,
	  'title'		: '',
	  'idea_size'	: '185',
	  'idea'		: "A Wealth of Information creates a Poverty of Attention.",
	  'quotes'		: true,
	  'select'		: 'Poverty of Attention',
	  'who'			: 'Herbert Simon',
	  'note'		: 'From Daniel Goleman's book Focus - Chapter 1',
	  'caption'		: setupCaption
    },

    {
	  'index'		: 3,
	  'title'		: '',
	  'idea_size'	: '135',
	  'idea'		: "In 2006, the word pizzled entered our lexicon; a combination of puzzled and pissed, it captured the feeling people had when the person they were with whipped out a BlackBerry and started talking to someone else. Back then people felt hurt and indignant in such moments. Today it's the norm.",
	  'quotes'		: true,
	  'select'		: 'In 2006, the word pizzled',
	  'who'			: 'Daniel Goleman',
	  'note'		: 'Focus - Chapter 1',
	  'caption'		: setupCaption
    },

    {
	  'index'		: 2,
	  'title'		: '',
	  'idea_size'	: '135',
	  'idea'		: "Though it matters enormously for how we navigate life, attention in all its varieties represents a little-notice and underrated mental asset. My goal here is to spotlight this elusive and under-appreciated mental faculty in the mind's operation and its role in living a fulfilling life.",
	  'quotes'		: true,
	  'select'		: 'My goal here',
	  'who'			: 'Daniel Goleman',
	  'note'		: 'Focus - Chapter 1',
	  'caption'		: setupCaption
    },

    {
	  'index'		: 1,
	  'title'		: "",
	  'idea'		: '',
	  'quotes'		: false,
	  'select'		: 'Cover: "Focus" - Daniel Goleman',
	  'who'			: '',
	  'note'		: '',
	  'caption'		: setupCaption
    }
  ]}<commit_msg>chapter 5<commit_after>/**
 * Note: Please scroll to the bottom for more details. The top has been reserved for notes and such.
 *
 *
 = return
 *

 = paragraph break
 *
 * ** If you're not familar with programming and how that relates to apostrophes, single quotes and double quotes then please use: **
 *
 * - apostrophe = '
 *
 * - left single quote = ‘
 * - right single quote = ’
 *
 * - left double quote = “
 * - right double quote = ”
 *
 * Other special characters: http://www.degraeve.com/reference/specialcharacters.php
 */

var ezMQ = {
  "ezobj":[

      {
	  'index'		: 23,
	  'title'		: '',
	  'idea_size'	: '125',
	  'idea'		: "Tightly focused attention gets fatigued—much like an overworked muscle—when we push to the point of cognitive exhaustion...

But what rests a mental muscle?

Surfing the Web, playing video games, or answering email does not.",
	  'quotes'		: true,
	  'select'		: 'What rests a mental muscle',
	  'who'			: 'Daniel Goleman',
	  'note'		: 'Focus - Chapter 5',
	  'caption'		: setupCaption
    },

      {
	  'index'		: 22,
	  'title'		: '',
	  'idea_size'	: '135',
	  'idea'		: "Those who have difficulty sustaining open awareness typically get caught up by irritating details...But there are no emotional hijacks in open awareness—just the richness of the moment.",
	  'quotes'		: true,
	  'select'		: 'The richness of the moment',
	  'who'			: 'Daniel Goleman',
	  'note'		: 'Focus - Chapter 5',
	  'caption'		: setupCaption
    },

      {
	  'index'		: 21,
	  'title'		: '',
	  'idea_size'	: '170',
	  'idea'		: "The more our mind wanders, the less we can register what's going on right now, right here.",
	  'quotes'		: true,
	  'select'		: 'Right now, right here',
	  'who'			: 'Daniel Goleman',
	  'note'		: 'Focus - Chapter 5',
	  'caption'		: setupCaption
    },

     {
	  'index'		: 20,
	  'title'		: '',
	  'idea_size'	: '135',
	  'idea'		: "It's not the chatter of people around us that is the most powerful distractor, but rather the chatter of our own minds. Utter concentration demands these inner voices to be stilled.",
	  'quotes'		: true,
	  'select'		: 'The chatter of our own minds',
	  'who'			: 'Daniel Goleman',
	  'note'		: 'Focus - Chapter 5',
	  'caption'		: setupCaption
    },

     {
	  'index'		: 19,
	  'title'		: '',
	  'idea_size'	: '140',
	  'idea'		: "On average, people's moods were generally skewed to the unpleasant while their minds wandered...Mind wandering itself seemed to be a cause of unhappiness some or much of the time.",
	  'quotes'		: true,
	  'select'		: 'Mind wandering',
	  'who'			: 'Daniel Goleman',
	  'note'		: 'Focus - Chapter 5',
	  'caption'		: setupCaption
    },

     {
	  'index'		: 18,
	  'title'		: '',
	  'idea_size'	: '115',
	  'idea'		: "Good days for insights had nothing to do with stunning breakthroughs or grand victories. The key turned out to be having small wins—minor innovations and troubling problems solved—on concrete steps toward a larger goal. Creative insights flowed best when people had clear goals but also freedom in how they reached them. And, most crucial, they had protected time—enough to really think freely. A creative cocoon.",
	  'quotes'		: true,
	  'select'		: 'A creative cocoon',
	  'who'			: 'Daniel Goleman',
	  'note'		: 'Focus - Chapter 4',
	  'caption'		: setupCaption
    },

     {
	  'index'		: 17,
	  'title'		: '',
	  'idea_size'	: '155',
	  'idea'		: "In the tumult of our daily distractions and to-do lists, innovation dead-ends; in open times it flourishes...

Open time lets the creative spirit flourish; tight schedules kill it.",
	  'quotes'		: true,
	  'select'		: 'Open time',
	  'who'			: 'Daniel Goleman',
	  'note'		: 'Focus - Chapter 4',
	  'caption'		: setupCaption
    },

    {
	  'index'		: 16,
	  'title'		: '',
	  'idea_size'	: '125',
	  'idea'		: "In a complex world where almost everyone has access to the same information, new value arises from the original synthesis, from putting ideas together in novel ways, and from smart questions that open up untapped potential. Creative insights entail joining elements in a useful, fresh way.",
	  'quotes'		: true,
	  'select'		: 'New value arises',
	  'who'			: 'Daniel Goleman',
	  'note'		: 'Focus - Chapter 4',
	  'caption'		: setupCaption
    },

    {
	  'index'		: 15,
	  'title'		: '',
	  'idea_size'	: '130',
	  'idea'		: "By contrast, a scientist too determined to confirm his hypothesis risks ignoring findings that don't fit his expectations—dismissing them as noise or error, not a doorway to new discoveries—and so misses what might become more fruitful theories.",
	  'quotes'		: true,
	  'select'		: 'A scientist',
	  'who'			: 'Daniel Goleman',
	  'note'		: 'Focus - Chapter 4',
	  'caption'		: setupCaption
    },

    {
	  'index'		: 14,
	  'title'		: '',
	  'idea_size'	: '125',
	  'idea'		: "So while emotions can drive our attention, with active effort we can also manage emotions top-down. Then the prefrontal areas take charge of the amygdala, tuning down its potency. An angry face, or even that cute baby, can fail to capture our attention when the circuits for top-down control of attention take over the brain's choices of what to ignore.",
	  'quotes'		: true,
	  'select'		: 'Manage emotions top-down',
	  'who'			: 'Daniel Goleman',
	  'note'		: 'Focus - Chapter 3',
	  'caption'		: setupCaption
    },

    {
	  'index'		: 13,
	  'title'		: '',
	  'idea_size'	: '165',
	  'idea'		: "We are wired to pay reflexive attention to 'super-normal stimuli,' whether for safety, nutrition, or sex—like a cat that can't help chasing a fake mouse on a string.",
	  'quotes'		: true,
	  'select'		: 'Super-normal stimuli',
	  'who'			: 'Daniel Goleman',
	  'note'		: 'Focus - Chapter 3',
	  'caption'		: setupCaption
    },

    {
	  'index'		: 12,
	  'title'		: '',
	  'idea_size'	: '115',
	  'idea'		: "Overloading attention shrinks mental control...Life immersed in digital distractions creates a near-constant cognitive overload. And that overload wears out self-control.

Forget that resolve to diet. Lost in the digital world we mindlessly reach for the Pringles.",
	  'quotes'		: true,
	  'select'		: 'The Pringles',
	  'who'			: 'Daniel Goleman',
	  'note'		: 'Focus - Chapter 3',
	  'caption'		: setupCaption
    },

    {
	  'index'		: 11,
	  'title'		: '',
	  'idea_size'	: '155',
	  'idea'		: "When the coach reviews plays from a game and only focuses on what not to do next time, it's a recipe for players to choke.",
	  'quotes'		: true,
	  'select'		: 'Recipe for players to choke',
	  'who'			: 'Daniel Goleman',
	  'note'		: 'Focus - Chapter 3',
	  'caption'		: setupCaption
    },

    {
	  'index'		: 10,
	  'title'		: '',
	  'idea_size'	: '115',
	  'idea'		: "As world-class champions attest, at the topmost levels, where your opponents have practiced about as many thousands of hours as you have, any competition becomes a mental game: your mind state determines how well you can focus, and so how well you can do. The more you can relax and trust in bottom-up moves, the more you free your mind to be nimble.",
	  'quotes'		: true,
	  'select'		: 'World-class champions',
	  'who'			: 'Daniel Goleman',
	  'note'		: 'Focus - Chapter 3',
	  'caption'		: setupCaption
    },

    {
	  'index'		: 9,
	  'title'		: '',
	  'idea_size'	: '135',
	  'idea'		: "The human brain counts among evolution's good-enough, but not perfect, designs. The brain's more ancient bottom-up systems apparently worked well for basic survival during most of human prehistory—but their design makes for some troubles today.",
	  'quotes'		: true,
	  'select'		: 'Good-enough, but not perfect',
	  'who'			: 'Daniel Goleman',
	  'note'		: 'Focus - Chapter 3',
	  'caption'		: setupCaption
    },

    {
	  'index'		: 8,
	  'title'		: '',
	  'idea_size'	: '135',
	  'idea'		: "Full focus gives us a potential doorway into flow. But when we choose to focus on one thing and ignore the rest, we surface a constant tension—usually invisible—between a great neural divide, where the top of the brain tussles with the bottom.",
	  'quotes'		: true,
	  'select'		: 'Doorway into flow',
	  'who'			: 'Daniel Goleman',
	  'note'		: 'Focus - Chapter 2',
	  'caption'		: setupCaption
    },

    {
	  'index'		: 7,
	  'title'		: '',
	  'idea_size'	: '150',
	  'idea'		: "Deep thinking demands sustaining a focused mind. The more distracted we are, the more shallow our reflections; likewise, the shorter our reflections, the more trivial they are likely to be.",
	  'quotes'		: true,
	  'select'		: 'Deep thinking demands',
	  'who'			: 'Daniel Goleman',
	  'note'		: 'Focus - Chapter 2',
	  'caption'		: setupCaption
    },

    {
	  'index'		: 6,
	  'title'		: '',
	  'idea_size'	: '120',
	  'idea'		: "The ability to stay steady on one target and ignore everything else operates in the brain's prefrontal regions...That means those who focus best are relatively immune to emotional turbulence...The power to disengage our attention from one thing and move it to another is essential for well-being.",
	  'quotes'		: true,
	  'select'		: 'Emotional turbulence',
	  'who'			: 'Daniel Goleman',
	  'note'		: 'Focus - Chapter 2',
	  'caption'		: setupCaption
    },

    {
	  'index'		: 5,
	  'title'		: '',
	  'idea_size'	: '135',
	  'idea'		: "The more our focus gets disrupted, the worse we do. For instance, a test of how much college athletes are prone to having their concentration disrupted by anxiety correlates significantly with how well or poorly they will perform in the upcoming season.",
	  'quotes'		: true,
	  'select'		: 'The worse we do',
	  'who'			: 'Daniel Goleman',
	  'note'		: 'Focus - Chapter 2',
	  'caption'		: setupCaption
    },

    {
	  'index'		: 4,
	  'title'		: '',
	  'idea_size'	: '185',
	  'idea'		: "A Wealth of Information creates a Poverty of Attention.",
	  'quotes'		: true,
	  'select'		: 'Poverty of Attention',
	  'who'			: 'Herbert Simon',
	  'note'		: 'From Daniel Goleman's book Focus - Chapter 1',
	  'caption'		: setupCaption
    },

    {
	  'index'		: 3,
	  'title'		: '',
	  'idea_size'	: '135',
	  'idea'		: "In 2006, the word pizzled entered our lexicon; a combination of puzzled and pissed, it captured the feeling people had when the person they were with whipped out a BlackBerry and started talking to someone else. Back then people felt hurt and indignant in such moments. Today it's the norm.",
	  'quotes'		: true,
	  'select'		: 'In 2006, the word pizzled',
	  'who'			: 'Daniel Goleman',
	  'note'		: 'Focus - Chapter 1',
	  'caption'		: setupCaption
    },

    {
	  'index'		: 2,
	  'title'		: '',
	  'idea_size'	: '135',
	  'idea'		: "Though it matters enormously for how we navigate life, attention in all its varieties represents a little-notice and underrated mental asset. My goal here is to spotlight this elusive and under-appreciated mental faculty in the mind's operation and its role in living a fulfilling life.",
	  'quotes'		: true,
	  'select'		: 'My goal here',
	  'who'			: 'Daniel Goleman',
	  'note'		: 'Focus - Chapter 1',
	  'caption'		: setupCaption
    },

    {
	  'index'		: 1,
	  'title'		: "",
	  'idea'		: '',
	  'quotes'		: false,
	  'select'		: 'Cover: "Focus" - Daniel Goleman',
	  'who'			: '',
	  'note'		: '',
	  'caption'		: setupCaption
    }
  ]}<|endoftext|>


<commit_before>var cc = cc || {};
var acg = acg || {};
acg.ext = acg.ext || {};

acg.ext._cp_layer = null;
acg.ext._cp_ctrls = [];
acg.ext._cp_ctrls_showed = false;

acg.ext.is_touch_in_content = function (touch, event) {
    var p = event.getCurrentTarget().convertTouchToNodeSpace(touch);
    var s = event.getCurrentTarget().getContentSize();
    return !(p.x < 0 || p.x > s.width || p.y < 0 || p.y > s.height);
}

acg.ext.cp_playbtn = function (callback) {
    var size = cc.director.getVisibleSize();
    var btn = cc.DrawNode.create();
    var playbtn_r = size.height * 0.1;
    btn.setAnchorPoint(cc.p(0, 0));
    btn._cp_paused = false;
    btn._cp_callback = callback;
    btn.drawPlay = function () {
        btn.clear();
        btn.drawDot(cc.p(playbtn_r, playbtn_r),
            playbtn_r, cc.color(255, 255, 255, 128));
        btn.drawPoly([
            cc.p(playbtn_r * 0.7113, playbtn_r * 1.5),
            cc.p(playbtn_r * 0.7113, playbtn_r * 0.5),
            cc.p(playbtn_r * 1.5774, playbtn_r)
        ], cc.color(255, 255, 255, 128), 1, cc.color(0, 0, 0, 255));
    };
    btn.drawPause = function () {
        btn.clear();
        btn.drawDot(cc.p(playbtn_r, playbtn_r),
            playbtn_r, cc.color(255, 255, 255, 128));
        btn.drawPoly([
            cc.p(playbtn_r * 0.7113, playbtn_r * 1.5),
            cc.p(playbtn_r * 0.7113, playbtn_r * 0.5),
            cc.p(playbtn_r * 0.8613, playbtn_r * 0.5),
            cc.p(playbtn_r * 0.8613, playbtn_r * 1.5)
        ], cc.color(255, 255, 255, 128), 1, cc.color(0, 0, 0, 255));
        btn.drawPoly([
            cc.p(playbtn_r * 1.2887, playbtn_r * 1.5),
            cc.p(playbtn_r * 1.2887, playbtn_r * 0.5),
            cc.p(playbtn_r * 1.1387, playbtn_r * 0.5),
            cc.p(playbtn_r * 1.1387, playbtn_r * 1.5)
        ], cc.color(255, 255, 255, 128), 1, cc.color(0, 0, 0, 255));
    };
    btn.drawPause();
    btn.setContentSize(cc.size(playbtn_r * 2, playbtn_r * 2));

    cc.eventManager.addListener({
        event: cc.EventListener.TOUCH_ONE_BY_ONE,
        swallowTouches: true,
        onTouchBegan: function (touch, event) {
            return (acg.ext._cp_ctrls_showed
                && acg.ext.is_touch_in_content(touch, event));
        },
        onTouchEnded: function (touch, event) {
            if (!acg.ext.is_touch_in_content(touch, event)) return;
            var t = event.getCurrentTarget();
            if (t._cp_paused) t.drawPause(); else t.drawPlay();
            t._cp_paused = !t._cp_paused;
            t._cp_callback(t._cp_paused);
        }
    }, btn);
    return btn;
};

acg.ext.cp_timeline = function (callback) {
    var size = cc.director.getVisibleSize();
    var tl = cc.DrawNode.create();
    var tl_w = size.width * 0.72;
    var tl_h = size.height * 0.08;
    var tl_r = size.height * 0.012;
    tl.setAnchorPoint(cc.p(1, 0.5));
    tl._cp_callback = callback;
    tl.drawSegment(cc.p(tl_r, tl_h / 2), cc.p(tl_w - tl_r, tl_h / 2),
        tl_r, cc.color(255, 255, 255, 128));
    // For debug use
    //tl.drawDot(cc.p(0, 0), 1, cc.color.RED);
    //tl.drawDot(cc.p(tl_w, tl_h), 1, cc.color.RED);
    tl.setContentSize(cc.size(tl_w, tl_h));
    tl.setCascadeOpacityEnabled(true);
    var tl_thumb = cc.DrawNode.create();
    var thumb_r = size.height * 0.03;
    tl_thumb.drawDot(cc.p(0, 0), thumb_r, cc.color(255, 255, 255, 192));
    tl_thumb.setNormalizedPosition(cc.p(0.4, 0.5));
    tl._cp_thumb = tl_thumb;
    tl.addChild(tl_thumb);

    tl.setProgress = function (p) {
        this._cp_thumb.setNormalizedPositionX(p);
    };

    cc.eventManager.addListener({
        event: cc.EventListener.TOUCH_ONE_BY_ONE,
        swallowTouches: true,
        onTouchBegan: function (touch, event) {
            var b = acg.ext._cp_ctrls_showed
                && acg.ext.is_touch_in_content(touch, event);
            if (b) this.onTouchMoved(touch, event);
            return b;
        },
        onTouchMoved: function (touch, event) {
            if (!acg.ext.is_touch_in_content(touch, event)) return;
            var t = event.getCurrentTarget();
            var p = t.convertTouchToNodeSpace(touch);
            var time = p.x / t.getContentSize().width;
            t.setProgress(time);
            t._cp_callback(time);
        }
    }, tl);
    return tl;
};

acg.ext.cp_enable = function () {
    cc.director.setDisplayStats(false);
    // Create the touch listener layer
    var cp = cc.Layer.create();
    acg.ext._cp_layer = cp;
    cc.director.getRunningScene().addChild(cp, 100012138);

    // Create the controls
    var size = cc.director.getVisibleSize();
    var btn = acg.ext.cp_playbtn(function (paused) {
        if (paused) acg.pause(); else acg.resume();
    });
    acg.ext._cp_ctrls[0] = btn;
    btn.setNormalizedPosition(cc.p(0.02, 0));
    btn.setOpacity(0);
    cp.addChild(btn);
    var tl = acg.ext.cp_timeline(function (time) {
        acg.travel(time * acg.tot_time());
    });
    acg.ext._cp_ctrls[1] = tl;
    tl.setNormalizedPosition(cc.p(0.95, 0.08));
    tl.setOpacity(0);
    cp.addChild(tl);
    // Update the progress of the timeline regularly
    cc.director.getRunningScene().schedule(function () {
        tl.setProgress(acg.time / acg.tot_time());
        if (acg.paused) {
            btn.drawPlay();
            btn._cp_paused = true;
        }
    }, 0);

    cc.eventManager.addListener({
        event: cc.EventListener.TOUCH_ONE_BY_ONE,
        swallowTouches: true,
        onTouchBegan: function (touch, event) {
            return true;
        },
        onTouchEnded: function (touch, event) {
            if (acg.ext._cp_ctrls_showed) {
                acg.ext._cp_ctrls_showed = false;
                btn.runAction(acg.ac.parse(['//',
                    ['move-to', 0.15, cc.p(0.02, 0)],
                    ['fade-out', 0.15]
                ]));
                tl.runAction(acg.ac.parse(['//',
                    ['move-to', 0.15, cc.p(0.95, 0.08)],
                    ['fade-out', 0.15]
                ]));
            } else {
                acg.ext._cp_ctrls_showed = true;
                btn.runAction(acg.ac.parse(['//',
                    ['move-to', 0.15, cc.p(0.02, 0.02)],
                    ['fade-in', 0.15]
                ]));
                tl.runAction(acg.ac.parse(['//',
                    ['move-to', 0.15, cc.p(0.95, 0.1)],
                    ['fade-in', 0.15]
                ]));
            }
        }
    }, cp);
};
<commit_msg>CP: Add a swipe-to-seek functionality<commit_after>var cc = cc || {};
var acg = acg || {};
acg.ext = acg.ext || {};

acg.ext._cp_layer = null;
acg.ext._cp_ctrls = [];
acg.ext._cp_ctrls_showed = false;
acg.ext._cp_swiping = false;
// Whether the animation is paused at the time when dragging started
// Used in both the timeline and the swipe-to-seek functionality
acg.ext._cp_shouldbepaused = null;

acg.ext.is_touch_in_content = function (touch, event) {
    var p = event.getCurrentTarget().convertTouchToNodeSpace(touch);
    var s = event.getCurrentTarget().getContentSize();
    return !(p.x < 0 || p.x > s.width || p.y < 0 || p.y > s.height);
};

acg.ext.touch_swiping = function (touch) {
    return cc.pDistanceSQ(touch.getStartLocation(), touch.getLocation()) > 100;
};

acg.ext.cp_playbtn = function (callback) {
    var size = cc.director.getVisibleSize();
    var btn = cc.DrawNode.create();
    var playbtn_r = size.height * 0.1;
    btn.setAnchorPoint(cc.p(0, 0));
    btn._cp_paused = false;
    btn._cp_callback = callback;
    btn.drawPlay = function () {
        btn.clear();
        btn.drawDot(cc.p(playbtn_r, playbtn_r),
            playbtn_r, cc.color(255, 255, 255, 128));
        btn.drawPoly([
            cc.p(playbtn_r * 0.7113, playbtn_r * 1.5),
            cc.p(playbtn_r * 0.7113, playbtn_r * 0.5),
            cc.p(playbtn_r * 1.5774, playbtn_r)
        ], cc.color(255, 255, 255, 128), 1, cc.color(0, 0, 0, 255));
    };
    btn.drawPause = function () {
        btn.clear();
        btn.drawDot(cc.p(playbtn_r, playbtn_r),
            playbtn_r, cc.color(255, 255, 255, 128));
        btn.drawPoly([
            cc.p(playbtn_r * 0.7113, playbtn_r * 1.5),
            cc.p(playbtn_r * 0.7113, playbtn_r * 0.5),
            cc.p(playbtn_r * 0.8613, playbtn_r * 0.5),
            cc.p(playbtn_r * 0.8613, playbtn_r * 1.5)
        ], cc.color(255, 255, 255, 128), 1, cc.color(0, 0, 0, 255));
        btn.drawPoly([
            cc.p(playbtn_r * 1.2887, playbtn_r * 1.5),
            cc.p(playbtn_r * 1.2887, playbtn_r * 0.5),
            cc.p(playbtn_r * 1.1387, playbtn_r * 0.5),
            cc.p(playbtn_r * 1.1387, playbtn_r * 1.5)
        ], cc.color(255, 255, 255, 128), 1, cc.color(0, 0, 0, 255));
    };
    btn.drawPause();
    btn.setContentSize(cc.size(playbtn_r * 2, playbtn_r * 2));

    cc.eventManager.addListener({
        event: cc.EventListener.TOUCH_ONE_BY_ONE,
        swallowTouches: true,
        onTouchBegan: function (touch, event) {
            return (acg.ext._cp_ctrls_showed
                && acg.ext.is_touch_in_content(touch, event));
        },
        onTouchEnded: function (touch, event) {
            if (!acg.ext.is_touch_in_content(touch, event)) return;
            // Update image
            var t = event.getCurrentTarget();
            if (t._cp_paused) t.drawPause(); else t.drawPlay();
            t._cp_paused = !t._cp_paused;
            t._cp_callback(t._cp_paused);
        }
    }, btn);
    return btn;
};

acg.ext.cp_timeline = function (callback) {
    var size = cc.director.getVisibleSize();
    var tl = cc.DrawNode.create();
    var tl_w = size.width * 0.72;
    var tl_h = size.height * 0.08;
    var tl_r = size.height * 0.012;
    tl.setAnchorPoint(cc.p(1, 0.5));
    tl._cp_callback = callback;
    tl.drawSegment(cc.p(tl_r, tl_h / 2), cc.p(tl_w - tl_r, tl_h / 2),
        tl_r, cc.color(255, 255, 255, 128));
    // For debug use
    //tl.drawDot(cc.p(0, 0), 1, cc.color.RED);
    //tl.drawDot(cc.p(tl_w, tl_h), 1, cc.color.RED);
    tl.setContentSize(cc.size(tl_w, tl_h));
    tl.setCascadeOpacityEnabled(true);
    var tl_thumb = cc.DrawNode.create();
    var thumb_r = size.height * 0.03;
    tl_thumb.drawDot(cc.p(0, 0), thumb_r, cc.color(255, 255, 255, 192));
    tl_thumb.setNormalizedPosition(cc.p(0.4, 0.5));
    tl._cp_thumb = tl_thumb;
    tl.addChild(tl_thumb);

    tl.setProgress = function (p) {
        this._cp_thumb.setNormalizedPositionX(p);
        this._cp_callback(p);
    };
    tl.getProgress = function (p) {
        return this._cp_thumb.getNormalizedPositionX();
    };

    cc.eventManager.addListener({
        event: cc.EventListener.TOUCH_ONE_BY_ONE,
        swallowTouches: true,
        onTouchBegan: function (touch, event) {
            var b = acg.ext._cp_ctrls_showed
                && acg.ext.is_touch_in_content(touch, event);
            if (b) {
                this.onTouchMoved(touch, event);
                if (acg.ext._cp_shouldbepaused === null)
                    acg.ext._cp_shouldbepaused = acg.paused;
                acg.pause();
            }
            return b;
        },
        onTouchMoved: function (touch, event) {
            if (!acg.ext.is_touch_in_content(touch, event)) return;
            // Update thumb's position
            var t = event.getCurrentTarget();
            var p = t.convertTouchToNodeSpace(touch);
            var time = p.x / t.getContentSize().width;
            t.setProgress(time);
        },
        onTouchEnded: function () {
            // If not paused at the beginning of dragging, we resume it now
            if (!acg.ext._cp_shouldbepaused) acg.resume();
            acg.ext._cp_shouldbepaused = null;
        }
    }, tl);
    return tl;
};

acg.ext.cp_enable = function () {
    cc.director.setDisplayStats(false);
    // Create the touch listener layer
    var cp = cc.Layer.create();
    acg.ext._cp_layer = cp;
    cc.director.getRunningScene().addChild(cp, 100012138);

    // Create the controls
    var size = cc.director.getVisibleSize();
    var btn = acg.ext.cp_playbtn(function (paused) {
        if (paused) acg.pause(); else acg.resume();
    });
    acg.ext._cp_ctrls[0] = btn;
    btn.setNormalizedPosition(cc.p(0.02, 0));
    btn.setOpacity(0);
    cp.addChild(btn);
    var tl = acg.ext.cp_timeline(function (time) {
        acg.travel(time * acg.tot_time());
    });
    acg.ext._cp_ctrls[1] = tl;
    tl.setNormalizedPosition(cc.p(0.95, 0.08));
    tl.setOpacity(0);
    cp.addChild(tl);
    // Update the progress of the timeline regularly
    cc.director.getRunningScene().schedule(function () {
        tl.setProgress(acg.time / acg.tot_time());
        btn._cp_paused = acg.paused;
        if (acg.paused) btn.drawPlay(); else btn.drawPause();
    }, 0);

    cc.eventManager.addListener({
        event: cc.EventListener.TOUCH_ONE_BY_ONE,
        swallowTouches: true,
        onTouchBegan: function (touch, event) {
            acg.ext._cp_swiping = false;
            if (!touch._startPoint) touch._startPoint = touch.getLocation();
            return true;
        },
        onTouchMoved: function (touch, event) {
            if (!acg.ext._cp_swiping && acg.ext.touch_swiping(touch)) {
                acg.ext._cp_swiping = true;
            }
            if (acg.ext._cp_swiping) {
                if (acg.ext._cp_shouldbepaused === null)
                    acg.ext._cp_shouldbepaused = acg.paused;
                acg.pause();
                tl.setProgress(tl.getProgress() + touch.getDelta().x / 600);
            }
        },
        onTouchEnded: function (touch, event) {
            if (!acg.ext._cp_swiping && acg.ext._cp_ctrls_showed) {
                acg.ext._cp_ctrls_showed = false;
                btn.runAction(acg.ac.parse(['//',
                    ['move-to', 0.15, cc.p(0.02, 0)],
                    ['fade-out', 0.15]
                ]));
                tl.runAction(acg.ac.parse(['//',
                    ['move-to', 0.15, cc.p(0.95, 0.08)],
                    ['fade-out', 0.15]
                ]));
            } else if (!acg.ext._cp_swiping) {
                acg.ext._cp_ctrls_showed = true;
                btn.runAction(acg.ac.parse(['//',
                    ['move-to', 0.15, cc.p(0.02, 0.02)],
                    ['fade-in', 0.15]
                ]));
                tl.runAction(acg.ac.parse(['//',
                    ['move-to', 0.15, cc.p(0.95, 0.1)],
                    ['fade-in', 0.15]
                ]));
            } else {
                if (!acg.ext._cp_shouldbepaused) acg.resume();
                acg.ext._cp_shouldbepaused = null;
            }
        }
    }, cp);
};
<|endoftext|>


<commit_before>/*
The MIT License (MIT)

Copyright (c) 2015 Robert Haladut, Andrey Kunitsyn

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

function updatePushView(push,prevPush){
	if (!push.active) {
		if (document.getElementById(push.iden)) { document.getElementById(push.iden).remove(); return}
			else {return}
		}
	if (document.getElementById(push.iden)) { var kid = document.getElementById(push.iden); var newPush = false;}
		else { var kid = document.createElement("div"); kid.id = push.iden;  var newPush = true;}

	kid.setAttribute("class","push_container_style");
	var type = push.type;
	switch (type) {
		case "note": {
				kid.innerHTML = "
"+push.sender_name+"

"+(push.title ? push.title : "")+"

"+(push.body ? push.body : "") +"
";
				break
				}
		case "link": {
				var body_link =	"
"+(push.body ? push.body : "")+"
"+push.url+"
";
				kid.innerHTML = "
"+push.sender_name+"

"+(push.title ? push.title : "")+"
"+body_link;
				break
				}
		case "address":{
				kid.innerHTML = "  Address: "+ push.name +"";
				break
				}
		case "file": {
				if (push.file_type == "image/png" || push.file_type == "image/jpg" || push.file_type == "image/jpeg" || push.file_type == "image/gif" || push.file_type == "image/bpm") {
					kid.innerHTML = "

";
				}else{
					kid.innerHTML = "
" + push.file_name + "
";
				}
			break
			}
	} //switch

	var trash = document.createElement("img");
	trash.setAttribute("src","images/trash.png");
	trash.setAttribute("class","trash");
	trash.addEventListener("click", deletePush, false);
	kid.appendChild(trash);

	if (newPush) {
			if (prevPush) {
				var PrevPushElem = document.getElementById(prevPush.iden);
				document.getElementById("push_container").insertBefore(kid, PrevPushElem);
					}
				else {document.getElementById("push_container").appendChild(kid)};
		}

}

function updateDeviceView(device){
	if (!device.active) {
		if (document.getElementById(device.iden)) { document.getElementById(device.iden).remove(); return}
			else {return}
		}
	if (document.getElementById(device.iden)) { var dev = document.getElementById(device.iden); var newDevice = false;}
		else { var dev = document.createElement("div"); dev.id = device.iden;  var newDevice = true;}
	dev.setAttribute("class","device_container_style");
	var type = device.type;
	switch (type) {
		case "windows":{
			dev.innerHTML = "
"+device.nickname+"
";
			break;
					   }
		case "android":{
			dev.innerHTML = "
"+device.nickname+"
";
			break;
					   }
		case "IE":
		case "chrome":
		case "safari":
		case "firefox":{
			dev.innerHTML = "
"+device.nickname+"
";
			break;
					   }
		default: 	   {
			dev.innerHTML = "
"+device.nickname+"
";
			break;
					   }
	} //switch
	var trash_device = document.createElement("img");
	trash_device.setAttribute("src","images/trash.png");
	trash_device.setAttribute("class","trash");
	trash_device.addEventListener("click", deleteDevice, false);
	dev.appendChild(trash_device);
	if (newDevice) {
		document.getElementById("devices_container").appendChild(dev);
		}

}

function show_devices(){
	if (localStorage.getItem("a") == 0){
	document.getElementById('devices_container').style = "display: block;";
	localStorage.setItem("a","1");
	}else{
		document.getElementById('devices_container').style = "display: none;"
		localStorage.setItem("a","0");
	}
}

function show_note(){
	if (localStorage.getItem("a") == 0){
	document.getElementById('notes').style = "display: block;";
	localStorage.setItem("a","1");
	}else{
		document.getElementById('notes').style = "display: none;"
		localStorage.setItem("a","0");
	}
}

function show_link(){
	if (localStorage.getItem("a") == 0){
		document.getElementById('links').style = "display: block;";
		localStorage.setItem("a","1");
	}else{
		document.getElementById('links').style = "display: none;"
		localStorage.setItem("a","0");
	}
}

function deletePush(e){
	if (confirm("Would you really delete this push?")){
		var iden = this.parentNode.id;
		console.log("Deleting push: " + iden);
		deletePushRQ(iden);
		}
}

function deleteDevice(e){
	if (confirm("Would you really delete this device?")){
		var iden = this.parentNode.id;
		console.log("Deleting device: " + iden);
		deleteDeviceRQ(iden);
		}
}

function dismissVisiblePushes(){
	if (!document.hidden){
	for (var i = 0; i < notDismissedPushes.length; i++) {
		var pushTop    = document.getElementById(notDismissedPushes[i]).getBoundingClientRect().top,
       		pushBottom = document.getElementById(notDismissedPushes[i]).getBoundingClientRect().bottom;
		if (pushTop >= 0 && pushBottom <= window.innerHeight) {
			console.log( "The push "+notDismissedPushes[i]+" is visible, dismissing it." );
			dismissRQ(notDismissedPushes[i])}
		}
	}
}<commit_msg>Update UI.js<commit_after>/*
The MIT License (MIT)

Copyright (c) 2015 Robert Halandut, Andrey Kunitsyn

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

function updatePushView(push,prevPush){
	if (!push.active) {
		if (document.getElementById(push.iden)) { document.getElementById(push.iden).remove(); return}
			else {return}
		}
	if (document.getElementById(push.iden)) { var kid = document.getElementById(push.iden); var newPush = false;}
		else { var kid = document.createElement("div"); kid.id = push.iden;  var newPush = true;}

	kid.setAttribute("class","push_container_style");
	var type = push.type;
	switch (type) {
		case "note": {
				kid.innerHTML = "
"+push.sender_name+"

"+(push.title ? push.title : "")+"

"+(push.body ? push.body : "") +"
";
				break
				}
		case "link": {
				var body_link =	"
"+(push.body ? push.body : "")+"
"+push.url+"
";
				kid.innerHTML = "
"+push.sender_name+"

"+(push.title ? push.title : "")+"
"+body_link;
				break
				}
		case "address":{
				kid.innerHTML = "  Address: "+ push.name +"";
				break
				}
		case "file": {
				if (push.file_type == "image/png" || push.file_type == "image/jpg" || push.file_type == "image/jpeg" || push.file_type == "image/gif" || push.file_type == "image/bpm") {
					kid.innerHTML = "

";
				}else{
					kid.innerHTML = "
" + push.file_name + "
";
				}
			break
			}
	} //switch

	var trash = document.createElement("img");
	trash.setAttribute("src","images/trash.png");
	trash.setAttribute("class","trash");
	trash.addEventListener("click", deletePush, false);
	kid.appendChild(trash);

	if (newPush) {
			if (prevPush) {
				var PrevPushElem = document.getElementById(prevPush.iden);
				document.getElementById("push_container").insertBefore(kid, PrevPushElem);
					}
				else {document.getElementById("push_container").appendChild(kid)};
		}

}

function updateDeviceView(device){
	if (!device.active) {
		if (document.getElementById(device.iden)) { document.getElementById(device.iden).remove(); return}
			else {return}
		}
	if (document.getElementById(device.iden)) { var dev = document.getElementById(device.iden); var newDevice = false;}
		else { var dev = document.createElement("div"); dev.id = device.iden;  var newDevice = true;}
	dev.setAttribute("class","device_container_style");
	var type = device.type;
	switch (type) {
		case "windows":{
			dev.innerHTML = "
"+device.nickname+"
";
			break;
					   }
		case "android":{
			dev.innerHTML = "
"+device.nickname+"
";
			break;
					   }
		case "IE":
		case "chrome":
		case "safari":
		case "firefox":{
			dev.innerHTML = "
"+device.nickname+"
";
			break;
					   }
		default: 	   {
			dev.innerHTML = "
"+device.nickname+"
";
			break;
					   }
	} //switch
	var trash_device = document.createElement("img");
	trash_device.setAttribute("src","images/trash.png");
	trash_device.setAttribute("class","trash");
	trash_device.addEventListener("click", deleteDevice, false);
	dev.appendChild(trash_device);
	if (newDevice) {
		document.getElementById("devices_container").appendChild(dev);
		}

}

function show_devices(){
	if (localStorage.getItem("a") == 0){
	document.getElementById('devices_container').style = "display: block;";
	localStorage.setItem("a","1");
	}else{
		document.getElementById('devices_container').style = "display: none;"
		localStorage.setItem("a","0");
	}
}

function show_note(){
	if (localStorage.getItem("a") == 0){
	document.getElementById('notes').style = "display: block;";
	localStorage.setItem("a","1");
	}else{
		document.getElementById('notes').style = "display: none;"
		localStorage.setItem("a","0");
	}
}

function show_link(){
	if (localStorage.getItem("a") == 0){
		document.getElementById('links').style = "display: block;";
		localStorage.setItem("a","1");
	}else{
		document.getElementById('links').style = "display: none;"
		localStorage.setItem("a","0");
	}
}

function deletePush(e){
	if (confirm("Would you really delete this push?")){
		var iden = this.parentNode.id;
		console.log("Deleting push: " + iden);
		deletePushRQ(iden);
		}
}

function deleteDevice(e){
	if (confirm("Would you really delete this device?")){
		var iden = this.parentNode.id;
		console.log("Deleting device: " + iden);
		deleteDeviceRQ(iden);
		}
}

function dismissVisiblePushes(){
	if (!document.hidden){
	for (var i = 0; i < notDismissedPushes.length; i++) {
		var pushTop    = document.getElementById(notDismissedPushes[i]).getBoundingClientRect().top,
       		pushBottom = document.getElementById(notDismissedPushes[i]).getBoundingClientRect().bottom;
		if (pushTop >= 0 && pushBottom <= window.innerHeight) {
			console.log( "The push "+notDismissedPushes[i]+" is visible, dismissing it." );
			dismissRQ(notDismissedPushes[i])}
		}
	}
}
<|endoftext|>


<commit_before>document.getElementById("calculate_button").addEventListener("click", doCalculations);

function doCalculations() {
  var a = sanitizeInput(document.getElementById('entry_price').value);
  var b = sanitizeInput(document.getElementById('exit_price').value);
  var decimalLength = getDecimalLength(a,b);
  a *= Math.pow(10,decimalLength);
  b *= Math.pow(10,decimalLength);
  a = parseInt(a, 10);
  b = parseInt(b, 10);
  var c = (a+b)/2;
  var f = b+0.5*(b-a);
  a /= Math.pow(10,decimalLength);
  b /= Math.pow(10,decimalLength);
  c /= Math.pow(10,decimalLength);
  f /= Math.pow(10,decimalLength);

  var d = sanitizeInput(document.getElementById('tick_size').value);
  var e = sanitizeInput(document.getElementById('price_per_tick').value);

  document.getElementById("midpoint_price").innerHTML = c;
  document.getElementById("150%_profit_price").innerHTML = f;

  if (document.getElementById('tick_size').value != null &&
    document.getElementById('tick_size').value != "" &&
    document.getElementById('price_per_tick').value != null &&
    document.getElementById('price_per_tick').value != "") {
    var profit50 = (c-Math.min(a,b))/d*e;
    document.getElementById("50%_profit").innerHTML = "$" + profit50.toFixed(2);
    var profit100 = Math.abs((a-b)/d*e);
    document.getElementById("100%_profit").innerHTML = "$" + profit100.toFixed(2);
    var profit150 = Math.abs((a-f)/d*e);
    document.getElementById("150%_profit").innerHTML = "$" + profit150.toFixed(2);
  } else {
    document.getElementById("50%_profit").innerHTML = '';
    document.getElementById("100%_profit").innerHTML = '';
    document.getElementById("150%_profit").innerHTML = '';
  }
}

function getDecimalLength(a,b) {
  var a = a.toString(10);
  var b = b.toString(10);
  var decimalLength = 0;
  if (a.split('.')[1]) {
    decimalLength = Math.max(decimalLength,a.split('.')[1].length);
  }
  if (b.split('.')[1]) {
    decimalLength = Math.max(decimalLength,b.split('.')[1].length);
  }
  return decimalLength+1;
}

function sanitizeInput(input) {
  if(input=== null || input === '') {return input;}
  input = input.trim();
  if(input[0] === '$') {
    input = input.substr(1);
  }
  console.log(input);
  return input;
}

var input1 = document.getElementById("entry_price");
input1.addEventListener("keyup", runCalculateButton);

var input2 = document.getElementById("exit_price");
input2.addEventListener("keyup", runCalculateButton);

var input3 = document.getElementById("tick_size");
input3.addEventListener("keyup", runCalculateButton);

var input4 = document.getElementById("price_per_tick");
input4.addEventListener("keyup", runCalculateButton);

function runCalculateButton(event) {
  event.preventDefault();
  if (event.keyCode === 13) {
    document.getElementById("calculate_button").click();
  }
}
<commit_msg>Update ai.js<commit_after>document.getElementById("calculate_button").addEventListener("click", doCalculations);

function doCalculations() {
  var a = sanitizeInput(document.getElementById('entry_price').value);
  var b = sanitizeInput(document.getElementById('exit_price').value);
  var decimalLength = getDecimalLength(a,b);
  a *= Math.pow(10,decimalLength);
  b *= Math.pow(10,decimalLength)
  var c = (a+b)/2;
  var f = b+0.5*(b-a);
  a /= Math.pow(10,decimalLength);
  b /= Math.pow(10,decimalLength);
  c /= Math.pow(10,decimalLength);
  f /= Math.pow(10,decimalLength);

  var d = sanitizeInput(document.getElementById('tick_size').value);
  var e = sanitizeInput(document.getElementById('price_per_tick').value);

  document.getElementById("midpoint_price").innerHTML = c;
  document.getElementById("150%_profit_price").innerHTML = f;

  if (document.getElementById('tick_size').value != null &&
    document.getElementById('tick_size').value != "" &&
    document.getElementById('price_per_tick').value != null &&
    document.getElementById('price_per_tick').value != "") {
    var profit50 = (c-Math.min(a,b))/d*e;
    document.getElementById("50%_profit").innerHTML = "$" + profit50.toFixed(2);
    var profit100 = Math.abs((a-b)/d*e);
    document.getElementById("100%_profit").innerHTML = "$" + profit100.toFixed(2);
    var profit150 = Math.abs((a-f)/d*e);
    document.getElementById("150%_profit").innerHTML = "$" + profit150.toFixed(2);
  } else {
    document.getElementById("50%_profit").innerHTML = '';
    document.getElementById("100%_profit").innerHTML = '';
    document.getElementById("150%_profit").innerHTML = '';
  }
}

function getDecimalLength(a,b) {
  var a = a.toString(10);
  var b = b.toString(10);
  var decimalLength = 0;
  if (a.split('.')[1]) {
    decimalLength = Math.max(decimalLength,a.split('.')[1].length);
  }
  if (b.split('.')[1]) {
    decimalLength = Math.max(decimalLength,b.split('.')[1].length);
  }
  return decimalLength+2;
}

function sanitizeInput(input) {
  if(input=== null || input === '') {return input;}
  input = input.trim();
  if(input[0] === '$') {
    input = input.substr(1);
  }
  console.log(input);
  return input;
}

var input1 = document.getElementById("entry_price");
input1.addEventListener("keyup", runCalculateButton);

var input2 = document.getElementById("exit_price");
input2.addEventListener("keyup", runCalculateButton);

var input3 = document.getElementById("tick_size");
input3.addEventListener("keyup", runCalculateButton);

var input4 = document.getElementById("price_per_tick");
input4.addEventListener("keyup", runCalculateButton);

function runCalculateButton(event) {
  event.preventDefault();
  if (event.keyCode === 13) {
    document.getElementById("calculate_button").click();
  }
}
<|endoftext|>


<commit_before>function myPassword() {
    var generator = document.getElementsByTagName(".pw-english")[0].getAttribute("data-id");
    console.info("password type: ", generator);
    if (generator === "english") {
        $(".english-result").append("");
        if (generator === "chinese");
        $(".chinese-result").append("");
    } else {
        $(".arabic-result").append("");
    }
}
myPassword();
<commit_msg>change to js version that works<commit_after>function myPassword() {
    var generator = document.getElementsByClassName(".pw-english")[0].getAttribute("data-id");
    console.info("password type: ", generator);
    if (generator === "english") {
        $(".english-result").append("");
        if (generator === "chinese");
        $(".chinese-result").append("");
    } else {
        $(".arabic-result").append("");
    }
}
myPassword();
<|endoftext|>


<commit_before>var T9 = function(_wordList, _config) {
	var _ = this;

	var wordList = _wordList;

	var config = {
		sort : function(wordA, wordB) {
			if(wordA.length <= wordB.length)
				return -1;
			if(wordA.length > wordB.length)
				return 1;
			if(wordA <= wordB)
				return -1;
			else
				return 1;
		},
		maxAmount : -1,
		caseSentitive : true
	};

	// Extends the config options
	(function(destination, source) {
		for (var property in source) {
			destination[property] = source[property];
		}
		return destination;
	})(config, _config);

	//The root of the tree
	var root = {
		$ : false,
		branches : []
	};

	/**
	 * Predict the words, given the initial word
	 * @param  {String} word The initial word
	 * @return {Array}      The array of Strings with the predicted words
	 */
	this.predict = function(word, amount) {
		var auxBranch = root;

		//Goes through the tree until it finds the branch from
		//where it will begin to predict
		for(var _ch_ in word) {
			var ch = word[_ch_]; //Get the current character from the word

			//If the leaf branch with the current character exists, goes to the next branch
			if(typeof auxBranch.branches[ch] !== 'undefined') {
				auxBranch = auxBranch.branches[ch];
			}
			else {
				// console.log('No matches');
				return [];
			}
		}

		var predictedList = _exploreBranch(word, auxBranch);

		predictedList.sort(config.sort);

		//If passes the amount as parameter, uses it
		//Otherwise, check if the user changed the default
		//max amount. If so, it uses the custom maxAmount,
		//otherwise return all the results
		if(typeof amount !== 'undefined') {
			return predictedList.slice(0, amount);
		}
		else {
			if(config.maxAmount > -1)
				return predictedList.slice(0, config.maxAmount);
			else
				return predictedList;
		}

	};

	/**
	 * Goes trough the branch looking for the words that contain the word passed as parameter
	 * @param  {String} baseWord The base word of the current branch
	 * @param  {Object} branch   The current branch
	 * @return {Array}          List of predicted words
	 */
	var _exploreBranch = function(baseWord, branch) {
		var predictedList = [];

		var keys = Object.keys(branch.branches); //Get the branch names that forks from the branch
		for(var _ch_ in keys) { //For each branch forking from the branch
			var ch = keys[_ch_]; //Get the leading character of the current branch

			if(branch.branches[ch].$ === true) { //If the current leaf ends a word, puts the word on the list
				predictedList.push(baseWord + ch);
			}

			//Recursively calls the function, passing the forking branches as parameter
			var predictedWords = _exploreBranch(baseWord + ch, branch.branches[ch]);

			predictedList =  predictedList.concat(predictedWords);

		}
		return predictedList;
	};

	/**
	 * Add a new word to the tree
	 * @param {String} word Word to be added to the tree
	 */
	this.addWord = function(word) {
		var auxBranch = root;

		//For each character of the current word
		for(var _ch_ in word) {
			var ch = word[_ch_]; //Get the current character of the word

			//If the branch doesn't have the word yet
			if(typeof auxBranch.branches[ch] === 'undefined') {
				auxBranch.branches[ch] = { //Adds a new leaf to the tree
					$ : false,
					branches : []
				};
			}
			auxBranch = auxBranch.branches[ch];
		}

		auxBranch.$ = true;
	};

	/**
	 *	Starts the trie tree with the list of words
	 *
	 * @constructor
	 */
	var _init = function() {
		// For each word in the list
		for(var _word_ in wordList) {

			var word = wordList[_word_]; //Get the current word to be added to the three

			_.addWord(word);
		}

	};

	//Calls the constructor
	_init();

	return this;
};<commit_msg>Objects are faster than arrays to store the branches.<commit_after>var T9 = function(_wordList, _config) {
	var _ = this;

	var wordList = _wordList;

	var config = {
		sort : function(wordA, wordB) {
			if(wordA.length <= wordB.length)
				return -1;
			if(wordA.length > wordB.length)
				return 1;
			if(wordA <= wordB)
				return -1;
			else
				return 1;
		},
		maxAmount : -1,
		caseSentitive : true
	};

	// Extends the config options
	(function(destination, source) {
		for (var property in source) {
			destination[property] = source[property];
		}
		return destination;
	})(config, _config);

	//The root of the tree
	var root = {
		$ : false,
		branches : {}
	};

	/**
	 * Predict the words, given the initial word
	 * @param  {String} word The initial word
	 * @return {Array}      The array of Strings with the predicted words
	 */
	this.predict = function(word, amount) {
		var auxBranch = root;

		//Goes through the tree until it finds the branch from
		//where it will begin to predict
		for(var _ch_ in word) {
			var ch = word[_ch_]; //Get the current character from the word

			//If the leaf branch with the current character exists, goes to the next branch
			if(typeof auxBranch.branches[ch] !== 'undefined') {
				auxBranch = auxBranch.branches[ch];
			}
			else {
				// console.log('No matches');
				return [];
			}
		}

		var predictedList = _exploreBranch(word, auxBranch);

		predictedList.sort(config.sort);

		//If passes the amount as parameter, uses it
		//Otherwise, check if the user changed the default
		//max amount. If so, it uses the custom maxAmount,
		//otherwise return all the results
		if(typeof amount !== 'undefined') {
			return predictedList.slice(0, amount);
		}
		else {
			if(config.maxAmount > -1)
				return predictedList.slice(0, config.maxAmount);
			else
				return predictedList;
		}

	};

	/**
	 * Goes trough the branch looking for the words that contain the word passed as parameter
	 * @param  {String} baseWord The base word of the current branch
	 * @param  {Object} branch   The current branch
	 * @return {Array}          List of predicted words
	 */
	var _exploreBranch = function(baseWord, branch) {
		var predictedList = [];

		var keys = Object.keys(branch.branches); //Get the branch names that forks from the branch
		for(var _ch_ in keys) { //For each branch forking from the branch
			var ch = keys[_ch_]; //Get the leading character of the current branch

			if(branch.branches[ch].$ === true) { //If the current leaf ends a word, puts the word on the list
				predictedList.push(baseWord + ch);
			}

			//Recursively calls the function, passing the forking branches as parameter
			var predictedWords = _exploreBranch(baseWord + ch, branch.branches[ch]);

			predictedList =  predictedList.concat(predictedWords);

		}
		return predictedList;
	};

	/**
	 * Add a new word to the tree
	 * @param {String} word Word to be added to the tree
	 */
	this.addWord = function(word) {
		var auxBranch = root;

		//For each character of the current word
		for(var _ch_ in word) {
			var ch = word[_ch_]; //Get the current character of the word

			//If the branch doesn't have the word yet
			if(typeof auxBranch.branches[ch] === 'undefined') {
				auxBranch.branches[ch] = { //Adds a new leaf to the tree
					$ : false,
					branches : {}
				};
			}
			auxBranch = auxBranch.branches[ch];
		}

		auxBranch.$ = true;
	};

	/**
	 *	Starts the trie tree with the list of words
	 *
	 * @constructor
	 */
	var _init = function() {
		// For each word in the list
		for(var _word_ in wordList) {

			var word = wordList[_word_]; //Get the current word to be added to the three

			_.addWord(word);
		}

	};

	//Calls the constructor
	_init();

	return this;
};<|endoftext|>


<commit_before>/*
    tx.js - Bitcoin transactions for JavaScript (public domain)

    Obtaining inputs:
    1) http://blockchain.info/unspent?address=<address>
    2) http://blockexplorer.com/q/mytransactions/<address>

    Sending transactions:
    1) http://bitsend.rowit.co.uk
    2) http://www.blockchain.info/pushtx
*/

var TX = new function () {

    var inputs = [];
    var outputs = [];
    var eckey = null;
    var balance = 0;

    this.init = function(_eckey) {
        outputs = [];
        eckey = _eckey;
    }

    this.addOutput = function(addr, fval) {
        outputs.push({address: addr, value: fval});
    }

    this.getOutputs = function() {
        return outputs;
    }

    this.getBalance = function() {
        return balance;
    }

    this.getSendBalance = function() {
      value = 0.0
      for (var i in outputs) {
          if(outputs[i].address == this.getAddress())
            continue;

          var fval = outputs[i].value;
          value += fval;
      }
      value += 0.0005;
      return value.toFixed(4);
    }

    this.getChange = function() {
      value = 0.0
      for (var i in outputs) {
          if(outputs[i].address != this.getAddress())
            continue;

          var fval = outputs[i].value;
          value += fval;
      }
      return value.toFixed(4);
    }

    this.getAddress = function() {
        return eckey.getBitcoinAddress().toString();
    }

    this.parseInputs = function(text, address) {
        try {
            var res = tx_parseBCI(text, address);
        } catch(err) {
            var res = { "balance":"0" };
        }

        balance = res.balance;
        inputs = res.unspenttxs;
    }

    this.construct = function() {
        var sendTx = new Bitcoin.Transaction();
        var selectedOuts = [];
        for (var hash in inputs) {
            if (!inputs.hasOwnProperty(hash))
                continue;
            for (var index in inputs[hash]) {
                if (!inputs[hash].hasOwnProperty(index))
                    continue;
                var script = parseScript(inputs[hash][index].script);
                var b64hash = Crypto.util.bytesToBase64(Crypto.util.hexToBytes(hash));
                var txin = new Bitcoin.TransactionIn({outpoint: {hash: b64hash, index: index}, script: script, sequence: 4294967295});
                selectedOuts.push(txin);
                sendTx.addInput(txin);
            }
        }

        for (var i in outputs) {
            var address = outputs[i].address;
            var fval = outputs[i].value;
            var value = new BigInteger('' + Math.round(fval * 1e8), 10);
            sendTx.addOutput(new Bitcoin.Address(address), value);
        }

        var hashType = 1;
        for (var i = 0; i < sendTx.ins.length; i++) {
            var connectedScript = selectedOuts[i].script;
            var hash = sendTx.hashTransactionForSignature(connectedScript, i, hashType);
            var pubKeyHash = connectedScript.simpleOutPubKeyHash();
            var signature = eckey.sign(hash);
            signature.push(parseInt(hashType, 10));
            var pubKey = eckey.getPub();
            var script = new Bitcoin.Script();
            script.writeBytes(signature);
            script.writeBytes(pubKey);
            sendTx.ins[i].script = script;
        }
        return sendTx;
    };

    this.toBBE = function(sendTx) {
        //serialize to Bitcoin Block Explorer format
        var buf = sendTx.serialize();
        var hash = Crypto.SHA256(Crypto.SHA256(buf, {asBytes: true}), {asBytes: true});

        var r = {};
        r['hash'] = Crypto.util.bytesToHex(hash.reverse());
        r['ver'] = sendTx.version;
        r['vin_sz'] = sendTx.ins.length;
        r['vout_sz'] = sendTx.outs.length;
        r['lock_time'] = sendTx.lock_time;
        r['size'] = buf.length;
        r['in'] = []
        r['out'] = []

        for (var i = 0; i < sendTx.ins.length; i++) {
            var txin = sendTx.ins[i];
            var hash = Crypto.util.base64ToBytes(txin.outpoint.hash);
            var n = txin.outpoint.index;
            var prev_out = {'hash': Crypto.util.bytesToHex(hash.reverse()), 'n': n};

            if (n == 4294967295) {
                var cb = Crypto.util.bytesToHex(txin.script.buffer);
                r['in'].push({'prev_out': prev_out, 'coinbase' : cb});
            } else {
                var ss = dumpScript(txin.script);
                r['in'].push({'prev_out': prev_out, 'scriptSig' : ss});
            }
        }

        for (var i = 0; i < sendTx.outs.length; i++) {
            var txout = sendTx.outs[i];
            var bytes = txout.value.slice(0);
            var fval = parseFloat(Bitcoin.Util.formatValue(bytes.reverse()));
            var value = fval.toFixed(8);
            var spk = dumpScript(txout.script);
            r['out'].push({'value' : value, 'scriptPubKey': spk});
        }

        return JSON.stringify(r, null, 4);
    };

    return this;
};

function dumpScript(script) {
    var out = [];
    for (var i = 0; i < script.chunks.length; i++) {
        var chunk = script.chunks[i];
        var op = new Bitcoin.Opcode(chunk);
        typeof chunk == 'number' ?  out.push(op.toString()) :
            out.push(Crypto.util.bytesToHex(chunk));
    }
    return out.join(' ');
}

// blockchain.info parser (adapted)
// uses http://blockchain.info/unspent?address=<address>
function tx_parseBCI(data, address) {
    var r = JSON.parse(data);
    var txs = r.unspent_outputs;

    if (!txs)
        throw 'Not a BCI format';

    delete unspenttxs;
    var unspenttxs = {};
    var balance = BigInteger.ZERO;
    for (var i in txs) {
        var o = txs[i];
        var lilendHash = o.tx_hash;

        //convert script back to BBE-compatible text
        var script = dumpScript( new Bitcoin.Script(Crypto.util.hexToBytes(o.script)) );

        var value = new BigInteger('' + o.value, 10);
        if (!(lilendHash in unspenttxs))
            unspenttxs[lilendHash] = {};
        unspenttxs[lilendHash][o.tx_output_n] = {amount: value, script: script};
        balance = balance.add(value);
    }
    return {balance:balance, unspenttxs:unspenttxs};
}

function isEmpty(ob) {
    for(var i in ob){ if(ob.hasOwnProperty(i)){return false;}}
    return true;
}

function endian(string) {
    var out = []
    for(var i = string.length; i > 0; i-=2) {
        out.push(string.substring(i-2,i));
    }
    return out.join("");
}

function btcstr2bignum(btc) {
    var i = btc.indexOf('.');
    var value = new BigInteger(btc.replace(/\./,''));
    var diff = 9 - (btc.length - i);
    if (i == -1) {
        var mul = "100000000";
    } else if (diff < 0) {
        return value.divide(new BigInteger(Math.pow(10,-1*diff).toString()));
    } else {
        var mul = Math.pow(10,diff).toString();
    }
    return value.multiply(new BigInteger(mul));
}

function parseScript(script) {
    var newScript = new Bitcoin.Script();
    var s = script.split(" ");
    for (var i in s) {
        if (Bitcoin.Opcode.map.hasOwnProperty(s[i])){
            newScript.writeOp(Bitcoin.Opcode.map[s[i]]);
        } else {
            newScript.writeBytes(Crypto.util.hexToBytes(s[i]));
        }
    }
    return newScript;
}
// --->8---

<commit_msg>Update tx.js<commit_after>/*
    tx.js - Bitcoin transactions for JavaScript (public domain)

    Obtaining inputs:
    1) http://blockchain.info/unspent?address=<address>
    2) http://blockexplorer.com/q/mytransactions/<address>

    Sending transactions:
    1) http://bitsend.rowit.co.uk
    2) http://www.blockchain.info/pushtx
*/

var TX = new function () {

    var inputs = [];
    var outputs = [];
    var eckey = null;
    var balance = 0;

    this.init = function(_eckey) {
        outputs = [];
        eckey = _eckey;
    }

    this.addOutput = function(addr, fval) {
        outputs.push({address: addr, value: fval});
    }

    this.getOutputs = function() {
        return outputs;
    }

    this.getBalance = function() {
        return balance;
    }

    this.getSendBalance = function() {
      value = 0.0
      for (var i in outputs) {
          if(outputs[i].address == this.getAddress())
            continue;

          var fval = outputs[i].value;
          value += fval;
      }
      value += 0.0001;
      return value.toFixed(4);
    }

    this.getChange = function() {
      value = 0.0
      for (var i in outputs) {
          if(outputs[i].address != this.getAddress())
            continue;

          var fval = outputs[i].value;
          value += fval;
      }
      return value.toFixed(6);
    }

    this.getAddress = function() {
        return eckey.getBitcoinAddress().toString();
    }

    this.parseInputs = function(text, address) {
        try {
            var res = tx_parseBCI(text, address);
        } catch(err) {
            var res = { "balance":"0" };
        }

        balance = res.balance;
        inputs = res.unspenttxs;
    }

    this.construct = function() {
        var sendTx = new Bitcoin.Transaction();
        var selectedOuts = [];
        for (var hash in inputs) {
            if (!inputs.hasOwnProperty(hash))
                continue;
            for (var index in inputs[hash]) {
                if (!inputs[hash].hasOwnProperty(index))
                    continue;
                var script = parseScript(inputs[hash][index].script);
                var b64hash = Crypto.util.bytesToBase64(Crypto.util.hexToBytes(hash));
                var txin = new Bitcoin.TransactionIn({outpoint: {hash: b64hash, index: index}, script: script, sequence: 4294967295});
                selectedOuts.push(txin);
                sendTx.addInput(txin);
            }
        }

        for (var i in outputs) {
            var address = outputs[i].address;
            var fval = outputs[i].value;
            var value = new BigInteger('' + Math.round(fval * 1e8), 10);
            sendTx.addOutput(new Bitcoin.Address(address), value);
        }

        var hashType = 1;
        for (var i = 0; i < sendTx.ins.length; i++) {
            var connectedScript = selectedOuts[i].script;
            var hash = sendTx.hashTransactionForSignature(connectedScript, i, hashType);
            var pubKeyHash = connectedScript.simpleOutPubKeyHash();
            var signature = eckey.sign(hash);
            signature.push(parseInt(hashType, 10));
            var pubKey = eckey.getPub();
            var script = new Bitcoin.Script();
            script.writeBytes(signature);
            script.writeBytes(pubKey);
            sendTx.ins[i].script = script;
        }
        return sendTx;
    };

    this.toBBE = function(sendTx) {
        //serialize to Bitcoin Block Explorer format
        var buf = sendTx.serialize();
        var hash = Crypto.SHA256(Crypto.SHA256(buf, {asBytes: true}), {asBytes: true});

        var r = {};
        r['hash'] = Crypto.util.bytesToHex(hash.reverse());
        r['ver'] = sendTx.version;
        r['vin_sz'] = sendTx.ins.length;
        r['vout_sz'] = sendTx.outs.length;
        r['lock_time'] = sendTx.lock_time;
        r['size'] = buf.length;
        r['in'] = []
        r['out'] = []

        for (var i = 0; i < sendTx.ins.length; i++) {
            var txin = sendTx.ins[i];
            var hash = Crypto.util.base64ToBytes(txin.outpoint.hash);
            var n = txin.outpoint.index;
            var prev_out = {'hash': Crypto.util.bytesToHex(hash.reverse()), 'n': n};

            if (n == 4294967295) {
                var cb = Crypto.util.bytesToHex(txin.script.buffer);
                r['in'].push({'prev_out': prev_out, 'coinbase' : cb});
            } else {
                var ss = dumpScript(txin.script);
                r['in'].push({'prev_out': prev_out, 'scriptSig' : ss});
            }
        }

        for (var i = 0; i < sendTx.outs.length; i++) {
            var txout = sendTx.outs[i];
            var bytes = txout.value.slice(0);
            var fval = parseFloat(Bitcoin.Util.formatValue(bytes.reverse()));
            var value = fval.toFixed(8);
            var spk = dumpScript(txout.script);
            r['out'].push({'value' : value, 'scriptPubKey': spk});
        }

        return JSON.stringify(r, null, 4);
    };

    return this;
};

function dumpScript(script) {
    var out = [];
    for (var i = 0; i < script.chunks.length; i++) {
        var chunk = script.chunks[i];
        var op = new Bitcoin.Opcode(chunk);
        typeof chunk == 'number' ?  out.push(op.toString()) :
            out.push(Crypto.util.bytesToHex(chunk));
    }
    return out.join(' ');
}

// blockchain.info parser (adapted)
// uses http://blockchain.info/unspent?address=<address>
function tx_parseBCI(data, address) {
    var r = JSON.parse(data);
    var txs = r.unspent_outputs;

    if (!txs)
        throw 'Not a BCI format';

    delete unspenttxs;
    var unspenttxs = {};
    var balance = BigInteger.ZERO;
    for (var i in txs) {
        var o = txs[i];
        var lilendHash = o.tx_hash;

        //convert script back to BBE-compatible text
        var script = dumpScript( new Bitcoin.Script(Crypto.util.hexToBytes(o.script)) );

        var value = new BigInteger('' + o.value, 10);
        if (!(lilendHash in unspenttxs))
            unspenttxs[lilendHash] = {};
        unspenttxs[lilendHash][o.tx_output_n] = {amount: value, script: script};
        balance = balance.add(value);
    }
    return {balance:balance, unspenttxs:unspenttxs};
}

function isEmpty(ob) {
    for(var i in ob){ if(ob.hasOwnProperty(i)){return false;}}
    return true;
}

function endian(string) {
    var out = []
    for(var i = string.length; i > 0; i-=2) {
        out.push(string.substring(i-2,i));
    }
    return out.join("");
}

function btcstr2bignum(btc) {
    var i = btc.indexOf('.');
    var value = new BigInteger(btc.replace(/\./,''));
    var diff = 9 - (btc.length - i);
    if (i == -1) {
        var mul = "100000000";
    } else if (diff < 0) {
        return value.divide(new BigInteger(Math.pow(10,-1*diff).toString()));
    } else {
        var mul = Math.pow(10,diff).toString();
    }
    return value.multiply(new BigInteger(mul));
}

function parseScript(script) {
    var newScript = new Bitcoin.Script();
    var s = script.split(" ");
    for (var i in s) {
        if (Bitcoin.Opcode.map.hasOwnProperty(s[i])){
            newScript.writeOp(Bitcoin.Opcode.map[s[i]]);
        } else {
            newScript.writeBytes(Crypto.util.hexToBytes(s[i]));
        }
    }
    return newScript;
}
// --->8---

<|endoftext|>


<commit_before>const path = require('path');
const FaviconsWebpackPlugin = require('favicons-webpack-plugin');
const Dotenv = require('dotenv-webpack');
require('dotenv').config();

module.exports = (env) => {
  const environment = (env && env.NODE_ENV) ?
    env.NODE_ENV.toLocaleLowerCase() : 'development';
  return {
    entry: {
      main: path.resolve(__dirname, '../../src/index.jsx'),
      polyfills: path.resolve(__dirname, './polyfills.js'),
    },
    devtool: 'source-map',
    plugins: [
      new FaviconsWebpackPlugin({
        logo: path.resolve(__dirname, '../../assets/logo.png'),
        prefix: 'icons/[hash]/',
        emitStats: false,
        statsFilename: 'icons/stats-[hash].json',
        persistentCache: true,
        inject: true,
        background: '#fff',
        title: 'Antonios Karagiannis',
        // @see https://github.com/haydenbleasel/favicons#usage
        icons: {
          android: true,
          appleIcon: true,
          appleStartup: true,
          coast: false,
          favicons: true,
          firefox: true,
          opengraph: true,
          twitter: true,
          yandex: false,
          windows: false,
        },
      }),
      new Dotenv({
        path: path.resolve(__dirname, '../../.env'),
        safe: false,
      }),
    ],
    output: {
      filename: '[name].bundle.js',
      path: path.resolve(__dirname, '../../dist'),
    },
    resolve: {
      extensions: ['.js', '.json', '.jsx'],
      alias: {
        Assets: path.resolve(__dirname, '../assets/'),
        Actions: path.resolve(__dirname, '../../src/actions/'),
        Components: path.resolve(__dirname, '../../src/components/'),
        Constants: path.resolve(__dirname, '../../src/constants/'),
        Containers: path.resolve(__dirname, '../../src/containers/'),
        Helpers: path.resolve(__dirname, '../../src/helpers/'),
        Reducers: path.resolve(__dirname, '../../src/reducers/'),
        ReduxLogger$: (environment !== 'production' ?
          'redux-logger' : path.resolve(__dirname, '../../src/helpers/empty.js')),
        ReduxDevtoolsExtension$: (environment !== 'production' ?
          'redux-devtools-extension' : path.resolve(__dirname, '../../src/helpers/empty.js')),
      },
    },
    module: {
      rules: [
        {
          test: /\.jsx?$/,
          enforce: 'pre',
          exclude: /(node_modules|bower_components)/,
          loader: 'eslint-loader',
          options: {
            cache: true,
            emitError: true,
            failOnWarning: true,
            failOnError: true,
            // Unfortunately, some config options must be duplicated here
            // even though they are defined within package.json[eslintConfig]
            // which is what IDEs use to configure ESLint but this one
            // uses the CLIEngine options instead...
            // @see https://github.com/eslint/eslint/issues/9484
            // @see https://eslint.org/docs/developer-guide/nodejs-api#cliengine
            plugins: [
              'jsx-a11y',
            ],
          },
        },
        {
          test: /\.jsx?$/,
          exclude: /(node_modules|bower_components)/,
          use: [
            {
              loader: 'babel-loader',
              options: {
                presets: ['es2015', 'react'],
                plugins: ['transform-object-rest-spread'],
              },
            },
          ],
        },
        // {
        //     test: /\.html$/,
        //     use: ['file-loader?name=[path][name].[ext]!extract-loader!html-loader']
        // },
        // {
        //     test: /\.(html)$/,
        //     use: {
        //         loader: 'html-loader',
        //         options: {
        //             attrs: [':data-src'],
        //             minimize: true
        //         }
        //     }
        // },
        // {
        //     test: /\.(png|jpg|gif)$/,
        //     use: [{
        //         loader: 'file-loader',
        //         options: {}
        //     }]
        // }
      ],
    },
  };
};
<commit_msg>build(config/webpack/common.js): change failOnWarning/Error of eslint-loader to be true when not in<commit_after>const path = require('path');
const FaviconsWebpackPlugin = require('favicons-webpack-plugin');
const Dotenv = require('dotenv-webpack');
require('dotenv').config();

module.exports = (env) => {
  const environment = (env && env.NODE_ENV) ?
    env.NODE_ENV.toLocaleLowerCase() : 'development';
  return {
    entry: {
      main: path.resolve(__dirname, '../../src/index.jsx'),
      polyfills: path.resolve(__dirname, './polyfills.js'),
    },
    devtool: 'source-map',
    plugins: [
      new FaviconsWebpackPlugin({
        logo: path.resolve(__dirname, '../../assets/logo.png'),
        prefix: 'icons/[hash]/',
        emitStats: false,
        statsFilename: 'icons/stats-[hash].json',
        persistentCache: true,
        inject: true,
        background: '#fff',
        title: 'Antonios Karagiannis',
        // @see https://github.com/haydenbleasel/favicons#usage
        icons: {
          android: true,
          appleIcon: true,
          appleStartup: true,
          coast: false,
          favicons: true,
          firefox: true,
          opengraph: true,
          twitter: true,
          yandex: false,
          windows: false,
        },
      }),
      new Dotenv({
        path: path.resolve(__dirname, '../../.env'),
        safe: false,
      }),
    ],
    output: {
      filename: '[name].bundle.js',
      path: path.resolve(__dirname, '../../dist'),
    },
    resolve: {
      extensions: ['.js', '.json', '.jsx'],
      alias: {
        Assets: path.resolve(__dirname, '../assets/'),
        Actions: path.resolve(__dirname, '../../src/actions/'),
        Components: path.resolve(__dirname, '../../src/components/'),
        Constants: path.resolve(__dirname, '../../src/constants/'),
        Containers: path.resolve(__dirname, '../../src/containers/'),
        Helpers: path.resolve(__dirname, '../../src/helpers/'),
        Reducers: path.resolve(__dirname, '../../src/reducers/'),
        ReduxLogger$: (environment !== 'production' ?
          'redux-logger' : path.resolve(__dirname, '../../src/helpers/empty.js')),
        ReduxDevtoolsExtension$: (environment !== 'production' ?
          'redux-devtools-extension' : path.resolve(__dirname, '../../src/helpers/empty.js')),
      },
    },
    module: {
      rules: [
        {
          test: /\.jsx?$/,
          enforce: 'pre',
          exclude: /(node_modules|bower_components)/,
          loader: 'eslint-loader',
          options: {
            cache: true,
            emitError: true,
            failOnWarning: environment !== 'development',
            failOnError: environment !== 'development',
            // Unfortunately, some config options must be duplicated here
            // even though they are defined within package.json[eslintConfig]
            // which is what IDEs use to configure ESLint but this one
            // uses the CLIEngine options instead...
            // @see https://github.com/eslint/eslint/issues/9484
            // @see https://eslint.org/docs/developer-guide/nodejs-api#cliengine
            plugins: [
              'jsx-a11y',
            ],
          },
        },
        {
          test: /\.jsx?$/,
          exclude: /(node_modules|bower_components)/,
          use: [
            {
              loader: 'babel-loader',
              options: {
                presets: ['es2015', 'react'],
                plugins: ['transform-object-rest-spread'],
              },
            },
          ],
        },
        // {
        //     test: /\.html$/,
        //     use: ['file-loader?name=[path][name].[ext]!extract-loader!html-loader']
        // },
        // {
        //     test: /\.(html)$/,
        //     use: {
        //         loader: 'html-loader',
        //         options: {
        //             attrs: [':data-src'],
        //             minimize: true
        //         }
        //     }
        // },
        // {
        //     test: /\.(png|jpg|gif)$/,
        //     use: [{
        //         loader: 'file-loader',
        //         options: {}
        //     }]
        // }
      ],
    },
  };
};
<|endoftext|>


<commit_before>load("util.js");

var io = {
	print: function(s) {
		return print(s);
	},
	quit: function() {
		return quit();
	},
};

var connector = {
	selector: java.nio.channels.Selector.open(),
	accept_pending: [],
	connect_pending: [],

	get_pending: function(pending_list, sd, keep) {
		for (var i = 0; i < pending_list.length; i++) {
			if (pending_list[i].sd == sd) {
				var pending = pending_list[i];
				if (!keep)
					pending_list.splice(i, 1)[0];
				return pending;
			}
		}
	},

	wait_for_event: function() {
		var n;
		do {
			n = this.selector.select();
		} while (n == 0);
		var key = this.selector.selectedKeys().iterator().next();
		var channel = key.channel();
		this.selector.selectedKeys().remove(key);
		var ev = {};
		if ((key.readyOps() & java.nio.channels.SelectionKey.OP_ACCEPT)
			== java.nio.channels.SelectionKey.OP_ACCEPT) {
			ev.type = "accept";
			ev.sd = channel.socket().accept().channel;
			/* Keep the pending record. */
			pending = this.get_pending(this.accept_pending, channel, true);
			ev.address = ev.sd.socket().getInetAddress().getHostAddress();
			ev.port = ev.sd.socket().getPort();
			ev.userdata = pending.userdata;
		} else if ((key.readyOps() & java.nio.channels.SelectionKey.OP_CONNECT)
			== java.nio.channels.SelectionKey.OP_CONNECT) {
			if (channel.isConnectionPending())
				channel.finishConnect();
			ev.type = "connect";
			ev.sd = channel;
			pending = this.get_pending(this.connect_pending, channel);
			ev.userdata = pending.userdata;
			key.cancel();
		} else {
			io.print("Unknown selection key op.");
			io.quit();
		}
		return ev;
	},
	listen: function(address, port, userdata) {
		var ssc = java.nio.channels.ServerSocketChannel.open();
		ssc.configureBlocking(false);
		var s = ssc.socket();
		s.bind(java.net.InetSocketAddress(port));
		ssc.register(this.selector, java.nio.channels.SelectionKey.OP_ACCEPT);
		this.accept_pending.push({ sd: ssc, userdata: userdata });
		return ssc;
	},
	connect: function(address, port, userdata) {
		var sc = java.nio.channels.SocketChannel.open();
		sc.configureBlocking(false);
		sc.register(this.selector, java.nio.channels.SelectionKey.OP_CONNECT);
		sc.connect(java.net.InetSocketAddress(address, port));
		this.connect_pending.push({ sd: sc, userdata: userdata });
		return sc;
	},
	recv: function(sd, userdata) {
	},
	send: function(sd, data, userdata) {
	},
	close: function(sd, userdata) {
	},
};

io.print("jscat starting.")

var LOCAL_ADDRESS = "0.0.0.0";
var LOCAL_PORT = 9998;

var DIRECTORY_ADDRESS = "localhost";
var DIRECTORY_PORT = 9999;

var peers = {};

var l = connector.listen(LOCAL_ADDRESS, LOCAL_PORT);

while (true) {
	var ev = connector.wait_for_event();
	io.print("ev: " + repr(ev));
	switch (ev.type) {
	case "accept":
		io.print("Connection from " + ev.address + ":" + ev.port + ".");
		connector.connect(DIRECTORY_ADDRESS, DIRECTORY_PORT, ev.sd);
		break;
	case "connect":
		peers[ev.sd] = ev.userdata;
		peers[ev.userdata] = ev.sd;
		/* Queue initial read events. */
		connector.recv(ev.sd, ev.userdata);
		connector.recv(ev.userdata, ev.sd);
		break;
	case "recv":
		connector.send(ev.userdata, ev.data);
		break;
	case "close":
		var peer = peers[ev.sd];
		connector.close(peer[ev.sd]);
		delete peers[ev.sd];
		delete peers[peer];
		break;
	case "error":
		io.quit();
		break;
	}
}
<commit_msg>Implement dummy recv.<commit_after>load("util.js");

var io = {
	print: function(s) {
		return print(s);
	},
	quit: function() {
		return quit();
	},
};

var connector = {
	selector: java.nio.channels.Selector.open(),
	read_buf: java.nio.ByteBuffer.allocate(1024),
	accept_pending: [],
	connect_pending: [],
	read_pending: [],

	get_pending: function(pending_list, sd, keep) {
		for (var i = 0; i < pending_list.length; i++) {
			if (pending_list[i].sd == sd) {
				var pending = pending_list[i];
				if (!keep)
					pending_list.splice(i, 1)[0];
				return pending;
			}
		}
	},

	wait_for_event: function() {
		var n;
		do {
			n = this.selector.select();
		} while (n == 0);
		var key = this.selector.selectedKeys().iterator().next();
		var channel = key.channel();
		this.selector.selectedKeys().remove(key);
		var ev = {};
		if ((key.readyOps() & java.nio.channels.SelectionKey.OP_ACCEPT)
			== java.nio.channels.SelectionKey.OP_ACCEPT) {
			ev.type = "accept";
			ev.sd = channel.socket().accept().channel;
			/* Keep the pending record. */
			pending = this.get_pending(this.accept_pending, channel, true);
			ev.address = ev.sd.socket().getInetAddress().getHostAddress();
			ev.port = ev.sd.socket().getPort();
			ev.userdata = pending.userdata;
		} else if ((key.readyOps() & java.nio.channels.SelectionKey.OP_CONNECT)
			== java.nio.channels.SelectionKey.OP_CONNECT) {
			if (channel.isConnectionPending())
				channel.finishConnect();
			ev.type = "connect";
			ev.sd = channel;
			pending = this.get_pending(this.connect_pending, channel);
			ev.userdata = pending.userdata;
			channel.register(this.selector, key.interestOps() & ~java.nio.channels.SelectionKey.OP_CONNECT);
		} else if ((key.readyOps() & java.nio.channels.SelectionKey.OP_READ)
			== java.nio.channels.SelectionKey.OP_READ) {
			ev.type = "recv";
			ev.sd = channel;
			var n = channel.read(this.read_buf);
			pending = this.get_pending(this.read_pending, channel);
			ev.userdata = pending.userdata;
			ev.data = "dummy";
			channel.register(this.selector, key.interestOps() & ~java.nio.channels.SelectionKey.OP_READ);
		} else {
			io.print("Unknown selection key op.");
			io.quit();
		}
		return ev;
	},
	listen: function(address, port, userdata) {
		var ssc = java.nio.channels.ServerSocketChannel.open();
		ssc.configureBlocking(false);
		var s = ssc.socket();
		s.bind(java.net.InetSocketAddress(port));
		ssc.register(this.selector, java.nio.channels.SelectionKey.OP_ACCEPT);
		this.accept_pending.push({ sd: ssc, userdata: userdata });
		return ssc;
	},
	connect: function(address, port, userdata) {
		var sc = java.nio.channels.SocketChannel.open();
		sc.configureBlocking(false);
		sc.register(this.selector, java.nio.channels.SelectionKey.OP_CONNECT);
		sc.connect(java.net.InetSocketAddress(address, port));
		this.connect_pending.push({ sd: sc, userdata: userdata });
		return sc;
	},
	recv: function(sd, userdata) {
		sd.configureBlocking(false);
		sd.register(this.selector, java.nio.channels.SelectionKey.OP_READ);
		this.read_pending.push({ sd: sd, userdata: userdata });
		return sd;
	},
	send: function(sd, data, userdata) {
	},
	close: function(sd, userdata) {
	},
};

io.print("jscat starting.")

var LOCAL_ADDRESS = "0.0.0.0";
var LOCAL_PORT = 9998;

var DIRECTORY_ADDRESS = "localhost";
var DIRECTORY_PORT = 9999;

var peers = {};

var l = connector.listen(LOCAL_ADDRESS, LOCAL_PORT);

while (true) {
	var ev = connector.wait_for_event();
	io.print("ev: " + repr(ev));
	switch (ev.type) {
	case "accept":
		io.print("Connection from " + ev.address + ":" + ev.port + ".");
		connector.connect(DIRECTORY_ADDRESS, DIRECTORY_PORT, ev.sd);
		break;
	case "connect":
		peers[ev.sd] = ev.userdata;
		peers[ev.userdata] = ev.sd;
		/* Queue initial read events. */
		connector.recv(ev.sd, ev.userdata);
		connector.recv(ev.userdata, ev.sd);
		break;
	case "recv":
		connector.send(ev.userdata, ev.data);
		connector.recv(ev.sd, ev.userdata);
		break;
	case "close":
		var peer = peers[ev.sd];
		connector.close(peer[ev.sd]);
		delete peers[ev.sd];
		delete peers[peer];
		break;
	case "error":
		io.quit();
		break;
	}
}
<|endoftext|>