<commit_before>(function displayStageTests() {
  var Stage = flash.display.Stage;
  var DisplayObject = flash.display.DisplayObject;
  var DisplayObjectContainer = flash.display.DisplayObjectContainer;

  function createDisplayObjectTree(depth, width, height) {
    var nodes = [];
    Shumway.Random.seed(0x12343);
    function make(parent, count, depth) {
      if (depth > 0) {
        for (var i = 0; i < count; i++) {
          var o = new DisplayObjectContainer();
          nodes.push(o);
          parent.addChild(o);
          make(o, count, depth - 1);
        }
      } else {
        parent.addChild(new DisplayObject());
      }
    }
    var container = new Stage();
    make(container, 2, depth);
    return {
      node: container,
      nodes: nodes,
      getRandomNode: function () {
        return this.nodes[(Math.random() * (this.nodes.length - 1)) | 0];
      }
    };
  }

  unitTests.push(function checkDefaults() {
    var stage = new Stage();
    eq(stage.root, stage, "root");
    check(stage.scaleMode === "showAll", "scaleMode");
    eq(stage.stage, stage, "stage");
    check(stage.tabIndex === -1, "tabIndex");
    eq(stage.mouseEnabled, true, "mouseEnabled");
    eq(stage.focusRect, null, "focusRect");
    eq(stage.mask, null, "mask");
    eq(stage.tabEnabled, false, "tabEnabled");
    eq(stage.visible, true, "visible");
    eq(stage.doubleClickEnabled, false, "doubleClickEnabled");
    eq(stage.scaleZ, 1, "scaleZ");
    eq(stage.accessibilityImplementation, null, "accessibilityImplementation");
    eq(stage.softKeyboardInputAreaOfInterest, null, "softKeyboardInputAreaOfInterest");
    eq(stage.rotation, 0, "rotation");
    eq(stage.needsSoftKeyboard, false, "needsSoftKeyboard");
    eq(stage.rotationX, 0, "rotationX");
    eq(stage.scaleX, 1, "scaleX");
    eq(stage.scaleY, 1, "scaleY");
    eq(stage.rotationZ, 0, "rotationZ");
    eq(stage.rotationY, 0, "rotationY");
    eq(stage.cacheAsBitmap, false, "cacheAsBitmap");
    eq(stage.opaqueBackground, null, "opaqueBackground");
    eq(stage.scrollRect, null, "scrollRect");
    eq(stage.contextMenu, null, "contextMenu");
    check(stage.blendMode === "normal", "blendMode");
    check(stage.transform, "transform");
    eq(stage.frameRate, 24, "frameRate");
    //check(o.numChildren === 1, "numChildren");
    eq(stage.scale9Grid, null, "scale9Grid");
    //check(o.constructor === null, "constructor");
    //check(o.stageWidth === 550, "stageWidth");
    eq(stage.color, 4294967295, "color");
    eq(stage.tabChildren, true, "tabChildren");
    //check(o.quality === "HIGH", "quality");
    eq(stage.mouseChildren, true, "mouseChildren");
    //check(o.loaderInfo, "loaderInfo");
    eq(stage.focus, null, "focus");
    check(stage.colorCorrection === "default", "colorCorrection");
    eq(stage.height, 0, "height");
    //check(o.name === null, "name");
    check(stage.colorCorrectionSupport === "defaultOff", "colorCorrectionSupport");
    eq(stage.showDefaultContextMenu, true, "showDefaultContextMenu");
    eq(stage.width, 0, "width");
    //check(o.accessibilityProperties === null, "accessibilityProperties");
    check(stage.align === "", "align");
    eq(stage.displayState, null, "displayState");
    eq(stage.fullScreenSourceRect, null, "fullScreenSourceRect");
    eq(stage.mouseLock, false, "mouseLock");
    eq(stage.stageFocusRect, true, "stageFocusRect");
    eq(stage.fullScreenWidth, 0, "fullScreenWidth");
    eq(stage.z, 0, "z");
    eq(stage.fullScreenHeight, 0, "fullScreenHeight");
    eq(stage.x, 0, "x");
    check(stage.softKeyboardRect, "softKeyboardRect");
    eq(stage.wmodeGPU, false, "wmodeGPU");
    eq(stage.allowsFullScreen, false, "allowsFullScreen");
    eq(stage.allowsFullScreenInteractive, false, "allowsFullScreenInteractive");
    eq(stage.contentsScaleFactor, 1, "contentsScaleFactor");
    eq(stage.alpha, 1, "alpha");
    //check(o.metaData === null, "metaData");
    eq(stage.y, 0, "y");
    eq(stage.displayContextInfo, null, "displayContextInfo");
    eq(stage.parent, null, "parent");
  });

  unitTests.push(function stagePropertySetup() {
    var s = new Stage();
    eq(s.stage, s, 'stage correctly assigns its `stage` property');
  });

  unitTests.push(function displayListStateConsistency() {
    var tree = createDisplayObjectTree(10, 1024, 1024);
    for (var i = 0; i < 1024; i++) {
      var element = tree.getRandomNode();
      if (DisplayObjectContainer.isType(element)) {
        var otherElement = tree.getRandomNode();
        if (!otherElement._isAncestor(element)) {
          element.addChild(otherElement);
        }
      }
      var stage = element.stage;
      var root = element.root;
      check(stage);
      eq(stage, stage.stage);
      check(root);
      eq(root, root.root);
    }
  });

})();
<commit_msg>Stage.align setter test.<commit_after>(function displayStageTests() {
  var Stage = flash.display.Stage;
  var DisplayObject = flash.display.DisplayObject;
  var DisplayObjectContainer = flash.display.DisplayObjectContainer;

  function createDisplayObjectTree(depth, width, height) {
    var nodes = [];
    Shumway.Random.seed(0x12343);
    function make(parent, count, depth) {
      if (depth > 0) {
        for (var i = 0; i < count; i++) {
          var o = new DisplayObjectContainer();
          nodes.push(o);
          parent.addChild(o);
          make(o, count, depth - 1);
        }
      } else {
        parent.addChild(new DisplayObject());
      }
    }
    var container = new Stage();
    make(container, 2, depth);
    return {
      node: container,
      nodes: nodes,
      getRandomNode: function () {
        return this.nodes[(Math.random() * (this.nodes.length - 1)) | 0];
      }
    };
  }

  unitTests.push(function checkDefaults() {
    var stage = new Stage();
    eq(stage.root, stage, "root");
    check(stage.scaleMode === "showAll", "scaleMode");
    eq(stage.stage, stage, "stage");
    check(stage.tabIndex === -1, "tabIndex");
    eq(stage.mouseEnabled, true, "mouseEnabled");
    eq(stage.focusRect, null, "focusRect");
    eq(stage.mask, null, "mask");
    eq(stage.tabEnabled, false, "tabEnabled");
    eq(stage.visible, true, "visible");
    eq(stage.doubleClickEnabled, false, "doubleClickEnabled");
    eq(stage.scaleZ, 1, "scaleZ");
    eq(stage.accessibilityImplementation, null, "accessibilityImplementation");
    eq(stage.softKeyboardInputAreaOfInterest, null, "softKeyboardInputAreaOfInterest");
    eq(stage.rotation, 0, "rotation");
    eq(stage.needsSoftKeyboard, false, "needsSoftKeyboard");
    eq(stage.rotationX, 0, "rotationX");
    eq(stage.scaleX, 1, "scaleX");
    eq(stage.scaleY, 1, "scaleY");
    eq(stage.rotationZ, 0, "rotationZ");
    eq(stage.rotationY, 0, "rotationY");
    eq(stage.cacheAsBitmap, false, "cacheAsBitmap");
    eq(stage.opaqueBackground, null, "opaqueBackground");
    eq(stage.scrollRect, null, "scrollRect");
    eq(stage.contextMenu, null, "contextMenu");
    check(stage.blendMode === "normal", "blendMode");
    check(stage.transform, "transform");
    eq(stage.frameRate, 24, "frameRate");
    //check(o.numChildren === 1, "numChildren");
    eq(stage.scale9Grid, null, "scale9Grid");
    //check(o.constructor === null, "constructor");
    //check(o.stageWidth === 550, "stageWidth");
    eq(stage.color, 4294967295, "color");
    eq(stage.tabChildren, true, "tabChildren");
    //check(o.quality === "HIGH", "quality");
    eq(stage.mouseChildren, true, "mouseChildren");
    //check(o.loaderInfo, "loaderInfo");
    eq(stage.focus, null, "focus");
    check(stage.colorCorrection === "default", "colorCorrection");
    eq(stage.height, 0, "height");
    //check(o.name === null, "name");
    check(stage.colorCorrectionSupport === "defaultOff", "colorCorrectionSupport");
    eq(stage.showDefaultContextMenu, true, "showDefaultContextMenu");
    eq(stage.width, 0, "width");
    //check(o.accessibilityProperties === null, "accessibilityProperties");
    check(stage.align === "", "align");
    eq(stage.displayState, null, "displayState");
    eq(stage.fullScreenSourceRect, null, "fullScreenSourceRect");
    eq(stage.mouseLock, false, "mouseLock");
    eq(stage.stageFocusRect, true, "stageFocusRect");
    eq(stage.fullScreenWidth, 0, "fullScreenWidth");
    eq(stage.z, 0, "z");
    eq(stage.fullScreenHeight, 0, "fullScreenHeight");
    eq(stage.x, 0, "x");
    check(stage.softKeyboardRect, "softKeyboardRect");
    eq(stage.wmodeGPU, false, "wmodeGPU");
    eq(stage.allowsFullScreen, false, "allowsFullScreen");
    eq(stage.allowsFullScreenInteractive, false, "allowsFullScreenInteractive");
    eq(stage.contentsScaleFactor, 1, "contentsScaleFactor");
    eq(stage.alpha, 1, "alpha");
    //check(o.metaData === null, "metaData");
    eq(stage.y, 0, "y");
    eq(stage.displayContextInfo, null, "displayContextInfo");
    eq(stage.parent, null, "parent");
  });

  unitTests.push(function stagePropertySetup() {
    var s = new Stage();
    eq(s.stage, s, 'stage correctly assigns its `stage` property');
  });

  unitTests.push(function displayListStateConsistency() {
    var tree = createDisplayObjectTree(10, 1024, 1024);
    for (var i = 0; i < 1024; i++) {
      var element = tree.getRandomNode();
      if (DisplayObjectContainer.isType(element)) {
        var otherElement = tree.getRandomNode();
        if (!otherElement._isAncestor(element)) {
          element.addChild(otherElement);
        }
      }
      var stage = element.stage;
      var root = element.root;
      check(stage);
      eq(stage, stage.stage);
      check(root);
      eq(root, root.root);
    }
  });

  unitTests.push(function align() {
    var s = new Stage();
    s.align = "1";
    eq(s.align, "");
    s.align = "TOP";
    eq(s.align, "T");
    s.align = "T";
    eq(s.align, "T");
    s.align = "B";
    eq(s.align, "B");
    s.align = "R";
    eq(s.align, "R");
    s.align = "L";
    eq(s.align, "L");
    s.align = "?";
    eq(s.align, "");
    s.align = "BOTTOM";
    eq(s.align, "TB");
    s.align = "12310B_TOP_RRRR";
    eq(s.align, "TBR");
  });

})();
<|endoftext|>


<commit_before>/*jslint node: true, indent: 4, maxlen: 80 */
"use strict";

/**
 * ENVy
 *
 * Handle your project environment properties from a simple .json file.
 * Determine multiple environments and inherit properties between them.
 */
var path = require("path"),
    envy = exports,

    /**
     * Checks for Object instances.
     */
    isObject = function (object) {
        return Object.prototype.toString.call(object) === "[object Object]";
    },

    /**
     * Deep copies the properties of the source object into the destination
     * object.
     */
    deepCopy = function (destination, source) {
        Object.keys(source).forEach(function (property) {
            if (destination[property] && isObject(destination[property])) {
                deepCopy(destination[property], source[property]);
            } else {
                destination[property] = source[property];
            }
        });
    };

/**
 * Loads the configuration .json file with the provided filename and returns an
 * object with the environment properties.
 * If no filename is providen then ./config.json will be loaded.
 */
envy.load = function (filename) {

    // filenames are relative to the execution path
    var configFile = require(path.join(process.cwd(), filename || "config")),
        config = configFile[configFile.environment];

    // Overwrite default configuration if the NODE_ENV environment variable is
    // defined
    if (process.env.NODE_ENV && configFile[process.env.NODE_ENV]) {
        deepCopy(config, configFile[process.env.NODE_ENV]);
    }

    return config;

};

/**
 * DEPRECATED
 *
 * envy.config can be replaced with envy.load(). Therefore it will
 * be deleted.
 */
// Load the default configuration file if it exists
try {
    envy.config = envy.load();
} catch (e) {
    // Ignore failure when loading default configuration file
}
<commit_msg>added message to warn users that continue to use the deprecated method<commit_after>/*jslint node: true, indent: 4, maxlen: 80 */
"use strict";

/**
 * ENVy
 *
 * Handle your project environment properties from a simple .json file.
 * Determine multiple environments and inherit properties between them.
 */
var path = require("path"),
    envy = exports,

    /**
     * Checks for Object instances.
     */
    isObject = function (object) {
        return Object.prototype.toString.call(object) === "[object Object]";
    },

    /**
     * Deep copies the properties of the source object into the destination
     * object.
     */
    deepCopy = function (destination, source) {
        Object.keys(source).forEach(function (property) {
            if (destination[property] && isObject(destination[property])) {
                deepCopy(destination[property], source[property]);
            } else {
                destination[property] = source[property];
            }
        });
    };

/**
 * Loads the configuration .json file with the provided filename and returns an
 * object with the environment properties.
 * If no filename is providen then ./config.json will be loaded.
 */
envy.load = function (filename) {

    // filenames are relative to the execution path
    var configFile = require(path.join(process.cwd(), filename || "config")),
        config = configFile[configFile.environment];

    // Overwrite default configuration if the NODE_ENV environment variable is
    // defined
    if (process.env.NODE_ENV && configFile[process.env.NODE_ENV]) {
        deepCopy(config, configFile[process.env.NODE_ENV]);
    }

    return config;

};

/**
 * DEPRECATED
 *
 * envy.config can be replaced with envy.load(). Therefore it will
 * be deleted.
 */
// Load the default configuration file if it exists
try {
    console.log("'envy.config' is deprecated, please use 'envy.load()'");
    envy.config = envy.load();
} catch (e) {
    // Ignore failure when loading default configuration file
}
<|endoftext|>


<commit_before>/*
 * slush-protosite
 * https://bitbucket.org/mrkp/slush-protosite
 *
 * Copyright (c) 2014, Alfonso Gómez-Arzola
 * Licensed under the MIT license.
 */

'use strict';

var gulp = require('gulp'),
    install = require('gulp-install'),
    conflict = require('gulp-conflict'),
    template = require('gulp-template'),
    rename = require('gulp-rename'),
    _ = require('underscore.string'),
    inquirer = require('inquirer');

function format(string) {
    var username = string.toLowerCase();
    return username.replace(/\s/g, '');
}

var defaults = (function () {
    var homeDir = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE,
        workingDirName = process.cwd().split('/').pop().split('\\').pop(),
        osUserName = homeDir && homeDir.split('/').pop() || 'root',
        configFile = homeDir + '/.gitconfig',
        user = {};
    if (require('fs').existsSync(configFile)) {
        user = require('iniparser').parseSync(configFile).user;
    }
    return {
        appName: workingDirName,
        userName: format(user.name) || osUserName,
        authorEmail: user.email || ''
    };
})();

gulp.task('default', function (done) {
    var prompts = [{
        name: 'appName',
        message: 'What is the name of your project?',
        default: defaults.appName
    }, {
        name: 'appDescription',
        message: 'What is the description?'
    }, {
        name: 'appVersion',
        message: 'What is the version of your project?',
        default: '0.1.0'
    }, {
        name: 'authorName',
        message: 'What is the author name?',
    }, {
        name: 'authorEmail',
        message: 'What is the author email?',
        default: defaults.authorEmail
    }, {
        name: 'userName',
        message: 'What is the github username?',
        default: defaults.userName
    }, {
        type: 'confirm',
        name: 'moveon',
        message: 'Continue?'
    }];
    //Ask
    inquirer.prompt(prompts,
        function (answers) {
            if (!answers.moveon) {
                return done();
            }
            answers.appNameSlug = _.slugify(answers.appName);
            gulp.src([__dirname + '/templates/**', __dirname + '/templates/.*'])
                .pipe(template(answers))
                .pipe(rename(function (file) {
                    if (file.basename[0] === '_') {
                        file.basename = '.' + file.basename.slice(1);
                    }
                }))
                .pipe(conflict('./'))
                .pipe(gulp.dest('./'))
                .pipe(install())
                .on('end', function () {
                    done();
                });
        });
});
<commit_msg>Don’t rename _files to .dotfiles<commit_after>/*
 * slush-protosite
 * https://bitbucket.org/mrkp/slush-protosite
 *
 * Copyright (c) 2014, Alfonso Gómez-Arzola
 * Licensed under the MIT license.
 */

'use strict';

var gulp = require('gulp'),
    install = require('gulp-install'),
    conflict = require('gulp-conflict'),
    template = require('gulp-template'),
    rename = require('gulp-rename'),
    _ = require('underscore.string'),
    inquirer = require('inquirer');

function format(string) {
    var username = string.toLowerCase();
    return username.replace(/\s/g, '');
}

var defaults = (function () {
    var homeDir = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE,
        workingDirName = process.cwd().split('/').pop().split('\\').pop(),
        osUserName = homeDir && homeDir.split('/').pop() || 'root',
        configFile = homeDir + '/.gitconfig',
        user = {};
    if (require('fs').existsSync(configFile)) {
        user = require('iniparser').parseSync(configFile).user;
    }
    return {
        appName: workingDirName,
        userName: format(user.name) || osUserName,
        authorEmail: user.email || ''
    };
})();

gulp.task('default', function (done) {
    var prompts = [{
        name: 'appName',
        message: 'What is the name of your project?',
        default: defaults.appName
    }, {
        name: 'appDescription',
        message: 'What is the description?'
    }, {
        name: 'appVersion',
        message: 'What is the version of your project?',
        default: '0.1.0'
    }, {
        name: 'authorName',
        message: 'What is the author name?',
    }, {
        name: 'authorEmail',
        message: 'What is the author email?',
        default: defaults.authorEmail
    }, {
        name: 'userName',
        message: 'What is the github username?',
        default: defaults.userName
    }, {
        type: 'confirm',
        name: 'moveon',
        message: 'Continue?'
    }];
    //Ask
    inquirer.prompt(prompts,
        function (answers) {
            if (!answers.moveon) {
                return done();
            }
            answers.appNameSlug = _.slugify(answers.appName);
            gulp.src([__dirname + '/templates/**', __dirname + '/templates/.*'])
                .pipe(template(answers))
                // .pipe(rename(function (file) {
                //     if (file.basename[0] === '_') {
                //         file.basename = '.' + file.basename.slice(1);
                //     }
                // }))
                .pipe(conflict('./'))
                .pipe(gulp.dest('./'))
                .pipe(install())
                .on('end', function () {
                    done();
                });
        });
});
<|endoftext|>


<commit_before>'use strict';

var chai = require('chai')
  , expect = chai.expect
  , util = require('hw-util')
  , log = util.logFactory('webbotSpec')
  , config = require('../config')
  , webbot = require('../lib/webbot');

describe('Helper', function () {
  var serverPort = 3999;

  this.timeout(3000);

  xit('should start selenium server', function (done) {
    webbot
      .startSelenium(config.selenium)
      .then(function () {
        return webbot.stopSelenium(config.selenium);
      })
      .then(function (result) {
        expect(result).to.be.true;
      })
      .then(done, done);
  });

  describe('browser tests', function () {
    var http = require('http')
      , httpServer
      , options, browser;

    before(function (done) {
      options = {
        selenium: config.selenium,
        browser: {
          verbose: true,
          logLevel: 'verbose',
          desiredCapabilities: config.browser.desiredCapabilities
        }
      };
      webbot
        .init(options)
        .then(function () {
          browser = webbot.getBrowser();
        })
        .then(function () {
          log.info('creating http server');
          httpServer = http.createServer(function (req, res) {
            res.writeHead(200, {'Content-Type': 'text/html'});
            res.end('
hello
');
          });
          expect(httpServer).to.be.ok;
          httpServer.listen(serverPort, function (err) {
            expect(err).to.be.undefined;
            log.info('http server ready');
            done();
          });
        });
    });

    after(function (done) {
      webbot
        .stopSelenium()
        .then(function () {
          log.info('closing http server');
          expect(httpServer).to.be.ok;
          httpServer.close(function () {
            log.info('http server closed');
            done();
          });
        });
    });

    it('should connect to local demo web site', function () {
      return browser
        .url(util.format('http://localhost:%s/', serverPort))
        .getText('h1', function (err, value) {
          if (err) {
            log.error(err);
          }
          expect(err).to.be.undefined;
          log.trace('value :', value);
          expect(value).to.equal('hello');
        })
        .end();
    });

  });

});

<commit_msg>debug build<commit_after>'use strict';

var chai = require('chai')
  , expect = chai.expect
  , util = require('hw-util')
  , log = util.logFactory('webbotSpec')
  , config = require('../config')
  , webbot = require('../lib/webbot');

describe('Helper', function () {
  var serverPort = 3999;

  this.timeout(10000);

  xit('should start selenium server', function (done) {
    webbot
      .startSelenium(config.selenium)
      .then(function () {
        return webbot.stopSelenium(config.selenium);
      })
      .then(function (result) {
        expect(result).to.be.true;
      })
      .then(done, done);
  });

  describe('browser tests', function () {
    var http = require('http')
      , httpServer
      , options, browser;

    before(function (done) {
      options = {
        selenium: config.selenium,
        browser: {
          verbose: true,
          logLevel: 'verbose',
          desiredCapabilities: config.browser.desiredCapabilities
        }
      };
      webbot
        .init(options)
        .then(function () {
          browser = webbot.getBrowser();
        })
        .then(function () {
          log.info('creating http server');
          httpServer = http.createServer(function (req, res) {
            res.writeHead(200, {'Content-Type': 'text/html'});
            res.end('
hello
');
          });
          expect(httpServer).to.be.ok;
          httpServer.listen(serverPort, function (err) {
            expect(err).to.be.undefined;
            log.info('http server ready');
            done();
          });
        });
    });

    after(function (done) {
      webbot
        .stopSelenium()
        .then(function () {
          log.info('closing http server');
          expect(httpServer).to.be.ok;
          httpServer.close(function () {
            log.info('http server closed');
            done();
          });
        });
    });

    it('should connect to local demo web site', function () {
      return browser
        .url(util.format('http://localhost:%s/', serverPort))
        .getText('h1', function (err, value) {
          if (err) {
            log.error(err);
          }
          expect(err).to.be.undefined;
          log.trace('value :', value);
          expect(value).to.equal('hello');
        })
        .end();
    });

  });

});

<|endoftext|>


<commit_before>// @flow
import React, { Component } from 'react';
import type { Node } from 'react';
import { observable, runInAction } from 'mobx';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import BigNumber from 'bignumber.js';
import moment from 'moment';

// Assets and helpers
import StoryDecorator from './support/StoryDecorator';
import walletsIcon from '../../source/renderer/app/assets/images/sidebar/wallet-ic.inline.svg';
import settingsIcon from '../../source/renderer/app/assets/images/sidebar/settings-ic.inline.svg';
import adaIcon from '../../source/renderer/app/assets/images/sidebar/ada-redemption-ic.inline.svg';
import paperCertificateIcon from '../../source/renderer/app/assets/images/sidebar/paper-certificate-ic.inline.svg';
import { formattedWalletAmount } from '../../source/renderer/app/utils/ada/formatters';
import NodeSyncStatusIcon from '../../source/renderer/app/components/widgets/NodeSyncStatusIcon';
import WalletAddress from '../../source/renderer/app/domains/WalletAddress';
import { generateTransaction } from './WalletTransactionsList.stories.js';
import { transactionStates, transactionTypes } from '../../source/renderer/app/domains/WalletTransaction';

// Empty screen elements
import TopBar from '../../source/renderer/app/components/layout/TopBar';
import Sidebar from '../../source/renderer/app/components/sidebar/Sidebar';
import SidebarLayout from '../../source/renderer/app/components/layout/SidebarLayout';
import SidebarWalletsMenu from '../../source/renderer/app/components/sidebar/wallets/SidebarWalletsMenu';
import WalletWithNavigation from '../../source/renderer/app/components/wallet/layouts/WalletWithNavigation';

// Screens
import WalletSummary from '../../source/renderer/app/components/wallet/summary/WalletSummary';
import WalletSendForm from '../../source/renderer/app/components/wallet/WalletSendForm';
import WalletReceive from '../../source/renderer/app/components/wallet/WalletReceive';
import WalletTransactionsList from '../../source/renderer/app/components/wallet/transactions/WalletTransactionsList';
import WalletSettings from '../../source/renderer/app/components/wallet/WalletSettings';

type Props = {
  activeNavItem?: string,
  children?: any | Node
};

const sidebarCategories = [
  {
    name: 'WALLETS',
    route: '/wallets',
    icon: walletsIcon,
  },
  {
    name: 'SETTINGS',
    route: '/settings',
    icon: settingsIcon,
  },
  {
    name: 'ADA_REDEMPTION',
    route: '/ada-redemption',
    icon: adaIcon,
  },
  {
    name: 'PAPER_WALLET',
    route: '/paper-wallet-create-certificate',
    icon: paperCertificateIcon,
  }
];

const sidebarMenus = observable({
  wallets: {
    items: [
      { id: '1', title: 'Mining', info: '0.000000 ADA', isConnected: true },
      { id: '2', title: 'Shopping', info: '66.998.623133 ADA', isConnected: true },
    ],
    activeWalletId: '2',
    actions: {
      onAddWallet: action('toggleAddWallet'),
      onWalletItemClick: (walletId: string) => {
        runInAction(() => sidebarMenus.wallets.activeWalletId = walletId);
      }
    }
  }
});

class WalletScreen extends Component<Props> {

  render() {

    const { children, activeNavItem } = this.props;

    return (

        <SidebarLayout
          sidebar={this.sidebar(!!children)}
          topbar={this.topbar}
        >
          {
            children &&
              (
                <WalletWithNavigation
                  isActiveScreen={item => item === activeNavItem}
                  onWalletNavItemClick={action('onWalletNavItemClick')}
                >
                  {children}
                </WalletWithNavigation>
              )
          }
        </SidebarLayout>

    );
  }

  sidebar = isShowingSubMenus => (
    <Sidebar
      categories={sidebarCategories}
      activeSidebarCategory={sidebarCategories[0].route}
      menus={sidebarMenus}
      isShowingSubMenus={isShowingSubMenus}
      onCategoryClicked={action('onCategoryClicked')}
      isDialogOpen={() => false}
      onAddWallet={action('onAddWallet')}
      openDialogAction={action('openDialog')}
      onSubmitSupportRequest={()=>{}}
    />
  )

  // TODO: Find out how to activave the `topBarTitle` on TopBar
  get topbar() {
    return (
      <TopBar
        formattedWalletAmount={formattedWalletAmount}
        currentRoute="summary"
        showSubMenuToggle
        showSubMenus
      >
        <NodeSyncStatusIcon
          networkStatus={{
            isSynced: true,
            syncPercentage: 100,
          }}
          isProduction
        />
      </TopBar>
    );
  }
}

storiesOf('WalletScreens', module)

  .addDecorator((story, { story:storyName }) => (
    <StoryDecorator>
      <WalletScreen
        activeNavItem={storyName.toLowerCase()}
      >
      {story()}
      </WalletScreen>
    </StoryDecorator>
  ))

  // ====== Stories ======

  .add('Empty', () => false)

  .add('Summary', () => (
    <WalletSummary
      walletName="Shopping wallet"
      amount="45119903750165.23"
      pendingAmount={{
        incoming: new BigNumber(1),
        outgoing: new BigNumber(2),
        total: new BigNumber(3)
      }}
      numberOfTransactions={20303585}
      isLoadingTransactions={false}
    />
  ))

  .add('Send', () => (
    <WalletSendForm
      currencyUnit="Ada"
      currencyMaxFractionalDigits={ 6}
      currencyMaxIntegerDigits={11}
      validateAmount={() => true}
      calculateTransactionFee={()=>{}}
      addressValidator={()=>{}}
      openDialogAction={()=>{}}
      isDialogOpen={()=>{}}
      isRestoreActive={false}
    />
  ))

  .add('Receive', () => (
    <WalletReceive
      walletAddress="5628aab8ac98c963e4a2e8cfce5aa1cbd4384fe2f9a0f3c5f791bfb83a5e02ds"
      isWalletAddressUsed={false}
      walletAddresses={[
        {
          id: '5628aab8ac98c963e4a2e8cfce5aa1cbd4384fe2f9a0f3c5f791bfb83a5e02ds',
          amount: new BigNumber(1),
          isUsed:false,
        },
        {
          id: 'f465aca571de909091967349e1dc39fc9ce9755ff8ffdb7cc3771b503904e49a',
          amount: new BigNumber(1),
          isUsed:false,
        },
        {
          id: '5628aab8ac98c963e4a2e8cfce5aa1cbd4384fe2f9a0f3c5f791bfb83a5e02ds',
          amount: new BigNumber(1),
          isUsed:false,
        },
        {
          id: 'f465aca571de909091967349e1dc39fc9ce9755ff8ffdb7cc3771b503904e49a',
          amount: new BigNumber(1),
          isUsed:false,
        },
        {
          id: '5628aab8ac98c963e4a2e8cfce5aa1cbd4384fe2f9a0f3c5f791bfb83a5e02ds',
          amount: new BigNumber(1),
          isUsed:false,
        },
        {
          id: 'f465aca571de909091967349e1dc39fc9ce9755ff8ffdb7cc3771b503904e49a',
          amount: new BigNumber(1),
          isUsed:false,
        },
        {
          id: '68a1107193a8183bcd7758c9b3d9f3e8b0437206cc432b4e01a49d948157f51e',
          amount: new BigNumber(1),
          isUsed:true,
        },
        {
          id: '68a1107193a8183bcd7758c9b3d9f3e8b0437206cc432b4e01a49d948157f51e',
          amount: new BigNumber(1),
          isUsed:true,
        },
        {
          id: '68a1107193a8183bcd7758c9b3d9f3e8b0437206cc432b4e01a49d948157f51e',
          amount: new BigNumber(1),
          isUsed:true,
        },
        {
          id: '68a1107193a8183bcd7758c9b3d9f3e8b0437206cc432b4e01a49d948157f51e',
          amount: new BigNumber(1),
          isUsed:true,
        },
        {
          id: '68a1107193a8183bcd7758c9b3d9f3e8b0437206cc432b4e01a49d948157f51e',
          amount: new BigNumber(1),
          isUsed:true,
        },
        {
          id: '68a1107193a8183bcd7758c9b3d9f3e8b0437206cc432b4e01a49d948157f51e',
          amount: new BigNumber(1),
          isUsed:true,
        }
      ]}
      onGenerateAddress={()=>{}}
      onCopyAddress={()=>{}}
      isSidebarExpanded
      walletHasPassword={false}
      isSubmitting={false}
    />
  ))

  .add('Transactions', () => (
    <WalletTransactionsList
      transactions={[
        generateTransaction(transactionTypes.INCOME, new Date(), new BigNumber(1), 1),
        generateTransaction(transactionTypes.EXCHANGE, new Date(), new BigNumber(1)),
        generateTransaction(transactionTypes.EXPEND, moment().subtract(1, 'days').toDate(), new BigNumber(2), 0, transactionStates.PENDING),
        generateTransaction(transactionTypes.INCOME, moment().subtract(1, 'days').toDate(), new BigNumber(1), 0, transactionStates.FAILED),
        generateTransaction(transactionTypes.EXPEND, moment().subtract(2, 'days').toDate(), new BigNumber(3)),
        generateTransaction(transactionTypes.EXPEND, moment().subtract(3, 'days').toDate(), new BigNumber(5)),
        generateTransaction(transactionTypes.INCOME, moment().subtract(4, 'days').toDate(), new BigNumber(6)),
      ]}
      isLoadingTransactions={false}
      hasMoreToLoad={false}
      assuranceMode={{ low: 1, medium: 2 }}
      walletId="test-wallet"
      formattedWalletAmount={formattedWalletAmount}
    />
  ))

  .add('Settings', () => (
    <WalletSettings
      activeField={null}
      assuranceLevels={[
        {
          "value": "CWANormal",
          "label": {
            "id": "global.assuranceLevel.normal",
            "defaultMessage": "!!!Normal"
          }
        },
        {
          "value": "CWAStrict",
          "label": {
            "id": "global.assuranceLevel.strict",
            "defaultMessage": "!!!Strict"
          }
        }
      ]}
      isDialogOpen={()=>false}
      isInvalid={false}
      isSubmitting={false}
      isWalletPasswordSet={false}
      lastUpdatedField={null}
      nameValidator={()=>true}
      onCancelEditing={()=>{}}
      onFieldValueChange={()=>{}}
      onStartEditing={()=>{}}
      onStopEditing={()=>{}}
      openDialogAction={()=>{}}
      walletAssurance="CWANormal"
      walletName="Test wallet"
      walletPasswordUpdateDate={moment().subtract(1, 'month').toDate()}
    />
  ));

<commit_msg>[DDW-280] Flow test error<commit_after>// @flow
import React, { Component } from 'react';
import type { Node } from 'react';
import { observable, runInAction } from 'mobx';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import BigNumber from 'bignumber.js';
import moment from 'moment';

// Assets and helpers
import StoryDecorator from './support/StoryDecorator';
import walletsIcon from '../../source/renderer/app/assets/images/sidebar/wallet-ic.inline.svg';
import settingsIcon from '../../source/renderer/app/assets/images/sidebar/settings-ic.inline.svg';
import adaIcon from '../../source/renderer/app/assets/images/sidebar/ada-redemption-ic.inline.svg';
import paperCertificateIcon from '../../source/renderer/app/assets/images/sidebar/paper-certificate-ic.inline.svg';
import { formattedWalletAmount } from '../../source/renderer/app/utils/ada/formatters';
import NodeSyncStatusIcon from '../../source/renderer/app/components/widgets/NodeSyncStatusIcon';
import WalletAddress from '../../source/renderer/app/domains/WalletAddress';
import { generateTransaction } from './WalletTransactionsList.stories.js';
import { transactionStates, transactionTypes } from '../../source/renderer/app/domains/WalletTransaction';

// Empty screen elements
import TopBar from '../../source/renderer/app/components/layout/TopBar';
import Sidebar from '../../source/renderer/app/components/sidebar/Sidebar';
import SidebarLayout from '../../source/renderer/app/components/layout/SidebarLayout';
import SidebarWalletsMenu from '../../source/renderer/app/components/sidebar/wallets/SidebarWalletsMenu';
import WalletWithNavigation from '../../source/renderer/app/components/wallet/layouts/WalletWithNavigation';

// Screens
import WalletSummary from '../../source/renderer/app/components/wallet/summary/WalletSummary';
import WalletSendForm from '../../source/renderer/app/components/wallet/WalletSendForm';
import WalletReceive from '../../source/renderer/app/components/wallet/WalletReceive';
import WalletTransactionsList from '../../source/renderer/app/components/wallet/transactions/WalletTransactionsList';
import WalletSettings from '../../source/renderer/app/components/wallet/WalletSettings';

type Props = {
  activeNavItem?: string,
  children?: any | Node
};

const sidebarCategories = [
  {
    name: 'WALLETS',
    route: '/wallets',
    icon: walletsIcon,
  },
  {
    name: 'SETTINGS',
    route: '/settings',
    icon: settingsIcon,
  },
  {
    name: 'ADA_REDEMPTION',
    route: '/ada-redemption',
    icon: adaIcon,
  },
  {
    name: 'PAPER_WALLET',
    route: '/paper-wallet-create-certificate',
    icon: paperCertificateIcon,
  }
];

const sidebarMenus = observable({
  wallets: {
    items: [
      { id: '1', title: 'Mining', info: '0.000000 ADA', isConnected: true },
      { id: '2', title: 'Shopping', info: '66.998.623133 ADA', isConnected: true },
    ],
    activeWalletId: '2',
    actions: {
      onAddWallet: action('toggleAddWallet'),
      onWalletItemClick: (walletId: string) => {
        runInAction(() => sidebarMenus.wallets.activeWalletId = walletId);
      }
    }
  }
});

class WalletScreen extends Component<Props> {

  render() {

    const { children, activeNavItem } = this.props;

    return (

        <SidebarLayout
          sidebar={this.sidebar(!!children)}
          topbar={this.topbar}
        >
          {
            children &&
              (
                <WalletWithNavigation
                  isActiveScreen={item => item === activeNavItem}
                  onWalletNavItemClick={action('onWalletNavItemClick')}
                >
                  {children}
                </WalletWithNavigation>
              )
          }
        </SidebarLayout>

    );
  }

  sidebar = isShowingSubMenus => (
    <Sidebar
      categories={sidebarCategories}
      activeSidebarCategory={sidebarCategories[0].route}
      menus={sidebarMenus}
      isShowingSubMenus={isShowingSubMenus}
      onCategoryClicked={action('onCategoryClicked')}
      isDialogOpen={() => false}
      onAddWallet={action('onAddWallet')}
      openDialogAction={action('openDialog')}
      onSubmitSupportRequest={()=>{}}
    />
  )

  // TODO: Find out how to activave the `topBarTitle` on TopBar
  get topbar() {
    return (
      <TopBar
        formattedWalletAmount={formattedWalletAmount}
        currentRoute="summary"
        showSubMenuToggle
        showSubMenus
      >
        <NodeSyncStatusIcon
          networkStatus={{
            isSynced: true,
            syncPercentage: 100,
          }}
          isProduction
        />
      </TopBar>
    );
  }
}

storiesOf('WalletScreens', module)

  .addDecorator((story, { story:storyName }) => (
    <StoryDecorator>
      <WalletScreen
        activeNavItem={storyName.toLowerCase()}
      >
      {story()}
      </WalletScreen>
    </StoryDecorator>
  ))

  // ====== Stories ======

  .add('Empty', () => false)

  .add('Summary', () => (
    <WalletSummary
      walletName="Shopping wallet"
      amount="45119903750165.23"
      pendingAmount={{
        incoming: new BigNumber(1),
        outgoing: new BigNumber(2),
        total: new BigNumber(3)
      }}
      numberOfTransactions={20303585}
      isLoadingTransactions={false}
    />
  ))

  .add('Send', () => (
    <WalletSendForm
      currencyUnit="Ada"
      currencyMaxFractionalDigits={ 6}
      currencyMaxIntegerDigits={11}
      validateAmount={() => true}
      calculateTransactionFee={()=>{}}
      addressValidator={()=>{}}
      openDialogAction={()=>{}}
      isDialogOpen={()=>{}}
      isRestoreActive={false}
    />
  ))

  .add('Receive', () => (
    <WalletReceive
      walletAddress="5628aab8ac98c963e4a2e8cfce5aa1cbd4384fe2f9a0f3c5f791bfb83a5e02ds"
      isWalletAddressUsed={false}
      walletAddresses={[
        {
          id: '5628aab8ac98c963e4a2e8cfce5aa1cbd4384fe2f9a0f3c5f791bfb83a5e02ds',
          amount: new BigNumber(1),
          isUsed:false,
        },
        {
          id: 'f465aca571de909091967349e1dc39fc9ce9755ff8ffdb7cc3771b503904e49a',
          amount: new BigNumber(1),
          isUsed:false,
        },
        {
          id: '5628aab8ac98c963e4a2e8cfce5aa1cbd4384fe2f9a0f3c5f791bfb83a5e02ds',
          amount: new BigNumber(1),
          isUsed:false,
        },
        {
          id: 'f465aca571de909091967349e1dc39fc9ce9755ff8ffdb7cc3771b503904e49a',
          amount: new BigNumber(1),
          isUsed:false,
        },
        {
          id: '5628aab8ac98c963e4a2e8cfce5aa1cbd4384fe2f9a0f3c5f791bfb83a5e02ds',
          amount: new BigNumber(1),
          isUsed:false,
        },
        {
          id: 'f465aca571de909091967349e1dc39fc9ce9755ff8ffdb7cc3771b503904e49a',
          amount: new BigNumber(1),
          isUsed:false,
        },
        {
          id: '68a1107193a8183bcd7758c9b3d9f3e8b0437206cc432b4e01a49d948157f51e',
          amount: new BigNumber(1),
          isUsed:true,
        },
        {
          id: '68a1107193a8183bcd7758c9b3d9f3e8b0437206cc432b4e01a49d948157f51e',
          amount: new BigNumber(1),
          isUsed:true,
        },
        {
          id: '68a1107193a8183bcd7758c9b3d9f3e8b0437206cc432b4e01a49d948157f51e',
          amount: new BigNumber(1),
          isUsed:true,
        },
        {
          id: '68a1107193a8183bcd7758c9b3d9f3e8b0437206cc432b4e01a49d948157f51e',
          amount: new BigNumber(1),
          isUsed:true,
        },
        {
          id: '68a1107193a8183bcd7758c9b3d9f3e8b0437206cc432b4e01a49d948157f51e',
          amount: new BigNumber(1),
          isUsed:true,
        },
        {
          id: '68a1107193a8183bcd7758c9b3d9f3e8b0437206cc432b4e01a49d948157f51e',
          amount: new BigNumber(1),
          isUsed:true,
        }
      ]}
      onGenerateAddress={()=>{}}
      onCopyAddress={()=>{}}
      isSidebarExpanded
      walletHasPassword={false}
      isSubmitting={false}
    />
  ))

  .add('Transactions', () => (
    <WalletTransactionsList
      transactions={[
        generateTransaction(transactionTypes.INCOME, new Date(), new BigNumber(1), 1),
        generateTransaction(transactionTypes.EXCHANGE, new Date(), new BigNumber(1)),
        generateTransaction(transactionTypes.EXPEND, moment().subtract(1, 'days').toDate(), new BigNumber(2), 0, transactionStates.PENDING),
        generateTransaction(transactionTypes.INCOME, moment().subtract(1, 'days').toDate(), new BigNumber(1), 0, transactionStates.FAILED),
        generateTransaction(transactionTypes.EXPEND, moment().subtract(2, 'days').toDate(), new BigNumber(3)),
        generateTransaction(transactionTypes.EXPEND, moment().subtract(3, 'days').toDate(), new BigNumber(5)),
        generateTransaction(transactionTypes.INCOME, moment().subtract(4, 'days').toDate(), new BigNumber(6)),
      ]}
      isLoadingTransactions={false}
      hasMoreToLoad={false}
      assuranceMode={{ low: 1, medium: 2 }}
      walletId="test-wallet"
      formattedWalletAmount={formattedWalletAmount}
    />
  ))

  .add('Settings', () => (
    <WalletSettings
      activeField={null}
      assuranceLevels={[
        {
          "value": "CWANormal",
          "label": {
            id: 'global.assuranceLevel.normal',
            defaultMessage: '!!!Normal',
            description: ''
          }
        },
        {
          "value": "CWAStrict",
          "label": {
            id: 'global.assuranceLevel.strict',
            defaultMessage: '!!!Strict',
            description: ''
          }
        }
      ]}
      isDialogOpen={()=>false}
      isInvalid={false}
      isSubmitting={false}
      isWalletPasswordSet={false}
      lastUpdatedField={null}
      nameValidator={()=>true}
      onCancelEditing={()=>{}}
      onFieldValueChange={()=>{}}
      onStartEditing={()=>{}}
      onStopEditing={()=>{}}
      openDialogAction={()=>{}}
      walletAssurance="CWANormal"
      walletName="Test wallet"
      walletPasswordUpdateDate={moment().subtract(1, 'month').toDate()}
    />
  ));

<|endoftext|>


<commit_before>var fs = require('fs');
var util = require('util');
var grunt = require("grunt");
var snc_eval = require("./snc-eval");

// Jasmine "runner"
function executeSpecs(specs, done, isVerbose, showColors) {
  var results = [];
  var started = new Date().getTime();

  function printResultSummary() {
    var elapsed = new Date().getTime() - started;
    console.log("\nSummary of " + results.length + " file(s):");
    var totalSpecs = 0,
        totalFailures = 0,
        totalCrashes = 0,
        totalTimeInSnc = 0.0;
    results.forEach(function(result) {
      var summary = 'CRASHED';
      if (result.status == 'OK') {
        summary = result.counts.specs + ' specs, ' + result.counts.failures + ' failures, ' +
          (result.counts.pending > 0 ? (result.counts.pending + ' pending, ') : '') +
          result.counts.time + ' seconds';
        totalSpecs += result.counts.specs;
        totalFailures += result.counts.failures;
        totalTimeInSnc += result.counts.time;
      } else {
        totalCrashes += 1;
      }
      console.log(result.filename + ': ' + summary);
    });
    console.log(results.length + " files, " + totalCrashes + " crashed, " + totalSpecs + " specs, " + totalFailures + " failures");
    console.log('Total time ' + elapsed / 1000 + ' seconds, ServiceNow time ' + Math.round(totalTimeInSnc * 1000) / 1000.0 + ' seconds');
  }

  var filefn = function(idx, next) {
    if (idx == specs.length) {
      printResultSummary();
      done(true);
    } else {
      var filename = specs[idx];
      console.log('running ' + filename);
      snc_eval.SnvEvalFile(filename, function(error, body) {
        if (error) {
          printResultSummary();
          console.log(error);
          done(false);
        } else {
          var result = JSON.parse(body);
          if (result.status == 'OK') {
            console.log(result.output);
            var re = /(\d+) specs?, (\d+) failures?(, (\d+) pending specs?)?\n*Finished in (\d+\.\d+) seconds?\n?$/;
            var matches = re.exec(result.output);
            results.push({
              filename: filename,
              status: result.status,
              counts: {
                specs: parseInt(matches[1]),
                failures: parseInt(matches[2]),
                pending: typeof matches[4] === 'undefined' ? 0 : parseInt(matches[4]),
                time: parseFloat(matches[5])
              }
            });
          } else {
            console.log('ERROR:');
            console.log(result.error);
            console.log("\nOUTPUT:");
            console.log(result.output);
            results.push({filename: filename, status: result.status, counts: null});
          }
          next(idx + 1, next);
        }
      });
    }
  };

  filefn(0, filefn);
}

function getFiles(dir, matcher) {
  var allFiles = [];

  if (fs.statSync(dir).isFile() && dir.match(matcher)) {
    allFiles.push(dir);
  } else {
    var files = fs.readdirSync(dir);
    for (var i = 0, len = files.length; i < len; ++i) {
      var filename = dir + '/' + files[i];
      if (fs.statSync(filename).isFile() && filename.match(matcher)) {
        allFiles.push(filename);
      } else if (fs.statSync(filename).isDirectory()) {
        var subfiles = getFiles(filename);
        subfiles.forEach(function(result) {
          allFiles.push(result);
        });
      }
    }
  }
  return allFiles;
}

function getSpecFiles(dir) {
  return getFiles(dir, new RegExp("\.js$"));
}

// options from command line
var isVerbose = false;
var showColors = true;
var perfSuite = false;

process.argv.forEach(function(arg) {
  switch (arg) {
    case '--color':
      showColors = true;
      break;
    case '--noColor':
      showColors = false;
      break;
    case '--verbose':
      isVerbose = true;
      break;
    case '--perf':
      perfSuite = true;
      break;
  }
});

specs = [];

if (perfSuite) {
  specs = getFiles(__dirname + '/snc_eval_spec/performance', new RegExp("test.js$"));
} else {

  var consoleSpecs = getSpecFiles(__dirname + "/snc_eval_spec/jasmine-snc"),
      coreSpecs = getSpecFiles(__dirname + "/snc_eval_spec/core"),
      specs = consoleSpecs.concat(coreSpecs);

  //var specs = getSpecFiles(__dirname + "/snc_eval_spec/jasmine-snc");
}

executeSpecs(specs, function(passed) {
  if (passed) {
    process.exit(0);
  } else {
    process.exit(1);
  }
}, isVerbose, showColors);
<commit_msg>show only failed files in the summary<commit_after>var fs = require('fs');
var util = require('util');
var grunt = require("grunt");
var snc_eval = require("./snc-eval");

// Jasmine "runner"
function executeSpecs(specs, done, isVerbose, showColors) {
  var results = [];
  var started = new Date().getTime();

  function printResultSummary() {
    var elapsed = new Date().getTime() - started,
        totalSpecs = 0,
        totalFailures = 0,
        totalCrashes = 0,
        totalTimeInSnc = 0.0;

    console.log("\nSummary of failed file(s):");
    results.forEach(function(result) {
      var summary = 'CRASHED';
      if (result.status == 'OK') {
        summary = result.counts.specs + ' specs, ' + result.counts.failures + ' failures, ' +
          (result.counts.pending > 0 ? (result.counts.pending + ' pending, ') : '') +
          result.counts.time + ' seconds';
        totalSpecs += result.counts.specs;
        totalFailures += result.counts.failures;
        totalTimeInSnc += result.counts.time;
      } else {
        totalCrashes += 1;
      }
      if (result.status != 'OK' || result.counts.failures > 0) {
        console.log(result.filename + ': ' + summary);
      }
    });
    console.log(results.length + " files, " + totalCrashes + " crashed, " + totalSpecs + " specs, " + totalFailures + " failures");
    console.log('Total time ' + elapsed / 1000 + ' seconds, ServiceNow time ' + Math.round(totalTimeInSnc * 1000) / 1000.0 + ' seconds');
  }

  var filefn = function(idx, next) {
    if (idx == specs.length) {
      printResultSummary();
      done(true);
    } else {
      var filename = specs[idx];
      console.log('running ' + filename);
      snc_eval.SnvEvalFile(filename, function(error, body) {
        if (error) {
          printResultSummary();
          console.log(error);
          done(false);
        } else {
          var result = JSON.parse(body);
          if (result.status == 'OK') {
            console.log(result.output);
            var re = /(\d+) specs?, (\d+) failures?(, (\d+) pending specs?)?\n*Finished in (\d+\.\d+) seconds?\n?$/;
            var matches = re.exec(result.output);
            results.push({
              filename: filename,
              status: result.status,
              counts: {
                specs: parseInt(matches[1]),
                failures: parseInt(matches[2]),
                pending: typeof matches[4] === 'undefined' ? 0 : parseInt(matches[4]),
                time: parseFloat(matches[5])
              }
            });
          } else {
            console.log('ERROR:');
            console.log(result.error);
            console.log("\nOUTPUT:");
            console.log(result.output);
            results.push({filename: filename, status: result.status, counts: null});
          }
          next(idx + 1, next);
        }
      });
    }
  };

  filefn(0, filefn);
}

function getFiles(dir, matcher) {
  var allFiles = [];

  if (fs.statSync(dir).isFile() && dir.match(matcher)) {
    allFiles.push(dir);
  } else {
    var files = fs.readdirSync(dir);
    for (var i = 0, len = files.length; i < len; ++i) {
      var filename = dir + '/' + files[i];
      if (fs.statSync(filename).isFile() && filename.match(matcher)) {
        allFiles.push(filename);
      } else if (fs.statSync(filename).isDirectory()) {
        var subfiles = getFiles(filename);
        subfiles.forEach(function(result) {
          allFiles.push(result);
        });
      }
    }
  }
  return allFiles;
}

function getSpecFiles(dir) {
  return getFiles(dir, new RegExp("\.js$"));
}

// options from command line
var isVerbose = false;
var showColors = true;
var perfSuite = false;

process.argv.forEach(function(arg) {
  switch (arg) {
    case '--color':
      showColors = true;
      break;
    case '--noColor':
      showColors = false;
      break;
    case '--verbose':
      isVerbose = true;
      break;
    case '--perf':
      perfSuite = true;
      break;
  }
});

specs = [];

if (perfSuite) {
  specs = getFiles(__dirname + '/snc_eval_spec/performance', new RegExp("test.js$"));
} else {

  var consoleSpecs = getSpecFiles(__dirname + "/snc_eval_spec/jasmine-snc"),
      coreSpecs = getSpecFiles(__dirname + "/snc_eval_spec/core"),
      specs = consoleSpecs.concat(coreSpecs);

  //var specs = getSpecFiles(__dirname + "/snc_eval_spec/jasmine-snc");
}

executeSpecs(specs, function(passed) {
  if (passed) {
    process.exit(0);
  } else {
    process.exit(1);
  }
}, isVerbose, showColors);
<|endoftext|>


<commit_before>/*doc
 ---
 title: Copy To Clipboard
 name: copy_to_clipboard_react
 categories:
 - react_components_copy-to-clipboard
 - react_all
 ---

 npm install pui-react-copy-to-clipboard --save

 Require the subcomponents:

 ```
var CopyToClipboard = require('pui-react-copy-to-clipboard').CopyToClipboard;
var CopyToClipboardButton = require('pui-react-copy-to-clipboard').CopyToClipboardButton;
 ```

 ```react_example_table
 <CopyToClipboard text="I got copied by a button"><button>Click Me To Copy</button></CopyToClipboard>

 <CopyToClipboardButton text="I got copied by a good looking button"/>
 ```

 The CopyToClipboard Components require the following property:

 Property           |  Type         | Description
 -------------      | --------------| --------------------------------------------------------------------------
 `text`       | String        | Text that is copied when the user clicks

Below is a common example combining a readonly input and a copy button:

```
var Input = require('pui-react-inputs').Input
```

 ```react_example_table
<div className="copy-input">
   <Input label="shareable link" value="bar.com/1234.jpg" readOnly />
   <CopyToClipboardButton text="bar.com/1234.jpg"/>
</div>

 ```

 */
<commit_msg>chore(styleguide): Add a note to the copy to clipboard example on styleguide<commit_after>/*doc
 ---
 title: Copy To Clipboard
 name: copy_to_clipboard_react
 categories:
 - react_components_copy-to-clipboard
 - react_all
 ---

 npm install pui-react-copy-to-clipboard --save

 Require the subcomponents:

 ```
var CopyToClipboard = require('pui-react-copy-to-clipboard').CopyToClipboard;
var CopyToClipboardButton = require('pui-react-copy-to-clipboard').CopyToClipboardButton;
 ```

 ```react_example_table
 <CopyToClipboard text="I got copied by a button"><button>Click Me To Copy</button></CopyToClipboard>

 <CopyToClipboardButton text="I got copied by a good looking button"/>
 ```

 The CopyToClipboard Components require the following property:

 Property           |  Type         | Description
 -------------      | --------------| --------------------------------------------------------------------------
 `text`       | String        | Text that is copied when the user clicks

Below is a common example combining a readonly input and a copy button.
Note that there is custom css on the styleguide to get the positioning right.

```
var Input = require('pui-react-inputs').Input
```

 ```react_example_table
<div className="copy-input">
   <Input label="shareable link" value="bar.com/1234.jpg" readOnly />
   <CopyToClipboardButton text="bar.com/1234.jpg"/>
</div>

 ```

 */
<|endoftext|>


<commit_before>"use strict";

var _gaq = _gaq || [];

angular.module("hikeio").
	run(function() {
		_gaq.push(["_setAccount", "UA-33552646-1"]);
		_gaq.push(["_setDomainName", "hike.io"]);

		var ga = document.createElement("script");
		ga.type = "text/javascript";
		ga.async = true;
		ga.src = ("https:" === document.location.protocol ? "https://ssl" : "http://www") + ".google-analytics.com/ga.js";
		var s = document.getElementsByTagName("script")[0];
		s.parentNode.insertBefore(ga, s);

	}).
	service("analytics", function($rootScope, $window, $location, $routeParams) {
		var trackPageView = function() {
			$window._gaq.push(["_trackPageview", $location.path()]);
		};

		$rootScope.$on("$viewContentLoaded", trackPageView);
	});<commit_msg>Explicitly add injections to avoid minification problems for analytics service.<commit_after>"use strict";

var _gaq = _gaq || [];

angular.module("hikeio").
	run(function() {
		_gaq.push(["_setAccount", "UA-33552646-1"]);
		_gaq.push(["_setDomainName", "hike.io"]);

		var ga = document.createElement("script");
		ga.type = "text/javascript";
		ga.async = true;
		ga.src = ("https:" === document.location.protocol ? "https://ssl" : "http://www") + ".google-analytics.com/ga.js";
		var s = document.getElementsByTagName("script")[0];
		s.parentNode.insertBefore(ga, s);

	}).
	service("analytics", ["$rootScope", "$window", "$location", "$routeParams", function($rootScope, $window, $location, $routeParams) {
		var trackPageView = function() {
			$window._gaq.push(["_trackPageview", $location.path()]);
		};

		$rootScope.$on("$viewContentLoaded", trackPageView);
	}]);<|endoftext|>


<commit_before>// This file should ONLY be imported for the Electron build

import fs from 'fs'
import path from 'path'
import thenify from 'thenify'
import childProcess from 'child_process'

// Returns a promise that will resolve to a string version of the specified exe file (or reject with
// any errors that may occur)
function getExeVersion(filePath) {
  const command = process.env.SystemRoot ?
      path.join(process.env.SystemRoot, 'System32', 'wbem', 'wmic.exe') :
      'wmic.exe'
  const wmicCommand =
      `datafile where name="${filePath.replace(/"/g, '\\"').replace(/\\/g, '\\\\')}" get version`
  return new Promise((resolve, reject) => {
    let spawned
    try {
      spawned = childProcess.spawn(command, [])
    } catch (err) {
      reject(err)
    }

    let stdout = ''
    let err
    spawned.stdout.on('data', data => { stdout += data })
    spawned.on('error', e => { err = err || e })
      .on('close', (code, signal) => {
        if (err === undefined && code !== 0) {
          err = new Error('Non-zero exit code: ' + (signal || code))
        }
        if (err !== undefined) {
          reject(err)
          return
        }

        // Output should look like:
        // Version
        // 1.16.1.1
        const lines = stdout.split(/\r?\n/g)
        if (lines.length < 2 || !lines[0].startsWith('wmic:root\\cli>Version')) {
          reject(new Error('Malformed wmic output'))
          return
        }

        resolve(lines[1].trim())
      })

    spawned.stdin.end(wmicCommand)
  })
}

const accessAsync = thenify(fs.access)
export async function checkStarcraftPath(dirPath) {
  const filePath = path.join(dirPath, 'starcraft.exe')
  try {
    await accessAsync(filePath, fs.constants.R_OK)
  } catch (err) {
    return { path: false, version: false }
  }

  let version
  try {
    version = await getExeVersion(filePath)
  } catch (err) {
    return { path: true, version: false }
  }

  return {
    path: true,
    version: version === '1.16.1.1'
  }
}
<commit_msg>Add some logging around wmic failures in checking starcraft version.<commit_after>// This file should ONLY be imported for the Electron build

import fs from 'fs'
import path from 'path'
import thenify from 'thenify'
import childProcess from 'child_process'
import logger from '../logging/logger'

// Returns a promise that will resolve to a string version of the specified exe file (or reject with
// any errors that may occur)
function getExeVersion(filePath) {
  const command = process.env.SystemRoot ?
      path.join(process.env.SystemRoot, 'System32', 'wbem', 'wmic.exe') :
      'wmic.exe'
  const wmicCommand =
      `datafile where name="${filePath.replace(/"/g, '\\"').replace(/\\/g, '\\\\')}" get version`
  return new Promise((resolve, reject) => {
    let spawned
    try {
      spawned = childProcess.spawn(command, [])
    } catch (err) {
      reject(err)
    }

    let stdout = ''
    let err
    spawned.stdout.on('data', data => { stdout += data })
    spawned.on('error', e => { err = err || e })
      .on('close', (code, signal) => {
        if (err === undefined && code !== 0) {
          err = new Error('Non-zero exit code: ' + (signal || code))
        }
        if (err !== undefined) {
          reject(err)
          return
        }

        // Output should look like:
        // Version
        // 1.16.1.1
        const lines = stdout.split(/\r?\n/g)
        if (lines.length < 2 || !lines[0].startsWith('wmic:root\\cli>Version')) {
          reject(new Error('Malformed wmic output'))
          return
        }

        resolve(lines[1].trim())
      })

    spawned.stdin.end(wmicCommand)
  })
}

const accessAsync = thenify(fs.access)
export async function checkStarcraftPath(dirPath) {
  const filePath = path.join(dirPath, 'starcraft.exe')
  try {
    await accessAsync(filePath, fs.constants.R_OK)
  } catch (err) {
    return { path: false, version: false }
  }

  let version
  try {
    version = await getExeVersion(filePath)
  } catch (err) {
    logger.warning('Error getting exe version: ' + err)
    return { path: true, version: false }
  }

  return {
    path: true,
    version: version === '1.16.1.1'
  }
}
<|endoftext|>


<commit_before>import React from 'react'

import { Container, Background, Content } from './styled'

const Home = () => (
  <Container id="home">
    <Background />

    <Content>

        Somos la comunidad de{' '}

          freeCodeCamp
        {' '}
        en{' '}

          Buenos Aires

Veni a conocernos para aprender sobre desarrollo web en comunidad!

      <video controls="controls" autoplay="autoplay" loop="loop">
        <source src="https://res.cloudinary.com/dnbygvvyz/video/upload/v1552479645/video-fcc.mp4" />
      </video>
    </Content>
  </Container>
)

export default Home
<commit_msg>Fix for video<commit_after>import React from 'react'

import { Container, Background, Content } from './styled'

const Home = () => (
  <Container id="home">
    <Background />

    <Content>

        Somos la comunidad de{' '}

          freeCodeCamp
        {' '}
        en{' '}

          Buenos Aires

Veni a conocernos para aprender sobre desarrollo web en comunidad!

      <video controls="controls" autoplay loop="loop">
        <source src="https://res.cloudinary.com/dnbygvvyz/video/upload/v1552479645/video-fcc.mp4" />
      </video>
    </Content>
  </Container>
)

export default Home
<|endoftext|>


<commit_before>enyo.kind({
	name: "Sound",
	kind: "enyo.FittableRows",
	published: {},
	events: {
		onMuteChanged: ""
	},
	handlers: {
		onClose: "closePopup",
		onTone: "tonepicked"
	},
	palm: false,
	mute: false,
	keys: false,
	vibrate: false,
	system: false,
	systemVolume: 0,
	ringerVolume: 0,
	ringTone: "??",
	debug: false,
	components: [
		{kind: "onyx.Toolbar", layoutKind: "FittableColumnsLayout",
		 classes: "onyx-toolbar", style: "line-height: 28px;", components: [
			 {content: "Sound & Ringtones"}, // This is hacky
			 {fit: true},
			 {content: "Mute"},
			 {name: "muteToggle",
			  kind: "onyx.ToggleButton",
			  onChange: "muteToggleChanged",
			  showing: "true",
			  style: "height: 31px;"}
		 ]},
		{kind: "Scroller", touch: true,	horizontal: "hidden", fit: true, components:[
			{name: "div", tag: "div", style: "padding: 35px 10% 35px 10%;", fit: true, components: [
				{kind: "enyo.FittableRows", components: [
					{name: "AudioList", kind: "onyx.Groupbox", layoutKind: "FittableRowsLayout", fit: true, components: [
						{kind: "onyx.GroupboxHeader", content: "Audio Settings"},

						{kind: "enyo.FittableColumns", classes: "group-item", components: [
							{style: "padding-top: 0px;", content: "Volume "},
							{kind: "onyx.TooltipDecorator", style: "padding-top: 2.5px;", fit: true, components: [
								{name: "volumeSlider", kind: "onyx.Slider",
								 onChanging: "volumeChange", onChange: "volumeChange"}
							]}
						]},
						{kind: "enyo.FittableColumns", classes: "group-item", style: "padding-bottom: 1px;", components: [
							{fit: true, content: "Keyboard Clicks"},
							{kind: "onyx.TooltipDecorator", components: [
								{name: "keyClicksToggle", kind: "onyx.ToggleButton", style: "float: right; ", onChange: "keyClicks"},
								{kind: "onyx.Tooltip", content: "Keyboard Clicks on/off"}
							]}
						]},
						{kind: "enyo.FittableColumns", classes: "group-item", components: [
							{name: "vibrate", fit: true, content: "Vibrate"},
							{kind: "onyx.TooltipDecorator", components: [
								{name: "vibrateToggle", kind: "onyx.ToggleButton", style: "float: right;", onChange: "vib"},
								{kind: "onyx.Tooltip", content: "Keyboard Vibrate on/off"}
							]}
						]},
						{kind: "enyo.FittableColumns", classes: "group-item", components: [
							{fit: true, content: "System Sounds"},
							{kind: "onyx.TooltipDecorator", components: [
								{name: "systemSoundToggle", kind: "onyx.ToggleButton", style: "float: right;", onChange: "systemSounds"},
								{kind: "onyx.Tooltip", content: "System sound  on/off"}
							]}
						]},
						{kind: "enyo.FittableColumns", classes: "group-item", components: [
							{content: "Ringer Volume ", style:  "padding-top: 0px;"},
							{kind: "onyx.TooltipDecorator", style: "padding-top: 2.5px;", fit: true, components: [
								{name:"ringerSlider", kind: "onyx.Slider", onChanging: "ringerVolumeChange"}
							]}
						]},
						{kind: "enyo.FittableColumns", classes: "group-item", style: "padding: 0px;", components: [
							{name: "ringerPicker", kind: "onyx.Button", fit: true,  content: "Ring tone Picker ", ontap: "ringerPopup"},
						]},
					]}
				]}
			]},
		]},
		{kind: "onyx.Toolbar", layoutKind: "FittableColumnsLayout", components: [
			{name: "Grabber", kind: "onyx.Grabber" }, // this is hacky
			{fit: true },
		]},
		{name: "ErrorPopup", kind: "onyx.Popup", classes: "error-popup", modal: true, style: "padding: 10px;", components: [
			{name: "ErrorMessage", content: "", style: "display: inline;"}
		]},
		{name: "ringPickerPopup", kind: "onyx.Popup", classes: "popup", centered: true, floating: true,	components: [
			{kind: "pickRingTones", style: "height: 100%; width: 100%;"},
		]},
		{name: "GetAudioStatus", kind: "enyo.LunaService", service: "luna://org.webosports.audio",
		 subscribe: true,
		 method: "getStatus", onComplete: "handleGetAudioStatusResponse"},
		{name: "SetMute", kind: "enyo.LunaService", service: "luna://org.webosports.audio",
		 method: "setMute"},
		{name: "SetVolume", kind: "enyo.LunaService", service: "luna://org.webosports.audio",
		 method: "setVolume"}
	],
	//Handlers
	create: function() {
		this.inherited(arguments);
		console.log ("Sound: created");

		if (!window.PalmSystem) {
			// If we're outside the webOS system add some entries for easier testing
			this.keys = true;
			this.vibrate = true;
			this.system = true;
			this.ringerVolume = 65;
			this.systemVolume = 45;
			this.showState();
			return;
		}
		this.palm = true;
		this.$.GetAudioStatus.send({});
	},
	reflow: function (inSender) {
		this.inherited(arguments);
		if (enyo.Panels.isScreenNarrow()) {
			this.$.Grabber.applyStyle("visibility", "hidden");
			this.$.div.setStyle("padding: 35px 5% 35px 5%;");
		} else {
			this.$.Grabber.applyStyle("visibility", "visible");
			this.$.div.setStyle("padding: 35px 10% 35px 10%;");
		}
	},
	showState: function() {
		this.$.muteToggle.setValue(this.mute);
		this.$.keyClicksToggle.setValue(this.keys);
		this.$.vibrateToggle.setValue(this.vibrate);
		this.$.systemSoundToggle.setValue(this.system);
		this.$.volumeSlider.setValue(this.systemVolume);
		this.$.ringerSlider.setValue(this.ringerVolume);
	},
	//Action Functions
	setMuteToggleValue: function(value) {
		this.$.muteToggle.setValue(value);
	},
	muteToggleChanged: function(inSender, inEvent) {
		this.mute = inEvent.value;
		if (this.palm) {
			this.$.SetMute.send({mute: this.mute});
		}
		this.doMuteChanged({mute: this.mute});
	},
	ringerPopup: function(inSender, inEvent) {
		this.$.ringPickerPopup.show();
		this.$.ringPickerPopup.setShowing(true);
	},
	closePopup: function(inSender, inEvent) {
		this.$.ringPickerPopup.hide();
	},
	tonepicked: function(inSender, inEvent) {
		this.$.ringerPicker.setContent("Ring tone -- " + inEvent);
	},
	keyClicks: function(inSender, inEvent) {
		this.keys = inEvent.value;
	},
	vib: function(inSender, inEvent) {
		this.vibrate = inEvent.value;
	},
	systemSounds: function(inSender, inEvent) {
		this.system = inEvent.value;
	},
	volumeChange: function(inSender, inEvent) {
		this.systemVolume = parseInt(inEvent.value, 10);
		if (this.palm) {
			this.$.SetVolume.send({volume: this.systemVolume});
		}
	},
	ringerVolumeChange: function(inSender, inEvent) {
		this.ringerVolume = inEvent.value;
	},
	//Service Callbacks
	handleGetAudioStatusResponse: function(inSender, inResponse) {
		if (inResponse.volume != undefined) {
			this.systemVolume = inResponse.volume;
			this.$.volumeSlider.silence();
			this.$.volumeSlider.setValue(this.systemVolume);
			this.$.volumeSlider.unsilence();
		}
		if (inResponse.mute != undefined) {
			this.mute = inResponse.mute;
			this.$.muteToggle.silence();
			this.$.muteToggle.setValue(this.mute);
			this.$.muteToggle.unsilence();
			this.doMuteChanged({mute: this.mute});
		}
	}
});
<commit_msg>Sounds: Get and set Mic Mute<commit_after>enyo.kind({
	name: "Sound",
	kind: "enyo.FittableRows",
	published: {},
	events: {
		onMuteChanged: ""
	},
	handlers: {
		onClose: "closePopup",
		onTone: "tonepicked"
	},
	palm: false,
	mute: false,
	keys: false,
	vibrate: false,
	micMute: false,
	system: false,
	systemVolume: 0,
	ringerVolume: 0,
	ringTone: "??",
	debug: false,
	components: [
		{kind: "onyx.Toolbar", layoutKind: "FittableColumnsLayout",
		 classes: "onyx-toolbar", style: "line-height: 28px;", components: [
			 {content: "Sound & Ringtones"}, // This is hacky
			 {fit: true},
			 {content: "Mute"},
			 {name: "muteToggle",
			  kind: "onyx.ToggleButton",
			  onChange: "muteToggleChanged",
			  showing: "true",
			  style: "height: 31px;"}
		 ]},
		{kind: "Scroller", touch: true,	horizontal: "hidden", fit: true, components:[
			{name: "div", tag: "div", style: "padding: 35px 10% 35px 10%;", fit: true, components: [
				{kind: "enyo.FittableRows", components: [
					{name: "AudioList", kind: "onyx.Groupbox", layoutKind: "FittableRowsLayout", fit: true, components: [
						{kind: "onyx.GroupboxHeader", content: "Audio Settings"},

						{kind: "enyo.FittableColumns", classes: "group-item", components: [
							{style: "padding-top: 0px;", content: "Volume "},
							{kind: "onyx.TooltipDecorator", style: "padding-top: 2.5px;", fit: true, components: [
								{name: "volumeSlider", kind: "onyx.Slider",
								 onChanging: "volumeChange", onChange: "volumeChange"}
							]}
						]},
						{kind: "enyo.FittableColumns", classes: "group-item", style: "padding-bottom: 1px;", components: [
							{fit: true, content: "Keyboard Clicks"},
							{kind: "onyx.TooltipDecorator", components: [
								{name: "keyClicksToggle", kind: "onyx.ToggleButton", style: "float: right; ", onChange: "keyClicks"},
								{kind: "onyx.Tooltip", content: "Keyboard Clicks on/off"}
							]}
						]},
						{kind: "enyo.FittableColumns", classes: "group-item", components: [
							{fit: true, content: "Vibrate"},
							{kind: "onyx.TooltipDecorator", components: [
								{name: "vibrateToggle", kind: "onyx.ToggleButton", style: "float: right;", onChange: "vib"},
								{kind: "onyx.Tooltip", content: "Keyboard Vibrate on/off"}
							]}
						]},
						{kind: "enyo.FittableColumns", classes: "group-item", components: [
							{fit: true, content: "Mic Mute"},
							{kind: "onyx.TooltipDecorator", components: [
								{name: "micMuteToggle", kind: "onyx.ToggleButton", style: "float: right;",
								 onChange: "micMuteToggleChanged"},
								{kind: "onyx.Tooltip", content: "Mic mute on/off"}
							]}
						]},
						{kind: "enyo.FittableColumns", classes: "group-item", components: [
							{fit: true, content: "System Sounds"},
							{kind: "onyx.TooltipDecorator", components: [
								{name: "systemSoundToggle", kind: "onyx.ToggleButton", style: "float: right;", onChange: "systemSounds"},
								{kind: "onyx.Tooltip", content: "System sound on/off"}
							]}
						]},
						{kind: "enyo.FittableColumns", classes: "group-item", components: [
							{content: "Ringer Volume ", style:  "padding-top: 0px;"},
							{kind: "onyx.TooltipDecorator", style: "padding-top: 2.5px;", fit: true, components: [
								{name:"ringerSlider", kind: "onyx.Slider", onChanging: "ringerVolumeChange"}
							]}
						]},
						{kind: "enyo.FittableColumns", classes: "group-item", style: "padding: 0px;", components: [
							{name: "ringerPicker", kind: "onyx.Button", fit: true,  content: "Ring tone Picker ", ontap: "ringerPopup"},
						]},
					]}
				]}
			]},
		]},
		{kind: "onyx.Toolbar", layoutKind: "FittableColumnsLayout", components: [
			{name: "Grabber", kind: "onyx.Grabber" }, // this is hacky
			{fit: true },
		]},
		{name: "ErrorPopup", kind: "onyx.Popup", classes: "error-popup", modal: true, style: "padding: 10px;", components: [
			{name: "ErrorMessage", content: "", style: "display: inline;"}
		]},
		{name: "ringPickerPopup", kind: "onyx.Popup", classes: "popup", centered: true, floating: true,	components: [
			{kind: "pickRingTones", style: "height: 100%; width: 100%;"},
		]},
		{name: "GetAudioStatus", kind: "enyo.LunaService", service: "luna://org.webosports.audio",
		 subscribe: true,
		 method: "getStatus", onComplete: "handleGetAudioStatusResponse"},
		{name: "SetMute", kind: "enyo.LunaService", service: "luna://org.webosports.audio",
		 method: "setMute"},
		{name: "SetVolume", kind: "enyo.LunaService", service: "luna://org.webosports.audio",
		 method: "setVolume"},
		{name: "SetMicMute", kind: "enyo.LunaService", service: "luna://org.webosports.audio",
		 method: "setMicMute"}
	],
	//Handlers
	create: function() {
		this.inherited(arguments);
		console.log ("Sound: created");

		if (!window.PalmSystem) {
			// If we're outside the webOS system add some entries for easier testing
			this.keys = true;
			this.vibrate = true;
			this.system = true;
			this.ringerVolume = 65;
			this.systemVolume = 45;
			this.showState();
			return;
		}
		this.palm = true;
		this.$.GetAudioStatus.send({});
	},
	reflow: function (inSender) {
		this.inherited(arguments);
		if (enyo.Panels.isScreenNarrow()) {
			this.$.Grabber.applyStyle("visibility", "hidden");
			this.$.div.setStyle("padding: 35px 5% 35px 5%;");
		} else {
			this.$.Grabber.applyStyle("visibility", "visible");
			this.$.div.setStyle("padding: 35px 10% 35px 10%;");
		}
	},
	showState: function() {
		this.$.muteToggle.setValue(this.mute);
		this.$.keyClicksToggle.setValue(this.keys);
		this.$.vibrateToggle.setValue(this.vibrate);
		this.$.systemSoundToggle.setValue(this.system);
		this.$.volumeSlider.setValue(this.systemVolume);
		this.$.ringerSlider.setValue(this.ringerVolume);
	},
	//Action Functions
	setMuteToggleValue: function(value) {
		this.$.muteToggle.setValue(value);
	},
	muteToggleChanged: function(inSender, inEvent) {
		this.mute = inEvent.value;
		if (this.palm) {
			this.$.SetMute.send({mute: this.mute});
		}
		this.doMuteChanged({mute: this.mute});
	},
	ringerPopup: function(inSender, inEvent) {
		this.$.ringPickerPopup.show();
		this.$.ringPickerPopup.setShowing(true);
	},
	closePopup: function(inSender, inEvent) {
		this.$.ringPickerPopup.hide();
	},
	tonepicked: function(inSender, inEvent) {
		this.$.ringerPicker.setContent("Ring tone -- " + inEvent);
	},
	keyClicks: function(inSender, inEvent) {
		this.keys = inEvent.value;
	},
	vib: function(inSender, inEvent) {
		this.vibrate = inEvent.value;
	},
	micMuteToggleChanged: function(inSender, inEvent) {
		this.micMute = inEvent.value;
		if (this.palm) {
			this.$.SetMicMute.send({micMute: this.micMute});
		}
	},
	systemSounds: function(inSender, inEvent) {
		this.system = inEvent.value;
	},
	volumeChange: function(inSender, inEvent) {
		this.systemVolume = parseInt(inEvent.value, 10);
		if (this.palm) {
			this.$.SetVolume.send({volume: this.systemVolume});
		}
	},
	ringerVolumeChange: function(inSender, inEvent) {
		this.ringerVolume = inEvent.value;
	},
	//Service Callbacks
	handleGetAudioStatusResponse: function(inSender, inResponse) {
		if (inResponse.volume != undefined) {
			this.systemVolume = inResponse.volume;
			this.$.volumeSlider.silence();
			this.$.volumeSlider.setValue(this.systemVolume);
			this.$.volumeSlider.unsilence();
		}
		if (inResponse.mute != undefined) {
			this.mute = inResponse.mute;
			this.$.muteToggle.silence();
			this.$.muteToggle.setValue(this.mute);
			this.$.muteToggle.unsilence();
			this.doMuteChanged({mute: this.mute});
		}
		if (inResponse.micMute != undefined) {
			this.micMute = inResponse.micMute;
			this.$.micMuteToggle.silence();
			this.$.micMuteToggle.setValue(this.micMute);
			this.$.micMuteToggle.unsilence();
		}
	}
});
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Card, CardHeader, CardText } from 'material-ui/Card';
import IconButton from 'material-ui/IconButton';
import Clear from 'material-ui/svg-icons/content/clear';
import {
  propTypes as routerPropTypes,
  withRouter,
} from 'react-router-dom';

import {
  setDisplayMode,
  setComposeState,
} from '../actions/ui';
import { postListing, loadListings, updateListing } from '../actions/listings';
import { postSeek, loadSeeks } from '../actions/seeks';
import ComposeForm from '../components/ComposeForm';
import SeekComposeForm from '../components/SeekComposeForm';
import RedirectToCas from '../components/RedirectToCas';

const overlayStyle = {
  position: 'fixed',
  bottom: '0',
  zIndex: '99',
  right: '5%',
  width: '40vw',
  minWidth: '16rem',
};

const showStyle = {};
const hideStyle = { display: 'none' };

class ComposeOverlay extends Component {
  static propTypes = {
    ...routerPropTypes,
    dispatch: PropTypes.func.isRequired,
    history: PropTypes.shape({
      push: PropTypes.func.isRequired,
    }).isRequired,
    user: PropTypes.shape({
      loggedIn: PropTypes.bool.isRequired,
    }).isRequired,
    currentUserLoading: PropTypes.bool.isRequired,
    mode: PropTypes.string.isRequired,
    // eslint-disable-next-line react/forbid-prop-types
    refreshQuery: PropTypes.object,
  };

  static defaultProps = {
    refreshQuery: { query: '' },
  }

  state = {
    mode: this.props.mode,
    expanded: true,
  }

  handleRequestClose = event => this.props.dispatch(setComposeState(false))

  handleSubmitListing = (data) => {
    this.props.dispatch(postListing({
      ...data,
      price: data.price ? Math.round(parseFloat(data.price) * 100) : 0,
    }));
    this.props.dispatch(loadListings());
    this.props.history.push('/listings');
    this.handleRequestClose();
  }

  handleSubmitSeek = (data) => {
    this.props.dispatch(postSeek({
      ...data,
      price: data.price ? Math.round(parseFloat(data.price) * 100) : 0,
    }));
    this.props.dispatch(loadSeeks());
    this.props.history.push('/seeks');
    this.handleRequestClose();
  }

  handleEditListing = (data) => {
    this.props.dispatch(updateListing({
      ...data,
      price: data.price ? Math.round(parseFloat(data.price) * 100) : 0,
    }, this.props.refreshQuery));
    this.handleRequestClose();
  }

  handleToggle = (event, isInputChecked) => {
    this.props.dispatch(setDisplayMode(isInputChecked ? 'seeks' : 'listings'));
  }

  handleExpandChange = (expanded) => {
    this.setState({ expanded });
  }

  render() {
    if (!this.props.currentUserLoading && !this.props.user.loggedIn) {
      return <RedirectToCas />;
    }

    return (

        <Card expanded={this.state.expanded} onExpandChange={this.handleExpandChange}>
          <CardHeader title={this.props.isEdit ? 'Edit' : 'Compose'} actAsExpander>
            <IconButton
              onTouchTap={this.handleRequestClose}
              style={{ float: 'right', marginTop: '-15px', marginRight: '-15px' }}
            >
              <Clear />
            </IconButton>
          </CardHeader>
          <CardText style={this.state.expanded ? showStyle : hideStyle}>
            { (this.state.mode === 'listings') ?
              <ComposeForm
                onSubmit={this.props.isEdit ? this.handleEditListing : this.handleSubmitListing}
                initialValues={this.props.isEdit && this.props.listing}
              /> :
              <SeekComposeForm onSubmit={this.handleSubmitSeek} />
            }
          </CardText>
        </Card>

    );
  }
}

const mapStateToProps = state => ({
  user: state.currentUser,
  form: state.form,
  mode: state.composeState.mode,
  currentUserLoading: state.currentUserLoading,
  isEdit: state.composeState.isEdit,
  listing: state.composeState.listing,
  seek: state.composeState.seek,
  refreshQuery: state.composeState.refreshQuery,
});

export default withRouter(connect(mapStateToProps)(ComposeOverlay));
<commit_msg>fix price convert between cents/dollars for display<commit_after>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Card, CardHeader, CardText } from 'material-ui/Card';
import IconButton from 'material-ui/IconButton';
import Clear from 'material-ui/svg-icons/content/clear';
import {
  propTypes as routerPropTypes,
  withRouter,
} from 'react-router-dom';

import {
  setDisplayMode,
  setComposeState,
} from '../actions/ui';
import { postListing, loadListings, updateListing } from '../actions/listings';
import { postSeek, loadSeeks } from '../actions/seeks';
import ComposeForm from '../components/ComposeForm';
import SeekComposeForm from '../components/SeekComposeForm';
import RedirectToCas from '../components/RedirectToCas';

const overlayStyle = {
  position: 'fixed',
  bottom: '0',
  zIndex: '99',
  right: '5%',
  width: '40vw',
  minWidth: '16rem',
};

const showStyle = {};
const hideStyle = { display: 'none' };

class ComposeOverlay extends Component {
  static propTypes = {
    ...routerPropTypes,
    dispatch: PropTypes.func.isRequired,
    history: PropTypes.shape({
      push: PropTypes.func.isRequired,
    }).isRequired,
    user: PropTypes.shape({
      loggedIn: PropTypes.bool.isRequired,
    }).isRequired,
    currentUserLoading: PropTypes.bool.isRequired,
    mode: PropTypes.string.isRequired,
    // eslint-disable-next-line react/forbid-prop-types
    refreshQuery: PropTypes.object,
  };

  static defaultProps = {
    refreshQuery: { query: '' },
  }

  state = {
    mode: this.props.mode,
    expanded: true,
  }

  handleRequestClose = event => this.props.dispatch(setComposeState(false))

  handleSubmitListing = (data) => {
    this.props.dispatch(postListing({
      ...data,
      price: data.price ? Math.round(parseFloat(data.price) * 100) : 0,
    }));
    this.props.dispatch(loadListings());
    this.props.history.push('/listings');
    this.handleRequestClose();
  }

  handleSubmitSeek = (data) => {
    this.props.dispatch(postSeek({
      ...data,
      price: data.price ? Math.round(parseFloat(data.price) * 100) : 0,
    }));
    this.props.dispatch(loadSeeks());
    this.props.history.push('/seeks');
    this.handleRequestClose();
  }

  handleEditListing = (data) => {
    this.props.dispatch(updateListing({
      ...data,
      price: data.price ? Math.round(parseFloat(data.price) * 100) : 0,
    }, this.props.refreshQuery));
    this.handleRequestClose();
  }

  handleToggle = (event, isInputChecked) => {
    this.props.dispatch(setDisplayMode(isInputChecked ? 'seeks' : 'listings'));
  }

  handleExpandChange = (expanded) => {
    this.setState({ expanded });
  }

  render() {
    if (!this.props.currentUserLoading && !this.props.user.loggedIn) {
      return <RedirectToCas />;
    }

    return (

        <Card expanded={this.state.expanded} onExpandChange={this.handleExpandChange}>
          <CardHeader title={this.props.isEdit ? 'Edit' : 'Compose'} actAsExpander>
            <IconButton
              onTouchTap={this.handleRequestClose}
              style={{ float: 'right', marginTop: '-15px', marginRight: '-15px' }}
            >
              <Clear />
            </IconButton>
          </CardHeader>
          <CardText style={this.state.expanded ? showStyle : hideStyle}>
            { (this.state.mode === 'listings') ?
              <ComposeForm
                onSubmit={this.props.isEdit ? this.handleEditListing : this.handleSubmitListing}
                initialValues={
                  this.props.isEdit ?
                  { ...this.props.listing, price: this.props.listing.price / 100 } : {}
                }
              /> :
                  <SeekComposeForm onSubmit={this.handleSubmitSeek} />
            }
          </CardText>
        </Card>

    );
  }
}

const mapStateToProps = state => ({
  user: state.currentUser,
  form: state.form,
  mode: state.composeState.mode,
  currentUserLoading: state.currentUserLoading,
  isEdit: state.composeState.isEdit,
  listing: state.composeState.listing,
  seek: state.composeState.seek,
  refreshQuery: state.composeState.refreshQuery,
});

export default withRouter(connect(mapStateToProps)(ComposeOverlay));
<|endoftext|>


<commit_before>Template.dashboard.helpers({
  'registrants': function () {
    return Registrants.find();
  }
});

Template.dashboard.events({
  'click #download-csv': function () {
    // Get current date for filename
    var dateNow = moment().format('YYYY-MM-DD');

    // Fetch all registrants
    registrantsJSON = Registrants.find().fetch();

    // Flatten registrant array fields to strings
    var arrayFields = ["foodPreference", "days"]
    _.each(arrayFields, flattenArray);

    // Convert boolean values into yes/no
    var booleanFields = ["linens", "firstTimeAttender"];
    _.each(booleanFields, booleanToYesNo);

    // Ensure that all optional fields have values for export
    var optionalFields = [
      "specialNeeds",
      "postalAddress",
      "telephone",
      "carbonTax",
      "registrantAffiliation",
      "grade"
    ];
    _.each(optionalFields, ensureFieldHasValue);

    var dateFields = ["createdAt"];
    _.each(dateFields, unixToISO);

    // Convert JSON to CSV
    // making sure to set field order
    var registrantsCSV = Papa.unparse({
      quotes: true,
      fields: [
        "last_name",
        "first_name",
        "age",
        "ageGroup",
        "grade",
        "registrantEmail",
        "postalAddress",
        "telephone",
        "registrantAffiliation",
        "firstTimeAttender",
        "registrationType",
        "accommodations",
        "days",
        "linens",
        "foodPreference",
        "specialNeeds",
        "carbonTax",
        "fee",
        "createdAt",
        "_id",
        "createdByEmail"
      ],
      data: registrantsJSON
    });

    // Add registrants to binary blob for downloading
    var registrantsBLOB = new Blob([registrantsCSV], {type: "text/csv"});

    // Download the file
    saveAs(registrantsBLOB, "pym2015-registrants-export-" + dateNow + ".csv");
  }
});

var flattenArray = function (field) {
  /*
  * Takes a registrant object
  * If value is present, flattens array to comma delimited string
  * Otherwise sets to empty string
  */
  _.each(registrantsJSON, function (registrant) {
    if (registrant[field]) {
      registrant[field] = registrant[field].join(", ");
    } else {
      registrant[field] = "";
    }
  });
};

var booleanToYesNo = function (field) {
  /*
  * Takes a registrant object
  * converts boolean field value into 'yes' 'no'
  */
  _.each(registrantsJSON, function (registrant) {
    if (registrant[field]) {
      registrant[field] = "yes";
    } else {
      registrant[field] = "no";
    }
  });
};

var ensureFieldHasValue = function (field) {
  /*
  * Takes a registrant object, looks at a given field
  * If the field is undefined, sets the value to an empty string
  */
  _.each(registrantsJSON, function (registrant) {
    // If the field is undefined
    if (!registrant[field]) {
      // Set the field to an empty string
      registrant[field] = "";
    }
  });
};

var unixToISO = function (field) {
  /*
  * Takes a registrant object
  * Converts a date field from Unix format to ISO 8601
  */
  _.each(registrantsJSON, function (registrant) {
    // Get the registration date, using moment
    var registrationDate = moment(registrant[field]);

    // Convert the registration date to ISO format
    var isoDate = registrationDate.format();

    // Update the registrant field with ISO date
    registrant[field] = isoDate;
  })
};
<commit_msg>Add template subscription; return registrations<commit_after>Template.dashboard.created = function () {
  // Get reference to template instance
  const instance = this;

  instance.subscribe('registrants');
};

Template.dashboard.helpers({
  'registrants': function () {
    return Registrants.find().fetch();
  }
});

Template.dashboard.events({
  'click #download-csv': function () {
    // Get current date for filename
    var dateNow = moment().format('YYYY-MM-DD');

    // Fetch all registrants
    registrantsJSON = Registrants.find().fetch();

    // Flatten registrant array fields to strings
    var arrayFields = ["foodPreference", "days"]
    _.each(arrayFields, flattenArray);

    // Convert boolean values into yes/no
    var booleanFields = ["linens", "firstTimeAttender"];
    _.each(booleanFields, booleanToYesNo);

    // Ensure that all optional fields have values for export
    var optionalFields = [
      "specialNeeds",
      "postalAddress",
      "telephone",
      "carbonTax",
      "registrantAffiliation",
      "grade"
    ];
    _.each(optionalFields, ensureFieldHasValue);

    var dateFields = ["createdAt"];
    _.each(dateFields, unixToISO);

    // Convert JSON to CSV
    // making sure to set field order
    var registrantsCSV = Papa.unparse({
      quotes: true,
      fields: [
        "last_name",
        "first_name",
        "age",
        "ageGroup",
        "grade",
        "registrantEmail",
        "postalAddress",
        "telephone",
        "registrantAffiliation",
        "firstTimeAttender",
        "registrationType",
        "accommodations",
        "days",
        "linens",
        "foodPreference",
        "specialNeeds",
        "carbonTax",
        "fee",
        "createdAt",
        "_id",
        "createdByEmail"
      ],
      data: registrantsJSON
    });

    // Add registrants to binary blob for downloading
    var registrantsBLOB = new Blob([registrantsCSV], {type: "text/csv"});

    // Download the file
    saveAs(registrantsBLOB, "pym2015-registrants-export-" + dateNow + ".csv");
  }
});

var flattenArray = function (field) {
  /*
  * Takes a registrant object
  * If value is present, flattens array to comma delimited string
  * Otherwise sets to empty string
  */
  _.each(registrantsJSON, function (registrant) {
    if (registrant[field]) {
      registrant[field] = registrant[field].join(", ");
    } else {
      registrant[field] = "";
    }
  });
};

var booleanToYesNo = function (field) {
  /*
  * Takes a registrant object
  * converts boolean field value into 'yes' 'no'
  */
  _.each(registrantsJSON, function (registrant) {
    if (registrant[field]) {
      registrant[field] = "yes";
    } else {
      registrant[field] = "no";
    }
  });
};

var ensureFieldHasValue = function (field) {
  /*
  * Takes a registrant object, looks at a given field
  * If the field is undefined, sets the value to an empty string
  */
  _.each(registrantsJSON, function (registrant) {
    // If the field is undefined
    if (!registrant[field]) {
      // Set the field to an empty string
      registrant[field] = "";
    }
  });
};

var unixToISO = function (field) {
  /*
  * Takes a registrant object
  * Converts a date field from Unix format to ISO 8601
  */
  _.each(registrantsJSON, function (registrant) {
    // Get the registration date, using moment
    var registrationDate = moment(registrant[field]);

    // Convert the registration date to ISO format
    var isoDate = registrationDate.format();

    // Update the registrant field with ISO date
    registrant[field] = isoDate;
  })
};
<|endoftext|>