<commit_before>// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP

import React, { Component } from 'react';
import Query from 'grommet-addons/utils/Query';
import DocsArticle from '../../components/DocsArticle';

let query = new Query('(a OR b) AND (n:v OR n:w) "big deal" NOT ' +
  '01:23:45:67:89:ab 2016-01-31T16:45:46Z');
let errorQuery = new Query('a b "');

export default class QueryDoc extends Component {

  render () {
    return (
      <DocsArticle title='Query'>

Utility functions for managing search and filter contexts. It can
            be used for:

User typed text containing simple text terms, which
              might be quoted. For
              instance, name or
              'search term'.

User typed text containing faceted filter terms. For
              instance, name:value.

Combined text terms, faceted filters, and boolean logic. The
              boolean logic available
              includes AND, OR, NOT, and
              parentheses for grouping.

Constructor

string

Typically, this is the user typed text string.

Methods

error    ({'{object}'})

An exception object indicating syntactical issues with
              parsing.

set      ({'{string}'})

Replace the current text string.

toString ()

Gets the current text string.

tree     ()

Returns a boolean logic tree object. This permits syntax
              highlighting and programmatic processing. Connecting nodes are
              of the form {'{ op: and|or, left: , right: }'}. Leaf
              nodes are of the form
              {'{ text: , name:, value: , not: true|false }'}

Examples

Boolean Logic

            {`let query = new Query('${query.toString()}');\n`}
            {'query.toString();\n'}
            {'>> ' + query.toString() + '\n'}
            {'query.error();\n'}
            {'>> ' + query.error() + '\n'}
            {'query.tree();\n'}
            {'>> ' + JSON.stringify(query.tree(), null, '  ')}

Syntax error

            {`let errorQuery = new Query('${errorQuery.toString()}');\n`}
            {'errorQuery.toString();\n'}
            {'>> ' + errorQuery.toString() + '\n'}
            {'errorQuery.error();\n'}
            {'>> ' + errorQuery.error() + '\n'}

      </DocsArticle>
    );
  }
};
<commit_msg>add grommet-addons note to Query (#244)<commit_after>// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP

import React, { Component } from 'react';
import Query from 'grommet-addons/utils/Query';
import DocsArticle from '../../components/DocsArticle';

let query = new Query('(a OR b) AND (n:v OR n:w) "big deal" NOT ' +
  '01:23:45:67:89:ab 2016-01-31T16:45:46Z');
let errorQuery = new Query('a b "');

export default class QueryDoc extends Component {

  render () {
    return (
      <DocsArticle title='Query'>

Utility functions for managing search and filter contexts. It can
            be used for:

User typed text containing simple text terms, which
              might be quoted. For
              instance, name or
              'search term'.

User typed text containing faceted filter terms. For
              instance, name:value.

Combined text terms, faceted filters, and boolean logic. The
              boolean logic available
              includes AND, OR, NOT, and
              parentheses for grouping.

NOTE: This component comes from
            the grommet-addons repository. You will need to add
            a dependency to that repository in order to use it.

Constructor

string

Typically, this is the user typed text string.

Methods

error    ({'{object}'})

An exception object indicating syntactical issues with
              parsing.

set      ({'{string}'})

Replace the current text string.

toString ()

Gets the current text string.

tree     ()

Returns a boolean logic tree object. This permits syntax
              highlighting and programmatic processing. Connecting nodes are
              of the form {'{ op: and|or, left: , right: }'}. Leaf
              nodes are of the form
              {'{ text: , name:, value: , not: true|false }'}

Examples

Boolean Logic

            {`let query = new Query('${query.toString()}');\n`}
            {'query.toString();\n'}
            {'>> ' + query.toString() + '\n'}
            {'query.error();\n'}
            {'>> ' + query.error() + '\n'}
            {'query.tree();\n'}
            {'>> ' + JSON.stringify(query.tree(), null, '  ')}

Syntax error

            {`let errorQuery = new Query('${errorQuery.toString()}');\n`}
            {'errorQuery.toString();\n'}
            {'>> ' + errorQuery.toString() + '\n'}
            {'errorQuery.error();\n'}
            {'>> ' + errorQuery.error() + '\n'}

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


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count<commit_msg>Not quite working<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count <|endoftext|>


<commit_before>/*
 * Methods for fetching pasted html before it gets inserted into content
**/

/* Modern event.clipboardData driven approach.
 * Advantage is that it does not have to loose selection or modify dom to catch the data.
 * IE does not support though.
**/
wysihtml5.dom.getPastedHtml = function(event) {
  var html;
  if (event.clipboardData) {
    if (wysihtml5.lang.array(event.clipboardData.types).contains('text/html')) {
      html = event.clipboardData.getData('text/html');
    } else if (wysihtml5.lang.array(event.clipboardData.types).contains('text/plain')) {
      html = wysihtml5.lang.string(event.clipboardData.getData('text/plain')).escapeHTML(true, true);
    }
  }
  return html;
};

/* Older temprorary contenteditable as paste source catcher method for fallbacks */
wysihtml5.dom.getPastedHtmlWithDiv = function (composer, f) {
  var selBookmark = composer.selection.getBookmark(),
      doc = composer.element.ownerDocument,
      cleanerDiv = doc.createElement('DIV');

  doc.body.appendChild(cleanerDiv);

  cleanerDiv.style.width = "1px";
  cleanerDiv.style.height = "1px";
  cleanerDiv.style.overflow = "hidden";

  cleanerDiv.setAttribute('contenteditable', 'true');
  cleanerDiv.focus();

  setTimeout(function () {
    var html;

    composer.selection.setBookmark(selBookmark);
    html = cleanerDiv.innerHTML;
    if (html && (/^<br\/?>$/i).test(html.trim())) {
      html = false;
    }
    f(html);
    cleanerDiv.parentNode.removeChild(cleanerDiv);
  }, 0);
};
<commit_msg>Fixes #140 IE pasting problems<commit_after>/*
 * Methods for fetching pasted html before it gets inserted into content
**/

/* Modern event.clipboardData driven approach.
 * Advantage is that it does not have to loose selection or modify dom to catch the data.
 * IE does not support though.
**/
wysihtml5.dom.getPastedHtml = function(event) {
  var html;
  if (event.clipboardData) {
    if (wysihtml5.lang.array(event.clipboardData.types).contains('text/html')) {
      html = event.clipboardData.getData('text/html');
    } else if (wysihtml5.lang.array(event.clipboardData.types).contains('text/plain')) {
      html = wysihtml5.lang.string(event.clipboardData.getData('text/plain')).escapeHTML(true, true);
    }
  }
  return html;
};

/* Older temprorary contenteditable as paste source catcher method for fallbacks */
wysihtml5.dom.getPastedHtmlWithDiv = function (composer, f) {
  var selBookmark = composer.selection.getBookmark(),
      doc = composer.element.ownerDocument,
      cleanerDiv = doc.createElement('DIV'),
      scrollPos = composer.getScrollPos();

  doc.body.appendChild(cleanerDiv);

  cleanerDiv.style.width = "1px";
  cleanerDiv.style.height = "1px";
  cleanerDiv.style.overflow = "hidden";
  cleanerDiv.style.position = "absolute";
  cleanerDiv.style.top = scrollPos.y + "px";
  cleanerDiv.style.left = scrollPos.x + "px";

  cleanerDiv.setAttribute('contenteditable', 'true');
  cleanerDiv.focus();

  setTimeout(function () {
    var html;

    composer.selection.setBookmark(selBookmark);
    html = cleanerDiv.innerHTML;
    if (html && (/^<br\/?>$/i).test(html.trim())) {
      html = false;
    }
    f(html);
    cleanerDiv.parentNode.removeChild(cleanerDiv);
  }, 0);
};
<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced i<commit_msg>One more time...<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue <commit_msg>How many more of these can I make?<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue w<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit<commit_msg>Fixing an important issue with the universe.<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    <|endoftext|>


<commit_before>/*
 * Purchase object that handles all the functions related to
 * contract purchase response
 */

var Purchase = (function () {
    'use strict';

    var purchase_data = {};
    BetSell.register();

    var display = function (details) {
        purchase_data = details;

        var receipt = details['buy'],
            passthrough = details['echo_req']['passthrough'],
            container = document.getElementById('contract_confirmation_container'),
            message_container = document.getElementById('confirmation_message'),
            heading = document.getElementById('contract_purchase_heading'),
            descr = document.getElementById('contract_purchase_descr'),
            reference = document.getElementById('contract_purchase_reference'),
            chart = document.getElementById('tick_chart'),
            balance = document.getElementById('contract_purchase_balance'),
            payout = document.getElementById('contract_purchase_payout'),
            cost = document.getElementById('contract_purchase_cost'),
            profit = document.getElementById('contract_purchase_profit'),
            spots = document.getElementById('contract_purchase_spots'),
            confirmation_error = document.getElementById('confirmation_error'),
            contracts_list = document.getElementById('contracts_list'),
            button = document.getElementById('contract_purchase_button');

        var error = details['error'];
        var show_chart = !error && passthrough['duration']<=10 && passthrough['duration_unit']==='t' && (sessionStorage.formname === 'risefall' || sessionStorage.formname === 'higherlower' || sessionStorage.formname === 'asian');

        container.style.display = 'block';
        contracts_list.style.display = 'none';

        if (error) {
            message_container.hide();
            confirmation_error.show();
            confirmation_error.textContent = error['message'];
        } else {
            message_container.show();
            confirmation_error.hide();

            heading.textContent = Content.localize().textContractConfirmationHeading;
            descr.textContent = receipt['longcode'];
            reference.textContent = Content.localize().textContractConfirmationReference + ' ' + receipt['fmb_id'];

            var payout_value, cost_value, profit_value;

            if(passthrough['basis'] === "payout"){
                payout_value = passthrough['amount'];
                cost_value = passthrough['ask-price'];
            }
            else{
                cost_value = passthrough['amount'];
                var match = receipt['longcode'].match(/\d+\.\d\d/);
                payout_value = match[0];
            }
            profit_value = Math.round((payout_value - cost_value)*100)/100;

            if(sessionStorage.getItem('formname')==='spreads'){
                payout.hide();
                cost.hide();
                profit.hide();

                // payout.innerHTML = Content.localize().textStopLoss + '
' + payout_value + '
';
                // cost.innerHTML = Content.localize().textAmountPerPoint + '
' + cost_value + '
';
                // profit.innerHTML = Content.localize().textStopProfit + '
' + profit_value + '
';
            }
            else {
                payout.show();
                cost.show();
                profit.show();
                payout.innerHTML = Content.localize().textContractConfirmationPayout + '
' + payout_value + '
';
                cost.innerHTML = Content.localize().textContractConfirmationCost + '
' + cost_value + '
';
                profit.innerHTML = Content.localize().textContractConfirmationProfit + '
' + profit_value + '
';
            }

            balance.textContent = Content.localize().textContractConfirmationBalance + ' ' + User.get().currency + ' ' + Math.round(receipt['balance_after']*100)/100;

            if(show_chart){
                chart.show();
            }
            else{
                chart.hide();
            }

            if(sessionStorage.formname === 'digits'){
                spots.textContent = '';
                spots.show();
            }
            else{
                spots.hide();
            }

            button.textContent = Content.localize().textContractConfirmationButton;
            var purchase_date = new Date(receipt['purchase_time']*1000);
            var button_attrs = {
                contract_id: receipt['fmb_id'],
                controller_action: 'sell',
                currency: document.getElementById('currency').value,
                payout: payout_value,
                purchase_price: cost_value,
                purchase_time: (purchase_date.getUTCFullYear()+'-'+(purchase_date.getUTCMonth()+1)+'-'+purchase_date.getUTCDate()+' '+purchase_date.getUTCHours()+':'+purchase_date.getUTCMinutes()+':'+purchase_date.getUTCSeconds()),
                qty:1,
                shortcode:receipt['shortcode'],
                url:'https://'+window.location.host+'/trade/analyse_contract?l=EN'
            };
            for(var k in button_attrs){
                if(k){
                    button.setAttribute(k,button_attrs[k]);
                }
            }
        }

        if(show_chart){
            var contract_sentiment;
            if(passthrough['contract_type']==='CALL' || passthrough['contract_type']==='ASIANU'){
                contract_sentiment = 'up';
            }
            else{
                contract_sentiment = 'down';
            }
            WSTickDisplay.initialize({
                "symbol":passthrough.symbol,
                "number_of_ticks":passthrough.duration,
                "previous_tick_epoch":receipt['start_time'],
                "contract_category":"callput",

                "display_symbol":Symbols.getName(passthrough.symbol),
                "contract_start":receipt['start_time'],
                "decimal":3,
                "contract_sentiment":contract_sentiment,
                "price":passthrough['ask-price'],
                "payout":passthrough['amount'],
                "show_contract_result":1
            });
        }
    };

    var update_spot_list = function(data){
        var spots = document.getElementById('contract_purchase_spots');
        if(isVisible(spots) && purchase_data.echo_req.passthrough['duration'] && data.tick.epoch && data.tick.epoch > purchase_data.buy.start_time){
            var fragment = document.createElement('div');
            fragment.classList.add('row');

            var el1 = document.createElement('div');
            el1.classList.add('col');
            el1.textContent = 'Tick '+ (spots.getElementsByClassName('row').length+1);
            fragment.appendChild(el1);

            var el2 = document.createElement('div');
            el2.classList.add('col');
            var date = new Date(data.tick.epoch*1000);
            var hours = date.getUTCHours() < 10 ? '0'+date.getUTCHours() : date.getUTCHours();
            var minutes = date.getUTCMinutes() < 10 ? '0'+date.getUTCMinutes() : date.getUTCMinutes();
            var seconds = date.getUTCSeconds() < 10 ? '0'+date.getUTCSeconds() : date.getUTCSeconds();
            el2.textContent = hours+':'+minutes+':'+seconds;
            fragment.appendChild(el2);

            var d1;
            var tick = data.tick.quote.replace(/\d$/,function(d){d1 = d; return ''+d+'';});
            var el3 = document.createElement('div');
            el3.classList.add('col');
            el3.innerHTML = tick;
            fragment.appendChild(el3);

            spots.appendChild(fragment);
            spots.scrollTop = spots.scrollHeight;

            if(d1 && purchase_data.echo_req.passthrough['duration']===1){
                var contract_status;
                if(d1==purchase_data.echo_req.passthrough['barrier']){
                    spots.className = 'won';
                    contract_status = 'This contract won';
                }
                else{
                    spots.className = 'lost';
                    contract_status = 'This contract lost';
                }
                document.getElementById('contract_purchase_heading').textContent = text.localize(contract_status);
            }

            purchase_data.echo_req.passthrough['duration']--;
        }
    };

    return {
        display: display,
        update_spot_list: update_spot_list
    };

})();
<commit_msg>hide view button for contracts with visualization<commit_after>/*
 * Purchase object that handles all the functions related to
 * contract purchase response
 */

var Purchase = (function () {
    'use strict';

    var purchase_data = {};
    BetSell.register();

    var display = function (details) {
        purchase_data = details;

        var receipt = details['buy'],
            passthrough = details['echo_req']['passthrough'],
            container = document.getElementById('contract_confirmation_container'),
            message_container = document.getElementById('confirmation_message'),
            heading = document.getElementById('contract_purchase_heading'),
            descr = document.getElementById('contract_purchase_descr'),
            reference = document.getElementById('contract_purchase_reference'),
            chart = document.getElementById('tick_chart'),
            balance = document.getElementById('contract_purchase_balance'),
            payout = document.getElementById('contract_purchase_payout'),
            cost = document.getElementById('contract_purchase_cost'),
            profit = document.getElementById('contract_purchase_profit'),
            spots = document.getElementById('contract_purchase_spots'),
            confirmation_error = document.getElementById('confirmation_error'),
            contracts_list = document.getElementById('contracts_list'),
            button = document.getElementById('contract_purchase_button');

        var error = details['error'];
        var show_chart = !error && passthrough['duration']<=10 && passthrough['duration_unit']==='t' && (sessionStorage.formname === 'risefall' || sessionStorage.formname === 'higherlower' || sessionStorage.formname === 'asian');

        container.style.display = 'block';
        contracts_list.style.display = 'none';

        if (error) {
            message_container.hide();
            confirmation_error.show();
            confirmation_error.textContent = error['message'];
        } else {
            message_container.show();
            confirmation_error.hide();

            heading.textContent = Content.localize().textContractConfirmationHeading;
            descr.textContent = receipt['longcode'];
            reference.textContent = Content.localize().textContractConfirmationReference + ' ' + receipt['fmb_id'];

            var payout_value, cost_value, profit_value;

            if(passthrough['basis'] === "payout"){
                payout_value = passthrough['amount'];
                cost_value = passthrough['ask-price'];
            }
            else{
                cost_value = passthrough['amount'];
                var match = receipt['longcode'].match(/\d+\.\d\d/);
                payout_value = match[0];
            }
            profit_value = Math.round((payout_value - cost_value)*100)/100;

            if(sessionStorage.getItem('formname')==='spreads'){
                payout.hide();
                cost.hide();
                profit.hide();

                // payout.innerHTML = Content.localize().textStopLoss + '
' + payout_value + '
';
                // cost.innerHTML = Content.localize().textAmountPerPoint + '
' + cost_value + '
';
                // profit.innerHTML = Content.localize().textStopProfit + '
' + profit_value + '
';
            }
            else {
                payout.show();
                cost.show();
                profit.show();
                payout.innerHTML = Content.localize().textContractConfirmationPayout + '
' + payout_value + '
';
                cost.innerHTML = Content.localize().textContractConfirmationCost + '
' + cost_value + '
';
                profit.innerHTML = Content.localize().textContractConfirmationProfit + '
' + profit_value + '
';
            }

            balance.textContent = Content.localize().textContractConfirmationBalance + ' ' + User.get().currency + ' ' + Math.round(receipt['balance_after']*100)/100;

            if(show_chart){
                chart.show();
            }
            else{
                chart.hide();
            }

            if(sessionStorage.formname === 'digits'){
                spots.textContent = '';
                spots.show();
            }
            else{
                spots.hide();
            }

            if(sessionStorage.formname !== 'digits' && !show_chart){
                button.show();
                button.textContent = Content.localize().textContractConfirmationButton;
                var purchase_date = new Date(receipt['purchase_time']*1000);
                var button_attrs = {
                    contract_id: receipt['fmb_id'],
                    controller_action: 'sell',
                    currency: document.getElementById('currency').value,
                    payout: payout_value,
                    purchase_price: cost_value,
                    purchase_time: (purchase_date.getUTCFullYear()+'-'+(purchase_date.getUTCMonth()+1)+'-'+purchase_date.getUTCDate()+' '+purchase_date.getUTCHours()+':'+purchase_date.getUTCMinutes()+':'+purchase_date.getUTCSeconds()),
                    qty:1,
                    shortcode:receipt['shortcode'],
                    url:'https://'+window.location.host+'/trade/analyse_contract?l=EN'
                };
                for(var k in button_attrs){
                    if(k){
                        button.setAttribute(k,button_attrs[k]);
                    }
                }
            }
            else{
                button.hide();
            }
        }

        if(show_chart){
            var contract_sentiment;
            if(passthrough['contract_type']==='CALL' || passthrough['contract_type']==='ASIANU'){
                contract_sentiment = 'up';
            }
            else{
                contract_sentiment = 'down';
            }
            WSTickDisplay.initialize({
                "symbol":passthrough.symbol,
                "number_of_ticks":passthrough.duration,
                "previous_tick_epoch":receipt['start_time'],
                "contract_category":"callput",

                "display_symbol":Symbols.getName(passthrough.symbol),
                "contract_start":receipt['start_time'],
                "decimal":3,
                "contract_sentiment":contract_sentiment,
                "price":passthrough['ask-price'],
                "payout":passthrough['amount'],
                "show_contract_result":1
            });
        }
    };

    var update_spot_list = function(data){
        var spots = document.getElementById('contract_purchase_spots');
        if(isVisible(spots) && purchase_data.echo_req.passthrough['duration'] && data.tick.epoch && data.tick.epoch > purchase_data.buy.start_time){
            var fragment = document.createElement('div');
            fragment.classList.add('row');

            var el1 = document.createElement('div');
            el1.classList.add('col');
            el1.textContent = 'Tick '+ (spots.getElementsByClassName('row').length+1);
            fragment.appendChild(el1);

            var el2 = document.createElement('div');
            el2.classList.add('col');
            var date = new Date(data.tick.epoch*1000);
            var hours = date.getUTCHours() < 10 ? '0'+date.getUTCHours() : date.getUTCHours();
            var minutes = date.getUTCMinutes() < 10 ? '0'+date.getUTCMinutes() : date.getUTCMinutes();
            var seconds = date.getUTCSeconds() < 10 ? '0'+date.getUTCSeconds() : date.getUTCSeconds();
            el2.textContent = hours+':'+minutes+':'+seconds;
            fragment.appendChild(el2);

            var d1;
            var tick = data.tick.quote.replace(/\d$/,function(d){d1 = d; return ''+d+'';});
            var el3 = document.createElement('div');
            el3.classList.add('col');
            el3.innerHTML = tick;
            fragment.appendChild(el3);

            spots.appendChild(fragment);
            spots.scrollTop = spots.scrollHeight;

            if(d1 && purchase_data.echo_req.passthrough['duration']===1){
                var contract_status;
                if(d1==purchase_data.echo_req.passthrough['barrier']){
                    spots.className = 'won';
                    contract_status = 'This contract won';
                }
                else{
                    spots.className = 'lost';
                    contract_status = 'This contract lost';
                }
                document.getElementById('contract_purchase_heading').textContent = text.localize(contract_status);
            }

            purchase_data.echo_req.passthrough['duration']--;
        }
    };

    return {
        display: display,
        update_spot_list: update_spot_list
    };

})();
<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var com<commit_msg>Fixing punctuation<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var comm<|endoftext|>


<commit_before>/**
 * Simple webserver with logging. By default, serves whatever files are
 * reachable from the directory where node is running.
 */
var posix = require('posix'),
	sys = require('sys'),
    config = require('./config').settings;

var DEBUG = 0, INFO = 1, WARN = 2, ERROR = 3;
var LOG_LEVEL = DEBUG;
var VERSION = "0.1"
var MAX_READ = 1024 * 1024 * 5; // 5MB - max bytes to request at a time
var TIMEOUT = 1000 * 30; // 30 seconds
var PORT = config.port || 8080; //listen port
var baseDir = config.baseDir || "./"; //web root

require("http").createServer(function(req,resp) {
    log(INFO, "Got request for",req.url);
    var pathname = require('url').parse(req.url).pathname || '/';
    function sanitize(path) {
        return path.replace(/\.\.\//g,''); //don't allow access to parent dirs
    }
    stream(baseDir + sanitize(pathname), resp);
}).listen(PORT);

log(INFO,"Server running on port",PORT);
log(INFO,"serving directory:",baseDir);

function stream(path, resp) {
    var die = setTimeout(finish,TIMEOUT);
    function sendHeaders(httpstatus, contentType) {
        resp.sendHeader(httpstatus, {
                "Content-Type" : contentType ||
                                 require("./content-type").mime_type(path) ||
                                 "application/octet-stream",
                "Server" : "Antinode/" + VERSION +
                           " Node.js/" + process.version +
                           " " + process.platform,
                "Date" : (new Date()).toUTCString()
            });
    }
    posix.stat(path).addCallback(function (stat) {
        if (stat.isDirectory()) {
            path += "/index.html";
        }
        streamFile(path,resp);
    }).addErrback(fileNotFound);

    function streamFile(file, resp) {
        posix.open(file,process.O_RDONLY, 0660).addCallback(function(fd) {
            var position = 0;
            log(DEBUG,"opened",fd);
            if(fd) {
                sendHeaders(200);
                read();
                function read() {
                    posix.read(fd,MAX_READ,position, "binary").addCallback(function(data,bytes_read) {
                        log(DEBUG,"read",bytes_read,"bytes of",file);
                        if(bytes_read > 0) {
                            resp.sendBody(data, "binary");
                            position += bytes_read;
                            read(); // read more
                        } else {
                            finish(fd);
                        }
                    }).addErrback(function() {
                        log(ERROR,"Error reading from",file,"position:",position,
                            ">",arguments);
                        resp.sendBody("*** Error reading from "+file+
                            ". Check the console for details. ***");
                        finish(fd);
                    });
                }
            } else {
                log(WARN,"Invalid fd for file:",file);
                sendHeader(500, "text/plain");
                resp.sendBody(file);
                resp.sendBody(" couldn't be opened.");
                finish(fd);
            }
        }).addErrback(fileNotFound);
    }
    function fileNotFound() {
        log(DEBUG,"404 opening",path,">",arguments);
        sendHeaders(404,"text/plain");
        resp.sendBody("*** Error opening " + path +
                ". Check the console for details. ***");
        finish();
    }
    function finish(fd) {
		resp.finish();
		log(DEBUG,"finished",fd);
		clearTimeout(die);
		if(fd) {
		    posix.close(fd);
		}
    }
}

/* Logging/Utility Functions */
function log(level) {
    if(level >= LOG_LEVEL) sys.puts(join(slice(arguments,1)));
}
function slice(array,start) {
	return Array.prototype.slice.call(array,start);
}
function isString(s) {
	return typeof s === "string" || s instanceof String;
}
function flatten(array) {
	var result = [], i, len = array && array.length;
	if(len && !isString(array)) {
		for(i = 0; i < len; i++) {
			result = result.concat(flatten(array[i]));
		}
	} else if(len !== 0) {
		result.push(array);
	}
	return result;
}
function join() {
	return flatten(slice(arguments,0)).join(" ");
}
<commit_msg>removed response variable - its available through closure<commit_after>/**
 * Simple webserver with logging. By default, serves whatever files are
 * reachable from the directory where node is running.
 */
var posix = require('posix'),
	sys = require('sys'),
    config = require('./config').settings;

var DEBUG = 0, INFO = 1, WARN = 2, ERROR = 3;
var LOG_LEVEL = DEBUG;
var VERSION = "0.1"
var MAX_READ = 1024 * 1024 * 5; // 5MB - max bytes to request at a time
var TIMEOUT = 1000 * 30; // 30 seconds
var PORT = config.port || 8080; //listen port
var baseDir = config.baseDir || "./"; //web root

require("http").createServer(function(req,resp) {
    log(INFO, "Got request for",req.url);
    var pathname = require('url').parse(req.url).pathname || '/';
    function sanitize(path) {
        return path.replace(/\.\.\//g,''); //don't allow access to parent dirs
    }
    stream(baseDir + sanitize(pathname), resp);
}).listen(PORT);

log(INFO,"Server running on port",PORT);
log(INFO,"serving directory:",baseDir);

function stream(path, resp) {
    var die = setTimeout(finish,TIMEOUT);
    function sendHeaders(httpstatus, contentType) {
        resp.sendHeader(httpstatus, {
                "Content-Type" : contentType ||
                                 require("./content-type").mime_type(path) ||
                                 "application/octet-stream",
                "Server" : "Antinode/" + VERSION +
                           " Node.js/" + process.version +
                           " " + process.platform,
                "Date" : (new Date()).toUTCString()
            });
    }
    posix.stat(path).addCallback(function (stat) {
        if (stat.isDirectory()) {
            path += "/index.html";
        }
        streamFile(path);
    }).addErrback(fileNotFound);

    function streamFile(file) {
        posix.open(file,process.O_RDONLY, 0660).addCallback(function(fd) {
            var position = 0;
            log(DEBUG,"opened",fd);
            if(fd) {
                sendHeaders(200);
                read();
                function read() {
                    posix.read(fd,MAX_READ,position, "binary").addCallback(function(data,bytes_read) {
                        log(DEBUG,"read",bytes_read,"bytes of",file);
                        if(bytes_read > 0) {
                            resp.sendBody(data, "binary");
                            position += bytes_read;
                            read(); // read more
                        } else {
                            finish(fd);
                        }
                    }).addErrback(function() {
                        log(ERROR,"Error reading from",file,"position:",position,
                            ">",arguments);
                        resp.sendBody("*** Error reading from "+file+
                            ". Check the console for details. ***");
                        finish(fd);
                    });
                }
            } else {
                log(WARN,"Invalid fd for file:",file);
                sendHeader(500, "text/plain");
                resp.sendBody(file);
                resp.sendBody(" couldn't be opened.");
                finish(fd);
            }
        }).addErrback(fileNotFound);
    }
    function fileNotFound() {
        log(DEBUG,"404 opening",path,">",arguments);
        sendHeaders(404,"text/plain");
        resp.sendBody("*** Error opening " + path +
                ". Check the console for details. ***");
        finish();
    }
    function finish(fd) {
		resp.finish();
		log(DEBUG,"finished",fd);
		clearTimeout(die);
		if(fd) {
		    posix.close(fd);
		}
    }
}

/* Logging/Utility Functions */
function log(level) {
    if(level >= LOG_LEVEL) sys.puts(join(slice(arguments,1)));
}
function slice(array,start) {
	return Array.prototype.slice.call(array,start);
}
function isString(s) {
	return typeof s === "string" || s instanceof String;
}
function flatten(array) {
	var result = [], i, len = array && array.length;
	if(len && !isString(array)) {
		for(i = 0; i < len; i++) {
			result = result.concat(flatten(array[i]));
		}
	} else if(len !== 0) {
		result.push(array);
	}
	return result;
}
function join() {
	return flatten(slice(arguments,0)).join(" ");
}
<|endoftext|>


<commit_before>var RealityCheck = (function() {
    "use strict";
    var reality_check_url = page.url.url_for('user/reality_check');
    var reality_freq_url  = page.url.url_for('user/reality_check_frequency');
    var defaultFrequencyInMin = 60;
    var loginTime;

    function computeIntervalForNextPopup(loginTime, interval) {
        var currentTime = Date.now();
        var timeLeft = interval - ((currentTime - loginTime) % interval);
        return timeLeft;
    }

    function currentFrequencyInMS() {
        var currentInterval = LocalStore.get('reality_check.interval');
        if (!currentInterval) {
            LocalStore.set('reality_check.interval', defaultFrequencyInMin * 60 * 1000);
            return defaultFrequencyInMin * 60 * 1000;
        }
        return currentInterval;
    }

    function updateFrequency(mins) {
        if (mins > 9999) {
            $('#realityDuration').val(9999);
            var ms = 9999 * 60 * 1000;
            LocalStore.set('reality_check.interval', ms);
        } else {
            var ms = mins * 60 * 1000;
            LocalStore.set('reality_check.interval', ms);
        }
    }

    function displayPopUp(div) {
        if ($('#reality-check').length > 0) {
            return;
        }
        LocalStore.set('reality_check.close', 'false');
        var lightboxDiv = $("

");

        var wrapper = $('

');
        wrapper = wrapper.append(div);
        wrapper = $('

').append(wrapper);
        wrapper.appendTo(lightboxDiv);
        lightboxDiv.appendTo('body');

        var inputBox = lightboxDiv.find('#realityDuration');
        inputBox.val(currentFrequencyInMS() / 60 / 1000);
        inputBox.change(function(e) {
            updateFrequency(e.target.value);
        });

        lightboxDiv.find('#continue').click(function() {
            LocalStore.set('reality_check.ack', 1);
            closePopUp();
        });
        lightboxDiv.find('#btn_logout').click(function(){
            LocalStore.set('reality_check.ack', 0);
            BinarySocket.send({"logout": "1"});
        });
    }

    function closePopUp() {
        $('#reality-check').remove();
        LocalStore.set('reality_check.close', 'true');
        popUpWhenIntervalHit();         // start timer only after user click continue trading
    }

    function popUpFrequency() {
        if(LocalStore.get('reality_check.ack') === '1') {
            return;
        }

        // show pop up to get user approval
        $.ajax({
            url: reality_freq_url,
            dataType: 'html',
            method: 'POST',
            success: function(realityFreqText) {
                displayPopUp($(realityFreqText));
            },
            error: function(xhr) {
                return;
            }
        });
    }

    function popUpRealityCheck() {
        $.ajax({
            url: reality_check_url,
            dataType: 'html',
            method: 'POST',
            success: function(realityCheckText) {
                displayPopUp($(realityCheckText));
            },
            error: function(xhr) {
                return;
            }
        });
    }

    function popUpWhenIntervalHit() {
        var interval = LocalStore.get('reality_check.interval');

        window.setTimeout(function() {
            popUpRealityCheck();
        }, computeIntervalForNextPopup(loginTime, interval));
    }

    function popUpCloseHandler(ev) {
        if (ev.key === 'reality_check.close' && ev.newValue === 'true') {
            closePopUp();
        } else if (ev.key === 'reality_check.interval') {
            $('#realityDuration').val(ev.newValue / 60 / 1000);
        }
    }

    function init() {
        // to change old interpretation of reality_check
        if (LocalStore.get('reality_check.ack') > 1) {
            LocalStore.set('reality_check.ack', 0);
        }

        var rcCookie = getCookieItem('reality_check');
        loginTime = rcCookie && rcCookie.split(',')[1] * 1000;
        window.addEventListener('storage', popUpCloseHandler, false);

        popUpFrequency();
        popUpWhenIntervalHit();
    }

    return {
        init: init
    };
}());
<commit_msg>Fix maximum validation using keyup event instead of change<commit_after>var RealityCheck = (function() {
    "use strict";
    var reality_check_url = page.url.url_for('user/reality_check');
    var reality_freq_url  = page.url.url_for('user/reality_check_frequency');
    var defaultFrequencyInMin = 60;
    var loginTime;

    function computeIntervalForNextPopup(loginTime, interval) {
        var currentTime = Date.now();
        var timeLeft = interval - ((currentTime - loginTime) % interval);
        return timeLeft;
    }

    function currentFrequencyInMS() {
        var currentInterval = LocalStore.get('reality_check.interval');
        if (!currentInterval) {
            LocalStore.set('reality_check.interval', defaultFrequencyInMin * 60 * 1000);
            return defaultFrequencyInMin * 60 * 1000;
        }
        return currentInterval;
    }

    function updateFrequency(mins) {
        if (mins > 9999) {
            $('#realityDuration').val(9999);
            var ms = 9999 * 60 * 1000;
            LocalStore.set('reality_check.interval', ms);
        } else {
            var ms = mins * 60 * 1000;
            LocalStore.set('reality_check.interval', ms);
        }
    }

    function displayPopUp(div) {
        if ($('#reality-check').length > 0) {
            return;
        }
        LocalStore.set('reality_check.close', 'false');
        var lightboxDiv = $("

");

        var wrapper = $('

');
        wrapper = wrapper.append(div);
        wrapper = $('

').append(wrapper);
        wrapper.appendTo(lightboxDiv);
        lightboxDiv.appendTo('body');

        var inputBox = lightboxDiv.find('#realityDuration');
        inputBox.val(currentFrequencyInMS() / 60 / 1000);
        inputBox.keyup(function(e) {
            updateFrequency(e.target.value);
        });

        lightboxDiv.find('#continue').click(function() {
            LocalStore.set('reality_check.ack', 1);
            closePopUp();
        });
        lightboxDiv.find('#btn_logout').click(function(){
            LocalStore.set('reality_check.ack', 0);
            BinarySocket.send({"logout": "1"});
        });
    }

    function closePopUp() {
        $('#reality-check').remove();
        LocalStore.set('reality_check.close', 'true');
        popUpWhenIntervalHit();         // start timer only after user click continue trading
    }

    function popUpFrequency() {
        if(LocalStore.get('reality_check.ack') === '1') {
            return;
        }

        // show pop up to get user approval
        $.ajax({
            url: reality_freq_url,
            dataType: 'html',
            method: 'POST',
            success: function(realityFreqText) {
                displayPopUp($(realityFreqText));
            },
            error: function(xhr) {
                return;
            }
        });
    }

    function popUpRealityCheck() {
        $.ajax({
            url: reality_check_url,
            dataType: 'html',
            method: 'POST',
            success: function(realityCheckText) {
                displayPopUp($(realityCheckText));
            },
            error: function(xhr) {
                return;
            }
        });
    }

    function popUpWhenIntervalHit() {
        var interval = LocalStore.get('reality_check.interval');

        window.setTimeout(function() {
            popUpRealityCheck();
        }, computeIntervalForNextPopup(loginTime, interval));
    }

    function popUpCloseHandler(ev) {
        if (ev.key === 'reality_check.close' && ev.newValue === 'true') {
            closePopUp();
        } else if (ev.key === 'reality_check.interval') {
            $('#realityDuration').val(ev.newValue / 60 / 1000);
        }
    }

    function init() {
        // to change old interpretation of reality_check
        if (LocalStore.get('reality_check.ack') > 1) {
            LocalStore.set('reality_check.ack', 0);
        }

        var rcCookie = getCookieItem('reality_check');
        loginTime = rcCookie && rcCookie.split(',')[1] * 1000;
        window.addEventListener('storage', popUpCloseHandler, false);

        popUpFrequency();
        popUpWhenIntervalHit();
    }

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


<commit_before>vvavarvar var fvar fsvar fs var fs =var fs = var fs = rvar fs = revar fs = reqvar fs = requvar fs = requivar fs = requirvar fs = requirevar fs = require(var fs = require('var fs = require('fvar fs = require('fsvar fs = require('fs'var fs = require('fs')var fs = require('fs');var fs = require('fs');
var fs = require('fs');
vvar fs = require('fs');
vavar fs = require('fs');
varvar fs = require('fs');
var var fs = require('fs');
var cvar fs = require('fs');
var chvar fs = require('fs');
var chivar fs = require('fs');
var chilvar fs = require('fs');
var childvar fs = require('fs');
var child_var fs = require('fs');
var child_pvar fs = require('fs');
var child_prvar fs = require('fs');
var child_provar fs = require('fs');
var child_procvar fs = require('fs');
var child_procevar fs = require('fs');
var child_procesvar fs = require('fs');
var child_processvar fs = require('fs');
var child_process var fs = require('fs');
var child_process =var fs = require('fs');
var child_process = var fs = require('fs');
var child_process = rvar fs = require('fs');
var child_process = revar fs = require('fs');
var child_process = reqvar fs = require('fs');
var child_process = requvar fs = require('fs');
var child_process = requivar fs = require('fs');
var child_process = requirvar fs = require('fs');
var child_process = requirevar fs = require('fs');
var child_process = require(var fs = require('fs');
var child_process = require('var fs = require('fs');
var child_process = require('cvar fs = require('fs');
var child_process = require('chvar fs = require('fs');
var child_process = require('chivar fs = require('fs');
var child_process = require('chilvar fs = require('fs');
var child_process = require('childvar fs = require('fs');
var child_process = require('child_var fs = require('fs');
var child_process = require('child_pvar fs = require('fs');
var child_process = require('child_prvar fs = require('fs');
var child_process = require('child_provar fs = require('fs');
var child_process = require('child_procvar fs = require('fs');
var child_process = require('child_procevar fs = require('fs');
var child_process = require('child_procesvar fs = require('fs');
var child_process = require('child_processvar fs = require('fs');
var child_process = require('child_process'var fs = require('fs');
var child_process = require('child_process')var fs = require('fs');
var child_process = require('child_process')
var fs = require('fs');
var child_process = require('child_process')

var fs = require('fs');
var child_process = require('child_process')

ivar fs = require('fs');
var child_process = require('child_process')

ifvar fs = require('fs');
var child_process = require('child_process')

if var fs = require('fs');
var child_process = require('child_process')

if (var fs = require('fs');
var child_process = require('child_process')

if ( var fs = require('fs');
var child_process = require('child_process')

if ( pvar fs = require('fs');
var child_process = require('child_process')

if ( prvar fs = require('fs');
var child_process = require('child_process')

if ( provar fs = require('fs');
var child_process = require('child_process')

if ( procvar fs = require('fs');
var child_process = require('child_process')

if ( procevar fs = require('fs');
var child_process = require('child_process')

if ( procesvar fs = require('fs');
var child_process = require('child_process')

if ( processvar fs = require('fs');
var child_process = require('child_process')

if ( process.var fs = require('fs');
var child_process = require('child_process')

if ( process.avar fs = require('fs');
var child_process = require('child_process')

if ( process.arvar fs = require('fs');
var child_process = require('child_process')

if ( process.argvar fs = require('fs');
var child_process = require('child_process')

if ( process.argvvar fs = require('fs');
var child_process = require('child_process')

if ( process.argv[var fs = require('fs');
var child_process = require('child_process')

if ( process.argv[ var fs = require('fs');
var child_process = require('child_process')

if ( process.argv[ 2var fs = require('fs');
var child_process = require('child_process')

if ( process.argv[ 2 var fs = require('fs');
var child_process = require('child_process')

if ( process.argv[ 2 ]<commit_msg>Update character<commit_after>vvavarvar var fvar fsvar fs var fs =var fs = var fs = rvar fs = revar fs = reqvar fs = requvar fs = requivar fs = requirvar fs = requirevar fs = require(var fs = require('var fs = require('fvar fs = require('fsvar fs = require('fs'var fs = require('fs')var fs = require('fs');var fs = require('fs');
var fs = require('fs');
vvar fs = require('fs');
vavar fs = require('fs');
varvar fs = require('fs');
var var fs = require('fs');
var cvar fs = require('fs');
var chvar fs = require('fs');
var chivar fs = require('fs');
var chilvar fs = require('fs');
var childvar fs = require('fs');
var child_var fs = require('fs');
var child_pvar fs = require('fs');
var child_prvar fs = require('fs');
var child_provar fs = require('fs');
var child_procvar fs = require('fs');
var child_procevar fs = require('fs');
var child_procesvar fs = require('fs');
var child_processvar fs = require('fs');
var child_process var fs = require('fs');
var child_process =var fs = require('fs');
var child_process = var fs = require('fs');
var child_process = rvar fs = require('fs');
var child_process = revar fs = require('fs');
var child_process = reqvar fs = require('fs');
var child_process = requvar fs = require('fs');
var child_process = requivar fs = require('fs');
var child_process = requirvar fs = require('fs');
var child_process = requirevar fs = require('fs');
var child_process = require(var fs = require('fs');
var child_process = require('var fs = require('fs');
var child_process = require('cvar fs = require('fs');
var child_process = require('chvar fs = require('fs');
var child_process = require('chivar fs = require('fs');
var child_process = require('chilvar fs = require('fs');
var child_process = require('childvar fs = require('fs');
var child_process = require('child_var fs = require('fs');
var child_process = require('child_pvar fs = require('fs');
var child_process = require('child_prvar fs = require('fs');
var child_process = require('child_provar fs = require('fs');
var child_process = require('child_procvar fs = require('fs');
var child_process = require('child_procevar fs = require('fs');
var child_process = require('child_procesvar fs = require('fs');
var child_process = require('child_processvar fs = require('fs');
var child_process = require('child_process'var fs = require('fs');
var child_process = require('child_process')var fs = require('fs');
var child_process = require('child_process')
var fs = require('fs');
var child_process = require('child_process')

var fs = require('fs');
var child_process = require('child_process')

ivar fs = require('fs');
var child_process = require('child_process')

ifvar fs = require('fs');
var child_process = require('child_process')

if var fs = require('fs');
var child_process = require('child_process')

if (var fs = require('fs');
var child_process = require('child_process')

if ( var fs = require('fs');
var child_process = require('child_process')

if ( pvar fs = require('fs');
var child_process = require('child_process')

if ( prvar fs = require('fs');
var child_process = require('child_process')

if ( provar fs = require('fs');
var child_process = require('child_process')

if ( procvar fs = require('fs');
var child_process = require('child_process')

if ( procevar fs = require('fs');
var child_process = require('child_process')

if ( procesvar fs = require('fs');
var child_process = require('child_process')

if ( processvar fs = require('fs');
var child_process = require('child_process')

if ( process.var fs = require('fs');
var child_process = require('child_process')

if ( process.avar fs = require('fs');
var child_process = require('child_process')

if ( process.arvar fs = require('fs');
var child_process = require('child_process')

if ( process.argvar fs = require('fs');
var child_process = require('child_process')

if ( process.argvvar fs = require('fs');
var child_process = require('child_process')

if ( process.argv[var fs = require('fs');
var child_process = require('child_process')

if ( process.argv[ var fs = require('fs');
var child_process = require('child_process')

if ( process.argv[ 2var fs = require('fs');
var child_process = require('child_process')

if ( process.argv[ 2 var fs = require('fs');
var child_process = require('child_process')

if ( process.argv[ 2 ]var fs = require('fs');
var child_process = require('child_process')

if ( process.argv[ 2 ] <|endoftext|>


<commit_before>describe("create", function() {

    it("should create single DOM element if parameter is not an HTML string", function() {
        var link = DOM.create("a");

        setFixtures(link._node);

        expect(link._node).toMatchSelector("a");
    });

    it("should return DOM collection when the first argument is a HTML string", function() {
        var elements = DOM.create("

"),
            expectedSelectors = ["ul.test", "a[href]"];

        expect(elements.length).toBe(2);

        elements.forEach(function(el, index) {
            setFixtures(el._node);

            expect(el._node).toMatchSelector(expectedSelectors[index]);
        });
    });

    it("should create new DOM element if the first argument is native element", function() {
        var el = DOM.create(document.createElement("em"));

        setFixtures(el._node);

        expect(el._node).toMatchSelector("em");
    });

    it("should crete DOM collection when the first argument is a native collection", function() {
        setFixtures("12");

        var elements = DOM.create(document.getElementById("test").children),
            expectedSelectors = ["strong", "span"];

        elements.forEach(function(el, index) {
            expect(el._node).toMatchSelector(expectedSelectors[index]);
        });
    });

    it("should crete DOM collection when the first argument is an array of native elements", function() {
        setFixtures("12");

        var elements = DOM.create(Array.prototype.slice.call(document.getElementById("test").children)),
            expectedSelectors = ["strong", "span"];

        elements.forEach(function(el, index) {
            expect(el._node).toMatchSelector(expectedSelectors[index]);
        });
    });

    it("should throw error if argument is invalid", function() {
        expect(function() { DOM.create(2); }).toThrow();
    });

});<commit_msg>fix create spec<commit_after>describe("create", function() {

    it("should create single DOM element if parameter is not an HTML string", function() {
        var link = DOM.create("a");

        setFixtures(link._node);

        expect(link._node).toMatchSelector("a");
    });

    it("should return DOM collection when the first argument is a HTML string", function() {
        var elements = DOM.create("

"),
            expectedSelectors = ["ul.test", "a[href]"];

        expect(elements.length).toBe(2);

        elements.forEach(function(el, index) {
            setFixtures(el._node);

            expect(el._node).toMatchSelector(expectedSelectors[index]);
        });
    });

    it("should create new DOM element if the first argument is native element", function() {
        var el = DOM.create(document.createElement("em"));

        setFixtures(el._node);

        expect(el._node).toMatchSelector("em");
    });

    it("should throw error if argument is invalid", function() {
        expect(function() { DOM.create(2); }).toThrow();
    });

});<|endoftext|>


<commit_before>angular.module('homepage', [])

  .config(function($provide, $locationProvider) {
    var pulseElements = $(),
        pulseColor = {r:0xE6, g:0xF0, b: 0xFF},
        baseColor = {r:0x99, g:0xc2, b: 0xFF},
        pulseDuration = 1000,
        pulseDelay = 15000;

    function hex(number) {
      return ('0' + Number(number).toString(16)).slice(-2);
    }

    jQuery.fn.pulse = function () {
      pulseElements = pulseElements.add(this);
    };
    var lastPulse;

    function tick() {
      var duration = new Date().getTime() - lastPulse,
          index = duration * Math.PI / pulseDuration ,
          level = Math.pow(Math.sin(index), 10),
          color = {
            r: Math.round(pulseColor.r * level + baseColor.r * (1 - level)),
            g: Math.round(pulseColor.g * level + baseColor.g * (1 - level)),
            b: Math.round(pulseColor.b * level + baseColor.b * (1 - level))
          },
          style = '#' + hex(color.r) + hex(color.g) + hex(color.b);

      pulseElements.css('backgroundColor', style);
      if (duration > pulseDuration) {
        setTimeout(function() {
          lastPulse = new Date().getTime();
          tick();
        }, pulseDelay);
      } else {
        setTimeout(tick, 50);
      }
    }

    $provide.value('startPulse', function() {
       setTimeout(function() {
         lastPulse = new Date().getTime();
         tick();
       }, 2000);
    });

    $locationProvider.html5Mode(true);
    $locationProvider.hashPrefix('!');
  })

  .value('indent', function(text, spaces) {
    if (!text) return text;
    var lines = text.split(/\r?\n/);
    var prefix = '      '.substr(0, spaces || 0);
    var i;

    // remove any leading blank lines
    while (lines.length && lines[0].match(/^\s*$/)) lines.shift();
    // remove any trailing blank lines
    while (lines.length && lines[lines.length - 1].match(/^\s*$/)) lines.pop();
    var minIndent = 999;
    for (i = 0; i < lines.length; i++) {
      var line = lines[0];
      var indent = line.match(/^\s*/)[0];
      if (indent !== line && indent.length < minIndent) {
        minIndent = indent.length;
      }
    }

    for (i = 0; i < lines.length; i++) {
      lines[i] = prefix + lines[i].substring(minIndent);
    }
    lines.push('');
    return lines.join('\n');
  })

  .value('escape', function(text) {
    return text.replace(/\&/g, '&').replace(/\</g, '<').replace(/\>/g, '>').replace(/"/g, '"');
  })

  .factory('script', function() {

    return {
      googlemaps: '\n',
      angular: '\n',
      resource: '\n',
      angulargm: '\n',
      firebase: '\n    \n',
    };
  })

  .factory('fetchCode', function(indent) {
    return function get(id, spaces) {
      return indent(angular.element(document.getElementById(id)).html(), spaces);
    }
  })

  .directive('code', function() {
    return {restrict: 'E', terminal: true};
  })

  .directive('appRun', function(fetchCode, $templateCache, $browser) {
    return {
      terminal: true,
      link: function(scope, element, attrs) {
        var modules = [];

        modules.push(function($provide, $locationProvider) {
          $provide.value('$templateCache', {
            get: function(key) {
              var value = $templateCache.get(key);
              if (value) {
                value = value.replace(/\#\//mg, '/');
              }
              return value;
            }
          });
          $provide.value('$anchorScroll', angular.noop);
          $provide.value('$browser', $browser);
          $locationProvider.html5Mode(true);
          $locationProvider.hashPrefix('!');
        });
        if (attrs.module) {
          modules.push(attrs.module);
        }

        element.html(fetchCode(attrs.appRun));
        element.bind('click', function(event) {
          if (event.target.attributes.getNamedItem('ng-click')) {
            event.preventDefault();
          }
        });
        element.data('$injector', null);
        angular.bootstrap(element, modules);
      }
    };
  })

  .directive('appSource', function(fetchCode, escape, script) {
    return {
      terminal: true,
      link: function(scope, element, attrs) {
        var tabs = [],
            panes = [],
            annotation = attrs.annotate && angular.fromJson(fetchCode(attrs.annotate)) || {},
            TEMPLATE = {
              'index.html':
                '<!doctype html>\n' +
                '\n' +
                '  \n' +
                /*
                '  \n' +
                '    ' + script.googlemaps +
                '    ' + script.angular.replace('></', '>\n    </') +
                '    ' + script.angulargm.replace('></', '>\n    </') +
               (attrs.resource ? ('    ' + script.resource.replace('></', '>\n    </')) : '') +
               (attrs.firebase ? ('    ' + script.firebase) : '') +
                '__HEAD__' +
                '  \n' +
                */
                '  \n' +
                '__BODY__' +
                '  \n' +
                ''
          };

    element.css('clear', 'both');

        angular.forEach(attrs.appSource.split(' '), function(filename, index) {
          var content;

          tabs.push(
            '
' +
              '' + (index ? filename : 'index.html') + '' +
            '
');

          if (index == 0) {
            var head = [];

            angular.forEach(attrs.appSource.split(' '), function(tab, index) {
              var filename = tab.split(':')[0],
                  fileType = filename.split(/\./)[1];

              if (index == 0) return;
              if (fileType == 'js') {
                head.push('    \n');
              } else if (fileType == 'css') {
                head.push('    <link rel="stylesheet" href="' + filename + '">\n');
              }
            });
            content = TEMPLATE['index.html'];
            content = content.
              replace('__MODULE__', attrs.module ? '="' + attrs.module + '"' : '').
              replace('__HEAD__', head.join('')).
              replace('__BODY__', fetchCode(filename, 4));
          } else {
            content = fetchCode(filename);
          }

          // hack around incorrect tokenization
          content = content.replace('.done-true', 'doneTrue');
          content = prettyPrintOne(escape(content), undefined, true);
          // hack around incorrect tokenization
          content = content.replace('doneTrue', '.done-true');

          var popovers = {},
              counter = 0;

          angular.forEach(annotation[filename], function(text, key) {
            var regexp = new RegExp('(\\W|^)(' + key.replace(/([\W\-])/g, '\\$1') + ')(\\W|$)');

            content = content.replace(regexp, function(_, before, token, after) {
              var token = "__" + (counter++) + "__";
              popovers[token] =
                '<code class="nocode" rel="popover" title="' + escape('' + key + '') +
                '" data-content="' + escape(text) + '">' + escape(key) + '';
              return before + token + after;
            });
          });

          angular.forEach(popovers, function(text, token) {
            content = content.replace(token, text);
          });

          panes.push(
            '
' +
              '
' + content +'
' +
            '
');
        });

        element.html(
          '
' +
            '
' +
            tabs.join('') +
            '
' +
            '
' +
            panes.join('') +
            '
' +
            '
');
        // element.find('[rel=popover]').popover().pulse();

        function id(id) {
          return id.replace(/\W/g, '-');
        }
      }
    }
  })

  .directive('jsFiddle', function(fetchCode, escape, script) {
    return {
      terminal: true,
      link: function(scope, element, attr) {
        var name = '',
            stylesheet = '<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css">\n',
            fields = {
              html: '',
              css: '',
              js: ''
            };

        angular.forEach(attr.jsFiddle.split(' '), function(file, index) {
          var fileType = file.split('.')[1];

          if (fileType == 'html') {
            if (index == 0) {
              fields[fileType] +=
                  '
\n' +
                    fetchCode(file, 2);
            } else {
              fields[fileType] += '\n\n\n  \n' +
                  '  \n';
            }
          } else {
            fields[fileType] += fetchCode(file) + '\n';
          }
        });

        fields.html += '
\n';

        element.html(
          '<form class="jsfiddle" method="post" action="http://jsfiddle.net/api/post/library/pure/" target="_blank">' +
            hiddenField('title', 'AngularJS Example: ' + name) +
            hiddenField('css', '</style>  \n' +
               stylesheet +
               script.googlemaps +
               script.angular +
               script.angulargm +
               (attr.resource ? script.resource : '') +
               '  \n' +
               stylesheet +
               script.googlemaps +
               script.angular +
               script.angulargm +
               (attr.resource ? script.resource : '') +
               '


<commit_before>'use strict';

for (let i=1; i<101; i++) {
	if (i%3 === 0 && i%5 === 0) {
		console.log('FizzBuzz');
	} else if (i%3 === 0) {
		console.log('Fizz');
	} else if (i%5 === 0) {
		console.log('Buzz');
	} else {
		console.log(i);
	}
}
<commit_msg>A simpler fizbuzz implementation<commit_after>'use strict';

for (let i = 1; i <= 100; i++) {
	let output = '';
	if (i % 3 === 0) {
		output += 'Fizz';
	}
	if (i % 5 === 0) {
		output += 'Buzz';
	}
	console.log(output || i);
}
<|endoftext|>


<commit_before>import {expect} from 'chai'

import {
  initialize as initializeSvgUse
} from 'ember-frost-core/instance-initializers/svg-use-polyfill'

import {$hook, initialize as initializeHook} from 'ember-hook'
import {describeComponent, it} from 'ember-mocha'
import hbs from 'htmlbars-inline-precompile'
import {beforeEach, describe} from 'mocha'
import sinon from 'sinon'

import {expectModalWithState} from 'dummy/tests/helpers/ember-frost-modal'

describeComponent(
  'frost-modal-confirm-message',
  'Integration: FrostModalConfirmMessageComponent',
  {
    integration: true
  },
  function () {
    beforeEach(function () {
      initializeHook()
      initializeSvgUse()
    })

    describe('render visible confirm modal', function () {
      let props

      beforeEach(function () {
        this.timeout(10000)

        this.set('closeModal', () => {
          this.set('isModalVisible', false)
        })

        props = {
          hook: 'confirm-dialog',
          isModalVisible: true,
          onConfirm: sinon.spy()
        }

        this.setProperties(props)

        this.render(hbs`
          {{frost-modal-outlet}}

          {{frost-modal-confirm-message
          hook=hook
          cancel=(hash
            isVisible=false
          )
          confirm=(hash
            text='100%'
          )
          isVisible=isModalVisible
          summary='I agree'
          title='Most definitely'
          onConfirm=onConfirm
          onClose=(action closeModal)
        }}`)
      })

      it('renders visually as expected', function (done) {
        return capture('confirm', done, {
          targetElement: this.$('.frost-modal-outlet-container.message')[0],
          experimentalSvgs: true
        })
      })

      it('confirm triggers the callback and closes', function () {
        expectModalWithState({
          cancel: {
            visible: false
          },
          confirm: {
            text: '100%'
          },
          summary: 'I agree',
          title: 'Most definitely'
        })
      })

      describe('press confirm button', function () {
        beforeEach(function () {
          $hook('confirm-dialog-modal-confirm').click()
        })

        it('triggers the callback', function () {
          expect(props.onConfirm.called).to.equal(true)
        })

        it('closes', function () {
          expect($hook('confirm-dialog-modal')).to.have.length(0)
        })
      })
    })
  }
)
<commit_msg>Fix test description<commit_after>import {expect} from 'chai'

import {
  initialize as initializeSvgUse
} from 'ember-frost-core/instance-initializers/svg-use-polyfill'

import {$hook, initialize as initializeHook} from 'ember-hook'
import {describeComponent, it} from 'ember-mocha'
import hbs from 'htmlbars-inline-precompile'
import {beforeEach, describe} from 'mocha'
import sinon from 'sinon'

import {expectModalWithState} from 'dummy/tests/helpers/ember-frost-modal'

describeComponent(
  'frost-modal-confirm-message',
  'Integration: FrostModalConfirmMessageComponent',
  {
    integration: true
  },
  function () {
    beforeEach(function () {
      initializeHook()
      initializeSvgUse()
    })

    describe('render visible confirm modal', function () {
      let props

      beforeEach(function () {
        this.timeout(10000)

        this.set('closeModal', () => {
          this.set('isModalVisible', false)
        })

        props = {
          hook: 'confirm-dialog',
          isModalVisible: true,
          onConfirm: sinon.spy()
        }

        this.setProperties(props)

        this.render(hbs`
          {{frost-modal-outlet}}

          {{frost-modal-confirm-message
          hook=hook
          cancel=(hash
            isVisible=false
          )
          confirm=(hash
            text='100%'
          )
          isVisible=isModalVisible
          summary='I agree'
          title='Most definitely'
          onConfirm=onConfirm
          onClose=(action closeModal)
        }}`)
      })

      it('renders visually as expected', function (done) {
        return capture('confirm', done, {
          targetElement: this.$('.frost-modal-outlet-container.message')[0],
          experimentalSvgs: true
        })
      })

      it('renders as expected', function () {
        expectModalWithState({
          cancel: {
            visible: false
          },
          confirm: {
            text: '100%'
          },
          summary: 'I agree',
          title: 'Most definitely'
        })
      })

      describe('press confirm button', function () {
        beforeEach(function () {
          $hook('confirm-dialog-modal-confirm').click()
        })

        it('triggers the callback', function () {
          expect(props.onConfirm.called).to.equal(true)
        })

        it('closes', function () {
          expect($hook('confirm-dialog-modal')).to.have.length(0)
        })
      })
    })
  }
)
<|endoftext|>


<commit_before>(function($) {

    /**
     * .slideshow
     *
     * Begins the slideshow by choosing the type of slide and duration
     *
     * type        Type of slideshow to run; Defaults to 'fade'
     * duration    Time in miliseconds that each element is visible; Defaults to
     *                 5000
     */
    $.fn.slideshow = function(type, duration) {
        type = typeof type !== 'undefined' ? type : 'fade';
        duration = typeof duration !== 'undefined' ? duration : 5000;
        var $container = this;

        var count =0;

        switch(type) {
            case 'fade':
                this.children().hide().fadeOut();
                this.children(":first").addClass('active').show();

                var intervalID = setInterval(function() {
                    $container.slideshowFade(intervalID);
                }, duration);
                break;
            case 'fade-into':
                this.initializeFadeInto();

                var intervalID = setInterval(function() {
                    count = $container.slideshowFadeInto(intervalID, count);
                }, duration);
                break;
        };
    };

    $.fn.slideshowFadeInto = function (intervalID, count, fadeSpeed) {
        /* if(count == 6) clearInterval(intervalID); */
        /* if(count !== 0 && count%7 == 0 ) this.reset(); */

        fadeSpeed = typeof fadeSpeed !== 'undefined' ? fadeSpeed : 'slow';
        var $swap = this.swap();
        var $container = this;

        $swap["active"].fadeOut(fadeSpeed, function() {
                $swap["active"].hide(function() {
                   $swap["next"].addClass('active');
                   var nextZ = $container.nextZ();
                   $swap["active"].css({'z-index':nextZ}).show();
                });
            })

        return count+1;

    };

    $.fn.swap = function () {
        var $active = this.children(".active").toggleClass('active');
        if($active.length == 0)
            $active = this.children(":last");
        var $next = $active.next().length ? $active.next()
            : this.children(":first");

        return {"active":$active,"next":$next};
    }

    $.fn.initializeFadeInto = function(start) {
        start = typeof start !== 'undefined' ? start : 999

        // Adds #active to first element in 'this'
        this.children(":first").addClass('active');

        /* Iterates through all children of 'this'
         *     sets initiale z-index (start - order in 'this')
         *     sets position: absolute
         *     shows child
         */
        for(var i=1; i<=this.children().length; i=i+1) {
            this.find(":nth-child("+i+")")
            .css({
                'z-index':start-i,
                'position':'absolute'
            })
            .show();
        }
    }

    $.fn.nextZ = function(){
        var nextZ = 999;
        var length = this.children().length;
        for(var count=1; count<=length; count = count +1) {
            if(nextZ>this.find(":nth-child("+count+")").css("z-index"))
                nextZ = this.find(":nth-child("+count+")").css("z-index");
        }
        return nextZ-1;
    }

    $.fn.slideshowFade = function (fadeSpeed) {
        fadeSpeed = typeof fadeSpeed !== 'undefined' ? fadeSpeed : 'slow';
        var $swap = this.swap();

        $swap["active"].fadeOut(fadeSpeed, function () {
                $swap["active"].hide(function () {
                    $swap["next"].addClass('active')
                        .fadeIn(fadeSpeed);
                });
            });

    };

}) (jQuery);
<commit_msg>Sets position:absolute in initFadeInto() instead of the css<commit_after>(function($) {

    /**
     * .slideshow
     *
     * Begins the slideshow by choosing the type of slide and duration
     *
     * type        Type of slideshow to run; Defaults to 'fade'
     * duration    Time in miliseconds that each element is visible; Defaults to
     *                 5000
     */
    $.fn.slideshow = function(type, duration) {
        type = typeof type !== 'undefined' ? type : 'fade';
        duration = typeof duration !== 'undefined' ? duration : 5000;
        var $container = this;

        var count =0;

        switch(type) {
            case 'fade':
                this.children().hide().fadeOut();
                this.children(":first").addClass('active').show();

                var intervalID = setInterval(function() {
                    $container.slideshowFade(intervalID);
                }, duration);
                break;
            case 'fade-into':
                this.initFadeInto();

                var intervalID = setInterval(function() {
                    count = $container.slideshowFadeInto(intervalID, count);
                }, duration);
                break;
        };
    };

    $.fn.slideshowFadeInto = function (intervalID, count, fadeSpeed) {
        /* if(count == 6) clearInterval(intervalID); */
        /* if(count !== 0 && count%7 == 0 ) this.reset(); */

        fadeSpeed = typeof fadeSpeed !== 'undefined' ? fadeSpeed : 'slow';
        var $swap = this.swap();
        var $container = this;

        $swap["active"].fadeOut(fadeSpeed, function() {
                $swap["active"].hide(function() {
                   $swap["next"].addClass('active');
                   var nextZ = $container.nextZ();
                   $swap["active"].css({'z-index':nextZ}).show();
                });
            })

        return count+1;

    };

    $.fn.swap = function () {
        var $active = this.children(".active").toggleClass('active');
        if($active.length == 0)
            $active = this.children(":last");
        var $next = $active.next().length ? $active.next()
            : this.children(":first");

        return {"active":$active,"next":$next};
    }

    $.fn.initFadeInto = function(start) {
        start = typeof start !== 'undefined' ? start : 999

        // Adds #active to first element in 'this'
        this.children(":first").addClass('active');

        /* Iterates through all children of 'this'
         *     sets initiale z-index (start - order in 'this')
         *     sets position: absolute
         *     shows child
         */
        for(var i=1; i<=this.children().length; i=i+1) {
            this.find(":nth-child("+i+")")
            .css({
                'z-index':start-i,
                'position':'absolute'
            })
            .show();
        }
    }

    $.fn.nextZ = function(){
        var nextZ = 999;
        var length = this.children().length;
        for(var count=1; count<=length; count = count +1) {
            if(nextZ>this.find(":nth-child("+count+")").css("z-index"))
                nextZ = this.find(":nth-child("+count+")").css("z-index");
        }
        return nextZ-1;
    }

    $.fn.slideshowFade = function (fadeSpeed) {
        fadeSpeed = typeof fadeSpeed !== 'undefined' ? fadeSpeed : 'slow';
        var $swap = this.swap();

        $swap["active"].fadeOut(fadeSpeed, function () {
                $swap["active"].hide(function () {
                    $swap["next"].addClass('active')
                        .fadeIn(fadeSpeed);
                });
            });

    };

}) (jQuery);
<|endoftext|>


<commit_before>import React from 'react';

import { Query } from 'react-apollo';
import { GraphQLError } from './../Error/GraphQLError';

import ListTable from '../ListTable/ListTable';
import LinkButton from './../../Components/FormInput/LinkButton';
import AddIcon from '@material-ui/icons/Add';

class ListContainer extends React.Component {
  render() {
    return (
      <Query
        query={this.props.repository.getListPage()}
        variables={{ 'first': this.props.rowsPerPage, 'offset': this.props.page * this.props.rowsPerPage, 'orderBy': this.props.sortColumn }}
        fetchPolicy={this.props.refetch ? 'cache-and-network' : 'cache-first'}
      >
        {({ loading, error, data }) => {
          if (loading && data !== null) {
            return
Loading...
;
          }
          if (error) {
            return <GraphQLError error={error} />;
          }
          this.props.setRowTotal(data[this.props.dataObjectName].totalCount);
          return (

                {this.props.tableHeader}

                <LinkButton label=<AddIcon /> type="create" color="secondary" variant="fab" to={this.props.newLink}/>

              <ListTable
                data={data[this.props.dataObjectName].nodes}
                buttons={this.props.buttons}
                {...this.props}
              />

          );
        }}
      </Query>
    );
  }
}

export default ListContainer;
<commit_msg>Fixed <Loading> view flicker when sorting the data.<commit_after>import React from 'react';

import { Query } from 'react-apollo';
import { GraphQLError } from './../Error/GraphQLError';

import ListTable from '../ListTable/ListTable';
import LinkButton from './../../Components/FormInput/LinkButton';
import AddIcon from '@material-ui/icons/Add';

class ListContainer extends React.Component {
  renderForm(data) {
    this.props.setRowTotal(data[this.props.dataObjectName].totalCount);
    return

        {this.props.tableHeader}

        <LinkButton label=<AddIcon /> type="create" color="secondary" variant="fab" to={this.props.newLink}/>

      <ListTable
        data={data[this.props.dataObjectName].nodes}
        buttons={this.props.buttons}
        {...this.props}
      />

;
  }

  render() {
    return (
      <Query
        query={this.props.repository.getListPage()}
        variables={{ 'first': this.props.rowsPerPage, 'offset': this.props.page * this.props.rowsPerPage, 'orderBy': this.props.sortColumn }}
        fetchPolicy={this.props.refetch ? 'cache-and-network' : 'cache-first'}
      >
        {({ loading, error, data }) => {
          if (loading) {
            //check if we already have data object so we would not remove the old data before we get the new one.
            if (Object.keys(data).length) {
              return this.renderForm(data);
            }
            return
Loading...
;
          }
          if (error) {
            return <GraphQLError error={error} />;
          }
          return this.renderForm(data);
        }}
      </Query>
    );
  }
}

export default ListContainer;
<|endoftext|>