<commit_before>/*

    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
      This file is part of the Smart Developer Hub Project:
        http://www.smartdeveloperhub.org/
      Center for Open Middleware
            http://www.centeropenmiddleware.com/
    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
      Copyright (C) 2015 Center for Open Middleware.
    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
      Licensed under the Apache License, Version 2.0 (the "License");
      you may not use this file except in compliance with the License.
      You may obtain a copy of the License at
                http://www.apache.org/licenses/LICENSE-2.0
      Unless required by applicable law or agreed to in writing, software
      distributed under the License is distributed on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      See the License for the specific language governing permissions and
     limitations under the License.
    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
*/

'use strict';

/* Aux Methods*/
var getNewTriple = function getNewTriple(triple, dataQ, agentId, theUuid) {
    if (triple.predicate == "http://www.smartdeveloperhub.org/vocabulary/curator#messageId") {
        triple.object = '"' + theUuid + '"^^http://www.smartdeveloperhub.org/vocabulary/types#UUID';
    }
    if (triple.predicate == "http://www.smartdeveloperhub.org/vocabulary/curator#submittedOn") {
        var submitDate = moment().format(); // ISO 8601
        triple.object = '"' + submitDate + '"^^http://www.w3.org/2001/XMLSchema#dateTime';
    }
    if (triple.predicate == "http://www.smartdeveloperhub.org/vocabulary/curator#agentId") {
        triple.object = '"' + agentId + '"^^http://www.smartdeveloperhub.org/vocabulary/types#UUID';
    }
    if (triple.predicate == "http://www.smartdeveloperhub.org/vocabulary/amqp#host") {
        triple.object = '"' + RABBITHOST.replace('amqp://', '') + '"^^http://www.smartdeveloperhub.org/vocabulary/types#Hostname';
    }
    if (triple.predicate == "http://www.smartdeveloperhub.org/vocabulary/amqp#port") {
        triple.object = '"' + RABBITPORT + '"^^http://www.smartdeveloperhub.org/vocabulary/types#Port';
    }
    if (triple.predicate == "http://www.smartdeveloperhub.org/vocabulary/amqp#routingKey") {
        triple.object = '"' + dataQ + '"^^http://www.smartdeveloperhub.org/vocabulary/types#Name';
    }
    return triple;
};

var getNewTtl = function getNewTtl(triples, prefixes, bNodes, callback) {
    // triples to ttl file
    // Write
    var writer = N3.Writer({ prefixes: prefixes });

    for(var i = 0; i < triples.length; i ++) {
        writer.addTriple(triples[i]);
    }

    // Blank Nodes
    for (var z = 0; z < bNodes.length; z ++) {
        writer.addTriple(bNodes[z]);
    }
    writer.end(callback);
};

var sendAfterWrite = function sendAfterWrite(result, ch) {
    // TODO ERROR control
    // Send file
    //ch.assertExchange(EXCHANGE, 'topic', {durable: false});
    ch.publish(EXCHANGE, ROUTINGKEY, new Buffer(result));
    //console.log(" [x] Sent " + ROUTINGKEY);
    //console.log(result);
    return;
};

module.exports.parseTriples = function parseTriples (triplesList) {
    var newElement = function newElement(subject, predicate, object) {
        /*if (typeof object == 'string') {
            object = "'" + object + "'";
        }*/
        return {
            subject: subject,
            predicate: predicate,
            object: object
        };
    };
    var c = 1;
    var subjects = {};
    var nodes = [];
    var sub1;
    var sub2;

    for (var i = 0; i < triplesList.length; i++) {
        var t = triplesList[i].split(' ');
        if (!(t[0] in subjects)) {
            if (t[0].indexOf('?') === 0) {
                sub1 = '_:n' + c;
                c++;
            } else {
                sub1 = t[0];
            }
            // new
            nodes.push(newElement(sub1, 'rdf:type', 'curator:Variable'));
            nodes.push(newElement(sub1, 'curator:label', JSON.stringify(t[0])));
            subjects[t[0]] = sub1;
        }
        if (!(t[2] in subjects)) {
            if (t[2].indexOf('?') === 0) {
                sub2 = '_:n' + c;
                c++;
            } else {
                sub2 = t[2];
            }
            // new
            nodes.push(newElement(sub2, 'rdf:type', 'curator:Variable'));
            nodes.push(newElement(sub2, 'curator:label', JSON.stringify(t[2])));
            subjects[t[2]] = sub2;
        }
        nodes.push(newElement(subjects[t[0]], t[1], subjects[t[2]]));
    }
    return nodes;
};

module.exports.getfromSDH = function getfromSDH(bNodes, callback) {
    try {
        if (!bNodes.length) {
            console.log('Bad bNodes parameter. N3 Node Array expected');
            callback(null);
            return -1;
        }
        // generate Agent ID for each request
        var agentId = uuid();
        // generate UUIDfor each request
        var theUuid = uuid();
        var qName = "curator.response." + agentId;
        var dataQ;
        amqp.connect(RABBITHOST + ':' + RABBITPORT, function (err, conn) {
            if (err) {
                console.log('Error connecting' + RABBITHOST + ':' + RABBITPORT + '---> ' + err);
                callback(null);
                return -1;
            }
            conn.createChannel(function (err, ch) {
                if (err) {
                    console.log('Error creating channel (ttl send): ' + err);
                    callback(null);
                    return -1;
                }
                ch.assertQueue('', {durable: false, autoDelete: true, exclusive: false}, function (err, q) {
                    ch.bindQueue(q.queue, EXCHANGE, qName);
                    ch.consume(q.queue, function (msg) {
                        //console.log(" [x Accept] %s", msg.fields.routingKey);
                        // Parse msg
                        var parser = N3.Parser();
                        var isOk = false;
                        var trip = [];
                        parser.parse(msg.content.toString(), function (error, triple, prefixes) {
                            if (error) {
                                console.log("Error parsing accept ttl.  " + error);
                                return -1;
                            }
                            if (triple) {
                                trip.push(triple);
                                if (triple.predicate === 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type' && triple.object === "http://www.smartdeveloperhub.org/vocabulary/curator#Accepted") {
                                    // Success
                                    isOk = true;
                                }
                            } else {
                                // Failed
                                if (!isOk) {
                                    console.log('Error: ');
                                    console.log(prefixes);
                                    console.log(trip);
                                    console.log('...Connection close...');
                                    conn.close();
                                }
                            }
                        });
                    }, {noAck: true});
                });
                // Data
                ch.assertQueue('', {durable: false, autoDelete: true, exclusive: false}, function (err, q) {
                    //ch.assertQueue('', {exclusive: false, durable: false, autoDelete: true}, function (err, q) {
                    dataQ = q.queue;
                    sendTtl();
                    var finalResponse = [];
                    ch.consume(q.queue, function (msg) {
                        if (msg.properties.headers.state == 'end') {
                            //console.log(" [x Data] %s: ", msg.fields.routingKey);
                            console.log('...Connection close...');
                            conn.close();
                            callback(finalResponse);
                        } else {
                            finalResponse = finalResponse.concat(JSON.parse(msg.content.toString()));
                        }
                    }, {noAck: true});
                });
            });
        });

        var sendTtl = function () {
            // Obtain request ttl
            amqp.connect(RABBITHOST + ':' + RABBITPORT, function (err, conn) {
                if (err) {
                    console.log('Error connecting' + RABBITHOST + ':' + RABBITPORT + '---> ' + err);
                    callback(null);
                    return -1;
                }
                conn.createChannel(function (err, ch) {
                    if (err) {
                        console.log('Error creating channel (ttl send): ' + err);
                        callback(null);
                        return -1;
                    }
                    // Generate the ttl
                    fs.readFile('./sdh/curatorExample.ttl', 'utf8', function (err, data) {
                        if (err) {
                            console.log('Error reading ./sdh/curatorExample.ttl.  ' + err);
                            return -1;
                        }
                        // Parse file
                        var parser = N3.Parser();
                        var triples = [];
                        parser.parse(data, function (error, triple, prefixes) {
                            if (error) {
                                console.log("Error parsing ttl.  " + error);
                                return -1;
                            }
                            if (triple) {
                                triples.push(getNewTriple(triple, dataQ, agentId, theUuid));
                            } else {

                                getNewTtl(triples, prefixes, bNodes,
                                    function (error, result) {
                                        if (error) {
                                            console.log("Error rewriting ttl.  " + error);
                                            return -1;
                                        }
                                        // send ttl
                                        sendAfterWrite(result, ch);
                                        return;
                                    }
                                );
                            }
                        });
                    });
                });
            });
        };
    } catch (err) {
        console.log('Error connecting' + RABBITHOST + ':' + RABBITPORT);
        callback(null);
    }

};<commit_msg>Change method position<commit_after>/*

    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
      This file is part of the Smart Developer Hub Project:
        http://www.smartdeveloperhub.org/
      Center for Open Middleware
            http://www.centeropenmiddleware.com/
    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
      Copyright (C) 2015 Center for Open Middleware.
    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
      Licensed under the Apache License, Version 2.0 (the "License");
      you may not use this file except in compliance with the License.
      You may obtain a copy of the License at
                http://www.apache.org/licenses/LICENSE-2.0
      Unless required by applicable law or agreed to in writing, software
      distributed under the License is distributed on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      See the License for the specific language governing permissions and
     limitations under the License.
    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
*/

'use strict';

/* Aux Methods*/
var getNewTriple = function getNewTriple(triple, dataQ, agentId, theUuid) {
    if (triple.predicate == "http://www.smartdeveloperhub.org/vocabulary/curator#messageId") {
        triple.object = '"' + theUuid + '"^^http://www.smartdeveloperhub.org/vocabulary/types#UUID';
    }
    if (triple.predicate == "http://www.smartdeveloperhub.org/vocabulary/curator#submittedOn") {
        var submitDate = moment().format(); // ISO 8601
        triple.object = '"' + submitDate + '"^^http://www.w3.org/2001/XMLSchema#dateTime';
    }
    if (triple.predicate == "http://www.smartdeveloperhub.org/vocabulary/curator#agentId") {
        triple.object = '"' + agentId + '"^^http://www.smartdeveloperhub.org/vocabulary/types#UUID';
    }
    if (triple.predicate == "http://www.smartdeveloperhub.org/vocabulary/amqp#host") {
        triple.object = '"' + RABBITHOST.replace('amqp://', '') + '"^^http://www.smartdeveloperhub.org/vocabulary/types#Hostname';
    }
    if (triple.predicate == "http://www.smartdeveloperhub.org/vocabulary/amqp#port") {
        triple.object = '"' + RABBITPORT + '"^^http://www.smartdeveloperhub.org/vocabulary/types#Port';
    }
    if (triple.predicate == "http://www.smartdeveloperhub.org/vocabulary/amqp#routingKey") {
        triple.object = '"' + dataQ + '"^^http://www.smartdeveloperhub.org/vocabulary/types#Name';
    }
    return triple;
};

var getNewTtl = function getNewTtl(triples, prefixes, bNodes, callback) {
    // triples to ttl file
    // Write
    var writer = N3.Writer({ prefixes: prefixes });

    for(var i = 0; i < triples.length; i ++) {
        writer.addTriple(triples[i]);
    }

    // Blank Nodes
    for (var z = 0; z < bNodes.length; z ++) {
        writer.addTriple(bNodes[z]);
    }
    writer.end(callback);
};

module.exports.parseTriples = function parseTriples (triplesList) {
    var newElement = function newElement(subject, predicate, object) {
        /*if (typeof object == 'string') {
            object = "'" + object + "'";
        }*/
        return {
            subject: subject,
            predicate: predicate,
            object: object
        };
    };
    var c = 1;
    var subjects = {};
    var nodes = [];
    var sub1;
    var sub2;

    for (var i = 0; i < triplesList.length; i++) {
        var t = triplesList[i].split(' ');
        if (!(t[0] in subjects)) {
            if (t[0].indexOf('?') === 0) {
                sub1 = '_:n' + c;
                c++;
            } else {
                sub1 = t[0];
            }
            // new
            nodes.push(newElement(sub1, 'rdf:type', 'curator:Variable'));
            nodes.push(newElement(sub1, 'curator:label', JSON.stringify(t[0])));
            subjects[t[0]] = sub1;
        }
        if (!(t[2] in subjects)) {
            if (t[2].indexOf('?') === 0) {
                sub2 = '_:n' + c;
                c++;
            } else {
                sub2 = t[2];
            }
            // new
            nodes.push(newElement(sub2, 'rdf:type', 'curator:Variable'));
            nodes.push(newElement(sub2, 'curator:label', JSON.stringify(t[2])));
            subjects[t[2]] = sub2;
        }
        nodes.push(newElement(subjects[t[0]], t[1], subjects[t[2]]));
    }
    return nodes;
};

var sendAfterWrite = function sendAfterWrite(result, ch) {
    // TODO ERROR control
    // Send file
    //ch.assertExchange(EXCHANGE, 'topic', {durable: false});
    ch.publish(EXCHANGE, ROUTINGKEY, new Buffer(result));
    //console.log(" [x] Sent " + ROUTINGKEY);
    //console.log(result);
    return;
};

module.exports.getfromSDH = function getfromSDH(bNodes, callback) {
    try {
        if (!bNodes.length) {
            console.log('Bad bNodes parameter. N3 Node Array expected');
            callback(null);
            return -1;
        }
        // generate Agent ID for each request
        var agentId = uuid();
        // generate UUIDfor each request
        var theUuid = uuid();
        var qName = "curator.response." + agentId;
        var dataQ;
        amqp.connect(RABBITHOST + ':' + RABBITPORT, function (err, conn) {
            if (err) {
                console.log('Error connecting' + RABBITHOST + ':' + RABBITPORT + '---> ' + err);
                callback(null);
                return -1;
            }
            conn.createChannel(function (err, ch) {
                if (err) {
                    console.log('Error creating channel (ttl send): ' + err);
                    callback(null);
                    return -1;
                }
                ch.assertQueue('', {durable: false, autoDelete: true, exclusive: false}, function (err, q) {
                    ch.bindQueue(q.queue, EXCHANGE, qName);
                    ch.consume(q.queue, function (msg) {
                        //console.log(" [x Accept] %s", msg.fields.routingKey);
                        // Parse msg
                        var parser = N3.Parser();
                        var isOk = false;
                        var trip = [];
                        parser.parse(msg.content.toString(), function (error, triple, prefixes) {
                            if (error) {
                                console.log("Error parsing accept ttl.  " + error);
                                return -1;
                            }
                            if (triple) {
                                trip.push(triple);
                                if (triple.predicate === 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type' && triple.object === "http://www.smartdeveloperhub.org/vocabulary/curator#Accepted") {
                                    // Success
                                    isOk = true;
                                }
                            } else {
                                // Failed
                                if (!isOk) {
                                    console.log('Error: ');
                                    console.log(prefixes);
                                    console.log(trip);
                                    console.log('...Connection close...');
                                    conn.close();
                                }
                            }
                        });
                    }, {noAck: true});
                });
                // Data
                ch.assertQueue('', {durable: false, autoDelete: true, exclusive: false}, function (err, q) {
                    //ch.assertQueue('', {exclusive: false, durable: false, autoDelete: true}, function (err, q) {
                    dataQ = q.queue;
                    sendTtl();
                    var finalResponse = [];
                    ch.consume(q.queue, function (msg) {
                        if (msg.properties.headers.state == 'end') {
                            //console.log(" [x Data] %s: ", msg.fields.routingKey);
                            console.log('...Connection close...');
                            conn.close();
                            callback(finalResponse);
                        } else {
                            finalResponse = finalResponse.concat(JSON.parse(msg.content.toString()));
                        }
                    }, {noAck: true});
                });
            });
        });

        var sendTtl = function () {
            // Obtain request ttl
            amqp.connect(RABBITHOST + ':' + RABBITPORT, function (err, conn) {
                if (err) {
                    console.log('Error connecting' + RABBITHOST + ':' + RABBITPORT + '---> ' + err);
                    callback(null);
                    return -1;
                }
                conn.createChannel(function (err, ch) {
                    if (err) {
                        console.log('Error creating channel (ttl send): ' + err);
                        callback(null);
                        return -1;
                    }
                    // Generate the ttl
                    fs.readFile('./sdh/curatorExample.ttl', 'utf8', function (err, data) {
                        if (err) {
                            console.log('Error reading ./sdh/curatorExample.ttl.  ' + err);
                            return -1;
                        }
                        // Parse file
                        var parser = N3.Parser();
                        var triples = [];
                        parser.parse(data, function (error, triple, prefixes) {
                            if (error) {
                                console.log("Error parsing ttl.  " + error);
                                return -1;
                            }
                            if (triple) {
                                triples.push(getNewTriple(triple, dataQ, agentId, theUuid));
                            } else {

                                getNewTtl(triples, prefixes, bNodes,
                                    function (error, result) {
                                        if (error) {
                                            console.log("Error rewriting ttl.  " + error);
                                            return -1;
                                        }
                                        // send ttl
                                        sendAfterWrite(result, ch);
                                        return;
                                    }
                                );
                            }
                        });
                    });
                });
            });
        };
    } catch (err) {
        console.log('Error connecting' + RABBITHOST + ':' + RABBITPORT);
        callback(null);
    }

};<|endoftext|>


<commit_before>$(document).ready(function() {
    // setup the drag drop zone
    var target_el = '';

    $('.image-uploader-trigger').click(function() {
        target_el = $(this).attr('data-target');
        var modal = $(this).attr('href');
        $(modal).modal('show');
        return false;
    });

    $(document).bind('dragover', function (e) {
        var dropZone = $('#image-dropzone'),
            timeout = window.dropZoneTimeout;
        if (!timeout) {
            dropZone.addClass('in');
        } else {
            clearTimeout(timeout);
        }
        if (e.target === dropZone[0]) {
            dropZone.addClass('hover');
        } else {
            dropZone.removeClass('hover');
        }
        window.dropZoneTimeout = setTimeout(function () {
            window.dropZoneTimeout = null;
            dropZone.removeClass('in hover');
        }, 100);
    });

    $(document).bind('drop dragover', function (e) {
        e.preventDefault();
    });

    // setup fileuploader
  $(document).on('DOMNodeInserted', function(e) {
    $('#image-upload-form', e.target).fileupload({
      maxFileSize: 5000000,
      acceptFileTypes: '/(\.|\/)(gif|jpe?g|png)$/i',
      autoUpload: true,
      dropZone: $('#image-dropzone'),
      dataType: 'json',
      url: $('#image-upload-form').attr('action'),
      formData: [
        {
          name: '_method',
          value: 'POST '
        }
      ],
      done: function(e, data) {
        $('.image-uploader-input-url').val(data.result.url);
        $('.image-uploader-preview-img').attr('src', data.result.url);
        $(target_el + '-preview').attr('src', data.result.url);
        $(target_el + '-input').attr('value', data.result.url);
        $('.image-uploader-insert-btn').click();
      }
    });
  });
});
<commit_msg>fix for image upload<commit_after>$(document).ready(function() {
    // setup the drag drop zone
    var target_el = '';

    $('.image-uploader-trigger').click(function() {
        target_el = $(this).attr('data-target');
        var modal = $(this).attr('href');
        $(modal).modal('show');
        return false;
    });

    $(document).bind('dragover', function (e) {
        var dropZone = $('#image-dropzone'),
            timeout = window.dropZoneTimeout;
        if (!timeout) {
            dropZone.addClass('in');
        } else {
            clearTimeout(timeout);
        }
        if (e.target === dropZone[0]) {
            dropZone.addClass('hover');
        } else {
            dropZone.removeClass('hover');
        }
        window.dropZoneTimeout = setTimeout(function () {
            window.dropZoneTimeout = null;
            dropZone.removeClass('in hover');
        }, 100);
    });

    $(document).bind('drop dragover', function (e) {
        e.preventDefault();
    });

    // setup fileuploader
  $(document).on('DOMNodeInserted', function(e) {
    $('#image-upload-form', e.target).fileupload({
      maxFileSize: 5000000,
      acceptFileTypes: '/(\.|\/)(gif|jpe?g|png)$/i',
      autoUpload: true,
      dropZone: $('#image-dropzone'),
      dataType: 'json',
      url: $('#image-upload-form').attr('data-url'),
      formData: [
        {
          name: '_method',
          value: 'POST '
        }
      ],
      done: function(e, data) {
        $('.image-uploader-input-url').val(data.result.url);
        $('.image-uploader-preview-img').attr('src', data.result.url);
        $(target_el + '-preview').attr('src', data.result.url);
        $(target_el + '-input').attr('value', data.result.url);
        $('.image-uploader-insert-btn').click();
      }
    });
  });
});
<|endoftext|>


<commit_before>export const extend = baseOps => {
  const mod = (x, y) => {
    if (x == 0)
      return 0;
    else {
      const t = x % y;
      return t < 0 ? t + y : t;
    }
  };

  const areClose = (x, y, eps=Math.pow(2, -40)) =>
    (x == 0 && Math.abs(y) < eps) || (y == 0 && Math.abs(x) < eps) ||
    Math.abs(x - y) <= eps * Math.max(Math.abs(x), Math.abs(y));

  const methods = {
    __context__: () => 'floats',

    isInteger: {
      Integer: x => true
    },
    isReal: {
      Integer: x => true,
      Float: x => true
    },
    toJS: {
      Integer: x => x,
      Float: x => x
    },
    negative: {
      Integer: x => -x,
      Float: x => -x
    },
    sgn: {
      Integer: x => (x > 0) - (x < 0),
      Float: x => (x > 0) - (x < 0)
    },
    __Float__: { Object: ({ Float: x }) => x },
    __Integer__: { Object: ({ Integer: x }) => x }
  };

  for (const name of [ 'abs', 'floor', 'ceil', 'round' ])
    methods[name] = {
      Integer: x => Math[name](x),
      Float: x => Math[name](x)
    }

  methods.sqrt = {
    Integer : x => Math.sqrt(x),
    Float   : x => Math.sqrt(x)
  };

  for (const [name, op] of [
    [ 'cmp'  , (x, y) => (x > y) - (x < y)              ],
    [ 'plus' , (x, y) => x + y                          ],
    [ 'minus', (x, y) => x - y                          ],
    [ 'times', (x, y) => (x == 0 || y == 0) ? 0 : x * y ],
    [ 'div'  , (x, y) => x == 0 ? 0 : x / y             ],
    [ 'mod'  , mod ],
    [ 'areClose', areClose ]
  ]) {
    methods[name] = {
      Float: {
        Float   : (x, y) => op(x, y),
        Integer : (x, y) => op(x, y)
      },
      Integer: {
        Float   : (x, y) => op(x, y),
        Integer : (x, y) => op(x, y)
      }
    };
  }

  return baseOps.register(methods);
};
<commit_msg>clean up the floats arithmetic context<commit_after>export const extend = baseOps => {
  const mod = (x, y) => {
    if (x == 0)
      return 0;
    else {
      const t = x % y;
      return t < 0 ? t + y : t;
    }
  };

  const methods = {
    __context__: () => 'floats',

    isInteger: {
      Integer: x => true
    },
    isReal: {
      Integer: x => true,
      Float: x => true
    },
    toJS: {
      Integer: x => x,
      Float: x => x
    },
    negative: {
      Integer: x => -x,
      Float: x => -x
    },
    sgn: {
      Integer: x => (x > 0) - (x < 0),
      Float: x => (x > 0) - (x < 0)
    },
    __Float__: { Object: ({ Float: x }) => x },
    __Integer__: { Object: ({ Integer: x }) => x }
  };

  for (const name of [ 'abs', 'floor', 'ceil', 'round', 'sqrt' ])
    methods[name] = {
      Integer: x => Math[name](x),
      Float: x => Math[name](x)
    }

  for (const [name, op] of [
    [ 'cmp'  , (x, y) => (x > y) - (x < y)              ],
    [ 'plus' , (x, y) => x + y                          ],
    [ 'minus', (x, y) => x - y                          ],
    [ 'times', (x, y) => (x == 0 || y == 0) ? 0 : x * y ],
    [ 'div'  , (x, y) => x == 0 ? 0 : x / y             ],
    [ 'mod'  , mod ]
  ]) {
    methods[name] = {
      Float: {
        Float  : op,
        Integer: op
      },
      Integer: {
        Float  : op,
        Integer: op
      }
    };
  }

  return baseOps.register(methods);
};
<|endoftext|>


<commit_before>/*
Copyright 2012, Kjel Delaey (https://github.com/trimentor/pwdcalc)
https://github.com/trimentor/pwdcalc/blob/master/LICENSE
*/

(function() {

  this.Pwdcalc = (function() {

    function Pwdcalc(selector) {
      this.$inputWrapper = $(selector);
      this.bindYapsm();
      this.bindSubmit();
    }

    Pwdcalc.prototype.bindYapsm = function() {
      var $input,
        _this = this;
      $input = $('input', this.$inputWrapper);
      return $input.yapsm({
        dictionary: function() {
          var dataDictionary, list;
          dataDictionary = $input.data('dictionary');
          list = [];
          if (dataDictionary) {
            try {
              list = eval(dataDictionary);
            } catch (_error) {}
          }
          return list;
        }
      }).keyup(function(event) {
        return _this.calculateStrength(event);
      });
    };

    Pwdcalc.prototype.bindSubmit = function() {
      var _this = this;
      return this.$inputWrapper.closest('form').submit(function(event) {
        return _this.trigger('pwdcalc-submit', event);
      });
    };

    Pwdcalc.prototype.calculateStrength = function(event) {
      var $input, el, i18nStrength, pwd, requiredChars, strength, yapsmInput, _i, _len;
      $input = $('input', this.$inputWrapper);
      yapsmInput = 'undefined';
      for (_i = 0, _len = $input.length; _i < _len; _i++) {
        el = $input[_i];
        if (el.complexity) {
          yapsmInput = el;
          break;
        }
      }
      pwd = $.trim(yapsmInput.value);
      strength = yapsmInput.complexity;
      requiredChars = $input.data('minlength');
      i18nStrength = $(".pwdcalc-hint[data-complexity=" + strength + "]").html();
      this.trigger('pwdcalc-keyup-init', event);
      this.showStrength(strength, i18nStrength, pwd, requiredChars);
      return this.trigger('pwdcalc-keyup-complete', event);
    };

    Pwdcalc.prototype.showStrength = function(strength, i18nStrength, pwd, requiredChars) {
      var $gauge, $helpBlock;
      $helpBlock = $('.pwdcalc-help-block', this.$inputWrapper);
      $gauge = $('.pwdcalc-gauge', this.$inputWrapper);
      if (!pwd.length || (requiredChars && pwd.length < requiredChars)) {
        $helpBlock.hide().empty();
        return $gauge.hide();
      } else {
        $helpBlock.show().attr('data-complexity', strength);
        $gauge.attr('data-strength', strength).show();
        if (i18nStrength === undefined || !$.trim(i18nStrength.length)) {
          return $helpBlock.html(strength);
        } else {
          return $helpBlock.html(i18nStrength);
        }
      }
    };

    Pwdcalc.prototype.trigger = function(eventType, event) {
      var $input;
      $input = $('input', this.$inputWrapper);
      return $(document).trigger(eventType, [event, $input]);
    };

    return Pwdcalc;

  })();

  $(function() {
    return $(".pwdcalc-form-group").each(function() {
      return new Pwdcalc(this);
    });
  });

}).call(this);
<commit_msg>Support Turbolinks-enabled projects<commit_after>/*
Copyright 2012, Kjel Delaey (https://github.com/trimentor/pwdcalc)
https://github.com/trimentor/pwdcalc/blob/master/LICENSE
*/

(function() {

  this.Pwdcalc = (function() {

    function Pwdcalc(selector) {
      this.$inputWrapper = $(selector);
      this.bindYapsm();
      this.bindSubmit();
    }

    Pwdcalc.prototype.bindYapsm = function() {
      var $input,
        _this = this;
      $input = $('input', this.$inputWrapper);
      return $input.yapsm({
        dictionary: function() {
          var dataDictionary, list;
          dataDictionary = $input.data('dictionary');
          list = [];
          if (dataDictionary) {
            try {
              list = eval(dataDictionary);
            } catch (_error) {}
          }
          return list;
        }
      }).keyup(function(event) {
        return _this.calculateStrength(event);
      });
    };

    Pwdcalc.prototype.bindSubmit = function() {
      var _this = this;
      return this.$inputWrapper.closest('form').submit(function(event) {
        return _this.trigger('pwdcalc-submit', event);
      });
    };

    Pwdcalc.prototype.calculateStrength = function(event) {
      var $input, el, i18nStrength, pwd, requiredChars, strength, yapsmInput, _i, _len;
      $input = $('input', this.$inputWrapper);
      yapsmInput = 'undefined';
      for (_i = 0, _len = $input.length; _i < _len; _i++) {
        el = $input[_i];
        if (el.complexity) {
          yapsmInput = el;
          break;
        }
      }
      pwd = $.trim(yapsmInput.value);
      strength = yapsmInput.complexity;
      requiredChars = $input.data('minlength');
      i18nStrength = $(".pwdcalc-hint[data-complexity=" + strength + "]").html();
      this.trigger('pwdcalc-keyup-init', event);
      this.showStrength(strength, i18nStrength, pwd, requiredChars);
      return this.trigger('pwdcalc-keyup-complete', event);
    };

    Pwdcalc.prototype.showStrength = function(strength, i18nStrength, pwd, requiredChars) {
      var $gauge, $helpBlock;
      $helpBlock = $('.pwdcalc-help-block', this.$inputWrapper);
      $gauge = $('.pwdcalc-gauge', this.$inputWrapper);
      if (!pwd.length || (requiredChars && pwd.length < requiredChars)) {
        $helpBlock.hide().empty();
        return $gauge.hide();
      } else {
        $helpBlock.show().attr('data-complexity', strength);
        $gauge.attr('data-strength', strength).show();
        if (i18nStrength === undefined || !$.trim(i18nStrength.length)) {
          return $helpBlock.html(strength);
        } else {
          return $helpBlock.html(i18nStrength);
        }
      }
    };

    Pwdcalc.prototype.trigger = function(eventType, event) {
      var $input;
      $input = $('input', this.$inputWrapper);
      return $(document).trigger(eventType, [event, $input]);
    };

    return Pwdcalc;

  })();

  $(document).on('ready page:load', function () {
    return $(".pwdcalc-form-group").each(function() {
      return new Pwdcalc(this);
    });
  });

}).call(this);
<|endoftext|>


<commit_before>import PossiblyUpdatingExpression from './expressions/PossiblyUpdatingExpression';
import buildContext from './evaluationUtils/buildContext';
/**
 * Evaluates an XPath on the given contextItem. Returns the string result as if the XPath is wrapped in string(...).
 *
 * @param  {!string}       updateScript     The updateScript to execute. Supports XPath 3.1.
 * @param  {*}             contextItem  The initial context for the script
 * @param  {?IDomFacade=}  domFacade    The domFacade (or DomFacade like interface) for retrieving relations.
 * @param  {?Object=}      variables    Extra variables (name=>value). Values can be number / string or boolean.
 * @param  {?Object=}      options      Extra options for evaluating this XPath
 *
 * @return  {Promise<{updateList: Array<Object>, result: Object}>}         The string result.
 */
export default async function evaluateUpdatingExpression (updateScript, contextItem, domFacade, variables, options) {
	const {
		dynamicContext,
		executionParameters,
		expression
	} = buildContext(
		updateScript,
		contextItem,
		domFacade || null,
		variables || {},
		options || {},
		{
			allowXQuery: true,
			allowUpdating: true,
			disableCache: false
		}
	);

	if (!expression.isUpdating) {
		throw new Error(`The expression ${updateScript} is not updating and can not be executed as an updating expression.`);
	}

	const resultIterator = (/** @type {PossiblyUpdatingExpression} **/(expression)).evaluateWithUpdateList(dynamicContext, executionParameters);

	let attempt = resultIterator.next();
	while (!attempt.ready) {
		await attempt.promise;
		attempt = resultIterator.next();
	}

	return {
		'xdmValue': attempt.value.xdmValue,
		'pendingUpdateList': attempt.value.pendingUpdateList.map(update => update.toTransferable())
	};
}
<commit_msg>Fix typedocs for evaluateUpdatingExpression<commit_after>import PossiblyUpdatingExpression from './expressions/PossiblyUpdatingExpression';
import buildContext from './evaluationUtils/buildContext';
/**
 * Evaluates an XPath on the given contextItem. Returns the string result as if the XPath is wrapped in string(...).
 *
 * @param  {!string}       updateScript     The updateScript to execute. Supports XPath 3.1.
 * @param  {*}             contextItem  The initial context for the script
 * @param  {?IDomFacade=}  domFacade    The domFacade (or DomFacade like interface) for retrieving relations.
 * @param  {?Object=}      variables    Extra variables (name=>value). Values can be number / string or boolean.
 * @param  {?Object=}      options      Extra options for evaluating this XPath
 *
 * @return  {Promise<{pendingUpdateList: Array<Object>, xdmValue: Object}>}         The string result.
 */
export default async function evaluateUpdatingExpression (updateScript, contextItem, domFacade, variables, options) {
	const {
		dynamicContext,
		executionParameters,
		expression
	} = buildContext(
		updateScript,
		contextItem,
		domFacade || null,
		variables || {},
		options || {},
		{
			allowXQuery: true,
			allowUpdating: true,
			disableCache: false
		}
	);

	if (!expression.isUpdating) {
		throw new Error(`The expression ${updateScript} is not updating and can not be executed as an updating expression.`);
	}

	const resultIterator = (/** @type {PossiblyUpdatingExpression} **/(expression)).evaluateWithUpdateList(dynamicContext, executionParameters);

	let attempt = resultIterator.next();
	while (!attempt.ready) {
		await attempt.promise;
		attempt = resultIterator.next();
	}

	return {
		'xdmValue': attempt.value.xdmValue,
		'pendingUpdateList': attempt.value.pendingUpdateList.map(update => update.toTransferable())
	};
}
<|endoftext|>


<commit_before>//META{"name":"staticAvatars"}*//

/*@cc_on
@if (@_jscript)
    // Offer to self-install for clueless users that try to run this directly.
    var shell = WScript.CreateObject("WScript.Shell");
    var fs = new ActiveXObject("Scripting.FileSystemObject");
    var pathPlugins = shell.ExpandEnvironmentStrings("%APPDATA%\\BetterDiscord\\plugins");
    var pathSelf = WScript.ScriptFullName;
    // Put the user at ease by addressing them in the first person
    shell.Popup("It looks like you mistakenly tried to run me directly. (don't do that!)", 0, "I'm a plugin for BetterDiscord", 0x30);
    if (fs.GetParentFolderName(pathSelf) === fs.GetAbsolutePathName(pathPlugins)) {
        shell.Popup("I'm in the correct folder already.\nJust reload Discord with Ctrl+R.", 0, "I'm already installed", 0x40);
    } else if (!fs.FolderExists(pathPlugins)) {
        shell.Popup("I can't find the BetterDiscord plugins folder.\nAre you sure it's even installed?", 0, "Can't install myself", 0x10);
    } else if (shell.Popup("Should I copy myself to BetterDiscord's plugins folder for you?", 0, "Do you need some help?", 0x34) === 6) {
        fs.CopyFile(pathSelf, fs.BuildPath(pathPlugins, fs.GetFileName(pathSelf)), true);
        // Show the user where to put plugins in the future
        shell.Exec("explorer " + pathPlugins);
        shell.Popup("I'm installed!\nJust reload Discord with Ctrl+R.", 0, "Successfully installed", 0x40);
    }
    WScript.Quit();
@else @*/

var staticAvatars = function () {};

(function () {
    "use strict";

    // This is super hackish, and will likely break as Discord's internal API changes
    // Anything using this or what it returns should be prepared to catch some exceptions
    const getInternalInstance = e => e[Object.keys(e).find(k => k.startsWith("__reactInternalInstance"))];

    function getOwnerInstance(e, {include, exclude=["Popout", "Tooltip", "Scroller", "BackgroundFlash"]} = {}) {
        if (e === undefined) {
            return undefined;
        }

        // Set up filter; if no include filter is given, match all except those in exclude
        const excluding = include === undefined;
        const filter = excluding ? exclude : include;

        // Get displayName of the React class associated with this element
        // Based on getName(), but only check for an explicit displayName
        function getDisplayName(owner) {
            const type = owner._currentElement.type;
            const constructor = owner._instance && owner._instance.constructor;
            return type.displayName || constructor && constructor.displayName || null;
        }
        // Check class name against filters
        function classFilter(owner) {
            const name = getDisplayName(owner);
            return (name !== null && !!(filter.includes(name) ^ excluding));
        }

        // Walk up the hierarchy until a proper React object is found
        for (let prev, curr=getInternalInstance(e); !_.isNil(curr); prev=curr, curr=curr._hostParent) {
            // Before checking its parent, try to find a React object for prev among renderedChildren
            // This finds React objects which don't have a direct counterpart in the DOM hierarchy
            // e.g. Message, ChannelMember, ...
            if (prev !== undefined && !_.isNil(curr._renderedChildren)) {
                /* jshint loopfunc: true */
                let owner = Object.values(curr._renderedChildren)
                    .find(v => !_.isNil(v._instance) && v.getHostNode() === prev.getHostNode());
                if (!_.isNil(owner) && classFilter(owner)) {
                    return owner._instance;
                }
            }

            if (_.isNil(curr._currentElement)) {
                continue;
            }

            // Get a React object if one corresponds to this DOM element
            // e.g. .user-popout -> UserPopout, ...
            let owner = curr._currentElement._owner;
            if (!_.isNil(owner) && classFilter(owner)) {
                return owner._instance;
            }
        }

        return null;
    }

    // Mark elements with modified state so that they may be restored later
    const animationDisabled = new WeakSet();

    staticAvatars.prototype.start = function () {
        $(".theme-dark, .theme-light").on("mouseenter.staticavatars", ".message-group", function () {
            try {
                const messageGroup = getOwnerInstance(this, {include: ["MessageGroup"]});
                if (messageGroup.state.animatedAvatar) {
                    animationDisabled.add(this);
                    messageGroup.setState({animate: false, animatedAvatar: false});
                }
            } catch (err) {
                // Something (not surprisingly) broke, but this isn't critical enough to completely bail over
                //console.error("DiscordStaticAvatars", this, err);
                return;
            }
        });
    };

    staticAvatars.prototype.stop = function () {
        $(".theme-dark, .theme-light").off(".staticavatars", ".message-group");
        // Restore original state
        $(".message-group").each(function () {
            if (!animationDisabled.delete(this)) {
                // This element's state was not modified
                // Don't trigger a pointless re-render with setState
                return;
            }
            try {
                getOwnerInstance(this, {include: ["MessageGroup"]}).setState({animatedAvatar: true});
            } catch (err) {
                // Something (not surprisingly) broke, but this isn't critical enough to completely bail over
                //console.error("DiscordStaticAvatars", this, err);
                return;
            }
        });
    };

    staticAvatars.prototype.load = function () {};

    staticAvatars.prototype.unload = function () {};

    staticAvatars.prototype.getName = function () {
        return "Static Avatars";
    };

    staticAvatars.prototype.getDescription = function () {
        return "Don't animate avatars in the chat area";
    };

    staticAvatars.prototype.getVersion = function () {
        return "1.0.2";
    };

    staticAvatars.prototype.getAuthor = function () {
        return "noodlebox";
    };
})();

/*@end @*/
<commit_msg>Rewrite StaticAvatars using Discord Internals library (fixes #9)<commit_after>//META{"name":"staticAvatars"}*//

/*@cc_on
@if (@_jscript)
    // Offer to self-install for clueless users that try to run this directly.
    var shell = WScript.CreateObject("WScript.Shell");
    var fs = new ActiveXObject("Scripting.FileSystemObject");
    var pathPlugins = shell.ExpandEnvironmentStrings("%APPDATA%\\BetterDiscord\\plugins");
    var pathSelf = WScript.ScriptFullName;
    // Put the user at ease by addressing them in the first person
    shell.Popup("It looks like you mistakenly tried to run me directly. (don't do that!)", 0, "I'm a plugin for BetterDiscord", 0x30);
    if (fs.GetParentFolderName(pathSelf) === fs.GetAbsolutePathName(pathPlugins)) {
        shell.Popup("I'm in the correct folder already.\nJust reload Discord with Ctrl+R.", 0, "I'm already installed", 0x40);
    } else if (!fs.FolderExists(pathPlugins)) {
        shell.Popup("I can't find the BetterDiscord plugins folder.\nAre you sure it's even installed?", 0, "Can't install myself", 0x10);
    } else if (shell.Popup("Should I copy myself to BetterDiscord's plugins folder for you?", 0, "Do you need some help?", 0x34) === 6) {
        fs.CopyFile(pathSelf, fs.BuildPath(pathPlugins, fs.GetFileName(pathSelf)), true);
        // Show the user where to put plugins in the future
        shell.Exec("explorer " + pathPlugins);
        shell.Popup("I'm installed!\nJust reload Discord with Ctrl+R.", 0, "Successfully installed", 0x40);
    }
    WScript.Quit();
@else @*/

var staticAvatars = function () {};

(function () {
    "use strict";

    staticAvatars.prototype.start = function () {
        const module = WebpackModules.findByUniqueProperties(["hasAnimatedAvatar", "default"], {cacheOnly: true});
        if (!module) {
            console.error("StaticAvatars:", "unable to monkey patch hasAnimatedAvatar method");
            return;
        }
        this._cancel = monkeyPatch(module, "hasAnimatedAvatar", {instead: ()=>false});
    };

    staticAvatars.prototype.stop = function () {
        if (this._cancel) {
            this._cancel();
            delete this._cancel;
        }
    };

    staticAvatars.prototype.load = function () {};

    staticAvatars.prototype.unload = function () {};

    staticAvatars.prototype.getName = function () {
        return "Static Avatars";
    };

    staticAvatars.prototype.getDescription = function () {
        return "Don't animate avatars in the chat area";
    };

    staticAvatars.prototype.getVersion = function () {
        return "2.0.0";
    };

    staticAvatars.prototype.getAuthor = function () {
        return "noodlebox";
    };

    /**
     * Function with no arguments and no return value that may be called to reverse changes that is done by {@link monkeyPatch} method, restoring (unpatching) original method.
     * @callback cancelPatch
     */

    /**
     * This is a shortcut for calling original method using this and arguments from data object. This is a function without input arguments. This function is defined as `() => data.returnValue = data.originalMethod.apply(data.thisObject, data.methodArguments)`
     * @callback originalMethodCall
     * @return {*} The same value, which is returned from original method, also this value would be written into `data.returnValue`
     */

    /**
     * A callback that modifies method logic. Callback is called on each call of original method and have all data about original call. Any of the data can be modified if you need, but do it wisely.
     * @callback doPatchCallback
     * @param {PatchData} data Data object with all information about current that you may need in your patching callback.callback.
     * @return {*} Makes sense only when used as `instead` parameter in {@link monkeyPatch}. If returned something other then undefined - it replaces value in `returnValue` param. If used as `before` or `after` parameters - return value if ignored.
     */

    /**
     * This is function for monkey-patching any object method. Can make patch before, after or instead of target method.
     * Be careful when monkey-patching. Think not only about original functionality of target method and you changes, but also about develovers of other plugins, who may also patch this method before or after you. Try to change target method behaviour little as you can, and try to never change method signatures.
     * By default this function makes log messages about each patching and unpatching, so you and other developers can see what methods a patched. This messages may be suppressed.
     * Display name of patched method is changed, so you can see if function is patched and how many times while debuging or in the stack trace. Also patched function have property `__monkeyPatched` is set to true, in case you want to check something programmatically.
     *
     * @param {object} what Object to be patched. You can can also pass class prototypes to patch all class instances. If you are patching prototype of react component you may also need {@link Renderer.rebindMethods}.
     * @param {string} methodName The name of the target message to be patched.
     * @param {object} options Options object. You should provide at least one of `before`, `after` or `instead` parameters. Other parameters are optional.
     * @param {doPatchCallback} options.before Callback that will be called before original target method call. You can modify arguments here, so it will be passed to original method. Can be combined with `after`.
     * @param {doPatchCallback} options.after Callback that will be called after original target method call. You can modify return value here, so it will be passed to external code which calls target method. Can be combined with `before`.
     * @param {doPatchCallback} options.instead Callback that will be called instead of original target method call. You can get access to original method using `originalMethod` parameter if you want to call it, but you do not have to. Can't be combined with `before` and `after`.
     * @param {boolean} [options.once=false] Set to true if you want automatically unpatch method after first call.
     * @param {boolean} [options.silent=false] Set to true if you want to suppress log messages about patching and unpatching. Useful to avoid clogging the console in case of frequent conditional patching/unpatching, for example from another monkeyPatch callback.
     * @param {boolean} [options.displayName] You can provide meaningful name of class/object provided in `what` param for logging purposes. By default there will be a try to determine name automatically.
     * @return {cancelPatch} Function with no arguments and no return value that should be called to cancel (unpatch) this patch. You should save and run it when your plugin is stopped.
     */
    const monkeyPatch = (what, methodName, options) => {
        const {before, after, instead, once = false, silent = false} = options;
        const displayName = options.displayName || what.displayName || what.name || what.constructor.displayName || what.constructor.name;
        if (!silent) console.log('patch', methodName, 'of', displayName);
        const origMethod = what[methodName];
        const cancel = () => {
            if (!silent) console.log('unpatch', methodName, 'of', displayName);
            what[methodName] = origMethod;
        };
        what[methodName] = function() {
            /**
             * @interface
             * @name PatchData
             * @property {object} thisObject Original `this` value in current call of patched method.
             * @property {Arguments} methodArguments Original `arguments` object in current call of patched method. Please, never change function signatures, as it may cause a lot of problems in future.
             * @property {cancelPatch} cancelPatch Function with no arguments and no return value that may be called to reverse patching of current method. Calling this function prevents running of this callback on further original method calls.
             * @property {function} originalMethod Reference to the original method that is patched. You can use in if you need some special usage. You should explicitly provide this value and method arguments when you call this function.
             * @property {originalMethodCall} callOriginalMethod This is a shortcut for calling original method using this and arguments from data object.
             * @property {*} returnValue This is a value returned from original function call. This property is avilable only in `after` callback, or in `instead` callback after calling `callOriginalMethod` function
             */
            const data = {
                thisObject: this,
                methodArguments: arguments,
                cancelPatch: cancel,
                originalMethod: origMethod,
                callOriginalMethod: () => data.returnValue = data.originalMethod.apply(data.thisObject, data.methodArguments)
            };
            if (instead) {
                const tempRet = instead(data);
                if (tempRet !== undefined)
                    data.returnValue = tempRet;
            }
            else {
                if (before) before(data);
                data.callOriginalMethod();
                if (after) after(data);
            }
            if (once) cancel();
            return data.returnValue;
        };
        what[methodName].__monkeyPatched = true;
        what[methodName].displayName = 'patched ' + (what[methodName].displayName || methodName);
        return cancel;
    };

    const WebpackModules = (() => {

        const req = webpackJsonp([], {
            '__extra_id__': (module, exports, req) => exports.default = req
        }, ['__extra_id__']).default;
        delete req.m['__extra_id__'];
        delete req.c['__extra_id__'];

        /**
         * Predicate for searching module
         * @callback modulePredicate
         * @param {*} module Module to test
         * @return {boolean} Thue if it is module that you need
         */

        /**
         * Look through all modules of internal Discord's Webpack and return first one that match filter predicate.
         * At first this function will look thruogh alreary loaded modules cache. If no one of loaded modules is matched - then this function tries to load all modules and match for them. Loading any module may have unexpected side effects, like changing current locale of moment.js, so in that case there will be a warning the console. If no module matches - function will return null. You sould always take such predicate to match something, gut your code should be ready to recieve null in case if Discord update something in codebase.
         * If module is ES6 module and has default property, consider default first, otherwise - full module object.
         * @param {modulePredicate} filter Predicate to match module
         * @param {object} [options] Options object.
         * @param {boolean} [options.cacheOnly=false] Set to true if you want to search only the cache for modules.
         * @return {*} First module that matched by filter or null if none is matched.
         */
        const find = (filter, options = {}) => {
            const {cacheOnly = false} = options;
            for (let i in req.c) {
                if (req.c.hasOwnProperty(i)) {
                    let m = req.c[i].exports;
                    if (m && m.__esModule && m.default && filter(m.default))
                        return m.default;
                    if (m && filter(m))
                        return m;
                }
            }
            if (cacheOnly) {
                console.warn('Cannot find loaded module in cache');
                return null;
            }
            console.warn('Cannot find loaded module in cache. Loading all modules may have unexpected side effects');
            for (let i = 0; i < req.m.length; ++i) {
                let m = req(i);
                if (m && m.__esModule && m.default && filter(m.default))
                    return m.default;
                if (m && filter(m))
                    return m;
            }
            console.warn('Cannot find module');
            return null;
        };

        /**
         * Look through all modules of internal Discord's Webpack and return first object that has all of following properties. You should be ready that in any moment, after Discord update, this function may start returning null (if no such object exists any more) or even some different object with the same properties. So you should provide all property names that you use, and often even some extra properties to make sure you'll get exactly what you want.
         * @see Read {@link find} documentation for more details how search works
         * @param {string[]} propNames Array of property names to look for
         * @param {object} [options] Options object to pass to {@link find}.
         * @return {object} First module that matched by propNames or null if none is matched.
         */
        const findByUniqueProperties = (propNames, options) => find(module => propNames.every(prop => module[prop] !== undefined), options);

        /**
         * Look through all modules of internal Discord's Webpack and return first object that has displayName property with following value. This is useful for searching React components by name. Take into account that not all components are exported as modules. Also there might be several components with same names
         * @see Use {@link ReactComponents} as another way to get react components
         * @see Read {@link find} documentation for more details how search works
         * @param {string} displayName Display name property value to look for
         * @param {object} [options] Options object to pass to {@link find}.
         * @return {object} First module that matched by displayName or null if none is matched.
         */
        const findByDisplayName = (displayName, options) => find(module => module.displayName === displayName, options);

        return {find, findByUniqueProperties, findByDisplayName};

    })();
})();

/*@end @*/
<|endoftext|>


<commit_before>module.exports = function (value, key, option, lang) {
  if(option[0] === 'infrastructure'){
    return render_infrastructures(value, key, lang);
  }else if(option[0] === 'project'){
    return render_projects(value, key, lang);
  }else if (option[0] === 'client') {
    return render_clients(value, key, lang);
  }else if (option[0] === 'serverspec') {
    return render_serverspecs(value, key, lang);
  }else if (option[0] === 'dish') {
    return render_dish(value, key, lang);
  }else if (option[0] === 'cf_template') {
    return render_cf_templates(value, key, lang);
  }else if (option[0] === 'user_admin') {
    return render_user_admin(value, key, lang);
  }else if (option[0] === 'serverspec_logs') {
    return render_serverspecs_logs(value, key);
  }else{
    return value;
  }
};

function render_infrastructures(value, key, lang){
  if(key === 'id'){
  var isEdit = $('#edit-'+value+'').attr('class');
  var href = $('#edit-'+value+'').attr('href');
  var isDelete = $('#delete-'+value+'').attr('class');
  var ret = " "+t('helpers.links.show')+" " +
    "Serverspecs " +
    ""+ t("helpers.links.edit")+" " +
    " "+t('helpers.links.detach')+" "+
    "
"+
        "" +
        "  "+t('infrastructures.btn.delete_stack')+"  " +
        "  " +
       "
"+
        "
 " +
         "Execute " +
      "
"+
      "
"+
     "
";

    return ret;
  }else{
    if(value == "CREATE_COMPLETE")
      return ""+value+"";
    else
      return value;
  }
}

function render_clients(value, key, lang){
  if(key === 'id'){
    var isEdit = $('#delete-'+value+'').attr('class');
    var isDelete = $('#delete-'+value+'').attr('class');
    var edit = '';
    var del = '';
    if(isEdit)
      edit = "  "+t("helpers.links.edit")+"";
    if(isDelete)
      del = "  "+t("common.btn.delete")+"";

    var ret = " "+t('clients.btn.show_projects')+" ";
       return ret+edit+del;
  }else{
    return value;
  }
}

function render_projects(value, key, lang){
  if(key === 'id'){
    var isDelete = $('#delete-'+value+'').attr('class');
    var del;
    if(isDelete){
     del = " "+t("common.btn.delete")+"";
    }else{
     del = '';
    }

    var ret = " "+t('projects.btn.show_infrastructures')+" " +
      "
" +
        "" +
          t ('common.btn.settings')+ " " +
        "" +
        "
" +
          "
" +
            ""+t('dishes.dishes')+"" +
            ""+t('key_pairs.key_pairs')+"" +
          "
" +
        "
" +
      "
" +
      "  "+t("helpers.links.edit")+" ";
       return ret+del;
  }else{
    return value;
  }
}

function render_serverspecs(value, key, lang){
  if(key === 'id'){
    var isEdit = $('#edit-'+value+'').attr('class');
    var isDelete = $('#delete-'+value+'').attr('class');
    var edit = '';
    var del = '';
    if(isEdit)
      edit = "  "+t("helpers.links.edit")+"";
    if(isDelete)
      del = "  "+t("common.btn.delete")+"";

    var ret = " "+t('helpers.links.show')+" ";
    return ret+edit+del;
  }else{
    return value;
  }
}

function render_cf_templates(value, key, lang){
  if(key === 'id'){
    var isEdit = $('#edit-'+value+'').attr('class');
    var isDelete = $('#delete-'+value+'').attr('class');
    var edit = '';
    var del = '';
    if(isEdit)
      edit = " "+t("helpers.links.edit")+"";
    if(isDelete)
      del = " Delete";

    var ret = ""+t('helpers.links.show')+" ";
    return ret+edit+del;
  }else{
    return value;
  }
}

function render_dish(value, key, lang){
  if(key === 'id'){
    var isDelete = $('#delete-'+value+'').attr('class');
    var del = '';
    if(isDelete)
      del = " "+t("helpers.links.destroy")+"";

    var ret = ""+t('helpers.links.show')+" ";
    return ret+del;
  }else if (key === 'status') {
    var label = null;
    if(value === 'SUCCESS'){
      label = 'label-success';
    }else if (value === 'FAILURE') {
      label = 'label-danger';
    }else if (value === 'CREATING' || value === 'BOOTSTRAPPING' || value === 'APPLYING' || value === 'SERVERSPEC') {
      label = 'label-info';
    }else {
      label = 'label-warning';
      value = 'NOT YET';
    }

    return ""+value+"";
  }else{
    return value;
  }
}

function render_user_admin(value, key, lang){
  if(key === 'id'){
    var isEdit = $('#edit-'+value+'').attr('class');
    var isDelete = $('#delete-'+value+'').attr('class');
    var edit = '';
    var del = '';
    if(isEdit)
      edit = "  "+t("helpers.links.edit")+"";
    if(isDelete)
      del = "  "+t("helpers.links.destroy")+"";
    return edit+del;
  }else if (key === 'email') {
    var image = "";
    var email = value[1];
    return image+" "+email;
  }else if (key === 'role') {
    var admin = (value[0] ? "admin" : "");
    var master = (value[1] ? "master" : "");

    return master+"  "+admin;
  }else{
    return value;
  }
}

function render_serverspecs_logs(value, key){
  if(key === 'status'){
    var ret;
    switch (value) {
      case 'success':
        ret = ""+value+"";
        break;
      case 'failed':
        ret = ""+value+"";
        break;
      case 'pending':
        ret = ""+value+"";
        break;
    }
    return ret;
  }else if (key === 'message') {
      var head = "Serverspec for "+value[1]+"  ... 	";

      var body = "
" +
        "" +
        "
" +
        "
"+value[2]+"
" +
        "
" +
        "	" +
      "
";

    return head+body;
  }else{
    return value;
  }
}
<commit_msg>added more filters for status<commit_after>module.exports = function (value, key, option, lang) {
  if(option[0] === 'infrastructure'){
    return render_infrastructures(value, key, lang);
  }else if(option[0] === 'project'){
    return render_projects(value, key, lang);
  }else if (option[0] === 'client') {
    return render_clients(value, key, lang);
  }else if (option[0] === 'serverspec') {
    return render_serverspecs(value, key, lang);
  }else if (option[0] === 'dish') {
    return render_dish(value, key, lang);
  }else if (option[0] === 'cf_template') {
    return render_cf_templates(value, key, lang);
  }else if (option[0] === 'user_admin') {
    return render_user_admin(value, key, lang);
  }else if (option[0] === 'serverspec_logs') {
    return render_serverspecs_logs(value, key);
  }else{
    return value;
  }
};

function render_infrastructures(value, key, lang){
  if(key === 'id'){
  var isEdit = $('#edit-'+value+'').attr('class');
  var href = $('#edit-'+value+'').attr('href');
  var isDelete = $('#delete-'+value+'').attr('class');
  var ret = " "+t('helpers.links.show')+" " +
    "Serverspecs " +
    ""+ t("helpers.links.edit")+" " +
    " "+t('helpers.links.detach')+" "+
    "
"+
        "" +
        "  "+t('infrastructures.btn.delete_stack')+"  " +
        "  " +
       "
"+
        "
 " +
         "Execute " +
      "
"+
      "
"+
     "
";

    return ret;
  }else if (key === 'status') {
    if(value == "CREATE_COMPLETE"){
      return ""+value+"";
    }else if (value === 'DELETE_IN_PROGRESS') {
      return ""+value+"";
    }else if (value === 'CREATE_IN_PROGRESS') {
      return ""+value+"";
    }else{
      return 'NO STACK INFO';
    }
  }else{
    return value;
  }
}

function render_clients(value, key, lang){
  if(key === 'id'){
    var isEdit = $('#delete-'+value+'').attr('class');
    var isDelete = $('#delete-'+value+'').attr('class');
    var edit = '';
    var del = '';
    if(isEdit)
      edit = "  "+t("helpers.links.edit")+"";
    if(isDelete)
      del = "  "+t("common.btn.delete")+"";

    var ret = " "+t('clients.btn.show_projects')+" ";
       return ret+edit+del;
  }else{
    return value;
  }
}

function render_projects(value, key, lang){
  if(key === 'id'){
    var isDelete = $('#delete-'+value+'').attr('class');
    var del;
    if(isDelete){
     del = " "+t("common.btn.delete")+"";
    }else{
     del = '';
    }

    var ret = " "+t('projects.btn.show_infrastructures')+" " +
      "
" +
        "" +
          t ('common.btn.settings')+ " " +
        "" +
        "
" +
          "
" +
            ""+t('dishes.dishes')+"" +
            ""+t('key_pairs.key_pairs')+"" +
          "
" +
        "
" +
      "
" +
      "  "+t("helpers.links.edit")+" ";
       return ret+del;
  }else{
    return value;
  }
}

function render_serverspecs(value, key, lang){
  if(key === 'id'){
    var isEdit = $('#edit-'+value+'').attr('class');
    var isDelete = $('#delete-'+value+'').attr('class');
    var edit = '';
    var del = '';
    if(isEdit)
      edit = "  "+t("helpers.links.edit")+"";
    if(isDelete)
      del = "  "+t("common.btn.delete")+"";

    var ret = " "+t('helpers.links.show')+" ";
    return ret+edit+del;
  }else{
    return value;
  }
}

function render_cf_templates(value, key, lang){
  if(key === 'id'){
    var isEdit = $('#edit-'+value+'').attr('class');
    var isDelete = $('#delete-'+value+'').attr('class');
    var edit = '';
    var del = '';
    if(isEdit)
      edit = " "+t("helpers.links.edit")+"";
    if(isDelete)
      del = " Delete";

    var ret = ""+t('helpers.links.show')+" ";
    return ret+edit+del;
  }else{
    return value;
  }
}

function render_dish(value, key, lang){
  if(key === 'id'){
    var isDelete = $('#delete-'+value+'').attr('class');
    var del = '';
    if(isDelete)
      del = " "+t("helpers.links.destroy")+"";

    var ret = ""+t('helpers.links.show')+" ";
    return ret+del;
  }else if (key === 'status') {
    var label = null;
    if(value === 'SUCCESS'){
      label = 'label-success';
    }else if (value === 'FAILURE') {
      label = 'label-danger';
    }else if (value === 'CREATING' || value === 'BOOTSTRAPPING' || value === 'APPLYING' || value === 'SERVERSPEC') {
      label = 'label-info';
    }else {
      label = 'label-warning';
      value = 'NOT YET';
    }

    return ""+value+"";
  }else{
    return value;
  }
}

function render_user_admin(value, key, lang){
  if(key === 'id'){
    var isEdit = $('#edit-'+value+'').attr('class');
    var isDelete = $('#delete-'+value+'').attr('class');
    var edit = '';
    var del = '';
    if(isEdit)
      edit = "  "+t("helpers.links.edit")+"";
    if(isDelete)
      del = "  "+t("helpers.links.destroy")+"";
    return edit+del;
  }else if (key === 'email') {
    var image = "";
    var email = value[1];
    return image+" "+email;
  }else if (key === 'role') {
    var admin = (value[0] ? "admin" : "");
    var master = (value[1] ? "master" : "");

    return master+"  "+admin;
  }else{
    return value;
  }
}

function render_serverspecs_logs(value, key){
  if(key === 'status'){
    var ret;
    switch (value) {
      case 'success':
        ret = ""+value+"";
        break;
      case 'failed':
        ret = ""+value+"";
        break;
      case 'pending':
        ret = ""+value+"";
        break;
    }
    return ret;
  }else if (key === 'message') {
      var head = "Serverspec for "+value[1]+"  ... 	";

      var body = "
" +
        "" +
        "
" +
        "
"+value[2]+"
" +
        "
" +
        "	" +
      "
";

    return head+body;
  }else{
    return value;
  }
}
<|endoftext|>


<commit_before>var roleArchitect = require('role.architect');
var bodyObj = require('module.bodyTypes');
var modCommon = require('module.common');
var modConstants = require('module.constants');
var modMemory = require('module.memory');
//TODO queue system
//Change max upgraders to 1 and just increase work parts

var modSpawning = {

  //These return booleans
  //TODO finish needX()
  needHarvester:function(roomName){
    var roles = Memory.rooms[roomName].roles;

    var LTMin = roles.numHarvesters < roles.maxHarvesters;
    var tier = this.calcTier(roomName);

    return LTMin && tier<=3;
  },

  needUpgrader:function(roomName){
    var roles = Memory.rooms[roomName].roles;
    var notEnoughHarvest = (roles.numHarvesters <= 0) && (roles.numMiners <= 0);

    if(notEnoughHarvest){
      return false;
    }else{
      var LTMin = roles.numUpgraders < roles.maxUpgraders;
      return LTMin;
    }
  },

  needBuilder:function(roomName){
    var roles = Memory.rooms[roomName].roles;
    var notEnoughHarvest = (roles.numHarvesters <= 0) && (roles.numMiners <= 0);

    if(notEnoughHarvest){
      return false;
    }else{
      var tier = this.calcTier(roomName);
      var construct = Game.rooms[roomName].find(FIND_MY_CONSTRUCTION_SITES).length;
      var LTMin = roles.numBuilders < roles.maxBuilders;
      var noArch = roles.numArchitects === 0;
      return (tier > 1) && construct && LTMin && noArch;
    }
  },

  needRepair:function(roomName){
    var roles = Memory.rooms[roomName].roles;
    var notEnoughHarvest = (roles.numHarvesters <= 0) && (roles.numMiners <= 0);

    if(notEnoughHarvest){
      return false;
    }else{
      var numTowers = Memory.rooms[roomName].towers.length;
      var LTMin = roles.numRepair < (roles.maxRepair - numTowers);
      return LTMin;
    }
  },

  needArchitect:function(roomName){
    var roles = Memory.rooms[roomName].roles;
    var notEnoughHarvest = (roles.numHarvesters <= 0) && (roles.numMiners <= 0);

    if(notEnoughHarvest){
      return false;
    }else{
      var flags = _.filter(Game.rooms[roomName].find(FIND_FLAGS), (flag) => roleArchitect.ableToBuild(controllerLvl, flag.name));

      return flags.length && roles.numArchitects < 1;
    }
  },

  needMiner:function(roomName){
    var roles = Memory.rooms[roomName].roles;
    var notEnoughHarvest = (roles.numHarvesters <= 0) && (roles.numMiners <= 0);

    if(notEnoughHarvest){
      return false;
    }else{
      var tier = this.calcTier(roomName);
      var sources = Memory.rooms[roomName].sourceIDs.length;
      var LTMin = roles.numMiners < sources;
      return (tier >= 4) && LTMin;
    }
  },
  needHauler:function(roomName){
    var roles = Memory.rooms[roomName].roles;
    var notEnoughHarvest = (roles.numHarvesters <= 0) && (roles.numMiners <= 0);

    if(notEnoughHarvest){
      return false;
    }else{
      var tier = this.calcTier(roomName);
      var LTMin = roles.numHaulers < roles.maxHaulers;
      return (tier >= 4) && LTMin;
    }
  },

  needFeeder:function(roomName){
    var roles = Memory.rooms[roomName].roles;
    var notEnoughHarvest = (roles.numHarvesters <= 0) && (roles.numMiners <= 0);

    if(notEnoughHarvest){
      return false;
    }else{
      var storage = Game.rooms[roomName].storage !== undefined;
      var LTMin = roles.numFeeders < roles.maxFeeders;
      return storage && LTMin;
    }
  },

  needGeoMiner:function(roomName){
    var roles = Memory.rooms[roomName].roles;
    var notEnoughHarvest = (roles.numHarvesters <= 0) && (roles.numMiners <= 0);

    if(notEnoughHarvest){
      return false;
    }else{
      var tier = this.calcTier(roomName);
      var LTMin = roles.numGeo < 1;

      var extractor = _.filter(Game.rooms[roomName].find(FIND_STRUCTURES), (structure) => structure.structureType === STRUCTURE_EXTRACTOR);
      var minerals = (_.filter(Game.rooms[roomName].find(FIND_MINERALS), (mineral) => mineral.mineralAmount > 0).length) > 0;

      return (tier >=4) && LTMin && extractor && minerals;
    }
  },

  needMerchant:function(roomName){
    var roles = Memory.rooms[roomName].roles;
    var notEnoughHarvest = (roles.numHarvesters <= 0) && (roles.numMiners <= 0);

    if(notEnoughHarvest){
      return false;
    }else{
      var tier = this.calcTier(roomName);
      var LTMin = roles.numMerchant < 1;

      var minerals = (_.filter(Game.rooms[roomName].find(FIND_MINERALS), (mineral) => mineral.mineralAmount > 0).length) > 0;
      var toSell = modCommon.whatStore(Game.rooms[roomName].storage) != RESOURCE_ENERGY;

      return !minerals && toSell && (tier >= 4) && LTMin;
    }
  },

  /* Add type to queue, full parameter list object
      Example:
      var memoryObj = {
        role:'harvester',
        selfHarvest:true,
        source:""
      };

      var harvesterObj = {
        description:"",
        body: null,
        name: undefined,
        memory:memoryObj
      };
  */
  enqueueHarvester:function(roomName){
    var tier = this.calcTier(roomName);
    var memoryObj = {
      role:'harvester',
      selfHarvest:true,
      source:"",
      military:true
    };

    var harvesterObj = {
      description:"Harvester",
      body: null,
      name: undefined,
      memory:memoryObj
    };
    harvesterObj.body = bodyObj.getBody('harvester',tier);
    //Using unshift() to add to front, basic priority
    //Only use this for miners/harvesters
    Memory.rooms[roomName].spawnQ.unshift(harvesterObj);
  },

  //TODO finish the rest of the enqueues
  enqueueUpgrader:function(roomName){
    var tier = this.calcTier(roomName);
    var memoryObj = {
      role:'upgrader',
      selfHarvest:false
    };

    var obj = {
      description:"Upgrader",
      body: null,
      name: undefined,
      memory:memoryObj
    };
    if(tier === 1){
      obj.memory.selfHarvest = true;
    }
    obj.body = bodyObj.getBody('upgrader',tier);
    Memory.rooms[roomName].spawnQ.unshift(obj);
  },
  enqueueBuilder:function(roomName){
    var tier = this.calcTier(roomName);
    var memoryObj = {
      role:'builder',
      selfHarvest:false
    };

    var obj = {
      description:"Builder",
      body: null,
      name: undefined,
      memory:memoryObj
    };
    obj.body = bodyObj.getBody('builder',tier);
    Memory.rooms[roomName].spawnQ.push(obj);
  },
  enqueueRepair:function(roomName){
    var tier = this.calcTier(roomName);
    var memoryObj = {
      role:'repair',
      selfHarvest:true,
      toFix:'',
      military:true
    };

    var obj = {
      description:"Repair",
      body: null,
      name: undefined,
      memory:memoryObj
    };
    if(tier === 1){
      obj.memory.selfHarvest = true;
    }
    obj.body = bodyObj.getBody('repair',tier);
    Memory.rooms[roomName].spawnQ.push(obj);
  }, //Attacks?
  enqueueArchitect:function(roomName){
    var tier = this.calcTier(roomName);
    var memoryObj = {
      role:'architect',
      selfHarvest:false
    };

    var obj = {
      description:"Architect",
      body: null,
      name: undefined,
      memory:memoryObj
    };
    obj.body = bodyObj.getBody('architect',tier);
    Memory.rooms[roomName].spawnQ.push(obj);
  },
  enqueueMiner:function(roomName){
    var tier = this.calcTier(roomName);
    var memoryObj = {
      role:'miner',
      source:"",
      dropOff:"",
      military:true
    };

    var obj = {
      description:"Miner",
      body: null,
      name: undefined,
      memory:memoryObj
    };
    obj.body = bodyObj.getBody('miner',tier);
    Memory.rooms[roomName].spawnQ.unshift(obj);
  },
  enqueueHauler:function(roomName){
    var tier = this.calcTier(roomName);
    var memoryObj = {
      role:'hauler',
      dropOff:"",
      military:true
    };

    var obj = {
      description:"Hauler",
      body: null,
      name: undefined,
      memory:memoryObj
    };
    obj.body = bodyObj.getBody('hauler',tier);
    Memory.rooms[roomName].spawnQ.unshift(obj);
  },
  enqueueFeeder:function(roomName){
    var tier = this.calcTier(roomName);
    var memoryObj = {
      role:'feeder',
      military:true
    };

    var obj = {
      description:"Feeder",
      body: null,
      name: undefined,
      memory:memoryObj
    };
    obj.body = bodyObj.getBody('feeder',tier);
    Memory.rooms[roomName].spawnQ.unshift(obj);
  },
  enqueueGeoMiner:function(roomName){
    var tier = this.calcTier(roomName);
    var memoryObj = {
      role:'geo',
      mineral:"",
      dropOff:""
    };

    var obj = {
      description:"Mineral Miner",
      body: null,
      name: undefined,
      memory:memoryObj
    };
    obj.body = bodyObj.getBody('geo',tier);
    Memory.rooms[roomName].spawnQ.unshift(obj);
  },
  enqueueMerchant:function(roomName){
    var tier = this.calcTier(roomName);
    var memoryObj = {
      role:'merchant',
      terminal:"",
      storage:""
    };

    var obj = {
      description:"Merchant",
      body: null,
      name: undefined,
      memory:memoryObj
    };
    obj.body = bodyObj.getBody('merchant',tier);
    Memory.rooms[roomName].spawnQ.unshift(obj);
  },

  //TODO call this and spawn() from main
  enqueueAllNeeded(roomName){
    if(this.needHarvester(roomName)) enqueueHarvester(roomName);
    if(this.needUpgrader(roomName)) enqueueUpgrader(roomName);
    if(this.needBuilder(roomName)) enqueueBuilder(roomName);
    if(this.needRepair(roomName)) enqueueRepair(roomName);
    if(this.needArchitect(roomName)) enqueueArchitect(roomName);
    if(this.needMiner(roomName)) enqueueMiner(roomName);
    if(this.needHauler(roomName)) enqueueHauler(roomName);
    if(this.needFeeder(roomName)) enqueueFeeder(roomName);
    if(this.needGeoMiner(roomName)) enqueueGeoMiner(roomName);
    if(this.needMerchant(roomName)) enqueueMerchant(roomName);
  },

  //Returns a number between 1 and highest tier inclusive
  calcTier:function(roomName){
    var energyCapacity = Memory.rooms[roomName].energyCapacityAvailable;
    var notEnoughHarvest = (Memory.rooms[roomName].roles.numHarvesters <= 0) && (Memory.rooms[roomName].roles.numMiners <= 0);

    var spawnTier1 = (energyCapacity<modConstants.tier2EnergyMin);
    var spawnTier2 = (energyCapacity<modConstants.tier3EnergyMin);
    var spawnTier3 = (energyCapacity<modConstants.tier4EnergyMin);
    var spawnTier4 = (energyCapacity>=modConstants.tier4EnergyMin);

    if(spawnTier1 || notEnoughHarvest){
      return 1;
    }else if(spawnTier2){
      return 2;
    }else if(spawnTier3){
      return 3;
    }else if(spawnTier4){
      return 4;
    }
    return 1;
  },

  //dequeue and spawn
  spawn:function(roomName){
    var available = Memory.rooms[roomName].energyAvailable;
    var queue = Memory.rooms[roomName].spawnQ;
    if(queue.length > 0){
      var spawners = Game.rooms[roomName].find(FIND_STRUCTURES, {
        filter: (structure) => {
          return (structure.structureType === STRUCTURE_SPAWN && !structure.spawning);
        }
      });
      for(var spawn in spawners){
        var toSpawn = queue.shift();
        if(toSpawn !== undefined && bodyObj.calcCost(toSpawn.body)<=available){
          var creep = spawn.createCreep(toSpawn.body,toSpawn.name,toSpawn.memory);
          console.log("Room "+roomName+": Spawning "+toSpawn.description+": "+creep);
        }
      }
    }
  }
};
modSpawning.maxCreeps = 20;

module.exports = modSpawning;
<commit_msg>removed TODO<commit_after>var roleArchitect = require('role.architect');
var bodyObj = require('module.bodyTypes');
var modCommon = require('module.common');
var modConstants = require('module.constants');
var modMemory = require('module.memory');
//TODO queue system
//Change max upgraders to 1 and just increase work parts

var modSpawning = {

  //These return booleans
  needHarvester:function(roomName){
    var roles = Memory.rooms[roomName].roles;

    var LTMin = roles.numHarvesters < roles.maxHarvesters;
    var tier = this.calcTier(roomName);

    return LTMin && tier<=3;
  },

  needUpgrader:function(roomName){
    var roles = Memory.rooms[roomName].roles;
    var notEnoughHarvest = (roles.numHarvesters <= 0) && (roles.numMiners <= 0);

    if(notEnoughHarvest){
      return false;
    }else{
      var LTMin = roles.numUpgraders < roles.maxUpgraders;
      return LTMin;
    }
  },

  needBuilder:function(roomName){
    var roles = Memory.rooms[roomName].roles;
    var notEnoughHarvest = (roles.numHarvesters <= 0) && (roles.numMiners <= 0);

    if(notEnoughHarvest){
      return false;
    }else{
      var tier = this.calcTier(roomName);
      var construct = Game.rooms[roomName].find(FIND_MY_CONSTRUCTION_SITES).length;
      var LTMin = roles.numBuilders < roles.maxBuilders;
      var noArch = roles.numArchitects === 0;
      return (tier > 1) && construct && LTMin && noArch;
    }
  },

  needRepair:function(roomName){
    var roles = Memory.rooms[roomName].roles;
    var notEnoughHarvest = (roles.numHarvesters <= 0) && (roles.numMiners <= 0);

    if(notEnoughHarvest){
      return false;
    }else{
      var numTowers = Memory.rooms[roomName].towers.length;
      var LTMin = roles.numRepair < (roles.maxRepair - numTowers);
      return LTMin;
    }
  },

  needArchitect:function(roomName){
    var roles = Memory.rooms[roomName].roles;
    var notEnoughHarvest = (roles.numHarvesters <= 0) && (roles.numMiners <= 0);

    if(notEnoughHarvest){
      return false;
    }else{
      var flags = _.filter(Game.rooms[roomName].find(FIND_FLAGS), (flag) => roleArchitect.ableToBuild(controllerLvl, flag.name));

      return flags.length && roles.numArchitects < 1;
    }
  },

  needMiner:function(roomName){
    var roles = Memory.rooms[roomName].roles;
    var notEnoughHarvest = (roles.numHarvesters <= 0) && (roles.numMiners <= 0);

    if(notEnoughHarvest){
      return false;
    }else{
      var tier = this.calcTier(roomName);
      var sources = Memory.rooms[roomName].sourceIDs.length;
      var LTMin = roles.numMiners < sources;
      return (tier >= 4) && LTMin;
    }
  },
  needHauler:function(roomName){
    var roles = Memory.rooms[roomName].roles;
    var notEnoughHarvest = (roles.numHarvesters <= 0) && (roles.numMiners <= 0);

    if(notEnoughHarvest){
      return false;
    }else{
      var tier = this.calcTier(roomName);
      var LTMin = roles.numHaulers < roles.maxHaulers;
      return (tier >= 4) && LTMin;
    }
  },

  needFeeder:function(roomName){
    var roles = Memory.rooms[roomName].roles;
    var notEnoughHarvest = (roles.numHarvesters <= 0) && (roles.numMiners <= 0);

    if(notEnoughHarvest){
      return false;
    }else{
      var storage = Game.rooms[roomName].storage !== undefined;
      var LTMin = roles.numFeeders < roles.maxFeeders;
      return storage && LTMin;
    }
  },

  needGeoMiner:function(roomName){
    var roles = Memory.rooms[roomName].roles;
    var notEnoughHarvest = (roles.numHarvesters <= 0) && (roles.numMiners <= 0);

    if(notEnoughHarvest){
      return false;
    }else{
      var tier = this.calcTier(roomName);
      var LTMin = roles.numGeo < 1;

      var extractor = _.filter(Game.rooms[roomName].find(FIND_STRUCTURES), (structure) => structure.structureType === STRUCTURE_EXTRACTOR);
      var minerals = (_.filter(Game.rooms[roomName].find(FIND_MINERALS), (mineral) => mineral.mineralAmount > 0).length) > 0;

      return (tier >=4) && LTMin && extractor && minerals;
    }
  },

  needMerchant:function(roomName){
    var roles = Memory.rooms[roomName].roles;
    var notEnoughHarvest = (roles.numHarvesters <= 0) && (roles.numMiners <= 0);

    if(notEnoughHarvest){
      return false;
    }else{
      var tier = this.calcTier(roomName);
      var LTMin = roles.numMerchant < 1;

      var minerals = (_.filter(Game.rooms[roomName].find(FIND_MINERALS), (mineral) => mineral.mineralAmount > 0).length) > 0;
      var toSell = modCommon.whatStore(Game.rooms[roomName].storage) != RESOURCE_ENERGY;

      return !minerals && toSell && (tier >= 4) && LTMin;
    }
  },

  /* Add type to queue, full parameter list object
      Example:
      var memoryObj = {
        role:'harvester',
        selfHarvest:true,
        source:""
      };

      var harvesterObj = {
        description:"",
        body: null,
        name: undefined,
        memory:memoryObj
      };
  */
  enqueueHarvester:function(roomName){
    var tier = this.calcTier(roomName);
    var memoryObj = {
      role:'harvester',
      selfHarvest:true,
      source:"",
      military:true
    };

    var harvesterObj = {
      description:"Harvester",
      body: null,
      name: undefined,
      memory:memoryObj
    };
    harvesterObj.body = bodyObj.getBody('harvester',tier);
    //Using unshift() to add to front, basic priority
    //Only use this for miners/harvesters
    Memory.rooms[roomName].spawnQ.unshift(harvesterObj);
  },

  //TODO finish the rest of the enqueues
  enqueueUpgrader:function(roomName){
    var tier = this.calcTier(roomName);
    var memoryObj = {
      role:'upgrader',
      selfHarvest:false
    };

    var obj = {
      description:"Upgrader",
      body: null,
      name: undefined,
      memory:memoryObj
    };
    if(tier === 1){
      obj.memory.selfHarvest = true;
    }
    obj.body = bodyObj.getBody('upgrader',tier);
    Memory.rooms[roomName].spawnQ.unshift(obj);
  },
  enqueueBuilder:function(roomName){
    var tier = this.calcTier(roomName);
    var memoryObj = {
      role:'builder',
      selfHarvest:false
    };

    var obj = {
      description:"Builder",
      body: null,
      name: undefined,
      memory:memoryObj
    };
    obj.body = bodyObj.getBody('builder',tier);
    Memory.rooms[roomName].spawnQ.push(obj);
  },
  enqueueRepair:function(roomName){
    var tier = this.calcTier(roomName);
    var memoryObj = {
      role:'repair',
      selfHarvest:true,
      toFix:'',
      military:true
    };

    var obj = {
      description:"Repair",
      body: null,
      name: undefined,
      memory:memoryObj
    };
    if(tier === 1){
      obj.memory.selfHarvest = true;
    }
    obj.body = bodyObj.getBody('repair',tier);
    Memory.rooms[roomName].spawnQ.push(obj);
  }, //Attacks?
  enqueueArchitect:function(roomName){
    var tier = this.calcTier(roomName);
    var memoryObj = {
      role:'architect',
      selfHarvest:false
    };

    var obj = {
      description:"Architect",
      body: null,
      name: undefined,
      memory:memoryObj
    };
    obj.body = bodyObj.getBody('architect',tier);
    Memory.rooms[roomName].spawnQ.push(obj);
  },
  enqueueMiner:function(roomName){
    var tier = this.calcTier(roomName);
    var memoryObj = {
      role:'miner',
      source:"",
      dropOff:"",
      military:true
    };

    var obj = {
      description:"Miner",
      body: null,
      name: undefined,
      memory:memoryObj
    };
    obj.body = bodyObj.getBody('miner',tier);
    Memory.rooms[roomName].spawnQ.unshift(obj);
  },
  enqueueHauler:function(roomName){
    var tier = this.calcTier(roomName);
    var memoryObj = {
      role:'hauler',
      dropOff:"",
      military:true
    };

    var obj = {
      description:"Hauler",
      body: null,
      name: undefined,
      memory:memoryObj
    };
    obj.body = bodyObj.getBody('hauler',tier);
    Memory.rooms[roomName].spawnQ.unshift(obj);
  },
  enqueueFeeder:function(roomName){
    var tier = this.calcTier(roomName);
    var memoryObj = {
      role:'feeder',
      military:true
    };

    var obj = {
      description:"Feeder",
      body: null,
      name: undefined,
      memory:memoryObj
    };
    obj.body = bodyObj.getBody('feeder',tier);
    Memory.rooms[roomName].spawnQ.unshift(obj);
  },
  enqueueGeoMiner:function(roomName){
    var tier = this.calcTier(roomName);
    var memoryObj = {
      role:'geo',
      mineral:"",
      dropOff:""
    };

    var obj = {
      description:"Mineral Miner",
      body: null,
      name: undefined,
      memory:memoryObj
    };
    obj.body = bodyObj.getBody('geo',tier);
    Memory.rooms[roomName].spawnQ.unshift(obj);
  },
  enqueueMerchant:function(roomName){
    var tier = this.calcTier(roomName);
    var memoryObj = {
      role:'merchant',
      terminal:"",
      storage:""
    };

    var obj = {
      description:"Merchant",
      body: null,
      name: undefined,
      memory:memoryObj
    };
    obj.body = bodyObj.getBody('merchant',tier);
    Memory.rooms[roomName].spawnQ.unshift(obj);
  },

  //TODO call this and spawn() from main
  enqueueAllNeeded(roomName){
    if(this.needHarvester(roomName)) enqueueHarvester(roomName);
    if(this.needUpgrader(roomName)) enqueueUpgrader(roomName);
    if(this.needBuilder(roomName)) enqueueBuilder(roomName);
    if(this.needRepair(roomName)) enqueueRepair(roomName);
    if(this.needArchitect(roomName)) enqueueArchitect(roomName);
    if(this.needMiner(roomName)) enqueueMiner(roomName);
    if(this.needHauler(roomName)) enqueueHauler(roomName);
    if(this.needFeeder(roomName)) enqueueFeeder(roomName);
    if(this.needGeoMiner(roomName)) enqueueGeoMiner(roomName);
    if(this.needMerchant(roomName)) enqueueMerchant(roomName);
  },

  //Returns a number between 1 and highest tier inclusive
  calcTier:function(roomName){
    var energyCapacity = Memory.rooms[roomName].energyCapacityAvailable;
    var notEnoughHarvest = (Memory.rooms[roomName].roles.numHarvesters <= 0) && (Memory.rooms[roomName].roles.numMiners <= 0);

    var spawnTier1 = (energyCapacity<modConstants.tier2EnergyMin);
    var spawnTier2 = (energyCapacity<modConstants.tier3EnergyMin);
    var spawnTier3 = (energyCapacity<modConstants.tier4EnergyMin);
    var spawnTier4 = (energyCapacity>=modConstants.tier4EnergyMin);

    if(spawnTier1 || notEnoughHarvest){
      return 1;
    }else if(spawnTier2){
      return 2;
    }else if(spawnTier3){
      return 3;
    }else if(spawnTier4){
      return 4;
    }
    return 1;
  },

  //dequeue and spawn
  spawn:function(roomName){
    var available = Memory.rooms[roomName].energyAvailable;
    var queue = Memory.rooms[roomName].spawnQ;
    if(queue.length > 0){
      var spawners = Game.rooms[roomName].find(FIND_STRUCTURES, {
        filter: (structure) => {
          return (structure.structureType === STRUCTURE_SPAWN && !structure.spawning);
        }
      });
      for(var spawn in spawners){
        var toSpawn = queue.shift();
        if(toSpawn !== undefined && bodyObj.calcCost(toSpawn.body)<=available){
          var creep = spawn.createCreep(toSpawn.body,toSpawn.name,toSpawn.memory);
          console.log("Room "+roomName+": Spawning "+toSpawn.description+": "+creep);
        }
      }
    }
  }
};
modSpawning.maxCreeps = 20;

module.exports = modSpawning;
<|endoftext|>