<commit_before>/*
This file is part of the Juju GUI, which lets users view and manage Juju
environments within a graphical interface (https://launchpad.net/juju-gui).
Copyright (C) 2016 Canonical Ltd.

This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3, as published by
the Free Software Foundation.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero
General Public License for more details.

You should have received a copy of the GNU Affero General Public License along
with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

'use strict';

const juju = {components: {}}; // eslint-disable-line no-unused-vars

describe('CreateModelButton', () => {
  let controllerAPI, users;

  beforeAll((done) => {
    // By loading this file it adds the component to the juju components.
    YUI().use('create-model-button', () => { done(); });
  });

  beforeEach(() => {
    controllerAPI = {
      findFacadeVersion: sinon.stub(),
      get: sinon.stub().returns('default'),
      createModel: (modelName, userName, callback) => {
        assert.equal(modelName, 'newmodelname', 'model name not set properly');
        assert.equal(userName, 'test-owner', 'user name not set properly');
        // Simulate the model being created.
        callback({
          err: null,
          uuid: 'abc123',
          name: modelName
        });
      }
    };
    users = {charmstore: {
      user: 'test-owner',
      usernameDisplay: 'test owner'
    }};
  });

  it('renders a button', () => {
    const component = jsTestUtils.shallowRender(
      <juju.components.CreateModelButton
        addNotification={sinon.stub()}
        className={'test'}
        controllerAPI={controllerAPI}
        hideConnectingMask={sinon.stub()}
        jem={null}
        showConnectingMask={sinon.stub()}
        switchModel={sinon.stub()}
        user={users.charmstore} />, true);
    const instance = component.getMountedInstance();
    const output = component.getRenderOutput();
    const expected = (

        <form onSubmit={instance.createAndSwitch}>
          <juju.components.GenericButton
            action={instance._nextCreateStep}
            type="inline-neutral first"
            title="Create new" />
          <juju.components.GenericInput
            placeholder="untitled_model"
            required={true}
            ref="modelName"
            validate={[{
              regex: /\S+/,
              error: 'This field is required.'
            }, {
              regex: /^[a-zA-Z0-9]([a-zA-Z0-9.-]*[a-zA-Z0-9])?$/,
              error: 'This field must only contain upper and lowercase ' +
                'letters, numbers, and hyphens. It must not start or ' +
                'end with a hyphen.'
            }]} />
          <juju.components.GenericButton
            action={instance.createAndSwitch}
            type="inline-neutral second"
            title="Submit" />
        </form>

    );
    assert.deepEqual(output, expected);
  });

  it('creates then switches to newly created models', () => {
    // This test doesn't check the user interactions and animations, that
    // will need to be done with the uitest suite.
    const showConnectingMask = sinon.stub();
    const switchModel = sinon.stub();
    const component = jsTestUtils.shallowRender(
      <juju.components.CreateModelButton
        addNotification={sinon.stub()}
        controllerAPI={controllerAPI}
        hideConnectingMask={sinon.stub()}
        showConnectingMask={showConnectingMask}
        switchModel={switchModel}
        user={users.charmstore} />, true);
    const instance = component.getMountedInstance();
    // Set up the component to simulate user action.
    instance.refs = {
      modelName: {
        validate: () => true,
        getValue: () => 'newmodelname'
      }
    };
    const preventable = { preventDefault: sinon.stub() };
    // Call the action method in the proper element.
    instance.createAndSwitch(preventable);
    assert.equal(preventable.preventDefault.callCount, 1,
                 'default not prevented');
    assert.equal(showConnectingMask.callCount, 1, 'mask not shown');
    // Make sure that it switches to the model after it's created.
    assert.equal(switchModel.callCount, 1, 'model not switched to');
    assert.equal(switchModel.args[0][0], 'abc123', 'uuid not passed through');
    assert.equal(switchModel.args[0][1], 'newmodelname', 'model name not set');
  });

  it('does not submit to create new if name does not validate', () => {
    // This test doesn't check the user interactions and animations, that
    // will need to be done with the uitest suite.
    const showConnectingMask = sinon.stub();
    const switchModel = sinon.stub();
    const component = jsTestUtils.shallowRender(
      <juju.components.CreateModelButton
        addNotification={sinon.stub()}
        controllerAPI={controllerAPI}
        hideConnectingMask={sinon.stub()}
        showConnectingMask={showConnectingMask}
        switchModel={switchModel}
        user={users.charmstore} />, true);
    const instance = component.getMountedInstance();
    // Set up the component to simulate user action.
    instance.refs = {
      modelName: {
        validate: () => false
      }
    };
    const preventable = { preventDefault: sinon.stub() };
    // Call the action method in the proper element.
    instance.createAndSwitch(preventable);
    assert.equal(
      preventable.preventDefault.callCount, 1, 'default not prevented');
    assert.equal(showConnectingMask.callCount, 0, 'mask shown');
    // Make sure that it switches to the model after it's created.
    assert.equal(switchModel.callCount, 0, 'model should not be switched to');
  });

  it('gracefully handles errors when creating new model', () => {
    // This test doesn't check the user interactions and animations, that
    // will need to be done with the uitest suite.
    controllerAPI.createModel = (modelName, userName, callback) => {
      assert.equal(modelName, 'newmodelname', 'model name not set properly');
      assert.equal(userName, 'test-owner', 'user name not set properly');
      // Simulate the model being created.
      callback({
        err: 'this is an error',
        uuid: 'abc123',
        name: modelName
      });
    };
    const hideConnectingMask = sinon.stub();
    const addNotification = sinon.stub();
    const component = jsTestUtils.shallowRender(
      <juju.components.CreateModelButton
        addNotification={addNotification}
        controllerAPI={controllerAPI}
        hideConnectingMask={hideConnectingMask}
        showConnectingMask={sinon.stub()}
        switchModel={sinon.stub()}
        user={users.charmstore} />, true);
    const instance = component.getMountedInstance();
    // Set up the component to simulate user action.
    instance.refs = {
      modelName: {
        validate: () => true,
        getValue: () => 'newmodelname'
      }
    };
    const preventable = { preventDefault: sinon.stub() };
    // Call the action method in the proper element.
    instance.createAndSwitch(preventable);
    // Make sure that the mask is hidden and that a notification was added
    // with the error message.
    assert.equal(hideConnectingMask.callCount, 1, 'mask not hidden');
    assert.equal(addNotification.callCount, 1, 'notification not added');
    assert.deepEqual(addNotification.args[0][0], {
      title: 'Failed to create new Model',
      message: 'this is an error',
      level: 'error'
    });
  });
});
<commit_msg>Add missing test for creating models button component<commit_after>/*
This file is part of the Juju GUI, which lets users view and manage Juju
environments within a graphical interface (https://launchpad.net/juju-gui).
Copyright (C) 2016 Canonical Ltd.

This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3, as published by
the Free Software Foundation.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero
General Public License for more details.

You should have received a copy of the GNU Affero General Public License along
with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

'use strict';

const juju = {components: {}}; // eslint-disable-line no-unused-vars

describe('CreateModelButton', () => {
  let controllerAPI, users;

  beforeAll((done) => {
    // By loading this file it adds the component to the juju components.
    YUI().use('create-model-button', () => { done(); });
  });

  beforeEach(() => {
    controllerAPI = {
      findFacadeVersion: sinon.stub(),
      get: sinon.stub().returns('default'),
      createModel: (modelName, userName, callback) => {
        assert.equal(modelName, 'newmodelname', 'model name not set properly');
        assert.equal(userName, 'test-owner', 'user name not set properly');
        // Simulate the model being created.
        callback({
          err: null,
          uuid: 'abc123',
          name: modelName
        });
      }
    };
    users = {charmstore: {
      user: 'test-owner',
      usernameDisplay: 'test owner'
    }};
  });

  it('renders a button', () => {
    const component = jsTestUtils.shallowRender(
      <juju.components.CreateModelButton
        addNotification={sinon.stub()}
        className={'test'}
        controllerAPI={controllerAPI}
        gisf={false}
        hideConnectingMask={sinon.stub()}
        jem={null}
        showConnectingMask={sinon.stub()}
        switchModel={sinon.stub()}
        user={users.charmstore} />, true);
    const instance = component.getMountedInstance();
    const output = component.getRenderOutput();
    const expected = (

        <form onSubmit={instance.createAndSwitch}>
          <juju.components.GenericButton
            action={instance._nextCreateStep}
            type="inline-neutral first"
            title="Create new" />
          <juju.components.GenericInput
            placeholder="untitled_model"
            required={true}
            ref="modelName"
            validate={[{
              regex: /\S+/,
              error: 'This field is required.'
            }, {
              regex: /^[a-zA-Z0-9]([a-zA-Z0-9.-]*[a-zA-Z0-9])?$/,
              error: 'This field must only contain upper and lowercase ' +
                'letters, numbers, and hyphens. It must not start or ' +
                'end with a hyphen.'
            }]} />
          <juju.components.GenericButton
            action={instance.createAndSwitch}
            type="inline-neutral second"
            title="Submit" />
        </form>

    );
    assert.deepEqual(output, expected);
  });

  it('creates then switches to newly created models', () => {
    // This test doesn't check the user interactions and animations, that
    // will need to be done with the uitest suite.
    const showConnectingMask = sinon.stub();
    const switchModel = sinon.stub();
    const component = jsTestUtils.shallowRender(
      <juju.components.CreateModelButton
        addNotification={sinon.stub()}
        controllerAPI={controllerAPI}
        gisf={false}
        hideConnectingMask={sinon.stub()}
        showConnectingMask={showConnectingMask}
        switchModel={switchModel}
        user={users.charmstore} />, true);
    const instance = component.getMountedInstance();
    // Set up the component to simulate user action.
    instance.refs = {
      modelName: {
        validate: () => true,
        getValue: () => 'newmodelname'
      }
    };
    const preventable = { preventDefault: sinon.stub() };
    // Call the action method in the proper element.
    instance.createAndSwitch(preventable);
    assert.equal(preventable.preventDefault.callCount, 1,
                 'default not prevented');
    assert.equal(showConnectingMask.callCount, 1, 'mask not shown');
    // Make sure that it switches to the model after it's created.
    assert.equal(switchModel.callCount, 1, 'model not switched to');
    assert.equal(switchModel.args[0][0], 'abc123', 'uuid not passed through');
    assert.equal(switchModel.args[0][1], 'newmodelname', 'model name not set');
  });

  it('switches to an unconnected state if in gisf mode', () => {
    const switchModel = sinon.stub();
    const component = jsTestUtils.shallowRender(
      <juju.components.CreateModelButton
        addNotification={sinon.stub()}
        controllerAPI={controllerAPI}
        gisf={true}
        hideConnectingMask={sinon.stub()}
        showConnectingMask={sinon.stub()}
        switchModel={switchModel}
        user={users.charmstore} />, true);
    const instance = component.getMountedInstance();
    instance._nextCreateStep();
    // Make sure that it switches to the model after it's created.
    assert.equal(switchModel.callCount, 1, 'model not switched to');
    assert.deepEqual(switchModel.args[0], [], 'not switching to uncommitted');
  });

  it('does not submit to create new if name does not validate', () => {
    // This test doesn't check the user interactions and animations, that
    // will need to be done with the uitest suite.
    const showConnectingMask = sinon.stub();
    const switchModel = sinon.stub();
    const component = jsTestUtils.shallowRender(
      <juju.components.CreateModelButton
        addNotification={sinon.stub()}
        controllerAPI={controllerAPI}
        gisf={false}
        hideConnectingMask={sinon.stub()}
        showConnectingMask={showConnectingMask}
        switchModel={switchModel}
        user={users.charmstore} />, true);
    const instance = component.getMountedInstance();
    // Set up the component to simulate user action.
    instance.refs = {
      modelName: {
        validate: () => false
      }
    };
    const preventable = { preventDefault: sinon.stub() };
    // Call the action method in the proper element.
    instance.createAndSwitch(preventable);
    assert.equal(
      preventable.preventDefault.callCount, 1, 'default not prevented');
    assert.equal(showConnectingMask.callCount, 0, 'mask shown');
    // Make sure that it switches to the model after it's created.
    assert.equal(switchModel.callCount, 0, 'model should not be switched to');
  });

  it('gracefully handles errors when creating new model', () => {
    // This test doesn't check the user interactions and animations, that
    // will need to be done with the uitest suite.
    controllerAPI.createModel = (modelName, userName, callback) => {
      assert.equal(modelName, 'newmodelname', 'model name not set properly');
      assert.equal(userName, 'test-owner', 'user name not set properly');
      // Simulate the model being created.
      callback({
        err: 'this is an error',
        uuid: 'abc123',
        name: modelName
      });
    };
    const hideConnectingMask = sinon.stub();
    const addNotification = sinon.stub();
    const component = jsTestUtils.shallowRender(
      <juju.components.CreateModelButton
        addNotification={addNotification}
        controllerAPI={controllerAPI}
        gisf={false}
        hideConnectingMask={hideConnectingMask}
        showConnectingMask={sinon.stub()}
        switchModel={sinon.stub()}
        user={users.charmstore} />, true);
    const instance = component.getMountedInstance();
    // Set up the component to simulate user action.
    instance.refs = {
      modelName: {
        validate: () => true,
        getValue: () => 'newmodelname'
      }
    };
    const preventable = { preventDefault: sinon.stub() };
    // Call the action method in the proper element.
    instance.createAndSwitch(preventable);
    // Make sure that the mask is hidden and that a notification was added
    // with the error message.
    assert.equal(hideConnectingMask.callCount, 1, 'mask not hidden');
    assert.equal(addNotification.callCount, 1, 'notification not added');
    assert.deepEqual(addNotification.args[0][0], {
      title: 'Failed to create new Model',
      message: 'this is an error',
      level: 'error'
    });
  });
});
<|endoftext|>


<commit_before>// TODO:
// - Check success of Roon API calls
// - Volume control
// - Seek

// Parts of this code are copied from https://github.com/RoonLabs/roon-extension-powermate

"use strict";

var pjson = require('./package.json');
var package_version = pjson.version; //process.env.npm_package_version does not work under forever

// Roon setup

var RoonApi        = require("node-roon-api"),
  RoonApiSettings  = require('node-roon-api-settings'),
  RoonApiStatus    = require('node-roon-api-status'),
  RoonApiTransport = require('node-roon-api-transport');

var core;
var roon = new RoonApi({
    extension_id:        'roonrest',
    display_name:        'Roon Rest Controller',
    display_version:     package_version,
    publisher:           'Matthew Eckhaus',
    email:               'contact@roonlabs.com',
    website:             'https://github.com/matteck/roonrest',

    core_paired: function(core_) {
        core = core_;
    },
    core_unpaired: function(core_) {
	      core = undefined;
    }
});

var mysettings = roon.load_config("settings") || {
    zone:             null,
};

function makelayout(settings) {
    var l = {
        values:    settings,
        layout:    [],
        has_error: false
    };

  l.layout.push({
	type:    "zone",
	title:   "Zone",
	setting: "zone",
    });

    return l;
}

var svc_settings = new RoonApiSettings(roon, {
    get_settings: function(cb) {
        cb(makelayout(mysettings));
    },
    save_settings: function(req, isdryrun, settings) {
	let l = makelayout(settings.values);
        req.send_complete(l.has_error ? "NotValid" : "Success", { settings: l });

        if (!isdryrun && !l.has_error) {
            mysettings = l.values;
            svc_settings.update_settings(l);
            roon.save_config("settings", mysettings);
            update_status();
        }
    }
});

var svc_status = new RoonApiStatus(roon);

roon.init_services({
    required_services:   [ RoonApiTransport ],
    provided_services:   [ svc_settings, svc_status ],
});

function update_status() {
  if (mysettings.zone.name) {
	  svc_status.set_status("Ready. Attached to " + mysettings.zone.name, false);
  } else {
    svc_status.set_status("Loaded. No zone assigned");
  }
}

update_status();
roon.start_discovery();

// Express
var port = 3000

var express = require('express')
var app = express()

var not_registered_error = "The RoonRest extension is not enabled. Please enable it in Roon settings and try again.";

// Zone-specific control actions
app.put('/api/v1/zone/current/control/:action(play|pause|playpause|stop|previous|next)', function (req, res) {
  if (core == undefined) {
    res.status('503').send(not_registered_error);
  } else {
    var action = req.params['action'];
    console.log('action is ' + action);
    core.services.RoonApiTransport.control(mysettings.zone, action);
    res.send('OK');
  }
})

// Universal control actions
app.put('/api/v1/zone/all/control/pause', function (req, res) {
  if (core == undefined) {
    res.status('503').send(not_registered_error);
  } else {
    console.log('Doing pause_all');
    core.services.RoonApiTransport.pause_all();
    res.send('OK');
  }
})

app.put('/api/v1/zone/current/settings/:name(shuffle|auto_radio)/:value(on|off)', function (req, res) {
  if (core == undefined) {
    res.status('503').send(not_registered_error);
  } else {
    console.log('Doing set ' + req.params['name'] + ' to ' + req.params['value']);
    var settings_object = {};
    var setting_name = req.params['name']
    if (req.params['value'] == 'on') {
      settings_object[setting_name] = 1;
    } else {
      settings_object[setting_name] = 0;
    }
    core.services.RoonApiTransport.change_settings(mysettings.zone, settings_object);
    res.send('OK');
  }
})

app.get('/api/v1', function (req, res) {
  res.send('RoonRest extensions v1')
})

app.listen(port, function () {
  console.log('RoonRest extension started, listening on port ' + port)
})<commit_msg>Added volume control<commit_after>// TODO:
// - Check success of Roon API calls
// - Volume control
// - Seek

// Parts of this code are copied from https://github.com/RoonLabs/roon-extension-powermate

"use strict";

var pjson = require('./package.json');
var package_version = pjson.version; //process.env.npm_package_version does not work under forever

// Roon setup

var RoonApi        = require("node-roon-api"),
  RoonApiSettings  = require('node-roon-api-settings'),
  RoonApiStatus    = require('node-roon-api-status'),
  RoonApiTransport = require('node-roon-api-transport');

var core;
var roon = new RoonApi({
    extension_id:        'roonrest',
    display_name:        'Roon Rest Controller',
    display_version:     package_version,
    publisher:           'Matthew Eckhaus',
    email:               'contact@roonlabs.com',
    website:             'https://github.com/matteck/roonrest',

    core_paired: function(core_) {
        core = core_;
    },
    core_unpaired: function(core_) {
	      core = undefined;
    }
});

var mysettings = roon.load_config("settings") || {
    zone:             null,
};

function makelayout(settings) {
    var l = {
        values:    settings,
        layout:    [],
        has_error: false
    };

  l.layout.push({
	type:    "zone",
	title:   "Zone",
	setting: "zone",
    });

    return l;
}

var svc_settings = new RoonApiSettings(roon, {
    get_settings: function(cb) {
        cb(makelayout(mysettings));
    },
    save_settings: function(req, isdryrun, settings) {
	let l = makelayout(settings.values);
        req.send_complete(l.has_error ? "NotValid" : "Success", { settings: l });

        if (!isdryrun && !l.has_error) {
            mysettings = l.values;
            svc_settings.update_settings(l);
            roon.save_config("settings", mysettings);
            update_status();
        }
    }
});

var svc_status = new RoonApiStatus(roon);

roon.init_services({
    required_services:   [ RoonApiTransport ],
    provided_services:   [ svc_settings, svc_status ],
});

function update_status() {
  if (mysettings.hasOwnProperty("zone") && mysettings.zone != null && mysettings.zone.hasOwnProperty("name")) {
	  svc_status.set_status("Ready. Attached to " + mysettings.zone.name, false);
  } else {
    svc_status.set_status("Loaded. No zone assigned");
  }
}

update_status();
roon.start_discovery();

// Express
var port = 3000

var express = require('express')
var app = express()

var not_registered_error = "The RoonRest extension is not enabled. Please enable it in Roon settings and try again.";

// Zone-specific control actions
app.put('/api/v1/zone/current/control/:action(play|pause|playpause|stop|previous|next)', function (req, res) {
  if (core == undefined) {
    res.status('503').send(not_registered_error);
  } else {
    var action = req.params['action'];
    console.log('action is ' + action);
    core.services.RoonApiTransport.control(mysettings.zone, action);
    res.send('OK');
  }
})

// Universal control actions
app.put('/api/v1/zone/all/control/pause', function (req, res) {
  if (core == undefined) {
    res.status('503').send(not_registered_error);
  } else {
    console.log('Doing pause_all');
    core.services.RoonApiTransport.pause_all();
    res.send('OK');
  }
})

// Settings
app.put('/api/v1/zone/current/settings/:name(shuffle|auto_radio)/:value(on|off)', function (req, res) {
  if (core == undefined) {
    res.status('503').send(not_registered_error);
  } else {
    console.log('Doing set ' + req.params['name'] + ' to ' + req.params['value']);
    var settings_object = {};
    var setting_name = req.params['name']
    if (req.params['value'] == 'on') {
      settings_object[setting_name] = 1;
    } else {
      settings_object[setting_name] = 0;
    }
    core.services.RoonApiTransport.change_settings(mysettings.zone, settings_object);
    res.send('OK');
  }
})

// Volume
app.put('/api/v1/zone/current/volume/:how(absolute|relative|relative_step)/:value', function (req, res) {
  if (core == undefined) {
    res.status('503').send(not_registered_error);
  } else {
    var how = req.params['how'];
    var value = req.params['value']
    console.log('volume how is ' + how);
    core.services.RoonApiTransport.change_volume(mysettings.zone, how, value);
    res.send('OK');
  }
})

app.get('/api/v1', function (req, res) {
  res.send('RoonRest extensions v1')
})

app.listen(port, function () {
  console.log('RoonRest extension started, listening on port ' + port)
})<|endoftext|>


<commit_before>var assert = require('assert'),
    path = require('path'),
    spawn = require('child_process').spawn;

describe('bin/license-checker', function() {
    this.timeout(8000);
    it('should exit 1 if it finds a single license type (MIT) license due to --failOn MIT', function(done) {
        spawn('node', [path.join(__dirname, '../bin/license-checker'), '--failOn', 'MIT'], {
            cwd: path.join(__dirname, '../'),
            stdio: 'ignore'
        }).on('exit', function(code) {
            assert.equal(code, 1);
            done();
        });
    });

    it('should exit 1 if it finds forbidden licenses license due to --failOn MIT;ISC', function(done) {
        spawn('node', [path.join(__dirname, '../bin/license-checker'), '--failOn', 'MIT,ISC'], {
            cwd: path.join(__dirname, '../'),
            stdio: 'ignore'
        }).on('exit', function(code) {
            assert.equal(code, 1);
            done();
        });
    });
});
<commit_msg>fix e2e test (transition from comma delimiter to semicolon)<commit_after>var assert = require('assert'),
    path = require('path'),
    spawn = require('child_process').spawn;

describe('bin/license-checker', function() {
    this.timeout(8000);
    it('should exit 1 if it finds a single license type (MIT) license due to --failOn MIT', function(done) {
        spawn('node', [path.join(__dirname, '../bin/license-checker'), '--failOn', 'MIT'], {
            cwd: path.join(__dirname, '../'),
            stdio: 'ignore'
        }).on('exit', function(code) {
            assert.equal(code, 1);
            done();
        });
    });

    it('should exit 1 if it finds forbidden licenses license due to --failOn MIT;ISC', function(done) {
        spawn('node', [path.join(__dirname, '../bin/license-checker'), '--failOn', 'MIT;ISC'], {
            cwd: path.join(__dirname, '../'),
            stdio: 'ignore'
        }).on('exit', function(code) {
            assert.equal(code, 1);
            done();
        });
    });
});
<|endoftext|>


<commit_before>function TransactionGenerationController($scope, userService){

  $scope.prepareTransaction = function(txType, data, from, $modalScope){
    var addressData = userService.getAddress(from);
    var privKey = new Bitcoin.ECKey.decodeEncryptedFormat(addressData.privkey, addressData.address); // Using address as temporary password
    var pubKey = privKey.getPubKeyHex();

    $scope.TxPromise = walletTransactionService.getUnsignedTransaction(txType,data);
    $scope.TxPromise.then(function(successData) {
      var successData = successData.data;
      if (successData.status != 200) {
        $modalScope.waiting = false;
        $modalScope.issueError = true;
        $modalScope.error = 'Error preparing Property Issuance transaction: ' + successData.data;
      } else {
        var unsignedTransaction = successData.unsignedhex;

        try {
          var bytes = Bitcoin.Util.hexToBytes(unsignedTransaction);
          var transaction = Bitcoin.Transaction.deserialize(bytes);
          var script = parseScript(successData.sourceScript);

          transaction.ins.forEach(function(input) {
            input.script = script;
          });

          //DEBUG console.log('before',transaction, Bitcoin.Util.bytesToHex(transaction.serialize()));
          var signedSuccess = transaction.signWithKey(privKey);

          var finalTransaction = Bitcoin.Util.bytesToHex(transaction.serialize());

          //Showing the user the transaction hash doesn't work right now
          //var transactionHash = Bitcoin.Util.bytesToHex(transaction.getHash().reverse());

          walletTransactionService.pushSignedTransaction(finalTransaction).then(function(successData) {
            var successData = successData.data;
            if (successData.pushed.match(/submitted|success/gi) != null) {
              $modalScope.waiting = false;
              $modalScope.issueSuccess = true;
              $modalScope.url = 'http://blockchain.info/address/' + from + '?sort=0';
            } else {
              $modalScope.waiting = false;
              $modalScope.issueError = true;
              $modalScope.error = successData.pushed; //Unspecified error, show user
            }
          }, function(errorData) {
            $modalScope.waiting = false;
            $modalScope.issueError = true;
            if (errorData.message)
              $modalScope.error = 'Server error: ' + errorData.message;
            else
              if (errorData.data)
                $modalScope.error = 'Server error: ' + errorData.data;
              else
                $modalScope.error = 'Unknown Server Error';
            console.error(errorData);
          });

          //DEBUG console.log(addressData, privKey, bytes, transaction, script, signedSuccess, finalTransaction );
          function parseScript(script) {
            var newScript = new Bitcoin.Script();
            var s = script.split(" ");
            for (var i = 0; i < s.length; i++) {
              if (Bitcoin.Opcode.map.hasOwnProperty(s[i])) {
                newScript.writeOp(Bitcoin.Opcode.map[s[i]]);
              } else {
                newScript.writeBytes(Bitcoin.Util.hexToBytes(s[i]));
              }
            }
            return newScript;
          }
        } catch (e) {
          $modalScope.sendError = true;
          if (e.message)
            $modalScope.error = 'Error sending transaction: ' + e.message;
          else
            if (e.data)
              $modalScope.error = 'Error sending transaction: ' + e.data;
            else
              $modalScope.error = 'Unknown error sending transaction';
          console.error(e);
        }
      }
    }, function(errorData) {
      $modalScope.sendError = true;
      if (errorData.message)
        $modalScope.error = 'Server error: ' + errorData.message;
      else
        if (errorData.data)
          $modalScope.error = 'Server error: ' + errorData.data;
        else
          $modalScope.error = 'Unknown Server Error';
      console.error(errorData);
    });
  };
};<commit_msg>Moved walletTransactionService<commit_after>function TransactionGenerationController($scope, userService, walletTransactionService){

  $scope.prepareTransaction = function(txType, data, from, $modalScope){
    var addressData = userService.getAddress(from);
    var privKey = new Bitcoin.ECKey.decodeEncryptedFormat(addressData.privkey, addressData.address); // Using address as temporary password
    var pubKey = privKey.getPubKeyHex();

    $scope.TxPromise = walletTransactionService.getUnsignedTransaction(txType,data);
    $scope.TxPromise.then(function(successData) {
      var successData = successData.data;
      if (successData.status != 200) {
        $modalScope.waiting = false;
        $modalScope.issueError = true;
        $modalScope.error = 'Error preparing Property Issuance transaction: ' + successData.data;
      } else {
        var unsignedTransaction = successData.unsignedhex;

        try {
          var bytes = Bitcoin.Util.hexToBytes(unsignedTransaction);
          var transaction = Bitcoin.Transaction.deserialize(bytes);
          var script = parseScript(successData.sourceScript);

          transaction.ins.forEach(function(input) {
            input.script = script;
          });

          //DEBUG console.log('before',transaction, Bitcoin.Util.bytesToHex(transaction.serialize()));
          var signedSuccess = transaction.signWithKey(privKey);

          var finalTransaction = Bitcoin.Util.bytesToHex(transaction.serialize());

          //Showing the user the transaction hash doesn't work right now
          //var transactionHash = Bitcoin.Util.bytesToHex(transaction.getHash().reverse());

          walletTransactionService.pushSignedTransaction(finalTransaction).then(function(successData) {
            var successData = successData.data;
            if (successData.pushed.match(/submitted|success/gi) != null) {
              $modalScope.waiting = false;
              $modalScope.issueSuccess = true;
              $modalScope.url = 'http://blockchain.info/address/' + from + '?sort=0';
            } else {
              $modalScope.waiting = false;
              $modalScope.issueError = true;
              $modalScope.error = successData.pushed; //Unspecified error, show user
            }
          }, function(errorData) {
            $modalScope.waiting = false;
            $modalScope.issueError = true;
            if (errorData.message)
              $modalScope.error = 'Server error: ' + errorData.message;
            else
              if (errorData.data)
                $modalScope.error = 'Server error: ' + errorData.data;
              else
                $modalScope.error = 'Unknown Server Error';
            console.error(errorData);
          });

          //DEBUG console.log(addressData, privKey, bytes, transaction, script, signedSuccess, finalTransaction );
          function parseScript(script) {
            var newScript = new Bitcoin.Script();
            var s = script.split(" ");
            for (var i = 0; i < s.length; i++) {
              if (Bitcoin.Opcode.map.hasOwnProperty(s[i])) {
                newScript.writeOp(Bitcoin.Opcode.map[s[i]]);
              } else {
                newScript.writeBytes(Bitcoin.Util.hexToBytes(s[i]));
              }
            }
            return newScript;
          }
        } catch (e) {
          $modalScope.sendError = true;
          if (e.message)
            $modalScope.error = 'Error sending transaction: ' + e.message;
          else
            if (e.data)
              $modalScope.error = 'Error sending transaction: ' + e.data;
            else
              $modalScope.error = 'Unknown error sending transaction';
          console.error(e);
        }
      }
    }, function(errorData) {
      $modalScope.sendError = true;
      if (errorData.message)
        $modalScope.error = 'Server error: ' + errorData.message;
      else
        if (errorData.data)
          $modalScope.error = 'Server error: ' + errorData.data;
        else
          $modalScope.error = 'Unknown Server Error';
      console.error(errorData);
    });
  };
};<|endoftext|>


<commit_before>import { caution } from '../images';
import { fieldGeneratorMapping } from '../shared';
import { oppositesToDropdown } from '../../utils';
import config from '../../../../common/const';
import { translate } from '../../../../../common/i18n';

export const marketDropdown = block => {
    block
        .appendDummyInput('MARKETDEFINITION')
        .appendField(`${translate('Market')}:`)
        .appendField(new Blockly.FieldDropdown(fieldGeneratorMapping.MARKET_LIST), 'MARKET_LIST')
        .appendField('>')
        .appendField(new Blockly.FieldDropdown(fieldGeneratorMapping.SUBMARKET_LIST(block)), 'SUBMARKET_LIST')
        .appendField('>')
        .appendField(new Blockly.FieldDropdown(fieldGeneratorMapping.SYMBOL_LIST(block)), 'SYMBOL_LIST');
};

export const tradeTypeDropdown = block => {
    block
        .appendDummyInput('TRADETYPEDEFINITION')
        .appendField(`${translate('Trade Type')}:`)
        .appendField(new Blockly.FieldDropdown(fieldGeneratorMapping.TRADETYPECAT_LIST(block)), 'TRADETYPECAT_LIST')
        .appendField('>')
        .appendField(new Blockly.FieldDropdown(fieldGeneratorMapping.TRADETYPE_LIST(block)), 'TRADETYPE_LIST');
};

export const contractTypes = block => {
    if (!block.getInput('CONTRACT_TYPE')) {
        const getContractTypes = () => {
            const tradeType = block.getFieldValue('TRADETYPE_LIST');
            if (tradeType) {
                return [[translate('Both'), 'both'], ...oppositesToDropdown(config.opposites[tradeType.toUpperCase()])];
            }
            return [['', '']];
        };
        block
            .appendDummyInput('CONTRACT_TYPE')
            .appendField(translate('Contract Type:'))
            .appendField(new Blockly.FieldDropdown(getContractTypes), 'TYPE_LIST');
    }
};

export const candleInterval = block => {
    if (!block.getInput('CANDLE_INTERVAL')) {
        block
            .appendDummyInput('CANDLE_INTERVAL')
            .appendField(translate('Default Candle Interval:'))
            .appendField(new Blockly.FieldDropdown(config.candleIntervals.slice(1)), 'CANDLEINTERVAL_LIST');
    }
};

export const duration = block => {
    if (!block.getInput('DURATION')) {
        block
            .appendValueInput('DURATION')
            .setCheck('Number')
            .appendField(translate('Duration:'))
            .appendField(new Blockly.FieldDropdown([['', '']]), 'DURATIONTYPE_LIST');
    }
};

export const payout = block => {
    if (!block.getInput('AMOUNT')) {
        block
            .appendValueInput('AMOUNT')
            .setCheck('Number')
            .appendField(`${translate('Stake')}:`)
            .appendField(new Blockly.FieldDropdown(config.lists.CURRENCY), 'CURRENCY_LIST');
    }
};

export const barrierOffset = block => {
    if (!block.getInput('BARRIEROFFSET')) {
        block
            .appendValueInput('BARRIEROFFSET')
            .setCheck('Number')
            .appendField(`${translate('Barrier Offset')} 1:`)
            .appendField(new Blockly.FieldDropdown(config.barrierTypes), 'BARRIEROFFSETTYPE_LIST');
    } else {
        const barrierOffsetList = block.getField('BARRIEROFFSETTYPE_LIST');

        if (
            !block.workspace.getBlockById('BARRIERVALUE') &&
            !block.getInput('BARRIEROFFSET').connection.isConnected()
        ) {
            const barrierValue = block.workspace.newBlock('math_number', 'BARRIERVALUE');
            barrierOffsetList.setValue('+');
            barrierValue.setFieldValue('0.27', 'NUM');
            barrierValue.setShadow(true);
            barrierValue.outputConnection.connect(block.getInput('BARRIEROFFSET').connection);
            barrierValue.initSvg();
            barrierValue.render();
        }
    }
};

export const secondBarrierOffset = block => {
    if (!block.getInput('SECONDBARRIEROFFSET')) {
        block
            .appendValueInput('SECONDBARRIEROFFSET')
            .setCheck('Number')
            .appendField(`${translate('Barrier Offset')} 2:`)
            .appendField(new Blockly.FieldDropdown(config.barrierTypes), 'SECONDBARRIEROFFSETTYPE_LIST');
    } else {
        const barrierOffsetList = block.getField('SECONDBARRIEROFFSETTYPE_LIST');

        if (
            !block.workspace.getBlockById('SECONDBARRIERVALUE') &&
            !block.getInput('SECONDBARRIEROFFSET').connection.isConnected()
        ) {
            const secondBarrierValue = block.workspace.newBlock('math_number', 'SECONDBARRIERVALUE');
            barrierOffsetList.setValue('-');
            secondBarrierValue.setFieldValue('0.27', 'NUM');
            secondBarrierValue.setShadow(true);
            secondBarrierValue.outputConnection.connect(block.getInput('SECONDBARRIEROFFSET').connection);
            secondBarrierValue.initSvg();
            secondBarrierValue.render();
        }
    }
};

export const prediction = block => {
    if (!block.getInput('PREDICTION')) {
        block
            .appendValueInput('PREDICTION')
            .setCheck('Number')
            .appendField(translate('Prediction:'));
    }
};

export const restart = block => {
    block
        .appendDummyInput()
        .appendField(`${translate('Restart buy/sell on error')}`)
        .appendField(`(${translate('disable for better performance')}):`)
        .appendField(new Blockly.FieldCheckbox('FALSE'), 'TIME_MACHINE_ENABLED');
    block
        .appendDummyInput()
        .appendField(`${translate('Restart last trade on error')}`)
        .appendField(`(${translate('bot ignores the unsuccessful trade')}):`)
        .appendField(new Blockly.FieldCheckbox('TRUE'), 'RESTARTONERROR')
        .appendField(new Blockly.FieldImage(caution, 15, 15, '!'));
};
<commit_msg>Create common function for generating barriers, hide fields by default<commit_after>import { caution } from '../images';
import { fieldGeneratorMapping } from '../shared';
import { oppositesToDropdown } from '../../utils';
import config from '../../../../common/const';
import { translate } from '../../../../../common/i18n';

export const marketDropdown = block => {
    block
        .appendDummyInput('MARKETDEFINITION')
        .appendField(`${translate('Market')}:`)
        .appendField(new Blockly.FieldDropdown(fieldGeneratorMapping.MARKET_LIST), 'MARKET_LIST')
        .appendField('>')
        .appendField(new Blockly.FieldDropdown(fieldGeneratorMapping.SUBMARKET_LIST(block)), 'SUBMARKET_LIST')
        .appendField('>')
        .appendField(new Blockly.FieldDropdown(fieldGeneratorMapping.SYMBOL_LIST(block)), 'SYMBOL_LIST');
};

export const tradeTypeDropdown = block => {
    block
        .appendDummyInput('TRADETYPEDEFINITION')
        .appendField(`${translate('Trade Type')}:`)
        .appendField(new Blockly.FieldDropdown(fieldGeneratorMapping.TRADETYPECAT_LIST(block)), 'TRADETYPECAT_LIST')
        .appendField('>')
        .appendField(new Blockly.FieldDropdown(fieldGeneratorMapping.TRADETYPE_LIST(block)), 'TRADETYPE_LIST');
};

export const contractTypes = block => {
    if (!block.getInput('CONTRACT_TYPE')) {
        const getContractTypes = () => {
            const tradeType = block.getFieldValue('TRADETYPE_LIST');
            if (tradeType) {
                return [[translate('Both'), 'both'], ...oppositesToDropdown(config.opposites[tradeType.toUpperCase()])];
            }
            return [['', '']];
        };
        block
            .appendDummyInput('CONTRACT_TYPE')
            .appendField(translate('Contract Type:'))
            .appendField(new Blockly.FieldDropdown(getContractTypes), 'TYPE_LIST');
    }
};

export const candleInterval = block => {
    if (!block.getInput('CANDLE_INTERVAL')) {
        block
            .appendDummyInput('CANDLE_INTERVAL')
            .appendField(translate('Default Candle Interval:'))
            .appendField(new Blockly.FieldDropdown(config.candleIntervals.slice(1)), 'CANDLEINTERVAL_LIST');
    }
};

export const duration = block => {
    if (!block.getInput('DURATION')) {
        block
            .appendValueInput('DURATION')
            .setCheck('Number')
            .appendField(translate('Duration:'))
            .appendField(new Blockly.FieldDropdown([['', '']]), 'DURATIONTYPE_LIST');
    }
};

export const payout = block => {
    if (!block.getInput('AMOUNT')) {
        block
            .appendValueInput('AMOUNT')
            .setCheck('Number')
            .appendField(`${translate('Stake')}:`)
            .appendField(new Blockly.FieldDropdown(config.lists.CURRENCY), 'CURRENCY_LIST');
    }
};

const barrierOffsetGenerator = (inputName, block) => {
    if (!block.getInput(inputName)) {
        // Determine amount of barrier-blocks on workspace
        const labelPrefix = translate('Barrier Offset');
        const barrierNumber = block.inputList.filter(input => /BARRIEROFFSET$/.test(input.name)).length;

        // Set barrier options according to barrierNumber (i.e. + and -)
        const barrierOffsetList = new Blockly.FieldDropdown(config.barrierTypes);
        barrierOffsetList.setValue(config.barrierTypes[barrierNumber % config.barrierTypes.length][1]);

        block
            .appendValueInput(inputName)
            .setCheck('Number')
            .appendField(`${labelPrefix} ${barrierNumber + 1}:`)
            .appendField(barrierOffsetList, `${inputName}TYPE_LIST`);

        const input = block.getInput(inputName);
        input.setVisible(false);
    }
};

export const barrierOffset = block => {
    barrierOffsetGenerator('BARRIEROFFSET', block);
};

export const secondBarrierOffset = block => {
    barrierOffsetGenerator('SECONDBARRIEROFFSET', block);
};

export const prediction = block => {
    const inputName = 'PREDICTION';
    if (!block.getInput(inputName)) {
        block
            .appendValueInput(inputName)
            .setCheck('Number')
            .appendField(`${translate('Prediction')}:`);

        const input = block.getInput(inputName);
        input.setVisible(false);
    }
};

export const restart = block => {
    block
        .appendDummyInput()
        .appendField(`${translate('Restart buy/sell on error')}`)
        .appendField(`(${translate('disable for better performance')}):`)
        .appendField(new Blockly.FieldCheckbox('FALSE'), 'TIME_MACHINE_ENABLED');
    block
        .appendDummyInput()
        .appendField(`${translate('Restart last trade on error')}`)
        .appendField(`(${translate('bot ignores the unsuccessful trade')}):`)
        .appendField(new Blockly.FieldCheckbox('TRUE'), 'RESTARTONERROR')
        .appendField(new Blockly.FieldImage(caution, 15, 15, '!'));
};
<|endoftext|>


<commit_before>/*
 *  Copyright 2014 TWO SIGMA OPEN SOURCE, LLC
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

(function () {
  'use strict';
  var retfunc = function (plotUtils) {

    var PlotTreeMapNode = function (data) {
      _(this).extend(data); // copy properties to itself
    };

    PlotTreeMapNode.prototype.isRoot = function () {
      return this.root === true;
    };

    PlotTreeMapNode.prototype.hideTips = function (scope, hidden) {
      //dummy function
    };

    PlotTreeMapNode.prototype.setHighlighted = function (scope, highlighted) {
      if (this.isRoot())
        return;
      var itemsvg = scope.maing.select("g").select("#" + this.id);
      if (highlighted) {
        itemsvg.node().parentNode.appendChild(itemsvg.node()); // workaround for bringing elements to the front (ie z-index)
      }
      itemsvg
        .transition()
        .duration(plotUtils.getHighlightDuration())
        .select("rect")
        .style("stroke", highlighted ? "#000000" : "#FFFFFF")
        .style("stroke-width", highlighted ? 2 : 0.2)
        .style("opacity", highlighted ? 0.9 : 1.0)
      ;
    };

    PlotTreeMapNode.prototype.prepare = function (scope) {
      if (!this.isRoot())
        return;

      var margin = {top: 0, right: 0, bottom: 0, left: 0},
        width = (scope ? plotUtils.safeWidth(scope.jqsvg) : 300) - margin.left - margin.right,
        height = (scope ? plotUtils.safeHeight(scope.jqsvg) : 200) - margin.top - margin.bottom;

      var treemap = d3.layout.treemap()
        .round(false)
        .size([width, height])
        .sticky(true)
        .value(function (d) {
          return d.showItem === true ? scope.stdmodel.valueAccessor === 'VALUE' ? d.doubleValue : d.weight : 0;
        });

      if (scope.stdmodel.mode) {
        treemap.mode(scope.stdmodel.mode)
      }
      if (scope.stdmodel.sticky) {
        treemap.sticky(scope.stdmodel.sticky)
      }
      if (scope.stdmodel.ratio) {
        treemap.ratio(scope.stdmodel.ratio)
      }
      if (scope.stdmodel.round) {
        treemap.round(scope.stdmodel.round)
      }

      this.nodes = treemap
        .nodes(this)
        .filter(function (d) {
          return !d.children || d.children.length === 0;
        });
    };

    PlotTreeMapNode.prototype.render = function (scope) {
      if (!this.isRoot())
        return;

      this.clear(scope);
      if (scope.showAllItems) {
        var hasVisible = false;
        var visitor = {

          visit: function (node) {
            if (!node.children && node.showItem === true)
              hasVisible = true;
          }
        };
        scope.stdmodel.process(visitor);
        if (hasVisible === true) {
          this.draw(scope);
        }
      }
    };

    PlotTreeMapNode.prototype.draw = function (scope) {

      var zoomed = function () {
        svg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
        setTextStyles();
      };

      var setTextStyles = function () {
        svg.selectAll("text")
          .style('font-size', function (d) {
            var scale = d3.event && d3.event.scale ? d3.event.scale : 1;
            var size = Math.min(18 / scale, Math.floor(d.dx));
            return size + "px"
          })
          .attr("textLength", function (d) {
            return this.getComputedTextLength() < d.dx ? this.getComputedTextLength() : d.dx;
          })
          .style("opacity", function (d) {
            d.w = this.getComputedTextLength();
            return d.dx > d.w && d.showItem === true ? 1 : 0;
          })
        ;
      };

      if (!this.isRoot())
        return;

      this.prepare(scope);

      var zoom = d3.behavior.zoom().scaleExtent([1, 10]);

      var enableZoom = function () {
        scope.maing.call(zoom.on("zoom", zoomed));
        scope.maing.call(zoom)
          .on("dblclick.zoom", function () {
            svg.attr("transform", "translate(" + [0, 0] + ")scale(" + 1 + ")");
            setTextStyles();
          });
      };

      var disableZoom = function () {
        scope.maing.call(zoom.on("zoom", null));
        scope.maing.on("wheel.zoom", null);
      };

      // set zoom object
      scope.maing.on("focusin", function () {
        enableZoom();
      }).on("focusout", function () {
        disableZoom();
      });

      scope.maing.call(zoom)
        .on("dblclick.zoom", function () {
          svg.attr("transform", "translate(" + [0, 0] + ")scale(" + 1 + ")");
          setTextStyles();
        });

      var svg = scope.maing.append("svg:g");
      var cell = svg.selectAll("g")
          .data(this.nodes)
          .enter().append('svg:g')
          .attr('class', 'cell')
          .attr("id", function (d) {
            return d.id;
          })
          .attr('transform', function (d) {
            return 'translate(' + d.x + ',' + d.y + ')';
          })
          .on("mouseover", function (d) {
            if (scope.stdmodel.useToolTip === true && d.tooltip) {
              scope.tooltip.style("visibility", "visible");
              scope.tooltip.transition().duration(200).style("opacity", 0.9);
            }
          })
          .on("mousemove", function (d) {
            var xPosition = d3.event.layerX + 2;
            var yPosition = d3.event.layerY - 2;

            scope.tooltip
              .style("left", xPosition + "px")
              .style("top", yPosition + "px");

            if (d.tooltip) {
              scope.tooltip.html(d.tooltip);
            }
          })
          .on("mouseout", function () {
            scope.tooltip.transition().duration(500).style("opacity", 0);
          })
        ;

      cell.append("svg:rect")
        .attr("width", function (d) {
          return Math.max(0, d.dx - 0.2);
        })
        .attr("height", function (d) {
          return Math.max(0, d.dy - 0.2);
        })
        .style("fill", function (d) {
          return d.children ? null : d.color;
        })
      ;

      cell.append("svg:text")
        .attr("x", function (d) {
          return d.dx / 2;
        })
        .attr("y", function (d) {
          return d.dy / 2;
        })
        .attr("cursor", "default")
        .attr("text-anchor", "middle")
        .text(function (d) {
          return d.children ? null : d.label;
        });
      setTextStyles();
      disableZoom();
    };

    PlotTreeMapNode.prototype.clear = function (scope) {
      if (!this.isRoot())
        return;
      scope.maing.selectAll("*").remove();
    };

    return PlotTreeMapNode;
  };
  beakerRegister.bkoFactory('PlotTreeMapNode', ['plotUtils', retfunc]);
})();<commit_msg>#4536 upgrade treemap code for d3v4<commit_after>/*
 *  Copyright 2014 TWO SIGMA OPEN SOURCE, LLC
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

(function () {
  'use strict';
  var retfunc = function (plotUtils) {

    var PlotTreeMapNode = function (data) {
      _(this).extend(data); // copy properties to itself
    };

    PlotTreeMapNode.prototype.isRoot = function () {
      return this.root === true;
    };

    PlotTreeMapNode.prototype.hideTips = function (scope, hidden) {
      //dummy function
    };

    PlotTreeMapNode.prototype.setHighlighted = function (scope, highlighted) {
      if (this.isRoot())
        return;
      var itemsvg = scope.maing.select("g").select("#" + this.id);
      if (highlighted) {
        itemsvg.node().parentNode.appendChild(itemsvg.node()); // workaround for bringing elements to the front (ie z-index)
      }
      itemsvg
        .transition()
        .duration(plotUtils.getHighlightDuration())
        .select("rect")
        .style("stroke", highlighted ? "#000000" : "#FFFFFF")
        .style("stroke-width", highlighted ? 2 : 0.2)
        .style("opacity", highlighted ? 0.9 : 1.0)
      ;
    };

    PlotTreeMapNode.prototype.prepare = function (scope) {
      if (!this.isRoot())
        return;

      console.log('THIS', this);

      var margin = {top: 0, right: 0, bottom: 0, left: 0},
        width = (scope ? plotUtils.safeWidth(scope.jqsvg) : 300) - margin.left - margin.right,
        height = (scope ? plotUtils.safeHeight(scope.jqsvg) : 200) - margin.top - margin.bottom;

      // assign ratio
      this.ratio = scope.stdmodel.ratio === undefined ? 1 : scope.stdmodel.ratio;

      console.log('size', [width, height]);
      var treemap = d3.treemap()
        .round(false)
        .size([width / this.ratio, height]);
      // .sticky(true)

      // mode
      var currentModeFn = this.getModeFn(scope.stdmodel.mode);
      treemap.tile(currentModeFn);

      if (scope.stdmodel.round) {
        treemap.round(scope.stdmodel.round)
      }

      // if (scope.stdmodel.sticky) {
      //   treemap.sticky(scope.stdmodel.sticky)
      // }

      console.log('prepare', this);

      this.hierarchy = d3.hierarchy(this);

      this.hierarchy
        .sum(function(d) {
          return d.showItem === true ? scope.stdmodel.valueAccessor === 'VALUE' ? d.doubleValue : d.weight : 0;
        })
        .sort(function(a, b) { return a.value - b.value; });

      console.log('hierarchy', this.hierarchy);

      // treemap(this.hierarchy);

      this.nodes = this.hierarchy.leaves();
      // .filter(function (d) {
      //   console.log('d',d);
      //   return !d.children || d.children.length === 0;
      // });
    };

    PlotTreeMapNode.prototype.render = function (scope) {
      if (!this.isRoot())
        return;

      this.clear(scope);
      if (scope.showAllItems) {
        var hasVisible = false;
        var visitor = {

          visit: function (node) {
            if (!node.children && node.showItem === true)
              hasVisible = true;
          }
        };
        scope.stdmodel.process(visitor);
        if (hasVisible === true) {
          this.draw(scope);
        }
      }
    };

    PlotTreeMapNode.prototype.draw = function (scope) {
      var self = this;

      var zoomed = function () {
        svg.attr("transform", d3.event.transform);
        setTextStyles();
      };

      var setTextStyles = function () {
        svg.selectAll("text")
          .style('font-size', function (d) {
            var scale = d3.event && d3.event.scale ? d3.event.scale : 1;
            var size = Math.min(18 / scale, Math.floor(d.x1 - d.x0));
            return size + "px"
          })
          .attr("textLength", function (d) {
            return this.getComputedTextLength() < d.x1 - d.x0 ? this.getComputedTextLength() : d.x1 - d.x0;
          })
          .style("opacity", function (d) {
            d.w = this.getComputedTextLength();
            return d.x1 - d.x0 > d.w && d.data.showItem === true ? 1 : 0;
          })
        ;
      };

      if (!this.isRoot())
        return;

      this.prepare(scope);

      var zoom = d3.zoom().scaleExtent([1, 10]);

      var enableZoom = function () {
        scope.maing.call(zoom.on("zoom", zoomed));
        scope.maing.call(zoom)
          .on("dblclick.zoom", function () {
            svg.attr("transform", "translate(" + [0, 0] + ")scale(" + 1 + ")");
            setTextStyles();
          });
      };

      var disableZoom = function () {
        scope.maing.call(zoom.on("zoom", null));
        scope.maing.on("wheel.zoom", null);
      };

      // set zoom object
      scope.maing.on("focusin", function () {
        enableZoom();
      }).on("focusout", function () {
        disableZoom();
      });

      scope.maing.call(zoom)
        .on("dblclick.zoom", function () {
          svg.attr("transform", "translate(" + [0, 0] + ")scale(" + 1 + ")");
          setTextStyles();
        });

      console.log('LEAVES', this.hierarchy.leaves());

      var svg = scope.maing.append("svg:g");
      var cell = svg.selectAll("g")
          .data(this.nodes)
          .enter().append('svg:g')
          .attr('class', 'cell')
          .attr("id", function (d) {
            return d.data.id;
          })
          .on("mouseover", function (d) {
            if (scope.stdmodel.useToolTip === true && d.data.tooltip) {
              scope.tooltip.style("visibility", "visible");
              scope.tooltip.transition().duration(200).style("opacity", 0.9);
            }
          })
          .on("mousemove", function (d) {
            var xPosition = d3.event.layerX + 2;
            var yPosition = d3.event.layerY - 2;

            scope.tooltip
              .style("left", xPosition + "px")
              .style("top", yPosition + "px");

            if (d.data.tooltip) {
              scope.tooltip.html(d.data.tooltip);
            }
          })
          .on("mouseout", function () {
            scope.tooltip.transition().duration(500).style("opacity", 0);
          })
        ;

      cell.append("svg:rect")
        .attr('transform', function (d) {
          return 'translate(' + d.x0 * self.ratio + ',' + d.y0 + ')';
        })
        .attr("width", function (d) {
          return Math.max(0, d.x1 * self.ratio - d.x0 * self.ratio - 0.2);
        })
        .attr("height", function (d) {
          return Math.max(0, d.y1 - d.y0 - 0.2);
        })
        .style("fill", function (d) {
          return d.children ? null : d.data.color;
        })
        .style("stroke", '#fff');

      cell.append("svg:text")
        .attr("x", function (d) {
          return (d.x0 + ((d.x1 - d.x0) / 2)) * self.ratio;
        })
        .attr("y", function (d) {
          return d.y0 + ((d.y1 - d.y0) / 2);
        })
        .attr("cursor", "default")
        .attr("text-anchor", "middle")
        .text(function (d) {
          return d.children ? null : d.data.label;
        });

      setTextStyles();
      disableZoom();
    };

    PlotTreeMapNode.prototype.getModeFn = function(modeName) {
      var res = null;

      modeName = modeName || '';

      if (modeName === 'squarify') {
        res = d3.treemapSquarify;
      } else if (modeName === 'dice') {
        res = d3.treemapDice;
      } else if (modeName === 'binary') {
        res = d3.treemapBinary;
      } else if (modeName === 'slice') {
        res = d3.treemapSlice;
      } else if (modeName === 'slice-dic') {
        res = d3.treemapSliceDice;
      } else if (modeName === 'resquarify') {
        res = d3.treemapResquarify;
      } else {
        res = d3.treemapSquarify;
      }
      return res;
    };

    PlotTreeMapNode.prototype.clear = function (scope) {
      if (!this.isRoot())
        return;
      scope.maing.selectAll("*").remove();
    };

    return PlotTreeMapNode;
  };
  beakerRegister.bkoFactory('PlotTreeMapNode', ['plotUtils', retfunc]);
})();<|endoftext|>


<commit_before>/*
 * SPEasyForms ShowAddOnsVersion - show the current AddOns version on the
 * About dialog.
 *
 * @version 2015.00.03
 * @requires SPEasyForms v2014.01
 * @copyright 2014-2015 Joe McShea
 * @license under the MIT license:
 *    http://www.opensource.org/licenses/mit-license.php
 */

/* global spefjQuery */
(function ($, undefined) {

    // return without doing anything if SPEasyForms has not been loaded
    if (!$.spEasyForms) return;

    // only operate on the
    if (window.location.href.toLowerCase().indexOf("speasyformssettings.aspx") > -1) {
        $().ready(function () {
            $("b:contains('Version: 2014.01')").parent().append("
AddOns: 2015.00.03");
        });
    }

})(spefjQuery);
<commit_msg>fixed comment<commit_after>/*
 * SPEasyForms ShowAddOnsVersion - show the current AddOns version on the
 * About dialog.
 *
 * @version 2015.00.03
 * @requires SPEasyForms v2014.01
 * @copyright 2014-2015 Joe McShea
 * @license under the MIT license:
 *    http://www.opensource.org/licenses/mit-license.php
 */

/* global spefjQuery */
(function ($, undefined) {

    // return without doing anything if SPEasyForms has not been loaded
    if (!$.spEasyForms) return;

    // only operate on the settings page
    if (window.location.href.toLowerCase().indexOf("speasyformssettings.aspx") > -1) {
        $().ready(function () {
            $("b:contains('Version: 2014.01')").parent().append("
AddOns: 2015.00.03");
        });
    }

})(spefjQuery);
<|endoftext|>


<commit_before>module("jquery/view/ejs, rendering",{
	setup : function(){

		this.animals = ['sloth', 'bear', 'monkey']
		if(!this.animals.each){
			this.animals.each = function(func){
				for(var i =0; i < this.length; i++){
					func(this[i])
				}
			}
		}

		this.squareBrackets = "
[% this.animals.each(function(animal){%]" +
		               "
[%= animal %]
" +
			      "[%});%]
"
	    this.squareBracketsNoThis = "
[% animals.each(function(animal){%]" +
		               "
[%= animal %]
" +
			      "[%});%]
"
	    this.angleBracketsNoThis  = "
<% animals.each(function(animal){%>" +
		               "
<%= animal %>
" +
			      "<%});%>
";

	}
})
test("render with left bracket", function(){
	var compiled = new $.EJS({text: this.squareBrackets, type: '['}).render({animals: this.animals})
	equals(compiled, "

sloth

bear

monkey

", "renders with bracket")
})
test("render with with", function(){
	var compiled = new $.EJS({text: this.squareBracketsNoThis, type: '['}).render({animals: this.animals}) ;
	equals(compiled, "

sloth

bear

monkey

", "renders bracket with no this")
})
test("default carrot", function(){
	var compiled = new $.EJS({text: this.angleBracketsNoThis}).render({animals: this.animals}) ;

	equals(compiled, "

sloth

bear

monkey

")
})
test("render with double angle", function(){
	var text = "<%% replace_me %>"+
			  "
<% animals.each(function(animal){%>" +
	               "
<%= animal %>
" +
		      "<%});%>
";
	var compiled = new $.EJS({text: text}).render({animals: this.animals}) ;
	equals(compiled, "<% replace_me %>

sloth

bear

monkey

", "works")
});

test("comments", function(){
	var text = "<%# replace_me %>"+
			  "
<% animals.each(function(animal){%>" +
	               "
<%= animal %>
" +
		      "<%});%>
";
	var compiled = new $.EJS({text: text}).render({animals: this.animals}) ;
	equals(compiled,"

sloth

bear

monkey

" )
});

test("multi line", function(){
	var text = "a \n b \n c",
		result = new $.EJS({text: text}).render({}) ;

	equals(result, text)
})

test("escapedContent", function(){
	var text = "<%= tags %>&<%= number %><input value='<%= quotes %>'/>";
	var compiled = new $.EJS({text: text}).render({tags: "foo < bar < car > zar > poo",
							quotes : "I use 'quote' fingers \"a lot\"",
							number : 123}) ;

	var div = $('
').html(compiled)
	equals(div.find('span').text(), "foo < bar < car > zar > poo" );
	equals(div.find('strong').text(), 123 );
	equals(div.find('input').val(), "I use 'quote' fingers \"a lot\"" );
	equals(div.find('label').html(), "&" );
})

test("unescapedContent", function(){
	var text = "<%== tags %>
<%= tags %>
<input value='<%== quotes %>'/>";
	var compiled = new $.EJS({text: text}).render({tags: "foobar",
							quotes : "I use 'quote' fingers "a lot""}) ;

	var div = $('
').html(compiled)
	equals(div.find('span').text(), "foobar" );
	equals(div.find('div').text(), "foobar" );
	equals(div.find('span').html(), "foobar" );
	equals(div.find('input').val(), "I use 'quote' fingers \"a lot\"" );
})
<commit_msg>handle IE caps on tag names<commit_after>module("jquery/view/ejs, rendering",{
	setup : function(){

		this.animals = ['sloth', 'bear', 'monkey']
		if(!this.animals.each){
			this.animals.each = function(func){
				for(var i =0; i < this.length; i++){
					func(this[i])
				}
			}
		}

		this.squareBrackets = "
[% this.animals.each(function(animal){%]" +
		               "
[%= animal %]
" +
			      "[%});%]
"
	    this.squareBracketsNoThis = "
[% animals.each(function(animal){%]" +
		               "
[%= animal %]
" +
			      "[%});%]
"
	    this.angleBracketsNoThis  = "
<% animals.each(function(animal){%>" +
		               "
<%= animal %>
" +
			      "<%});%>
";

	}
})
test("render with left bracket", function(){
	var compiled = new $.EJS({text: this.squareBrackets, type: '['}).render({animals: this.animals})
	equals(compiled, "

sloth

bear

monkey

", "renders with bracket")
})
test("render with with", function(){
	var compiled = new $.EJS({text: this.squareBracketsNoThis, type: '['}).render({animals: this.animals}) ;
	equals(compiled, "

sloth

bear

monkey

", "renders bracket with no this")
})
test("default carrot", function(){
	var compiled = new $.EJS({text: this.angleBracketsNoThis}).render({animals: this.animals}) ;

	equals(compiled, "

sloth

bear

monkey

")
})
test("render with double angle", function(){
	var text = "<%% replace_me %>"+
			  "
<% animals.each(function(animal){%>" +
	               "
<%= animal %>
" +
		      "<%});%>
";
	var compiled = new $.EJS({text: text}).render({animals: this.animals}) ;
	equals(compiled, "<% replace_me %>

sloth

bear

monkey

", "works")
});

test("comments", function(){
	var text = "<%# replace_me %>"+
			  "
<% animals.each(function(animal){%>" +
	               "
<%= animal %>
" +
		      "<%});%>
";
	var compiled = new $.EJS({text: text}).render({animals: this.animals}) ;
	equals(compiled,"

sloth

bear

monkey

" )
});

test("multi line", function(){
	var text = "a \n b \n c",
		result = new $.EJS({text: text}).render({}) ;

	equals(result, text)
})

test("escapedContent", function(){
	var text = "<%= tags %>&<%= number %><input value='<%= quotes %>'/>";
	var compiled = new $.EJS({text: text}).render({tags: "foo < bar < car > zar > poo",
							quotes : "I use 'quote' fingers \"a lot\"",
							number : 123}) ;

	var div = $('
').html(compiled)
	equals(div.find('span').text(), "foo < bar < car > zar > poo" );
	equals(div.find('strong').text(), 123 );
	equals(div.find('input').val(), "I use 'quote' fingers \"a lot\"" );
	equals(div.find('label').html(), "&" );
})

test("unescapedContent", function(){
	var text = "<%== tags %>
<%= tags %>
<input value='<%== quotes %>'/>";
	var compiled = new $.EJS({text: text}).render({tags: "foobar",
							quotes : "I use 'quote' fingers "a lot""}) ;

	var div = $('
').html(compiled)
	equals(div.find('span').text(), "foobar" );
	equals(div.find('div').text().toLowerCase(), "foobar" );
	equals(div.find('span').html().toLowerCase(), "foobar" );
	equals(div.find('input').val(), "I use 'quote' fingers \"a lot\"" );
})
<|endoftext|>