<commit_before>type("ExportIcalInterface", [], {
    _getExportURLs: function(progressTarget) {
        var self = this;
        indicoRequest(self.getURLsMethod, self.getURLsParams,
                function(result, error) {
                    $(progressTarget).html('');
                    if (error){
                        IndicoUI.Dialogs.Util.error(error);
                    }
                    else{
                        self.requestURLs = result;
                        self.setURLsFunction(self.requestURLs);
                        switch(self.apiMode){

                            case 0:
                                if(self.apiActive){
                                    self._postAcceptAgreements('#agreementApiKey'+self.id);
                                }
                                break;
                            case 1:
                                if(self.apiActive){
                                    $('#publicLinkWrapper'+self.id).append($("#publicLink"+self.id)).show();
                                    self._postAcceptAgreements('#agreementApiKey'+self.id);

                                }
                                break;

                            case 2:
                                if(self.apiActive){
                                    $('#agreementApiKey'+self.id).hide();
                                    if(self.persistentUserEnabled && self.persistentAllowed){
                                        self._postAcceptAgreements('#agreementPersistentSignatures'+self.id);
                                    }
                                }
                                break;

                            case 3:
                                if(self.apiActive){
                                    $('#publicLinkWrapper'+self.id).append($("#publicLink"+self.id)).show();
                                    if(self.persistentUserEnabled && self.persistentAllowed){
                                        self._postAcceptAgreements('#agreementPersistentSignatures'+self.id);
                                    }
                                    else {
                                        $('#extraInformation'+self.id).insertAfter('#publicLinkWrapper'+self.id);
                                    }
                                    $('#agreementApiKey'+self.id).hide();
                                }

                                break;

                            case 4:
                                if(self.apiActive){
                                    $('#agreementApiKey'+self.id).hide();
                                    if(self.persistentUserEnabled && self.persistentAllowed){
                                        $('#publicLinkWrapper'+self.id).append($("#publicLink"+self.id)).show();
                                        self._postAcceptAgreements('#agreementPersistentSignatures'+self.id);
                                    }
                                }
                                break;
                    };
                    }
                });
    },

    _showPrivatePanel: function(question){
        var self = this;
        if(self.persistentAllowed){
            if(self.persistentUserEnabled){
                self._showAuthLink();
            }else{
                question = question || $T("Would you like to export private information to your calendar?");
                var privateInfo = $(""+question+"");

                $('#authLinkWrapper'+self.id).append(privateInfo).show();

                privateInfo.click(function(){
                    privateInfo.hide();
                    $('#exportIcalHeader'+self.id).show();
                    $('#authLinkWrapper'+self.id).append($("#agreementPersistentSignatures"+self.id)).show();
                });
            }
            $('#iCalSeparator'+self.id).show();
        }
    },

    _postAcceptAgreements: function(targetAgreement){
        $('#authLinkWrapper'+this.id).append($("#authLink"+this.id)).show();
        $('#extraInformation'+this.id).insertAfter('#authLinkWrapper'+this.id);
        $(targetAgreement).hide();
    },

    _showAuthLink: function(){
        $('#exportIcalHeader'+this.id).show();
        $('#authLinkWrapper'+this.id).append($("#authLink"+this.id)).show();
        $('#extraInformation'+this.id).insertAfter('#authLinkWrapper'+this.id);
    },

    _showAgreement: function(agreementTarget){
        $('#extraInformation').insertAfter('#publicLinkWrapper'+this.id);
        $('#authLinkWrapper'+this.id).append($(agreementTarget)).show();
    },

    getAgreementMethod: function(){
        return this.agreementMethod;
    },

    getRequestURLs: function(){
        return this.requestURLs;
    },

    createKey: function(enablePersistent, progressTarget){
        var self = this;
        $(progressTarget).html($(progressIndicator(true, false).dom));
        indicoRequest('user.createKeyAndEnablePersistent', {enablePersistent: enablePersistent},
                function(result, error) {
                    if (error){
                        $(progressTarget).html('');
                        IndicoUI.Dialogs.Util.error(error);
                    }
                    else{
                        self.apiActive = true;
                        self.persistentUserEnabled = enablePersistent;
                        self._getExportURLs(progressTarget);
                    }
                });
    },

    enablePersistentSignatures: function() {
        var self = this;
        if(self.apiActive){
            indicoRequest('user.togglePersistentSignatures', {userId: self.userId},
                    function(result, error) {
                        if (error){
                            $('#progressPersistentSignatures').html('');
                            IndicoUI.Dialogs.Util.error(error);
                        }
                        else{
                            self.persistentUserEnabled = true;
                            self._getExportURLs('progressPersistentSignatures');
                        }
                    });
        }

        else{
            self.createKey(true, '#progressPersistentSignatures');
        }
    },

    showPopup: function(){
        $('#icalExportPopup'+this.id).show();
    },

    showContent: function(){
        var self = this;
        self.setURLsFunction(self.requestURLs);
        switch(self.apiMode){
        case 0://Public:nothing; Private:API_KEY
            $('#publicLinkWrapper'+self.id).append($("#publicLink"+self.id)).show();
            if(self.userLogged){
                if (self.apiActive){
                    self._showAuthLink();
                } else{
                    $('#exportIcalHeader'+self.id).show();
                    self._showAgreement('#agreementApiKey'+self.id);
                }
                $('#iCalSeparator'+self.id).show();
            }
            break;
        case 1://Public:API_KEY; Private:API_KEY
            if(self.userLogged){
                if (self.apiActive){
                    $('#publicLinkWrapper'+self.id).append($("#publicLink"+self.id)).show();
                    self._showAuthLink();
                } else{
                    $('#exportIcalHeader'+self.id).show();
                    $('#authLinkWrapper'+self.id).append($("#agreementApiKey"+self.id)).show();
                }
                $('#iCalSeparator'+self.id).show();
            }
            break;
        case 2://Public:nothing; Private:SIGNED
            $('#publicLinkWrapper'+self.id).append($("#publicLink"+self.id)).show();
            if(self.userLogged){
                self._showPrivatePanel();
            }
            else {
                $('#extraInformation'+self.id).insertAfter('#publicLinkWrapper'+self.id);
            }
            $('#iCalSeparator'+self.id).show();
            break;
        case 3://Public:API_KEY; Private:SIGNED
            if(self.userLogged){
                if(self.apiActive){
                    $('#publicLinkWrapper'+self.id).append($("#publicLink"+self.id)).show();
                } else{
                    $('#publicLinkWrapper'+self.id).append($("#agreementApiKey"+self.id)).show();
                }
                self._showPrivatePanel();
                $('#iCalSeparator'+self.id).show();
            }
            break;
        case 4://ALL_SIGNED
            if(self.userLogged){
                if(self.persistentAllowed){
                    if(self.persistentUserEnabled){
                        $('#publicLinkWrapper'+self.id).append($("#publicLink"+self.id)).show();
                    }
                    self._showPrivatePanel($T("Would you like to create a persistent URL for use with your calendaring application?"));
                }
            }
            break;
        };
    }

}, function(apiMode, persistentUserEnabled, persistentAllowed, apiActive, userLogged, setURLsFunction, getURLsMethod, getURLsParams, requestURLs, id, userId){

    this.apiMode = any(apiMode, 0);
    this.persistentUserEnabled = any(persistentUserEnabled, false);
    this.persistentAllowed = any(persistentAllowed, false);
    this.apiActive = any(apiActive, false);
    this.userLogged = any(userLogged, false);
    this.setURLsFunction = setURLsFunction;
    this.getURLsMethod = any(getURLsMethod, "");
    this.getURLsParams = any(getURLsParams, {});
    this.requestURLs = any(requestURLs, {});
    this.id = any(id,"");
    this.agreementMethod = "";
    this.userId = any(userId, "");

    var self = this;

    self.showContent();

});

var exportPopups= {};

$(document).ready(function() {

    $(".exportIcal").on('menu_select', function() {
        var $button = $(this);

        if ($button.hasClass('open')) {
            return;
        } else {
            $button.addClass('open');

            $("").qtip({
                style: {
                    width: '350px',
                    classes: 'ui-tooltip-rounded ui-tooltip-shadow ui-tooltip-popup',
                    tip: {
                        corner: true,
                        width: 20,
                        height: 15
                    }
                },
                position: {
                    my: 'top center',
                    at: 'bottom center',
                    target: $button
                },
                content: function(api) {
                    return $('#icalExportPopup' + $button.data("id"));
                },
                show: {
                    ready: true,
                    effect: function() {
                        $(this).fadeIn(300);
                    }
                },
                hide: {
                    event: 'unfocus',
                    fixed: true,
                    target: $button,
                    effect: function() {
                        $(this).fadeOut(300);
                    }
                }
            });
        }

        return true;
    });

    $('body').delegate('.apiURL','click',function(e){
        $(this).select();
    });

    $('body').delegate('.agreementButtonPersistent','click',function(e){
        $('#progressPersistentSignatures'+this.getAttribute('data-id')).html($(progressIndicator(true, false).dom));
        exportPopups[this.getAttribute('data-id')].enablePersistentSignatures();
    });

    $('body').delegate('.agreementButtonKey','click',function(e){
        exportPopups[this.getAttribute('data-id')].createKey(false, '#progressPersistentKey'+this.getAttribute('data-id'));
    });

    $('body').delegate('.agreeCheckBoxKey','click',function(e){
        if(this.checked){
            $('#agreementButtonKey'+this.getAttribute('data-id')).removeAttr("disabled");
        }else{
            $('#agreementButtonKey'+this.getAttribute('data-id')).attr("disabled","disabled");
        }
    });

    $('body').delegate('.agreeCheckBoxPersistent','click',function(e){
        if(this.checked){
            $('#agreementButtonPersistent'+this.getAttribute('data-id')).removeAttr("disabled");
            $('#agreeCheckBoxKey'+this.getAttribute('data-id'))[0].checked = true;
            $('#agreeCheckBoxKey'+this.getAttribute('data-id')).attr("disabled","disabled");
            $('#agreementButtonKey'+this.getAttribute('data-id')).attr("disabled","disabled");
        }else{
            $('#agreementButtonPersistent'+this.getAttribute('data-id')).attr("disabled","disabled");
            $('#agreeCheckBoxKey'+this.getAttribute('data-id')).removeAttr("disabled");
            $('#agreeCheckBoxKey'+this.getAttribute('data-id'))[0].checked = false;
        }
    });
});<commit_msg>[FIX] iCal popup opening only once<commit_after>type("ExportIcalInterface", [], {
    _getExportURLs: function(progressTarget) {
        var self = this;
        indicoRequest(self.getURLsMethod, self.getURLsParams,
                function(result, error) {
                    $(progressTarget).html('');
                    if (error){
                        IndicoUI.Dialogs.Util.error(error);
                    }
                    else{
                        self.requestURLs = result;
                        self.setURLsFunction(self.requestURLs);
                        switch(self.apiMode){

                            case 0:
                                if(self.apiActive){
                                    self._postAcceptAgreements('#agreementApiKey'+self.id);
                                }
                                break;
                            case 1:
                                if(self.apiActive){
                                    $('#publicLinkWrapper'+self.id).append($("#publicLink"+self.id)).show();
                                    self._postAcceptAgreements('#agreementApiKey'+self.id);

                                }
                                break;

                            case 2:
                                if(self.apiActive){
                                    $('#agreementApiKey'+self.id).hide();
                                    if(self.persistentUserEnabled && self.persistentAllowed){
                                        self._postAcceptAgreements('#agreementPersistentSignatures'+self.id);
                                    }
                                }
                                break;

                            case 3:
                                if(self.apiActive){
                                    $('#publicLinkWrapper'+self.id).append($("#publicLink"+self.id)).show();
                                    if(self.persistentUserEnabled && self.persistentAllowed){
                                        self._postAcceptAgreements('#agreementPersistentSignatures'+self.id);
                                    }
                                    else {
                                        $('#extraInformation'+self.id).insertAfter('#publicLinkWrapper'+self.id);
                                    }
                                    $('#agreementApiKey'+self.id).hide();
                                }

                                break;

                            case 4:
                                if(self.apiActive){
                                    $('#agreementApiKey'+self.id).hide();
                                    if(self.persistentUserEnabled && self.persistentAllowed){
                                        $('#publicLinkWrapper'+self.id).append($("#publicLink"+self.id)).show();
                                        self._postAcceptAgreements('#agreementPersistentSignatures'+self.id);
                                    }
                                }
                                break;
                    };
                    }
                });
    },

    _showPrivatePanel: function(question){
        var self = this;
        if(self.persistentAllowed){
            if(self.persistentUserEnabled){
                self._showAuthLink();
            }else{
                question = question || $T("Would you like to export private information to your calendar?");
                var privateInfo = $(""+question+"");

                $('#authLinkWrapper'+self.id).append(privateInfo).show();

                privateInfo.click(function(){
                    privateInfo.hide();
                    $('#exportIcalHeader'+self.id).show();
                    $('#authLinkWrapper'+self.id).append($("#agreementPersistentSignatures"+self.id)).show();
                });
            }
            $('#iCalSeparator'+self.id).show();
        }
    },

    _postAcceptAgreements: function(targetAgreement){
        $('#authLinkWrapper'+this.id).append($("#authLink"+this.id)).show();
        $('#extraInformation'+this.id).insertAfter('#authLinkWrapper'+this.id);
        $(targetAgreement).hide();
    },

    _showAuthLink: function(){
        $('#exportIcalHeader'+this.id).show();
        $('#authLinkWrapper'+this.id).append($("#authLink"+this.id)).show();
        $('#extraInformation'+this.id).insertAfter('#authLinkWrapper'+this.id);
    },

    _showAgreement: function(agreementTarget){
        $('#extraInformation').insertAfter('#publicLinkWrapper'+this.id);
        $('#authLinkWrapper'+this.id).append($(agreementTarget)).show();
    },

    getAgreementMethod: function(){
        return this.agreementMethod;
    },

    getRequestURLs: function(){
        return this.requestURLs;
    },

    createKey: function(enablePersistent, progressTarget){
        var self = this;
        $(progressTarget).html($(progressIndicator(true, false).dom));
        indicoRequest('user.createKeyAndEnablePersistent', {enablePersistent: enablePersistent},
                function(result, error) {
                    if (error){
                        $(progressTarget).html('');
                        IndicoUI.Dialogs.Util.error(error);
                    }
                    else{
                        self.apiActive = true;
                        self.persistentUserEnabled = enablePersistent;
                        self._getExportURLs(progressTarget);
                    }
                });
    },

    enablePersistentSignatures: function() {
        var self = this;
        if(self.apiActive){
            indicoRequest('user.togglePersistentSignatures', {userId: self.userId},
                    function(result, error) {
                        if (error){
                            $('#progressPersistentSignatures').html('');
                            IndicoUI.Dialogs.Util.error(error);
                        }
                        else{
                            self.persistentUserEnabled = true;
                            self._getExportURLs('progressPersistentSignatures');
                        }
                    });
        }

        else{
            self.createKey(true, '#progressPersistentSignatures');
        }
    },

    showPopup: function(){
        $('#icalExportPopup'+this.id).show();
    },

    showContent: function(){
        var self = this;
        self.setURLsFunction(self.requestURLs);
        switch(self.apiMode){
        case 0://Public:nothing; Private:API_KEY
            $('#publicLinkWrapper'+self.id).append($("#publicLink"+self.id)).show();
            if(self.userLogged){
                if (self.apiActive){
                    self._showAuthLink();
                } else{
                    $('#exportIcalHeader'+self.id).show();
                    self._showAgreement('#agreementApiKey'+self.id);
                }
                $('#iCalSeparator'+self.id).show();
            }
            break;
        case 1://Public:API_KEY; Private:API_KEY
            if(self.userLogged){
                if (self.apiActive){
                    $('#publicLinkWrapper'+self.id).append($("#publicLink"+self.id)).show();
                    self._showAuthLink();
                } else{
                    $('#exportIcalHeader'+self.id).show();
                    $('#authLinkWrapper'+self.id).append($("#agreementApiKey"+self.id)).show();
                }
                $('#iCalSeparator'+self.id).show();
            }
            break;
        case 2://Public:nothing; Private:SIGNED
            $('#publicLinkWrapper'+self.id).append($("#publicLink"+self.id)).show();
            if(self.userLogged){
                self._showPrivatePanel();
            }
            else {
                $('#extraInformation'+self.id).insertAfter('#publicLinkWrapper'+self.id);
            }
            $('#iCalSeparator'+self.id).show();
            break;
        case 3://Public:API_KEY; Private:SIGNED
            if(self.userLogged){
                if(self.apiActive){
                    $('#publicLinkWrapper'+self.id).append($("#publicLink"+self.id)).show();
                } else{
                    $('#publicLinkWrapper'+self.id).append($("#agreementApiKey"+self.id)).show();
                }
                self._showPrivatePanel();
                $('#iCalSeparator'+self.id).show();
            }
            break;
        case 4://ALL_SIGNED
            if(self.userLogged){
                if(self.persistentAllowed){
                    if(self.persistentUserEnabled){
                        $('#publicLinkWrapper'+self.id).append($("#publicLink"+self.id)).show();
                    }
                    self._showPrivatePanel($T("Would you like to create a persistent URL for use with your calendaring application?"));
                }
            }
            break;
        };
    }

}, function(apiMode, persistentUserEnabled, persistentAllowed, apiActive, userLogged, setURLsFunction, getURLsMethod, getURLsParams, requestURLs, id, userId){

    this.apiMode = any(apiMode, 0);
    this.persistentUserEnabled = any(persistentUserEnabled, false);
    this.persistentAllowed = any(persistentAllowed, false);
    this.apiActive = any(apiActive, false);
    this.userLogged = any(userLogged, false);
    this.setURLsFunction = setURLsFunction;
    this.getURLsMethod = any(getURLsMethod, "");
    this.getURLsParams = any(getURLsParams, {});
    this.requestURLs = any(requestURLs, {});
    this.id = any(id,"");
    this.agreementMethod = "";
    this.userId = any(userId, "");

    var self = this;

    self.showContent();

});

var exportPopups= {};

$(document).ready(function() {

    $(".exportIcal").on('menu_select', function() {
        var $button = $(this);

        if ($button.hasClass('open')) {
            return;
        } else {
            $button.addClass('open');

            $("").qtip({
                style: {
                    width: '350px',
                    classes: 'ui-tooltip-rounded ui-tooltip-shadow ui-tooltip-popup',
                    tip: {
                        corner: true,
                        width: 20,
                        height: 15
                    }
                },
                position: {
                    my: 'top center',
                    at: 'bottom center',
                    target: $button
                },
                content: function(api) {
                    return $('#icalExportPopup' + $button.data("id"));
                },
                show: {
                    ready: true,
                    effect: function() {
                        $(this).fadeIn(300);
                    }
                },
                hide: {
                    event: 'unfocus',
                    fixed: true,
                    target: $button,
                    effect: function() {
                        $(this).fadeOut(300);
                        $button.removeClass('open');
                    }
                }
            });
        }

        return true;
    });

    $('body').delegate('.apiURL','click',function(e){
        $(this).select();
    });

    $('body').delegate('.agreementButtonPersistent','click',function(e){
        $('#progressPersistentSignatures'+this.getAttribute('data-id')).html($(progressIndicator(true, false).dom));
        exportPopups[this.getAttribute('data-id')].enablePersistentSignatures();
    });

    $('body').delegate('.agreementButtonKey','click',function(e){
        exportPopups[this.getAttribute('data-id')].createKey(false, '#progressPersistentKey'+this.getAttribute('data-id'));
    });

    $('body').delegate('.agreeCheckBoxKey','click',function(e){
        if(this.checked){
            $('#agreementButtonKey'+this.getAttribute('data-id')).removeAttr("disabled");
        }else{
            $('#agreementButtonKey'+this.getAttribute('data-id')).attr("disabled","disabled");
        }
    });

    $('body').delegate('.agreeCheckBoxPersistent','click',function(e){
        if(this.checked){
            $('#agreementButtonPersistent'+this.getAttribute('data-id')).removeAttr("disabled");
            $('#agreeCheckBoxKey'+this.getAttribute('data-id'))[0].checked = true;
            $('#agreeCheckBoxKey'+this.getAttribute('data-id')).attr("disabled","disabled");
            $('#agreementButtonKey'+this.getAttribute('data-id')).attr("disabled","disabled");
        }else{
            $('#agreementButtonPersistent'+this.getAttribute('data-id')).attr("disabled","disabled");
            $('#agreeCheckBoxKey'+this.getAttribute('data-id')).removeAttr("disabled");
            $('#agreeCheckBoxKey'+this.getAttribute('data-id'))[0].checked = false;
        }
    });
});<|endoftext|>


<commit_before>const DefinePlugin = require("webpack").DefinePlugin;
const path = require("path");
const SourceMapDevToolPlugin = require("webpack").SourceMapDevToolPlugin;
const webpack = require("webpack");
const BabiliPlugin = require("babili-webpack-plugin");

const config = require("../../project.config");

module.exports = {
  context: config.srcFullPath,

  entry: {
    main: "./js/main.js"
  },
  output: {
    path: path.join(config.destFullPath, config.js),
    filename: "[name].bundle.js",
    chunkFilename: "[id].bundle.js"
  },

  module: {
    rules: [{
      test: /\.jsx?$/,
      exclude: /node_modules/,
      use: {
        loader: "babel-loader"
      }
    }]
  },

  plugins: [
    new SourceMapDevToolPlugin({
      test: /\.(css|js)($|\?)/,
      filename: "[file].map",
      append: "\n//# sourceMappingURL=[url]",
      module: true,
      columns: true
    }),
    new DefinePlugin({
      // Signal production, so that webpack removes non-production code that
      // is in condtionals like: `if (process.env.NODE_ENV === "production")`
      // "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV)
      "process.env.NODE_ENV": JSON.stringify("production")
    }),
    new BabiliPlugin({}, {
      sourceMap: true
    })
  ],

  /**
   * This defines the 'root' of your project.  If you `require('some-package')`
   * from within your application JS, Webpack will first check the directory
   * specified in config.root for `some-package.js` before checking node_modules.
   */

  resolve: {
    modules: [
      path.join(config.root, config.src),
      "node_modules"
    ]
  }
};
<commit_msg>Fix more lint erors<commit_after>"use strict";

const DefinePlugin = require("webpack").DefinePlugin;
const path = require("path");
const SourceMapDevToolPlugin = require("webpack").SourceMapDevToolPlugin;
const BabiliPlugin = require("babili-webpack-plugin");

const config = require("../../project.config");

module.exports = {
  context: config.srcFullPath,

  entry: {
    main: "./js/main.js"
  },
  output: {
    path: path.join(config.destFullPath, config.js),
    filename: "[name].bundle.js",
    chunkFilename: "[id].bundle.js"
  },

  module: {
    rules: [{
      test: /\.jsx?$/,
      exclude: /node_modules/,
      use: {
        loader: "babel-loader"
      }
    }]
  },

  plugins: [
    new SourceMapDevToolPlugin({
      test: /\.(css|js)($|\?)/,
      filename: "[file].map",
      append: "\n//# sourceMappingURL=[url]",
      module: true,
      columns: true
    }),
    new DefinePlugin({
      // Signal production, so that webpack removes non-production code that
      // is in condtionals like: `if (process.env.NODE_ENV === "production")`
      // "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV)
      "process.env.NODE_ENV": JSON.stringify("production")
    }),
    new BabiliPlugin({}, {
      sourceMap: true
    })
  ],

  /**
   * This defines the 'root' of your project.  If you `require('some-package')`
   * from within your application JS, Webpack will first check the directory
   * specified in config.root for `some-package.js` before checking node_modules.
   */

  resolve: {
    modules: [
      path.join(config.root, config.src),
      "node_modules"
    ]
  }
};
<|endoftext|>


<commit_before>var fs = require('fs'),
    path = require('path'),
    glob = require('glob'),
    svgo = require('svgo'),
    idify = require('html4-id'),
    merge = require('webpack-merge'),
    xmldom = require('xmldom'),
    loaderUtils = require('loader-utils'),
    RawSource = require('webpack-sources').RawSource;

function SVGSpritemapPlugin(options) {
    // Merge specified options with default options
    this.options = merge({
        src: '**/*.svg',
        svgo: {},
        glob: {},
        prefix: 'sprite-',
        gutter: 2,
        filename: 'spritemap.svg',
        chunk: 'spritemap',
        svg4everybody: false
    }, options, {
        svgo: {
            plugins: [{
                cleanupIDs: false
            }]
        }
    });
}

SVGSpritemapPlugin.prototype.apply = function(compiler) {
    var options = this.options,
        files = glob.sync(options.src, options.glob);

    compiler.plugin('this-compilation', function(compilation) {
        compilation.plugin('optimize-chunks', function optmizeChunks(chunks) {
            if ( files.length ) {
                // Add new chunk for spritemap
                compilation.addChunk(options.chunk);
            }
        });

        compilation.plugin('additional-chunk-assets', function additionalChunkAssets(chunks) {
            var svg = generateSVG();
            if ( !svg ) {
                return;
            }

            var source = new RawSource(svg);
            var sourceChunk = compilation.namedChunks[options.chunk];
            var filename = options.filename
                .replace(/\[hash]/ig, compilation.getStats().hash)
                .replace(/\[contenthash]/ig, function() {
                    return loaderUtils.getHashDigest(source.source(), 'sha1', 'hex', 16);
                });

            // Add actual (unoptimized) SVG to spritemap chunk
            compilation.additionalChunkAssets.push(filename);
            compilation.assets[filename] = source;
            sourceChunk.files.push(filename);
        });

        compilation.plugin('optimize-chunk-assets', function optimizeChunkAssets(chunks, callback) {
            // Optimize spritemap using SVGO
            if ( options.svgo === false ) {
                callback();
                return;
            }

            chunks = chunks.filter(function(chunk) {
                return chunk.name === options.chunk;
            });

            if ( !chunks.length ) {
                callback();
                return;
            }

            chunks.forEach(function(chunk) {
                var SVGOptimizer = new svgo(options.svgo);
                var filename = chunk.files[1];

                SVGOptimizer.optimize(compilation.assets[filename].source(), function(o) {
                    compilation.assets[filename] = new RawSource(o.data);
                    callback();
                });
            });
        });

        var generateSVG = function() {
            // No point in generating when there are no files
            if ( !files.length ) {
                return false;
            }

            // Initialize DOM/XML classes and SVGO
            var DOMParser = new xmldom.DOMParser(),
                XMLSerializer = new xmldom.XMLSerializer(),
                XMLDoc = new xmldom.DOMImplementation().createDocument(null, null, null); // `document` alternative for NodeJS environments

            // Create SVG element
            var spritemap = XMLDoc.createElement('svg'),
                sizes = { width: [], height: [] };

            // Add namespaces
            spritemap.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
            spritemap.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');

            // Add symbol for each file
            files.forEach(function(file) {
                var id = options.prefix + path.basename(file, path.extname(file)),
                    validId = idify(id);

                // Parse source SVG
                var contents = fs.readFileSync(file, 'utf8'),
                    svg = DOMParser.parseFromString(contents).documentElement,
                    viewbox = (svg.getAttribute('viewBox') || svg.getAttribute('viewbox')).split(' ').map(function(a) { return parseFloat(a); }),
                    width = parseFloat(svg.getAttribute('width')) || viewbox[2],
                    height = parseFloat(svg.getAttribute('height')) || viewbox[3];

                // Create symbol
                var symbol = XMLDoc.createElement('symbol');
                symbol.setAttribute('id', validId);
                symbol.setAttribute('viewBox', viewbox.join(' '));

                // Make sure we don't overwrite the existing title
                var hasTitle = false;
                for ( var i = 0; i < svg.childNodes.length; i++ ) {
                    if ( svg.childNodes[i].tagName && svg.childNodes[i].tagName.toLowerCase() === 'title' ) {
                        var hasTitle = true;
                    }
                }

                // Add title for improved accessibility
                if ( !hasTitle ) {
                    var title = XMLDoc.createElement('title');
                    title.appendChild(XMLDoc.createTextNode(id.replace(options.prefix, '')));
                    symbol.appendChild(title);
                }

                // Clone the original contents of the SVG file into the new symbol
                while ( svg.childNodes.length > 0 ) {
                    symbol.appendChild(svg.childNodes[0]);
                }

                spritemap.insertBefore(symbol, spritemap.firstChild);

                // Generate <use> elements within spritemap to allow usage within CSS
                var sprite = XMLDoc.createElement('use');
                sprite.setAttribute('xlink:href', '#' + validId);
                sprite.setAttribute('x', 0);
                sprite.setAttribute('y', sizes.height.reduce(function(a, b) { return a + b; }, 0) + sizes.height.length * options.gutter);
                sprite.setAttribute('width', width);
                sprite.setAttribute('height', height);
                spritemap.appendChild(sprite);

                // Update sizes
                sizes.width.push(width);
                sizes.height.push(height);
            });

            // Adds width/height to spritemap
            spritemap.setAttribute('width', Math.max.apply(null, sizes.width));
            spritemap.setAttribute('height', sizes.height.reduce(function(a, b) { return a + b; }, 0) + (sizes.height.length - 1) * options.gutter);

            // No point in optimizing/saving when there are no SVGs
            if ( !spritemap.childNodes.length ) {
                return false;
            }

            return XMLSerializer.serializeToString(spritemap);
        }
    });

    compiler.plugin('emit', function(compilation, callback) {
        compilation.chunks.forEach(function(chunk) {
            if ( chunk.name !== options.chunk ) {
                return;
            }

            // Remove entry (.js file) from compilation assets since it's empty anyway
            delete compilation.assets[chunk.files[0]];
        });

        callback();
    });

    compiler.plugin('entry-option', function(context, entry) {
        if ( options.svg4everybody ) {
            // This is a little hacky but there's no other way since Webpack
            // doesn't support virtual files (https://github.com/rmarscher/virtual-module-webpack-plugin)
            var helper = fs.readFileSync(path.join(__dirname, '/helpers/svg4everybody.template.js'), 'utf8');
            fs.writeFileSync(path.join(__dirname, '/svg4everybody-helper.js'), helper.replace('{/* PLACEHOLDER */}', JSON.stringify(options.svg4everybody)), 'utf8');

            var newEntry = path.join(__dirname, '/svg4everybody-helper.js');
            if ( typeof entry === 'string' ) {
                entry = [entry, newEntry];
            } else if ( Array.isArray(entry) ) {
                entry.push(newEntry);
            } else {
                Object.keys(entry).forEach(function(item) {
                    entry[item].push(newEntry);
                });
            }
        }
    });
};

module.exports = SVGSpritemapPlugin;
<commit_msg>Fixes #15: Improves handling of width/height and viewBox attributes<commit_after>var fs = require('fs'),
    path = require('path'),
    glob = require('glob'),
    svgo = require('svgo'),
    idify = require('html4-id'),
    merge = require('webpack-merge'),
    xmldom = require('xmldom'),
    loaderUtils = require('loader-utils'),
    RawSource = require('webpack-sources').RawSource;

function SVGSpritemapPlugin(options) {
    // Merge specified options with default options
    this.options = merge({
        src: '**/*.svg',
        svgo: {},
        glob: {},
        prefix: 'sprite-',
        gutter: 2,
        filename: 'spritemap.svg',
        chunk: 'spritemap',
        svg4everybody: false
    }, options, {
        svgo: {
            plugins: [{
                cleanupIDs: false
            }]
        }
    });
}

SVGSpritemapPlugin.prototype.apply = function(compiler) {
    var options = this.options,
        files = glob.sync(options.src, options.glob);

    compiler.plugin('this-compilation', function(compilation) {
        compilation.plugin('optimize-chunks', function optmizeChunks(chunks) {
            if ( files.length ) {
                // Add new chunk for spritemap
                compilation.addChunk(options.chunk);
            }
        });

        compilation.plugin('additional-chunk-assets', function additionalChunkAssets(chunks) {
            var svg = generateSVG();
            if ( !svg ) {
                return;
            }

            var source = new RawSource(svg);
            var sourceChunk = compilation.namedChunks[options.chunk];
            var filename = options.filename
                .replace(/\[hash]/ig, compilation.getStats().hash)
                .replace(/\[contenthash]/ig, function() {
                    return loaderUtils.getHashDigest(source.source(), 'sha1', 'hex', 16);
                });

            // Add actual (unoptimized) SVG to spritemap chunk
            compilation.additionalChunkAssets.push(filename);
            compilation.assets[filename] = source;
            sourceChunk.files.push(filename);
        });

        compilation.plugin('optimize-chunk-assets', function optimizeChunkAssets(chunks, callback) {
            // Optimize spritemap using SVGO
            if ( options.svgo === false ) {
                callback();
                return;
            }

            chunks = chunks.filter(function(chunk) {
                return chunk.name === options.chunk;
            });

            if ( !chunks.length ) {
                callback();
                return;
            }

            chunks.forEach(function(chunk) {
                var SVGOptimizer = new svgo(options.svgo);
                var filename = chunk.files[1];

                SVGOptimizer.optimize(compilation.assets[filename].source(), function(o) {
                    compilation.assets[filename] = new RawSource(o.data);
                    callback();
                });
            });
        });

        var generateSVG = function() {
            // No point in generating when there are no files
            if ( !files.length ) {
                return false;
            }

            // Initialize DOM/XML classes and SVGO
            var DOMParser = new xmldom.DOMParser(),
                XMLSerializer = new xmldom.XMLSerializer(),
                XMLDoc = new xmldom.DOMImplementation().createDocument(null, null, null); // `document` alternative for NodeJS environments

            // Create SVG element
            var spritemap = XMLDoc.createElement('svg'),
                sizes = { width: [], height: [] };

            // Add namespaces
            spritemap.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
            spritemap.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');

            // Add symbol for each file
            files.forEach(function(file) {
                var id = options.prefix + path.basename(file, path.extname(file)),
                    validId = idify(id);

                // Parse source SVG
                var contents = fs.readFileSync(file, 'utf8'),
                    svg = DOMParser.parseFromString(contents).documentElement,
                    viewbox = (svg.getAttribute('viewBox') || svg.getAttribute('viewbox')).split(' ').map(function(a) { return parseFloat(a); }),
                    width = parseFloat(svg.getAttribute('width')),
                    height = parseFloat(svg.getAttribute('height'));

                if ( viewbox.length !== 4 && ( isNaN(width) || isNaN(height) ) ) {
                    console.error('Skipping sprite \'%s\' since it\'s lacking both a viewBox and width/height attributes...', id.replace(options.prefix, ''));
                    return;
                }

                if ( viewbox.length !== 4 ) {
                    viewbox = [0, 0, width, height];
                }

                if ( isNaN(width) ) {
                    width = viewbox[2];
                }

                if ( isNaN(height) ) {
                    height = viewbox[3];
                }

                // Create symbol
                var symbol = XMLDoc.createElement('symbol');
                symbol.setAttribute('id', validId);
                symbol.setAttribute('viewBox', viewbox.join(' '));

                // Make sure we don't overwrite the existing title
                var hasTitle = false;
                for ( var i = 0; i < svg.childNodes.length; i++ ) {
                    if ( svg.childNodes[i].tagName && svg.childNodes[i].tagName.toLowerCase() === 'title' ) {
                        var hasTitle = true;
                    }
                }

                // Add title for improved accessibility
                if ( !hasTitle ) {
                    var title = XMLDoc.createElement('title');
                    title.appendChild(XMLDoc.createTextNode(id.replace(options.prefix, '')));
                    symbol.appendChild(title);
                }

                // Clone the original contents of the SVG file into the new symbol
                while ( svg.childNodes.length > 0 ) {
                    symbol.appendChild(svg.childNodes[0]);
                }

                spritemap.insertBefore(symbol, spritemap.firstChild);

                // Generate <use> elements within spritemap to allow usage within CSS
                var sprite = XMLDoc.createElement('use');
                sprite.setAttribute('xlink:href', '#' + validId);
                sprite.setAttribute('x', 0);
                sprite.setAttribute('y', sizes.height.reduce(function(a, b) { return a + b; }, 0) + sizes.height.length * options.gutter);
                sprite.setAttribute('width', width);
                sprite.setAttribute('height', height);
                spritemap.appendChild(sprite);

                // Update sizes
                sizes.width.push(width);
                sizes.height.push(height);
            });

            // Adds width/height to spritemap
            spritemap.setAttribute('width', Math.max.apply(null, sizes.width));
            spritemap.setAttribute('height', sizes.height.reduce(function(a, b) { return a + b; }, 0) + (sizes.height.length - 1) * options.gutter);

            // No point in optimizing/saving when there are no SVGs
            if ( !spritemap.childNodes.length ) {
                return false;
            }

            return XMLSerializer.serializeToString(spritemap);
        }
    });

    compiler.plugin('emit', function(compilation, callback) {
        compilation.chunks.forEach(function(chunk) {
            if ( chunk.name !== options.chunk ) {
                return;
            }

            // Remove entry (.js file) from compilation assets since it's empty anyway
            delete compilation.assets[chunk.files[0]];
        });

        callback();
    });

    compiler.plugin('entry-option', function(context, entry) {
        if ( options.svg4everybody ) {
            // This is a little hacky but there's no other way since Webpack
            // doesn't support virtual files (https://github.com/rmarscher/virtual-module-webpack-plugin)
            var helper = fs.readFileSync(path.join(__dirname, '/helpers/svg4everybody.template.js'), 'utf8');
            fs.writeFileSync(path.join(__dirname, '/svg4everybody-helper.js'), helper.replace('{/* PLACEHOLDER */}', JSON.stringify(options.svg4everybody)), 'utf8');

            var newEntry = path.join(__dirname, '/svg4everybody-helper.js');
            if ( typeof entry === 'string' ) {
                entry = [entry, newEntry];
            } else if ( Array.isArray(entry) ) {
                entry.push(newEntry);
            } else {
                Object.keys(entry).forEach(function(item) {
                    entry[item].push(newEntry);
                });
            }
        }
    });
};

module.exports = SVGSpritemapPlugin;
<|endoftext|>


<commit_before>/**
 * Created by hms-mac on 11/17/15.
 */
'use strict';

var React = require('react-native');
const Dimensions = require('Dimensions');
var {
    Image,
    ListView,
    StyleSheet,
    Text,
    View,
    TouchableHighlight,
    AlertIOS,
    } = React;

var REQUEST_URL = '/Users/hms-mac/research/react-native/apptizer-mock/apptizer/data.json';

var Profile = React.createClass({

    getInitialState: function () {
        return {
            dataSource: new ListView.DataSource({
                rowHasChanged: (row1, row2) => row1 !== row2,
            }),
            loaded: false,
        };
    },
    componentDidMount: function () {
        this.fetchData();
    },
    fetchData: function () {
        fetch(REQUEST_URL)
            .then((response) => response.json())
            .then((responseData) => {
                this.setState({
                    dataSource: this.state.dataSource.cloneWithRows(responseData.fooditems),
                    loaded: true,
                });
            })
            .done();
    },
    render: function () {
        if (!this.state.loaded) {
            return this.renderLoadingView();
        }

        return (
            <ListView
                dataSource={this.state.dataSource}
                renderRow={this.renderItem}
                style={styles.listView}
                automaticallyAdjustContentInsets={false}
            />
        );
    },

    renderLoadingView: function () {
        return (
            <View style={styles.container}>
                <Text>
                    Loading fooditems...
                </Text>
            </View>
        );
    },

    renderItem: function (item) {
        return (
            <View style={styles.container}>
                <Image
                    source={{uri: item.images.main}}
                    style={styles.image}
                />

                <View style={styles.rightContainer}>
                    <Text>{item.name}</Text>
                    <Text style={styles.text}>Rs.{item.price}</Text>
                </View>
                <View style={styles.buttonContainer}>
                    <TouchableHighlight underlayColor="#36ea00" style={styles.button}onPress={() => AlertIOS.alert(
                        'Share',
                        'Do you want to Share this item?',
                        [
                          {text: 'Cancel', onPress: () => console.log('Cancel Pressed!')},
                          {text: 'Share', onPress: () => console.log('Share Pressed!')},
                        ]
                    )}>
                        <Text style={styles.buttonText}>Share</Text>
                    </TouchableHighlight>
                    <TouchableHighlight underlayColor="#36ea00" style={styles.button}onPress={() => AlertIOS.alert(
                        'Item added to Cart!',
                        null,
                        [
                          {text: 'Okay', onPress: () => console.log('Okay Pressed!')},
                        ]
                    )}>
                        <Text style={styles.buttonText}>Add to Cart</Text>
                    </TouchableHighlight>
                </View>
            </View>
        );
    }
});

var styles = StyleSheet.create({
    container: {
        width: Dimensions.get('window').width / 100 * 95,
        marginBottom: 10,
        borderColor: '#cecece',
        flexDirection: 'column',
        alignItems: 'center',
        paddingBottom: 10,
        backgroundColor: '#F5FCFF',
        shadowColor: 'grey',
        shadowOpacity: 40,
        shadowOffset: {width: 0, height: 2}

    },
    rightContainer: {
        flexDirection: 'row',
        alignItems: 'stretch',
        paddingTop: 10,
        paddingBottom: 10,
    },
    image: {
        alignItems: 'stretch',
        width: Dimensions.get('window').width / 100 * 95,
        height: 100,
    },
    text: {
        paddingLeft: 10,
    },
    listView: {
        paddingHorizontal: Dimensions.get('window').width / 100 * 2.5,
        paddingTop: 70,
        paddingBottom: 20,
        //backgroundColor: '#c4ff9b', //Background Color behind the Cards
    },
    buttonText: {
        fontSize: 10,
        color: '#36ea00',
        paddingTop: 2,
        paddingBottom: 2,
    },
    button: {
        width: 100,
        height: 20,
        borderColor: '#36ea00',
        alignItems: 'center',
        borderRadius: 10,
        borderWidth: 1,
    },
    buttonContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingRight: 10,
    }
});

module.exports = Profile;<commit_msg>Alert moved to a method<commit_after>/**
 * Created by hms-mac on 11/17/15.
 */
'use strict';

var React = require('react-native');
const Dimensions = require('Dimensions');
var {
    Image,
    ListView,
    StyleSheet,
    Text,
    View,
    TouchableHighlight,
    AlertIOS,
    } = React;

var REQUEST_URL = '/Users/hms-mac/research/react-native/apptizer-mock/apptizer/data.json';

var Profile = React.createClass({

    getInitialState: function () {
        return {
            dataSource: new ListView.DataSource({
                rowHasChanged: (row1, row2) => row1 !== row2,
            }),
            loaded: false,
        };
    },
    componentDidMount: function () {
        this.fetchData();
    },
    fetchData: function () {
        fetch(REQUEST_URL)
            .then((response) => response.json())
            .then((responseData) => {
                this.setState({
                    dataSource: this.state.dataSource.cloneWithRows(responseData.fooditems),
                    loaded: true,
                });
            })
            .done();
    },
    render: function () {
        if (!this.state.loaded) {
            return this.renderLoadingView();
        }

        return (
            <ListView
                dataSource={this.state.dataSource}
                renderRow={this.renderItem}
                style={styles.listView}
                automaticallyAdjustContentInsets={false}
            />
        );
    },

    renderLoadingView: function () {
        return (
            <View style={styles.container}>
                <Text>
                    Loading fooditems...
                </Text>
            </View>
        );
    },

    onAddToCartPressed: function(){
        AlertIOS.alert(
            'Item added to Cart!',
            null,
            [
                {text: 'Okay', onPress: () => console.log('Okay Pressed!')},
            ]
        )
    },

    onSharePressed: function(){
        AlertIOS.alert(
            'Share',
            'Do you want to Share this Item?',
            [
                {text: 'Cancel', onPress: () => console.log('Cancel Pressed!')},
                {text: 'Share', onPress: () => console.log('Share Pressed!')},
            ]
        )
    },

    renderItem: function (item) {
        return (
            <View style={styles.container}>
                <Image
                    source={{uri: item.images.main}}
                    style={styles.image}
                />

                <View style={styles.rightContainer}>
                    <Text>{item.name}</Text>
                    <Text style={styles.text}>Rs.{item.price}</Text>
                </View>
                <View style={styles.buttonContainer}>
                    <TouchableHighlight underlayColor="#36ea00" style={styles.button}onPress={this.onSharePressed}>
                        <Text style={styles.buttonText}>Share</Text>
                    </TouchableHighlight>
                    <TouchableHighlight underlayColor="#36ea00" style={styles.button}onPress={this.onAddToCartPressed}>
                        <Text style={styles.buttonText}>Add to Cart</Text>
                    </TouchableHighlight>
                </View>
            </View>
        );
    }
});

var styles = StyleSheet.create({
    container: {
        width: Dimensions.get('window').width / 100 * 95,
        marginBottom: 10,
        borderColor: '#cecece',
        flexDirection: 'column',
        alignItems: 'center',
        paddingBottom: 10,
        backgroundColor: '#F5FCFF',
        shadowColor: 'grey',
        shadowOpacity: 40,
        shadowOffset: {width: 0, height: 2}

    },
    rightContainer: {
        flexDirection: 'row',
        alignItems: 'stretch',
        paddingTop: 10,
        paddingBottom: 10,
    },
    image: {
        alignItems: 'stretch',
        width: Dimensions.get('window').width / 100 * 95,
        height: 100,
    },
    text: {
        paddingLeft: 10,
    },
    listView: {
        paddingHorizontal: Dimensions.get('window').width / 100 * 2.5,
        paddingTop: 70,
        paddingBottom: 20,
        //backgroundColor: '#c4ff9b', //Background Color behind the Cards
    },
    buttonText: {
        fontSize: 10,
        color: '#36ea00',
        paddingTop: 2,
        paddingBottom: 2,
    },
    button: {
        width: 100,
        height: 20,
        borderColor: '#36ea00',
        alignItems: 'center',
        borderRadius: 10,
        borderWidth: 1,
    },
    buttonContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingRight: 10,
    }
});

module.exports = Profile;<|endoftext|>


<commit_before>var redis      = require('redis');
var SerialPort = require('serialport');
var fs = require('fs');

var files = fs.readdirSync('/dev/');
//console.log('files=<',files,'>');
var uartDevice = false;
files.forEach(function(file) {
  //console.log('file=<',file,'>');
  if(file.startsWith('ttyUSB')) {
    //console.log('file=<',file,'>');
    uartDevice = '/dev/' +file;
  }
});
if(uartDevice === false) {
  uartDevice = '/dev/ttyS1';
}
console.log('uartDevice=<',uartDevice,'>');

function writeMotor(motor) {
  console.log('JSON.stringify(motor)=<',JSON.stringify(motor),'>');
  serialPort.flush();
  serialPort.write(JSON.stringify(motor),'utf8',function(err) {
    if (err) {
      console.log('err=<',err,'>');
    } else {
      console.log('message written');
    }
  });
  serialPort.drain();
}

var readClient = redis.createClient(6379, 'localhost');

var gBaseMotorSpeed = 50;

var subscriber = redis.createClient(6379, 'localhost');
subscriber.subscribe('/dbc/webui2uart');
subscriber.on("message", function(channel, message) {
  console.log('message=<',message,'>');
  if(message === 'forword') {
    var motor = {
      FL:{s:gBaseMotorSpeed,f:1},
      FR:{s:gBaseMotorSpeed,f:1},
      BL:{s:gBaseMotorSpeed,f:1},
      BR:{s:gBaseMotorSpeed,f:1},
    };
    writeMotor(motor);
  }
  if(message === 'back') {
    var motor = {
      FL:{s:gBaseMotorSpeed,f:0},
      FR:{s:gBaseMotorSpeed,f:0},
      BL:{s:gBaseMotorSpeed,f:0},
      BR:{s:gBaseMotorSpeed,f:0},
    };
    writeMotor(motor);
  }
  if(message === 'left') {
    var motor = {
      FL:{s:gBaseMotorSpeed,f:0},
      FR:{s:gBaseMotorSpeed,f:1},
      BL:{s:gBaseMotorSpeed,f:0},
      BR:{s:gBaseMotorSpeed,f:1},
    };
    writeMotor(motor);
  }
  if(message === 'right') {
    var motor = {
      FL:{s:gBaseMotorSpeed,f:1},
      FR:{s:gBaseMotorSpeed,f:0},
      BL:{s:gBaseMotorSpeed,f:1},
      BR:{s:gBaseMotorSpeed,f:0},
    };
    writeMotor(motor);
  }
  if(message === 'stop') {
    var motor = {
      FL:{s:254,f:1},
      FR:{s:254,f:1},
      BL:{s:254,f:1},
      BR:{s:254,f:1},
    };
    writeMotor(motor);
  }
  if(message.startsWith('speed:=<')) {
    var speed = parseInt(message.replace('speed:=<').replace('>'));
    console.log('speed=<',speed,'>');
    readClient.set('/dbc/speed',);
    readClient.get('/dbc/speed',function(err, val) {
      if(err) {
         console.log('err=<',err,'>');
      } else {
        console.log('val=<',val,'>');
        var speed = parseInt(val);
        if(speed > 1 && speed < 256) {
           gBaseMotorSpeed = 256 - speed;
        }
      }
    });
  }

});

var serialPort = new SerialPort(uartDevice, {
 baudRate: 115200
});

serialPort.on("open", function () {
  console.log('open');
 });

serialPort.on('data', function(data) {
  console.log('received data =<',data.toString('utf8'),'>');
});

serialPort.on('error', function(err) {
  console.log('err =<',err,'>');
});
<commit_msg>Update app.js<commit_after>var redis      = require('redis');
var SerialPort = require('serialport');
var fs = require('fs');

var files = fs.readdirSync('/dev/');
//console.log('files=<',files,'>');
var uartDevice = false;
files.forEach(function(file) {
  //console.log('file=<',file,'>');
  if(file.startsWith('ttyUSB')) {
    //console.log('file=<',file,'>');
    uartDevice = '/dev/' +file;
  }
});
if(uartDevice === false) {
  uartDevice = '/dev/ttyS1';
}
console.log('uartDevice=<',uartDevice,'>');

function writeMotor(motor) {
  console.log('JSON.stringify(motor)=<',JSON.stringify(motor),'>');
  serialPort.flush();
  serialPort.write(JSON.stringify(motor),'utf8',function(err) {
    if (err) {
      console.log('err=<',err,'>');
    } else {
      console.log('message written');
    }
  });
  serialPort.drain();
}

var readClient = redis.createClient(6379, 'localhost');

var gBaseMotorSpeed = 50;

var subscriber = redis.createClient(6379, 'localhost');
subscriber.subscribe('/dbc/webui2uart');
subscriber.on("message", function(channel, message) {
  console.log('message=<',message,'>');
  if(message === 'forword') {
    var motor = {
      FL:{s:gBaseMotorSpeed,f:1},
      FR:{s:gBaseMotorSpeed,f:1},
      BL:{s:gBaseMotorSpeed,f:1},
      BR:{s:gBaseMotorSpeed,f:1},
    };
    writeMotor(motor);
  }
  if(message === 'back') {
    var motor = {
      FL:{s:gBaseMotorSpeed,f:0},
      FR:{s:gBaseMotorSpeed,f:0},
      BL:{s:gBaseMotorSpeed,f:0},
      BR:{s:gBaseMotorSpeed,f:0},
    };
    writeMotor(motor);
  }
  if(message === 'left') {
    var motor = {
      FL:{s:gBaseMotorSpeed,f:0},
      FR:{s:gBaseMotorSpeed,f:1},
      BL:{s:gBaseMotorSpeed,f:0},
      BR:{s:gBaseMotorSpeed,f:1},
    };
    writeMotor(motor);
  }
  if(message === 'right') {
    var motor = {
      FL:{s:gBaseMotorSpeed,f:1},
      FR:{s:gBaseMotorSpeed,f:0},
      BL:{s:gBaseMotorSpeed,f:1},
      BR:{s:gBaseMotorSpeed,f:0},
    };
    writeMotor(motor);
  }
  if(message === 'stop') {
    var motor = {
      FL:{s:254,f:1},
      FR:{s:254,f:1},
      BL:{s:254,f:1},
      BR:{s:254,f:1},
    };
    writeMotor(motor);
  }
  if(message.startsWith('speed:=<')) {
    var speedSpr = message.replace('speed:=<').replace('>');
    console.log('speedSpr=<',speedSpr,'>');
    readClient.set('/dbc/speed',speedSpr);
    readClient.get('/dbc/speed',function(err, val) {
      if(err) {
         console.log('err=<',err,'>');
      } else {
        console.log('val=<',val,'>');
        var speed = parseInt(val);
        if(speed > 1 && speed < 256) {
           gBaseMotorSpeed = 256 - speed;
        }
      }
    });
  }

});

var serialPort = new SerialPort(uartDevice, {
 baudRate: 115200
});

serialPort.on("open", function () {
  console.log('open');
 });

serialPort.on('data', function(data) {
  console.log('received data =<',data.toString('utf8'),'>');
});

serialPort.on('error', function(err) {
  console.log('err =<',err,'>');
});
<|endoftext|>


<commit_before>"use strict";
var express = require("express"),
    logger = require("morgan"),
    cookieParser = require("cookie-parser"),
    bodyParser = require("body-parser"),
    methodOverride = require("method-override"),
    session = require("express-session"),
    mongojs = require("mongojs"),
    compression = require('compression');

const MongoStore = require("connect-mongo")(session);

let app = express();

let config = {
    db: process.env.DBURL,
    numplayers: 2
};

// Integrate Middleware
app.use(logger("dev"));
app.use(methodOverride("_method"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
    secret: "keyboard cat",
    store: new MongoStore({ url: config.db })
}));

app.use((req, res, next) => {
    // MONGOJS - See GH for Docs
    req.db = mongojs(config.db);
    next();
});

app.get("/dynamic", (req, res) => {
	res.send("Hello, world");
});

app.use(compression());
app.use(express.static("Build/Client"));

app.use("/", require("./routes/api.js"));

var server = app.listen(process.env.PORT || 3000, () => {
	var {address: host, port} = server.address();

	console.log(`Listening on http://${host}:${port}/`);
});

var io = require("socket.io")(server)
// usernames which are currently connected to the chat
var usernames = {};
var numUsers = 0;

//new stuff, in addition to chat parts above
var users = {};
var teams = {};
var games = [];

io.on('connection', function (socket) {
  socket.on("register", function(data){
  	//eventually add auth here
  	socket.username = data.username;
  	users[data.username] = {socket: socket};
    socket.emit("loggedin", data.username);
  });
  socket.on("checkusername", function(username){
    if(false){ //add auth check here
      socket.emit("usernamecheckresponse", "not available");
    }
  });
  socket.on("checkteamname", function(teamname){
    console.log(teamname);
    console.log(teams);
    console.log(teamname in teams);
    if(teamname in teams){
      if(teams[teamname].users.length == config.numplayers){
        socket.emit("teamcheckresponse", "full");
      }
      else{
        socket.emit("teamcheckresponse", "exists");
      }
    }
    else{
      socket.emit("teamcheckresponse", "new");
    }
  });
  socket.on("jointeam", function(teamname){
    if(!(teamname in teams)){
      teams[teamname] = {
        name: teamname,
        users: [],
        game: null
      };
      fullteams().forEach(function(team){
        team.users.forEach(function(username){
          users[username].socket.emit("teamslist newteam", {
            name: teamname,
            state: "Not Full"
          });
        });
      });
    }
    teams[teamname].users.push(socket.username);
    console.log(teams);
    users[socket.username].teamname = teamname;
    socket.emit("joinedteam");
    teams[teamname].users.forEach(function(user){
        socket.emit("newmember", user);
        if(user !== socket.username){
          console.log("users");
          console.log(users);
          users[user].socket.emit("newmember", socket.username);
        }
    });
    if(teams[teamname].users.length == config.numplayers){
        teams[teamname].users.forEach(function(user){
            users[user].socket.emit("readytoselect");
        });
        fullteams().forEach(function(team){
          team.users.forEach(function(username){
            users[username].socket.emit("teamslist update", {
              team: teamname,
              state: "Ready"
            });
          });
        });
    }
    else {
      fullteams().forEach(function(team){
        team.users.forEach(function(username){
          users[username].socket.emit("teamslist update", {
            team: teamname,
            state: "Not Full"
          });
        });
      });
    }

    console.log("Teams: " + JSON.stringify(teams));
    for (let i in users) {
        console.log("" + i + ": " + users[i]);
    }
    //debugger;
  });

  socket.on("requestgamestart", function () {
      console.log("Recieved a request to start the game");

      let teamname = users[socket.username].teamname;
      let team = teams[teamname];

      for (let username of team.users) {
          users[username].socket.emit("startgame");
          console.log("Telling user to start: " + username);
      }
  });

  socket.on("position-update-user", function(data){
    //console.log("" + socket.username + "sent position update " + JSON.stringify(data));

    let teamname = users[socket.username].teamname;
    let team = teams[teamname];

    for (let username of team.users) {
        if (username !== socket.username) {
            let user = users[username];
            data.user = socket.username;
            user.socket.emit("position-update-others", data);
        }
    }
  });

  function fullteams(){
    var fullteams2 = [];
    console.log("fullteams");
    console.log(teams);
    Object.keys(teams).forEach(function(teamname){
      var team = teams[teamname];
      if(team.users.length == config.numplayers){
        fullteams2.push(team);
      }
    });
    return fullteams2;
  }

  socket.on("teamslist firstshow", function(){
    var teamdata = [];
    var fullteamslist = fullteams();
    console.log("Full teams:")
    console.log(fullteamslist);
    Object.keys(teams).forEach(function(teamname){
      var team = teams[teamname];
      var teamstate = "";
      if(team.users.length == config.numplayers){
        if(team.game){
          teamstate = "In Game";
        }
        else {
          teamstate = "Ready";
        }
      }
      else {
        teamstate = "Not Full";
      }
      teamdata.push({
        name: team.name,
        state: teamstate
      });
    });
    teams[users[socket.username].teamname].users.forEach(function(username){
      users[username].socket.emit("teamslist fulldata", teamdata);
    });
  });

  socket.on("teamslist click", function(otherteamname){
    var gameid = games.length;
    var userscores = {};
    teams[users[socket.username].teamname].users.concat(teams[otherteamname]).forEach(function(username){
      userscores[username] = 0;
    });
    games.push({
      id: gameid,
      team1: teams[users[socket.username].teamname],
      team2: teams[otherteamname],
      scores: {
        [users[socket.username].teamname]: 0,
        [otherteamname]: 0,
      },
      allusers: teams[users[socket.username].teamname].users.concat(teams[otherteamname].users),
      starttime: Date.now(),
      endtime: (Date.now() + 120000),
      end: function(){
        this.allusers.forEach(function(username){
          users[username].socket.emit("gameover");
        });
      }
    });
    setTimeout(games[gameid].end, 120000);

    console.log("New Game Started");
    console.log(games);
    games[gameid].allusers.forEach(function(username){
      users[username].game = gameid;
      users[username].socket.emit("startgame");
    });
  });

  socket.on("objectcollected", function(data){
    games[users[socket.username].gameid].allusers.forEach(function(username){
      users[username].socket.emit("otheruserobjectcollected", data);
    });
    var scorechange = 0;
    if(data.active){
      scorechange = -1;
    }
    else {
      scorechange = 5;
    }
    games[users[socket.username].gameid].userscores[socket.username] += scorechange;
    games[users[socket.username].gameid].scores[users[socket.username].teamname] += scorechange;
    socket.emit("scoreupdate user", games[users[socket.username].gameid].userscores[socket.username])
    games[users[socket.username].gameid].team1.users.forEach(function(username){
      users[username].socket.emit("scoreupdate all", games[users[socket.username].gameid].team1.score + "-" + games[users[socket.username].gameid].team2.score);
    });
    games[users[socket.username].gameid].team2.users.forEach(function(username){
      users[username].socket.emit("scoreupdate all", games[users[socket.username].gameid].team2.score + "-" + games[users[socket.username].gameid].team1.score);
    });
  });
});
<commit_msg>Fixed this reference<commit_after>"use strict";
var express = require("express"),
    logger = require("morgan"),
    cookieParser = require("cookie-parser"),
    bodyParser = require("body-parser"),
    methodOverride = require("method-override"),
    session = require("express-session"),
    mongojs = require("mongojs"),
    compression = require('compression');

const MongoStore = require("connect-mongo")(session);

let app = express();

let config = {
    db: process.env.DBURL,
    numplayers: 2
};

// Integrate Middleware
app.use(logger("dev"));
app.use(methodOverride("_method"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
    secret: "keyboard cat",
    store: new MongoStore({ url: config.db })
}));

app.use((req, res, next) => {
    // MONGOJS - See GH for Docs
    req.db = mongojs(config.db);
    next();
});

app.get("/dynamic", (req, res) => {
	res.send("Hello, world");
});

app.use(compression());
app.use(express.static("Build/Client"));

app.use("/", require("./routes/api.js"));

var server = app.listen(process.env.PORT || 3000, () => {
	var {address: host, port} = server.address();

	console.log(`Listening on http://${host}:${port}/`);
});

var io = require("socket.io")(server)
// usernames which are currently connected to the chat
var usernames = {};
var numUsers = 0;

//new stuff, in addition to chat parts above
var users = {};
var teams = {};
var games = [];

io.on('connection', function (socket) {
  socket.on("register", function(data){
  	//eventually add auth here
  	socket.username = data.username;
  	users[data.username] = {socket: socket};
    socket.emit("loggedin", data.username);
  });
  socket.on("checkusername", function(username){
    if(false){ //add auth check here
      socket.emit("usernamecheckresponse", "not available");
    }
  });
  socket.on("checkteamname", function(teamname){
    console.log(teamname);
    console.log(teams);
    console.log(teamname in teams);
    if(teamname in teams){
      if(teams[teamname].users.length == config.numplayers){
        socket.emit("teamcheckresponse", "full");
      }
      else{
        socket.emit("teamcheckresponse", "exists");
      }
    }
    else{
      socket.emit("teamcheckresponse", "new");
    }
  });
  socket.on("jointeam", function(teamname){
    if(!(teamname in teams)){
      teams[teamname] = {
        name: teamname,
        users: [],
        game: null
      };
      fullteams().forEach(function(team){
        team.users.forEach(function(username){
          users[username].socket.emit("teamslist newteam", {
            name: teamname,
            state: "Not Full"
          });
        });
      });
    }
    teams[teamname].users.push(socket.username);
    console.log(teams);
    users[socket.username].teamname = teamname;
    socket.emit("joinedteam");
    teams[teamname].users.forEach(function(user){
        socket.emit("newmember", user);
        if(user !== socket.username){
          console.log("users");
          console.log(users);
          users[user].socket.emit("newmember", socket.username);
        }
    });
    if(teams[teamname].users.length == config.numplayers){
        teams[teamname].users.forEach(function(user){
            users[user].socket.emit("readytoselect");
        });
        fullteams().forEach(function(team){
          team.users.forEach(function(username){
            users[username].socket.emit("teamslist update", {
              team: teamname,
              state: "Ready"
            });
          });
        });
    }
    else {
      fullteams().forEach(function(team){
        team.users.forEach(function(username){
          users[username].socket.emit("teamslist update", {
            team: teamname,
            state: "Not Full"
          });
        });
      });
    }

    console.log("Teams: " + JSON.stringify(teams));
    for (let i in users) {
        console.log("" + i + ": " + users[i]);
    }
    //debugger;
  });

  socket.on("requestgamestart", function () {
      console.log("Recieved a request to start the game");

      let teamname = users[socket.username].teamname;
      let team = teams[teamname];

      for (let username of team.users) {
          users[username].socket.emit("startgame");
          console.log("Telling user to start: " + username);
      }
  });

  socket.on("position-update-user", function(data){
    //console.log("" + socket.username + "sent position update " + JSON.stringify(data));

    let teamname = users[socket.username].teamname;
    let team = teams[teamname];

    for (let username of team.users) {
        if (username !== socket.username) {
            let user = users[username];
            data.user = socket.username;
            user.socket.emit("position-update-others", data);
        }
    }
  });

  function fullteams(){
    var fullteams2 = [];
    console.log("fullteams");
    console.log(teams);
    Object.keys(teams).forEach(function(teamname){
      var team = teams[teamname];
      if(team.users.length == config.numplayers){
        fullteams2.push(team);
      }
    });
    return fullteams2;
  }

  socket.on("teamslist firstshow", function(){
    var teamdata = [];
    var fullteamslist = fullteams();
    console.log("Full teams:")
    console.log(fullteamslist);
    Object.keys(teams).forEach(function(teamname){
      var team = teams[teamname];
      var teamstate = "";
      if(team.users.length == config.numplayers){
        if(team.game){
          teamstate = "In Game";
        }
        else {
          teamstate = "Ready";
        }
      }
      else {
        teamstate = "Not Full";
      }
      teamdata.push({
        name: team.name,
        state: teamstate
      });
    });
    teams[users[socket.username].teamname].users.forEach(function(username){
      users[username].socket.emit("teamslist fulldata", teamdata);
    });
  });

  socket.on("teamslist click", function(otherteamname){
    var gameid = games.length;
    var userscores = {};
    teams[users[socket.username].teamname].users.concat(teams[otherteamname]).forEach(function(username){
      userscores[username] = 0;
    });
    games.push({
      id: gameid,
      team1: teams[users[socket.username].teamname],
      team2: teams[otherteamname],
      scores: {
        [users[socket.username].teamname]: 0,
        [otherteamname]: 0,
      },
      allusers: teams[users[socket.username].teamname].users.concat(teams[otherteamname].users),
      starttime: Date.now(),
      endtime: (Date.now() + 120000),
      end: function(){
        games[gameid].allusers.forEach(function(username){
          users[username].socket.emit("gameover");
        });
      }
    });
    setTimeout(games[gameid].end, 120000);

    console.log("New Game Started");
    console.log(games);
    games[gameid].allusers.forEach(function(username){
      users[username].game = gameid;
      users[username].socket.emit("startgame");
    });
  });

  socket.on("objectcollected", function(data){
    games[users[socket.username].gameid].allusers.forEach(function(username){
      users[username].socket.emit("otheruserobjectcollected", data);
    });
    var scorechange = 0;
    if(data.active){
      scorechange = -1;
    }
    else {
      scorechange = 5;
    }
    games[users[socket.username].gameid].userscores[socket.username] += scorechange;
    games[users[socket.username].gameid].scores[users[socket.username].teamname] += scorechange;
    socket.emit("scoreupdate user", games[users[socket.username].gameid].userscores[socket.username])
    games[users[socket.username].gameid].team1.users.forEach(function(username){
      users[username].socket.emit("scoreupdate all", games[users[socket.username].gameid].team1.score + "-" + games[users[socket.username].gameid].team2.score);
    });
    games[users[socket.username].gameid].team2.users.forEach(function(username){
      users[username].socket.emit("scoreupdate all", games[users[socket.username].gameid].team2.score + "-" + games[users[socket.username].gameid].team1.score);
    });
  });
});
<|endoftext|>


<commit_before>

"use strict";
var
  OS = require('os'),
  Net = require('net'),
  CPP = require('childprocess-promise');
class Main{
  constructor(Port){
    this.Port = Port;
    this.Server = null;
    this.Children = [];
    this.DataBase = new Map();
  }
  Run(){
    let NumCPUs = OS.cpus().length;
    let SupportedEvents = [];

    for(let Name in Main){
      if (typeof Main[Name] === 'function' && Name.substr(0, 6) === 'Action')
        SupportedEvents.push(Name.substr(6));
    }
    for(var i = 0; i < NumCPUs; ++i){
      let Child = new CPP(__dirname + '/../Main.js');
      SupportedEvents.forEach(function(Child, Event){
        Child.on(Event, function(Request, Message){
          try {
            Main['Action' + Event].call(this, Child, Request, Message);
          } catch(error){
            Message.Result = {Type: 'Error', Message: error.message};
            Child.Finished(Message);
          }
        }.bind(this));
      }.bind(this, Child));
      Child.Send('SupportedEvents', SupportedEvents);
      this.Children.push(Child);
    }
    let Server = this.Server = Net.createServer();
    this.Server.listen(this.Port, this.Children.forEach.bind(this.Children, function(Child){
      Child.Target.send('Server', Server);
    }));
  }
  static ActionSET(Child, Request, Message){
    if(Request.length % 2 !== 0)
      throw new Error("Invalid Parameter length, Parameter number should be even");
    for(let Number = 0; Number < Request.length; Number += 2){
      this.DataBase.set(Request[Number], Request[Number + 1]);
    }
    Message.Result = {Type: 'OK'};
    Child.Finished(Message);
  }
  static ActionGET(Child, Request, Message){
    if(Request.length === 1){
      Message.Result = this.DataBase.get(Request[0]) || null;
    } else {
      let ToReturn = [];
      Request.forEach(function(Name){
        ToReturn.push(this.DataBase.get(Name) || null);
      }.bind(this));
      Message.Result = ToReturn;
    }
    Child.Finished(Message);
  }
}<commit_msg>:art: Case Port to Number<commit_after>

"use strict";
var
  OS = require('os'),
  Net = require('net'),
  CPP = require('childprocess-promise');
class Main{
  constructor(Port){
    this.Port = Number(Port);
    this.Server = null;
    this.Children = [];
    this.DataBase = new Map();
  }
  Run(){
    let NumCPUs = OS.cpus().length;
    let SupportedEvents = [];

    for(let Name in Main){
      if (typeof Main[Name] === 'function' && Name.substr(0, 6) === 'Action')
        SupportedEvents.push(Name.substr(6));
    }
    for(var i = 0; i < NumCPUs; ++i){
      let Child = new CPP(__dirname + '/../Main.js');
      SupportedEvents.forEach(function(Child, Event){
        Child.on(Event, function(Request, Message){
          try {
            Main['Action' + Event].call(this, Child, Request, Message);
          } catch(error){
            Message.Result = {Type: 'Error', Message: error.message};
            Child.Finished(Message);
          }
        }.bind(this));
      }.bind(this, Child));
      Child.Send('SupportedEvents', SupportedEvents);
      this.Children.push(Child);
    }
    let Server = this.Server = Net.createServer();
    this.Server.listen(this.Port, this.Children.forEach.bind(this.Children, function(Child){
      Child.Target.send('Server', Server);
    }));
  }
  static ActionSET(Child, Request, Message){
    if(Request.length % 2 !== 0)
      throw new Error("Invalid Parameter length, Parameter number should be even");
    for(let Number = 0; Number < Request.length; Number += 2){
      this.DataBase.set(Request[Number], Request[Number + 1]);
    }
    Message.Result = {Type: 'OK'};
    Child.Finished(Message);
  }
  static ActionGET(Child, Request, Message){
    if(Request.length === 1){
      Message.Result = this.DataBase.get(Request[0]) || null;
    } else {
      let ToReturn = [];
      Request.forEach(function(Name){
        ToReturn.push(this.DataBase.get(Name) || null);
      }.bind(this));
      Message.Result = ToReturn;
    }
    Child.Finished(Message);
  }
}<|endoftext|>


<commit_before>var tag_filter  = document.getElementById( 'tag_filter' );
var builds_div  = document.getElementById( 'builds' );
var add_form    = document.getElementById( 'add_form' );
var submit_form = document.getElementById( 'submit_form' );
var file_input  = document.getElementById( 'file_input' );
var add_btn     = document.getElementById( 'add_files_btn' );
var submit_btn  = document.getElementById( 'submit_files_btn' );
var file_box    = document.getElementById( 'file_container' );

function loadDMCC()
{
    builds_div.innerHTML = "Retrieving build rules. 0%";
    var builds_req = new XMLHttpRequest();
    builds_req.addEventListener( "progress", buildsProgress, false );
    builds_req.addEventListener( "load",     buildsComplete, false );
    builds_req.addEventListener( "error",    buildsFailed,   false );
    builds_req.addEventListener( "abort",    buildsCanceled, false );
    builds_req.open( "get", "build_rules.json" );
    builds_req.send();
}

// progress on transfers from the server to the client (downloads)
function buildsProgress( evt ) {
    if( evt.lengthComputable ) {
        var percentComplete = evt.loaded / evt.total;
        // console.log( percentComplete );
        builds_div.innerHTML = "Retrieving build rules. "+
            ( 100.0 * percentComplete ).toFixed( 0 ) +"%";
    }
    else {
        builds_div.innerHTML = "Retrieving build rules. ???%";
    }
}

function buildsComplete( evt ) {
    console.log( "The transfer is complete." );
    console.log( evt );
    console.log( this );
    builds = JSON.parse( this.responseText );
    console.log( builds );
    removeAllChildren( builds_div );
    for( var i = 0; i < builds.length; i++ )
    {
        var id = "build_rule_"+i;
        var lelem = document.createElement( "label" );
        lelem.for = id;
        lelem.className = "build-item";
        builds_div.appendChild( lelem );
        var ielem = document.createElement( "input" );
        ielem.id    = id;
        ielem.type  = "radio";
        ielem.name  = "build_rule";
        lelem.appendChild( ielem );
        var selem = document.createElement( "span" );
        selem.innerHTML = builds[i].path;
        lelem.appendChild( selem );
        console.log( ielem );
    }

// <input name="year" type="radio" value="F" onclick="alert('CS3')">

}

function buildsFailed( evt ) {
    alert("An error occurred while transferring the file.");
}

function buildsCanceled( evt ) {
    alert("The transfer has been canceled by the user.");
}

add_form.onsubmit = function( evt )
{
    console.log( evt );
    evt.preventDefault();

    var files = file_input.files;
    for( var i = 0; i < files.length; i++ )
    {
        var file_stuff = document.createElement( "p" );
        file_stuff.innerHTML = files[i].name;
        file_stuff.actual_file = files[i];
        file_box.appendChild( file_stuff );
    }
}

var submission_in_progress = false;

function got_check_id()
{
    console.log( "GOT IT" );
    console.log( this );
    if( this.status === 200 )
    {
        // File(s) uploaded.
        // uploadButton.innerHTML = 'Upload';
    }
    else
    {
        alert('An error occurred!');
        return;
    }

    var formData = new FormData();
    for( var i = 0; i < file_box.childNodes.length; i++ )
    {
        var elem = file_box.childNodes[i];
        console.log( file_box.childNodes[i] );
        formData.append( 'photos[]', elem.actual_file, elem.actual_file.name );
    }
}

submit_form.onsubmit = function( evt )
{
    console.log( evt );
    evt.preventDefault();

    var submission_in_progress = true;
    var new_req = new XMLHttpRequest();
    new_req.open( 'GET', 'new_req.php?file_count='+file_box.childNodes.length );
    new_req.onload = got_check_id;
    new_req.send();
}

/* Misc utils */

function removeAllChildren( elem )
{
    while( elem.firstChild )
    {
        elem.removeChild( elem.firstChild );
    }
}

function logFields( path, obj, objs )
{
    if( obj !== null && typeof( obj ) === 'object' )
    {
        if( objs.indexOf( obj ) > -1 )
        {
            return;
        }
        objs.push( obj );
        for( field in obj )
        {
            try {
                logFields( path + "." + field, obj[ field ], objs );
            }
            catch( e ) {
                console.log( path + "." + field + " MISSING" );
            }
        }
    }
    else
    {
        console.log( path + " > " + obj );
    }
}
<commit_msg>More js<commit_after>var tag_filter  = document.getElementById( 'tag_filter' );
var builds_div  = document.getElementById( 'builds' );
var add_form    = document.getElementById( 'add_form' );
var submit_form = document.getElementById( 'submit_form' );
var file_input  = document.getElementById( 'file_input' );
var add_btn     = document.getElementById( 'add_files_btn' );
var submit_btn  = document.getElementById( 'submit_files_btn' );
var file_box    = document.getElementById( 'file_container' );

function loadDMCC()
{
    builds_div.innerHTML = "Retrieving build rules. 0%";
    var builds_req = new XMLHttpRequest();
    builds_req.addEventListener( "progress", buildsProgress, false );
    builds_req.addEventListener( "load",     buildsComplete, false );
    builds_req.addEventListener( "error",    buildsFailed,   false );
    builds_req.addEventListener( "abort",    buildsCanceled, false );
    builds_req.open( "get", "build_rules.json" );
    builds_req.send();
}

// progress on transfers from the server to the client (downloads)
function buildsProgress( evt ) {
    if( evt.lengthComputable ) {
        var percentComplete = evt.loaded / evt.total;
        // console.log( percentComplete );
        builds_div.innerHTML = "Retrieving build rules. "+
            ( 100.0 * percentComplete ).toFixed( 0 ) +"%";
    }
    else {
        builds_div.innerHTML = "Retrieving build rules. ???%";
    }
}

function buildsFailed( evt ) {
    alert("An error occurred while transferring the file.");
}

function buildsCanceled( evt ) {
    alert("The transfer has been canceled by the user.");
}

function makeBuildSelectionCallback( elem )
{
    return function() { buildSelected( elem ); }
}

function buildsComplete( evt ) {
    console.log( "The transfer is complete." );
    console.log( evt );
    console.log( this );
    builds = JSON.parse( this.responseText );
    console.log( builds );
    removeAllChildren( builds_div );
    for( var i = 0; i < builds.length; i++ )
    {
        var id = "build_rule_"+i;
        var lelem = document.createElement( "label" );
        lelem.for = id;
        lelem.className = "build-item";
        var ielem = document.createElement( "input" );
        ielem.id    = id;
        ielem.type  = "radio";
        ielem.name  = "build_rule";
        ielem.build_path = builds[i].path;
        ielem.addEventListener( "click", makeBuildSelectionCallback( ielem ) );
        var selem = document.createElement( "span" );
        selem.innerHTML = builds[i].path;

        builds_div.appendChild( lelem );
        lelem.appendChild( ielem );
        lelem.appendChild( selem );
    }

// <input name="year" type="radio" value="F" onclick="alert('CS3')">

}

function buildSelected( elem )
{
    console.log( elem.build_path );
    console.log( this );
}

add_form.onsubmit = function( evt )
{
    console.log( evt );
    evt.preventDefault();

    var files = file_input.files;
    for( var i = 0; i < files.length; i++ )
    {
        var file_stuff = document.createElement( "p" );
        file_stuff.innerHTML = files[i].name;
        file_stuff.actual_file = files[i];
        file_box.appendChild( file_stuff );
    }
}

var submission_in_progress = false;

function got_check_id()
{
    console.log( "GOT IT" );
    console.log( this );
    if( this.status === 200 )
    {
        // File(s) uploaded.
        // uploadButton.innerHTML = 'Upload';
    }
    else
    {
        alert('An error occurred!');
        return;
    }

    var formData = new FormData();
    for( var i = 0; i < file_box.childNodes.length; i++ )
    {
        var elem = file_box.childNodes[i];
        console.log( file_box.childNodes[i] );
        formData.append( 'photos[]', elem.actual_file, elem.actual_file.name );
    }
}

submit_form.onsubmit = function( evt )
{
    console.log( evt );
    evt.preventDefault();

    var submission_in_progress = true;
    var new_req = new XMLHttpRequest();
    new_req.open( 'GET', 'new_req.php?file_count='+file_box.childNodes.length );
    new_req.onload = got_check_id;
    new_req.send();
}

/* Misc utils */

function removeAllChildren( elem )
{
    while( elem.firstChild )
    {
        elem.removeChild( elem.firstChild );
    }
}

function logFields( path, obj, objs )
{
    if( obj !== null && typeof( obj ) === 'object' )
    {
        if( objs.indexOf( obj ) > -1 )
        {
            return;
        }
        objs.push( obj );
        for( field in obj )
        {
            try {
                logFields( path + "." + field, obj[ field ], objs );
            }
            catch( e ) {
                console.log( path + "." + field + " MISSING" );
            }
        }
    }
    else
    {
        console.log( path + " > " + obj );
    }
}
<|endoftext|>