<commit_before>'use strict';

var Raygun = require('raygun');
var assert = require('assert-plus');

function BunyanRaygun(opt){
  assert.object(opt, 'options');
  assert.string(opt.apiKey, 'options.apiKey');
  assert.optionalFunc(opt.user, 'options.user');

  this._client = new Raygun.Client();
  this._client.init(opt);

  if (opt.user) {
    this._client.user = opt.user;
  }
}

BunyanRaygun.prototype.write = function(entry) {
  assert.object(entry, 'entry');

  if (entry.err) {
    this._client.send(entry.err || entry, undefined, undefined, entry.req);
  }
};

module.exports = BunyanRaygun;
<commit_msg>only log errors<commit_after>'use strict';

var Raygun = require('raygun');
var assert = require('assert-plus');

function BunyanRaygun(opt){
  assert.object(opt, 'options');
  assert.string(opt.apiKey, 'options.apiKey');
  assert.optionalFunc(opt.user, 'options.user');

  this._client = new Raygun.Client();
  this._client.init(opt);

  if (opt.user) {
    this._client.user = opt.user;
  }
}

BunyanRaygun.prototype.write = function(entry) {
  assert.object(entry, 'entry');

  if (entry.err) {
    this._client.send(entry.err, undefined, undefined, entry.req);
  }
};

module.exports = BunyanRaygun;
<|endoftext|>


<commit_before>module.exports = HTTPCallback

var EventEmitter = require('events').EventEmitter
var concat = require('concat-stream')
var http = require('http')
var https = require('https')
var inherits = require('util').inherits
var retry = require('retry')
var url = require('url')

function HTTPCallback(options) {
  options = ( options || {} )
  this.retryOptions =  ( 'retry' in options ? options.retry : { } )
  this.listeners = { }
  EventEmitter.call(this) }

inherits(HTTPCallback, EventEmitter)

var prototype = HTTPCallback.prototype

// An HTTP request handler that registers HTTP callback endpoints. Suitable for
// use with the core Node.js HTTP module.
prototype.handler = function(request, response) {
  // TODO Check that the callback registration request comes from the same host as the hook target.
  var self = this
  request.pipe(concat(function(body) {
    var parsedURL = parseBody(body.toString())
    var href = parsedURL.href
    if (validBody(parsedURL)) {
      // Store the provided callback.
      self.listeners[href] = parsedURL
      // Respond 201
      response.statusCode = 201
      response.end()
      // Emit an event.
      self.emit('registration', parsedURL) }
    else {
      // Respond 400.
      response.statusCode = 400
      response.end('Invalid URL')
      // Emit an event.
      self.emit('badrequest', parsedURL) } })) }

// Helper function to parse HTTP request bodies sent to endpoints to register
// callback URLS.
function parseBody(string) {
  // Freeze the object, to prevent event listeners from mutating it.
  return Object.freeze(url.parse(string)) }

// Helper function to check whether an HTTP request body with a callback URL
// includes all the URL components needed to make callback HTTP requests.
function validBody(parsedURL) {
  var protocol = parsedURL.protocol
  return (
    ( protocol === 'https:' || protocol === 'http:' ) &&
    parsedURL.hostname ) }

// Send data to all registered HTTP callback endpoints, passing a function that
// will write data to the bodies of requests sent.
prototype.send = function(dataCallback) {
  var self = this
  self._forEachListener(function(listener) {
    self._sendDataToListener(dataCallback, listener, function(error) {
      if (error) {
        self.emit('failure', error)
        self._deregister(listener.href) } }) }) }

// Helper function to call back to a specific HTTP endpoint, retrying according
// to configuration and emitting events.
prototype._sendDataToListener = function(dataCallback, listener, errback) {
  var self = this
  var protocol = ( listener.protocol === 'https:' ? https : http )
  var operation = retry.operation(self.retryOptions)
  operation.attempt(function(count) {
    self.emit('attempt', listener.href, count)
    var request = protocol.request(parsedURLToRequestOptions(listener))
      .once('response', function() {
        // TODO treat error responses as failures
        self.emit('success', listener.href)
        errback() })
      .once('error', function(error) {
        if (!operation.retry(error)) {
          errback(operation.mainError()) } })
    dataCallback(request) }) }

// Helper functionto iterate registered HTTP callback endpoints.
prototype._forEachListener = function(callback) {
  var listeners = this.listeners
  Object.keys(listeners).forEach(function(href) {
    callback(listeners[href]) }) }

// Helper function to convert objects created with url.parse into options
// arguments for http.request when sending callback requests.
function parsedURLToRequestOptions(parsedURL) {
  return {
    auth: parsedURL.auth,
    host: parsedURL.hostname,
    method: 'POST',
    path: ( parsedURL.pathname || '/' ),
    port: ( parsedURL.port || 80 ),
    query: parsedURL.query } }

// Helper function to deregister an HTTP callback endpoint.
prototype._deregister = function(href) {
  delete this.listeners[href]
  this.emit('deregistration', href) }

// Returns an array of all HREFs of registered callback endpoints.
prototype.callbackListeners = function() {
  return Object.keys(this.listeners) }
<commit_msg>Correctly infer port for HTTPS callbacks<commit_after>module.exports = HTTPCallback

var EventEmitter = require('events').EventEmitter
var concat = require('concat-stream')
var http = require('http')
var https = require('https')
var inherits = require('util').inherits
var retry = require('retry')
var url = require('url')

function HTTPCallback(options) {
  options = ( options || {} )
  this.retryOptions =  ( 'retry' in options ? options.retry : { } )
  this.listeners = { }
  EventEmitter.call(this) }

inherits(HTTPCallback, EventEmitter)

var prototype = HTTPCallback.prototype

// An HTTP request handler that registers HTTP callback endpoints. Suitable for
// use with the core Node.js HTTP module.
prototype.handler = function(request, response) {
  // TODO Check that the callback registration request comes from the same host as the hook target.
  var self = this
  request.pipe(concat(function(body) {
    var parsedURL = parseBody(body.toString())
    var href = parsedURL.href
    if (validBody(parsedURL)) {
      // Store the provided callback.
      self.listeners[href] = parsedURL
      // Respond 201
      response.statusCode = 201
      response.end()
      // Emit an event.
      self.emit('registration', parsedURL) }
    else {
      // Respond 400.
      response.statusCode = 400
      response.end('Invalid URL')
      // Emit an event.
      self.emit('badrequest', parsedURL) } })) }

// Helper function to parse HTTP request bodies sent to endpoints to register
// callback URLS.
function parseBody(string) {
  // Freeze the object, to prevent event listeners from mutating it.
  return Object.freeze(url.parse(string)) }

// Helper function to check whether an HTTP request body with a callback URL
// includes all the URL components needed to make callback HTTP requests.
function validBody(parsedURL) {
  var protocol = parsedURL.protocol
  return (
    ( protocol === 'https:' || protocol === 'http:' ) &&
    parsedURL.hostname ) }

// Send data to all registered HTTP callback endpoints, passing a function that
// will write data to the bodies of requests sent.
prototype.send = function(dataCallback) {
  var self = this
  self._forEachListener(function(listener) {
    self._sendDataToListener(dataCallback, listener, function(error) {
      if (error) {
        self.emit('failure', error)
        self._deregister(listener.href) } }) }) }

// Helper function to call back to a specific HTTP endpoint, retrying according
// to configuration and emitting events.
prototype._sendDataToListener = function(dataCallback, listener, errback) {
  var self = this
  var useHTTPS = ( listener.protocol === 'https:' )
  var protocol = ( useHTTPS ? https : http )
  var operation = retry.operation(self.retryOptions)
  operation.attempt(function(count) {
    self.emit('attempt', listener.href, count)
    var options = parsedURLToRequestOptions(listener, useHTTPS)
    var request = protocol.request(options)
      .once('response', function() {
        // TODO treat error responses as failures
        self.emit('success', listener.href)
        errback() })
      .once('error', function(error) {
        if (!operation.retry(error)) {
          errback(operation.mainError()) } })
    dataCallback(request) }) }

// Helper functionto iterate registered HTTP callback endpoints.
prototype._forEachListener = function(callback) {
  var listeners = this.listeners
  Object.keys(listeners).forEach(function(href) {
    callback(listeners[href]) }) }

// Helper function to convert objects created with url.parse into options
// arguments for http.request when sending callback requests.
function parsedURLToRequestOptions(parsedURL, useHTTPS) {
  return {
    auth: parsedURL.auth,
    host: parsedURL.hostname,
    method: 'POST',
    path: ( parsedURL.pathname || ( useHTTPS ? 443 : 80 ) ),
    port: ( parsedURL.port || 80 ),
    query: parsedURL.query } }

// Helper function to deregister an HTTP callback endpoint.
prototype._deregister = function(href) {
  delete this.listeners[href]
  this.emit('deregistration', href) }

// Returns an array of all HREFs of registered callback endpoints.
prototype.callbackListeners = function() {
  return Object.keys(this.listeners) }
<|endoftext|>


<commit_before>/**
 * GitBit Bot for Slack !
 * @author: Vasu Jain
 */

// Libraries
var https = require('https');
var BotConfig = require('./config.json');
//var beepboop = require('beepboop-botkit').start(controller, { debug: true });

var authTokenEncrypted = BotConfig.auth_token;
//var authTokenDecrypted = "token " + Buffer.from(authTokenEncrypted, 'base64').toString("ascii");

// For Node.js v5.11.1 and below
var buf = new Buffer(authTokenEncrypted, 'base64');
var authTokenDecrypted = "token " + buf.toString("ascii");
var colors = ['green', 'red', 'blue', 'yellow'];

function onInstallation(bot, installer) {
    if (installer) {
        bot.startPrivateConversation({
            user: installer
        }, function(err, convo) {
            if (err) {
                console.log(err);
            } else {
                convo.say('I am GitBit bot that has just joined your team');
                convo.say('You must now /invite me to a channel so that I can be of use!');
            }
        });
    }
}

// Configure the persistence options
var config = {};
if (process.env.MONGOLAB_URI) {
    var BotkitStorage = require('botkit-storage-mongo');
    config = {
        storage: BotkitStorage({
            mongoUri: process.env.MONGOLAB_URI
        }),
    };
} else {
    config = {
        json_file_store: ((process.env.TOKEN) ? './db_slack_bot_ci/' : './db_slack_bot_a/'), //use a different name if an app or CI
    };
}

////if (process.env.TOKEN || process.env.SLACK_TOKEN) {
//    //Treat this as a custom integration
//    var customIntegration = require('./lib/custom_integrations');
//    var token = (process.env.TOKEN) ? process.env.TOKEN : process.env.SLACK_TOKEN;
//    var controller = customIntegration.configure(token, config, onInstallation);
////} else if (process.env.CLIENT_ID && process.env.CLIENT_SECRET && process.env.PORT) {
//    //Treat this as an app
//    var app = require('./lib/apps');
////    var controller = app.configure(process.env.PORT, process.env.CLIENT_ID, process.env.CLIENT_SECRET, config, onInstallation);
////} else {
////    console.log('Error: If this is a custom integration, please specify TOKEN in the environment. If this is an app, please specify CLIENTID, CLIENTSECRET, and PORT in the environment');
////    process.exit(1);
////}

//var app = require('./lib/apps');
//var customIntegration = require('./lib/custom_integrations');
//var token = (process.env.TOKEN) ? process.env.TOKEN : process.env.SLACK_TOKEN;
//var controller = customIntegration.configure(token, config, onInstallation);

if (process.env.TOKEN || process.env.SLACK_TOKEN) {
   //Treat this as a custom integration
   var customIntegration = require('./lib/custom_integrations');
   var token = (process.env.TOKEN) ? process.env.TOKEN : process.env.SLACK_TOKEN;
   var controller = customIntegration.configure(token, config, onInstallation);
} else {
   //Treat this as an app
   var app = require('./lib/apps');
   var controller = app.configure(config, onInstallation);
}

/**
 * A demonstration for how to handle websocket events. In this case, just log when we have and have not
 * been disconnected from the websocket. In the future, it would be super awesome to be able to specify
 * a reconnect policy, and do reconnections automatically. In the meantime, we aren't going to attempt reconnects,
 * WHICH IS A B0RKED WAY TO HANDLE BEING DISCONNECTED. So we need to fix this.
 *
 * TODO: fixed b0rked reconnect behavior
 */
// Handle events related to the websocket connection to Slack
controller.on('rtm_open', function(bot) {
    console.log('** The RTM api just connected!');
});

controller.on('rtm_close', function(bot) {
    console.log('** The RTM api just closed');
    // you may want to attempt to re-open
});

// Core bot logic !
controller.on('bot_channel_join', function(bot, message) {
    bot.reply(message, "Thank you for inviting me to your Slack Channel!")
});

controller.hears(['hello', 'hi', 'greetings'], ['direct_mention', 'mention', 'direct_message'], function(bot, message) {
    bot.reply(message, 'Hello!');
});

controller.hears('pr (.*)', ['direct_mention', 'mention', 'direct_message'], function(bot, message) {
    var repo = message.match[1];
    if (typeof repo !== 'undefined' && repo) {
        var githubRepo = BotConfig.repos[repo];
        var flagZeroPRComment = false;
        if (githubRepo) {
            flagZeroPRComment = true;
            githubGetPullRequest(githubRepo, bot, message, flagZeroPRComment);
        } else if (repo == 'custom') {
            for (var r in BotConfig.repos) {
                githubGetPullRequest(BotConfig.repos[r], bot, message, flagZeroPRComment);
            }
        } else if (repo == 'all') {
            getListOfAllGithubReposInOrg(bot, message);
        } else {
            bot.reply(message, "Invalid Repo or Repo not configured");
        }
    } else {
        bot.reply(message, "Repo is undefined -- Invalid request or Repo not configured");
    }
});

// Make a POST call to GITHUB API to fetch all OPEN PR's
function githubGetPullRequest(repo, bot, message, flagZeroPRComment) {
    console.log("Making a POST call to GITHUB API to fetch all OPEN PR's...");
    var request = require('request');
    var url = BotConfig.github_api_url + 'repos/' + BotConfig.repo_org + repo + '/pulls?state=open';
    console.log(url);
    request({
        headers: {
            'Accept': 'application/vnd.github.v3+json',
            'Authorization': authTokenDecrypted,
            'User-Agent': 'GitBit-slackbot'
        },
        uri: url,
        method: 'GET'
    }, function(err, res, body) {
        parseAndResponse(body, bot, message, repo, flagZeroPRComment);
    });
}

// Parse the pull response json and extract PR#, Title, User out of it.
function parseAndResponse(body, bot, message, repo, flagZeroPRComment) {
    console.log("Parsing the pull response json and extracting PR#, Title, User out of it...");
    var repoSource = BotConfig.repo_org + repo + " Open Pull Requests : ";
    var response = "";
    var obj = JSON.parse(body);
    var objLength = obj.length;
    if (objLength == 0) {
        if (!BotConfig.disable_zero_pr_repo) { //if false, then only display Repo with Zero PR
            response = repoSource;
            if (flagZeroPRComment) {
                response += "No open PR's @ the moment ! Are you guys coding ?"
            } else {
                response += "0."
            }
            bot.reply(message, response);
        }
    } else {
        for (var i = 0; i < objLength; i++) {
            response += "\nPR # " + obj[i].number + " - " + obj[i].title + " by " + obj[i].user.login;
        }
        bot.reply(message, {
            "attachments": [{
                "fallback": repoSource,
                "color": "#36a64f",
                "title": repoSource,
//                "title_link": BotConfig.github_api_url + 'repos/' + BotConfig.repo_org + repo ,
                "text": response
            }]
        });
    }
    console.log(response);
    console.log("parseAndResponse for " + repo + " with " + objLength + " PR'(s) executed successfully.");
}

// Getting list of all Github Repos in an Org. Can be 100+. For the initial phase only top 100 results will display
function getListOfAllGithubReposInOrg(bot, message) {
    console.log("Getting list of all Github Repos in an Org. Can be 100+....");
    var ghArray = new Array();
    var url = BotConfig.github_api_url + 'orgs/' + BotConfig.repo_org + 'repos?per_page=' + BotConfig.max_page_count;
    console.log(url);
    var request = require('request');
    request({
        headers: {
            'Accept': 'application/vnd.github.v3+json',
            'Authorization': authTokenDecrypted,
            'User-Agent': 'GitBit-slackbot'
        },
        uri: url,
        method: 'GET'
    }, function(err, res, body) {
        ghArray = constructAllGithubRepoObject(body, bot, message);
    });
    console.log("getListOfAllGithubReposInOrg executed successfully.\n");
}

// Parse the Org Repos response json and extracting Repo details out of it.
function constructAllGithubRepoObject(body, bot, message) {
    console.log("Parsing the Org Repos response json and extracting Repo details out of it...");
    var orgGithubRepo = new Array();
    var obj = JSON.parse(body);
    var objLength = obj.length;
    for (var i = 0; i < objLength; i++) {
        orgGithubRepo.push(obj[i].name);
        githubGetPullRequest(obj[i].name, bot, message, false);
    }
    console.log("constructAllGithubRepoObject executed successfully.\n");
}<commit_msg>updated auth<commit_after>/**
 * GitBit Bot for Slack !
 * @author: Vasu Jain
 */

// Libraries
var https = require('https');
var BotConfig = require('./config.json');
//var beepboop = require('beepboop-botkit').start(controller, { debug: true });

var authTokenEncrypted = BotConfig.auth_token;
//var authTokenDecrypted = "token " + Buffer.from(authTokenEncrypted, 'base64').toString("ascii");

// For Node.js v5.11.1 and below
var buf = new Buffer(authTokenEncrypted, 'base64');
var authTokenDecrypted = "token " + buf.toString("ascii");

function onInstallation(bot, installer) {
    if (installer) {
        bot.startPrivateConversation({
            user: installer
        }, function(err, convo) {
            if (err) {
                console.log(err);
            } else {
                convo.say('I am GitBit bot that has just joined your team');
                convo.say('You must now /invite me to a channel so that I can be of use!');
            }
        });
    }
}

// Configure the persistence options
var config = {};
if (process.env.MONGOLAB_URI) {
    var BotkitStorage = require('botkit-storage-mongo');
    config = {
        storage: BotkitStorage({
            mongoUri: process.env.MONGOLAB_URI
        }),
    };
} else {
    config = {
        json_file_store: ((process.env.TOKEN) ? './db_slack_bot_ci/' : './db_slack_bot_a/'), //use a different name if an app or CI
    };
}

if (process.env.TOKEN || process.env.SLACK_TOKEN) {
    console.log("custom integration");
   //Treat this as a custom integration
   var customIntegration = require('./lib/custom_integrations');
   var token = (process.env.TOKEN) ? process.env.TOKEN : process.env.SLACK_TOKEN;
   var controller = customIntegration.configure(token, config, onInstallation);
} else {
    console.log("multi team");
   //Treat this as an app
   var app = require('./lib/apps');
   var controller = app.configure(config, onInstallation);
}

/**
 * A demonstration for how to handle websocket events. In this case, just log when we have and have not
 * been disconnected from the websocket. In the future, it would be super awesome to be able to specify
 * a reconnect policy, and do reconnections automatically. In the meantime, we aren't going to attempt reconnects,
 * WHICH IS A B0RKED WAY TO HANDLE BEING DISCONNECTED. So we need to fix this.
 *
 * TODO: fixed b0rked reconnect behavior
 */
// Handle events related to the websocket connection to Slack
controller.on('rtm_open', function(bot) {
    console.log('** The RTM api just connected!');
});

controller.on('rtm_close', function(bot) {
    console.log('** The RTM api just closed');
    // you may want to attempt to re-open
});

// Core bot logic !
controller.on('bot_channel_join', function(bot, message) {
    bot.reply(message, "Thank you for inviting me to your Slack Channel!")
});

controller.hears(['hello', 'hi', 'greetings'], ['direct_mention', 'mention', 'direct_message'], function(bot, message) {
    bot.reply(message, 'Hello!');
});

controller.hears('pr (.*)', ['direct_mention', 'mention', 'direct_message'], function(bot, message) {
    var repo = message.match[1];
    if (typeof repo !== 'undefined' && repo) {
        var githubRepo = BotConfig.repos[repo];
        var flagZeroPRComment = false;
        if (githubRepo) {
            flagZeroPRComment = true;
            githubGetPullRequest(githubRepo, bot, message, flagZeroPRComment);
        } else if (repo == 'custom') {
            for (var r in BotConfig.repos) {
                githubGetPullRequest(BotConfig.repos[r], bot, message, flagZeroPRComment);
            }
        } else if (repo == 'all') {
            getListOfAllGithubReposInOrg(bot, message);
        } else {
            bot.reply(message, "Invalid Repo or Repo not configured");
        }
    } else {
        bot.reply(message, "Repo is undefined -- Invalid request or Repo not configured");
    }
});

// Make a POST call to GITHUB API to fetch all OPEN PR's
function githubGetPullRequest(repo, bot, message, flagZeroPRComment) {
    console.log("Making a POST call to GITHUB API to fetch all OPEN PR's...");
    var request = require('request');
    var url = BotConfig.github_api_url + 'repos/' + BotConfig.repo_org + repo + '/pulls?state=open';
    console.log(url);
    request({
        headers: {
            'Accept': 'application/vnd.github.v3+json',
            'Authorization': authTokenDecrypted,
            'User-Agent': 'GitBit-slackbot'
        },
        uri: url,
        method: 'GET'
    }, function(err, res, body) {
        parseAndResponse(body, bot, message, repo, flagZeroPRComment);
    });
}

// Parse the pull response json and extract PR#, Title, User out of it.
function parseAndResponse(body, bot, message, repo, flagZeroPRComment) {
    console.log("Parsing the pull response json and extracting PR#, Title, User out of it...");
    var repoSource = BotConfig.repo_org + repo + " Open Pull Requests : ";
    var response = "";
    var obj = JSON.parse(body);
    var objLength = obj.length;
    if (objLength == 0) {
        if (!BotConfig.disable_zero_pr_repo) { //if false, then only display Repo with Zero PR
            response = repoSource;
            if (flagZeroPRComment) {
                response += "No open PR's @ the moment ! Are you guys coding ?"
            } else {
                response += "0."
            }
            bot.reply(message, response);
        }
    } else {
        for (var i = 0; i < objLength; i++) {
            response += "\nPR # " + obj[i].number + " - " + obj[i].title + " by " + obj[i].user.login;
        }
        bot.reply(message, {
            "attachments": [{
                "fallback": repoSource,
                "color": "#36a64f",
                "title": repoSource,
//                "title_link": BotConfig.github_api_url + 'repos/' + BotConfig.repo_org + repo ,
                "text": response
            }]
        });
    }
    console.log(response);
    console.log("parseAndResponse for " + repo + " with " + objLength + " PR'(s) executed successfully.");
}

// Getting list of all Github Repos in an Org. Can be 100+. For the initial phase only top 100 results will display
function getListOfAllGithubReposInOrg(bot, message) {
    console.log("Getting list of all Github Repos in an Org. Can be 100+....");
    var ghArray = new Array();
    var url = BotConfig.github_api_url + 'orgs/' + BotConfig.repo_org + 'repos?per_page=' + BotConfig.max_page_count;
    console.log(url);
    var request = require('request');
    request({
        headers: {
            'Accept': 'application/vnd.github.v3+json',
            'Authorization': authTokenDecrypted,
            'User-Agent': 'GitBit-slackbot'
        },
        uri: url,
        method: 'GET'
    }, function(err, res, body) {
        ghArray = constructAllGithubRepoObject(body, bot, message);
    });
    console.log("getListOfAllGithubReposInOrg executed successfully.\n");
}

// Parse the Org Repos response json and extracting Repo details out of it.
function constructAllGithubRepoObject(body, bot, message) {
    console.log("Parsing the Org Repos response json and extracting Repo details out of it...");
    var orgGithubRepo = new Array();
    var obj = JSON.parse(body);
    var objLength = obj.length;
    for (var i = 0; i < objLength; i++) {
        orgGithubRepo.push(obj[i].name);
        githubGetPullRequest(obj[i].name, bot, message, false);
    }
    console.log("constructAllGithubRepoObject executed successfully.\n");
}<|endoftext|>


<commit_before>/*jslint devel: true*/
/*global perfis */

// variables
var project, beam, mk, concrete, steel;
var x, tsd, as, bw, fcd;
var betax23, betax34, epc, eps, epyd, fyd, Es, fck, fyk, fckForm, fykForm;
var d, h, cob, diamEstForm, diamLongForm, diamEst, diamLong, ncam, n;
var mk, msd, md;
var x2lim, x3lim, dominio;
var gamac, gamaf, gamas, s;
var result, situationD, situationLN;

var bitola = [
    {
        "diametro": 5.0,
        "area": 0.20
    },
    {
        "diametro": 6.3,
        "area": 0.315
    },
    {
        "diametro": 8.0,
        "area": 0.50
    },
    {
        "diametro": 10.0,
        "area": 0.80
    },
    {
        "diametro": 12.5,
        "area": 1.25
    },
    {
        "diametro": 16.0,
        "area": 2.0
    },
    {
        "diametro": 20.0,
        "area": 3.15
    },
    {
        "diametro": 25.0,
        "area": 5.0
    },
    {
        "diametro": 32.0,
        "area": 8.0
    },
    {
        "diametro": 40.0,
        "area": 12.50
    }

];

var steelProp = [
    {
        "steelType": "CA25",
        "fy": 250,
        "fu": 217.4,
        "E": 21000
    },
    {
        "steelType": "CA50",
        "fy": 500,
        "fu": 434.8,
        "E": 21000
    },
    {
        "steelType": "CA60",
        "fy": 600,
        "fu": 521.7,
        "E": 21000
    }
];

var concreteProp = [
    {
        "concType": "C20",
        "fckProp": 200
    },
    {
        "concType": "C25",
        "fckProp": 250
    },
    {
        "concType": "C30",
        "fckProp": 300
    },
    {
        "concType": "C35",
        "fckProp": 350
    },

    {
        "concType": "C40",
        "fckProp": 400
    },
    {
        "concType": "C45",
        "fckProp": 450
    },
    {
        "concType": "C50",
        "fckProp": 500
    }

];

function processFormCC() {
    "use strict";
    var i, j, k;

    // Getting values from HTML form inputs
    project = document.formCC.projectCC.value;
    /* if (project === "") {
        alert("Por favor preencha o campo Projeto.");
        console.log("Por favor preencha o campo Projeto.");
        return false;
    } */
    if (project === "") {
        project = "Exemplo 1";
    }

    beam = document.formCC.beamCC.value;
    /* if (beam === "") {
        alert("Por favor preencha o campo Viga.");
        console.log("Por favor preencha o campo Viga.");
        return false;
    } */
    if (beam === "") {
        beam = "V1";
    }

    h = Number(document.formCC.hCC.value);
    if (document.formCC.hCC.value === "" || isNaN(h)) {
        alert("Por favor preencha o campo Altura da Viga com números.");
        console.log("Por favor preencha o campo Altura da Viga.");
        return false;
    }

    bw = Number(document.formCC.bwCC.value);
    if (document.formCC.bwCC.value === "" || isNaN(bw)) {
        alert("Por favor preencha o campo Largura da Viga com números.");
        console.log("Por favor preencha o campo Largura da Viga.");
        return false;
    }

    ncam = Number(document.formCC.layerCC.value);
    if (document.formCC.layerCC.value === "" || isNaN(ncam)) {
        alert("Por favor preencha o campo Nº de Camadas com números.");
        console.log("Por favor preencha o campo Nº de Camadas.");
        return false;
    }

    if (Number.isInteger(ncam) === false) {
        alert("Por favor preencha o campo Nº de Camadas com números inteiros.");
        console.log("Por favor preencha o campo com valores inteiros.");
        return false;
    }

    n = Number(document.formCC.barsCC.value);
    if (document.formCC.barsCC.value === "" || isNaN(n)) {
        alert("Por favor preencha o campo Nº de Barras/Camadas com números.");
        console.log("Por favor preencha o campo Nº de Barras/Camadas.");
        return false;
    }

    if (Number.isInteger(n) === false) {
        alert("Por favor preencha o campo Nº de Barras/Camadas com números inteiros.");
        console.log("Por favor preencha o campo com valores inteiros.");
        return false;
    }

    mk = Number(document.formCC.mCC.value);
    if (document.formCC.mCC.value === "" || isNaN(mk)) {
        alert("Por favor preencha o campo Momento com números.");
        console.log("Por favor preencha o campo Momento.");
        return false;
    }

    concrete = concreteProp[(document.formCC.concreteCC.value)].concType;
    steel = steelProp[(document.formCC.steelCC.value)].steelType;
    diamLongForm = bitola[Number(document.formCC.longCC.value)].diametro;
    diamEstForm = bitola[Number(document.formCC.estCC.value)].diametro;
    gamac = Number(document.formCC.gamacCC.value);
    gamaf = Number(document.formCC.gamafCC.value);
    gamas = Number(document.formCC.gamasCC.value);
    s = Number(document.formCC.sCC.value);
    cob = Number(document.formCC.cobCC.value);

    // Getting bitolaLong properties
    i = Number(document.getElementById("bitolaLong").value);

    as = (bitola[i].area) * n * ncam;

    // Getting concrete properties
    j = Number(document.getElementById("concrete").value);

    fckForm = concreteProp[j].fckProp;

    // Getting steel properties
    k = Number(document.getElementById("steel").value);

    fykForm = steelProp[k].fy;
    Es = steelProp[k].E;

    // Converting Units
    fyk = fykForm / 10;
    fck = fckForm / 100;
    diamEst = diamEstForm / 10;
    diamLong = diamLongForm / 10;

    // Calculating parameters
    fcd = fck / gamac;
    fyd = fyk / gamas;
    tsd = fyd;
    epc = 3.5;
    eps = 10.0;

    // Calculating LN position
    x = (tsd * as) / (0.68 * bw * fcd);

    // Establishing Dominio limits
    betax23 = epc / (epc + eps);
    epyd = (fyd / Es) * 1000;
    betax34 = epc / (epc + epyd);

    // Calculating d (altura útil)

    d = h - (cob + diamEst + 0.5 * diamLong + ((ncam - 1) * (diamLong + s)));

    // Checking Dominio

    x2lim = betax23 * d;
    x3lim = betax34 * d;

    if (x > x2lim && x < x3lim) {
        dominio = "Domínio 3";
        situationD = "Aprovado";
    } else if (x < x2lim) {
        dominio = "Domínio 2";
        situationD = "Aprovado";
    } else if (x > x3lim) {
        dominio = "Domínio 4";
        situationD = "Reprovado";
    } else {
        dominio = "Error";
    }

    // Check x/d
    if (x / d <= 0.45) {
        situationLN = "Aprovada";
    } else {
        situationLN = "Reprovada";
    }

    // Calculating Bending
    md = 0.68 * bw * x * fcd * (d - 0.4 * x);

    // Results
    msd = mk * gamaf;
    if (msd <= md) {
        result = "Aprovada";
    } else {
        result = "Reprovada";
    }
    alert(result);
}

/*
    Cria um objeto bitola
*/
function criarBitola(nomeBitola, linhaBitola) {
    "use strict";
    var opcao = document.createElement("OPTION"),
        texto = document.createTextNode(nomeBitola);
    opcao.value = linhaBitola;
    opcao.appendChild(texto);
    return opcao;
}

var bitolaLista1 = document.getElementById("bitolaLong"),
    bitolaLista2 = document.getElementById("bitolaEst"),
    acoLista = document.getElementById("steel"),
    concretoLista = document.getElementById("concrete"),
    i;

for (i = 0; i < bitola.length; i += 1) {
    bitolaLista1.appendChild(criarBitola(bitola[i].diametro, i));
}

for (i = 0; i < bitola.length; i += 1) {
    bitolaLista2.appendChild(criarBitola(bitola[i].diametro, i));
}

function criarAco(nomeAco, linhaAco) {
    "use strict";
    var opcao = document.createElement("OPTION"),
        texto = document.createTextNode(nomeAco);
    opcao.value = linhaAco;
    opcao.appendChild(texto);
    return opcao;
}

for (i = 0; i < steelProp.length; i += 1) {
    acoLista.appendChild(criarAco(steelProp[i].steelType, i));
}

function criarConcreto(nomeConcreto, linhaConcreto) {
    "use strict";
    var opcao = document.createElement("OPTION"),
        texto = document.createTextNode(nomeConcreto);
    opcao.value = linhaConcreto;
    opcao.appendChild(texto);
    return opcao;
}

for (i = 0; i < concreteProp.length; i += 1) {
    concretoLista.appendChild(criarConcreto(concreteProp[i].concType, i));
}
<commit_msg>Update scriptCC.js<commit_after>/*jslint devel: true*/
/*global perfis */

// variables
var project, beam, mk, concrete, steel;
var x, tsd, as, bw, fcd;
var betax23, betax34, epc, eps, epyd, fyd, Es, fck, fyk, fckForm, fykForm;
var d, h, cob, diamEstForm, diamLongForm, diamEst, diamLong, ncam, n;
var mk, msd, md;
var x2lim, x3lim, dominio;
var gamac, gamaf, gamas, s;
var result, situationD, situationLN, situationAlturaUtil;

var bitola = [
    {
        "diametro": 5.0,
        "area": 0.20
    },
    {
        "diametro": 6.3,
        "area": 0.315
    },
    {
        "diametro": 8.0,
        "area": 0.50
    },
    {
        "diametro": 10.0,
        "area": 0.80
    },
    {
        "diametro": 12.5,
        "area": 1.25
    },
    {
        "diametro": 16.0,
        "area": 2.0
    },
    {
        "diametro": 20.0,
        "area": 3.15
    },
    {
        "diametro": 25.0,
        "area": 5.0
    },
    {
        "diametro": 32.0,
        "area": 8.0
    },
    {
        "diametro": 40.0,
        "area": 12.50
    }

];

var steelProp = [
    {
        "steelType": "CA25",
        "fy": 250,
        "fu": 217.4,
        "E": 21000
    },
    {
        "steelType": "CA50",
        "fy": 500,
        "fu": 434.8,
        "E": 21000
    },
    {
        "steelType": "CA60",
        "fy": 600,
        "fu": 521.7,
        "E": 21000
    }
];

var concreteProp = [
    {
        "concType": "C20",
        "fckProp": 200
    },
    {
        "concType": "C25",
        "fckProp": 250
    },
    {
        "concType": "C30",
        "fckProp": 300
    },
    {
        "concType": "C35",
        "fckProp": 350
    },

    {
        "concType": "C40",
        "fckProp": 400
    },
    {
        "concType": "C45",
        "fckProp": 450
    },
    {
        "concType": "C50",
        "fckProp": 500
    }

];

function processFormCC() {
    "use strict";
    var i, j, k;

    // Getting values from HTML form inputs
    project = document.formCC.projectCC.value;
    /* if (project === "") {
        alert("Por favor preencha o campo Projeto.");
        console.log("Por favor preencha o campo Projeto.");
        return false;
    } */
    if (project === "") {
        project = "Exemplo 1";
    }

    beam = document.formCC.beamCC.value;
    /* if (beam === "") {
        alert("Por favor preencha o campo Viga.");
        console.log("Por favor preencha o campo Viga.");
        return false;
    } */
    if (beam === "") {
        beam = "V1";
    }

    h = Number(document.formCC.hCC.value);
    if (document.formCC.hCC.value === "" || isNaN(h)) {
        alert("Por favor preencha o campo Altura da Viga com números.");
        console.log("Por favor preencha o campo Altura da Viga.");
        return false;
    }

    bw = Number(document.formCC.bwCC.value);
    if (document.formCC.bwCC.value === "" || isNaN(bw)) {
        alert("Por favor preencha o campo Largura da Viga com números.");
        console.log("Por favor preencha o campo Largura da Viga.");
        return false;
    }

    as = Number(document.formCC.asCC.value);
    if (document.formCC.asCC.value === "" || isNaN(as)) {
        alert("Por favor preencha o campo Área de Aço com números.");
        console.log("Por favor preencha o campo Área de Aço.");
        return false;
    }

    d = Number(document.formCC.dCC.value);
    if (document.formCC.dCC.value === "" || isNaN(d)) {
        alert("Por favor preencha o campo Altura Útil com números.");
        console.log("Por favor preencha o campo Altura Útil.");
        return false;
    }

    /* ncam = Number(document.formCC.layerCC.value);
    if (document.formCC.layerCC.value === "" || isNaN(ncam)) {
        alert("Por favor preencha o campo Nº de Camadas com números.");
        console.log("Por favor preencha o campo Nº de Camadas.");
        return false;
    }

    if (Number.isInteger(ncam) === false) {
        alert("Por favor preencha o campo Nº de Camadas com números inteiros.");
        console.log("Por favor preencha o campo com valores inteiros.");
        return false;
    }

    n = Number(document.formCC.barsCC.value);
    if (document.formCC.barsCC.value === "" || isNaN(n)) {
        alert("Por favor preencha o campo Nº de Barras/Camadas com números.");
        console.log("Por favor preencha o campo Nº de Barras/Camadas.");
        return false;
    }

    if (Number.isInteger(n) === false) {
        alert("Por favor preencha o campo Nº de Barras/Camadas com números inteiros.");
        console.log("Por favor preencha o campo com valores inteiros.");
        return false;
    } */

    mk = Number(document.formCC.mCC.value);
    if (document.formCC.mCC.value === "" || isNaN(mk)) {
        alert("Por favor preencha o campo Momento com números.");
        console.log("Por favor preencha o campo Momento.");
        return false;
    }

    concrete = concreteProp[(document.formCC.concreteCC.value)].concType;
    steel = steelProp[(document.formCC.steelCC.value)].steelType;
    /* diamLongForm = bitola[Number(document.formCC.longCC.value)].diametro;
    diamEstForm = bitola[Number(document.formCC.estCC.value)].diametro; */
    gamac = Number(document.formCC.gamacCC.value);
    gamaf = Number(document.formCC.gamafCC.value);
    gamas = Number(document.formCC.gamasCC.value);
    s = Number(document.formCC.sCC.value);
    cob = Number(document.formCC.cobCC.value);

    /*  // Getting bitolaLong properties
    i = Number(document.getElementById("bitolaLong").value);

    as = (bitola[i].area) * n * ncam; */

    // Getting concrete properties
    j = Number(document.getElementById("concrete").value);

    fckForm = concreteProp[j].fckProp;

    // Getting steel properties
    k = Number(document.getElementById("steel").value);

    fykForm = steelProp[k].fy;
    Es = steelProp[k].E;

    // Converting Units
    fyk = fykForm / 10;
    fck = fckForm / 100;
    /* diamEst = diamEstForm / 10;
    diamLong = diamLongForm / 10; */

    // Calculating parameters
    fcd = fck / gamac;
    fyd = fyk / gamas;
    tsd = fyd;
    epc = 3.5;
    eps = 10.0;

    // Calculating LN position
    x = (tsd * as) / (0.68 * bw * fcd);

    // Establishing Dominio limits
    betax23 = epc / (epc + eps);
    epyd = (fyd / Es) * 1000;
    betax34 = epc / (epc + epyd);

   /* // Calculating d (altura útil)

    d = h - (cob + diamEst + 0.5 * diamLong + ((ncam - 1) * (diamLong + s))); */

    // Verificação

    if (d <= h - cob - diamEst - 0.5 * diamLong) {
        situationAlturaUtil = "Coerente";
    } else {
        situationAlturaUtil = "Incoerente";
    }

    console.log(situationAlturaUtil);

    // Checking Dominio

    x2lim = betax23 * d;
    x3lim = betax34 * d;

    if (x > x2lim && x < x3lim) {
        dominio = "Domínio 3";
        situationD = "Aprovado";
    } else if (x < x2lim) {
        dominio = "Domínio 2";
        situationD = "Aprovado";
    } else if (x > x3lim) {
        dominio = "Domínio 4";
        situationD = "Reprovado";
    } else {
        dominio = "Error";
    }

    // Check x/d
    if (x / d <= 0.45) {
        situationLN = "Aprovada";
    } else {
        situationLN = "Reprovada";
    }

    // Calculating Bending
    md = 0.68 * bw * x * fcd * (d - 0.4 * x);

    // Results
    msd = mk * gamaf;
    if (msd <= md) {
        result = "Aprovada";
    } else {
        result = "Reprovada";
    }
    alert(result);
}

/*
    Cria um objeto bitola
*/
function criarBitola(nomeBitola, linhaBitola) {
    "use strict";
    var opcao = document.createElement("OPTION"),
        texto = document.createTextNode(nomeBitola);
    opcao.value = linhaBitola;
    opcao.appendChild(texto);
    return opcao;
}

var bitolaLista1 = document.getElementById("bitolaLong"),
    bitolaLista2 = document.getElementById("bitolaEst"),
    acoLista = document.getElementById("steel"),
    concretoLista = document.getElementById("concrete"),
    i;

for (i = 0; i < bitola.length; i += 1) {
    bitolaLista1.appendChild(criarBitola(bitola[i].diametro, i));
}

for (i = 0; i < bitola.length; i += 1) {
    bitolaLista2.appendChild(criarBitola(bitola[i].diametro, i));
}

function criarAco(nomeAco, linhaAco) {
    "use strict";
    var opcao = document.createElement("OPTION"),
        texto = document.createTextNode(nomeAco);
    opcao.value = linhaAco;
    opcao.appendChild(texto);
    return opcao;
}

for (i = 0; i < steelProp.length; i += 1) {
    acoLista.appendChild(criarAco(steelProp[i].steelType, i));
}

function criarConcreto(nomeConcreto, linhaConcreto) {
    "use strict";
    var opcao = document.createElement("OPTION"),
        texto = document.createTextNode(nomeConcreto);
    opcao.value = linhaConcreto;
    opcao.appendChild(texto);
    return opcao;
}

for (i = 0; i < concreteProp.length; i += 1) {
    concretoLista.appendChild(criarConcreto(concreteProp[i].concType, i));
}
<|endoftext|>


<commit_before>'use strict';

const path = require('path');
const groupBy = require('lodash/groupBy');
const cloneDeepWith = require('lodash/cloneDeepWith');

function identity (input) {
    return input;
}

function paginate (filePath, collection, fileName, files, iteratee) {
    const allPosts = collection.filter((colItem) => Boolean(colItem.date));
    const origFile = files[fileName];
    const ext      = path.extname(fileName);
    const baseName = filePath || fileName.substr(0, fileName.lastIndexOf(ext));

    const postsByYear = groupBy(allPosts, (post) => new Date(post.date).getFullYear());
    const years       = Object.keys(postsByYear).sort().reverse();
    const latestYear  = years[0];

    let last = origFile;
    let clone;

    // no posts had date field :(
    if (!years.length) {
        return;
    }

    origFile.pagination = {
        year: latestYear,
        posts: postsByYear[latestYear].map(iteratee)
    };

    years.forEach((year, idx) => {
        if (idx === 0) {
            return;
        }

        const posts = postsByYear[year];
        const cloneName = `${baseName}-${year}${ext}`;

        clone = cloneDeepWith(origFile, (value) => {
            if (Buffer.isBuffer(value)) {
                return value.slice();
            }
        });

        last.pagination.next = clone;
        clone.pagination.year = year;
        clone.pagination.prev = last;
        clone.pagination.posts = posts.map(iteratee);

        files[cloneName] = clone;

        last = clone;
    });
}

module.exports = function(opts) {
    const options = {iteratee: identity, ...opts};

    return (files, metalsmith, done) => {
        const metadata      = metalsmith.metadata();
        const {collections} = metadata;

        let colName;
        let file;
        let filePath;

        for (file in files) {
            if (Object.prototype.hasOwnProperty.call(files, file)) {
                colName = files[file].paginate;
                filePath = options.path;

                if (colName) {
                    if (filePath) {
                        filePath = filePath.replace(':collection', colName);
                    }

                    paginate(filePath, collections[colName], file, files, options.iteratee);
                }
            }
        }

        done();
    };
};
<commit_msg>Use `path.basename`.<commit_after>'use strict';

const path = require('path');
const groupBy = require('lodash/groupBy');
const cloneDeepWith = require('lodash/cloneDeepWith');

function identity (input) {
    return input;
}

function paginate (filePath, collection, fileName, files, iteratee) {
    const allPosts = collection.filter((colItem) => Boolean(colItem.date));
    const origFile = files[fileName];
    const ext      = path.extname(fileName);
    const baseName = filePath || path.basename(fileName, ext);

    const postsByYear = groupBy(allPosts, (post) => new Date(post.date).getFullYear());
    const years       = Object.keys(postsByYear).sort().reverse();
    const latestYear  = years[0];

    let last = origFile;
    let clone;

    // no posts had date field :(
    if (!years.length) {
        return;
    }

    origFile.pagination = {
        year: latestYear,
        posts: postsByYear[latestYear].map(iteratee)
    };

    years.forEach((year, idx) => {
        if (idx === 0) {
            return;
        }

        const posts = postsByYear[year];
        const cloneName = `${baseName}-${year}${ext}`;

        clone = cloneDeepWith(origFile, (value) => {
            if (Buffer.isBuffer(value)) {
                return value.slice();
            }
        });

        last.pagination.next = clone;
        clone.pagination.year = year;
        clone.pagination.prev = last;
        clone.pagination.posts = posts.map(iteratee);

        files[cloneName] = clone;

        last = clone;
    });
}

module.exports = function(opts) {
    const options = {iteratee: identity, ...opts};

    return (files, metalsmith, done) => {
        const metadata      = metalsmith.metadata();
        const {collections} = metadata;

        let colName;
        let file;
        let filePath;

        for (file in files) {
            if (Object.prototype.hasOwnProperty.call(files, file)) {
                colName = files[file].paginate;
                filePath = options.path;

                if (colName) {
                    if (filePath) {
                        filePath = filePath.replace(':collection', colName);
                    }

                    paginate(filePath, collections[colName], file, files, options.iteratee);
                }
            }
        }

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


<commit_before>/*jslint devel: true*/
/*global perfis */

// variables
var project, beam, vk, mk, lbForm, section, steel, fyForm, fuForm, EForm;
var ml, d, bf, tw, tf, h, dl, area, ix, wx, rx, zx, iy, wy, ry, zy, rt, it, mesa, alma, cw, u;
var fy, fu, E, aw, gama, gama1, cb, kv, lb, kc, tr, beta1, a, priority;
var lambV, lambpV, lambrV, vpl, vrd;
var mpl, lambA, lambpA, lambrA, mrA, mcrA, mrdA;
var lambM, lambpM, lambrM, mrM, mcrM, mrdM;
var lambT, lambpT, lambrT, mrT, mcrT, mrdT;
var vsd, msd, vrd, mrd, mrdOut, situationV, situationA, situationM, situationT, result;
var ratioDSV, ratioDSM, ratiopDSV, ratiopDSM;
var approved = [];
var suggestion = [];

var steelProp = [
    {
        "steelType": "ASTM A36/ MR250",
        "fy": 250,
        "fu": 400,
        "E": 200000
    },
    {
        "steelType": "ASTM A572 G50/ AR345",
        "fy": 345,
        "fu": 450,
        "E": 200000
    }
];

kv = 5; // "Enrijecedor" not available Kv = 5

function processFormDS() {
    "use strict";
    var i, j, contFamily;

    /* Clean suggestion array */
    suggestion = [];
    approved = [];

    // Getting project values from HTML form inputs

    project = document.formDS.projectDS.value;
    /* if (project === "") {
        alert("Por favor preencha o campo Projeto.");
     console.log("Por favor preencha o campo Projeto.");
        return false;
    } */
    if (project === "") {
        project = "Exemplo 1";
    }

    beam = document.formDS.beamDS.value;
    /* if (beam === "") {
        alert("Por favor preencha o campo Viga.");
        console.log("Por favor preencha o campo Viga.");
        return false;
    } */
    if (beam === "") {
        beam = "V1";
    }

    vk = Number(document.formDS.vDS.value);
    if (document.formDS.vDS.value === "" || isNaN(vk)) {
        alert("Por favor preencha o campo Cortante com números.");
        console.log("Por favor preencha o campo Cortante.");
        return false;
    }

    mk = Number(document.formDS.mDS.value);
    if (document.formDS.mDS.value === "" || isNaN(mk)) {
        alert("Por favor preencha o campo Momento com números.");
        console.log("Por favor preencha o campo Momento.");
        return false;
    }

    lbForm = Number(document.formDS.lbDS.value);
    if (document.formDS.lbDS.value === "" || isNaN(lbForm)) {
        alert("Por favor preencha o campo Distância entre travamentos laterais com números.");
        console.log("Por favor preencha o campo Distância entre travamentos laterais com números.");
        return false;
    }

    steel = steelProp[Number(document.formDS.typeS.value)].steelType;
    gama = Number(document.formDS.gama.value);
    gama1 = Number(document.formDS.gama1.value);
    cb = Number(document.formDS.cb.value);
    priority = document.formDS.priority.value;

    for (i = 0; i < perfis.length; i += 1) { //Looping through our available sections
        section = perfis[i].bitola;

        // START OF FUNCTION TO SAVE CHECK EACH SECTION

        // Getting section properties

        ml = perfis[i].ml;
        d = perfis[i].d;
        bf = perfis[i].bf;
        tw = perfis[i].tw;
        tf = perfis[i].tf;
        h = perfis[i].h;
        dl = perfis[i].dl;
        area = perfis[i].area;
        ix = perfis[i].ix;
        wx = perfis[i].wx;
        rx = perfis[i].rx;
        zx = perfis[i].zx;
        iy = perfis[i].iy;
        wy = perfis[i].wy;
        ry = perfis[i].ry;
        zy = perfis[i].zy;
        rt = perfis[i].rt;
        it = perfis[i].it;
        mesa = perfis[i].mesa;
        alma = perfis[i].alma;
        cw = perfis[i].cw;
        u = perfis[i].u;

        // Getting values from steel properties array
        j = Number(document.getElementById("acos").value);

        fyForm = steelProp[j].fy;
        fuForm = steelProp[j].fu;
        EForm = steelProp[j].E;

        // Calculating parameters
        aw = (d * tw) / 100;
        lb = lbForm * 100;
        fy = fyForm / 10;
        fu = fuForm / 10;
        E = EForm / 10;
        beta1 = (0.7 * fy * wx) / (E * it);
        kc = 4 / Math.sqrt(h / tw);
        tr = 0.3 * fy;

        // Shear Vrd
        lambV = h / tw;
        lambpV = (1.1 * Math.sqrt(kv * E / fy));
        lambrV = (1.37 * Math.sqrt(kv * E / fy));
        vpl = 0.6 * fy * aw;

        if (lambV <= lambpV) {
            situationV = "Caso 1";
        } else if (lambpV < lambV && lambV <= lambrV) {
            situationV = "Caso 2";
        } else if (lambrV < lambV) {
            situationV = "Caso 3";
        } else {
            situationV = "Error";
        }

        switch (situationV) {
        case "Caso 1":
            vrd = vpl / gama1;
            break;
        case "Caso 2":
            vrd = (lambpV / lambV) * (vpl / gama1);
            break;
        case "Caso 3":
            vrd = 1.24 * Math.pow(lambpV / lambV, 2) * (vpl / gama1);
            break;
        }

        // Bending
        //FLA
        mpl = zx * fy;
        lambA = dl / tw; // lambA = h / tw;
        lambpA = 3.76 * Math.sqrt(E / fy);
        lambrA = 5.7 * Math.sqrt(E / fy);

        if (lambA <= lambpA) {
            situationA = "Caso 1";
        } else if (lambpA < lambA && lambA <= lambrA) {
            situationA = "Caso 2";
        } else if (lambrA < lambA) {
            situationA = "Caso 3";
        } else {
            situationA = "Error";
        }

        switch (situationA) {
        case "Caso 1":
            mrdA = mpl / gama1;
            break;
        case "Caso 2":
            mrA = 0.7 * fy * wx;
            mrdA = (cb / gama1) * (mpl - ((mpl - mrA) * ((lambA - lambpA) / (lambrA - lambpA))));
            break;
        case "Caso 3":
            // mcrA = Anexo H
            mrdA = mcrA / gama1;
            break;
        }

        //FLM
        lambM = mesa;
        lambpM = 0.38 * Math.sqrt(E / fy);
        lambrM = 0.83 * Math.sqrt(E / (fy - tr));

        if (lambM <= lambpM) {
            situationM = "Caso 1";
        } else if (lambpM < lambM && lambM <= lambrM) {
            situationM = "Caso 2";
        } else if (lambrM < lambM) {
            situationM = "Caso 3";
        } else {
            situationM = "Error";
        }

        switch (situationM) {
        case "Caso 1":
            mrdM = mpl / gama1;
            break;
        case "Caso 2":
            mrM = 0.7 * fy * wx;
            mrdM = (cb / gama1) * (mpl - ((mpl - mrM) * ((lambM - lambpM) / (lambrM - lambpM))));
            break;
        case "Caso 3":
            mcrM = ((0.69 * E) / (lambM * lambM)) * wx;
            mrdM = mcrM / gama1;
            break;
        }

        // FLT
        lambT = lb / ry;
        lambpT = 1.76 * Math.sqrt(E / fy);
        lambrT = ((1.38 * Math.sqrt(iy * it)) / (ry * it * beta1)) * Math.sqrt(1 + Math.sqrt(1 + (27 * cw * beta1 * beta1) / iy));

        if (lambT <= lambpT) {
            situationT = "Caso 1";
        } else if (lambpT < lambT && lambT <= lambrT) {
            situationT = "Caso 2";
        } else if (lambrT < lambT) {
            situationT = "Caso 3";
        } else {
            situationT = "Error";
        }

        switch (situationT) {
        case "Caso 1":
            mrdT = mpl / gama1;
            break;
        case "Caso 2":
            mrT = 0.7 * fy * wx;
            mrdT = (cb / gama1) * (mpl - ((mpl - mrT) * ((lambT - lambpT) / (lambrT - lambpT))));
            break;
        case "Caso 3":
            mcrT = ((cb * Math.PI * Math.PI * E * iy) / Math.pow(lb, 2)) * Math.sqrt((cw / iy) * (1 + 0.039 * (it * lb * lb) / cw));
            mrdT = mcrT / gama1;
            break;
        }

        //Compare & Results
        vsd = vk * gama;
        msd = mk * gama;
        mrd = Math.min(mrdA, mrdM, mrdT);
        mrdOut = mrd / 100;
        ratioDSV = vsd / vrd;
        ratioDSM = msd / mrdOut;
        ratiopDSV = ratioDSV * 100;
        ratiopDSM = ratioDSM * 100;

        if (vsd <= vrd && msd <= mrdOut) {
            result = "OK";
            approved.push({    // saves to a list of approved sections
                "perfil": perfis[i],
                "vrd": vrd,
                "mrdOut": mrdOut,
                "ratioDSV": ratioDSV,
                "ratioDSM": ratioDSM,
                "ratiopDSV": ratiopDSV,
                "ratiopDSM": ratiopDSM
            });
        } else {
            result = "Não OK";
        }

     // END OF FUNCTION TO SAVE CHECK EACH SECTION

    }

/*
    APPROVED: Printing a log to check
*/

    for (i = 0; i < approved.length; i += 1) { //Log of approved
        console.log(approved[i]);
    }

/*
    Suggestion list
*/
    contFamily = [];
    contFamily[610] = 0;
    contFamily.fill(0);

    switch (priority) {
    case "Maior aproveitamento quanto ao Esforço Cortante":
        approved.sort(function (a, b) {
            return b.ratioDSV - a.ratioDSV;
        });
        //approved.reverse();
        for (i = 0; i < 5; i += 1) {
            suggestion[i] = approved[i];
        }
        break;
    case "Maior aproveitamento quanto ao Momento Fletor":
        approved.sort(function (a, b) {
            return b.ratioDSM - a.ratioDSM;
        });
        //approved.reverse();
        for (i = 0; i < 5; i += 1) {
            suggestion[i] = approved[i];
        }
        break;
    case "Menor base":
        approved.sort(function (a, b) {
            return a.perfil.bf - b.perfil.bf;
        });
        for (i = 0; i < 5; i += 1) {
            suggestion[i] = approved[i];
        }
        break;
    case "Menor altura":
        approved.sort(function (a, b) {
            return a.perfil.d - b.perfil.d;
        });
        for (i = 0; i < 5; i += 1) {
            suggestion[i] = approved[i];
        }
        break;
    case "Menor massa linear em cada família W/HP": //incompleto
        approved.sort(function (a, b) {
            return a.perfil.ml - b.perfil.ml;
        });
        for (i = 0; i < approved.length; i += 1) {
            if (contFamily[approved[i].perfil.family] === 0) {
                suggestion.push(approved[i]);
                contFamily[approved[i].perfil.family] = 1;
            }
        }
        break;
    case "Menor massa linear":
        approved.sort(function (a, b) {
            return a.perfil.ml - b.perfil.ml;
        });
        for (i = 0; i < 5; i += 1) {
            suggestion[i] = approved[i];
        }
        break;
    }

/*
    SUGGESTION: Printing a log to check
*/

    for (i = 0; i < suggestion.length; i += 1) { //Log of approved
        console.log(suggestion[i]);
    }

}

/*
    Cria um objeto aco
*/

var acoLista = document.getElementById("acos"),
    i;

function criarAco(nomeAco, linhaAco) {
    "use strict";
    var opcao = document.createElement("OPTION"),
        texto = document.createTextNode(nomeAco);
    opcao.value = linhaAco;
    opcao.appendChild(texto);
    return opcao;
}

for (i = 0; i < steelProp.length; i += 1) {
    acoLista.appendChild(criarAco(steelProp[i].steelType, i));
}
<commit_msg>Update scriptDS.js<commit_after>/*jslint devel: true*/
/*global perfis */

// variables
var project, beam, vk, mk, lbForm, section, steel, fyForm, fuForm, EForm;
var ml, d, bf, tw, tf, h, dl, area, ix, wx, rx, zx, iy, wy, ry, zy, rt, it, mesa, alma, cw, u;
var fy, fu, E, aw, gama, gama1, cb, kv, lb, kc, tr, beta1, a, priority;
var lambV, lambpV, lambrV, vpl, vrd;
var mpl, lambA, lambpA, lambrA, mrA, mcrA, mrdA;
var lambM, lambpM, lambrM, mrM, mcrM, mrdM;
var lambT, lambpT, lambrT, mrT, mcrT, mrdT;
var vsd, msd, vrd, mrd, mrdOut, situationV, situationA, situationM, situationT, result;
var ratioDSV, ratioDSM, ratiopDSV, ratiopDSM;
var approved = [];
var suggestion = [];

var steelProp = [
    {
        "steelType": "ASTM A36/ MR250",
        "fy": 250,
        "fu": 400,
        "E": 200000
    },
    {
        "steelType": "ASTM A572 G50/ AR345",
        "fy": 345,
        "fu": 450,
        "E": 200000
    }
];

kv = 5; // "Enrijecedor" not available Kv = 5

function processFormDS() {
    "use strict";
    var i, j, contFamily;

    /* Clean suggestion array */
    suggestion = [];
    approved = [];

    // Getting project values from HTML form inputs

    project = document.formDS.projectDS.value;
    /* if (project === "") {
        alert("Por favor preencha o campo Projeto.");
     console.log("Por favor preencha o campo Projeto.");
        return false;
    } */
    if (project === "") {
        project = "Exemplo 1";
    }

    beam = document.formDS.beamDS.value;
    /* if (beam === "") {
        alert("Por favor preencha o campo Viga.");
        console.log("Por favor preencha o campo Viga.");
        return false;
    } */
    if (beam === "") {
        beam = "V1";
    }

    vk = Number(document.formDS.vDS.value);
    if (document.formDS.vDS.value === "" || isNaN(vk)) {
        alert("Por favor preencha o campo Cortante com números.");
        console.log("Por favor preencha o campo Cortante.");
        return false;
    }

    mk = Number(document.formDS.mDS.value);
    if (document.formDS.mDS.value === "" || isNaN(mk)) {
        alert("Por favor preencha o campo Momento com números.");
        console.log("Por favor preencha o campo Momento.");
        return false;
    }

    lbForm = Number(document.formDS.lbDS.value);
    if (document.formDS.lbDS.value === "" || isNaN(lbForm)) {
        alert("Por favor preencha o campo Distância entre travamentos laterais com números.");
        console.log("Por favor preencha o campo Distância entre travamentos laterais com números.");
        return false;
    }

    steel = steelProp[Number(document.formDS.typeS.value)].steelType;
    gama = Number(document.formDS.gama.value);
    gama1 = Number(document.formDS.gama1.value);
    cb = Number(document.formDS.cb.value);
    priority = document.formDS.priority.value;

    for (i = 0; i < perfis.length; i += 1) { //Looping through our available sections
        section = perfis[i].bitola;

        // START OF FUNCTION TO SAVE CHECK EACH SECTION

        // Getting section properties

        ml = perfis[i].ml;
        d = perfis[i].d;
        bf = perfis[i].bf;
        tw = perfis[i].tw;
        tf = perfis[i].tf;
        h = perfis[i].h;
        dl = perfis[i].dl;
        area = perfis[i].area;
        ix = perfis[i].ix;
        wx = perfis[i].wx;
        rx = perfis[i].rx;
        zx = perfis[i].zx;
        iy = perfis[i].iy;
        wy = perfis[i].wy;
        ry = perfis[i].ry;
        zy = perfis[i].zy;
        rt = perfis[i].rt;
        it = perfis[i].it;
        mesa = perfis[i].mesa;
        alma = perfis[i].alma;
        cw = perfis[i].cw;
        u = perfis[i].u;

        // Getting values from steel properties array
        j = Number(document.getElementById("acos").value);

        fyForm = steelProp[j].fy;
        fuForm = steelProp[j].fu;
        EForm = steelProp[j].E;

        // Calculating parameters
        aw = (d * tw) / 100;
        lb = lbForm * 100;
        fy = fyForm / 10;
        fu = fuForm / 10;
        E = EForm / 10;
        beta1 = (0.7 * fy * wx) / (E * it);
        kc = 4 / Math.sqrt(h / tw);
        tr = 0.3 * fy;

        // Shear Vrd
        lambV = h / tw;
        lambpV = (1.1 * Math.sqrt(kv * E / fy));
        lambrV = (1.37 * Math.sqrt(kv * E / fy));
        vpl = 0.6 * fy * aw;

        if (lambV <= lambpV) {
            situationV = "Caso 1";
        } else if (lambpV < lambV && lambV <= lambrV) {
            situationV = "Caso 2";
        } else if (lambrV < lambV) {
            situationV = "Caso 3";
        } else {
            situationV = "Error";
        }

        switch (situationV) {
        case "Caso 1":
            vrd = vpl / gama1;
            break;
        case "Caso 2":
            vrd = (lambpV / lambV) * (vpl / gama1);
            break;
        case "Caso 3":
            vrd = 1.24 * Math.pow(lambpV / lambV, 2) * (vpl / gama1);
            break;
        }

        // Bending
        //FLA
        mpl = zx * fy;
        lambA = dl / tw; // lambA = h / tw;
        lambpA = 3.76 * Math.sqrt(E / fy);
        lambrA = 5.7 * Math.sqrt(E / fy);

        if (lambA <= lambpA) {
            situationA = "Caso 1";
        } else if (lambpA < lambA && lambA <= lambrA) {
            situationA = "Caso 2";
        } else if (lambrA < lambA) {
            situationA = "Caso 3";
        } else {
            situationA = "Error";
        }

        switch (situationA) {
        case "Caso 1":
            mrdA = mpl / gama1;
            break;
        case "Caso 2":
            mrA = 0.7 * fy * wx;
            mrdA = (cb / gama1) * (mpl - ((mpl - mrA) * ((lambA - lambpA) / (lambrA - lambpA))));
            break;
        case "Caso 3":
            // mcrA = Anexo H
            mrdA = mcrA / gama1;
            break;
        }

        //FLM
        lambM = mesa;
        lambpM = 0.38 * Math.sqrt(E / fy);
        lambrM = 0.83 * Math.sqrt(E / (fy - tr));

        if (lambM <= lambpM) {
            situationM = "Caso 1";
        } else if (lambpM < lambM && lambM <= lambrM) {
            situationM = "Caso 2";
        } else if (lambrM < lambM) {
            situationM = "Caso 3";
        } else {
            situationM = "Error";
        }

        switch (situationM) {
        case "Caso 1":
            mrdM = mpl / gama1;
            break;
        case "Caso 2":
            mrM = 0.7 * fy * wx;
            mrdM = (cb / gama1) * (mpl - ((mpl - mrM) * ((lambM - lambpM) / (lambrM - lambpM))));
            break;
        case "Caso 3":
            mcrM = ((0.69 * E) / (lambM * lambM)) * wx;
            mrdM = mcrM / gama1;
            break;
        }

        // FLT
        lambT = lb / ry;
        lambpT = 1.76 * Math.sqrt(E / fy);
        lambrT = ((1.38 * Math.sqrt(iy * it)) / (ry * it * beta1)) * Math.sqrt(1 + Math.sqrt(1 + (27 * cw * beta1 * beta1) / iy));

        if (lambT <= lambpT) {
            situationT = "Caso 1";
        } else if (lambpT < lambT && lambT <= lambrT) {
            situationT = "Caso 2";
        } else if (lambrT < lambT) {
            situationT = "Caso 3";
        } else {
            situationT = "Error";
        }

        switch (situationT) {
        case "Caso 1":
            mrdT = mpl / gama1;
            break;
        case "Caso 2":
            mrT = 0.7 * fy * wx;
            mrdT = (cb / gama1) * (mpl - ((mpl - mrT) * ((lambT - lambpT) / (lambrT - lambpT))));
            break;
        case "Caso 3":
            mcrT = ((cb * Math.PI * Math.PI * E * iy) / Math.pow(lb, 2)) * Math.sqrt((cw / iy) * (1 + 0.039 * (it * lb * lb) / cw));
            mrdT = mcrT / gama1;
            break;
        }

        //Compare & Results
        vsd = vk * gama;
        msd = mk * gama;
        mrd = Math.min(mrdA, mrdM, mrdT);
        mrdOut = mrd / 100;
        ratioDSV = vsd / vrd;
        ratioDSM = msd / mrdOut;
        ratiopDSV = ratioDSV * 100;
        ratiopDSM = ratioDSM * 100;

        if (vsd <= vrd && msd <= mrdOut) {
            result = "OK";
            approved.push({    // saves to a list of approved sections
                "perfil": perfis[i],
                "vrd": vrd,
                "mrdOut": mrdOut,
                "ratioDSV": ratioDSV,
                "ratioDSM": ratioDSM,
                "ratiopDSV": ratiopDSV,
                "ratiopDSM": ratiopDSM
            });
        } else {
            result = "Não OK";
        }

     // END OF FUNCTION TO SAVE CHECK EACH SECTION

    }

/*
    APPROVED: Printing a log to check
*/

    for (i = 0; i < approved.length; i += 1) { //Log of approved
        console.log(approved[i]);
    }

/*
    Suggestion list
*/
    contFamily = [];
    contFamily[610] = 0;
    contFamily.fill(0);

    switch (priority) {
    case "Maior aproveitamento quanto ao Esforço Cortante":
        approved.sort(function (a, b) {
            return b.ratioDSV - a.ratioDSV;
        });
        //approved.reverse();
        for (i = 0; i < 5; i += 1) {
            suggestion[i] = approved[i];
        }
        break;
    case "Maior aproveitamento quanto ao Momento Fletor":
        approved.sort(function (a, b) {
            return b.ratioDSM - a.ratioDSM;
        });
        //approved.reverse();
        for (i = 0; i < 5; i += 1) {
            suggestion[i] = approved[i];
        }
        break;
    case "Menor base":
        approved.sort(function (a, b) {
            return a.perfil.bf - b.perfil.bf;
        });
        for (i = 0; i < 5; i += 1) {
            suggestion[i] = approved[i];
        }
        break;
    case "Menor altura":
        approved.sort(function (a, b) {
            return a.perfil.d - b.perfil.d;
        });
        for (i = 0; i < 5; i += 1) {
            suggestion[i] = approved[i];
        }
        break;
    case "Menor massa linear em cada família W/HP": //incompleto
        approved.sort(function (a, b) {
            return a.perfil.ml - b.perfil.ml;
        });
        for (i = 0; i < approved.length; i += 1) {
            if (contFamily[approved[i].perfil.family] === 0) {
                suggestion.push(approved[i]);
                contFamily[approved[i].perfil.family] = 1;
            }
        }
        suggestion.sort(function (a, b) {
            return a.perfil.family - b.perfil.family;
        });
        break;
    case "Menor massa linear":
        approved.sort(function (a, b) {
            return a.perfil.ml - b.perfil.ml;
        });
        for (i = 0; i < 5; i += 1) {
            suggestion[i] = approved[i];
        }
        break;
    }

/*
    SUGGESTION: Printing a log to check
*/

    console.table(suggestion[i]);
    alert("O perfil " + suggestion.perfil.bitola[0] + " pode ser utilizado para a Viga " + beam + ". Confira o relatório para mais opções.");
}

/*
    Cria um objeto aco
*/

var acoLista = document.getElementById("acos"),
    i;

function criarAco(nomeAco, linhaAco) {
    "use strict";
    var opcao = document.createElement("OPTION"),
        texto = document.createTextNode(nomeAco);
    opcao.value = linhaAco;
    opcao.appendChild(texto);
    return opcao;
}

for (i = 0; i < steelProp.length; i += 1) {
    acoLista.appendChild(criarAco(steelProp[i].steelType, i));
}
<|endoftext|>


<commit_before>var fs = require('fs')
var Plugin = require('broccoli-plugin')
var symlinkOrCopySync = require('symlink-or-copy').sync
var debug = require('debug')

module.exports = BroccoliMergeTrees
BroccoliMergeTrees.prototype = Object.create(Plugin.prototype)
BroccoliMergeTrees.prototype.constructor = BroccoliMergeTrees
function BroccoliMergeTrees(inputNodes, options) {
  if (!(this instanceof BroccoliMergeTrees)) return new BroccoliMergeTrees(inputNodes, options)
  options = options || {}
  var name = 'broccoli-merge-trees:' + (options.annotation || '')
  if (!Array.isArray(inputNodes)) {
    throw new TypeError(name + ': Expected array, got: [' + inputNodes +']')
  }
  Plugin.call(this, inputNodes, {
    annotation: options.annotation
  })

  this._debug = debug(name);
  this.options = options
  this._buildCount = 0;
}

BroccoliMergeTrees.prototype.debug = function(message, args) {
  this._debug(message, args);
}

BroccoliMergeTrees.prototype.build = function() {
  var inputPaths = this.inputPaths
  var outputPath = this.outputPath
  var overwrite = this.options.overwrite
  this._buildCount++;

  var start = new Date()
  mergeRelativePath('')
  this.debug('build: \n %o', {
    count: this._buildCount,
    in: new Date() - start + 'ms'
  })

  function mergeRelativePath (baseDir, possibleIndices) {
    // baseDir has a trailing path.sep if non-empty
    var i, j, fileName, fullPath

    // Array of readdir arrays
    var names = inputPaths.map(function (inputPath, i) {
      if (possibleIndices == null || possibleIndices.indexOf(i) !== -1) {
        return fs.readdirSync(inputPath + '/' + baseDir).sort()
      } else {
        return []
      }
    })

    // Guard against conflicting capitalizations
    var lowerCaseNames = {}
    for (i = 0; i < inputPaths.length; i++) {
      for (j = 0; j < names[i].length; j++) {
        fileName = names[i][j]
        var lowerCaseName = fileName.toLowerCase()
        // Note: We are using .toLowerCase to approximate the case
        // insensitivity behavior of HFS+ and NTFS. While .toLowerCase is at
        // least Unicode aware, there are probably better-suited functions.
        if (lowerCaseNames[lowerCaseName] == null) {
          lowerCaseNames[lowerCaseName] = {
            index: i,
            originalName: fileName
          }
        } else {
          var originalIndex = lowerCaseNames[lowerCaseName].index
          var originalName = lowerCaseNames[lowerCaseName].originalName
          if (originalName !== fileName) {
            throw new Error('Merge error: conflicting capitalizations:\n'
              + baseDir + originalName + ' in ' + inputPaths[originalIndex] + '\n'
              + baseDir + fileName + ' in ' + inputPaths[i] + '\n'
              + 'Remove one of the files and re-add it with matching capitalization.\n'
              + 'We are strict about this to avoid divergent behavior '
              + 'between case-insensitive Mac/Windows and case-sensitive Linux.'
            )
          }
        }
      }
    }
    // From here on out, no files and directories exist with conflicting
    // capitalizations, which means we can use `===` without .toLowerCase
    // normalization.

    // Accumulate fileInfo hashes of { isDirectory, indices }.
    // Also guard against conflicting file types and overwriting.
    var fileInfo = {}
    for (i = 0; i < inputPaths.length; i++) {
      for (j = 0; j < names[i].length; j++) {
        fileName = names[i][j]
        fullPath = inputPaths[i] + '/' + baseDir + fileName
        var isDirectory = checkIsDirectory(fullPath)
        if (fileInfo[fileName] == null) {
          fileInfo[fileName] = {
            isDirectory: isDirectory,
            indices: [i] // indices into inputPaths in which this file exists
          }
        } else {
          fileInfo[fileName].indices.push(i)

          // Guard against conflicting file types
          var originallyDirectory = fileInfo[fileName].isDirectory
          if (originallyDirectory !== isDirectory) {
            throw new Error('Merge error: conflicting file types: ' + baseDir + fileName
              + ' is a ' + (originallyDirectory ? 'directory' : 'file')
                + ' in ' + inputPaths[fileInfo[fileName].indices[0]]
              + ' but a ' + (isDirectory ? 'directory' : 'file')
                + ' in ' + inputPaths[i] + '\n'
              + 'Remove or rename either of those.'
            )
          }

          // Guard against overwriting when disabled
          if (!isDirectory && !overwrite) {
            throw new Error('Merge error: '
              + 'file ' + baseDir + fileName + ' exists in '
              + inputPaths[fileInfo[fileName].indices[0]] + ' and ' + inputPaths[i] + '\n'
              + 'Pass option { overwrite: true } to mergeTrees in order '
              + 'to have the latter file win.'
            )
          }
        }
      }
    }

    // Done guarding against all error conditions. Actually merge now.
    for (i = 0; i < inputPaths.length; i++) {
      for (j = 0; j < names[i].length; j++) {
        fileName = names[i][j]
        fullPath = inputPaths[i] + '/' + baseDir + fileName
        var destPath = outputPath + '/' + baseDir + fileName
        var infoHash = fileInfo[fileName]

        if (infoHash.isDirectory) {
          if (infoHash.indices.length > 1) {
            // Copy/merge subdirectory
            if (infoHash.indices[0] === i) { // avoid duplicate recursion
              fs.mkdirSync(destPath)
              mergeRelativePath(baseDir + fileName + '/', infoHash.indices)
            }
          } else {
            // Symlink entire subdirectory
            symlinkOrCopySync(fullPath, destPath)
          }
        } else { // isFile
          if (infoHash.indices[infoHash.indices.length-1] === i) {
            symlinkOrCopySync(fullPath, destPath)
          } else {
            // This file exists in a later inputPath. Do nothing here to have the
            // later file win out and thus "overwrite" the earlier file.
          }
        }
      }
    }
  }
}

// True if directory, false if file, exception otherwise
function checkIsDirectory (fullPath) {
  var stat = fs.statSync(fullPath) // may throw ENOENT on broken symlink
  if (stat.isDirectory()) {
    return true
  } else if (stat.isFile()) {
    return false
  } else {
    throw new Error('Unexpected file type for ' + fullPath)
  }
}
<commit_msg>extract mergeRelativePath to prototype method<commit_after>var fs = require('fs')
var Plugin = require('broccoli-plugin')
var symlinkOrCopySync = require('symlink-or-copy').sync
var debug = require('debug')

module.exports = BroccoliMergeTrees
BroccoliMergeTrees.prototype = Object.create(Plugin.prototype)
BroccoliMergeTrees.prototype.constructor = BroccoliMergeTrees
function BroccoliMergeTrees(inputNodes, options) {
  if (!(this instanceof BroccoliMergeTrees)) return new BroccoliMergeTrees(inputNodes, options)
  options = options || {}
  var name = 'broccoli-merge-trees:' + (options.annotation || '')
  if (!Array.isArray(inputNodes)) {
    throw new TypeError(name + ': Expected array, got: [' + inputNodes +']')
  }
  Plugin.call(this, inputNodes, {
    annotation: options.annotation
  })

  this._debug = debug(name);
  this.options = options
  this._buildCount = 0;
}

BroccoliMergeTrees.prototype.debug = function(message, args) {
  this._debug(message, args);
}

BroccoliMergeTrees.prototype.build = function() {
  this._buildCount++;

  var start = new Date()
  this._mergeRelativePath('')
  this.debug('build: \n %o', {
    count: this._buildCount,
    in: new Date() - start + 'ms'
  })
};

BroccoliMergeTrees.prototype._mergeRelativePath = function(baseDir, possibleIndices) {
  // baseDir has a trailing path.sep if non-empty
  var i, j, fileName, fullPath
  var overwrite = this.options.overwrite

  // Array of readdir arrays
  var names = this.inputPaths.map(function (inputPath, i) {
    if (possibleIndices == null || possibleIndices.indexOf(i) !== -1) {
      return fs.readdirSync(inputPath + '/' + baseDir).sort()
    } else {
      return []
    }
  })

  // Guard against conflicting capitalizations
  var lowerCaseNames = {}
  for (i = 0; i < this.inputPaths.length; i++) {
    for (j = 0; j < names[i].length; j++) {
      fileName = names[i][j]
      var lowerCaseName = fileName.toLowerCase()
      // Note: We are using .toLowerCase to approximate the case
      // insensitivity behavior of HFS+ and NTFS. While .toLowerCase is at
      // least Unicode aware, there are probably better-suited functions.
      if (lowerCaseNames[lowerCaseName] == null) {
        lowerCaseNames[lowerCaseName] = {
          index: i,
          originalName: fileName
        }
      } else {
        var originalIndex = lowerCaseNames[lowerCaseName].index
        var originalName = lowerCaseNames[lowerCaseName].originalName
        if (originalName !== fileName) {
          throw new Error('Merge error: conflicting capitalizations:\n'
                          + baseDir + originalName + ' in ' + this.inputPaths[originalIndex] + '\n'
                          + baseDir + fileName + ' in ' + this.inputPaths[i] + '\n'
                          + 'Remove one of the files and re-add it with matching capitalization.\n'
                          + 'We are strict about this to avoid divergent behavior '
                          + 'between case-insensitive Mac/Windows and case-sensitive Linux.'
                         )
        }
      }
    }
  }
  // From here on out, no files and directories exist with conflicting
  // capitalizations, which means we can use `===` without .toLowerCase
  // normalization.

  // Accumulate fileInfo hashes of { isDirectory, indices }.
  // Also guard against conflicting file types and overwriting.
  var fileInfo = {}
  for (i = 0; i < this.inputPaths.length; i++) {
    for (j = 0; j < names[i].length; j++) {
      fileName = names[i][j]
      fullPath = this.inputPaths[i] + '/' + baseDir + fileName
      var isDirectory = checkIsDirectory(fullPath)
      if (fileInfo[fileName] == null) {
        fileInfo[fileName] = {
          isDirectory: isDirectory,
          indices: [i] // indices into inputPaths in which this file exists
        }
      } else {
        fileInfo[fileName].indices.push(i)

        // Guard against conflicting file types
        var originallyDirectory = fileInfo[fileName].isDirectory
        if (originallyDirectory !== isDirectory) {
          throw new Error('Merge error: conflicting file types: ' + baseDir + fileName
                          + ' is a ' + (originallyDirectory ? 'directory' : 'file')
                          + ' in ' + this.inputPaths[fileInfo[fileName].indices[0]]
                          + ' but a ' + (isDirectory ? 'directory' : 'file')
                          + ' in ' + this.inputPaths[i] + '\n'
                          + 'Remove or rename either of those.'
                         )
        }

        // Guard against overwriting when disabled
        if (!isDirectory && !overwrite) {
          throw new Error('Merge error: '
                          + 'file ' + baseDir + fileName + ' exists in '
                          + this.inputPaths[fileInfo[fileName].indices[0]] + ' and ' + this.inputPaths[i] + '\n'
                          + 'Pass option { overwrite: true } to mergeTrees in order '
                          + 'to have the latter file win.'
                         )
        }
      }
    }
  }

  // Done guarding against all error conditions. Actually merge now.
  for (i = 0; i < this.inputPaths.length; i++) {
    for (j = 0; j < names[i].length; j++) {
      fileName = names[i][j]
      fullPath = this.inputPaths[i] + '/' + baseDir + fileName
      var destPath = this.outputPath + '/' + baseDir + fileName
      var infoHash = fileInfo[fileName]

      if (infoHash.isDirectory) {
        if (infoHash.indices.length > 1) {
          // Copy/merge subdirectory
          if (infoHash.indices[0] === i) { // avoid duplicate recursion
            fs.mkdirSync(destPath)
            this._mergeRelativePath(baseDir + fileName + '/', infoHash.indices)
          }
        } else {
          // Symlink entire subdirectory
          symlinkOrCopySync(fullPath, destPath)
        }
      } else { // isFile
        if (infoHash.indices[infoHash.indices.length-1] === i) {
          symlinkOrCopySync(fullPath, destPath)
        } else {
          // This file exists in a later inputPath. Do nothing here to have the
          // later file win out and thus "overwrite" the earlier file.
        }
      }
    }
  }
};

// True if directory, false if file, exception otherwise
function checkIsDirectory (fullPath) {
  var stat = fs.statSync(fullPath) // may throw ENOENT on broken symlink
  if (stat.isDirectory()) {
    return true
  } else if (stat.isFile()) {
    return false
  } else {
    throw new Error('Unexpected file type for ' + fullPath)
  }
}
<|endoftext|>