<commit_before>Kwf.EyeCandy.List.Plugins.StateListener.ResizeSwitchContent = Ext.extend(Kwf.EyeCandy.List.Plugins.Abstract, {
    //animationConfig = {}
    //sizes = { state: {width:123, height:123}}
    init: function() {
        this.list.on('childStateChanged', this._change, this);
    },
    render: function() {
        // saves old states as follows: this.oldState[item.id] = 'state'
        this.oldState = {};

        this.list.items.each(function(item) {
            var currentState = item.getState();
            this.oldState[item.id] = currentState;

            // hide all
            // and measure the original sizes
            for (var i in this.sizes) {
                for (var j in this.sizes[i].contentElements) {
                    var contentElement = item.el.child(this.sizes[i].contentElements[j].selector);
                    if (!contentElement) continue;
                    contentElement.enableDisplayMode('block');
                    contentElement.show(); //show to mesure correctly
                    if (!contentElement.ResizeSwitchContentOriginalWidth) {
                        contentElement.ResizeSwitchContentOriginalWidth = contentElement.getWidth();
                    }
                    if (!contentElement.ResizeSwitchContentOriginalHeight) {
                        contentElement.ResizeSwitchContentOriginalHeight = contentElement.getHeight();
                    }
                    contentElement.hide(); //hide by default, correct one will be activated below
                }
            }

            // measure the max sizes
            for (var i in this.sizes) {
                //show all elements for this state (to be able to measure)
                for (var j in this.sizes[i].contentElements) {
                    var contentElement = item.el.child(this.sizes[i].contentElements[j].selector);
                    if (!contentElement) continue;
                    contentElement.show();
                }
                var maxWidth = 0;
                var maxHeight = 0;
                item.el.select('*').each(function(childEl) {
                    if (childEl.isVisible(true)) {
                        if (childEl.getWidth() > maxWidth) maxWidth = childEl.getWidth();
                        if (childEl.getHeight() > maxHeight) maxHeight = childEl.getHeight();
                    }
                }, this);
                if (!this.sizes[i].maxSize) this.sizes[i].maxSize = {};
                this.sizes[i].maxSize[item.id] = { width: maxWidth, height: maxHeight };

                //hide all elements for this state (to be able to measure the next state)
                for (var j in this.sizes[i].contentElements) {
                    var contentElement = item.el.child(this.sizes[i].contentElements[j].selector);
                    if (!contentElement) continue;
                    contentElement.hide();
                }
            }

            // show elements for current state
            for (var j in this.sizes[currentState].contentElements) {
                var contentElement = item.el.child(this.sizes[currentState].contentElements[j].selector);
                if (!contentElement) continue;
                contentElement.show();
            }

        }, this);
    },
    _change: function(item) {
        var state = item.getState();
        var oldState = this.oldState[item.id];

        // measure old elements
        var contentElementsOldSizes = {};
        for (var j in this.sizes[oldState].contentElements) {
            var contentElement = item.el.child(this.sizes[oldState].contentElements[j].selector);
            if (!contentElement) continue;
            contentElementsOldSizes[j] = contentElement.getSize();
        }

        // hide old elements
        for (var i in this.sizes) {
            if (i != state) {
                for (var j in this.sizes[i].contentElements) {
                    var contentElement = item.el.child(this.sizes[i].contentElements[j].selector);
                    if (!contentElement) continue;
                    contentElement.hide();
                }
            }
        }

        // display new elements
        for (var j in this.sizes[state].contentElements) {
            var contentElement = item.el.child(this.sizes[state].contentElements[j].selector);
            if (!contentElement) continue;
            contentElement.show();
        }

        // set the inner content elements to the old size and animate them to their original size
        for (var j in this.sizes[state].contentElements) {
            var contentElement = item.el.child(this.sizes[state].contentElements[j].selector);
            if (!contentElement) continue;
            if (this.sizes[state].contentElements[j].animate === false) continue;

            contentElement.setSize(contentElementsOldSizes[j].width, contentElementsOldSizes[j].height);
            contentElement.setSize(contentElement.ResizeSwitchContentOriginalWidth, contentElement.ResizeSwitchContentOriginalHeight, true);
        }

        var maxWidth = this.sizes[state].maxSize[item.id].width;
        var maxHeight = this.sizes[state].maxSize[item.id].height;

        item.el.setSize(
            maxWidth+item.el.getPadding('lr'),
            maxHeight+item.el.getPadding('tb'),
            true
        );

        this.oldState[item.id] = state;
    }
});
<commit_msg>show item el before measuring size<commit_after>Kwf.EyeCandy.List.Plugins.StateListener.ResizeSwitchContent = Ext.extend(Kwf.EyeCandy.List.Plugins.Abstract, {
    //animationConfig = {}
    //sizes = { state: {width:123, height:123}}
    init: function() {
        this.list.on('childStateChanged', this._change, this);
    },
    render: function() {
        // saves old states as follows: this.oldState[item.id] = 'state'
        this.oldState = {};

        this.list.items.each(function(item) {
            var currentState = item.getState();
            this.oldState[item.id] = currentState;

            var itemIsVisible = item.el.isVisible(); //could be hidden by Carousel plugin
            item.el.show();

            // hide all
            // and measure the original sizes
            for (var i in this.sizes) {
                for (var j in this.sizes[i].contentElements) {
                    var contentElement = item.el.child(this.sizes[i].contentElements[j].selector);
                    if (!contentElement) continue;
                    contentElement.enableDisplayMode('block');
                    contentElement.show(); //show to mesure correctly
                    if (!contentElement.ResizeSwitchContentOriginalWidth) {
                        contentElement.ResizeSwitchContentOriginalWidth = contentElement.getWidth();
                    }
                    if (!contentElement.ResizeSwitchContentOriginalHeight) {
                        contentElement.ResizeSwitchContentOriginalHeight = contentElement.getHeight();
                    }
                    contentElement.hide(); //hide by default, correct one will be activated below
                }
            }

            // measure the max sizes
            for (var i in this.sizes) {
                //show all elements for this state (to be able to measure)
                for (var j in this.sizes[i].contentElements) {
                    var contentElement = item.el.child(this.sizes[i].contentElements[j].selector);
                    if (!contentElement) continue;
                    contentElement.show();
                }
                var maxWidth = 0;
                var maxHeight = 0;
                item.el.select('*').each(function(childEl) {
                    if (childEl.isVisible(true)) {
                        if (childEl.getWidth() > maxWidth) maxWidth = childEl.getWidth();
                        if (childEl.getHeight() > maxHeight) maxHeight = childEl.getHeight();
                    }
                }, this);
                if (!this.sizes[i].maxSize) this.sizes[i].maxSize = {};
                this.sizes[i].maxSize[item.id] = { width: maxWidth, height: maxHeight };

                //hide all elements for this state (to be able to measure the next state)
                for (var j in this.sizes[i].contentElements) {
                    var contentElement = item.el.child(this.sizes[i].contentElements[j].selector);
                    if (!contentElement) continue;
                    contentElement.hide();
                }
            }

            // show elements for current state
            for (var j in this.sizes[currentState].contentElements) {
                var contentElement = item.el.child(this.sizes[currentState].contentElements[j].selector);
                if (!contentElement) continue;
                contentElement.show();
            }

            if (!itemIsVisible) item.el.hide(); //restore item visibility

        }, this);
    },
    _change: function(item) {
        var state = item.getState();
        var oldState = this.oldState[item.id];

        // measure old elements
        var contentElementsOldSizes = {};
        for (var j in this.sizes[oldState].contentElements) {
            var contentElement = item.el.child(this.sizes[oldState].contentElements[j].selector);
            if (!contentElement) continue;
            contentElementsOldSizes[j] = contentElement.getSize();
        }

        // hide old elements
        for (var i in this.sizes) {
            if (i != state) {
                for (var j in this.sizes[i].contentElements) {
                    var contentElement = item.el.child(this.sizes[i].contentElements[j].selector);
                    if (!contentElement) continue;
                    contentElement.hide();
                }
            }
        }

        // display new elements
        for (var j in this.sizes[state].contentElements) {
            var contentElement = item.el.child(this.sizes[state].contentElements[j].selector);
            if (!contentElement) continue;
            contentElement.show();
        }

        // set the inner content elements to the old size and animate them to their original size
        for (var j in this.sizes[state].contentElements) {
            var contentElement = item.el.child(this.sizes[state].contentElements[j].selector);
            if (!contentElement) continue;
            if (this.sizes[state].contentElements[j].animate === false) continue;

            contentElement.setSize(contentElementsOldSizes[j].width, contentElementsOldSizes[j].height);
            contentElement.setSize(contentElement.ResizeSwitchContentOriginalWidth, contentElement.ResizeSwitchContentOriginalHeight, true);
        }

        var maxWidth = this.sizes[state].maxSize[item.id].width;
        var maxHeight = this.sizes[state].maxSize[item.id].height;

        item.el.setSize(
            maxWidth+item.el.getPadding('lr'),
            maxHeight+item.el.getPadding('tb'),
            true
        );

        this.oldState[item.id] = state;
    }
});
<|endoftext|>


<commit_before>import normalizeAst from "./normalize-ast";
import estraverse from "estraverse";
import * as acorn from "../../acorn";

export default function (code, opts = {}) {
  var comments = [];
  var tokens   = [];

  var parseOpts = {
    allowImportExportEverywhere: opts.looseModules,
    allowReturnOutsideFunction:  opts.looseModules,
    allowHashBang:               true,
    ecmaVersion:                 6,
    strictMode:                  opts.strictMode,
    sourceType:                  opts.sourceType,
    locations:                   true,
    onComment:                   comments,
    features:                    opts.features || {},
    plugins:                     opts.plugins || {},
    onToken:                     tokens,
    ranges:                      true
  };

  if (opts.nonStandard) {
    parseOpts.plugins.jsx = true;
    parseOpts.plugins.flow = true;
  }

  var ast = acorn.parse(code, parseOpts);

  estraverse.attachComments(ast, comments, tokens);
  ast = normalizeAst(ast, comments, tokens);
  return ast;
}

export function all(code, opts = {}) {
  opts.allowHashBang = true;
  opts.sourceType = "module";
  opts.ecmaVersion = Infinity;
  opts.plugins = {
    flow: true,
    jsx:  true
  };
  opts.features = {};

  for (var key in transform.pipeline.transformers) {
    opts.features[key] = true;
  }

  return acorn.parse(code, opts);
}
<commit_msg>add transform import - closes babel/babel-eslint#83<commit_after>import normalizeAst from "./normalize-ast";
import transform from "../transformation";
import estraverse from "estraverse";
import * as acorn from "../../acorn";

export default function (code, opts = {}) {
  var comments = [];
  var tokens   = [];

  var parseOpts = {
    allowImportExportEverywhere: opts.looseModules,
    allowReturnOutsideFunction:  opts.looseModules,
    allowHashBang:               true,
    ecmaVersion:                 6,
    strictMode:                  opts.strictMode,
    sourceType:                  opts.sourceType,
    locations:                   true,
    onComment:                   comments,
    features:                    opts.features || {},
    plugins:                     opts.plugins || {},
    onToken:                     tokens,
    ranges:                      true
  };

  if (opts.nonStandard) {
    parseOpts.plugins.jsx = true;
    parseOpts.plugins.flow = true;
  }

  var ast = acorn.parse(code, parseOpts);

  estraverse.attachComments(ast, comments, tokens);
  ast = normalizeAst(ast, comments, tokens);
  return ast;
}

export function all(code, opts = {}) {
  opts.allowHashBang = true;
  opts.sourceType = "module";
  opts.ecmaVersion = Infinity;
  opts.plugins = {
    flow: true,
    jsx:  true
  };
  opts.features = {};

  for (var key in transform.pipeline.transformers) {
    opts.features[key] = true;
  }

  return acorn.parse(code, opts);
}
<|endoftext|>


<commit_before>import React from 'react';

import List from '@ichef/gypcrete/src/List';
import ListRow from '@ichef/gypcrete/src/ListRow';
import TextLabel from '@ichef/gypcrete/src/TextLabel';

function DemoList() {
    return (
        <List>
            <ListRow>
                <TextLabel basic="Row 1" />
            </ListRow>
            <ListRow>
                <TextLabel basic="Row 2" />
            </ListRow>
            <ListRow>
                <TextLabel basic="Row 3" />
            </ListRow>
        </List>
    );
}

export default DemoList;
<commit_msg>[core] Update example for <Popover> to verify behavior<commit_after>import React from 'react';
import { action } from '@storybook/addon-actions';

import Button from '@ichef/gypcrete/src/Button';
import List from '@ichef/gypcrete/src/List';
import ListRow from '@ichef/gypcrete/src/ListRow';

function DemoButton(props) {
    return (
        <Button
            bold
            minified={false}
            color="black"
            {...props} />
    );
}

function DemoList() {
    return (
        <List>
            <ListRow>
                <DemoButton basic="Row 1" onClick={action('click.1')} />
            </ListRow>
            <ListRow>
                <DemoButton basic="Row 2" onClick={action('click.2')} />
            </ListRow>
            <ListRow>
                <DemoButton basic="Row 3" onClick={action('click.3')} />
            </ListRow>
        </List>
    );
}

export default DemoList;
<|endoftext|>


<commit_before>import mongoose, { Schema } from 'mongoose';
import timestamps from 'mongoose-timestamp';
import mongooseStringQuery from 'mongoose-string-query';
import autopopulate from 'mongoose-autopopulate';
import Cache from './cache';
import { ParseArticle } from '../parsers/article';
import { getUrl } from '../utils/urls';

import { createHash } from 'crypto';

import { EnclosureSchema } from './enclosure';

export const ArticleSchema = new Schema(
	{
		rss: {
			type: Schema.Types.ObjectId,
			ref: 'RSS',
			required: true,
			autopopulate: {
				select: [
					'title',
					'url',
					'feedUrl',
					'favicon',
					'categories',
					'description',
					'public',
					'valid',
					'publicationDate',
					'lastScraped',
					'images',
					'featured',
				],
			},
		},
		url: {
			type: String,
			trim: true,
			required: true,
			index: { type: 'hashed' },
		},
		// fingerprint stores the best uniqueness field we have for the given article
		fingerprint: {
			type: String,
			trim: true,
			required: true,
		},
		guid: {
			type: String,
			trim: true,
		},
		link: {
			type: String,
			trim: true,
		},
		title: {
			type: String,
			trim: true,
			required: true,
		},
		description: {
			type: String,
			trim: true,
			maxLength: 240,
			default: '',
		},
		content: {
			type: String,
			trim: true,
			default: '',
		},
		commentUrl: {
			type: String,
			trim: true,
			default: '',
		},
		images: {
			featured: {
				type: String,
				trim: true,
				default: '',
			},
			banner: {
				type: String,
				trim: true,
				default: '',
			},
			favicon: {
				type: String,
				trim: true,
				default: '',
			},
			og: {
				type: String,
				trim: true,
				default: '',
			},
		},
		publicationDate: {
			type: Date,
			default: Date.now,
		},
		enclosures: [EnclosureSchema],
		likes: {
			type: Number,
			default: 0,
		},
		valid: {
			type: Boolean,
			default: true,
			valid: true,
		},
	},
	{
		collection: 'articles',

		toJSON: {
			transform: function(doc, ret) {
				// Frontend breaks if images is null, should be {} instead
				if (!ret.images) {
					ret.images = {};
				}
				ret.images.favicon = ret.images.favicon || '';
				ret.images.og = ret.images.og || '';
			},
		},
		toObject: {
			transform: function(doc, ret) {
				// Frontend breaks if images is null, should be {} instead
				if (!ret.images) {
					ret.images = {};
				}
				ret.images.favicon = ret.images.favicon || '';
				ret.images.og = ret.images.og || '';
			},
		},
	},
);

ArticleSchema.plugin(timestamps, {
	createdAt: { index: true },
	updatedAt: { index: true },
});
ArticleSchema.plugin(mongooseStringQuery);
ArticleSchema.plugin(autopopulate);

ArticleSchema.index({ rss: 1, fingerprint: 1 }, { unique: true });

ArticleSchema.methods.getUrl = function() {
	return getUrl('article_detail', this.rss._id, this._id)
};

ArticleSchema.methods.getParsedArticle = async function() {
	let cached = await Cache.findOne({ url: this.url });
	if (cached) {
		return cached;
	}

	let response = await ParseArticle(this.url);
	let parsed = response.data;
	let content = parsed.content;

	// XKCD doesn't like Mercury
	if (this.url.indexOf('https://xkcd') === 0) {
		content = this.content;
	}

	cached = await Cache.create({
		content: content,
		excerpt: parsed.excerpt || parsed.title,
		image: parsed.lead_image_url || '',
		publicationDate: parsed.date_published || this.publicationDate,
		title: parsed.title,
		url: this.url,
		commentUrl: this.commentUrl,
		enclosures: this.enclosures,
	});
	return cached;
};

module.exports = exports = mongoose.model('Article', ArticleSchema);
module.exports.ArticleSchema = ArticleSchema;
<commit_msg>less error output on broken mercury api call<commit_after>import mongoose, { Schema } from 'mongoose';
import timestamps from 'mongoose-timestamp';
import mongooseStringQuery from 'mongoose-string-query';
import autopopulate from 'mongoose-autopopulate';
import Cache from './cache';
import { ParseArticle } from '../parsers/article';
import { getUrl } from '../utils/urls';

import { createHash } from 'crypto';

import { EnclosureSchema } from './enclosure';

export const ArticleSchema = new Schema(
	{
		rss: {
			type: Schema.Types.ObjectId,
			ref: 'RSS',
			required: true,
			autopopulate: {
				select: [
					'title',
					'url',
					'feedUrl',
					'favicon',
					'categories',
					'description',
					'public',
					'valid',
					'publicationDate',
					'lastScraped',
					'images',
					'featured',
				],
			},
		},
		url: {
			type: String,
			trim: true,
			required: true,
			index: { type: 'hashed' },
		},
		// fingerprint stores the best uniqueness field we have for the given article
		fingerprint: {
			type: String,
			trim: true,
			required: true,
		},
		guid: {
			type: String,
			trim: true,
		},
		link: {
			type: String,
			trim: true,
		},
		title: {
			type: String,
			trim: true,
			required: true,
		},
		description: {
			type: String,
			trim: true,
			maxLength: 240,
			default: '',
		},
		content: {
			type: String,
			trim: true,
			default: '',
		},
		commentUrl: {
			type: String,
			trim: true,
			default: '',
		},
		images: {
			featured: {
				type: String,
				trim: true,
				default: '',
			},
			banner: {
				type: String,
				trim: true,
				default: '',
			},
			favicon: {
				type: String,
				trim: true,
				default: '',
			},
			og: {
				type: String,
				trim: true,
				default: '',
			},
		},
		publicationDate: {
			type: Date,
			default: Date.now,
		},
		enclosures: [EnclosureSchema],
		likes: {
			type: Number,
			default: 0,
		},
		valid: {
			type: Boolean,
			default: true,
			valid: true,
		},
	},
	{
		collection: 'articles',

		toJSON: {
			transform: function(doc, ret) {
				// Frontend breaks if images is null, should be {} instead
				if (!ret.images) {
					ret.images = {};
				}
				ret.images.favicon = ret.images.favicon || '';
				ret.images.og = ret.images.og || '';
			},
		},
		toObject: {
			transform: function(doc, ret) {
				// Frontend breaks if images is null, should be {} instead
				if (!ret.images) {
					ret.images = {};
				}
				ret.images.favicon = ret.images.favicon || '';
				ret.images.og = ret.images.og || '';
			},
		},
	},
);

ArticleSchema.plugin(timestamps, {
	createdAt: { index: true },
	updatedAt: { index: true },
});
ArticleSchema.plugin(mongooseStringQuery);
ArticleSchema.plugin(autopopulate);

ArticleSchema.index({ rss: 1, fingerprint: 1 }, { unique: true });

ArticleSchema.methods.getUrl = function() {
	return getUrl('article_detail', this.rss._id, this._id);
};

ArticleSchema.methods.getParsedArticle = async function() {
	let cached = await Cache.findOne({ url: this.url });
	if (cached) {
		return cached;
	}

	let response;
	try {
		response = await ParseArticle(this.url);
	} catch (e) {
		throw new Error(`Mercury API call failed for ${this.url}`);
	}
	let parsed = response.data;
	let content = parsed.content;

	// XKCD doesn't like Mercury
	if (this.url.indexOf('https://xkcd') === 0) {
		content = this.content;
	}

	cached = await Cache.create({
		content: content,
		excerpt: parsed.excerpt || parsed.title,
		image: parsed.lead_image_url || '',
		publicationDate: parsed.date_published || this.publicationDate,
		title: parsed.title,
		url: this.url,
		commentUrl: this.commentUrl,
		enclosures: this.enclosures,
	});
	return cached;
};

module.exports = exports = mongoose.model('Article', ArticleSchema);
module.exports.ArticleSchema = ArticleSchema;
<|endoftext|>


<commit_before>import { isString, isObject, mapKeys, mapValues, transform } from 'lodash';

const PARAM_FILTER = { filters: 1, query: 1, sort: 1, qindex: 1 };

export function getNsKey(key, params) {
  if (!params || !PARAM_FILTER[key]) return key;
  return (isString(params)) ? `${params}.${key}` : params[key];
}

// Adds namespace / prefix to keys for given query
//
// example:
// values = { query: "test", filters: 'active', userId: 1 }, params = 'users'
// result:
// { "users.query" : "test", "users.filters": "active", userId: 1 }
export function mapNsKeys(values, params) {
  if (!params) return values;
  return mapKeys(values, (value, key) =>
    (PARAM_FILTER[key] ? getNsKey(key, params) : key));
}

// Removes namespace / prefix from keys for given values
//
// example:
// values = { "users.query" : "test", "users.filters": "active" }, params = 'users'
// result:
// { query: "test", filters: 'active' }
export function removeNsKeys(values, params) {
  if (!params) return values;

  if (isObject(params)) {
    return mapValues(params, value => values[value]);
  }

  if (isString(params)) {
    const prefix = new RegExp(`^${params}\\.`, 'i');
    return transform(values, (result, value, key) => {
      if (key.match(prefix)) {
        result[key.replace(prefix, '')] = value;
      }
      return result;
    }, {});
  }

  return values;
}
<commit_msg>Cleanup<commit_after>import { isString, isObject, mapKeys, mapValues, transform } from 'lodash';

const PARAM_FILTER = { filters: 1, query: 1, sort: 1, qindex: 1 };

export function getNsKey(key, params) {
  if (!params || !PARAM_FILTER[key]) return key;
  return (isString(params)) ? `${params}.${key}` : (params[key] || key);
}

// Adds namespace / prefix to keys for given query
//
// example:
// values = { query: "test", filters: 'active', userId: 1 }, params = 'users'
// result:
// { "users.query" : "test", "users.filters": "active", userId: 1 }
export function mapNsKeys(values, params) {
  if (!params) return values;
  return mapKeys(values, (value, key) =>
    (PARAM_FILTER[key] ? getNsKey(key, params) : key));
}

// Removes namespace / prefix from keys for given values
//
// example:
// values = { "users.query" : "test", "users.filters": "active" }, params = 'users'
// result:
// { query: "test", filters: 'active' }
export function removeNsKeys(values, params) {
  if (!params) return values;

  if (isObject(params)) {
    return mapValues(params, value => values[value]);
  }

  if (isString(params)) {
    const prefix = new RegExp(`^${params}\\.`, 'i');
    return transform(values, (result, value, key) => {
      if (key.match(prefix)) {
        result[key.replace(prefix, '')] = value;
      }
      return result;
    }, {});
  }

  return values;
}
<|endoftext|>


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

var text = fs.readFileSync(__dirname + '/../index.js', 'utf8');

var textarea = document.querySelector('textarea#doc');
var crate = require('crate-core');

module.exports = stream => {
  var doc = new crate(null, stream);
  window.doc = doc;

  if (stream.server) {
    console.log('Sending initial state');

    // Sssshhhh
    var send = stream.send;
    stream.send = () => {};

    // Start off doc with contents of textarea.
    doc.insert('\n', 0);

    stream.send = send;

    var initial = JSON.stringify(doc.sequence);
    doc.broadcast.send(initial);
    edit(doc);
  } else {
    console.log('Awaiting initial state...');
    var cb = (initial) => {
      console.log('Received initial state...');
      doc.sequence.fromJSON(JSON.parse(initial));
      edit(doc);
    };
    doc.broadcast.once('message', cb);
  }
}

function getStringChildNode(childNode){
  var result = '';
  if (childNode.e !== null){ result = childNode.e; };
  for (var i=0; i<childNode.children.length; ++i){
    result += getStringChildNode(childNode.children[i]);
  };
  return result;
};

var docToString = (doc) => getStringChildNode(doc.sequence.root);

var isConsistent = (doc, editor) => docToString(doc) === editor.getContent();

var edit = (doc) => {
  var editor = window.editor;

  editor.setContent(docToString(doc));

  var debug = () => {
    console.log(docToString(doc));

    if(!isConsistent(doc, editor)) {
      console.warn('INCONSISTENT');
      debugger;
    }
  };

  window.docAsString = () => docToString(doc);
  window.debug = debug;

  // var insertRemoveOp = false;
  //
  // editor.getSession().getSelection().on('changeCursor', function(e, sel){
  //   if (!insertRemoveOp){
  //     var range = sel.getRange();
  //     doc.caretMoved({
  //       start: editor.getSession().getDocument().positionToIndex(range.start),
  //       end: editor.getSession().getDocument().positionToIndex(range.end)
  //     });
  //   }
  //   insertRemoveOp = false;
  // });

  editor.on('contentChangedExt', (_, diffs) => {
    var start = 0;
    var end = 0;
    var text = '';
    var diff;
    for (var i = 0; i < diffs.length; i++) {
      var exit = false;
      diff = diffs[i];
      var [type, text] = diff;

      switch (type) {
        case 0:
          // No change
          start = start + text.length;
          end = end + text.length;
          break;
        case 1:
          // Addition
          end = end + text.length;
          exit = true;
          break;
        case -1:
          // Removal
          end = end + text.length;
          exit = true;
          break;
      }

      if (exit) { break; }
    }

    var e;
    var [type, text] = diff;
    switch (type) {
      case 1:
        e = {
          action: 'insert',
          start,
          end,
          text
        };
        break;
      case -1:
        e = {
          action: 'remove',
          start,
          end,
        };
        break;
      default:
        return;
    }

    var begin, end, text, message, j=0;

    begin = e.start;
    end = e.end;

    for (var i=begin; i<end; ++i){
      switch (e.action){
        case 'insert':
          console.log('insert: ' + text[j] + ' at ' + i);
          doc.insert(text[j], i);
          break;
        case 'remove':
          console.log('remove: ' + text[j] + ' at ' + begin);
          doc.remove(begin);
          break;
      };
      ++j;
    };

    debug();
  });

  doc.on('remoteInsert', (element, index) => {
    if (index === -1) { return; }
    editor.watcherExt.noWatch(() => {
      console.log('remote insert: ' + element + ' at ' + index);
      editor.replace(index-1, index-1, element);
    });
    debug();
  });

  doc.on('remoteRemove', (index) => {
    if (index === -1) { return; }
    editor.watcherExt.noWatch(() => {
      console.log('remote remove: ' + editor.getContent().split('')[index-1] + ' at ' + (index-1));
      editor.replace(index-1, index, '');
    });
    debug();
  });
};
<commit_msg>Refactor op generator into function for rewrite.<commit_after>var fs = require('fs');

var text = fs.readFileSync(__dirname + '/../index.js', 'utf8');

var textarea = document.querySelector('textarea#doc');
var crate = require('crate-core');

var diffsToOps = (diffs) => {
  var start = 0;
  var end = 0;
  var type = 0;
  var text = '';
  var diff;
  for (var i = 0; i < diffs.length; i++) {
    var exit = false;
    diff = diffs[i];
    [type, text] = diff;

    switch (type) {
      case 0:
        // No change
        start = start + text.length;
        end = end + text.length;
        break;
      case 1:
        // Addition
        end = end + text.length;
        exit = true;
        break;
      case -1:
        // Removal
        end = end + text.length;
        exit = true;
        break;
    }

    if (exit) { break; }
  }

  var e;
  var [type, text] = diff;
  switch (type) {
    case 1:
      e = {
        action: 'insert',
        start,
        end,
        text
      };
      break;
    case -1:
      e = {
        action: 'remove',
        start,
        end,
        text
      };
      break;
    default:
      return;
  }

  return [e];
};

module.exports = stream => {
  var doc = new crate(null, stream);
  window.doc = doc;

  if (stream.server) {
    console.log('Sending initial state');

    // Sssshhhh
    var send = stream.send;
    stream.send = () => {};

    // Start off doc with contents of textarea.
    doc.insert('\n', 0);

    stream.send = send;

    var initial = JSON.stringify(doc.sequence);
    doc.broadcast.send(initial);
    edit(doc);
  } else {
    console.log('Awaiting initial state...');
    var cb = (initial) => {
      console.log('Received initial state...');
      doc.sequence.fromJSON(JSON.parse(initial));
      edit(doc);
    };
    doc.broadcast.once('message', cb);
  }
}

function getStringChildNode(childNode){
  var result = '';
  if (childNode.e !== null){ result = childNode.e; };
  for (var i=0; i<childNode.children.length; ++i){
    result += getStringChildNode(childNode.children[i]);
  };
  return result;
};

var docToString = (doc) => getStringChildNode(doc.sequence.root);

var isConsistent = (doc, editor) => docToString(doc) === editor.getContent();

var edit = (doc) => {
  var editor = window.editor;

  editor.setContent(docToString(doc));

  var debug = () => {
    console.log(docToString(doc));

    if(!isConsistent(doc, editor)) {
      console.warn('INCONSISTENT');
      debugger;
    }
  };

  window.docAsString = () => docToString(doc);
  window.debug = debug;

  // var insertRemoveOp = false;
  //
  // editor.getSession().getSelection().on('changeCursor', function(e, sel){
  //   if (!insertRemoveOp){
  //     var range = sel.getRange();
  //     doc.caretMoved({
  //       start: editor.getSession().getDocument().positionToIndex(range.start),
  //       end: editor.getSession().getDocument().positionToIndex(range.end)
  //     });
  //   }
  //   insertRemoveOp = false;
  // });

  editor.on('contentChangedExt', (_, diffs) => {
    var ops = diffsToOps(diffs);

    ops.forEach(({ start, end, text, action }) => {
      var j = 0;
      for (var i=start; i<end; ++i){
        switch (action){
          case 'insert':
            console.log('insert: ' + text[j] + ' at ' + i);
            doc.insert(text[j], i);
            break;
          case 'remove':
            console.log('remove: ' + text[j] + ' at ' + start);
            doc.remove(start);
            break;
        };
        ++j;
      };
    });

    debug();
  });

  doc.on('remoteInsert', (element, index) => {
    if (index === -1) { return; }
    editor.watcherExt.noWatch(() => {
      console.log('remote insert: ' + element + ' at ' + index);
      editor.replace(index-1, index-1, element);
    });
    debug();
  });

  doc.on('remoteRemove', (index) => {
    if (index === -1) { return; }
    editor.watcherExt.noWatch(() => {
      console.log('remote remove: ' + editor.getContent().split('')[index-1] + ' at ' + (index-1));
      editor.replace(index-1, index, '');
    });
    debug();
  });
};
<|endoftext|>


<commit_before>import { defaults } from './module.js';

angular.module('anol.savesettings')

.directive('anolSavesettings', ['$templateRequest', '$compile', 'SaveSettingsService', 'ProjectSettings', 'NotificationService',
    function($templateRequest, $compile, SaveSettingsService, ProjectSettings, NotificationService) {
    return {
        restrict: 'A',
        template: function(tElement, tAttrs) {
            if (tAttrs.templateUrl) {
                return '

';
            }
            return require('./templates/savemanager.html')
        },
        scope: {
            modalCallBack:'&'
        },
        link: function(scope, element, attrs, controllers) {

            if (attrs.templateUrl && attrs.templateUrl !== '') {
                $templateRequest(attrs.templateUrl).then(function(html){
                    var template = angular.element(html);
                    element.html(template);
                    $compile(template)(scope);
                });
            }

            scope.projectSettings = ProjectSettings;
            scope.close = function() {
                scope.modalCallBack();
            }
            scope.delete = function(id) {
                SaveSettingsService.delete(id).then(function(data) {
                    scope.modalCallBack();
                    NotificationService.addInfo(data.message)
                }, function() {
                    NotificationService.addError(data.message)
                });
            };
            scope.save = function(name) {
                // load project name to overwrite
                if (name === undefined || scope.id) {
                    angular.forEach(scope.projectSettings, function(value) {
                        if (value.id == scope.id) {
                            name = value.name;
                        }
                    });
                }
                if (name == undefined || name == '') {
                    return;
                }
                SaveSettingsService.save(name).then(function(data) {
                    scope.modalCallBack();
                    NotificationService.addInfo(data.message)
                }, function() {
                    NotificationService.addError(data.message)
                });
            };
            scope.load = function(id) {
                if (id === undefined) {
                    return;
                }
                SaveSettingsService.load(id).then(function(data) {
                    scope.modalCallBack();
                    NotificationService.addInfo(data.message)
                }, function() {
                    NotificationService.addError(data.message)
                });
            };
        }
    };
}])
<commit_msg>dont close modul if user delete settings<commit_after>import { defaults } from './module.js';

angular.module('anol.savesettings')

.directive('anolSavesettings', ['$templateRequest', '$compile', 'SaveSettingsService', 'ProjectSettings', 'NotificationService',
    function($templateRequest, $compile, SaveSettingsService, ProjectSettings, NotificationService) {
    return {
        restrict: 'A',
        template: function(tElement, tAttrs) {
            if (tAttrs.templateUrl) {
                return '

';
            }
            return require('./templates/savemanager.html')
        },
        scope: {
            modalCallBack:'&'
        },
        link: function(scope, element, attrs, controllers) {

            if (attrs.templateUrl && attrs.templateUrl !== '') {
                $templateRequest(attrs.templateUrl).then(function(html){
                    var template = angular.element(html);
                    element.html(template);
                    $compile(template)(scope);
                });
            }

            scope.projectSettings = ProjectSettings;
            scope.close = function() {
                scope.modalCallBack();
            }
            scope.delete = function(id) {
                SaveSettingsService.delete(id).then(function(data) {
                    NotificationService.addInfo(data.message)
                }, function() {
                    NotificationService.addError(data.message)
                });
            };
            scope.save = function(name) {
                // load project name to overwrite
                if (name === undefined || scope.id) {
                    angular.forEach(scope.projectSettings, function(value) {
                        if (value.id == scope.id) {
                            name = value.name;
                        }
                    });
                }
                if (name == undefined || name == '') {
                    return;
                }
                SaveSettingsService.save(name).then(function(data) {
                    scope.modalCallBack();
                    NotificationService.addInfo(data.message)
                }, function() {
                    NotificationService.addError(data.message)
                });
            };
            scope.load = function(id) {
                if (id === undefined) {
                    return;
                }
                SaveSettingsService.load(id).then(function(data) {
                    scope.modalCallBack();
                    NotificationService.addInfo(data.message)
                }, function() {
                    NotificationService.addError(data.message)
                });
            };
        }
    };
}])
<|endoftext|>


<commit_before>var fixtures = require('node-require-directory')(__dirname);

exports.load = function(specificFixtures) {
  return exports.unload().then(function() {
    if (typeof specificFixtures === 'string') {
      specificFixtures = [specificFixtures];
    }
    var promises = [];
    Object.keys(fixtures).filter(function(key) {
      if (key === 'index') {
        return false;
      }
      if (specificFixtures && specificFixtures.indexOf(key) === -1) {
        return false;
      }
      return true;
    }).forEach(function(key) {
      var promise = fixtures[key].load().then(function(instances) {
        exports[key] = instances;
      });
      promises.push(promise);
    });
    return Promise.all(promises);
  }).catch(function(err) {
    console.error(err.stack);
  });
};

exports.unload = function() {
  return sequelize.query('SET FOREIGN_KEY_CHECKS = 0').then(function() {
    return sequelize.sync({ force: true });
  }).then(function() {
    return sequelize.query('SET FOREIGN_KEY_CHECKS = 1');
  });
};
<commit_msg>Fix running SET command in sqlite<commit_after>var fixtures = require('node-require-directory')(__dirname);

exports.load = function(specificFixtures) {
  return exports.unload().then(function() {
    if (typeof specificFixtures === 'string') {
      specificFixtures = [specificFixtures];
    }
    var promises = [];
    Object.keys(fixtures).filter(function(key) {
      if (key === 'index') {
        return false;
      }
      if (specificFixtures && specificFixtures.indexOf(key) === -1) {
        return false;
      }
      return true;
    }).forEach(function(key) {
      var promise = fixtures[key].load().then(function(instances) {
        exports[key] = instances;
      });
      promises.push(promise);
    });
    return Promise.all(promises);
  }).catch(function(err) {
    console.error(err.stack);
  });
};

exports.unload = function() {
  if (sequelize.options.dialect === 'mysql') {
    return sequelize.query('SET FOREIGN_KEY_CHECKS = 0').then(function() {
      return sequelize.sync({ force: true });
    }).then(function() {
      return sequelize.query('SET FOREIGN_KEY_CHECKS = 1');
    });
  } else {
    return sequelize.sync({ force: true });
  }
};
<|endoftext|>


<commit_before>/**
	_enyo.Input_ implements an HTML <input> element with cross-platform
	support for	change events.

	You can listen for _oninput_ and _onchange_ DOM events from this control
	to know when the text inside has been modified. _oninput_ fires immediately,
	while _onchange_ fires when the text has changed and the input subsequently
	loses focus.

	For more information, see the documentation on
	[Text Fields](https://github.com/enyojs/enyo/wiki/Text-Fields) in the Enyo
	Developer Guide.
*/
enyo.kind({
	name: "enyo.Input",
	published: {
		/**
			Value of the input.  Use this property only to initialize the value.
			Call _getValue_ and _setValue_ to manipulate the value at runtime.
		*/
		value: "",
		//* Text to display when the input is empty
		placeholder: "",
		/**
			Type of input; if not specified, it's treated as "text". It can
			be anything specified for the _type_ attribute in the HTML
			specification, including "url", "email", "search", or "number".
		*/
		type: "",
		/**
			When true, prevents input into the control. This maps to the
			_disabled_ DOM attribute.
		*/
		disabled: false,
		//* When true, select the contents of the input when it gains focus.
		selectOnFocus: false
	},
	events: {
		//* Fires when the input is disabled or enabled.
		onDisabledChange: ""
	},
	//* Set to true to focus this control when it is rendered
	defaultFocus: false,
	//* @protected
	tag: "input",
	classes: "enyo-input",
	handlers: {
		onfocus: "focused",
		oninput: "input",
		onclear: "clear",
		ondragstart: "dragstart"
	},
	create: function() {
		if (enyo.platform.ie) {
			this.handlers.onkeyup = "iekeyup";
		}
		if (enyo.platform.windowsPhone) {
			this.handlers.onkeydown = "iekeydown";
		}
		this.inherited(arguments);
		this.placeholderChanged();
		// prevent overriding a custom attribute with null
		if (this.type) {
			this.typeChanged();
		}
		this.valueChanged();
	},
	rendered: function() {
		this.inherited(arguments);

		enyo.makeBubble(this, "focus", "blur");

		//Force onchange event to be bubbled inside Enyo for IE8
		if(enyo.platform.ie == 8){
      		this.setAttribute("onchange", enyo.bubbler);
      	}

		this.disabledChanged();
		if (this.defaultFocus) {
			this.focus();
		}
	},
	typeChanged: function() {
		this.setAttribute("type", this.type);
	},
	placeholderChanged: function() {
		this.setAttribute("placeholder", this.placeholder);
	},
	disabledChanged: function() {
		this.setAttribute("disabled", this.disabled);
		this.bubble("onDisabledChange");
	},
	getValue: function() {
		return this.getNodeProperty("value", this.value);
	},
	valueChanged: function() {
		this.setAttribute("value", this.value);
		this.setNodeProperty("value", this.value);
	},
	iekeyup: function(inSender, inEvent) {
		var ie = enyo.platform.ie, kc = inEvent.keyCode;
		// input event missing on ie 8, fails to fire on backspace and delete keys in ie 9
		if (ie <= 8 || (ie == 9 && (kc == 8 || kc == 46))) {
			this.bubble("oninput", inEvent);
		}
	},
	iekeydown: function(inSender, inEvent) {
		var wp = enyo.platform.windowsPhone, kc = inEvent.keyCode;
		// on input controls, onchange event fails to fire on enter key for Windows Phone 8
		if (wp <= 8 && kc == 13 && this.tag == "input") {
			this.bubble("onchange", inEvent);
		}
	},
	clear: function() {
		this.setValue("");
	},
	focus: function() {
		if (this.hasNode()) {
			this.node.focus();
		}
	},
	//* Returns true if the Input is focused.
	hasFocus: function() {
		if (this.hasNode()) {
			return document.activeElement === this.node;
		}
	},
	// note: we disallow dragging of an input to allow text selection on all platforms
	dragstart: function() {
		return this.hasFocus();
	},
	focused: function() {
		if (this.selectOnFocus) {
			enyo.asyncMethod(this, "selectContents");
		}
	},
	selectContents: function() {
		var n = this.hasNode();

		if (n && n.setSelectionRange) {
			n.setSelectionRange(0, n.value.length);
		} else if (n && n.createTextRange) {
			var r = n.createTextRange();
			r.expand("textedit");
			r.select();
		}
	}
});
<commit_msg>ENYO-1959: Forcing blur instead of onchange<commit_after>/**
	_enyo.Input_ implements an HTML <input> element with cross-platform
	support for	change events.

	You can listen for _oninput_ and _onchange_ DOM events from this control
	to know when the text inside has been modified. _oninput_ fires immediately,
	while _onchange_ fires when the text has changed and the input subsequently
	loses focus.

	For more information, see the documentation on
	[Text Fields](https://github.com/enyojs/enyo/wiki/Text-Fields) in the Enyo
	Developer Guide.
*/
enyo.kind({
	name: "enyo.Input",
	published: {
		/**
			Value of the input.  Use this property only to initialize the value.
			Call _getValue_ and _setValue_ to manipulate the value at runtime.
		*/
		value: "",
		//* Text to display when the input is empty
		placeholder: "",
		/**
			Type of input; if not specified, it's treated as "text". It can
			be anything specified for the _type_ attribute in the HTML
			specification, including "url", "email", "search", or "number".
		*/
		type: "",
		/**
			When true, prevents input into the control. This maps to the
			_disabled_ DOM attribute.
		*/
		disabled: false,
		//* When true, select the contents of the input when it gains focus.
		selectOnFocus: false
	},
	events: {
		//* Fires when the input is disabled or enabled.
		onDisabledChange: ""
	},
	//* Set to true to focus this control when it is rendered
	defaultFocus: false,
	//* @protected
	tag: "input",
	classes: "enyo-input",
	handlers: {
		onfocus: "focused",
		oninput: "input",
		onclear: "clear",
		ondragstart: "dragstart"
	},
	create: function() {
		if (enyo.platform.ie) {
			this.handlers.onkeyup = "iekeyup";
		}
		if (enyo.platform.windowsPhone) {
			this.handlers.onkeydown = "iekeydown";
		}
		this.inherited(arguments);
		this.placeholderChanged();
		// prevent overriding a custom attribute with null
		if (this.type) {
			this.typeChanged();
		}
		this.valueChanged();
	},
	rendered: function() {
		this.inherited(arguments);

		enyo.makeBubble(this, "focus", "blur");

		//Force onchange event to be bubbled inside Enyo for IE8
		if(enyo.platform.ie == 8){
      		this.setAttribute("onchange", enyo.bubbler);
      	}

		this.disabledChanged();
		if (this.defaultFocus) {
			this.focus();
		}
	},
	typeChanged: function() {
		this.setAttribute("type", this.type);
	},
	placeholderChanged: function() {
		this.setAttribute("placeholder", this.placeholder);
	},
	disabledChanged: function() {
		this.setAttribute("disabled", this.disabled);
		this.bubble("onDisabledChange");
	},
	getValue: function() {
		return this.getNodeProperty("value", this.value);
	},
	valueChanged: function() {
		this.setAttribute("value", this.value);
		this.setNodeProperty("value", this.value);
	},
	iekeyup: function(inSender, inEvent) {
		var ie = enyo.platform.ie, kc = inEvent.keyCode;
		// input event missing on ie 8, fails to fire on backspace and delete keys in ie 9
		if (ie <= 8 || (ie == 9 && (kc == 8 || kc == 46))) {
			this.bubble("oninput", inEvent);
		}
	},
	iekeydown: function(inSender, inEvent) {
		var wp = enyo.platform.windowsPhone, kc = inEvent.keyCode, dt = inEvent.dispatchTarget;
		// onchange event fails to fire on enter key for Windows Phone 8, so we force blur
		if (wp <= 8 && kc == 13 && this.tag == "input" && dt.hasNode()) {
			dt.node.blur();
		}
	},
	clear: function() {
		this.setValue("");
	},
	focus: function() {
		if (this.hasNode()) {
			this.node.focus();
		}
	},
	//* Returns true if the Input is focused.
	hasFocus: function() {
		if (this.hasNode()) {
			return document.activeElement === this.node;
		}
	},
	// note: we disallow dragging of an input to allow text selection on all platforms
	dragstart: function() {
		return this.hasFocus();
	},
	focused: function() {
		if (this.selectOnFocus) {
			enyo.asyncMethod(this, "selectContents");
		}
	},
	selectContents: function() {
		var n = this.hasNode();

		if (n && n.setSelectionRange) {
			n.setSelectionRange(0, n.value.length);
		} else if (n && n.createTextRange) {
			var r = n.createTextRange();
			r.expand("textedit");
			r.select();
		}
	}
});
<|endoftext|>


<commit_before>const http = require('http')
http.globalAgent.maxSockets = 300

module.exports = {
  internal: {
    documentupdater: {
      host: process.env.LISTEN_ADDRESS || 'localhost',
      port: 3003
    }
  },

  apis: {
    web: {
      url: `http://${
        process.env.WEB_API_HOST || process.env.WEB_HOST || 'localhost'
      }:${process.env.WEB_API_PORT || process.env.WEB_PORT || 3000}`,
      user: process.env.WEB_API_USER || 'sharelatex',
      pass: process.env.WEB_API_PASSWORD || 'password'
    },
    trackchanges: {
      url: `http://${process.env.TRACK_CHANGES_HOST || 'localhost'}:3015`
    },
    project_history: {
      enabled: true,
      url: `http://${process.env.PROJECT_HISTORY_HOST || 'localhost'}:3054`
    }
  },

  redis: {
    pubsub: {
      host:
        process.env.PUBSUB_REDIS_HOST || process.env.REDIS_HOST || 'localhost',
      port: process.env.PUBSUB_REDIS_PORT || process.env.REDIS_PORT || '6379',
      password:
        process.env.PUBSUB_REDIS_PASSWORD || process.env.REDIS_PASSWORD || '',
      maxRetriesPerRequest: parseInt(
        process.env.REDIS_MAX_RETRIES_PER_REQUEST || '20'
      )
    },

    history: {
      port: process.env.HISTORY_REDIS_PORT || process.env.REDIS_PORT || '6379',
      host:
        process.env.HISTORY_REDIS_HOST || process.env.REDIS_HOST || 'localhost',
      password:
        process.env.HISTORY_REDIS_PASSWORD || process.env.REDIS_PASSWORD || '',
      maxRetriesPerRequest: parseInt(
        process.env.REDIS_MAX_RETRIES_PER_REQUEST || '20'
      ),
      key_schema: {
        uncompressedHistoryOps({ doc_id: docId }) {
          return `UncompressedHistoryOps:{${docId}}`
        },
        docsWithHistoryOps({ project_id: projectId }) {
          return `DocsWithHistoryOps:{${projectId}}`
        }
      }
    },

    project_history: {
      port:
        process.env.NEW_HISTORY_REDIS_PORT || process.env.REDIS_PORT || '6379',
      host:
        process.env.NEW_HISTORY_REDIS_HOST ||
        process.env.REDIS_HOST ||
        'localhost',
      password:
        process.env.NEW_HISTORY_REDIS_PASSWORD ||
        process.env.REDIS_PASSWORD ||
        '',
      maxRetriesPerRequest: parseInt(
        process.env.REDIS_MAX_RETRIES_PER_REQUEST || '20'
      ),
      key_schema: {
        projectHistoryOps({ project_id: projectId }) {
          return `ProjectHistory:Ops:{${projectId}}`
        },
        projectHistoryFirstOpTimestamp({ project_id: projectId }) {
          return `ProjectHistory:FirstOpTimestamp:{${projectId}}`
        }
      }
    },

    lock: {
      port: process.env.LOCK_REDIS_PORT || process.env.REDIS_PORT || '6379',
      host:
        process.env.LOCK_REDIS_HOST || process.env.REDIS_HOST || 'localhost',
      password:
        process.env.LOCK_REDIS_PASSWORD || process.env.REDIS_PASSWORD || '',
      maxRetriesPerRequest: parseInt(
        process.env.REDIS_MAX_RETRIES_PER_REQUEST || '20'
      ),
      key_schema: {
        blockingKey({ doc_id: docId }) {
          return `Blocking:{${docId}}`
        }
      }
    },

    documentupdater: {
      port:
        process.env.DOC_UPDATER_REDIS_PORT || process.env.REDIS_PORT || '6379',
      host:
        process.env.DOC_UPDATER_REDIS_HOST ||
        process.env.REDIS_HOST ||
        'localhost',
      password:
        process.env.DOC_UPDATER_REDIS_PASSWORD ||
        process.env.REDIS_PASSWORD ||
        '',
      maxRetriesPerRequest: parseInt(
        process.env.REDIS_MAX_RETRIES_PER_REQUEST || '20'
      ),
      key_schema: {
        blockingKey({ doc_id: docId }) {
          return `Blocking:{${docId}}`
        },
        docLines({ doc_id: docId }) {
          return `doclines:{${docId}}`
        },
        docOps({ doc_id: docId }) {
          return `DocOps:{${docId}}`
        },
        docVersion({ doc_id: docId }) {
          return `DocVersion:{${docId}}`
        },
        docHash({ doc_id: docId }) {
          return `DocHash:{${docId}}`
        },
        projectKey({ doc_id: docId }) {
          return `ProjectId:{${docId}}`
        },
        docsInProject({ project_id: projectId }) {
          return `DocsIn:{${projectId}}`
        },
        ranges({ doc_id: docId }) {
          return `Ranges:{${docId}}`
        },
        unflushedTime({ doc_id: docId }) {
          return `UnflushedTime:{${docId}}`
        },
        pathname({ doc_id: docId }) {
          return `Pathname:{${docId}}`
        },
        projectHistoryId({ doc_id: docId }) {
          return `ProjectHistoryId:{${docId}}`
        },
        projectHistoryType({ doc_id: docId }) {
          return `ProjectHistoryType:{${docId}}`
        },
        projectState({ project_id: projectId }) {
          return `ProjectState:{${projectId}}`
        },
        pendingUpdates({ doc_id: docId }) {
          return `PendingUpdates:{${docId}}`
        },
        lastUpdatedBy({ doc_id: docId }) {
          return `lastUpdatedBy:{${docId}}`
        },
        lastUpdatedAt({ doc_id: docId }) {
          return `lastUpdatedAt:{${docId}}`
        },
        flushAndDeleteQueue() {
          return 'DocUpdaterFlushAndDeleteQueue'
        }
      }
    }
  },

  max_doc_length: 2 * 1024 * 1024, // 2mb
  maxJsonRequestSize:
    parseInt(process.env.MAX_JSON_REQUEST_SIZE, 10) || 8 * 1024 * 1024,

  dispatcherCount: parseInt(process.env.DISPATCHER_COUNT || 10, 10)

  mongo: {
    options: {
      useUnifiedTopology:
        (process.env.MONGO_USE_UNIFIED_TOPOLOGY || 'true') === 'true'
    },
    url:
      process.env.MONGO_CONNECTION_STRING ||
      `mongodb://${process.env.MONGO_HOST || '127.0.0.1'}/sharelatex`
  },

  sentry: {
    dsn: process.env.SENTRY_DSN
  },

  publishOnIndividualChannels:
    process.env.PUBLISH_ON_INDIVIDUAL_CHANNELS || false,

  continuousBackgroundFlush: process.env.CONTINUOUS_BACKGROUND_FLUSH || false,

  smoothingOffset: process.env.SMOOTHING_OFFSET || 1000, // milliseconds

  disableDoubleFlush: process.env.DISABLE_DOUBLE_FLUSH || false // don't flush track-changes for projects using project-history
}
<commit_msg>add missing comma in settings file<commit_after>const http = require('http')
http.globalAgent.maxSockets = 300

module.exports = {
  internal: {
    documentupdater: {
      host: process.env.LISTEN_ADDRESS || 'localhost',
      port: 3003
    }
  },

  apis: {
    web: {
      url: `http://${
        process.env.WEB_API_HOST || process.env.WEB_HOST || 'localhost'
      }:${process.env.WEB_API_PORT || process.env.WEB_PORT || 3000}`,
      user: process.env.WEB_API_USER || 'sharelatex',
      pass: process.env.WEB_API_PASSWORD || 'password'
    },
    trackchanges: {
      url: `http://${process.env.TRACK_CHANGES_HOST || 'localhost'}:3015`
    },
    project_history: {
      enabled: true,
      url: `http://${process.env.PROJECT_HISTORY_HOST || 'localhost'}:3054`
    }
  },

  redis: {
    pubsub: {
      host:
        process.env.PUBSUB_REDIS_HOST || process.env.REDIS_HOST || 'localhost',
      port: process.env.PUBSUB_REDIS_PORT || process.env.REDIS_PORT || '6379',
      password:
        process.env.PUBSUB_REDIS_PASSWORD || process.env.REDIS_PASSWORD || '',
      maxRetriesPerRequest: parseInt(
        process.env.REDIS_MAX_RETRIES_PER_REQUEST || '20'
      )
    },

    history: {
      port: process.env.HISTORY_REDIS_PORT || process.env.REDIS_PORT || '6379',
      host:
        process.env.HISTORY_REDIS_HOST || process.env.REDIS_HOST || 'localhost',
      password:
        process.env.HISTORY_REDIS_PASSWORD || process.env.REDIS_PASSWORD || '',
      maxRetriesPerRequest: parseInt(
        process.env.REDIS_MAX_RETRIES_PER_REQUEST || '20'
      ),
      key_schema: {
        uncompressedHistoryOps({ doc_id: docId }) {
          return `UncompressedHistoryOps:{${docId}}`
        },
        docsWithHistoryOps({ project_id: projectId }) {
          return `DocsWithHistoryOps:{${projectId}}`
        }
      }
    },

    project_history: {
      port:
        process.env.NEW_HISTORY_REDIS_PORT || process.env.REDIS_PORT || '6379',
      host:
        process.env.NEW_HISTORY_REDIS_HOST ||
        process.env.REDIS_HOST ||
        'localhost',
      password:
        process.env.NEW_HISTORY_REDIS_PASSWORD ||
        process.env.REDIS_PASSWORD ||
        '',
      maxRetriesPerRequest: parseInt(
        process.env.REDIS_MAX_RETRIES_PER_REQUEST || '20'
      ),
      key_schema: {
        projectHistoryOps({ project_id: projectId }) {
          return `ProjectHistory:Ops:{${projectId}}`
        },
        projectHistoryFirstOpTimestamp({ project_id: projectId }) {
          return `ProjectHistory:FirstOpTimestamp:{${projectId}}`
        }
      }
    },

    lock: {
      port: process.env.LOCK_REDIS_PORT || process.env.REDIS_PORT || '6379',
      host:
        process.env.LOCK_REDIS_HOST || process.env.REDIS_HOST || 'localhost',
      password:
        process.env.LOCK_REDIS_PASSWORD || process.env.REDIS_PASSWORD || '',
      maxRetriesPerRequest: parseInt(
        process.env.REDIS_MAX_RETRIES_PER_REQUEST || '20'
      ),
      key_schema: {
        blockingKey({ doc_id: docId }) {
          return `Blocking:{${docId}}`
        }
      }
    },

    documentupdater: {
      port:
        process.env.DOC_UPDATER_REDIS_PORT || process.env.REDIS_PORT || '6379',
      host:
        process.env.DOC_UPDATER_REDIS_HOST ||
        process.env.REDIS_HOST ||
        'localhost',
      password:
        process.env.DOC_UPDATER_REDIS_PASSWORD ||
        process.env.REDIS_PASSWORD ||
        '',
      maxRetriesPerRequest: parseInt(
        process.env.REDIS_MAX_RETRIES_PER_REQUEST || '20'
      ),
      key_schema: {
        blockingKey({ doc_id: docId }) {
          return `Blocking:{${docId}}`
        },
        docLines({ doc_id: docId }) {
          return `doclines:{${docId}}`
        },
        docOps({ doc_id: docId }) {
          return `DocOps:{${docId}}`
        },
        docVersion({ doc_id: docId }) {
          return `DocVersion:{${docId}}`
        },
        docHash({ doc_id: docId }) {
          return `DocHash:{${docId}}`
        },
        projectKey({ doc_id: docId }) {
          return `ProjectId:{${docId}}`
        },
        docsInProject({ project_id: projectId }) {
          return `DocsIn:{${projectId}}`
        },
        ranges({ doc_id: docId }) {
          return `Ranges:{${docId}}`
        },
        unflushedTime({ doc_id: docId }) {
          return `UnflushedTime:{${docId}}`
        },
        pathname({ doc_id: docId }) {
          return `Pathname:{${docId}}`
        },
        projectHistoryId({ doc_id: docId }) {
          return `ProjectHistoryId:{${docId}}`
        },
        projectHistoryType({ doc_id: docId }) {
          return `ProjectHistoryType:{${docId}}`
        },
        projectState({ project_id: projectId }) {
          return `ProjectState:{${projectId}}`
        },
        pendingUpdates({ doc_id: docId }) {
          return `PendingUpdates:{${docId}}`
        },
        lastUpdatedBy({ doc_id: docId }) {
          return `lastUpdatedBy:{${docId}}`
        },
        lastUpdatedAt({ doc_id: docId }) {
          return `lastUpdatedAt:{${docId}}`
        },
        flushAndDeleteQueue() {
          return 'DocUpdaterFlushAndDeleteQueue'
        }
      }
    }
  },

  max_doc_length: 2 * 1024 * 1024, // 2mb
  maxJsonRequestSize:
    parseInt(process.env.MAX_JSON_REQUEST_SIZE, 10) || 8 * 1024 * 1024,

  dispatcherCount: parseInt(process.env.DISPATCHER_COUNT || 10, 10),

  mongo: {
    options: {
      useUnifiedTopology:
        (process.env.MONGO_USE_UNIFIED_TOPOLOGY || 'true') === 'true'
    },
    url:
      process.env.MONGO_CONNECTION_STRING ||
      `mongodb://${process.env.MONGO_HOST || '127.0.0.1'}/sharelatex`
  },

  sentry: {
    dsn: process.env.SENTRY_DSN
  },

  publishOnIndividualChannels:
    process.env.PUBLISH_ON_INDIVIDUAL_CHANNELS || false,

  continuousBackgroundFlush: process.env.CONTINUOUS_BACKGROUND_FLUSH || false,

  smoothingOffset: process.env.SMOOTHING_OFFSET || 1000, // milliseconds

  disableDoubleFlush: process.env.DISABLE_DOUBLE_FLUSH || false // don't flush track-changes for projects using project-history
}
<|endoftext|>


<commit_before>
var checkRating = function () { };

$(document).ready(function () {
    var $form = $('#form-rating');

    if ($form.length == 0) return;

    var timeStep = 0.05;

    var shieldWeapon = function (shield, aggregate)
    {
        if (shield.HitPoints > 0) {
            var hp = shield.HitPoints;
            shield.HitPoints -= aggregate.Physical / shield.Physical_DamageAbsorbDirect;
            shield.HitPoints -= aggregate.Energy / shield.Energy_DamageAbsorbDirect;
            shield.HitPoints -= aggregate.Distortion / shield.Distortion_DamageAbsorbDirect;

            if (shield.HitPoints < 0) {
                var ratio = shield.HitPoints / (shield.HitPoints - hp);

                aggregate.Physical   = aggregate.Physical * ratio * shield.Physical_DamageAbsorbDirect;
                aggregate.Energy     = aggregate.Energy * ratio * shield.Energy_DamageAbsorbDirect;
                aggregate.Distortion = aggregate.Distortion * ratio * shield.Distortion_DamageAbsorbDirect;

                shield.HitPoints = 0;
            } else {
                aggregate.Physical = 0;
                aggregate.Energy = 0;
                aggregate.Distortion = 0;
            }
        }

        return aggregate;
    }

    var fireWeapon = function(weapon, aggregate)
    {
        if (weapon.Heat + weapon.HeatingRate < weapon.MaxHeat) {
            weapon.ShotsFired++;
            weapon.Heat += weapon.HeatingRate;

            aggregate.Physical += weapon.Physical;
            aggregate.Energy += weapon.Energy;
            aggregate.Distortion += weapon.Distortion;
        }

        return aggregate;
    }

    var attack = function(source, target, time, min_max)
    {
        if (target.Health <= 0)
            return;

        var aggregate = {
            Physical: 0,
            Energy: 0,
            Distortion: 0,
        };

        if (time > 0) {
            for (var i = 0, j = source.Damage.length; i < j; i++) {
                aggregate = {
                    Physical: 0,
                    Energy: 0,
                    Distortion: 0,
                };

                if (source.Damage[i].ShotsFired == null)
                    source.Damage[i].ShotsFired = 0;

                if (source.Damage[i].ShotsChecked == null)
                    source.Damage[i].ShotsChecked = 0;

                if (source.Damage[i].Heat == null)
                    source.Damage[i].Heat = 0;

                source.Damage[i].Heat = Math.max(0, source.Damage[i].Heat - source.Damage[i].CoolingRate * timeStep);

                console.log(source.Damage[i].ShotsChecked, time, source.Damage[i].Rate / 60);

                while (source.Damage[i].ShotsChecked < (time * source.Damage[i].Rate / 60)) {
                    source.Damage[i].ShotsChecked++;
                    fireWeapon(source.Damage[i], aggregate);
                }
            }
        }

        // if (min_max == "min") {
        //     console.log('Shield', source.DisplayName, source.Damage.length, 'Guns', (aggregate.Physical + aggregate.Energy + aggregate.Distortion), 'Damage', target.Shield, target.Health);
        // }

        target.Shield = 0;

        if (target.Shields != null && target.Shields.length > 0) {
            for (var i = 0, j = target.Shields.length; i < j; i++) {
                if (target.Shields[i].HitPoints == null) {
                    if (min_max == "min") {
                        switch (target.Shields[i].FaceType)
                        {
                            case "Quadrant":
                                target.Shields[i].HitPoints = target.Shields[i].MaxHitPoints / 4;
                                break;
                            case "FrontBack":
                                target.Shields[i].HitPoints = target.Shields[i].MaxHitPoints / 2;
                                break;
                            default:
                                target.Shields[i].HitPoints = target.Shields[i].MaxHitPoints;
                                break;
                        }
                    } else {
                        target.Shields[i].HitPoints = target.Shields[i].MaxHitPoints;
                    }
                }

                // if (target.Shields[i].HitPoints < target.Shields[i].MaxHitPoints)
                //     target.Shields[i].HitPoints = Math.min(target.Shields[i].MaxHitPoints, target.Shields[i].HitPoints + target.Shields[i].MaxRegenRate);

                shieldWeapon(target.Shields[i], aggregate);

                target.Shield += target.Shields[i].HitPoints;
            }
        }

        // console.log('Armor', source.DisplayName, source.Damage.length, 'Guns', (aggregate.Physical + aggregate.Energy + aggregate.Distortion), 'Damage');

        if (target.Armor != null) {
            aggregate.Physical = aggregate.Physical * target.Armor.Physical;
            aggregate.Energy = aggregate.Energy * target.Armor.Energy;
            aggregate.Distortion = aggregate.Distortion * target.Armor.Distortion;
        }

        if (time > 0) {
            target.Health -= aggregate.Physical;
            target.Health -= aggregate.Energy;
            target.Health -= aggregate.Distortion;

            if (target.Health < 0 && target.TTK == null)
            {
                target.TTK = time;
                target.Health = Math.max(0, target.Health);
            }
        }
    }

    checkRating = function () {
        $.ajax({
            url: $form[0].action,
            method: 'POST',
            data: { targetShip: $('#cig-rating').val() },
            // data: { targetShip: 'AEGS_Retaliator' },
            dataType: 'json',
            success: function (data) {
                rating = data;

                var maxSelf1 = $.extend(true, { Health: data.Self.MaxHealth }, data.Self);
                var minSelf1 = $.extend(true, { Health: data.Self.MinHealth }, data.Self);
                var maxEnemy1 = $.extend(true, { Health: data.Enemy.MaxHealth }, data.Enemy);
                var minEnemy1 = $.extend(true, { Health: data.Enemy.MinHealth }, data.Enemy);

                var maxSelf2 = $.extend(true, { Health: data.Self.MaxHealth }, data.Self);
                var minSelf2 = $.extend(true, { Health: data.Self.MinHealth }, data.Self);
                var maxEnemy2 = $.extend(true, { Health: data.Enemy.MaxHealth }, data.Enemy);
                var minEnemy2 = $.extend(true, { Health: data.Enemy.MinHealth }, data.Enemy);

                var time = 0;
                var raw = []; // { self: self.Health, enemy: enemy.Health, time: time }];

                while ((maxSelf2.Health > 0 || maxEnemy2.Health > 0) && (time < 1800)) {
                    attack(maxSelf1, maxEnemy2, time);
                    attack(maxEnemy1, maxSelf2, time);

                    attack(minSelf1, minEnemy2, time, "min");
                    attack(minEnemy1, minSelf2, time, "min");

                    raw.push({
                        maxSelf: maxSelf2.Health + maxSelf2.Shield,
                        maxEnemy: maxEnemy2.Health + maxEnemy2.Shield,
                        minSelf: minSelf2.Health + minSelf2.Shield,
                        minEnemy: minEnemy2.Health + minEnemy2.Shield,
                        time: time
                    });

                    time += timeStep;
                }

                console.log(maxSelf2, maxEnemy2, minSelf2, minEnemy2);

                var margin = { top: 10, right: 10, bottom: 10, left: 10 },
                    width = 650,
                    height = 200;

                var color = d3.scale.category10();

                var x = d3.scale.linear().range([0, width]).domain([0, d3.max(raw, function(d) { return d.time })]);
                var y = d3.scale.linear().range([0, height]).domain([Math.max(d3.max(raw, function (d) { return d.maxSelf }), d3.max(raw, function (d) { return d.maxEnemy })), 0]);

                var xAxis = d3.svg.axis()
                    .scale(x)
                    .orient("bottom");

                var maxhealth_self = d3.svg.line()
                    .interpolate("monotone")
                    .x(function (d) { return x(d.time); })
                    .y(function (d) { return y(d.maxSelf); });

                var minhealth_self = d3.svg.line()
                    .interpolate("monotone")
                    .x(function (d) { return x(d.time); })
                    .y(function (d) { return y(d.minSelf); });

                var maxhealth_enemy = d3.svg.line()
                    .interpolate("monotone")
                    .x(function (d) { return x(d.time); })
                    .y(function (d) { return y(d.maxEnemy); });

                var minhealth_enemy = d3.svg.line()
                    .interpolate("monotone")
                    .x(function (d) { return x(d.time); })
                    .y(function (d) { return y(d.minEnemy); });

                $('#rating').empty();

                var svg = d3.select('#rating').append("svg")
                    .attr("viewbox", "0 0 " + (width + margin.left + margin.right) + " " + (height + margin.top + margin.bottom))
                    .attr("preserveAspectRatio", "xMidYMid meet")
                    .append("g")
                    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

                var graph = svg.selectAll(".graph")
                    .data([raw])
                    .enter().append("g")
                    .attr("class", "graph");

                graph.append("path")
                    .attr("class", "max-self")
                    .attr("d", function (d) { return maxhealth_self(d); })
                    .style("fill", "none");

                graph.append("path")
                    .attr("class", "min-self")
                    .attr("d", function (d) { return minhealth_self(d); })
                    .style("fill", "none");

                graph.append("path")
                    .attr("class", "max-enemy")
                    .attr("d", function (d) { return maxhealth_enemy(d); })
                    .style("fill", "none");

                graph.append("path")
                    .attr("class", "min-enemy")
                    .attr("d", function (d) { return minhealth_enemy(d); })
                    .style("fill", "none");

                // Hack for Chrome
                var $rating = $('#rating');
                $rating.html($rating.html());
            }
        });
    };

    checkRating();

    $("a[href='#specs']").on('shown.bs.tab', checkRating);
    // $('#cig-rating').on('change', checkRating);
});<commit_msg>TTK included<commit_after>
var checkRating = function () { };

$(document).ready(function () {
    var $form = $('#form-rating');

    if ($form.length == 0) return;

    var timeStep = 0.05;

    var shieldWeapon = function (shield, aggregate)
    {
        if (shield.HitPoints > 0) {
            var hp = shield.HitPoints;
            shield.HitPoints -= aggregate.Physical / shield.Physical_DamageAbsorbDirect;
            shield.HitPoints -= aggregate.Energy / shield.Energy_DamageAbsorbDirect;
            shield.HitPoints -= aggregate.Distortion / shield.Distortion_DamageAbsorbDirect;

            if (shield.HitPoints < 0) {
                var ratio = shield.HitPoints / (shield.HitPoints - hp);

                aggregate.Physical   = aggregate.Physical * ratio * shield.Physical_DamageAbsorbDirect;
                aggregate.Energy     = aggregate.Energy * ratio * shield.Energy_DamageAbsorbDirect;
                aggregate.Distortion = aggregate.Distortion * ratio * shield.Distortion_DamageAbsorbDirect;

                shield.HitPoints = 0;
            } else {
                aggregate.Physical = 0;
                aggregate.Energy = 0;
                aggregate.Distortion = 0;
            }
        }

        return aggregate;
    }

    var fireWeapon = function(weapon, aggregate)
    {
        if (weapon.Heat + weapon.HeatingRate < weapon.MaxHeat) {
            weapon.ShotsFired++;
            weapon.TotalDamage += weapon.Physical;
            weapon.TotalDamage += weapon.Energy;
            weapon.TotalDamage += weapon.Distortion;
            weapon.Heat += weapon.HeatingRate;

            aggregate.Physical += weapon.Physical;
            aggregate.Energy += weapon.Energy;
            aggregate.Distortion += weapon.Distortion;
        }

        return aggregate;
    }

    var attack = function(source, target, time, min_max)
    {
        if (target.Health <= -5)
            return;

        var aggregate = {
            Physical: 0,
            Energy: 0,
            Distortion: 0,
        };

        if (time > 0) {
            aggregate = {
                Physical: 0,
                Energy: 0,
                Distortion: 0,
            };

            for (var i = 0, j = source.Damage.length; i < j; i++) {
                if (source.Damage[i].ShotsFired == null)
                    source.Damage[i].ShotsFired = 0;

                if (source.Damage[i].TotalDamage == null)
                    source.Damage[i].TotalDamage = 0;

                if (source.Damage[i].ShotsChecked == null)
                    source.Damage[i].ShotsChecked = 0;

                if (source.Damage[i].Heat == null)
                    source.Damage[i].Heat = 0;

                source.Damage[i].Heat = Math.max(0, source.Damage[i].Heat - source.Damage[i].CoolingRate * timeStep);

                while (source.Damage[i].ShotsChecked < (time * source.Damage[i].Rate / 60)) {
                    source.Damage[i].ShotsChecked++;
                    fireWeapon(source.Damage[i], aggregate);
                }
            }
        }

        target.Shield = 0;

        if (target.Shields != null && target.Shields.length > 0) {
            for (var i = 0, j = target.Shields.length; i < j; i++) {
                if (target.Shields[i].HitPoints == null) {
                    if (min_max == "min") {
                        switch (target.Shields[i].FaceType)
                        {
                            case "Quadrant":
                                target.Shields[i].HitPoints = target.Shields[i].MaxHitPoints / 4;
                                break;
                            case "FrontBack":
                                target.Shields[i].HitPoints = target.Shields[i].MaxHitPoints / 2;
                                break;
                            default:
                                target.Shields[i].HitPoints = target.Shields[i].MaxHitPoints;
                                break;
                        }
                    } else {
                        target.Shields[i].HitPoints = target.Shields[i].MaxHitPoints;
                    }
                }

                shieldWeapon(target.Shields[i], aggregate);

                target.Shield += target.Shields[i].HitPoints;
            }
        }

        if (target.Armor != null) {
            aggregate.Physical = aggregate.Physical * target.Armor.Physical;
            aggregate.Energy = aggregate.Energy * target.Armor.Energy;
            aggregate.Distortion = aggregate.Distortion * target.Armor.Distortion;
        }

        if (time > 0) {
            target.Health -= aggregate.Physical;
            target.Health -= aggregate.Energy;
            target.Health -= aggregate.Distortion;

            if (target.Health < 0 && target.TTK == null)
            {
                target.TTK = time;
            }
            target.Health = Math.max(-5, target.Health);
        }
    }

    checkRating = function () {
        $.ajax({
            url: $form[0].action,
            method: 'POST',
            data: { targetShip: $('#cig-rating').val() },
            dataType: 'json',
            success: function (data) {
                rating = data;

                var maxSelf = $.extend(true, { Health: data.Self.MaxHealth }, data.Self);
                var minSelf = $.extend(true, { Health: data.Self.MinHealth }, data.Self);
                var maxEnemy = $.extend(true, { Health: data.Enemy.MaxHealth }, data.Enemy);
                var minEnemy = $.extend(true, { Health: data.Enemy.MinHealth }, data.Enemy);

                var time = 0;
                var raw = []; // { self: self.Health, enemy: enemy.Health, time: time }];

                while ((maxSelf.Health > 0 || maxEnemy.Health > 0) && (time < 1800)) {
                    attack(maxSelf, maxEnemy, time);
                    attack(maxEnemy, maxSelf, time);

                    attack(minSelf, minEnemy, time, "min");
                    attack(minEnemy, minSelf, time, "min");

                    raw.push({
                        maxSelf: maxSelf.Health + maxSelf.Shield,
                        maxEnemy: maxEnemy.Health + maxEnemy.Shield,
                        minSelf: minSelf.Health + minSelf.Shield,
                        minEnemy: minEnemy.Health + minEnemy.Shield,
                        time: time
                    });

                    time += timeStep;
                }

                var margin = { top: 10, right: 10, bottom: 10, left: 10 },
                    width = 650,
                    height = 150;

                var color = d3.scale.category10();

                var x = d3.scale.linear().range([0, width]).domain([0, d3.max(raw, function(d) { return d.time })]);
                var y = d3.scale.linear().range([0, height]).domain([Math.max(d3.max(raw, function (d) { return d.maxSelf }), d3.max(raw, function (d) { return d.maxEnemy })), 0]);

                var xAxis = d3.svg.axis()
                    .scale(x)
                    .orient("bottom");

                var maxhealth_self = d3.svg.line()
                    .interpolate("monotone")
                    .x(function (d) { return x(d.time); })
                    .y(function (d) { return y(d.maxSelf); });

                var minhealth_self = d3.svg.line()
                    .interpolate("monotone")
                    .x(function (d) { return x(d.time); })
                    .y(function (d) { return y(d.minSelf); });

                var maxhealth_enemy = d3.svg.line()
                    .interpolate("monotone")
                    .x(function (d) { return x(d.time); })
                    .y(function (d) { return y(d.maxEnemy); });

                var minhealth_enemy = d3.svg.line()
                    .interpolate("monotone")
                    .x(function (d) { return x(d.time); })
                    .y(function (d) { return y(d.minEnemy); });

                $('#rating').empty();

                var svg = d3.select('#rating').append("svg")
                    .attr("viewbox", "0 0 " + (width + margin.left + margin.right) + " " + (height + margin.top + margin.bottom))
                    .attr("preserveAspectRatio", "xMidYMid meet")
                    .append("g")
                    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

                var graph = svg.selectAll(".graph")
                    .data([raw])
                    .enter().append("g")
                    .attr("class", "graph");

                graph.append("path")
                    .attr("class", "max-self")
                    .attr("d", function (d) { return maxhealth_self(d); })
                    .style("fill", "none");

                graph.append("path")
                    .attr("class", "min-self")
                    .attr("d", function (d) { return minhealth_self(d); })
                    .style("fill", "none");

                graph.append("path")
                    .attr("class", "max-enemy")
                    .attr("d", function (d) { return maxhealth_enemy(d); })
                    .style("fill", "none");

                graph.append("path")
                    .attr("class", "min-enemy")
                    .attr("d", function (d) { return minhealth_enemy(d); })
                    .style("fill", "none");

                // Hack for Chrome
                var $rating = $('#rating');

                var $table = $('<table class="table table-borderless table-striped table-condensed cig-table cig-table-2">');

                $table.append('<tr><th></th><th>' + data.Self.DisplayName + '</th><th>' + data.Enemy.DisplayName + '</th></tr>');
                $table.append('<tr><th>Min TTK</th><td>' + minSelf.TTK.toFixed(2) + 's</td><td>' + minEnemy.TTK.toFixed(2) + 's</td></tr>');
                $table.append('<tr><th>Max TTK</th><td>' + maxSelf.TTK.toFixed(2) + 's</td><td>' + maxEnemy.TTK.toFixed(2) + 's</td></tr>');

                $rating.append($table);
                $rating.html($rating.html());
            }
        });
    };

    checkRating();

    $("a[href='#specs']").on('shown.bs.tab', checkRating);
    // $('#cig-rating').on('change', checkRating);
});<|endoftext|>


<commit_before>/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow strict-local
 * @format
 */

import type {ScrollViewNativeProps as Props} from './ScrollViewNativeComponentType';
import type {HostComponent} from '../../Renderer/shims/ReactNativeTypes';
import * as NativeComponentRegistry from '../../NativeComponent/NativeComponentRegistry';

const ScrollViewNativeComponent: HostComponent<Props> =
  NativeComponentRegistry.get<Props>('RCTScrollView', () => ({
    uiViewClassName: 'RCTScrollView',
    bubblingEventTypes: {},
    directEventTypes: {
      topScrollToTop: {
        registrationName: 'onScrollToTop',
      },
    },
    validAttributes: {
      alwaysBounceHorizontal: true,
      alwaysBounceVertical: true,
      automaticallyAdjustContentInsets: true,
      automaticallyAdjustKeyboardInsets: true,
      automaticallyAdjustsScrollIndicatorInsets: true,
      bounces: true,
      bouncesZoom: true,
      canCancelContentTouches: true,
      centerContent: true,
      contentInset: {
        diff: require('../../Utilities/differ/pointsDiffer'),
      },
      contentOffset: {
        diff: require('../../Utilities/differ/pointsDiffer'),
      },
      contentInsetAdjustmentBehavior: true,
      decelerationRate: true,
      directionalLockEnabled: true,
      disableIntervalMomentum: true,
      endFillColor: {
        process: require('../../StyleSheet/processColor'),
      },
      fadingEdgeLength: true,
      indicatorStyle: true,
      inverted: true,
      keyboardDismissMode: true,
      maintainVisibleContentPosition: true,
      maximumZoomScale: true,
      minimumZoomScale: true,
      nestedScrollEnabled: true,
      onMomentumScrollBegin: true,
      onMomentumScrollEnd: true,
      onScroll: true,
      onScrollBeginDrag: true,
      onScrollEndDrag: true,
      onScrollToTop: true,
      overScrollMode: true,
      pagingEnabled: true,
      persistentScrollbar: true,
      pinchGestureEnabled: true,
      scrollEnabled: true,
      scrollEventThrottle: true,
      scrollIndicatorInsets: {
        diff: require('../../Utilities/differ/pointsDiffer'),
      },
      scrollPerfTag: true,
      scrollToOverflowEnabled: true,
      scrollsToTop: true,
      sendMomentumEvents: true,
      showsHorizontalScrollIndicator: true,
      showsVerticalScrollIndicator: true,
      snapToAlignment: true,
      snapToEnd: true,
      snapToInterval: true,
      snapToOffsets: true,
      snapToStart: true,
      zoomScale: true,
    },
  }));

export default ScrollViewNativeComponent;
<commit_msg>Fix SVC for RCTScrollView<commit_after>/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow strict-local
 * @format
 */

import type {ScrollViewNativeProps as Props} from './ScrollViewNativeComponentType';
import type {HostComponent} from '../../Renderer/shims/ReactNativeTypes';
import * as NativeComponentRegistry from '../../NativeComponent/NativeComponentRegistry';
import Platform from '../../Utilities/Platform';

const RCTScrollViewViewConfig =
  Platform.OS === 'android'
    ? {
        uiViewClassName: 'RCTScrollView',
        bubblingEventTypes: {},
        directEventTypes: {
          topMomentumScrollBegin: {
            registrationName: 'onMomentumScrollBegin',
          },
          topMomentumScrollEnd: {
            registrationName: 'onMomentumScrollEnd',
          },
          topScroll: {
            registrationName: 'onScroll',
          },
          topScrollBeginDrag: {
            registrationName: 'onScrollBeginDrag',
          },
          topScrollEndDrag: {
            registrationName: 'onScrollEndDrag',
          },
        },
        validAttributes: {
          contentOffset: {
            diff: require('../../Utilities/differ/pointsDiffer'),
          },
          decelerationRate: true,
          disableIntervalMomentum: true,
          pagingEnabled: true,
          scrollEnabled: true,
          showsVerticalScrollIndicator: true,
          snapToAlignment: true,
          snapToEnd: true,
          snapToInterval: true,
          snapToOffsets: true,
          snapToStart: true,
          borderBottomLeftRadius: true,
          borderBottomRightRadius: true,
          sendMomentumEvents: true,
          borderRadius: true,
          nestedScrollEnabled: true,
          borderStyle: true,
          borderRightColor: {process: require('../../StyleSheet/processColor')},
          borderColor: {process: require('../../StyleSheet/processColor')},
          borderBottomColor: {
            process: require('../../StyleSheet/processColor'),
          },
          persistentScrollbar: true,
          endFillColor: {process: require('../../StyleSheet/processColor')},
          fadingEdgeLength: true,
          overScrollMode: true,
          borderTopLeftRadius: true,
          scrollPerfTag: true,
          borderTopColor: {process: require('../../StyleSheet/processColor')},
          removeClippedSubviews: true,
          borderTopRightRadius: true,
          borderLeftColor: {process: require('../../StyleSheet/processColor')},
        },
      }
    : {
        uiViewClassName: 'RCTScrollView',
        bubblingEventTypes: {},
        directEventTypes: {
          topMomentumScrollBegin: {
            registrationName: 'onMomentumScrollBegin',
          },
          topMomentumScrollEnd: {
            registrationName: 'onMomentumScrollEnd',
          },
          topScroll: {
            registrationName: 'onScroll',
          },
          topScrollBeginDrag: {
            registrationName: 'onScrollBeginDrag',
          },
          topScrollEndDrag: {
            registrationName: 'onScrollEndDrag',
          },
          topScrollToTop: {
            registrationName: 'onScrollToTop',
          },
        },
        validAttributes: {
          alwaysBounceHorizontal: true,
          alwaysBounceVertical: true,
          automaticallyAdjustContentInsets: true,
          automaticallyAdjustKeyboardInsets: true,
          automaticallyAdjustsScrollIndicatorInsets: true,
          bounces: true,
          bouncesZoom: true,
          canCancelContentTouches: true,
          centerContent: true,
          contentInset: {
            diff: require('../../Utilities/differ/insetsDiffer'),
          },
          contentOffset: {
            diff: require('../../Utilities/differ/pointsDiffer'),
          },
          contentInsetAdjustmentBehavior: true,
          decelerationRate: true,
          directionalLockEnabled: true,
          disableIntervalMomentum: true,
          indicatorStyle: true,
          inverted: true,
          keyboardDismissMode: true,
          maintainVisibleContentPosition: true,
          maximumZoomScale: true,
          minimumZoomScale: true,
          pagingEnabled: true,
          pinchGestureEnabled: true,
          scrollEnabled: true,
          scrollEventThrottle: true,
          scrollIndicatorInsets: {
            diff: require('../../Utilities/differ/insetsDiffer'),
          },
          scrollToOverflowEnabled: true,
          scrollsToTop: true,
          showsHorizontalScrollIndicator: true,
          showsVerticalScrollIndicator: true,
          snapToAlignment: true,
          snapToEnd: true,
          snapToInterval: true,
          snapToOffsets: true,
          snapToStart: true,
          zoomScale: true,
        },
      };

const ScrollViewNativeComponent: HostComponent<Props> =
  NativeComponentRegistry.get<Props>(
    'RCTScrollView',
    () => RCTScrollViewViewConfig,
  );

export default ScrollViewNativeComponent;
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {withRouter} from "react-router-dom"
import { I18n } from 'react-i18next';

import BottomNavTile from "./bottom-nav-bar-tile"
import {nav} from "./_nav"
import "./bottom-nav-bar.scss"

class BottomNavBar extends Component {

  static propTypes = {
    auth: PropTypes.object.isRequired,
    selectedProject: PropTypes.object,
  };

  activeRoute = (routeName, pathIncludes)  =>{
    if(pathIncludes) {
      return this.props.location.pathname.includes(pathIncludes);
    }else{
      return this.props.location.pathname === routeName;
    }
  };

  render() {
    const {auth, selectedProject} = this.props;
    const projectUrl = this.props.selectedProject? this.props.selectedProject.url : null;
    const routes = nav(auth, projectUrl);

    return (
      <I18n ns='translations'>
        {
          (t, {i18n}) => (

                {routes.map(r => (<BottomNavTile key={r.path} icon={r.icon} path={r.path} active={this.activeRoute(r.path, r.pathIncludes)}/>))}

          )
        }
      </I18n>
    );
  }
}

export default withRouter(BottomNavBar);
<commit_msg>Fixed warnings<commit_after>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {withRouter} from "react-router-dom"
import { I18n } from 'react-i18next';

import BottomNavTile from "./bottom-nav-bar-tile"
import {nav} from "./_nav"
import "./bottom-nav-bar.scss"

class BottomNavBar extends Component {

  static propTypes = {
    auth: PropTypes.object.isRequired,
    selectedProject: PropTypes.object,
  };

  activeRoute = (routeName, pathIncludes)  =>{
    if(pathIncludes) {
      return this.props.location.pathname.includes(pathIncludes);
    }else{
      return this.props.location.pathname === routeName;
    }
  };

  render() {
    const {auth, selectedProject} = this.props;
    const projectUrl = selectedProject? selectedProject.url : null;
    const routes = nav(auth, projectUrl);

    return (
      <I18n ns='translations'>
        {
          (t, {i18n}) => (

                {routes.map(r => (<BottomNavTile key={r.path} icon={r.icon} path={r.path} active={this.activeRoute(r.path, r.pathIncludes)}/>))}

          )
        }
      </I18n>
    );
  }
}

export default withRouter(BottomNavBar);
<|endoftext|>


<commit_before>require("ember-data/system/model/model");

/**
  @module ember-data
*/

var get = Ember.get;

/**
  @class Model
  @namespace DS
*/
DS.Model.reopenClass({
  attributes: Ember.computed(function() {
    var map = Ember.Map.create();

    this.eachComputedProperty(function(name, meta) {
      if (meta.isAttribute) {
        Ember.assert("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('<type>')` from " + this.toString(), name !== 'id');

        meta.name = name;
        map.set(name, meta);
      }
    });

    return map;
  }),

  transformedAttributes: Ember.computed(function() {
    var map = Ember.Map.create();

    this.eachAttribute(function(key, meta) {
      if (meta.type) {
        map.set(key, meta.type);
      }
    });

    return map;
  }),

  eachAttribute: function(callback, binding) {
    get(this, 'attributes').forEach(function(name, meta) {
      callback.call(binding, name, meta);
    }, binding);
  },

  eachTransformedAttribute: function(callback, binding) {
    get(this, 'transformedAttributes').forEach(function(name, type) {
      callback.call(binding, name, type);
    });
  }
});

DS.Model.reopen({
  eachAttribute: function(callback, binding) {
    this.constructor.eachAttribute(callback, binding);
  }
});

function getDefaultValue(record, options, key) {
  if (typeof options.defaultValue === "function") {
    return options.defaultValue();
  } else {
    return options.defaultValue;
  }
}

function hasValue(record, key) {
  return record._attributes.hasOwnProperty(key) ||
         record._inFlightAttributes.hasOwnProperty(key) ||
         record._data.hasOwnProperty(key);
}

function getValue(record, key) {
  if (record._attributes.hasOwnProperty(key)) {
    return record._attributes[key];
  } else if (record._inFlightAttributes.hasOwnProperty(key)) {
    return record._inFlightAttributes[key];
  } else {
    return record._data[key];
  }
}

DS.attr = function(type, options) {
  options = options || {};

  var meta = {
    type: type,
    isAttribute: true,
    options: options
  };

  return Ember.computed(function(key, value, oldValue) {
    var currentValue;

    if (arguments.length > 1) {
      Ember.assert("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('<type>')` from " + this.constructor.toString(), key !== 'id');
      this.send('didSetProperty', { name: key, oldValue: this._attributes[key] || this._inFlightAttributes[key] || this._data[key], value: value });
      this._attributes[key] = value;
      return value;
    } else if (hasValue(this, key)) {
      return getValue(this, key);
    } else {
      return getDefaultValue(this, options, key);
    }

  // `data` is never set directly. However, it may be
  // invalidated from the state manager's setData
  // event.
  }).property('data').meta(meta);
};

<commit_msg>DS.attr doc<commit_after>require("ember-data/system/model/model");

/**
  @module ember-data
*/

var get = Ember.get;

/**
  @class Model
  @namespace DS
*/
DS.Model.reopenClass({
  attributes: Ember.computed(function() {
    var map = Ember.Map.create();

    this.eachComputedProperty(function(name, meta) {
      if (meta.isAttribute) {
        Ember.assert("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('<type>')` from " + this.toString(), name !== 'id');

        meta.name = name;
        map.set(name, meta);
      }
    });

    return map;
  }),

  transformedAttributes: Ember.computed(function() {
    var map = Ember.Map.create();

    this.eachAttribute(function(key, meta) {
      if (meta.type) {
        map.set(key, meta.type);
      }
    });

    return map;
  }),

  eachAttribute: function(callback, binding) {
    get(this, 'attributes').forEach(function(name, meta) {
      callback.call(binding, name, meta);
    }, binding);
  },

  eachTransformedAttribute: function(callback, binding) {
    get(this, 'transformedAttributes').forEach(function(name, type) {
      callback.call(binding, name, type);
    });
  }
});

DS.Model.reopen({
  eachAttribute: function(callback, binding) {
    this.constructor.eachAttribute(callback, binding);
  }
});

function getDefaultValue(record, options, key) {
  if (typeof options.defaultValue === "function") {
    return options.defaultValue();
  } else {
    return options.defaultValue;
  }
}

function hasValue(record, key) {
  return record._attributes.hasOwnProperty(key) ||
         record._inFlightAttributes.hasOwnProperty(key) ||
         record._data.hasOwnProperty(key);
}

function getValue(record, key) {
  if (record._attributes.hasOwnProperty(key)) {
    return record._attributes[key];
  } else if (record._inFlightAttributes.hasOwnProperty(key)) {
    return record._inFlightAttributes[key];
  } else {
    return record._data[key];
  }
}

/**
  `DS.attr` defines an attribute on a DS.Model.
  By default, attributes are passed through as-is, however you can specify an
  optional type to have the value automatically transformed.
  Ember Data ships with four basic transform types:
    'string', 'number', 'boolean' and 'date'.
  You can define your own transforms by subclassing DS.Transform.

  DS.attr takes an optional hash as a second parameter, currently
  supported options are:
    'defaultValue': Pass a string or a function to be called to set the attribute
                    to a default value if none is supplied.

  @method attr
  @param {String} type the attribute type
  @param {Object} options a hash of options
*/

DS.attr = function(type, options) {
  options = options || {};

  var meta = {
    type: type,
    isAttribute: true,
    options: options
  };

  return Ember.computed(function(key, value, oldValue) {
    var currentValue;

    if (arguments.length > 1) {
      Ember.assert("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('<type>')` from " + this.constructor.toString(), key !== 'id');
      this.send('didSetProperty', { name: key, oldValue: this._attributes[key] || this._inFlightAttributes[key] || this._data[key], value: value });
      this._attributes[key] = value;
      return value;
    } else if (hasValue(this, key)) {
      return getValue(this, key);
    } else {
      return getDefaultValue(this, options, key);
    }

  // `data` is never set directly. However, it may be
  // invalidated from the state manager's setData
  // event.
  }).property('data').meta(meta);
};

<|endoftext|>