<commit_before>(function (factory) {
    if (typeof define === "function" && define.amd) {
        define('bforms-inlineQuestion', ['jquery', 'bootstrap', 'jquery-ui-core', 'icanhaz'], factory);
    } else {
        factory(window.jQuery);
    }
})(function ($) {

    var bsInlineQuestion = function (options) {
        this.options = $.extend(true, {}, this.options, options);
    };

    bsInlineQuestion.prototype.options = {
        template: '
{{question}}
' +
                    '
' +
                    '{{#buttons}}' +
                        '<button type="button" class="btn bs-popoverBtn {{cssClass}}"> {{text}} </button> ' +
                    '{{/buttons}}',
        contentTemplate: '{{{content}}}' +
                          '
' +
                         '{{#buttons}}' +
                             '<button type="button" class="btn bs-popoverBtn {{cssClass}}"> {{text}} </button> ' +
                         '{{/buttons}}',
        jqueryContentTemplate: '
' +
                                '' +
                                  '
' +
                                 '{{#buttons}}' +
                                     '<button type="button" class="btn bs-popoverBtn {{cssClass}}"> {{text}} </button> ' +
                                 '{{/buttons}}' +
                             '
',
        placement: 'left',
        placementArray: 'left,right,bottom,top',
        content: undefined,
        stretch: false,
        closeOnOuterClick: true
    };

    //#region init and render
    bsInlineQuestion.prototype._init = function () {

        if (this.element.hasClass('bs-hasInlineQuestion')) return this.element;

        this.$element = this.element;

        this.$element.addClass('bs-hasInlineQuestion');

        if (this.options.placement === 'auto') {
            this._placementArray = this.options.placementArray.split(',');

            this.options.placement = $.proxy(this._placementMethod, this);
        }

        if (typeof ich.renderPopoverQuestion !== "function") {
            ich.addTemplate('renderPopoverQuestion', this.options.template);
        }

        if (typeof ich.renderPopoverContent !== "function") {
            ich.addTemplate('renderPopoverContent', this.options.contentTemplate);
        }

        if (typeof ich.renderjQueryPopoverContent !== "function") {
            ich.addTemplate('renderjQueryPopoverContent', this.options.jqueryContentTemplate);
        }

        this._addPopover();

        if (this.options.stretch == true) {
            this.$tip.css('max-width', 'none');
        }
    };

    bsInlineQuestion.prototype._delegateEvents = function () {
        this.$tip.on('click', '.bs-popoverBtn', $.proxy(function (e) {
            var idx = this.$tip.find('.bs-popoverBtn').index(e.currentTarget),
                btn = this.options.buttons[idx];

            if (btn != null && typeof btn.callback === "function") {
                e.preventDefault();
                e.stopPropagation();

                btn.callback.apply(this, arguments);
            }

        }, this));

        if (this.options.closeOnOuterClick && $(document).data('bsPopoverClickHandler') !== true) {
            $(document).on('click', function (e) {
                var $target = $(e.target);

                var $openPopovers = $('.bs-hasInlineQuestion').filter(function (idx, elem) {
                    var $elem = $(elem),
                        popover = $elem.data('bs.popover');

                    if (typeof popover !== "undefined" && popover != null) {
                        var $tip = popover.$tip;
                        return $tip.is(':visible') && $elem[0] != $target[0] && $elem.find($target).length == 0 && $target[0] != $tip[0] && $tip.find($target).length == 0;
                    }

                    return false;

                });

                $openPopovers.bsInlineQuestion('toggle');

            }).data('bsPopoverClickHandler', true);
        }
    };

    bsInlineQuestion.prototype._addPopover = function () {

        this.$element.popover($.extend(true, {
            html: true,
            placement: this.options.placement,
            content: this.options.cacheContent === true ? this._renderPopover() : $.proxy(this._renderPopover, this)
        }, this.options.popoverOptions)).addClass('bs-hasInlineQuestion');

        this.$element.on('show.bs.popover', $.proxy(function () {
            this._trigger('show', 0, arguments);
        }, this));

        this.$element.on('shown.bs.popover', $.proxy(function () {
            this._trigger('shown', 0, arguments);
        }, this));

        this.$element.on('hide.bs.popover', $.proxy(function () {
            this._trigger('hide', 0, arguments);
        }, this));

        this.$element.on('hidden.bs.popover', $.proxy(function () {
            this._trigger('hidden', 0, arguments);
        }, this));

        this.$tip = this.$element.data('bs.popover').tip();
        this._delegateEvents();
    };

    bsInlineQuestion.prototype._renderPopover = function () {

        var popover = typeof this.options.content === "undefined" ? ich.renderPopoverQuestion(this.options, true) : (this.options.content instanceof jQuery ? ich.renderjQueryPopoverContent(this.options, true) : ich.renderPopoverContent(this.options, true));

        if (this.options.content instanceof jQuery) {

            console.log(popover);

            var $pop = $(popover);
            $pop.find('.js-replaceme').replaceWith(this.options.content);

            console.log($pop);

            return $pop;
        }

        return popover;

    };
    //#endregion

    //#region public
    bsInlineQuestion.prototype.hide = function () {
        this.$element.popover('hide');

        return this;
    };

    bsInlineQuestion.prototype.show = function () {
        this.$element.popover('show');

        return this;
    };

    bsInlineQuestion.prototype.toggle = function () {
        this.$element.popover('toggle');

        return this;
    };

    bsInlineQuestion.prototype.content = function (data, overwriteIfNull) {

        if (typeof data !== "undefined") {

            if (typeof data.content !== "undefined" || overwriteIfNull) {
                this.options.content = data.content;
            }

            if (typeof data.question !== "undefined" || overwriteIfNull) {
                this.options.question = data.question;
            }

            if (typeof data.buttons !== "undefined" || overwriteIfNull) {
                this.options.buttons = data.buttons;
            }
        }

        return this;
    };

    bsInlineQuestion.prototype.destroy = function () {

        this.hide();
        this.$element.popover('destroy');

        this.$element.removeData('bformsBsInlineQuestion');
        this.$element.removeClass('bs-hasInlineQuestion');
        this.$tip.remove();
    };

    bsInlineQuestion.prototype._placementMethod = function (tip, button) {
        var $tip = $(tip),
            $button = $(button),
            offset = $button.offset(),
            top = offset.top,
            left = offset.left,
            windowHeight = $(window).outerHeight(),
            windowWidth = $(window).outerWidth();

        var $tipClone = $tip.clone().appendTo($('body')),
            tipWidth = $tipClone.outerWidth(),
            tipHeight = $tipClone.outerHeight();

        $tipClone.remove();

        var positionsSpace = {
            'left': left,
            'right': windowWidth - $button.outerWidth() - left,
            'top': top - $(window).scrollTop(),
            'bottom': windowHeight - $button.outerHeight() - (top - $(window).scrollTop())
        };

        for (var placementKey in this._placementArray) {
            var placement = this._placementArray[placementKey];

            if (placement == 'right' || placement == 'left') {
                if (positionsSpace[placement] > tipWidth) return placement;
            }

            if (placement == 'top' || placement == 'bottom') {
                if (positionsSpace[placement] > tipHeight) return placement;
            }
        }

        return this._placementArray[0] || 'left';
    };
    //#endregion

    $.widget('bforms.bsInlineQuestion', bsInlineQuestion.prototype);
});
<commit_msg>removed console.logs from bsinlinequestion<commit_after>(function (factory) {
    if (typeof define === "function" && define.amd) {
        define('bforms-inlineQuestion', ['jquery', 'bootstrap', 'jquery-ui-core', 'icanhaz'], factory);
    } else {
        factory(window.jQuery);
    }
})(function ($) {

    var bsInlineQuestion = function (options) {
        this.options = $.extend(true, {}, this.options, options);
    };

    bsInlineQuestion.prototype.options = {
        template: '
{{question}}
' +
                    '
' +
                    '{{#buttons}}' +
                        '<button type="button" class="btn bs-popoverBtn {{cssClass}}"> {{text}} </button> ' +
                    '{{/buttons}}',
        contentTemplate: '{{{content}}}' +
                          '
' +
                         '{{#buttons}}' +
                             '<button type="button" class="btn bs-popoverBtn {{cssClass}}"> {{text}} </button> ' +
                         '{{/buttons}}',
        jqueryContentTemplate: '
' +
                                '' +
                                  '
' +
                                 '{{#buttons}}' +
                                     '<button type="button" class="btn bs-popoverBtn {{cssClass}}"> {{text}} </button> ' +
                                 '{{/buttons}}' +
                             '
',
        placement: 'left',
        placementArray: 'left,right,bottom,top',
        content: undefined,
        stretch: false,
        closeOnOuterClick: true
    };

    //#region init and render
    bsInlineQuestion.prototype._init = function () {

        if (this.element.hasClass('bs-hasInlineQuestion')) return this.element;

        this.$element = this.element;

        this.$element.addClass('bs-hasInlineQuestion');

        if (this.options.placement === 'auto') {
            this._placementArray = this.options.placementArray.split(',');

            this.options.placement = $.proxy(this._placementMethod, this);
        }

        if (typeof ich.renderPopoverQuestion !== "function") {
            ich.addTemplate('renderPopoverQuestion', this.options.template);
        }

        if (typeof ich.renderPopoverContent !== "function") {
            ich.addTemplate('renderPopoverContent', this.options.contentTemplate);
        }

        if (typeof ich.renderjQueryPopoverContent !== "function") {
            ich.addTemplate('renderjQueryPopoverContent', this.options.jqueryContentTemplate);
        }

        this._addPopover();

        if (this.options.stretch == true) {
            this.$tip.css('max-width', 'none');
        }
    };

    bsInlineQuestion.prototype._delegateEvents = function () {
        this.$tip.on('click', '.bs-popoverBtn', $.proxy(function (e) {
            var idx = this.$tip.find('.bs-popoverBtn').index(e.currentTarget),
                btn = this.options.buttons[idx];

            if (btn != null && typeof btn.callback === "function") {
                e.preventDefault();
                e.stopPropagation();

                btn.callback.apply(this, arguments);
            }

        }, this));

        if (this.options.closeOnOuterClick && $(document).data('bsPopoverClickHandler') !== true) {
            $(document).on('click', function (e) {
                var $target = $(e.target);

                var $openPopovers = $('.bs-hasInlineQuestion').filter(function (idx, elem) {
                    var $elem = $(elem),
                        popover = $elem.data('bs.popover');

                    if (typeof popover !== "undefined" && popover != null) {
                        var $tip = popover.$tip;
                        return $tip.is(':visible') && $elem[0] != $target[0] && $elem.find($target).length == 0 && $target[0] != $tip[0] && $tip.find($target).length == 0;
                    }

                    return false;

                });

                $openPopovers.bsInlineQuestion('toggle');

            }).data('bsPopoverClickHandler', true);
        }
    };

    bsInlineQuestion.prototype._addPopover = function () {

        this.$element.popover($.extend(true, {
            html: true,
            placement: this.options.placement,
            content: this.options.cacheContent === true ? this._renderPopover() : $.proxy(this._renderPopover, this)
        }, this.options.popoverOptions)).addClass('bs-hasInlineQuestion');

        this.$element.on('show.bs.popover', $.proxy(function () {
            this._trigger('show', 0, arguments);
        }, this));

        this.$element.on('shown.bs.popover', $.proxy(function () {
            this._trigger('shown', 0, arguments);
        }, this));

        this.$element.on('hide.bs.popover', $.proxy(function () {
            this._trigger('hide', 0, arguments);
        }, this));

        this.$element.on('hidden.bs.popover', $.proxy(function () {
            this._trigger('hidden', 0, arguments);
        }, this));

        this.$tip = this.$element.data('bs.popover').tip();
        this._delegateEvents();
    };

    bsInlineQuestion.prototype._renderPopover = function () {

        var popover = typeof this.options.content === "undefined" ? ich.renderPopoverQuestion(this.options, true) : (this.options.content instanceof jQuery ? ich.renderjQueryPopoverContent(this.options, true) : ich.renderPopoverContent(this.options, true));

        if (this.options.content instanceof jQuery) {

            var $pop = $(popover);
            $pop.find('.js-replaceme').replaceWith(this.options.content);

            return $pop;
        }

        return popover;

    };
    //#endregion

    //#region public
    bsInlineQuestion.prototype.hide = function () {
        this.$element.popover('hide');

        return this;
    };

    bsInlineQuestion.prototype.show = function () {
        this.$element.popover('show');

        return this;
    };

    bsInlineQuestion.prototype.toggle = function () {
        this.$element.popover('toggle');

        return this;
    };

    bsInlineQuestion.prototype.content = function (data, overwriteIfNull) {

        if (typeof data !== "undefined") {

            if (typeof data.content !== "undefined" || overwriteIfNull) {
                this.options.content = data.content;
            }

            if (typeof data.question !== "undefined" || overwriteIfNull) {
                this.options.question = data.question;
            }

            if (typeof data.buttons !== "undefined" || overwriteIfNull) {
                this.options.buttons = data.buttons;
            }
        }

        return this;
    };

    bsInlineQuestion.prototype.destroy = function () {

        this.hide();
        this.$element.popover('destroy');

        this.$element.removeData('bformsBsInlineQuestion');
        this.$element.removeClass('bs-hasInlineQuestion');
        this.$tip.remove();
    };

    bsInlineQuestion.prototype._placementMethod = function (tip, button) {
        var $tip = $(tip),
            $button = $(button),
            offset = $button.offset(),
            top = offset.top,
            left = offset.left,
            windowHeight = $(window).outerHeight(),
            windowWidth = $(window).outerWidth();

        var $tipClone = $tip.clone().appendTo($('body')),
            tipWidth = $tipClone.outerWidth(),
            tipHeight = $tipClone.outerHeight();

        $tipClone.remove();

        var positionsSpace = {
            'left': left,
            'right': windowWidth - $button.outerWidth() - left,
            'top': top - $(window).scrollTop(),
            'bottom': windowHeight - $button.outerHeight() - (top - $(window).scrollTop())
        };

        for (var placementKey in this._placementArray) {
            var placement = this._placementArray[placementKey];

            if (placement == 'right' || placement == 'left') {
                if (positionsSpace[placement] > tipWidth) return placement;
            }

            if (placement == 'top' || placement == 'bottom') {
                if (positionsSpace[placement] > tipHeight) return placement;
            }
        }

        return this._placementArray[0] || 'left';
    };
    //#endregion

    $.widget('bforms.bsInlineQuestion', bsInlineQuestion.prototype);
});
<|endoftext|>


<commit_before>function ViewSwitcher(el, options) {
    options || (options = {});
    this.el = el;
    this.config = {
        hide: null,
        show: null,
        waitForRemove: false
    };
    for (var item in options) {
        this.config[item] = options[item];
    }
    this.current = null;
}

ViewSwitcher.prototype.set = function (view) {
    var self = this;
    var prev = this.previous = this.current;
    var current = this.current = view;
    if (this.config.waitForRemove) {
        this._hide(prev, function () {
            // make sure we're still dealing with the same one
            // that way if we're navigating quickly we don't start
            // to show one that's already old.
            if (prev === self.previous && current === self.current) {
                self._show(current);
            }
        });
    } else {
        this._hide(prev);
        this._show(current);
    }
};

ViewSwitcher.prototype._show = function (view, cb) {
    var customShow = this.config.show;
    if (customShow) {
        // async
        if (customShow.length === 3) {
            this._render(view);
            customShow(view, cb);
        } else {
            this._render(view);
            customShow(view);
            if (cb) cb();
        }
    } else {
        this._render(view);
        if (cb) cb();
    }
};

ViewSwitcher.prototype._render = function (view) {
    view.render({containerEl: this.el});
    this.el.appendChild(view.el);
};

ViewSwitcher.prototype._hide = function (view, cb) {
    var customHide = this.config.hide;
    if (!view) return cb && cb();
    if (customHide) {
        // async
        if (customHide.length === 3) {
            customHide(view, this.current, function () {
                view.remove();
            });
        } else {
            customHide(view, this.current);
            view.remove();
            if (cb) cb();
        }
    } else {
        view.remove();
        if (cb) cb();
    }
};

module.exports = ViewSwitcher;
<commit_msg>only render if not rendered is true<commit_after>function ViewSwitcher(el, options) {
    options || (options = {});
    this.el = el;
    this.config = {
        hide: null,
        show: null,
        waitForRemove: false
    };
    for (var item in options) {
        this.config[item] = options[item];
    }
    this.current = null;
}

ViewSwitcher.prototype.set = function (view) {
    var self = this;
    var prev = this.previous = this.current;
    var current = this.current = view;
    if (this.config.waitForRemove) {
        this._hide(prev, function () {
            // make sure we're still dealing with the same one
            // that way if we're navigating quickly we don't start
            // to show one that's already old.
            if (prev === self.previous && current === self.current) {
                self._show(current);
            }
        });
    } else {
        this._hide(prev);
        this._show(current);
    }
};

ViewSwitcher.prototype._show = function (view, cb) {
    var customShow = this.config.show;
    if (customShow) {
        // async
        if (customShow.length === 3) {
            this._render(view);
            customShow(view, cb);
        } else {
            this._render(view);
            customShow(view);
            if (cb) cb();
        }
    } else {
        this._render(view);
        if (cb) cb();
    }
};

ViewSwitcher.prototype._render = function (view) {
    if (!view.rendered) view.render({containerEl: this.el});
    this.el.appendChild(view.el);
};

ViewSwitcher.prototype._hide = function (view, cb) {
    var customHide = this.config.hide;
    if (!view) return cb && cb();
    if (customHide) {
        // async
        if (customHide.length === 3) {
            customHide(view, this.current, function () {
                view.remove();
            });
        } else {
            customHide(view, this.current);
            view.remove();
            if (cb) cb();
        }
    } else {
        view.remove();
        if (cb) cb();
    }
};

module.exports = ViewSwitcher;
<|endoftext|>


<commit_before>angular.module('MyApp', ['ngResource', 'ngMessages', 'ui.router', 'mgcrea.ngStrap', 'satellizer'])
  .config(function($stateProvider, $urlRouterProvider, $authProvider) {
    $stateProvider
      .state('home', {
        url: '/',
        templateUrl: 'partials/home.html'
      })
      .state('login', {
        url: '/login',
        templateUrl: 'partials/login.html',
        controller: 'LoginCtrl'
      })
      .state('signup', {
        url: '/signup',
        templateUrl: 'partials/signup.html',
        controller: 'SignupCtrl'
      })
      .state('logout', {
        url: '/logout',
        template: null,
        controller: 'LogoutCtrl'
      })
      .state('profile', {
        url: '/profile',
        templateUrl: 'partials/profile.html',
        controller: 'ProfileCtrl',
        resolve: {
          authenticated: function($q, $location, $auth) {
            var deferred = $q.defer();

            if (!$auth.isAuthenticated()) {
              $location.path('/login');
            } else {
              deferred.resolve();
            }

            return deferred.promise;
          }
        }
      });

    $urlRouterProvider.otherwise('/');

    $authProvider.facebook({
      clientId: '603122136500203'
    });

    $authProvider.google({
      clientId: '631036554609-v5hm2amv4pvico3asfi97f54sc51ji4o.apps.googleusercontent.com'
    });

    $authProvider.github({
      clientId: '45ab07066fb6a805ed74'
    });

    $authProvider.linkedin({
      clientId: '77cw786yignpzj'
    });

    $authProvider.yahoo({
      clientId: 'dj0yJmk9SDVkM2RhNWJSc2ZBJmQ9WVdrOWIzVlFRMWxzTXpZbWNHbzlNQS0tJnM9Y29uc3VtZXJzZWNyZXQmeD0yYw--'
    });

    $authProvider.twitter({
      url: '/auth/twitter'
    });

    $authProvider.live({
      clientId: '000000004C12E68D'
    });

    $authProvider.oauth2({
      name: 'foursquare',
      url: '/auth/foursquare',
      clientId: 'MTCEJ3NGW2PNNB31WOSBFDSAD4MTHYVAZ1UKIULXZ2CVFC2K',
      redirectUri: window.location.origin || window.location.protocol + '//' + window.location.host,
      authorizationEndpoint: 'https://foursquare.com/oauth2/authenticate'
    });
  });
<commit_msg>added skipIfLoggedIn resolver to signup and login states<commit_after>angular.module('MyApp', ['ngResource', 'ngMessages', 'ui.router', 'mgcrea.ngStrap', 'satellizer'])
  .config(function($stateProvider, $urlRouterProvider, $authProvider) {
    $stateProvider
      .state('home', {
        url: '/',
        templateUrl: 'partials/home.html'
      })
      .state('login', {
        url: '/login',
        templateUrl: 'partials/login.html',
        controller: 'LoginCtrl',
        resolve: {
          skipIfLoggedIn: skipIfLoggedIn
        }
      })
      .state('signup', {
        url: '/signup',
        templateUrl: 'partials/signup.html',
        controller: 'SignupCtrl',
        resolve: {
          skipIfLoggedIn: skipIfLoggedIn
        }
      })
      .state('logout', {
        url: '/logout',
        template: null,
        controller: 'LogoutCtrl'
      })
      .state('profile', {
        url: '/profile',
        templateUrl: 'partials/profile.html',
        controller: 'ProfileCtrl',
        resolve: {
          loginRequired: loginRequired
        }
      });

    $urlRouterProvider.otherwise('/');

    $authProvider.facebook({
      clientId: '603122136500203'
    });

    $authProvider.google({
      clientId: '631036554609-v5hm2amv4pvico3asfi97f54sc51ji4o.apps.googleusercontent.com'
    });

    $authProvider.github({
      clientId: '45ab07066fb6a805ed74'
    });

    $authProvider.linkedin({
      clientId: '77cw786yignpzj'
    });

    $authProvider.yahoo({
      clientId: 'dj0yJmk9SDVkM2RhNWJSc2ZBJmQ9WVdrOWIzVlFRMWxzTXpZbWNHbzlNQS0tJnM9Y29uc3VtZXJzZWNyZXQmeD0yYw--'
    });

    $authProvider.twitter({
      url: '/auth/twitter'
    });

    $authProvider.live({
      clientId: '000000004C12E68D'
    });

    $authProvider.oauth2({
      name: 'foursquare',
      url: '/auth/foursquare',
      clientId: 'MTCEJ3NGW2PNNB31WOSBFDSAD4MTHYVAZ1UKIULXZ2CVFC2K',
      redirectUri: window.location.origin || window.location.protocol + '//' + window.location.host,
      authorizationEndpoint: 'https://foursquare.com/oauth2/authenticate'
    });

    function skipIfLoggedIn($q, $auth) {
      var deferred = $q.defer();
      if ($auth.isAuthenticated()) {
        deferred.reject();
      } else {
        deferred.resolve();
      }
      return deferred.promise;
    }

    function loginRequired($q, $location, $auth) {
      var deferred = $q.defer();
      if ($auth.isAuthenticated()) {
        deferred.resolve();
      } else {
        $location.path('/login');
      }
      return deferred.promise;
    }
  });
<|endoftext|>


<commit_before>/* This file is part of NIT ( http://www.nitlanguage.org ).

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

   Documentation generator for the nit language.
   Generate API documentation in HTML format from nit source code.
*/

var Nitdoc = Nitdoc || {};

/*
 * Nitdoc QuickSearch module
 *
 */

Nitdoc.QuickSearch = function() {
	var rawList = nitdocQuickSearchRawList; // List of raw resulsts generated by nitdoc tool
	var searchField = null; // <input:text> search field
	var currentTable = null; // current search results

	var currentIndex = -1; // current cursor position into search results table

	// Enable QuickSearch plugin
	var enableQuickSearch = function(containerSelector) {
		searchField = $(document.createElement("input"))
		.attr({
			id: "nitdoc-qs-field",
			type: "text",
			autocomplete: "off",
			value: "quick search..."
		})
		.addClass("nitdoc-qs-field-notused")
		.keydown(function(event) {
			return Nitdoc.QuickSearch.doKeyDownAction(event.keyCode);
		})
		.keyup(function(event) {
			Nitdoc.QuickSearch.doKeyUpAction(event.keyCode);
		})
		.focusout(function() {
			if($(this).val() == "") {
				$(this).addClass("nitdoc-qs-field-notused");
				$(this).val("quick search...");
			}
		})
		.focusin(function() {
			if($(this).val() == "quick search...") {
				$(this).removeClass("nitdoc-qs-field-notused");
				$(this).val("");
			}
		});

		$(containerSelector).append(
			$(document.createElement("li"))
			.attr("id", "nitdoc-qs-li")
			.append(searchField)
		);

		// Close quicksearch list on click
		$(document).click(function(e) {
			console.log(e);
			Nitdoc.QuickSearch.closeResultsTable();
		});
	}

	var doKeyDownAction = function(key) {
		switch(key) {
			case 38: // Up
				selectPrevResult();
				return false;
			case 40: // Down
				selectNextResult();
				return false;
			default:
				return true;
		 }
	}

	var doKeyUpAction = function(key) {
		switch(key) {
			case 38: // Up
			case 40: // Down
			break;

			case 13: // Enter
				goToResult();
				return false;
			break;

			case 27: // Escape
				$(this).blur();
				closeResultsTable();
			break;

			default: // Other keys
				var query = searchField.val();
				if(!query) {
					return false;
				}
				var results = getResults(query);
				displayResultsTable(query, results);
			break;
		}
	}

	// Get results corresponding to search query
	var getResults = function(query) {
		var results = {};
		results.matches = new Array();
		for(var entry in rawList) {
			if(!entry.startsWith(query, true)) {
				continue;
			}
			var cat = new Object();
			cat.name = entry;
			cat.entries = rawList[entry];
			results.matches[results.matches.length] = cat;

			if(entry == query) {
				cat.rank = 3;
			} else if(entry.toUpperCase() == query.toUpperCase()) {
				cat.rank = 2;
			} else {
				cat.rank = 1 + query.dice(entry);
			}
		}
		results.matches.sort(rankSorter);
		results.partials = new Array();
		if(results.matches.length == 0) {
			for(var entry in rawList) {
				var cat = new Object();
				cat.name = entry;
				cat.entries = rawList[entry];
				cat.rank = query.dice(entry);
				if(cat.rank > 0) {
					results.partials[results.partials.length] = cat;
				}
			}
			results.partials.sort(rankSorter);
		}
		return results;
	}

	// Sort an array of results by rank
	var rankSorter = function(a, b){
		if(a.rank  b.rank) {
			return -1;
		}
		return 0;
	}

	// Display results in a popup table
	var displayResultsTable = function(query, results) {
		// Clear results table
		if(currentTable) currentTable.remove();

		// Build results table
		currentIndex = -1;
		currentTable = $(document.createElement("table"));
		currentTable.attr("id", "nitdoc-qs-table");
		currentTable.css("position", "absolute");
		currentTable.width(searchField.outerWidth());

		var maxSize = 10;
		var count = 0;
		var resultSet;
		if(results.matches.length == 0) {
			resultSet = results.partials
		} else {
			resultSet = results.matches
		}
		for(var i in resultSet) {
			var cat = resultSet[i];
			var result = cat.entries[0];

			addResultRow(count, cat.name, result.txt, result.url, "nitdoc-qs-cat")
			if(count >= maxSize) {
				currentTable.find("tbody").children().last().hide();
			}
			count++;

			for(var j = 1; j < cat.entries.length; j++) {
				var result = cat.entries[j];
				addResultRow(count, cat.name, result.txt, result.url, "nitdoc-qs-sub")
				if(count >= maxSize) {
					currentTable.find("tr.nitdoc-qs-row").last().hide();
				}
				count++;
			}
		}
		if(count >= maxSize) {
			currentTable.prepend(
				$(document.createElement("tr"))
				.addClass("nitdoc-qs-overflow-up")
				.addClass("nitdoc-qs-overflow-inactive")
				.append(
					$(document.createElement("td"))
					.attr("colspan", 2)
					.html("▲")
				)
				.click( function(e) {
					e.stopPropagation();
					selectPrevResult();
				})
			);
			currentTable.append(
				$(document.createElement("tr"))
				.addClass("nitdoc-qs-overflow-down")
				.addClass(count >= maxSize ? "nitdoc-qs-overflow-active" : "nitdoc-qs-overflow-inactive")
				.append(
					$(document.createElement("td"))
					.attr("colspan", 2)
					.html("▼")
				)
				.click( function(e) {
					e.stopPropagation();
					console.log("nest");
					selectNextResult();
				})
			);
		}
		if(results.matches.length == 0) {
			currentTable.prepend(
				$("
")
				.append(
					$("")
					.html("Sorry, there is no match, best results are:")
				)
			);
		}

		// Initialize table
		$("body").append(currentTable);
		resizeResultsTable();
		if(currentTable.find("tr").length > 0) {
			setIndex(0);
		}
	}

	// adds a result row to the current result table
	var addResultRow = function(index, name, txt, url, cls) {
		currentTable.append(
			$(document.createElement("tr"))
			.addClass("nitdoc-qs-row")
			.data("searchDetails", {name: name, url: url})
			.data("index", index)
			.append(
				$(document.createElement("td")).html(name)
				.addClass(cls)
			)
			.append(
				$(document.createElement("td"))
					.addClass("nitdoc-qs-info")
					.html(txt + " »")
			)
			.mouseover( function() {
				setIndex($(this).data("index"));
			})
			.mouseout( function() {
				$(this).removeClass("nitdoc-qs-active");
			 })
			.click( function() {
				window.location = $(this).data("searchDetails")["url"];
			})
		);
	}

	// adapts result table to content
	var resizeResultsTable = function() {
		currentTable.offset({
			left: searchField.offset().left + (searchField.outerWidth() - currentTable.outerWidth()),
			top: searchField.offset().top + searchField.outerHeight()
		});
	}

	// select row at index
	var setIndex = function(index) {
		$(currentTable.find("tr.nitdoc-qs-row")[currentIndex]).removeClass("nitdoc-qs-active");
		currentIndex = index;
		var currentRow = $(currentTable.find("tr.nitdoc-qs-row")[currentIndex]);
		currentRow.addClass("nitdoc-qs-active");
		//searchField.val(currentRow.data("searchDetails").name);
	}

	var hasPrev = function(index) {
		return index - 1 >= 0;
	}

	var hasNext = function(index) {
		return index + 1 < currentTable.find("tr.nitdoc-qs-row").length;
	}

	var selectPrevResult = function() {
		if(hasPrev(currentIndex)) {
			setIndex(currentIndex - 1);
			if(!$(currentTable.find("tr.nitdoc-qs-row")[currentIndex]).is(":visible")) {
				currentTable.find("tr.nitdoc-qs-row:visible").last().hide();
				currentTable.find("tr.nitdoc-qs-overflow-down").addClass("nitdoc-qs-overflow-active");
				$(currentTable.find("tr.nitdoc-qs-row")[currentIndex]).show();
				if(!hasPrev(currentIndex)) {
					currentTable.find("tr.nitdoc-qs-overflow-up").removeClass("nitdoc-qs-overflow-active");
				}
				resizeResultsTable();
			}
		}
	}

	var selectNextResult = function() {
		if(hasNext(currentIndex)) {
			setIndex(currentIndex + 1);
			if(!$(currentTable.find("tr.nitdoc-qs-row")[currentIndex]).is(":visible")) {
				currentTable.find("tr.nitdoc-qs-row:visible").first().hide();
				currentTable.find("tr.nitdoc-qs-overflow-up").addClass("nitdoc-qs-overflow-active");
				$(currentTable.find("tr.nitdoc-qs-row")[currentIndex]).show();
				if(!hasNext(currentIndex)) {
					currentTable.find("tr.nitdoc-qs-overflow-down").removeClass("nitdoc-qs-overflow-active");
				}
				resizeResultsTable();
			}
		}
	}

	// Load selected search result page
	var goToResult = function() {
		if(currentIndex > -1) {
			window.location = $(currentTable.find("tr.nitdoc-qs-row")[currentIndex]).data("searchDetails").url;
			return;
		}

		if(searchField.val().length == 0) { return; }

		window.location = "search.html#q=" + searchField.val();
		if(window.location.href.indexOf("search.html") > -1) {
			location.reload();
		}
	}

	// Close the results table
	closeResultsTable = function(target) {
		if(target != searchField && target != currentTable) {
			if(currentTable != null) {
				currentTable.remove();
				currentTable = null;
			}
		}
	}

	// Public interface
	var quicksearch = {
		enableQuickSearch: enableQuickSearch,
		doKeyUpAction: doKeyUpAction,
		doKeyDownAction: doKeyDownAction,
		closeResultsTable: closeResultsTable
	};

	return quicksearch;
}();

$(document).ready(function() {
	Nitdoc.QuickSearch.enableQuickSearch("nav.main ul");
});

/*
 * Utils
 */

String.prototype.startsWith = function(prefix, caseSensitive) {
	if(caseSensitive) {
		return this.toUpperCase().indexOf(prefix.toUpperCase()) === 0;
	}
    return this.indexOf(prefix) === 0;
}

// Compare two strings using Sorensen-Dice Coefficient
// see: http://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficient
String.prototype.dice = function(other) {
	var length1 = this.length - 1;
	var length2 = other.length - 1;
	if(length1 < 1 || length2 < 1) return 0;

	var bigrams2 = [];
	for(var i = 0; i < length2; i++) {
		bigrams2.push(other.substr(i, 2));
	}

	var intersection = 0;
	for(var i = 0; i < length1; i++) {
		var bigram1 = this.substr(i, 2);
		for(var j = 0; j < length2; j++) {
			if(bigram1 == bigrams2[j]) {
				intersection++;
				bigrams2[j] = null;
				break;
			}
		}
	}
	return (2.0 * intersection) / (length1 + length2);
}

<commit_msg>nitdoc: clean useless console.log on body click event<commit_after>/* This file is part of NIT ( http://www.nitlanguage.org ).

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

   Documentation generator for the nit language.
   Generate API documentation in HTML format from nit source code.
*/

var Nitdoc = Nitdoc || {};

/*
 * Nitdoc QuickSearch module
 *
 */

Nitdoc.QuickSearch = function() {
	var rawList = nitdocQuickSearchRawList; // List of raw resulsts generated by nitdoc tool
	var searchField = null; // <input:text> search field
	var currentTable = null; // current search results

	var currentIndex = -1; // current cursor position into search results table

	// Enable QuickSearch plugin
	var enableQuickSearch = function(containerSelector) {
		searchField = $(document.createElement("input"))
		.attr({
			id: "nitdoc-qs-field",
			type: "text",
			autocomplete: "off",
			value: "quick search..."
		})
		.addClass("nitdoc-qs-field-notused")
		.keydown(function(event) {
			return Nitdoc.QuickSearch.doKeyDownAction(event.keyCode);
		})
		.keyup(function(event) {
			Nitdoc.QuickSearch.doKeyUpAction(event.keyCode);
		})
		.focusout(function() {
			if($(this).val() == "") {
				$(this).addClass("nitdoc-qs-field-notused");
				$(this).val("quick search...");
			}
		})
		.focusin(function() {
			if($(this).val() == "quick search...") {
				$(this).removeClass("nitdoc-qs-field-notused");
				$(this).val("");
			}
		});

		$(containerSelector).append(
			$(document.createElement("li"))
			.attr("id", "nitdoc-qs-li")
			.append(searchField)
		);

		// Close quicksearch list on click
		$(document).click(function(e) {
			Nitdoc.QuickSearch.closeResultsTable();
		});
	}

	var doKeyDownAction = function(key) {
		switch(key) {
			case 38: // Up
				selectPrevResult();
				return false;
			case 40: // Down
				selectNextResult();
				return false;
			default:
				return true;
		 }
	}

	var doKeyUpAction = function(key) {
		switch(key) {
			case 38: // Up
			case 40: // Down
			break;

			case 13: // Enter
				goToResult();
				return false;
			break;

			case 27: // Escape
				$(this).blur();
				closeResultsTable();
			break;

			default: // Other keys
				var query = searchField.val();
				if(!query) {
					return false;
				}
				var results = getResults(query);
				displayResultsTable(query, results);
			break;
		}
	}

	// Get results corresponding to search query
	var getResults = function(query) {
		var results = {};
		results.matches = new Array();
		for(var entry in rawList) {
			if(!entry.startsWith(query, true)) {
				continue;
			}
			var cat = new Object();
			cat.name = entry;
			cat.entries = rawList[entry];
			results.matches[results.matches.length] = cat;

			if(entry == query) {
				cat.rank = 3;
			} else if(entry.toUpperCase() == query.toUpperCase()) {
				cat.rank = 2;
			} else {
				cat.rank = 1 + query.dice(entry);
			}
		}
		results.matches.sort(rankSorter);
		results.partials = new Array();
		if(results.matches.length == 0) {
			for(var entry in rawList) {
				var cat = new Object();
				cat.name = entry;
				cat.entries = rawList[entry];
				cat.rank = query.dice(entry);
				if(cat.rank > 0) {
					results.partials[results.partials.length] = cat;
				}
			}
			results.partials.sort(rankSorter);
		}
		return results;
	}

	// Sort an array of results by rank
	var rankSorter = function(a, b){
		if(a.rank  b.rank) {
			return -1;
		}
		return 0;
	}

	// Display results in a popup table
	var displayResultsTable = function(query, results) {
		// Clear results table
		if(currentTable) currentTable.remove();

		// Build results table
		currentIndex = -1;
		currentTable = $(document.createElement("table"));
		currentTable.attr("id", "nitdoc-qs-table");
		currentTable.css("position", "absolute");
		currentTable.width(searchField.outerWidth());

		var maxSize = 10;
		var count = 0;
		var resultSet;
		if(results.matches.length == 0) {
			resultSet = results.partials
		} else {
			resultSet = results.matches
		}
		for(var i in resultSet) {
			var cat = resultSet[i];
			var result = cat.entries[0];

			addResultRow(count, cat.name, result.txt, result.url, "nitdoc-qs-cat")
			if(count >= maxSize) {
				currentTable.find("tbody").children().last().hide();
			}
			count++;

			for(var j = 1; j < cat.entries.length; j++) {
				var result = cat.entries[j];
				addResultRow(count, cat.name, result.txt, result.url, "nitdoc-qs-sub")
				if(count >= maxSize) {
					currentTable.find("tr.nitdoc-qs-row").last().hide();
				}
				count++;
			}
		}
		if(count >= maxSize) {
			currentTable.prepend(
				$(document.createElement("tr"))
				.addClass("nitdoc-qs-overflow-up")
				.addClass("nitdoc-qs-overflow-inactive")
				.append(
					$(document.createElement("td"))
					.attr("colspan", 2)
					.html("▲")
				)
				.click( function(e) {
					e.stopPropagation();
					selectPrevResult();
				})
			);
			currentTable.append(
				$(document.createElement("tr"))
				.addClass("nitdoc-qs-overflow-down")
				.addClass(count >= maxSize ? "nitdoc-qs-overflow-active" : "nitdoc-qs-overflow-inactive")
				.append(
					$(document.createElement("td"))
					.attr("colspan", 2)
					.html("▼")
				)
				.click( function(e) {
					e.stopPropagation();
					console.log("nest");
					selectNextResult();
				})
			);
		}
		if(results.matches.length == 0) {
			currentTable.prepend(
				$("
")
				.append(
					$("")
					.html("Sorry, there is no match, best results are:")
				)
			);
		}

		// Initialize table
		$("body").append(currentTable);
		resizeResultsTable();
		if(currentTable.find("tr").length > 0) {
			setIndex(0);
		}
	}

	// adds a result row to the current result table
	var addResultRow = function(index, name, txt, url, cls) {
		currentTable.append(
			$(document.createElement("tr"))
			.addClass("nitdoc-qs-row")
			.data("searchDetails", {name: name, url: url})
			.data("index", index)
			.append(
				$(document.createElement("td")).html(name)
				.addClass(cls)
			)
			.append(
				$(document.createElement("td"))
					.addClass("nitdoc-qs-info")
					.html(txt + " »")
			)
			.mouseover( function() {
				setIndex($(this).data("index"));
			})
			.mouseout( function() {
				$(this).removeClass("nitdoc-qs-active");
			 })
			.click( function() {
				window.location = $(this).data("searchDetails")["url"];
			})
		);
	}

	// adapts result table to content
	var resizeResultsTable = function() {
		currentTable.offset({
			left: searchField.offset().left + (searchField.outerWidth() - currentTable.outerWidth()),
			top: searchField.offset().top + searchField.outerHeight()
		});
	}

	// select row at index
	var setIndex = function(index) {
		$(currentTable.find("tr.nitdoc-qs-row")[currentIndex]).removeClass("nitdoc-qs-active");
		currentIndex = index;
		var currentRow = $(currentTable.find("tr.nitdoc-qs-row")[currentIndex]);
		currentRow.addClass("nitdoc-qs-active");
		//searchField.val(currentRow.data("searchDetails").name);
	}

	var hasPrev = function(index) {
		return index - 1 >= 0;
	}

	var hasNext = function(index) {
		return index + 1 < currentTable.find("tr.nitdoc-qs-row").length;
	}

	var selectPrevResult = function() {
		if(hasPrev(currentIndex)) {
			setIndex(currentIndex - 1);
			if(!$(currentTable.find("tr.nitdoc-qs-row")[currentIndex]).is(":visible")) {
				currentTable.find("tr.nitdoc-qs-row:visible").last().hide();
				currentTable.find("tr.nitdoc-qs-overflow-down").addClass("nitdoc-qs-overflow-active");
				$(currentTable.find("tr.nitdoc-qs-row")[currentIndex]).show();
				if(!hasPrev(currentIndex)) {
					currentTable.find("tr.nitdoc-qs-overflow-up").removeClass("nitdoc-qs-overflow-active");
				}
				resizeResultsTable();
			}
		}
	}

	var selectNextResult = function() {
		if(hasNext(currentIndex)) {
			setIndex(currentIndex + 1);
			if(!$(currentTable.find("tr.nitdoc-qs-row")[currentIndex]).is(":visible")) {
				currentTable.find("tr.nitdoc-qs-row:visible").first().hide();
				currentTable.find("tr.nitdoc-qs-overflow-up").addClass("nitdoc-qs-overflow-active");
				$(currentTable.find("tr.nitdoc-qs-row")[currentIndex]).show();
				if(!hasNext(currentIndex)) {
					currentTable.find("tr.nitdoc-qs-overflow-down").removeClass("nitdoc-qs-overflow-active");
				}
				resizeResultsTable();
			}
		}
	}

	// Load selected search result page
	var goToResult = function() {
		if(currentIndex > -1) {
			window.location = $(currentTable.find("tr.nitdoc-qs-row")[currentIndex]).data("searchDetails").url;
			return;
		}

		if(searchField.val().length == 0) { return; }

		window.location = "search.html#q=" + searchField.val();
		if(window.location.href.indexOf("search.html") > -1) {
			location.reload();
		}
	}

	// Close the results table
	closeResultsTable = function(target) {
		if(target != searchField && target != currentTable) {
			if(currentTable != null) {
				currentTable.remove();
				currentTable = null;
			}
		}
	}

	// Public interface
	var quicksearch = {
		enableQuickSearch: enableQuickSearch,
		doKeyUpAction: doKeyUpAction,
		doKeyDownAction: doKeyDownAction,
		closeResultsTable: closeResultsTable
	};

	return quicksearch;
}();

$(document).ready(function() {
	Nitdoc.QuickSearch.enableQuickSearch("nav.main ul");
});

/*
 * Utils
 */

String.prototype.startsWith = function(prefix, caseSensitive) {
	if(caseSensitive) {
		return this.toUpperCase().indexOf(prefix.toUpperCase()) === 0;
	}
    return this.indexOf(prefix) === 0;
}

// Compare two strings using Sorensen-Dice Coefficient
// see: http://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficient
String.prototype.dice = function(other) {
	var length1 = this.length - 1;
	var length2 = other.length - 1;
	if(length1 < 1 || length2 < 1) return 0;

	var bigrams2 = [];
	for(var i = 0; i < length2; i++) {
		bigrams2.push(other.substr(i, 2));
	}

	var intersection = 0;
	for(var i = 0; i < length1; i++) {
		var bigram1 = this.substr(i, 2);
		for(var j = 0; j < length2; j++) {
			if(bigram1 == bigrams2[j]) {
				intersection++;
				bigrams2[j] = null;
				break;
			}
		}
	}
	return (2.0 * intersection) / (length1 + length2);
}

<|endoftext|>


<commit_before>'use strict';

var debug = require('debug')('swara:processFiles'),
  async = require('async'),
  chalk = require('chalk'),
  fs = require('fs'),
  path = require('path'),
  util = require('util'),
  _ = require('lodash'),
  mm = require('musicmetadata'),
  moment = require('moment'),
  mongoose = require('mongoose'),
  errorHandler = require('../../controllers/errors.server.controller'),
  Subfolder = mongoose.model('Subfolder'),
  Track = mongoose.model('Track');

var getTitleFromPath = function (musicFilePath) {
  if (!musicFilePath) {
    return null;
  }
  var title = musicFilePath.substr(musicFilePath.lastIndexOf(path.sep) + 1);
  return title.substr(0, title.lastIndexOf('.'));
};

var incrementDictionaryItemCount = function (dict, item) {
  if (!dict[item]) {
    dict[item] = 0;
  }
  dict[item] += 1;
  return dict;
};

// ** Reference **
//  var files = {
//    musicFilepaths       : [],
//    tracksBySubfolder    : {},
//    fileCountBySubfolder : {}
//  };
//

var createProcessFileIterator = function (folder, files) {
  var counter = 0;
  return function (musicFilepath, nextTrack) {
    var musicFileStream = fs.createReadStream(musicFilepath);
    if (!musicFilepath) {
      console.log('(%s) Cannot open file %s', moment(), musicFilepath);
      counter++;
      nextTrack();
    }
    mm(musicFileStream, function (err, metadata) {
      if (err) {
        console.warn(util.format(chalk.red('Error in parsing the music file %s'), musicFilepath));
        console.warn(err);
        counter++;
        nextTrack();
      } else {
        // have the metadata here -> Save the Track
        //  check if the sub-folder for this track is already added into the sub-folder dictionary and add it if it is not
        //    increment the tracks count for the root-folder and sub-folder in the in-memory variables
        Track.findOne({path : musicFilepath}, function (err, existingTrack) {
          if (err) {
            console.error(chalk.red(err));
            counter++;
            nextTrack();
          } else {
            var action = 'added';
            var track = {};
            if (existingTrack) {
              action = 'updated';
              track = _.extend(existingTrack, track);
            } else {
              track = new Track();
            }
            track.parentFolder = folder;
            track.path = musicFilepath;
            track.title = metadata.title || getTitleFromPath(musicFilepath);
            var year = parseInt(metadata.year || '', 10);
            if (!Number.isNaN(year)) {
              track.year = year;
            }
            if (metadata.track && metadata.track.no) {
              track.trackNumber = metadata.track.no;
            }
            track.album = metadata.album || '';
            track.artist = metadata.artist.join(', ');
            track.genre = metadata.genre.join(', ');
            track.modified = track.lastScanned = Date.now();
            track.user = folder.user;
            track.save(function (err, track) {
              counter++;
              if (err) {
                console.error(chalk.red(errorHandler.getErrorMessage(err)));
              } else {
                var subfolderPath = path.dirname(musicFilepath);
                if (!files.tracksBySubfolder[subfolderPath]) {
                  files.tracksBySubfolder[subfolderPath] = [];
                }
                files.tracksBySubfolder[subfolderPath].push(track);
                console.log(util.format(chalk.gray('%s') + ' - %s track - ' + chalk.blue('%s'),
                  counter, action, musicFilepath));
              }
              nextTrack();
            });
          }
        });
      }
    });
  };
};

var processFiles = {
  /**
   * Creates a listener for the `file` event emitted by `walk` that adds all the walked files
   * into the internal buffer - `files`
   * @param files The buffer where the array of files and the dictionaries of music files and total files is stored
   * @returns {Function}
   */
  createWalkerFileHandler : function (files) {
    return function (root, fileStats, next) {
      var filepath = path.join(root, fileStats.name);
      debug('Walking file - %s', filepath);
      files.fileCountBySubfolder = incrementDictionaryItemCount(files.fileCountBySubfolder, root);

      if (fileStats.name.match(/\.mp3$/i)) {
        files.musicFilepaths.push(filepath);
      }
      next();
    };
  },
  /**
   * Creates a listener for the `end` event emitted by `walk` to process the buffer - `files`
   * @param folder The folder being scanned
   * @param files The buffer where the array of files and the dictionaries of music files and total files is stored
   * @param allDoneCallback Callback that will be called when all of the walked files have been processed
   * @returns {Function}
   */
  createWalkerEndHandler  : function (folder, files, allDoneCallback) {
    return function () {
      // process all the music files from the musicfilepaths array
      debug('About to start parsing %s music filepaths', files.musicFilepaths.length);
      async.eachLimit(files.musicFilepaths, 100, createProcessFileIterator(folder, files), function (err) { // done processing all files or there was an error
        debug('Done processing all the musicFilepaths from array');
        if (err) {
          console.error(util.format(chalk.red('Error processing one of the music files - (%s)'), moment()));
          console.error(chalk.red(err));
        } else {
          // save the in memory dictionaries as new sub-folders
          var processed = 0;
          var cumulativeMusicFilesCount = 0;
          var subfolders = [];
          var subfolderPaths = Object.keys(files.tracksBySubfolder);
          debug('About to iterate through the subfolderPaths which has %s items', subfolderPaths.length);
          async.eachLimit(subfolderPaths, 20, function (subfolderPath, nextSubfolder) {
            var subfolderTracks = files.tracksBySubfolder[subfolderPath];
            var musicFilesCount = subfolderTracks.length;
            Subfolder.findOne({path : subfolderPath}, function (err, existingSubfolder) {
              if (err) {
                nextSubfolder(err);
              } else {
                // increment the counter and collect the cumulatives
                processed++;
                cumulativeMusicFilesCount += musicFilesCount;

                var action = 'added';
                var subfolder = {};
                if (existingSubfolder) {
                  action = 'updated';
                  subfolder = _.extend(existingSubfolder, subfolder);
                } else {
                  subfolder = new Subfolder();
                }
                subfolder.parentFolder = folder;
                subfolder.path = subfolderPath;
                subfolder.title = subfolderPath.substr(subfolderPath.lastIndexOf(path.sep) + 1);
                subfolder.filesCount = files.fileCountBySubfolder[subfolderPath];
                subfolder.musicFilesCount = musicFilesCount;
                subfolder.tracks = subfolderTracks;
                subfolder.modified = subfolder.lastScanned = Date.now();
                subfolder.user = folder.user;
                subfolder.save(function (err, subfolder) {
                  if (err) {
                    nextSubfolder(errorHandler.getErrorMessage(err));
                  } else {
                    subfolders.push(subfolder);
                    console.log(util.format('%s subfolder ' + chalk.green('%s'), action, subfolderPath));
                    nextSubfolder();
                  }
                });
              }
            });
          }, function (err) { // done saving all subfolders
            debug('Done iterating and saving all subfolders');
            // update the root folder entry
            if (err) {
              console.error(chalk.red(err));
            } else {
              var foldersCount = Object.keys(files.fileCountBySubfolder).length;
              var musicFoldersCount = Object.keys(files.tracksBySubfolder).length;
              var totalFilesCount = 0;
              if (foldersCount) {
                totalFilesCount = _.values(files.fileCountBySubfolder).reduce(function (prev, curr) {
                  return prev + curr;
                });
              }
              folder.foldersCount = foldersCount;
              folder.musicFoldersCount = musicFoldersCount;
              folder.filesCount = totalFilesCount;
              folder.musicFilesCount = cumulativeMusicFilesCount;
              folder.scanning = false;
              folder.subfolders = subfolders;
              folder.lastScanned = folder.modified = Date.now();

              folder.save(function (err) {
                if (err) {
                  console.error(chalk.red(errorHandler.getErrorMessage(err)));
                } else {
                  allDoneCallback(folder, cumulativeMusicFilesCount, totalFilesCount, musicFoldersCount, foldersCount);
                }
                console.info('Exiting background process: %s (pid)', process.pid);
                process.exit(!!err);
              });
            }
          });
        }
      });
    };
  }
};

module.exports = processFiles;
<commit_msg>destroy the open streams after processing a file<commit_after>'use strict';

var debug = require('debug')('swara:processFiles'),
  async = require('async'),
  chalk = require('chalk'),
  fs = require('fs'),
  path = require('path'),
  util = require('util'),
  _ = require('lodash'),
  mm = require('musicmetadata'),
  moment = require('moment'),
  mongoose = require('mongoose'),
  errorHandler = require('../../controllers/errors.server.controller'),
  Subfolder = mongoose.model('Subfolder'),
  Track = mongoose.model('Track');

var getTitleFromPath = function (musicFilePath) {
  if (!musicFilePath) {
    return null;
  }
  var title = musicFilePath.substr(musicFilePath.lastIndexOf(path.sep) + 1);
  return title.substr(0, title.lastIndexOf('.'));
};

var incrementDictionaryItemCount = function (dict, item) {
  if (!dict[item]) {
    dict[item] = 0;
  }
  dict[item] += 1;
  return dict;
};

// ** Reference **
//  var files = {
//    musicFilepaths       : [],
//    tracksBySubfolder    : {},
//    fileCountBySubfolder : {}
//  };
//

var createProcessFileIterator = function (folder, files) {
  var counter = 0;
  return function (musicFilepath, nextTrack) {
    var musicFileStream = fs.createReadStream(musicFilepath);
    if (!musicFileStream) {
      console.log('(%s) Cannot open file %s', moment(), musicFilepath);
      counter++;
      nextTrack();
    }
    mm(musicFileStream, function (err, metadata) {
      if (err) {
        console.warn(util.format(chalk.red('Error in parsing the music file %s'), musicFilepath));
        console.warn(err);
        counter++;
        musicFileStream.destroy();
        nextTrack();
      } else {
        // have the metadata here -> Save the Track
        //  check if the sub-folder for this track is already added into the sub-folder dictionary and add it if it is not
        //    increment the tracks count for the root-folder and sub-folder in the in-memory variables
        Track.findOne({path : musicFilepath}, function (err, existingTrack) {
          if (err) {
            console.error(chalk.red(err));
            counter++;
            musicFileStream.destroy();
            nextTrack();
          } else {
            var action = 'added';
            var track = {};
            if (existingTrack) {
              action = 'updated';
              track = _.extend(existingTrack, track);
            } else {
              track = new Track();
            }
            track.parentFolder = folder;
            track.path = musicFilepath;
            track.title = metadata.title || getTitleFromPath(musicFilepath);
            var year = parseInt(metadata.year || '', 10);
            if (!Number.isNaN(year)) {
              track.year = year;
            }
            if (metadata.track && metadata.track.no) {
              track.trackNumber = metadata.track.no;
            }
            track.album = metadata.album || '';
            track.artist = metadata.artist.join(', ');
            track.genre = metadata.genre.join(', ');
            track.modified = track.lastScanned = Date.now();
            track.user = folder.user;

            track.save(function (err, track) {
              counter++;
              if (err) {
                console.error(chalk.red(errorHandler.getErrorMessage(err)));
              } else {
                var subfolderPath = path.dirname(musicFilepath);
                if (!files.tracksBySubfolder[subfolderPath]) {
                  files.tracksBySubfolder[subfolderPath] = [];
                }
                files.tracksBySubfolder[subfolderPath].push(track);
                console.log(util.format(chalk.gray('%s') + ' - %s track - ' + chalk.blue('%s'),
                  counter, action, musicFilepath));
              }
              musicFileStream.destroy();
              nextTrack();
            });

          }
        });
      }
    });
  };
};

var processFiles = {
  /**
   * Creates a listener for the `file` event emitted by `walk` that adds all the walked files
   * into the internal buffer - `files`
   * @param files The buffer where the array of files and the dictionaries of music files and total files is stored
   * @returns {Function}
   */
  createWalkerFileHandler : function (files) {
    return function (root, fileStats, next) {
      var filepath = path.join(root, fileStats.name);
      debug('Walking file - %s', filepath);
      files.fileCountBySubfolder = incrementDictionaryItemCount(files.fileCountBySubfolder, root);

      if (fileStats.name.match(/\.mp3$/i)) {
        files.musicFilepaths.push(filepath);
      }
      next();
    };
  },
  /**
   * Creates a listener for the `end` event emitted by `walk` to process the buffer - `files`
   * @param folder The folder being scanned
   * @param files The buffer where the array of files and the dictionaries of music files and total files is stored
   * @param allDoneCallback Callback that will be called when all of the walked files have been processed
   * @returns {Function}
   */
  createWalkerEndHandler  : function (folder, files, allDoneCallback) {
    return function () {
      // process all the music files from the musicfilepaths array
      debug('About to start parsing %s music filepaths', files.musicFilepaths.length);
      async.eachLimit(files.musicFilepaths, 100, createProcessFileIterator(folder, files), function (err) { // done processing all files or there was an error
        debug('Done processing all the musicFilepaths from array');
        if (err) {
          console.error(util.format(chalk.red('Error processing one of the music files - (%s)'), moment()));
          console.error(chalk.red(err));
        } else {
          // save the in memory dictionaries as new sub-folders
          var processed = 0;
          var cumulativeMusicFilesCount = 0;
          var subfolders = [];
          var subfolderPaths = Object.keys(files.tracksBySubfolder);

          debug('About to iterate through the subfolderPaths which has %s items', subfolderPaths.length);
          async.eachLimit(subfolderPaths, 20, function (subfolderPath, nextSubfolder) {
            var subfolderTracks = files.tracksBySubfolder[subfolderPath];
            var musicFilesCount = subfolderTracks.length;
            Subfolder.findOne({path : subfolderPath}, function (err, existingSubfolder) {
              if (err) {
                nextSubfolder(err);
              } else {
                // increment the counter and collect the cumulatives
                processed++;
                cumulativeMusicFilesCount += musicFilesCount;

                var action = 'added';
                var subfolder = {};
                if (existingSubfolder) {
                  action = 'updated';
                  subfolder = _.extend(existingSubfolder, subfolder);
                } else {
                  subfolder = new Subfolder();
                  subfolder.parentFolder = folder;
                  subfolder.path = subfolderPath;
                  subfolder.title = subfolderPath.substr(subfolderPath.lastIndexOf(path.sep) + 1);
                }
                subfolder.filesCount = files.fileCountBySubfolder[subfolderPath];
                subfolder.musicFilesCount = musicFilesCount;
                subfolder.tracks = subfolderTracks;
                subfolder.modified = subfolder.lastScanned = Date.now();
                subfolder.user = folder.user;

                subfolder.save(function (err, subfolder) {
                  if (err) {
                    nextSubfolder(errorHandler.getErrorMessage(err));
                  } else {
                    subfolders.push(subfolder);
                    console.log(util.format('%s subfolder ' + chalk.green('%s'), action, subfolderPath));
                    nextSubfolder();
                  }
                });

              }
            });
          }, function (err) { // done saving all subfolders
            debug('Done iterating and saving all subfolders');
            // update the root folder entry
            if (err) {
              console.error(chalk.red(err));
            } else {
              var foldersCount = Object.keys(files.fileCountBySubfolder).length;
              var musicFoldersCount = Object.keys(files.tracksBySubfolder).length;
              var totalFilesCount = 0;
              if (foldersCount) {
                totalFilesCount = _.values(files.fileCountBySubfolder).reduce(function (prev, curr) {
                  return prev + curr;
                });
              }
              folder.foldersCount = foldersCount;
              folder.musicFoldersCount = musicFoldersCount;
              folder.filesCount = totalFilesCount;
              folder.musicFilesCount = cumulativeMusicFilesCount;
              folder.scanning = false;
              folder.subfolders = subfolders;
              folder.lastScanned = folder.modified = Date.now();

              folder.save(function (err) {
                if (err) {
                  console.error(chalk.red(errorHandler.getErrorMessage(err)));
                } else {
                  allDoneCallback(folder, cumulativeMusicFilesCount, totalFilesCount, musicFoldersCount, foldersCount);
                }
                console.info('Exiting background process: %s (pid)', process.pid);
                process.exit(!!err);
              });

            }
          });
        }
      });
    };
  }
};

module.exports = processFiles;
<|endoftext|>


<commit_before>"use strict";

angular.module("angular-mobile-docs")
    .factory("MockFetchService", function ($http, $q) {

        var config = {
            url: "http://apidocs.angularjs.de/code.angularjs.org/"
        };

        var getVersionList = function (version) {
            return $http.get(config.url+"versions.json");
        }

        var getFileList = function (version) {
            return $http.get(
                config.url
                    + version
                    + "/docs/partials/api/filelist.json");
        }

        var getPartial = function (version, name) {
            return $http.get(
                config.url
                    + version
                    + "/docs/partials/api/" + name);
        }

        var getAllPartials = function (version) {
            var promises = [];
            var fileNameList = getFileList(version);

            angular.forEach(fileNameList, function (fileName) {
                promises.push(getPartial(fileName, version));
            })

            return $q.all(promises);
        }

        return {
            getVersionList: function () {
                return getVersionList();
            },
            getFileList   : function (version) {
                return getFileList(version);
            },
            getPartial    : function (version, name) {
                return getPartial(version, name);
            },
            getAllPartials: function (version) {
                return getAllPartials(version);
            }

        };

    });<commit_msg>Change Basic-URL<commit_after>"use strict";

angular.module("angular-mobile-docs")
    .factory("MockFetchService", function ($http, $q) {

        var config = {
            url: "http://apidocs.angularjs.de/code/"
        };

        var getVersionList = function (version) {
            return $http.get(config.url+"versions.json");
        }

        var getFileList = function (version) {
            return $http.get(
                config.url
                    + version
                    + "/docs/partials/api/filelist.json");
        }

        var getPartial = function (version, name) {
            return $http.get(
                config.url
                    + version
                    + "/docs/partials/api/" + name);
        }

        var getAllPartials = function (version) {
            var promises = [];
            var fileNameList = getFileList(version);

            angular.forEach(fileNameList, function (fileName) {
                promises.push(getPartial(fileName, version));
            })

            return $q.all(promises);
        }

        return {
            getVersionList: function () {
                return getVersionList();
            },
            getFileList   : function (version) {
                return getFileList(version);
            },
            getPartial    : function (version, name) {
                return getPartial(version, name);
            },
            getAllPartials: function (version) {
                return getAllPartials(version);
            }

        };

    });<|endoftext|>


<commit_before>'use strict'

var spawn = require('child_process').spawn
var path = require('path')
var helpers = require('./helpers')
var chai = require('chai')
var chaiAsPromised = require('chai-as-promised')

var rootDir = path.dirname(__dirname)
var packageInfo = require(path.join(rootDir, 'package.json'))
var scriptPath = path.join(rootDir, packageInfo.main)
var testConfigPath = path.join(rootDir, 'tests', 'helpers', 'test-config.json')

chai.should()
chai.use(chaiAsPromised)

describe('Smoke test', function() {
  var urlpServer, redisServer, launchServer, stdout, stderr, exitCode = 0

  before(function() {
    return helpers.pickUnusedPort()
      .then(helpers.launchRedis)
      .then(function(redisData) {
        process.env.URL_POINTERS_REDIS_PORT = redisData.port
        redisServer = redisData.server
      })
  })

  launchServer = function() {
    return new Promise(function(resolve, reject) {
      stdout = ''
      stderr = ''

      urlpServer = spawn('node', [ scriptPath, testConfigPath ])

      urlpServer.stdout.on('data', function(data) {
        stdout += data
        if (stdout.match(packageInfo.name + ' listening on port ')) {
          setTimeout(resolve, 250)
        }
      })
      urlpServer.stderr.on('data', function(data) {
        stderr += data
        reject(new Error(stderr))
      })
      urlpServer.on('close', function(code) {
        exitCode = code
      })
      urlpServer.on('error', function(err) {
        err.message = 'failed to start ' + scriptPath + ': ' + err.message
        reject(err)
      })
    })
  }

  afterEach(function() {
    return helpers.killServer(urlpServer)
  })

  after(function() {
    return helpers.killServer(redisServer)
  })

  it('launches successfully using a well-formed config file', function() {
    return launchServer().should.be.fulfilled
      .then(function() {
        stderr.should.equal('')
        exitCode.should.equal(0)
      })
  })
})
<commit_msg>smoke-test: Call launchServer in beforeEach<commit_after>'use strict'

var spawn = require('child_process').spawn
var path = require('path')
var helpers = require('./helpers')
var chai = require('chai')
var chaiAsPromised = require('chai-as-promised')

var rootDir = path.dirname(__dirname)
var packageInfo = require(path.join(rootDir, 'package.json'))
var scriptPath = path.join(rootDir, packageInfo.main)
var testConfigPath = path.join(rootDir, 'tests', 'helpers', 'test-config.json')

chai.should()
chai.use(chaiAsPromised)

describe('Smoke test', function() {
  var urlpServer, redisServer, launchServer, stdout, stderr, exitCode = 0

  before(function() {
    return helpers.pickUnusedPort()
      .then(helpers.launchRedis)
      .then(function(redisData) {
        process.env.URL_POINTERS_REDIS_PORT = redisData.port
        redisServer = redisData.server
      })
  })

  launchServer = function() {
    return new Promise(function(resolve, reject) {
      stdout = ''
      stderr = ''

      urlpServer = spawn('node', [ scriptPath, testConfigPath ])

      urlpServer.stdout.on('data', function(data) {
        stdout += data
        if (stdout.match(packageInfo.name + ' listening on port ')) {
          setTimeout(resolve, 250)
        }
      })
      urlpServer.stderr.on('data', function(data) {
        stderr += data
        reject(new Error(stderr))
      })
      urlpServer.on('close', function(code) {
        exitCode = code
      })
      urlpServer.on('error', function(err) {
        err.message = 'failed to start ' + scriptPath + ': ' + err.message
        reject(err)
      })
    })
  }

  afterEach(function() {
    return helpers.killServer(urlpServer)
  })

  after(function() {
    return helpers.killServer(redisServer)
  })

  describe('launches successfully', function() {
    beforeEach(function() {
      return launchServer()
    })

    it('launches successfully using a well-formed config file', function() {
      stderr.should.equal('')
      exitCode.should.equal(0)
    })
  })
})
<|endoftext|>


<commit_before>export default {
  // Plugin versions are sourced from the public pub.dev API
  // See website/plugins/source-versions.js for more information on how these are sourced & injected via Webpack
  plugins: {
    firebase_analytics: PUB_FIREBASE_ANALYTICS,
    firebase_analytics_ns: PUB_NS_FIREBASE_ANALYTICS,
    firebase_app_check: PUB_FIREBASE_APP_CHECK,
    firebase_app_check_ns: PUB_NS_FIREBASE_APP_CHECK,
    firebase_auth: PUB_FIREBASE_AUTH,
    firebase_auth_ns: PUB_NS_FIREBASE_AUTH,
    cloud_firestore: PUB_CLOUD_FIRESTORE,
    cloud_firestore_ns: PUB_NS_CLOUD_FIRESTORE,
    cloud_functions: PUB_CLOUD_FUNCTIONS,
    cloud_functions_ns: PUB_NS_CLOUD_FUNCTIONS,
    firebase_messaging: PUB_FIREBASE_MESSAGING,
    firebase_messaging_ns: PUB_NS_FIREBASE_MESSAGING,
    firebase_storage: PUB_FIREBASE_STORAGE,
    firebase_storage_ns: PUB_NS_FIREBASE_STORAGE,
    firebase_core: PUB_FIREBASE_CORE,
    firebase_core_ns: PUB_NS_FIREBASE_CORE,
    firebase_crashlytics: PUB_FIREBASE_CRASHLYTICS,
    firebase_crashlytics_ns: PUB_NS_FIREBASE_CRASHLYTICS,
    firebase_database: PUB_FIREBASE_DATABASE,
    firebase_database_ns: PUB_NS_FIREBASE_DATABASE,
    firebase_dynamic_links: PUB_FIREBASE_DYNAMIC_LINKS,
    firebase_dynamic_links_ns: PUB_NS_FIREBASE_DYNAMIC_LINKS,
    firebase_in_app_messaging: PUB_FIREBASE_IN_APP_MESSAGING,
    firebase_in_app_messaging_ns: PUB_NS_FIREBASE_IN_APP_MESSAGING,
    firebase_ml_vision: PUB_FIREBASE_ML_VISION,
    firebase_performance: PUB_FIREBASE_PERFORMANCE,
    firebase_performance_ns: PUB_NS_FIREBASE_PERFORMANCE,
    firebase_remote_config: PUB_FIREBASE_REMOTE_CONFIG,
    firebase_remote_config_ns: PUB_NS_FIREBASE_REMOTE_CONFIG,
    google_sign_in: "^4.4.4",
  },
  android: {
    google_services: "4.3.8", // com.google.gms:google-services
  },
  web: {
    firebase_cdn: "8.6.1", // https://firebase.google.com/support/release-notes/js
  },
  external: {
    google_sign_in: "^4.5.1",
    flutter_facebook_auth: "^1.0.0"
  }
};
<commit_msg>docs: updated the `flutter_facebook_auth` recommended version (#6719)<commit_after>export default {
  // Plugin versions are sourced from the public pub.dev API
  // See website/plugins/source-versions.js for more information on how these are sourced & injected via Webpack
  plugins: {
    firebase_analytics: PUB_FIREBASE_ANALYTICS,
    firebase_analytics_ns: PUB_NS_FIREBASE_ANALYTICS,
    firebase_app_check: PUB_FIREBASE_APP_CHECK,
    firebase_app_check_ns: PUB_NS_FIREBASE_APP_CHECK,
    firebase_auth: PUB_FIREBASE_AUTH,
    firebase_auth_ns: PUB_NS_FIREBASE_AUTH,
    cloud_firestore: PUB_CLOUD_FIRESTORE,
    cloud_firestore_ns: PUB_NS_CLOUD_FIRESTORE,
    cloud_functions: PUB_CLOUD_FUNCTIONS,
    cloud_functions_ns: PUB_NS_CLOUD_FUNCTIONS,
    firebase_messaging: PUB_FIREBASE_MESSAGING,
    firebase_messaging_ns: PUB_NS_FIREBASE_MESSAGING,
    firebase_storage: PUB_FIREBASE_STORAGE,
    firebase_storage_ns: PUB_NS_FIREBASE_STORAGE,
    firebase_core: PUB_FIREBASE_CORE,
    firebase_core_ns: PUB_NS_FIREBASE_CORE,
    firebase_crashlytics: PUB_FIREBASE_CRASHLYTICS,
    firebase_crashlytics_ns: PUB_NS_FIREBASE_CRASHLYTICS,
    firebase_database: PUB_FIREBASE_DATABASE,
    firebase_database_ns: PUB_NS_FIREBASE_DATABASE,
    firebase_dynamic_links: PUB_FIREBASE_DYNAMIC_LINKS,
    firebase_dynamic_links_ns: PUB_NS_FIREBASE_DYNAMIC_LINKS,
    firebase_in_app_messaging: PUB_FIREBASE_IN_APP_MESSAGING,
    firebase_in_app_messaging_ns: PUB_NS_FIREBASE_IN_APP_MESSAGING,
    firebase_ml_vision: PUB_FIREBASE_ML_VISION,
    firebase_performance: PUB_FIREBASE_PERFORMANCE,
    firebase_performance_ns: PUB_NS_FIREBASE_PERFORMANCE,
    firebase_remote_config: PUB_FIREBASE_REMOTE_CONFIG,
    firebase_remote_config_ns: PUB_NS_FIREBASE_REMOTE_CONFIG,
    google_sign_in: "^4.4.4",
  },
  android: {
    google_services: "4.3.8", // com.google.gms:google-services
  },
  web: {
    firebase_cdn: "8.6.1", // https://firebase.google.com/support/release-notes/js
  },
  external: {
    google_sign_in: "^4.5.1",
    flutter_facebook_auth: "^3.5.0",
  }
};
<|endoftext|>


<commit_before><commit_msg>Updates script to build test folders into sites<commit_after><|endoftext|>


<commit_before>//==================================
//	Kyle Russell
//	github.com/denkers/GameTop100
//	nav-controller
//==================================

(function()
{
	angular.module('main').controller('notificationController', function($scope, $rootScope)
	{
		$scope.notifications		=	{};
		$scope.notificationResponse	=	{};

		$scope.toggleNotification	=	function(index)
		{
			if(index == selectedNotification)
				selectedNotification = null;
			else
				selectedNotification	=	index;
		};

		$scope.removeNotification	=	function(url)
		{
			if(selectedNotification == null) return;
			else
			{
				var notification	=	$scope.notifications[selectedNotification];
				var params			=	{ notification_id: notification.id };
				var data			=	params;
				url					=	$rootScope.setParams(url, params);

				$rootScope.postData(url, data, function(response)
				{
					$scope.notificationResponse			=	response;
					$scope.notificationResponse.show	=	true;

					if(response.status)
					{
						notifications.splice(selectedNotification, 1);
						selectedNotification	=	null;
					}
				});
			}
		};
	});
})();
<commit_msg>Fixed notification content container toggling in controllers/notification-controller<commit_after>//==================================
//	Kyle Russell
//	github.com/denkers/GameTop100
//	nav-controller
//==================================

(function()
{
	angular.module('main').controller('notificationController', function($scope, $rootScope)
	{
		$scope.notifications		=	{};
		$scope.notificationResponse	=	{};

		$scope.toggleNotification	=	function(index)
		{
			if(index == $scope.selectedNotification)
				$scope.selectedNotification = null;
			else
				$scope.selectedNotification	=	index;
		};

		$scope.removeNotification	=	function(url)
		{
			if(selectedNotification == null) return;
			else
			{
				var notification	=	$scope.notifications[selectedNotification];
				var params			=	{ notification_id: notification.id };
				var data			=	params;
				url					=	$rootScope.setParams(url, params);

				$rootScope.postData(url, data, function(response)
				{
					$scope.notificationResponse			=	response;
					$scope.notificationResponse.show	=	true;

					if(response.status)
					{
						notifications.splice(selectedNotification, 1);
						selectedNotification	=	null;
					}
				});
			}
		};
	});
})();
<|endoftext|>


<commit_before>const mongoose = require('./db'),
		Schema = mongoose.Schema;

/**
 * 索引和默认值
 */

/**
 * User Info
 */

let UserSchema = new Schema({
	username: {type: String, index: true},
	password: {type: String},
	age: {type: String},
	loginDate: {type: Date, default: Date.now}
});

module.exports = mongoose.model("User", UserSchema);

/**
 * LBS 地址位置
 * lbs : {type: Array, index: "2d", spaese: true}
 */

/**
 * 去重
 * Model.distinct(field, [conditions], [callback])
 */

/**
 * 特殊运算符
 *
 *  $or　　　　		或关系
 *	$nor　　　 		或关系取反
 * 	$gt　　　　		大于
 *  $gte　　　 		大于等于
 *  $lt　　　　 	小于
 *  $lte　　　  	小于等于
 *  $ne            	不等于
 *  $in             在多个值范围内
 *  $nin           	不在多个值范围内
 *  $all            匹配数组中多个值
 *  $regex　　		正则，用于模糊查询
 *  $size　　　		匹配数组大小
 *  $maxDistance　　范围查询，距离（基于LBS）
 *  $mod　　   		取模运算
 *  $near　　　		邻域查询，查询附近的位置（基于LBS）
 *  $exists　　  	字段是否存在
 *  $elemMatch　　	匹配内数组内的元素
 *  $within　　		范围查询（基于LBS）
 *  $box　　　 		范围查询，矩形范围（基于LBS）
 *  $center       	范围查询，圆形范围（基于LBS）
 *  $centerSphere　	范围查询，球形范围（基于LBS）
 *  $slice　　　　	查询字段集合中的元素（比如从第几个之后，第N到第M个元素）
 */<commit_msg>[fix]<commit_after>const mongoose = require('./db'),
		Schema = mongoose.Schema;

/**
 * 索引和默认值
 */

/**
 * User Info
 */

let UserSchema = new Schema({
	username: {type: String, index: true},
	password: {type: String},
	age: {type: String},
	loginDate: {type: Date, default: Date.now}
});

module.exports = mongoose.model("User", UserSchema);

/**
 * LBS 地址位置
 * lbs : {type: Array, index: "2d", spaese: true}
 */

/**
 * 去重
 * Model.distinct(field, [conditions], [callback])
 */

/**
 * 特殊运算符
 *
 *  $or　　　　		或关系
 *	$nor　　　 		或关系取反
 * 	$gt　　　　		大于
 *  $gte　　　 		大于等于
 *  $lt　　　　 	小于
 *  $lte　　　  	小于等于
 *  $ne            	不等于
 *  $in             在多个值范围内
 *  $nin           	不在多个值范围内
 *  $all            匹配数组中多个值
 *  $regex　　		正则，用于模糊查询
 *  $size　　　		匹配数组大小
 *  $maxDistance　　范围查询，距离（基于LBS）
 *  $mod　　   		取模运算
 *  $near　　　		邻域查询，查询附近的位置（基于LBS）
 *  $exists　　  	字段是否存在
 *  $elemMatch　　	匹配内数组内的元素
 *  $within　　		范围查询（基于LBS）
 *  $box　　　 		范围查询，矩形范围（基于LBS）
 *  $center       	范围查询，圆形范围（基于LBS）
 *  $centerSphere　	范围查询，球形范围（基于LBS）
 *  $slice　　　　	查询字段集合中的元素（比如从第几个之后，第N到第M个元素）
 */
<|endoftext|>


<commit_before>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Albertina Durante
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4,
maxerr: 50 */
/*global exports, module, require, define, tern */

(function (mod) {
    if (typeof exports === "object" && typeof module === "object") { // CommonJS
        return mod(require("../tern/lib/infer"), require("../tern/lib/tern"), require("../tern/plugin/modules"), require);
    }
    if (typeof define === "function" && define.amd) { // AMD
        return define(["../tern/lib/infer", "../tern/lib/tern", "../tern/plugin/modules"]);
    }
    mod(tern, tern);
})(function (infer, tern) {
    "use strict";

    function preCondenseReach(state) {
        if (!state.roots["!modules"]) {
            return;
        }

        // patchModules
        var server = infer.cx().parent,
            modModules = server.mod.modules.modules,
            mods = server.mod.cordovaPluginDef.modulesDef,
            node = state.roots["!modules"], // infer.Obj
            props = node.props,
            currProp,
            modDef,
            mod,
            prop,
            path;

        for (path in props) {
            currProp = props[path];
            modDef = mods[currProp.origin];
            mod = modModules[currProp.origin];

            if (modDef) {
                prop = node.defProp(modDef.name);
                mod.origin = modDef.name;
                mod.propagate(prop);
                prop.origin = mod.origin;
            }

            delete props[path];
        }
    }

    function postCondense(state) {
        if (!state.output["!define"] || !state.output["!define"]["!modules"]) {
            return;
        }

        var output = state.output,
            modulesOutput = state.output["!define"]["!modules"],
            cordovaPluginDef = infer.cx().parent.mod.cordovaPluginDef,
            name,
            moduleDef,
            outputPoint,
            namespace;

        for (name in modulesOutput) {
            moduleDef = cordovaPluginDef.getModuleDefByName(name);

            if (moduleDef) {
                outputPoint = "+!modules." + name;
                namespace = moduleDef.getNamespace();

                var count = namespace.length,
                    lastIndex = count - 1,
                    lastNamespace = output,
                    part,
                    i;

                for (i = 0; i < count; i++) {
                    part = namespace[i];

                    if (!lastNamespace[part]) {
                        lastNamespace[part] = (i === lastIndex) ? outputPoint : {};
                    }

                    lastNamespace = lastNamespace[part];
                }
            }
        }
    }

    tern.registerPlugin("cordova-plugin-modules", function (server, options) {
        server.loadPlugin("modules");

        server.on("preCondenseReach", preCondenseReach);
        server.on("postCondense", postCondense);
    });
});
<commit_msg>Fixing references to !modules definitions.<commit_after>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Albertina Durante
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4,
maxerr: 50 */
/*global exports, module, require, define, tern */

(function (mod) {
    if (typeof exports === "object" && typeof module === "object") { // CommonJS
        return mod(require("../tern/lib/infer"), require("../tern/lib/tern"), require("../tern/plugin/modules"), require);
    }
    if (typeof define === "function" && define.amd) { // AMD
        return define(["../tern/lib/infer", "../tern/lib/tern", "../tern/plugin/modules"]);
    }
    mod(tern, tern);
})(function (infer, tern) {
    "use strict";

    function preCondenseReach(state) {
        if (!state.roots["!modules"]) {
            return;
        }

        // patchModules
        var server = infer.cx().parent,
            modModules = server.mod.modules.modules,
            mods = server.mod.cordovaPluginDef.modulesDef,
            node = state.roots["!modules"], // infer.Obj
            props = node.props,
            currProp,
            modDef,
            mod,
            prop,
            path;

        for (path in props) {
            currProp = props[path];
            modDef = mods[currProp.origin];
            mod = modModules[currProp.origin];

            if (modDef) {
                prop = node.defProp(modDef.name);
                mod.origin = modDef.name;
                mod.propagate(prop);
                prop.origin = mod.origin;
            }

            delete props[path];
        }
    }

    function postCondense(state) {
        if (!state.output["!define"] || !state.output["!define"]["!modules"]) {
            return;
        }

        var output = state.output,
            modulesOutput = state.output["!define"]["!modules"],
            cordovaPluginDef = infer.cx().parent.mod.cordovaPluginDef,
            name,
            moduleDef,
            outputPoint,
            namespace;

        for (name in modulesOutput) {
            moduleDef = cordovaPluginDef.getModuleDefByName(name);

            if (moduleDef) {
                outputPoint = "!modules." + name;
                namespace = moduleDef.getNamespace();

                var count = namespace.length,
                    lastIndex = count - 1,
                    lastNamespace = output,
                    part,
                    i;

                for (i = 0; i < count; i++) {
                    part = namespace[i];

                    if (!lastNamespace[part]) {
                        lastNamespace[part] = (i === lastIndex) ? outputPoint : {};
                    }

                    lastNamespace = lastNamespace[part];
                }
            }
        }
    }

    tern.registerPlugin("cordova-plugin-modules", function (server, options) {
        server.loadPlugin("modules");

        server.on("preCondenseReach", preCondenseReach);
        server.on("postCondense", postCondense);
    });
});
<|endoftext|>


<commit_before>define([
    'angular'
], function(angular) {
    'use strict';

    angular.module('superdesk.services', []);
});<commit_msg>Remove obsolete file<commit_after><|endoftext|>