<commit_before>/**
 * Copyright 2013 IBM Corp.
 *
 * 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.
 **/

var RED = require("../../red/red");
var reconnectTime = RED.settings.socketReconnectTime||10000;
var net = require('net');

function TcpIn(n) {
	RED.nodes.createNode(this,n);
	this.host = n.host;
	this.port = n.port * 1;
	this.topic = n.topic;
	this.stream = (!n.datamode||n.datamode=='stream'); /* stream,single*/
	this.datatype = n.datatype||'buffer'; /* buffer,utf8,base64 */
	this.newline = (n.newline||"").replace("\\n","\n").replace("\\r","\r");
	this.base64 = n.base64;
	this.server = (typeof n.server == 'boolean')?n.server:(n.server == "server");
	this.closing = false;
	var node = this;

	if (!node.server) {
        var buffer = null;
		var client;
		var reconnectTimeout;
		function setupTcpClient() {
			node.log("connecting to "+node.host+":"+node.port);
			client = net.connect(node.port, node.host, function() {
			        buffer = (node.datatype == 'buffer')? new Buffer(0):"";
			        node.log("connected to "+node.host+":"+node.port);
			});

			client.on('data', function (data) {
			        if (node.datatype != 'buffer') {
			            data = data.toString(node.datatype);
			        }
			        if (node.stream) {
			            if ((typeof data) === "string" && node.newline != "") {
			                buffer = buffer+data;
			                var parts = buffer.split(node.newline);
			                for (var i = 0;i<parts.length-1;i+=1) {
			                    var msg = {topic:node.topic, payload:parts[i]};
			                    node.send(msg);
			                }
			                buffer = parts[parts.length-1];
			            } else {
			                var msg = {topic:node.topic, payload:data};
			                node.send(msg);
			            }
			        } else {
			            if ((typeof data) === "string") {
			                buffer = buffer+data;
			            } else {
			                buffer = Buffer.concat([buffer,data],buffer.length+data.length);
			            }
			        }
			});
			client.on('end', function() {
			        if (!node.stream || (node.datatype == "utf8" && node.newline != "" && buffer.length > 0)) {
			            var msg = {topic:node.topic,payload:buffer};
			            node.send(msg);
			            buffer = null;
			        }
			});

			client.on('close', function() {
			        node.log("connection lost to "+node.host+":"+node.port);
			        if (!node.closing) {
			            reconnectTimeout = setTimeout(setupTcpClient, reconnectTime);
			        }
			});

			client.on('error', function(err) {
			        node.log(err);
			});
		}
		setupTcpClient();

		this._close = function() {
		    this.closing = true;
			client.end();
			clearTimeout(reconnectTimeout);
		}
	} else {
		var server = net.createServer(function (socket) {
		        var buffer = (node.datatype == 'buffer')? new Buffer(0):"";
		        socket.on('data', function (data) {
		                if (node.datatype != 'buffer') {
		                    data = data.toString(node.datatype);
		                }

		                if (node.stream) {
		                    if ((typeof data) === "string" && node.newline != "") {
		                        buffer = buffer+data;
		                        var parts = buffer.split(node.newline);
		                        for (var i = 0;i<parts.length-1;i+=1) {
		                            var msg = {topic:node.topic, payload:parts[i]};
		                            node.send(msg);
		                        }
		                        buffer = parts[parts.length-1];
		                    } else {
		                        var msg = {topic:node.topic, payload:data};
		                        node.send(msg);
		                    }
		                } else {
		                    if ((typeof data) === "string") {
		                        buffer = buffer+data;
		                    } else {
		                        buffer = Buffer.concat([buffer,data],buffer.length+data.length);
		                    }
		                }
		        });
		        socket.on('end', function() {
		                if (!node.stream || (node.datatype == "utf8" && node.newline != "" && buffer.length > 0)) {
		                    var msg = {topic:node.topic,payload:buffer};
		                    node.send(msg);
		                    buffer = null;
		                }
		        });
		        socket.on('error',function(err) {
		            node.log(err);
		        });
		});
		server.listen(node.port);
		node.log('listening on port '+node.port);

		this._close = function() {
		    this.closing = true;
			server.close();
			node.log('stopped listening on port '+node.port);
		}
	}

}

RED.nodes.registerType("tcp in",TcpIn);

TcpIn.prototype.close = function() {
	this._close();
}

<commit_msg>Fix wrong type of string being detected by TCPin node<commit_after>/**
 * Copyright 2013 IBM Corp.
 *
 * 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.
 **/

var RED = require("../../red/red");
var reconnectTime = RED.settings.socketReconnectTime||10000;
var net = require('net');

function TcpIn(n) {
	RED.nodes.createNode(this,n);
	this.host = n.host;
	this.port = n.port * 1;
	this.topic = n.topic;
	this.stream = (!n.datamode||n.datamode=='stream'); /* stream,single*/
	this.datatype = n.datatype||'buffer'; /* buffer,utf8,base64 */
	this.newline = (n.newline||"").replace("\\n","\n").replace("\\r","\r");
	this.base64 = n.base64;
	this.server = (typeof n.server == 'boolean')?n.server:(n.server == "server");
	this.closing = false;
	var node = this;

	if (!node.server) {
        var buffer = null;
		var client;
		var reconnectTimeout;
		function setupTcpClient() {
			node.log("connecting to "+node.host+":"+node.port);
			client = net.connect(node.port, node.host, function() {
			        buffer = (node.datatype == 'buffer')? new Buffer(0):"";
			        node.log("connected to "+node.host+":"+node.port);
			});

			client.on('data', function (data) {
			        if (node.datatype != 'buffer') {
			            data = data.toString(node.datatype);
			        }
			        if (node.stream) {
			            if ((node.datatype) === "utf8" && node.newline != "") {
			                buffer = buffer+data;
			                var parts = buffer.split(node.newline);
			                for (var i = 0;i<parts.length-1;i+=1) {
			                    var msg = {topic:node.topic, payload:parts[i]};
			                    node.send(msg);
			                }
			                buffer = parts[parts.length-1];
			            } else {
			                var msg = {topic:node.topic, payload:data};
			                node.send(msg);
			            }
			        } else {
			            if ((typeof data) === "string") {
			                buffer = buffer+data;
			            } else {
			                buffer = Buffer.concat([buffer,data],buffer.length+data.length);
			            }
			        }
			});
			client.on('end', function() {
			        if (!node.stream || (node.datatype == "utf8" && node.newline != "" && buffer.length > 0)) {
			            var msg = {topic:node.topic,payload:buffer};
			            node.send(msg);
			            buffer = null;
			        }
			});

			client.on('close', function() {
			        node.log("connection lost to "+node.host+":"+node.port);
			        if (!node.closing) {
			            reconnectTimeout = setTimeout(setupTcpClient, reconnectTime);
			        }
			});

			client.on('error', function(err) {
			        node.log(err);
			});
		}
		setupTcpClient();

		this._close = function() {
		    this.closing = true;
			client.end();
			clearTimeout(reconnectTimeout);
		}
	} else {
		var server = net.createServer(function (socket) {
		        var buffer = (node.datatype == 'buffer')? new Buffer(0):"";
		        socket.on('data', function (data) {
		                if (node.datatype != 'buffer') {
		                    data = data.toString(node.datatype);
		                }

		                if (node.stream) {
		                    if ((typeof data) === "string" && node.newline != "") {
		                        buffer = buffer+data;
		                        var parts = buffer.split(node.newline);
		                        for (var i = 0;i<parts.length-1;i+=1) {
		                            var msg = {topic:node.topic, payload:parts[i]};
		                            node.send(msg);
		                        }
		                        buffer = parts[parts.length-1];
		                    } else {
		                        var msg = {topic:node.topic, payload:data};
		                        node.send(msg);
		                    }
		                } else {
		                    if ((typeof data) === "string") {
		                        buffer = buffer+data;
		                    } else {
		                        buffer = Buffer.concat([buffer,data],buffer.length+data.length);
		                    }
		                }
		        });
		        socket.on('end', function() {
		                if (!node.stream || (node.datatype == "utf8" && node.newline != "" && buffer.length > 0)) {
		                    var msg = {topic:node.topic,payload:buffer};
		                    node.send(msg);
		                    buffer = null;
		                }
		        });
		        socket.on('error',function(err) {
		            node.log(err);
		        });
		});
		server.listen(node.port);
		node.log('listening on port '+node.port);

		this._close = function() {
		    this.closing = true;
			server.close();
			node.log('stopped listening on port '+node.port);
		}
	}

}

RED.nodes.registerType("tcp in",TcpIn);

TcpIn.prototype.close = function() {
	this._close();
}
<|endoftext|>


<commit_before>import * as React from 'react';
import * as PropTypes from 'prop-types';
import classNames from 'classnames';

import {
    ListRow,
    Switch as GypSwitch,
    TextLabel,
} from '@ichef/gypcrete';

import formRow, { rowPropTypes } from './mixins/formRow';

function Switch({
    label,
    aside,
    // from formRow()
    ineditable,
    rowProps,
    // React props,
    className,
    ...switchProps,
}) {
    const rootClassName = classNames('', className);

    return (
        <ListRow className={rootClassName} {...rowProps}>
            <TextLabel
                bold={!ineditable}
                basic={label}
                aside={aside} />

            <GypSwitch
                status={null}
                {...switchProps} />
        </ListRow>
    );
}

Switch.propTypes = {
    label: PropTypes.node.isRequired,
    aside: PropTypes.node,
    // from formRow()
    ineditable: PropTypes.bool,
    rowProps: rowPropTypes,
};

Switch.defaultProps = {
    aside: undefined,
    ineditable: false,
    rowProps: {},
};

export { Switch as PureSwitch };
export default formRow()(Switch);
<commit_msg>Add comments to clarify form <Switch><commit_after>import * as React from 'react';
import * as PropTypes from 'prop-types';
import classNames from 'classnames';

import {
    ListRow,
    Switch as SwitchButton,
    TextLabel,
} from '@ichef/gypcrete';

import formRow, { rowPropTypes } from './mixins/formRow';

/**
 * <Switch>
 * ========
 * A row consisting a text label (on the left) and a switch button (on the right).
 * The aside of left label can be updated with the checked state of switch.
 *
 * All unknown props should go to the `<SwitchButton>` inside.
 */
function Switch({
    label,
    aside,
    // from formRow()
    ineditable,
    rowProps,
    // React props,
    className,
    ...switchProps,
}) {
    const rootClassName = classNames('', className);

    return (
        <ListRow className={rootClassName} {...rowProps}>
            <TextLabel
                bold={!ineditable}
                basic={label}
                aside={aside} />

            <SwitchButton
                status={null}
                {...switchProps} />
        </ListRow>
    );
}

Switch.propTypes = {
    label: PropTypes.node.isRequired,
    aside: PropTypes.node,
    // from formRow()
    ineditable: PropTypes.bool,
    rowProps: rowPropTypes,
};

Switch.defaultProps = {
    aside: undefined,
    ineditable: false,
    rowProps: {},
};

export { Switch as PureSwitch };
export default formRow()(Switch);
<|endoftext|>


<commit_before>(function() {
  var cached_client, config_from_redis, resolve, rx;

  rx = /\$\{([^\}]+)\}/;

  resolve = function(config, v) {
    var match;
    if (v == null) {
      return null;
    }
    while ((match = rx.exec(v)) != null) {
      v = v.replace(match[0], resolve(config, config[match[1]]));
    }
    return v;
  };

  config_from_redis = function(app) {
    return function(done) {
      return module.exports.environment(app.environment).get(true, function(err, config) {
        var k, v;
        console.log(arguments);
        if (err != null) {
          return done(err);
        }
        for (k in config) {
          v = config[k];
          process.env[k] = resolve(config, v);
        }
        return done();
      });
    };
  };

  module.exports = function(app) {
    if (process.env.REDIS_ENV_VAR_URL == null) {
      throw new Error('To use redis-env-var-layer you must define the REDIS_ENV_VAR_URL environment variable.');
    }
    return app.sequence('init').insert('config-from-redis', config_from_redis(app), {
      before: 'config'
    });
  };

  cached_client = null;

  module.exports.__defineGetter__('client', function() {
    return cached_client || (cached_client = require('redis-builder')({
      url: process.env.REDIS_ENV_VAR_URL
    }));
  });

  module.exports.environments = {
    list: function(cb) {
      return module.exports.client.keys('*', cb);
    }
  };

  module.exports.environment = function(env) {
    return {
      get: function(key, should_resolve, cb) {
        if (typeof key === 'function') {
          return module.exports.client.hgetall(env, key);
        } else if (typeof key === 'boolean' && typeof should_resolve === 'function') {
          if (key === false) {
            return module.exports.client.hgetall(env, should_resolve);
          }
          return module.exports.client.hgetall(env, function(err, config) {
            if (err != null) {
              return should_resolve(err);
            }
            return should_resolve(null, Object.keys(config).reduce(function(o, k) {
              o[k] = resolve(config, config[k]);
              return o;
            }, {}));
          });
        } else if (typeof key === 'string' && typeof should_resolve === 'function') {
          return module.exports.client.hget(env, key, should_resolve);
        } else if (typeof key === 'string' && typeof should_resolve === 'boolean' && typeof cb === 'function') {
          if (should_resolve === false) {
            return module.exports.client.hget(env, key, cb);
          }
          return this.get(true, function(err, config) {
            if (err != null) {
              return cb(err);
            }
            return cb(null, config[key]);
          });
        }
      },
      set: function(k, v, cb) {
        if (typeof k === 'object' && typeof v === 'function' && (cb == null)) {
          return module.exports.client.hmset(env, k, v);
        } else if (typeof k === 'string' && (v != null) && typeof cb === 'function') {
          return module.exports.client.hset(env, k, v, cb);
        }
      },
      remove: function(key, cb) {
        return module.exports.client.hdel(env, key, cb);
      }
    };
  };

}).call(this);
<commit_msg>grunted<commit_after>(function() {
  var cached_client, config_from_redis, resolve, rx;

  rx = /\$\{([^\}]+)\}/;

  resolve = function(config, v) {
    var match;
    if (v == null) {
      return null;
    }
    while ((match = rx.exec(v)) != null) {
      v = v.replace(match[0], resolve(config, config[match[1]]));
    }
    return v;
  };

  config_from_redis = function(app) {
    return function(done) {
      return module.exports.environment(app.environment).get(true, function(err, config) {
        var k, v;
        if (err != null) {
          return done(err);
        }
        for (k in config) {
          v = config[k];
          process.env[k] = resolve(config, v);
        }
        return done();
      });
    };
  };

  module.exports = function(app) {
    if (process.env.REDIS_ENV_VAR_URL == null) {
      throw new Error('To use redis-env-var-layer you must define the REDIS_ENV_VAR_URL environment variable.');
    }
    return app.sequence('init').insert('config-from-redis', config_from_redis(app), {
      before: 'config'
    });
  };

  cached_client = null;

  module.exports.__defineGetter__('client', function() {
    return cached_client || (cached_client = require('redis-builder')({
      url: process.env.REDIS_ENV_VAR_URL
    }));
  });

  module.exports.environments = {
    list: function(cb) {
      return module.exports.client.keys('*', cb);
    }
  };

  module.exports.environment = function(env) {
    return {
      get: function(key, should_resolve, cb) {
        if (typeof key === 'function') {
          return module.exports.client.hgetall(env, key);
        } else if (typeof key === 'boolean' && typeof should_resolve === 'function') {
          if (key === false) {
            return module.exports.client.hgetall(env, should_resolve);
          }
          return module.exports.client.hgetall(env, function(err, config) {
            if (err != null) {
              return should_resolve(err);
            }
            return should_resolve(null, Object.keys(config).reduce(function(o, k) {
              o[k] = resolve(config, config[k]);
              return o;
            }, {}));
          });
        } else if (typeof key === 'string' && typeof should_resolve === 'function') {
          return module.exports.client.hget(env, key, should_resolve);
        } else if (typeof key === 'string' && typeof should_resolve === 'boolean' && typeof cb === 'function') {
          if (should_resolve === false) {
            return module.exports.client.hget(env, key, cb);
          }
          return this.get(true, function(err, config) {
            if (err != null) {
              return cb(err);
            }
            return cb(null, config[key]);
          });
        }
      },
      set: function(k, v, cb) {
        if (typeof k === 'object' && typeof v === 'function' && (cb == null)) {
          return module.exports.client.hmset(env, k, v);
        } else if (typeof k === 'string' && (v != null) && typeof cb === 'function') {
          return module.exports.client.hset(env, k, v, cb);
        }
      },
      remove: function(key, cb) {
        return module.exports.client.hdel(env, key, cb);
      }
    };
  };

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


<commit_before>import React, {useRef} from "react";

const quotes = [
  "Not all who wander are lost",
  "If you don’t know where your destination is, you don’t know how long you have to wander",
  "Its origin and purpose are still a total mystery...",
  "For everything, there is a first time",
  "I like to believe that there are always possibilities",
  "Sometimes a feeling is all we humans have to go on.",
  "Failure is the mark of a life well lived. In turn, the only way to live without failure is to be of no use to anyone.",
  "History has its eyes on you.",
  "We take one step at a time. In doing so we reach toward the unknown.",
  "Where does this lead us? Where do we go?",
  "If you listen carefully, the silence is beautiful.",
  "The man who has no imagination has no wings.",
  "Life before death. Strength before weakness. Journey before destination.",
  "We are the ones we have been waiting for.",
  "I am burdened with glorious purpose.",
  "While you live, shine; have no grief at all. Life exists only for a short while and Time demands his due.",
  "The hardest choices require the strongest wills.",
  "Like a snowflake in a blizzard...",
  "Fun isn’t something one considers when balancing the universe. But this… does put a smile on my face.",
  "The work is done, as it always will be. I am inevitable.",
  "It's better to look good than to feel good.",
  "Some of us have to work for a living!",
  "Educating minds with the discipline of wonder.",
  "While others sleep, you dream.",
  "Time is an illusion. Lunchtime doubly so.",
  "I may not have gone where I intended to go, but I think I have ended up where I needed to be.",
  "Don't Panic.",
  "I'd far rather be happy than right any day.",
  "For a moment, nothing happened. Then, after a second or so, nothing continued to happen.",
  "Reality is frequently inaccurate.",
  "It is a mistake to think you can solve any major problems just with potatoes.",
  "Dangerous But Not Unbearably So",
  "So much for subtlety",
  "Just as likely to still be an intergalactic jellyfish.",
  "And the world will fall with ignorance...",
  "You don't know I'm not crazy.",
  "If you cannot do great things, do small things in a great way.",
  "This is the way. I have spoken.",
  "Suffering exists. It has a cause. It has an end. And there is a noble path to ending it.",
  "We are what they grow beyond. That is the true burden of all masters.",
  "We grow small trying to be great.",
  "The whole point of getting things done is knowing what to leave undone.",
  "The days are long, but the years are short.",
  "I preferred to be called Nobody.",
  "He who least needs tomorrow, will most gladly greet tomorrow",
  /* Banksy */
  "They say you die twice; Once when you stop breathing and again when someone says your name for the last time.",
  "There's nothing more dangerous than someone who wants to make the world a better place.",
  "There are three kinds of people in this world: those who like you, those who hate you, and those who don't care about you.",
  "I need someone to protect me from all the measures they take in order to protect me.",
  "If you get tired, learn to rest, not to quit.",
  "Be positive, patient and persistent.",
  "This revolution is for display purposes only.",
  /* Back to regularly scheduled programming */
  "Nobody knows what their story is until the end.",
  "Love isn't a triangle. It's a five dimensional blob.",
  "This spaceship doesn't come with an insurance plan.",
  "There is some good news. There’s some cake left!",
  "In case you were wondering, I am, by definition, the best version of myself.",
  "I'm not crazy, I'm just colorful.",
  "What we do in life, echoes in eternity.",
  "Institutions have a future … but people have no future. People have only hope.",
  "Destroying an empire to win a war is no victory. And ending a battle to save an empire is no defeat.",
  "Great people do not seek power; they have power thrust upon them.",
  "I am not afraid. I will not hide my face behind stone and mortar. I will stand before the wind and make it respect me.",
  "What are the tools you use to create memories?",
  "The one and only, the original, accept-no-substitute.",
  "The monkey's the only cookie animal that gets to wear clothes. You know that?",
  'Like is the hippo goin\', "Hey man. Where are my pants? I have my hippo dignity."',
  'The monkey\'s just, "I mock you with my monkey pants!"',
  "And then there's a big coup in the zoo.",
  "Man can't turn his back on what he came from. Besides, black is slimming.",
  "It's not a joke; I'm a legit snack!",
  "Words are the threads that weave the tapestries of life.",
  "Salutations of the seasons be upon you.",
  "Little victories, my friends. Little victories.",
  "It is what we can’t see that fuels our imagination.",
  "This is Art holding a Mirror up to Life. That’s why everything is exactly the wrong way around.",
  "Listen to the quiet.",
  "Don't try to be a great man, just be a man. And let history make its own judgments.",
];

const QuoteOfTheDay = () => {
  const quote = useRef(quotes[Math.floor(Math.random() * quotes.length)]);
  return (

      {quote.current}

  );
};

export default QuoteOfTheDay;
<commit_msg>Moar quotes<commit_after>import React, {useRef} from "react";

const quotes = [
  "Not all who wander are lost",
  "If you don’t know where your destination is, you don’t know how long you have to wander",
  "Its origin and purpose are still a total mystery...",
  "For everything, there is a first time",
  "I like to believe that there are always possibilities",
  "Sometimes a feeling is all we humans have to go on.",
  "Failure is the mark of a life well lived. In turn, the only way to live without failure is to be of no use to anyone.",
  "History has its eyes on you.",
  "We take one step at a time. In doing so we reach toward the unknown.",
  "Where does this lead us? Where do we go?",
  "If you listen carefully, the silence is beautiful.",
  "The man who has no imagination has no wings.",
  "Life before death. Strength before weakness. Journey before destination.",
  "We are the ones we have been waiting for.",
  "I am burdened with glorious purpose.",
  "While you live, shine; have no grief at all. Life exists only for a short while and Time demands his due.",
  "The hardest choices require the strongest wills.",
  "Like a snowflake in a blizzard...",
  "Fun isn’t something one considers when balancing the universe. But this… does put a smile on my face.",
  "The work is done, as it always will be. I am inevitable.",
  "It's better to look good than to feel good.",
  "Some of us have to work for a living!",
  "Educating minds with the discipline of wonder.",
  "While others sleep, you dream.",
  "Time is an illusion. Lunchtime doubly so.",
  "I may not have gone where I intended to go, but I think I have ended up where I needed to be.",
  "Don't Panic.",
  "I'd far rather be happy than right any day.",
  "For a moment, nothing happened. Then, after a second or so, nothing continued to happen.",
  "Reality is frequently inaccurate.",
  "It is a mistake to think you can solve any major problems just with potatoes.",
  "Dangerous But Not Unbearably So",
  "So much for subtlety",
  "Just as likely to still be an intergalactic jellyfish.",
  "And the world will fall with ignorance...",
  "You don't know I'm not crazy.",
  "If you cannot do great things, do small things in a great way.",
  "This is the way. I have spoken.",
  "Suffering exists. It has a cause. It has an end. And there is a noble path to ending it.",
  "We are what they grow beyond. That is the true burden of all masters.",
  "We grow small trying to be great.",
  "The whole point of getting things done is knowing what to leave undone.",
  "The days are long, but the years are short.",
  "I preferred to be called Nobody.",
  "He who least needs tomorrow, will most gladly greet tomorrow",
  /* Banksy */
  "They say you die twice; Once when you stop breathing and again when someone says your name for the last time.",
  "There's nothing more dangerous than someone who wants to make the world a better place.",
  "There are three kinds of people in this world: those who like you, those who hate you, and those who don't care about you.",
  "I need someone to protect me from all the measures they take in order to protect me.",
  "If you get tired, learn to rest, not to quit.",
  "Be positive, patient and persistent.",
  "This revolution is for display purposes only.",
  /* Back to regularly scheduled programming */
  "Nobody knows what their story is until the end.",
  "Love isn't a triangle. It's a five dimensional blob.",
  "This spaceship doesn't come with an insurance plan.",
  "There is some good news. There’s some cake left!",
  "In case you were wondering, I am, by definition, the best version of myself.",
  "I'm not crazy, I'm just colorful.",
  "What we do in life, echoes in eternity.",
  "Institutions have a future … but people have no future. People have only hope.",
  "Destroying an empire to win a war is no victory. And ending a battle to save an empire is no defeat.",
  "Great people do not seek power; they have power thrust upon them.",
  "I am not afraid. I will not hide my face behind stone and mortar. I will stand before the wind and make it respect me.",
  "What are the tools you use to create memories?",
  "The one and only, the original, accept-no-substitute.",
  "The monkey's the only cookie animal that gets to wear clothes. You know that?",
  'Like is the hippo goin\', "Hey man. Where are my pants? I have my hippo dignity."',
  'The monkey\'s just, "I mock you with my monkey pants!"',
  "And then there's a big coup in the zoo.",
  "Man can't turn his back on what he came from. Besides, black is slimming.",
  "It's not a joke; I'm a legit snack!",
  "Words are the threads that weave the tapestries of life.",
  "Salutations of the seasons be upon you.",
  "Little victories, my friends. Little victories.",
  "It is what we can’t see that fuels our imagination.",
  "This is Art holding a Mirror up to Life. That’s why everything is exactly the wrong way around.",
  "Listen to the quiet.",
  "Don't try to be a great man, just be a man. And let history make its own judgments.",
  // Horrible Goose
  "Your garden? I make it terrible! I make a puzzle of your garden!",
  "Here I come again!",
  "You cannot anticipate me because your brain is so big and weighty and far from the ground, but my brain is aerodynamic and small and ground-sure and I have all I need in my wicked goose-body, and also I have your radio.",
  "I put my honk in a jar so there is more honk!",
  // AI Generated Spaceship Names
  "Still Wrong, After All These Years",
  "I'll just be over here",
  "I do the best I can",
  "Would you like to know more?",
  "I did it for Science!",
  "Can't Win 'Em All",
  "Extreme Problems call for Extreme Solutions",
  "An attempt at perspective",
];

const QuoteOfTheDay = () => {
  const quote = useRef(quotes[Math.floor(Math.random() * quotes.length)]);
  return (

      {quote.current}

  );
};

export default QuoteOfTheDay;
<|endoftext|>


<commit_before>define([
	"dojo/_base/declare", "dojo/_base/lang",
	"dojo/topic",
	"./GridContainer", "./BlastResultGrid"
], function(declare, lang,
			Topic,
			GridContainer, BlastResultGrid){

	return declare([GridContainer], {
		gridCtor: BlastResultGrid,
		containerType: "",
		enableFilterPanel: false,
		visible: true,
		store: null,

		buildQuery: function(){
		},
		_setQueryAttr: function(q){
		},

		_setStoreAttr: function(store){
			if(this.grid){
				this.grid.store = store;
			}
			this._set('store', store);
		},

		onSetState: function(attr, oldState, state){
			if(!state){
				return;
			}

			if(this.grid){
				this.grid.set('state', state);
			}
		},
		selectionActions: GridContainer.prototype.selectionActions.concat([
			[
				"GenomeBrowser",
				"fa icon-genome-browser fa-2x",
				{
					label: "GBrws",
					multiple: false,
					validTypes: ["*"],
					validContainerTypes: ["sequence_data"],
					tooltip: "View in Genome Browser"
				},
				function(selection){

					var target = selection[0];
					var hit_from = target.detail.hsps[0].hit_from;
					var hit_to = target.detail.hsps[0].hit_to;

					var hash = lang.replace("#view_tab=browser&loc={0}:{1}..{2}&highlight={0}:{3}..{4}&tracks=refseqs,PATRICGenes,RefSeqGenes", [target.accession, Math.min(hit_from, hit_from - 200), Math.max(hit_to, hit_to + 200), hit_from, hit_to]);

					Topic.publish("/navigate", {
						href: "/view/Genome/" + target.genome_id + hash,
						target: "blank"
					});
				},
				false
			]
		])
	});
});<commit_msg>rename to GBrwr to Browser<commit_after>define([
	"dojo/_base/declare", "dojo/_base/lang",
	"dojo/topic",
	"./GridContainer", "./BlastResultGrid"
], function(declare, lang,
			Topic,
			GridContainer, BlastResultGrid){

	return declare([GridContainer], {
		gridCtor: BlastResultGrid,
		containerType: "",
		enableFilterPanel: false,
		visible: true,
		store: null,

		buildQuery: function(){
		},
		_setQueryAttr: function(q){
		},

		_setStoreAttr: function(store){
			if(this.grid){
				this.grid.store = store;
			}
			this._set('store', store);
		},

		onSetState: function(attr, oldState, state){
			if(!state){
				return;
			}

			if(this.grid){
				this.grid.set('state', state);
			}
		},
		selectionActions: GridContainer.prototype.selectionActions.concat([
			[
				"GenomeBrowser",
				"fa icon-genome-browser fa-2x",
				{
					label: "Browser",
					multiple: false,
					validTypes: ["*"],
					validContainerTypes: ["sequence_data"],
					tooltip: "View in Genome Browser"
				},
				function(selection){

					var target = selection[0];
					var hit_from = target.detail.hsps[0].hit_from;
					var hit_to = target.detail.hsps[0].hit_to;

					var hash = lang.replace("#view_tab=browser&loc={0}:{1}..{2}&highlight={0}:{3}..{4}&tracks=refseqs,PATRICGenes,RefSeqGenes", [target.accession, Math.min(hit_from, hit_from - 200), Math.max(hit_to, hit_to + 200), hit_from, hit_to]);

					Topic.publish("/navigate", {
						href: "/view/Genome/" + target.genome_id + hash,
						target: "blank"
					});
				},
				false
			]
		])
	});
});<|endoftext|>


<commit_before>// $Revision$

Ensembl.Panel.FuncgenMatrix = Ensembl.Panel.ModalContent.extend({
  constructor: function (id, params) {
    this.base(id, params);

    Ensembl.EventManager.register('mouseUp',             this, this.dragStop);
    Ensembl.EventManager.register('updateConfiguration', this, this.updateConfiguration);
  },

  init: function () {
    var panel = this;

    this.base();

    this.startCell   = [];
    this.dragCell    = [];
    this.imageConfig = {};
    this.viewConfig  = {};

    this.elLk.table = $('table.funcgen_matrix', this.el);

    var colClasses = $.map(this.elLk.table[0].rows[0].cells, function (el) { return el.className; });
    var linkData   = $.map(this.params.links, function (link) { return 'a.' + link; }).join(', ');

    this.elLk.noResults  = $('.no_results',           this.el);
    this.elLk.headers    = $('thead tr:first th',     this.elLk.table);
    this.elLk.renderers  = $('thead tr.renderers th', this.elLk.table);
    this.elLk.rows       = $('tbody tr',              this.elLk.table);
    this.elLk.trackNames = $('.track_name',           this.elLk.renderers).each(function () { panel.imageConfig[this.name] = { renderer: this.value }; });
    this.elLk.options    = $('.option',               this.elLk.rows).each(function () {
      this.configCode  = 'opt_cft_' + this.title; // configCode is used to set the correct values for the ViewConfig
      this.searchTerms = $.trim(this.parentNode.className + ' ' + colClasses[$(this).index()]).toLowerCase(); // Do this here so we don't have to look up the header row for every cell
      panel.viewConfig[this.configCode] = $(this).hasClass('on') ? 'on' : 'off';
    }).bind('click', function () {
      panel.resetSelectAll($(this).toggleClass('on'));
    });

    $('.help', this.el).bind('click', function () {
      $(this).toggleClass('open').attr('title', function (i, title) {
        return title === 'Hide information' ? 'Click for more information' : 'Hide information';
      }).siblings('.desc').width($(this).parent().width() - 25).toggle();
    });

    $('select.filter', this.el).bind('change', function () {
      panel.elLk.rows.removeClass('hidden');

      if (this.value) {
        panel.elLk.rows.not('.' + this.value).addClass('hidden');
      }

      panel.elLk.noResults[panel.elLk.rows.filter(function () { return this.style.display !== 'none' && this.className.indexOf('hidden') === -1; }).length ? 'hide' : 'show']();
    });

    $('input.filter', this.el).bind({
      keyup: function () {
        var value = this.value;

        if (value && value.length < 2) {
          this.lastQuery = value;
        }

        if (value !== this.lastQuery) {
          if (this.searchTimer) {
            clearTimeout(this.searchTimer);
          }

          this.searchTimer = setTimeout(function () {
            panel.filter(value);
          }, 250);
        }
      },
      focus: function () {
        this.value = '';
        this.style.color = '#000';
      },
      blur: function () {
        if (!this.value) {
          panel.filter();
          this.value = 'Enter cell or evidence types';
          this.style.color = '#999';
        }
      }
    });

    if (!$('body').hasClass('ie')) { // IE 8 and below are too slow
      this.elLk.table.bind('mousedown', function (e) {
        // only for left clicks, create a highlight overlay to show which cells are being dragged over
        if ((!e.which || e.which === 1) && (e.target.nodeName === 'TD' || e.target.nodeName === 'P')) {
          panel.dragStart(e);
        }

        return false;
      });
    }

    // Display a select all popup for columns
    this.elLk.headers.not('.disabled').hover(function () {
      if (panel.mousemove) {
        return;
      }

      panel.selectAllCol($(this).children('div').show());
    }, function () {
      $(this).children('div').hide();
    }).find('.select_all_column input').bind('click', function () {
      var cls   = this.className;
      var cells = panel.elLk.rows.children('.' + this.name);

      switch (cls) {
        case ''     : break;
        case 'none' : cells.removeClass('on'); break;
        case 'all'  : cells.addClass('on');    break;
        default     : cells.filter('.' + cls).addClass('on').end().not('.' + cls).removeClass('on');
      }

      panel.resetSelectAll(cells);

      cells = null;
    });

    // Display a select all popup for rows
    $('th', this.elLk.rows).hover(function () {
      if (panel.mousemove) {
        return;
      }

      var popup = $(this).children().show();

      if (!popup.data('selectAll')) {
        popup.children('input').prop('checked', panel.allOnRow(this));
        popup.data('selectAll', true);
      }

      popup = null;
    }, function () {
      $(this).children().hide();
    }).children('.select_all_row').bind('click', function () {
      var input   = $('input', this);
      var checked = panel.allOnRow(this.parentNode);

      panel.resetSelectAll($(this).parent().siblings('.option')[checked ? 'removeClass' : 'addClass']('on'));

      input.prop('checked', !checked);
      input = null;
    });

    this.elLk.renderers.filter('.select_all').find('.popup_menu li').bind('click', function () {
      $(this).parents('.popup_menu').hide().parent().siblings().find('.popup_menu li.' + this.className).trigger('click');
      return false;
    });

    this.elLk.renderers.not('.select_all').data('links', linkData);

    // Fix z-index for popups in IE6 and 7
    if ($('body').hasClass('ie67')) {
      this.elLk.headers.css('zIndex',   function (i) { return 200 - i; });
      this.elLk.renderers.css('zIndex', function (i) { return 100 - i; });
    }
  },

  allOnRow: function (el) {
    var tds  = $(el).siblings(':not(.disabled)');
    var rtn  = tds.length === tds.filter('.on').length;
    tds = el = null;
    return rtn;
  },

  selectAllCol: function (el) {
    if (!el.length || el.data('selectAll')) {
      return;
    }

    var radio = el.find('input');
    var tds   = this.elLk.rows.children('.' + radio[0].name);
    var on    = tds.filter('.on');
    var checked, i, cls, filtered;

    if (tds.length === tds.filter('.default').length) {
      checked = '.default'; // Prioritize the Default option
    } else if (!on.length) {
      checked = '.none';
    } else if (tds.length === on.length) {
      checked = '.all';
    }

    if (checked) {
      radio.filter(checked).prop('checked', true);
    } else {
      checked = radio.filter(':checked');
      radio   = radio.not('.all, .none');
      i       = radio.length;

      while (i--) {
        cls      = radio[i].className;
        filtered = tds.filter('.' + cls);

        if (filtered.length === on.length && filtered.length === on.filter('.' + cls).length) {
          radio[i].checked = 'checked';
          break;
        }
      }

      if (i === -1) {
        checked.prop('checked', false); // Deselect all options if nothing matches
      }

      checked = null;
    }

    el.data('selectAll', true);

    el = radio = tds = null;
  },

  // Sets the selectAll state of relevant column and row headers to false,
  // so they will be recalculated the next time the th mouseover is triggered.
  resetSelectAll: function (cells) {
    var reset = { row: {}, col: {} };
    var i, className, renderer, off, on;

    cells.each(function () {
      reset.row[$(this).parent().index()] = 1;
      reset.col[$(this).index()] = 1;
    });

    for (i in reset.row) {
      $('th .select_all_row', this.elLk.rows[i]).data('selectAll', false);
    }

    for (i in reset.col) {
      className = $('.select_all_column', this.elLk.headers[i]).data('selectAll', false).parent().attr('class');
      renderer  = this.elLk.renderers.filter('.' + className).find('.track_name');
      off       = renderer.val() === 'off';
      on        = !!this.elLk.rows.children('.' + className + '.on').length;

      if (off === on) {
        renderer.siblings('.popup_menu').children(':eq(' + (on ? 1 : 0) + ')').trigger('click');
      }
    }

    cells = null;
  },

  // Called by triggerSpecific from the parent Configurator panel.
  // Does not cause an AJAX request, just returns the diff data.
  updateConfiguration: function () {
    var panel  = this;
    var config = { viewConfig: {}, imageConfig: {} };
    var diff   = false;
    var on;

    this.elLk.options.each(function () {
      on = $(this).hasClass('on') ? 'on' : 'off';

      if (panel.viewConfig[this.configCode] !== on) {
        config.viewConfig[this.configCode] = on;
        diff = true;
      }
    });

    this.elLk.trackNames.each(function () {
      if (panel.imageConfig[this.name].renderer !== this.value) {
        config.imageConfig[this.name] = { renderer: this.value };
        diff = true;
      }
    });

    if (diff) {
      $.extend(true, this.viewConfig,  config.viewConfig);
      $.extend(true, this.imageConfig, config.imageConfig);
      return config;
    }
  },

  dragStart: function (e) {
    var panel  = this;
    var target = $(e.target);

    // Cache the mousemove event for easy unbinding
    this.mousemove = function (e2) {
      panel.drag(e2);
      return false;
    };

    this.startCell = [ target.index(), target.parent().index() + 2 ]; // cell and row coordinates
    this.elLk.table.bind('mousemove', this.mousemove);

    target = null;
  },

  dragStop: function () {
    if (!this.mousemove) {
      return;
    }

    this.resetSelectAll($('.highlight', this.elLk.table).removeClass('highlight').not('.disabled').toggleClass('on'));
    this.elLk.table.unbind('mousemove', this.mousemove);
    this.mousemove = false;
  },

  drag: function (e) {
    var target = e.target.nodeName === 'P' ? $(e.target.parentNode) : $(e.target);

    if (target[0].nodeName !== 'TD') {
      target = null;
      return;
    }

    var cell = [ target.index(), target.parent().index() + 2 ];

    if (cell[0] === this.dragCell[0] && cell[1] === this.dragCell[1]) {
      return; // Target is unchanged
    }

    var x     = [ cell[0], this.startCell[0] ].sort(function (a, b) { return a - b; });
    var y     = [ cell[1], this.startCell[1] ].sort(function (a, b) { return a - b; });
    var cells = [];
    var i, j;

    for (i = y[0]; i <= y[1]; i++) {
      if (this.elLk.table[0].rows[i].style.display !== 'none' && this.elLk.table[0].rows[i].className !== 'gap') {
        for (j = x[0]; j <= x[1]; j++) {
          cells.push(this.elLk.table[0].rows[i].cells[j]); // Get the cells in the rows and columns between the current target and the start cell
        }
      }
    }

    $('.highlight', this.elLk.table).not(cells).removeClass('highlight');
    $(cells).not('.highlight').addClass('highlight');

    this.dragCell = cell;

    target = cells = null;
  },

  filter: function (value) {
    var cells      = [];
    var rows       = [];
    var rowMatches = {};
    var i;

    if (value) {
      value = $.trim(value.toLowerCase()).split(' '); // remove extra whitespace

      this.elLk.options.each(function () {
        for (i in value) {
          if (this.searchTerms.indexOf(value[i]) !== -1) {
            cells.push(this);
            rowMatches[$(this.parentNode).index()] = true;
            break;
          }
        }
      });

      if (cells.length) {
        for (i in rowMatches) {
          rows.push(this.elLk.rows[i]);
        }

        this.elLk.rows.not(rows).hide();
        this.elLk.options.filter('.filter').removeClass('filter');
        $(rows).show();
        $(cells).addClass('filter');
      } else {
        this.elLk.rows.hide();
      }
    } else {
      this.elLk.rows.show();
      this.elLk.options.filter('.filter').removeClass('filter');
    }

    this.elLk.noResults[this.elLk.rows.filter(function () { return this.style.display !== 'none' && this.className.indexOf('hidden') === -1; }).length ? 'hide' : 'show']();
  }
});
<commit_msg>fix bug where updateConfiguration was being called twice if configuration was reset, with the second occurence nuking view config changes<commit_after>// $Revision$

Ensembl.Panel.FuncgenMatrix = Ensembl.Panel.ModalContent.extend({
  constructor: function (id, params) {
    this.base(id, params);

    Ensembl.EventManager.register('mouseUp',             this, this.dragStop);
    Ensembl.EventManager.register('updateConfiguration', this, this.updateConfiguration);
  },

  init: function () {
    var panel = this;

    this.base();

    this.startCell   = [];
    this.dragCell    = [];
    this.imageConfig = {};
    this.viewConfig  = {};

    this.elLk.table = $('table.funcgen_matrix', this.el);

    var colClasses = $.map(this.elLk.table[0].rows[0].cells, function (el) { return el.className; });
    var linkData   = $.map(this.params.links, function (link) { return 'a.' + link; }).join(', ');

    this.elLk.noResults  = $('.no_results',           this.el);
    this.elLk.headers    = $('thead tr:first th',     this.elLk.table);
    this.elLk.renderers  = $('thead tr.renderers th', this.elLk.table);
    this.elLk.rows       = $('tbody tr',              this.elLk.table);
    this.elLk.trackNames = $('.track_name',           this.elLk.renderers).each(function () { panel.imageConfig[this.name] = { renderer: this.value }; });
    this.elLk.options    = $('.option',               this.elLk.rows).each(function () {
      this.configCode  = 'opt_cft_' + this.title; // configCode is used to set the correct values for the ViewConfig
      this.searchTerms = $.trim(this.parentNode.className + ' ' + colClasses[$(this).index()]).toLowerCase(); // Do this here so we don't have to look up the header row for every cell
      panel.viewConfig[this.configCode] = $(this).hasClass('on') ? 'on' : 'off';
    }).bind('click', function () {
      panel.resetSelectAll($(this).toggleClass('on'));
    });

    $('.help', this.el).bind('click', function () {
      $(this).toggleClass('open').attr('title', function (i, title) {
        return title === 'Hide information' ? 'Click for more information' : 'Hide information';
      }).siblings('.desc').width($(this).parent().width() - 25).toggle();
    });

    $('select.filter', this.el).bind('change', function () {
      panel.elLk.rows.removeClass('hidden');

      if (this.value) {
        panel.elLk.rows.not('.' + this.value).addClass('hidden');
      }

      panel.elLk.noResults[panel.elLk.rows.filter(function () { return this.style.display !== 'none' && this.className.indexOf('hidden') === -1; }).length ? 'hide' : 'show']();
    });

    $('input.filter', this.el).bind({
      keyup: function () {
        var value = this.value;

        if (value && value.length < 2) {
          this.lastQuery = value;
        }

        if (value !== this.lastQuery) {
          if (this.searchTimer) {
            clearTimeout(this.searchTimer);
          }

          this.searchTimer = setTimeout(function () {
            panel.filter(value);
          }, 250);
        }
      },
      focus: function () {
        this.value = '';
        this.style.color = '#000';
      },
      blur: function () {
        if (!this.value) {
          panel.filter();
          this.value = 'Enter cell or evidence types';
          this.style.color = '#999';
        }
      }
    });

    if (!$('body').hasClass('ie')) { // IE 8 and below are too slow
      this.elLk.table.bind('mousedown', function (e) {
        // only for left clicks, create a highlight overlay to show which cells are being dragged over
        if ((!e.which || e.which === 1) && (e.target.nodeName === 'TD' || e.target.nodeName === 'P')) {
          panel.dragStart(e);
        }

        return false;
      });
    }

    // Display a select all popup for columns
    this.elLk.headers.not('.disabled').hover(function () {
      if (panel.mousemove) {
        return;
      }

      panel.selectAllCol($(this).children('div').show());
    }, function () {
      $(this).children('div').hide();
    }).find('.select_all_column input').bind('click', function () {
      var cls   = this.className;
      var cells = panel.elLk.rows.children('.' + this.name);

      switch (cls) {
        case ''     : break;
        case 'none' : cells.removeClass('on'); break;
        case 'all'  : cells.addClass('on');    break;
        default     : cells.filter('.' + cls).addClass('on').end().not('.' + cls).removeClass('on');
      }

      panel.resetSelectAll(cells);

      cells = null;
    });

    // Display a select all popup for rows
    $('th', this.elLk.rows).hover(function () {
      if (panel.mousemove) {
        return;
      }

      var popup = $(this).children().show();

      if (!popup.data('selectAll')) {
        popup.children('input').prop('checked', panel.allOnRow(this));
        popup.data('selectAll', true);
      }

      popup = null;
    }, function () {
      $(this).children().hide();
    }).children('.select_all_row').bind('click', function () {
      var input   = $('input', this);
      var checked = panel.allOnRow(this.parentNode);

      panel.resetSelectAll($(this).parent().siblings('.option')[checked ? 'removeClass' : 'addClass']('on'));

      input.prop('checked', !checked);
      input = null;
    });

    this.elLk.renderers.filter('.select_all').find('.popup_menu li').bind('click', function () {
      $(this).parents('.popup_menu').hide().parent().siblings().find('.popup_menu li.' + this.className).trigger('click');
      return false;
    });

    this.elLk.renderers.not('.select_all').data('links', linkData);

    // Fix z-index for popups in IE6 and 7
    if ($('body').hasClass('ie67')) {
      this.elLk.headers.css('zIndex',   function (i) { return 200 - i; });
      this.elLk.renderers.css('zIndex', function (i) { return 100 - i; });
    }
  },

  allOnRow: function (el) {
    var tds  = $(el).siblings(':not(.disabled)');
    var rtn  = tds.length === tds.filter('.on').length;
    tds = el = null;
    return rtn;
  },

  selectAllCol: function (el) {
    if (!el.length || el.data('selectAll')) {
      return;
    }

    var radio = el.find('input');
    var tds   = this.elLk.rows.children('.' + radio[0].name);
    var on    = tds.filter('.on');
    var checked, i, cls, filtered;

    if (tds.length === tds.filter('.default').length) {
      checked = '.default'; // Prioritize the Default option
    } else if (!on.length) {
      checked = '.none';
    } else if (tds.length === on.length) {
      checked = '.all';
    }

    if (checked) {
      radio.filter(checked).prop('checked', true);
    } else {
      checked = radio.filter(':checked');
      radio   = radio.not('.all, .none');
      i       = radio.length;

      while (i--) {
        cls      = radio[i].className;
        filtered = tds.filter('.' + cls);

        if (filtered.length === on.length && filtered.length === on.filter('.' + cls).length) {
          radio[i].checked = 'checked';
          break;
        }
      }

      if (i === -1) {
        checked.prop('checked', false); // Deselect all options if nothing matches
      }

      checked = null;
    }

    el.data('selectAll', true);

    el = radio = tds = null;
  },

  // Sets the selectAll state of relevant column and row headers to false,
  // so they will be recalculated the next time the th mouseover is triggered.
  resetSelectAll: function (cells) {
    var reset = { row: {}, col: {} };
    var i, className, renderer, off, on;

    cells.each(function () {
      reset.row[$(this).parent().index()] = 1;
      reset.col[$(this).index()] = 1;
    });

    for (i in reset.row) {
      $('th .select_all_row', this.elLk.rows[i]).data('selectAll', false);
    }

    for (i in reset.col) {
      className = $('.select_all_column', this.elLk.headers[i]).data('selectAll', false).parent().attr('class');
      renderer  = this.elLk.renderers.filter('.' + className).find('.track_name');
      off       = renderer.val() === 'off';
      on        = !!this.elLk.rows.children('.' + className + '.on').length;

      if (off === on) {
        renderer.siblings('.popup_menu').children(':eq(' + (on ? 1 : 0) + ')').trigger('click');
      }
    }

    cells = null;
  },

  // Called by triggerSpecific from the parent Configurator panel.
  // Does not cause an AJAX request, just returns the diff data.
  updateConfiguration: function (subPanel) {
    if (!subPanel) {
      return;
    }

    var panel  = this;
    var config = { viewConfig: {}, imageConfig: {} };
    var diff   = false;
    var on;

    this.elLk.options.each(function () {
      on = $(this).hasClass('on') ? 'on' : 'off';

      if (panel.viewConfig[this.configCode] !== on) {
        config.viewConfig[this.configCode] = on;
        diff = true;
      }
    });

    this.elLk.trackNames.each(function () {
      if (panel.imageConfig[this.name].renderer !== this.value) {
        config.imageConfig[this.name] = { renderer: this.value };
        diff = true;
      }
    });

    if (diff) {
      $.extend(true, this.viewConfig,  config.viewConfig);
      $.extend(true, this.imageConfig, config.imageConfig);
      return config;
    }
  },

  dragStart: function (e) {
    var panel  = this;
    var target = $(e.target);

    // Cache the mousemove event for easy unbinding
    this.mousemove = function (e2) {
      panel.drag(e2);
      return false;
    };

    this.startCell = [ target.index(), target.parent().index() + 2 ]; // cell and row coordinates
    this.elLk.table.bind('mousemove', this.mousemove);

    target = null;
  },

  dragStop: function () {
    if (!this.mousemove) {
      return;
    }

    this.resetSelectAll($('.highlight', this.elLk.table).removeClass('highlight').not('.disabled').toggleClass('on'));
    this.elLk.table.unbind('mousemove', this.mousemove);
    this.mousemove = false;
  },

  drag: function (e) {
    var target = e.target.nodeName === 'P' ? $(e.target.parentNode) : $(e.target);

    if (target[0].nodeName !== 'TD') {
      target = null;
      return;
    }

    var cell = [ target.index(), target.parent().index() + 2 ];

    if (cell[0] === this.dragCell[0] && cell[1] === this.dragCell[1]) {
      return; // Target is unchanged
    }

    var x     = [ cell[0], this.startCell[0] ].sort(function (a, b) { return a - b; });
    var y     = [ cell[1], this.startCell[1] ].sort(function (a, b) { return a - b; });
    var cells = [];
    var i, j;

    for (i = y[0]; i <= y[1]; i++) {
      if (this.elLk.table[0].rows[i].style.display !== 'none' && this.elLk.table[0].rows[i].className !== 'gap') {
        for (j = x[0]; j <= x[1]; j++) {
          cells.push(this.elLk.table[0].rows[i].cells[j]); // Get the cells in the rows and columns between the current target and the start cell
        }
      }
    }

    $('.highlight', this.elLk.table).not(cells).removeClass('highlight');
    $(cells).not('.highlight').addClass('highlight');

    this.dragCell = cell;

    target = cells = null;
  },

  filter: function (value) {
    var cells      = [];
    var rows       = [];
    var rowMatches = {};
    var i;

    if (value) {
      value = $.trim(value.toLowerCase()).split(' '); // remove extra whitespace

      this.elLk.options.each(function () {
        for (i in value) {
          if (this.searchTerms.indexOf(value[i]) !== -1) {
            cells.push(this);
            rowMatches[$(this.parentNode).index()] = true;
            break;
          }
        }
      });

      if (cells.length) {
        for (i in rowMatches) {
          rows.push(this.elLk.rows[i]);
        }

        this.elLk.rows.not(rows).hide();
        this.elLk.options.filter('.filter').removeClass('filter');
        $(rows).show();
        $(cells).addClass('filter');
      } else {
        this.elLk.rows.hide();
      }
    } else {
      this.elLk.rows.show();
      this.elLk.options.filter('.filter').removeClass('filter');
    }

    this.elLk.noResults[this.elLk.rows.filter(function () { return this.style.display !== 'none' && this.className.indexOf('hidden') === -1; }).length ? 'hide' : 'show']();
  }
});
<|endoftext|>


<commit_before>var _bigdeal_opts = undefined;

var _bigdeal_template = '\
  \

\

\

\

\

\

\
          \
          <input type="text" class="form-control holder search suggest" do="add" placeholder="Search" style="font-size:1.6em;height:50px;border-bottom:1px solid #D82D34;">\

\
            \
            \

\

\

\

\

\

\

\
        \

\

\
          Download\

\

\

\

\

\

\
      Institution 	\
      Publisher 	\
      Collection 	\
      FTE 	\
      Carnegie 	\
      Year 	\
      USD Value 	\

\

\

\

\

\
      < previous results\

\

\
      back to top\

\

\
      next results >\

\

\

';

var bigdeal_build = function() {
  jQuery(document).ready(function() {
    var opts = _bigdeal_opts;
    var api = opts.api ? opts.api : 'https://dev.api.cottagelabs.com/service/bigdeal';

    $(opts.target).append(opts.template);
    $('body').on('click','.backtotop', function(e) {
      if (e) e.preventDefault();
      $('html,body').animate({ scrollTop: 0 }, 'fast');
    });
    $('body').on('click','.sorters', function(e) {
      if (e) e.preventDefault();
      var w = $(this).attr('href') !== '#' ? $(this).attr('href') : $(this).html().toLowerCase();
      var cs = $('.holder.sortfield').val();
      var icon = $(this).children('img').attr('src');
      var src = opts.static.replace('https:','').replace('http:','');
      src += icon.indexOf('red') === -1 ? (icon.indexOf('up') !== -1 ? 'up' : 'down') : (icon.indexOf('up') === -1 ? 'up' : 'down');
      $(this).children('img').attr('src',src + '_red_cropped.png');
      $(this).parent().siblings().children().children('img').each(function() {
        if ($(this).attr('src').indexOf('red') !== -1) $(this).attr('src',$(this).attr('src').replace('red_','grey_'));
      });
      if (cs === w) {
        $('.holder.sortdirection').val($('.holder.sortdirection').val() !== 'asc' ? 'asc' : 'desc').trigger('change');
      } else {
        $('.holder.sortdirection').val('asc');
        $('.holder.sortfield').val(w).trigger('change');
      }
    });

    var record = function(rec,idx) {
      var options = $.fn.holder.options;
      var fromclass='.from' + options.query.from;
      var rr = '';
      var iid = rec.institution.replace(/ /g,'_');
      if (rec.years) {
        rr += '

' + (rec.url ? '' + rec.institution + '' : rec.institution) + '
';
        rr += '
' + (rec.notes && rec.notes.toLowerCase().trim() !== 'not found' ? rec.notes : '') + '
';
        rr += '	' + rec.publisher + '	' + rec.collection + '	';
        rr += '' + rec.fte + '	' + rec.carnegiebasicclassification + '	' + rec.years + '	$' + rec.usdvalue + '
';
      }
      return rr;
    }

    var exporter = function(e) {
      var q = JSON.parse(JSON.stringify($('#holder').holder.options.query))
      q.size = $('#holder').holder.options.response.hits.total;
      $(this).attr('href', api + '.csv?source=' + encodeURIComponent(JSON.stringify(q)));
    }
    $('.exporter').bind('click',exporter);

    var _citv = undefined;
    var completes = function(event,th) {
      if (th.is(':checked')) {
        $('#holder').holder.options.defaultfilters = [{"query_string": {"query": "url:*"}}];
        setInterval(function() {
          if ($('a.holder:contains(\'url:*\')').length) {
            $('a.holder:contains(\'url:*\')').hide();
            clearInterval(_citv);
            _citv = undefined;
          }
        }, 100);
      } else {
        $('#holder').holder.options.defaultfilters = [];
        $('#holder').holder.options.remove(undefined, $('a.holder:contains(\'url:*\')'));
      }
      $('#holder').holder.options.execute();
    }

    var review = function(data) {
      $('.lowercontrols').show();
      var options = $('#holder').holder.options;
      if (data === undefined) data = options.response;
      var fromclass='.from' + options.query.from;
      if (options.paging) {
        if (!options.scroll) $('.' + options.class + '.result').not(fromclass).hide();
      } else {
        options.records = [];
        $('.' + options.class + '.result').remove();
      }
      var results = options.extract ? dotindex(data,options.extract) : data;
      for ( var r in results ) {
        var rec = results[r];
        if (rec.fields) rec = rec.fields;
        if (rec._source) rec = rec._source;
        for ( var f in rec ) { // is this loop worth doing by default?
          if ( rec[f] instanceof Array && rec[f].length === 1) rec[f] = rec[f][0];
          if ( rec[f] !== 0 && rec[f] !== false && !rec[f] ) rec[f] = "Not found";
        }
        options.records.push(rec);
        if (typeof options.record === 'function') {
          $('.' + options.class + '.results').append(options.record(rec,r));
        }
      }
    }

    $.fn.holder.display.sort.fields = ['institution.exact','publisher.exact','collection.exact','fte','carnegiebasicclassification.exact','years.exact','value'];
    $.fn.holder.display.sort.default = {'value': 'desc'};

    $('#holder').holder({
      completes: completes,
      review: review,
      url: api,
      datatype: 'JSON',
      pushstate: false,
      record: record,
      collapse: false,
      //sort: 'institution.exact',
      //sticky:true,
      display: ['filters','range','sort'],
      size: 100,
      facets: {
        institution: { terms: { field: "institution.exact", size: 1000, order: "term" } },
        publisher: { terms: { field: "publisher.exact", size: 1000, order: "term", exclude: [''] } },
        'Carnegie': { terms: { field: "carnegiebasicclassification.exact", size: 1000, order: "term" } },
        collection: { terms: { field: "collection.exact", size: 1000, order: "term" } }
      },
      ranges: {
        usdvalue: {
          name: 'USD Value',
          step: 100,
          min: 0,
          max: 10000000
        },
        years: {
          name: 'Years',
          step: 1,
          min: 2002,
          max: 2022
        },
        fte: {
          name: 'FTE',
          step: 10,
          min: 100,
          max: 100000
        }
      }
    });
  });
};

var _bigdeal_got = 0;
var bigdeal_get = function() {
  var headTag = document.getElementsByTagName("head")[0];
  var need = ['/holder/jquery.holder.js','/holder/display/filters.js','/holder/display/sort.js','/holder/display/range.js'];
  var jqTag = document.createElement('script');
  jqTag.type = 'text/javascript';
  jqTag.src = _bigdeal_opts.static + need[_bigdeal_got];
  if (_bigdeal_got === need.length-1) {
    jqTag.onload = bigdeal_build;
  } else {
    _bigdeal_got += 1;
    jqTag.onload = bigdeal_get;
  }
  headTag.appendChild(jqTag);
}

var bigdeal_setup = function(opts) {
  if (opts === undefined) opts = {}
  if (opts.api === undefined) opts.api = 'https://api.cottagelabs.com/service/bigdeal';
  //if (opts.site === undefined) opts.site = 'https://bigdeal.test.cottagelabs.com';
  if (opts.static === undefined) opts.static = 'https://openaccessbutton.org/static/bigdeal';
  if (opts.target === undefined) opts.target = '#bigdeal';
  if (opts.template === undefined) opts.template = _bigdeal_template;
  opts.template = opts.template.replace(/\{\{static\}\}/g,opts.static.replace('https:','').replace('http:',''));
  _bigdeal_opts = opts;

  if ($ === undefined) {
    var headTag = document.getElementsByTagName("head")[0];
    var jqTag = document.createElement('script');
    jqTag.type = 'text/javascript';
    jqTag.src = opts.static + '/jquery-1.10.2.min.js';
    jqTag.onload = bigdeal_get;
    headTag.appendChild(jqTag);
  } else {
     bigdeal_get();
  }
}
<commit_msg>bigdeal template fix<commit_after>var _bigdeal_opts = undefined;

var _bigdeal_template = '\
  \

\

\

\

\

\

\
          \
          <input type="text" class="form-control holder search suggest" do="add" placeholder="Search" style="font-size:1.6em;height:50px;border-bottom:1px solid #D82D34;">\

\
            \
            \

\

\

\

\

\

\

\
        \

\

\
          Download\

\

\

\

\

\

\
      Institution 	\
      Publisher 	\
      Collection 	\
      FTE 	\
      Carnegie 	\
      Year 	\
      USD Value 	\

\

\

\

\

\
      < previous results\

\

\
      back to top\

\

\
      next results >\

\

\

';

var bigdeal_build = function() {
  jQuery(document).ready(function() {
    var opts = _bigdeal_opts;
    var api = opts.api ? opts.api : 'https://dev.api.cottagelabs.com/service/bigdeal';

    $(opts.target).append(opts.template);
    $('body').on('click','.backtotop', function(e) {
      if (e) e.preventDefault();
      $('html,body').animate({ scrollTop: 0 }, 'fast');
    });
    $('body').on('click','.sorters', function(e) {
      if (e) e.preventDefault();
      var w = $(this).attr('href') !== '#' ? $(this).attr('href') : $(this).html().toLowerCase();
      var cs = $('.holder.sortfield').val();
      var icon = $(this).children('img').attr('src');
      var src = opts.static.replace('https:','').replace('http:','');
      src += icon.indexOf('red') === -1 ? (icon.indexOf('up') !== -1 ? 'up' : 'down') : (icon.indexOf('up') === -1 ? 'up' : 'down');
      $(this).children('img').attr('src',src + '_red_cropped.png');
      $(this).parent().siblings().children().children('img').each(function() {
        if ($(this).attr('src').indexOf('red') !== -1) $(this).attr('src',$(this).attr('src').replace('red_','grey_'));
      });
      if (cs === w) {
        $('.holder.sortdirection').val($('.holder.sortdirection').val() !== 'asc' ? 'asc' : 'desc').trigger('change');
      } else {
        $('.holder.sortdirection').val('asc');
        $('.holder.sortfield').val(w).trigger('change');
      }
    });

    var record = function(rec,idx) {
      var options = $.fn.holder.options;
      var fromclass='.from' + options.query.from;
      var rr = '';
      var iid = rec.institution.replace(/ /g,'_');
      if (rec.years) {
        rr += '

' + (rec.url ? '' + rec.institution + '' : rec.institution) + '
';
        rr += '
' + (rec.notes && rec.notes.toLowerCase().trim() !== 'not found' ? rec.notes : '') + '
';
        rr += '	' + rec.publisher + '	' + rec.collection + '	';
        rr += '' + rec.fte + '	' + rec.carnegiebasicclassification + '	' + rec.years + '	$' + rec.usdvalue + '
';
      }
      return rr;
    }

    var exporter = function(e) {
      var q = JSON.parse(JSON.stringify($('#holder').holder.options.query))
      q.size = $('#holder').holder.options.response.hits.total;
      $(this).attr('href', api + '.csv?source=' + encodeURIComponent(JSON.stringify(q)));
    }
    $('.exporter').bind('click',exporter);

    var _citv = undefined;
    var completes = function(event,th) {
      if (th.is(':checked')) {
        $('#holder').holder.options.defaultfilters = [{"query_string": {"query": "url:*"}}];
        setInterval(function() {
          if ($('a.holder:contains(\'url:*\')').length) {
            $('a.holder:contains(\'url:*\')').hide();
            clearInterval(_citv);
            _citv = undefined;
          }
        }, 100);
      } else {
        $('#holder').holder.options.defaultfilters = [];
        $('#holder').holder.options.remove(undefined, $('a.holder:contains(\'url:*\')'));
      }
      $('#holder').holder.options.execute();
    }

    var review = function(data) {
      $('.lowercontrols').show();
      var options = $('#holder').holder.options;
      if (data === undefined) data = options.response;
      var fromclass='.from' + options.query.from;
      if (options.paging) {
        if (!options.scroll) $('.' + options.class + '.result').not(fromclass).hide();
      } else {
        options.records = [];
        $('.' + options.class + '.result').remove();
      }
      var results = options.extract ? dotindex(data,options.extract) : data;
      for ( var r in results ) {
        var rec = results[r];
        if (rec.fields) rec = rec.fields;
        if (rec._source) rec = rec._source;
        for ( var f in rec ) { // is this loop worth doing by default?
          if ( rec[f] instanceof Array && rec[f].length === 1) rec[f] = rec[f][0];
          if ( rec[f] !== 0 && rec[f] !== false && !rec[f] ) rec[f] = "Not found";
        }
        options.records.push(rec);
        if (typeof options.record === 'function') {
          $('.' + options.class + '.results').append(options.record(rec,r));
        }
      }
    }

    $.fn.holder.display.sort.fields = ['institution.exact','publisher.exact','collection.exact','fte','carnegiebasicclassification.exact','years.exact','value'];
    $.fn.holder.display.sort.default = {'value': 'desc'};

    $('#holder').holder({
      completes: completes,
      review: review,
      url: api,
      datatype: 'JSON',
      pushstate: false,
      record: record,
      collapse: false,
      //sort: 'institution.exact',
      //sticky:true,
      display: ['filters','range','sort'],
      size: 100,
      facets: {
        institution: { terms: { field: "institution.exact", size: 1000, order: "term" } },
        publisher: { terms: { field: "publisher.exact", size: 1000, order: "term", exclude: [''] } },
        'Carnegie': { terms: { field: "carnegiebasicclassification.exact", size: 1000, order: "term" } },
        collection: { terms: { field: "collection.exact", size: 1000, order: "term" } }
      },
      ranges: {
        usdvalue: {
          name: 'USD Value',
          step: 100,
          min: 0,
          max: 10000000
        },
        years: {
          name: 'Years',
          step: 1,
          min: 2002,
          max: 2022
        },
        fte: {
          name: 'FTE',
          step: 10,
          min: 100,
          max: 100000
        }
      }
    });
  });
};

var _bigdeal_got = 0;
var bigdeal_get = function() {
  var headTag = document.getElementsByTagName("head")[0];
  var need = ['/holder/jquery.holder.js','/holder/display/filters.js','/holder/display/sort.js','/holder/display/range.js'];
  var jqTag = document.createElement('script');
  jqTag.type = 'text/javascript';
  jqTag.src = _bigdeal_opts.static + need[_bigdeal_got];
  if (_bigdeal_got === need.length-1) {
    jqTag.onload = bigdeal_build;
  } else {
    _bigdeal_got += 1;
    jqTag.onload = bigdeal_get;
  }
  headTag.appendChild(jqTag);
}

var bigdeal_setup = function(opts) {
  if (opts === undefined) opts = {}
  if (opts.api === undefined) opts.api = 'https://api.cottagelabs.com/service/bigdeal';
  //if (opts.site === undefined) opts.site = 'https://bigdeal.test.cottagelabs.com';
  if (opts.static === undefined) opts.static = 'https://openaccessbutton.org/static/bigdeal';
  if (opts.target === undefined) opts.target = '#bigdeal';
  if (opts.template === undefined) opts.template = _bigdeal_template;
  opts.template = opts.template.replace(/XXXSTATICXXX/g,opts.static.replace('https:','').replace('http:',''));
  _bigdeal_opts = opts;

  if ($ === undefined) {
    var headTag = document.getElementsByTagName("head")[0];
    var jqTag = document.createElement('script');
    jqTag.type = 'text/javascript';
    jqTag.src = opts.static + '/jquery-1.10.2.min.js';
    jqTag.onload = bigdeal_get;
    headTag.appendChild(jqTag);
  } else {
     bigdeal_get();
  }
}
<|endoftext|>


<commit_before>/// <reference path="controller.js" />
/// <reference path="dataAccess.js" />
(function () {
    //var serviceRoot = "http://roadrunnerchat.apphb.com/api/";
    var serviceRoot = "http://localhost:16502/api/";

    var persister = Chat.persisters.get(serviceRoot);

    var controller = Chat.controller.get(persister);
    controller.loadUI("#body");

}());<commit_msg>Fix root url<commit_after>/// <reference path="controller.js" />
/// <reference path="dataAccess.js" />
(function () {
    var serviceRoot = "http://roadrunnerchat.apphb.com/api/";
    //var serviceRoot = "http://localhost:16502/api/";

    var persister = Chat.persisters.get(serviceRoot);

    var controller = Chat.controller.get(persister);
    controller.loadUI("#body");

}());<|endoftext|>


<commit_before>var creep_asshealer = {

    /** @param {Creep} creep **/
    run: function(creep) {
        var unboostedTough = 0;
        var unboostedHeal = 0;
        var unboostedMove = 0;

        creep.body.forEach(function(thisPart) {
            if (thisPart.type == HEAL && !thisPart.boost) {
                unboostedHeal = unboostedHeal + 1;
            }

            if (thisPart.type == TOUGH && !thisPart.boost) {
                unboostedTough = unboostedTough + 1;
            }

            if (thisPart.type == MOVE && !thisPart.boost) {
                unboostedMove = unboostedMove + 1;
            }
        });

        if (Game.flags[creep.memory.homeRoom + "DoBoost"] && Game.flags[creep.memory.homeRoom + "RunningAssault"] && (unboostedMove > 0 || unboostedTough > 0 || unboostedHeal > 0)) {
            let MoveLab = creep.room.find(FIND_MY_STRUCTURES, {
                filter: (structure) => (structure.structureType == STRUCTURE_LAB && structure.mineralType == RESOURCE_CATALYZED_ZYNTHIUM_ALKALIDE)
            });
            let ToughLab = creep.room.find(FIND_MY_STRUCTURES, {
                filter: (structure) => (structure.structureType == STRUCTURE_LAB && structure.mineralType == RESOURCE_CATALYZED_GHODIUM_ALKALIDE)
            });
            var HealLab = creep.room.find(FIND_MY_STRUCTURES, {
                filter: (structure) => (structure.structureType == STRUCTURE_LAB && structure.mineralType == RESOURCE_CATALYZED_LEMERGIUM_ALKALIDE)
            });
            let hasTraveled = false;
            if (MoveLab.length && unboostedMove > 0) {
                MoveLab[0].boostCreep(creep);
                creep.travelTo(MoveLab[0]);
                hasTraveled = true;
            }
            if (ToughLab.length && unboostedTough > 0) {
                if (!hasTraveled) {
                    creep.travelTo(ToughLab[0], {
                        ignoreRoads: true
                    });
                    hasTraveled = true;
                }
                ToughLab[0].boostCreep(creep);
            }
            if (HealLab.length && unboostedHeal > 0) {
                if (!hasTraveled) {
                    creep.travelTo(HealLab[0], {
                        ignoreRoads: true
                    });
                    hasTraveled = true;
                }
                HealLab[0].boostCreep(creep);
            }
        } else {
            var targetAttacker = Game.getObjectById(creep.memory.attackerID);
            if (targetAttacker) {
                var thisPortal = undefined;
                if (Game.flags["TakePortal"] && Game.flags["TakePortal"].pos.roomName == creep.pos.roomName) {
                    var thisPortal = creep.pos.findClosestByRange(FIND_STRUCTURES, {
                        filter: (structure) => (structure.structureType == STRUCTURE_PORTAL)
                    });
                }
                if (thisPortal) {
                    creep.travelTo(thisPortal, {
                        ignoreRoads: true
                    });
                } else if ((creep.pos.x == 0 || creep.pos.x == 49 || creep.pos.y == 0 || creep.pos.y == 49) && targetAttacker.room.name == creep.room.name) {
                    /*var xTarget = 0;
                    var yTarget = 0;
                    if (creep.pos.x == 0) {
                        xTarget = 2;
                        yTarget = creep.pos.y;
                    } else if (creep.pos.x == 49) {
                        xTarget = 47;
                        yTarget = creep.pos.y;
                    }
                    if (creep.pos.y == 0) {
                        yTarget = 2;
                        xTarget = creep.pos.x;
                    } else if (creep.pos.y == 49) {
                        yTarget = 47;
                        xTarget = creep.pos.x;
                    }

                    creep.moveTo(xTarget, yTarget);*/
                    creep.moveTo(targetAttacker.pos);
                } else {
                    /*if (creep.pos.inRangeTo(targetAttacker, 2)) {
                        creep.move(creep.pos.getDirectionTo(targetAttacker));
                    } else {*/
                    if (targetAttacker.room.name == creep.room.name) {
                        creep.travelTo(targetAttacker, {
                            maxRooms: 1,
                            ignoreRoads: true,
                            stuckValue: 2
                        });
                    } else {
                        creep.travelTo(targetAttacker, {
                            ignoreRoads: true,
                            stuckValue: 2
                        });
                    }
                    //}
                }

                if (creep.hits < creep.hitsMax - 400) {
                    creep.heal(creep);
                    creep.say("(=\u2716\u11BD\u2716=)", true);
                } else {

                    if (Game.time % 2 == 0) {
                        creep.say("(=\u25D5\u11BD\u25D5\u0E3A=)", true);
                    } else {
                        creep.say("(=\u229D\u11BD\u229D=)", true);
                    }

                    var hurtAlly = creep.pos.findInRange(FIND_CREEPS, 3, {
                        filter: (thisCreep) => thisCreep.hits < thisCreep.hitsMax - 600 && thisCreep.id != targetAttacker.id && (thisCreep.owner.username == "Montblanc" || Memory.whiteList.includes(thisCreep.owner.username))
                    });
                    var healedAlly = false
                    if (hurtAlly.length > 0) {
                        hurtAlly.sort(healCompare);
                        if (creep.pos.getRangeTo(hurtAlly[0]) > 1) {
                            if (creep.rangedHeal(hurtAlly[0]) == OK) {
                                healedAlly = true;
                            }
                        } else {
                            if (creep.heal(hurtAlly[0]) == OK) {
                                healedAlly = true;
                            }
                        }
                    }

                    if (!healedAlly) {
                        if (creep.pos.getRangeTo(targetAttacker) > 1) {
                            creep.rangedHeal(targetAttacker);
                        } else {
                            creep.heal(targetAttacker);
                        }
                    }
                }
            } else {
                creep.memory.priority = 'targetlessHealer';
                creep.heal(creep);
                if (Game.flags[creep.memory.homeRoom + "RallyHere"] && Game.flags[creep.memory.homeRoom + "RallyHere"].pos) {
                    creep.travelTo(Game.flags[creep.memory.homeRoom + "RallyHere"], {
                        ignoreRoads: true
                    });
                }
                var newTarget = creep.pos.findInRange(FIND_MY_CREEPS, 10, {
                    filter: (mCreep) => (mCreep.memory.priority == "assattacker")
                });
                if (newTarget.length) {
                    creep.memory.attackerID = newTarget[0].id;
                }
            }
        }
    }

};

function healCompare(a, b) {
    if (a.hits < b.hits)
        return -1;
    if (a.hits > b.hits)
        return 1;
    return 0;
}

module.exports = creep_asshealer;<commit_msg>Fix1<commit_after>var creep_asshealer = {

    /** @param {Creep} creep **/
    run: function(creep) {
        var unboostedTough = 0;
        var unboostedHeal = 0;
        var unboostedMove = 0;

        creep.body.forEach(function(thisPart) {
            if (thisPart.type == HEAL && !thisPart.boost) {
                unboostedHeal = unboostedHeal + 1;
            }

            if (thisPart.type == TOUGH && !thisPart.boost) {
                unboostedTough = unboostedTough + 1;
            }

            if (thisPart.type == MOVE && !thisPart.boost) {
                unboostedMove = unboostedMove + 1;
            }
        });

        if (!creep.memory.UnassignDelay) {
            creep.memory.UnassignDelay = 0;
        }

        if (Game.flags[creep.memory.homeRoom + "DoBoost"] && Game.flags[creep.memory.homeRoom + "RunningAssault"] && (unboostedMove > 0 || unboostedTough > 0 || unboostedHeal > 0)) {
            let MoveLab = creep.room.find(FIND_MY_STRUCTURES, {
                filter: (structure) => (structure.structureType == STRUCTURE_LAB && structure.mineralType == RESOURCE_CATALYZED_ZYNTHIUM_ALKALIDE)
            });
            let ToughLab = creep.room.find(FIND_MY_STRUCTURES, {
                filter: (structure) => (structure.structureType == STRUCTURE_LAB && structure.mineralType == RESOURCE_CATALYZED_GHODIUM_ALKALIDE)
            });
            var HealLab = creep.room.find(FIND_MY_STRUCTURES, {
                filter: (structure) => (structure.structureType == STRUCTURE_LAB && structure.mineralType == RESOURCE_CATALYZED_LEMERGIUM_ALKALIDE)
            });
            let hasTraveled = false;
            if (MoveLab.length && unboostedMove > 0) {
                MoveLab[0].boostCreep(creep);
                creep.travelTo(MoveLab[0]);
                hasTraveled = true;
            }
            if (ToughLab.length && unboostedTough > 0) {
                if (!hasTraveled) {
                    creep.travelTo(ToughLab[0], {
                        ignoreRoads: true
                    });
                    hasTraveled = true;
                }
                ToughLab[0].boostCreep(creep);
            }
            if (HealLab.length && unboostedHeal > 0) {
                if (!hasTraveled) {
                    creep.travelTo(HealLab[0], {
                        ignoreRoads: true
                    });
                    hasTraveled = true;
                }
                HealLab[0].boostCreep(creep);
            }
        } else {
            var targetAttacker = Game.getObjectById(creep.memory.attackerID);
            if (targetAttacker) {
                var thisPortal = undefined;
                if (Game.flags["TakePortal"] && Game.flags["TakePortal"].pos.roomName == creep.pos.roomName) {
                    var thisPortal = creep.pos.findClosestByRange(FIND_STRUCTURES, {
                        filter: (structure) => (structure.structureType == STRUCTURE_PORTAL)
                    });
                }
                if (thisPortal) {
                    creep.travelTo(thisPortal, {
                        ignoreRoads: true
                    });
                } else if ((creep.pos.x == 0 || creep.pos.x == 49 || creep.pos.y == 0 || creep.pos.y == 49) && targetAttacker.room.name == creep.room.name) {
                    /*var xTarget = 0;
                    var yTarget = 0;
                    if (creep.pos.x == 0) {
                        xTarget = 2;
                        yTarget = creep.pos.y;
                    } else if (creep.pos.x == 49) {
                        xTarget = 47;
                        yTarget = creep.pos.y;
                    }
                    if (creep.pos.y == 0) {
                        yTarget = 2;
                        xTarget = creep.pos.x;
                    } else if (creep.pos.y == 49) {
                        yTarget = 47;
                        xTarget = creep.pos.x;
                    }

                    creep.moveTo(xTarget, yTarget);*/
                    creep.moveTo(targetAttacker.pos);
                } else {
                    /*if (creep.pos.inRangeTo(targetAttacker, 2)) {
                        creep.move(creep.pos.getDirectionTo(targetAttacker));
                    } else {*/
                    if (targetAttacker.room.name == creep.room.name) {
                        creep.travelTo(targetAttacker, {
                            maxRooms: 1,
                            ignoreRoads: true,
                            stuckValue: 2
                        });
                    } else {
                        creep.travelTo(targetAttacker, {
                            ignoreRoads: true,
                            stuckValue: 2
                        });
                    }
                    //}
                }

                if (creep.hits < creep.hitsMax - 400) {
                    creep.heal(creep);
                    creep.say("(=\u2716\u11BD\u2716=)", true);
                } else {

                    if (Game.time % 2 == 0) {
                        creep.say("(=\u25D5\u11BD\u25D5\u0E3A=)", true);
                    } else {
                        creep.say("(=\u229D\u11BD\u229D=)", true);
                    }

                    var hurtAlly = creep.pos.findInRange(FIND_CREEPS, 3, {
                        filter: (thisCreep) => thisCreep.hits < thisCreep.hitsMax - 600 && thisCreep.id != targetAttacker.id && (thisCreep.owner.username == "Montblanc" || Memory.whiteList.includes(thisCreep.owner.username))
                    });
                    var healedAlly = false
                    if (hurtAlly.length > 0) {
                        hurtAlly.sort(healCompare);
                        if (creep.pos.getRangeTo(hurtAlly[0]) > 1) {
                            if (creep.rangedHeal(hurtAlly[0]) == OK) {
                                healedAlly = true;
                            }
                        } else {
                            if (creep.heal(hurtAlly[0]) == OK) {
                                healedAlly = true;
                            }
                        }
                    }

                    if (!healedAlly) {
                        if (creep.pos.getRangeTo(targetAttacker) > 1) {
                            creep.rangedHeal(targetAttacker);
                        } else {
                            creep.heal(targetAttacker);
                        }
                    }
                }
            } else {
                creep.memory.UnassignDelay++;
                if (creep.memory.UnassignDelay > 10) {
                    creep.memory.priority = 'targetlessHealer';
                }
                creep.heal(creep);
                if (Game.flags[creep.memory.homeRoom + "RallyHere"] && Game.flags[creep.memory.homeRoom + "RallyHere"].pos) {
                    creep.travelTo(Game.flags[creep.memory.homeRoom + "RallyHere"], {
                        ignoreRoads: true
                    });
                }
                var newTarget = creep.pos.findInRange(FIND_MY_CREEPS, 10, {
                    filter: (mCreep) => (mCreep.memory.priority == "assattacker")
                });
                if (newTarget.length) {
                    creep.memory.attackerID = newTarget[0].id;
                }
            }
        }
    }

};

function healCompare(a, b) {
    if (a.hits < b.hits)
        return -1;
    if (a.hits > b.hits)
        return 1;
    return 0;
}

module.exports = creep_asshealer;<|endoftext|>


<commit_before>db.jVMs.find().forEach(function(vm) {
    var hostnameAlias, rel, vmUser;

    hostnameAlias = vm.hostnameAlias;
    vmUser = vm.users.filter(function(u) {
      return u.owner === true;
    });
    if (!vmUser) {
      console.warn("The VM " + hostnameAlias + "doesn't have any owners.");
      return;
    }
    rel = db.relationships.findOne({
      targetName: "JAccount",
      sourceId: vmUser[0].id,
      sourceName: "JUser",
      as: "owner"
    });
    return db.jDomains.find({
      hostnameAlias: {
        $in: [vm.hostnameAlias]
      }
    }).forEach(function(domain) {
      var domainRelCount, relSelector;

      relSelector = {
        targetName: "JDomain",
        targetId: domain._id,
        sourceName: "JAccount",
        sourceId: rel.targetId,
        as: "owner"
      };
      domainRelCount = db.relationships.count(relSelector);
      if (domainRelCount === 0) {
        relSelector.timestamp = new Date();
        return db.relationships.insert(relSelector);
      }
    });
  });<commit_msg>if there any domains with hostnameAlias set to a string, update them to an array<commit_after>db.jDomains.find().forEach(function(domain){
  if (typeof(domain.hostnameAlias) === 'string') {
    db.jDomains.update({_id:domain._id}, {$set:{"hostnameAlias":[domain.hostnameAlias]}});
  }
});

db.jVMs.find().forEach(function(vm) {
    var hostnameAlias, rel, vmUser;

    hostnameAlias = vm.hostnameAlias;
    vmUser = vm.users.filter(function(u) {
      return u.owner === true;
    });
    if (!vmUser) {
      console.warn("The VM " + hostnameAlias + "doesn't have any owners.");
      return;
    }
    rel = db.relationships.findOne({
      targetName: "JAccount",
      sourceId: vmUser[0].id,
      sourceName: "JUser",
      as: "owner"
    });
    return db.jDomains.find({
      hostnameAlias: {
        $in: [vm.hostnameAlias]
      }
    }).forEach(function(domain) {
      var domainRelCount, relSelector;

      relSelector = {
        targetName: "JDomain",
        targetId: domain._id,
        sourceName: "JAccount",
        sourceId: rel.targetId,
        as: "owner"
      };
      domainRelCount = db.relationships.count(relSelector);
      if (domainRelCount === 0) {
        relSelector.timestamp = new Date();
        return db.relationships.insert(relSelector);
      }
    });
  });<|endoftext|>