<commit_before>/*global define */
/*jslint white: true, browser: true, plusplus: true */
define([
    'jquery',
    'handlebars',
    'numeral',
    'bluebird',
    'datatables',
    'kb/common/html',
    'kb_sdk_clients/SetAPI/dev/SetAPIClient',
    'kb/service/client/workspace',
    '../utils',
    'text!../../resources/html/reads_set.html',
    'datatables_bootstrap'
], function (
    $,
    handlebars,
    Numeral,
    Promise,
    DataTable,
    html,
    SetAPI,
    Workspace,
    utils,
    RSTemplate
) {
        'use strict';

        //http://localhost:8080/#dataview/11700/set_o_reads/1
        function factory(config) {
            var parent,
                container,
                runtime = config.runtime,
                div = html.tag('div'),
                templates = $.parseHTML(RSTemplate),
                outer = templates[0].innerHTML,
                browse_fill = "{{#each readLibraries}}"
                    + "
"
                    + "{{this.name}}	"
                    + "{{this.type}}	"
                    + "{{this.data.read_count}}	"
                    + "{{this.data.read_size}}	"
                    + "{{this.data.insert_size_mean}}	"
                    + "
"
                    + "{{/each}}";

            // VIEW

            function layout() {
                return div(
                    html.makePanel({
                        title: 'Summary',
                        content: outer
                    })
                );
            }

            function setDataElementHTML(element, value) {
                try {
                    container.querySelector("[data-element='" + element + "']").innerHTML = value;
                }
                catch (err) {
                    console.error("While setting data element '" + element + "':", err);
                    throw err;
                }
            }

            function renderSummary(data) {
                var formatValue = function (data, type, row) {
                    var out = Numeral(data).format('0,0');

                    if (out === '0') {
                        return "Missing";
                    } else {
                        return out;
                    }
                };

                setDataElementHTML('reads-set-description', data.set.description);
                setDataElementHTML('reads-set-type', data.set.type);
                setDataElementHTML('reads-set-libraries-count',
                    Numeral(data.set.item_count).format('0,0'));
                setDataElementHTML('reads-set-total-reads',
                    Numeral(data.set.stats.read_count).format('0,0'));
                setDataElementHTML('reads-set-total-basepairs',
                    Numeral(data.set.stats.bp_count).format('0,0'));
                container.querySelector('[id="reads-set-browse-id"] table tbody').innerHTML = handlebars.compile(browse_fill)({ 'readLibraries': data.row_contents });
                $('[id="reads-set-browse-id"]').removeClass('hidden');
                $('[id="reads-set-browse-table"]').DataTable({
                    "columns": [
                        { data: 'name' },
                        { data: 'type' },
                        {
                            data: 'data.read_count',
                            render: formatValue
                        },
                        {
                            data: 'data.read_size',
                            render: formatValue
                        },
                        {
                            data: 'data.insert_size_mean',
                            render: formatValue
                        }
                    ]
                });
            }

            // utility functions

            function getReadsSetClient() {
                return new SetAPI({
                    url: runtime.getConfig('services.service_wizard.url'),
                    auth: { token: runtime.service('session').getAuthToken() },
                    version: 'release'
                });
            }

            function getWorkspaceClient() {
                return new Workspace(
                    runtime.getConfig('services.workspace.url'),
                    { token: runtime.service('session').getAuthToken() }
                );
            }

            function fetchReadsSet(params) {
                var setAPI = getReadsSetClient(),
                    wsClient = getWorkspaceClient(),
                    readsSetInfo = {};

                return setAPI.get_reads_set_v1({
                    ref: utils.getRef(params),
                    include_item_info: 1
                })
                    .then(function (results) {
                        var refs = [],
                            readsTypeId,
                            readsType;

                        // pull all reads objects to calculate summary stats
                        // and individual browse row contents
                        if (results.data.items.length === 0) {
                            readsType = 'No Reads';
                        } else {
                            results.data.items.forEach(function (item, index) {
                                if (index === 0) {
                                    readsTypeId = item.info[2];
                                } else if (item.info[2] !== readsTypeId) {
                                    readsType = 'Mixed Reads';
                                }
                                refs.push({
                                    ref: item.ref
                                });
                            });
                        }
                        if (!readsType) {
                            readsType = readsTypeId.split('-')[0].split('.')[1]
                        }
                        readsSetInfo.set = {
                            name: results.info[1],
                            type: readsType,
                            description: results.data.description,
                            items: results.data.items,
                            item_count: results.data.items.length
                        };

                        return refs;
                    })
                    .then(function (refs) {
                        if (refs.length) {
                            return wsClient.get_objects(refs);
                        } else {
                            return [];
                        }
                    })
                    .then(function (data) {
                        var i = 0;

                        readsSetInfo.row_contents = data;
                        readsSetInfo.set.stats = {
                            read_count: 0,
                            bp_count: 0
                        };
                        // calculate summary stats
                        for (i = 0; i < data.length; i++) {
                            readsSetInfo.row_contents[i].name = data[i].info[1];
                            readsSetInfo.row_contents[i].type = data[i].info[2].split('-')[0].split('.')[1];
                            if (data[i].data.hasOwnProperty('read_count')) {
                                readsSetInfo.set.stats.read_count += data[i].data.read_count;
                                if (data[i].data.hasOwnProperty('read_size')) {
                                    readsSetInfo.set.stats.bp_count += data[i].data.read_count * data[i].data.read_size;
                                }
                            }
                        }
                        return readsSetInfo;
                    })
                    .error(function (err) {
                        console.error(err);
                        container.empty();
                        container.appendChild('Error' + JSON.stringify(err));
                    });
            }

            // WIDGET API
            function attach(node) {
                parent = node;
                container = parent.appendChild(document.createElement('div'));
                container.innerHTML = layout();
            }

            function start(params) {
                Array.prototype.slice.call(container.querySelectorAll("[data-element]"))
                    .forEach(function (e) {
                        e.innerHTML = html.loading();
                    });

                return fetchReadsSet(params).then(function (results) {
                    renderSummary(results);
                });
            }

            function stop() {
                // nothing to do
            }

            function detach() {
                // nothing to do necessarily, since the parent dom node will
                // be removed the controller for this widget removes it,
                // but it is nice to take responsibility for undoing what we
                // changed in the parent node:
                if (parent && container) {
                    container.innerHTML = '';
                    parent.removeChild(container);
                }
            }

            return Object.freeze({
                attach: attach,
                start: start,
                stop: stop,
                detach: detach
            });
        }

        return {
            make: function (config) {
                return factory(config);
            }
        };
    });<commit_msg>Reformat according to js-beautify (via vsc plugin)<commit_after>/*global define */
/*jslint white: true, browser: true, plusplus: true */
define([
    'jquery',
    'handlebars',
    'numeral',
    'bluebird',
    'datatables',
    'kb/common/html',
    'kb_sdk_clients/SetAPI/dev/SetAPIClient',
    'kb/service/client/workspace',
    '../utils',
    'text!../../resources/html/reads_set.html',
    'datatables_bootstrap'
], function(
    $,
    handlebars,
    Numeral,
    Promise,
    DataTable,
    html,
    SetAPI,
    Workspace,
    utils,
    RSTemplate
) {
    'use strict';

    //http://localhost:8080/#dataview/11700/set_o_reads/1
    function factory(config) {
        var parent,
            container,
            runtime = config.runtime,
            div = html.tag('div'),
            templates = $.parseHTML(RSTemplate),
            outer = templates[0].innerHTML,
            browse_fill = "{{#each readLibraries}}" +
            "
" +
            "{{this.name}}	" +
            "{{this.type}}	" +
            "{{this.data.read_count}}	" +
            "{{this.data.read_size}}	" +
            "{{this.data.insert_size_mean}}	" +
            "
" +
            "{{/each}}";

        // VIEW

        function layout() {
            return div(
                html.makePanel({
                    title: 'Summary',
                    content: outer
                })
            );
        }

        function setDataElementHTML(element, value) {
            try {
                container.querySelector("[data-element='" + element + "']").innerHTML = value;
            } catch (err) {
                console.error("While setting data element '" + element + "':", err);
                throw err;
            }
        }

        function renderSummary(data) {
            var formatValue = function(data, type, row) {
                var out = Numeral(data).format('0,0');

                if (out === '0') {
                    return "Missing";
                } else {
                    return out;
                }
            };

            setDataElementHTML('reads-set-description', data.set.description);
            setDataElementHTML('reads-set-type', data.set.type);
            setDataElementHTML('reads-set-libraries-count',
                Numeral(data.set.item_count).format('0,0'));
            setDataElementHTML('reads-set-total-reads',
                Numeral(data.set.stats.read_count).format('0,0'));
            setDataElementHTML('reads-set-total-basepairs',
                Numeral(data.set.stats.bp_count).format('0,0'));
            container.querySelector('[id="reads-set-browse-id"] table tbody').innerHTML = handlebars.compile(browse_fill)({ 'readLibraries': data.row_contents });
            $('[id="reads-set-browse-id"]').removeClass('hidden');
            $('[id="reads-set-browse-table"]').DataTable({
                "columns": [
                    { data: 'name' },
                    { data: 'type' },
                    {
                        data: 'data.read_count',
                        render: formatValue
                    },
                    {
                        data: 'data.read_size',
                        render: formatValue
                    },
                    {
                        data: 'data.insert_size_mean',
                        render: formatValue
                    }
                ]
            });
        }

        // utility functions

        function getReadsSetClient() {
            return new SetAPI({
                url: runtime.getConfig('services.service_wizard.url'),
                auth: { token: runtime.service('session').getAuthToken() },
                version: 'release'
            });
        }

        function getWorkspaceClient() {
            return new Workspace(
                runtime.getConfig('services.workspace.url'), { token: runtime.service('session').getAuthToken() }
            );
        }

        function fetchReadsSet(params) {
            var setAPI = getReadsSetClient(),
                wsClient = getWorkspaceClient(),
                readsSetInfo = {};

            return setAPI.get_reads_set_v1({
                    ref: utils.getRef(params),
                    include_item_info: 1
                })
                .then(function(results) {
                    var refs = [],
                        readsTypeId,
                        readsType;

                    // pull all reads objects to calculate summary stats
                    // and individual browse row contents
                    if (results.data.items.length === 0) {
                        readsType = 'No Reads';
                    } else {
                        results.data.items.forEach(function(item, index) {
                            if (index === 0) {
                                readsTypeId = item.info[2];
                            } else if (item.info[2] !== readsTypeId) {
                                readsType = 'Mixed Reads';
                            }
                            refs.push({
                                ref: item.ref
                            });
                        });
                    }
                    if (!readsType) {
                        readsType = readsTypeId.split('-')[0].split('.')[1]
                    }
                    readsSetInfo.set = {
                        name: results.info[1],
                        type: readsType,
                        description: results.data.description,
                        items: results.data.items,
                        item_count: results.data.items.length
                    };

                    return refs;
                })
                .then(function(refs) {
                    if (refs.length) {
                        return wsClient.get_objects(refs);
                    } else {
                        return [];
                    }
                })
                .then(function(data) {
                    var i = 0;

                    readsSetInfo.row_contents = data;
                    readsSetInfo.set.stats = {
                        read_count: 0,
                        bp_count: 0
                    };
                    // calculate summary stats
                    for (i = 0; i < data.length; i++) {
                        readsSetInfo.row_contents[i].name = data[i].info[1];
                        readsSetInfo.row_contents[i].type = data[i].info[2].split('-')[0].split('.')[1];
                        if (data[i].data.hasOwnProperty('read_count')) {
                            readsSetInfo.set.stats.read_count += data[i].data.read_count;
                            if (data[i].data.hasOwnProperty('read_size')) {
                                readsSetInfo.set.stats.bp_count += data[i].data.read_count * data[i].data.read_size;
                            }
                        }
                    }
                    return readsSetInfo;
                })
                .error(function(err) {
                    console.error(err);
                    container.empty();
                    container.appendChild('Error' + JSON.stringify(err));
                });
        }

        // WIDGET API
        function attach(node) {
            parent = node;
            container = parent.appendChild(document.createElement('div'));
            container.innerHTML = layout();
        }

        function start(params) {
            Array.prototype.slice.call(container.querySelectorAll("[data-element]"))
                .forEach(function(e) {
                    e.innerHTML = html.loading();
                });

            return fetchReadsSet(params).then(function(results) {
                renderSummary(results);
            });
        }

        function stop() {
            // nothing to do
        }

        function detach() {
            // nothing to do necessarily, since the parent dom node will
            // be removed the controller for this widget removes it,
            // but it is nice to take responsibility for undoing what we
            // changed in the parent node:
            if (parent && container) {
                container.innerHTML = '';
                parent.removeChild(container);
            }
        }

        return Object.freeze({
            attach: attach,
            start: start,
            stop: stop,
            detach: detach
        });
    }

    return {
        make: function(config) {
            return factory(config);
        }
    };
});<|endoftext|>


<commit_before>var startOfDay = require('./start_of_day')
var startOfYear = require('./start_of_year')
var parse = require('./parse')

var NUMBER_OF_MS_IN_DAY = 864e5

/**
 * Returns formatted date string in a given format
 * @param {date|string} date
 * @param {string} format
 * @returns {string}
 */
var format = function(date, format) {
  if (typeof date == 'string') {
    date = parse(date)
  } else if (typeof date == 'number') {
    date = new Date(date)
  }

  if (!format) {
    format = 'YYYY-MM-DDTHH:mm:ss.SSSZ'
  }

  var formatFunction = makeFormatFunction(format)
  return formatFunction(date)
}

var formats = {
  'M': function() {
    return this.getMonth() + 1
  },
  'MM': function() {
    return leftZeroFill(this.getMonth() + 1, 2)
  },
  'MMM': function() {
    return locale.monthsShort[this.getMonth()]
  },
  'MMMM': function() {
    return locale.months[this.getMonth()]
  },
  'Q': function() {
    return Math.ceil((this.getMonth() + 1) / 3)
  },
  'D': function() {
    return this.getDate()
  },
  'DD': function() {
    return leftZeroFill(this.getDate(), 2)
  },
  'DDD': function() {
    var diffWithStartOfYear
      = startOfDay(this).getTime() - startOfYear(this).getTime()
    return Math.floor(diffWithStartOfYear / NUMBER_OF_MS_IN_DAY) + 1
  },
  'DDDD': function() {
    return leftZeroFill(formats['DDD'].apply(this), 3)
  },
  'd': function() {
    return this.getDay()
  },
  'dd': function() {
    return locale.dayNamesMin[this.getDay()]
  },
  'ddd': function() {
    return locale.dayNamesShort[this.getDay()]
  },
  'dddd': function() {
    return locale.dayNames[this.getDay()]
  },
  'E': function() {
    return this.getDay() + 1
  },
  'YY': function() {
    return String(this.getFullYear()).substr(2)
  },
  'YYYY': function() {
    return this.getFullYear()
  },
  'A': function() {
    return (this.getHours() / 12) >= 1 ? 'PM' : 'AM'
  },
  'a': function() {
    return (this.getHours() / 12) >= 1 ? 'pm' : 'am'
  },
  'aa': function(){
    return (this.getHours() / 12) >= 1 ? 'p.m.' : 'a.m.'
  },
  'H': function() {
    return this.getHours()
  },
  'HH': function() {
    return leftZeroFill(this.getHours(), 2)
  },
  'h': function() {
    var hours = this.getHours()
    if (hours == 0) {
      return 12
    } else if (hours > 12) {
      return hours % 12
    } else {
      return hours
    }
  },
  'hh': function() {
    return leftZeroFill(formats['h'].apply(this), 2)
  },
  'm': function() {
    return this.getMinutes()
  },
  'mm': function() {
    return leftZeroFill(this.getMinutes(), 2)
  },
  's': function() {
    return this.getSeconds()
  },
  'ss': function() {
    return leftZeroFill(this.getSeconds(), 2)
  },
  'S': function() {
    return this.getMilliseconds()
  },
  'SS': function() {
    return leftZeroFill(this.getMilliseconds(), 2)
  },
  'SSS': function() {
    return leftZeroFill(this.getMilliseconds(), 3)
  }
}

var ordinalFunctions = ['M', 'D', 'DDD', 'd']
ordinalFunctions.forEach(function(functionName) {
  formats[functionName + 'o'] = function() {
    return locale.ordinal(formats[functionName].apply(this))
  }
})

var formattingTokens = Object.keys(formats).sort().reverse()
var formattingTokensRegexp = new RegExp(
  '(\\[[^\\[]*\\])|(\\\\)?' + '(' + formattingTokens.join('|') + '|.)', 'g'
)

var makeFormatFunction = function(format) {
  var array = format.match(formattingTokensRegexp), i, length

  for (i = 0, length = array.length; i < length; i++) {
    if (formats[array[i]]) {
      array[i] = formats[array[i]]
    } else {
      array[i] = removeFormattingTokens(array[i])
    }
  }

  return function(mom) {
    var output = ''
    for (i = 0; i < length; i++) {
      if (array[i] instanceof Function) {
        output += array[i].call(mom, format)
      } else {
        output += array[i]
      }
    }
    return output
  }
}

var removeFormattingTokens = function(input) {
  if (input.match(/\[[\s\S]/)) {
    return input.replace(/^\[|\]$/g, '')
  }
  return input.replace(/\\/g, '')
}

var leftZeroFill = function(number, targetLength) {
  var output = String(Math.abs(number))

  while (output.length < targetLength) {
    output = '0' + output
  }
  return output
}

var locale = {
  ordinal: function(number) {
    if (number > 20 || number < 10) {
      switch (number % 10) {
        case 1:
          return number + 'st'
        case 2:
          return number + 'nd'
        case 3:
          return number + 'rd'
      }
    }
    return number + 'th'
  },
  months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
  monthsShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
  dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
  dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
  dayNamesMin: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']
}

module.exports = format

<commit_msg>Fix linting error<commit_after>var startOfDay = require('./start_of_day')
var startOfYear = require('./start_of_year')
var parse = require('./parse')

var NUMBER_OF_MS_IN_DAY = 864e5

/**
 * Returns formatted date string in a given format
 * @param {date|string} date
 * @param {string} format
 * @returns {string}
 */
var format = function(date, format) {
  if (typeof date == 'string') {
    date = parse(date)
  } else if (typeof date == 'number') {
    date = new Date(date)
  }

  if (!format) {
    format = 'YYYY-MM-DDTHH:mm:ss.SSSZ'
  }

  var formatFunction = makeFormatFunction(format)
  return formatFunction(date)
}

var formats = {
  'M': function() {
    return this.getMonth() + 1
  },
  'MM': function() {
    return leftZeroFill(this.getMonth() + 1, 2)
  },
  'MMM': function() {
    return locale.monthsShort[this.getMonth()]
  },
  'MMMM': function() {
    return locale.months[this.getMonth()]
  },
  'Q': function() {
    return Math.ceil((this.getMonth() + 1) / 3)
  },
  'D': function() {
    return this.getDate()
  },
  'DD': function() {
    return leftZeroFill(this.getDate(), 2)
  },
  'DDD': function() {
    var diffWithStartOfYear
      = startOfDay(this).getTime() - startOfYear(this).getTime()
    return Math.floor(diffWithStartOfYear / NUMBER_OF_MS_IN_DAY) + 1
  },
  'DDDD': function() {
    return leftZeroFill(formats['DDD'].apply(this), 3)
  },
  'd': function() {
    return this.getDay()
  },
  'dd': function() {
    return locale.dayNamesMin[this.getDay()]
  },
  'ddd': function() {
    return locale.dayNamesShort[this.getDay()]
  },
  'dddd': function() {
    return locale.dayNames[this.getDay()]
  },
  'E': function() {
    return this.getDay() + 1
  },
  'YY': function() {
    return String(this.getFullYear()).substr(2)
  },
  'YYYY': function() {
    return this.getFullYear()
  },
  'A': function() {
    return (this.getHours() / 12) >= 1 ? 'PM' : 'AM'
  },
  'a': function() {
    return (this.getHours() / 12) >= 1 ? 'pm' : 'am'
  },
  'aa': function() {
    return (this.getHours() / 12) >= 1 ? 'p.m.' : 'a.m.'
  },
  'H': function() {
    return this.getHours()
  },
  'HH': function() {
    return leftZeroFill(this.getHours(), 2)
  },
  'h': function() {
    var hours = this.getHours()
    if (hours == 0) {
      return 12
    } else if (hours > 12) {
      return hours % 12
    } else {
      return hours
    }
  },
  'hh': function() {
    return leftZeroFill(formats['h'].apply(this), 2)
  },
  'm': function() {
    return this.getMinutes()
  },
  'mm': function() {
    return leftZeroFill(this.getMinutes(), 2)
  },
  's': function() {
    return this.getSeconds()
  },
  'ss': function() {
    return leftZeroFill(this.getSeconds(), 2)
  },
  'S': function() {
    return this.getMilliseconds()
  },
  'SS': function() {
    return leftZeroFill(this.getMilliseconds(), 2)
  },
  'SSS': function() {
    return leftZeroFill(this.getMilliseconds(), 3)
  }
}

var ordinalFunctions = ['M', 'D', 'DDD', 'd']
ordinalFunctions.forEach(function(functionName) {
  formats[functionName + 'o'] = function() {
    return locale.ordinal(formats[functionName].apply(this))
  }
})

var formattingTokens = Object.keys(formats).sort().reverse()
var formattingTokensRegexp = new RegExp(
  '(\\[[^\\[]*\\])|(\\\\)?' + '(' + formattingTokens.join('|') + '|.)', 'g'
)

var makeFormatFunction = function(format) {
  var array = format.match(formattingTokensRegexp), i, length

  for (i = 0, length = array.length; i < length; i++) {
    if (formats[array[i]]) {
      array[i] = formats[array[i]]
    } else {
      array[i] = removeFormattingTokens(array[i])
    }
  }

  return function(mom) {
    var output = ''
    for (i = 0; i < length; i++) {
      if (array[i] instanceof Function) {
        output += array[i].call(mom, format)
      } else {
        output += array[i]
      }
    }
    return output
  }
}

var removeFormattingTokens = function(input) {
  if (input.match(/\[[\s\S]/)) {
    return input.replace(/^\[|\]$/g, '')
  }
  return input.replace(/\\/g, '')
}

var leftZeroFill = function(number, targetLength) {
  var output = String(Math.abs(number))

  while (output.length < targetLength) {
    output = '0' + output
  }
  return output
}

var locale = {
  ordinal: function(number) {
    if (number > 20 || number < 10) {
      switch (number % 10) {
        case 1:
          return number + 'st'
        case 2:
          return number + 'nd'
        case 3:
          return number + 'rd'
      }
    }
    return number + 'th'
  },
  months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
  monthsShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
  dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
  dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
  dayNamesMin: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']
}

module.exports = format

<|endoftext|>


<commit_before>import React, { Component } from 'react';
import {Page, List, ListItem, ListHeader, Icon} from 'react-onsenui';
import ons from 'onsenui';

import {ngm} from './NagomeConn.js';
import SettingPlugin from './SettingPlugin.js';
import SettingAccount from './SettingAccount.js';
import Settings from './Settings.js';

export default class Menu extends Component {
    constructor() {
        super();

        this.refSettingPlugin = null;
        this.refSettings = null;

        ngm.addNgmEvHandler("nagome_directngm", this.settingsDirectHandler.bind(this));
    }

    settingsDirectHandler(arrM) {
        for (let i = 0, len = arrM.length; i < len; i++) {
            let m = arrM[i];
            switch (m.command) {
            case "Plug.List":
                if (this.refSettingPlugin === null) return;
                this.refSettingPlugin.updateList(m.content.plugins);
                break;

            case "Settings.Current":
                if (this.refSettings === null) return;
                this.refSettings.update(m.content);
                break;

            default:
                console.log(m);
            }
        }
    }

    componentWillMount() {
        this.menuLists = [
            {
                title: "Comment",
                list: [
                    {text: "Connect to URI",
                        icon: "fa-link",
                        fn: () => {
                            ons.notification.prompt({
                                title: 'Connect',
                                message: 'Input Live ID or URI',
                                cancelable: true,
                                callback: (br) => {
                                    ngm.broadConnect(br);
                                },
                            }).catch(()=>{});
                        }},
                    {text: "Disconnect",
                        icon: "fa-minus-circle",
                        fn: () => {
                            ngm.broadDisconnect();
                        }},
                    {text: "Clear comments",
                        icon: "fa-file-o",
                        fn: () => {
                            ngm.clearComments();
                        }},
                ],
            },
            {
                title: "Settings",
                list: [
                    {text: "Plugins",
                        icon: "fa-file-o",
                        fn: () => {
                            ngm.pluginList();
                            this.props.navigator.pushPage({
                                component: SettingPlugin,
                                props: {
                                    ref: (r) => {
                                        this.refSettingPlugin = r;
                                    },
                                },
                                key: "Plugins"
                            });
                        }},
                    {text: "Settings",
                        icon: "fa-file-o",
                        fn: () => {
                            ngm.settingsCurrent();
                            this.props.navigator.pushPage({
                                component: Settings,
                                props: {
                                    ref: (r) => {
                                        this.refSettings = r;
                                    },
                                },
                                key: "Settings"
                            });
                        }},
                ]
            },
            {
                title: "App Settings",
                list: [
                    {text: "Account",
                        icon: "fa-file-o",
                        fn: () => {
                            this.props.navigator.pushPage({
                                component: SettingAccount,
                                key: "Account"
                            });
                        }},
                ]
            },
        ];
    }

    handleMenuSelect(f) {
        this.props.onSelect();
        f();
    }

    renderRow(m) {
        return (
            <ListItem key={m.text} onClick={this.handleMenuSelect.bind(this, m.fn)} tappable>

                        <Icon icon={m.icon} />

                        {m.text}

                </ListItem>
            );
    }

    renderLists(lists) {
        return lists.map((list)=>{
            return (
                <List
                    key={list.title}
                    dataSource={list.list}
                    renderRow={this.renderRow.bind(this)}
                    renderHeader={() =>
                        <ListHeader>{list.title}</ListHeader>
                    }
                />
            );
        });
    }

    render() {
        return (
            <Page>
                {this.renderLists(this.menuLists)}
            </Page>
        );
    }
}
<commit_msg>change menu icons<commit_after>import React, { Component } from 'react';
import {Page, List, ListItem, ListHeader, Icon} from 'react-onsenui';
import ons from 'onsenui';

import {ngm} from './NagomeConn.js';
import SettingPlugin from './SettingPlugin.js';
import SettingAccount from './SettingAccount.js';
import Settings from './Settings.js';

export default class Menu extends Component {
    constructor() {
        super();

        this.refSettingPlugin = null;
        this.refSettings = null;

        ngm.addNgmEvHandler("nagome_directngm", this.settingsDirectHandler.bind(this));
    }

    settingsDirectHandler(arrM) {
        for (let i = 0, len = arrM.length; i < len; i++) {
            let m = arrM[i];
            switch (m.command) {
            case "Plug.List":
                if (this.refSettingPlugin === null) return;
                this.refSettingPlugin.updateList(m.content.plugins);
                break;

            case "Settings.Current":
                if (this.refSettings === null) return;
                this.refSettings.update(m.content);
                break;

            default:
                console.log(m);
            }
        }
    }

    componentWillMount() {
        this.menuLists = [
            {
                title: "Comment",
                list: [
                    {text: "Connect to URI",
                        icon: "fa-link",
                        fn: () => {
                            ons.notification.prompt({
                                title: 'Connect',
                                message: 'Input Live ID or URI',
                                cancelable: true,
                                callback: (br) => {
                                    ngm.broadConnect(br);
                                },
                            }).catch(()=>{});
                        }},
                    {text: "Disconnect",
                        icon: "fa-minus-circle",
                        fn: () => {
                            ngm.broadDisconnect();
                        }},
                    {text: "Clear comments",
                        icon: "fa-trash",
                        fn: () => {
                            ngm.clearComments();
                        }},
                ],
            },
            {
                title: "Settings",
                list: [
                    {text: "Plugins",
                        icon: "fa-plug",
                        fn: () => {
                            ngm.pluginList();
                            this.props.navigator.pushPage({
                                component: SettingPlugin,
                                props: {
                                    ref: (r) => {
                                        this.refSettingPlugin = r;
                                    },
                                },
                                key: "Plugins"
                            });
                        }},
                    {text: "Settings",
                        icon: "fa-gear",
                        fn: () => {
                            ngm.settingsCurrent();
                            this.props.navigator.pushPage({
                                component: Settings,
                                props: {
                                    ref: (r) => {
                                        this.refSettings = r;
                                    },
                                },
                                key: "Settings"
                            });
                        }},
                ]
            },
            {
                title: "App Settings",
                list: [
                    {text: "Account",
                        icon: "fa-user",
                        fn: () => {
                            this.props.navigator.pushPage({
                                component: SettingAccount,
                                key: "Account"
                            });
                        }},
                ]
            },
        ];
    }

    handleMenuSelect(f) {
        this.props.onSelect();
        f();
    }

    renderRow(m) {
        return (
            <ListItem key={m.text} onClick={this.handleMenuSelect.bind(this, m.fn)} tappable>

                        <Icon icon={m.icon} />

                        {m.text}

                </ListItem>
            );
    }

    renderLists(lists) {
        return lists.map((list)=>{
            return (
                <List
                    key={list.title}
                    dataSource={list.list}
                    renderRow={this.renderRow.bind(this)}
                    renderHeader={() =>
                        <ListHeader>{list.title}</ListHeader>
                    }
                />
            );
        });
    }

    render() {
        return (
            <Page>
                {this.renderLists(this.menuLists)}
            </Page>
        );
    }
}
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies
 */
var Color = require('famous-utilities').Color;

/**
 * The Mesh class is responsible for providing the API for how
 * a RenderNode will interact with the WebGL API by adding
 * a set of commands to the renderer.
 *
 * @class Mesh
 * @constructor
 * @param {RenderNode} RenderNode to which the instance of Mesh will be a component of
 */
function Mesh (dispatch, options) {
    this.dispatch = dispatch;
    this.queue = ['GL_CREATE_MESH'];
    this._id = dispatch.addRenderable(this);
    this._color = new Color('rgb', 0.5, 0.5, 0.5);
    this._size = [];

    this._expressions = {};
    this._geometry = void 0;

    init.call(this);

    if (options) this.setOptions(options);
}

Mesh.toString = function toString () {
    return 'Mesh';
};

function init() {
    var dispatch = this.dispatch;
    dispatch.onTransformChange(this._receiveTransformChange.bind(this));
    dispatch.onSizeChange(this._receiveSizeChange.bind(this));
    dispatch.onOpacityChange(this._receiveOpacityChange.bind(this));
    dispatch.onOriginChange(this._receiveOriginChange.bind(this));
    this._receiveTransformChange(dispatch.getContext()._transform);
    this._receiveOriginChange(dispatch.getContext()._origin);
    return this;
};

Mesh.prototype._receiveTransformChange = function _receiveTransformChange(transform) {
    this.dispatch.dirtyRenderable(this._id);
    this.queue.push('GL_UNIFORMS');
    this.queue.push('transform');
    this.queue.push(transform._matrix);
};

Mesh.prototype._receiveSizeChange = function _receiveSizeChange(size) {
    var size = size.getTopDownSize();
    this.dispatch.dirtyRenderable(this._id);

    this._size[0] = size[0];
    this._size[1] = size[1];
    this._size[2] = size[2];

    this.queue.push('GL_UNIFORMS');
    this.queue.push('size');
    this.queue.push(size);
};

Mesh.prototype._receiveOriginChange = function _receiveOriginChange(origin) {
    this.dispatch.dirtyRenderable(this._id);
    this.queue.push('GL_UNIFORMS');
    this.queue.push('origin');
    this.queue.push(origin);
};

Mesh.prototype._receiveOpacityChange = function _receiveOpacityChange(opacity) {
    this.dispatch.dirtyRenderable(this._id);
    this.queue.push('GL_UNIFORMS');
    this.queue.push('opacity');
    this.queue.push(opacity.value);
};

Mesh.prototype.getSize = function getSize() {
    return this._size;
};

/**
 * Set the geometry of a mesh
 *
 * @method setGeometry
 * @chainable
 *
 * @param {Geometry} geometry instance to be associated with the mesh
 */
Mesh.prototype.setGeometry = function (geometry) {
    var i;
    var key;
    var buffers;
    var bufferIndex;

    if (this._geometry !== geometry) {
        this.queue.push('GL_SET_GEOMETRY');
        this.queue.push(geometry.id);
        this.queue.push(geometry.spec.type);
        this.queue.push(geometry.spec.dynamic);

        this._geometry = geometry;
    }

    return this;
};

/**
 * Empties the command queue
 *
 * @method clean
 * @chainable
 *
 */
Mesh.prototype.clean = function clean() {
    var path = this.dispatch.getRenderPath();

    this.dispatch
        .sendDrawCommand('WITH')
        .sendDrawCommand(path);

    var bufferIndex;
    if (this._geometry) {
        i = this._geometry.spec.invalidations.length;
        while (i--) {
            bufferIndex = this._geometry.spec.invalidations.pop();
            this.dispatch.sendDrawCommand('GL_BUFFER_DATA');
            this.dispatch.sendDrawCommand(this._geometry.id);
            this.dispatch.sendDrawCommand(this._geometry.spec.bufferNames[i]);
            this.dispatch.sendDrawCommand(this._geometry.spec.bufferValues[i]);
            this.dispatch.sendDrawCommand(this._geometry.spec.bufferSpacings[i]);
        }
    }

    var baseColor = this._expressions.baseColor;
    var uniformKey;
    if (baseColor) {
        i = baseColor.invalidations.length;
        while (i--) {
            uniformKey = baseColor.invalidations.pop();
            this.dispatch.sendDrawCommand('GL_UNIFORMS');
            this.dispatch.sendDrawCommand(uniformKey);
            this.dispatch.sendDrawCommand(baseColor.uniforms[uniformKey]);
        }
    }

    if (this._color.isActive()) {
        this.dispatch.sendDrawCommand('GL_UNIFORMS');
        this.dispatch.sendDrawCommand('baseColor');
        this.dispatch.sendDrawCommand(this._color.getRGB());
    }

    var i = this.queue.length;
    while (i--) this.dispatch.sendDrawCommand(this.queue.shift());

    return this.queue.length;
};

/**
 * Defines a 3-element map that provides the overall color of the mesh.
 *
 * @method baseColor
 * @chainable
 *
 * @param {Object, Array} Material, image, or vec3
 * @return {Element} current Mesh
 */
Mesh.prototype.baseColor = function baseColor() {
    this.dispatch.dirtyRenderable(this._id);
    var materialExpression = Array.prototype.concat.apply([], arguments);

    if (materialExpression[0]._compile) {
        this.queue.push('MATERIAL_INPUT');
        this._expressions.baseColor = materialExpression[0];
        materialExpression = materialExpression[0]._compile();
    }
    else {
        this.queue.push('GL_UNIFORMS');
        this._color.set(materialExpression);
    }

    this.queue.push('baseColor');
    this.queue.push(materialExpression);
    return this;
};

/**
 * Defines a 3-element map which is used to provide significant physical detail to
 * the surface by perturbing the facing direction of each individual pixel.
 *
 * @method normal
 * @chainable
 *
 * @param {Object, Array} Material, Image or vec3
 * @return {Element} current Mesh
 */
Mesh.prototype.normal = function (materialExpression) {
    if (materialExpression._compile) materialExpression = materialExpression._compile();
    this.queue.push(typeof materialExpression === 'number' ? 'UNIFORM_INPUT' : 'MATERIAL_INPUT');
    this.queue.push('normal');
    this.queue.push(materialExpression);
    return this;
};

/**
 * Defines 1 element map which is used to normalize the specular and diffuseness of a surface.
 *
 * @method glossiness
 * @chainable
 *
 * @param {Object} Material or Image
 * @return {Element} current Mesh
 */
Mesh.prototype.glossiness = function (materialExpression) {
    if (materialExpression._compile) materialExpression = materialExpression._compile();
    this.queue.push(typeof materialExpression === 'number' ? 'UNIFORM_INPUT' : 'MATERIAL_INPUT');
    this.queue.push('glossiness');
    this.queue.push(materialExpression);
    return this;
};

/**
 * Defines 1 element map which describes the electrical conductivity of a material.
 *
 * @method metallic
 * @chainable
 *
 * @param {Object} Material or Image
 * @return {Element} current Mesh
 */
Mesh.prototype.metallic = function metallic(materialExpression) {
    if (materialExpression._compile) materialExpression = materialExpression._compile();
    this.queue.push(typeof materialExpression === 'number' ? 'UNIFORM_INPUT' : 'MATERIAL_INPUT');
    this.queue.push('metallic');
    this.queue.push(materialExpression);
    return this;
};

/**
 * Defines 3 element map which displaces the position of each vertex in world space.
 *
 * @method metallic
 * @chainable
 *
 * @param {Object} Material or Image
 * @return {Element} current Mesh
 */

Mesh.prototype.setOptions = function setOptions(options) {
    this.queue.push('GL_SET_DRAW_OPTIONS');
    this.queue.push(options);
    return this;
};

module.exports = Mesh;
<commit_msg>add positionOffset<commit_after>'use strict';

/**
 * Module dependencies
 */
var Color = require('famous-utilities').Color;

/**
 * The Mesh class is responsible for providing the API for how
 * a RenderNode will interact with the WebGL API by adding
 * a set of commands to the renderer.
 *
 * @class Mesh
 * @constructor
 * @param {RenderNode} RenderNode to which the instance of Mesh will be a component of
 */
function Mesh (dispatch, options) {
    this.dispatch = dispatch;
    this.queue = ['GL_CREATE_MESH'];
    this._id = dispatch.addRenderable(this);
    this._color = new Color('rgb', 0.5, 0.5, 0.5);
    this._size = [];

    this._expressions = {};
    this._geometry = void 0;

    init.call(this);

    if (options) this.setOptions(options);
}

Mesh.toString = function toString () {
    return 'Mesh';
};

function init() {
    var dispatch = this.dispatch;
    dispatch.onTransformChange(this._receiveTransformChange.bind(this));
    dispatch.onSizeChange(this._receiveSizeChange.bind(this));
    dispatch.onOpacityChange(this._receiveOpacityChange.bind(this));
    dispatch.onOriginChange(this._receiveOriginChange.bind(this));
    this._receiveTransformChange(dispatch.getContext()._transform);
    this._receiveOriginChange(dispatch.getContext()._origin);
    return this;
};

Mesh.prototype._receiveTransformChange = function _receiveTransformChange(transform) {
    this.dispatch.dirtyRenderable(this._id);
    this.queue.push('GL_UNIFORMS');
    this.queue.push('transform');
    this.queue.push(transform._matrix);
};

Mesh.prototype._receiveSizeChange = function _receiveSizeChange(size) {
    var size = size.getTopDownSize();
    this.dispatch.dirtyRenderable(this._id);

    this._size[0] = size[0];
    this._size[1] = size[1];
    this._size[2] = size[2];

    this.queue.push('GL_UNIFORMS');
    this.queue.push('size');
    this.queue.push(size);
};

Mesh.prototype._receiveOriginChange = function _receiveOriginChange(origin) {
    this.dispatch.dirtyRenderable(this._id);
    this.queue.push('GL_UNIFORMS');
    this.queue.push('origin');
    this.queue.push(origin);
};

Mesh.prototype._receiveOpacityChange = function _receiveOpacityChange(opacity) {
    this.dispatch.dirtyRenderable(this._id);
    this.queue.push('GL_UNIFORMS');
    this.queue.push('opacity');
    this.queue.push(opacity.value);
};

Mesh.prototype.getSize = function getSize() {
    return this._size;
};

/**
 * Set the geometry of a mesh
 *
 * @method setGeometry
 * @chainable
 *
 * @param {Geometry} geometry instance to be associated with the mesh
 */
Mesh.prototype.setGeometry = function (geometry) {
    var i;
    var key;
    var buffers;
    var bufferIndex;

    if (this._geometry !== geometry) {
        this.queue.push('GL_SET_GEOMETRY');
        this.queue.push(geometry.id);
        this.queue.push(geometry.spec.type);
        this.queue.push(geometry.spec.dynamic);

        this._geometry = geometry;
    }

    return this;
};

/**
 * Empties the command queue
 *
 * @method clean
 * @chainable
 *
 */
Mesh.prototype.clean = function clean() {
    var path = this.dispatch.getRenderPath();

    this.dispatch
        .sendDrawCommand('WITH')
        .sendDrawCommand(path);

    var bufferIndex;
    if (this._geometry) {
        i = this._geometry.spec.invalidations.length;
        while (i--) {
            bufferIndex = this._geometry.spec.invalidations.pop();
            this.dispatch.sendDrawCommand('GL_BUFFER_DATA');
            this.dispatch.sendDrawCommand(this._geometry.id);
            this.dispatch.sendDrawCommand(this._geometry.spec.bufferNames[i]);
            this.dispatch.sendDrawCommand(this._geometry.spec.bufferValues[i]);
            this.dispatch.sendDrawCommand(this._geometry.spec.bufferSpacings[i]);
        }
    }

    var baseColor = this._expressions.baseColor;
    var uniformKey;
    if (baseColor) {
        i = baseColor.invalidations.length;
        while (i--) {
            uniformKey = baseColor.invalidations.pop();
            this.dispatch.sendDrawCommand('GL_UNIFORMS');
            this.dispatch.sendDrawCommand(uniformKey);
            this.dispatch.sendDrawCommand(baseColor.uniforms[uniformKey]);
        }
    }

    if (this._color.isActive()) {
        this.dispatch.sendDrawCommand('GL_UNIFORMS');
        this.dispatch.sendDrawCommand('baseColor');
        this.dispatch.sendDrawCommand(this._color.getRGB());
    }

    var i = this.queue.length;
    while (i--) this.dispatch.sendDrawCommand(this.queue.shift());

    return this.queue.length;
};

/**
 * Defines a 3-element map that provides the overall color of the mesh.
 *
 * @method baseColor
 * @chainable
 *
 * @param {Object, Array} Material, image, or vec3
 * @return {Element} current Mesh
 */
Mesh.prototype.baseColor = function baseColor() {
    this.dispatch.dirtyRenderable(this._id);
    var materialExpression = Array.prototype.concat.apply([], arguments);

    if (materialExpression[0]._compile) {
        this.queue.push('MATERIAL_INPUT');
        this._expressions.baseColor = materialExpression[0];
        materialExpression = materialExpression[0]._compile();
    }
    else {
        this.queue.push('GL_UNIFORMS');
        this._color.set(materialExpression);
    }

    this.queue.push('baseColor');
    this.queue.push(materialExpression);
    return this;
};

/**
 * Defines a 3-element map which is used to provide significant physical detail to
 * the surface by perturbing the facing direction of each individual pixel.
 *
 * @method normal
 * @chainable
 *
 * @param {Object, Array} Material, Image or vec3
 * @return {Element} current Mesh
 */
Mesh.prototype.normal = function (materialExpression) {
    if (materialExpression._compile) materialExpression = materialExpression._compile();
    this.queue.push(typeof materialExpression === 'number' ? 'UNIFORM_INPUT' : 'MATERIAL_INPUT');
    this.queue.push('normal');
    this.queue.push(materialExpression);
    return this;
};

/**
 * Defines 1 element map which is used to normalize the specular and diffuseness of a surface.
 *
 * @method glossiness
 * @chainable
 *
 * @param {Object} Material or Image
 * @return {Element} current Mesh
 */
Mesh.prototype.glossiness = function (materialExpression) {
    if (materialExpression._compile) materialExpression = materialExpression._compile();
    this.queue.push(typeof materialExpression === 'number' ? 'UNIFORM_INPUT' : 'MATERIAL_INPUT');
    this.queue.push('glossiness');
    this.queue.push(materialExpression);
    return this;
};

/**
 * Defines 1 element map which describes the electrical conductivity of a material.
 *
 * @method metallic
 * @chainable
 *
 * @param {Object} Material or Image
 * @return {Element} current Mesh
 */
Mesh.prototype.metallic = function metallic(materialExpression) {
    if (materialExpression._compile) materialExpression = materialExpression._compile();
    this.queue.push(typeof materialExpression === 'number' ? 'UNIFORM_INPUT' : 'MATERIAL_INPUT');
    this.queue.push('metallic');
    this.queue.push(materialExpression);
    return this;
};

/**
 * Defines 3 element map which displaces the position of each vertex in world space.
 *
 * @method metallic
 * @chainable
 *
 * @param {Object} Material or Image
 * @return {Element} current Mesh
 */

Mesh.prototype.positionOffset = function positionOffset(materialExpression) {
    if (materialExpression._compile) materialExpression = materialExpression._compile();
    this.queue.push(typeof materialExpression === 'number' ? 'UNIFORM_INPUT' : 'MATERIAL_INPUT');
    this.queue.push('positionOffset');
    this.queue.push(materialExpression);
    return this;
};

/**
 * Defines 3 element map which displaces the position of each vertex in world space.
 *
 * @method metallic
 * @chainable
 *
 * @param {Object} Material or Image
 * @return {Element} current Mesh
 */

Mesh.prototype.setOptions = function setOptions(options) {
    this.queue.push('GL_SET_DRAW_OPTIONS');
    this.queue.push(options);
    return this;
};

module.exports = Mesh;
<|endoftext|>


<commit_before>/**
 * Created by elgs on 7/1/14.
 */

(function () {
    "use strict";

    var Yotta = require('./yotta.js').Yotta;
    var db;

    var p = {
        context: ''
    };
    module.exports = p;

    p.test = function () {
        console.log(Array.prototype.slice.call(arguments));
    };

    p.use = function () {
        var args = Array.prototype.slice.call(arguments);
        var dbName = args[0];
        if (dbName === p.context) {
            return;
        }
        if (!dbName) {
            db.close();
            p.context = dbName;
            return;
        }
        if (db) {
            db.close();
        }
        p.context = dbName;
        db = new Yotta(p.context);
        db.open();
    };

    p.close = function () {
        if (p.context) {
            db.close();
        }
    };

    p.put = function () {
    };

    p.get = function () {
    };

    p.remove = function () {
    };

    p.vacuum = function () {
    };
})();<commit_msg>implemented yotta cli<commit_after>/**
 * Created by elgs on 7/1/14.
 */

(function () {
    "use strict";

    var Yotta = require('./yotta.js').Yotta;
    var db;

    var p = {
        context: ''
    };
    module.exports = p;

    p.test = function () {
        console.log(Array.prototype.slice.call(arguments));
    };

    p.open = function () {
        var args = Array.prototype.slice.call(arguments);
        var dbName = args[0];
        if (dbName === p.context) {
            return;
        }
        if (!dbName) {
            db.close();
            p.context = dbName;
            return;
        }
        if (db) {
            p.close();
        }
        p.context = dbName;
        db = new Yotta(p.context);
        db.open();
    };

    p.close = function () {
        if (db) {
            db.close();
            db = undefined;
        }
        if (p.context) {
            p.context = undefined;
        }
    };

    p.put = function () {
        var args = Array.prototype.slice.call(arguments);
        if (db) {
            db.put(args[0], args[1]);
        }
    };

    p.get = function () {
        var args = Array.prototype.slice.call(arguments);
        if (db) {
            console.log(db.get(args[0]));
        }
    };

    p.remove = function () {
        var args = Array.prototype.slice.call(arguments);
        if (db) {
            db.remove(args[0]);
        }
    };

    p.vacuum = function () {
        if (db) {
            db.vacuum();
        }
    };
})();<|endoftext|>


<commit_before>'use strict';

var LocalDispatch = require('./LocalDispatch');

function Node (proxy, globalDispatch, localDispatch) {
    this._localDispatch = localDispatch != null ? localDispatch : new LocalDispatch(this, proxy);
    this._globalDispatch = globalDispatch;
    this._children = [];
}

Node.prototype.addChild = function addChild (index) {
    var child = new this.constructor(this._localDispatch.getRenderProxy(), this._globalDispatch);
    if (index == null) this._children.push(child);
    else this._children.splice(index, 0, child);
    return child;
};

Node.prototype.removeChild = function removeChild (node) {
    var index = this._children.indexOf(node);
    if (index !== -1) {
        var result = this._children.splice(index, 1);
        result[0].kill();
    }
    return this;
};

Node.prototype.removeChildAtIndex = function removeChildAtIndex (index) {
    var result = this._layoutNodes.splice(index, 1);
    if (result.length) result[0].kill();
    return this;
};

Node.prototype.removeAllChildren = function removeAllChildren () {
    for (var i = 0, len = this._children.length ; i < len ; i++) {
        this._children.pop().kill();
    }
    return this;
};

Node.prototype.kill = function kill () {
    this._localDispatch.kill();
    this.removeAllChildren();
    return this;
};

Node.prototype.getDispatch = function getDispatch () {
    return this._localDispatch;
};

Node.prototype.getChildren = function getChildren () {
    return this._children;
};

Node.prototype.update = function update (parent) {
    this._localDispatch.update(parent);
    for (var i = 0, len = this._children.length ; i < len ; i++)
        this._children[i].update(this);
    return this;
};

module.exports = Node;
<commit_msg>fix: Node.prototype.removeChildAtIndex<commit_after>'use strict';

var LocalDispatch = require('./LocalDispatch');

function Node (proxy, globalDispatch, localDispatch) {
    this._localDispatch = localDispatch != null ? localDispatch : new LocalDispatch(this, proxy);
    this._globalDispatch = globalDispatch;
    this._children = [];
}

Node.prototype.addChild = function addChild (index) {
    var child = new this.constructor(this._localDispatch.getRenderProxy(), this._globalDispatch);
    if (index == null) this._children.push(child);
    else this._children.splice(index, 0, child);
    return child;
};

Node.prototype.removeChild = function removeChild (node) {
    var index = this._children.indexOf(node);
    if (index !== -1) {
        var result = this._children.splice(index, 1);
        result[0].kill();
    }
    return this;
};

Node.prototype.removeChildAtIndex = function removeChildAtIndex (index) {
    var result = this._children.splice(index, 1);
    if (result.length) result[0].kill();
    return this;
};

Node.prototype.removeAllChildren = function removeAllChildren () {
    for (var i = 0, len = this._children.length ; i < len ; i++) {
        this._children.pop().kill();
    }
    return this;
};

Node.prototype.kill = function kill () {
    this._localDispatch.kill();
    this.removeAllChildren();
    return this;
};

Node.prototype.getDispatch = function getDispatch () {
    return this._localDispatch;
};

Node.prototype.getChildren = function getChildren () {
    return this._children;
};

Node.prototype.update = function update (parent) {
    this._localDispatch.update(parent);
    for (var i = 0, len = this._children.length ; i < len ; i++)
        this._children[i].update(this);
    return this;
};

module.exports = Node;
<|endoftext|>


<commit_before>var Modules = (function(E) {
  E.ModulesTest = function() {
    return true;
  };
  E.Escape = function(doc) {
    return doc;
  };
  return E;
})(DocTypBeta || {});
<commit_msg>Update Modules.js<commit_after>var Modules = (function(exports) {
  exports.Escape = function(doc) {
    return doc;
  };
  return exports;
})({});
<|endoftext|>


<commit_before>define([
    'controllers/module'
], function(controllers) {
    'use strict';

    controllers.controller('projectDetailController', ['$scope', '$state', 'projectsFactory', function($scope, $state, projectsFactory) {
         $scope.projects = [];
         $scope.project = {};
         $scope.project.slides = [{}];

         projectsFactory.getProjects()
            .success(function(response) {
                $scope.projects = response;

                var project = $scope.projects[$scope.projects.length - parseInt($state.params.projectIndex) - 1];

                if(project) {
                    $scope.project = project;
                } else {
                    $state.go('404');
                }
            });
    }]);
});
<commit_msg>Fixed indentation and missing parseInt radix errors.<commit_after>define([
    'controllers/module'
], function(controllers) {
    'use strict';

    controllers.controller('projectDetailController', ['$scope', '$state', 'projectsFactory', function($scope, $state, projectsFactory) {
        $scope.projects = [];
        $scope.project = {};
        $scope.project.slides = [{}];

        projectsFactory.getProjects()
            .success(function(response) {
                $scope.projects = response;

                var project = $scope.projects[$scope.projects.length - parseInt($state.params.projectIndex, 10) - 1];

                if(project) {
                    $scope.project = project;
                } else {
                    $state.go('404');
                }
            });
    }]);
});
<|endoftext|>


<commit_before>"use strict";
/**
 * todo: chart height as option
 *
 */
var $ = require("jquery"), utils = require("./utils.js"), yUtils = require("yasgui-utils");

var root = module.exports = function(yasr) {
  var options = $.extend(true, {}, root.defaults);
  var id = yasr.container.closest("[id]").attr("id");

  var chartWrapper = null;
  var editor = null;

  var initEditor = function(callback) {
    var google = require("google");
    editor = new google.visualization.ChartEditor();
    google.visualization.events.addListener(editor, "ok", function() {
      var tmp;
      chartWrapper = editor.getChartWrapper();
      tmp = chartWrapper.getDataTable();
      chartWrapper.setDataTable(null);
      //ugly: need to parse json string to json obj again, as google chart does not provide access to object directly
      options.chartConfig = JSON.parse(chartWrapper.toJSON());
      //remove container ID though, for portability
      if (options.chartConfig.containerId) delete options.chartConfig["containerId"];
      yasr.store();
      chartWrapper.setDataTable(tmp);
      var wrapperId = id + "_gchartWrapper";
      var $wrapper = $("#" + wrapperId);
      chartWrapper.setOption("width", $wrapper.width());
      chartWrapper.setOption("height", $wrapper.height());
      chartWrapper.draw();
      yasr.updateHeader();
    });
    if (callback) callback();
  };

  return {
    name: "Google Chart",
    hideFromSelection: false,
    priority: 7,
    options: options,
    getPersistentSettings: function() {
      return {
        chartConfig: options.chartConfig,
        motionChartState: options.motionChartState
      };
    },
    setPersistentSettings: function(persSettings) {
      if (persSettings["chartConfig"]) options.chartConfig = persSettings["chartConfig"];
      if (persSettings["motionChartState"]) options.motionChartState = persSettings["motionChartState"];
    },
    canHandleResults: function(yasr) {
      var results, variables;
      return (results = yasr.results) != null && (variables = results.getVariables()) && variables.length > 0;
    },
    getDownloadInfo: function() {
      if (!yasr.results) return null;
      var svgEl = yasr.resultsContainer.find("svg");
      if (svgEl.length > 0) {
        return {
          getContent: function() {
            if (svgEl[0].outerHTML) {
              return svgEl[0].outerHTML;
            } else {
              //outerHTML not supported. use workaround
              return $("
").append(svgEl.clone()).html();
            }
          },
          filename: "queryResults.svg",
          contentType: "image/svg+xml",
          buttonTitle: "Download SVG Image"
        };
      }
      //ok, not a svg. is it a table?
      var $table = yasr.resultsContainer.find(".google-visualization-table-table");
      if ($table.length > 0) {
        return {
          getContent: function() {
            return $table.tableToCsv();
          },
          filename: "queryResults.csv",
          contentType: "text/csv",
          buttonTitle: "Download as CSV"
        };
      }
    },
    getEmbedHtml: function() {
      if (!yasr.results) return null;

      var svgEl = yasr.resultsContainer
        .find("svg")
        .clone() //create clone, as we'd like to remove height/width attributes
        .removeAttr("height")
        .removeAttr("width")
        .css("height", "")
        .css("width", "");
      if (svgEl.length == 0) return null;

      var htmlString = svgEl[0].outerHTML;
      if (!htmlString) {
        //outerHTML not supported. use workaround
        htmlString = $("
").append(svgEl.clone()).html();
      }
      //wrap in div, so users can more easily tune width/height
      //don't use jquery, so we can easily influence indentation
      return '
\n' + htmlString + "\n
";
    },
    draw: function(_customOpts) {
      var customOpts = $.extend(true, {}, options, _customOpts);
      var doDraw = function() {
        //clear previous results (if any)
        yasr.resultsContainer.empty();
        var wrapperId = id + "_gchartWrapper";

        yasr.resultsContainer
          .append(
            $("<button>", {
              class: "openGchartBtn yasr_btn"
            })
              .text("Chart Config")
              .click(function() {
                editor.openDialog(chartWrapper);
              })
          )
          .append(
            $("
", {
              id: wrapperId,
              class: "gchartWrapper"
            })
          );
        var dataTable = new google.visualization.DataTable();
        //clone, because we'll be manipulating the literals types
        var jsonResults = $.extend(true, {}, yasr.results.getAsJson());
        jsonResults.head.vars.forEach(function(variable) {
          var type = "string";
          try {
            type = utils.getGoogleTypeForBindings(jsonResults.results.bindings, variable);
          } catch (e) {
            if (e instanceof require("./exceptions.js").GoogleTypeException) {
              yasr.warn(e.toHtml());
            } else {
              throw e;
            }
          }
          dataTable.addColumn(type, variable);
        });
        var usedPrefixes = null;
        if (yasr.options.getUsedPrefixes) {
          usedPrefixes = typeof yasr.options.getUsedPrefixes == "function"
            ? yasr.options.getUsedPrefixes(yasr)
            : yasr.options.getUsedPrefixes;
        }
        jsonResults.results.bindings.forEach(function(binding) {
          var row = [];
          jsonResults.head.vars.forEach(function(variable, columnId) {
            row.push(utils.castGoogleType(binding[variable], usedPrefixes, dataTable.getColumnType(columnId)));
          });
          dataTable.addRow(row);
        });
        console.log(customOpts)
        if (customOpts.chartConfig && customOpts.chartConfig.chartType) {
          customOpts.chartConfig.containerId = wrapperId;
          chartWrapper = new google.visualization.ChartWrapper(customOpts.chartConfig);
          if (chartWrapper.getChartType() === "MotionChart" && customOpts.motionChartState) {
            chartWrapper.setOption("state", customOpts.motionChartState);
            google.visualization.events.addListener(chartWrapper, "ready", function() {
              var motionChart;
              motionChart = chartWrapper.getChart();
              google.visualization.events.addListener(motionChart, "statechange", function() {
                customOpts.motionChartState = motionChart.getState();
                yasr.store();
              });
            });
          }
          chartWrapper.setDataTable(dataTable);
        } else {
          chartWrapper = new google.visualization.ChartWrapper({
            chartType: "Table",
            dataTable: dataTable,
            containerId: wrapperId
          });
        }
        var $wrapper = $("#" + wrapperId);
        chartWrapper.setOption("width", $wrapper.width());
        chartWrapper.setOption("height", $wrapper.height());
        chartWrapper.draw();
        google.visualization.events.addListener(chartWrapper, "ready", yasr.updateHeader);
      };

      if (!require("google") || !require("google").visualization || !editor) {
        require("./gChartLoader.js")
          .on("done", function() {
            initEditor();
            doDraw();
          })
          .on("error", function() {
            //TODO: disable or something?
          })
          .googleLoad();
      } else {
        //everything (editor as well) is already initialized
        doDraw();
      }
    }
  };
};
root.defaults = {
  height: "100%",
  width: "100%",
  persistencyId: "gchart",
  chartConfig: null,
  motionChartState: null
};

function deepEq$(x, y, type) {
  var toString = ({}).toString,
    hasOwnProperty = ({}).hasOwnProperty,
    has = function(obj, key) {
      return hasOwnProperty.call(obj, key);
    };
  var first = true;
  return eq(x, y, []);

  function eq(a, b, stack) {
    var className, length, size, result, alength, blength, r, key, ref, sizeB;
    if (a == null || b == null) {
      return a === b;
    }
    if (a.__placeholder__ || b.__placeholder__) {
      return true;
    }
    if (a === b) {
      return a !== 0 || 1 / a == 1 / b;
    }
    className = toString.call(a);
    if (toString.call(b) != className) {
      return false;
    }
    switch (className) {
      case "[object String]":
        return a == String(b);
      case "[object Number]":
        return a != +a ? b != +b : a == 0 ? 1 / a == 1 / b : a == +b;
      case "[object Date]":
      case "[object Boolean]":
        return +a == +b;
      case "[object RegExp]":
        return a.source == b.source &&
          a.global == b.global &&
          a.multiline == b.multiline &&
          a.ignoreCase == b.ignoreCase;
    }
    if (typeof a != "object" || typeof b != "object") {
      return false;
    }
    length = stack.length;
    while (length--) {
      if (stack[length] == a) {
        return true;
      }
    }
    stack.push(a);
    size = 0;
    result = true;
    if (className == "[object Array]") {
      alength = a.length;
      blength = b.length;
      if (first) {
        switch (type) {
          case "===":
            result = alength === blength;
            break;
          case "<==":
            result = alength <= blength;
            break;
          case "<<=":
            result = alength < blength;
            break;
        }
        size = alength;
        first = false;
      } else {
        result = alength === blength;
        size = alength;
      }
      if (result) {
        while (size--) {
          if (!(result = size in a == size in b && eq(a[size], b[size], stack))) {
            break;
          }
        }
      }
    } else {
      if ("constructor" in a != "constructor" in b || a.constructor != b.constructor) {
        return false;
      }
      for (key in a) {
        if (has(a, key)) {
          size++;
          if (!(result = has(b, key) && eq(a[key], b[key], stack))) {
            break;
          }
        }
      }
      if (result) {
        sizeB = 0;
        for (key in b) {
          if (has(b, key)) {
            ++sizeB;
          }
        }
        if (first) {
          if (type === "<<=") {
            result = size < sizeB;
          } else if (type === "<==") {
            result = size <= sizeB;
          } else {
            result = size === sizeB;
          }
        } else {
          first = false;
          result = size === sizeB;
        }
      }
    }
    stack.pop();
    return result;
  }
}
<commit_msg>removed log statement<commit_after>"use strict";
/**
 * todo: chart height as option
 *
 */
var $ = require("jquery"), utils = require("./utils.js"), yUtils = require("yasgui-utils");

var root = module.exports = function(yasr) {
  var options = $.extend(true, {}, root.defaults);
  var id = yasr.container.closest("[id]").attr("id");

  var chartWrapper = null;
  var editor = null;

  var initEditor = function(callback) {
    var google = require("google");
    editor = new google.visualization.ChartEditor();
    google.visualization.events.addListener(editor, "ok", function() {
      var tmp;
      chartWrapper = editor.getChartWrapper();
      tmp = chartWrapper.getDataTable();
      chartWrapper.setDataTable(null);
      //ugly: need to parse json string to json obj again, as google chart does not provide access to object directly
      options.chartConfig = JSON.parse(chartWrapper.toJSON());
      //remove container ID though, for portability
      if (options.chartConfig.containerId) delete options.chartConfig["containerId"];
      yasr.store();
      chartWrapper.setDataTable(tmp);
      var wrapperId = id + "_gchartWrapper";
      var $wrapper = $("#" + wrapperId);
      chartWrapper.setOption("width", $wrapper.width());
      chartWrapper.setOption("height", $wrapper.height());
      chartWrapper.draw();
      yasr.updateHeader();
    });
    if (callback) callback();
  };

  return {
    name: "Google Chart",
    hideFromSelection: false,
    priority: 7,
    options: options,
    getPersistentSettings: function() {
      return {
        chartConfig: options.chartConfig,
        motionChartState: options.motionChartState
      };
    },
    setPersistentSettings: function(persSettings) {
      if (persSettings["chartConfig"]) options.chartConfig = persSettings["chartConfig"];
      if (persSettings["motionChartState"]) options.motionChartState = persSettings["motionChartState"];
    },
    canHandleResults: function(yasr) {
      var results, variables;
      return (results = yasr.results) != null && (variables = results.getVariables()) && variables.length > 0;
    },
    getDownloadInfo: function() {
      if (!yasr.results) return null;
      var svgEl = yasr.resultsContainer.find("svg");
      if (svgEl.length > 0) {
        return {
          getContent: function() {
            if (svgEl[0].outerHTML) {
              return svgEl[0].outerHTML;
            } else {
              //outerHTML not supported. use workaround
              return $("
").append(svgEl.clone()).html();
            }
          },
          filename: "queryResults.svg",
          contentType: "image/svg+xml",
          buttonTitle: "Download SVG Image"
        };
      }
      //ok, not a svg. is it a table?
      var $table = yasr.resultsContainer.find(".google-visualization-table-table");
      if ($table.length > 0) {
        return {
          getContent: function() {
            return $table.tableToCsv();
          },
          filename: "queryResults.csv",
          contentType: "text/csv",
          buttonTitle: "Download as CSV"
        };
      }
    },
    getEmbedHtml: function() {
      if (!yasr.results) return null;

      var svgEl = yasr.resultsContainer
        .find("svg")
        .clone() //create clone, as we'd like to remove height/width attributes
        .removeAttr("height")
        .removeAttr("width")
        .css("height", "")
        .css("width", "");
      if (svgEl.length == 0) return null;

      var htmlString = svgEl[0].outerHTML;
      if (!htmlString) {
        //outerHTML not supported. use workaround
        htmlString = $("
").append(svgEl.clone()).html();
      }
      //wrap in div, so users can more easily tune width/height
      //don't use jquery, so we can easily influence indentation
      return '
\n' + htmlString + "\n
";
    },
    draw: function(_customOpts) {
      var customOpts = $.extend(true, {}, options, _customOpts);
      var doDraw = function() {
        //clear previous results (if any)
        yasr.resultsContainer.empty();
        var wrapperId = id + "_gchartWrapper";

        yasr.resultsContainer
          .append(
            $("<button>", {
              class: "openGchartBtn yasr_btn"
            })
              .text("Chart Config")
              .click(function() {
                editor.openDialog(chartWrapper);
              })
          )
          .append(
            $("
", {
              id: wrapperId,
              class: "gchartWrapper"
            })
          );
        var dataTable = new google.visualization.DataTable();
        //clone, because we'll be manipulating the literals types
        var jsonResults = $.extend(true, {}, yasr.results.getAsJson());
        jsonResults.head.vars.forEach(function(variable) {
          var type = "string";
          try {
            type = utils.getGoogleTypeForBindings(jsonResults.results.bindings, variable);
          } catch (e) {
            if (e instanceof require("./exceptions.js").GoogleTypeException) {
              yasr.warn(e.toHtml());
            } else {
              throw e;
            }
          }
          dataTable.addColumn(type, variable);
        });
        var usedPrefixes = null;
        if (yasr.options.getUsedPrefixes) {
          usedPrefixes = typeof yasr.options.getUsedPrefixes == "function"
            ? yasr.options.getUsedPrefixes(yasr)
            : yasr.options.getUsedPrefixes;
        }
        jsonResults.results.bindings.forEach(function(binding) {
          var row = [];
          jsonResults.head.vars.forEach(function(variable, columnId) {
            row.push(utils.castGoogleType(binding[variable], usedPrefixes, dataTable.getColumnType(columnId)));
          });
          dataTable.addRow(row);
        });
        if (customOpts.chartConfig && customOpts.chartConfig.chartType) {
          customOpts.chartConfig.containerId = wrapperId;
          chartWrapper = new google.visualization.ChartWrapper(customOpts.chartConfig);
          if (chartWrapper.getChartType() === "MotionChart" && customOpts.motionChartState) {
            chartWrapper.setOption("state", customOpts.motionChartState);
            google.visualization.events.addListener(chartWrapper, "ready", function() {
              var motionChart;
              motionChart = chartWrapper.getChart();
              google.visualization.events.addListener(motionChart, "statechange", function() {
                customOpts.motionChartState = motionChart.getState();
                yasr.store();
              });
            });
          }
          chartWrapper.setDataTable(dataTable);
        } else {
          chartWrapper = new google.visualization.ChartWrapper({
            chartType: "Table",
            dataTable: dataTable,
            containerId: wrapperId
          });
        }
        var $wrapper = $("#" + wrapperId);
        chartWrapper.setOption("width", $wrapper.width());
        chartWrapper.setOption("height", $wrapper.height());
        chartWrapper.draw();
        google.visualization.events.addListener(chartWrapper, "ready", yasr.updateHeader);
      };

      if (!require("google") || !require("google").visualization || !editor) {
        require("./gChartLoader.js")
          .on("done", function() {
            initEditor();
            doDraw();
          })
          .on("error", function() {
            //TODO: disable or something?
          })
          .googleLoad();
      } else {
        //everything (editor as well) is already initialized
        doDraw();
      }
    }
  };
};
root.defaults = {
  height: "100%",
  width: "100%",
  persistencyId: "gchart",
  chartConfig: null,
  motionChartState: null
};

function deepEq$(x, y, type) {
  var toString = ({}).toString,
    hasOwnProperty = ({}).hasOwnProperty,
    has = function(obj, key) {
      return hasOwnProperty.call(obj, key);
    };
  var first = true;
  return eq(x, y, []);

  function eq(a, b, stack) {
    var className, length, size, result, alength, blength, r, key, ref, sizeB;
    if (a == null || b == null) {
      return a === b;
    }
    if (a.__placeholder__ || b.__placeholder__) {
      return true;
    }
    if (a === b) {
      return a !== 0 || 1 / a == 1 / b;
    }
    className = toString.call(a);
    if (toString.call(b) != className) {
      return false;
    }
    switch (className) {
      case "[object String]":
        return a == String(b);
      case "[object Number]":
        return a != +a ? b != +b : a == 0 ? 1 / a == 1 / b : a == +b;
      case "[object Date]":
      case "[object Boolean]":
        return +a == +b;
      case "[object RegExp]":
        return a.source == b.source &&
          a.global == b.global &&
          a.multiline == b.multiline &&
          a.ignoreCase == b.ignoreCase;
    }
    if (typeof a != "object" || typeof b != "object") {
      return false;
    }
    length = stack.length;
    while (length--) {
      if (stack[length] == a) {
        return true;
      }
    }
    stack.push(a);
    size = 0;
    result = true;
    if (className == "[object Array]") {
      alength = a.length;
      blength = b.length;
      if (first) {
        switch (type) {
          case "===":
            result = alength === blength;
            break;
          case "<==":
            result = alength <= blength;
            break;
          case "<<=":
            result = alength < blength;
            break;
        }
        size = alength;
        first = false;
      } else {
        result = alength === blength;
        size = alength;
      }
      if (result) {
        while (size--) {
          if (!(result = size in a == size in b && eq(a[size], b[size], stack))) {
            break;
          }
        }
      }
    } else {
      if ("constructor" in a != "constructor" in b || a.constructor != b.constructor) {
        return false;
      }
      for (key in a) {
        if (has(a, key)) {
          size++;
          if (!(result = has(b, key) && eq(a[key], b[key], stack))) {
            break;
          }
        }
      }
      if (result) {
        sizeB = 0;
        for (key in b) {
          if (has(b, key)) {
            ++sizeB;
          }
        }
        if (first) {
          if (type === "<<=") {
            result = size < sizeB;
          } else if (type === "<==") {
            result = size <= sizeB;
          } else {
            result = size === sizeB;
          }
        } else {
          first = false;
          result = size === sizeB;
        }
      }
    }
    stack.pop();
    return result;
  }
}
<|endoftext|>


<commit_before>/*
 * Internal Helpers
 * */
exports.getRequestingUser = function(req, callback) {
  var user = req.user;
  return callback(null, user);
};

/*
 * Status helpers
 * */
// xxx
exports.sendStatusMessage = function(res, status, object) {
  var json = JSON.stringify(object);
  return res.status(status).set('Content-Type', 'application/json').end(json);
};
exports.sendStatusError = function(res, status, errorDescription) {
  errorDescription = errorDescription || "Unknown";
  var error = {
    error: errorDescription
  };
  return exports.sendStatusMessage(res, status, error);
};
// 200
exports.sendOk = function(res, data) {
  return exports.sendStatusMessage(res, 200, data);
};
// 400
exports.sendBadRequest = function(res, errorDescription) {
  errorDescription = errorDescription || "Bad Request";
  return exports.sendStatusError(res, 400, errorDescription);
};
// 403
exports.sendForbidden = function(res, errorDescription) {
  errorDescription = errorDescription || "Forbidden";
  return exports.sendStatusError(res, 403, errorDescription);
};
// 500
exports.sendInternalServerError = function(res, errorDescription) {
  errorDescription = errorDescription || "Internal Server Error";
  return exports.sendStatusError(res, 500, errorDescription);
};

/*
 * Flow helpers
 * */

// AUTHENTICATION
exports._checkUserAuthentication = function(req, res, callback, authCallback) {
  return exports.getRequestingUser(req, function(err, user) {
    if ( !!err ) {
      return exports.sendInternalServerError(res);
    }

    var authenticated = authCallback(null, user);
    if ( !authenticated ) {
      return exports.sendForbidden(res);
    }

    return callback(null, {
      authenticated: authenticated,
      user: user
    });
  });
};
exports.authenticate = function(req, res, callback) {
  return exports._checkUserAuthentication(req, res, callback, function(err, user) {
    return !!user;
  });
};
exports.authenticatePrivileged = function(req, res, callback) {
  return exports._checkUserAuthentication(req, res, callback, function(err, user) {
    return !!user && user.isPrivileged();
  });
};
exports.authenticateAdmin = function(req, res, callback) {
  return exports._checkUserAuthentication(req, res, callback, function(err, user) {
    return !!user && user.isAdmin();
  });
};
// SENDING models
exports.getPublicModels = function(modelList, callback) {
  var retVal = modelList.map(function(model) {
    return model.getPublicModel();
  });
  return callback(null, retVal);
};
exports.sendPublicModels = function(res, publicModels, wrapper) {
  var response = {};
  response[wrapper] = publicModels;
  return exports.sendOk(res, response);
};
exports.sendModels = function(res, modelList, wrapper) {
  exports.getPublicModels(modelList, function(err, models) {
    if ( !!err ) {
      return exports.sendInternalServerError(res);
    }

    exports.sendPublicModels(res, models, wrapper);
  });
};
<commit_msg>getPublicModels can now handle single objects.<commit_after>/*
 * Internal Helpers
 * */
exports.getRequestingUser = function(req, callback) {
  var user = req.user;
  return callback(null, user);
};

/*
 * Status helpers
 * */
// xxx
exports.sendStatusMessage = function(res, status, object) {
  var json = JSON.stringify(object);
  return res.status(status).set('Content-Type', 'application/json').end(json);
};
exports.sendStatusError = function(res, status, errorDescription) {
  errorDescription = errorDescription || "Unknown";
  var error = {
    error: errorDescription
  };
  return exports.sendStatusMessage(res, status, error);
};
// 200
exports.sendOk = function(res, data) {
  return exports.sendStatusMessage(res, 200, data);
};
// 400
exports.sendBadRequest = function(res, errorDescription) {
  errorDescription = errorDescription || "Bad Request";
  return exports.sendStatusError(res, 400, errorDescription);
};
// 403
exports.sendForbidden = function(res, errorDescription) {
  errorDescription = errorDescription || "Forbidden";
  return exports.sendStatusError(res, 403, errorDescription);
};
// 500
exports.sendInternalServerError = function(res, errorDescription) {
  errorDescription = errorDescription || "Internal Server Error";
  return exports.sendStatusError(res, 500, errorDescription);
};

/*
 * Flow helpers
 * */

// AUTHENTICATION
exports._checkUserAuthentication = function(req, res, callback, authCallback) {
  return exports.getRequestingUser(req, function(err, user) {
    if ( !!err ) {
      return exports.sendInternalServerError(res);
    }

    var authenticated = authCallback(null, user);
    if ( !authenticated ) {
      return exports.sendForbidden(res);
    }

    return callback(null, {
      authenticated: authenticated,
      user: user
    });
  });
};
exports.authenticate = function(req, res, callback) {
  return exports._checkUserAuthentication(req, res, callback, function(err, user) {
    return !!user;
  });
};
exports.authenticatePrivileged = function(req, res, callback) {
  return exports._checkUserAuthentication(req, res, callback, function(err, user) {
    return !!user && user.isPrivileged();
  });
};
exports.authenticateAdmin = function(req, res, callback) {
  return exports._checkUserAuthentication(req, res, callback, function(err, user) {
    return !!user && user.isAdmin();
  });
};
// SENDING models
exports.getPublicModels = function(modelList, callback) {
  if ( !modelList.length ) {
    modelList = [ modelList ];
  }

  var retVal = modelList.map(function(model) {
    return model.getPublicModel();
  });

  if ( retVal.length === 1 ) {
    retVal = retVal[0];
  }
  return callback(null, retVal);
};
exports.sendPublicModels = function(res, publicModels, wrapper) {
  var response = {};
  response[wrapper] = publicModels;
  return exports.sendOk(res, response);
};
exports.sendModels = function(res, modelList, wrapper) {
  exports.getPublicModels(modelList, function(err, models) {
    if ( !!err ) {
      return exports.sendInternalServerError(res);
    }

    exports.sendPublicModels(res, models, wrapper);
  });
};
<|endoftext|>