<commit_before>function OAuthServiceGoogle(options) {
    var parent = OAuthServiceGoogle.prototype;

	var _private = {
		debug: false,
		scope: []
	};

    this.signature_method = 'HMAC-SHA1';

    this.realm = 'https://www.google.com/accounts/';
    this.requestTokenUrl = this.realm + 'OAuthGetRequestToken';
    this.authorizationUrl = this.realm + 'OAuthAuthorizeToken';
    this.accessTokenUrl = this.realm + 'OAuthGetAccessToken';
    this.authenticationUrl = null;

    this.init = function(options) {
		_private.debug = 'debug' in options ? options.debug : _private.debug;
        parent.init.apply(this, arguments);
    };

	this.setScope = function (scope_arr) {
		scope = scope_arr;
	};

	this.getScope = function () {
		return scope.join(' ');
	};

    this.getAuthorizationHeaderParameters = function () {
        var params = parent.getAuthorizationHeaderParameters.apply(this);
		params.scope = this.getScope();

        return params;
    };

	this.getRequestParameters = function () {
		return {'scope': this.getScope()}
	};

    this.getQueryParams = function () {
        return 'scope=' + OAuthUtilities.urlEncode(this.getScope());
    }

    this.getContacts = function () {
        if (_private.debug) {
            netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead UniversalBrowserWrite");
        }

		var header_params = this.getAuthorizationHeaderParameters();

        var request = new OAuthRequest({
            method: 'GET',
			url: 'https://www.google.com/m8/feeds/contacts/default/full',
			query: {'alt':'json'},
			authorization_header_params: header_params
        });

        var signature = new OAuthConsumer.signatureMethods[this.signature_method]().sign(
            request, this.getConsumerToken().secret, this.getAccessToken().secret
        );

		request.setAuthorizationHeaderParam('oauth_signature', signature);

		var header_string = 'OAuth ' + request.toHeaderString();

        var xhr = new XMLHttpRequest();
        xhr.open(request.getMethod(), request.getUrl(), false);
        xhr.setRequestHeader('Authorization', header_string);
        xhr.send(request.toQueryString());
        if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 304)) {
            document.write(xhr.responseText);
        }
    };

    if (arguments.length > 0) {
        this.init(options);
    }
}

OAuthServiceGoogle.prototype = new OAuthService();
<commit_msg>GET request should send null, need to abstract this out NS.XHR has code for this<commit_after>function OAuthServiceGoogle(options) {
    var parent = OAuthServiceGoogle.prototype;

	var _private = {
		debug: false,
		scope: []
	};

    this.signature_method = 'HMAC-SHA1';

    this.realm = 'https://www.google.com/accounts/';
    this.requestTokenUrl = this.realm + 'OAuthGetRequestToken';
    this.authorizationUrl = this.realm + 'OAuthAuthorizeToken';
    this.accessTokenUrl = this.realm + 'OAuthGetAccessToken';
    this.authenticationUrl = null;

    this.init = function(options) {
		_private.debug = 'debug' in options ? options.debug : _private.debug;
        parent.init.apply(this, arguments);
    };

	this.setScope = function (scope_arr) {
		scope = scope_arr;
	};

	this.getScope = function () {
		return scope.join(' ');
	};

    this.getAuthorizationHeaderParameters = function () {
        var params = parent.getAuthorizationHeaderParameters.apply(this);
		params.scope = this.getScope();

        return params;
    };

	this.getRequestParameters = function () {
		return {'scope': this.getScope()}
	};

    this.getQueryParams = function () {
        return 'scope=' + OAuthUtilities.urlEncode(this.getScope());
    }

    this.getContacts = function () {
        if (_private.debug) {
            netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead UniversalBrowserWrite");
        }

		var header_params = this.getAuthorizationHeaderParameters();

        var request = new OAuthRequest({
            method: 'GET',
			url: 'https://www.google.com/m8/feeds/contacts/default/full',
			query: {},
			authorization_header_params: header_params
        });

        var signature = new OAuthConsumer.signatureMethods[this.signature_method]().sign(
            request, this.getConsumerToken().secret, this.getAccessToken().secret
        );

		request.setAuthorizationHeaderParam('oauth_signature', signature);

		var header_string = 'OAuth ' + request.toHeaderString();

        var xhr = new XMLHttpRequest();
        xhr.open(request.getMethod(), request.getUrl(), false);
        xhr.setRequestHeader('Authorization', header_string);
        xhr.send(null);
        if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 304)) {
            document.write(xhr.responseXML);
        }
    };

    if (arguments.length > 0) {
        this.init(options);
    }
}

OAuthServiceGoogle.prototype = new OAuthService();
<|endoftext|>


<commit_before>import React, { PureComponent } from "react";
import moment from "moment";
import debounce from "lodash.debounce";
import classNames from "classnames";

import FirebaseProvider from "./FirebaseProvider";

export default class Day extends PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      focused: false,
    };
  }

  onFocus = () => {
    this.setState({ focused: true });
    this.props.onFocus();
  };

  onBlur = () => {
    this.setState({ focused: false });
    this.props.onBlur();
  };

  render() {
    const isToday = this.props.day.isSame(moment().startOf("day"));
    const isWeekend = !this.props.someday &&
      (this.props.day.day() === 0 || this.props.day.day() === 6);
    const isFocused = this.state.focused ||
      (!this.props.aDayIsFocused && isToday);

    const dayNumber = this.props.day.format("DD");
    const weekday = this.props.day.format("dddd");

    // Additional entries
    let additionalTexts;

    if (this.props.textCount > 1) {
      let pluralConflictingEntries = `is a conflicting entry`;
      let next;

      if (this.props.textCount > 2) {
        pluralConflictingEntries = `are ${this.props.textCount} conflicting entries`;
        next = "next ";
      }

      additionalTexts = (

          Problem: there
          {" "}
          {pluralConflictingEntries}
          {" "}
          for this day. If you remove this ↑ entry, the
          {" "}
          {next}
          conflicting entry should appear and you can decide what to do with it. This sometimes happens with an unstable connection. Sorry for the hassle. :(

      );
    }

    // Date label
    let label, dayLabel, monthLabel;

    if (!this.props.someday) {
      dayLabel = this.props.day.format("ddd DD");
      const todayLabel = isToday ? ", Today" : false;

      if (
        this.props.day.isSame(moment(this.props.day).startOf("isoweek")) ||
        this.props.day.isSame(moment(this.props.day).startOf("month"))
      ) {
        monthLabel = `, ${this.props.day.format("MMM YYYY")}`;
      }

      label = (

          {dayLabel}{monthLabel}{todayLabel}

      );
    }

    return (

          <time className="dateStamp">
            {this.props.day.format(
              this.props.isList ? "D" : isFocused ? "DD ddd" : "DD"
            )}
          </time>
          {isToday && isFocused && ", today"}

          <FirebaseProvider
            uid={this.props.uid}
            day={this.props.day}
            focused={this.state.focused}
            onFocus={this.onFocus}
            onBlur={this.onBlur}
            placeholder={
              isFocused && !this.props.isList ? "This day" : undefined
            }
          />

          {!this.props.isList &&
            <FirebaseProvider
              uid={this.props.uid}
              day={weekday}
              focused={this.state.focused}
              onFocus={this.onFocus}
              onBlur={this.onBlur}
              placeholder={
                isFocused ? "Every " + this.props.day.format("dddd") : undefined
              }
              autoSize
            />}

          {!this.props.isList &&
            dayNumber < 29 &&
            <FirebaseProvider
              uid={this.props.uid}
              day={dayNumber}
              focused={this.state.focused}
              onFocus={this.onFocus}
              onBlur={this.onBlur}
              placeholder={
                isFocused ? "Every " + this.props.day.format("Do") : undefined
              }
              autoSize
            />}

    );
  }
}
<commit_msg>Removes today coloring<commit_after>import React, { PureComponent } from "react";
import moment from "moment";
import debounce from "lodash.debounce";
import classNames from "classnames";

import FirebaseProvider from "./FirebaseProvider";

export default class Day extends PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      focused: false,
    };
  }

  onFocus = () => {
    this.setState({ focused: true });
    this.props.onFocus();
  };

  onBlur = () => {
    this.setState({ focused: false });
    this.props.onBlur();
  };

  render() {
    const isToday = this.props.day.isSame(moment().startOf("day"));
    const isWeekend = !this.props.someday &&
      (this.props.day.day() === 0 || this.props.day.day() === 6);
    const isFocused = this.state.focused ||
      (!this.props.aDayIsFocused && isToday);

    const dayNumber = this.props.day.format("DD");
    const weekday = this.props.day.format("dddd");

    // Additional entries
    let additionalTexts;

    if (this.props.textCount > 1) {
      let pluralConflictingEntries = `is a conflicting entry`;
      let next;

      if (this.props.textCount > 2) {
        pluralConflictingEntries = `are ${this.props.textCount} conflicting entries`;
        next = "next ";
      }

      additionalTexts = (

          Problem: there
          {" "}
          {pluralConflictingEntries}
          {" "}
          for this day. If you remove this ↑ entry, the
          {" "}
          {next}
          conflicting entry should appear and you can decide what to do with it. This sometimes happens with an unstable connection. Sorry for the hassle. :(

      );
    }

    // Date label
    let label, dayLabel, monthLabel;

    if (!this.props.someday) {
      dayLabel = this.props.day.format("ddd DD");
      const todayLabel = isToday ? ", Today" : false;

      if (
        this.props.day.isSame(moment(this.props.day).startOf("isoweek")) ||
        this.props.day.isSame(moment(this.props.day).startOf("month"))
      ) {
        monthLabel = `, ${this.props.day.format("MMM YYYY")}`;
      }

      label = (

          {dayLabel}{monthLabel}{todayLabel}

      );
    }

    return (

          <time className="dateStamp">
            {this.props.day.format(
              this.props.isList ? "D" : isFocused ? "DD ddd" : "DD"
            )}
          </time>
          {isToday && isFocused && ", today"}

          <FirebaseProvider
            uid={this.props.uid}
            day={this.props.day}
            focused={this.state.focused}
            onFocus={this.onFocus}
            onBlur={this.onBlur}
            placeholder={
              isFocused && !this.props.isList ? "This day" : undefined
            }
          />

          {!this.props.isList &&
            <FirebaseProvider
              uid={this.props.uid}
              day={weekday}
              focused={this.state.focused}
              onFocus={this.onFocus}
              onBlur={this.onBlur}
              placeholder={
                isFocused ? "Every " + this.props.day.format("dddd") : undefined
              }
              autoSize
            />}

          {!this.props.isList &&
            dayNumber < 29 &&
            <FirebaseProvider
              uid={this.props.uid}
              day={dayNumber}
              focused={this.state.focused}
              onFocus={this.onFocus}
              onBlur={this.onBlur}
              placeholder={
                isFocused ? "Every " + this.props.day.format("Do") : undefined
              }
              autoSize
            />}

    );
  }
}
<|endoftext|>


<commit_before>var loader = require('auto-loader');
var bases = require('./base.js');

/**
 * Instantiates Providers.
 * @class Represents an instance of Providers. Only one needed.
 */

function Providers() {
	var self = this;

	self.media = {
		getProvider : function(prov_id) {
			for(p in this.__list) {
				if (this.__list[p].id == prov_id) {
					return this.__list[p];
				}
			}
			return null;
		},
		search : function(string) {
			var results = {};

			for(p in this.__list) {
				provider = this.__list[p];
				if(provider.ready) {
					results[provider.id] = provider.search(string);
				}
			}

			return results;
		},
		__list : [],
	};

	var	metadata = {
		setMetadata : function(media) {
		},
		__list : [],
	};

	self.init = function(mediaModule) {
		var modules = loader.load(__dirname);
		console.log("Modules loaded",  modules);

		for (var module in modules) {
			if(module == 'base' || module == 'providers' || module == '_path') {
				delete modules[module];
				continue;
			}
			var provider = new modules[module](bases, mediaModule);
			console.log(module, provider);

			if(provider instanceof bases.MediaProvider) {
				providers.media.__list.push(provider);
			}

			if(provider instanceof bases.MetadataProvider) {
				providers.metadata.__list.push(provider);
			}
		}

		console.log("Providers", providers);

	};

}

var providers = new Providers();
module.exports = providers;
<commit_msg>Small fix<commit_after>var loader = require('auto-loader');
var bases = require('./base.js');

/**
 * Instantiates Providers.
 * @class Represents an instance of Providers. Only one needed.
 */

function Providers() {
	var self = this;

	self.media = {
		getProvider : function(prov_id) {
			for(p in this.__list) {
				if (this.__list[p].id == prov_id) {
					return this.__list[p];
				}
			}
			return null;
		},
		search : function(string) {
			var results = {};

			for(p in this.__list) {
				provider = this.__list[p];
				if(provider.ready) {
					results[provider.id] = provider.search(string);
				}
			}

			return results;
		},
		__list : [],
	};

	self.metadata = {
		setMetadata : function(media) {
		},
		__list : [],
	};

	self.init = function(mediaModule) {
		var modules = loader.load(__dirname);
		console.log("Modules loaded",  modules);

		for (var module in modules) {
			if(module == 'base' || module == 'providers' || module == '_path') {
				delete modules[module];
				continue;
			}
			var provider = new modules[module](bases, mediaModule);
			console.log(module, provider);

			if(provider instanceof bases.MediaProvider) {
				providers.media.__list.push(provider);
			}

			if(provider instanceof bases.MetadataProvider) {
				providers.metadata.__list.push(provider);
			}
		}

		console.log("Providers", providers);

	};

}

var providers = new Providers();
module.exports = providers;
<|endoftext|>


<commit_before>// View for /gerrit/tags.
//
// Manages a set of TagsWordCloud subviews, one per word cloud.
Twigg.Views.Tags = Backbone.View.extend({
  initialize: function() {
    this.$globalUsed = $('#global-used');
    this.width = this.$globalUsed.width();
    this.fetch();
  },

  fetch: function() {
    $.getJSON(window.location.href)
      .fail(function() { this.$globalUsed.displayAlert(); }.bind(this))
      .done(function(data) {
        this.$globalUsed.empty();
        this.data = data;
        this.render();
      }.bind(this));
  },

  render: function() {
    // first render global stats
    new Twigg.Views.TagsWordCloud({
      el:    this.$globalUsed[0],
      data:  this.data.global,
      width: this.width
    });

    // then render per-author stats
    var authors = JSON.parse(_.unescape(this.$el.data('authors')));
    _.each(authors, function(author, idx, list) {
      var id = this.nameToId(author);

      // tags used
      new Twigg.Views.TagsWordCloud({
        el:    this.$('#' + id + '-used')[0],
        data:  this.data.from[author],
        width: this.width
      });

      // tags received
      new Twigg.Views.TagsWordCloud({
        el:    this.$('#' + id + '-received')[0],
        data:  this.data.to[author],
        width: this.width
      });
    }, this);

    return this;
  },

  // Duplicative of `#name_to_id` Ruby method in Twigg::App::Server.
  nameToId: function(name) {
    return name.replace(/[ .@]/, '-').toLowerCase();
  }
});
<commit_msg>Fix tag word cloud display for Kim<commit_after>// View for /gerrit/tags.
//
// Manages a set of TagsWordCloud subviews, one per word cloud.
Twigg.Views.Tags = Backbone.View.extend({
  initialize: function() {
    this.$globalUsed = $('#global-used');
    this.width = this.$globalUsed.width();
    this.fetch();
  },

  fetch: function() {
    $.getJSON(window.location.href)
      .fail(function() { this.$globalUsed.displayAlert(); }.bind(this))
      .done(function(data) {
        this.$globalUsed.empty();
        this.data = data;
        this.render();
      }.bind(this));
  },

  render: function() {
    // first render global stats
    new Twigg.Views.TagsWordCloud({
      el:    this.$globalUsed[0],
      data:  this.data.global,
      width: this.width
    });

    // then render per-author stats
    var authors = JSON.parse(_.unescape(this.$el.data('authors')));
    _.each(authors, function(author, idx, list) {
      var id = this.nameToId(author);

      // tags used
      new Twigg.Views.TagsWordCloud({
        el:    this.$('#' + id + '-used')[0],
        data:  this.data.from[author],
        width: this.width
      });

      // tags received
      new Twigg.Views.TagsWordCloud({
        el:    this.$('#' + id + '-received')[0],
        data:  this.data.to[author],
        width: this.width
      });
    }, this);

    return this;
  },

  // Duplicative of `#name_to_id` Ruby method in Twigg::App::Server.
  nameToId: function(name) {
    return name.replace(/[ .@]/g, '-').toLowerCase();
  }
});
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you 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.
 */

/**
 * @fileoverview This library provides functions for navigating to and dealing
 *     with views of the current gadget.
 */

var gadgets = gadgets || {};

/**
 * Implements the gadgets.views API spec. See
 * http://code.google.com/apis/gadgets/docs/reference/gadgets.views.html
 */
gadgets.views = function() {

  /**
   * Reference to the current view object.
   */
  var currentView = null;

  /**
   * Map of all supported views for this container.
   */
  var supportedViews = {};

  /**
   * Map of parameters passed to the current request.
   */
  var params = {};

  /**
   * Initializes views. Assumes that the current view is the "view"
   * url parameter (or default if "view" isn't supported), and that
   * all view parameters are in the form view-<name>
   * TODO: Use unified configuration when it becomes available.
   *
   */
  function init(config) {
    var supported = config["views"];

    for (var s in supported) if (supported.hasOwnProperty(s)) {
      var obj = supported[s];
      supportedViews[s] = new gadgets.views.View(s, obj.isOnlyVisible);
      var aliases = obj.aliases || [];
      for (var i = 0, alias; alias = aliases[i]; ++i) {
        supportedViews[alias] = new gadgets.views.View(s, obj.isOnlyVisible);
      }
    }

    var urlParams = gadgets.util.getUrlParameters();
    // View parameters are passed as a single parameter.
    if (urlParams["view-params"]) {
      var tmpParams = gadgets.json.parse(
          decodeURIComponent(urlParams["view-params"]));
      if (tmpParams) {
        params = tmpParams;
        for (var p in params) if (params.hasOwnProperty(p)) {
          params[p] = gadgets.util.escapeString(params[p]);
        }
      }
    }
    currentView = supportedViews[urlParams.view] || supportedViews["default"];
  }

  gadgets.config.register("views", null, init);

  return {
    /**
     * Attempts to navigate to this gadget in a different view. If the container
     * supports parameters will pass the optional parameters along to the gadget
     * in the new view.
     *
     * @param {gadgets.views.View} view The view to navigate to
     * @param {Map.<String, String>} opt_params Parameters to pass to the
     *     gadget after it has been navigated to on the surface
     */
    requestNavigateTo : function(view, opt_params) {
      gadgets.rpc.call(
          null, "requestNavigateTo", null, view.getName(), opt_params);
    },

    /**
     * Returns the current view.
     *
     * @return {gadgets.views.View} The current view
     */
    getCurrentView : function() {
      return currentView;
    },

    /**
     * Returns a map of all the supported views. Keys each gadgets.view.View by
     * its name.
     *
     * @return {Map<gadgets.views.ViewType | String, gadgets.views.View>}
     *   All supported views, keyed by their name attribute.
     */
    getSupportedViews : function() {
      return supportedViews;
    },

    /**
     * Returns the parameters passed into this gadget for this view. Does not
     * include all url parameters, only the ones passed into
     * gadgets.views.requestNavigateTo
     *
     * @return {Map.<String, String>} The parameter map
     */
    getParams : function() {
      return params;
    }
  };
}();

gadgets.views.View = function(name, opt_isOnlyVisible) {
  this.name_ = name;
  this.isOnlyVisible_ = !!opt_isOnlyVisible;
};

/**
 * @return {String} The view name.
 */
gadgets.views.View.prototype.getName = function() {
  return this.name_;
};

/**
 * @return {Boolean} True if this is the only visible gadget on the page.
 */
gadgets.views.View.prototype.isOnlyVisibleGadget = function() {
  return this.isOnlyVisible_;
};

gadgets.views.ViewType = gadgets.util.makeEnum([
  "FULL_PAGE", "DASHBOARD", "POPUP"
]);<commit_msg>Added a sanity check to views.js.<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you 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.
 */

/**
 * @fileoverview This library provides functions for navigating to and dealing
 *     with views of the current gadget.
 */

var gadgets = gadgets || {};

/**
 * Implements the gadgets.views API spec. See
 * http://code.google.com/apis/gadgets/docs/reference/gadgets.views.html
 */
gadgets.views = function() {

  /**
   * Reference to the current view object.
   */
  var currentView = null;

  /**
   * Map of all supported views for this container.
   */
  var supportedViews = {};

  /**
   * Map of parameters passed to the current request.
   */
  var params = {};

  /**
   * Initializes views. Assumes that the current view is the "view"
   * url parameter (or default if "view" isn't supported), and that
   * all view parameters are in the form view-<name>
   * TODO: Use unified configuration when it becomes available.
   *
   */
  function init(config) {
    var supported = config["views"];

    for (var s in supported) if (supported.hasOwnProperty(s)) {
      var obj = supported[s];
      if (!obj) {
        continue;
      }
      supportedViews[s] = new gadgets.views.View(s, obj.isOnlyVisible);
      var aliases = obj.aliases || [];
      for (var i = 0, alias; alias = aliases[i]; ++i) {
        supportedViews[alias] = new gadgets.views.View(s, obj.isOnlyVisible);
      }
    }

    var urlParams = gadgets.util.getUrlParameters();
    // View parameters are passed as a single parameter.
    if (urlParams["view-params"]) {
      var tmpParams = gadgets.json.parse(
          decodeURIComponent(urlParams["view-params"]));
      if (tmpParams) {
        params = tmpParams;
        for (var p in params) if (params.hasOwnProperty(p)) {
          params[p] = gadgets.util.escapeString(params[p]);
        }
      }
    }
    currentView = supportedViews[urlParams.view] || supportedViews["default"];
  }

  gadgets.config.register("views", null, init);

  return {
    /**
     * Attempts to navigate to this gadget in a different view. If the container
     * supports parameters will pass the optional parameters along to the gadget
     * in the new view.
     *
     * @param {gadgets.views.View} view The view to navigate to
     * @param {Map.<String, String>} opt_params Parameters to pass to the
     *     gadget after it has been navigated to on the surface
     */
    requestNavigateTo : function(view, opt_params) {
      gadgets.rpc.call(
          null, "requestNavigateTo", null, view.getName(), opt_params);
    },

    /**
     * Returns the current view.
     *
     * @return {gadgets.views.View} The current view
     */
    getCurrentView : function() {
      return currentView;
    },

    /**
     * Returns a map of all the supported views. Keys each gadgets.view.View by
     * its name.
     *
     * @return {Map<gadgets.views.ViewType | String, gadgets.views.View>}
     *   All supported views, keyed by their name attribute.
     */
    getSupportedViews : function() {
      return supportedViews;
    },

    /**
     * Returns the parameters passed into this gadget for this view. Does not
     * include all url parameters, only the ones passed into
     * gadgets.views.requestNavigateTo
     *
     * @return {Map.<String, String>} The parameter map
     */
    getParams : function() {
      return params;
    }
  };
}();

gadgets.views.View = function(name, opt_isOnlyVisible) {
  this.name_ = name;
  this.isOnlyVisible_ = !!opt_isOnlyVisible;
};

/**
 * @return {String} The view name.
 */
gadgets.views.View.prototype.getName = function() {
  return this.name_;
};

/**
 * @return {Boolean} True if this is the only visible gadget on the page.
 */
gadgets.views.View.prototype.isOnlyVisibleGadget = function() {
  return this.isOnlyVisible_;
};

gadgets.views.ViewType = gadgets.util.makeEnum([
  "FULL_PAGE", "DASHBOARD", "POPUP"
]);
<|endoftext|>


<commit_before>var gitHelper = require('../index.js'),
    path = require('path');

function generateRandomStr(len) {
    len = isNaN(len) ? 5 : len;
    var str = '',
        base = '012345679ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    for (var i = 0; i < len; i++) {
        str += base.charAt(Math.floor(Math.random() * base.length));
    }
    return str;
}

var tests = {

    setUp: function(callback) {
        this.branch = 'testBranch';
        callback();
    },

    tearDown: function(callback) {
        gitHelper.removeBranch(this.branch, '.', callback);
    },

    testFindGitDir: function(test) {
        var cwd = process.env.PWD;
        gitHelper.gitPath('.', function(err, dir) {
            test.ifError(err, 'caught error when finding git');
            test.equal(cwd, dir, 'did not find git dir at current dir (' + cwd + ' vs. ' + dir + ')');
            gitHelper.gitPath('tests', function(err, dir) {
                test.ifError(err, 'caught error when finding git');
                test.equal(cwd, dir, 'did not find git dir at current dir (' + cwd + ' vs. ' + dir + ')');
                test.done();
            });
        });
    },

    testFindGitDirNotExistent: function(test) {
        var cwd = process.env.PWD;
        gitHelper.gitPath('foobar', function(err, dir) {
            test.ok(err instanceof Error, 'did not get an error when finding git in non-existent directory');
            test.equal('NOTADIR', err.code, 'non-existent directory did not report back "NOTADIR" code');
            test.done();
        });
    },

    testFileTypeIsFile: function(test) {
        var self = this;
        gitHelper.fileType(this.branch, '.', 'package.json', function(err, isDir) {
            test.ifError(err, 'caught error when checking "' + self.branch + '" for package.json');
            test.ok(!isDir, 'package.json in "' + self.branch + '" should not be a directory');
            test.done();
        });
    },

    testFileTypeIsDir: function(test) {
        var self = this;
        gitHelper.fileType(this.branch, '.', 'tests', function(err, isDir) {
            test.ifError(err, 'caught error when checking "' + self.branch + '" for tests');
            test.ok(isDir, 'tests in "' + self.branch + '" should be a directory');
            test.done();
        });
    },

    testFileTypeOfNonGit: function(test) {
        var self = this;
        gitHelper.fileType(this.branch, '/tmp/', 'foobar', function(err, isDir) {
            test.ok(err instanceof Error, 'did not get an error when checking "' + self.branch + '" in non-git directory');
            test.equal('NONGIT', err.code, '/tmp repository did not report back "NONGIT" code');
            test.done();
        });
    },

    testFileTypeNotExists: function(test) {
        var self = this;
        gitHelper.fileType(this.branch, '.', 'not.exists', function(err, isDir) {
            test.ok(err instanceof Error, 'did not get an error when checking "' + self.branch + '" for non existing file (non.exists)');
            test.done();
        });
    },

    testReadDir: function(test) {
        var self = this;
        gitHelper.readDir(this.branch, '.', '', function(err, tree) {
            test.ifError(err, 'caught error when reading root directory of "' + self.branch + '"');
            var entries = Object.getOwnPropertyNames(tree);
            test.ok(entries.indexOf('package.json') > -1, 'package.json could not be found in root directory of "' + self.branch + '"');
            test.equal(tree['package.json'].objectType, 'blob', 'package.json was not of type "blob" in "' + self.branch + '"');
            test.ok(entries.indexOf('tests') > -1, 'tests could not be found in root directory of "' + self.branch + '"');
            test.equal(tree['tests'].objectType, 'tree', 'tests was not of type "tree" in "' + self.branch + '"');
            test.done();
        });
    },

    testFileCreationAndDeletion: function(test) {
        var self = this,
            randomString = generateRandomStr(10),
            textBuffer = new Buffer('I am ' + randomString),
            fileName = 'tests/' + randomString + '.txt';

        gitHelper.readFile(self.branch, '.', fileName, function(err) {
            test.ok(err instanceof Error, 'did not get an error when checking "' + self.branch + '" for ' + fileName);
            gitHelper.writeFile(self.branch, '.', fileName, textBuffer, 'utf-8', function(err) {
                test.ifError(err, 'caught error when writing ' + fileName + ' to "' + self.branch + '"');
                gitHelper.readFile(/* should still not exist on */ 'master', '.', fileName, function(err) {
                    test.ok(err instanceof Error, 'did not get an error when checking "master" for ' + fileName);
                    gitHelper.readFile(/* should exist on */ self.branch, '.', fileName, function(err, buffer) {
                        test.ifError(err, 'caught error when checking "' + self.branch + '" for ' + fileName);
                        test.equal(buffer.toString(), textBuffer.toString(), 'content was not inserted write');
                        gitHelper.unlink(self.branch, '.', fileName, function(err) {
                            test.ifError(err, 'caught error when deleting ' + fileName + ' from "' + self.branch + '"');
                            gitHelper.readFile(self.branch, '.', fileName, function(err) {
                                test.ok(err instanceof Error, 'did not get an error when checking "' + self.branch + '" for ' + fileName + ' after delete');
                                test.done();
                            });
                        });
                    });
                });
            });
        });
    },

    testDirCreationAndDeletion: function(test) {
        var self = this,
            randomString = generateRandomStr(10);
        // TODO: read tree and make sure the dir does not exist
        gitHelper.mkDir(this.branch, '.', 'tests/dir_' + randomString, function(err) {
            test.ifError(err, 'caught error when creating tests/dir_' + randomString + ' in "' + self.branch + '"');
            // TODO: read tree from master and make sure it was not changed
            gitHelper.unlink(self.branch, '.', 'tests/dir_' + randomString, function(err) {
                test.ifError(err, 'caught error when deleting tests/dir_' + randomString + ' from "' + self.branch + '"');
                // TODO: read tree and make sure the dir does not exist anymore
                test.done();
            });
        });
    },

    testIsIgnored: function(test) {
        gitHelper.isIgnored('.', 'node_modules', function(err, ignored) {
            test.ifError(err, 'caught error when checking (working copy) whether node_modules is ignored');
            test.ok(ignored, 'node_modules should be ignored (in the currenty working copy)');

            gitHelper.isIgnored('.', 'package.json', function(err, ignored) {
                test.ifError(err, 'caught error when checking (working copy) whether package.json is ignored');
                test.ok(!ignored, 'package.json should not be ignored (in the currenty working copy)');
                test.done();
            });
        });
    },

    testIsIgnoredInNonGit: function(test) {
        gitHelper.isIgnored('/tmp/', 'foobar', function(err, ignored) {
            test.ok(err instanceof Error, 'did not get an error when checking non-git directory for ignored file');
            test.equal('NONGIT', err.code, '/tmp repository did not report back "NONGIT" code');
            test.done();
        });
    },

    testStats: function(test) {
        var self = this,
            randomString = generateRandomStr(10),
            textBuffer = new Buffer(randomString),
            fileName = 'tests/' + randomString + '.txt',
            startDate = new Date().getTime();

        gitHelper.writeFile(self.branch, '.', fileName, textBuffer, 'utf-8', function(err) {
            test.ifError(err, 'caught error when writing ' + fileName + ' to "' + self.branch + '"');
            gitHelper.fileSize(self.branch, '.', fileName, function(err, size) {
                test.ifError(err, 'caught error when checking file size of  ' + fileName + ' on "' + self.branch + '"');
                test.equal(size, 10, 'could not read the correct file size from ' + fileName + ' on "' + self.branch + '"');
                gitHelper.lastModified(self.branch, '.', fileName, function(err, date) {
                    test.ifError(err, 'caught error when checking last modified of  ' + fileName + ' on "' + self.branch + '"');
                    test.ok(date.getTime() - startDate < 2000, 'could not read the correct last modified from ' + fileName + ' on "' + self.branch + '"');
                    gitHelper.unlink(self.branch, '.', fileName, function(err) {
                        test.ifError(err, 'caught error when deleting ' + fileName + ' from "' + self.branch + '"');
                        test.done();
                    });
                });
            });
        });
    },

    testListBranches: function(test) {
        gitHelper.listBranches('.', function(err, branches) {
            test.ifError(err, 'caught error when reading list of branches');
            test.ok(branches instanceof Array, 'did not get a list of branches back');
            test.ok(branches.indexOf('master') > -1, 'could not find master in the list of branches');
            test.done();
        });
    },

    testCommitNotes: function(test) {
        var commitId = '1a038771857d371ab9ce6f0cd83c6d8fb58f4f1e',
            commitNote = 'This is a simple commit note.';

        gitHelper.util.removeCommitNote('.', commitId, function(err) {
            test.ifError(err, 'did get error when removing notes from ' + commitId);
            gitHelper.util.getCommitNote('.', commitId, function(err, note) {
                test.ifError(err, 'did get error when reading note for ' + commitId);
                test.equal(note, null, 'did not get an empty note when reading ' + commitId);
                gitHelper.util.addCommitNote('.', commitId, commitNote, function(err) {
                    test.ifError(err, 'did get error when adding note for ' + commitId);
                    gitHelper.util.getCommitNote('.', commitId, function(err, note) {
                        test.ifError(err, 'did get error when reading note for ' + commitId);
                        test.equal(note, commitNote, 'did not get back the stored note when reading ' + commitId);
                        test.done();
                    });
                });
            });
        });
    },

    testDiffCommits: function(test) {
        var testBranch = 'TESTING_do_not_change',
            addCommit = 'c3b20aa980bef5a352b016c752ffe8439d3c2781';

        gitHelper.util.diffCommits(testBranch, '.', function(err, diff) { // single commitish
            test.ifError(err, 'did get error when diffing commits for ' + testBranch);
            test.equal(diff.added.length, 2, 'did not find the correct number of added commits in ' + testBranch);
            test.ok(diff.missing.length > 0, 'did not find the correct number of missing commits in ' + testBranch);
            gitHelper.util.diffCommits(testBranch, addCommit, '.', function(err, diff) { // two commitishs (no branch but commit)
                test.ifError(err, 'did get error when diffing commits for ' + testBranch);
                test.equal(diff.added.length, 2, 'did not find the correct number of added commits in ' + testBranch + ' compared to ' + addCommit);
                test.equal(diff.missing.length,1 , 'did not find the correct number of missing commits in ' + testBranch + ' compared to ' + addCommit);
                gitHelper.util.diffCommits('foobar123654', '.', function(err, diff) { // non-existing
                    test.ok(err instanceof Error, 'did not get an error when diffing commits for non-existing commitish');
                    test.equal('NOTACOMMIT', err.code, 'non-existent commitish did not report back "NOTACOMMIT" code');
                    test.done();
                });
            });
        });
    }

};

module.exports = tests;<commit_msg>Fixing test to work on newly cloned copies<commit_after>var gitHelper = require('../index.js'),
    path = require('path');

function generateRandomStr(len) {
    len = isNaN(len) ? 5 : len;
    var str = '',
        base = '012345679ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    for (var i = 0; i < len; i++) {
        str += base.charAt(Math.floor(Math.random() * base.length));
    }
    return str;
}

var tests = {

    setUp: function(callback) {
        this.branch = 'testBranch';
        callback();
    },

    tearDown: function(callback) {
        gitHelper.removeBranch(this.branch, '.', callback);
    },

    testFindGitDir: function(test) {
        var cwd = process.env.PWD;
        gitHelper.gitPath('.', function(err, dir) {
            test.ifError(err, 'caught error when finding git');
            test.equal(cwd, dir, 'did not find git dir at current dir (' + cwd + ' vs. ' + dir + ')');
            gitHelper.gitPath('tests', function(err, dir) {
                test.ifError(err, 'caught error when finding git');
                test.equal(cwd, dir, 'did not find git dir at current dir (' + cwd + ' vs. ' + dir + ')');
                test.done();
            });
        });
    },

    testFindGitDirNotExistent: function(test) {
        var cwd = process.env.PWD;
        gitHelper.gitPath('foobar', function(err, dir) {
            test.ok(err instanceof Error, 'did not get an error when finding git in non-existent directory');
            test.equal('NOTADIR', err.code, 'non-existent directory did not report back "NOTADIR" code');
            test.done();
        });
    },

    testFileTypeIsFile: function(test) {
        var self = this;
        gitHelper.fileType(this.branch, '.', 'package.json', function(err, isDir) {
            test.ifError(err, 'caught error when checking "' + self.branch + '" for package.json');
            test.ok(!isDir, 'package.json in "' + self.branch + '" should not be a directory');
            test.done();
        });
    },

    testFileTypeIsDir: function(test) {
        var self = this;
        gitHelper.fileType(this.branch, '.', 'tests', function(err, isDir) {
            test.ifError(err, 'caught error when checking "' + self.branch + '" for tests');
            test.ok(isDir, 'tests in "' + self.branch + '" should be a directory');
            test.done();
        });
    },

    testFileTypeOfNonGit: function(test) {
        var self = this;
        gitHelper.fileType(this.branch, '/tmp/', 'foobar', function(err, isDir) {
            test.ok(err instanceof Error, 'did not get an error when checking "' + self.branch + '" in non-git directory');
            test.equal('NONGIT', err.code, '/tmp repository did not report back "NONGIT" code');
            test.done();
        });
    },

    testFileTypeNotExists: function(test) {
        var self = this;
        gitHelper.fileType(this.branch, '.', 'not.exists', function(err, isDir) {
            test.ok(err instanceof Error, 'did not get an error when checking "' + self.branch + '" for non existing file (non.exists)');
            test.done();
        });
    },

    testReadDir: function(test) {
        var self = this;
        gitHelper.readDir(this.branch, '.', '', function(err, tree) {
            test.ifError(err, 'caught error when reading root directory of "' + self.branch + '"');
            var entries = Object.getOwnPropertyNames(tree);
            test.ok(entries.indexOf('package.json') > -1, 'package.json could not be found in root directory of "' + self.branch + '"');
            test.equal(tree['package.json'].objectType, 'blob', 'package.json was not of type "blob" in "' + self.branch + '"');
            test.ok(entries.indexOf('tests') > -1, 'tests could not be found in root directory of "' + self.branch + '"');
            test.equal(tree['tests'].objectType, 'tree', 'tests was not of type "tree" in "' + self.branch + '"');
            test.done();
        });
    },

    testFileCreationAndDeletion: function(test) {
        var self = this,
            randomString = generateRandomStr(10),
            textBuffer = new Buffer('I am ' + randomString),
            fileName = 'tests/' + randomString + '.txt';

        gitHelper.readFile(self.branch, '.', fileName, function(err) {
            test.ok(err instanceof Error, 'did not get an error when checking "' + self.branch + '" for ' + fileName);
            gitHelper.writeFile(self.branch, '.', fileName, textBuffer, 'utf-8', function(err) {
                test.ifError(err, 'caught error when writing ' + fileName + ' to "' + self.branch + '"');
                gitHelper.readFile(/* should still not exist on */ 'master', '.', fileName, function(err) {
                    test.ok(err instanceof Error, 'did not get an error when checking "master" for ' + fileName);
                    gitHelper.readFile(/* should exist on */ self.branch, '.', fileName, function(err, buffer) {
                        test.ifError(err, 'caught error when checking "' + self.branch + '" for ' + fileName);
                        test.equal(buffer.toString(), textBuffer.toString(), 'content was not inserted write');
                        gitHelper.unlink(self.branch, '.', fileName, function(err) {
                            test.ifError(err, 'caught error when deleting ' + fileName + ' from "' + self.branch + '"');
                            gitHelper.readFile(self.branch, '.', fileName, function(err) {
                                test.ok(err instanceof Error, 'did not get an error when checking "' + self.branch + '" for ' + fileName + ' after delete');
                                test.done();
                            });
                        });
                    });
                });
            });
        });
    },

    testDirCreationAndDeletion: function(test) {
        var self = this,
            randomString = generateRandomStr(10);
        // TODO: read tree and make sure the dir does not exist
        gitHelper.mkDir(this.branch, '.', 'tests/dir_' + randomString, function(err) {
            test.ifError(err, 'caught error when creating tests/dir_' + randomString + ' in "' + self.branch + '"');
            // TODO: read tree from master and make sure it was not changed
            gitHelper.unlink(self.branch, '.', 'tests/dir_' + randomString, function(err) {
                test.ifError(err, 'caught error when deleting tests/dir_' + randomString + ' from "' + self.branch + '"');
                // TODO: read tree and make sure the dir does not exist anymore
                test.done();
            });
        });
    },

    testIsIgnored: function(test) {
        gitHelper.isIgnored('.', 'node_modules', function(err, ignored) {
            test.ifError(err, 'caught error when checking (working copy) whether node_modules is ignored');
            test.ok(ignored, 'node_modules should be ignored (in the currenty working copy)');

            gitHelper.isIgnored('.', 'package.json', function(err, ignored) {
                test.ifError(err, 'caught error when checking (working copy) whether package.json is ignored');
                test.ok(!ignored, 'package.json should not be ignored (in the currenty working copy)');
                test.done();
            });
        });
    },

    testIsIgnoredInNonGit: function(test) {
        gitHelper.isIgnored('/tmp/', 'foobar', function(err, ignored) {
            test.ok(err instanceof Error, 'did not get an error when checking non-git directory for ignored file');
            test.equal('NONGIT', err.code, '/tmp repository did not report back "NONGIT" code');
            test.done();
        });
    },

    testStats: function(test) {
        var self = this,
            randomString = generateRandomStr(10),
            textBuffer = new Buffer(randomString),
            fileName = 'tests/' + randomString + '.txt',
            startDate = new Date().getTime();

        gitHelper.writeFile(self.branch, '.', fileName, textBuffer, 'utf-8', function(err) {
            test.ifError(err, 'caught error when writing ' + fileName + ' to "' + self.branch + '"');
            gitHelper.fileSize(self.branch, '.', fileName, function(err, size) {
                test.ifError(err, 'caught error when checking file size of  ' + fileName + ' on "' + self.branch + '"');
                test.equal(size, 10, 'could not read the correct file size from ' + fileName + ' on "' + self.branch + '"');
                gitHelper.lastModified(self.branch, '.', fileName, function(err, date) {
                    test.ifError(err, 'caught error when checking last modified of  ' + fileName + ' on "' + self.branch + '"');
                    test.ok(date.getTime() - startDate < 2000, 'could not read the correct last modified from ' + fileName + ' on "' + self.branch + '"');
                    gitHelper.unlink(self.branch, '.', fileName, function(err) {
                        test.ifError(err, 'caught error when deleting ' + fileName + ' from "' + self.branch + '"');
                        test.done();
                    });
                });
            });
        });
    },

    testListBranches: function(test) {
        gitHelper.listBranches('.', function(err, branches) {
            test.ifError(err, 'caught error when reading list of branches');
            test.ok(branches instanceof Array, 'did not get a list of branches back');
            test.ok(branches.indexOf('master') > -1, 'could not find master in the list of branches');
            test.done();
        });
    },

    testCommitNotes: function(test) {
        var commitId = '1a038771857d371ab9ce6f0cd83c6d8fb58f4f1e',
            commitNote = 'This is a simple commit note.';

        gitHelper.util.removeCommitNote('.', commitId, function(err) {
            test.ifError(err, 'did get error when removing notes from ' + commitId);
            gitHelper.util.getCommitNote('.', commitId, function(err, note) {
                test.ifError(err, 'did get error when reading note for ' + commitId);
                test.equal(note, null, 'did not get an empty note when reading ' + commitId);
                gitHelper.util.addCommitNote('.', commitId, commitNote, function(err) {
                    test.ifError(err, 'did get error when adding note for ' + commitId);
                    gitHelper.util.getCommitNote('.', commitId, function(err, note) {
                        test.ifError(err, 'did get error when reading note for ' + commitId);
                        test.equal(note, commitNote, 'did not get back the stored note when reading ' + commitId);
                        test.done();
                    });
                });
            });
        });
    },

    testDiffCommits: function(test) {
        var testBranch = 'remotes/origin/TESTING_do_not_change',
            addCommit = 'c3b20aa980bef5a352b016c752ffe8439d3c2781';

        gitHelper.util.diffCommits(testBranch, '.', function(err, diff) { // single commitish
            test.ifError(err, 'did get error when diffing commits for ' + testBranch);
            test.equal(diff.added.length, 2, 'did not find the correct number of added commits in ' + testBranch);
            test.ok(diff.missing.length > 0, 'did not find the correct number of missing commits in ' + testBranch);
            gitHelper.util.diffCommits(testBranch, addCommit, '.', function(err, diff) { // two commitishs (no branch but commit)
                test.ifError(err, 'did get error when diffing commits for ' + testBranch);
                test.equal(diff.added.length, 2, 'did not find the correct number of added commits in ' + testBranch + ' compared to ' + addCommit);
                test.equal(diff.missing.length,1 , 'did not find the correct number of missing commits in ' + testBranch + ' compared to ' + addCommit);
                gitHelper.util.diffCommits('foobar123654', '.', function(err, diff) { // non-existing
                    test.ok(err instanceof Error, 'did not get an error when diffing commits for non-existing commitish');
                    test.equal('NOTACOMMIT', err.code, 'non-existent commitish did not report back "NOTACOMMIT" code');
                    test.done();
                });
            });
        });
    }

};

module.exports = tests;
<|endoftext|>


<commit_before>
exports.print = typeof print !== "undefined" ? print : function () {
    var system = require("system");
    var stdio = system.stdio;
    stdio.print.apply(stdio, arguments);
};

exports.assert = function (guard, message) {
    if (guard) {
        exports.print('PASS ' + message, 'pass');
    } else {
        exports.print('FAIL ' + message, 'fail');
    }
};

<commit_msg>Fixed formatting in tests/test.js<commit_after>exports.print = typeof print !== "undefined" ? print : function () {
  var system = require("system");
  var stdio = system.stdio;
  stdio.print.apply(stdio, arguments);
};

exports.assert = function (guard, message) {
  if (guard) {
    exports.print('PASS ' + message, 'pass');
  } else {
    exports.print('FAIL ' + message, 'fail');
  }
};
<|endoftext|>


<commit_before>import { expect } from 'chai';

// test data
import aForm from './data/a.form.js';
import bForm from './data/b.form.js';
import cForm from './data/c.form.js';
import dForm from './data/d.form.js';

// do some stuff
dForm.update({ username: 'changed' });

// do tests
describe('mobx-ajv-form', () => {
  // test isValid
  it('aForm isValid should be true', () => expect(aForm.isValid).to.be.true);
  it('bForm isValid should be false', () => expect(bForm.isValid).to.be.false);
  it('cForm isValid should be false', () => expect(cForm.isValid).to.be.false);
  it('dForm isValid should be false', () => expect(dForm.isValid).to.be.false);

  // test isDirty
  it('aForm isDirty should be false', () => expect(aForm.isDirty).to.be.false);
  it('bForm isDirty should be false', () => expect(bForm.isDirty).to.be.false);
  it('cForm isDirty should be false', () => expect(cForm.isDirty).to.be.false);
  it('dForm isDirty should be true', () => expect(dForm.isDirty).to.be.true);

  // others
  it('aForm fieldKeys() should be array', () => expect(aForm.fieldKeys()).to.be.array);
  it('aForm values() should be array', () => expect(aForm.values()).to.be.array);
});
<commit_msg>test: added tests<commit_after>import { expect } from 'chai';

// test data
import aForm from './data/a.form.js';
import bForm from './data/b.form.js';
import cForm from './data/c.form.js';
import dForm from './data/d.form.js';

// do some stuff
cForm.invalidate('The user already exist');
dForm.update({ username: 'Jonathan Ive' });

// do tests
describe('mobx-ajv-form', () => {
  // test isValid
  it('aForm isValid should be true', () => expect(aForm.isValid).to.be.true);
  it('bForm isValid should be false', () => expect(bForm.isValid).to.be.false);
  it('cForm isValid should be false', () => expect(cForm.isValid).to.be.false);
  it('dForm isValid should be false', () => expect(dForm.isValid).to.be.false);

  // test isDirty
  it('aForm isDirty should be false', () => expect(aForm.isDirty).to.be.false);
  it('bForm isDirty should be false', () => expect(bForm.isDirty).to.be.false);
  it('cForm isDirty should be false', () => expect(cForm.isDirty).to.be.false);
  it('dForm isDirty should be true', () => expect(dForm.isDirty).to.be.true);

  // others check
  it('aForm fieldKeys() should be array', () => expect(aForm.fieldKeys()).to.be.array);
  it('aForm values() should be array', () => expect(aForm.values()).to.be.array);

  it('cForm username should be equal to "The user already exist."', () =>
    expect(cForm.genericErrorMessage).to.be.equal('The user already exist'));

  it('dForm username should be equal to "Jonathan Ive"', () =>
    expect(dForm.fields.username.value).to.be.equal('Jonathan Ive'));
});
<|endoftext|>


<commit_before>var tiff2pdf = require('../'),
    test = require('tape'),
    path = require('path'),
    fs = require('fs');

test('Convert tiff to pdf', function (t){
  var outDir = path.join(__dirname+'/fixtures/out/'),
      inFile1 = path.join(__dirname,'/fixtures/in/test1.tiff'),
      inFile2 = path.join(__dirname,'/fixtures/in/test2.tif'),
      inFile3 = path.join(__dirname,'/fixtures/in/test3.tiff'),
      inFile4 = path.join(__dirname,'/fixtures/in/test4.pdf'),
      inFile5 = path.join(__dirname,'/fixtures/in/test5.tif'),
      inFile6 = path.join(__dirname,'/fixtures/in/test6.tif');

  //Test 1: Successful conversion file ending with extension .tiff
  t.comment('Test 1: Successful conversion file ending with extension .tiff');
  tiff2pdf(inFile1, outDir, function(result){
    t.ok(result.message, 'Test 1: Successful');
  });

  //Test 2: Successful conversion file ending with extension .tif
  t.comment('Test 2: Successful conversion file ending with extension .tif');
  tiff2pdf(inFile2, outDir, function(result){
    t.ok(result.message, 'Test 2: successful');
  });

  //Test 3: File not found
  t.comment('Test 3: File not found');
  tiff2pdf(inFile3, outDir, function(result){
    t.ok(result.message, 'Test 3: successful, file does not exisit');
  });

  //Test 4: Wrong file extension
  t.comment('Test 4: Wrong file extension');
  tiff2pdf(inFile4, outDir, function(result){
    t.ok(result.message, 'Test 4: successful, inccorect file type');
  });

  //Test 5: Corrupt file
  t.comment('Test 5: Corrupt file');
  tiff2pdf(inFile5, outDir, function(result){
    t.ok(result.message, 'Test 5: successful, corrupt file');
  });

  //Test 6: GeoTiff
  t.comment('Test 6: Normal tiff');
  tiff2pdf(inFile6, outDir, function(result){
    t.notOk(result.code, 'Test 6: successful, Normal tiff');
  });

  t.end();
});
<commit_msg>Changed test 6<commit_after>var tiff2pdf = require('../'),
    test = require('tape'),
    path = require('path'),
    fs = require('fs');

test('Convert tiff to pdf', function (t){
  var outDir = path.join(__dirname+'/fixtures/out/'),
      inFile1 = path.join(__dirname,'/fixtures/in/test1.tiff'),
      inFile2 = path.join(__dirname,'/fixtures/in/test2.tif'),
      inFile3 = path.join(__dirname,'/fixtures/in/test3.tiff'),
      inFile4 = path.join(__dirname,'/fixtures/in/test4.pdf'),
      inFile5 = path.join(__dirname,'/fixtures/in/test5.tif'),
      inFile6 = path.join(__dirname,'/fixtures/in/test6.tif');

  //Test 1: Successful conversion file ending with extension .tiff
  t.comment('Test 1: Successful conversion file ending with extension .tiff');
  tiff2pdf(inFile1, outDir, function(result){
    t.ok(result.message, 'Test 1: Successful');
  });

  //Test 2: Successful conversion file ending with extension .tif
  t.comment('Test 2: Successful conversion file ending with extension .tif');
  tiff2pdf(inFile2, outDir, function(result){
    t.ok(result.message, 'Test 2: successful');
  });

  //Test 3: File not found
  t.comment('Test 3: File not found');
  tiff2pdf(inFile3, outDir, function(result){
    t.ok(result.message, 'Test 3: successful, file does not exisit');
  });

  //Test 4: Wrong file extension
  t.comment('Test 4: Wrong file extension');
  tiff2pdf(inFile4, outDir, function(result){
    t.ok(result.message, 'Test 4: successful, inccorect file type');
  });

  //Test 5: Corrupt file
  t.comment('Test 5: Corrupt file');
  tiff2pdf(inFile5, outDir, function(result){
    t.ok(result.message, 'Test 5: successful, corrupt file');
  });

  //Test 6: GeoTiff
  t.comment('Test 6: Normal tiff');
  tiff2pdf(inFile6, outDir, function(result){
    t.ok(result.message, 'Test 6: successful, Normal tiff');
  });

  t.end();
});
<|endoftext|>


<commit_before>/*---------------------------------------------------------------------------/
 *
 *  textselect.js
 *
 *  Author: Declan de Wet <declandewet@me.com>
 *
 *  This script will trigger an event `textselect` when text is highlighted
 *  on the page. It's only dependency is jQuery.
 *
 *--------------------------------------------------------------------------*/

// enclose code in top-level function scope to prevent creation of globals
(function() {

  /**
   * @function getSelectedTextContent
   * @return {String} Content within a highlighted selection, if any present.
   *
   * Immediately-invoked self-modifying function.
   * Executes instantly and uses feature detection to determine the text
   * selection method the browser supports, then modifies itself to return
   * the value returned by that method any time it is manually called.
   */
  var getSelectedTextContent = (function() {
    if (window.getSelection) {
      return function() {
        return window.getSelection.toString();
      };
    } else if (document.getSelection) {
      return function() {
        return document.getSelection();
      };
    } else if (document.selection) {
      return function() {
        return document.selection.createRange().text;
      };
    }
  }).apply(this);

  /**
   * @function getSelectionInformation
   * @return {Object} Contains coordinate and size properties of selection.
   *
   * Immediately-invoked self-modifying function.
   * Executes instantly and uses feature detection to determine the
   * method to use to get location and size information about the current
   * selection, if any - then modifes itself to return the output of
   * that method.
   *
   * N.B. - Temporary implementation until more research is done on
   * supporting more browsers.
   */
  var getSelectionInformation = (function(){
    if (window.getSelection) {
      return function() {
        return window.getSelection().getRangeAt(0).getBoundingClientRect();
      };
    } else {
      return function() {
        var message = "Selection coordinates are not supported in this browser";
        throw new Error(message);
      };
    }
  }).apply(this);

}).call(this);
<commit_msg>Added function that determines selection state and triggers  event<commit_after>/*---------------------------------------------------------------------------/
 *
 *  textselect.js
 *
 *  Author: Declan de Wet <declandewet@me.com>
 *
 *  This script will trigger an event `textselect` when text is highlighted
 *  on the page. It's only dependency is jQuery.
 *
 *--------------------------------------------------------------------------*/

// enclose code in top-level function scope to prevent creation of globals
(function() {

  /**
   * @function getSelectedTextContent
   * @return {String} Content within a highlighted selection, if any present.
   *
   * Immediately-invoked self-modifying function.
   * Executes instantly and uses feature detection to determine the text
   * selection method the browser supports, then modifies itself to return
   * the value returned by that method any time it is manually called.
   */
  var getSelectedTextContent = (function() {
    if (window.getSelection) {
      return function() {
        return window.getSelection.toString();
      };
    } else if (document.getSelection) {
      return function() {
        return document.getSelection();
      };
    } else if (document.selection) {
      return function() {
        return document.selection.createRange().text;
      };
    }
  }).apply(this);

  /**
   * @function getSelectionInformation
   * @return {Object} Contains coordinate and size properties of selection.
   *
   * Immediately-invoked self-modifying function.
   * Executes instantly and uses feature detection to determine the
   * method to use to get location and size information about the current
   * selection, if any - then modifes itself to return the output of
   * that method.
   *
   * N.B. - Temporary implementation until more research is done on
   * supporting more browsers.
   */
  var getSelectionInformation = (function(){
    if (window.getSelection) {
      return function() {
        return window.getSelection().getRangeAt(0).getBoundingClientRect();
      };
    }
  }).apply(this);

  // the below 3 variables are used to prevent triggering the event
  // when selected text is deselected on mouse click, as well as to
  // ensure that text is actually selected before triggering the event

  // stores selection text content
  var selectionText = '',
  // used to determine active state of selection
  isTextSelected = false,
  // used to ensure current selection content is not same as the previous one
  previousSelection;

  /**
   * @function triggerSelectedTextEvent
   * @param  {Object} $el [a jQuery element object]
   * @returns nothing
   *
   * Determines current state of the selection and triggers the `textselect`
   * event on the element passed to it
   */
  var triggerSelectedTextEvent = function($el) {

    // get the selection text
    selectionText = getSelectedTextContent();

    // store the selection coords/size in this
    var selectionInformation;

    // sugary syntax for easy reading
    var selectionNotEmpty = (selectionText !== ''),
        uniqueSelection = (selectionText !== previousSelection);

    // we do not want to trigger the `textselect` event if the selection
    // is empty, if the user is clicking off a selection, or if the user
    // is clicking on a selection to unselect it
    if (selectionNotEmpty && uniqueSelection) {

      // get the coordinates and size of the selection
      selectionInformation = getSelectionInformation();

      // trigger the event
      $el.trigger('textselect', {
        top: selectionInformation.top,
        bottom: selectionInformation.bottom,
        left: selectionInformation.left,
        right: selectionInformation.right,
        width: selectionInformation.width,
        height: selectionInformation.height,
        text: selectionText
      });

    }

    // store the most recent selection for the next check
    previousSelection = selectionText;

    // reset selection content
    selectionText = '';

  };

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


<commit_before>/**
 *  Tidy Table
 *  Generate a sortable HTML table from JSON
 *
 *  Copyright 2012-2015, Marc S. Brooks (http://mbrooks.info)
 *  Licensed under the MIT license:
 *  http://www.opensource.org/licenses/mit-license.php
 *
 *  Dependencies:
 *    jquery.js
 */

if (!window.jQuery || (window.jQuery && window.jQuery.fn.jquery < '1.8.3')) {
	throw new Error('Tidy-Table requires jQuery 1.8.3 or greater.');
}

(function($) {

	/**
	 * @namespace TidyTable
	 */
	var methods = {

		/**
		 * Create new instance of Tidy-Table
		 * @memberof TidyTable
		 * @method init
		 * @param {Object} settings
		 * @param {Object} config
		 * @returns {Object} jQuery object
		 */
		"init": function(settings, config) {
			var $this = $(this),
				data  = $this.data();

			// default settings
			var defaults = {
				enableCheckbox: false,
				enableMenu:     false,
				reverseSortDir: false
			};

			if (arguments.length > 1) {
				$.extend(defaults, settings);
			}
			else {
				config = settings;
			}

			// config defaults
			config = $.extend({
				sortByPattern: function(col_num, val) {
					if ( $.trim(col_num) ) {
						return String(val).replace(/$|%|#/g, '');
					}
				}
			}, config);

			if ( $.isEmptyObject(data) ) {
				$this.data({
					settings: defaults,
					config:   config
				});
			}

			return $this.TidyTable('_createTable');
		},

		/**
		 * Perform cleanup
		 * @memberof TidyTable
		 * @method destroy
		 */
		"destroy": function() {
			$(this).removeData();
		},

		/**
		 * Create HTML table elements
		 * @memberof TidyTable
		 * @method _createTable
		 * @param {String} num
		 * @param {String} order
		 * @returns {Object}
		 * @private
		 */
		"_createTable": function(num, order) {
			var $this = $(this),
				data  = $this.data();

			// create reusable elements
			var table = $('

')
				.addClass('tidy_table');

			table.mousedown(function() { return false; });
			table.mouseover(function() { return false; });

			var thead = $('

'),
				tbody = $('

');

			// ..

			(function() {
				var row = $('

');

				for (var i = 0; i < data.config.columnTitles.length; i++) {
					var title = data.config.columnTitles[i];

					var col = $('	')
						.append(title)
						.attr('title', title);
					row.append(col);

					var col_class;

					// determine column result ordet
					if (!data.settings.reverseSortDir) {
						if (order == 'asc' || !order) {
							col_class = 'sort_asc';
							col.order = 'desc';
						}
						else {
							col_class = 'sort_desc';
							col.order = 'asc';
						}
					}
					else {
						if (order == 'desc' || !order) {
							col_class = 'sort_asc';
							col.order = 'asc';
						}
						else {
							col_class = 'sort_desc';
							col.order = 'desc';
						}
					}

					// highlight selected column
					if (num == i) {
						col.addClass(col_class);
					}

					// attach sorting event to each column
					col.on('click', {
						col_number: i,
						sort_order: (num == i) ? col.order : 'asc'
					},
					function(event) {
						$this.TidyTable('_sortByColumn', event.data.col_number, event.data.sort_order);
					});
				}

				thead.append(row);
			})();

			// ..

			(function() {
				var vals = data.config.columnValues;

				for (var j = 0; j < vals.length; j++) {
					var row = $('

');

					for (var k = 0; k < vals[j].length; k++) {
						var val = vals[j][k];

						var col = $('	')
							.append(val)
							.attr('title', val);
						row.append(col);

						// post-process table column HTML object
						if (data.config.postProcess && $.isFunction(data.config.postProcess.column)) {
							data.config.postProcess.column(col);
						}
					}

					tbody.append(row);
				}

				table.append(thead);
				table.append(tbody);

				// append check boxes to beginning each row
				if (data.settings && data.settings.enableCheckbox) {
					var rows = table.find('tr');

					rows.each(function(index) {
						var input = $('<input></input>')
							.attr('type', 'checkbox');

						var col;

						// first row is always the header
						if (index === 0) {
							col = $('	');

							// attach event to check all boxes
							input.on('click', function() {
								$this.TidyTable('_toggleSelRows', rows);
							});
						}
						else {
							col = $('	');

							// attach event to each checkbox
							input.on('click', {
								box_number: index
							},
							function(event) {
								$this.TidyTable('_toggleSelRows', rows, event.data.box_number);
							});
						}

						col.append(input);

						// insert before first cell
						$(this).prepend(col);
					});
				}
			})();

			// post-process table results HTML object
			if (data.config.postProcess && $.isFunction(data.config.postProcess.table)) {
				data.config.postProcess.table(table);
			}

			var block = $this.children('table.tidy_table');

			// if table exists, perform an in-place update of the element
			if (block[0]) {
				block.replaceWith(table);
			}

			// generate table/menu elements
			else {
				if (data.settings && data.settings.enableMenu) {
					$this.append(
						$this.TidyTable('_createMenu', block, 'options')
					);
				}

				$this.append(table);
			}

			return table;
		},

		/**
		 * Create HTML select menu element
		 * @memberof TidyTable
		 * @method _createMenu
		 * @param {Object} table
		 * @param {String} name
		 * @returns {Object}
		 * @private
		 */
		"_createMenu": function(table, name) {
			var $this = $(this),
				data  = $this.data();

			// create reusable elements
			var select = $('<select></select>')
				.addClass('tidy_table ' + name)
				.change(function() {
					var elm = $(this);

					var callback = data.config.menuOptions[ elm.val() ][1]['callback'];

					// callback event
					if ( $.isFunction(callback) ) {
						callback( $this.TidyTable('_getCheckedAsObj', table) );
					}

					elm.val(0);
				});

			// .. options
			$.each(data.config.menuOptions, function(index) {
				var option = $('<option>' + data.config.menuOptions[index][0] + '</option>')
					.attr('value', index);

				select.append(option);
			});

			// post-process select menu HTML object
			if (data.config.postProcess && $.isFunction(data.config.postProcess.menu)) {
				data.config.postProcess.menu(select);
			}

			return select;
		},

		/**
		 * Return selected row values as an array
		 * @memberof TidyTable
		 * @method _getCheckedAsObj
		 * @param {Object} table
		 * @returns {Array}
		 * @private
		 */
		"_getCheckedAsObj": function(table) {
			var rows = table.find('tbody > tr'),
				objs = [];

			for (var i = 0; i < rows.length; i++) {
				var cols = rows[i].childNodes;

				// if the row checkbox is selected
				if (cols[0].firstChild.checked) {
					var row = [];

					// simulate an associative array
					for (var j = 1; j < cols.length; j++) {
						row[j - 1] = cols[j].textContent;
					}

					objs.push(row);
				}
			}

			return objs;
		},

		/**
		 * Select/Deselect (input checkbox and row highlight)
		 * @memberof TidyTable
		 * @method _toggleSelRows
		 * @param {Object} rows
		 * @param {Number} num
		 * @private
		 */
		"_toggleSelRows": function(rows, num) {
			var checked = null;

			rows.each(function(index) {
				var row   = $(this),
					input = row.find(':checkbox').first();

				// update all rows
				if (!num) {
					if (index === 0) {
						checked = (input.is(':checked')) ? true : false;
						return;
					}

					if (checked) {
						row.removeClass('check_off').addClass('check_on');
						input.prop('checked', true);
					}
					else {
						row.removeClass('check_on').addClass('check_off');
						input.prop('checked', false);
					}
				}

				// update selected row
				else {
					if (index === 0) {
						return;
					}

					if (input.is(':checked')) {
						row.removeClass('check_off').addClass('check_on');
						input.prop('checked', true);
					}
					else {
						row.removeClass('check_on').addClass('check_off');
						input.prop('checked', false);
					}
				}
			});
		},

		/**
		 * Display results ordered by selected column
		 * @memberof TidyTable
		 * @method _sortByColumn
		 * @param {Number} num
		 * @param {Number} order
		 * @private
		 */
		"_sortByColumn": function(num, order) {
			var $this = $(this),
				data  = $this.data();

			if ( $.isFunction(data.config.sortByPattern) ) {
				var reverse = (order == 'desc') ? -1 : 1;

				// sort JSON object by bucket number
				data.config.columnValues.sort(function(a, b) {
					var str1 = data.config.sortByPattern(num, a[num]),
						str2 = data.config.sortByPattern(num, b[num]);

					if (isNaN(str1)) {
						return [reverse * cmpAny(str1, str2)] >
						       [reverse * cmpAny(str2, str1)] ? -1 : 1;
					}
					else {
						return [reverse * cmpInt(str1, str2)];
					}
				});
			}

			$this.TidyTable('_createTable', num, order);
		}
	};

	$.fn.TidyTable = function(method) {
		if (methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		}
		else
		if (typeof method === 'object' || !method) {
			return methods.init.apply(this, arguments);
		}
		else {
			$.error('Method ' +  method + ' does not exist in jQuery.TidyTable');
		}
	};

	/**
	 * Generic string comparison functions
	 * @param {String} a
	 * @param {String} b
	 * @returns {Number}
	 * @protected
	 */
	function cmpAny(a, b) {
		return (a > b) ? 1 : (a < b) ? -1 : 0;
	}

	function cmpInt(a, b) {
		return b - a;
	}
})(jQuery);
<commit_msg>Updated jQuery detection to resolve issue #7 - used replace method vs split.join() since it's faster<commit_after>/**
 *  Tidy Table
 *  Generate a sortable HTML table from JSON
 *
 *  Copyright 2012-2015, Marc S. Brooks (http://mbrooks.info)
 *  Licensed under the MIT license:
 *  http://www.opensource.org/licenses/mit-license.php
 *
 *  Dependencies:
 *    jquery.js
 */

if (!window.jQuery || (window.jQuery && parseInt(window.jQuery.fn.jquery.replace('.', '')) < parseInt('1.8.3'.replace('.', '')))) {
	throw new Error('Tidy-Table requires jQuery 1.8.3 or greater.');
}

(function($) {

	/**
	 * @namespace TidyTable
	 */
	var methods = {

		/**
		 * Create new instance of Tidy-Table
		 * @memberof TidyTable
		 * @method init
		 * @param {Object} settings
		 * @param {Object} config
		 * @returns {Object} jQuery object
		 */
		"init": function(settings, config) {
			var $this = $(this),
				data  = $this.data();

			// default settings
			var defaults = {
				enableCheckbox: false,
				enableMenu:     false,
				reverseSortDir: false
			};

			if (arguments.length > 1) {
				$.extend(defaults, settings);
			}
			else {
				config = settings;
			}

			// config defaults
			config = $.extend({
				sortByPattern: function(col_num, val) {
					if ( $.trim(col_num) ) {
						return String(val).replace(/$|%|#/g, '');
					}
				}
			}, config);

			if ( $.isEmptyObject(data) ) {
				$this.data({
					settings: defaults,
					config:   config
				});
			}

			return $this.TidyTable('_createTable');
		},

		/**
		 * Perform cleanup
		 * @memberof TidyTable
		 * @method destroy
		 */
		"destroy": function() {
			$(this).removeData();
		},

		/**
		 * Create HTML table elements
		 * @memberof TidyTable
		 * @method _createTable
		 * @param {String} num
		 * @param {String} order
		 * @returns {Object}
		 * @private
		 */
		"_createTable": function(num, order) {
			var $this = $(this),
				data  = $this.data();

			// create reusable elements
			var table = $('

')
				.addClass('tidy_table');

			table.mousedown(function() { return false; });
			table.mouseover(function() { return false; });

			var thead = $('

'),
				tbody = $('

');

			// ..

			(function() {
				var row = $('

');

				for (var i = 0; i < data.config.columnTitles.length; i++) {
					var title = data.config.columnTitles[i];

					var col = $('	')
						.append(title)
						.attr('title', title);
					row.append(col);

					var col_class;

					// determine column result ordet
					if (!data.settings.reverseSortDir) {
						if (order == 'asc' || !order) {
							col_class = 'sort_asc';
							col.order = 'desc';
						}
						else {
							col_class = 'sort_desc';
							col.order = 'asc';
						}
					}
					else {
						if (order == 'desc' || !order) {
							col_class = 'sort_asc';
							col.order = 'asc';
						}
						else {
							col_class = 'sort_desc';
							col.order = 'desc';
						}
					}

					// highlight selected column
					if (num == i) {
						col.addClass(col_class);
					}

					// attach sorting event to each column
					col.on('click', {
						col_number: i,
						sort_order: (num == i) ? col.order : 'asc'
					},
					function(event) {
						$this.TidyTable('_sortByColumn', event.data.col_number, event.data.sort_order);
					});
				}

				thead.append(row);
			})();

			// ..

			(function() {
				var vals = data.config.columnValues;

				for (var j = 0; j < vals.length; j++) {
					var row = $('

');

					for (var k = 0; k < vals[j].length; k++) {
						var val = vals[j][k];

						var col = $('	')
							.append(val)
							.attr('title', val);
						row.append(col);

						// post-process table column HTML object
						if (data.config.postProcess && $.isFunction(data.config.postProcess.column)) {
							data.config.postProcess.column(col);
						}
					}

					tbody.append(row);
				}

				table.append(thead);
				table.append(tbody);

				// append check boxes to beginning each row
				if (data.settings && data.settings.enableCheckbox) {
					var rows = table.find('tr');

					rows.each(function(index) {
						var input = $('<input></input>')
							.attr('type', 'checkbox');

						var col;

						// first row is always the header
						if (index === 0) {
							col = $('	');

							// attach event to check all boxes
							input.on('click', function() {
								$this.TidyTable('_toggleSelRows', rows);
							});
						}
						else {
							col = $('	');

							// attach event to each checkbox
							input.on('click', {
								box_number: index
							},
							function(event) {
								$this.TidyTable('_toggleSelRows', rows, event.data.box_number);
							});
						}

						col.append(input);

						// insert before first cell
						$(this).prepend(col);
					});
				}
			})();

			// post-process table results HTML object
			if (data.config.postProcess && $.isFunction(data.config.postProcess.table)) {
				data.config.postProcess.table(table);
			}

			var block = $this.children('table.tidy_table');

			// if table exists, perform an in-place update of the element
			if (block[0]) {
				block.replaceWith(table);
			}

			// generate table/menu elements
			else {
				if (data.settings && data.settings.enableMenu) {
					$this.append(
						$this.TidyTable('_createMenu', block, 'options')
					);
				}

				$this.append(table);
			}

			return table;
		},

		/**
		 * Create HTML select menu element
		 * @memberof TidyTable
		 * @method _createMenu
		 * @param {Object} table
		 * @param {String} name
		 * @returns {Object}
		 * @private
		 */
		"_createMenu": function(table, name) {
			var $this = $(this),
				data  = $this.data();

			// create reusable elements
			var select = $('<select></select>')
				.addClass('tidy_table ' + name)
				.change(function() {
					var elm = $(this);

					var callback = data.config.menuOptions[ elm.val() ][1]['callback'];

					// callback event
					if ( $.isFunction(callback) ) {
						callback( $this.TidyTable('_getCheckedAsObj', table) );
					}

					elm.val(0);
				});

			// .. options
			$.each(data.config.menuOptions, function(index) {
				var option = $('<option>' + data.config.menuOptions[index][0] + '</option>')
					.attr('value', index);

				select.append(option);
			});

			// post-process select menu HTML object
			if (data.config.postProcess && $.isFunction(data.config.postProcess.menu)) {
				data.config.postProcess.menu(select);
			}

			return select;
		},

		/**
		 * Return selected row values as an array
		 * @memberof TidyTable
		 * @method _getCheckedAsObj
		 * @param {Object} table
		 * @returns {Array}
		 * @private
		 */
		"_getCheckedAsObj": function(table) {
			var rows = table.find('tbody > tr'),
				objs = [];

			for (var i = 0; i < rows.length; i++) {
				var cols = rows[i].childNodes;

				// if the row checkbox is selected
				if (cols[0].firstChild.checked) {
					var row = [];

					// simulate an associative array
					for (var j = 1; j < cols.length; j++) {
						row[j - 1] = cols[j].textContent;
					}

					objs.push(row);
				}
			}

			return objs;
		},

		/**
		 * Select/Deselect (input checkbox and row highlight)
		 * @memberof TidyTable
		 * @method _toggleSelRows
		 * @param {Object} rows
		 * @param {Number} num
		 * @private
		 */
		"_toggleSelRows": function(rows, num) {
			var checked = null;

			rows.each(function(index) {
				var row   = $(this),
					input = row.find(':checkbox').first();

				// update all rows
				if (!num) {
					if (index === 0) {
						checked = (input.is(':checked')) ? true : false;
						return;
					}

					if (checked) {
						row.removeClass('check_off').addClass('check_on');
						input.prop('checked', true);
					}
					else {
						row.removeClass('check_on').addClass('check_off');
						input.prop('checked', false);
					}
				}

				// update selected row
				else {
					if (index === 0) {
						return;
					}

					if (input.is(':checked')) {
						row.removeClass('check_off').addClass('check_on');
						input.prop('checked', true);
					}
					else {
						row.removeClass('check_on').addClass('check_off');
						input.prop('checked', false);
					}
				}
			});
		},

		/**
		 * Display results ordered by selected column
		 * @memberof TidyTable
		 * @method _sortByColumn
		 * @param {Number} num
		 * @param {Number} order
		 * @private
		 */
		"_sortByColumn": function(num, order) {
			var $this = $(this),
				data  = $this.data();

			if ( $.isFunction(data.config.sortByPattern) ) {
				var reverse = (order == 'desc') ? -1 : 1;

				// sort JSON object by bucket number
				data.config.columnValues.sort(function(a, b) {
					var str1 = data.config.sortByPattern(num, a[num]),
						str2 = data.config.sortByPattern(num, b[num]);

					if (isNaN(str1)) {
						return [reverse * cmpAny(str1, str2)] >
						       [reverse * cmpAny(str2, str1)] ? -1 : 1;
					}
					else {
						return [reverse * cmpInt(str1, str2)];
					}
				});
			}

			$this.TidyTable('_createTable', num, order);
		}
	};

	$.fn.TidyTable = function(method) {
		if (methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		}
		else
		if (typeof method === 'object' || !method) {
			return methods.init.apply(this, arguments);
		}
		else {
			$.error('Method ' +  method + ' does not exist in jQuery.TidyTable');
		}
	};

	/**
	 * Generic string comparison functions
	 * @param {String} a
	 * @param {String} b
	 * @returns {Number}
	 * @protected
	 */
	function cmpAny(a, b) {
		return (a > b) ? 1 : (a < b) ? -1 : 0;
	}

	function cmpInt(a, b) {
		return b - a;
	}
})(jQuery);
<|endoftext|>


<commit_before>import declare from 'dojo/_base/declare';
import lang from 'dojo/_base/lang';
import _RightDrawerListMixin from '../_RightDrawerListMixin';
import _MetricListMixin from '../_MetricListMixin';
import MODEL_NAMES from '../../Models/Names';
import MyList from './MyList';
import MyDayOffline from './MyDayOffline';

const resource = window.localeContext.getEntitySync('activityMyDay').attributes;

/**
 * @class crm.Views.Activity.MyDay
 *
 * @requires argos._ListBase
 * @requires argos.Format
 * @requires argos.Utility
 * @requires argos.Convert
 * @requires argos.ErrorManager
 *
 * @requires crm.Format
 * @requires crm.Environment
 * @requires crm.Views.Activity.List
 * @requires crm.Action
 */
const __class = declare('crm.Views.Activity.MyDay', [MyList, _RightDrawerListMixin, _MetricListMixin], {

  // Localization
  titleText: resource.titleText,

  // View Properties
  id: 'myday_list',
  resourceKind: 'userActivities',
  modelName: MODEL_NAMES.USERACTIVITY,
  enableSearch: false,
  pageSize: 105,
  queryModelName: 'myday',

  show: function show(options) {
    if (App.onLine) {
      this._showOfflineView(options);
      return;
    }
    this.inherited(arguments);
  },
  _showOfflineView: function _showOfflineView(options) {
    let view = App.getView('myday_offline_list');
    if (!view) {
      view = new MyDayOffline();
      App.registerView(view);
    }

    view = App.getView('myday_offline_list');
    if (view) {
      view.show(options);
    }
  },
  createToolLayout: function createToolLayout() {
    this.inherited(arguments);
    if (this.tools && this.tools.tbar && !this._refreshAdded && !window.App.supportsTouch()) {
      this.tools.tbar.push({
        id: 'refresh',
        cls: 'fa fa-refresh fa-fw fa-lg',
        action: '_refreshClicked',
      });

      this._refreshAdded = true;
    }

    return this.tools;
  },
  _refreshAdded: false,
  _refreshClicked: function _refreshClicked() {
    this.clear();
    this.refreshRequired = true;
    this.refresh();

    // Hook for customizers
    this.onRefreshClicked();
  },
  onRefreshClicked: function onRefreshClicked() {},
  _getCurrentQuery: function _getCurrentQuery(options) {
    const myDayQuery = this._model.getMyDayQuery();
    const optionsQuery = options && options.queryArgs && options.queryArgs._activeFilter;
    return [myDayQuery, optionsQuery].filter(function checkItem(item) {
        return !!item;
      })
      .join(' and ');
  },
  allowSelection: true,
  enableActions: true,
  hashTagQueriesText: {},
});

lang.setObject('Mobile.SalesLogix.Views.Activity.MyDay', __class);
export default __class;
<commit_msg>Fixing offline mode<commit_after>import declare from 'dojo/_base/declare';
import lang from 'dojo/_base/lang';
import _RightDrawerListMixin from '../_RightDrawerListMixin';
import _MetricListMixin from '../_MetricListMixin';
import MODEL_NAMES from '../../Models/Names';
import MyList from './MyList';
import MyDayOffline from './MyDayOffline';

const resource = window.localeContext.getEntitySync('activityMyDay').attributes;

/**
 * @class crm.Views.Activity.MyDay
 *
 * @requires argos._ListBase
 * @requires argos.Format
 * @requires argos.Utility
 * @requires argos.Convert
 * @requires argos.ErrorManager
 *
 * @requires crm.Format
 * @requires crm.Environment
 * @requires crm.Views.Activity.List
 * @requires crm.Action
 */
const __class = declare('crm.Views.Activity.MyDay', [MyList, _RightDrawerListMixin, _MetricListMixin], {

  // Localization
  titleText: resource.titleText,

  // View Properties
  id: 'myday_list',
  resourceKind: 'userActivities',
  modelName: MODEL_NAMES.USERACTIVITY,
  enableSearch: false,
  pageSize: 105,
  queryModelName: 'myday',

  show: function show(options) {
    if (!App.onLine) {
      this._showOfflineView(options);
      return;
    }
    this.inherited(arguments);
  },
  _showOfflineView: function _showOfflineView(options) {
    let view = App.getView('myday_offline_list');
    if (!view) {
      view = new MyDayOffline();
      App.registerView(view);
    }

    view = App.getView('myday_offline_list');
    if (view) {
      view.show(options);
    }
  },
  createToolLayout: function createToolLayout() {
    this.inherited(arguments);
    if (this.tools && this.tools.tbar && !this._refreshAdded && !window.App.supportsTouch()) {
      this.tools.tbar.push({
        id: 'refresh',
        cls: 'fa fa-refresh fa-fw fa-lg',
        action: '_refreshClicked',
      });

      this._refreshAdded = true;
    }

    return this.tools;
  },
  _refreshAdded: false,
  _refreshClicked: function _refreshClicked() {
    this.clear();
    this.refreshRequired = true;
    this.refresh();

    // Hook for customizers
    this.onRefreshClicked();
  },
  onRefreshClicked: function onRefreshClicked() {},
  _getCurrentQuery: function _getCurrentQuery(options) {
    const myDayQuery = this._model.getMyDayQuery();
    const optionsQuery = options && options.queryArgs && options.queryArgs._activeFilter;
    return [myDayQuery, optionsQuery].filter(function checkItem(item) {
        return !!item;
      })
      .join(' and ');
  },
  allowSelection: true,
  enableActions: true,
  hashTagQueriesText: {},
});

lang.setObject('Mobile.SalesLogix.Views.Activity.MyDay', __class);
export default __class;
<|endoftext|>