<commit_before>import { LOG_DISABLE } from 'karma/lib/constants';

import webpackTestConfig from './webpack.test';

export default {
    port: 3001,
    webpackPort: 3002,
    colors: true,
    basePath: './',
    files: [
        'test/index.js'
    ],

    // https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
        'test/index.js': 'webpack'
    },

    // https://npmjs.org/browse/keyword/karma-adapter
    frameworks: [ 'mocha' ],
    webpack: webpackTestConfig,
    webpackMiddleware: {
        noInfo: true,
        quiet: true
    },

    // https://npmjs.org/browse/keyword/karma-reporter
    reporters: [ 'mocha', 'coverage' ],

    // https://github.com/karma-runner/karma-coverage/blob/master/docs/configuration.md
    coverageReporter: {
        dir: 'coverage/',
        subdir(browser) {
            return browser.toLowerCase().split(/[ /-]/)[0];
        },
        reporters: [
            {
                type: 'html'
            },
            {
                type: 'lcovonly', subdir: '.'
            },
            {
                type: 'text-summary', subdir: '.'
            }
        ]
    },

    logLevel: LOG_DISABLE,

    // customLaunchers: {
        // ChromeCustom: {
        //     base: 'Chrome',
        //     flags: [
        //         '--window-size=0,0',
        //         '--window-position=0,0'
        //     ]
        // }
    // },

    browsers: [ 'jsdom' ],

    browserNoActivityTimeout: 30000, // default 10 * 1000
    browserDisconnectTimeout: 10000, // default 2 * 1000
    browserDisconnectTolerance: 1 // default 0
};
<commit_msg>:lipstick: tweak karma config<commit_after>import { LOG_WARN } from 'karma/lib/constants';

import webpackTestConfig from './webpack.test';

export default {
    port: 3001,
    webpackPort: 3002,
    colors: true,
    basePath: './',
    files: [
        'test/index.js'
    ],
    // https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
        'test/index.js': 'webpack'
    },
    // https://npmjs.org/browse/keyword/karma-adapter
    frameworks: [ 'mocha' ],
    webpack: webpackTestConfig,
    webpackMiddleware: {
        noInfo: true,
        quiet: true
    },
    // https://npmjs.org/browse/keyword/karma-reporter
    reporters: [ 'mocha', 'coverage' ],
    // https://github.com/karma-runner/karma-coverage/blob/master/docs/configuration.md
    coverageReporter: {
        dir: 'coverage/',
        reporters: [
            {
                type: 'html'
            },
            {
                type: 'text-summary'
            },
            {
                type: 'lcovonly', subdir: '.'
            }
        ]
    },
    logLevel: LOG_WARN,
    browsers: [ 'jsdom' ],
    browserNoActivityTimeout: 30000, // default 10 * 1000
    browserDisconnectTimeout: 10000, // default 2 * 1000
    browserDisconnectTolerance: 1 // default 0
};
<|endoftext|>


<commit_before>/**
 * Unit test framework used with thali-tape.
 */

'use strict';

var util = require('util');
var TestFramework = require('./TestFramework');

var logger = console;

function UnitTestFramework(testConfig, _logger)
{
  if (_logger) {
    logger = _logger;
  }

  var configFile = "./UnitTestConfig";
  if (testConfig.configFile) {
    configFile = testConfig.configFile;
  }
  var unitTestConfig = require(configFile);

  UnitTestFramework.super_.call(this, testConfig, unitTestConfig, _logger);

  // Track which platforms we expect to be running on
  var self = this;
  self.runningTests = Object.keys(self.requiredDevices).filter(function (platform) {
    return self.requiredDevices[platform];
  });
}

util.inherits(UnitTestFramework, TestFramework);

UnitTestFramework.prototype.finishRun = function(devices, platform, tests, results) {

  // All devices have completed all their tests
  logger.info("Test run on %s complete", platform);

  // The whole point !! Log test results from the
  // server
  this.testReport(platform, tests, results);

  // Signal devices to quit
  devices.forEach(function(device) {
    device.socket.emit("complete");
  });

  // We're done running for this platform..
  this.runningTests = this.runningTests.filter(function(p) {
    return (p != platform);
  });

  // There may be other platforms still running
  if (this.runningTests.length == 0) {
    process.exit(0);
  }
}

UnitTestFramework.prototype.startTests = function(platform, tests) {

  var toComplete;
  var results = {};

  if (!tests) {
    // Default to all tests named by first device
    tests = this.devices[platform][0].tests;
  }

  // Copy arrays
  var _tests = tests.slice();
  var devices = this.devices[platform].slice();

  logger.info("Starting unit test run for platform: %s", platform);

  var self = this;
  function doTest(test, cb) {

    logger.info("Running on %s test: %s", platform, test);

    function emit(device, msg) {
      var retries = 10;

      var acknowledged = false;
      device.socket.once(util.format("%s_ok", msg), function() {
        acknowledged = true;
      });

      // Emit message every second until acknowledged
      function _emit() {
        if (!acknowledged) {
          console.log("emit: %s", msg);
          device.socket.emit(msg);
          if (--retries > 0) {
            setTimeout(_emit, 1000);
          } else {
            logger.error("test server: Device %s", device);
          }
        }
      }
      setTimeout(_emit, 0);
    };

    // Convenience: Move to next stage in test
    function doNext(stage) {
      // We need to have seen all devices report in before we
      // can proceed to the next stage
      if (--toComplete == 0) {
        toComplete = devices.length;
        devices.forEach(function(device) {
          // Tell each device to proceed to the next stage
          emit(device, stage + "_" + test);
        });
      }
    }

    // Add event handlers for each stage of a single test
    // Test proceed in the order shown below
    toComplete = devices.length;
    devices.forEach(function(device) {

      // The device has completed setup for this test
      device.socket.once("setup_complete", function(info) {
        doNext("start_test");
      });

      // The device has completed it's test
      device.socket.once("test_complete", function(result) {
        result = JSON.parse(result);
        if (!results[result.test])
          results[result.test] = result.success;
        else
          results[result.test] &= result.success;
        doNext('teardown');
      });

      // The device has completed teardown for this test
      device.socket.once("teardown_complete", function(info) {
        if (--toComplete == 0) {
          cb();
        }
      });

      // All server-side handlers for this test are now installed, let's go..
      emit(device, "setup_" + test);
    });
  }

  function nextTest() {
    // Pop the completed test off the list
    // and move to next test
    tests.shift();
    if (tests.length) {
      process.nextTick(function() {
        doTest(tests[0], nextTest);
      });
    } else {
      // ALL DONE !!
      self.finishRun(devices, platform, _tests, results);
    }
  }

  toComplete = devices.length;

  devices.forEach(function(device) {
    // Wait for devices to signal they've scheduled their
    // test runs and then begin
    device.socket.once("schedule_complete", function() {
      if (tests.length) {
        if (--toComplete == 0) {
          doTest(tests[0], nextTest);
        }
      } else {
        logger.warn("Schedule complete with no tests to run");
        self.finishRun(devices, platform, _tests, results);
      }
    });

    // Tell devices to set tests up to run in the order we supply
    device.socket.emit("schedule", JSON.stringify(tests));
  });
}

UnitTestFramework.prototype.testReport = function(platform, tests, results) {

  logger.info("\n\n-== UNIT TEST RESULTS ==-");

  var passed = 0;
  for (var test in results) {
    passed += results[test];
  }

  logger.info("PLATFORM: %s", platform);
  logger.info("RESULT: %s", passed == tests.length ? "PASS" : "FAIL");
  logger.info("%d of %d tests completed", Object.keys(results).length, tests.length);
  logger.info("%d/%d passed (%d failures)", passed, tests.length, tests.length - passed);

  logger.info("--- Test Details ---\n\n");

  for (test in results) {
    logger.info(test + " - " + (results[test] ? "pass" : "fail"));
  }

  logger.info("\n\n-== END ==-");
}

module.exports = UnitTestFramework;
<commit_msg>Don't create massive logs<commit_after>/**
 * Unit test framework used with thali-tape.
 */

'use strict';

var util = require('util');
var TestFramework = require('./TestFramework');

var logger = console;

function UnitTestFramework(testConfig, _logger)
{
  if (_logger) {
    logger = _logger;
  }

  var configFile = "./UnitTestConfig";
  if (testConfig.configFile) {
    configFile = testConfig.configFile;
  }
  var unitTestConfig = require(configFile);

  UnitTestFramework.super_.call(this, testConfig, unitTestConfig, _logger);

  // Track which platforms we expect to be running on
  var self = this;
  self.runningTests = Object.keys(self.requiredDevices).filter(function (platform) {
    return self.requiredDevices[platform];
  });
}

util.inherits(UnitTestFramework, TestFramework);

UnitTestFramework.prototype.finishRun = function(devices, platform, tests, results) {

  // All devices have completed all their tests
  logger.info("Test run on %s complete", platform);

  // The whole point !! Log test results from the
  // server
  this.testReport(platform, tests, results);

  // Signal devices to quit
  devices.forEach(function(device) {
    device.socket.emit("complete");
  });

  // We're done running for this platform..
  this.runningTests = this.runningTests.filter(function(p) {
    return (p != platform);
  });

  // There may be other platforms still running
  if (this.runningTests.length == 0) {
    process.exit(0);
  }
}

UnitTestFramework.prototype.startTests = function(platform, tests) {

  var toComplete;
  var results = {};

  if (!tests) {
    // Default to all tests named by first device
    tests = this.devices[platform][0].tests;
  }

  // Copy arrays
  var _tests = tests.slice();
  var devices = this.devices[platform].slice();

  logger.info("Starting unit test run for platform: %s", platform);

  var self = this;
  function doTest(test, cb) {

    logger.info("Running on %s test: %s", platform, test);

    function emit(device, msg) {
      var retries = 10;

      var acknowledged = false;
      device.socket.once(util.format("%s_ok", msg), function() {
        acknowledged = true;
      });

      // Emit message every second until acknowledged
      function _emit() {
        if (!acknowledged) {
          console.log("emit: %s", msg);
          device.socket.emit(msg);
          if (--retries > 0) {
            setTimeout(_emit, 1000);
          } else {
            logger.error("test server: Device %s", device.name);
          }
        }
      }
      setTimeout(_emit, 0);
    };

    // Convenience: Move to next stage in test
    function doNext(stage) {
      // We need to have seen all devices report in before we
      // can proceed to the next stage
      if (--toComplete == 0) {
        toComplete = devices.length;
        devices.forEach(function(device) {
          // Tell each device to proceed to the next stage
          emit(device, stage + "_" + test);
        });
      }
    }

    // Add event handlers for each stage of a single test
    // Test proceed in the order shown below
    toComplete = devices.length;
    devices.forEach(function(device) {

      // The device has completed setup for this test
      device.socket.once("setup_complete", function(info) {
        doNext("start_test");
      });

      // The device has completed it's test
      device.socket.once("test_complete", function(result) {
        result = JSON.parse(result);
        if (!results[result.test])
          results[result.test] = result.success;
        else
          results[result.test] &= result.success;
        doNext('teardown');
      });

      // The device has completed teardown for this test
      device.socket.once("teardown_complete", function(info) {
        if (--toComplete == 0) {
          cb();
        }
      });

      // All server-side handlers for this test are now installed, let's go..
      emit(device, "setup_" + test);
    });
  }

  function nextTest() {
    // Pop the completed test off the list
    // and move to next test
    tests.shift();
    if (tests.length) {
      process.nextTick(function() {
        doTest(tests[0], nextTest);
      });
    } else {
      // ALL DONE !!
      self.finishRun(devices, platform, _tests, results);
    }
  }

  toComplete = devices.length;

  devices.forEach(function(device) {
    // Wait for devices to signal they've scheduled their
    // test runs and then begin
    device.socket.once("schedule_complete", function() {
      if (tests.length) {
        if (--toComplete == 0) {
          doTest(tests[0], nextTest);
        }
      } else {
        logger.warn("Schedule complete with no tests to run");
        self.finishRun(devices, platform, _tests, results);
      }
    });

    // Tell devices to set tests up to run in the order we supply
    device.socket.emit("schedule", JSON.stringify(tests));
  });
}

UnitTestFramework.prototype.testReport = function(platform, tests, results) {

  logger.info("\n\n-== UNIT TEST RESULTS ==-");

  var passed = 0;
  for (var test in results) {
    passed += results[test];
  }

  logger.info("PLATFORM: %s", platform);
  logger.info("RESULT: %s", passed == tests.length ? "PASS" : "FAIL");
  logger.info("%d of %d tests completed", Object.keys(results).length, tests.length);
  logger.info("%d/%d passed (%d failures)", passed, tests.length, tests.length - passed);

  logger.info("--- Test Details ---\n\n");

  for (test in results) {
    logger.info(test + " - " + (results[test] ? "pass" : "fail"));
  }

  logger.info("\n\n-== END ==-");
}

module.exports = UnitTestFramework;
<|endoftext|>


<commit_before>var moment = require('moment')
var chai = require("chai")
var chaiAsPromised = require("chai-as-promised")

chai.use(chaiAsPromised)
var assert = chai.assert

var StandingOrder = artifacts.require('StandingOrder')
var StandingOrderFactory = artifacts.require('StandingOrderFactory')

const helper = require('./helper')

contract('StandingOrderFactory', function (accounts) {

    let owner = accounts[0]
    let payee = accounts[1]
    let factory

    before('obtain factory', function () {
        return StandingOrderFactory.deployed().then(function (_factory) {
            factory = _factory
        })
    })

    describe('Create StandingOrder', function () {

        it('should throw when trying to create an order with 0 interval', function () {
            let interval = 0
            let startTime = moment().add(1, 'days') // First payment due in one day
            let amount = 100000000
            let label = 'testorder'
            return assert.isRejected(
                helper.createOrder(factory, owner, payee, amount, interval, startTime, label),
                /out of gas/,
                'When factory creation throw, you always get "out-of-gas" error instead of invalid jump'
            )
        })

        it('should throw when trying to create an order with 0 amount', function () {
            let interval = 60 // one minute
            let startTime = moment().add(1, 'days') // First payment due in one day
            let amount = 0
            let label = 'testorder'
            return assert.isRejected(
                helper.createOrder(factory, owner, payee, amount, interval, startTime, label),
                /out of gas/,
                'When factory creation throw, you always get "out-of-gas" error instead of invalid jump'
            )
        })

        it('should throw when trying to create an order with empty label', function () {
            let interval = 60 // one minute
            let startTime = moment().add(1, 'days') // First payment due in one day
            let amount = 100000000
            let label = ''
            return assert.isRejected(
                helper.createOrder(factory, owner, payee, amount, interval, startTime, label),
                /out of gas/,
                'When factory creation throw, you always get "out-of-gas" error instead of invalid jump'
            )
        })

        it('should throw when trying to create an order with label shorter than 3 chars', function () {
            let interval = 60 // one minute
            let startTime = moment().add(1, 'days') // First payment due in one day
            let amount = 100000000
            let label = 'ab'
            return assert.isRejected(
                helper.createOrder(factory, owner, payee, amount, interval, startTime, label),
                /out of gas/,
                'When factory creation throw, you always get "out-of-gas" error instead of invalid jump'
            )
        })

        it('should create a standingOrder when valid parameters are used', function () {
            let interval = 60 // one minute
            let startTime = moment().add(1, 'days') // First payment due in one day
            let amount = 100000000
            let label = 'testorder'
            return assert.isFulfilled(helper.createOrder(factory, owner, payee, amount, interval, startTime, label))
        })

        it('should set correct owner', function() {
            let interval = 60 // one minute
            let startTime = moment().add(1, 'days') // First payment due in one day
            let amount = 100000000
            let label = 'testorder'
            return helper.createOrder(factory, owner, payee, amount, interval, startTime, label)
                .then(function (order) {
                    return order.owner()
                })
                .then(function (_owner) {
                    assert.equal(owner, _owner);
                })
        })

    })

})
<commit_msg>Make tests look for 'invalid opcode' instead of 'out of gas'.<commit_after>var moment = require('moment')
var chai = require("chai")
var chaiAsPromised = require("chai-as-promised")

chai.use(chaiAsPromised)
var assert = chai.assert

var StandingOrder = artifacts.require('StandingOrder')
var StandingOrderFactory = artifacts.require('StandingOrderFactory')

const helper = require('./helper')

contract('StandingOrderFactory', function (accounts) {

    let owner = accounts[0]
    let payee = accounts[1]
    let factory

    before('obtain factory', function () {
        return StandingOrderFactory.deployed().then(function (_factory) {
            factory = _factory
        })
    })

    describe('Create StandingOrder', function () {

        it('should throw when trying to create an order with 0 interval', function () {
            let interval = 0
            let startTime = moment().add(1, 'days') // First payment due in one day
            let amount = 100000000
            let label = 'testorder'
            return assert.isRejected(
                helper.createOrder(factory, owner, payee, amount, interval, startTime, label),
                /*/out of gas/,*/
                /invalid opcode/,
                'When factory creation throw, you always get "out-of-gas" error instead of invalid jump'
            )
        })

        it('should throw when trying to create an order with 0 amount', function () {
            let interval = 60 // one minute
            let startTime = moment().add(1, 'days') // First payment due in one day
            let amount = 0
            let label = 'testorder'
            return assert.isRejected(
                helper.createOrder(factory, owner, payee, amount, interval, startTime, label),
                /*/out of gas/,*/
                /invalid opcode/,
                'When factory creation throw, you always get "out-of-gas" error instead of invalid jump'
            )
        })

        it('should throw when trying to create an order with empty label', function () {
            let interval = 60 // one minute
            let startTime = moment().add(1, 'days') // First payment due in one day
            let amount = 100000000
            let label = ''
            return assert.isRejected(
                helper.createOrder(factory, owner, payee, amount, interval, startTime, label),
                /*/out of gas/,*/
                /invalid opcode/,
                'When factory creation throw, you always get "out-of-gas" error instead of invalid jump'
            )
        })

        it('should throw when trying to create an order with label shorter than 3 chars', function () {
            let interval = 60 // one minute
            let startTime = moment().add(1, 'days') // First payment due in one day
            let amount = 100000000
            let label = 'ab'
            return assert.isRejected(
                helper.createOrder(factory, owner, payee, amount, interval, startTime, label),
                /*/out of gas/,*/
                /invalid opcode/,
                'When factory creation throw, you always get "out-of-gas" error instead of invalid jump'
            )
        })

        it('should create a standingOrder when valid parameters are used', function () {
            let interval = 60 // one minute
            let startTime = moment().add(1, 'days') // First payment due in one day
            let amount = 100000000
            let label = 'testorder'
            return assert.isFulfilled(helper.createOrder(factory, owner, payee, amount, interval, startTime, label))
        })

        it('should set correct owner', function() {
            let interval = 60 // one minute
            let startTime = moment().add(1, 'days') // First payment due in one day
            let amount = 100000000
            let label = 'testorder'
            return helper.createOrder(factory, owner, payee, amount, interval, startTime, label)
                .then(function (order) {
                    return order.owner()
                })
                .then(function (_owner) {
                    assert.equal(owner, _owner);
                })
        })

    })

})
<|endoftext|>


<commit_before>// @flow

import React from 'react'
import {Emoji} from 'emoji-mart'

// Just the single set we use
import emojiSet from 'emoji-datasource/sheet_apple_64.png'

import type {Props} from 'emoji-mart'

const backgroundImageFn = (set: string, sheetSize: string) => emojiSet

// Size 0 is cause we want the native emoji for copy/paste and not for rendering
const EmojiWrapper = (props: Props) => {
  const emojiText = String(props.children)
  return (
    <Emoji {...props} emoji={emojiText} backgroundImageFn={backgroundImageFn}>
      <Emoji emoji={emojiText} size={0} native={true} />
    </Emoji>
  )
}

export {backgroundImageFn}

export default EmojiWrapper
<commit_msg>Fix props import<commit_after>// @flow

import React from 'react'
import {Emoji} from 'emoji-mart'

// Just the single set we use
import emojiSet from 'emoji-datasource/sheet_apple_64.png'

import type {Props} from './emoji'

const backgroundImageFn = (set: string, sheetSize: string) => emojiSet

// Size 0 is cause we want the native emoji for copy/paste and not for rendering
const EmojiWrapper = (props: Props) => {
  const emojiText = String(props.children)
  return (
    <Emoji {...props} emoji={emojiText} backgroundImageFn={backgroundImageFn}>
      <Emoji emoji={emojiText} size={0} native={true} />
    </Emoji>
  )
}

export {backgroundImageFn}

export default EmojiWrapper
<|endoftext|>


<commit_before>import React, {Component} from 'react'
import {globalStyles, globalColors} from '../styles/style-guide'
import {autoResize} from '../../desktop/renderer/remote-component-helper'
import {Button, FormWithCheckbox, Header, Text} from '../common-adapters'

export default class PinentryRender extends Component {
  constructor (props) {
    super(props)

    this.state = {
      passphrase: '',
      features: {},
      showTyping: false
    }
    for (const feature in this.props.features) {
      this.state.features[feature] = this.props.features[feature].defaultValue

      if (feature === 'showTyping') {
        this.state.showTyping = this.props.features[feature].defaultValue
      }
    }
  }

  onCheck (feature, checked) {
    this.setState({
      features: {
        ...this.state.features,
        [feature]: checked
      }
    })

    if (feature === 'showTyping') {
      this.setState({showTyping: checked})
    }
  }

  componentDidMount () {
    autoResize()
  }

  render () {
    const submitPassphrase = () => this.props.onSubmit(this.state.passphrase, this.state.features)

    const inputProps = {
      floatingLabelText: 'Passphrase',
      style: {marginBottom: 0},
      onChange: event => this.setState({passphrase: event.target.value}),
      onEnterKeyDown: () => submitPassphrase(),
      type: this.state.showTyping ? 'passwordVisible' : 'password',
      errorText: this.props.retryLabel,
      autoFocus: true
    }

    const checkboxProps = Object.keys(this.props.features).map(feature => {
      return ({
        label: this.props.features[feature].label,
        checked: this.state.features[feature],
        key: feature,
        name: feature,
        style: styles.checkbox,
        onCheck: checked => this.onCheck(feature, checked)
      })
    })

    return (

         this.props.onCancel()} />

          <Text type='Body'>{this.props.prompt}</Text>

          <FormWithCheckbox
            style={{alignSelf: 'stretch'}}
            inputProps={inputProps}
            checkboxContainerStyle={{paddingLeft: 60, paddingRight: 60}}
            checkboxesProps={checkboxProps}
          />

          <Button type='Primary' label='Continue' onClick={submitPassphrase} disabled={!this.state.passphrase} />

    )
  }
}

PinentryRender.propTypes = {
  onSubmit: React.PropTypes.func.isRequired,
  onCancel: React.PropTypes.func.isRequired,
  features: React.PropTypes.object.isRequired,
  prompt: React.PropTypes.string.isRequired,
  retryLabel: React.PropTypes.string.isRequired,
  cancelLabel: React.PropTypes.string,
  submitLabel: React.PropTypes.string,
  windowTitle: React.PropTypes.string.isRequired
}

const styles = {
  container: {
    ...globalStyles.flexBoxColumn,
    backgroundColor: globalColors.white
  },
  checkbox: {
    ...globalStyles.topMost,
    color: globalColors.black100,
    marginLeft: 10
  }
}
<commit_msg>Fix missing black100 color reference<commit_after>import React, {Component} from 'react'
import {globalStyles, globalColors} from '../styles/style-guide'
import {autoResize} from '../../desktop/renderer/remote-component-helper'
import {Button, FormWithCheckbox, Header, Text} from '../common-adapters'

export default class PinentryRender extends Component {
  constructor (props) {
    super(props)

    this.state = {
      passphrase: '',
      features: {},
      showTyping: false
    }
    for (const feature in this.props.features) {
      this.state.features[feature] = this.props.features[feature].defaultValue

      if (feature === 'showTyping') {
        this.state.showTyping = this.props.features[feature].defaultValue
      }
    }
  }

  onCheck (feature, checked) {
    this.setState({
      features: {
        ...this.state.features,
        [feature]: checked
      }
    })

    if (feature === 'showTyping') {
      this.setState({showTyping: checked})
    }
  }

  componentDidMount () {
    autoResize()
  }

  render () {
    const submitPassphrase = () => this.props.onSubmit(this.state.passphrase, this.state.features)

    const inputProps = {
      floatingLabelText: 'Passphrase',
      style: {marginBottom: 0},
      onChange: event => this.setState({passphrase: event.target.value}),
      onEnterKeyDown: () => submitPassphrase(),
      type: this.state.showTyping ? 'passwordVisible' : 'password',
      errorText: this.props.retryLabel,
      autoFocus: true
    }

    const checkboxProps = Object.keys(this.props.features).map(feature => {
      return ({
        label: this.props.features[feature].label,
        checked: this.state.features[feature],
        key: feature,
        name: feature,
        style: styles.checkbox,
        onCheck: checked => this.onCheck(feature, checked)
      })
    })

    return (

         this.props.onCancel()} />

          <Text type='Body'>{this.props.prompt}</Text>

          <FormWithCheckbox
            style={{alignSelf: 'stretch'}}
            inputProps={inputProps}
            checkboxContainerStyle={{paddingLeft: 60, paddingRight: 60}}
            checkboxesProps={checkboxProps}
          />

          <Button type='Primary' label='Continue' onClick={submitPassphrase} disabled={!this.state.passphrase} />

    )
  }
}

PinentryRender.propTypes = {
  onSubmit: React.PropTypes.func.isRequired,
  onCancel: React.PropTypes.func.isRequired,
  features: React.PropTypes.object.isRequired,
  prompt: React.PropTypes.string.isRequired,
  retryLabel: React.PropTypes.string.isRequired,
  cancelLabel: React.PropTypes.string,
  submitLabel: React.PropTypes.string,
  windowTitle: React.PropTypes.string.isRequired
}

const styles = {
  container: {
    ...globalStyles.flexBoxColumn,
    backgroundColor: globalColors.white
  },
  checkbox: {
    ...globalStyles.topMost,
    color: globalColors.black,
    marginLeft: 10
  }
}
<|endoftext|>


<commit_before>/*
 * Based on comments by @runanet and @coomsie
 * https://github.com/CloudMade/Leaflet/issues/386
 *
 * Wrapping function is needed to preserve L.Marker.update function
 */
(function () {
    var _old__setPos = L.Marker.prototype._setPos;
    L.Marker.include({
        _updateImg: function(i, a, s) {
            a = L.point(s).divideBy(2)._subtract(L.point(a));
            var transform = '';
            transform += ' translate(' + -a.x + 'px, ' + -a.y + 'px)';
            transform += ' rotate(' + this.options.iconAngle + 'deg)';
            transform += ' translate(' + a.x + 'px, ' + a.y + 'px)';
            i.style[L.DomUtil.TRANSFORM] += transform;
        },

        setIconAngle: function (iconAngle) {
            this.options.iconAngle = iconAngle;

            if (this._map) this.update();
        },

        _setPos: function (pos) {
            if (this._icon) {
                this._icon.style[L.DomUtil.TRANSFORM] = "";
            }
            if (this._shadow) {
                this._shadow.style[L.DomUtil.TRANSFORM] = "";
            }

            _old__setPos.apply(this,[pos]);

            if (this.options.iconAngle) {
                var a = this.options.icon.options.iconAnchor;
                var s = this.options.icon.options.iconSize;
                var i;
                if (this._icon) {
                    i = this._icon;
                    this._updateImg(i, a, s);
                }

                if (this._shadow) {
                    // Rotate around the icons anchor.
                    s = this.options.icon.options.shadowSize;
                    i = this._shadow;
                    this._updateImg(i, a, s);
                }

            }    }
    });
}());
<commit_msg>fix indentation from #70<commit_after>/*
 * Based on comments by @runanet and @coomsie
 * https://github.com/CloudMade/Leaflet/issues/386
 *
 * Wrapping function is needed to preserve L.Marker.update function
 */
(function () {
	var _old__setPos = L.Marker.prototype._setPos;
	L.Marker.include({
		_updateImg: function(i, a, s) {
			a = L.point(s).divideBy(2)._subtract(L.point(a));
			var transform = '';
			transform += ' translate(' + -a.x + 'px, ' + -a.y + 'px)';
			transform += ' rotate(' + this.options.iconAngle + 'deg)';
			transform += ' translate(' + a.x + 'px, ' + a.y + 'px)';
			i.style[L.DomUtil.TRANSFORM] += transform;
		},

		setIconAngle: function (iconAngle) {
			this.options.iconAngle = iconAngle;
			if (this._map)
				this.update();
		},

		_setPos: function (pos) {
			if (this._icon)
				this._icon.style[L.DomUtil.TRANSFORM] = "";
			if (this._shadow)
				this._shadow.style[L.DomUtil.TRANSFORM] = "";

			_old__setPos.apply(this,[pos]);

			if (this.options.iconAngle) {
				var a = this.options.icon.options.iconAnchor;
				var s = this.options.icon.options.iconSize;
				var i;
				if (this._icon) {
					i = this._icon;
					this._updateImg(i, a, s);
				}
				if (this._shadow) {
					// Rotate around the icons anchor.
					s = this.options.icon.options.shadowSize;
					i = this._shadow;
					this._updateImg(i, a, s);
				}
			}
		}
	});
}());
<|endoftext|>


<commit_before><commit_msg>Library added on right place<commit_after><|endoftext|>


<commit_before>define(['sprd/data/SprdModel', 'sprd/entity/Person', 'sprd/model/Country'], function (SprdModel, Person, Country) {
	return SprdModel.inherit('sprd.model.Address', {
        defaults: {
            person: null,
            street: '',
            streetAnnex: '',
            houseNumber: '',
            zipCode: '',
            city: '',
            country: '',
            email: '',
            phone: '',
            fax: ''
        },
        schema: {
            person: Person,
            street: String,
            streetAnnex: String,
            houseNumber: String,
            zipCode: String,
            city: String,
            country: Country,
            email: String,
            phone: String,
            fax: String
        }
	});
});<commit_msg>Extended Address model with companyName and tradeRegister.<commit_after>define(['sprd/data/SprdModel', 'sprd/entity/Person', 'sprd/model/Country'], function (SprdModel, Person, Country) {
	return SprdModel.inherit('sprd.model.Address', {
        defaults: {
            person: null,
            companyName: '',
            tradeRegister: '',
            street: '',
            streetAnnex: '',
            houseNumber: '',
            zipCode: '',
            city: '',
            country: '',
            email: '',
            phone: '',
            fax: ''
        },
        schema: {
            person: Person,
            companyName: String,
            tradeRegister: String,
            street: String,
            streetAnnex: String,
            houseNumber: String,
            zipCode: String,
            city: String,
            country: Country,
            email: String,
            phone: String,
            fax: String
        }
	});
});<|endoftext|>


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

var assert = require("assert"),
    vows = require("vows"),
    Step = require("step"),
    _ = require("underscore"),
    http = require("http"),
    OAuth = require("oauth-evanp").OAuth,
    httputil = require("./lib/http"),
    oauthutil = require("./lib/oauth"),
    setupApp = oauthutil.setupApp,
    newClient = oauthutil.newClient,
    register = oauthutil.register,
    accessToken = oauthutil.accessToken,
    newCredentials = oauthutil.newCredentials,
    newPair = oauthutil.newPair;

var makeCred = function(cl, pair) {
    return {
        consumer_key: cl.client_id,
        consumer_secret: cl.client_secret,
        token: pair.token,
        token_secret: pair.token_secret
    };
};

var suite = vows.describe("Test shares items in favorites stream");

var haveShares = function(feed) {
    assert.include(feed, "items");
    assert.isArray(feed.items);
    assert.lengthOf(feed.items, 20);
    _.each(feed.items, function(object) {
        assert.isObject(object);
        assert.include(object, "shares");
        assert.isObject(object.shares);
        assert.include(object.shares, "totalItems");
        assert.include(object.shares, "url");
    });
};

var correctShares = function(feed) {
    assert.include(feed, "items");
    assert.isArray(feed.items);
    assert.lengthOf(feed.items, 20);
    _.each(feed.items, function(object) {
        assert.isObject(object);
        assert.include(object, "shares");
        assert.isObject(object.shares);
        assert.include(object.shares, "totalItems");
        if (object.secretNumber % 2) {
            assert.equal(object.shares.totalItems, 1);
        } else {
            assert.equal(object.shares.totalItems, 0);
        }
    });
};

var haveShared = function(feed) {
    assert.include(feed, "items");
    assert.isArray(feed.items);
    assert.lengthOf(feed.items, 20);
    _.each(feed.items, function(object) {
        assert.isObject(object);
        assert.include(object, "pump_io");
        assert.isObject(object.pump_io);
        assert.include(object.pump_io, "shared");
        assert.isBoolean(object.pump_io.shared);
    });
};

var noShared = function(feed) {
    assert.include(feed, "items");
    assert.isArray(feed.items);
    assert.lengthOf(feed.items, 20);
    _.each(feed.items, function(object) {
        assert.isObject(object);
        assert.isFalse(_.has(object, "pump_io") && _.has(object.pump_io, "shared"));
    });
};

var sharedIs = function(val) {
    return function(feed) {
        assert.include(feed, "items");
        assert.isArray(feed.items);
        assert.lengthOf(feed.items, 20);
        _.each(feed.items, function(object) {
            assert.isObject(object);
            assert.include(object, "pump_io");
            assert.isObject(object.pump_io);
            assert.include(object.pump_io, "shared");
            if (object.secretNumber % 2) {
                assert.equal(object.pump_io.shared, val);
            } else {
                assert.equal(object.pump_io.shared, false);
            }
        });
    };
};

var sameUser = function(url, objects) {

    var ctx = {
        topic: function(pair0, pair1, cl) {
            var callback = this.callback,
                cred = makeCred(cl, pair0);

            Step(
                function() {
                    httputil.getJSON(url, cred, this);
                },
                function(err, feed, response) {
                    if (err) {
                        callback(err, null);
                    } else {
                        callback(null, feed);
                    }
                }
            );
        },
        "it works": function(err, feed) {
            assert.ifError(err);
            assert.isObject(feed);
        },
        "and we examine the feed": {
            topic: function(feed) {
                return feed;
            },
            "all items have shares": haveShares,
            "some items have non-empty shares": correctShares,
            "all items have the shared flag": haveShared,
            "all items have shared = false": sharedIs(false)
        }
    };

    return ctx;
};

var justClient = function(url, objects) {

    var ctx = {
        topic: function(pair0, pair1, cl) {
            var callback = this.callback,
                cred =  {
                    consumer_key: cl.client_id,
                    consumer_secret: cl.client_secret
                };

            Step(
                function() {
                    httputil.getJSON(url, cred, this);
                },
                function(err, feed, response) {
                    if (err) {
                        callback(err, null);
                    } else {
                        callback(null, feed);
                    }
                }
            );
        },
        "it works": function(err, feed) {
            assert.ifError(err);
            assert.isObject(feed);
        },
        "and we examine the feed": {
            topic: function(feed) {
                return feed;
            },
            "all items have shares": haveShares,
            "some items have non-empty shares": correctShares,
            "no items have the shared flag": noShared
        }
    };

    return ctx;
};

var otherUser = function(url, objects) {

    var ctx = {
        topic: function(pair0, pair1, cl) {
            var callback = this.callback,
                cred = makeCred(cl, pair1);

            Step(
                function() {
                    httputil.getJSON(url, cred, this);
                },
                function(err, feed, response) {
                    if (err) {
                        callback(err, null);
                    } else {
                        callback(null, feed);
                    }
                }
            );
        },
        "it works": function(err, feed) {
            assert.ifError(err);
            assert.isObject(feed);
        },
        "and we examine the feed": {
            topic: function(feed) {
                return feed;
            },
            "all items have shares": haveShares,
            "some items have non-empty shares": correctShares,
            "all items have the shared flag": haveShared,
            "all items have correct shared value": sharedIs(true)
        }
    };

    return ctx;
};

// A batch to test favoriting/unfavoriting objects

suite.addBatch({
    "When we set up the app": {
        topic: function() {
            setupApp(this.callback);
        },
        teardown: function(app) {
            if (app && app.close) {
                app.close();
            }
        },
        "it works": function(err, app) {
            assert.ifError(err);
        },
        "and we register a client": {
            topic: function() {
                newClient(this.callback);
            },
            "it works": function(err, cl) {
                assert.ifError(err);
                assert.isObject(cl);
            },
            "and we register two users": {
                topic: function(cl) {
                    var callback = this.callback;

                    Step(
                        function() {
                            newPair(cl, "click", "don't drive like my brother", this.parallel());
                            newPair(cl, "clack", "don't drive like *my* brother", this.parallel());
                        },
                        callback
                    );
                },
                "it works": function(err, pair0, pair1) {
                    assert.ifError(err);
                    assert.isObject(pair0);
                    assert.isObject(pair1);
                },
                "and the first one posts a bunch of notes and the second one shares every other one": {
                    topic: function(pair0, pair1, cl) {
                        var callback = this.callback,
                            cred0 = makeCred(cl, pair0),
                            cred1 = makeCred(cl, pair1),
                            url0 = "http://localhost:4815/api/user/click/feed",
                            url1 = "http://localhost:4815/api/user/clack/feed",
                            posts;

                        Step(
                            function() {
                                var group = this.group();
                                _.times(20, function(i) {
                                    var act = {
                                        to: [pair0.user.profile],
                                        cc: [{objectType: "collection",
                                              id: "http://activityschema.org/collection/public"}],
                                        verb: "post",
                                        object: {
                                            objectType: "note",
                                            secretNumber: i,
                                            content: "Our fair city " + i
                                        }
                                    };
                                    httputil.postJSON(url0, cred0, act, group());
                                });
                            },
                            function(err, results) {
                                var group = this.group();
                                if (err) throw err;
                                posts = results;
                                _.each(posts, function(post, i) {
                                    var act = {
                                        verb: "like",
                                        object: post.object
                                    };
                                    httputil.postJSON(url0, cred0, act, group());
                                });
                            },
                            function(err, results) {
                                var group = this.group();
                                if (err) throw err;
                                _.each(posts, function(post, i) {
                                    if (i % 2) {
                                        var act = {
                                            verb: "share",
                                            object: post.object
                                        };
                                        httputil.postJSON(url1, cred1, act, group());
                                    }
                                });
                            },
                            function(err, shares) {
                                if (err) {
                                    callback(err);
                                } else {
                                    callback(null);
                                }
                            }
                        );
                    },
                    "it works": function(err) {
                        assert.ifError(err);
                    },
                    "and we check their major inbox with same user credentials":
                    sameUser("http://localhost:4815/api/user/click/favorites"),
                    "and we check their major feed with client credentials":
                    justClient("http://localhost:4815/api/user/click/favorites"),
                    "and we check the first user's major feed with different user credentials":
                    otherUser("http://localhost:4815/api/user/click/favorites")
                }
            }
        }
    }
});

suite["export"](module);
<commit_msg>Remove use of accessToken() from favorites-stream-shares-test<commit_after>// major-stream-replies-test.js
//
// Test that objects have "replies" stream in */major streams
//
// Copyright 2012, E14N https://e14n.com/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var assert = require("assert"),
    vows = require("vows"),
    Step = require("step"),
    _ = require("underscore"),
    http = require("http"),
    OAuth = require("oauth-evanp").OAuth,
    httputil = require("./lib/http"),
    oauthutil = require("./lib/oauth"),
    setupApp = oauthutil.setupApp,
    newClient = oauthutil.newClient,
    register = oauthutil.register,
    newCredentials = oauthutil.newCredentials,
    newPair = oauthutil.newPair;

var makeCred = function(cl, pair) {
    return {
        consumer_key: cl.client_id,
        consumer_secret: cl.client_secret,
        token: pair.token,
        token_secret: pair.token_secret
    };
};

var suite = vows.describe("Test shares items in favorites stream");

var haveShares = function(feed) {
    assert.include(feed, "items");
    assert.isArray(feed.items);
    assert.lengthOf(feed.items, 20);
    _.each(feed.items, function(object) {
        assert.isObject(object);
        assert.include(object, "shares");
        assert.isObject(object.shares);
        assert.include(object.shares, "totalItems");
        assert.include(object.shares, "url");
    });
};

var correctShares = function(feed) {
    assert.include(feed, "items");
    assert.isArray(feed.items);
    assert.lengthOf(feed.items, 20);
    _.each(feed.items, function(object) {
        assert.isObject(object);
        assert.include(object, "shares");
        assert.isObject(object.shares);
        assert.include(object.shares, "totalItems");
        if (object.secretNumber % 2) {
            assert.equal(object.shares.totalItems, 1);
        } else {
            assert.equal(object.shares.totalItems, 0);
        }
    });
};

var haveShared = function(feed) {
    assert.include(feed, "items");
    assert.isArray(feed.items);
    assert.lengthOf(feed.items, 20);
    _.each(feed.items, function(object) {
        assert.isObject(object);
        assert.include(object, "pump_io");
        assert.isObject(object.pump_io);
        assert.include(object.pump_io, "shared");
        assert.isBoolean(object.pump_io.shared);
    });
};

var noShared = function(feed) {
    assert.include(feed, "items");
    assert.isArray(feed.items);
    assert.lengthOf(feed.items, 20);
    _.each(feed.items, function(object) {
        assert.isObject(object);
        assert.isFalse(_.has(object, "pump_io") && _.has(object.pump_io, "shared"));
    });
};

var sharedIs = function(val) {
    return function(feed) {
        assert.include(feed, "items");
        assert.isArray(feed.items);
        assert.lengthOf(feed.items, 20);
        _.each(feed.items, function(object) {
            assert.isObject(object);
            assert.include(object, "pump_io");
            assert.isObject(object.pump_io);
            assert.include(object.pump_io, "shared");
            if (object.secretNumber % 2) {
                assert.equal(object.pump_io.shared, val);
            } else {
                assert.equal(object.pump_io.shared, false);
            }
        });
    };
};

var sameUser = function(url, objects) {

    var ctx = {
        topic: function(pair0, pair1, cl) {
            var callback = this.callback,
                cred = makeCred(cl, pair0);

            Step(
                function() {
                    httputil.getJSON(url, cred, this);
                },
                function(err, feed, response) {
                    if (err) {
                        callback(err, null);
                    } else {
                        callback(null, feed);
                    }
                }
            );
        },
        "it works": function(err, feed) {
            assert.ifError(err);
            assert.isObject(feed);
        },
        "and we examine the feed": {
            topic: function(feed) {
                return feed;
            },
            "all items have shares": haveShares,
            "some items have non-empty shares": correctShares,
            "all items have the shared flag": haveShared,
            "all items have shared = false": sharedIs(false)
        }
    };

    return ctx;
};

var justClient = function(url, objects) {

    var ctx = {
        topic: function(pair0, pair1, cl) {
            var callback = this.callback,
                cred =  {
                    consumer_key: cl.client_id,
                    consumer_secret: cl.client_secret
                };

            Step(
                function() {
                    httputil.getJSON(url, cred, this);
                },
                function(err, feed, response) {
                    if (err) {
                        callback(err, null);
                    } else {
                        callback(null, feed);
                    }
                }
            );
        },
        "it works": function(err, feed) {
            assert.ifError(err);
            assert.isObject(feed);
        },
        "and we examine the feed": {
            topic: function(feed) {
                return feed;
            },
            "all items have shares": haveShares,
            "some items have non-empty shares": correctShares,
            "no items have the shared flag": noShared
        }
    };

    return ctx;
};

var otherUser = function(url, objects) {

    var ctx = {
        topic: function(pair0, pair1, cl) {
            var callback = this.callback,
                cred = makeCred(cl, pair1);

            Step(
                function() {
                    httputil.getJSON(url, cred, this);
                },
                function(err, feed, response) {
                    if (err) {
                        callback(err, null);
                    } else {
                        callback(null, feed);
                    }
                }
            );
        },
        "it works": function(err, feed) {
            assert.ifError(err);
            assert.isObject(feed);
        },
        "and we examine the feed": {
            topic: function(feed) {
                return feed;
            },
            "all items have shares": haveShares,
            "some items have non-empty shares": correctShares,
            "all items have the shared flag": haveShared,
            "all items have correct shared value": sharedIs(true)
        }
    };

    return ctx;
};

// A batch to test favoriting/unfavoriting objects

suite.addBatch({
    "When we set up the app": {
        topic: function() {
            setupApp(this.callback);
        },
        teardown: function(app) {
            if (app && app.close) {
                app.close();
            }
        },
        "it works": function(err, app) {
            assert.ifError(err);
        },
        "and we register a client": {
            topic: function() {
                newClient(this.callback);
            },
            "it works": function(err, cl) {
                assert.ifError(err);
                assert.isObject(cl);
            },
            "and we register two users": {
                topic: function(cl) {
                    var callback = this.callback;

                    Step(
                        function() {
                            newPair(cl, "click", "don't drive like my brother", this.parallel());
                            newPair(cl, "clack", "don't drive like *my* brother", this.parallel());
                        },
                        callback
                    );
                },
                "it works": function(err, pair0, pair1) {
                    assert.ifError(err);
                    assert.isObject(pair0);
                    assert.isObject(pair1);
                },
                "and the first one posts a bunch of notes and the second one shares every other one": {
                    topic: function(pair0, pair1, cl) {
                        var callback = this.callback,
                            cred0 = makeCred(cl, pair0),
                            cred1 = makeCred(cl, pair1),
                            url0 = "http://localhost:4815/api/user/click/feed",
                            url1 = "http://localhost:4815/api/user/clack/feed",
                            posts;

                        Step(
                            function() {
                                var group = this.group();
                                _.times(20, function(i) {
                                    var act = {
                                        to: [pair0.user.profile],
                                        cc: [{objectType: "collection",
                                              id: "http://activityschema.org/collection/public"}],
                                        verb: "post",
                                        object: {
                                            objectType: "note",
                                            secretNumber: i,
                                            content: "Our fair city " + i
                                        }
                                    };
                                    httputil.postJSON(url0, cred0, act, group());
                                });
                            },
                            function(err, results) {
                                var group = this.group();
                                if (err) throw err;
                                posts = results;
                                _.each(posts, function(post, i) {
                                    var act = {
                                        verb: "like",
                                        object: post.object
                                    };
                                    httputil.postJSON(url0, cred0, act, group());
                                });
                            },
                            function(err, results) {
                                var group = this.group();
                                if (err) throw err;
                                _.each(posts, function(post, i) {
                                    if (i % 2) {
                                        var act = {
                                            verb: "share",
                                            object: post.object
                                        };
                                        httputil.postJSON(url1, cred1, act, group());
                                    }
                                });
                            },
                            function(err, shares) {
                                if (err) {
                                    callback(err);
                                } else {
                                    callback(null);
                                }
                            }
                        );
                    },
                    "it works": function(err) {
                        assert.ifError(err);
                    },
                    "and we check their major inbox with same user credentials":
                    sameUser("http://localhost:4815/api/user/click/favorites"),
                    "and we check their major feed with client credentials":
                    justClient("http://localhost:4815/api/user/click/favorites"),
                    "and we check the first user's major feed with different user credentials":
                    otherUser("http://localhost:4815/api/user/click/favorites")
                }
            }
        }
    }
});

suite["export"](module);
<|endoftext|>


<commit_before>"use strict";
/*global require, global, process*/

var fs = require("fs"),
    dependencyMissing = false;
try {
    global.esprima = require("esprima");
} catch (e) {
    console.error("Missing esprima, use npm install esprima");
    dependencyMissing = true;
}
try {
    global.escodegen = require("escodegen");
} catch (e) {
    console.error("Missing escodegen, use npm install escodegen");
    dependencyMissing = true;
}
if (dependencyMissing) {
    process.exit();
}

global.gpfSourcesPath = "../src";
require("../src/boot.js"); /*source version*/
require("./make.js");  /*global make*/

var
    version,
    sources = {
        _list: gpf.sources().split(",")
    },
    idx,
    output;

// Handle the empty source tag
idx = sources._list.indexOf("");
if (-1 < idx) {
    sources._list.splice(idx, sources._list.length - idx - 1);
}

if (process.argv.length > 2) {
    version = process.argv[2];
} else {
    version = "debug";
}

console.log("Generating version '" + version + "'");

for (idx = 0; idx < sources._list.length; ++idx) {
    sources[sources._list[idx]] =
        fs.readFileSync("../" + sources._list[idx] + ".js").toString();
}
sources.UMD = fs.readFileSync("UMD.js").toString();
sources.boot = fs.readFileSync("../boot.js").toString();

try {
    make(sources, version);
} catch (e) {
    console.error(e.message);
}

// ---------- For debugging purposes

function save (name, version) {
    var
        path = "tmp/" + version + "/" + name,
        parsed = sources[version],
        json = parsed[name];
    if (!fs.existsSync("tmp")) {
        fs.mkdirSync("tmp");
    }
    if (!fs.existsSync("tmp/" + version)) {
        fs.mkdirSync("tmp/" + version);
    }
    if (parsed[name + ".js"]) {
        fs.writeFileSync(path + ".js",parsed[name + ".js"]);
    }
    if (parsed[name + ".compact.js"]) {
        fs.writeFileSync(path + ".compact.js",parsed[name + ".compact.js"]);
    }
    fs.writeFileSync(path + ".json", JSON.stringify(json, true, 4));
}

for (idx = 0; idx < sources._list.length; ++idx) {
    save(sources._list[idx], version);
}
save("UMD", version);
save("boot", version);
save("result", version);

if (!fs.existsSync("../build")) {
    fs.mkdirSync("../build");
}
output = ["../build/gpf"];
if (version !== "release") {
    output.push("-", version);
}
output.push(".js");
fs.writeFileSync(output.join(""), sources[version]["result.js"]);
<commit_msg>Fixed path<commit_after>"use strict";
/*global require, global, process*/

var fs = require("fs"),
    dependencyMissing = false;
try {
    global.esprima = require("esprima");
} catch (e) {
    console.error("Missing esprima, use npm install esprima");
    dependencyMissing = true;
}
try {
    global.escodegen = require("escodegen");
} catch (e) {
    console.error("Missing escodegen, use npm install escodegen");
    dependencyMissing = true;
}
if (dependencyMissing) {
    process.exit();
}

global.gpfSourcesPath = "../src";
require("../src/boot.js"); /*source version*/
require("./make.js");  /*global make*/

var
    version,
    sources = {
        _list: gpf.sources().split(",")
    },
    idx,
    output;

// Handle the empty source tag
idx = sources._list.indexOf("");
if (-1 < idx) {
    sources._list.splice(idx, sources._list.length - idx);
}

if (process.argv.length > 2) {
    version = process.argv[2];
} else {
    version = "debug";
}

console.log("Generating version '" + version + "'");

for (idx = 0; idx < sources._list.length; ++idx) {
    sources[sources._list[idx]] =
        fs.readFileSync("../src/" + sources._list[idx] + ".js").toString();
}
sources.UMD = fs.readFileSync("UMD.js").toString();
sources.boot = fs.readFileSync("../src/boot.js").toString();

try {
    make(sources, version);
} catch (e) {
    console.error(e.message);
}

// ---------- For debugging purposes

function save (name, version) {
    var
        path = "tmp/" + version + "/" + name,
        parsed = sources[version],
        json = parsed[name];
    if (!fs.existsSync("tmp")) {
        fs.mkdirSync("tmp");
    }
    if (!fs.existsSync("tmp/" + version)) {
        fs.mkdirSync("tmp/" + version);
    }
    if (parsed[name + ".js"]) {
        fs.writeFileSync(path + ".js",parsed[name + ".js"]);
    }
    if (parsed[name + ".compact.js"]) {
        fs.writeFileSync(path + ".compact.js",parsed[name + ".compact.js"]);
    }
    fs.writeFileSync(path + ".json", JSON.stringify(json, true, 4));
}

for (idx = 0; idx < sources._list.length; ++idx) {
    save(sources._list[idx], version);
}
save("UMD", version);
save("boot", version);
save("result", version);

if (!fs.existsSync("../build")) {
    fs.mkdirSync("../build");
}
output = ["../build/gpf"];
if (version !== "release") {
    output.push("-", version);
}
output.push(".js");
fs.writeFileSync(output.join(""), sources[version]["result.js"]);
<|endoftext|>


<commit_before>/**
 * Built-in Log Configuration
 * (sails.config.log)
 *
 * Configure the log level for your app, as well as the transport
 * (Underneath the covers, Sails uses Winston for logging, which
 * allows for some pretty neat custom transports/adapters for log messages)
 *
 * For more information on the Sails logger, check out:
 * http://sailsjs.org/#!/documentation/concepts/Logging
 */

// Customize the Logger to use Winstons
var winston = require('winston');
var customLogger = new winston.Logger();

customLogger.add(winston.transports.Console, {
  colorize: true,
  level: 'debug'
});

customLogger.add(winston.transports.File, {
  filename: 'sails-hw.log',
  level: 'debug',
  json: false
});

module.exports.log = {

  /***************************************************************************
  *                                                                          *
  * Valid `level` configs: i.e. the minimum log level to capture with        *
  * sails.log.*()                                                            *
  *                                                                          *
  * The order of precedence for log levels from lowest to highest is:        *
  * silly, verbose, info, debug, warn, error                                 *
  *                                                                          *
  * You may also set the level to "silent" to suppress all logs.             *
  *                                                                          *
  ***************************************************************************/
  custom: customLogger,
  //level: 'info'

};
<commit_msg>Config to use Winston Logger instead of default logger<commit_after>/**
 * Built-in Log Configuration
 * (sails.config.log)
 *
 * Configure the log level for your app, as well as the transport
 * (Underneath the covers, Sails uses Winston for logging, which
 * allows for some pretty neat custom transports/adapters for log messages)
 *
 * For more information on the Sails logger, check out:
 * http://sailsjs.org/#!/documentation/concepts/Logging
 */

// Customize the Logger to use Winstons
var winston = require('winston');
var customLogger = new winston.Logger();

customLogger.add(winston.transports.Console, {
  colorize: true,
  level: 'debug'
});

customLogger.add(winston.transports.File, {
  filename: 'sails-hw.log',
  level: 'debug',
  json: false
});

module.exports.log = {

  /***************************************************************************
  *                                                                          *
  * Valid `level` configs: i.e. the minimum log level to capture with        *
  * sails.log.*()                                                            *
  *                                                                          *
  * The order of precedence for log levels from lowest to highest is:        *
  * silly, verbose, info, debug, warn, error                                 *
  *                                                                          *
  * You may also set the level to "silent" to suppress all logs.             *
  *                                                                          *
  ***************************************************************************/
  //custom: customLogger,
  //level: 'info'

};
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import LinkedStateMixin from 'react-addons-linked-state-mixin'; // for manage form input...
import _ from 'lodash';

import AddressEditForm from './AddressEditForm';
import AddressView from './AddressView';
import SellerBox from 'components/CartSellerBox';
import i18n from 'commons/utils/i18n';
import CartProduct from 'components/CartProduct';
import numberUtil from 'commons/utils/numberUtil';
import orderUtil from 'commons/utils/orderUtil';

export default React.createClass({
  propTypes: {
    activeAddressId: PropTypes.number,
    addresses: PropTypes.object,
    doCheckout: PropTypes.func,
    order: PropTypes.object.isRequired,
  },
  contextTypes: {
    activeLocale: PropTypes.string,
    activeCurrency: PropTypes.string,
    currencySign: PropTypes.object,
    router: PropTypes.object.isRequired,
  },
  mixins: [LinkedStateMixin],
  getInitialState() {
    return { paymentMethod: 0 };
  },
  renderVBank() {
    const { order } = this.props;
    if (order.status === 1) {
      const payment = _.find(order.payments, (p) => p.type === 3 && p.status === 2 && p.data.payMethod === 'VBank');
      if (payment) {
        return (

입금은행: {payment.data.vactBankName}

입금계좌번호: {payment.data.VACT_Num}

예금주명: {payment.data.VACT_Name}

송금자명: {payment.data.VACT_InputName}

        );
      }
    }
  },
  render() {
    const { order } = this.props;
    const { activeAddressId, addresses, isEditMode,
      checkoutNewAddress, setActiveAddressId, saveOrderAddress } = this.props;
    const { activeCurrency, currencySign } = this.context;
    if (!order) {
      return (

      );
    }

    const renderAddresses = () => {
      if (isEditMode) {
        return (
          <AddressEditForm {...this.props} />
        );
      }
      const onSetActiveAddress = (address) => {
        setActiveAddressId(address.id);
        saveOrderAddress(order.id, address);
      };
      const renderAddress = (address) => (
        <AddressView key={`address-view-${address.id}`}
          {...this.props}
          address={address}
          isActive={activeAddressId === address.id}
          onClickMe={onSetActiveAddress}
        />
      );
      const addressIds = Object.keys(addresses);
      for (let i = 0; i < addressIds.length; i++) {
        const addressId = addressIds[i];
        if (addressId.toString() === activeAddressId.toString()) {
          for (let j = i - 1; j >= 0; j--) {
            addressIds[j + 1] = addressIds[j];
          }
          addressIds[0] = addressId;
          break;
        }
      }
      return (

          {addressIds.map((addressId) => renderAddress(addresses[addressId]))}

{i18n.get('pcPayment.addNewAddress')}

      );
    };

    const paymentMethods = [
      { icon: 'icon-inicis', name: '무통장 입금', method: 'VBank' },
      { icon: 'icon-credit-card', name: i18n.get('pcPayment.creditCard'), method: 'Card' },
    ];
    const renderPaymentMethod = (method, index) => (
      <div key={`payment-${index}`} className={`row ${index === this.state.paymentMethod ? 'active' : ''}`} onClick={() => this.setState({ paymentMethod: index })}>
        <i className={`label ${method.icon}`}>

          {method.name}

    );

    const renderPayments = () => {
      const { doCheckout } = this.props;
      const handleCheckout = (e) => {
        e.preventDefault();
        if (!activeAddressId) {
          window.alert('주소를 입력해 주세요');
          return;
        }
        const method = paymentMethods[this.state.paymentMethod].method;
        $('form input[name=gopaymethod]').val(method);
        doCheckout(order.id, method, Object.assign({}, this.refs,
          { gopaymethod: { value: method } }));
      };
      return (
        <form id="checkout" method="POST" ref="checkoutForm">
          {/* alipay */}
          <input type="hidden" name="webordernumber" ref="webordernumber" />
          <input type="hidden" name="reqtype" ref="reqtype" />
          <input type="hidden" name="returnurl" ref="returnurl" />
          <input type="hidden" name="hashdata" ref="hashdata" />
          <input type="hidden" name="notiurl" ref="notiurl" />
          <input type="hidden" name="notiidle" ref="notiidle" value="1" />

          {/* web */}
          <input type="hidden" name="gopaymethod" />
          <input type="hidden" name="version" value="1.0" />
          <input type="hidden" name="mid" ref="mid" />
          <input type="hidden" name="oid" ref="oid" />
          <input type="hidden" name="goodname" ref="goods" value="의류" />
          <input type="hidden" name="price" ref="price" />
          <input type="hidden" name="currency" value="WON" />
          <input type="hidden" name="buyername" ref="buyername" />
          <input type="hidden" name="buyertel" ref="buyertel" />
          <input type="hidden" name="buyeremail" ref="buyeremail" />
          <input type="hidden" name="timestamp" ref="timestamp" />
          <input type="hidden" name="signature" ref="signature" />
          <input type="hidden" name="returnUrl" ref="returnUrl" />
          <input type="hidden" name="mKey" ref="mKey" />
          <input type="hidden" name="quotabase" value="2:3:4:5:6:7:8:9:10:11:12" />
          <button type="submit" className="cart-button-order" onClick={handleCheckout}>
            {i18n.get('pcPayment.placeOrder')}
          </button>
        </form>
      );
    };

    const formatPrice = (type) =>
      numberUtil.formatPrice(order[`${type}${activeCurrency}`], activeCurrency, currencySign);

    const brands = orderUtil.collectByBrands(order.orderProducts);
    const subtotalPrice = formatPrice('subtotal');
    const handlingFeePrice = formatPrice('handlingFee');
    const shippingCostPrice = formatPrice('shippingCost');
    const taxPrice = formatPrice('tax');
    const totalPrice = formatPrice('total');
    return (

           {i18n.get('pcPayment.payment')}

{i18n.get('pcPayment.shippingAddress')}

          {renderAddresses()}

{i18n.get('pcPayment.orderSummary')}

          <CartProduct brands={brands} />

{i18n.get('pcPayment.paymentInfo')}

{i18n.get('pcPayment.subtotal')}

{subtotalPrice}

{i18n.get('pcPayment.tax')} (10%)

{taxPrice}

{i18n.get('pcPayment.handlingFee')} (3.3%)

{handlingFeePrice}

{i18n.get('pcPayment.shippingCost')}

{shippingCostPrice}

{i18n.get('pcPayment.totalPrice')}

{totalPrice}

{i18n.get('pcPayment.paymentMethod')}

            {paymentMethods.map(renderPaymentMethod)}
            {renderPayments()}
            {/*

알리페이

은련카드

텐페이

             */}

        { /*

 handleClickStep('review')}>
         checkout informations

 handleClickStep('payment')}>
         payment

 handleClickStep('done')}>
         done

         {getContent()}

         */ }

    );
  },
});
<commit_msg>현금 영수증.<commit_after>import React, { PropTypes } from 'react';
import LinkedStateMixin from 'react-addons-linked-state-mixin'; // for manage form input...
import _ from 'lodash';

import AddressEditForm from './AddressEditForm';
import AddressView from './AddressView';
import SellerBox from 'components/CartSellerBox';
import i18n from 'commons/utils/i18n';
import CartProduct from 'components/CartProduct';
import numberUtil from 'commons/utils/numberUtil';
import orderUtil from 'commons/utils/orderUtil';

export default React.createClass({
  propTypes: {
    activeAddressId: PropTypes.number,
    addresses: PropTypes.object,
    doCheckout: PropTypes.func,
    order: PropTypes.object.isRequired,
  },
  contextTypes: {
    activeLocale: PropTypes.string,
    activeCurrency: PropTypes.string,
    currencySign: PropTypes.object,
    router: PropTypes.object.isRequired,
  },
  mixins: [LinkedStateMixin],
  getInitialState() {
    return { paymentMethod: 0 };
  },
  renderVBank() {
    const { order } = this.props;
    if (order.status === 1) {
      const payment = _.find(order.payments, (p) => p.type === 3 && p.status === 2 && p.data.payMethod === 'VBank');
      if (payment) {
        return (

입금은행: {payment.data.vactBankName}

입금계좌번호: {payment.data.VACT_Num}

예금주명: {payment.data.VACT_Name}

송금자명: {payment.data.VACT_InputName}

        );
      }
    }
  },
  render() {
    const { order } = this.props;
    const { activeAddressId, addresses, isEditMode,
      checkoutNewAddress, setActiveAddressId, saveOrderAddress } = this.props;
    const { activeCurrency, currencySign } = this.context;
    if (!order) {
      return (

      );
    }

    const renderAddresses = () => {
      if (isEditMode) {
        return (
          <AddressEditForm {...this.props} />
        );
      }
      const onSetActiveAddress = (address) => {
        setActiveAddressId(address.id);
        saveOrderAddress(order.id, address);
      };
      const renderAddress = (address) => (
        <AddressView key={`address-view-${address.id}`}
          {...this.props}
          address={address}
          isActive={activeAddressId === address.id}
          onClickMe={onSetActiveAddress}
        />
      );
      const addressIds = Object.keys(addresses);
      for (let i = 0; i < addressIds.length; i++) {
        const addressId = addressIds[i];
        if (addressId.toString() === activeAddressId.toString()) {
          for (let j = i - 1; j >= 0; j--) {
            addressIds[j + 1] = addressIds[j];
          }
          addressIds[0] = addressId;
          break;
        }
      }
      return (

          {addressIds.map((addressId) => renderAddress(addresses[addressId]))}

{i18n.get('pcPayment.addNewAddress')}

      );
    };

    const paymentMethods = [
      { icon: 'icon-inicis', name: '무통장 입금', method: 'VBank' },
      { icon: 'icon-credit-card', name: i18n.get('pcPayment.creditCard'), method: 'Card' },
    ];
    const renderPaymentMethod = (method, index) => (
      <div key={`payment-${index}`} className={`row ${index === this.state.paymentMethod ? 'active' : ''}`} onClick={() => this.setState({ paymentMethod: index })}>
        <i className={`label ${method.icon}`}>

          {method.name}

    );

    const renderPayments = () => {
      const { doCheckout } = this.props;
      const handleCheckout = (e) => {
        e.preventDefault();
        if (!activeAddressId) {
          window.alert('주소를 입력해 주세요');
          return;
        }
        const method = paymentMethods[this.state.paymentMethod].method;
        $('form input[name=gopaymethod]').val(method);
        doCheckout(order.id, method, Object.assign({}, this.refs,
          { gopaymethod: { value: method } }));
      };
      return (
        <form id="checkout" method="POST" ref="checkoutForm">
          {/* alipay */}
          <input type="hidden" name="webordernumber" ref="webordernumber" />
          <input type="hidden" name="reqtype" ref="reqtype" />
          <input type="hidden" name="returnurl" ref="returnurl" />
          <input type="hidden" name="hashdata" ref="hashdata" />
          <input type="hidden" name="notiurl" ref="notiurl" />
          <input type="hidden" name="notiidle" ref="notiidle" value="1" />

          {/* web */}
          <input type="hidden" name="gopaymethod" />
          <input type="hidden" name="version" value="1.0" />
          <input type="hidden" name="mid" ref="mid" />
          <input type="hidden" name="oid" ref="oid" />
          <input type="hidden" name="goodname" ref="goods" value="의류" />
          <input type="hidden" name="price" ref="price" />
          <input type="hidden" name="currency" value="WON" />
          <input type="hidden" name="buyername" ref="buyername" />
          <input type="hidden" name="buyertel" ref="buyertel" />
          <input type="hidden" name="buyeremail" ref="buyeremail" />
          <input type="hidden" name="timestamp" ref="timestamp" />
          <input type="hidden" name="signature" ref="signature" />
          <input type="hidden" name="returnUrl" ref="returnUrl" />
          <input type="hidden" name="mKey" ref="mKey" />
          <input type="hidden" name="quotabase" value="2:3:4:5:6:7:8:9:10:11:12" />
          <input type="hidden" name="acceptmethod" value="va_receipt" ref="acceptmethod" />
          <button type="submit" className="cart-button-order" onClick={handleCheckout}>
            {i18n.get('pcPayment.placeOrder')}
          </button>
        </form>
      );
    };

    const formatPrice = (type) =>
      numberUtil.formatPrice(order[`${type}${activeCurrency}`], activeCurrency, currencySign);

    const brands = orderUtil.collectByBrands(order.orderProducts);
    const subtotalPrice = formatPrice('subtotal');
    const handlingFeePrice = formatPrice('handlingFee');
    const shippingCostPrice = formatPrice('shippingCost');
    const taxPrice = formatPrice('tax');
    const totalPrice = formatPrice('total');
    return (

           {i18n.get('pcPayment.payment')}

{i18n.get('pcPayment.shippingAddress')}

          {renderAddresses()}

{i18n.get('pcPayment.orderSummary')}

          <CartProduct brands={brands} />

{i18n.get('pcPayment.paymentInfo')}

{i18n.get('pcPayment.subtotal')}

{subtotalPrice}

{i18n.get('pcPayment.tax')} (10%)

{taxPrice}

{i18n.get('pcPayment.handlingFee')} (3.3%)

{handlingFeePrice}

{i18n.get('pcPayment.shippingCost')}

{shippingCostPrice}

{i18n.get('pcPayment.totalPrice')}

{totalPrice}

{i18n.get('pcPayment.paymentMethod')}

            {paymentMethods.map(renderPaymentMethod)}
            {renderPayments()}
            {/*

알리페이

은련카드

텐페이

             */}

        { /*

 handleClickStep('review')}>
         checkout informations

 handleClickStep('payment')}>
         payment

 handleClickStep('done')}>
         done

         {getContent()}

         */ }

    );
  },
});
<|endoftext|>


<commit_before>/**********************
* jquery.readmore.js
* Creates read more link after approximate number of chars, but only splits between works
* author: andy hill andy@andyhill.us
*********************/
if (!String.prototype.trim) {
  String.prototype.trim = function () {
    return this.replace(/^\s+|\s+$/g, '');
  };
}

(function($){
	$.fn.readmore = function(options) {
		var defaults = {                             ////set up default parameters
			chars: 50,
			moreText: 'More...',
			lessText: 'Less',
			newline: false,
			duration: 1000,
			prefix: 'readmore'
		};
		options = $.extend({}, defaults, options);   ////options will be the parameter scope
		return this.each(function() {                ////loop through each matched element
			var text = $(this).text().trim();
			var content = $(this).html().trim();
			var original = 'readmore-original'
			if ($(this).data(original)) {
				// console.log('reload');
				content = $(this).data(original);
				// text = $(this).data(original+'-text');
				text = $(this).text();
				$(this).html(content);
			} else {
				// console.log('new');
				$(this).data(original, content);
				// $(this).data(original+'-text', text);
			}
			// console.log(content);
			var words = text.split(/\s/);
			//// Determine number of words to display before cutoff
			var len = 0;
			var numwords = 0;
			for (numwords = 0; numwords < words.length; numwords++) {
				len += words[numwords].length + 1;
				if (len >= options.chars) {
					break;
				}
			}
			//// Split content
			var show = '';
			var hide = content;
			for (var i = 0; i < numwords; i++) {
				var cutoff = findWord(hide, words[i]);
				show += hide.slice(0, cutoff);
				hide = hide.slice(cutoff);
			}
			//// replace original content with readmore structure
			var separator = (typeof options.newline == 'boolean') ?
				(options.newline) ? '
' : ' ' :
				options.newline;
			var replace = ''+ show +''+
				''+hide+''+
				''+separator+''+
				''+options.moreText+'';
			$(this).html(replace);

			//// hide rest
			$('.'+options.prefix+'-rest', this).hide();
			//// toggle content
		    $('.'+options.prefix+'-toggle', this).click(function() {
		    	var text = options.moreText;
		    	var rest = $(this).siblings('.'+options.prefix+'-rest');
		    	var toggle = $(this);
		    	//// hide
		    	if (toggle.text().trim() == options.lessText) {
		    		toggle.css('display', 'none', options.duration);
		    		rest.animate({ 'opacity': 0}, options.duration, function() {
		    			$(this).css('display', 'none');
		    			toggle.css('display', 'inline');
		    		});
		    	//// show
		    	} else {
		    		text = options.lessText;
		    		toggle.hide(0);
		    		toggle.show(options.duration);
		    		rest.css({ 'opacity': 0, 'display': 'inline'}).animate({ 'opacity': 1}, options.duration);
		    	}
				toggle.text(text);
		    	return false;
		    });
		    /**
		     *	Finds word in content, ignoring any html
		     */
		    function findWord(content, word) {
		    	var inTag = false,		//// whether we're in an html tag
		    		buildword = '';		//// build html-free word to test
		    	for (var i = 0; i < content.length; i++) {
		    		var chr = content.charAt(i);
		    		if (chr == '<') {
		    			inTag = true;
		    		} else if (chr == '>') {
		    			inTag = false;
		    		} else {
			    		if (!inTag && !/\s/.test(chr)) {
			    			buildword += chr;
			    		}
			    		if (buildword == word) {
			    			return i+1;
			    		}
		    		}
		    	}
		    	return i;
		    }
		});

	};
})(jQuery);
<commit_msg>cleaned up a bit<commit_after>/**********************
* jquery.readmore.js
* Creates read more link after approximate number of chars, but only splits between works
* author: andy hill andy@andyhill.us
*********************/
if (!String.prototype.trim) {
  String.prototype.trim = function () {
    return this.replace(/^\s+|\s+$/g, '');
  };
}

(function($){
	$.fn.readmore = function(options) {
		var defaults = {                             ////set up default parameters
			chars: 50,
			moreText: 'More...',
			lessText: 'Less',
			newline: false,
			duration: 1000,
			prefix: 'readmore'
		};
		options = $.extend({}, defaults, options);   ////options will be the parameter scope
		return this.each(function() {                ////loop through each matched element
			var container = $(this);
			var content = container.html().trim();
			var original = 'readmore-original'
			//// reloading
			if (container.data(original)) {
				content = container.data(original);
				container.html(content);
			//// first loading
			} else {
				$(this).data(original, content);
			}
			var text = container.text().trim();
			//// Determine number of words to display before cutoff
			var words = text.split(/\s/);
			var len = 0;
			var numwords = 0;
			for (numwords = 0; numwords < words.length; numwords++) {
				len += words[numwords].length + 1;
				if (len >= options.chars) {
					break;
				}
			}
			//// Split content
			var show = '';
			var hide = content;
			for (var i = 0; i < numwords; i++) {
				var cutoff = findWord(hide, words[i]);
				show += hide.slice(0, cutoff);
				hide = hide.slice(cutoff);
			}
			//// replace original content with readmore structure
			var separator = (typeof options.newline == 'boolean') ?
				(options.newline) ? '
' : ' ' :
				options.newline;
			var replace = ''+ show +''+
				''+hide+''+
				''+separator+''+
				''+options.moreText+'';
			container.html(replace);

			//// hide rest
			$('.'+options.prefix+'-rest', this).hide();
			//// toggle content
		    $('.'+options.prefix+'-toggle', this).click(function() {
		    	var text = options.moreText;
		    	var rest = $(this).siblings('.'+options.prefix+'-rest');
		    	var toggle = $(this);
		    	//// hide
		    	if (toggle.text().trim() == options.lessText) {
		    		toggle.css('display', 'none', options.duration);
		    		rest.animate({ 'opacity': 0}, options.duration, function() {
		    			$(this).css('display', 'none');
		    			toggle.css('display', 'inline');
		    		});
		    	//// show
		    	} else {
		    		text = options.lessText;
		    		toggle.hide(0);
		    		toggle.show(options.duration);
		    		rest.css({ 'opacity': 0, 'display': 'inline'}).animate({ 'opacity': 1}, options.duration);
		    	}
				toggle.text(text);
		    	return false;
		    });
		    /**
		     *	Finds word in content, ignoring any html
		     */
		    function findWord(content, word) {
		    	var inTag = false,		//// whether we're in an html tag
		    		buildword = '';		//// build html-free word to test
		    	for (var i = 0; i < content.length; i++) {
		    		var chr = content.charAt(i);
		    		if (chr == '<') {
		    			inTag = true;
		    		} else if (chr == '>') {
		    			inTag = false;
		    		} else {
			    		if (!inTag && !/\s/.test(chr)) {
			    			buildword += chr;
			    		}
			    		if (buildword == word) {
			    			return i+1;
			    		}
		    		}
		    	}
		    	return i;
		    }
		});

	};
})(jQuery);
<|endoftext|>


<commit_before>var config = require('../src/config/config')
var client = require('mongodb').MongoClient
var fs = require('fs-extra')

client.connect(config.database.host+'vegodev', function(err, db){
  if (err) throw err

  //Drop vegodev database if it exists
  db.dropDatabase(function(err, result) {

    var adminDb = db.admin()
    //Get a fresh copy
    adminDb.command({
      copydb: 1,
      fromdb: 'vegosvar',
      todb: 'vegodev'

    }, function(err, result) {
      if (err) throw err
      if(result.ok) {
        console.log('Database copied successfully')
      }

      //Copy uploads folder
      var source = '/var/www/beta.vegosvar.se/src/uploads'
      var destination = '/var/www/dev.vegosvar.se/src/uploads'

      //assume this directory has a lot of files and folders
      fs.emptyDir(destination, function (err) {
        if (err) throw err
        fs.copy(source, destination, function (err) {
          if (err) throw err

          console.log('Uploads folder copied successfully')

          if(config.environment === 'development') {
            //Set all pages to published
            db.collection('pages').update({}, {
              $set: {
                accepted: true
              }
            }, {
              multi: true
            })
          } else {
            db.close()
          }
        })
      })
    })
  })
})
<commit_msg>Close db connection once all pages are published<commit_after>var config = require('../src/config/config')
var client = require('mongodb').MongoClient
var fs = require('fs-extra')

client.connect(config.database.host+'vegodev', function(err, db){
  if (err) throw err

  //Drop vegodev database if it exists
  db.dropDatabase(function(err, result) {

    var adminDb = db.admin()
    //Get a fresh copy
    adminDb.command({
      copydb: 1,
      fromdb: 'vegosvar',
      todb: 'vegodev'

    }, function(err, result) {
      if (err) throw err
      if(result.ok) {
        console.log('Database copied successfully')
      }

      //Copy uploads folder
      var source = '/var/www/beta.vegosvar.se/src/uploads'
      var destination = '/var/www/dev.vegosvar.se/src/uploads'

      //assume this directory has a lot of files and folders
      fs.emptyDir(destination, function (err) {
        if (err) throw err
        fs.copy(source, destination, function (err) {
          if (err) throw err

          console.log('Uploads folder copied successfully')

          if('environment' in config && config.environment === 'development') {
            //Set all pages to published
            db.collection('pages').update({}, {
              $set: {
                accepted: true
              }
            }, {
              multi: true
            }, function(err, result) {
              db.close()
            })
          } else {
            db.close()
          }
        })
      })
    })
  })
})
<|endoftext|>