<commit_before>'use strict';

/**
 * Module dependencies.
 */
var path = require('path'),
  mongoose = require('mongoose'),
  Project = mongoose.model('Project'),
  errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'));

// Reference modules/articles/server for examples on what can go here
exports.create = function(req, res) {
  var project = new Projects(req.body);

    exports.create = function (req, res) {
        var project = new Project(req.body);
        project.user = req.user;

        project.save(function (err) {
            if (err) {
                return res.status(400).send({
                    message: errorHandler.getErrorMessage(err)
                });
            } else {
                res.json(project);
            }
        });
    };
};
<commit_msg>stashing<commit_after>'use strict';

/**
 * Module dependencies.
 */
var path = require('path'),
  mongoose = require('mongoose'),
  Project = mongoose.model('Project'),
  errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'));

// Reference modules/articles/server for examples on what can go here
exports.create = function(req, res) {
  var project = new Projects(req.body);

    exports.create = function (req, res) {
        var project = new Project(req.body);
        project.user = req.user;

        project.save(function (err) {
            if (err) {
                return res.status(400).send({
                    message: errorHandler.getErrorMessage(err)
                });
            } else {
                res.json(project);
            }
        });
    };
exports.category = function (req, res) {
  var project = req.project;

  // project.title = req.body.title;
  // project.details = req.body.details;
  project.category = req.body.category;

  project.save(function (err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.json(project);
    }
        });
    };
};
<|endoftext|>


<commit_before>const webpack = require("webpack");
const path = require("path");

const config = {
  mode: "production",
  entry: path.resolve(__dirname, "app/App.js"),
  output: {
    path: path.resolve(__dirname, "public/js/"),
    publicPath: "/js/",
    filename: "bundle.js"
  },
  module: {
    rules: [
      {
        test: /.jsx?$/,
        exclude: [path.resolve(__dirname, "node_modules")],
        loader: "babel-loader"
      }
    ]
  },
  devServer: {
    contentBase: path.resolve(__dirname, "public"),
    historyApiFallback: true,
    compress: true,
    open: true
  }
};

module.exports = config;
<commit_msg>Move to new webpack config files<commit_after><|endoftext|>


<commit_before>#! /usr/bin/env node

var program = require("commander");
var prompt = require("cli-prompt");
var Table = require("cli-table");
var fs = require("fs");

var ImpConfig = require("../lib/impConfig.js");
var config = new ImpConfig();

program
  .option("-r, --revision [revision]", "pulls the specified revision from development account")

program.parse(process.argv);

function apiKeyPrompt(env, apiKey, next) {
  var promptText = env + " Account Api-Key";
  if (apiKey) promptText += " (" + apiKey + ")";
  promptText += ": ";

  prompt(promptText, function(val){

    else if (!apiKey && !val) {
      apiKeyPrompt(env, apiKey, next);
      return;
    }

    if (apiKey && !val) val = apiKey;
    config.setLocal("apiKey", val);
    config.setLocal(env+"apiKey", val);

    imp = config.createImpWithConfig();
    // Lookup a bad device_id to make sure the API Key works
    imp.getDevices({ "device_id" : "garbage" }, function(err, data) {
      if (err) {
        // clear API Key, and try again
        imp[env + "apiKey"] = null;
        console.log("ERROR: Invalid Api-Key..");
        apiKeyPrompt(env, apiKey, next);
        return;
      }

      next();
    });
  });
}

function modelPrompt(env, next) {
  var promptText = env + " Model Id or Name";
  var modelName = config.getLocal("modelName");
  if (modelName) promptText += " (" + modelName + ")"
  promptText += ": ";

  prompt(promptText, function(val) {
    if (modelName && !val) val = modelName;
    else if (!val) {
      modelPrompt(env, next);
      return;
    }

    // try to get model by id
    imp.getModel(val, function(err, data) {
      if (!err) {
        prompt("Found a matching model '" + data.model.name + "', use this (y): ", function(confirm) {
          if (confirm && confirm.toLowerCase()[0] != "y") {
            modelPrompt(env, next);
            return;
          }

          config.setLocal("modelId", data.model.id);
          config.setLocal("modelName", data.model.name);
          next();
          return;
        });
      } else {
        // an error means no model_id match was found
        imp.getModels({ "name": val }, function(err, data) {
          if (err) {
            console.log("Something went horribly wrong!");
            return;
          }

          // see if we found a matching result
          var foundMatch = false;
          for(var i = 0; i < data.models.length; i++) {
            if(data.models[i].name.toLowerCase() == val.toLowerCase()) {
              foundMatch = true;
              break;
            }
          }
          if (foundMatch) {
            prompt("Found a matching model '" + data.models[i].name + "', use this (y): ", function(confirm){
              if (confirm && confirm.toLowerCase()[0] != "y") {
                modelPrompt(env, next);
                return;
              }

              config.setLocal("modelId", data.models[i].id);
              config.setLocal("modelName", data.models[i].name);
              next();
              return;
            });
          } else {
            prompt("Create new model '" + val + "' (y): ", function(confirm) {
              if (confirm && confirm.toLowerCase()[0] != "y") {
                modelPrompt(env, next);
                return;
              }

              imp.createModel(val, function(err, data) {
                if (err) {
                  console.log("ERROR: Could not create model");
                  return;
                }

                config.setLocal("modelName", data.model.name);
                config.setLocal("modelId", data.model.id);
                next();
              });
              return;
            });
          }
        });
      }
    });
  });
}

function fileNamePrompt(next) {
  var modelName = config.getLocal("modelName");

  var baseFileName = modelName.split(" ").join("_").toLowerCase();

  var defaultDeviceFileName = config.getLocal("deviceFile") || (baseFileName + ".device.nut");
  var defaultAgentFileName = config.getLocal("agentFile") || (baseFileName + ".agent.nut");

  prompt.multi([
    {
      label: "Device code file ("+defaultDeviceFileName+")",
      key: "deviceFile"
    },
    {
      label: "Agent code file ("+defaultAgentFileName+")",
      key: "agentFile"
    }
  ], function(data){

    if (data.deviceFile === "next") data.deviceFile = defaultDeviceFileName;
    if (data.agentFile === "next") data.agentFile = defaultAgentFileName;

    config.setLocal("deviceFile", data.deviceFile || defaultDeviceFileName);
    config.setLocal("agentFile", data.agentFile || defaultAgentFileName);
    next();
  });

}

function pull(next){

  function getVersion(ver, cb) {
    imp.getModelRevision(config.get("modelId"), ver, cb);
  }

  function done(err, data) {
    if (err) {
      console.log("ERROR: " + err.message_short);
      return;
    }
    else {
      if ("revision" in data) {
        fs.writeFile(config.get("deviceFile"), data.revision.device_code);
        fs.writeFile(config.get("agentFile"), data.revision.agent_code);

        console.log("Success! Pulled version " + data.revision.version + "..");
      }
    }
    next();
  }

  if ("revision" in program){
    getVersion(program.revision, done);
  } else {
    imp.getModelRevisions(config.get("modelId"), null, function(err, data) {
      if (err) {
        console.log("ERROR: Something went horribly wrong..");
        return;
      }
      if ("revisions" in data && data.revisions.length > 0) {
        getVersion(data.revisions[0].version, done);
      }
    });
  }
}

function deploy(next){

  var model = {
    device_code: null,
    agent_code: null
  };

  // Make sure the code files exist
  if (!fs.existsSync(config.get("agentFile"))) {
    console.log("ERROR: Could not find agent code file: " + config.get("deviceFile"));
    return;
  }
  if (!fs.existsSync(config.get("deviceFile"))) {
    console.log("ERROR: Could not find device code file: " + config.get("deviceFile"));
    return;
  }

  model.agent_code = fs.readFileSync(config.get("agentFile"), "utf8");
  model.device_code = fs.readFileSync(config.get("deviceFile"), "utf8");

  // Add the tag (if one was specified)
  if ("tag" in program) model["marker"] = program.tag;

  imp.createModelRevision(config.get("modelId"), model, function(err, data) {
    if (err) {
      if (err.code != "CompileFailed") {
        console.log(colors.red("ERROR: " + err.message_short));
        return;
      }

      if (err.details.agent_errors) {
        for(var i = 0; i < err.details.agent_errors.length; i ++) {
          var thisErr = err.details.agent_errors[i];
          console.log(colors.red("ERROR: " + thisErr.error));
          console.log("   at: " + config.get("agentFile") +":" + thisErr.row + " (col "+thisErr.column+")");
        }
      }

      if (err.details.device_errors) {
        for(var i = 0; i < err.details.device_errors.length; i ++) {
          var thisErr = err.details.device_errors[i];
          console.log(colors.red("ERROR: " + thisErr.error));
          console.log("   at: " + config.get("deviceFile") +":" + thisErr.row + " (col "+thisErr.column+")");
        }
      }

      return;
    }

    imp.restartModel(config.get("modelId"), function(err, restartData) {
      if (err) {
        console.log("Warning: Could not restart model");
      }

      console.log("Successfully created revision " + data.revision.version);
      next();
    });
  });
}

function finalize(){
  console.log("");
  console.log("=================================================================")
  console.log("Migration complete! Saving local configuration...");
  config.saveLocalConfig(function(err) {
    if (err) {
      console.log("ERROR: Problem saving local configuration: " + err);
      console.log("=================================================================")
      return;
    }

    console.log("Configuration saved!")
    console.log("FYI - next time, you can press 'enter' to use the default values!");
    console.log("=================================================================")
  });
}

config.init(null, function() {
  apiKeyPrompt("Development", config.get("DevelopmentapiKey"), function() {
    modelPrompt("Development", function() {
      fileNamePrompt(function() {
        pull(function() {
          apiKeyPrompt("Production", config.get("ProductionapiKey"), function() {
            modelPrompt("Production", function() {
              deploy(function() {
                finalize();
              });
            });
          });
        });
      });
    });
  });
}.bind(config));
<commit_msg>Remove rogue 'else'<commit_after>#! /usr/bin/env node

var program = require("commander");
var prompt = require("cli-prompt");
var Table = require("cli-table");
var fs = require("fs");

var ImpConfig = require("../lib/impConfig.js");
var config = new ImpConfig();

program
  .option("-r, --revision [revision]", "pulls the specified revision from development account")

program.parse(process.argv);

function apiKeyPrompt(env, apiKey, next) {
  var promptText = env + " Account Api-Key";
  if (apiKey) promptText += " (" + apiKey + ")";
  promptText += ": ";

  prompt(promptText, function(val){
    if (!apiKey && !val) {
      apiKeyPrompt(env, apiKey, next);
      return;
    }

    if (apiKey && !val) val = apiKey;
    config.setLocal("apiKey", val);
    config.setLocal(env+"apiKey", val);

    imp = config.createImpWithConfig();
    // Lookup a bad device_id to make sure the API Key works
    imp.getDevices({ "device_id" : "garbage" }, function(err, data) {
      if (err) {
        // clear API Key, and try again
        imp[env + "apiKey"] = null;
        console.log("ERROR: Invalid Api-Key..");
        apiKeyPrompt(env, apiKey, next);
        return;
      }

      next();
    });
  });
}

function modelPrompt(env, next) {
  var promptText = env + " Model Id or Name";
  var modelName = config.getLocal("modelName");
  if (modelName) promptText += " (" + modelName + ")"
  promptText += ": ";

  prompt(promptText, function(val) {
    if (modelName && !val) val = modelName;
    else if (!val) {
      modelPrompt(env, next);
      return;
    }

    // try to get model by id
    imp.getModel(val, function(err, data) {
      if (!err) {
        prompt("Found a matching model '" + data.model.name + "', use this (y): ", function(confirm) {
          if (confirm && confirm.toLowerCase()[0] != "y") {
            modelPrompt(env, next);
            return;
          }

          config.setLocal("modelId", data.model.id);
          config.setLocal("modelName", data.model.name);
          next();
          return;
        });
      } else {
        // an error means no model_id match was found
        imp.getModels({ "name": val }, function(err, data) {
          if (err) {
            console.log("Something went horribly wrong!");
            return;
          }

          // see if we found a matching result
          var foundMatch = false;
          for(var i = 0; i < data.models.length; i++) {
            if(data.models[i].name.toLowerCase() == val.toLowerCase()) {
              foundMatch = true;
              break;
            }
          }
          if (foundMatch) {
            prompt("Found a matching model '" + data.models[i].name + "', use this (y): ", function(confirm){
              if (confirm && confirm.toLowerCase()[0] != "y") {
                modelPrompt(env, next);
                return;
              }

              config.setLocal("modelId", data.models[i].id);
              config.setLocal("modelName", data.models[i].name);
              next();
              return;
            });
          } else {
            prompt("Create new model '" + val + "' (y): ", function(confirm) {
              if (confirm && confirm.toLowerCase()[0] != "y") {
                modelPrompt(env, next);
                return;
              }

              imp.createModel(val, function(err, data) {
                if (err) {
                  console.log("ERROR: Could not create model");
                  return;
                }

                config.setLocal("modelName", data.model.name);
                config.setLocal("modelId", data.model.id);
                next();
              });
              return;
            });
          }
        });
      }
    });
  });
}

function fileNamePrompt(next) {
  var modelName = config.getLocal("modelName");

  var baseFileName = modelName.split(" ").join("_").toLowerCase();

  var defaultDeviceFileName = config.getLocal("deviceFile") || (baseFileName + ".device.nut");
  var defaultAgentFileName = config.getLocal("agentFile") || (baseFileName + ".agent.nut");

  prompt.multi([
    {
      label: "Device code file ("+defaultDeviceFileName+")",
      key: "deviceFile"
    },
    {
      label: "Agent code file ("+defaultAgentFileName+")",
      key: "agentFile"
    }
  ], function(data){

    if (data.deviceFile === "next") data.deviceFile = defaultDeviceFileName;
    if (data.agentFile === "next") data.agentFile = defaultAgentFileName;

    config.setLocal("deviceFile", data.deviceFile || defaultDeviceFileName);
    config.setLocal("agentFile", data.agentFile || defaultAgentFileName);
    next();
  });

}

function pull(next){

  function getVersion(ver, cb) {
    imp.getModelRevision(config.get("modelId"), ver, cb);
  }

  function done(err, data) {
    if (err) {
      console.log("ERROR: " + err.message_short);
      return;
    }
    else {
      if ("revision" in data) {
        fs.writeFile(config.get("deviceFile"), data.revision.device_code);
        fs.writeFile(config.get("agentFile"), data.revision.agent_code);

        console.log("Success! Pulled version " + data.revision.version + "..");
      }
    }
    next();
  }

  if ("revision" in program){
    getVersion(program.revision, done);
  } else {
    imp.getModelRevisions(config.get("modelId"), null, function(err, data) {
      if (err) {
        console.log("ERROR: Something went horribly wrong..");
        return;
      }
      if ("revisions" in data && data.revisions.length > 0) {
        getVersion(data.revisions[0].version, done);
      }
    });
  }
}

function deploy(next){

  var model = {
    device_code: null,
    agent_code: null
  };

  // Make sure the code files exist
  if (!fs.existsSync(config.get("agentFile"))) {
    console.log("ERROR: Could not find agent code file: " + config.get("deviceFile"));
    return;
  }
  if (!fs.existsSync(config.get("deviceFile"))) {
    console.log("ERROR: Could not find device code file: " + config.get("deviceFile"));
    return;
  }

  model.agent_code = fs.readFileSync(config.get("agentFile"), "utf8");
  model.device_code = fs.readFileSync(config.get("deviceFile"), "utf8");

  // Add the tag (if one was specified)
  if ("tag" in program) model["marker"] = program.tag;

  imp.createModelRevision(config.get("modelId"), model, function(err, data) {
    if (err) {
      if (err.code != "CompileFailed") {
        console.log(colors.red("ERROR: " + err.message_short));
        return;
      }

      if (err.details.agent_errors) {
        for(var i = 0; i < err.details.agent_errors.length; i ++) {
          var thisErr = err.details.agent_errors[i];
          console.log(colors.red("ERROR: " + thisErr.error));
          console.log("   at: " + config.get("agentFile") +":" + thisErr.row + " (col "+thisErr.column+")");
        }
      }

      if (err.details.device_errors) {
        for(var i = 0; i < err.details.device_errors.length; i ++) {
          var thisErr = err.details.device_errors[i];
          console.log(colors.red("ERROR: " + thisErr.error));
          console.log("   at: " + config.get("deviceFile") +":" + thisErr.row + " (col "+thisErr.column+")");
        }
      }

      return;
    }

    imp.restartModel(config.get("modelId"), function(err, restartData) {
      if (err) {
        console.log("Warning: Could not restart model");
      }

      console.log("Successfully created revision " + data.revision.version);
      next();
    });
  });
}

function finalize(){
  console.log("");
  console.log("=================================================================")
  console.log("Migration complete! Saving local configuration...");
  config.saveLocalConfig(function(err) {
    if (err) {
      console.log("ERROR: Problem saving local configuration: " + err);
      console.log("=================================================================")
      return;
    }

    console.log("Configuration saved!")
    console.log("FYI - next time, you can press 'enter' to use the default values!");
    console.log("=================================================================")
  });
}

config.init(null, function() {
  apiKeyPrompt("Development", config.get("DevelopmentapiKey"), function() {
    modelPrompt("Development", function() {
      fileNamePrompt(function() {
        pull(function() {
          apiKeyPrompt("Production", config.get("ProductionapiKey"), function() {
            modelPrompt("Production", function() {
              deploy(function() {
                finalize();
              });
            });
          });
        });
      });
    });
  });
}.bind(config));
<|endoftext|>


<commit_before>#!/usr/bin/env node

"use strict";

var opts = require("optimist")
  .usage("Usage: $0 --consumer-key <consumer key> --consumer-secret <consumer secret>\n" +
         "       [--token <token>] [--token-secret <token secret>] [-p <proxy port>] [--ssl]")
  .describe("consumer-key", "OAuth Consumer Key")
  .describe("consumer-secret", "OAuth Consumer Secret")
  .describe("token", "OAuth Access/Request Token")
  .describe("token-secret", "OAuth Access/Request Token Secret")
  .describe("p", "Proxy port")
  .alias("p", "port")
  .describe("ssl", "Make upstream requests via HTTPS")
  .describe("help", "Display this help");

var argv = opts.argv;

if (argv.help) {
  opts.showHelp();
  process.exit();
}

var server = require("../")({
  consumerKey: argv["consumer-key"],
  consumerSecret: argv["consumer-secret"],
  token: argv.token,
  tokenSecret: argv["token-secret"],
  ssl: argv.ssl
})
  // TODO add an option to specify the interface to listen on
  .listen(argv.port || process.env.PORT || 8001, function() {
    console.log("Listening at http://%s:%d/", this.address().address, this.address().port);
  });

process.on("SIGINT", function() {
  server.close(function() {
    process.exit();
  });
});
<commit_msg>It's a message, not actual help<commit_after>#!/usr/bin/env node

"use strict";

var opts = require("optimist")
  .usage("Usage: $0 --consumer-key <consumer key> --consumer-secret <consumer secret>\n" +
         "       [--token <token>] [--token-secret <token secret>] [-p <proxy port>] [--ssl]")
  .describe("consumer-key", "OAuth Consumer Key")
  .describe("consumer-secret", "OAuth Consumer Secret")
  .describe("token", "OAuth Access/Request Token")
  .describe("token-secret", "OAuth Access/Request Token Secret")
  .describe("p", "Proxy port")
  .alias("p", "port")
  .describe("ssl", "Make upstream requests via HTTPS")
  .describe("help", "Display this help message");

var argv = opts.argv;

if (argv.help) {
  opts.showHelp();
  process.exit();
}

var server = require("../")({
  consumerKey: argv["consumer-key"],
  consumerSecret: argv["consumer-secret"],
  token: argv.token,
  tokenSecret: argv["token-secret"],
  ssl: argv.ssl
})
  // TODO add an option to specify the interface to listen on
  .listen(argv.port || process.env.PORT || 8001, function() {
    console.log("Listening at http://%s:%d/", this.address().address, this.address().port);
  });

process.on("SIGINT", function() {
  server.close(function() {
    process.exit();
  });
});
<|endoftext|>


<commit_before>var fs = require('fs')
var path = require('path')
var fstream = require('fstream')
var tar = require('tar');
let zlib = require('zlib');

var walk = function (dir, authfolderData, done) {
    fs.readdir(dir, function (err, list) {
        if (err) return done(err);
        // authfolderData.name = path.basename(authfolderData.name) || path.basename(dir)
        // authfolderData.child = []
        // authfolderData.file = []
        var pending = list.length;
        if (!pending) return done(null, authfolderData);
        list.forEach(function (file) {
            file = path.resolve(dir, file);
            fs.stat(file, function (err, stat) {
                if (stat && stat.isDirectory()) {
                    var childItem = {
                        name: path.basename(file)
                    }
                    authfolderData.folder ? authfolderData.folder.push(childItem) : authfolderData.folder = [childItem]
                    walk(file, childItem, function (err, res) {
                        // authfolderData = authfolderData.concat(res);
                        if (!--pending) done(null, authfolderData);
                    });
                } else {
                    let fileName = path.basename(file)
                    authfolderData.file ? authfolderData.file.push(fileName) : authfolderData.file = [fileName]
                    authfolderData.file.sort()
                    // authfolderData.push(file);
                    if (!--pending) done(null, authfolderData);
                }
            });
        });
    });
};
// 创建多层文件夹
function mkdirSync(dirpath, mode) {
    if (!fs.existsSync(dirpath)) {
        var pathtmp;
        dirpath.split(path.sep).forEach(function (dirname) {
            if (pathtmp) {
                pathtmp = path.join(pathtmp, dirname);
            } else {
                pathtmp = dirname;
            }
            if (!fs.existsSync(pathtmp)) {
                if (!fs.mkdirSync(pathtmp, mode)) {
                    return false;
                }
            }
        });
    }
    return true;
}
// 删除文件夹
function deleteFolder(dirPath) {
    var files = [];
    if (fs.existsSync(dirPath)) {
        files = fs.readdirSync(dirPath);
        files.forEach(function (file, index) {
            var curPath = path.resolve(dirPath, file);
            if (fs.lstatSync(curPath).isDirectory()) { // recurse
                deleteFolder(curPath);
            } else { // delete file
                fs.unlinkSync(curPath);
            }
        });
        fs.rmdirSync(dirPath);
    }
}

// 清空文件夹内文件
function clearFolder(dirPath) {
    var files = [];
    if (fs.existsSync(dirPath)) {
        files = fs.readdirSync(dirPath);
        files.forEach(function (file, index) {
            var curPath = path.resolve(dirPath, file);
            if (!fs.lstatSync(curPath).isDirectory()) { // recurse
                fs.unlinkSync(curPath);
            }
        });
    }
}

// 压缩，生成tar.gz
function compression(input, output) {
    return new Promise((resolve, reject) => {
        let result = {
            status: 0
        }
        if (!fs.existsSync(input)) {
            result.message = '压缩资源不存在！'
            reject(result)
        } else {
            fs.stat(input, function (err, stat) {
                if (err || !stat) {
                    result.message = '无法获取压缩资源！'
                    reject(result)
                }
                var r, w = fstream.Writer(output)
                if (stat && stat.isDirectory()) {
                    // 文件夹
                    r = fstream.Reader({
                        'path': input,
                        'type': 'Directory'
                    });
                } else if (stat && stat.isFile()) {
                    // 文件
                    r = fstream.Reader({
                        'path': input,
                        'type': 'File'
                    });
                } else {
                    result.message = '压缩资源失败！'
                    reject(result)
                }
                r.pipe(tar.Pack({
                    noRepository: true,
                    fromBase: true
                }))
                    .pipe(zlib.Gzip())
                    .pipe(w);
                r.on('end', () => {
                    result.status = 1
                    result.data = {
                        output: output
                    }
                    resolve(result);
                })
                r.on('error', (err) => {
                    result.message = '压缩资源失败！'
                    reject(result)
                })
            })
        }
    })
}

module.exports = {
    walk,
    mkdirSync,
    deleteFolder,
    clearFolder,
    compression
}<commit_msg>修改：压缩实现法方式<commit_after>var fs = require('fs')
var path = require('path')
var archiver = require('archiver');

var walk = function (dir, authfolderData, done) {
    fs.readdir(dir, function (err, list) {
        if (err) return done(err);
        // authfolderData.name = path.basename(authfolderData.name) || path.basename(dir)
        // authfolderData.child = []
        // authfolderData.file = []
        var pending = list.length;
        if (!pending) return done(null, authfolderData);
        list.forEach(function (file) {
            file = path.resolve(dir, file);
            fs.stat(file, function (err, stat) {
                if (stat && stat.isDirectory()) {
                    var childItem = {
                        name: path.basename(file)
                    }
                    authfolderData.folder ? authfolderData.folder.push(childItem) : authfolderData.folder = [childItem]
                    walk(file, childItem, function (err, res) {
                        // authfolderData = authfolderData.concat(res);
                        if (!--pending) done(null, authfolderData);
                    });
                } else {
                    let fileName = path.basename(file)
                    authfolderData.file ? authfolderData.file.push(fileName) : authfolderData.file = [fileName]
                    authfolderData.file.sort()
                    // authfolderData.push(file);
                    if (!--pending) done(null, authfolderData);
                }
            });
        });
    });
};
// 创建多层文件夹
function mkdirSync(dirpath, mode) {
    if (!fs.existsSync(dirpath)) {
        var pathtmp;
        dirpath.split(path.sep).forEach(function (dirname) {
            if (pathtmp) {
                pathtmp = path.join(pathtmp, dirname);
            } else {
                pathtmp = dirname;
            }
            if (!fs.existsSync(pathtmp)) {
                if (!fs.mkdirSync(pathtmp, mode)) {
                    return false;
                }
            }
        });
    }
    return true;
}
// 删除文件夹
function deleteFolder(dirPath) {
    var files = [];
    if (fs.existsSync(dirPath)) {
        files = fs.readdirSync(dirPath);
        files.forEach(function (file, index) {
            var curPath = path.resolve(dirPath, file);
            if (fs.lstatSync(curPath).isDirectory()) { // recurse
                deleteFolder(curPath);
            } else { // delete file
                fs.unlinkSync(curPath);
            }
        });
        fs.rmdirSync(dirPath);
    }
}

// 清空文件夹内文件
function clearFolder(dirPath) {
    var files = [];
    if (fs.existsSync(dirPath)) {
        files = fs.readdirSync(dirPath);
        files.forEach(function (file, index) {
            var curPath = path.resolve(dirPath, file);
            if (!fs.lstatSync(curPath).isDirectory()) { // recurse
                fs.unlinkSync(curPath);
            }
        });
    }
}

// 压缩，生成.zip
function compression(inputPath, outputPath) {
    return new Promise((resolve, reject) => {
        let result = {
            status: 0
        }
        if (!fs.existsSync(inputPath)) {
            result.message = '压缩资源不存在！'
            reject(result)
        } else {
            fs.stat(inputPath, function (err, stat) {
                if (err || !stat) {
                    result.message = '无法获取压缩资源！'
                    reject(result)
                }
                var output = fs.createWriteStream(outputPath);
                var archive = archiver('zip', {
                    zlib: { level: 9 } // Sets the compression level.
                });
                output.on('close', function () {
                    result.status = 1
                    result.data = {
                        output: outputPath
                    }
                    resolve(result);
                });
                archive.on('error', function (err) {
                    result.message = '压缩资源失败！'
                    reject(result)
                });
                archive.pipe(output);
                if (stat && stat.isDirectory()) {
                    archive.directory(inputPath + '\\', path.basename(inputPath));
                    archive.finalize();
                } else if (stat && stat.isFile()) {
                    archive.append(fs.createReadStream(inputPath), { name: path.basename(inputPath) });
                    archive.finalize();
                } else {
                    result.message = '压缩资源失败！'
                    reject(result)
                }
            })
        }
    })
}

module.exports = {
    walk,
    mkdirSync,
    deleteFolder,
    clearFolder,
    compression
}<|endoftext|>


<commit_before>/*globals require */

require.config({
    baseUrl: '/',
    paths: {
        'kademlia': 'src',
        'when': 'node_modules/when',
        //'when': 'node_modules/when/when',
        //'when/timed': 'node_modules/when/timed',
        'lodash': 'node_modules/lodash/dist/lodash',
        'Bacon': 'node_modules/baconjs/dist/Bacon',
        'peerjs': 'node_modules/peerjs/dist/peer',
        'bencode-js': 'node_modules/bencode-js/bencode',
        'stringview': 'lib/stringview',
        'jquery': 'lib/jquery/jquery'
    },
    shim: {
        'bencode-js': {
            exports: 'Bencode'
        },
        'peerjs': {
            exports: 'Peer'
        }
    },
    enforceDefine: true
});

require([
    'kademlia/dht',
    'kademlia/id',
    'when/when',
    'when/timed',
    'jquery',
    'lodash'
], function(DHT, Id, when, t, $, _) {
    'use strict';

    var id = param('id') || Id.random();
    var bootstrapId = param('bootstrap');
    var name = "anon";

    var self = {
        id: id,
        host: 'zinc.sitr.us',
        port: 9000
    };
    var dht = new DHT({
        id: id,
        brokerInfo: { host: 'zinc.sitr.us', port: 9000 }
    });

    (function syncStats() {
        var connects = dht.connectEvents;
        var disconnects = dht.closeEvents;
        var connectionEvents = connects.merge(disconnects);

        connectionEvents.onValue(function() {
            var count = dht.routeTable.getNodes().length;
            $('#stats .nodeId').text(self.id);
            $('#stats .peerCount').text(count);
        });
    }());

    var broadcasts = [];

    $('#getName').on('submit', function(event) {
        event.preventDefault();
        $(this).find(':input[name="name"]').each(function() {
            name = this.value;
        });
        $(this).remove();
    });

    $('#upload').on('submit', function(event) {
        event.preventDefault();
        var files = $(this).find(':file').get(0).files;
        for (var i = 0; i < files.length; i += 1) {
            blobToUri(files[i]).then(broadcast);
        }
    });

    dht.messages.onValue(function(incoming) {
        var msg     = incoming[0]
          , respond = incoming[1]
          , params  = msg.a
          , token   = params.token;
        if (msg.q === 'broadcast') {
            if (!broadcasts[token]) {
                params.chunks = new Array(params.len);
                params.received = 0;
                params.start = new Date();
                broadcasts[token] = params;
            }
            else {
                params = broadcasts[token];
            }
            if (typeof params.chunks[msg.a.i] === 'undefined') {
                params.chunks[msg.a.i] = msg.a.chunk;
                params.received += 1;

                rebroadcast(msg.a, respond);

                if (params.received === params.len) {
                    params.data = params.chunks.join('');
                    onbroadcast(params);
                }
            }
        }
    });

    function onbroadcast(params) {
        $('#posts').prepend(
            $('<div/>').append(
                $('<img/>').prop('src', params.data)
            ).append(
                ' '
            ).append(
                $('<span/>').text('posted by ').append(
                    $('<abbr/>').attr('title', params.origin).text(params.by)
                )
            )
        );
        $('#posts > *').slice(10).remove();  // limit to 10 posts
    }

    function broadcast(msg) {
        var chunks = inChunks(msg, 500);
        var peers  = [];
        var params = {
            id: self.id,
            by: name,
            origin: self.id,
            token: Id.random(),
            len: chunks.length
        };

        dht.routeTable.getBuckets().forEach(function(bucket) {
            peers.push.apply(peers, bucket.slice(0, 3));
        });

        var maxRetries = 10;

        peers.forEach(function(peer) {
            (function broadcast_(i, retries) {
                var resp = dht.query(peer, 'broadcast', _.assign({
                    i: i,
                    chunk: chunks[i]
                }, params));
                //t.timeout(500, resp).then(function() {

                resp.then(function() {
                    if (i + 1 < chunks.length) {
                        broadcast_(i + 1, maxRetries);
                    }
                }, function() {
                    if (retries > 0) {
                        setTimeout(function() {
                            broadcast_(i, retries - 1);
                        }, Math.pow(2, maxRetries - retries));
                    }
                });

            }(0, maxRetries));
        });

        onbroadcast(_.assign({
            data: msg
        }, params));
    }

    function rebroadcast(params, respond) {
        var from = params.id;
        respond({
            id: self.id,
            token: params.token,
            i: params.i
        });
        dht.routeTable.getNodes().filter(function(node) {
            return Id.compare(Id.dist(node.id, self.id), Id.dist(node.id, from)) < 0;
        }).forEach(function(node) {
            dht.query(node, 'broadcast', {
                id: self.id,
                by: params.by,
                origin: params.origin,
                token: params.token,
                len: params.len,
                i: params.i,
                chunk: params.chunk
            });
        });
    }

    function inChunks(msg, chunkSize) {
        var chunks = [];
        while (msg.length > chunkSize) {
            chunks.push(msg.slice(0, chunkSize));
            msg = msg.slice(chunkSize);
        }
        return chunks;
    }

    function blobToUri(file) {
        return when.promise(function(resolve) {
            var reader = new FileReader();
            reader.onload = function(event) {
                var uri = event.target.result;
                resolve(uri);
            };
            reader.readAsDataURL(file);
        });
    }

    window.meow = function() {
        var nonce = Math.floor(Math.random() * 10000)
          , data  = "meow"+ nonce;
        broadcast(data);
    };

    // cleanup buffered data
    setInterval(function() {
        var cutoff = new Date() - 600000;
        Object.keys(broadcasts).forEach(function(token) {
            if (broadcasts[token].start < cutoff) {
                delete broadcasts[token];
            }
        });
    }, 600000);

    console.log('ready', self.id, self);

    if (bootstrapId) {
        dht.bootstrap([{
            id: bootstrapId,
            host: "zinc.sitr.us",
            port: 9000
        }]);
    }

    dht.connectEvents.onValue(function(peer) {
        var msg = "connected to "+ peer.id;
        console.log('connection', peer.id, peer);
    });

    dht.closeEvents.onValue(function(id) {
        var msg = "lost connection to"+ id;
        console.log('lost connection', id);
    });

    dht.messages.onError(function(err) {
        console.error(err);
    });

    function param(key) {
        var exp = new RegExp('\\b'+ key +'=([^&=]+)');
        var matches = exp.exec(window.location);
        return matches && matches[1];
    }

    window.self = self;
    window.dht  = dht;
});
<commit_msg>successful transmission!<commit_after>/*globals require */

require.config({
    baseUrl: '/',
    paths: {
        'kademlia': 'src',
        'when': 'node_modules/when',
        //'when': 'node_modules/when/when',
        //'when/timed': 'node_modules/when/timed',
        'lodash': 'node_modules/lodash/dist/lodash',
        'Bacon': 'node_modules/baconjs/dist/Bacon',
        'peerjs': 'node_modules/peerjs/dist/peer',
        'bencode-js': 'node_modules/bencode-js/bencode',
        'stringview': 'lib/stringview',
        'jquery': 'lib/jquery/jquery'
    },
    shim: {
        'bencode-js': {
            exports: 'Bencode'
        },
        'peerjs': {
            exports: 'Peer'
        }
    },
    enforceDefine: true
});

require([
    'kademlia/dht',
    'kademlia/id',
    'when/when',
    'when/timed',
    'jquery',
    'lodash'
], function(DHT, Id, when, t, $, _) {
    'use strict';

    var id = param('id') || Id.random();
    var bootstrapId = param('bootstrap');
    var name = "anon";

    var self = {
        id: id,
        host: 'zinc.sitr.us',
        port: 9000
    };
    var dht = new DHT({
        id: id,
        brokerInfo: { host: 'zinc.sitr.us', port: 9000 }
    });

    (function syncStats() {
        var connects = dht.connectEvents;
        var disconnects = dht.closeEvents;
        var connectionEvents = connects.merge(disconnects);

        connectionEvents.onValue(function() {
            var count = dht.routeTable.getNodes().length;
            $('#stats .nodeId').text(self.id);
            $('#stats .peerCount').text(count);
        });
    }());

    var broadcasts = [];

    $('#getName').on('submit', function(event) {
        event.preventDefault();
        $(this).find(':input[name="name"]').each(function() {
            name = this.value;
        });
        $(this).remove();
    });

    $('#upload').on('submit', function(event) {
        event.preventDefault();
        var files = $(this).find(':file').get(0).files;
        for (var i = 0; i < files.length; i += 1) {
            blobToUri(files[i]).then(broadcast);
        }
    });

    dht.messages.onValue(function(incoming) {
        var msg     = incoming[0]
          , respond = incoming[1]
          , params  = msg.a
          , token   = msg && msg.a && params.token;
        if (msg.q === 'broadcast' && token) {
            if (!broadcasts[token]) {
                params.chunks = new Array(params.len);
                params.received = 0;
                params.start = new Date();
                broadcasts[token] = params;
            }
            else {
                params = broadcasts[token];
            }
            if (typeof params.chunks[msg.a.i] === 'undefined') {
                params.chunks[msg.a.i] = msg.a.chunk;
                params.received += 1;

                rebroadcast(msg.a, respond);

                if (params.received === params.len) {
                    params.data = params.chunks.join('');
                    onbroadcast(params);
                }
            }
        }
    });

    function onbroadcast(params) {
        $('#posts').prepend(
            $('<div/>').append(
                $('<img/>').prop('src', params.data)
            ).append(
                ' '
            ).append(
                $('<span/>').text('posted by ').append(
                    $('<abbr/>').attr('title', params.origin).text(params.by)
                )
            )
        );
        $('#posts > *').slice(10).remove();  // limit to 10 posts
    }

    function broadcast(msg) {
        var chunks = inChunks(msg, 500);
        var peers  = [];
        var params = {
            id: self.id,
            by: name,
            origin: self.id,
            token: Id.random(),
            len: chunks.length
        };

        dht.routeTable.getBuckets().forEach(function(bucket) {
            peers.push.apply(peers, bucket.slice(0, 3));
        });

        var maxRetries = 10;

        peers.forEach(function(peer) {
            (function broadcast_(i, retries) {
                var resp = dht.query(peer, 'broadcast', _.assign({
                    i: i,
                    chunk: chunks[i]
                }, params));
                //t.timeout(500, resp).then(function() {

                resp.then(function() {
                    if (i + 1 < chunks.length) {
                        broadcast_(i + 1, maxRetries);
                    }
                }, function() {
                    if (retries > 0) {
                        setTimeout(function() {
                            broadcast_(i, retries - 1);
                        }, Math.pow(2, maxRetries - retries));
                    }
                });

            }(0, maxRetries));
        });

        onbroadcast(_.assign({
            data: msg
        }, params));
    }

    function rebroadcast(params, respond) {
        var from = params.id;
        respond({
            id: self.id,
            token: params.token,
            i: params.i
        });
        dht.routeTable.getNodes().filter(function(node) {
            return Id.compare(Id.dist(node.id, self.id), Id.dist(node.id, from)) < 0;
        }).forEach(function(node) {
            dht.query(node, 'broadcast', {
                id: self.id,
                by: params.by,
                origin: params.origin,
                token: params.token,
                len: params.len,
                i: params.i,
                chunk: params.chunk
            });
        });
    }

    function inChunks(msg, chunkSize) {
        var chunks = [];
        while (msg.length > chunkSize) {
            chunks.push(msg.slice(0, chunkSize));
            msg = msg.slice(chunkSize);
        }
        if (msg.length > 0) {
            chunks.push(msg);
        }
        return chunks;
    }

    function blobToUri(file) {
        return when.promise(function(resolve) {
            var reader = new FileReader();
            reader.onload = function(event) {
                var uri = event.target.result;
                resolve(uri);
            };
            reader.readAsDataURL(file);
        });
    }

    window.meow = function() {
        var nonce = Math.floor(Math.random() * 10000)
          , data  = "meow"+ nonce;
        broadcast(data);
    };

    // cleanup buffered data
    setInterval(function() {
        var cutoff = new Date() - 600000;
        Object.keys(broadcasts).forEach(function(token) {
            if (broadcasts[token].start < cutoff) {
                delete broadcasts[token];
            }
        });
    }, 600000);

    console.log('ready', self.id, self);

    if (bootstrapId) {
        dht.bootstrap([{
            id: bootstrapId,
            host: "zinc.sitr.us",
            port: 9000
        }]);
    }

    dht.connectEvents.onValue(function(peer) {
        var msg = "connected to "+ peer.id;
        console.log('connection', peer.id, peer);
    });

    dht.closeEvents.onValue(function(id) {
        var msg = "lost connection to"+ id;
        console.log('lost connection', id);
    });

    dht.messages.onError(function(err) {
        console.error(err);
    });

    function param(key) {
        var exp = new RegExp('\\b'+ key +'=([^&=]+)');
        var matches = exp.exec(window.location);
        return matches && matches[1];
    }

    window.self = self;
    window.dht  = dht;
});
<|endoftext|>


<commit_before>/**
 * @author sunag / http://www.sunag.com.br/
 */

import {
	FrontSide,
	LessEqualDepth,
	NoColors,
	NormalBlending,
	ShaderMaterial
} from '../../../../build/three.module.js';

import { NodeBuilder } from '../core/NodeBuilder.js';
import { ColorNode } from '../inputs/ColorNode.js';
import { PositionNode } from '../accessors/PositionNode.js';
import { RawNode } from './nodes/RawNode.js';

function NodeMaterial( vertex, fragment ) {

	ShaderMaterial.call( this );

	var scope = this;

	this.vertex = vertex || new RawNode( new PositionNode( PositionNode.PROJECTION ) );
	this.fragment = fragment || new RawNode( new ColorNode( 0xFF0000 ) );

	this.updaters = [];

}

NodeMaterial.prototype = Object.create( ShaderMaterial.prototype );
NodeMaterial.prototype.constructor = NodeMaterial;
NodeMaterial.prototype.type = "NodeMaterial";

NodeMaterial.prototype.isNodeMaterial = true;

Object.defineProperties( NodeMaterial.prototype, {

	properties: {

		get: function () {

			return this.fragment.properties;

		}

	},

	needsUpdate: {

		set: function ( value ) {

			if ( value === true ) this.version ++;
			this.needsCompile = value;

		},

		get: function () {

			return this.needsCompile;

		}

	}

} );

NodeMaterial.prototype.onBeforeCompile = function ( shader, renderer ) {

	var materialProperties = renderer.properties.get( this );

	if ( this.version !== materialProperties.__version ) {

		this.build( { renderer: renderer } );

		shader.uniforms = this.uniforms;
		shader.vertexShader = this.vertexShader;
		shader.fragmentShader = this.fragmentShader;

	}

};

NodeMaterial.prototype.customProgramCacheKey = function () {

	var hash = this.getHash();

	return hash;

};

NodeMaterial.prototype.getHash = function () {

	var hash = '{';

	hash += '"vertex":' + this.vertex.getHash() + ',\n';
	hash += '"fragment":' + this.fragment.getHash() + '\n';

	hash += '}'

	return hash;

};

NodeMaterial.prototype.updateFrame = function ( frame ) {

	for ( var i = 0; i < this.updaters.length; ++ i ) {

		frame.updateNode( this.updaters[ i ] );

	}

};

NodeMaterial.prototype.build = function ( params ) {

	params = params || {};

	var builder = params.builder || new NodeBuilder();

	builder.setMaterial( this, params.renderer );
	builder.build( this.vertex, this.fragment );

	this.vertexShader = builder.getCode( 'vertex' );
	this.fragmentShader = builder.getCode( 'fragment' );

	this.defines = builder.defines;
	this.uniforms = builder.uniforms;
	this.extensions = builder.extensions;
	this.updaters = builder.updaters;

	this.fog = builder.requires.fog;
	this.lights = builder.requires.lights;

	this.transparent = builder.requires.transparent || this.blending > NormalBlending;

	return this;

};

NodeMaterial.prototype.copy = function ( source ) {

	var uuid = this.uuid;

	for ( var name in source ) {

		this[ name ] = source[ name ];

	}

	this.uuid = uuid;

	if ( source.userData !== undefined ) {

		this.userData = JSON.parse( JSON.stringify( source.userData ) );

	}

	return this;

};

NodeMaterial.prototype.toJSON = function ( meta ) {

	var isRootObject = ( meta === undefined || typeof meta === 'string' );

	if ( isRootObject ) {

		meta = {
			nodes: {}
		};

	}

	if ( meta && ! meta.materials ) meta.materials = {};

	if ( ! meta.materials[ this.uuid ] ) {

		var data = {};

		data.uuid = this.uuid;
		data.type = this.type;

		meta.materials[ data.uuid ] = data;

		if ( this.name !== "" ) data.name = this.name;

		if ( this.size !== undefined ) data.size = this.size;
		if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;

		if ( this.blending !== NormalBlending ) data.blending = this.blending;
		if ( this.flatShading === true ) data.flatShading = this.flatShading;
		if ( this.side !== FrontSide ) data.side = this.side;
		if ( this.vertexColors !== NoColors ) data.vertexColors = this.vertexColors;

		if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
		if ( this.depthTest === false ) data.depthTest = this.depthTest;
		if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;

		if ( this.linewidth !== 1 ) data.linewidth = this.linewidth;
		if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
		if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
		if ( this.scale !== undefined ) data.scale = this.scale;

		if ( this.dithering === true ) data.dithering = true;

		if ( this.wireframe === true ) data.wireframe = this.wireframe;
		if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
		if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
		if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;

		if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
		if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;

		if ( this.morphTargets === true ) data.morphTargets = true;
		if ( this.skinning === true ) data.skinning = true;

		if ( this.visible === false ) data.visible = false;
		if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData;

		data.fog = this.fog;
		data.lights = this.lights;

		data.vertex = this.vertex.toJSON( meta ).uuid;
		data.fragment = this.fragment.toJSON( meta ).uuid;

	}

	meta.material = this.uuid;

	return meta;

};

export { NodeMaterial };
<commit_msg>semicolon<commit_after>/**
 * @author sunag / http://www.sunag.com.br/
 */

import {
	FrontSide,
	LessEqualDepth,
	NoColors,
	NormalBlending,
	ShaderMaterial
} from '../../../../build/three.module.js';

import { NodeBuilder } from '../core/NodeBuilder.js';
import { ColorNode } from '../inputs/ColorNode.js';
import { PositionNode } from '../accessors/PositionNode.js';
import { RawNode } from './nodes/RawNode.js';

function NodeMaterial( vertex, fragment ) {

	ShaderMaterial.call( this );

	var scope = this;

	this.vertex = vertex || new RawNode( new PositionNode( PositionNode.PROJECTION ) );
	this.fragment = fragment || new RawNode( new ColorNode( 0xFF0000 ) );

	this.updaters = [];

}

NodeMaterial.prototype = Object.create( ShaderMaterial.prototype );
NodeMaterial.prototype.constructor = NodeMaterial;
NodeMaterial.prototype.type = "NodeMaterial";

NodeMaterial.prototype.isNodeMaterial = true;

Object.defineProperties( NodeMaterial.prototype, {

	properties: {

		get: function () {

			return this.fragment.properties;

		}

	},

	needsUpdate: {

		set: function ( value ) {

			if ( value === true ) this.version ++;
			this.needsCompile = value;

		},

		get: function () {

			return this.needsCompile;

		}

	}

} );

NodeMaterial.prototype.onBeforeCompile = function ( shader, renderer ) {

	var materialProperties = renderer.properties.get( this );

	if ( this.version !== materialProperties.__version ) {

		this.build( { renderer: renderer } );

		shader.uniforms = this.uniforms;
		shader.vertexShader = this.vertexShader;
		shader.fragmentShader = this.fragmentShader;

	}

};

NodeMaterial.prototype.customProgramCacheKey = function () {

	var hash = this.getHash();

	return hash;

};

NodeMaterial.prototype.getHash = function () {

	var hash = '{';

	hash += '"vertex":' + this.vertex.getHash() + ',\n';
	hash += '"fragment":' + this.fragment.getHash() + '\n';

	hash += '}';

	return hash;

};

NodeMaterial.prototype.updateFrame = function ( frame ) {

	for ( var i = 0; i < this.updaters.length; ++ i ) {

		frame.updateNode( this.updaters[ i ] );

	}

};

NodeMaterial.prototype.build = function ( params ) {

	params = params || {};

	var builder = params.builder || new NodeBuilder();

	builder.setMaterial( this, params.renderer );
	builder.build( this.vertex, this.fragment );

	this.vertexShader = builder.getCode( 'vertex' );
	this.fragmentShader = builder.getCode( 'fragment' );

	this.defines = builder.defines;
	this.uniforms = builder.uniforms;
	this.extensions = builder.extensions;
	this.updaters = builder.updaters;

	this.fog = builder.requires.fog;
	this.lights = builder.requires.lights;

	this.transparent = builder.requires.transparent || this.blending > NormalBlending;

	return this;

};

NodeMaterial.prototype.copy = function ( source ) {

	var uuid = this.uuid;

	for ( var name in source ) {

		this[ name ] = source[ name ];

	}

	this.uuid = uuid;

	if ( source.userData !== undefined ) {

		this.userData = JSON.parse( JSON.stringify( source.userData ) );

	}

	return this;

};

NodeMaterial.prototype.toJSON = function ( meta ) {

	var isRootObject = ( meta === undefined || typeof meta === 'string' );

	if ( isRootObject ) {

		meta = {
			nodes: {}
		};

	}

	if ( meta && ! meta.materials ) meta.materials = {};

	if ( ! meta.materials[ this.uuid ] ) {

		var data = {};

		data.uuid = this.uuid;
		data.type = this.type;

		meta.materials[ data.uuid ] = data;

		if ( this.name !== "" ) data.name = this.name;

		if ( this.size !== undefined ) data.size = this.size;
		if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;

		if ( this.blending !== NormalBlending ) data.blending = this.blending;
		if ( this.flatShading === true ) data.flatShading = this.flatShading;
		if ( this.side !== FrontSide ) data.side = this.side;
		if ( this.vertexColors !== NoColors ) data.vertexColors = this.vertexColors;

		if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
		if ( this.depthTest === false ) data.depthTest = this.depthTest;
		if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;

		if ( this.linewidth !== 1 ) data.linewidth = this.linewidth;
		if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
		if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
		if ( this.scale !== undefined ) data.scale = this.scale;

		if ( this.dithering === true ) data.dithering = true;

		if ( this.wireframe === true ) data.wireframe = this.wireframe;
		if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
		if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
		if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;

		if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
		if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;

		if ( this.morphTargets === true ) data.morphTargets = true;
		if ( this.skinning === true ) data.skinning = true;

		if ( this.visible === false ) data.visible = false;
		if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData;

		data.fog = this.fog;
		data.lights = this.lights;

		data.vertex = this.vertex.toJSON( meta ).uuid;
		data.fragment = this.fragment.toJSON( meta ).uuid;

	}

	meta.material = this.uuid;

	return meta;

};

export { NodeMaterial };
<|endoftext|>


<commit_before>/**
 * Kettle Sample app - multipartForm using code
 *
 * Copyright 2018 OCAD University
 *
 * Licensed under the New BSD license. You may not use this file except in
 * compliance with this License.
 *
 * You may obtain a copy of the License at
 * https://github.com/gpii/universal/LICENSE.txt
 */

"use strict";

var fluid = require("infusion"),
    examples = fluid.registerNamespace("examples");

require("../../kettle.js");

fluid.defaults("examples.uploadConfig", {
    "gradeNames": ["fluid.component"],
    "components": {
        "server": {
            "type": "kettle.server",
            "options": {
                "port": 8081,
                "components": {
                    "imageUpload": {
                        "type": "kettle.middleware.multer",
                        "options": {
                            "formFieldOptions": {
                                "method": "single",
                                "fieldName": "image"
                            },
                            "members": {
                                "storage": "{that}.diskStorage"
                            },
                            "invokers": {
                                "diskStorageDestination": {
                                    "funcName": "examples.uploadConfig.diskStorageDestination"
                                }
                            }
                        }
                    },
                    "app": {
                        "type": "kettle.app",
                        "options": {
                            "requestHandlers": {
                                "imageUploadHandler": {
                                    "type": "examples.uploadConfig.handler",
                                    "route": "/upload",
                                    "method": "post"
                                }
                            }
                        }
                    }
                }
            }
        }
    }
});

examples.uploadConfig.diskStorageDestination = function (req, file, cb) {
    cb(null, "./examples/multipartForm/uploads");
};

fluid.defaults("examples.uploadConfig.handler", {
    gradeNames: "kettle.request.http",
    requestMiddleware: {
        imageUpload: {
            middleware: "{server}.imageUpload"
        }
    },
    invokers: {
        handleRequest: "examples.uploadConfig.handleRequest"
    }
});

examples.uploadConfig.handleRequest = function (request) {
    var uploadedFileDetails = request.req.file;
    request.events.onSuccess.fire({
        message: fluid.stringTemplate("POST request received on path /upload; file %originalName uploaded to %uploadedPath", {originalName: uploadedFileDetails.originalname, uploadedPath: uploadedFileDetails.path})
    });
};

// Construct the server using the above config
examples.uploadConfig();

// Load the client to make a test request
require("./multipartForm-client.js");
<commit_msg>KETTLE-66: update example in light of refactoring.<commit_after>/**
 * Kettle Sample app - multipartForm using code
 *
 * Copyright 2018 OCAD University
 *
 * Licensed under the New BSD license. You may not use this file except in
 * compliance with this License.
 *
 * You may obtain a copy of the License at
 * https://github.com/gpii/universal/LICENSE.txt
 */

"use strict";

var fluid = require("infusion"),
    examples = fluid.registerNamespace("examples");

require("../../kettle.js");

fluid.defaults("examples.uploadConfig", {
    "gradeNames": ["fluid.component"],
    "components": {
        "server": {
            "type": "kettle.server",
            "options": {
                "port": 8081,
                "components": {
                    "imageUpload": {
                        "type": "kettle.middleware.multer",
                        "options": {
                            "formFieldOptions": {
                                "method": "single",
                                "fieldName": "image"
                            },
                            "components": {
                                "storage": {
                                    "type": "kettle.middleware.multer.storage.disk",
                                    "options": {
                                        "destination": "./examples/multipartForm/uploads"
                                    }
                                }
                            }
                        }
                    },
                    "app": {
                        "type": "kettle.app",
                        "options": {
                            "requestHandlers": {
                                "imageUploadHandler": {
                                    "type": "examples.uploadConfig.handler",
                                    "route": "/upload",
                                    "method": "post"
                                }
                            }
                        }
                    }
                }
            }
        }
    }
});

fluid.defaults("examples.uploadConfig.handler", {
    gradeNames: "kettle.request.http",
    requestMiddleware: {
        imageUpload: {
            middleware: "{server}.imageUpload"
        }
    },
    invokers: {
        handleRequest: "examples.uploadConfig.handleRequest"
    }
});

examples.uploadConfig.handleRequest = function (request) {
    var uploadedFileDetails = request.req.file;
    request.events.onSuccess.fire({
        message: fluid.stringTemplate("POST request received on path /upload; file %originalName uploaded to %uploadedPath", {originalName: uploadedFileDetails.originalname, uploadedPath: uploadedFileDetails.path})
    });
};

// Construct the server using the above config
examples.uploadConfig();

// Load the client to make a test request
require("./multipartForm-client.js");
<|endoftext|>


<commit_before>/*
 *
 */

/*
 * オブジェクト構造
 * {
 *   summarydata: {
 *     beginning: ,
 *     duration: ,
 *     durationstopped: ,
 *     work: ,
 *     hr: { max:, min:, avg: },
 *     spd: { max:, min:, avg: },
 *     dist: ,
 *     alt: { max:, min:, avg: },
 *   },
 *   sample: [{
 *     timeoffset:,
 *     spd:,
 *     cad:,
 *     dist:,
 *     lat:,
 *     lon:,
 *     alt:,
 *   }],
 * }
 */

var pwx = {
  summarydata: {},
  sample: [],

  /*
   * xml: DOMParser.parseFromString(xmltext, 'text/html')　しておいて下さい
   */
  readFromXML: function(xml) {
    var obj = {};
    var summaryData = {};
    var result = null;

    var nsResolver = { lookupNamespaceURI : function(prefix) {
      console.log("prefix " + prefix);
      return "http://www.peaksware.com/PWX/1/0";
    }};

    var num = function(name) {
      result = xml.evaluate('/pwx/workout/summarydata/' + name, xml, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, result);
      var elem = result.singleNodeValue;
      if(elem) {
	summaryData[name] = elem.textContent;
	console.log(">>> " + name + " " + summaryData[name]);
      }
    };
    var mma = function(name) {
      var prop = {};
      var found = false;

      result = xml.evaluate('/pwx/workout/summarydata/' + name, xml, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, result);
      var elem = result.singleNodeValue;
      if(elem) {
	prop.max = elem.getAttributeNode('max').textContent;
	prop.min = elem.getAttributeNode('min').textContent;
	prop.avg = elem.getAttributeNode('avg').textContent;
	summaryData[name] = prop;
	console.log(">>> " + name + " max:" + prop.max + " min:" + prop.min + " avg:" + prop.avg);
      }
    }

    num('beginning');
    num('duration');
    num('durationstopped');
    num('work');
    mma('hr');
    mma('spd');
    mma('cad');
    num('dist');
    mma('alt');
    obj.summarydata = summaryData;

    result = null;
    return obj;
  },

  checkCompat: function() {
    return window.DOMParser;
  },
};

/* debug code */
function debugmorpwx() {
  console.log("launch morpwx debug");
  var domParser = new DOMParser();
  var elem = document.getElementById('xmlarea');
  var xml = domParser.parseFromString(elem.value, 'text/xml');
  var obj = pwx.readFromXML(xml);
  console.log("result as follows");
  console.log(obj.summarydata.duration);
  console.log(obj.summarydata.work);
  return false;
};

<commit_msg>created tcx converter<commit_after>/*
 *
 */

/*
 * オブジェクト構造
 * {
 *   summarydata: {
 *     beginning: ,
 *     duration: ,
 *     durationstopped: ,
 *     work: ,
 *     hr: { max:, min:, avg: },
 *     spd: { max:, min:, avg: },
 *     dist: ,
 *     alt: { max:, min:, avg: },
 *   },
 *   sample: [{
 *     timeoffset:,
 *     spd:,
 *     cad:,
 *     dist:,
 *     lat:,
 *     lon:,
 *     alt:,
 *   }],
 * }
 */

var pwx = {
  summarydata: {},
  sample: [],

  /*
   * xml: DOMParser.parseFromString(xmltext, 'text/html')　しておいて下さい
   */
  readFromXML: function(xml) {
    var obj = {};
    var summaryData = {};
    var samples = [];
    var result = null;

    var nsResolver = { lookupNamespaceURI : function(prefix) {
      if(prefix == "p")
	return "http://www.peaksware.com/PWX/1/0";
      else
	return "";
    }};

    result = xml.evaluate('/p:pwx/p:workout/p:text' + name, xml, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, result);
    obj.time = '';

    var num = function(name) {
      result = xml.evaluate('/p:pwx/p:workout/p:summarydata/p:' + name, xml, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, result);
      var elem = result.singleNodeValue;
      if(elem) {
	var text = elem.textContent;
	if(text) {
	  summaryData[name] = text;
	}
      }
    };

    var mma = function(name) {
      var prop = {};
      var found = false;

      result = xml.evaluate('/p:pwx/p:workout/p:summarydata/p:' + name, xml, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, result);
      var elem = result.singleNodeValue;
      if(elem) {
	prop.max = elem.getAttributeNode('max').textContent;
	prop.min = elem.getAttributeNode('min').textContent;
	prop.avg = elem.getAttributeNode('avg').textContent;
	summaryData[name] = prop;
      }
    }

    num('beginning');
    num('duration');
    num('durationstopped');
    num('work');
    mma('hr');
    mma('spd');
    mma('cad');
    num('dist');
    mma('alt');
    obj.summarydata = summaryData;

    result = xml.evaluate('/p:pwx/p:workout/p:sample', xml, nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, result);
    var sampleElem = result.iteratorNext();
    while(sampleElem) {
      var sampleObj = {};
      var setText = function(name) {
	var elem = sampleElem.getChildElement(name);
	if(elem) {
	  var text = elem.textContent;
	  if(text) {
	    sampleObj[name] = text;
	  }
	}
      };

      setText('timeoffset');
      setText('hr');
      setText('spd');
      setText('dist');
      setText('lat');
      setText('lon');
      setText('alt');
      samples.push(sampleObj);

      sampleElem = result.iteratorNext();
    }
    obj.sample = samples;

    result = null;
    return obj;
  },

  checkCompat: function() {
    return window.DOMParser;
  },
};

/* debug code */
function debugmorpwx() {
  console.log("launch morpwx debug");
  var domParser = new DOMParser();
  var elem = document.getElementById('xmlarea');
  var xml = domParser.parseFromString(elem.value, 'text/xml');
  var obj = pwx.readFromXML(xml);
  console.log("result as follows");
  console.log(obj.summarydata.duration);
  console.log(obj.summarydata.work);
  return false;
};

<|endoftext|>


<commit_before>var constants = {
    SHORT_ANSWER: 1,
    MCQ: 2,
    CORRECT_FEEDBACK: "Correct",
    WRONG_FEEDBACK: "Nope",
    QUESTION_PLACEHOLDER: "Enter the Question in Markdown"
};

var ChoiceModel = Backbone.Model.extend({

    idAttribute: "choiceInput",

    defaults: {
        choiceInput: "",
        choiceDisplay: "",
        isCorrect: false
    }

});

//todo -> figure out where to reset collection and switch off event listeners.
var ChoiceCollection = Backbone.Collection.extend({

    model: ChoiceModel,

    initialize: function() {
        this.on("add", this.listenToModelChange, this);

        //http://stackoverflow.com/a/9137772/817277
        _.defer(_.bind(this.addModelChangeListeners, this));

        this.currentModelCid = null;
    },

    addModelChangeListeners: function(model) {
        _.each(this.models, function(model) {
            this.listenToModelChange(model);
        }, this);
    },

    listenToModelChange: function(model) {
        model.on("change:choiceInput", this.addNewEmptyChoice, this);
    },

    addNewEmptyChoice: function(model) {
        console.log("Choice Input:", model.attributes.choiceInput);
        if(this.any({choiceInput: ""})) {
            return;
        }
        this.currentModelCid = model.cid;
        console.log("currentModelCid: ", model.cid);

        //remove duplicates. But if currently being edited model is a duplicate,
        //don't remove it since it is changing on every keystroke and it could be a substring of a previous choice.
        //We have to do this since Backbone does not enforce uniqueness
        //based on `idAttribute` on model.change, but does so only on model.add
        var choiceInputHash = {};
        var modelsToBeRemoved = [];
        _.each(this.models, function(model) {
            var isDupe = !_.isUndefined(choiceInputHash[model.attributes.choiceInput]);
            if(isDupe) {
                if(model.cid !== this.currentModelCid) {
                    modelsToBeRemoved.push(model);
                }
            }
            else {
                choiceInputHash[model.attributes.choiceInput] = model.cid;
            }
        }, this);

        this.remove(modelsToBeRemoved);
        this.add({});
    }
});

//#todo -> Should I just change it the name to `GuessModel` ?
var ShortAnswerSubmitModel = Backbone.Model.extend({

    idAttribute: "guess",

    defaults: {
        guess: null,
        result: null,
        timestamp: null,
        planNumber: null
    }

});

var MCQAnswerModel = ShortAnswerSubmitModel;

var GuessCollection = Backbone.Collection.extend({

    model: ShortAnswerSubmitModel,

    initialize: function() {
        this.on("add", this.ifCorrectTriggerAnsweredCorrectlyEvent, this);
    },

    ifCorrectTriggerAnsweredCorrectlyEvent: function(guess) {
        if(guess.attributes.result) {
            this.trigger("answeredCorrectly", guess);
        }
    }

});

//#todo -> consider changing answer to short-answer to be more explicit.
var QuizModel = Backbone.Model.extend({

    defaults: {
        quizType: constants.MCQ,
        questionInput: "",
        questionDisplay: "",
        answer: ""
    },

    initialize: function() {

        var placeholderChoices = [
            {
                choiceInput: ""
            }
        ];
        placeholderChoices.forEach(function(c) {
            c.choiceDisplay = mdAndMathToHtml(c.choiceInput);
        });

        //todo -> Change choices to choiceCollection as well. To make things explicit, and consistent.
        this.choices = new ChoiceCollection(placeholderChoices);

        this.guessCollection = new GuessCollection();

    }

});

var PlanModel = Backbone.Model.extend({

    defaults: {
        planInput: "",
        planDisplay: "",
    },

    //idAttribute: "planInput" -> Well, it's ok to have a plan in mind and not explictly write it, I guess. Especially for new users.

});

var PlanCollection = Backbone.Collection.extend({

    model: PlanModel

});

var ProblemSolvingModel = Backbone.Model.extend({

    defaults: {
        understandProblemInput: "",
        understandProblemDisplay: "",
        result: null
    },

    initialize: function() {
        this.plans = new PlanCollection();
    }

});

<commit_msg>Added a convenience method to choice collection for MCQs with single answers. Should we have explicit radio buttons and check boxes for students, like in other apps? I have not decided yet?<commit_after>var constants = {
    SHORT_ANSWER: 1,
    MCQ: 2,
    CORRECT_FEEDBACK: "Correct",
    WRONG_FEEDBACK: "Nope",
    QUESTION_PLACEHOLDER: "Enter the Question in Markdown"
};

var ChoiceModel = Backbone.Model.extend({

    idAttribute: "choiceInput",

    defaults: {
        choiceInput: "",
        choiceDisplay: "",
        isCorrect: false
    }

});

//todo -> figure out where to reset collection and switch off event listeners.
var ChoiceCollection = Backbone.Collection.extend({

    model: ChoiceModel,

    initialize: function() {
        this.on("add", this.listenToModelChange, this);

        //http://stackoverflow.com/a/9137772/817277
        _.defer(_.bind(this.addModelChangeListeners, this));

        this.currentModelCid = null;
    },

    addModelChangeListeners: function(model) {
        _.each(this.models, function(model) {
            this.listenToModelChange(model);
        }, this);
    },

    listenToModelChange: function(model) {
        model.on("change:choiceInput", this.addNewEmptyChoice, this);
    },

    addNewEmptyChoice: function(model) {
        console.log("Choice Input:", model.attributes.choiceInput);
        if(this.any({choiceInput: ""})) {
            return;
        }
        this.currentModelCid = model.cid;
        console.log("currentModelCid: ", model.cid);

        //remove duplicates. But if currently being edited model is a duplicate,
        //don't remove it since it is changing on every keystroke and it could be a substring of a previous choice.
        //We have to do this since Backbone does not enforce uniqueness
        //based on `idAttribute` on model.change, but does so only on model.add
        var choiceInputHash = {};
        var modelsToBeRemoved = [];
        _.each(this.models, function(model) {
            var isDupe = !_.isUndefined(choiceInputHash[model.attributes.choiceInput]);
            if(isDupe) {
                if(model.cid !== this.currentModelCid) {
                    modelsToBeRemoved.push(model);
                }
            }
            else {
                choiceInputHash[model.attributes.choiceInput] = model.cid;
            }
        }, this);

        this.remove(modelsToBeRemoved);
        this.add({});
    },

    isSingleAnswerCorrect: function() {
        return this.where({isCorrect: true}).length === 1;
    }
});

//#todo -> Should I just change it the name to `GuessModel` ?
var ShortAnswerSubmitModel = Backbone.Model.extend({

    idAttribute: "guess",

    defaults: {
        guess: null,
        result: null,
        timestamp: null,
        planNumber: null
    }

});

var MCQAnswerModel = ShortAnswerSubmitModel;

var GuessCollection = Backbone.Collection.extend({

    model: ShortAnswerSubmitModel,

    initialize: function() {
        this.on("add", this.ifCorrectTriggerAnsweredCorrectlyEvent, this);
    },

    ifCorrectTriggerAnsweredCorrectlyEvent: function(guess) {
        if(guess.attributes.result) {
            this.trigger("answeredCorrectly", guess);
        }
    }

});

//#todo -> consider changing answer to short-answer to be more explicit.
var QuizModel = Backbone.Model.extend({

    defaults: {
        quizType: constants.MCQ,
        questionInput: "",
        questionDisplay: "",
        answer: ""
    },

    initialize: function() {

        var placeholderChoices = [
            {
                choiceInput: ""
            }
        ];
        placeholderChoices.forEach(function(c) {
            c.choiceDisplay = mdAndMathToHtml(c.choiceInput);
        });

        //todo -> Change choices to choiceCollection as well. To make things explicit, and consistent.
        this.choices = new ChoiceCollection(placeholderChoices);

        this.guessCollection = new GuessCollection();

    }

});

var PlanModel = Backbone.Model.extend({

    defaults: {
        planInput: "",
        planDisplay: "",
    },

    //idAttribute: "planInput" -> Well, it's ok to have a plan in mind and not explictly write it, I guess. Especially for new users.

});

var PlanCollection = Backbone.Collection.extend({

    model: PlanModel

});

var ProblemSolvingModel = Backbone.Model.extend({

    defaults: {
        understandProblemInput: "",
        understandProblemDisplay: "",
        result: null
    },

    initialize: function() {
        this.plans = new PlanCollection();
    }

});

<|endoftext|>


<commit_before>var MC = module.exports = require('emcee')
MC.model('showprofile', require('./models/showprofile.js'))
MC.model('profile', require('./models/profile.js'))
MC.model('package', require('./models/package.js'))
MC.model('keyword', require('./models/keyword.js'))
MC.model('browse', require('./models/browse.js'))
<commit_msg>Remove keyword.js model<commit_after>var MC = module.exports = require('emcee')
MC.model('showprofile', require('./models/showprofile.js'))
MC.model('profile', require('./models/profile.js'))
MC.model('package', require('./models/package.js'))
MC.model('browse', require('./models/browse.js'))
<|endoftext|>


<commit_before>var mongoose = require('mongoose');
var _ = require('underscore');

module.exports = function(wagner) {
  // mongoose.connect('mongodb://localhost:27017/running-events');
  mongoose.connect(process.env.MONGOLAB_URI);

  var Event =
    mongoose.model('Event', require('./schema/Event'), 'Events');
  var numEvents =
    mongoose.model('numEvents', require('./schema/numEvents'), 'numEvents');
  var totalDist =
    mongoose.model('totalDist', require('./schema/totalDist'), 'totalDist');

  var models = {
    Event: Event,
    numEvents: numEvents,
    totalDist: totalDist
  };

  // To ensure DRY-ness, register factories in a loop
  _.each(models, function(value, key) {
    wagner.factory(key, function() {
      return value;
    });
  });

  return models;
};<commit_msg>Fix for mongolab<commit_after>var mongoose = require('mongoose');
var _ = require('underscore');
var uristring =
    // process.env.MONGOLAB_URI ||
    process.env.MONGOHQ_URL ||
    // process.env.PROD_MONGODB ||
    'mongodb://localhost:27017/running-events';

module.exports = function(wagner) {

  // Makes connection asynchronously.  Mongoose will queue up database
  // operations and release them when the connection is complete.
  mongoose.connect(uristring, function (err, res) {
    if (err) {
    console.log ('ERROR connecting to: ' + uristring + '. ' + err);
    } else {
    console.log ('Succeeded connected to: ' + uristring);
    }
  });

  var Event =
    mongoose.model('Event', require('./schema/Event'), 'Events');
  var numEvents =
    mongoose.model('numEvents', require('./schema/numEvents'), 'numEvents');
  var totalDist =
    mongoose.model('totalDist', require('./schema/totalDist'), 'totalDist');

  var models = {
    Event: Event,
    numEvents: numEvents,
    totalDist: totalDist
  };

  // To ensure DRY-ness, register factories in a loop
  _.each(models, function(value, key) {
    wagner.factory(key, function() {
      return value;
    });
  });

  return models;
};<|endoftext|>


<commit_before>define([
    'intern!object',
    'intern/chai!assert',
    'intern/dojo/request'
], function (registerSuite, assert, request) {
    var suite = {
        name: "SOLR Data Query"
    };

    var basicQueries = [
//        ["&q=*:*&rows=10", function (data) {
//           assert.strictEqual(data.response.docs.length, 10);
//        }]
    ];

    var dataModel = {
        "genome": {
            queries: [
                ['q=*:*&rows=0&facet=true&json.facet=%7Bgenome_count:%7Brange:%7Bfield:completion_date,start:"2010-01-01T00:00:00.000Z",end:"2016-01-01T00:00:00.000Z",gap:"%2B1YEAR",other:"before"%7D%7D%7D', function (data) {
                    assert.strictEqual(data.facets.genome_count.buckets.length, 6);
                }]
            ]
        },
        "enzyme_class_ref": {},
        "gene_ontology_ref": {},
        "genome_feature": {
            queries: [
                ['q=*:*&rows=0&fq=feature_type:CDS+AND+annotation:PATRIC&fq={!join+from%3Dgenome_id+to%3Dgenome_id+fromIndex%3Dgenome}taxon_lineage_ids:83332&facet=true&json.facet={stat:{field:{field:figfam_id,limit:-1,allBuckets:true,facet:{genome_count:"unique(genome_id)"}}}}', function (data) {
                    assert.isDefined(data.facets.stat);
                    assert.isArray(data.facets.stat.buckets);
                    assert.isTrue((data.facets.stat.buckets.length > 20));
                }]
            ]
        },
        "genome_sequence": {},
        "id_ref": {},
        "misc_niaid_gsc": {},
        "pathway": {
            queries: [
                ['q=genome_id:83332.12&rows=0&facet=true&json.facet={stat:{field:{field:genome_id,facet:{pathway_count:"unique(pathway_id)"}}}}}', function(data) {
                    assert.isTrue(data.facets.stat.buckets[0].pathway_count > 1);
                }],
                ['q=genome_id:83332.12&rows=0&fq=annotation:PATRIC&facet=true&json.facet={stat:{field:{field:pathway_id,sort:{ec_count:desc},facet:{ec_count:"unique(ec_number)",gene_count:"unique(feature_id)",field:{field:pathway_name}}}}}', function(data){
                    assert.isArray(data.facets.stat.buckets);
                    assert.isTrue(data.facets.stat.buckets.length > 0, 'data.facets.stat.buckets is empty');
                }],
                ['q=annotation:PATRIC&fq={!join+from%3Dgenome_id+to%3Dgenome_id+fromIndex%3Dgenome}genome_status:(Complete+OR+WGS)+AND+taxon_lineage_ids:83332&rows=0&facet=true&json.facet={stat:{field:{field:pathway_id,limit:-1,facet:{ec_count:"unique(ec_number)",genome_count:"unique(genome_id)",genome_ec_count:"unique(genome_ec)"}}}}', function(data) {
                    assert.isArray(data.facets.stat.buckets);
                    assert.isTrue(data.facets.stat.buckets.length > 0, 'data.facets.stat.buckets is empty');
                }]
            ]
        },
        "pathway_ref": {},
        "ppi": {},
        "protein_family_ref": {},
        "sp_gene": {},
        "sp_gene_evidence": {},
        "sp_gene_ref": {},
        "taxonomy": {
            queries: []

        },
        "transcriptomics_experiment": {},
        "transcriptomics_gene": {},
        "transcriptomics_sample": {}
    };

    var filter = [
        "user", "collection", "client", "genome_sequence", "host-resp", "misc_niaid_gsc",
        "proteomics_peptide", "proteomics_protein", "proteomics_experiment"
    ];

    Object.keys(dataModel).filter(function (x) {
        return filter.indexOf(x) == -1
    }).forEach(function (model) {
        var Model = dataModel[model];
        var queries = Model.queries ? basicQueries.concat(Model.queries) : basicQueries;
        queries.forEach(function (bq) {
            var query = bq[0];
            var handler = bq[1];
            suite["GET /" + model + "/?" + query] = function () {
                var dfd = this.async(120000);
                request('http://localhost:3001/' + model + '/?' + query, {
                    headers: {
                        accept: "application/solr+json",
                        "content-type": "application/solrquery+x-www-form-urlencoded"
                    }, handleAs: "json"
                }).then(dfd.callback(handler), dfd.reject.bind(dfd));
                return dfd;
            }
        });
    });

    Object.keys(dataModel).filter(function (x) {
        return filter.indexOf(x) == -1
    }).forEach(function (model) {
        var Model = dataModel[model];
        var queries = Model.queries ? basicQueries.concat(Model.queries) : basicQueries;
        queries.forEach(function (bq) {
            var query = bq[0];
            var handler = bq[1];
            suite["POST /" + model + "/" + query] = function () {
                var dfd = this.async(120000);
                request('http://localhost:3001/' + model + '/', {
                    method: "POST",
                    headers: {
                        accept: "application/solr+json",
                        "content-type": "application/solrquery+x-www-form-urlencoded"
                    },
                    handleAs: "json",
                    data: query
                }).then(dfd.callback(handler), dfd.reject.bind(dfd));
                return dfd;
            }
        });
    });

    registerSuite(suite);
});
<commit_msg>uncomment commented out tests<commit_after>define([
    'intern!object',
    'intern/chai!assert',
    'intern/dojo/request'
], function (registerSuite, assert, request) {
    var suite = {
        name: "SOLR Data Query"
    };

    var basicQueries = [
        ["&q=*:*&rows=10", function (data) {
           assert.strictEqual(data.response.docs.length, 10);
        }]
    ];

    var dataModel = {
        "genome": {
            queries: [
                ['q=*:*&rows=0&facet=true&json.facet=%7Bgenome_count:%7Brange:%7Bfield:completion_date,start:"2010-01-01T00:00:00.000Z",end:"2016-01-01T00:00:00.000Z",gap:"%2B1YEAR",other:"before"%7D%7D%7D', function (data) {
                    assert.strictEqual(data.facets.genome_count.buckets.length, 6);
                }]
            ]
        },
        "enzyme_class_ref": {},
        "gene_ontology_ref": {},
        "genome_feature": {
            queries: [
                ['q=*:*&rows=0&fq=feature_type:CDS+AND+annotation:PATRIC&fq={!join+from%3Dgenome_id+to%3Dgenome_id+fromIndex%3Dgenome}taxon_lineage_ids:83332&facet=true&json.facet={stat:{field:{field:figfam_id,limit:-1,allBuckets:true,facet:{genome_count:"unique(genome_id)"}}}}', function (data) {
                    assert.isDefined(data.facets.stat);
                    assert.isArray(data.facets.stat.buckets);
                    assert.isTrue((data.facets.stat.buckets.length > 20));
                }]
            ]
        },
        "genome_sequence": {},
        "id_ref": {},
        "misc_niaid_gsc": {},
        "pathway": {
            queries: [
                ['q=genome_id:83332.12&rows=0&facet=true&json.facet={stat:{field:{field:genome_id,facet:{pathway_count:"unique(pathway_id)"}}}}}', function(data) {
                    assert.isTrue(data.facets.stat.buckets[0].pathway_count > 1);
                }],
                ['q=genome_id:83332.12&rows=0&fq=annotation:PATRIC&facet=true&json.facet={stat:{field:{field:pathway_id,sort:{ec_count:desc},facet:{ec_count:"unique(ec_number)",gene_count:"unique(feature_id)",field:{field:pathway_name}}}}}', function(data){
                    assert.isArray(data.facets.stat.buckets);
                    assert.isTrue(data.facets.stat.buckets.length > 0, 'data.facets.stat.buckets is empty');
                }],
                ['q=annotation:PATRIC&fq={!join+from%3Dgenome_id+to%3Dgenome_id+fromIndex%3Dgenome}genome_status:(Complete+OR+WGS)+AND+taxon_lineage_ids:83332&rows=0&facet=true&json.facet={stat:{field:{field:pathway_id,limit:-1,facet:{ec_count:"unique(ec_number)",genome_count:"unique(genome_id)",genome_ec_count:"unique(genome_ec)"}}}}', function(data) {
                    assert.isArray(data.facets.stat.buckets);
                    assert.isTrue(data.facets.stat.buckets.length > 0, 'data.facets.stat.buckets is empty');
                }]
            ]
        },
        "pathway_ref": {},
        "ppi": {},
        "protein_family_ref": {},
        "sp_gene": {},
        "sp_gene_evidence": {},
        "sp_gene_ref": {},
        "taxonomy": {
            queries: []

        },
        "transcriptomics_experiment": {},
        "transcriptomics_gene": {},
        "transcriptomics_sample": {}
    };

    var filter = [
        "user", "collection", "client", "genome_sequence", "host-resp", "misc_niaid_gsc",
        "proteomics_peptide", "proteomics_protein", "proteomics_experiment"
    ];

    Object.keys(dataModel).filter(function (x) {
        return filter.indexOf(x) == -1
    }).forEach(function (model) {
        var Model = dataModel[model];
        var queries = Model.queries ? basicQueries.concat(Model.queries) : basicQueries;
        queries.forEach(function (bq) {
            var query = bq[0];
            var handler = bq[1];
            suite["GET /" + model + "/?" + query] = function () {
                var dfd = this.async(120000);
                request('http://localhost:3001/' + model + '/?' + query, {
                    headers: {
                        accept: "application/solr+json",
                        "content-type": "application/solrquery+x-www-form-urlencoded"
                    }, handleAs: "json"
                }).then(dfd.callback(handler), dfd.reject.bind(dfd));
                return dfd;
            }
        });
    });

    Object.keys(dataModel).filter(function (x) {
        return filter.indexOf(x) == -1
    }).forEach(function (model) {
        var Model = dataModel[model];
        var queries = Model.queries ? basicQueries.concat(Model.queries) : basicQueries;
        queries.forEach(function (bq) {
            var query = bq[0];
            var handler = bq[1];
            suite["POST /" + model + "/" + query] = function () {
                var dfd = this.async(120000);
                request('http://localhost:3001/' + model + '/', {
                    method: "POST",
                    headers: {
                        accept: "application/solr+json",
                        "content-type": "application/solrquery+x-www-form-urlencoded"
                    },
                    handleAs: "json",
                    data: query
                }).then(dfd.callback(handler), dfd.reject.bind(dfd));
                return dfd;
            }
        });
    });

    registerSuite(suite);
});
<|endoftext|>