<commit_before>var subarg = require('subarg');

function Prorogram(opts) {
    this.opts = opts || {};

    this.options = {};
    this.commands = {};

    this.raw_arguments = {};
    this.parsed = {};

    this.selected = {};
}

// Prototype Setter/Getter Properties

Object.defineProperty(Prorogram.prototype, "action", {
    enumerable: false,
    get: function() {
        return this.opts.action;
    },
    set: function(fn) {
        this.opts.action = fn;
    }
});

Object.defineProperty(Prorogram.prototype, "required", {
    enumerable: false,
    get: function() {
        return this.opts.required;
    },
    set: function(reqd) {
        this.opts.required = reqd;
    }
});

// Main API Methods

Prorogram.prototype.create = function create(opts) {
    return new Prorogram(opts);
};

Prorogram.prototype.option = function(flag_name, opts, fn) {

    opts = mergeOpts(opts, fn);

    if (typeof flag_name !== 'string') {
        throw new Error("Missing Flag Name");
    }

    opts.flag_name = flag_name = clearLeadingDashes(flag_name);
    opts.shortcut = createShortcut(opts.shortcut, flag_name, this.options);
    opts.description = opts.description || '';

    this.options[flag_name] = opts;

    return this;
};

Prorogram.prototype.command = function(command_name, opts, fn) {

    opts = mergeOpts(opts, fn);

    if (typeof command_name !== 'string') {
        throw new Error("Missing Command Name");
    }

    opts.command_name = command_name;
    opts.description = opts.description || '';

    this.commands[command_name] = this.create(opts);

    return this.commands[command_name];
};

Prorogram.prototype.parse = function(argv) {

    if (!Array.isArray(argv) && typeof argv === 'object') {
        argv = this.rebuildArgArray(argv);
    }

    this.parsed = subarg(argv);
    this.raw_arguments = {
        _: argv
    };

    if (!evalCmd(this, this.parsed, argv, this.commands)) {
        evalFlags(this, this.parsed, this.options);
    }
};

// Core Functional Evaluation Methods

function evalFlags(program, args, options) {

    var value = null,
        err = null,
        flag = null;

    for (var flag_name in options) {

        flag = options[flag_name];
        value = args[flag_name] || args[flag.shortcut];

        if (value) {
            if (flag.required && value === true) {
                err = new Error('Required argument <' + flag.required + '> missing for flag: \'--' + flag_name  + '\'');
            } else {
                err = null;
            }

            program.selected[flag_name] = value;

            if (typeof flag.action === 'function') {
                flag.action(err, value, program);
            }
        }
    }
}

function evalCmd(program, parse_args, argv, commands) {

    var possible_commands = parse_args._,
        command,
        possible,
        remaining_args,
        err;

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

        possible = possible_commands[i];

        for (var command_name in commands) {

            if (possible === command_name || possible === commands[command_name].alias) {

                command = commands[command_name];

                if (command.opts.required && possible_commands[i+1] === undefined) {
                    err = new Error('Required argument <' + command.opts.required + '> missing for command: \'' + command_name + '\'');
                } else {
                    err = null;
                }

                remaining_args = argv.slice(i);
                command.parse(remaining_args);

                if (typeof command.action === 'function') {
                    command.action(err, remaining_args, program);
                }
                return true;
            }
        }
    }
    return false;
}

// Extra Sauce API Methods

Prorogram.prototype.rebuildArgString = function(parsed_args) {
    return unparse(parsed_args).command_string;
};

Prorogram.prototype.rebuildArgArray = function(parsed_args) {
    return unparse(parsed_args);
};

function createShortcut(shortcut, flag_name, options) {

    var exists;

    if (!shortcut) {
        for (var i = 0; i < flag_name.length; i++) {
            exists = false;
            shortcut = flag_name[i];
            for (var flag in options) {
                if (options[flag].shortcut === shortcut) {
                    exists = true;
                    break;
                }
            }
            if (!exists) {
                break;
            }
        }
    } else {
        shortcut = clearLeadingDashes(shortcut);
    }
    return shortcut;
}

function clearLeadingDashes(str) {
    for (var i = 0; i < str.length; i++) {
        if (str[i] !== '-')
            break;
    }
    return str.slice(i);
}

function mergeOpts(opts, fn) {
    opts = opts || {};

    if (typeof opts === 'function' && fn === undefined) {
        fn = opts;
        opts = {};
    }
    if (typeof fn === 'function' && typeof opts.action !== 'function') {
        opts.action = fn;
    }

    return opts;
}

module.exports = exports = new Prorogram();
<commit_msg>adding prorogram as parent property on options and commands<commit_after>var subarg = require('subarg');

function Prorogram(opts) {
    this.opts = opts || {};

    this.options = {};
    this.commands = {};

    this.raw_arguments = {};
    this.parsed = {};

    this.selected = {};
}

// Prototype Setter/Getter Properties

Object.defineProperty(Prorogram.prototype, "action", {
    enumerable: false,
    get: function() {
        return this.opts.action;
    },
    set: function(fn) {
        this.opts.action = fn;
    }
});

Object.defineProperty(Prorogram.prototype, "required", {
    enumerable: false,
    get: function() {
        return this.opts.required;
    },
    set: function(reqd) {
        this.opts.required = reqd;
    }
});

// Main API Methods

Prorogram.prototype.create = function create(opts) {
    return new Prorogram(opts);
};

Prorogram.prototype.option = function(flag_name, opts, fn) {

    opts = mergeOpts(opts, fn);

    if (typeof flag_name !== 'string') {
        throw new Error("Missing Flag Name");
    }

    opts.flag_name = flag_name = clearLeadingDashes(flag_name);
    opts.shortcut = createShortcut(opts.shortcut, flag_name, this.options);
    opts.description = opts.description || '';
    opts.prorogram = this;

    this.options[flag_name] = opts;

    return this;
};

Prorogram.prototype.command = function(command_name, opts, fn) {

    opts = mergeOpts(opts, fn);

    if (typeof command_name !== 'string') {
        throw new Error("Missing Command Name");
    }

    opts.command_name = command_name;
    opts.description = opts.description || '';
    opts.prorogram = this;

    this.commands[command_name] = this.create(opts);

    return this.commands[command_name];
};

Prorogram.prototype.parse = function(argv) {

    if (!Array.isArray(argv) && typeof argv === 'object') {
        argv = this.rebuildArgArray(argv);
    }

    this.parsed = subarg(argv);
    this.raw_arguments = {
        _: argv
    };

    if (!evalCmd(this, this.parsed, argv, this.commands)) {
        evalFlags(this, this.parsed, this.options);
    }
};

// Core Functional Evaluation Methods

function evalFlags(program, args, options) {

    var value = null,
        err = null,
        flag = null;

    for (var flag_name in options) {

        flag = options[flag_name];
        value = args[flag_name] || args[flag.shortcut];

        if (value) {
            if (flag.required && value === true) {
                err = new Error('Required argument <' + flag.required + '> missing for flag: \'--' + flag_name  + '\'');
            } else {
                err = null;
            }

            program.selected[flag_name] = value;

            if (typeof flag.action === 'function') {
                flag.action(err, value, program);
            }
        }
    }
}

function evalCmd(program, parse_args, argv, commands) {

    var possible_commands = parse_args._,
        command,
        possible,
        remaining_args,
        err;

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

        possible = possible_commands[i];

        for (var command_name in commands) {

            if (possible === command_name || possible === commands[command_name].alias) {

                command = commands[command_name];

                if (command.opts.required && possible_commands[i+1] === undefined) {
                    err = new Error('Required argument <' + command.opts.required + '> missing for command: \'' + command_name + '\'');
                } else {
                    err = null;
                }

                remaining_args = argv.slice(i);
                command.parse(remaining_args);

                if (typeof command.action === 'function') {
                    command.action(err, remaining_args, program);
                }
                return true;
            }
        }
    }
    return false;
}

// Extra Sauce API Methods

Prorogram.prototype.rebuildArgString = function(parsed_args) {
    return unparse(parsed_args).command_string;
};

Prorogram.prototype.rebuildArgArray = function(parsed_args) {
    return unparse(parsed_args);
};

function createShortcut(shortcut, flag_name, options) {

    var exists;

    if (!shortcut) {
        for (var i = 0; i < flag_name.length; i++) {
            exists = false;
            shortcut = flag_name[i];
            for (var flag in options) {
                if (options[flag].shortcut === shortcut) {
                    exists = true;
                    break;
                }
            }
            if (!exists) {
                break;
            }
        }
    } else {
        shortcut = clearLeadingDashes(shortcut);
    }
    return shortcut;
}

function clearLeadingDashes(str) {
    for (var i = 0; i < str.length; i++) {
        if (str[i] !== '-')
            break;
    }
    return str.slice(i);
}

function mergeOpts(opts, fn) {
    opts = opts || {};

    if (typeof opts === 'function' && fn === undefined) {
        fn = opts;
        opts = {};
    }
    if (typeof fn === 'function' && typeof opts.action !== 'function') {
        opts.action = fn;
    }

    return opts;
}

module.exports = exports = new Prorogram();
<|endoftext|>


<commit_before>
function getQueryVariable(variable)
{
       var query = window.location.search.substring(1);
       var vars = query.split("&");
       for (var i=0;i<vars.length;i++) {
               var pair = vars[i].split("=");
               if(pair[0] == variable){return pair[1];}
       }
       return(false);
}
<commit_msg>Delete main.js<commit_after><|endoftext|>


<commit_before>// # ########################### #
// # Sample AT&T M2X trigger app #
// # ########################### #

var util = require("util");
var express = require("express");
var bodyParser = require("body-parser");

// Define from/to constants used to form and send each notification email
var EMAIL_FROM = "ns8783@intl.att.com";
var EMAIL_RCPT = "ns8783@intl.att.com";

// Define a subject for the email
//
// Example:
//
// var EMAIL_SUBJECT = "Temperature reached limit";
var EMAIL_SUBJECT = "Trigger notification";

// Define a content for the email
//
// Example:
//
// var EMAIL_BODY =
//     "Temperature measured by the birdi device has reached the limit.\n" +
//     "Current temperature is %s oC";
//
// In this example we use data from the trigger event that comes in each request
// the API sends to us. Check out below where we form the body to see what other data
// is available.
var EMAIL_BODY = "Current value: %s";

// Initialize express application that will handle trigger requests from the API
var app = express();

// Heroku sets the PORT environment variable with the port it expects the application
// to listen for connections. If you are going to run this application outside
// Heroku, you can set the variable, or change this to whatever fits your needs.
app.set("port", process.env.PORT || 5000);

// bodyParser makes sure the JSON request data from the API comes as an object
app.use(bodyParser.json());

// Initialize SendGrid object
var sendgrid = require("sendgrid")(
    process.env.SENDGRID_USERNAME,
    process.env.SENDGRID_PASSWORD
);

// Define HTTP endpoint that will receive trigger requests from AT&T M2X API
app.post("/email-trigger", function(req, res) {

    // In order to include more information in our email we pass the
    // current value for the stream that triggered this event.
    //
    // To see which data comes with the request, please check the
    // AT&T M2X API documentation:
    // http://m2x.att.com/developer/documentation/v2/device#Test-Trigger
    var body = util.format(EMAIL_BODY, req.body.value);

    sendgrid.send({
        from: EMAIL_FROM,
        to: EMAIL_RCPT,
        subject: EMAIL_SUBJECT,
        text: body
    });

    res.send("OK");
});

app.get("/status", function(req, res) {
    res.send("Application is running!");
});

app.listen(app.get("port"), function() {
  console.log("Node app is running at localhost:" + app.get("port"));
});
<commit_msg>M2X trigger 2 by Nao<commit_after>// # ########################### #
// # Sample AT&T M2X trigger app #
// # ########################### #

var util = require("util");
var express = require("express");
var bodyParser = require("body-parser");

// Define from/to constants used to form and send each notification email
var EMAIL_FROM = "ns8783@intl.att.com";
var EMAIL_RCPT = "nao@saitoinc.net";

// Define a subject for the email
//
// Example:
//
// var EMAIL_SUBJECT = "Temperature reached limit";
var EMAIL_SUBJECT = "Trigger notification";

// Define a content for the email
//
// Example:
//
// var EMAIL_BODY =
//     "Temperature measured by the birdi device has reached the limit.\n" +
//     "Current temperature is %s oC";
//
// In this example we use data from the trigger event that comes in each request
// the API sends to us. Check out below where we form the body to see what other data
// is available.
var EMAIL_BODY = "Current value: %s";

// Initialize express application that will handle trigger requests from the API
var app = express();

// Heroku sets the PORT environment variable with the port it expects the application
// to listen for connections. If you are going to run this application outside
// Heroku, you can set the variable, or change this to whatever fits your needs.
app.set("port", process.env.PORT || 5000);

// bodyParser makes sure the JSON request data from the API comes as an object
app.use(bodyParser.json());

// Initialize SendGrid object
var sendgrid = require("sendgrid")(
    process.env.SENDGRID_USERNAME,
    process.env.SENDGRID_PASSWORD
);

// Define HTTP endpoint that will receive trigger requests from AT&T M2X API
app.post("/email-trigger", function(req, res) {

    // In order to include more information in our email we pass the
    // current value for the stream that triggered this event.
    //
    // To see which data comes with the request, please check the
    // AT&T M2X API documentation:
    // http://m2x.att.com/developer/documentation/v2/device#Test-Trigger
    var body = util.format(EMAIL_BODY, req.body.value);

    sendgrid.send({
        from: EMAIL_FROM,
        to: EMAIL_RCPT,
        subject: EMAIL_SUBJECT,
        text: body
    });

    res.send("OK");
});

app.get("/status", function(req, res) {
    res.send("Application is running!");
});

app.listen(app.get("port"), function() {
  console.log("Node app is running at localhost:" + app.get("port"));
});
<|endoftext|>


<commit_before>import electron from 'electron';
import { app, BrowserWindow, Menu, dialog, shell } from 'electron';
import moment from 'moment';
import path from 'path';
import setupEvents from './installers/setupEvents';

let mainWindow = null;
let willQuit = false;

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 800,
    minWidth: 800,
    height: 600,
    fullscreenable: false,
    backgroundColor: '#403F4D',
    icon: path.join(__dirname, 'assets/png/128x128.png')
  });
  mainWindow.loadURL('file://' + __dirname + '/index.html');
}

function manageRefresh() {
  const time = moment('24:00:00', 'hh:mm:ss').diff(moment(), 'seconds');
  setTimeout(
    midnightTask,
    time*1000
  );

  function midnightTask() {
    mainWindow.reload();
  }
}

function menuSetup() {
  const menuTemplate = [
    {
      label: 'todometer',
      submenu: [
        {
          label: 'About',
          click: () => {
            dialog.showMessageBox(mainWindow, {
              type: 'info',
              title: 'About',
              message: 'todometer is built by Cassidy Williams',
              detail: 'You can find her on GitHub and Twitter as @cassidoo, or on her website cassidoo.co.',
              icon: path.join(__dirname, 'assets/png/64x64.png')
            });
          }
        },
        {
          label: 'Contribute',
          click: () => {
            shell.openExternal('http://github.com/cassidoo/todometer');
          }
        },
        {
          type: 'separator'
        /* For debugging
        }, {
          label: 'Dev tools',
          click: () => {
            mainWindow.webContents.openDevTools();
          }
          */
        }, {
          label: 'Quit',
          accelerator: 'CommandOrControl+Q',
          click: () => {
            app.quit();
          }
        }
      ]
    },
    {
      label: 'Edit',
      submenu: [
        {role: 'undo'},
        {role: 'redo'},
        {role: 'cut'},
        {role: 'copy'},
        {role: 'paste'},
        {role: 'delete'},
        {role: 'selectall'}
      ]
    },
    {
      label: 'View',
      submenu: [
        {role: 'reload'},
        {role: 'togglefullscreen'},
        {role: 'minimize'},
        {role: 'hide'},
        {role: 'close'}
      ]
    }
  ];
  const menu = Menu.buildFromTemplate(menuTemplate);
  Menu.setApplicationMenu(menu);
}

app.on('ready', () => {
  // Squirrel events have to be handled before anything else
  if (setupEvents.handleSquirrelEvent()) {
    // squirrel event handled and app will exit in 1000ms, so don't do anything else
    return;
  }
  createWindow();
  menuSetup();

  electron.powerMonitor.on('resume', () => {
    mainWindow.reload();
    console.log('reloaded');
  });

  mainWindow.on('close', (e) => {
    if (willQuit) {
      mainWindow = null;
    } else {
      e.preventDefault();
      mainWindow.hide();
    }
  });

  manageRefresh();
});

app.on('activate', () => mainWindow.show());
app.on('before-quit', () => willQuit = true);
<commit_msg>Fix #3 and #17 by adding temp non-null main window<commit_after>import electron from 'electron';
import { app, BrowserWindow, Menu, dialog, shell } from 'electron';
import moment from 'moment';
import path from 'path';
import setupEvents from './installers/setupEvents';

let mainWindow = { show: () => { console.log('show'); } }; // temp object while app loads
let willQuit = false;

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 800,
    minWidth: 800,
    height: 600,
    fullscreenable: false,
    backgroundColor: '#403F4D',
    icon: path.join(__dirname, 'assets/png/128x128.png')
  });
  mainWindow.loadURL('file://' + __dirname + '/index.html');
}

function manageRefresh() {
  const time = moment('24:00:00', 'hh:mm:ss').diff(moment(), 'seconds');
  setTimeout(
    midnightTask,
    time*1000
  );

  function midnightTask() {
    mainWindow.reload();
  }
}

function menuSetup() {
  const menuTemplate = [
    {
      label: 'todometer',
      submenu: [
        {
          label: 'About',
          click: () => {
            dialog.showMessageBox(mainWindow, {
              type: 'info',
              title: 'About',
              message: 'todometer is built by Cassidy Williams',
              detail: 'You can find her on GitHub and Twitter as @cassidoo, or on her website cassidoo.co.',
              icon: path.join(__dirname, 'assets/png/64x64.png')
            });
          }
        },
        {
          label: 'Contribute',
          click: () => {
            shell.openExternal('http://github.com/cassidoo/todometer');
          }
        },
        {
          type: 'separator'
        /* For debugging
        }, {
          label: 'Dev tools',
          click: () => {
            mainWindow.webContents.openDevTools();
          }
          */
        }, {
          label: 'Quit',
          accelerator: 'CommandOrControl+Q',
          click: () => {
            app.quit();
          }
        }
      ]
    },
    {
      label: 'Edit',
      submenu: [
        {role: 'undo'},
        {role: 'redo'},
        {role: 'cut'},
        {role: 'copy'},
        {role: 'paste'},
        {role: 'delete'},
        {role: 'selectall'}
      ]
    },
    {
      label: 'View',
      submenu: [
        {role: 'reload'},
        {role: 'togglefullscreen'},
        {role: 'minimize'},
        {role: 'hide'},
        {role: 'close'}
      ]
    }
  ];
  const menu = Menu.buildFromTemplate(menuTemplate);
  Menu.setApplicationMenu(menu);
}

app.on('ready', () => {
  // Squirrel events have to be handled before anything else
  if (setupEvents.handleSquirrelEvent()) {
    // squirrel event handled and app will exit in 1000ms, so don't do anything else
    return;
  }
  createWindow();
  menuSetup();

  electron.powerMonitor.on('resume', () => {
    mainWindow.reload();
    console.log('reloaded');
  });

  mainWindow.on('close', (e) => {
    if (willQuit) {
      mainWindow = null;
    } else {
      e.preventDefault();
      mainWindow.hide();
    }
  });

  manageRefresh();
});

app.on('activate', () => mainWindow.show());
app.on('before-quit', () => willQuit = true);
<|endoftext|>


<commit_before>const electron = require('electron')
const app = electron.app // Module to control application life.
process.env.directory = process.env.directory || app.getAppPath()
const BrowserWindow = electron.BrowserWindow // Module to create native browser window.
const ipc = electron.ipcMain
const dialog = electron.dialog

require('./server')
var settings = require('./helpers/settings')

var http = require('http')
var fs = require('fs-extra')
var path = require('path')
var unzip = require('unzip2');
var GeoJson = require('./helpers/rebuild-geojson')

ipc.on('show_configuration', function (event, arg) {
  try {
    var _defaults = settings.defaults
    var _results = {
      'directory': settings.getDataDirectory() || _defaults.data_directory,
      'station': settings.getStation() || _defaults.station,
      'baseUrl': settings.getBaseUrl(),
      'shared_secret': settings.getSharedSecret(),
      'locale': settings.getLocale() || _defaults.locale,
      'community_lands': !(settings.getCommunityLandsServer() === undefined || settings.getCommunityLandsToken() === undefined)
    }
    console.log(_results)
    event.sender.send('has_configuration', _results)
  } catch (err) {
    event.sender.send('has_configuration', [])
  }
})

ipc.on('backup_submissions', function (event, arg) {
  var options = {
    hostname: 'localhost',
    port: settings.getPort() || 3000,
    path: '/save/all',
    method: 'GET'
  }
  http.request(options, function (res) {
    var data = ''
    res.on('data', function (chunk) {
      data += chunk
    })
    res.on('end', function () {
      event.sender.send('backup_submissions_complete', data)
    })
  }).on('error', function (e) {
    event.sender.send('backup_submissions_complete', '{"error":true, "code":"could_not_connect", "message":"Could not connect to server"}')
  }).end()
})

ipc.on('check_last_backup', function (event, arg) {
  var options = {
    hostname: 'localhost',
    port: settings.getPort() || 3000,
    path: '/save/status',
    method: 'GET'
  }
  http.request(options, function (res) {
    var data = ''
    res.on('data', function (chunk) {
      data += chunk
    })
    res.on('end', function () {
      event.sender.send('has_last_backup', data)
    })
  }).end()
})

ipc.on('form_delete', function (event, arg) {
  var folder = settings.getUserFormsDirectory()
  fs.readdir(folder, function (err, files) {
    if (err) {
      event.sender.send('has_form_delete')
    } else {
      var found = false
      for (var i in files) {
        if (files[i] === arg) {
          fs.unlinkSync(path.join(folder, files[i]))
          event.sender.send('has_form_delete')
          found = true
          break
        }
      }
      if (!found)
        event.sender.send('has_form_delete')
    }
  })
})

ipc.on('form_list', function (event, arg) {
  var folder = settings.getUserFormsDirectory();
  fs.readdir(folder, function (err, files) {
    var data = { forms: [] }
    if (err) {
      event.sender.send('has_form_list', data)
    } else {
      data.forms = files
      event.sender.send('has_form_list', data)
    }
  })
})

ipc.on('select_data_directory', function (event, arg) {
  var options = {
    properties: ['openDirectory'],
    defaultPath: settings.getDataDirectory()
  }
  dialog.showOpenDialog(mainWindow, options, function (folder) {
    if (folder) {
      event.sender.send('has_select_data_directory', folder)
    }
  })
})

ipc.on('select_form', function (event, arg) {
  var options = {
    properties: ['openFile', 'multiSelections'],
    filters: [ { name: 'XML', extensions: ['xml'] } ]
  }
  dialog.showOpenDialog(mainWindow, options, function (arr) {
    if (arr !== undefined) {
      var destDir = settings.getUserFormsDirectory()
      var uploaded = {
        count: arr.length,
        names: []
      }
      for (var index in arr) {
        var source = arr[index]
        var filename = path.basename(source)
        var target = path.join(destDir, filename)
        fs.copySync(source, target)
        uploaded.names.push(filename)
      }
      event.sender.send('has_select_form', uploaded)
    }
  })
})

ipc.on('filter_list', function (event, arg) {
  var options = {
    hostname: 'localhost',
    port: settings.getPort() || 3000,
    path: '/mapfilter/filters',
    method: 'GET'
  }
  http.request(options, function (res) {
    var data = ''
    res.on('data', function (chunk) {
      data += chunk
    })
    res.on('end', function () {
      event.sender.send('has_filter_list', data)
    })
  }).on('error', function (e) {
    event.sender.send('has_filter_list', '{"error":true, "code":"could_not_connect", "message":"Could not connect to server"}')
  }).end()
})

ipc.on('settings_list', function (event, arg) {
  settings.get(function(err, selected) {
    if (err) {
      event.sender.send('has_settings_list', settings.defaults)
    } else {
      var defaults = settings.defaults
      for (var key in selected)
        defaults[key] = selected[key]
      event.sender.send('has_settings_list', defaults)
    }
  })
})

ipc.on('settings_save', function (event, arg) {
  settings.save(arg, function (err) {
    if (err) {
      event.sender.send('has_settings_save', '{"error",true, "code":"could_not_save_settings", "message":"Could not save settings file"}')
    } else {
      event.sender.send('has_settings_save', '{"error":false}')
    }
  })
})

ipc.on('list_map_layers', function (event, arg) {
  fs.readdir(settings.getTilesDirectory(), function(err, files) {
    if (err)
      event.sender.send('has_list_map_layers', [])
    else {
      var arr = []
      for (var i = 0; i < files.length; i++)
        arr.push({name: files[i], value: files[i]});
      event.sender.send('has_list_map_layers', arr);
    }
  });
});

ipc.on('import_files', function(event, args) {
  var options = {
    properties: ['openFile'],
    filters: [ { name: 'ZIP', extensions: ['zip'] } ]
  };

  dialog.showOpenDialog(mainWindow, options, function(file) {
    if (file) {
      var source = '' + file;
      var target = path.dirname(settings.getSubmissionsDirectory());

      var complete = function(err) {
        if (err) {
          event.sender.send('has_import_files', { error: true, code: 'import_delete_failed', ex: err });
        } else {
          try {
            fs.createReadStream(source)
            .pipe(unzip.Extract({ path: target }))
            .on('close', function() {
              GeoJson.generate(function(err_json, details) {
                if (err_json)
                  event.sender.send('has_import_files', err_json);
                else
                  event.sender.send('has_import_files', { error: false, details: details });
              });
            });
          } catch (e) {
            console.log(e);
            event.sender.send('has_import_files', { error: true, code: 'import_unzip_failed', ex: e });
          }
        }
      };

      if (args.mode == 'merge')
        complete(null);
      else
        fs.emptydir(path.join(target, 'Submissions'), complete);
    } else {
      event.sender.send('has_import_files', { error: true, code: 'import_cancelled' });
    }
  });
});

ipc.on('community_lands_backup', function(event, arg) {
  if (settings.getCommunityLandsServer()) {
    var options = {
      hostname: 'localhost',
      port: settings.getPort() || 3000,
      path: '/backup/latest',
      method: 'GET'
    }
    http.request(options, function (res) {
      var data = ''
      res.on('data', function (chunk) {
        data += chunk
      })
      res.on('end', function () {
        event.sender.send('has_community_lands_backup', data)
      })
    }).on('error', function (e) {
      event.sender.send('has_community_lands_backup', '{"error":true, "code":"could_not_connect", "message":"Could not connect to server"}')
    }).end()
  } else {
    event.sender.send('has_community_lands_backup', '{"error":true, "code":"community_lands_not_configured", "message":"Community Lands connection not configured"}')
  }
})

ipc.on('community_lands_status', function (event, arg) {
  if (settings.getCommunityLandsServer()) {
    var options = {
      hostname: 'localhost',
      port: settings.getPort() || 3000,
      path: '/backup/status',
      method: 'GET'
    }
    http.request(options, function (res) {
      var data = ''
      res.on('data', function (chunk) {
        data += chunk
      })
      res.on('end', function () {
        event.sender.send('has_community_lands_status', data)
      })
    }).on('error', function (e) {
      event.sender.send('has_community_lands_status', null)
    }).end()
  } else {
    event.sender.send('has_community_lands_status', null)
  }
})

ipc.on('community_lands_online', function (event, arg) {
  event.sender.send('has_community_lands_online', arg)
})

var FiltersDir = settings.getFiltersDirectory()
try {
  fs.mkdirpSync(FiltersDir)
} catch (e) { // It's ok
}
fs.watch(FiltersDir, function (evt, filename) {
  mainWindow.reload()
})

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
var mainWindow = null

// Quit when all windows are closed.
app.on('window-all-closed', function () {
  app.quit()
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', function () {
  // Create the browser window.
  mainWindow = new BrowserWindow({minWidth: 400, minHeight: 400})

  // and load the index.html of the app.
  mainWindow.loadURL('file://' + __dirname + '/index.html?locale=' + (settings.getLocale() || 'en'))

  // Open the DevTools.
  mainWindow.openDevTools()

  // Emitted when the window is closed.
  mainWindow.on('closed', function () {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null
  })
})
<commit_msg>Turn off dev tools.<commit_after>const electron = require('electron')
const app = electron.app // Module to control application life.
process.env.directory = process.env.directory || app.getAppPath()
const BrowserWindow = electron.BrowserWindow // Module to create native browser window.
const ipc = electron.ipcMain
const dialog = electron.dialog

require('./server')
var settings = require('./helpers/settings')

var http = require('http')
var fs = require('fs-extra')
var path = require('path')
var unzip = require('unzip2');
var GeoJson = require('./helpers/rebuild-geojson')

ipc.on('show_configuration', function (event, arg) {
  try {
    var _defaults = settings.defaults
    var _results = {
      'directory': settings.getDataDirectory() || _defaults.data_directory,
      'station': settings.getStation() || _defaults.station,
      'baseUrl': settings.getBaseUrl(),
      'shared_secret': settings.getSharedSecret(),
      'locale': settings.getLocale() || _defaults.locale,
      'community_lands': !(settings.getCommunityLandsServer() === undefined || settings.getCommunityLandsToken() === undefined)
    }
    console.log(_results)
    event.sender.send('has_configuration', _results)
  } catch (err) {
    event.sender.send('has_configuration', [])
  }
})

ipc.on('backup_submissions', function (event, arg) {
  var options = {
    hostname: 'localhost',
    port: settings.getPort() || 3000,
    path: '/save/all',
    method: 'GET'
  }
  http.request(options, function (res) {
    var data = ''
    res.on('data', function (chunk) {
      data += chunk
    })
    res.on('end', function () {
      event.sender.send('backup_submissions_complete', data)
    })
  }).on('error', function (e) {
    event.sender.send('backup_submissions_complete', '{"error":true, "code":"could_not_connect", "message":"Could not connect to server"}')
  }).end()
})

ipc.on('check_last_backup', function (event, arg) {
  var options = {
    hostname: 'localhost',
    port: settings.getPort() || 3000,
    path: '/save/status',
    method: 'GET'
  }
  http.request(options, function (res) {
    var data = ''
    res.on('data', function (chunk) {
      data += chunk
    })
    res.on('end', function () {
      event.sender.send('has_last_backup', data)
    })
  }).end()
})

ipc.on('form_delete', function (event, arg) {
  var folder = settings.getUserFormsDirectory()
  fs.readdir(folder, function (err, files) {
    if (err) {
      event.sender.send('has_form_delete')
    } else {
      var found = false
      for (var i in files) {
        if (files[i] === arg) {
          fs.unlinkSync(path.join(folder, files[i]))
          event.sender.send('has_form_delete')
          found = true
          break
        }
      }
      if (!found)
        event.sender.send('has_form_delete')
    }
  })
})

ipc.on('form_list', function (event, arg) {
  var folder = settings.getUserFormsDirectory();
  fs.readdir(folder, function (err, files) {
    var data = { forms: [] }
    if (err) {
      event.sender.send('has_form_list', data)
    } else {
      data.forms = files
      event.sender.send('has_form_list', data)
    }
  })
})

ipc.on('select_data_directory', function (event, arg) {
  var options = {
    properties: ['openDirectory'],
    defaultPath: settings.getDataDirectory()
  }
  dialog.showOpenDialog(mainWindow, options, function (folder) {
    if (folder) {
      event.sender.send('has_select_data_directory', folder)
    }
  })
})

ipc.on('select_form', function (event, arg) {
  var options = {
    properties: ['openFile', 'multiSelections'],
    filters: [ { name: 'XML', extensions: ['xml'] } ]
  }
  dialog.showOpenDialog(mainWindow, options, function (arr) {
    if (arr !== undefined) {
      var destDir = settings.getUserFormsDirectory()
      var uploaded = {
        count: arr.length,
        names: []
      }
      for (var index in arr) {
        var source = arr[index]
        var filename = path.basename(source)
        var target = path.join(destDir, filename)
        fs.copySync(source, target)
        uploaded.names.push(filename)
      }
      event.sender.send('has_select_form', uploaded)
    }
  })
})

ipc.on('filter_list', function (event, arg) {
  var options = {
    hostname: 'localhost',
    port: settings.getPort() || 3000,
    path: '/mapfilter/filters',
    method: 'GET'
  }
  http.request(options, function (res) {
    var data = ''
    res.on('data', function (chunk) {
      data += chunk
    })
    res.on('end', function () {
      event.sender.send('has_filter_list', data)
    })
  }).on('error', function (e) {
    event.sender.send('has_filter_list', '{"error":true, "code":"could_not_connect", "message":"Could not connect to server"}')
  }).end()
})

ipc.on('settings_list', function (event, arg) {
  settings.get(function(err, selected) {
    if (err) {
      event.sender.send('has_settings_list', settings.defaults)
    } else {
      var defaults = settings.defaults
      for (var key in selected)
        defaults[key] = selected[key]
      event.sender.send('has_settings_list', defaults)
    }
  })
})

ipc.on('settings_save', function (event, arg) {
  settings.save(arg, function (err) {
    if (err) {
      event.sender.send('has_settings_save', '{"error",true, "code":"could_not_save_settings", "message":"Could not save settings file"}')
    } else {
      event.sender.send('has_settings_save', '{"error":false}')
    }
  })
})

ipc.on('list_map_layers', function (event, arg) {
  fs.readdir(settings.getTilesDirectory(), function(err, files) {
    if (err)
      event.sender.send('has_list_map_layers', [])
    else {
      var arr = []
      for (var i = 0; i < files.length; i++)
        arr.push({name: files[i], value: files[i]});
      event.sender.send('has_list_map_layers', arr);
    }
  });
});

ipc.on('import_files', function(event, args) {
  var options = {
    properties: ['openFile'],
    filters: [ { name: 'ZIP', extensions: ['zip'] } ]
  };

  dialog.showOpenDialog(mainWindow, options, function(file) {
    if (file) {
      var source = '' + file;
      var target = path.dirname(settings.getSubmissionsDirectory());

      var complete = function(err) {
        if (err) {
          event.sender.send('has_import_files', { error: true, code: 'import_delete_failed', ex: err });
        } else {
          try {
            fs.createReadStream(source)
            .pipe(unzip.Extract({ path: target }))
            .on('close', function() {
              GeoJson.generate(function(err_json, details) {
                if (err_json)
                  event.sender.send('has_import_files', err_json);
                else
                  event.sender.send('has_import_files', { error: false, details: details });
              });
            });
          } catch (e) {
            console.log(e);
            event.sender.send('has_import_files', { error: true, code: 'import_unzip_failed', ex: e });
          }
        }
      };

      if (args.mode == 'merge')
        complete(null);
      else
        fs.emptydir(path.join(target, 'Submissions'), complete);
    } else {
      event.sender.send('has_import_files', { error: true, code: 'import_cancelled' });
    }
  });
});

ipc.on('community_lands_backup', function(event, arg) {
  if (settings.getCommunityLandsServer()) {
    var options = {
      hostname: 'localhost',
      port: settings.getPort() || 3000,
      path: '/backup/latest',
      method: 'GET'
    }
    http.request(options, function (res) {
      var data = ''
      res.on('data', function (chunk) {
        data += chunk
      })
      res.on('end', function () {
        event.sender.send('has_community_lands_backup', data)
      })
    }).on('error', function (e) {
      event.sender.send('has_community_lands_backup', '{"error":true, "code":"could_not_connect", "message":"Could not connect to server"}')
    }).end()
  } else {
    event.sender.send('has_community_lands_backup', '{"error":true, "code":"community_lands_not_configured", "message":"Community Lands connection not configured"}')
  }
})

ipc.on('community_lands_status', function (event, arg) {
  if (settings.getCommunityLandsServer()) {
    var options = {
      hostname: 'localhost',
      port: settings.getPort() || 3000,
      path: '/backup/status',
      method: 'GET'
    }
    http.request(options, function (res) {
      var data = ''
      res.on('data', function (chunk) {
        data += chunk
      })
      res.on('end', function () {
        event.sender.send('has_community_lands_status', data)
      })
    }).on('error', function (e) {
      event.sender.send('has_community_lands_status', null)
    }).end()
  } else {
    event.sender.send('has_community_lands_status', null)
  }
})

ipc.on('community_lands_online', function (event, arg) {
  event.sender.send('has_community_lands_online', arg)
})

var FiltersDir = settings.getFiltersDirectory()
try {
  fs.mkdirpSync(FiltersDir)
} catch (e) { // It's ok
}
fs.watch(FiltersDir, function (evt, filename) {
  mainWindow.reload()
})

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
var mainWindow = null

// Quit when all windows are closed.
app.on('window-all-closed', function () {
  app.quit()
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', function () {
  // Create the browser window.
  mainWindow = new BrowserWindow({minWidth: 400, minHeight: 400})

  // and load the index.html of the app.
  mainWindow.loadURL('file://' + __dirname + '/index.html?locale=' + (settings.getLocale() || 'en'))

  // Open the DevTools.
  // mainWindow.openDevTools()

  // Emitted when the window is closed.
  mainWindow.on('closed', function () {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null
  })
})
<|endoftext|>


<commit_before>var mongoose = require('mongoose');
var feedparser = require('feedparser')
var request = require('request');

var feedSchema = mongoose.Schema({
    title:            String,
    description:      String,
    link:             String,
    xmlUrl:           String,
    date:             { type: Date, default: Date.now },
    pubDate:          { type: Date, default: Date.now },
    author:           String,
    language:         String,
    image:            { title: String, url: String },
    favicon:          String,
    copyright:        String,
    generator:        String,
    categories:       [String]
});

function connect(uri, database, port) {
    port = typeof port !== 'undefined' ? port : 27017;
    mongoose.connect(uri, database, port);

    mongoose.connection.on('error', function(e){
        console.log("Could not connect to MongoDB: "+e.message);
        process.exit(1);
    });

    mongoose.connection.once('open', function callback () {
        console.log("Connection to MongoDB was successful.");
    });
}

function addFeed(uri) {
    //TODO CHECK IF EXISTING, ELSE MAKE REQUEST AND PARSE
    request(createRequest(uri), handleResponse);
}

function createRequest(uri) {
    var request = { uri: uri };
    return request;
}

function handleResponse(error, response, body) {
    if(error != null) {
        console.log('error: '+error);
    }
    else if (response.statusCode == 200) {
        feedparser.parseString(body)
        .on('meta', saveFeedMeta)
        .on('article', saveArticle);
    }
    else if (response.statusCode == 304) {
        //HTTP status code for not modified, do nothing
    }
    else {
        console.log('HTTP status code received that can not be handled by this module: '+response.statusCode);
    }
}

function saveFeedMeta(meta) {

}

function saveArticle(article) {

}

exports.connect = connect;
exports.addFeed = addFeed;
<commit_msg>Added mongoose model for feed.<commit_after>var mongoose = require('mongoose');
var feedparser = require('feedparser')
var request = require('request');

var feedSchema = mongoose.Schema({
    title:            String,
    description:      String,
    link:             String,
    xmlUrl:           String,
    date:             { type: Date, default: Date.now },
    pubDate:          { type: Date, default: Date.now },
    author:           String,
    language:         String,
    image:            { title: String, url: String },
    favicon:          String,
    copyright:        String,
    generator:        String,
    categories:       [String]
});

var Feed = mongoose.model('Feed', feedSchema);

function connect(uri, database, port) {
    port = typeof port !== 'undefined' ? port : 27017;
    mongoose.connect(uri, database, port);

    mongoose.connection.on('error', function(e){
        console.log("Could not connect to MongoDB: "+e.message);
        process.exit(1);
    });

    mongoose.connection.once('open', function callback () {
        console.log("Connection to MongoDB was successful.");
    });
}

function addFeed(uri) {
    //TODO CHECK IF EXISTING, ELSE MAKE REQUEST AND PARSE
    request(createRequest(uri), handleResponse);
}

function createRequest(uri) {
    var request = { uri: uri };
    return request;
}

function handleResponse(error, response, body) {
    if(error != null) {
        console.log('error: '+error);
    }
    else if (response.statusCode == 200) {
        feedparser.parseString(body)
        .on('meta', saveFeedMeta)
        .on('article', saveArticle);
    }
    else if (response.statusCode == 304) {
        //HTTP status code for not modified, do nothing
    }
    else {
        console.log('HTTP status code received that can not be handled by this module: '+response.statusCode);
    }
}

function saveFeedMeta(meta) {

}

function saveArticle(article) {

}

exports.connect = connect;
exports.addFeed = addFeed;
<|endoftext|>


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

let transpilations = {};
let zwitterionJSON = {
    files: {}
};
let io;

const builder = createBuilder();

const chokidar = require('chokidar');
const program = require('commander');
const fs = require('fs');
const mkdirp = require('mkdirp');

program
    .version('0.0.8')
    .option('-s, --serve-dir [serveDir]', 'The directory to serve files from; the root directory of the server')
    .option('-h, --http', 'Use HTTP 1.x (the default is HTTP 2)')
    .option('-c, --cert-path [certPath]', 'Specify path to SSL certificate')
    .option('-k, --key-path [keyPath]', 'Specify path to SSL key')
    .option('-o, --output-dir [outputDir]', 'Specify the output directory for transpiled files (the default is in-memory transpilation only)')
    .option('-b, --build', 'Transpile all files specified in the files property in zwitterion.json to the corresponding location in the specified output directory (--output-dir)')
    .option('-t, --type-check-level [typeCheckLevel]', 'Specify the level of type checking (none, warn, error)')
    .parse(process.argv);

const serveDir = program.serveDir || '';
const httpVersion = program.http ? 1 : 2;
const keyPath = program.keyPath;
const certPath = program.certPath;
const outputDir = program.outputDir;
const typeCheckLevel = program.typeCheckLevel;
const build = program.build;

try {
    zwitterionJSON = JSON.parse(fs.readFileSync('zwitterion.json'));
}
catch(error) {
    fs.writeFileSync('zwitterion.json', JSON.stringify(zwitterionJSON, null, 4));
}

if (build) {
    if (!outputDir) {
        throw new Error('You must specify an output directory from the command line, --output-dir [outputDir]');
    }

    mkdirp.sync(outputDir);
    const filePaths = Object.keys(zwitterionJSON.files);
    filePaths.forEach((filePath) => {
        try {
            const directoriesWithFile = filePath.split('/');
            if (directoriesWithFile.length > 1) {
                const directories = directoriesWithFile.slice(0, -1).join('/');
                mkdirp.sync(`${outputDir}/${directories}`);
            }

            if (filePath === `browser-config.js`) {
                fs.writeFileSync(`${outputDir}/browser-config.js`, getBrowserConfig());
            }
            else if (filePath === `system.js.map`) {
                fs.writeFileSync(`${outputDir}/system.js.map`, getSystemJSSourceMap());
            }
            else {
                const fileEnding = filePath.slice(filePath.lastIndexOf('.'));
                if (fileEnding === '.ts') {
                    builder.compile(`${serveDir}/${filePath}`).then((output) => {
                        fs.writeFileSync(`${outputDir}/${filePath}`, output.source);
                    }, (error) => {
                        console.log(error);
                    });
                }
                else {
                    fs.writeFileSync(`${outputDir}/${filePath}`, fs.readFileSync(`${serveDir}/${filePath}`));
                }
            }
        }
        catch(error) {
            console.log(error);
        }
    });

    return;
}

let watcher = configureFileWatching(serveDir);
createServer(builder, httpVersion, keyPath, certPath, outputDir, typeCheckLevel, serveDir);

function writeZwitterionJSON() {
    fs.writeFileSync('zwitterion.json', JSON.stringify(zwitterionJSON, null, 4));
}

function configureFileWatching(serveDir) {
    return chokidar.watch([]).on('change', (path) => {
        const fileEnding = path.slice(path.lastIndexOf('.'));

        if (fileEnding === '.ts') {
            const relativeFilePath = path.replace(`${serveDir}/`, '');
            const isChildImport = !zwitterionJSON.files[relativeFilePath].parentImport;
            compile(isChildImport, serveDir, relativeFilePath).then((source) => {
                transpilations[relativeFilePath] = source;
                reloadBrowser();
            });
        }
        else {
            reloadBrowser();
        }
    });
}

function reloadBrowser() {
    io.emit('reload');
}

function createServer(builder, httpVersion, keyPath, certPath, outputDir, typeCheckLevel, serveDir) {
    const static = require('node-static');
    const fileServer = new static.Server(`${process.cwd()}/${serveDir}`);
    const httpServerPromise = httpVersion === 2 ? createHTTP2Server(builder, fileServer, keyPath, certPath) : createHTTPServer(builder, fileServer);
    httpServerPromise.then((httpServer) => {
        io = require('socket.io')(httpServer);
        httpServer.listen(8000, (error) => {
            if (error) {
                console.log(error);
            }
            else {
                console.log('zwitterion server listening on port 8000');
            }
        });
    }, (error) => {
        console.log(error);
    });
}

function createHTTPServer(builder, fileServer) {
    return new Promise((resolve, reject) => {
        resolve(require('http').createServer(handler(fileServer)));
    });
}

function createHTTP2Server(builder, fileServer, keyPath, certPath) {
    return new Promise((resolve, reject) => {
        getCertAndKey(keyPath, certPath).then((certAndKey) => {
            const options = {
                key: certAndKey.key,
                cert: certAndKey.cert
            };

            resolve(require('http2').createServer(options, handler(fileServer)));
        }, (error) => {
            console.log(error);
        });
    });
}

function getCertAndKey(keyPath, certPath) {
    return new Promise((resolve, reject) => {
        const fs = require('fs');
        const defaultKeyPath = `localhost.key`;
        const defaultCertPath = `localhost.cert`;

        try {
            const key = fs.readFileSync(keyPath || defaultKeyPath);
            const cert = fs.readFileSync(certPath || defaultCertPath);

            resolve({
                key,
                cert
            });
        }
        catch(error) {
            if (!keyPath && !certPath) {
                createCertAndKey(defaultKeyPath, defaultCertPath).then((certAndKey) => {
                    resolve(certAndKey);
                }, (error) => {
                    console.log(error);
                });
            }
            else {
                throw error;
            }
        }
    });
}

function handler(fileServer) {
    return (req, res) => {
        const absoluteFilePath = `${process.cwd()}${req.url}`;
        const relativeFilePath = req.url.slice(1);
        const fileExtension = relativeFilePath.slice(relativeFilePath.lastIndexOf('.'));

        const isChildImport = isSystemImportRequest(req);
        writeRelativeFilePathToZwitterionJSON(relativeFilePath || 'index.html', isChildImport);
        watcher.add(`${serveDir}/${relativeFilePath}` || `${serveDir}/index.html`);
        fileExtension === '.ts' ? buildAndServe(req, res, relativeFilePath) : serveWithoutBuild(fileServer, req, res);
    };
}

function writeRelativeFilePathToZwitterionJSON(relativeFilePath, isChildImport) {
    const newRelativeFilePath = relativeFilePath.indexOf(serveDir) === 0 ? relativeFilePath.replace(`${serveDir}/`, '') : relativeFilePath;

    zwitterionJSON.files[newRelativeFilePath] = {
        parentImport: !isChildImport
    };
    writeZwitterionJSON();
}

function buildAndServe(req, res, relativeFilePath) {
    const transpilation = transpilations[relativeFilePath];
    if (transpilation) {
        res.end(transpilation);
    }
    else {
        const isChildImport = isSystemImportRequest(req);
        compile(isChildImport, serveDir, relativeFilePath).then((source) => {
            transpilations[relativeFilePath] = source;
            res.end(transpilations[relativeFilePath]);
        });
    }
}

function compile(isChildImport, serveDir, relativeFilePath) {
    return new Promise((resolve, reject) => {
        builder.compile(`${serveDir}/${relativeFilePath}`, null, {
            minify: true
        }).then((output) => {
            const source = prepareSource(isChildImport, relativeFilePath, output.source);
            resolve(source);
        }, (error) => {
            console.log(error);
        });
    });
}

function prepareSource(isChildImport, relativeFilePath, rawSource) {
    if (isChildImport) {
        return rawSource;
    }
    else {
        const escapedSource = rawSource.replace(/\\/g, '\\\\');
        const preparedSource = `
            System.define(System.normalizeSync('${relativeFilePath}'), \`
                ${escapedSource}
            \`);
        `;
        return preparedSource;
    }
}

function isSystemImportRequest(req) {
    return req.headers.accept && req.headers.accept.includes('application/x-es-module');
}

function serveWithoutBuild(fileServer, req, res) {
    req.addListener('end', () => {
        if (req.url === '/browser-config.js') {
            res.end(getBrowserConfig());
        }
        else if (req.url === '/system.js.map') {
            res.end(getSystemJSSourceMap());
        }
        else {
            fileServer.serve(req, res, (error, result) => {
                if (error && error.status === 404) {
                    fileServer.serveFile('/index.html', 200, {}, req, res);
                }
            });
        }
    }).resume();
}

function getBrowserConfig() {
    const systemJS = fs.readFileSync('node_modules/systemjs/dist/system.js');
    const socketIO = fs.readFileSync('node_modules/socket.io-client/dist/socket.io.min.js');
    const tsImportsConfig = fs.readFileSync('node_modules/zwitterion/ts-imports-config.js');
    const socketIOConfig = fs.readFileSync('node_modules/zwitterion/socket-io-config.js');

    return `${systemJS}${socketIO}${tsImportsConfig}${socketIOConfig}`;
}

function getSystemJSSourceMap() {
    return fs.readFileSync('node_modules/systemjs/dist/system.js.map');
}

function createBuilder() {
    const Builder = require('systemjs-builder');

    const builder = new Builder();

    //TODO redo this config, get rid of everything that is unnecessary, becuase I believe there might be quite a bit of it
    builder.config({
        transpiler: 'ts',
        typescriptOptions: {
            target: 'es5',
            module: 'system'
        },
        meta: {
            '*.ts': {
                loader: 'ts'
            }
        },
        packages: {
            '/': {
                defaultExtension: 'ts'
            },
            ts: {
                main: 'plugin.js'
            },
            typescript: {
                main: 'typescript.js',
                meta: {
                    'typescript.js': {
                        exports: 'ts'
                    }
                }
            }
        },
        map: {
            ts: './node_modules/plugin-typescript/lib/',
            typescript: './node_modules/typescript/lib/'
        }
    });

    return builder;
}

function createCertAndKey(keyPath, certPath) {
    return new Promise((resolve, reject) => {
        const pem = require('pem');

        pem.createCertificate({
            selfSigned: true
        }, (error, keys) => {
            if (error) {
                console.log(error);
            }
            else {
                fs.writeFileSync(keyPath, keys.serviceKey);
                fs.writeFileSync(certPath, keys.certificate);

                resolve({
                    key: keys.serviceKey,
                    cert: keys.certificate
                });
            }
        });
    });
}
<commit_msg>prepare rewriting to output dir<commit_after>#!/usr/bin/env node

let transpilations = {};
let zwitterionJSON = {
    files: {}
};
let io;

const builder = createBuilder();

const chokidar = require('chokidar');
const program = require('commander');
const fs = require('fs');
const mkdirp = require('mkdirp');

program
    .version('0.0.8')
    .option('-s, --serve-dir [serveDir]', 'The directory to serve files from; the root directory of the server')
    .option('-h, --http', 'Use HTTP 1.x (the default is HTTP 2)')
    .option('-c, --cert-path [certPath]', 'Specify path to SSL certificate')
    .option('-k, --key-path [keyPath]', 'Specify path to SSL key')
    .option('-o, --output-dir [outputDir]', 'Specify the output directory for transpiled files (the default is in-memory transpilation only)')
    .option('-b, --build', 'Transpile all files specified in the files property in zwitterion.json to the corresponding location in the specified output directory (--output-dir)')
    .option('-t, --type-check-level [typeCheckLevel]', 'Specify the level of type checking (none, warn, error)')
    .parse(process.argv);

const serveDir = program.serveDir || '';
const httpVersion = program.http ? 1 : 2;
const keyPath = program.keyPath;
const certPath = program.certPath;
const outputDir = program.outputDir;
const typeCheckLevel = program.typeCheckLevel;
const build = program.build;

try {
    zwitterionJSON = JSON.parse(fs.readFileSync('zwitterion.json'));
}
catch(error) {
    fs.writeFileSync('zwitterion.json', JSON.stringify(zwitterionJSON, null, 4));
}

if (build) {
    if (!outputDir) {
        throw new Error('You must specify an output directory from the command line, --output-dir [outputDir]');
    }

    mkdirp.sync(outputDir);
    const filePaths = Object.keys(zwitterionJSON.files);
    filePaths.forEach((filePath) => {
        try {
            const directoriesWithFile = filePath.split('/');
            if (directoriesWithFile.length > 1) {
                const directories = directoriesWithFile.slice(0, -1).join('/');
                mkdirp.sync(`${outputDir}/${directories}`);
            }

            if (filePath === `browser-config.js`) {
                fs.writeFileSync(`${outputDir}/browser-config.js`, getBrowserConfig());
            }
            else if (filePath === `system.js.map`) {
                fs.writeFileSync(`${outputDir}/system.js.map`, getSystemJSSourceMap());
            }
            else {
                const fileEnding = filePath.slice(filePath.lastIndexOf('.'));
                if (fileEnding === '.ts') {
                    const isChildImport = !zwitterionJSON.files[relativeFilePath].parentImport;
                    compile(isChildImport, serveDir, filePath).then((source) => {
                        fs.writeFileSync(`${outputDir}/${filePath}`, source);
                    });
                }
                else {
                    fs.writeFileSync(`${outputDir}/${filePath}`, fs.readFileSync(`${serveDir}/${filePath}`));
                }
            }
        }
        catch(error) {
            console.log(error);
        }
    });

    return;
}

let watcher = configureFileWatching(serveDir);
createServer(builder, httpVersion, keyPath, certPath, outputDir, typeCheckLevel, serveDir);

function writeZwitterionJSON() {
    fs.writeFileSync('zwitterion.json', JSON.stringify(zwitterionJSON, null, 4));
}

function configureFileWatching(serveDir) {
    return chokidar.watch([]).on('change', (path) => {
        const fileEnding = path.slice(path.lastIndexOf('.'));

        if (fileEnding === '.ts') {
            const relativeFilePath = path.replace(`${serveDir}/`, '');
            const isChildImport = !zwitterionJSON.files[relativeFilePath].parentImport;
            compile(isChildImport, serveDir, relativeFilePath).then((source) => {
                transpilations[relativeFilePath] = source;
                reloadBrowser();
            });
        }
        else {
            reloadBrowser();
        }
    });
}

function reloadBrowser() {
    io.emit('reload');
}

function createServer(builder, httpVersion, keyPath, certPath, outputDir, typeCheckLevel, serveDir) {
    const static = require('node-static');
    const fileServer = new static.Server(`${process.cwd()}/${serveDir}`);
    const httpServerPromise = httpVersion === 2 ? createHTTP2Server(builder, fileServer, keyPath, certPath) : createHTTPServer(builder, fileServer);
    httpServerPromise.then((httpServer) => {
        io = require('socket.io')(httpServer);
        httpServer.listen(8000, (error) => {
            if (error) {
                console.log(error);
            }
            else {
                console.log('zwitterion server listening on port 8000');
            }
        });
    }, (error) => {
        console.log(error);
    });
}

function createHTTPServer(builder, fileServer) {
    return new Promise((resolve, reject) => {
        resolve(require('http').createServer(handler(fileServer)));
    });
}

function createHTTP2Server(builder, fileServer, keyPath, certPath) {
    return new Promise((resolve, reject) => {
        getCertAndKey(keyPath, certPath).then((certAndKey) => {
            const options = {
                key: certAndKey.key,
                cert: certAndKey.cert
            };

            resolve(require('http2').createServer(options, handler(fileServer)));
        }, (error) => {
            console.log(error);
        });
    });
}

function getCertAndKey(keyPath, certPath) {
    return new Promise((resolve, reject) => {
        const fs = require('fs');
        const defaultKeyPath = `localhost.key`;
        const defaultCertPath = `localhost.cert`;

        try {
            const key = fs.readFileSync(keyPath || defaultKeyPath);
            const cert = fs.readFileSync(certPath || defaultCertPath);

            resolve({
                key,
                cert
            });
        }
        catch(error) {
            if (!keyPath && !certPath) {
                createCertAndKey(defaultKeyPath, defaultCertPath).then((certAndKey) => {
                    resolve(certAndKey);
                }, (error) => {
                    console.log(error);
                });
            }
            else {
                throw error;
            }
        }
    });
}

function handler(fileServer) {
    return (req, res) => {
        const absoluteFilePath = `${process.cwd()}${req.url}`;
        const relativeFilePath = req.url.slice(1);
        const fileExtension = relativeFilePath.slice(relativeFilePath.lastIndexOf('.'));

        const isChildImport = isSystemImportRequest(req);
        writeRelativeFilePathToZwitterionJSON(relativeFilePath || 'index.html', isChildImport);
        watcher.add(`${serveDir}/${relativeFilePath}` || `${serveDir}/index.html`);
        fileExtension === '.ts' ? buildAndServe(req, res, relativeFilePath) : serveWithoutBuild(fileServer, req, res);
    };
}

function writeRelativeFilePathToZwitterionJSON(relativeFilePath, isChildImport) {
    const newRelativeFilePath = relativeFilePath.indexOf(serveDir) === 0 ? relativeFilePath.replace(`${serveDir}/`, '') : relativeFilePath;

    zwitterionJSON.files[newRelativeFilePath] = {
        parentImport: !isChildImport
    };
    writeZwitterionJSON();
}

function buildAndServe(req, res, relativeFilePath) {
    const transpilation = transpilations[relativeFilePath];
    if (transpilation) {
        res.end(transpilation);
    }
    else {
        const isChildImport = isSystemImportRequest(req);
        compile(isChildImport, serveDir, relativeFilePath).then((source) => {
            transpilations[relativeFilePath] = source;
            res.end(transpilations[relativeFilePath]);
        });
    }
}

function compile(isChildImport, serveDir, relativeFilePath) {
    return new Promise((resolve, reject) => {
        builder.compile(`${serveDir}/${relativeFilePath}`, null, {
            minify: true
        }).then((output) => {
            const source = prepareSource(isChildImport, relativeFilePath, output.source);
            resolve(source);
        }, (error) => {
            console.log(error);
        });
    });
}

function prepareSource(isChildImport, relativeFilePath, rawSource) {
    if (isChildImport) {
        return rawSource;
    }
    else {
        const escapedSource = rawSource.replace(/\\/g, '\\\\');
        const preparedSource = `
            System.define(System.normalizeSync('${relativeFilePath}'), \`
                ${escapedSource}
            \`);
        `;
        return preparedSource;
    }
}

function isSystemImportRequest(req) {
    return req.headers.accept && req.headers.accept.includes('application/x-es-module');
}

function serveWithoutBuild(fileServer, req, res) {
    req.addListener('end', () => {
        if (req.url === '/browser-config.js') {
            res.end(getBrowserConfig());
        }
        else if (req.url === '/system.js.map') {
            res.end(getSystemJSSourceMap());
        }
        else {
            fileServer.serve(req, res, (error, result) => {
                if (error && error.status === 404) {
                    fileServer.serveFile('/index.html', 200, {}, req, res);
                }
            });
        }
    }).resume();
}

function getBrowserConfig() {
    const systemJS = fs.readFileSync('node_modules/systemjs/dist/system.js');
    const socketIO = fs.readFileSync('node_modules/socket.io-client/dist/socket.io.min.js');
    const tsImportsConfig = fs.readFileSync('node_modules/zwitterion/ts-imports-config.js');
    const socketIOConfig = fs.readFileSync('node_modules/zwitterion/socket-io-config.js');

    return `${systemJS}${socketIO}${tsImportsConfig}${socketIOConfig}`;
}

function getSystemJSSourceMap() {
    return fs.readFileSync('node_modules/systemjs/dist/system.js.map');
}

function createBuilder() {
    const Builder = require('systemjs-builder');

    const builder = new Builder();

    //TODO redo this config, get rid of everything that is unnecessary, becuase I believe there might be quite a bit of it
    builder.config({
        transpiler: 'ts',
        typescriptOptions: {
            target: 'es5',
            module: 'system'
        },
        meta: {
            '*.ts': {
                loader: 'ts'
            }
        },
        packages: {
            '/': {
                defaultExtension: 'ts'
            },
            ts: {
                main: 'plugin.js'
            },
            typescript: {
                main: 'typescript.js',
                meta: {
                    'typescript.js': {
                        exports: 'ts'
                    }
                }
            }
        },
        map: {
            ts: './node_modules/plugin-typescript/lib/',
            typescript: './node_modules/typescript/lib/'
        }
    });

    return builder;
}

function createCertAndKey(keyPath, certPath) {
    return new Promise((resolve, reject) => {
        const pem = require('pem');

        pem.createCertificate({
            selfSigned: true
        }, (error, keys) => {
            if (error) {
                console.log(error);
            }
            else {
                fs.writeFileSync(keyPath, keys.serviceKey);
                fs.writeFileSync(certPath, keys.certificate);

                resolve({
                    key: keys.serviceKey,
                    cert: keys.certificate
                });
            }
        });
    });
}
<|endoftext|>


<commit_before>/**
 * Created by Samuel Gratzl on 15.12.2014.
 */
define(function (require) {
  'use strict';
  var $ = require('jquery');
  var data = require('../caleydo_core/data');
  var vis = require('../caleydo_core/vis');
  var C = require('../caleydo_core/main');
  var template = require('../clue_demo/template');
  var cmode = require('../caleydo_provenance/mode');

  var helper = document.querySelector('#mainhelper');
  var elems = template.create(document.body, {
    app: 'StratomeX.js'
  });
  elems.header.addMainMenu('New Workspace', elems.reset.bind(elems));
  var graph = elems.graph;
  {
    while(helper.firstChild) {
      elems.$main.node().appendChild(helper.firstChild);
    }
    helper.remove();
  }

  var datavalues;
  var stratomex = require('./StratomeX').create(document.getElementById('stratomex'), graph);

  var lineup =  require('./lineup').create(document.getElementById('tab_stratifications'),function (rowStrat) {
    if (rowStrat.desc.type === 'stratification') {
      rowStrat.origin().then(function (d) {
        var colStrat = null;
        if (d.desc.type === 'matrix') {
          if(rowStrat.idtypes[0] !== d.idtypes[0]) {
            d = d.t; //transpose
          }
          //look for stratification that has the other idtype and the same origin
          var available = lineup.rawData,
              targetType = d.idtypes[1];
          available = available.filter(function(ds) {
            return ds.idtype === targetType && ds.desc.origin === d.desc.fqname && ds.desc.ngroups === 1;
          });
          colStrat = available[0];
        }
        if (d.desc.type === 'table') {
          stratomex.addData(rowStrat, rowStrat);
        } else {
          stratomex.addData(rowStrat, d, colStrat);
        }
      });
    } else if (rowStrat.desc.type === 'vector') {
      rowStrat.stratification().then(function(d) {
        stratomex.addData(d, d);
      });
    }
  });

  var lineupData =  require('./lineup').createData(document.getElementById('tab_data'),function (vector) {
    stratomex.addDependentData(vector);
  });

  var $left_data = $('#databrowser');
  if (cmode.getMode().exploration < 0.8) {
    $left_data.hide();
  } else {
    $left_data.show();
  }
  function updateLineUp() {
    if (lineup.lineup) {
      lineup.lineup.update();
    }
    if (lineupData.lineup) {
      lineupData.lineup.update();
    }
  }
  $('a[data-toggle="tab"]').on('shown.bs.tab', function() {
    updateLineUp();
  });

  function updateBounds() {
    var bounds = C.bounds(stratomex.parent);
    stratomex.setBounds(bounds.x, bounds.y, bounds.w, bounds.h);
    updateLineUp();
  }
  elems.on('modeChanged', function(event, new_) {
    if (new_.exploration < 0.8) {
      $left_data.hide(); //.animate({height: 'hide'});
    } else {
      $left_data.show(); //.animate({height: 'show'});
    }

    //for the animations to end
    setTimeout(updateBounds, 700);
  });
  $(window).on('resize', updateBounds);
  updateBounds();
  //var notes = require('./notes').create(document.getElementById('notes'), graph);

  function splitAndConvert(arr) {
    var strat = arr.filter(function(d) { return d.desc.type === 'stratification'});

    strat = strat.concat(arr.filter(function(d) { return d.desc.type === 'vector'}));

    //convert all matrices to slices with their corresponding name
    return Promise.all(arr.filter(function(d) { return d.desc.type === 'matrix'}).map(function(d) {
      return d.cols().then(function(colNames) {
        var cols = d.ncol, r = [];
        for(var i = 0; i < cols; ++i) {
          var v = d.slice(i);
          v.desc.name = colNames[i];
          v.desc.fqname = d.desc.fqname+'/'+colNames[i];
          r.push(v);
        }
        return r;
      });
    })).then(function(colsarray) {
      return strat.concat.apply(strat, colsarray);
    });
  }

  function createLineUp(r) {
    lineup.setData(r);
  }

  function filterTypes(arr) {
    return arr.filter(function(d) {
      var desc = d.desc;
      if (desc.type === 'matrix' || desc.type === 'vector') {
        return desc.value.type === 'categorical';
      }
      return desc.type === 'stratification' && desc.origin != null;
    });
  }

  function createDataLineUp(r) {
    lineupData.setData(r);
  }

  function filterDataTypes(arr) {
    return arr.filter(function(d) {
      var desc = d.desc;
      if (desc.type === 'matrix' || desc.type == 'vector') {
        return desc.value.type === 'real' || desc.value.type === 'int';
      }
      return false;
    });
  }
  var vectors = data.list().then(data.convertTableToVectors);
  vectors.then(filterTypes).then(splitAndConvert).then(createLineUp);
  vectors.then(filterDataTypes).then(createDataLineUp);

  elems.jumpToStored();
});
<commit_msg>use a different id for storing prov graph<commit_after>/**
 * Created by Samuel Gratzl on 15.12.2014.
 */
define(function (require) {
  'use strict';
  var $ = require('jquery');
  var data = require('../caleydo_core/data');
  var vis = require('../caleydo_core/vis');
  var C = require('../caleydo_core/main');
  var template = require('../clue_demo/template');
  var cmode = require('../caleydo_provenance/mode');

  var helper = document.querySelector('#mainhelper');
  var elems = template.create(document.body, {
    app: 'StratomeX.js',
    id: 'clue_stratomex'
  });
  elems.header.addMainMenu('New Workspace', elems.reset.bind(elems));
  var graph = elems.graph;
  {
    while(helper.firstChild) {
      elems.$main.node().appendChild(helper.firstChild);
    }
    helper.remove();
  }

  var datavalues;
  var stratomex = require('./StratomeX').create(document.getElementById('stratomex'), graph);

  var lineup =  require('./lineup').create(document.getElementById('tab_stratifications'),function (rowStrat) {
    if (rowStrat.desc.type === 'stratification') {
      rowStrat.origin().then(function (d) {
        var colStrat = null;
        if (d.desc.type === 'matrix') {
          if(rowStrat.idtypes[0] !== d.idtypes[0]) {
            d = d.t; //transpose
          }
          //look for stratification that has the other idtype and the same origin
          var available = lineup.rawData,
              targetType = d.idtypes[1];
          available = available.filter(function(ds) {
            return ds.idtype === targetType && ds.desc.origin === d.desc.fqname && ds.desc.ngroups === 1;
          });
          colStrat = available[0];
        }
        if (d.desc.type === 'table') {
          stratomex.addData(rowStrat, rowStrat);
        } else {
          stratomex.addData(rowStrat, d, colStrat);
        }
      });
    } else if (rowStrat.desc.type === 'vector') {
      rowStrat.stratification().then(function(d) {
        stratomex.addData(d, d);
      });
    }
  });

  var lineupData =  require('./lineup').createData(document.getElementById('tab_data'),function (vector) {
    stratomex.addDependentData(vector);
  });

  var $left_data = $('#databrowser');
  if (cmode.getMode().exploration < 0.8) {
    $left_data.hide();
  } else {
    $left_data.show();
  }
  function updateLineUp() {
    if (lineup.lineup) {
      lineup.lineup.update();
    }
    if (lineupData.lineup) {
      lineupData.lineup.update();
    }
  }
  $('a[data-toggle="tab"]').on('shown.bs.tab', function() {
    updateLineUp();
  });

  function updateBounds() {
    var bounds = C.bounds(stratomex.parent);
    stratomex.setBounds(bounds.x, bounds.y, bounds.w, bounds.h);
    updateLineUp();
  }
  elems.on('modeChanged', function(event, new_) {
    if (new_.exploration < 0.8) {
      $left_data.hide(); //.animate({height: 'hide'});
    } else {
      $left_data.show(); //.animate({height: 'show'});
    }

    //for the animations to end
    setTimeout(updateBounds, 700);
  });
  $(window).on('resize', updateBounds);
  updateBounds();
  //var notes = require('./notes').create(document.getElementById('notes'), graph);

  function splitAndConvert(arr) {
    var strat = arr.filter(function(d) { return d.desc.type === 'stratification'});

    strat = strat.concat(arr.filter(function(d) { return d.desc.type === 'vector'}));

    //convert all matrices to slices with their corresponding name
    return Promise.all(arr.filter(function(d) { return d.desc.type === 'matrix'}).map(function(d) {
      return d.cols().then(function(colNames) {
        var cols = d.ncol, r = [];
        for(var i = 0; i < cols; ++i) {
          var v = d.slice(i);
          v.desc.name = colNames[i];
          v.desc.fqname = d.desc.fqname+'/'+colNames[i];
          r.push(v);
        }
        return r;
      });
    })).then(function(colsarray) {
      return strat.concat.apply(strat, colsarray);
    });
  }

  function createLineUp(r) {
    lineup.setData(r);
  }

  function filterTypes(arr) {
    return arr.filter(function(d) {
      var desc = d.desc;
      if (desc.type === 'matrix' || desc.type === 'vector') {
        return desc.value.type === 'categorical';
      }
      return desc.type === 'stratification' && desc.origin != null;
    });
  }

  function createDataLineUp(r) {
    lineupData.setData(r);
  }

  function filterDataTypes(arr) {
    return arr.filter(function(d) {
      var desc = d.desc;
      if (desc.type === 'matrix' || desc.type == 'vector') {
        return desc.value.type === 'real' || desc.value.type === 'int';
      }
      return false;
    });
  }
  var vectors = data.list().then(data.convertTableToVectors);
  vectors.then(filterTypes).then(splitAndConvert).then(createLineUp);
  vectors.then(filterDataTypes).then(createDataLineUp);

  elems.jumpToStored();
});
<|endoftext|>


<commit_before>//Import Modules
require('prototype.spawn')();
var roleHarvester = require('role.harvester');
var roleUpgrader = require('role.upgrader');
var roleBuilder = require('role.builder');
var roleRepairer = require('role.repairer');

module.exports.loop = function () {

    var tower = Game.getObjectById('TOWER_ID');
    if(tower) {
        var closestDamagedStructure = tower.pos.findClosestByRange(FIND_STRUCTURES, {
            filter: (structure) => structure.hits < structure.hitsMax
        });
        if(closestDamagedStructure) {
            tower.repair(closestDamagedStructure);
        }

        var closestHostile = tower.pos.findClosestByRange(FIND_HOSTILE_CREEPS);
        if(closestHostile) {
            tower.attack(closestHostile);
        }
    }

    // clear memory
    for (let name in Memory.creeps) {
        if (Game.creeps[name] == undefined) {
            delete Memory.creeps[name];
        }
    }

    //for every creep name in game.creeps
    for (let name in Game.creeps) {
        // get the creep object
        var creep = Game.creeps[name];

        //if creep is harvester, call harvester script
        if (creep.memory.role == 'harvester') {
            roleHarvester.run(creep);
        }
        // if creep is upgrader, call upgrader script
        else if (creep.memory.role == 'upgrader') {
            roleUpgrader.run(creep);
        }
        // if creep is builder, call builder script
        else if (creep.memory.role == 'builder') {
            roleUpgrader.run(creep);
        }
        // if creep is repairier, call repairer script
        else if (creep.memory.role == 'repairer') {
            roleRepairer.run(creep);
        }
    }

    var minimumNumberOfHarvesters = 4;
    var minimumNumberOfUpgraders = 1;
    var minimumNumberOfBuilders = 1;
    var minimumNumberOfRepairers = 2;

    var numberOfHarvesters = _.sum(Game.creeps, (c) => c.memory.role == 'harvester');
    var numberOfUpgraders = _.sum(Game.creeps, (c) => c.memory.role == 'upgrader');
    var numberOfBuilders = _.sum(Game.creeps, (c) => c.memory.role == 'builder');
    var numberOfRepairers = _.sum(Game.creeps, (c) => c.memory.role == 'repairer');

    var energy = Game.spawns.Spawn1.room.energyCapacityAvailable;
    var name = undefined;

    if (numberOfHarvesters < minimumNumberOfHarvesters) {
        name = Game.spawns.Spawn1.createCustomCreep(energy, 'harvester');

            if (name == ERR_NOT_ENOUGH_ENERGY && numberOfHarvesters == 0) {
                name = Game,spawns.Spawn1.createCustomCreep(
                    Game.spawns.Spawn1.room.energyAvailable, 'harvester');
        }
    }
    else if (numberOfUpgraders < minimumNumberOfUpgraders) {
        name = Game.spawns.Spawn1.createCustomCreep(energy, 'upgrader');
    }
    else if (numberOfRepairers < minimumNumberOfRepairers) {
        name = Game.spawns.Spawn1.createCustomCreep(energy, 'repairer');
    }
    else if (numberOfBuilders < minimumNumberOfBuilders) {
        name = Game.spawns.Spawn1.createCustomCreep(energy, 'builder');
    }
    else {
        name = Game.spawns.Spawn1.createCustomCreep(energy, 'builder');
    }
    if (!(name < 0)) {
        console.log("Spawned new creep: " + name );
    }
};
<commit_msg>FUCKING roleBuilder<commit_after>//Import Modules
require('prototype.spawn')();
var roleHarvester = require('role.harvester');
var roleUpgrader = require('role.upgrader');
var roleBuilder = require('role.builder');
var roleRepairer = require('role.repairer');

module.exports.loop = function () {

    var tower = Game.getObjectById('TOWER_ID');
    if(tower) {
        var closestDamagedStructure = tower.pos.findClosestByRange(FIND_STRUCTURES, {
            filter: (structure) => structure.hits < structure.hitsMax
        });
        if(closestDamagedStructure) {
            tower.repair(closestDamagedStructure);
        }

        var closestHostile = tower.pos.findClosestByRange(FIND_HOSTILE_CREEPS);
        if(closestHostile) {
            tower.attack(closestHostile);
        }
    }

    // clear memory
    for (let name in Memory.creeps) {
        if (Game.creeps[name] == undefined) {
            delete Memory.creeps[name];
        }
    }

    //for every creep name in game.creeps
    for (let name in Game.creeps) {
        // get the creep object
        var creep = Game.creeps[name];

        //if creep is harvester, call harvester script
        if (creep.memory.role == 'harvester') {
            roleHarvester.run(creep);
        }
        // if creep is upgrader, call upgrader script
        else if (creep.memory.role == 'upgrader') {
            roleUpgrader.run(creep);
        }
        // if creep is builder, call builder script
        else if (creep.memory.role == 'builder') {
            roleBuilder.run(creep);
        }
        // if creep is repairier, call repairer script
        else if (creep.memory.role == 'repairer') {
            roleRepairer.run(creep);
        }
    }

    var minimumNumberOfHarvesters = 4;
    var minimumNumberOfUpgraders = 1;
    var minimumNumberOfBuilders = 1;
    var minimumNumberOfRepairers = 2;

    var numberOfHarvesters = _.sum(Game.creeps, (c) => c.memory.role == 'harvester');
    var numberOfUpgraders = _.sum(Game.creeps, (c) => c.memory.role == 'upgrader');
    var numberOfBuilders = _.sum(Game.creeps, (c) => c.memory.role == 'builder');
    var numberOfRepairers = _.sum(Game.creeps, (c) => c.memory.role == 'repairer');

    var energy = Game.spawns.Spawn1.room.energyCapacityAvailable;
    var name = undefined;

    if (numberOfHarvesters < minimumNumberOfHarvesters) {
        name = Game.spawns.Spawn1.createCustomCreep(energy, 'harvester');

            if (name == ERR_NOT_ENOUGH_ENERGY && numberOfHarvesters == 0) {
                name = Game,spawns.Spawn1.createCustomCreep(
                    Game.spawns.Spawn1.room.energyAvailable, 'harvester');
        }
    }
    else if (numberOfUpgraders < minimumNumberOfUpgraders) {
        name = Game.spawns.Spawn1.createCustomCreep(energy, 'upgrader');
    }
    else if (numberOfRepairers < minimumNumberOfRepairers) {
        name = Game.spawns.Spawn1.createCustomCreep(energy, 'repairer');
    }
    else if (numberOfBuilders < minimumNumberOfBuilders) {
        name = Game.spawns.Spawn1.createCustomCreep(energy, 'builder');
    }
    else {
        name = Game.spawns.Spawn1.createCustomCreep(energy, 'builder');
    }
    if (!(name < 0)) {
        console.log("Spawned new creep: " + name );
    }
};
<|endoftext|>