<commit_before>// ==UserScript==
// @name         Ads DOM Remover
// @namespace    sagiegurari
// @version      1.17
// @author       Sagie Gur-Ari
// @description  Removes Ad Containers from DOM (doesn't replace adblocker extension, but blocks dynamic content which the adblocker fails to block by removing whole sections from the HTML DOM.)
// @homepage     https://github.com/sagiegurari/userscripts-ads-dom-remover
// @supportURL   https://github.com/sagiegurari/userscripts-ads-dom-remover/issues
// @match        http://www.ynet.co.il/home/*
// @match        https://www.ynet.co.il/home/*
// @match        http://www.ynet.co.il/articles/*
// @match        https://www.ynet.co.il/articles/*
// @match        http://www.mynet.co.il/articles/*
// @match        https://www.mynet.co.il/articles/*
// @match        http://www.calcalist.co.il/*
// @match        https://www.calcalist.co.il/*
// @match        http://www.globes.co.il/*
// @match        https://www.globes.co.il/*
// @match        https://sourceforge.net/projects/*/download*
// @match        https://sourceforge.net/projects/*/postdownload*
// @match        http://subscenter.cinemast.com/*
// @match        https://subscenter.cinemast.com/*
// @match        http://www.subscenter.co/*
// @match        https://www.subscenter.co/*
// @match        http://www.subscenter.org/*
// @match        https://www.subscenter.org/*
// @match        https://*.wikipedia.org/*
// @match        http://*.techonthenet.com/*
// @match        https://*.techonthenet.com/*
// @match        http://www.opensubtitles.org/*
// @match        https://www.opensubtitles.org/*
// @match        http://*.wikia.com/wiki/*
// @match        https://*.wikia.com/wiki/*
// @match        http://*.reddit.com/*
// @match        https://*.reddit.com/*
// @require      https://code.jquery.com/jquery-2.2.2.min.js
// @require      https://greasyfork.org/scripts/18490-ads-dom-remover-runner/code/Ads%20DOM%20Remover%20Runner.js?version=189663
// @grant        none
// @license      MIT License
// ==/UserScript==

(function run($, runner) {
    'use strict';

    var selectorDefinitions = {
        ynet: {
            hostNames: [
                'ynet',
                'calcalist'
            ],
            selectors: [
                '#colorbox',
                '#cboxOverlay',
                '#ads.premium',
                '#articleLayoutrightsidtable',
                '#google_image_div',
                'img[src*="dynamicyield"]',
                'div.MSCmainContent',
                '[id*="arketingCarouse"]',
                '[id*="arketingRecommended"]',
                '.mainVerticalArticleSharingLinks',
                '.OUTBRAIN',
                '.topBannerWrap',
                '.block.B3 .B3.ghcite.dyother.dyMonitor div',
                '.bigdealhomepage',
                '#ww6s_Main',
                '.buyandsavedy',
                '.area.footer.ghcite',
                '.hdr_set_homepage',
                '#c1_Hor',
                '#c2_Hor',
                '#c3_Hor',
                '#c4_Hor',
                '#c5_Hor',
                '#c6_Hor',
                '.homepagevideo-x6',
                '.buyandsave',
                '.general-image',
                '.PhotoArticlesTalkbacks',
                '[name="ExternalWebpageIframe"]',
                '#PROCOIL_SearchForm',
                '#magazines1024',
                '[id^="promo_"]',
                '[id^="ads."]',
                '[class*="facebook"]',
                '[class*="WinWin"]',
                '.main_search_radio',
                'tr td [id^="ads."]',
                '.art-action-wrp',
                '.header-user-profile',
                '.left-art-content',
                '[class*="GeneralBanner"]',
                '#vilon',
                '#prime.shook',
                '#articlebottomsharinglinks',
                {
                    selector: '.homepagelitevideo',
                    fineTuneSelector: function ($element) {
                        return $element.parent().parent();
                    }
                },
                {
                    selector: 'iframe',
                    fineTuneSelector: function ($element) {
                        return $element.filter(function () {
                            return !$(this).parent().hasClass('news_ticker_iframe');
                        });
                    }
                },
                {
                    selector: 'div.B2b.block div',
                    pre: function ($element) {
                        $element.parent().css({
                            height: '1px'
                        });
                    }
                }
            ]
        },
        globes: {
            hostNames: 'globes',
            selectors: [
                '#chromeWindow',
                {
                    selector: 'iframe',
                    filter: function ($element) {
                        var id = $element.attr('id');
                        var src = $element.attr('src') || '';

                        return (id !== 'GlobalFinanceData_home') && (src.indexOf('/news/') !== -1);
                    }
                }
            ]
        },
        techonthenet: {
            hostNames: 'techonthenet.com',
            selectors: ['.adsblocked']
        },
        sourceforge: {
            hostNames: 'sourceforge.net',
            selectors: [
                '#content-for-adblock',
                '#newsletter-floating',
                '#page-body'
            ]
        },
        subscenter: {
            hostNames: 'subscenter',
            selectors: [
                '.weekBottom',
                '.reviewsWindow',
                '#banner_cinemast',
                '.bottomMenu',
                'footer',
                '#paypal',
                '#aboveSite',
                {
                    selector: '#subtitles_list a[href="/he/contactus/"]',
                    fineTuneSelector: function ($element) {
                        return $element.parent();
                    }
                }
            ]
        },
        wikipedia: {
            hostNames: 'wikipedia.org',
            selectors: [
                '#frbanner',
                '#frb-inline',
                '#wlm-banner',
                '#centralNotice',
                '.frb-main',
                '.frbanner',
                '.frm',
                '.frb'
            ]
        },
        opensubtitles: {
            hostNames: 'opensubtitles',
            selectors: ['.rec_container_right']
        },
        wikia: {
            hostNames: 'wikia.com',
            selectors: [
                '.WikiaFooter',
                '.WikiaRail',
                '.wds-global-footer'
            ]
        },
        reddit: {
            hostNames: 'reddit.com',
            selectors: [
                '#onboarding-splash'
            ]
        }
    };

    [
        '#dcPremiumRightImg',
        '.boulevard',
        '#multiarticles-9',
        '#multiarticles-12',
        '#multiarticles-13',
        '#multiarticles-14',
        '#multiarticles-15',
        '#multiarticles-16',
        '.CdaMostViews',
        '.CdaCalcalistToday',
        '.CdaRecomendedMovies',
        '#SpecialBuilder1280',
        '.cdaFooter1280'
    ].forEach(function addSelector(selector) {
        selectorDefinitions.ynet.selectors.push({
            selector: selector,
            fineTuneSelector: function ($element) {
                return $element.parent();
            }
        });
    });

    runner($, {
        getSelectorDefinitions: function () {
            return selectorDefinitions;
        }
    });
}(window.jQuery.noConflict(true), window.adrRunner));
<commit_msg>add boston globe<commit_after>// ==UserScript==
// @name         Ads DOM Remover
// @namespace    sagiegurari
// @version      1.18
// @author       Sagie Gur-Ari
// @description  Removes Ad Containers from DOM (doesn't replace adblocker extension, but blocks dynamic content which the adblocker fails to block by removing whole sections from the HTML DOM.)
// @homepage     https://github.com/sagiegurari/userscripts-ads-dom-remover
// @supportURL   https://github.com/sagiegurari/userscripts-ads-dom-remover/issues
// @match        http://www.ynet.co.il/home/*
// @match        https://www.ynet.co.il/home/*
// @match        http://www.ynet.co.il/articles/*
// @match        https://www.ynet.co.il/articles/*
// @match        http://www.mynet.co.il/articles/*
// @match        https://www.mynet.co.il/articles/*
// @match        http://www.calcalist.co.il/*
// @match        https://www.calcalist.co.il/*
// @match        http://www.globes.co.il/*
// @match        https://www.globes.co.il/*
// @match        https://sourceforge.net/projects/*/download*
// @match        https://sourceforge.net/projects/*/postdownload*
// @match        http://subscenter.cinemast.com/*
// @match        https://subscenter.cinemast.com/*
// @match        http://www.subscenter.co/*
// @match        https://www.subscenter.co/*
// @match        http://www.subscenter.org/*
// @match        https://www.subscenter.org/*
// @match        https://*.wikipedia.org/*
// @match        http://*.techonthenet.com/*
// @match        https://*.techonthenet.com/*
// @match        http://www.opensubtitles.org/*
// @match        https://www.opensubtitles.org/*
// @match        http://*.wikia.com/wiki/*
// @match        https://*.wikia.com/wiki/*
// @match        http://*.reddit.com/*
// @match        https://*.reddit.com/*
// @match        http://*.bostonglobe.com/*
// @match        https://*.bostonglobe.com/*
// @require      https://code.jquery.com/jquery-2.2.2.min.js
// @require      https://greasyfork.org/scripts/18490-ads-dom-remover-runner/code/Ads%20DOM%20Remover%20Runner.js?version=189663
// @grant        none
// @license      MIT License
// ==/UserScript==

(function run($, runner) {
    'use strict';

    var selectorDefinitions = {
        ynet: {
            hostNames: [
                'ynet',
                'calcalist'
            ],
            selectors: [
                '#colorbox',
                '#cboxOverlay',
                '#ads.premium',
                '#articleLayoutrightsidtable',
                '#google_image_div',
                'img[src*="dynamicyield"]',
                'div.MSCmainContent',
                '[id*="arketingCarouse"]',
                '[id*="arketingRecommended"]',
                '.mainVerticalArticleSharingLinks',
                '.OUTBRAIN',
                '.topBannerWrap',
                '.block.B3 .B3.ghcite.dyother.dyMonitor div',
                '.bigdealhomepage',
                '#ww6s_Main',
                '.buyandsavedy',
                '.area.footer.ghcite',
                '.hdr_set_homepage',
                '#c1_Hor',
                '#c2_Hor',
                '#c3_Hor',
                '#c4_Hor',
                '#c5_Hor',
                '#c6_Hor',
                '.homepagevideo-x6',
                '.buyandsave',
                '.general-image',
                '.PhotoArticlesTalkbacks',
                '[name="ExternalWebpageIframe"]',
                '#PROCOIL_SearchForm',
                '#magazines1024',
                '[id^="promo_"]',
                '[id^="ads."]',
                '[class*="facebook"]',
                '[class*="WinWin"]',
                '.main_search_radio',
                'tr td [id^="ads."]',
                '.art-action-wrp',
                '.header-user-profile',
                '.left-art-content',
                '[class*="GeneralBanner"]',
                '#vilon',
                '#prime.shook',
                '#articlebottomsharinglinks',
                {
                    selector: '.homepagelitevideo',
                    fineTuneSelector: function ($element) {
                        return $element.parent().parent();
                    }
                },
                {
                    selector: 'iframe',
                    fineTuneSelector: function ($element) {
                        return $element.filter(function () {
                            return !$(this).parent().hasClass('news_ticker_iframe');
                        });
                    }
                },
                {
                    selector: 'div.B2b.block div',
                    pre: function ($element) {
                        $element.parent().css({
                            height: '1px'
                        });
                    }
                }
            ]
        },
        globes: {
            hostNames: 'globes',
            selectors: [
                '#chromeWindow',
                {
                    selector: 'iframe',
                    filter: function ($element) {
                        var id = $element.attr('id');
                        var src = $element.attr('src') || '';

                        return (id !== 'GlobalFinanceData_home') && (src.indexOf('/news/') !== -1);
                    }
                }
            ]
        },
        techonthenet: {
            hostNames: 'techonthenet.com',
            selectors: ['.adsblocked']
        },
        sourceforge: {
            hostNames: 'sourceforge.net',
            selectors: [
                '#content-for-adblock',
                '#newsletter-floating',
                '#page-body'
            ]
        },
        subscenter: {
            hostNames: 'subscenter',
            selectors: [
                '.weekBottom',
                '.reviewsWindow',
                '#banner_cinemast',
                '.bottomMenu',
                'footer',
                '#paypal',
                '#aboveSite',
                {
                    selector: '#subtitles_list a[href="/he/contactus/"]',
                    fineTuneSelector: function ($element) {
                        return $element.parent();
                    }
                }
            ]
        },
        wikipedia: {
            hostNames: 'wikipedia.org',
            selectors: [
                '#frbanner',
                '#frb-inline',
                '#wlm-banner',
                '#centralNotice',
                '.frb-main',
                '.frbanner',
                '.frm',
                '.frb'
            ]
        },
        opensubtitles: {
            hostNames: 'opensubtitles',
            selectors: ['.rec_container_right']
        },
        wikia: {
            hostNames: 'wikia.com',
            selectors: [
                '.WikiaFooter',
                '.WikiaRail',
                '.wds-global-footer'
            ]
        },
        reddit: {
            hostNames: 'reddit.com',
            selectors: ['#onboarding-splash']
        },
        bostonglobe: {
            hostNames: 'bostonglobe.com',
            selectors: [
                '.meter-social-connect',
                '.meter-social-connect__container'
            ]
        }
    };

    [
        '#dcPremiumRightImg',
        '.boulevard',
        '#multiarticles-9',
        '#multiarticles-12',
        '#multiarticles-13',
        '#multiarticles-14',
        '#multiarticles-15',
        '#multiarticles-16',
        '.CdaMostViews',
        '.CdaCalcalistToday',
        '.CdaRecomendedMovies',
        '#SpecialBuilder1280',
        '.cdaFooter1280'
    ].forEach(function addSelector(selector) {
        selectorDefinitions.ynet.selectors.push({
            selector: selector,
            fineTuneSelector: function ($element) {
                return $element.parent();
            }
        });
    });

    runner($, {
        getSelectorDefinitions: function () {
            return selectorDefinitions;
        }
    });
}(window.jQuery.noConflict(true), window.adrRunner));
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';

var argv = require('minimist')(process.argv.slice(2));

const browserify = require('browserify');
const es6ify = require('es6ify');
const brfs = require('brfs');
const fs = require('fs');

var output = './bundle.js';
var w;
var debug = argv.d || false;

var i = 0;
if (argv.w) {
  let watchify = require('watchify');
  let b = browserify({cache: {}, packageCache: {}, debug: debug});

  applyTransforms(b);

  w = watchify(b);
  w.on('update', bundle);
  bundle();
}
else {
  var b = browserify({debug: debug});
  applyTransforms(b);
  b.bundle().pipe(process.stdout);
}

function bundle() {
  console.log('bundled', ++i);
  w.bundle()
    .on('error', function(e) {
      console.error(String(e))
    })
    .pipe(fs.createWriteStream(output))
  ;
}

function applyTransforms(b) {
  return b
    .add(es6ify.runtime)
    .transform(es6ify)
    .transform(brfs)
    .require(require.resolve('./'), {entry: true})
  ;
}
<commit_msg>Remove build.js<commit_after><|endoftext|>


<commit_before>/**
@module ember
@submodule ember-runtime
*/

// ..........................................................
// HELPERS
//
import Ember from "ember-metal/core"; // ES6TODO: Ember.A

import { get } from "ember-metal/property_get";
import { set } from "ember-metal/property_set";
import {
  computed,
  cacheFor
} from "ember-metal/computed";
import {
  isNone,
  none
} from 'ember-metal/is_none';
import Enumerable from "ember-runtime/mixins/enumerable";
import { map } from "ember-metal/enumerable_utils";
import {
  Mixin,
  required
} from "ember-metal/mixin";
import {
  propertyWillChange,
  propertyDidChange
} from "ember-metal/property_events";
import {
  addListener,
  removeListener,
  sendEvent,
  hasListeners
} from "ember-metal/events";
import { isWatching } from "ember-metal/watching";

// ..........................................................
// ARRAY
//
/**
  This mixin implements Observer-friendly Array-like behavior. It is not a
  concrete implementation, but it can be used up by other classes that want
  to appear like arrays.

  For example, ArrayProxy and ArrayController are both concrete classes that can
  be instantiated to implement array-like behavior. Both of these classes use
  the Array Mixin by way of the MutableArray mixin, which allows observable
  changes to be made to the underlying array.

  Unlike `Ember.Enumerable,` this mixin defines methods specifically for
  collections that provide index-ordered access to their contents. When you
  are designing code that needs to accept any kind of Array-like object, you
  should use these methods instead of Array primitives because these will
  properly notify observers of changes to the array.

  Although these methods are efficient, they do add a layer of indirection to
  your application so it is a good idea to use them only when you need the
  flexibility of using both true JavaScript arrays and "virtual" arrays such
  as controllers and collections.

  You can use the methods defined in this module to access and modify array
  contents in a KVO-friendly way. You can also be notified whenever the
  membership of an array changes by using `.observes('myArray.[]')`.

  To support `Ember.Array` in your own class, you must override two
  primitives to use it: `replace()` and `objectAt()`.

  Note that the Ember.Array mixin also incorporates the `Ember.Enumerable`
  mixin. All `Ember.Array`-like objects are also enumerable.

  @class Array
  @namespace Ember
  @uses Ember.Enumerable
  @since Ember 0.9.0
*/
export default Mixin.create(Enumerable, {

  /**
    Your array must support the `length` property. Your replace methods should
    set this property whenever it changes.

    @property {Number} length
  */
  length: required(),

  /**
    Returns the object at the given `index`. If the given `index` is negative
    or is greater or equal than the array length, returns `undefined`.

    This is one of the primitives you must implement to support `Ember.Array`.
    If your object supports retrieving the value of an array item using `get()`
    (i.e. `myArray.get(0)`), then you do not need to implement this method
    yourself.

    ```javascript
    var arr = ['a', 'b', 'c', 'd'];
    arr.objectAt(0);   // "a"
    arr.objectAt(3);   // "d"
    arr.objectAt(-1);  // undefined
    arr.objectAt(4);   // undefined
    arr.objectAt(5);   // undefined
    ```

    @method objectAt
    @param {Number} idx The index of the item to return.
    @return {*} item at index or undefined
  */
  objectAt: function(idx) {
    if ((idx < 0) || (idx >= get(this, 'length'))) return undefined;
    return get(this, idx);
  },

  /**
    This returns the objects at the specified indexes, using `objectAt`.

    ```javascript
    var arr = ['a', 'b', 'c', 'd'];
    arr.objectsAt([0, 1, 2]);  // ["a", "b", "c"]
    arr.objectsAt([2, 3, 4]);  // ["c", "d", undefined]
    ```

    @method objectsAt
    @param {Array} indexes An array of indexes of items to return.
    @return {Array}
   */
  objectsAt: function(indexes) {
    var self = this;
    return map(indexes, function(idx) { return self.objectAt(idx); });
  },

  // overrides Ember.Enumerable version
  nextObject: function(idx) {
    return this.objectAt(idx);
  },

  /**
    This is the handler for the special array content property. If you get
    this property, it will return this. If you set this property it a new
    array, it will replace the current content.

    This property overrides the default property defined in `Ember.Enumerable`.

    @property []
    @return this
  */
  '[]': computed(function(key, value) {
    if (value !== undefined) this.replace(0, get(this, 'length'), value) ;
    return this ;
  }),

  firstObject: computed(function() {
    return this.objectAt(0);
  }),

  lastObject: computed(function() {
    return this.objectAt(get(this, 'length')-1);
  }),

  // optimized version from Enumerable
  contains: function(obj) {
    return this.indexOf(obj) >= 0;
  },

  // Add any extra methods to Ember.Array that are native to the built-in Array.
  /**
    Returns a new array that is a slice of the receiver. This implementation
    uses the observable array methods to retrieve the objects for the new
    slice.

    ```javascript
    var arr = ['red', 'green', 'blue'];
    arr.slice(0);       // ['red', 'green', 'blue']
    arr.slice(0, 2);    // ['red', 'green']
    arr.slice(1, 100);  // ['green', 'blue']
    ```

    @method slice
    @param {Integer} beginIndex (Optional) index to begin slicing from.
    @param {Integer} endIndex (Optional) index to end the slice at (but not included).
    @return {Array} New array with specified slice
  */
  slice: function(beginIndex, endIndex) {
    var ret = Ember.A();
    var length = get(this, 'length') ;
    if (isNone(beginIndex)) beginIndex = 0 ;
    if (isNone(endIndex) || (endIndex > length)) endIndex = length ;

    if (beginIndex < 0) beginIndex = length + beginIndex;
    if (endIndex < 0) endIndex = length + endIndex;

    while(beginIndex < endIndex) {
      ret[ret.length] = this.objectAt(beginIndex++) ;
    }
    return ret ;
  },

  /**
    Returns the index of the given object's first occurrence.
    If no `startAt` argument is given, the starting location to
    search is 0. If it's negative, will count backward from
    the end of the array. Returns -1 if no match is found.

    ```javascript
    var arr = ["a", "b", "c", "d", "a"];
    arr.indexOf("a");       //  0
    arr.indexOf("z");       // -1
    arr.indexOf("a", 2);    //  4
    arr.indexOf("a", -1);   //  4
    arr.indexOf("b", 3);    // -1
    arr.indexOf("a", 100);  // -1
    ```

    @method indexOf
    @param {Object} object the item to search for
    @param {Number} startAt optional starting location to search, default 0
    @return {Number} index or -1 if not found
  */
  indexOf: function(object, startAt) {
    var idx, len = get(this, 'length');

    if (startAt === undefined) startAt = 0;
    if (startAt < 0) startAt += len;

    for(idx = startAt; idx < len; idx++) {
      if (this.objectAt(idx) === object) return idx;
    }
    return -1;
  },

  /**
    Returns the index of the given object's last occurrence.
    If no `startAt` argument is given, the search starts from
    the last position. If it's negative, will count backward
    from the end of the array. Returns -1 if no match is found.

    ```javascript
    var arr = ["a", "b", "c", "d", "a"];
    arr.lastIndexOf("a");       //  4
    arr.lastIndexOf("z");       // -1
    arr.lastIndexOf("a", 2);    //  0
    arr.lastIndexOf("a", -1);   //  4
    arr.lastIndexOf("b", 3);    //  1
    arr.lastIndexOf("a", 100);  //  4
    ```

    @method lastIndexOf
    @param {Object} object the item to search for
    @param {Number} startAt optional starting location to search, default 0
    @return {Number} index or -1 if not found
  */
  lastIndexOf: function(object, startAt) {
    var idx, len = get(this, 'length');

    if (startAt === undefined || startAt >= len) startAt = len-1;
    if (startAt < 0) startAt += len;

    for(idx = startAt; idx >= 0; idx--) {
      if (this.objectAt(idx) === object) return idx;
    }
    return -1;
  },

  // ..........................................................
  // ARRAY OBSERVERS
  //

  /**
    Adds an array observer to the receiving array. The array observer object
    normally must implement two methods:

    * `arrayWillChange(observedObj, start, removeCount, addCount)` - This method will be
      called just before the array is modified.
    * `arrayDidChange(observedObj, start, removeCount, addCount)` - This method will be
      called just after the array is modified.

    Both callbacks will be passed the observed object, starting index of the
    change as well a a count of the items to be removed and added. You can use
    these callbacks to optionally inspect the array during the change, clear
    caches, or do any other bookkeeping necessary.

    In addition to passing a target, you can also include an options hash
    which you can use to override the method names that will be invoked on the
    target.

    @method addArrayObserver
    @param {Object} target The observer object.
    @param {Hash} opts Optional hash of configuration options including
      `willChange` and `didChange` option.
    @return {Ember.Array} receiver
  */
  addArrayObserver: function(target, opts) {
    var willChange = (opts && opts.willChange) || 'arrayWillChange',
        didChange  = (opts && opts.didChange) || 'arrayDidChange';

    var hasObservers = get(this, 'hasArrayObservers');
    if (!hasObservers) propertyWillChange(this, 'hasArrayObservers');
    addListener(this, '@array:before', target, willChange);
    addListener(this, '@array:change', target, didChange);
    if (!hasObservers) propertyDidChange(this, 'hasArrayObservers');
    return this;
  },

  /**
    Removes an array observer from the object if the observer is current
    registered. Calling this method multiple times with the same object will
    have no effect.

    @method removeArrayObserver
    @param {Object} target The object observing the array.
    @param {Hash} opts Optional hash of configuration options including
      `willChange` and `didChange` option.
    @return {Ember.Array} receiver
  */
  removeArrayObserver: function(target, opts) {
    var willChange = (opts && opts.willChange) || 'arrayWillChange',
        didChange  = (opts && opts.didChange) || 'arrayDidChange';

    var hasObservers = get(this, 'hasArrayObservers');
    if (hasObservers) propertyWillChange(this, 'hasArrayObservers');
    removeListener(this, '@array:before', target, willChange);
    removeListener(this, '@array:change', target, didChange);
    if (hasObservers) propertyDidChange(this, 'hasArrayObservers');
    return this;
  },

  /**
    Becomes true whenever the array currently has observers watching changes
    on the array.

    @property {Boolean} hasArrayObservers
  */
  hasArrayObservers: computed(function() {
    return hasListeners(this, '@array:change') || hasListeners(this, '@array:before');
  }),

  /**
    If you are implementing an object that supports `Ember.Array`, call this
    method just before the array content changes to notify any observers and
    invalidate any related properties. Pass the starting index of the change
    as well as a delta of the amounts to change.

    @method arrayContentWillChange
    @param {Number} startIdx The starting index in the array that will change.
    @param {Number} removeAmt The number of items that will be removed. If you
      pass `null` assumes 0
    @param {Number} addAmt The number of items that will be added. If you
      pass `null` assumes 0.
    @return {Ember.Array} receiver
  */
  arrayContentWillChange: function(startIdx, removeAmt, addAmt) {

    // if no args are passed assume everything changes
    if (startIdx===undefined) {
      startIdx = 0;
      removeAmt = addAmt = -1;
    } else {
      if (removeAmt === undefined) removeAmt=-1;
      if (addAmt    === undefined) addAmt=-1;
    }

    // Make sure the @each proxy is set up if anyone is observing @each
    if (isWatching(this, '@each')) { get(this, '@each'); }

    sendEvent(this, '@array:before', [this, startIdx, removeAmt, addAmt]);

    var removing, lim;
    if (startIdx>=0 && removeAmt>=0 && get(this, 'hasEnumerableObservers')) {
      removing = [];
      lim = startIdx+removeAmt;
      for(var idx=startIdx;idx<lim;idx++) removing.push(this.objectAt(idx));
    } else {
      removing = removeAmt;
    }

    this.enumerableContentWillChange(removing, addAmt);

    return this;
  },

  /**
    If you are implementing an object that supports `Ember.Array`, call this
    method just after the array content changes to notify any observers and
    invalidate any related properties. Pass the starting index of the change
    as well as a delta of the amounts to change.

    @method arrayContentDidChange
    @param {Number} startIdx The starting index in the array that did change.
    @param {Number} removeAmt The number of items that were removed. If you
      pass `null` assumes 0
    @param {Number} addAmt The number of items that were added. If you
      pass `null` assumes 0.
    @return {Ember.Array} receiver
  */
  arrayContentDidChange: function(startIdx, removeAmt, addAmt) {

    // if no args are passed assume everything changes
    if (startIdx===undefined) {
      startIdx = 0;
      removeAmt = addAmt = -1;
    } else {
      if (removeAmt === undefined) removeAmt=-1;
      if (addAmt    === undefined) addAmt=-1;
    }

    var adding, lim;
    if (startIdx>=0 && addAmt>=0 && get(this, 'hasEnumerableObservers')) {
      adding = [];
      lim = startIdx+addAmt;
      for(var idx=startIdx;idx<lim;idx++) adding.push(this.objectAt(idx));
    } else {
      adding = addAmt;
    }

    this.enumerableContentDidChange(removeAmt, adding);
    sendEvent(this, '@array:change', [this, startIdx, removeAmt, addAmt]);

    var length      = get(this, 'length'),
        cachedFirst = cacheFor(this, 'firstObject'),
        cachedLast  = cacheFor(this, 'lastObject');
    if (this.objectAt(0) !== cachedFirst) {
      propertyWillChange(this, 'firstObject');
      propertyDidChange(this, 'firstObject');
    }
    if (this.objectAt(length-1) !== cachedLast) {
      propertyWillChange(this, 'lastObject');
      propertyDidChange(this, 'lastObject');
    }

    return this;
  },

  // ..........................................................
  // ENUMERATED PROPERTIES
  //

  /**
    Returns a special object that can be used to observe individual properties
    on the array. Just get an equivalent property on this object and it will
    return an enumerable that maps automatically to the named key on the
    member objects.

    If you merely want to watch for any items being added or removed to the array,
    use the `[]` property instead of `@each`.

    @property @each
  */
  '@each': computed(function() {
    if (!this.__each) {
      // ES6TODO: GRRRRR
      var EachProxy = requireModule('ember-runtime/system/each_proxy')['EachProxy'];

      this.__each = new EachProxy(this);
    }

    return this.__each;
  })
});
<commit_msg>[DOC] Fix typo in Array docs<commit_after>/**
@module ember
@submodule ember-runtime
*/

// ..........................................................
// HELPERS
//
import Ember from "ember-metal/core"; // ES6TODO: Ember.A

import { get } from "ember-metal/property_get";
import { set } from "ember-metal/property_set";
import {
  computed,
  cacheFor
} from "ember-metal/computed";
import {
  isNone,
  none
} from 'ember-metal/is_none';
import Enumerable from "ember-runtime/mixins/enumerable";
import { map } from "ember-metal/enumerable_utils";
import {
  Mixin,
  required
} from "ember-metal/mixin";
import {
  propertyWillChange,
  propertyDidChange
} from "ember-metal/property_events";
import {
  addListener,
  removeListener,
  sendEvent,
  hasListeners
} from "ember-metal/events";
import { isWatching } from "ember-metal/watching";

// ..........................................................
// ARRAY
//
/**
  This mixin implements Observer-friendly Array-like behavior. It is not a
  concrete implementation, but it can be used up by other classes that want
  to appear like arrays.

  For example, ArrayProxy and ArrayController are both concrete classes that can
  be instantiated to implement array-like behavior. Both of these classes use
  the Array Mixin by way of the MutableArray mixin, which allows observable
  changes to be made to the underlying array.

  Unlike `Ember.Enumerable,` this mixin defines methods specifically for
  collections that provide index-ordered access to their contents. When you
  are designing code that needs to accept any kind of Array-like object, you
  should use these methods instead of Array primitives because these will
  properly notify observers of changes to the array.

  Although these methods are efficient, they do add a layer of indirection to
  your application so it is a good idea to use them only when you need the
  flexibility of using both true JavaScript arrays and "virtual" arrays such
  as controllers and collections.

  You can use the methods defined in this module to access and modify array
  contents in a KVO-friendly way. You can also be notified whenever the
  membership of an array changes by using `.observes('myArray.[]')`.

  To support `Ember.Array` in your own class, you must override two
  primitives to use it: `replace()` and `objectAt()`.

  Note that the Ember.Array mixin also incorporates the `Ember.Enumerable`
  mixin. All `Ember.Array`-like objects are also enumerable.

  @class Array
  @namespace Ember
  @uses Ember.Enumerable
  @since Ember 0.9.0
*/
export default Mixin.create(Enumerable, {

  /**
    Your array must support the `length` property. Your replace methods should
    set this property whenever it changes.

    @property {Number} length
  */
  length: required(),

  /**
    Returns the object at the given `index`. If the given `index` is negative
    or is greater or equal than the array length, returns `undefined`.

    This is one of the primitives you must implement to support `Ember.Array`.
    If your object supports retrieving the value of an array item using `get()`
    (i.e. `myArray.get(0)`), then you do not need to implement this method
    yourself.

    ```javascript
    var arr = ['a', 'b', 'c', 'd'];
    arr.objectAt(0);   // "a"
    arr.objectAt(3);   // "d"
    arr.objectAt(-1);  // undefined
    arr.objectAt(4);   // undefined
    arr.objectAt(5);   // undefined
    ```

    @method objectAt
    @param {Number} idx The index of the item to return.
    @return {*} item at index or undefined
  */
  objectAt: function(idx) {
    if ((idx < 0) || (idx >= get(this, 'length'))) return undefined;
    return get(this, idx);
  },

  /**
    This returns the objects at the specified indexes, using `objectAt`.

    ```javascript
    var arr = ['a', 'b', 'c', 'd'];
    arr.objectsAt([0, 1, 2]);  // ["a", "b", "c"]
    arr.objectsAt([2, 3, 4]);  // ["c", "d", undefined]
    ```

    @method objectsAt
    @param {Array} indexes An array of indexes of items to return.
    @return {Array}
   */
  objectsAt: function(indexes) {
    var self = this;
    return map(indexes, function(idx) { return self.objectAt(idx); });
  },

  // overrides Ember.Enumerable version
  nextObject: function(idx) {
    return this.objectAt(idx);
  },

  /**
    This is the handler for the special array content property. If you get
    this property, it will return this. If you set this property to a new
    array, it will replace the current content.

    This property overrides the default property defined in `Ember.Enumerable`.

    @property []
    @return this
  */
  '[]': computed(function(key, value) {
    if (value !== undefined) this.replace(0, get(this, 'length'), value) ;
    return this ;
  }),

  firstObject: computed(function() {
    return this.objectAt(0);
  }),

  lastObject: computed(function() {
    return this.objectAt(get(this, 'length')-1);
  }),

  // optimized version from Enumerable
  contains: function(obj) {
    return this.indexOf(obj) >= 0;
  },

  // Add any extra methods to Ember.Array that are native to the built-in Array.
  /**
    Returns a new array that is a slice of the receiver. This implementation
    uses the observable array methods to retrieve the objects for the new
    slice.

    ```javascript
    var arr = ['red', 'green', 'blue'];
    arr.slice(0);       // ['red', 'green', 'blue']
    arr.slice(0, 2);    // ['red', 'green']
    arr.slice(1, 100);  // ['green', 'blue']
    ```

    @method slice
    @param {Integer} beginIndex (Optional) index to begin slicing from.
    @param {Integer} endIndex (Optional) index to end the slice at (but not included).
    @return {Array} New array with specified slice
  */
  slice: function(beginIndex, endIndex) {
    var ret = Ember.A();
    var length = get(this, 'length') ;
    if (isNone(beginIndex)) beginIndex = 0 ;
    if (isNone(endIndex) || (endIndex > length)) endIndex = length ;

    if (beginIndex < 0) beginIndex = length + beginIndex;
    if (endIndex < 0) endIndex = length + endIndex;

    while(beginIndex < endIndex) {
      ret[ret.length] = this.objectAt(beginIndex++) ;
    }
    return ret ;
  },

  /**
    Returns the index of the given object's first occurrence.
    If no `startAt` argument is given, the starting location to
    search is 0. If it's negative, will count backward from
    the end of the array. Returns -1 if no match is found.

    ```javascript
    var arr = ["a", "b", "c", "d", "a"];
    arr.indexOf("a");       //  0
    arr.indexOf("z");       // -1
    arr.indexOf("a", 2);    //  4
    arr.indexOf("a", -1);   //  4
    arr.indexOf("b", 3);    // -1
    arr.indexOf("a", 100);  // -1
    ```

    @method indexOf
    @param {Object} object the item to search for
    @param {Number} startAt optional starting location to search, default 0
    @return {Number} index or -1 if not found
  */
  indexOf: function(object, startAt) {
    var idx, len = get(this, 'length');

    if (startAt === undefined) startAt = 0;
    if (startAt < 0) startAt += len;

    for(idx = startAt; idx < len; idx++) {
      if (this.objectAt(idx) === object) return idx;
    }
    return -1;
  },

  /**
    Returns the index of the given object's last occurrence.
    If no `startAt` argument is given, the search starts from
    the last position. If it's negative, will count backward
    from the end of the array. Returns -1 if no match is found.

    ```javascript
    var arr = ["a", "b", "c", "d", "a"];
    arr.lastIndexOf("a");       //  4
    arr.lastIndexOf("z");       // -1
    arr.lastIndexOf("a", 2);    //  0
    arr.lastIndexOf("a", -1);   //  4
    arr.lastIndexOf("b", 3);    //  1
    arr.lastIndexOf("a", 100);  //  4
    ```

    @method lastIndexOf
    @param {Object} object the item to search for
    @param {Number} startAt optional starting location to search, default 0
    @return {Number} index or -1 if not found
  */
  lastIndexOf: function(object, startAt) {
    var idx, len = get(this, 'length');

    if (startAt === undefined || startAt >= len) startAt = len-1;
    if (startAt < 0) startAt += len;

    for(idx = startAt; idx >= 0; idx--) {
      if (this.objectAt(idx) === object) return idx;
    }
    return -1;
  },

  // ..........................................................
  // ARRAY OBSERVERS
  //

  /**
    Adds an array observer to the receiving array. The array observer object
    normally must implement two methods:

    * `arrayWillChange(observedObj, start, removeCount, addCount)` - This method will be
      called just before the array is modified.
    * `arrayDidChange(observedObj, start, removeCount, addCount)` - This method will be
      called just after the array is modified.

    Both callbacks will be passed the observed object, starting index of the
    change as well a a count of the items to be removed and added. You can use
    these callbacks to optionally inspect the array during the change, clear
    caches, or do any other bookkeeping necessary.

    In addition to passing a target, you can also include an options hash
    which you can use to override the method names that will be invoked on the
    target.

    @method addArrayObserver
    @param {Object} target The observer object.
    @param {Hash} opts Optional hash of configuration options including
      `willChange` and `didChange` option.
    @return {Ember.Array} receiver
  */
  addArrayObserver: function(target, opts) {
    var willChange = (opts && opts.willChange) || 'arrayWillChange',
        didChange  = (opts && opts.didChange) || 'arrayDidChange';

    var hasObservers = get(this, 'hasArrayObservers');
    if (!hasObservers) propertyWillChange(this, 'hasArrayObservers');
    addListener(this, '@array:before', target, willChange);
    addListener(this, '@array:change', target, didChange);
    if (!hasObservers) propertyDidChange(this, 'hasArrayObservers');
    return this;
  },

  /**
    Removes an array observer from the object if the observer is current
    registered. Calling this method multiple times with the same object will
    have no effect.

    @method removeArrayObserver
    @param {Object} target The object observing the array.
    @param {Hash} opts Optional hash of configuration options including
      `willChange` and `didChange` option.
    @return {Ember.Array} receiver
  */
  removeArrayObserver: function(target, opts) {
    var willChange = (opts && opts.willChange) || 'arrayWillChange',
        didChange  = (opts && opts.didChange) || 'arrayDidChange';

    var hasObservers = get(this, 'hasArrayObservers');
    if (hasObservers) propertyWillChange(this, 'hasArrayObservers');
    removeListener(this, '@array:before', target, willChange);
    removeListener(this, '@array:change', target, didChange);
    if (hasObservers) propertyDidChange(this, 'hasArrayObservers');
    return this;
  },

  /**
    Becomes true whenever the array currently has observers watching changes
    on the array.

    @property {Boolean} hasArrayObservers
  */
  hasArrayObservers: computed(function() {
    return hasListeners(this, '@array:change') || hasListeners(this, '@array:before');
  }),

  /**
    If you are implementing an object that supports `Ember.Array`, call this
    method just before the array content changes to notify any observers and
    invalidate any related properties. Pass the starting index of the change
    as well as a delta of the amounts to change.

    @method arrayContentWillChange
    @param {Number} startIdx The starting index in the array that will change.
    @param {Number} removeAmt The number of items that will be removed. If you
      pass `null` assumes 0
    @param {Number} addAmt The number of items that will be added. If you
      pass `null` assumes 0.
    @return {Ember.Array} receiver
  */
  arrayContentWillChange: function(startIdx, removeAmt, addAmt) {

    // if no args are passed assume everything changes
    if (startIdx===undefined) {
      startIdx = 0;
      removeAmt = addAmt = -1;
    } else {
      if (removeAmt === undefined) removeAmt=-1;
      if (addAmt    === undefined) addAmt=-1;
    }

    // Make sure the @each proxy is set up if anyone is observing @each
    if (isWatching(this, '@each')) { get(this, '@each'); }

    sendEvent(this, '@array:before', [this, startIdx, removeAmt, addAmt]);

    var removing, lim;
    if (startIdx>=0 && removeAmt>=0 && get(this, 'hasEnumerableObservers')) {
      removing = [];
      lim = startIdx+removeAmt;
      for(var idx=startIdx;idx<lim;idx++) removing.push(this.objectAt(idx));
    } else {
      removing = removeAmt;
    }

    this.enumerableContentWillChange(removing, addAmt);

    return this;
  },

  /**
    If you are implementing an object that supports `Ember.Array`, call this
    method just after the array content changes to notify any observers and
    invalidate any related properties. Pass the starting index of the change
    as well as a delta of the amounts to change.

    @method arrayContentDidChange
    @param {Number} startIdx The starting index in the array that did change.
    @param {Number} removeAmt The number of items that were removed. If you
      pass `null` assumes 0
    @param {Number} addAmt The number of items that were added. If you
      pass `null` assumes 0.
    @return {Ember.Array} receiver
  */
  arrayContentDidChange: function(startIdx, removeAmt, addAmt) {

    // if no args are passed assume everything changes
    if (startIdx===undefined) {
      startIdx = 0;
      removeAmt = addAmt = -1;
    } else {
      if (removeAmt === undefined) removeAmt=-1;
      if (addAmt    === undefined) addAmt=-1;
    }

    var adding, lim;
    if (startIdx>=0 && addAmt>=0 && get(this, 'hasEnumerableObservers')) {
      adding = [];
      lim = startIdx+addAmt;
      for(var idx=startIdx;idx<lim;idx++) adding.push(this.objectAt(idx));
    } else {
      adding = addAmt;
    }

    this.enumerableContentDidChange(removeAmt, adding);
    sendEvent(this, '@array:change', [this, startIdx, removeAmt, addAmt]);

    var length      = get(this, 'length'),
        cachedFirst = cacheFor(this, 'firstObject'),
        cachedLast  = cacheFor(this, 'lastObject');
    if (this.objectAt(0) !== cachedFirst) {
      propertyWillChange(this, 'firstObject');
      propertyDidChange(this, 'firstObject');
    }
    if (this.objectAt(length-1) !== cachedLast) {
      propertyWillChange(this, 'lastObject');
      propertyDidChange(this, 'lastObject');
    }

    return this;
  },

  // ..........................................................
  // ENUMERATED PROPERTIES
  //

  /**
    Returns a special object that can be used to observe individual properties
    on the array. Just get an equivalent property on this object and it will
    return an enumerable that maps automatically to the named key on the
    member objects.

    If you merely want to watch for any items being added or removed to the array,
    use the `[]` property instead of `@each`.

    @property @each
  */
  '@each': computed(function() {
    if (!this.__each) {
      // ES6TODO: GRRRRR
      var EachProxy = requireModule('ember-runtime/system/each_proxy')['EachProxy'];

      this.__each = new EachProxy(this);
    }

    return this.__each;
  })
});
<|endoftext|>


<commit_before>const { Pool } = require('pg');
const express = require('express');
const uuidv4 = require('uuid/v4');
const bcrypt = require('bcrypt');
const asyncHandler = require('express-async-handler');
const { check, validationResult } = require('express-validator/check');
const { matchedData, sanitize } = require('express-validator/filter');
const error = require('./utils').appThrow;
var app = express();
const pool = new Pool({ connectionString: process.env.DATABASE_URL });

var requireUser = asyncHandler(async (req, res, next) => {
  var userId = req.body.id;
  var token = req.body.token;
  const queryResult = await pool.query('SELECT * FROM users WHERE id = $1;', [userId]);
  if (queryResult.rows.length != 1) {
    error(403, "user");
    return;
  }
  var user = queryResult.rows[0];
  if (!await bcrypt.compare(token, queryResult.rows[0].token)) {
    error(403, "user");
    return;
  }
  req.user = user;
  next();
});
var router = express.Router();
router.get('/users', asyncHandler(async (req, res) => {
  const queryResult = await pool.query('SELECT * FROM users;');
  res.send(JSON.stringify(queryResult.rows));
}));
router.post('/users/new', asyncHandler(async (req, res) => {
  var rawToken = uuidv4();
  var token = await bcrypt.hash(rawToken, 10);
  const queryResult = await pool.query('INSERT INTO users (token) VALUES ($1) RETURNING id;', [token]);
  res.send(JSON.stringify({id: queryResult.rows[0].id, token: rawToken}));
}));
router.get('/mai/:nickname', asyncHandler(async (req, res) => {
  var nickname = req.params.nickname;
  const queryResult = await pool.query('SELECT * FROM laundry_players WHERE nickname = $1;', [nickname]);
  if (queryResult.rows.length == 0) {
    error(404, "not_found");
  }
  var player = queryResult.rows[0];
  const recordResult = await pool.query('SELECT * FROM laundry_records_recent WHERE player_id = $1;', [player.id]);
  if (recordResult.rows.length > 0) {
    player.record = recordResult.rows[0];
  }
  const scoreResult = await pool.query('SELECT * FROM laundry_scores_recent WHERE player_id = $1;', [player.id]);
  if (scoreResult.rows.length > 0) {
    player.scores = scoreResult.rows;
  }
  res.send(JSON.stringify(player));
}));
router.post('/mai/new', express.json({ limit: '50kb' }), requireUser, [
  check('nickname').matches(/[0-9a-z\-\_]/),
  check('privacy').matches(/^(public|anonymous|private)$/)
], asyncHandler(async (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    console.log(errors.mapped());
    error(422, "validation");
  }
  var data = matchedData(req);
  var nickname = data.nickname;
  var privacy = data.privacy;
  var user = req.user;
  const queryResult = await pool.query('SELECT id FROM laundry_players WHERE nickname = $1;', [nickname]);
  if (queryResult.rows.length > 0) {
    error(400, "exists");
    return;
  }
  await pool.query('INSERT INTO laundry_players (nickname, user_id, privacy) VALUES ($1, $2, $3);', [nickname, user.id, privacy]);
  res.send(JSON.stringify({}));
}));

router.post('/mai/:nickname',  express.json({ limit: '2mb' }), requireUser, [
  check('cardName').isString(),
  check('rating').isFloat({min: 0, max: 20}),
  check('maxRating').isFloat({min: 0, max: 20}),
  check('icon').isString(),
  check('title').isString(),
  check('class').isString()
  ], asyncHandler(async (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    console.log(errors.mapped());
    error(422, "validation");
  }
  var data = matchedData(req);
  var nickname = req.params.nickname;
  var user = req.user;
  const queryResult = await pool.query('SELECT id, user_id FROM laundry_players WHERE nickname = $1;', [nickname]);
  if (queryResult.rows.length == 0) {
    error(404, "not_exists");
    return;
  }
  var player = queryResult.rows[0];
  if (player.user_id != user.id) {
    error(403, "forbidden");
    return;
  }
  await pool.query(`INSERT INTO laundry_records_recent
                   (player_id, card_name, rating, max_rating, icon, title, class) VALUES ($1, $2, $3, $4, $5, $6, $7)
                   ON CONFLICT(player_id) DO UPDATE SET card_name = $2, rating = $3, max_rating = $4, icon = $5, title = $6, class = $7;`,
                  [player.id, data.cardName, data.rating, data.maxRating, data.icon, data.title, data.class]);

  var scores = req.body.scores;
  for (var i = 0; i < scores.length; i++) {
    var score = scores[i];
    if (!score.flag) { score.flag = ''; }
    await pool.query(`INSERT INTO laundry_scores_recent
                     (player_id, seq, category, song_name, difficulty, score, flag) VALUES ($1, $2, $3, $4, $5, $6, $7)
                     ON CONFLICT(category, song_name, difficulty, player_id) DO UPDATE SET seq = $2, category = $3, song_name = $4, difficulty = $5, score = $6, flag = $7;`,
                    [player.id, i, score.category, score.songName, score.difficulty, score.score, score.flag]);
  }
  res.send(JSON.stringify({}));
}));
app.use("/api", router);
app.use(function(err, req, res, next) {
  if (!err.exposed) {
    console.log(err);
    res.status(500).send(JSON.stringify({"err": "internal"}));
  } else {
    res.status(err.status).send(JSON.stringify({"err": err.message}));
  }
});

app.listen(8585);
<commit_msg>Use prepared statement.<commit_after>const { Pool } = require('pg');
const express = require('express');
const uuidv4 = require('uuid/v4');
const bcrypt = require('bcrypt');
const asyncHandler = require('express-async-handler');
const { check, validationResult } = require('express-validator/check');
const { matchedData, sanitize } = require('express-validator/filter');
const error = require('./utils').appThrow;
var app = express();
const pool = new Pool({ connectionString: process.env.DATABASE_URL });

var requireUser = asyncHandler(async (req, res, next) => {
  var userId = req.body.id;
  var token = req.body.token;
  const queryResult = await pool.query('SELECT * FROM users WHERE id = $1;', [userId]);
  if (queryResult.rows.length != 1) {
    error(403, "user");
    return;
  }
  var user = queryResult.rows[0];
  if (!await bcrypt.compare(token, queryResult.rows[0].token)) {
    error(403, "user");
    return;
  }
  req.user = user;
  next();
});
var router = express.Router();
router.get('/users', asyncHandler(async (req, res) => {
  const queryResult = await pool.query('SELECT * FROM users;');
  res.send(JSON.stringify(queryResult.rows));
}));
router.post('/users/new', asyncHandler(async (req, res) => {
  var rawToken = uuidv4();
  var token = await bcrypt.hash(rawToken, 10);
  const queryResult = await pool.query('INSERT INTO users (token) VALUES ($1) RETURNING id;', [token]);
  res.send(JSON.stringify({id: queryResult.rows[0].id, token: rawToken}));
}));
router.get('/mai/:nickname', asyncHandler(async (req, res) => {
  var nickname = req.params.nickname;
  const queryResult = await pool.query('SELECT * FROM laundry_players WHERE nickname = $1;', [nickname]);
  if (queryResult.rows.length == 0) {
    error(404, "not_found");
  }
  var player = queryResult.rows[0];
  const recordResult = await pool.query('SELECT * FROM laundry_records_recent WHERE player_id = $1;', [player.id]);
  if (recordResult.rows.length > 0) {
    player.record = recordResult.rows[0];
  }
  const scoreResult = await pool.query('SELECT * FROM laundry_scores_recent WHERE player_id = $1;', [player.id]);
  if (scoreResult.rows.length > 0) {
    player.scores = scoreResult.rows;
  }
  res.send(JSON.stringify(player));
}));
router.post('/mai/new', express.json({ limit: '50kb' }), requireUser, [
  check('nickname').matches(/[0-9a-z\-\_]/),
  check('privacy').matches(/^(public|anonymous|private)$/)
], asyncHandler(async (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    console.log(errors.mapped());
    error(422, "validation");
  }
  var data = matchedData(req);
  var nickname = data.nickname;
  var privacy = data.privacy;
  var user = req.user;
  const queryResult = await pool.query('SELECT id FROM laundry_players WHERE nickname = $1;', [nickname]);
  if (queryResult.rows.length > 0) {
    error(400, "exists");
    return;
  }
  await pool.query('INSERT INTO laundry_players (nickname, user_id, privacy) VALUES ($1, $2, $3);', [nickname, user.id, privacy]);
  res.send(JSON.stringify({}));
}));

router.post('/mai/:nickname',  express.json({ limit: '2mb' }), requireUser, [
  check('cardName').isString(),
  check('rating').isFloat({min: 0, max: 20}),
  check('maxRating').isFloat({min: 0, max: 20}),
  check('icon').isString(),
  check('title').isString(),
  check('class').isString()
  ], asyncHandler(async (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    console.log(errors.mapped());
    error(422, "validation");
  }
  var data = matchedData(req);
  var nickname = req.params.nickname;
  var user = req.user;
  const queryResult = await pool.query('SELECT id, user_id FROM laundry_players WHERE nickname = $1;', [nickname]);
  if (queryResult.rows.length == 0) {
    error(404, "not_exists");
    return;
  }
  var player = queryResult.rows[0];
  if (player.user_id != user.id) {
    error(403, "forbidden");
    return;
  }
  await pool.query(`INSERT INTO laundry_records_recent
                   (player_id, card_name, rating, max_rating, icon, title, class) VALUES ($1, $2, $3, $4, $5, $6, $7)
                   ON CONFLICT(player_id) DO UPDATE SET card_name = $2, rating = $3, max_rating = $4, icon = $5, title = $6, class = $7;`,
                  [player.id, data.cardName, data.rating, data.maxRating, data.icon, data.title, data.class]);

  var scores = req.body.scores;
  for (var i = 0; i < scores.length; i++) {
    var score = scores[i];
    if (!score.flag) { score.flag = ''; }
    const query = {
      name: 'insert-scores-recent',
      text: `INSERT INTO laundry_scores_recent
                     (player_id, seq, category, song_name, difficulty, score, flag) VALUES ($1, $2, $3, $4, $5, $6, $7)
      ON CONFLICT(category, song_name, difficulty, player_id) DO UPDATE SET seq = $2, category = $3, song_name = $4, difficulty = $5, score = $6, flag = $7;`,
      values: [player.id, i, score.category, score.songName, score.difficulty, score.score, score.flag]
    }
    await pool.query(query);
  }
  res.send(JSON.stringify({}));
}));
app.use("/api", router);
app.use(function(err, req, res, next) {
  if (!err.exposed) {
    console.log(err);
    res.status(500).send(JSON.stringify({"err": "internal"}));
  } else {
    res.status(err.status).send(JSON.stringify({"err": err.message}));
  }
});

app.listen(8585);
<|endoftext|>


<commit_before>import { computed, get } from '@ember/object';
import { or } from '@ember/object/computed';
import Resource from 'ember-api-store/models/resource';
import { download } from 'shared/utils/util';
import C from 'ui/utils/constants';
import StateCounts from 'ui/mixins/state-counts';
import { inject as service } from "@ember/service";
import { reference } from 'ember-api-store/utils/denormalize';
import ResourceUsage from 'shared/mixins/resource-usage';

var Node = Resource.extend(StateCounts, ResourceUsage, {
  type: 'node',

  modalService: service('modal'),
  settings: service(),
  prefs: service(),
  router: service(),
  globalStore: service(),
  clusterStore: service(),
  intl: service(),

  cluster: reference('clusterId','cluster'),
  nodePool: reference('nodePoolId'),

  init() {
    this._super(...arguments);
    this.defineStateCounts('arrangedInstances', 'instanceStates', 'instanceCountSort');
  },

  actions: {
    activate: function() {
      return this.doAction('activate');
    },

    deactivate: function() {
      return this.doAction('deactivate');
    },

    cordon: function() {
      return this.doAction('cordon');
    },

    uncordon: function() {
      return this.doAction('uncordon');
    },

    drain: function() {
      return this.doAction('drain');
    },

    promptEvacuate: function() {
      get(this,'modalService').toggleModal('modal-host-evacuate', {
        model: [this]
      });
    },

    evacuate: function() {
      return this.doAction('evacuate');
    },

    newContainer: function() {
      get(this,'router').transitionTo('containers.run', {queryParams: {hostId: get(this,'model.id')}});
    },

    edit: function() {
      get(this,'modalService').toggleModal('modal-edit-host', this);
    },

    nodeConfig: function() {
      var url = this.linkFor('nodeConfig');
      if ( url )
      {
        download(url);
      }
    }
  },

  availableActions: computed('links.{nodeConfig}', 'actionLinks.{cordon,uncordon,drain}', function() {
    let l = get(this,'links');
    const a = get(this, 'actionLinks');

    let out = [
      { label: 'action.cordon', icon: 'icon icon-pause', action: 'cordon', enabled: !!a.cordon, bulkable: true},
      { label: 'action.uncordon', icon: 'icon icon-play', action: 'uncordon', enabled: !!a.uncordon, bulkable: true},
      { label: 'action.drain', icon: 'icon icon-snapshot', action: 'drain', enabled: !!a.drain, bulkable: true},
      { divider: true},
      { label: 'action.nodeConfig', icon: 'icon icon-download', action: 'nodeConfig', enabled: !!l.nodeConfig},
      { divider: true },
    ];

    return out;
  }),

  displayIp: or('externalIpAddress','ipAddress'),

  displayName: computed('name','nodeName','requestedHostname','id', function() {
    let name = get(this,'name');
    if ( name ) {
      return name;
    }

    name = get(this,'nodeName');
    if ( name ) {
      if ( name.match(/[a-z]/i) ) {
        name = name.replace(/\..*$/,'');
      }

      return name;
    }

    name = get(this,'requestedHostname');
    if ( name ) {
      return name;
    }

    return '('+get(this,'id')+')';
  }),

  rolesArray: computed('etcd','controlPlane','worker', function() {
    return ['etcd','controlPlane','worker'].filter(x => !!get(this,x));
  }),

  displayRoles: computed('intl.locale','rolesArray.[]', function() {
    const intl = get(this, 'intl');
    const roles = get(this, 'rolesArray');

    if ( roles.length >= 3 ) {
      return [intl.t('generic.all')];
    }

    return roles.map(role => {
      let key = `model.machine.role.${role}`;
      if ( intl.exists(key) ) {
        return intl.t(key);
      }

      return key;
    });
  }),

  sortRole: computed('rolesArray.[]', function() {
    let roles = get(this, 'rolesArray');

    if ( roles.length >= 3 ) {
      return 1;
    }

    if ( roles.includes('controlPlane') ) {
      return 2;
    }

    if ( roles.includes('etcd') ) {
      return 3;
    }

    return 4;
  }),

  isUnschedulable: computed('taints.@each.{effect,key}', function(){
    const taints = get(this, 'taints') || [];
    return taints.some(taint => taint.effect === 'NoExecute' && (
      taint.key === 'node-role.kubernetes.io/etcd' || taint.key === 'node-role.kubernetes.io/controlplane'
    ));
  }),

  osBlurb: computed('info.os.operatingSystem', function() {
    var out = get(this,'info.os.operatingSystem')||'';

    out = out.replace(/\s+\(.*?\)/,''); // Remove details in parens
    out = out.replace(/;.*$/,''); // Or after semicolons
    out = out.replace('Red Hat Enterprise Linux Server','RHEL'); // That's kinda long

    return out;
  }),

/*
  osBlurb: function() {
    var out = get(this,'info.osInfo.operatingSystem')||'';

    out = out.replace(/\s+\(.*?\)/,''); // Remove details in parens
    out = out.replace(/;.*$/,''); // Or after semicolons
    out = out.replace('Red Hat Enterprise Linux Server','RHEL'); // That's kinda long

    var hasKvm = (get(this,'labels')||{})[C.LABEL.KVM] === 'true';
    if ( hasKvm && out )
    {
      out += ' (with KVM)';
    }

    return out;
  }.property('info.osInfo.operatingSystem','labels'),

  osDetail: alias('info.osInfo.operatingSystem'),

  dockerEngineVersion: function() {
    if ( get(this,'info.osInfo') )
    {
*/
//      return (get(this,'info.osInfo.dockerVersion')||'').replace(/^Docker version\s*/i,'').replace(/,.*/,'');
/*    }
  }.property('info.osInfo.dockerVersion'),

  supportState: function() {
    let my = get(this,'dockerEngineVersion')||'';
    my = my.replace(/-(cs|ce|ee)[0-9.-]*$/,'');

    let supported = get(this,`settings.${C.SETTING.SUPPORTED_DOCKER}`);
    let newest = get(this,`settings.${C.SETTING.NEWEST_DOCKER}`);

    if ( !my || !supported || !newest) {
      return 'unknown';
    } else if ( satisfies(my, supported) ) {
      return 'supported';
    } else if ( compare(my, newest) > 0 ) {
      return 'untested';
    } else {
      return 'unsupported';
    }
  }.property('dockerEngineVersion',`settings.${C.SETTING.SUPPORTED_DOCKER}`,`settings.${C.SETTING.NEWEST_DOCKER}`),

  dockerDetail: alias('info.osInfo.operatingSystem'),

  kernelBlurb: function() {
    if ( get(this,'info.osInfo') )
    {
      return (get(this,'info.osInfo.kernelVersion')||'');
    }
  }.property('info.osInfo.kernelVersion'),

  cpuBlurb: function() {
    if ( get(this,'info.cpuInfo.count') )
    {
      var ghz = Math.round(get(this,'info.cpuInfo.mhz')/10)/100;

      if ( get(this,'info.cpuInfo.count') > 1 )
      {
        return get(this,'info.cpuInfo.count')+'x' + ghz + ' GHz';
      }
      else
      {
        return ghz + ' GHz';
      }
    }
  }.property('info.cpuInfo.{count,mhz}'),

  cpuTooltip: alias('info.cpuInfo.modelName'),

  memoryBlurb: function() {
    if ( get(this,'info.memoryInfo') )
    {
      return formatMib(get(this,'info.memoryInfo.memTotal'));
    }
  }.property('info.memoryInfo.memTotal'),

  memoryLimitBlurb: computed('memory', function() {
    if ( get(this,'memory') )
    {
      return formatSi(get(this,'memory'), 1024, 'iB', 'B');
    }
  }),

  localStorageBlurb: computed('localStorageMb', function() {
    if (get(this,'localStorageMb')) {
      return formatSi(get(this,'localStorageMb'), 1024, 'iB', 'B', 2); // start at 1024^2==MB
    }
  }),

  diskBlurb: function() {
    var totalMb = 0;

    // New hotness
    if ( get(this,'info.diskInfo.fileSystems') )
    {
      var fses = get(this,'info.diskInfo.fileSystems')||[];
      Object.keys(fses).forEach((fs) => {
        totalMb += fses[fs].capacity;
      });

      return formatMib(totalMb);
    }
    else if ( get(this,'info.diskInfo.mountPoints') )
    {
      // Old & busted
      var mounts = get(this,'info.diskInfo.mountPoints')||[];
      Object.keys(mounts).forEach((mountPoint) => {
        totalMb += mounts[mountPoint].total;
      });

      return formatMib(totalMb);
    }
  }.property('info.diskInfo.mountPoints.@each.total','info.diskInfo.fileSystems.@each.capacity'),

  diskDetail: function() {
    // New hotness
    if ( get(this,'info.diskInfo.fileSystems') )
    {
      var out = [];
      var fses = get(this,'info.diskInfo.fileSystems')||[];
      Object.keys(fses).forEach((fs) => {
        out.pushObject(EmberObject.create({label: fs, value: formatMib(fses[fs].capacity)}));
      });

      return out;
    }
  }.property('info.diskInfo.fileSystems.@each.capacity'),
*/

  // If you use this you must ensure that services and containers are already in the store
  //  or they will not be pulled in correctly.
  displayEndpoints: function() {
    var store = get(this,'clusterStore');
    return (get(this,'publicEndpoints')||[]).map((endpoint) => {
      if ( !endpoint.service ) {
        endpoint.service = store.getById('service', endpoint.serviceId);
      }

      endpoint.instance = store.getById('instance', endpoint.instanceId);
      return endpoint;
    });
  }.property('publicEndpoints.@each.{ipAddress,port,serviceId,instanceId}'),

  requireAnyLabelStrings: function() {
    return  ((get(this,'labels')||{})[C.LABEL.REQUIRE_ANY]||'')
              .split(/\s*,\s*/)
              .filter((x) => x.length > 0 && x !== C.LABEL.SYSTEM_TYPE);
  }.property(`labels.${C.LABEL.REQUIRE_ANY}`),
});

Node.reopenClass({
  defaultSortBy: 'name,hostname',
});

export default Node;
<commit_msg>Mark NoExecute and NoSchedule as Unschedulable<commit_after>import { computed, get } from '@ember/object';
import { or } from '@ember/object/computed';
import Resource from 'ember-api-store/models/resource';
import { download } from 'shared/utils/util';
import C from 'ui/utils/constants';
import StateCounts from 'ui/mixins/state-counts';
import { inject as service } from "@ember/service";
import { reference } from 'ember-api-store/utils/denormalize';
import ResourceUsage from 'shared/mixins/resource-usage';

var Node = Resource.extend(StateCounts, ResourceUsage, {
  type: 'node',

  modalService: service('modal'),
  settings: service(),
  prefs: service(),
  router: service(),
  globalStore: service(),
  clusterStore: service(),
  intl: service(),

  cluster: reference('clusterId','cluster'),
  nodePool: reference('nodePoolId'),

  init() {
    this._super(...arguments);
    this.defineStateCounts('arrangedInstances', 'instanceStates', 'instanceCountSort');
  },

  actions: {
    activate: function() {
      return this.doAction('activate');
    },

    deactivate: function() {
      return this.doAction('deactivate');
    },

    cordon: function() {
      return this.doAction('cordon');
    },

    uncordon: function() {
      return this.doAction('uncordon');
    },

    drain: function() {
      return this.doAction('drain');
    },

    promptEvacuate: function() {
      get(this,'modalService').toggleModal('modal-host-evacuate', {
        model: [this]
      });
    },

    evacuate: function() {
      return this.doAction('evacuate');
    },

    newContainer: function() {
      get(this,'router').transitionTo('containers.run', {queryParams: {hostId: get(this,'model.id')}});
    },

    edit: function() {
      get(this,'modalService').toggleModal('modal-edit-host', this);
    },

    nodeConfig: function() {
      var url = this.linkFor('nodeConfig');
      if ( url )
      {
        download(url);
      }
    }
  },

  availableActions: computed('links.{nodeConfig}', 'actionLinks.{cordon,uncordon,drain}', function() {
    let l = get(this,'links');
    const a = get(this, 'actionLinks');

    let out = [
      { label: 'action.cordon', icon: 'icon icon-pause', action: 'cordon', enabled: !!a.cordon, bulkable: true},
      { label: 'action.uncordon', icon: 'icon icon-play', action: 'uncordon', enabled: !!a.uncordon, bulkable: true},
      { label: 'action.drain', icon: 'icon icon-snapshot', action: 'drain', enabled: !!a.drain, bulkable: true},
      { divider: true},
      { label: 'action.nodeConfig', icon: 'icon icon-download', action: 'nodeConfig', enabled: !!l.nodeConfig},
      { divider: true },
    ];

    return out;
  }),

  displayIp: or('externalIpAddress','ipAddress'),

  displayName: computed('name','nodeName','requestedHostname','id', function() {
    let name = get(this,'name');
    if ( name ) {
      return name;
    }

    name = get(this,'nodeName');
    if ( name ) {
      if ( name.match(/[a-z]/i) ) {
        name = name.replace(/\..*$/,'');
      }

      return name;
    }

    name = get(this,'requestedHostname');
    if ( name ) {
      return name;
    }

    return '('+get(this,'id')+')';
  }),

  rolesArray: computed('etcd','controlPlane','worker', function() {
    return ['etcd','controlPlane','worker'].filter(x => !!get(this,x));
  }),

  displayRoles: computed('intl.locale','rolesArray.[]', function() {
    const intl = get(this, 'intl');
    const roles = get(this, 'rolesArray');

    if ( roles.length >= 3 ) {
      return [intl.t('generic.all')];
    }

    return roles.map(role => {
      let key = `model.machine.role.${role}`;
      if ( intl.exists(key) ) {
        return intl.t(key);
      }

      return key;
    });
  }),

  sortRole: computed('rolesArray.[]', function() {
    let roles = get(this, 'rolesArray');

    if ( roles.length >= 3 ) {
      return 1;
    }

    if ( roles.includes('controlPlane') ) {
      return 2;
    }

    if ( roles.includes('etcd') ) {
      return 3;
    }

    return 4;
  }),

  isUnschedulable: computed('taints.@each.{effect,key}', function(){
    const taints = get(this, 'taints') || [];
    return taints.some(taint => (taint.effect === 'NoExecute' || taint.effect === 'NoSchedule') && (
      taint.key === 'node-role.kubernetes.io/etcd' || taint.key === 'node-role.kubernetes.io/controlplane'
    ));
  }),

  osBlurb: computed('info.os.operatingSystem', function() {
    var out = get(this,'info.os.operatingSystem')||'';

    out = out.replace(/\s+\(.*?\)/,''); // Remove details in parens
    out = out.replace(/;.*$/,''); // Or after semicolons
    out = out.replace('Red Hat Enterprise Linux Server','RHEL'); // That's kinda long

    return out;
  }),

/*
  osBlurb: function() {
    var out = get(this,'info.osInfo.operatingSystem')||'';

    out = out.replace(/\s+\(.*?\)/,''); // Remove details in parens
    out = out.replace(/;.*$/,''); // Or after semicolons
    out = out.replace('Red Hat Enterprise Linux Server','RHEL'); // That's kinda long

    var hasKvm = (get(this,'labels')||{})[C.LABEL.KVM] === 'true';
    if ( hasKvm && out )
    {
      out += ' (with KVM)';
    }

    return out;
  }.property('info.osInfo.operatingSystem','labels'),

  osDetail: alias('info.osInfo.operatingSystem'),

  dockerEngineVersion: function() {
    if ( get(this,'info.osInfo') )
    {
*/
//      return (get(this,'info.osInfo.dockerVersion')||'').replace(/^Docker version\s*/i,'').replace(/,.*/,'');
/*    }
  }.property('info.osInfo.dockerVersion'),

  supportState: function() {
    let my = get(this,'dockerEngineVersion')||'';
    my = my.replace(/-(cs|ce|ee)[0-9.-]*$/,'');

    let supported = get(this,`settings.${C.SETTING.SUPPORTED_DOCKER}`);
    let newest = get(this,`settings.${C.SETTING.NEWEST_DOCKER}`);

    if ( !my || !supported || !newest) {
      return 'unknown';
    } else if ( satisfies(my, supported) ) {
      return 'supported';
    } else if ( compare(my, newest) > 0 ) {
      return 'untested';
    } else {
      return 'unsupported';
    }
  }.property('dockerEngineVersion',`settings.${C.SETTING.SUPPORTED_DOCKER}`,`settings.${C.SETTING.NEWEST_DOCKER}`),

  dockerDetail: alias('info.osInfo.operatingSystem'),

  kernelBlurb: function() {
    if ( get(this,'info.osInfo') )
    {
      return (get(this,'info.osInfo.kernelVersion')||'');
    }
  }.property('info.osInfo.kernelVersion'),

  cpuBlurb: function() {
    if ( get(this,'info.cpuInfo.count') )
    {
      var ghz = Math.round(get(this,'info.cpuInfo.mhz')/10)/100;

      if ( get(this,'info.cpuInfo.count') > 1 )
      {
        return get(this,'info.cpuInfo.count')+'x' + ghz + ' GHz';
      }
      else
      {
        return ghz + ' GHz';
      }
    }
  }.property('info.cpuInfo.{count,mhz}'),

  cpuTooltip: alias('info.cpuInfo.modelName'),

  memoryBlurb: function() {
    if ( get(this,'info.memoryInfo') )
    {
      return formatMib(get(this,'info.memoryInfo.memTotal'));
    }
  }.property('info.memoryInfo.memTotal'),

  memoryLimitBlurb: computed('memory', function() {
    if ( get(this,'memory') )
    {
      return formatSi(get(this,'memory'), 1024, 'iB', 'B');
    }
  }),

  localStorageBlurb: computed('localStorageMb', function() {
    if (get(this,'localStorageMb')) {
      return formatSi(get(this,'localStorageMb'), 1024, 'iB', 'B', 2); // start at 1024^2==MB
    }
  }),

  diskBlurb: function() {
    var totalMb = 0;

    // New hotness
    if ( get(this,'info.diskInfo.fileSystems') )
    {
      var fses = get(this,'info.diskInfo.fileSystems')||[];
      Object.keys(fses).forEach((fs) => {
        totalMb += fses[fs].capacity;
      });

      return formatMib(totalMb);
    }
    else if ( get(this,'info.diskInfo.mountPoints') )
    {
      // Old & busted
      var mounts = get(this,'info.diskInfo.mountPoints')||[];
      Object.keys(mounts).forEach((mountPoint) => {
        totalMb += mounts[mountPoint].total;
      });

      return formatMib(totalMb);
    }
  }.property('info.diskInfo.mountPoints.@each.total','info.diskInfo.fileSystems.@each.capacity'),

  diskDetail: function() {
    // New hotness
    if ( get(this,'info.diskInfo.fileSystems') )
    {
      var out = [];
      var fses = get(this,'info.diskInfo.fileSystems')||[];
      Object.keys(fses).forEach((fs) => {
        out.pushObject(EmberObject.create({label: fs, value: formatMib(fses[fs].capacity)}));
      });

      return out;
    }
  }.property('info.diskInfo.fileSystems.@each.capacity'),
*/

  // If you use this you must ensure that services and containers are already in the store
  //  or they will not be pulled in correctly.
  displayEndpoints: function() {
    var store = get(this,'clusterStore');
    return (get(this,'publicEndpoints')||[]).map((endpoint) => {
      if ( !endpoint.service ) {
        endpoint.service = store.getById('service', endpoint.serviceId);
      }

      endpoint.instance = store.getById('instance', endpoint.instanceId);
      return endpoint;
    });
  }.property('publicEndpoints.@each.{ipAddress,port,serviceId,instanceId}'),

  requireAnyLabelStrings: function() {
    return  ((get(this,'labels')||{})[C.LABEL.REQUIRE_ANY]||'')
              .split(/\s*,\s*/)
              .filter((x) => x.length > 0 && x !== C.LABEL.SYSTEM_TYPE);
  }.property(`labels.${C.LABEL.REQUIRE_ANY}`),
});

Node.reopenClass({
  defaultSortBy: 'name,hostname',
});

export default Node;
<|endoftext|>


<commit_before>window.Auger || (window.Auger = {});
Auger.Event = {};

// Event.add(element, event, function)

if(document.addEventListener){
	Auger.Event.add    = function(l, t, f){ if(!this.prepare(t, l, f)) return; l.addEventListener(t, f, false); };
	Auger.Event.remove = function(l, t, f){ l.removeEventListener(t, f, false); };
	Auger.Event.send   = function(l, t){ var e=document.createEvent('Events'); e.initEvent(t,true,false); l.dispatchEvent(e); };
}
else if(document.attachEvent){ 	// IE [5+]
	Auger.Event._isIE = true;
	Auger.Event.add = function(l, t, f) {
		var a = this;
		if(!a.prepare(t, l, f)) return;
		if(a._get(l, t, f) != -1) return; 	// ignore duplicates
		var ff = function(e) {
			if (!e) e = window.event;
			// emulate DOM events
			e.target = e.srcElement,
			e.currentTarget = l,
			e.relatedTarget = (e.fromElement||e.toElement),
			e.eventPhase = (e.srcElement==l?2:3),
			e.charCode = e.keyCode,
			e.preventDefault = a._d_preventDefault,
			e.stopPropagation = a._d_stopPropagation;
			// invoke function as method on element for correct value of 'this'
			f.call(l, e);
		};
		l.attachEvent('on' + t, ff); 	// save wrapper as event handler

		var h = [l,t,f,ff]; 			// remember these values so we can detach later
		var w = a.elementWindow(l);

		var u = a._uid();
		var nw = a._cache_w;
		var nl = a._cache_l;
		var un = false;
		if(un=!w[nw]) w[nw]={};
		w[nw][u] = h; 	// store on window to be removed on window unload
		if(!l[nl]) l[nl] = [];
		l[nl].push(u); 	// store uid on element
		if(un) 			// explicitly remove handlers to try to avoid memory leaks
			w.attachEvent('onunload', a._d_onWindowUnload);
	};
	Auger.Event.remove = function(l, t, f) {
		var a = this;
		var i = a._get(l, t, f);
		if(i>=0){
			var nl = a._cache_l;
			var wn = a.elementWindow(l)[a._cache_w];
			var hid = l[nl][i]; 	// get id
			var h = wn[hid]; 	// find on window
			l.detachEvent('on' + t, h[3]);
			l[nl].splice(i, 1); 	// pop
			delete wn[hid];
		}
	};
	Auger.Event.send = function(l, t){ var e = document.createEventObject(); l.fireEvent('on'+t,e); }
	Auger.Event._get = function(l, t, f) {
		var nl = this._cache_l, nw = this._cache_w;
		var hs = l[nl];
		if(hs && hs.length){
			var wn = this.elementWindow(l)[nw];
			for(var i = hs.length-1; i>=0; i--){ 	// LIFO
				var h = wn[hs[i]];
				if(h[1] == t && h[2] == f) 		// same type and same function
					return i;
			}
		}
		return -1; 	// index (not found)
	};
	// we need separate cache objects in case the element is a window
	Auger.Event._cache_w = ' Auger.Event._cache_w'; 	// window
	Auger.Event._cache_l = ' Auger.Event._cache_l'; 	// element
	Auger.Event._uidc = 0;
	Auger.Event._uid = function(){ return 'ae' + this._uidc++; };
	Auger.Event.elementWindow = function(l){ return (l.document || l).parentWindow; };
	// declare these here to avoid unnecessary closures (we are doing this only for IE)
	// These will be detached so 'this' will be something else (and Auger.Event must be fully qualified)
	Auger.Event._d_preventDefault  = function(){this.returnValue = false;}; // this = event
	Auger.Event._d_stopPropagation = function(){this.cancelBubble = true;};
	Auger.Event._d_onWindowUnload = function(){
		var wn = this[Auger.Event._cache_w]; 	// this = window being unloaded
		for(var u in wn){
			var h = wn[u];
			h[0].detachEvent('on' + h[1], h[3]);
			delete wn[u];
		}
	}
}
//else
//	l['on'+e] = f;
//	Auger.Event.send = function(l, t){ if(ot in l && typeof(l[ot]) == 'function') l[ot](); }
Auger.Event._prepared = {};
Auger.Event._cached = {};
Auger.Event.prepare = function(t, l, f){
	var a = this;
	if(!(t in a._prepared)){
		a._prepared[t] = true;
		a._cached[t] = [];
		if(a.synthesize[t]) 		// if an event synthesizer exists call it
			a._prepared[t] = a.synthesize[t].init(l, f); // otherwise just ignore (and don't call prepare again)
	}
	if(!a._prepared[t])
		a._cached[t].push([l,f]);
	return a._prepared[t];
};
Auger.Event.synthesize = {};
// only define method for synthesizing if the browser doesn't natively support it
if(!('onhashchange' in window) || (window.attachEvent && (document.documentMode||0) < 8)){ // only ie8 in ie8 mode supports it
	Auger.Event.synthesize.hashchange = {_iframe: Auger.Event._isIE, _timer: null};
	Auger.Event.synthesize.hashchange.init = function(){
		//throw 'not implemented yet';
		var _ = Auger.Event.synthesize.hashchange;
		if( _._iframe ){
			var frame = document.createElement('iframe');
			frame.setAttribute('src', 'javascript:""');
			var s = frame.style;
				s.position = 'absolute';
				s.top = s.left = '-1px';
				s.width = s.height = '1px';
				s.display = 'none';
			document.body.appendChild(frame);
			_._iframe = frame.contentWindow;
			_._iframeUpdate(_._hash());
		}
		_._start();
		return !_._iframe; 	// return false to indicate that this custom event is not supported
	};
	Auger.Event.synthesize.hashchange._start = function(h){
		var _ = this;
		if(!_._timer){ 	// ignore if timer already set
			_._last = h||_._hash();
			_._timer = setInterval(_._poll,200);
		}
	};
	Auger.Event.synthesize.hashchange._stop  = function(){ clearInterval(this._timer); this._timer = null; };
	Auger.Event.synthesize.hashchange._hash  = function(u){
		return (u||location.href).replace(/^[^#]*#?(.*)$/,'$1');
	};
	if( Auger.Event.synthesize.hashchange._iframe ){
		Auger.Event.synthesize.hashchange._iframeHash  = function(){
			return this._hash(this._iframe.location.href);
		};
		Auger.Event.synthesize.hashchange._iframeUpdate = function(h){
			var fr = this._iframe;
			fr.document.open().close(); 	// reset the iframe so IE will add a history entry
			fr.location.hash = '#' + h;
			//if((f = this._iframe)) f.src = f.src.replace(/#.*$/, h);
		};
	}
	Auger.Event.synthesize.hashchange._poll = function(){
		var a = Auger.Event, et = 'hashchange';
		var _ = a.synthesize[et];
		var b = false, h = _._hash(), f = _._iframe, ac = a._cached[et];
		var fh = f ? _._iframeHash() : h;
		if(h !== _._last){
			b = true;
			if(f && h !== fh) _._iframeUpdate(h);
		}else if(f && fh !== _._last){
			b = true;
			location.href = location.href.replace(/#.*$/,'#'+fh);
		}
		if(b){
			_._stop(); 									// pause polling until after events
			if(f) 										// IE doesn't allow custom events
				for(var i=0;i<ac.length;++i) 			// so roll through the cache
					ac[i][1].call(ac[i][0]);
			else
				Auger.Event.send(window, et); // synchronous (wait)
			_._start(_._last=h); 						// resume polling
		}
	};
}
<commit_msg>Move processing of cached custom events into the IE version of send() since that's where it belongs anyway<commit_after>window.Auger || (window.Auger = {});
Auger.Event = {};

// Event.add(element, event, function)

if(document.addEventListener){
	Auger.Event.add    = function(l, t, f){ if(!this.prepare(t, l, f)) return; l.addEventListener(t, f, false); };
	Auger.Event.remove = function(l, t, f){ l.removeEventListener(t, f, false); };
	Auger.Event.send   = function(l, t){ var e=document.createEvent('Events'); e.initEvent(t,true,false); l.dispatchEvent(e); };
}
else if(document.attachEvent){ 	// IE [5+]
	Auger.Event._isIE = true;
	Auger.Event.add = function(l, t, f) {
		var a = this;
		if(!a.prepare(t, l, f)) return;
		if(a._get(l, t, f) != -1) return; 	// ignore duplicates
		var ff = function(e) {
			if (!e) e = window.event;
			// emulate DOM events
			e.target = e.srcElement,
			e.currentTarget = l,
			e.relatedTarget = (e.fromElement||e.toElement),
			e.eventPhase = (e.srcElement==l?2:3),
			e.charCode = e.keyCode,
			e.preventDefault = a._d_preventDefault,
			e.stopPropagation = a._d_stopPropagation;
			// invoke function as method on element for correct value of 'this'
			f.call(l, e);
		};
		l.attachEvent('on' + t, ff); 	// save wrapper as event handler

		var h = [l,t,f,ff]; 			// remember these values so we can detach later
		var w = a.elementWindow(l);

		var u = a._uid();
		var nw = a._cache_w;
		var nl = a._cache_l;
		var un = false;
		if(un=!w[nw]) w[nw]={};
		w[nw][u] = h; 	// store on window to be removed on window unload
		if(!l[nl]) l[nl] = [];
		l[nl].push(u); 	// store uid on element
		if(un) 			// explicitly remove handlers to try to avoid memory leaks
			w.attachEvent('onunload', a._d_onWindowUnload);
	};
	Auger.Event.remove = function(l, t, f) {
		var a = this;
		var i = a._get(l, t, f);
		if(i>=0){
			var nl = a._cache_l;
			var wn = a.elementWindow(l)[a._cache_w];
			var hid = l[nl][i]; 	// get id
			var h = wn[hid]; 	// find on window
			l.detachEvent('on' + t, h[3]);
			l[nl].splice(i, 1); 	// pop
			delete wn[hid];
		}
	};
	Auger.Event.send = function(l, t){
		var i, c = this._cached[t], e = document.createEventObject();
		if(c && c.length) 						// IE doesn't allow custom events
			for(i=0;i<c.length;++i) 			// so roll through the cache
				c[i][1].call(c[i][0],e);
		else
			l.fireEvent('on'+t,e);
	};
	Auger.Event._get = function(l, t, f) {
		var nl = this._cache_l, nw = this._cache_w;
		var hs = l[nl];
		if(hs && hs.length){
			var wn = this.elementWindow(l)[nw];
			for(var i = hs.length-1; i>=0; i--){ 	// LIFO
				var h = wn[hs[i]];
				if(h[1] == t && h[2] == f) 		// same type and same function
					return i;
			}
		}
		return -1; 	// index (not found)
	};
	// we need separate cache objects in case the element is a window
	Auger.Event._cache_w = ' Auger.Event._cache_w'; 	// window
	Auger.Event._cache_l = ' Auger.Event._cache_l'; 	// element
	Auger.Event._uidc = 0;
	Auger.Event._uid = function(){ return 'ae' + this._uidc++; };
	Auger.Event.elementWindow = function(l){ return (l.document || l).parentWindow; };
	// declare these here to avoid unnecessary closures (we are doing this only for IE)
	// These will be detached so 'this' will be something else (and Auger.Event must be fully qualified)
	Auger.Event._d_preventDefault  = function(){this.returnValue = false;}; // this = event
	Auger.Event._d_stopPropagation = function(){this.cancelBubble = true;};
	Auger.Event._d_onWindowUnload = function(){
		var wn = this[Auger.Event._cache_w]; 	// this = window being unloaded
		for(var u in wn){
			var h = wn[u];
			h[0].detachEvent('on' + h[1], h[3]);
			delete wn[u];
		}
	}
}
//else
//	l['on'+e] = f;
//	Auger.Event.send = function(l, t){ if(ot in l && typeof(l[ot]) == 'function') l[ot](); }
Auger.Event._prepared = {};
Auger.Event._cached = {};
Auger.Event.prepare = function(t, l, f){
	var a = this;
	if(!(t in a._prepared)){
		a._prepared[t] = true;
		a._cached[t] = [];
		if(a.synthesize[t]) 		// if an event synthesizer exists call it
			a._prepared[t] = a.synthesize[t].init(l, f); // otherwise just ignore (and don't call prepare again)
	}
	if(!a._prepared[t])
		a._cached[t].push([l,f]);
	return a._prepared[t];
};
Auger.Event.synthesize = {};
// only define method for synthesizing if the browser doesn't natively support it
if(!('onhashchange' in window) || (window.attachEvent && (document.documentMode||0) < 8)){ // only ie8 in ie8 mode supports it
	Auger.Event.synthesize.hashchange = {_iframe: Auger.Event._isIE, _timer: null};
	Auger.Event.synthesize.hashchange.init = function(){
		//throw 'not implemented yet';
		var _ = Auger.Event.synthesize.hashchange;
		if( _._iframe ){
			var frame = document.createElement('iframe');
			frame.setAttribute('src', 'javascript:""');
			var s = frame.style;
				s.position = 'absolute';
				s.top = s.left = '-1px';
				s.width = s.height = '1px';
				s.display = 'none';
			document.body.appendChild(frame);
			_._iframe = frame.contentWindow;
			_._iframeUpdate(_._hash());
		}
		_._start();
		return !_._iframe; 	// return false to indicate that this custom event is not supported
	};
	Auger.Event.synthesize.hashchange._start = function(h){
		var _ = this;
		if(!_._timer){ 	// ignore if timer already set
			_._last = h||_._hash();
			_._timer = setInterval(_._poll,200);
		}
	};
	Auger.Event.synthesize.hashchange._stop  = function(){ clearInterval(this._timer); this._timer = null; };
	Auger.Event.synthesize.hashchange._hash  = function(u){
		return (u||location.href).replace(/^[^#]*#?(.*)$/,'$1');
	};
	if( Auger.Event.synthesize.hashchange._iframe ){
		Auger.Event.synthesize.hashchange._iframeHash  = function(){
			return this._hash(this._iframe.location.href);
		};
		Auger.Event.synthesize.hashchange._iframeUpdate = function(h){
			var fr = this._iframe;
			fr.document.open().close(); 	// reset the iframe so IE will add a history entry
			fr.location.hash = '#' + h;
			//if((f = this._iframe)) f.src = f.src.replace(/#.*$/, h);
		};
	}
	Auger.Event.synthesize.hashchange._poll = function(){
		var a = Auger.Event, et = 'hashchange';
		var _ = a.synthesize[et];
		var b = false, h = _._hash(), f = _._iframe;
		var fh = f ? _._iframeHash() : h;
		if(h !== _._last){
			b = true;
			if(f && h !== fh) _._iframeUpdate(h);
		}else if(f && fh !== _._last){
			b = true;
			location.href = location.href.replace(/#.*$/,'#'+fh);
		}
		if(b){
			_._stop(); 									// pause polling until after events
			Auger.Event.send(window, et); 				// synchronous (wait)
			_._start(_._last=h); 						// resume polling
		}
	};
}
<|endoftext|>