<commit_before>;(function(win, undef) {
    function Loader(options){
        options = options || {};

        this.init();
        this.disableTextInjection = options.disableTextInjection;
        this.CORS = options.CORS;
        this.build = this.get('build_id');
        if(this.disableTextInjection || !this.build || this.build < this.expiredTimestamp ){
            this.build = +new Date();
            this.clearAll();
            this.set('build_id', this.build);
        }
    }

    Loader.prototype.init = function(){
        this.head = document.head || document.getElementsByTagName('head')[0];
        this.defaultExpiration = 1; //hours
        this.expiredTimestamp = +new Date() - this.defaultExpiration * 60 * 60 * 1000;
    };

    Loader.prototype.promise = (function() {
        function k() {
            this._callbacks = []
        }

        function l(b, c, a) {
            var e = new k;
            0 === b.length ? e.done(c, a) : b[0](c, a).then(function(a, c) {
                b.splice(0, 1);
                l(b, a, c).then(function(a, b) {
                    e.done(a, b)
                })
            });
            return e
        }

        function n(b, c, a, e) {
            function j() {
                f.abort();
                g.done(this.promise.ETIMEOUT, "")
            }
            var g = new k,
                f, d;
            a = a || {};
            e = e || {};
            try {
                var h;
                if (win.XMLHttpRequest) h = new XMLHttpRequest;
                else if (win.ActiveXObject) try {
                    h = new ActiveXObject("Msxml2.XMLHTTP")
                } catch (m) {
                    h = new ActiveXObject("Microsoft.XMLHTTP")
                }
                f = h
            } catch (p) {
                return g.done(-1, ""), g
            }
            h = "";
            if ("string" === typeof a) h = a;
            else {
                var l = encodeURIComponent;
                for (d in a) a.hasOwnProperty(d) && (h += "&" + l(d) + "=" + l(a[d]))
            }
            d = h;
            "GET" === b && d && (c += "?" + d, d = null);
            f.open(b, c);
            f.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            for (var q in e) e.hasOwnProperty(q) && f.setRequestHeader(q, e[q]);
            var r = this.ajaxTimeout;
            if (r) var n = setTimeout(j, r);
            f.onreadystatechange = function() {
                r && clearTimeout(n);
                4 === f.readyState && (200 === f.status ? g.done(null, f.responseText) : g.done(f.status, f.responseText))
            };
            f.send(d);
            return g
        }

        function j(b) {
            return function(c, a, e) {
                return n(b, c, a, e)
            }
        }
        k.prototype.then = function(b, c) {
            var a;
            a = function() {
                return b.apply(c, arguments)
            };
            this._isdone ? a(this.error, this.result) : this._callbacks.push(a)
        };
        k.prototype.done = function(b, c) {
            this._isdone = !0;
            this.error = b;
            this.result = c;
            for (var a = 0; a < this._callbacks.length; a++) this._callbacks[a](b, c);
            this._callbacks = []
        };
        var p = {
            get: j("GET"),
            post: j("POST"),
            put: j("PUT"),
            del: j("DELETE"),
            Promise: k,
            join: function(b) {
                function c(b) {
                    return function(c, d) {
                        e += 1;
                        g[b] = c;
                        f[b] = d;
                        e === a && j.done(g, f)
                    }
                }
                for (var a = b.length, e = 0, j = new k, g = [], f = [], d = 0; d < a; d++)
                    b[d]().then(c(d));
                return j;
            },
            chain: l,
            ajax: n,
            ENOXHR: 1,
            ETIMEOUT: 2,
            ajaxTimeout: 5000
        }, m;
        for (m in p) p.hasOwnProperty(m) && (this[m] = p[m]);
        return this;
    })();

    Loader.prototype.set = function(key, data) {
        try {
            localStorage.setItem(key, JSON.stringify(data));
            return true;
        } catch (e) {
            for(var i in localStorage){
                console.log(localStorage[i])
            }
            if (e.name === "QUOTA_EXCEEDED_ERR") {
                console.log("Oh no! We ran out of room!");
                this.clearAll();
            }
            return false;
        }
    };

    Loader.prototype.get = function(key) {
        var data = JSON.parse(localStorage.getItem(key) || 'false');
        return data;
    };

    Loader.prototype.clear = function(key) {
        if (!localStorage) return;
        this.remove(key);
    };

    Loader.prototype.clearAll = function(){
        for (key in localStorage) {
            this.clear(key);
        }
    };

    Loader.prototype.remove = function(key) {
        localStorage.removeItem(key);
        return this;
    };

    Loader.prototype.addExpiration = function(obj) {
        var now = +new Date();
        obj.stamp = now;
    };

    Loader.prototype.isJS = function(url){
        var isJS = url.indexOf('.js') != -1;
        return isJS;
    };

    Loader.prototype.isCSS = function(url) {
        var isCSS = url.indexOf('.css') != -1;
        return isCSS;
    };

    Loader.prototype.injectScriptTagByText = function(text) {
        var script = document.createElement('script');
        script.text = text;
        this.head.appendChild(this.createFragAndAddChild(script));
    };

    Loader.prototype.injectStyleTagByText = function(text) {
        var style = document.createElement('style');
        style.textContent = text;
        this.head.appendChild(this.createFragAndAddChild(style));
    };

    Loader.prototype.injectScriptTagBySrc = function(url, promise) {
        var script = document.createElement('script');
        script.src = url;
        script.onload = script.onreadystatechange = function() {
            promise.done();
        };
        this.head.appendChild(this.createFragAndAddChild(script));
    };

    Loader.prototype.createFragAndAddChild = function(child){
        var frag = document.createDocumentFragment();
        frag.appendChild(child);
        return frag;
    }

    Loader.prototype.injectStyleTagBySrc = function(url) {
        var style = document.createElement('link');
        style.href = url;
        style.rel = "stylesheet";
        this.head.appendChild(this.createFragAndAddChild(style));
    };

    Loader.prototype.replaceRelativeURLWithFullURL = function(segments, url_fragment, text) {
        if (segments.length > 1) {
            return text.replace(segments[0], 'url(' + url_fragment + '/..' + segments[1] + ')');
        }
        return text;
    };

    Loader.prototype.replaceURLs = function(url, text) {
        var regex = /url\(\s*['"]*\s*\.\.([^)]+)\s*['"]*\s*\)/g,
            regex2 = /url\(\s*['"]*\s*\.\.([^)]+)\s*['"]*\s*\)/,
            urls = text.match(regex),
            _url = url.split('/');

        _url.pop();
        _url = _url.join('/');

        for (var i in urls) {
            text = this.replaceRelativeURLWithFullURL(urls[i].match(regex2), _url, text);
        }

        return text;
    };

    Loader.prototype.load = function( /* files to load */ ) {
        var args = [].slice.call(arguments),
            len = args.length,
            promises = [],
            self = this,
            p;

        for(var i=0; i<len; i++){
            promises.push(
                (function(file){
                    return function(){ return self.loadFile(file); };
                })(args[i])
            );
        }

        return this.promise.join(promises);
    };

    Loader.prototype.loadFile = function(file){
        var url = file.url,
            name = file.name,
            self = this;

        if(!this.get(url)){ //file doesnt exist
            return this.handleFileDownloadOrCORSAndInject(file);
        }

        return this.loadAndInjectFile(file, this.isCSS(url), this.isJS(url));
    };

    Loader.prototype.handleFileDownloadOrCORSAndInject = function(file){
        var url = file.url,
            name = file.name,
            isCSS = this.isCSS(url),
            isJS = this.isJS(url),
            promise = new this.promise.Promise();

        if(this.isCORS(url) || this.disableTextInjection){
            if(url.charAt(0) !== '/'){
                url = '//'+url;
            }
            if(isCSS){
                this.injectStyleTagBySrc(url);
                promise.done();
            } else if(isJS){
                this.injectScriptTagBySrc(url, promise);
            }

            return promise;
        } else {
            if(isCSS || isJS){
                return this.loadAndInjectFile(file, isCSS, isJS);
            }
        }
    };

    Loader.prototype.loadAndInjectFile = function(file, isCSS, isJS){
        var url = file.url,
            name = file.name,
            hasProtocol = url.indexOf('//'),
            _file = this.get(url);

        if(!_file){
            if(hasProtocol === -1){
                url = '//'+url;
            }
            if(isCSS){
                return this.loadAndInjectStyleTag(file);
            } else if (isJS){
                return this.loadAndInjectScriptTag(file);
            }
        } else {
            var promise = new this.promise.Promise();
            promise.done();
            if(isCSS){
                this.injectStyleTagByText(_file.text);
            } else if(isJS){
                this.injectScriptTagByText(_file.text);
            }
            return promise;
        }
    };

    Loader.prototype.isCORS = function(url){
        var hasProtocol = url.indexOf('//'),
            protocol = null;
        if(hasProtocol!==-1){
            prototype = url.substr(0, hasProtocol+2);
            url = url.substr(hasProtocol+2);
        }

        var isLocal;

        var hasRelativeDotSlash = url.indexOf('./');
        if(hasRelativeDotSlash === 0){
            hasRelativeDotSlash = true;
            isLocal = true;
            url = url.substr(2);
        } else {
            hasRelativeDotSlash = false;
        }

        var hasRelativeSingleSlash = url.indexOf('/');
        if(hasRelativeSingleSlash === 0){
            isLocal = true;
            hasRelativeSingleSlash = true;
            url = url.substr(1);
        } else {
            hasRelativeSingleSlash = false;
        }

        if(!hasRelativeSingleSlash && !hasRelativeDotSlash){
            var hasAnotherSlash = url.indexOf('/'),
                hostname,
                pathname;
            if( hasAnotherSlash !== -1 ){
                hostname = url.substr(0,hasAnotherSlash);
                pathname = url.substr(hasAnotherSlash);
            } else if( url.indexOf('js') !== -1 || url.indexOf('css') !== -1 || url.indexOf('tmpl') !== -1 ) {
                isLocal = true;
                pathname = url;
            } else {
                hostname = url;
            }

            if( hostname.indexOf(win.location.host)!==-1 ){
                isLocal = true;
            }
        }

        return !isLocal;
    };

    Loader.prototype.loadAndInjectStyleTag = function(file){
        var self = this,
            url = file.url,
            p = new this.promise.Promise();

        this.promise.get(url).then(function(error, result){
            self.addExpiration(file);
            file.text = self.replaceURLs(url, result);
            self.set(url, file);
            self.injectStyleTagByText(result);
            p.done();
        });

        return p;
    };

    Loader.prototype.loadAndInjectScriptTag = function(file){
        var self = this,
            url = file.url,
            p = new this.promise.Promise();

        this.promise.get(url).then(function(error, result){
            self.addExpiration(file);
            file.text = result;
            self.set(url, file);
            self.injectScriptTagByText(result);
            p.done();
        });

        return p;
    };

    win.Loader = Loader;

    var tag = document.getElementById("loaderjs");
    var app = tag && tag.getAttribute("data-app");
    if(app){
        var disableTextInjection = tag.getAttribute("disableTextInjection") !== null;
        var loader = win.loader = new Loader({
            disableTextInjection: tag.getAttribute("disableTextInjection")
            , CORS: tag.getAttribute("CORS")
        });
        loader.load({url:app});
    }
})(window, undefined);
<commit_msg>adding a mechanism to prevent reloading of resources, thus any subsequent requests to 'a.css' will not add a new stylesheet to the page<commit_after>;(function(win, undef) {
    function Loader(options){
        options = options || {};

        this.init();
        this.disableTextInjection = options.disableTextInjection;
        this.CORS = options.CORS;
        this.build = this.get('build_id');

        if(this.disableTextInjection || !this.build || this.build < this.expiredTimestamp ){
            this.build = +new Date();
            this.clearAll();
            this.set('build_id', this.build);
        }
    }

    Loader.prototype.loadedItems = {};

    Loader.prototype.init = function(){
        this.head = document.head || document.getElementsByTagName('head')[0];
        this.defaultExpiration = 1; //hours
        this.expiredTimestamp = +new Date() - this.defaultExpiration * 60 * 60 * 1000;
    };

    Loader.prototype.promise = (function() {
        function k() {
            this._callbacks = []
        }

        function l(b, c, a) {
            var e = new k;
            0 === b.length ? e.done(c, a) : b[0](c, a).then(function(a, c) {
                b.splice(0, 1);
                l(b, a, c).then(function(a, b) {
                    e.done(a, b)
                })
            });
            return e
        }

        function n(b, c, a, e) {
            function j() {
                f.abort();
                g.done(this.promise.ETIMEOUT, "")
            }
            var g = new k,
                f, d;
            a = a || {};
            e = e || {};
            try {
                var h;
                if (win.XMLHttpRequest) h = new XMLHttpRequest;
                else if (win.ActiveXObject) try {
                    h = new ActiveXObject("Msxml2.XMLHTTP")
                } catch (m) {
                    h = new ActiveXObject("Microsoft.XMLHTTP")
                }
                f = h
            } catch (p) {
                return g.done(-1, ""), g
            }
            h = "";
            if ("string" === typeof a) h = a;
            else {
                var l = encodeURIComponent;
                for (d in a) a.hasOwnProperty(d) && (h += "&" + l(d) + "=" + l(a[d]))
            }
            d = h;
            "GET" === b && d && (c += "?" + d, d = null);
            f.open(b, c);
            f.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            for (var q in e) e.hasOwnProperty(q) && f.setRequestHeader(q, e[q]);
            var r = this.ajaxTimeout;
            if (r) var n = setTimeout(j, r);
            f.onreadystatechange = function() {
                r && clearTimeout(n);
                4 === f.readyState && (200 === f.status ? g.done(null, f.responseText) : g.done(f.status, f.responseText))
            };
            f.send(d);
            return g
        }

        function j(b) {
            return function(c, a, e) {
                return n(b, c, a, e)
            }
        }
        k.prototype.then = function(b, c) {
            var a;
            a = function() {
                return b.apply(c, arguments)
            };
            this._isdone ? a(this.error, this.result) : this._callbacks.push(a)
        };
        k.prototype.done = function(b, c) {
            this._isdone = !0;
            this.error = b;
            this.result = c;
            for (var a = 0; a < this._callbacks.length; a++) this._callbacks[a](b, c);
            this._callbacks = []
        };
        var p = {
            get: j("GET"),
            post: j("POST"),
            put: j("PUT"),
            del: j("DELETE"),
            Promise: k,
            join: function(b) {
                function c(b) {
                    return function(c, d) {
                        e += 1;
                        g[b] = c;
                        f[b] = d;
                        e === a && j.done(g, f)
                    }
                }
                for (var a = b.length, e = 0, j = new k, g = [], f = [], d = 0; d < a; d++)
                    b[d]().then(c(d));
                return j;
            },
            chain: l,
            ajax: n,
            ENOXHR: 1,
            ETIMEOUT: 2,
            ajaxTimeout: 5000
        }, m;
        for (m in p) p.hasOwnProperty(m) && (this[m] = p[m]);
        return this;
    })();

    Loader.prototype.set = function(key, data) {
        try {
            localStorage.setItem(key, JSON.stringify(data));
            return true;
        } catch (e) {
            for(var i in localStorage){
                console.log(localStorage[i])
            }
            if (e.name === "QUOTA_EXCEEDED_ERR") {
                console.log("Oh no! We ran out of room!");
                this.clearAll();
            }
            return false;
        }
    };

    Loader.prototype.get = function(key) {
        var data = JSON.parse(localStorage.getItem(key) || 'false');
        return data;
    };

    Loader.prototype.clear = function(key) {
        if (!localStorage) return;
        this.remove(key);
    };

    Loader.prototype.clearAll = function(){
        for (key in localStorage) {
            this.clear(key);
        }
    };

    Loader.prototype.remove = function(key) {
        localStorage.removeItem(key);
        return this;
    };

    Loader.prototype.addExpiration = function(obj) {
        var now = +new Date();
        obj.stamp = now;
    };

    Loader.prototype.isJS = function(url){
        var isJS = url.indexOf('.js') != -1;
        return isJS;
    };

    Loader.prototype.isCSS = function(url) {
        var isCSS = url.indexOf('.css') != -1;
        return isCSS;
    };

    Loader.prototype.injectScriptTagByText = function(text) {
        var script = document.createElement('script');
        script.text = text;
        this.head.appendChild(this.createFragAndAddChild(script));
    };

    Loader.prototype.injectStyleTagByText = function(text) {
        var style = document.createElement('style');
        style.textContent = text;
        this.head.appendChild(this.createFragAndAddChild(style));
    };

    Loader.prototype.injectScriptTagBySrc = function(url, promise) {
        var script = document.createElement('script');
        script.src = url;
        script.onload = script.onreadystatechange = function() {
            promise.done();
        };
        this.head.appendChild(this.createFragAndAddChild(script));
    };

    Loader.prototype.createFragAndAddChild = function(child){
        var frag = document.createDocumentFragment();
        frag.appendChild(child);
        return frag;
    }

    Loader.prototype.injectStyleTagBySrc = function(url) {
        var style = document.createElement('link');
        style.href = url;
        style.rel = "stylesheet";
        this.head.appendChild(this.createFragAndAddChild(style));
    };

    Loader.prototype.replaceRelativeURLWithFullURL = function(segments, url_fragment, text) {
        if (segments.length > 1) {
            return text.replace(segments[0], 'url(' + url_fragment + '/..' + segments[1] + ')');
        }
        return text;
    };

    Loader.prototype.replaceURLs = function(url, text) {
        var regex = /url\(\s*['"]*\s*\.\.([^)]+)\s*['"]*\s*\)/g,
            regex2 = /url\(\s*['"]*\s*\.\.([^)]+)\s*['"]*\s*\)/,
            urls = text.match(regex),
            _url = url.split('/');

        _url.pop();
        _url = _url.join('/');

        for (var i in urls) {
            text = this.replaceRelativeURLWithFullURL(urls[i].match(regex2), _url, text);
        }

        return text;
    };

    Loader.prototype.load = function( /* files to load */ ) {
        var args = [].slice.call(arguments),
            len = args.length,
            promises = [],
            self = this;

        for(var i=0, len=args.length; i<len; i++){
            (function(file){
                if(!self.loadedItems[file.url])
                {
                    self.loadedItems[file.url] = 1;
                    promises.push(function(){ return self.loadFile(file); });
                }
            })(args[i])
        }

        return this.promise.join(promises);
    };

    Loader.prototype.loadFile = function(file){
        var url = file.url,
            name = file.name,
            self = this;

        if(!this.get(url)){ //file doesnt exist
            return this.handleFileDownloadOrCORSAndInject(file);
        }

        return this.loadAndInjectFile(file, this.isCSS(url), this.isJS(url));
    };

    Loader.prototype.handleFileDownloadOrCORSAndInject = function(file){
        var url = file.url,
            name = file.name,
            isCSS = this.isCSS(url),
            isJS = this.isJS(url),
            promise = new this.promise.Promise();

        if(this.isCORS(url) || this.disableTextInjection){
            if(url.charAt(0) !== '/'){
                url = '//'+url;
            }
            if(isCSS){
                this.injectStyleTagBySrc(url);
                promise.done();
            } else if(isJS){
                this.injectScriptTagBySrc(url, promise);
            }

            return promise;
        } else {
            if(isCSS || isJS){
                return this.loadAndInjectFile(file, isCSS, isJS);
            }
        }
    };

    Loader.prototype.loadAndInjectFile = function(file, isCSS, isJS){
        var url = file.url,
            name = file.name,
            hasProtocol = url.indexOf('//'),
            _file = this.get(url);

        if(!_file){
            if(hasProtocol === -1){
                url = '//'+url;
            }
            if(isCSS){
                return this.loadAndInjectStyleTag(file);
            } else if (isJS){
                return this.loadAndInjectScriptTag(file);
            }
        } else {
            var promise = new this.promise.Promise();
            promise.done();
            if(isCSS){
                this.injectStyleTagByText(_file.text);
            } else if(isJS){
                this.injectScriptTagByText(_file.text);
            }
            return promise;
        }
    };

    Loader.prototype.isCORS = function(url){
        var hasProtocol = url.indexOf('//'),
            protocol = null;
        if(hasProtocol!==-1){
            prototype = url.substr(0, hasProtocol+2);
            url = url.substr(hasProtocol+2);
        }

        var isLocal;

        var hasRelativeDotSlash = url.indexOf('./');
        if(hasRelativeDotSlash === 0){
            hasRelativeDotSlash = true;
            isLocal = true;
            url = url.substr(2);
        } else {
            hasRelativeDotSlash = false;
        }

        var hasRelativeSingleSlash = url.indexOf('/');
        if(hasRelativeSingleSlash === 0){
            isLocal = true;
            hasRelativeSingleSlash = true;
            url = url.substr(1);
        } else {
            hasRelativeSingleSlash = false;
        }

        if(!hasRelativeSingleSlash && !hasRelativeDotSlash){
            var hasAnotherSlash = url.indexOf('/'),
                hostname,
                pathname;
            if( hasAnotherSlash !== -1 ){
                hostname = url.substr(0,hasAnotherSlash);
                pathname = url.substr(hasAnotherSlash);
            } else if( url.indexOf('js') !== -1 || url.indexOf('css') !== -1 || url.indexOf('tmpl') !== -1 ) {
                isLocal = true;
                pathname = url;
            } else {
                hostname = url;
            }

            if( hostname.indexOf(win.location.host)!==-1 ){
                isLocal = true;
            }
        }

        return !isLocal;
    };

    Loader.prototype.loadAndInjectStyleTag = function(file){
        var self = this,
            url = file.url,
            p = new this.promise.Promise();

        this.promise.get(url).then(function(error, result){
            self.addExpiration(file);
            file.text = self.replaceURLs(url, result);
            self.set(url, file);
            self.injectStyleTagByText(result);
            p.done();
        });

        return p;
    };

    Loader.prototype.loadAndInjectScriptTag = function(file){
        var self = this,
            url = file.url,
            p = new this.promise.Promise();

        this.promise.get(url).then(function(error, result){
            self.addExpiration(file);
            file.text = result;
            self.set(url, file);
            self.injectScriptTagByText(result);
            p.done();
        });

        return p;
    };

    win.Loader = Loader;

    var tag = document.getElementById("loaderjs");
    var app = tag && tag.getAttribute("data-app");
    if(app){
        var disableTextInjection = tag.getAttribute("disableTextInjection") !== null;
        var loader = win.loader = new Loader({
            disableTextInjection: tag.getAttribute("disableTextInjection")
            , CORS: tag.getAttribute("CORS")
        });
        loader.load({url:app});
    }
})(window, undefined);
<|endoftext|>


<commit_before>import React from 'react';
import { props, t, skinnable } from '../utils';
import Select from 'react-select';
import find from 'lodash/find';
import omit from 'lodash/omit';
import cx from 'classnames';
import { warn } from '../utils/log';

const PropTypes = {
  value: t.maybe(t.union([t.Number, t.String, t.Object])),
  valueLink: t.maybe(t.struct({
    value: t.maybe(t.union([t.Number, t.String, t.Object])),
    requestChange: t.Function
  })),
  onChange: t.maybe(t.Function),
  options: t.Array,
  size: t.enums.of(['medium', 'small']),
  disabled: t.maybe(t.Boolean),
  searchable: t.maybe(t.Boolean),
  clearable: t.maybe(t.Boolean),
  backspaceRemoves: t.maybe(t.Boolean),
  multi: t.maybe(t.Boolean),
  flat: t.maybe(t.Boolean),
  id: t.maybe(t.String),
  className: t.maybe(t.String),
  style: t.maybe(t.Object)
};

@skinnable()
@props(PropTypes, { strict: false })
export default class Dropdown extends React.Component {

  static defaultProps = {
    delimiter: ',',
    size: 'medium',
    disabled: false,
    searchable: false,
    clearable: false,
    multi: false,
    flat: false
  }

  componentDidMount() {
    this.logWarnings();
  }

  logWarnings = () => {
    if (this.props.children) {
      warn('You\'re passing children. Not expected behaviour');
    }
  };

  getValue = () => (
    this.props.valueLink ? this.props.valueLink.value : this.props.value
  );

  valueToOption = (value, options) => {
    if (t.String.is(value) || t.Number.is(value)) {
      const { multi, delimiter } = this.props;
      if (multi) {
        const values = String(value).split(delimiter);
        return values.map(v => find(options, { value: v }));
      }
      return find(options, { value });
    }
    return value;
  };

  getOnChange = () => this.props.valueLink ? this.props.valueLink.requestChange : this.props.onChange;

  _onBlur = () => this.forceUpdate();

  getCustomClassNames() {
    const { size, flat, clearable } = this.props;
    return cx({
      'is-medium': size === 'medium',
      'is-small': size === 'small',
      'is-flat': flat,
      'is-clearable': clearable
    });
  }

  getLocals() {
    const { className, options, backspaceRemoves, clearable, ...props } = this.props;

    return {
      ...omit(props, 'valueLink'),
      options,
      clearable,
      backspaceRemoves: t.Nil.is(backspaceRemoves) ? clearable : backspaceRemoves,
      className: cx('dropdown', className, this.getCustomClassNames()),
      value: this.valueToOption(this.getValue(), options),
      onChange: this.getOnChange(),
      onBlur: this._onBlur
    };
  }

  template(locals) {
    return <Select {...locals} />;
  }
}
<commit_msg>fix value/options proptypes<commit_after>import React from 'react';
import { props, t, skinnable } from '../utils';
import Select from 'react-select';
import find from 'lodash/find';
import omit from 'lodash/omit';
import cx from 'classnames';
import { warn } from '../utils/log';

const PropTypes = {
  value: t.maybe(t.union([t.Number, t.String, t.Object, t.list(t.Object)])),
  valueLink: t.maybe(t.struct({
    value: t.maybe(t.union([t.Number, t.String, t.Object, t.list(t.Object)])),
    requestChange: t.Function
  })),
  onChange: t.maybe(t.Function),
  options: t.list(t.Object),
  size: t.enums.of(['medium', 'small']),
  disabled: t.maybe(t.Boolean),
  searchable: t.maybe(t.Boolean),
  clearable: t.maybe(t.Boolean),
  backspaceRemoves: t.maybe(t.Boolean),
  multi: t.maybe(t.Boolean),
  flat: t.maybe(t.Boolean),
  id: t.maybe(t.String),
  className: t.maybe(t.String),
  style: t.maybe(t.Object)
};

@skinnable()
@props(PropTypes, { strict: false })
export default class Dropdown extends React.Component {

  static defaultProps = {
    delimiter: ',',
    size: 'medium',
    disabled: false,
    searchable: false,
    clearable: false,
    multi: false,
    flat: false
  }

  componentDidMount() {
    this.logWarnings();
  }

  logWarnings = () => {
    if (this.props.children) {
      warn('You\'re passing children. Not expected behaviour');
    }
  };

  getValue = () => (
    this.props.valueLink ? this.props.valueLink.value : this.props.value
  );

  valueToOption = (value, options) => {
    if (t.String.is(value) || t.Number.is(value)) {
      const { multi, delimiter } = this.props;
      if (multi) {
        const values = String(value).split(delimiter);
        return values.map(v => find(options, { value: v }));
      }
      return find(options, { value });
    }
    return value;
  };

  getOnChange = () => this.props.valueLink ? this.props.valueLink.requestChange : this.props.onChange;

  _onBlur = () => this.forceUpdate();

  getCustomClassNames() {
    const { size, flat, clearable } = this.props;
    return cx({
      'is-medium': size === 'medium',
      'is-small': size === 'small',
      'is-flat': flat,
      'is-clearable': clearable
    });
  }

  getLocals() {
    const { className, options, backspaceRemoves, clearable, ...props } = this.props;

    return {
      ...omit(props, 'valueLink'),
      options,
      clearable,
      backspaceRemoves: t.Nil.is(backspaceRemoves) ? clearable : backspaceRemoves,
      className: cx('dropdown', className, this.getCustomClassNames()),
      value: this.valueToOption(this.getValue(), options),
      onChange: this.getOnChange(),
      onBlur: this._onBlur
    };
  }

  template(locals) {
    return <Select {...locals} />;
  }
}
<|endoftext|>


<commit_before>var parsers = require('./parsers');
var zlib = require('zlib');
var utils = require('./utils');
var parseUrl = require('url').parse;
var uuid = require('node-uuid');
var transports = require('./transports');
var node_util = require('util'); // node_util to avoid confusion with "utils"
var events = require('events');

module.exports.version = require('../package.json').version;

var Client = function Client(dsn, options) {
    if(arguments.length === 0) {
        // no arguments, use default from environment
        dsn = process.env.SENTRY_DSN;
        options = {};
    }
    if(typeof dsn === 'object') {
        // They must only be passing through options
        options = dsn;
        dsn = process.env.SENTRY_DSN;
    }
    options = options || {};

    this.raw_dsn = dsn;
    this.dsn = utils.parseDSN(dsn);
    this.name = options.name || process.env.SENTRY_NAME || require('os').hostname();
    this.root = options.root || process.cwd();
    this.transport = options.transport || transports[this.dsn.protocol];

    this.loggerName = options.logger || '';
    this.dataCallback = options.dataCallback;

    // enabled if a dsn is set
    this._enabled = !!this.dsn;

    this.on('error', function(e) {});  // noop
};
node_util.inherits(Client, events.EventEmitter);
var _ = Client.prototype;

module.exports.Client = Client;

_.getIdent =
_.get_ident = function getIdent(result) {
    return result.id;
};

_.process = function process(kwargs) {
    kwargs['modules'] = utils.getModules();
    kwargs['server_name'] = kwargs['server_name'] || this.name;
    kwargs['extra'] = kwargs['extra'] || {};
    if (typeof process.version !== undefined) {
        kwargs['extra']['node'] = process.version;
    }
    kwargs['tags'] = kwargs['tags'] || {};
    kwargs['logger'] = kwargs['logger'] || this.loggerName;
    kwargs['event_id'] = uuid().replace(/-/g, '');
    kwargs['timestamp'] = new Date().toISOString().split('.')[0];
    kwargs['project'] = this.dsn.project_id;
    kwargs['platform'] = 'node';

    var ident = {'id': kwargs['event_id']};

    if (this.dataCallback) {
        kwargs = this.dataCallback(kwargs);
    }

    // this will happen asynchronously. We don't care about it's response.
    this._enabled && this.send(kwargs, ident);

    return ident;
};

_.send = function send(kwargs, ident) {
    var self = this;

    // stringify, but don't choke on circular references, see: http://stackoverflow.com/questions/11616630/json-stringify-avoid-typeerror-converting-circular-structure-to-json
    var cache = [];
    var skwargs = JSON.stringify(kwargs, function(k, v) {
        if (typeof v === 'object' && v !== null) {
            if (cache.indexOf(v) !== -1) return;
            cache.push(v);
        }
        return v;
    });

    zlib.deflate(skwargs, function(err, buff) {
        var message = buff.toString('base64'),
            timestamp = new Date().getTime(),
            headers = {
                'X-Sentry-Auth': utils.getAuthHeader(timestamp, self.dsn.public_key, self.dsn.private_key),
                'Content-Type': 'application/octet-stream',
                'Content-Length': message.length
            };

        self.transport.send(self, message, headers, ident);
    });
};

_.captureMessage = function captureMessage(message, kwargs, cb) {
    if(!cb && typeof kwargs === 'function') {
        cb = kwargs;
        kwargs = {};
    } else {
        kwargs = kwargs || {};
    }
    var result = this.process(parsers.parseText(message, kwargs));
    cb && cb(result);
    return result;
};

_.captureError =
_.captureException = function captureError(err, kwargs, cb) {
    if(!(err instanceof Error)) {
        // This handles when someone does:
        //   throw "something awesome";
        // We synthesize an Error here so we can extract a (rough) stack trace.
        var err = new Error(err);
    }

    var self = this;
    if(!cb && typeof kwargs === 'function') {
        cb = kwargs;
        kwargs = {};
    } else {
        kwargs = kwargs || {};
    }
    parsers.parseError(err, kwargs, function(kw) {
        var result = self.process(kw);
        cb && cb(result);
    });
};

_.captureQuery = function captureQuery(query, engine, kwargs, cb) {
    if(!cb && typeof kwargs === 'function') {
        cb = kwargs;
        kwargs = {};
    } else {
        kwargs = kwargs || {};
    }
    var result = this.process(parsers.parseQuery(query, engine, kwargs));
    cb && cb(result);
    return result;
};

_.patchGlobal = function patchGlobal(cb) {
    module.exports.patchGlobal(this, cb);
};

module.exports.patchGlobal = function patchGlobal(client, cb) {
    // handle when the first argument is the callback, with no client specified
    if(typeof client === 'function') {
        cb = client;
        client = new Client();
    // first argument is a string DSN
    } else if(typeof client === 'string') {
        client = new Client(client);
    }
    // at the end, if we still don't have a Client, let's make one!
    !(client instanceof Client) && (client = new Client());

    var called = false;
    process.on('uncaughtException', function(err) {
        if(cb) {  // bind event listeners only if a callback was supplied
            var onLogged = function onLogged() {
                called = false;
                cb(true, err);
            };

            var onError = function onError() {
                called = false;
                cb(false, err);
            };

            if(called) {
                client.removeListener('logged', onLogged);
                client.removeListener('error', onError);
                return cb(false, err);
            }

            client.once('logged', onLogged);
            client.once('error', onError);
        }

        called = true;

        client.captureError(err, function(result) {
            node_util.log('uncaughtException: '+client.getIdent(result));
        });
    });
};
<commit_msg>We don't need to redeclare `err`<commit_after>var parsers = require('./parsers');
var zlib = require('zlib');
var utils = require('./utils');
var parseUrl = require('url').parse;
var uuid = require('node-uuid');
var transports = require('./transports');
var node_util = require('util'); // node_util to avoid confusion with "utils"
var events = require('events');

module.exports.version = require('../package.json').version;

var Client = function Client(dsn, options) {
    if(arguments.length === 0) {
        // no arguments, use default from environment
        dsn = process.env.SENTRY_DSN;
        options = {};
    }
    if(typeof dsn === 'object') {
        // They must only be passing through options
        options = dsn;
        dsn = process.env.SENTRY_DSN;
    }
    options = options || {};

    this.raw_dsn = dsn;
    this.dsn = utils.parseDSN(dsn);
    this.name = options.name || process.env.SENTRY_NAME || require('os').hostname();
    this.root = options.root || process.cwd();
    this.transport = options.transport || transports[this.dsn.protocol];

    this.loggerName = options.logger || '';
    this.dataCallback = options.dataCallback;

    // enabled if a dsn is set
    this._enabled = !!this.dsn;

    this.on('error', function(e) {});  // noop
};
node_util.inherits(Client, events.EventEmitter);
var _ = Client.prototype;

module.exports.Client = Client;

_.getIdent =
_.get_ident = function getIdent(result) {
    return result.id;
};

_.process = function process(kwargs) {
    kwargs['modules'] = utils.getModules();
    kwargs['server_name'] = kwargs['server_name'] || this.name;
    kwargs['extra'] = kwargs['extra'] || {};
    if (typeof process.version !== undefined) {
        kwargs['extra']['node'] = process.version;
    }
    kwargs['tags'] = kwargs['tags'] || {};
    kwargs['logger'] = kwargs['logger'] || this.loggerName;
    kwargs['event_id'] = uuid().replace(/-/g, '');
    kwargs['timestamp'] = new Date().toISOString().split('.')[0];
    kwargs['project'] = this.dsn.project_id;
    kwargs['platform'] = 'node';

    var ident = {'id': kwargs['event_id']};

    if (this.dataCallback) {
        kwargs = this.dataCallback(kwargs);
    }

    // this will happen asynchronously. We don't care about it's response.
    this._enabled && this.send(kwargs, ident);

    return ident;
};

_.send = function send(kwargs, ident) {
    var self = this;

    // stringify, but don't choke on circular references, see: http://stackoverflow.com/questions/11616630/json-stringify-avoid-typeerror-converting-circular-structure-to-json
    var cache = [];
    var skwargs = JSON.stringify(kwargs, function(k, v) {
        if (typeof v === 'object' && v !== null) {
            if (cache.indexOf(v) !== -1) return;
            cache.push(v);
        }
        return v;
    });

    zlib.deflate(skwargs, function(err, buff) {
        var message = buff.toString('base64'),
            timestamp = new Date().getTime(),
            headers = {
                'X-Sentry-Auth': utils.getAuthHeader(timestamp, self.dsn.public_key, self.dsn.private_key),
                'Content-Type': 'application/octet-stream',
                'Content-Length': message.length
            };

        self.transport.send(self, message, headers, ident);
    });
};

_.captureMessage = function captureMessage(message, kwargs, cb) {
    if(!cb && typeof kwargs === 'function') {
        cb = kwargs;
        kwargs = {};
    } else {
        kwargs = kwargs || {};
    }
    var result = this.process(parsers.parseText(message, kwargs));
    cb && cb(result);
    return result;
};

_.captureError =
_.captureException = function captureError(err, kwargs, cb) {
    if(!(err instanceof Error)) {
        // This handles when someone does:
        //   throw "something awesome";
        // We synthesize an Error here so we can extract a (rough) stack trace.
        err = new Error(err);
    }

    var self = this;
    if(!cb && typeof kwargs === 'function') {
        cb = kwargs;
        kwargs = {};
    } else {
        kwargs = kwargs || {};
    }
    parsers.parseError(err, kwargs, function(kw) {
        var result = self.process(kw);
        cb && cb(result);
    });
};

_.captureQuery = function captureQuery(query, engine, kwargs, cb) {
    if(!cb && typeof kwargs === 'function') {
        cb = kwargs;
        kwargs = {};
    } else {
        kwargs = kwargs || {};
    }
    var result = this.process(parsers.parseQuery(query, engine, kwargs));
    cb && cb(result);
    return result;
};

_.patchGlobal = function patchGlobal(cb) {
    module.exports.patchGlobal(this, cb);
};

module.exports.patchGlobal = function patchGlobal(client, cb) {
    // handle when the first argument is the callback, with no client specified
    if(typeof client === 'function') {
        cb = client;
        client = new Client();
    // first argument is a string DSN
    } else if(typeof client === 'string') {
        client = new Client(client);
    }
    // at the end, if we still don't have a Client, let's make one!
    !(client instanceof Client) && (client = new Client());

    var called = false;
    process.on('uncaughtException', function(err) {
        if(cb) {  // bind event listeners only if a callback was supplied
            var onLogged = function onLogged() {
                called = false;
                cb(true, err);
            };

            var onError = function onError() {
                called = false;
                cb(false, err);
            };

            if(called) {
                client.removeListener('logged', onLogged);
                client.removeListener('error', onError);
                return cb(false, err);
            }

            client.once('logged', onLogged);
            client.once('error', onError);
        }

        called = true;

        client.captureError(err, function(result) {
            node_util.log('uncaughtException: '+client.getIdent(result));
        });
    });
};
<|endoftext|>


<commit_before>import React from 'react'
import styled from 'styled-components'
import Close from 'react-icons/lib/md/close'

const Modal = props =>
  props.isOpen ? (
    <ModalContainer>
      <ModalContent>
        <CloseIcon onClick={() => props.handleClose()} />
        {props.children}
      </ModalContent>
    </ModalContainer>
  ) : (

  )

const ModalContainer = styled.div`
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 999;
  padding: 50px;
`

const ModalContent = styled.div`
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  max-width: 600px;
  min-height: 200px;
  border-radius: 4px;
  background-color: ${props => props.theme.paletteTertiary};
  box-shadow: rgba(25, 17, 34, 0.05) 0px 3px 10px;
  padding: 2rem 2rem 5rem 2rem;
`

const CloseIcon = styled(Close)`
  width: 2rem;
  height: 2rem;
  cursor: pointer;
  color: ${props => props.theme.paletteFontPrimary};
  padding-left: 80%;
  margin: 0 0 4rem 0;
`

export default Modal
<commit_msg>Modal styling improvements<commit_after>import React from 'react'
import styled from 'styled-components'
import Close from 'react-icons/lib/md/close'

const Modal = props =>
  props.isOpen ? (
    <ModalContainer>
      <ModalContent>
        <CloseIcon onClick={() => props.handleClose()} />
        {props.children}
      </ModalContent>
    </ModalContainer>
  ) : (

  )

const ModalContainer = styled.div`
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 999;
  padding: 50px;
`

const ModalContent = styled.div`
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  max-width: 600px;
  min-height: 200px;
  border-radius: 4px;
  background-color: ${props => props.theme.paletteTertiary};
  box-shadow: rgba(25, 17, 34, 0.05) 0px 3px 10px;
  padding: 2rem 1rem 2rem 1rem;
`

const CloseIcon = styled(Close)`
  width: 2rem;
  height: 2rem;
  cursor: pointer;
  color: ${props => props.theme.paletteFontPrimary};
  align-self: flex-end;
  margin: 0 0 4rem 0;
`

export default Modal
<|endoftext|>


<commit_before>/**
 * slice for arguments
 */
exports.argumentSlice = function (args, start, end) {
    var acc = []
    if (end === undefined) {
        end = args.length
    } else {
        end = Math.min(args.length, end)
    }

    for(var i = start; i < end; i++) {
        acc.push(args[i])
    }

    return acc
}

/**
 *
 * mixin from dst to src
 *
 * if additional arguments are given, they specify the names to mixin.
 *
 * otherwise all functions are taken
 *
 */
exports.mixin = function (dst, src /*names */) {
    var argslice = exports.argumentSlice(arguments, 2)
        , to = dst.prototype
        , from = src.prototype

    if (argslice.length == 0) {
        for(var m in from) {
            if (typeof from[m] != 'function') continue;
            to[m] = from[m]
        }
    } else {
        argslice.forEach(function (m) {
            to[m] = from[m]
        })
    }
}

/**
 *
 * chain method calls
 *
 * example:
 * chainCall(initialThis, [this.method1, arg1, arg1]
 *      [this.method2, arg3, arg4]);
 *
 *  the chain will be started by calling method1 bound to intialThis.
 *  method2 will be called bound to the result of method1, and so on.
 *  the final result is returned.
 *
 *  For convenience, if any method returns undefined, the last bound this
 *  is reused.
 *
 */
exports.chainCall = function (bindTo) {
    var calls = exports.argumentSlice(arguments, 1)
        , callsLen = calls.length
        , i, method, args, result = bindTo
    for(i = 0; i < callsLen; i++) {
        method = calls[i][0], args = calls[i].slice(1)
        result = method.apply(bindTo, args)
            , bindTo = (result === undefined) ? bindTo : result
    }
    return bindTo
}

<commit_msg>jslint ...<commit_after>"use strict";

/**
 * slice for arguments
 */
exports.argumentSlice = function (args, start, end) {
    var acc = [], i;

    if (end === undefined) {
        end = args.length;
    } else {
        end = Math.min(args.length, end);
    }

    for (i = start; i < end; i += 1) {
        acc.push(args[i]);
    }

    return acc;
};

/**
 *
 * mixin from dst to src
 *
 * if additional arguments are given, they specify the names to mixin.
 *
 * otherwise all functions are taken
 *
 */
exports.mixin = function (dst, src) {
    var argslice = exports.argumentSlice(arguments, 2),
        to = dst.prototype,
        from = src.prototype,
		m;

    if (argslice.length === 0) {
        for (m in from) {
			if (from.hasOwnProperty(m)) {
				if (typeof from[m] !== 'function') {
					continue;
				}
				to[m] = from[m];
			}
        }
    } else {
        argslice.forEach(function (m) {
            to[m] = from[m];
        });
    }
};

/**
 * invert a dictionary
 *
 * Switches key and value in a dictionary.
 *
 * If a keyname is given, it gives the the attribute name in the value
 * for the new key.
 */
exports.invertDictionary = function (dict, keyname) {
	var newDict = { }, key, v;
	if (keyname === undefined) {
		for (key in dict) {
			if (dict.hasOwnProperty(key)) {
				newDict[dict[key]] = key;
			}
		}
	} else {
		for (key in dict) {
			if (dict.hasOwnProperty(key)) {
				v = dict[key][keyname];
				newDict[v] = key;
			}
		}
	}
	return newDict;
};

/**
 *
 * chain method calls
 *
 * example:
 * chainCall(initialThis, [this.method1, arg1, arg1]
 *      [this.method2, arg3, arg4]);
 *
 *  the chain will be started by calling method1 bound to intialThis.
 *  method2 will be called bound to the result of method1, and so on.
 *  the final result is returned.
 *
 *  For convenience, if any method returns undefined, the last bound this
 *  is reused.
 *
 */
exports.chainCall = function (initialBind) {
    var calls = exports.argumentSlice(arguments, 1),
        callsLen = calls.length,
		bindTo = initialBind,
		result = bindTo,
        i,
		method,
		args;
    for (i = 0; i < callsLen; i += 1) {
        method = calls[i][0];
		args = calls[i].slice(1);
        result = method.apply(bindTo, args);
        bindTo = (result === undefined) ? bindTo : result;
    }
    return bindTo;
};

<|endoftext|>


<commit_before>'use strict';
var logger = require('@hoist/logger');
var Agenda = require('agenda');
var config = require('config');
var agenda = new Agenda();
var chefJob = require('./lib/tasks/chef_task');
var countQueuesJob = require('./lib/tasks/count_queues_task');
var checkEC2Job = require('./lib/tasks/ec2_check_status_task');
var rebalanceJob = require('./lib/tasks/rebalance_executors_task');
var pruneNewRelicJob = require('./lib/tasks/prune_new_relic_task');
var cullQueuesTask = require('./lib/tasks/cull_queues_task');
var rebootExecutorsTask = require('./lib/tasks/reboot_executors_task');

agenda.database(config.get('Hoist.mongo.overlord'), 'operational-jobs');

logger.info('starting server');
logger.info('registering chef maintainance job');
agenda.define('maintain chef nodes', function (job, done) {
  logger.info('starting chef job');
  chefJob().nodeify(done);
});
agenda.define('rebalance executors', {
  lockLifetime: 10000
}, function (job, done) {
  logger.info('starting rebalance job');
  rebalanceJob().nodeify(done);
});
agenda.define('count queues', {
  lockLifetime: 10000
}, function (job, done) {
  logger.info('starting count queues job');
  countQueuesJob().nodeify(done);
});
agenda.define('check ec2 instances', {
  lockLifetime: 10000
}, function (job, done) {
  logger.info('starting ec2 check job');
  checkEC2Job().nodeify(done);
});

agenda.define('prune new relic servers', {
  lockLifetime: 10000
}, function (job, done) {
  logger.info('starting new relic prune job');
  pruneNewRelicJob().nodeify(done);
});
agenda.define('prune rabbitmq queues', {
  lockLifetime: 10000
}, function (job, done) {
  logger.info('starting rabbitmq prune job');
  cullQueuesTask().nodeify(done);
});
agenda.define('reboot executor instances', {
  lockLifetime: 10000
}, function (job, done) {
  logger.info('starting executor reboot job');
  rebootExecutorsTask().nodeify(done);
});
logger.info('registering schedule');

agenda.every('2 minutes', 'maintain chef nodes');
agenda.every('1 minute', 'count queues');
agenda.every('5 minutes', 'check ec2 instances');
agenda.every('10 seconds', 'rebalance executors');
agenda.every('5 minutes', 'prune new relic servers');
agenda.every('30 minutes', 'prune rabbitmq queues');
agenda.every('6 hours', 'reboot executor instances');
logger.info('starting agenda');
agenda.start();

function graceful() {
  logger.info('stopping agenda');
  agenda.stop(function () {
    process.exit(0);
  });
}
process.on('SIGTERM', graceful);
process.on('SIGINT', graceful);
<commit_msg>add task to task server script<commit_after>'use strict';
var logger = require('@hoist/logger');
var Agenda = require('agenda');
var config = require('config');
var agenda = new Agenda();
var chefJob = require('./lib/tasks/chef_task');
var countQueuesJob = require('./lib/tasks/count_queues_task');
var checkEC2Job = require('./lib/tasks/ec2_check_status_task');
var rebalanceJob = require('./lib/tasks/rebalance_executors_task');
var pruneNewRelicJob = require('./lib/tasks/prune_new_relic_task');
var cullQueuesTask = require('./lib/tasks/cull_queues_task');
var rebootExecutorsTask = require('./lib/tasks/reboot_executors_task');

agenda.database(config.get('Hoist.mongo.overlord'), 'operational-jobs');

logger.info('starting server');
logger.info('registering chef maintainance job');
agenda.define('maintain chef nodes', function (job, done) {
  logger.info('starting chef job');
  chefJob().nodeify(done);
});
agenda.define('rebalance executors', {
  lockLifetime: 10000
}, function (job, done) {
  logger.info('starting rebalance job');
  rebalanceJob().nodeify(done);
});
agenda.define('count queues', {
  lockLifetime: 10000
}, function (job, done) {
  logger.info('starting count queues job');
  countQueuesJob().nodeify(done);
});
agenda.define('check ec2 instances', {
  lockLifetime: 10000
}, function (job, done) {
  logger.info('starting ec2 check job');
  checkEC2Job().nodeify(done);
});

agenda.define('prune new relic servers', {
  lockLifetime: 10000
}, function (job, done) {
  logger.info('starting new relic prune job');
  pruneNewRelicJob().nodeify(done);
});
agenda.define('prune rabbitmq queues', {
  lockLifetime: 10000
}, function (job, done) {
  logger.info('starting rabbitmq prune job');
  cullQueuesTask().nodeify(done);
});
agenda.define('reboot executor instances', {
  lockLifetime: 10000
}, function (job, done) {
  logger.info('starting executor reboot job');
  rebootExecutorsTask().nodeify(done);
});
logger.info('registering schedule');

agenda.every('2 minutes', 'maintain chef nodes');
agenda.every('1 minute', 'count queues');
agenda.every('5 minutes', 'check ec2 instances');
agenda.every('10 seconds', 'rebalance executors');
agenda.every('5 minutes', 'prune new relic servers');
agenda.every('30 minutes', 'prune rabbitmq queues');
agenda.every('6 hours', 'reboot executor instances');

logger.info('starting agenda');
agenda.start();

function graceful() {
  logger.info('stopping agenda');
  agenda.stop(function () {
    process.exit(0);
  });
}
process.on('SIGTERM', graceful);
process.on('SIGINT', graceful);
<|endoftext|>


<commit_before>import Command from './Command'

export default class EditInlineNodeCommand extends Command {
  constructor (...args) {
    super(...args)
    if (!this.config.nodeType) {
      throw new Error('Every AnnotationCommand must have a nodeType')
    }
  }

  getCommandState (params, context) { // eslint-disable-line no-unused
    let sel = params.selection
    let newState = {
      disabled: true,
      active: false
    }
    let annos = this._getAnnotationsForSelection(params)
    // Among the annotations found we need to pick the first that exactly
    // matches the current selection
    if (annos.length > 0) {
      annos.forEach(anno => {
        if (anno.getSelection().equals(sel)) {
          newState.disabled = false
          newState.nodeId = anno.id
        }
      })
    }
    return newState
  }

  execute (params, context) { } // eslint-disable-line no-unused

  _getAnnotationsForSelection (params) {
    return params.selectionState.annosByType[this.config.nodeType] || []
  }
}
<commit_msg>Using for-of.<commit_after>import Command from './Command'

export default class EditInlineNodeCommand extends Command {
  constructor (...args) {
    super(...args)
    if (!this.config.nodeType) {
      throw new Error('Every AnnotationCommand must have a nodeType')
    }
  }

  getCommandState (params, context) { // eslint-disable-line no-unused
    let sel = params.selection
    let newState = {
      disabled: true,
      active: false
    }
    let annos = this._getAnnotationsForSelection(params)
    // Among the annotations found we need to pick the first that exactly
    // matches the current selection
    if (annos.length > 0) {
      for (let anno of annos) {
        if (anno.getSelection().equals(sel)) {
          newState.disabled = false
          newState.nodeId = anno.id
          break
        }
      }
    }
    return newState
  }

  execute (params, context) { } // eslint-disable-line no-unused

  _getAnnotationsForSelection (params) {
    return params.selectionState.annosByType[this.config.nodeType] || []
  }
}
<|endoftext|>


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

/* minify binary
 * usage: node minify <input-file> <output-file>
 */
(function() {
    'use strict';

    var Util        = require('util-io'),

        Pack        = require('../package.json'),
        Version     = Pack.version,
        Chunks      = '',

        log         = function() {
            console.log.apply(console, arguments);
            process.exit();
        },

        getMinify   = function() {
            return require('../minify');
        },

        Argv        = process.argv,
        files       = Util.slice(Argv, 2),
        In          = files[0];

    readStd(function() {
        if (Chunks && In) {
            getMinify().optimizeData({
                ext     : Util.replaceStr(In, '-', '.'),
                data    : Chunks
            }, function(error, data) {
                log(error || data);
            });
        }
        else if (!In || Util.strCmp(In, ['-h', '--help']))
            log('minify <input-file1> <input-file2> <inputfileN>\n');
        else if (Util.strCmp(In, ['-v', '--version']) )
            log('v' + Version);
        else if (In)
            files.forEach(function(current) {
                getMinify().optimize(current, {
                    notLog  : true,
                    callback: function(error, data) {
                        log(error || data);
                    }
                });
            });
    });

    function readStd(callback) {
        process.stdin.on('readable', function() {
            var chunk = process.stdin.read();

            if (chunk !== null)
                Chunks += chunk;
            else
                callback();
        });
    }

})();
<commit_msg>fix(minify) optimize: callback in options<commit_after>#!/usr/bin/env node

/* minify binary
 * usage: node minify <input-file> <output-file>
 */
(function() {
    'use strict';

    var Util        = require('util-io'),

        Pack        = require('../package.json'),
        Version     = Pack.version,
        Chunks      = '',

        log         = function() {
            console.log.apply(console, arguments);
            process.exit();
        },

        getMinify   = function() {
            return require('../minify');
        },

        Argv        = process.argv,
        files       = Util.slice(Argv, 2),
        In          = files[0];

    readStd(function() {
        if (Chunks && In) {
            getMinify().optimizeData({
                ext     : Util.replaceStr(In, '-', '.'),
                data    : Chunks
            }, function(error, data) {
                log(error || data);
            });
        }
        else if (!In || Util.strCmp(In, ['-h', '--help']))
            log('minify <input-file1> <input-file2> <inputfileN>\n');
        else if (Util.strCmp(In, ['-v', '--version']) )
            log('v' + Version);
        else if (In)
            files.forEach(function(current) {
                getMinify().optimize(current, {
                    notLog  : true,
                }, function(error, data) {
                    log(error || data);
                });
            });
    });

    function readStd(callback) {
        process.stdin.on('readable', function() {
            var chunk = process.stdin.read();

            if (chunk !== null)
                Chunks += chunk;
            else
                callback();
        });
    }

})();
<|endoftext|>


<commit_before>import { useState, useRef, useEffect, useCallback, useMemo } from 'react';
import axios from 'axios';

import { NULL, replaceAtIndex } from '~client/modules/data';
import { API_PREFIX } from '~client/constants/data';

function buildMakeRequest({ method, url, apiKey, onSuccess, onError, onComplete }) {
    return async (source, id = null, params = {}, data = null, done = null) => {
        try {
            let requestUrl = `${API_PREFIX}/${url}`;
            if (id) {
                requestUrl += `/${id}`;
            }

            const res = await axios({
                cancelToken: source.token,
                method,
                url: requestUrl,
                headers: {
                    Authorization: apiKey
                },
                params,
                data
            });

            onSuccess(res.data, id);
        } catch (err) {
            onError(err);
        } finally {
            onComplete();

            if (done) {
                done();
            }
        }
    };
}

export function useApi({
    method = 'get',
    url,
    apiKey,
    onSuccess = NULL
}) {
    const source = useRef(null);

    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);

    const onError = useCallback(err => {
        setError(err);
    }, []);

    const onComplete = useCallback(() => {
        setLoading(false);
    }, []);

    useEffect(() => () => {
        if (source.current) {
            source.current.cancel('Component unmounted');
        }
    }, []);

    const makeRequest = useMemo(() => buildMakeRequest({
        method,
        url,
        apiKey,
        onSuccess,
        onError,
        onComplete
    }), [method, url, apiKey, onSuccess, onError, onComplete]);

    const initiateRequest = useCallback((...args) => {
        if (source.current) {
            source.current.cancel('Another request made');
        }

        source.current = axios.CancelToken.source();

        setLoading(true);
        makeRequest(source.current, ...args);
    }, [makeRequest]);

    return [initiateRequest, loading, error];
}

function useResponseOp(url, apiKey, setResponse, method, query = null) {
    const [response, setTempResponse] = useState(null);
    const handleResponse = useCallback(res => {
        setTempResponse(res);
    }, []);

    const [onTrigger, loading, error] = useApi({
        method,
        url,
        apiKey,
        onSuccess: handleResponse
    });

    const triggerWithQuery = useMemo(() => {
        if (query) {
            return (id, params, data, done) => onTrigger(id, params || query, data, done);
        }

        return onTrigger;
    }, [query, onTrigger]);

    useEffect(() => {
        if (response) {
            setResponse(response);
            setTempResponse(null);
        }
    }, [response, setResponse]);

    return [triggerWithQuery, loading, error];
}

function useDelete(url, apiKey, data, setData) {
    const [deletedId, setDeletedId] = useState(null);
    const handleDelete = useCallback((res, id) => {
        setDeletedId(id);
    }, []);

    const [onDelete, loading, error] = useApi({
        method: 'delete',
        url,
        apiKey,
        onSuccess: handleDelete
    });

    useEffect(() => {
        if (deletedId) {
            setData(data.filter(({ id }) => id !== deletedId));
            setDeletedId(null);
        }
    }, [data, setData, deletedId]);

    return [onDelete, loading, error];
}

export function useCrud({
    url,
    numPerPage = null,
    apiKey
}) {
    const [page, setPage] = useState(0);
    const [prevPage, setPrevPage] = useState(0);
    const [numPages, setNumPages] = useState(null);
    const [prevPages, setPrevPages] = useState(null);

    const [data, setData] = useState([]);
    const setResponse = useCallback(response => {
        let item = response;
        if (numPerPage && Array.isArray(response.data)) {
            item = response.data;

            setNumPages(Math.ceil(response.count / numPerPage));
        }
        if (Array.isArray(item)) {
            return setData(item);
        }

        const index = data.findIndex(({ id }) => id === item.id);
        if (index === -1) {
            return setData([...data, item]);
        }

        return setData(replaceAtIndex(data, index, item));
    }, [data, numPerPage]);

    useEffect(() => {
        if (numPages !== prevPages) {
            setPage(0);
            setPrevPages(numPages);
        }
    }, [numPages, prevPages]);

    const [onCreate, loadingCreate, errorCreate] = useResponseOp(url, apiKey, setResponse, 'post');

    const readQuery = useMemo(() => {
        if (numPerPage) {
            return { page, limit: numPerPage };
        }

        return null;
    }, [numPerPage, page]);

    const [onRead, loadingRead, errorRead] = useResponseOp(url, apiKey, setResponse, 'get', readQuery);
    const [onUpdate, loadingUpdate, errorUpdate] = useResponseOp(url, apiKey, setResponse, 'put');
    const [onDelete, loadingDelete, errorDelete] = useDelete(url, apiKey, data, setData);

    useEffect(() => {
        if (numPerPage && page !== prevPage) {
            onRead();
            setPrevPage(page);
        }
    }, [numPerPage, page, prevPage, onRead]);

    const loading = loadingCreate || loadingRead || loadingUpdate || loadingDelete;
    const error = errorCreate || errorRead || errorUpdate || errorDelete;

    return [data, loading, error, onCreate, onRead, onUpdate, onDelete, page, setPage, numPages];
}
<commit_msg>Removed obsolete CRUD hooks module<commit_after><|endoftext|>


<commit_before>import path from "path";
import fs from "fs";

import { watch } from "chokidar";
import {sync as mkdirp} from "mkdirp";
import most from "most";

import compile from "./compile";
import { entries } from "./util";
import loadAst from "./compile/modules/load-ast";
import compileModules from "./compile/modules/compile";

export default function Interlock (options) {
  const cwd = process.cwd();
  options = options || {};

  if (!options.emit || !options.emit.length) {
    throw new Error("Must define at least one bundle.");
  }

  // TODO: validate options, or only persist specific values
  options.context = options.context || cwd;
  options.outputPath = options.outputPath || path.join(cwd, "dist");
  options.extensions = options.extensions || [".js", ".jsx", ".es6"];
  options.ns = options.ns || require(path.join(options.root, "./package.json")).name;
  options.context = options.context || cwd;
  this.options = options;
}

Interlock.prototype.build = function () {
  compile(this.options).then(this._saveBundles);
};

Interlock.prototype._saveBundles = function (compilation) {
  for (let [bundleDest, bundle] of entries(compilation.bundles)) {
    const bundleOutput = bundle.raw;
    const outputPath = path.join(this.options.outputPath, bundleDest);
    mkdirp(path.dirname(outputPath));
    fs.writeFileSync(outputPath, bundleOutput);
  }
};

function getRefreshedAsset (compilation, changedFilePath) {
  const origAsset = compilation.cache.modulesByAbsPath[changedFilePath];
  let newAsset = Object.assign({}, origAsset, {
    rawSource: null,
    ast: null,
    requireNodes: null,
    dependencies: null,
    hash: null
  });

  return loadAst.call(compilation, newAsset);
}

Interlock.prototype.watch = function (save=false) {
  const self = this;
  let lastCompilation = null;
  const absPathToModuleHash = Object.create(null);

  const watcher = watch([], {});

  return most.create(add => {
    function onCompileComplete (compilation) {
      lastCompilation = compilation;
      for (let [, bundleObj] of entries(compilation.bundles)) {
        for (let module of bundleObj.modules || []) {
          watcher.add(module.path);
          absPathToModuleHash[module.path] = module.hash;
        }
      }
      if (save) { self._saveBundles(compilation); }
      // Emit compilation.
      add({ compilation });
    }

    watcher.on("change", changedFilePath => {
      for (let modulePath of Object.keys(absPathToModuleHash)) { watcher.unwatch(modulePath); }

      const refreshedAsset = getRefreshedAsset(lastCompilation, changedFilePath);
      delete lastCompilation.cache.modulesByAbsPath[changedFilePath];

      compileModules(lastCompilation, most.from([refreshedAsset]))
        .reduce((updatedModules, module) => {
          updatedModules.push(module);
          return updatedModules;
        }, [])
        .then(patchModules => {
          // Emit patch modules (changed module plus any new dependencies).
          add({ patchModules, changedFilePath });
          compile(lastCompilation.opts).then(onCompileComplete);
        });
    });

    compile(this.options).then(onCompileComplete);
  });
};
<commit_msg>Fix build method after `watch` implementation.<commit_after>import * as path from "path";
import * as fs from "fs";

import { watch } from "chokidar";
import {sync as mkdirp} from "mkdirp";
import most from "most";

import compile from "./compile";
import { entries } from "./util";
import loadAst from "./compile/modules/load-ast";
import compileModules from "./compile/modules/compile";

export default function Interlock (options) {
  const cwd = process.cwd();
  options = options || {};

  if (!options.emit || !options.emit.length) {
    throw new Error("Must define at least one bundle.");
  }

  // TODO: validate options, or only persist specific values
  options.context = options.context || cwd;
  options.outputPath = options.outputPath || path.join(cwd, "dist");
  options.extensions = options.extensions || [".js", ".jsx", ".es6"];
  options.ns = options.ns || require(path.join(options.root, "./package.json")).name;
  options.context = options.context || cwd;
  this.options = options;
}

Interlock.prototype.build = function () {
  compile(this.options).then(this._saveBundles);
};

Interlock.prototype._saveBundles = function (compilation) {
  for (let [bundleDest, bundle] of entries(compilation.bundles)) {
    const bundleOutput = bundle.raw;
    const outputPath = path.join(compilation.opts.outputPath, bundleDest);
    mkdirp(path.dirname(outputPath));
    fs.writeFileSync(outputPath, bundleOutput);
  }
};

function getRefreshedAsset (compilation, changedFilePath) {
  const origAsset = compilation.cache.modulesByAbsPath[changedFilePath];
  let newAsset = Object.assign({}, origAsset, {
    rawSource: null,
    ast: null,
    requireNodes: null,
    dependencies: null,
    hash: null
  });

  return loadAst.call(compilation, newAsset);
}

Interlock.prototype.watch = function (save=false) {
  const self = this;
  let lastCompilation = null;
  const absPathToModuleHash = Object.create(null);

  const watcher = watch([], {});

  return most.create(add => {
    function onCompileComplete (compilation) {
      lastCompilation = compilation;
      for (let [, bundleObj] of entries(compilation.bundles)) {
        for (let module of bundleObj.modules || []) {
          watcher.add(module.path);
          absPathToModuleHash[module.path] = module.hash;
        }
      }
      if (save) { self._saveBundles(compilation); }
      // Emit compilation.
      add({ compilation });
    }

    watcher.on("change", changedFilePath => {
      for (let modulePath of Object.keys(absPathToModuleHash)) { watcher.unwatch(modulePath); }

      const refreshedAsset = getRefreshedAsset(lastCompilation, changedFilePath);
      delete lastCompilation.cache.modulesByAbsPath[changedFilePath];

      compileModules(lastCompilation, most.from([refreshedAsset]))
        .reduce((updatedModules, module) => {
          updatedModules.push(module);
          return updatedModules;
        }, [])
        .then(patchModules => {
          // Emit patch modules (changed module plus any new dependencies).
          add({ patchModules, changedFilePath });
          compile(lastCompilation.opts).then(onCompileComplete);
        });
    });

    compile(this.options).then(onCompileComplete);
  });
};
<|endoftext|>


<commit_before>exports.BattleAliases = {
	// formats
	"randbats": "Random Battle",
	"overused": "OU",
	"underused": "UU",
	"rarelyused": "RU",
	"neverused": "NU",
	"vgc": "VGC 2014",
	"bh": "Balanced Hackmons",
	"monotype": "OU Monotype",
	"createapokemon": "CAP",
	"cc1v1": "Challenge Cup 1vs1",

	// mega evos
	"megaabomasnow": "Abomasnow-Mega",
	"megaabsol": "Absol-Mega",
	"megaaerodactyl": "Aerodactyl-Mega",
	"megaaggron": "Aggron-Mega",
	"megaalakazam": "Alakazam-Mega",
	"megaampharos": "Ampharos-Mega",
	"megabanette": "Banette-Mega",
	"megablastoise": "Blastoise-Mega",
	"megablaziken": "Blaziken-Mega",
	"megacharizard": "Charizard-Mega-Y",
	"megacharizardx": "Charizard-Mega-X",
	"megacharizardy": "Charizard-Mega-Y",
	"megagarchomp": "Garchomp-Mega",
	"megagardevoir": "Gardevoir-Mega",
	"megagengar": "Gengar-Mega",
	"megagyarados": "Gyarados-Mega",
	"megaheracross": "Heracross-Mega",
	"megahoundoom": "Houndoom-Mega",
	"megakangaskhan": "Kangaskhan-Mega",
	"megalatias": "Latias-Mega",
	"megalatios": "Latios-Mega",
	"megalucario": "Lucario-Mega",
	"megaluke": "Lucario-Mega",
	"megamanectric": "Manectric-Mega",
	"megamawile": "Mawile-Mega",
	"megamaw": "Mawile-Mega",
	"megamedicham": "Medicham-Mega",
	"megamedi": "Medicham-Mega",
	"megamewtwo": "Mewtwo-Mega-Y",
	"megamewtwox": "Mewtwo-Mega-X",
	"megamewtwoy": "Mewtwo-Mega-Y",
	"megapinsir": "Pinsir-Mega",
	"megascizor": "Scizor-Mega",
	"megatyranitar": "Tyranitar-Mega",
	"megattar": "Tyranitar-Mega",
	"megavenusaur": "Venusaur-Mega",
	"megavenu": "Venusaur-Mega",
	"mmx": "Mewtwo-Mega-X",
	"mmy": "Mewtwo-Mega-Y",

	// formes
	"basculinb": "Basculin-Blue-Striped",
	"basculinblue": "Basculin-Blue-Striped",
	"basculinbluestripe": "Basculin-Blue-Striped",
	"castformh": "Castform-Snowy",
	"castformice": "Castform-Snowy",
	"castformr": "Castform-Rainy",
	"castformwater": "Castform-Rainy",
	"castforms": "Castform-Sunny",
	"castformfire": "Castform-Sunny",
	"cherrims": "Cherrim-Sunshine",
	"cherrimsunny": "Cherrim-Sunshine",
	"darmanitanz": "Darmanitan-Zen",
	"darmanitanzenmode": "Darmanitan-Zen",
	"deoxysnormal": "Deoxys",
	"deon": "Deoxys",
	"deoxysa": "Deoxys-Attack",
	"deoa": "Deoxys-Attack",
	"deoxysd": "Deoxys-Defense",
	"deoxysdefence": "Deoxys-Defense",
	"deod": "Deoxys-Defense",
	"deoxyss": "Deoxys-Speed",
	"deos": "Deoxys-Speed",
	"giratinao": "Giratina-Origin",
	"gourgeisthuge": "Gourgeist-Super",
	"keldeor": "Keldeo-Resolute",
	"keldeoresolution": "Keldeo-Resolute",
	"kyuremb": "Kyurem-Black",
	"kyuremw": "Kyurem-White",
	"landorust": "Landorus-Therian",
	"meloettap": "Meloetta-Pirouette",
	"meloettas": "Meloetta-Pirouette",
	"pumpkaboohuge": "Pumpkaboo-Super",
	"rotomc": "Rotom-Mow",
	"rotomf": "Rotom-Frost",
	"rotomh": "Rotom-Heat",
	"rotoms": "Rotom-Fan",
	"rotomw": "Rotom-Wash",
	"shaymins": "Shaymin-Sky",
	"skymin": "Shaymin-Sky",
	"thundurust": "Thundurus-Therian",
	"tornadust": "Tornadus-Therian",
	"wormadamg": "Wormadam-Sandy",
	"wormadamground": "Wormadam-Sandy",
	"wormadams": "Wormadam-Trash",
	"wormadamsteel": "Wormadam-Trash",
	"floettee": "Floette-Eternal-Flower",

	// base formes
	"nidoranfemale": "Nidoran-F",
	"nidoranmale": "Nidoran-M",
	"giratinaa": "Giratina",
	"giratinaaltered": "Giratina",
	"cherrimo": "Cherrim",
	"cherrimovercast": "Cherrim",
	"meloettaa": "Meloetta",
	"meloettaaria": "Meloetta",
	"basculinr": "Basculin",
	"basculinred": "Basculin",
	"basculinredstripe": "Basculin",
	"basculinredstriped": "Basculin",
	"tornadusi": "Tornadus",
	"tornadusincarnation": "Tornadus",
	"thundurusi": "Thundurus",
	"thundurusincarnation": "Thundurus",
	"landorusi": "Landorus",
	"landorusincarnation": "Landorus",
	"pumpkabooaverage": "Pumpkaboo",
	"gourgeistaverage": "Gourgeist",

	// cosmetic formes
	"gastrodone": "Gastrodon",
	"gastrodoneast": "Gastrodon",
	"gastrodonw": "Gastrodon",
	"gastrodonwest": "Gastrodon",

	// items
	"band": "Choice Band",
	"cb": "Choice Band",
	"chesto": "Chesto Berry",
	"chople": "Chople Berry",
	"custap": "Custap Berry",
	"fightgem": "Fighting Gem",
	"flightgem": "Flying Gem",
	"lefties": "Leftovers",
	"lo": "Life Orb",
	"lum": "Lum Berry",
	"occa": "Occa Berry",
	"salac": "Salac Berry",
	"scarf": "Choice Scarf",
	"specs": "Choice Specs",
	"yache": "Yache Berry",
	"av": "Assault Vest",
	"assvest": "Assault Vest",

	// gen 1-2 berries
	"berry": "Oran Berry",
	"bitterberry": "Persim Berry",
	"burntberry": "Rawst Berry",
	"goldberry": "Sitrus Berry",
	"iceberry": "Aspear Berry",
	"mintberry": "Chesto Berry",
	"miracleberry": "Lum Berry",
	"mysteryberry": "Leppa Berry",
	"przcureberry": "Cheri Berry",
	"psncureberry": "Pecha Berry",

	// pokemon
	"aboma": "Abomasnow",
	"chomp": "Garchomp",
	"dnite": "Dragonite",
	"ferro": "Ferrothorn",
	"forry": "Forretress",
	"gar": "Gengar",
	"garde": "Gardevoir",
	"hippo": "Hippowdon",
	"kyub": "Kyurem-Black",
	"kyuw": "Kyurem-White",
	"lando": "Landorus",
	"landoi": "Landorus",
	"landot": "Landorus-Therian",
	"luke":  "Lucario",
	"mence": "Salamence",
	"p2": "Porygon2",
	"pory2": "Porygon2",
	"pz": "Porygon-Z",
	"poryz": "Porygon-Z",
	"rank": "Reuniclus",
	"talon": "Talonflame",
	"terra": "Terrakion",
	"ttar": "Tyranitar",
	"zam": "Alakazam",

	// moves
	"bpass": "Baton Pass",
	"cc": "Close Combat",
	"cm": "Calm Mind",
	"dd": "Dragon Dance",
	"eq": "Earthquake",
	"faintattack": "Feint Attack",
	"hjk": "High Jump Kick",
	"hijumpkick": "High Jump Kick",
	"np": "Nasty Plot",
	"pup": "Power-up Punch",
	"qd": "Quiver Dance",
	"rocks": "Stealth Rock",
	"sd": "Swords Dance",
	"se": "Stone Edge",
	"spin": "Rapid Spin",
	"sr": "Stealth Rock",
	"sub": "Substitute",
	"tr": "Trick Room",
	"tbolt": "Thunderbolt",
	"tspikes": "Toxic Spikes",
	"twave": "Thunder Wave",
	"web": "Sticky Web",
	"wow": "Will-O-Wisp",
	"playaround": "Play Rough",
	"glowpunch": "Power-up Punch",

	// Japanese names
	"birijion": "Virizion",
	"terakion": "Terrakion",
	"agirudaa": "Accelgor",
	"randorosu": "Landorus",
	"urugamosu": "Volcarona",
	"erufuun": "Whimsicott",
	"doryuuzu": "Excadrill",
	"burungeru": "Jellicent",
	"nattorei": "Ferrothorn",
	"shandera": "Chandelure",
	"roobushin": "Conkeldurr",
	"ononokusu": "Haxorus",
	"sazandora": "Hydreigon",
	"chirachiino": "Cinccino",
	"kyuremu": "Kyurem",
	"jarooda": "Serperior",
	"zoroaaku": "Zoroark",
	"shinboraa": "Sigilyph",
	"barujiina": "Mandibuzz",
	"rankurusu": "Reuniclus",
	"borutorosu": "Thundurus"
	// there's no need to type out the other Japanese names
	// I'll autogenerate them at some point
};
<commit_msg>Updated aliases.js with common terms<commit_after>exports.BattleAliases = {
	// formats
	"randbats": "Random Battle",
	"overused": "OU",
	"underused": "UU",
	"rarelyused": "RU",
	"neverused": "NU",
	"vgc": "VGC 2014",
	"bh": "Balanced Hackmons",
	"monotype": "OU Monotype",
	"createapokemon": "CAP",
	"cc1v1": "Challenge Cup 1vs1",

	// mega evos
	"megaabomasnow": "Abomasnow-Mega",
	"megaabsol": "Absol-Mega",
	"megaaerodactyl": "Aerodactyl-Mega",
	"megaaggron": "Aggron-Mega",
	"megaalakazam": "Alakazam-Mega",
	"megaampharos": "Ampharos-Mega",
	"megabanette": "Banette-Mega",
	"megablastoise": "Blastoise-Mega",
	"megablaziken": "Blaziken-Mega",
	"megacharizard": "Charizard-Mega-Y",
	"megacharizardx": "Charizard-Mega-X",
	"megacharizardy": "Charizard-Mega-Y",
	"megagarchomp": "Garchomp-Mega",
	"megagardevoir": "Gardevoir-Mega",
	"megagengar": "Gengar-Mega",
	"megagyarados": "Gyarados-Mega",
	"megaheracross": "Heracross-Mega",
	"megahoundoom": "Houndoom-Mega",
	"megakangaskhan": "Kangaskhan-Mega",
	"megalatias": "Latias-Mega",
	"megalatios": "Latios-Mega",
	"megalucario": "Lucario-Mega",
	"megaluke": "Lucario-Mega",
	"megamanectric": "Manectric-Mega",
	"megamawile": "Mawile-Mega",
	"megamaw": "Mawile-Mega",
	"megamedicham": "Medicham-Mega",
	"megamedi": "Medicham-Mega",
	"megamewtwo": "Mewtwo-Mega-Y",
	"megamewtwox": "Mewtwo-Mega-X",
	"megamewtwoy": "Mewtwo-Mega-Y",
	"megapinsir": "Pinsir-Mega",
	"megascizor": "Scizor-Mega",
	"megatyranitar": "Tyranitar-Mega",
	"megattar": "Tyranitar-Mega",
	"megavenusaur": "Venusaur-Mega",
	"megavenu": "Venusaur-Mega",
	"mmx": "Mewtwo-Mega-X",
	"mmy": "Mewtwo-Mega-Y",

	// formes
	"basculinb": "Basculin-Blue-Striped",
	"basculinblue": "Basculin-Blue-Striped",
	"basculinbluestripe": "Basculin-Blue-Striped",
	"castformh": "Castform-Snowy",
	"castformice": "Castform-Snowy",
	"castformr": "Castform-Rainy",
	"castformwater": "Castform-Rainy",
	"castforms": "Castform-Sunny",
	"castformfire": "Castform-Sunny",
	"cherrims": "Cherrim-Sunshine",
	"cherrimsunny": "Cherrim-Sunshine",
	"darmanitanz": "Darmanitan-Zen",
	"darmanitanzenmode": "Darmanitan-Zen",
	"deoxysnormal": "Deoxys",
	"deon": "Deoxys",
	"deoxysa": "Deoxys-Attack",
	"deoa": "Deoxys-Attack",
	"deoxysd": "Deoxys-Defense",
	"deoxysdefence": "Deoxys-Defense",
	"deod": "Deoxys-Defense",
	"deoxyss": "Deoxys-Speed",
	"deos": "Deoxys-Speed",
	"giratinao": "Giratina-Origin",
	"gourgeisthuge": "Gourgeist-Super",
	"keldeor": "Keldeo-Resolute",
	"keldeoresolution": "Keldeo-Resolute",
	"kyuremb": "Kyurem-Black",
	"kyuremw": "Kyurem-White",
	"landorust": "Landorus-Therian",
	"meloettap": "Meloetta-Pirouette",
	"meloettas": "Meloetta-Pirouette",
	"pumpkaboohuge": "Pumpkaboo-Super",
	"rotomc": "Rotom-Mow",
	"rotomf": "Rotom-Frost",
	"rotomh": "Rotom-Heat",
	"rotoms": "Rotom-Fan",
	"rotomw": "Rotom-Wash",
	"shaymins": "Shaymin-Sky",
	"skymin": "Shaymin-Sky",
	"thundurust": "Thundurus-Therian",
	"tornadust": "Tornadus-Therian",
	"wormadamg": "Wormadam-Sandy",
	"wormadamground": "Wormadam-Sandy",
	"wormadams": "Wormadam-Trash",
	"wormadamsteel": "Wormadam-Trash",
	"floettee": "Floette-Eternal-Flower",

	// base formes
	"nidoranfemale": "Nidoran-F",
	"nidoranmale": "Nidoran-M",
	"giratinaa": "Giratina",
	"giratinaaltered": "Giratina",
	"cherrimo": "Cherrim",
	"cherrimovercast": "Cherrim",
	"meloettaa": "Meloetta",
	"meloettaaria": "Meloetta",
	"basculinr": "Basculin",
	"basculinred": "Basculin",
	"basculinredstripe": "Basculin",
	"basculinredstriped": "Basculin",
	"tornadusi": "Tornadus",
	"tornadusincarnation": "Tornadus",
	"thundurusi": "Thundurus",
	"thundurusincarnation": "Thundurus",
	"landorusi": "Landorus",
	"landorusincarnation": "Landorus",
	"pumpkabooaverage": "Pumpkaboo",
	"gourgeistaverage": "Gourgeist",

	// cosmetic formes
	"gastrodone": "Gastrodon",
	"gastrodoneast": "Gastrodon",
	"gastrodonw": "Gastrodon",
	"gastrodonwest": "Gastrodon",

	// items
	"band": "Choice Band",
	"cb": "Choice Band",
	"chesto": "Chesto Berry",
	"chople": "Chople Berry",
	"custap": "Custap Berry",
	"fightgem": "Fighting Gem",
	"flightgem": "Flying Gem",
	"lefties": "Leftovers",
	"lo": "Life Orb",
	"lum": "Lum Berry",
	"occa": "Occa Berry",
	"salac": "Salac Berry",
	"scarf": "Choice Scarf",
	"specs": "Choice Specs",
	"yache": "Yache Berry",
	"av": "Assault Vest",
	"assvest": "Assault Vest",

	// gen 1-2 berries
	"berry": "Oran Berry",
	"bitterberry": "Persim Berry",
	"burntberry": "Rawst Berry",
	"goldberry": "Sitrus Berry",
	"iceberry": "Aspear Berry",
	"mintberry": "Chesto Berry",
	"miracleberry": "Lum Berry",
	"mysteryberry": "Leppa Berry",
	"przcureberry": "Cheri Berry",
	"psncureberry": "Pecha Berry",

	// pokemon
	"aboma": "Abomasnow",
	"chomp": "Garchomp",
	"dnite": "Dragonite",
	"don": "Groudon",
	"ferro": "Ferrothorn",
	"forry": "Forretress",
	"gar": "Gengar",
	"garde": "Gardevoir",
	"hippo": "Hippowdon",
	"kyub": "Kyurem-Black",
	"kyuw": "Kyurem-White",
	"lando": "Landorus",
	"landoi": "Landorus",
	"landot": "Landorus-Therian",
	"luke":  "Lucario",
	"mence": "Salamence",
	"ogre": "Kyogre",
	"p2": "Porygon2",
	"pory2": "Porygon2",
	"pz": "Porygon-Z",
	"poryz": "Porygon-Z",
	"rank": "Reuniclus",
	"talon": "Talonflame",
	"terra": "Terrakion",
	"ttar": "Tyranitar",
	"zam": "Alakazam",

	// moves
	"bpass": "Baton Pass",
	"cc": "Close Combat",
	"cm": "Calm Mind",
	"dd": "Dragon Dance",
	"eq": "Earthquake",
	"espeed": "ExtremeSpeed"
	"faintattack": "Feint Attack",
	"hjk": "High Jump Kick",
	"hijumpkick": "High Jump Kick",
	"np": "Nasty Plot",
	"pup": "Power-up Punch",
	"qd": "Quiver Dance",
	"rocks": "Stealth Rock",
	"sd": "Swords Dance",
	"se": "Stone Edge",
	"spin": "Rapid Spin",
	"sr": "Stealth Rock",
	"sub": "Substitute",
	"tr": "Trick Room",
	"troom": "Trick Room",
	"tbolt": "Thunderbolt",
	"tspikes": "Toxic Spikes",
	"twave": "Thunder Wave",
	"web": "Sticky Web",
	"wow": "Will-O-Wisp",
	"playaround": "Play Rough",
	"glowpunch": "Power-up Punch",

	// Japanese names
	"birijion": "Virizion",
	"terakion": "Terrakion",
	"agirudaa": "Accelgor",
	"randorosu": "Landorus",
	"urugamosu": "Volcarona",
	"erufuun": "Whimsicott",
	"doryuuzu": "Excadrill",
	"burungeru": "Jellicent",
	"nattorei": "Ferrothorn",
	"shandera": "Chandelure",
	"roobushin": "Conkeldurr",
	"ononokusu": "Haxorus",
	"sazandora": "Hydreigon",
	"chirachiino": "Cinccino",
	"kyuremu": "Kyurem",
	"jarooda": "Serperior",
	"zoroaaku": "Zoroark",
	"shinboraa": "Sigilyph",
	"barujiina": "Mandibuzz",
	"rankurusu": "Reuniclus",
	"borutorosu": "Thundurus"
	// there's no need to type out the other Japanese names
	// I'll autogenerate them at some point
};
<|endoftext|>