<commit_before>
// Expose modules in ./support for demo purposes
require.paths.unshift(__dirname + '/../../support');

/**
 * Module dependencies.
 */

var express = require('../../lib/express'),
    crypto = require('crypto');

var app = express.createServer();

app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

app.use(express.bodyDecoder());
app.use(express.cookieDecoder());
app.use(express.session());

// Message helper, ideally we would use req.flash()
// however this is more light-weight for an example

app.dynamicHelpers({
    message: function(req){
        var err = req.session.error,
            msg = req.session.success;
        delete req.session.error;
        delete req.session.success;
        if (err) return '
' + err + '
';
        if (msg) return '
' + msg + '
';
    }
});

// Generate a salt for the user to prevent rainbow table attacks

var users = {
    tj: {
        name: 'tj',
        salt: 'randomly-generated-salt',
        pass: md5('foobar' + 'randomly-generated-salt')
    }
};

// Used to generate a hash of the plain-text password + salt

function md5(str) {
    return crypto.createHash('md5').update(str).digest('hex');
}

// Authenticate using our plain-object database of doom!

function authenticate(name, pass, fn) {
    var user = users[name];
    // query the db for the given username
    if (!user) return fn(new Error('cannot find user'));
    // apply the same algorithm to the POSTed password, applying
    // the md5 against the pass / salt, if there is a match we
    // found the user
    if (user.pass == md5(pass + user.salt)) return fn(null, user);
    // Otherwise password is invalid
    fn(new Error('invalid password'));
}

function restrict(req, res, next) {
  if (req.session.user) {
    next();
  } else {
    req.session.error = 'Access denied!';
    res.redirect('/login');
  }
}

function accessLogger(req, res, next) {
    console.log('/restricted accessed by %s', req.session.user.name);
    next();
}

app.get('/', function(req, res){
    res.redirect('/login');
});

app.get('/restricted', restrict, accessLogger, function(req, res){
    res.send('Wahoo! restricted area');
});

app.get('/logout', function(req, res){
    // destroy the user's session to log them out
    // will be re-created next request
    req.session.destroy(function(){
        res.redirect('home');
    });
});

app.get('/login', function(req, res){
    if (req.session.user) {
        req.session.success = 'Authenticated as ' + req.session.user.name
            + ' click to logout. '
            + ' You may now access /restricted.';
    }
    res.render('login');
});

app.post('/login', function(req, res){
    authenticate(req.body.username, req.body.password, function(err, user){
        if (user) {
            // Regenerate session when signing in
            // to prevent fixation
            req.session.regenerate(function(){
                // Store the user's primary key
                // in the session store to be retrieved,
                // or in this case the entire user object
                req.session.user = user;
                res.redirect('back');
            });
        } else {
            req.session.error = 'Authentication failed, please check your '
                + ' username and password.'
                + ' (use "tj" and "foobar")';
            res.redirect('back');
        }
    });
});

app.listen(3000);
console.log('Express started on port 3000');<commit_msg>refactored auth example<commit_after>
// Expose modules in ./support for demo purposes
require.paths.unshift(__dirname + '/../../support');

/**
 * Module dependencies.
 */

var express = require('../../lib/express')
  , crypto = require('crypto');

var app = express.createServer();

app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

app.use(express.bodyDecoder());
app.use(express.cookieDecoder());
app.use(express.session());

// Message helper, ideally we would use req.flash()
// however this is more light-weight for an example

app.dynamicHelpers({
  message: function(req){
    var err = req.session.error
      , msg = req.session.success;
    delete req.session.error;
    delete req.session.success;
    if (err) return '
' + err + '
';
    if (msg) return '
' + msg + '
';
  }
});

// Generate a salt for the user to prevent rainbow table attacks

var users = {
  tj: {
    name: 'tj'
    , salt: 'randomly-generated-salt'
    , pass: md5('foobar' + 'randomly-generated-salt')
  }
};

// Used to generate a hash of the plain-text password + salt

function md5(str) {
  return crypto.createHash('md5').update(str).digest('hex');
}

// Authenticate using our plain-object database of doom!

function authenticate(name, pass, fn) {
  var user = users[name];
  // query the db for the given username
  if (!user) return fn(new Error('cannot find user'));
  // apply the same algorithm to the POSTed password, applying
  // the md5 against the pass / salt, if there is a match we
  // found the user
  if (user.pass == md5(pass + user.salt)) return fn(null, user);
  // Otherwise password is invalid
  fn(new Error('invalid password'));
}

function restrict(req, res, next) {
  if (req.session.user) {
    next();
  } else {
    req.session.error = 'Access denied!';
    res.redirect('/login');
  }
}

function accessLogger(req, res, next) {
  console.log('/restricted accessed by %s', req.session.user.name);
  next();
}

app.get('/', function(req, res){
  res.redirect('/login');
});

app.get('/restricted', restrict, accessLogger, function(req, res){
  res.send('Wahoo! restricted area');
});

app.get('/logout', function(req, res){
  // destroy the user's session to log them out
  // will be re-created next request
  req.session.destroy(function(){
    res.redirect('home');
  });
});

app.get('/login', function(req, res){
  if (req.session.user) {
    req.session.success = 'Authenticated as ' + req.session.user.name
      + ' click to logout. '
      + ' You may now access /restricted.';
  }
  res.render('login');
});

app.post('/login', function(req, res){
  authenticate(req.body.username, req.body.password, function(err, user){
    if (user) {
      // Regenerate session when signing in
      // to prevent fixation
      req.session.regenerate(function(){
        // Store the user's primary key
        // in the session store to be retrieved,
        // or in this case the entire user object
        req.session.user = user;
        res.redirect('back');
      });
    } else {
      req.session.error = 'Authentication failed, please check your '
        + ' username and password.'
        + ' (use "tj" and "foobar")';
      res.redirect('back');
    }
  });
});

app.listen(3000);
console.log('Express started on port 3000');<|endoftext|>


<commit_before>/**
 * conduitjs - Give any method a pre/post invocation pipeline....
 * Author: Jim Cowart (http://freshbrewedcode.com/jimcowart)
 * Version: v0.3.2
 * Url: http://github.com/ifandelse/ConduitJS
 * License: MIT
 */
(function (root, factory) {
    if (typeof module === "object" && module.exports) {
        // Node, or CommonJS-Like environments
        module.exports = factory();
    } else if (typeof define === "function" && define.amd) {
        // AMD. Register as an anonymous module.
        define(factory(root));
    } else {
        // Browser globals
        root.Conduit = factory(root);
    }
}(this, function (global, undefined) {
    function Conduit(options) {
        if (typeof options.target !== "function") {
            throw new Error("You can only make functions into Conduits.");
        }
        var _steps = {
            pre: options.pre || [],
            post: options.post || [],
            all: []
        };
        var _defaultContext = options.context;
        var _target = options.target;
        var _targetStep = {
            isTarget: true,
            fn: options.sync ?
            function () {
                var args = Array.prototype.slice.call(arguments, 0);
                var result = _target.apply(_defaultContext, args);
                return result;
            } : function (next) {
                var args = Array.prototype.slice.call(arguments, 1);
                args.splice(1, 1, _target.apply(_defaultContext, args));
                next.apply(this, args);
            }
        };
        var _genPipeline = function () {
            _steps.all = _steps.pre.concat([_targetStep].concat(_steps.post));
        };
        _genPipeline();
        var conduit = function () {
            var idx = 0;
            var retval;
            var phase;
            var next = function next() {
                var args = Array.prototype.slice.call(arguments, 0);
                var thisIdx = idx;
                var step;
                var nextArgs;
                idx += 1;
                if (thisIdx < _steps.all.length) {
                    step = _steps.all[thisIdx];
                    phase = (phase === "target") ? "after" : (step.isTarget) ? "target" : "before";
                    if (options.sync) {
                        if (phase === "before") {
                            nextArgs = step.fn.apply(step.context || _defaultContext, args);
                            next.apply(this, nextArgs || args);
                        } else {
                            retval = step.fn.apply(step.context || _defaultContext, args) || retval;
                            next.apply(this, [retval].concat(args));
                        }
                    } else {
                        step.fn.apply(step.context || _defaultContext, [next].concat(args));
                    }
                }
            };
            next.apply(this, arguments);
            return retval;
        };
        conduit.steps = function () {
            return _steps.all;
        };
        conduit.context = function (ctx) {
            if (arguments.length === 0) {
                return _defaultContext;
            } else {
                _defaultContext = ctx;
            }
        };
        conduit.before = function (step, options) {
            step = typeof step === "function" ? {
                fn: step
            } : step;
            options = options || {};
            if (options.prepend) {
                _steps.pre.unshift(step);
            } else {
                _steps.pre.push(step);
            }
            _genPipeline();
        };
        conduit.after = function (step, options) {
            step = typeof step === "function" ? {
                fn: step
            } : step;
            options = options || {};
            if (options.prepend) {
                _steps.post.unshift(step);
            } else {
                _steps.post.push(step);
            }
            _genPipeline();
        };
        conduit.clear = function () {
            _steps = {
                pre: [],
                post: [],
                all: []
            };
            _genPipeline();
        };
        conduit.target = function (fn) {
            if (fn) {
                _target = fn;
            }
            return _target;
        };
        return conduit;
    };
    return {
        Sync: function (options) {
            options.sync = true;
            return Conduit.call(this, options)
        },
        Async: function (options) {
            return Conduit.call(this, options);
        }
    }
}));<commit_msg>Deleted<commit_after><|endoftext|>


<commit_before>// var exports = {};
// exports.exports = exports;

exports.micropolar = require('./micropolar');
exports.micropolar.manager = require('./micropolar_manager');

// order of requires should matter only for interdependencies
// in attributes definitions. put the common modules first
exports.Lib = require('./lib');
exports.util = require('./plotly_util');
exports.Color = require('./color');
exports.Drawing = require('./drawing');
// then the plot structure
exports.Plots = require('./graph_obj');
exports.Axes = require('./axes');
exports.Fx = require('./graph_interact');
// then trace modules - scatter has to come first
exports.Scatter = require('./scatter');
exports.Bars = require('./bars');
exports.Boxes = require('./boxes');
exports.Contour = require('./contour');
exports.ErrorBars = require('./errorbars');
exports.Heatmap = require('./heatmap');
exports.Histogram = require('./histogram');
// and extra plot components
exports.Annotations = require('./annotations');
exports.Shapes = require('./shapes');
exports.Legend = require('./legend');
exports.Colorbar = require('./colorbar');
exports.ModeBar = require('./modebar');
exports.XXX = 'foo';

// promise polyfill, embed rather than requiring dependencies
// var promise = require('promise')
// if(!Promise) Promise = promise;
// else Promise.prototype.done = promise.prototype.done;
require('../../../../shelly/static/js/plugins/promise-1.0.0.min.js');
require('../../../../shelly/static/js/plugins/promise-done-1.0.0.js');
<commit_msg>remove cruft in plotly.js file<commit_after>// var exports = {};
// exports.exports = exports;

exports.micropolar = require('./micropolar');
exports.micropolar.manager = require('./micropolar_manager');

// order of requires should matter only for interdependencies
// in attributes definitions. put the common modules first
exports.Lib = require('./lib');
exports.util = require('./plotly_util');
exports.Color = require('./color');
exports.Drawing = require('./drawing');
// then the plot structure
exports.Plots = require('./graph_obj');
exports.Axes = require('./axes');
exports.Fx = require('./graph_interact');
// then trace modules - scatter has to come first
exports.Scatter = require('./scatter');
exports.Bars = require('./bars');
exports.Boxes = require('./boxes');
exports.Contour = require('./contour');
exports.ErrorBars = require('./errorbars');
exports.Heatmap = require('./heatmap');
exports.Histogram = require('./histogram');
// and extra plot components
exports.Annotations = require('./annotations');
exports.Shapes = require('./shapes');
exports.Legend = require('./legend');
exports.Colorbar = require('./colorbar');
exports.ModeBar = require('./modebar');

// promise polyfill, embed rather than requiring dependencies
require('../../../../shelly/static/js/plugins/promise-1.0.0.min.js');
require('../../../../shelly/static/js/plugins/promise-done-1.0.0.js');
<|endoftext|>


<commit_before>angular.module('app.services', [

])
.factory('queryService',function($http, chartService){

  return {
    getDataFromServer: getDataFromServer
  };

  function getDataFromServer(endpoint, callback){
    function success(response){
      callback(response.data);
    }

    function error(err){
      console.log("error geting from database ==>", error);
    }

    $http.get(endpoint)
      .then(success, error)
  }

})
.factory('navService', function($http) {
  //var country = keys.collections.geo.united_states;
  // country.states = Object.keys(keys.collections.geo.united_states);
  // country.states.unshift('Select State:');

  return {
    getHubsFromServer: getHubsFromServer,
    getViewsFromServer: getViewsFromServer,
    selectedHub: "san_francisco",
  };

  function getHubsFromServer(callback) {

    function success(response){
      callback(response.data);
    }

    function error(err){
      console.log("error fetching hubs ==>", err)
    }

     $http.get('/analyzed-data/hubs')
      .then(success, error);
  }

  function getViewsFromServer(callback){
    function success(response){
      callback(response.data);
    }
    function error(err){
      console.log("error getting view list from database ==>", err);
    }

    $http.get("/analyzed-data/views")
      .then(success, error);
  }

})
.factory('chartService',function(){

  function createCategories(hubDataPoints){
    //each databpoint is a list of techs and numbers
    let keys = Object.keys(hubDataPoints[0]);
    let result = [];

    keys.forEach( (category) => {
      let categoryObject = {
        name: category,
        data: []
      };
      hubDataPoints.forEach( (dataPoint) => {
        categoryObject.data.push(dataPoint[category]);
      });
      result.push(categoryObject);
    });
    return result;
  }

  function extractDates(dateList){
    return dateList.map((data) => {
      return moment.unix(data.date).format('MMMM DD'); //change format later
    });
  }

  function extractDataPoints(dataList){
    return dataList.map((data) => {
      return data.data;
    });
  }

  function highChartsFormat(data){
    let result = {};

    result.dates = extractDates(data);
    //result for particular view

    result.data = createCategories(extractDataPoints(data));

    return result;
  }
  //aray of objects with name and data
  //iterate over the views
  function formatViews(data){
    var obj = {};
    for(let key in data) { //each individual view
      //skip unfilled views
        if(data[key].length > 0){
          obj[key] = highChartsFormat(data[key]);
        }
      }
    return obj;

  }

  return {
    formatResponseData: formatViews,
    highChartsFormat: highChartsFormat,
    // extractDataPoints: extractDataPoints,
    // createCatagories: createCatagories,
    // extractDates: extractDates,
  };

})
<commit_msg>formats dates correctly<commit_after>angular.module('app.services', [

])
.factory('queryService',function($http, chartService){

  return {
    getDataFromServer: getDataFromServer
  };

  function getDataFromServer(endpoint, callback){
    function success(response){
      callback(response.data);
    }

    function error(err){
      console.log("error geting from database ==>", error);
    }

    $http.get(endpoint)
      .then(success, error)
  }

})
.factory('navService', function($http) {
  //var country = keys.collections.geo.united_states;
  // country.states = Object.keys(keys.collections.geo.united_states);
  // country.states.unshift('Select State:');

  return {
    getHubsFromServer: getHubsFromServer,
    getViewsFromServer: getViewsFromServer,
    selectedHub: "san_francisco",
  };

  function getHubsFromServer(callback) {

    function success(response){
      callback(response.data);
    }

    function error(err){
      console.log("error fetching hubs ==>", err)
    }

     $http.get('/analyzed-data/hubs')
      .then(success, error);
  }

  function getViewsFromServer(callback){
    function success(response){
      callback(response.data);
    }
    function error(err){
      console.log("error getting view list from database ==>", err);
    }

    $http.get("/analyzed-data/views")
      .then(success, error);
  }

})
.factory('chartService',function(){

  function createCategories(hubDataPoints){
    //each databpoint is a list of techs and numbers
    let keys = Object.keys(hubDataPoints[0]);
    let result = [];

    keys.forEach( (category) => {
      let categoryObject = {
        name: category,
        data: []
      };
      hubDataPoints.forEach( (dataPoint) => {
        categoryObject.data.push(dataPoint[category]);
      });
      result.push(categoryObject);
    });
    return result;
  }

  function extractDates(dateList){
    return dateList.map((data) => {
      return moment(data.date, "x").format('MMMM DD'); //change format later
    });
  }

  function extractDataPoints(dataList){
    return dataList.map((data) => {
      return data.data;
    });
  }

  function highChartsFormat(data){
    let result = {};

    result.dates = extractDates(data);
    //result for particular view

    result.data = createCategories(extractDataPoints(data));

    return result;
  }
  //aray of objects with name and data
  //iterate over the views
  function formatViews(data){
    var obj = {};
    for(let key in data) { //each individual view
      //skip unfilled views
        if(data[key].length > 0){
          obj[key] = highChartsFormat(data[key]);
        }
      }
    return obj;

  }

  return {
    formatResponseData: formatViews,
    highChartsFormat: highChartsFormat,
    // extractDataPoints: extractDataPoints,
    // createCatagories: createCatagories,
    // extractDates: extractDates,
  };

})
<|endoftext|>


<commit_before>'use strict';
var React = require('react');
var globals = require('../globals');

// Import react-tabs npm to create tabs
var ReactTabs = require('react-tabs');
var Tab = ReactTabs.Tab;
var Tabs = ReactTabs.Tabs;
var TabList = ReactTabs.TabList;
var TabPanel = ReactTabs.TabPanel;

// Prevent react-tabs default styles being used on tabs
Tabs.setUseDefaultStyles(false);

// Import individual tab components
var CurationInterpretationBasicInfo = require('./interpretation/basic_info').CurationInterpretationBasicInfo;
var CurationInterpretationPopulation = require('./interpretation/population').CurationInterpretationPopulation;
var CurationInterpretationComputational = require('./interpretation/computational').CurationInterpretationComputational;
var CurationInterpretationFunctional = require('./interpretation/functional').CurationInterpretationFunctional;
var CurationInterpretationSegregation = require('./interpretation/segregation').CurationInterpretationSegregation;
var CurationInterpretationGeneSpecific = require('./interpretation/gene_specific').CurationInterpretationGeneSpecific;

// Curation data header for Gene:Disease
var VariantCurationInterpretation = module.exports.VariantCurationInterpretation = React.createClass({
    propTypes: {
        variantData: React.PropTypes.object, // ClinVar data payload
        interpretationUuid: React.PropTypes.string,
        loadingComplete: React.PropTypes.bool
    },

    handleSelect: function (index, last) {
        console.log('Selected tab: ' + index + ', Last tab: ' + last);
    },

    render: function() {
        var variant = this.props.variantData;
        var interpretationUuid = this.props.interpretationUuid;
        var loadingComplete = this.props.loadingComplete;

        // The ordering of TabPanels are corresponding to that of tabs
        // Adding or deleting a tab also requires its corresponding TabPanel to be added/deleted
        return (

                <Tabs onSelect={this.handleSelect} selectedIndex={0}>
                    <TabList className="tab-label-list">
                        <Tab className="tab-label col-sm-2">Basic Information</Tab>
                        <Tab className="tab-label col-sm-2">Population</Tab>
                        <Tab className="tab-label col-sm-2">Computational</Tab>
                        <Tab className="tab-label col-sm-2">Functional</Tab>
                        <Tab className="tab-label col-sm-2">Segregation/Case</Tab>
                        <Tab className="tab-label col-sm-2">Gene-specific</Tab>
                    </TabList>
                    <TabPanel>

<CurationInterpretationBasicInfo data={variant} shouldFetchData={loadingComplete} />

                    </TabPanel>
                    <TabPanel>

<CurationInterpretationPopulation data={variant} shouldFetchData={loadingComplete} interpretationUuid={interpretationUuid} />

                    </TabPanel>
                    <TabPanel>

<CurationInterpretationComputational data={variant} shouldFetchData={loadingComplete} />

                    </TabPanel>
                    <TabPanel>

<CurationInterpretationFunctional data={variant} shouldFetchData={loadingComplete} />

                    </TabPanel>
                    <TabPanel>

<CurationInterpretationSegregation data={variant} shouldFetchData={loadingComplete} />

                    </TabPanel>
                    <TabPanel>

<CurationInterpretationGeneSpecific data={variant} shouldFetchData={loadingComplete} />

                    </TabPanel>
                </Tabs>

        );
    }
});
<commit_msg>Added interpretationUuid props to all tab components<commit_after>'use strict';
var React = require('react');
var globals = require('../globals');

// Import react-tabs npm to create tabs
var ReactTabs = require('react-tabs');
var Tab = ReactTabs.Tab;
var Tabs = ReactTabs.Tabs;
var TabList = ReactTabs.TabList;
var TabPanel = ReactTabs.TabPanel;

// Prevent react-tabs default styles being used on tabs
Tabs.setUseDefaultStyles(false);

// Import individual tab components
var CurationInterpretationBasicInfo = require('./interpretation/basic_info').CurationInterpretationBasicInfo;
var CurationInterpretationPopulation = require('./interpretation/population').CurationInterpretationPopulation;
var CurationInterpretationComputational = require('./interpretation/computational').CurationInterpretationComputational;
var CurationInterpretationFunctional = require('./interpretation/functional').CurationInterpretationFunctional;
var CurationInterpretationSegregation = require('./interpretation/segregation').CurationInterpretationSegregation;
var CurationInterpretationGeneSpecific = require('./interpretation/gene_specific').CurationInterpretationGeneSpecific;

// Curation data header for Gene:Disease
var VariantCurationInterpretation = module.exports.VariantCurationInterpretation = React.createClass({
    propTypes: {
        variantData: React.PropTypes.object, // ClinVar data payload
        interpretationUuid: React.PropTypes.string,
        loadingComplete: React.PropTypes.bool
    },

    handleSelect: function (index, last) {
        console.log('Selected tab: ' + index + ', Last tab: ' + last);
    },

    render: function() {
        var variant = this.props.variantData;
        var interpretationUuid = this.props.interpretationUuid;
        var loadingComplete = this.props.loadingComplete;

        // The ordering of TabPanels are corresponding to that of tabs
        // Adding or deleting a tab also requires its corresponding TabPanel to be added/deleted
        return (

                <Tabs onSelect={this.handleSelect} selectedIndex={0}>
                    <TabList className="tab-label-list">
                        <Tab className="tab-label col-sm-2">Basic Information</Tab>
                        <Tab className="tab-label col-sm-2">Population</Tab>
                        <Tab className="tab-label col-sm-2">Computational</Tab>
                        <Tab className="tab-label col-sm-2">Functional</Tab>
                        <Tab className="tab-label col-sm-2">Segregation/Case</Tab>
                        <Tab className="tab-label col-sm-2">Gene-specific</Tab>
                    </TabList>
                    <TabPanel>

<CurationInterpretationBasicInfo data={variant} shouldFetchData={loadingComplete} />

                    </TabPanel>
                    <TabPanel>

<CurationInterpretationPopulation data={variant} shouldFetchData={loadingComplete} interpretationUuid={interpretationUuid} />

                    </TabPanel>
                    <TabPanel>

<CurationInterpretationComputational data={variant} shouldFetchData={loadingComplete} interpretationUuid={interpretationUuid} />

                    </TabPanel>
                    <TabPanel>

<CurationInterpretationFunctional data={variant} shouldFetchData={loadingComplete} interpretationUuid={interpretationUuid} />

                    </TabPanel>
                    <TabPanel>

<CurationInterpretationSegregation data={variant} shouldFetchData={loadingComplete} interpretationUuid={interpretationUuid} />

                    </TabPanel>
                    <TabPanel>

<CurationInterpretationGeneSpecific data={variant} shouldFetchData={loadingComplete} interpretationUuid={interpretationUuid} />

                    </TabPanel>
                </Tabs>

        );
    }
});
<|endoftext|>


<commit_before>/*              Het mechanisme van het spel         */
/*
*   Deze code gebruikt stukken van de template voor deze opdracht
*   Auteur: Wesley van Osch
*   Template Auteur: ICT-Academie
*/
var totaal = 0;
var score  = 0;

var stenen = [1, 2, 3, 4, 5];
var locked = [false, false, false, false, false];

var rolls = 3;
var beurt = 1;

var enabled = false;

//Het scoreboard
var scoreboard =
[
    ['Enen', 0],
    ['Tweeën', 0],
    ['Drieën', 0],
    ['Vieren', 0],
    ['Vijven', 0],
    ['Zessen', 0],
];

function randomGetal()
{
    var getal = Math.floor((Math.random()*6)+1);

    return getal;
}

/*  Zorgt ervoor dat een dobbelsteen wordt gelocked
*   @param1: De dobbelsteen die moet worden gelocked
*   geen return
*/
function lockSteen(steen)
{
    //console.log(steen);
    var isLocked = locked[steen - 1];

    //Als de entry bestaat wordt deze verwijderd
    if(!isLocked)
    {
        locked[steen - 1] = true;
        $('#d' + steen).css('border', '5px solid red');
    }
    else
    {
        locked[steen - 1] = false;
        $('#d' + steen).css('border', '1px solid black');
    }
}

/*  Reset het aantal rolls
*   geen params
*   geen return
*/
function reset()
{
    this.rolls = 3;
    this.stenen = [1, 2, 3, 4, 5];
    this.locked = [false, false, false, false, false];
    enabled = false;

    this.beurt++;

    $('#werp1').text('Gooi');

    $('.dobbelsteen').css('border', '1px solid black');
    updateInfo();
}

/*  Update info
*   geen params
*   geen return
*/
function updateInfo()
{
    $('#rolls').text('Rolls Over: ' + rolls);
    $('#beurt').text('Beurt: ' + beurt);
}

$(document).ready(function ()
{
    //Wanneer je op de werp knop klikt
    $('#werp1').click(function ()
    {
        if (rolls > 0)
        {
            resetRender();

            var ogen = [];

            //Zorgt ervoor dat alle niet gelockte dobbelstenen worden gerolt
            for (var i = 0; i < stenen.length; i++)
            {
                var isLocked = locked[stenen[i] - 1];

                if(!isLocked)
                {
                    var oog = randomGetal();
                    $('#d' + stenen[i]).html(oog);
                    ogen.push(oog);
                }
                else
                {
                    ogen.push(parseInt($('#d' + stenen[i]).text()));
                }
            }
            setOgen(ogen);

            animate();

            //De html inhoud van alle dobbelsten
            var d1 = $('#d1').html();
            var d2 = $('#d2').html();
            var d3 = $('#d3').html();
            var d4 = $('#d4').html();
            var d5 = $('#d5').html();

            //Het totaal van alle dobbelstenen
            totaal = parseInt(d1) + parseInt(d2) + parseInt(d3) + parseInt(d4) + parseInt(d5);

            //Veranderd het totaal van het aantal dobbelstenen
            $('#totaal').html('Totaal: ' + totaal);

            rolls--;
            updateInfo();

            if (rolls == 0)
            {
                showScoreboard();

                $('#werp1').text('Volgende Beurt');
            }

            enabled = true;
        }
        else
        {
            updateInfo();
            reset();
        }
    });

    //Waneer je op een dobbelsteen klikt wordt deze gelocked of geunlocked
    $('.dobbelsteen').on('click', function ()
    {
        if(enabled == true)
        {
            lockSteen($(this).attr('id').split('d')[1]);
        }
        else
        {
            alert('Je moet eerst gooien voordat je een dobbelsteen kan vergrendelen');
        }
    });
});

/*  Laat de scoreboard zien
*   geen parameters
*   geen return
*/
function showScoreboard()
{
    //Voegt opties toe
    var gegooid = getGegooid();

    for (var i = 0; i < gegooid.length; i++)
    {
        var item = gegooid[i];
        console.log(item[0] + ':' + item[1]);
    }

    //Laat een dialog zien
    var dialog = $('#scoreboard').dialog({
        width: "75%"
    });
}

/*  Deze berekent alle gegooide ogen met hoeveelheid
*   geen parameters
*   @return: alle gegooide ogen met aantal
*/
function getGegooid()
{
    var gegooid =
    [
        [1, 0],
        [2, 0],
        [3, 0],
        [4, 0],
        [5, 0],
        [6, 0]
    ];

    for (var i = 0; i < stenen.length; i++)
    {
        var punt = parseInt($('#d' + (i + 1)).html());
        var waarde = gegooid[punt - 1][1];

        gegooid[punt - 1][1] = waarde + 1;
    }

    return gegooid;
}

/*  Zorgt ervoor dat alle mogelijke combinaties worden berekent
*   @param1: Multi-Dimensional array met alle ogen en aantal keer gegooid
*   @return: Alle mogelijke combinaties
*/
function getCombinaties(gegooid)
{

}

/*  Of de score optie al eens is gebruikt
*   @param1: De score optie als iteratie in de array
*   @return: Of de score gebruikt is
*/
function isScoreUsed(optie)
{
    var score = scoreboard[optie];

    return score[1] > 0;
}<commit_msg>Update - 15:53<commit_after>/*              Het mechanisme van het spel         */
/*
*   Deze code gebruikt stukken van de template voor deze opdracht
*   Auteur: Wesley van Osch
*   Template Auteur: ICT-Academie
*/
var totaal = 0;
var score  = 0;

var stenen = [1, 2, 3, 4, 5];
var locked = [false, false, false, false, false];

var rolls = 3;
var beurt = 1;

var enabled = false;

//Het scoreboard
var scoreboard =
[
    ['Enen', 0],
    ['Tweeën', 0],
    ['Drieën', 0],
    ['Vieren', 0],
    ['Vijven', 0],
    ['Zessen', 0],
];

function randomGetal()
{
    var getal = Math.floor((Math.random()*6)+1);

    return getal;
}

/*  Zorgt ervoor dat een dobbelsteen wordt gelocked
*   @param1: De dobbelsteen die moet worden gelocked
*   geen return
*/
function lockSteen(steen)
{
    //console.log(steen);
    var isLocked = locked[steen - 1];

    //Als de entry bestaat wordt deze verwijderd
    if(!isLocked)
    {
        locked[steen - 1] = true;
        $('#d' + steen).css('border', '5px solid red');
    }
    else
    {
        locked[steen - 1] = false;
        $('#d' + steen).css('border', '1px solid black');
    }
}

/*  Reset het aantal rolls
*   geen params
*   geen return
*/
function reset()
{
    this.rolls = 3;
    this.stenen = [1, 2, 3, 4, 5];
    this.locked = [false, false, false, false, false];
    enabled = false;

    this.beurt++;

    $('#werp1').text('Gooi');

    $('.dobbelsteen').css('border', '1px solid black');
    updateInfo();
}

/*  Update info
*   geen params
*   geen return
*/
function updateInfo()
{
    $('#rolls').text('Rolls Over: ' + rolls);
    $('#beurt').text('Beurt: ' + beurt);
}

$(document).ready(function ()
{
    //Wanneer je op de werp knop klikt
    $('#werp1').click(function ()
    {
        if (rolls > 0)
        {
            resetRender();

            var ogen = [];

            //Zorgt ervoor dat alle niet gelockte dobbelstenen worden gerolt
            for (var i = 0; i < stenen.length; i++)
            {
                var isLocked = locked[stenen[i] - 1];

                if(!isLocked)
                {
                    var oog = randomGetal();
                    $('#d' + stenen[i]).html(oog);
                    ogen.push(oog);
                }
                else
                {
                    ogen.push(parseInt($('#d' + stenen[i]).text()));
                }
            }
            setOgen(ogen);

            animate();

            //De html inhoud van alle dobbelsten
            var d1 = $('#d1').html();
            var d2 = $('#d2').html();
            var d3 = $('#d3').html();
            var d4 = $('#d4').html();
            var d5 = $('#d5').html();

            //Het totaal van alle dobbelstenen
            totaal = parseInt(d1) + parseInt(d2) + parseInt(d3) + parseInt(d4) + parseInt(d5);

            //Veranderd het totaal van het aantal dobbelstenen
            $('#totaal').html('Totaal: ' + totaal);

            rolls--;
            updateInfo();

            if (rolls == 0)
            {
                showScoreboard();

                $('#werp1').text('Volgende Beurt');
            }

            enabled = true;
        }
        else
        {
            updateInfo();
            reset();
        }
    });

    //Waneer je op een dobbelsteen klikt wordt deze gelocked of geunlocked
    $('.dobbelsteen').on('click', function ()
    {
        if(enabled == true)
        {
            lockSteen($(this).attr('id').split('d')[1]);
        }
        else
        {
            alert('Je moet eerst gooien voordat je een dobbelsteen kan vergrendelen');
        }
    });
});

/*  Laat de scoreboard zien
*   geen parameters
*   geen return
*/
function showScoreboard()
{
    //Alle benodige informatie om opties te generen
    var gegooid = getGegooid();
    var combinaties = getCombinaties(gegooid);
    addOptions(combinaties, gegooid);

    //Laat een dialog zien
    var dialog = $('#scoreboard').dialog({
        width: "75%"
    });
}

/*  Deze berekent alle gegooide ogen met hoeveelheid
*   geen parameters
*   @return: alle gegooide ogen met aantal
*/
function getGegooid()
{
    var gegooid =
    [
        [1, 0],
        [2, 0],
        [3, 0],
        [4, 0],
        [5, 0],
        [6, 0]
    ];

    for (var i = 0; i < stenen.length; i++)
    {
        var punt = parseInt($('#d' + (i + 1)).html());
        var waarde = gegooid[punt - 1][1];

        gegooid[punt - 1][1] = waarde + 1;
    }

    return gegooid;
}

/*  Zorgt ervoor dat alle mogelijke combinaties worden berekent
*   @param1: Multi-Dimensional array met alle ogen en aantal keer gegooid
*   @return: Alle mogelijke combinaties
*/
function getCombinaties(gegooid)
{
    var combinaties = [];
    for (var i = 0; i < gegooid.length; i++)
    {
        var item = gegooid[i];
        var key = item[0];
        var value = item[1];

        if(value > 0)
        {
            if(key == 1 && scoreboard[0][1] == 0)
            {
                combinaties.push('Enen');
            }

            if(key == 2 && scoreboard[1][1] == 0)
            {
                combinaties.push('Tweeën');
            }

            if(key == 3 && scoreboard[2][1] == 0)
            {
                combinaties.push('Drieën');
            }

            if(key == 4 && scoreboard[3][1] == 0)
            {
                combinaties.push('Vieren');
            }

            if(key == 5 && scoreboard[4][1] == 0)
            {
                combinaties.push('Vijven');
            }

            if(key == 6 && scoreboard[5][1] == 0)
            {
                combinaties.push('Zessen');
            }
        }
    }

    return combinaties;
}

/*  Voegt alle valid opties toe
*   @param1: De combinaties die moeten worden toegevoegd
*   @param2: Het aantal keer dat een aantal ogen voor komt
*   Geen return
*/
function addOptions(combinaties, aantal)
{
    console.log(aantal);
    for(var i = 0; i < combinaties.length; i++)
    {
        var naam = combinaties[i];

        //Nieuwe rij
        var row = document.createElement('tr');

        //Optie Naam
        var optieData = document.createElement('td');
        var optieNaam = document.createTextNode(naam);
        optieData.appendChild(optieNaam);

        //Optie Radiobox

        //Optie Score

        //Voeg alle data toe aan de rij
        row.appendChild(optieData);

        //Voegt de rij toe aan de tabel
        document.getElementById('score').appendChild(row);
        console.log(naam);
    }
}

/*  Of de score optie al eens is gebruikt
*   @param1: De score optie als iteratie in de array
*   @return: Of de score gebruikt is
*/
function isScoreUsed(optie)
{
    var score = scoreboard[optie];

    return score[1] > 0;
}<|endoftext|>


<commit_before>/*
 * Filename: documentations.js
 */
var DocumentationsDocumentation = require(__dirname+'/documentation.js');

var self = this; // Set the context locally, for access protection

/**
 * Create a new Documentations that let users create sub-documentations.
 * @return {Documentations}
 */
function Documentations() {
  self._directory = 'documentation';
  self._document = 'documentation.html';
  self._proxies = {}; // Will be set
  self._filepath = ''; // Will be set
  self._filename = ''; // Will be set
  self._linktitle = 'Documentation';
  self._style = 'body { background-color: #ffffff; }'; // Default
  self._title = 'Documentations'; // Will be set
}

Documentations.prototype.directory = function() {
  return self._directory;
}

Documentations.prototype.setdirectory = function(fnOrValue) {
  self._directory = fnOrValue;
}

Documentations.prototype.document = function() {
  return self._document;
}

Documentations.prototype.setdocument = function(fnOrValue) {
  self._document = fnOrValue;
}

Documentations.prototype.proxies = function() {
  return self._proxies;
}

Documentations.prototype.setproxies = function(fnOrValue) {
  self._proxies = fnOrValue;
}

Documentations.prototype.filepath = function() {
  return self._filepath;
}

Documentations.prototype.setfilepath = function(fnOrValue) {
  self._filepath = fnOrValue;
}

Documentations.prototype.filename = function() {
  return self._filename;
}

Documentations.prototype.setfilename = function(fnOrValue) {
  self._filename = fnOrValue;
}

Documentations.prototype.linktitle = function() {
  return self._linktitle;
}

Documentations.prototype.setlinktitle = function(fnOrValue) {
  self._linktitle = fnOrValue;
}

Documentations.prototype.style = function() {
  return self._style;
}

Documentations.prototype.setstyle= function(fnOrValue) {
  self._style = fnOrValue;
}

Documentations.prototype.title = function() {
  return self._title;
}

Documentations.prototype.settitle = function(fnOrValue) {
  self._title = fnOrValue;
}

/**
 * Create a new DocumentationsDocumentation object.
 * @return {DocumentationsDocumentation}
 */
Documentations.prototype.documentation = function() {
  console.log('documentations documentation called')
  var _document = this.document();
  var _directory = this.directory();
  var _proxies = this.proxies();
  var _filepath = this.filepath();
  var _title = this.title();
  var _style = this.style();
  var _linktitle = this.linktitle();
  var _styleArray = [];
  var _scriptArray = [];
  var _headArray = [];
  var _bodyArray = [];
  var _path = _proxies().proxy().libraries().library().path();

  this._documentationsdocumentation = new DocumentationsDocumentation();

  /* START OPENING UP ALL BELOW LOGIC STEP BY STEP */

  console.log('documentations documentation - _document: ', _document) // 'documentation.html'
  this._documentationsdocumentation.setfilename(_document);

  console.log('documentations documentation - _path.join(_filepath, _directory): ', _path.join(_filepath, _directory))
  this._documentationsdocumentation.setfilepath(_path.join(_filepath, _directory));

  this._documentationsdocumentation.setproxies(_proxies);
  this._documentationsdocumentation.append = this.append; // Assign the function, don't call it
  this._documentationsdocumentation.buildHtml = this.buildHtml; // Assign the function, don't call it
  this._documentationsdocumentation.ensureExists = this.ensureExists; // Assign the function, don't call it

  var _jsdom = _proxies().proxy().libraries().library().jsdom();
  var _htmlDocument = _jsdom.jsdom().implementation.createHTMLDocument('');

  /* Title: System */
  var _titleElem = _htmlDocument.createElement('title');
  _titleElem.innerHTML = _title;
  console.log('documentations documentation - documentation _titleElem: ',
    _titleElem)

  /* Style: Tether */
  var _styleElem = _htmlDocument.createElement('link');
  console.log('documentations documentation - documentation _styleElem: ',
    _styleElem)
  _styleElem.setAttribute("rel",
    "stylesheet");
  _styleElem.setAttribute("type",
    "text/css");
  _styleElem.setAttribute("href",
    "../../../assets/asset/tether/dist/css/tether.min.css");
  console.log('documentations documentation - documentation _styleElem: ',
    _styleElem)

  _styleArray.push(_styleElem);

  /* Style: Bootstrap */
  var _styleElem = _htmlDocument.createElement('link');
  console.log('documentations documentation - documentation _styleElem: ',
    _styleElem)
  _styleElem.setAttribute("rel",
    "stylesheet");
  _styleElem.setAttribute("type",
    "text/css");
  _styleElem.setAttribute("href",
    "../../../assets/asset/bootstrap/dist/css/bootstrap.min.css");
  console.log('documentations documentation - documentation _styleElem: ',
    _styleElem)

  _styleArray.push(_styleElem);

  /* Style: inline */
  var _styleElem = _htmlDocument.createElement('link');
  console.log('documentations documentation - documentation _styleElem: ',
    _styleElem)
  _styleElem.innerHTML = _style;
  console.log('documentations documentation - documentation _styleElem: ',
    _styleElem)

  _styleArray.push(_styleElem);

  /* Head */
  _headArray.push(_titleElem);

  _styleArray.forEach(function(styleElem) {
    _headArray.push(styleElem); // Possible to add more elements to head
  }, _headArray);

  console.log('documentations documentation - documentation _headArray: ',
    _headArray)

  /*
   * Body
   */

  /* Navbar */
  var _navElem = _htmlDocument.createElement("nav");
  _navElem.setAttribute("class",
    "navbar navbar-light bg-faded");

  var _ulElem = _htmlDocument.createElement("ul");
  _ulElem.setAttribute("class",
    "nav navbar-nav");

  var _liElem = _htmlDocument.createElement("li");
  _liElem.setAttribute("class",
    "nav-item active");

  var _aElem = _htmlDocument.createElement("a");
  _aElem.setAttribute("class",
    "nav-link");
  _aElem.setAttribute("href",
    "#");
  _aElem.innerHTML = _title;

  _liElem.appendChild(_aElem);
  _ulElem.appendChild(_liElem);
  _navElem.appendChild(_ulElem);

  _bodyArray.push(_navElem);

  /* Container */
  var _divElem = _htmlDocument.createElement("div");
  _divElem.setAttribute("class",
    "container")

  /* List */
  var _ulElem = _htmlDocument.createElement('ul');
  _ulElem.setAttribute("class",
    "list-group");
  console.log('documentations documentation - documentation _ulElem: ',
    _ulElem)

  var _liElem = _htmlDocument.createElement('li');
  _liElem.setAttribute("class",
    "list-group-item");
  console.log('documentations documentation - documentation _liElem: ',
	_liElem)

  var _aElem = _htmlDocument.createElement('a');
  console.log('documentations documentation - documentation _aElem: ',
    _aElem)

  _aElem.setAttribute("href", "./" + _directory + "/" + _document);
  _aElem.innerHTML = _linktitle;
  _liElem.appendChild(_aElem);
  _ulElem.appendChild(_liElem);
  _divElem.appendChild(_ulElem);

  _bodyArray.push(_divElem); // Possible to add more elements to body
  console.log('documentations documentation - documentation _bodyArray: ',
    _bodyArray)

  /* Footer */
  var _footerElem = _htmlDocument.createElement("footer");
  _footerElem.setAttribute("class",
    "footer");
  var _divElem = _htmlDocument.createElement("div");
  _divElem.setAttribute("class",
    "container");
  var _spanElem = _htmlDocument.createElement("span");
  _spanElem.setAttribute("class",
    "text_muted");
  _spanElem.innerHTML = "Generated on: " +new Date;

  _divElem.appendChild(_spanElem);
  _footerElem.appendChild(_divElem);

  _bodyArray.push(_footerElem);

  return this._documentationsdocumentation;
}

Documentations.prototype.append = function(headArray, bodyArray) {
  console.log('documentations append(headArray, bodyArray) called')
  var _headArray = typeof headArray !== 'undefined' ? headArray : [];
  var _bodyArray = typeof bodyArray !== 'undefined' ? bodyArray : [];
  var _proxies = this.proxies();
  var _filepath = this.filepath();
  var _filename = this.filename();
  // temporarily we do all the file creation and appending in here
  // move most of this logic out to its best location. e.g. at documentation level
  var _path = _proxies().proxy().libraries().library().path();

  var filePathAndName = _path.join(_filepath, _filename);

  console.log('documentations - append(headArray, bodyArray) _headArray: ', _headArray);
  console.log('documentations - append(headArray, bodyArray) _bodyArray: ', _bodyArray);

  var _buildHtml = this.buildHtml(_headArray, _bodyArray);

  this.ensureExists(_filepath, 0744, function(err) {
    if (err) { // Handle folder creation error
      console.log('documentations - error', err)
    }
    else { // We're all good
      var fs = _proxies().proxy().libraries().library().fs();
      var stream = fs.createWriteStream(filePathAndName);
      stream.once('open', function(fd) {
      	console.log('documentations - append(headArray, bodyArray) _buildHtml: ', _buildHtml);
        var _jsdom = _proxies().proxy().libraries().library().jsdom();
        var _html = _jsdom.serializeDocument(_buildHtml); // Converts DOM Object to HTML as a String
        console.log('documentations - append(headArray, bodyArray) _html: ', _html);
        stream.end(_html);
      });
    }
  });
}

Documentations.prototype.buildHtml = function(headArray, bodyArray) {
  console.log('documentations - buildHtml(headArray, bodyArray) called')
  var _headArray = typeof headArray !== 'undefined' ? headArray : [];
  var _bodyArray = typeof bodyArray !== 'undefined' ? bodyArray : [];
  // concatenate head string
  // concatenate body string

  var _proxies = this.proxies();
  var _jsdom = _proxies().proxy().libraries().library().jsdom();
  var _htmlDocument = _jsdom.jsdom().implementation.createHTMLDocument('');
  _htmlDocument.head.innerHTML = ''; // Removes the default title element

  console.log('documentations - buildHtml(headArray, bodyArray) _headArray: ', _headArray);
  console.log('documentations - buildHtml(headArray, bodyArray) _bodyArray: ', _bodyArray);

  _headArray.forEach( function(entry) {
    _htmlDocument.head.appendChild(entry);
  }, _htmlDocument);

  _bodyArray.forEach( function(entry) {
    _htmlDocument.body.appendChild(entry);
  }, _htmlDocument);

  console.log('documentations - buildHtml(headArray, bodyArray) _htmlDocument: ', _htmlDocument)

  return _htmlDocument;
};

// This function is documented here:
// http://lmws.net/making-directory-along-with-missing-parents-in-node-js
Documentations.prototype.ensureExists = function(path, mask, callback) {
  console.log('documentations - ensureExists(path, mask, callback) called')
  console.log('documentations - ensureExists: path: ', path)
  console.log('documentations - ensureExists: mask: ', mask)
  if (typeof mask == 'function') { // Allow the `mask` parameter to be optional
    callback = mask;
    mask = 0777; // Read and Write permissions
  }
  var fs = require('fs');
  fs.mkdir(path, mask, function(error) {
    if (error) {
      if (error.code == 'EEXIST') {
      	// Ignore the error if the folder already exists
      	callback(null);
      }
      else {
      	// Something else went wrong
        // When it fail in this way, do the custom steps
        if (error && error.errno === 34) {
          // Create all the parents recursively
          fs.mkdirParent(path.dirname(dirPath), mode, callback);
          // And then the directory
          fs.mkdirParent(dirPath, mode, callback);
        }
        // Manually run the callback since we used our own callback to do all these
        callback && callback(error);
      }
    }
    else {
      // Successfully created folder
      callback(null);
    }
  });
};

module.exports = Documentations;
<commit_msg>Modified<commit_after>/*
 * Filename: documentations.js
 */
var DocumentationsDocumentation = require(__dirname+'/documentation.js');

var self = this; // Set the context locally, for access protection

/**
 * Create a new Documentations that let users create sub-documentations.
 * @return {Documentations}
 */
function Documentations() {
  self._directory = 'documentation';
  self._document = 'documentation.html';
  self._proxies = {}; // Will be set
  self._filepath = ''; // Will be set
  self._filename = ''; // Will be set
  self._linktitle = 'Documentation';
  self._style = 'body { background-color: #ffffff; }'; // Default
  self._title = 'Documentations'; // Will be set
}

Documentations.prototype.directory = function() {
  return self._directory;
}

Documentations.prototype.setdirectory = function(fnOrValue) {
  self._directory = fnOrValue;
}

Documentations.prototype.document = function() {
  return self._document;
}

Documentations.prototype.setdocument = function(fnOrValue) {
  self._document = fnOrValue;
}

Documentations.prototype.proxies = function() {
  return self._proxies;
}

Documentations.prototype.setproxies = function(fnOrValue) {
  self._proxies = fnOrValue;
}

Documentations.prototype.filepath = function() {
  return self._filepath;
}

Documentations.prototype.setfilepath = function(fnOrValue) {
  self._filepath = fnOrValue;
}

Documentations.prototype.filename = function() {
  return self._filename;
}

Documentations.prototype.setfilename = function(fnOrValue) {
  self._filename = fnOrValue;
}

Documentations.prototype.linktitle = function() {
  return self._linktitle;
}

Documentations.prototype.setlinktitle = function(fnOrValue) {
  self._linktitle = fnOrValue;
}

Documentations.prototype.style = function() {
  return self._style;
}

Documentations.prototype.setstyle= function(fnOrValue) {
  self._style = fnOrValue;
}

Documentations.prototype.title = function() {
  return self._title;
}

Documentations.prototype.settitle = function(fnOrValue) {
  self._title = fnOrValue;
}

/**
 * Create a new DocumentationsDocumentation object.
 * @return {DocumentationsDocumentation}
 */
Documentations.prototype.documentation = function() {
  console.log('documentations documentation called')
  var _document = this.document();
  var _directory = this.directory();
  var _proxies = this.proxies();
  var _filepath = this.filepath();
  var _title = this.title();
  var _style = this.style();
  var _linktitle = this.linktitle();
  var _styleArray = [];
  var _scriptArray = [];
  var _headArray = [];
  var _bodyArray = [];
  var _path = _proxies().proxy().libraries().library().path();

  this._documentationsdocumentation = new DocumentationsDocumentation();

  /* START OPENING UP ALL BELOW LOGIC STEP BY STEP */

  console.log('documentations documentation - _document: ', _document) // 'documentation.html'
  this._documentationsdocumentation.setfilename(_document);

  console.log('documentations documentation - _path.join(_filepath, _directory): ', _path.join(_filepath, _directory))
  this._documentationsdocumentation.setfilepath(_path.join(_filepath, _directory));

  this._documentationsdocumentation.setproxies(_proxies);
  this._documentationsdocumentation.append = this.append; // Assign the function, don't call it
  this._documentationsdocumentation.buildHtml = this.buildHtml; // Assign the function, don't call it
  this._documentationsdocumentation.ensureExists = this.ensureExists; // Assign the function, don't call it

  var _jsdom = _proxies().proxy().libraries().library().jsdom();
  var _htmlDocument = _jsdom.jsdom().implementation.createHTMLDocument('');

  /* Title: System */
  var _titleElem = _htmlDocument.createElement('title');
  _titleElem.innerHTML = _title;
  console.log('documentations documentation - documentation _titleElem: ',
    _titleElem)

  /* Style: Tether */
  var _styleElem = _htmlDocument.createElement('link');
  console.log('documentations documentation - documentation _styleElem: ',
    _styleElem)
  _styleElem.setAttribute("rel",
    "stylesheet");
  _styleElem.setAttribute("type",
    "text/css");
  _styleElem.setAttribute("href",
    "../../../assets/asset/tether/dist/css/tether.min.css");
  console.log('documentations documentation - documentation _styleElem: ',
    _styleElem)

  _styleArray.push(_styleElem);

  /* Style: Bootstrap */
  var _styleElem = _htmlDocument.createElement('link');
  console.log('documentations documentation - documentation _styleElem: ',
    _styleElem)
  _styleElem.setAttribute("rel",
    "stylesheet");
  _styleElem.setAttribute("type",
    "text/css");
  _styleElem.setAttribute("href",
    "../../../assets/asset/bootstrap/dist/css/bootstrap.min.css");
  console.log('documentations documentation - documentation _styleElem: ',
    _styleElem)

  _styleArray.push(_styleElem);

  /* Style: Bootstrap - sticky footer */
  var _styleElem = _htmlDocument.createElement('link');
  console.log('systems system execute - documentation _styleElem: ',
    _styleElem)
  _styleElem.setAttribute("rel",
    "stylesheet");
  _styleElem.setAttribute("type",
    "text/css");
  _styleElem.setAttribute("href",
    "../../../assets/asset/bootstrap/dist/css/sticky-footer-navbar.css");
  console.log('systems system execute - documentation _styleElem: ',
    _styleElem)

  _styleArray.push(_styleElem);

  /* Style: inline */
  var _styleElem = _htmlDocument.createElement('link');
  console.log('documentations documentation - documentation _styleElem: ',
    _styleElem)
  _styleElem.innerHTML = _style;
  console.log('documentations documentation - documentation _styleElem: ',
    _styleElem)

  _styleArray.push(_styleElem);

  /* Head */
  _headArray.push(_titleElem);

  _styleArray.forEach(function(styleElem) {
    _headArray.push(styleElem); // Possible to add more elements to head
  }, _headArray);

  console.log('documentations documentation - documentation _headArray: ',
    _headArray)

  /*
   * Body
   */

  /* Navbar */
  var _navElem = _htmlDocument.createElement("nav");
  _navElem.setAttribute("class",
    "navbar navbar-light bg-faded");

  var _ulElem = _htmlDocument.createElement("ul");
  _ulElem.setAttribute("class",
    "nav navbar-nav");

  var _liElem = _htmlDocument.createElement("li");
  _liElem.setAttribute("class",
    "nav-item active");

  var _aElem = _htmlDocument.createElement("a");
  _aElem.setAttribute("class",
    "nav-link");
  _aElem.setAttribute("href",
    "#");
  _aElem.innerHTML = _title;

  _liElem.appendChild(_aElem);
  _ulElem.appendChild(_liElem);
  _navElem.appendChild(_ulElem);

  _bodyArray.push(_navElem);

  /* Container */
  var _divElem = _htmlDocument.createElement("div");
  _divElem.setAttribute("class",
    "container")

  /* List */
  var _ulElem = _htmlDocument.createElement('ul');
  _ulElem.setAttribute("class",
    "list-group");
  console.log('documentations documentation - documentation _ulElem: ',
    _ulElem)

  var _liElem = _htmlDocument.createElement('li');
  _liElem.setAttribute("class",
    "list-group-item");
  console.log('documentations documentation - documentation _liElem: ',
	_liElem)

  var _aElem = _htmlDocument.createElement('a');
  console.log('documentations documentation - documentation _aElem: ',
    _aElem)

  _aElem.setAttribute("href", "./" + _directory + "/" + _document);
  _aElem.innerHTML = _linktitle;
  _liElem.appendChild(_aElem);
  _ulElem.appendChild(_liElem);
  _divElem.appendChild(_ulElem);

  _bodyArray.push(_divElem); // Possible to add more elements to body
  console.log('documentations documentation - documentation _bodyArray: ',
    _bodyArray)

  /* Footer */
  var _footerElem = _htmlDocument.createElement("footer");
  _footerElem.setAttribute("class",
    "footer");
  var _divElem = _htmlDocument.createElement("div");
  _divElem.setAttribute("class",
    "container");
  var _spanElem = _htmlDocument.createElement("span");
  _spanElem.setAttribute("class",
    "text_muted");
  _spanElem.innerHTML = "Generated on: " +new Date;

  _divElem.appendChild(_spanElem);
  _footerElem.appendChild(_divElem);

  _bodyArray.push(_footerElem);

  /* Scripts, put at bottom of body to make the page load faster */

  /* Script: JQuery */
  var _scriptElem = _htmlDocument.createElement('script');
  _scriptElem.setAttribute("type", "text/javascript");
  _scriptElem.setAttribute("src", "../../../assets/asset/jquery/dist/js/jquery.min.js");
  console.log('documentations documentation - documentation _scriptElem: ',
    _scriptElem)

  _scriptArray.push(_scriptElem);

  /* Script: Tether */
  var _scriptElem = _htmlDocument.createElement('script');
  _scriptElem.setAttribute("type", "text/javascript");
  _scriptElem.setAttribute("src", "../../../assets/asset/tether/dist/js/tether.min.js");
  console.log('documentations documentation - documentation _scriptElem: ',
    _scriptElem)

  _scriptArray.push(_scriptElem);

  /* Script: Bootstrap */
  var _scriptElem = _htmlDocument.createElement('script');
  _scriptElem.setAttribute("type", "text/javascript");
  _scriptElem.setAttribute("src", "../../../assets/asset/bootstrap/dist/js/bootstrap.min.js");
  console.log('documentations documentation - documentation _scriptElem: ',
    _scriptElem)

  _scriptArray.push(_scriptElem);

  _scriptArray.forEach(function(scriptElem) {
    _bodyArray.push(scriptElem);
  }, _bodyArray);

  this._documentationsdocumentation.append(_headArray, _bodyArray);

  return this._documentationsdocumentation;
}

Documentations.prototype.append = function(headArray, bodyArray) {
  console.log('documentations append(headArray, bodyArray) called')
  var _headArray = typeof headArray !== 'undefined' ? headArray : [];
  var _bodyArray = typeof bodyArray !== 'undefined' ? bodyArray : [];
  var _proxies = this.proxies();
  var _filepath = this.filepath();
  var _filename = this.filename();
  // temporarily we do all the file creation and appending in here
  // move most of this logic out to its best location. e.g. at documentation level
  var _path = _proxies().proxy().libraries().library().path();

  var filePathAndName = _path.join(_filepath, _filename);

  console.log('documentations - append(headArray, bodyArray) _headArray: ', _headArray);
  console.log('documentations - append(headArray, bodyArray) _bodyArray: ', _bodyArray);

  var _buildHtml = this.buildHtml(_headArray, _bodyArray);

  this.ensureExists(_filepath, 0744, function(err) {
    if (err) { // Handle folder creation error
      console.log('documentations - error', err)
    }
    else { // We're all good
      var fs = _proxies().proxy().libraries().library().fs();
      var stream = fs.createWriteStream(filePathAndName);
      stream.once('open', function(fd) {
      	console.log('documentations - append(headArray, bodyArray) _buildHtml: ', _buildHtml);
        var _jsdom = _proxies().proxy().libraries().library().jsdom();
        var _html = _jsdom.serializeDocument(_buildHtml); // Converts DOM Object to HTML as a String
        console.log('documentations - append(headArray, bodyArray) _html: ', _html);
        stream.end(_html);
      });
    }
  });
}

Documentations.prototype.buildHtml = function(headArray, bodyArray) {
  console.log('documentations - buildHtml(headArray, bodyArray) called')
  var _headArray = typeof headArray !== 'undefined' ? headArray : [];
  var _bodyArray = typeof bodyArray !== 'undefined' ? bodyArray : [];
  // concatenate head string
  // concatenate body string

  var _proxies = this.proxies();
  var _jsdom = _proxies().proxy().libraries().library().jsdom();
  var _htmlDocument = _jsdom.jsdom().implementation.createHTMLDocument('');
  _htmlDocument.head.innerHTML = ''; // Removes the default title element

  console.log('documentations - buildHtml(headArray, bodyArray) _headArray: ', _headArray);
  console.log('documentations - buildHtml(headArray, bodyArray) _bodyArray: ', _bodyArray);

  _headArray.forEach( function(entry) {
    _htmlDocument.head.appendChild(entry);
  }, _htmlDocument);

  _bodyArray.forEach( function(entry) {
    _htmlDocument.body.appendChild(entry);
  }, _htmlDocument);

  console.log('documentations - buildHtml(headArray, bodyArray) _htmlDocument: ', _htmlDocument)

  return _htmlDocument;
};

// This function is documented here:
// http://lmws.net/making-directory-along-with-missing-parents-in-node-js
Documentations.prototype.ensureExists = function(path, mask, callback) {
  console.log('documentations - ensureExists(path, mask, callback) called')
  console.log('documentations - ensureExists: path: ', path)
  console.log('documentations - ensureExists: mask: ', mask)
  if (typeof mask == 'function') { // Allow the `mask` parameter to be optional
    callback = mask;
    mask = 0777; // Read and Write permissions
  }
  var fs = require('fs');
  fs.mkdir(path, mask, function(error) {
    if (error) {
      if (error.code == 'EEXIST') {
      	// Ignore the error if the folder already exists
      	callback(null);
      }
      else {
      	// Something else went wrong
        // When it fail in this way, do the custom steps
        if (error && error.errno === 34) {
          // Create all the parents recursively
          fs.mkdirParent(path.dirname(dirPath), mode, callback);
          // And then the directory
          fs.mkdirParent(dirPath, mode, callback);
        }
        // Manually run the callback since we used our own callback to do all these
        callback && callback(error);
      }
    }
    else {
      // Successfully created folder
      callback(null);
    }
  });
};

module.exports = Documentations;
<|endoftext|>


<commit_before>/* global _, Array, window */

/**
 * Instantiates the Drift analytics and customer support messaging platform.
 */
hqDefine('analytics/js/drift', function () {
    'use strict';
    var _get = hqImport('analytics/js/initial').getFn('drift'),
        _global = hqImport('analytics/js/initial').getFn('global'),
        logger = hqImport('analytics/js/logging').getLoggerForApi('Drift'),
        _utils = hqImport('analytics/js/utils'),
        _data = {},
        _drift = {};

    var __init__ = function () {
        _drift = window.driftt = window.drift = window.driftt || [];
        if (!_drift.init && !_drift.invoked ) {
            _drift.methods = [ "identify", "config", "track", "reset", "debug", "show", "ping", "page", "hide", "off", "on" ];
            _drift.factory = function (methodName) {
               return function() {
                    var methodFn = Array.prototype.slice.call(arguments);
                    methodFn.unshift(methodName);
                    _drift.push(methodFn);
                    return _drift;
                };
            };
            _.each(_drift.methods, function (methodName) {
                _drift[methodName] = _drift.factory(methodName);
            });
        }

        _drift.SNIPPET_VERSION = '0.3.1';
        _data.apiId = _get('apiId');

        if (_data.apiId) {
            _data.scriptUrl = "https://js.driftt.com/include/" + _utils.getDateHash() + "/" + _data.apiId;
            logger.verbose.log(_data.scriptUrl, "Adding Script");
            _utils.insertScript(_data.scriptUrl, logger.debug.log, {
                crossorigin: 'anonymous',
            });
        }
        _drift.on('emailCapture',function(e){
            hqImport('analytics/js/hubspot').identify({email: e.data.email});
            hqImport('analytics/js/hubspot').trackEvent('Identified via Drift');
        });
    };
    if (_global('isEnabled')) {
        __init__();
        logger.debug.log("Initialized");
    }

    // no methods just yet
    return {
        logger: logger,
    };
});
<commit_msg>fix indent<commit_after>/* global _, Array, window */

/**
 * Instantiates the Drift analytics and customer support messaging platform.
 */
hqDefine('analytics/js/drift', function () {
    'use strict';
    var _get = hqImport('analytics/js/initial').getFn('drift'),
        _global = hqImport('analytics/js/initial').getFn('global'),
        logger = hqImport('analytics/js/logging').getLoggerForApi('Drift'),
        _utils = hqImport('analytics/js/utils'),
        _data = {},
        _drift = {};

    var __init__ = function () {
        _drift = window.driftt = window.drift = window.driftt || [];
        if (!_drift.init && !_drift.invoked ) {
            _drift.methods = [ "identify", "config", "track", "reset", "debug", "show", "ping", "page", "hide", "off", "on" ];
            _drift.factory = function (methodName) {
                return function() {
                    var methodFn = Array.prototype.slice.call(arguments);
                    methodFn.unshift(methodName);
                    _drift.push(methodFn);
                    return _drift;
                };
            };
            _.each(_drift.methods, function (methodName) {
                _drift[methodName] = _drift.factory(methodName);
            });
        }

        _drift.SNIPPET_VERSION = '0.3.1';
        _data.apiId = _get('apiId');

        if (_data.apiId) {
            _data.scriptUrl = "https://js.driftt.com/include/" + _utils.getDateHash() + "/" + _data.apiId;
            logger.verbose.log(_data.scriptUrl, "Adding Script");
            _utils.insertScript(_data.scriptUrl, logger.debug.log, {
                crossorigin: 'anonymous',
            });
        }
        _drift.on('emailCapture',function(e){
            hqImport('analytics/js/hubspot').identify({email: e.data.email});
            hqImport('analytics/js/hubspot').trackEvent('Identified via Drift');
        });
    };
    if (_global('isEnabled')) {
        __init__();
        logger.debug.log("Initialized");
    }

    // no methods just yet
    return {
        logger: logger,
    };
});
<|endoftext|>


<commit_before>import macro from 'vtk.js/Sources/macro';
import vtkRenderer from 'vtk.js/Sources/Rendering/Core/Renderer';
import Constants from 'vtk.js/Sources/Interaction/Widgets/OrientationMarkerWidget/Constants';

const { vtkErrorMacro } = macro;
const { Corners } = Constants;

// ----------------------------------------------------------------------------
// vtkOrientationMarkerWidget
// ----------------------------------------------------------------------------

function vtkOrientationMarkerWidget(publicAPI, model) {
  // Set our className
  model.classHierarchy.push('vtkOrientationMarkerWidget');

  // Private variables

  const previousCameraInput = [];
  const selfRenderer = vtkRenderer.newInstance();
  let interactorUnsubscribe = null;
  let viewUnsubscribe = null;

  publicAPI.computeViewport = () => {
    const [viewXSize, viewYSize] = model.interactor.getView().getSize();
    const minViewSize = Math.min(viewXSize, viewYSize);

    let pixelSize = model.viewportSize * minViewSize;
    // clamp pixel size
    pixelSize = Math.max(
      Math.min(model.minPixelSize, minViewSize),
      Math.min(model.maxPixelSize, pixelSize)
    );

    const xFrac = pixelSize / viewXSize;
    const yFrac = pixelSize / viewYSize;
    // [left bottom right top]
    switch (model.viewportCorner) {
      case Corners.TOP_LEFT:
        return [0, 1 - yFrac, xFrac, 1];
      case Corners.TOP_RIGHT:
        return [1 - xFrac, 1 - yFrac, 1, 1];
      case Corners.BOTTOM_LEFT:
        return [0, 0, xFrac, yFrac];
      case Corners.BOTTOM_RIGHT:
        return [1 - xFrac, 0, 1, yFrac];
      default:
        vtkErrorMacro('Invalid widget corner');
        return null;
    }
  };

  publicAPI.updateViewport = () => {
    selfRenderer.setViewport(...publicAPI.computeViewport());
    model.interactor.render();
  };

  publicAPI.updateMarkerOrientation = () => {
    const currentCamera = model.interactor
      .findPokedRenderer()
      .getActiveCamera();

    if (!currentCamera) {
      return;
    }

    const position = currentCamera.getReferenceByName('position');
    const focalPoint = currentCamera.getReferenceByName('focalPoint');
    const viewUp = currentCamera.getReferenceByName('viewUp');
    if (
      previousCameraInput[0] !== position[0] ||
      previousCameraInput[1] !== position[1] ||
      previousCameraInput[2] !== position[2] ||
      previousCameraInput[3] !== focalPoint[0] ||
      previousCameraInput[4] !== focalPoint[1] ||
      previousCameraInput[5] !== focalPoint[2] ||
      previousCameraInput[6] !== viewUp[0] ||
      previousCameraInput[7] !== viewUp[1] ||
      previousCameraInput[8] !== viewUp[2]
    ) {
      previousCameraInput[0] = position[0];
      previousCameraInput[1] = position[1];
      previousCameraInput[2] = position[2];
      previousCameraInput[3] = focalPoint[0];
      previousCameraInput[4] = focalPoint[1];
      previousCameraInput[5] = focalPoint[2];
      previousCameraInput[6] = viewUp[0];
      previousCameraInput[7] = viewUp[1];
      previousCameraInput[8] = viewUp[2];
      const activeCamera = selfRenderer.getActiveCamera();
      activeCamera.setPosition(position[0], position[1], position[2]);
      activeCamera.setFocalPoint(focalPoint[0], focalPoint[1], focalPoint[2]);
      activeCamera.setViewUp(viewUp[0], viewUp[1], viewUp[2]);
      selfRenderer.resetCamera();
    }
  };

  /**
   * Enables/Disables the orientation marker.
   */
  publicAPI.setEnabled = (enabling) => {
    if (enabling) {
      if (model.enabled) {
        return;
      }

      if (!model.actor) {
        vtkErrorMacro('Must set actor before enabling orientation marker.');
        return;
      }

      if (!model.interactor) {
        vtkErrorMacro(
          'Must set interactor before enabling orientation marker.'
        );
        return;
      }

      const renderWindow = model.interactor
        .findPokedRenderer()
        .getRenderWindow();
      renderWindow.addRenderer(selfRenderer);
      if (renderWindow.getNumberOfLayers() < 2) {
        renderWindow.setNumberOfLayers(2);
      }
      // Highest number is foreground
      selfRenderer.setLayer(renderWindow.getNumberOfLayers() - 1);
      selfRenderer.setInteractive(false);

      selfRenderer.addViewProp(model.actor);
      model.actor.setVisibility(true);

      ({ unsubscribe: interactorUnsubscribe } = model.interactor.onAnimation(
        publicAPI.updateMarkerOrientation
      ));

      ({ unsubscribe: viewUnsubscribe } = model.interactor
        .getView()
        .onModified(publicAPI.updateViewport));

      publicAPI.updateViewport();
      publicAPI.updateMarkerOrientation();

      model.enabled = true;
    } else {
      if (!model.enabled) {
        return;
      }
      model.enabled = false;

      viewUnsubscribe();
      viewUnsubscribe = null;
      interactorUnsubscribe();
      interactorUnsubscribe = null;

      model.actor.setVisibility(false);
      selfRenderer.removeViewProp(model.actor);

      const renderWindow = model.interactor
        .findPokedRenderer()
        .getRenderWindow();
      if (renderWindow) {
        renderWindow.removeRenderer(selfRenderer);
      }
    }
    publicAPI.modified();
  };

  /**
   * Sets the viewport corner.
   */
  publicAPI.setViewportCorner = (corner) => {
    if (corner === model.viewportCorner) {
      return;
    }

    model.viewportCorner = corner;
    if (model.enabled) {
      publicAPI.updateViewport();
    }
  };

  /**
   * Sets the viewport size.
   */
  publicAPI.setViewportSize = (sizeFactor) => {
    const viewportSize = Math.min(1, Math.max(0, sizeFactor));
    if (viewportSize === model.viewportSize) {
      return;
    }

    model.viewportSize = viewportSize;
    if (model.enabled) {
      publicAPI.updateViewport();
    }
  };
}

// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------

export const DEFAULT_VALUES = {
  // actor: null,
  // interactor: null,
  viewportCorner: Constants.Corners.BOTTOM_LEFT,
  viewportSize: 0.2,
  minPixelSize: 50,
  maxPixelSize: 200,
};

// ----------------------------------------------------------------------------

export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);

  // Build VTK API
  macro.obj(publicAPI, model);

  macro.get(publicAPI, model, ['enabled', 'viewportCorner', 'viewportSize']);

  // NOTE: setting these while the widget is enabled will
  // not update the widget.
  macro.setGet(publicAPI, model, [
    'actor',
    'interactor',
    'minPixelSize',
    'maxPixelSize',
  ]);

  // Object methods
  vtkOrientationMarkerWidget(publicAPI, model);
}

// ----------------------------------------------------------------------------

export const newInstance = macro.newInstance(
  extend,
  'vtkOrientationMarkerWidget'
);

// ----------------------------------------------------------------------------

export default Object.assign({ newInstance, extend }, Constants);
<commit_msg>fix(OrientationMarkerWidget): Allow to change actor dynamically<commit_after>import macro from 'vtk.js/Sources/macro';
import vtkRenderer from 'vtk.js/Sources/Rendering/Core/Renderer';
import Constants from 'vtk.js/Sources/Interaction/Widgets/OrientationMarkerWidget/Constants';

const { vtkErrorMacro } = macro;
const { Corners } = Constants;

// ----------------------------------------------------------------------------
// vtkOrientationMarkerWidget
// ----------------------------------------------------------------------------

function vtkOrientationMarkerWidget(publicAPI, model) {
  // Set our className
  model.classHierarchy.push('vtkOrientationMarkerWidget');

  // Private variables

  const previousCameraInput = [];
  const selfRenderer = vtkRenderer.newInstance();
  let interactorUnsubscribe = null;
  let viewUnsubscribe = null;

  publicAPI.computeViewport = () => {
    const [viewXSize, viewYSize] = model.interactor.getView().getSize();
    const minViewSize = Math.min(viewXSize, viewYSize);

    let pixelSize = model.viewportSize * minViewSize;
    // clamp pixel size
    pixelSize = Math.max(
      Math.min(model.minPixelSize, minViewSize),
      Math.min(model.maxPixelSize, pixelSize)
    );

    const xFrac = pixelSize / viewXSize;
    const yFrac = pixelSize / viewYSize;
    // [left bottom right top]
    switch (model.viewportCorner) {
      case Corners.TOP_LEFT:
        return [0, 1 - yFrac, xFrac, 1];
      case Corners.TOP_RIGHT:
        return [1 - xFrac, 1 - yFrac, 1, 1];
      case Corners.BOTTOM_LEFT:
        return [0, 0, xFrac, yFrac];
      case Corners.BOTTOM_RIGHT:
        return [1 - xFrac, 0, 1, yFrac];
      default:
        vtkErrorMacro('Invalid widget corner');
        return null;
    }
  };

  publicAPI.updateViewport = () => {
    selfRenderer.setViewport(...publicAPI.computeViewport());
    model.interactor.render();
  };

  publicAPI.updateMarkerOrientation = () => {
    const currentCamera = model.interactor
      .findPokedRenderer()
      .getActiveCamera();

    if (!currentCamera) {
      return;
    }

    const position = currentCamera.getReferenceByName('position');
    const focalPoint = currentCamera.getReferenceByName('focalPoint');
    const viewUp = currentCamera.getReferenceByName('viewUp');
    if (
      previousCameraInput[0] !== position[0] ||
      previousCameraInput[1] !== position[1] ||
      previousCameraInput[2] !== position[2] ||
      previousCameraInput[3] !== focalPoint[0] ||
      previousCameraInput[4] !== focalPoint[1] ||
      previousCameraInput[5] !== focalPoint[2] ||
      previousCameraInput[6] !== viewUp[0] ||
      previousCameraInput[7] !== viewUp[1] ||
      previousCameraInput[8] !== viewUp[2]
    ) {
      previousCameraInput[0] = position[0];
      previousCameraInput[1] = position[1];
      previousCameraInput[2] = position[2];
      previousCameraInput[3] = focalPoint[0];
      previousCameraInput[4] = focalPoint[1];
      previousCameraInput[5] = focalPoint[2];
      previousCameraInput[6] = viewUp[0];
      previousCameraInput[7] = viewUp[1];
      previousCameraInput[8] = viewUp[2];
      const activeCamera = selfRenderer.getActiveCamera();
      activeCamera.setPosition(position[0], position[1], position[2]);
      activeCamera.setFocalPoint(focalPoint[0], focalPoint[1], focalPoint[2]);
      activeCamera.setViewUp(viewUp[0], viewUp[1], viewUp[2]);
      selfRenderer.resetCamera();
    }
  };

  /**
   * Enables/Disables the orientation marker.
   */
  publicAPI.setEnabled = (enabling) => {
    if (enabling) {
      if (model.enabled) {
        return;
      }

      if (!model.actor) {
        vtkErrorMacro('Must set actor before enabling orientation marker.');
        return;
      }

      if (!model.interactor) {
        vtkErrorMacro(
          'Must set interactor before enabling orientation marker.'
        );
        return;
      }

      const renderWindow = model.interactor
        .findPokedRenderer()
        .getRenderWindow();
      renderWindow.addRenderer(selfRenderer);
      if (renderWindow.getNumberOfLayers() < 2) {
        renderWindow.setNumberOfLayers(2);
      }
      // Highest number is foreground
      selfRenderer.setLayer(renderWindow.getNumberOfLayers() - 1);
      selfRenderer.setInteractive(false);

      selfRenderer.addViewProp(model.actor);
      model.actor.setVisibility(true);

      ({ unsubscribe: interactorUnsubscribe } = model.interactor.onAnimation(
        publicAPI.updateMarkerOrientation
      ));

      ({ unsubscribe: viewUnsubscribe } = model.interactor
        .getView()
        .onModified(publicAPI.updateViewport));

      publicAPI.updateViewport();
      publicAPI.updateMarkerOrientation();

      model.enabled = true;
    } else {
      if (!model.enabled) {
        return;
      }
      model.enabled = false;

      viewUnsubscribe();
      viewUnsubscribe = null;
      interactorUnsubscribe();
      interactorUnsubscribe = null;

      model.actor.setVisibility(false);
      selfRenderer.removeViewProp(model.actor);

      const renderWindow = model.interactor
        .findPokedRenderer()
        .getRenderWindow();
      if (renderWindow) {
        renderWindow.removeRenderer(selfRenderer);
      }
    }
    publicAPI.modified();
  };

  /**
   * Sets the viewport corner.
   */
  publicAPI.setViewportCorner = (corner) => {
    if (corner === model.viewportCorner) {
      return;
    }

    model.viewportCorner = corner;
    if (model.enabled) {
      publicAPI.updateViewport();
    }
  };

  /**
   * Sets the viewport size.
   */
  publicAPI.setViewportSize = (sizeFactor) => {
    const viewportSize = Math.min(1, Math.max(0, sizeFactor));
    if (viewportSize === model.viewportSize) {
      return;
    }

    model.viewportSize = viewportSize;
    if (model.enabled) {
      publicAPI.updateViewport();
    }
  };

  publicAPI.setActor = (actor) => {
    const previousState = model.enabled;
    publicAPI.setEnabled(false);
    model.actor = actor;
    publicAPI.setEnabled(previousState);
  };
}

// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------

export const DEFAULT_VALUES = {
  // actor: null,
  // interactor: null,
  viewportCorner: Constants.Corners.BOTTOM_LEFT,
  viewportSize: 0.2,
  minPixelSize: 50,
  maxPixelSize: 200,
};

// ----------------------------------------------------------------------------

export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);

  // Build VTK API
  macro.obj(publicAPI, model);

  macro.get(publicAPI, model, ['enabled', 'viewportCorner', 'viewportSize']);

  // NOTE: setting these while the widget is enabled will
  // not update the widget.
  macro.setGet(publicAPI, model, [
    'interactor',
    'minPixelSize',
    'maxPixelSize',
  ]);
  macro.get(publicAPI, model, [
    'actor',
  ]);

  // Object methods
  vtkOrientationMarkerWidget(publicAPI, model);
}

// ----------------------------------------------------------------------------

export const newInstance = macro.newInstance(
  extend,
  'vtkOrientationMarkerWidget'
);

// ----------------------------------------------------------------------------

export default Object.assign({ newInstance, extend }, Constants);
<|endoftext|>